From ef065ee66e98b1e826d2aee755ba037bc1e66673 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 01/35] Refactor UI application for strict Clippy checks --- 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 | 10 +- 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 +- 15 files changed, 124 insertions(+), 92 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2ce599e30e..413dc5ea6d 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, 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..3288b9c9f8 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, + 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. @@ -74,7 +80,7 @@ impl PhotocraftApp { if !screen_picker::tick(self, ctx) { jobs_ui::tick(self, ctx); #[cfg(not(target_arch = "wasm32"))] - filter_preview_worker::discard_closed(self); + crate::dialogs::filter_preview_worker::discard_closed(self); if type_tool::in_ui_pass(ctx) { if self.fonts_ready { shortcuts::handle(self, ctx); 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 From 9366cd58ec2d889a96033d1bd3e80befd0bdfd99 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 02/35] Refactor UI canvas for strict Clippy checks --- crates/ui-egui/src/canvas.rs | 2621 +++++++++-------- 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 | 4 +- 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/tests.rs | 6 +- 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 +- 24 files changed, 1608 insertions(+), 1298 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 6912a149e6..bfddadad51 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -201,6 +201,1393 @@ 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); + } +} + +struct CanvasToolInput<'a> { + ctx: &'a egui::Context, + response: &'a egui::Response, + xf: &'a ViewXform, + rect: Rect, + full: Rect, + tool: Tool, + idx: usize, + primary: bool, + transform_owns_pointer: bool, + hand_pan: bool, + ppp: f32, + under_dialog: bool, + zoom_out: &'a dyn Fn(bool) -> bool, + display_zoom: f32, +} + +fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, input: &CanvasToolInput<'_>) { + let ctx = input.ctx; + let response = input.response; + let xf = input.xf; + let rect = input.rect; + let tool = input.tool; + let idx = input.idx; + let under_dialog = input.under_dialog; + let mods = ui.input(|i| i.modifiers); + // An ⌥-click the window manager took never arrives; say so (alt_grab.rs). + crate::alt_grab::watch(app, &ctx, egui::Id::unique(("pc-alt-grab", idx)), rect, tool, !under_dialog); + // Tools follow the left button; the right one opens the Brush Preset picker or erases + // (Preferences › Tools, `paint_mouse`). + crate::paint_mouse::sync_tool_brush(app); + let mut buttons = crate::paint_mouse::canvas_buttons(app, &response, tool); + // The Crop tool's frame is edited from the press (before egui's drag threshold), so the + // pixels past the canvas show at once, as in Photoshop. + if tool == Tool::Crop && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down()) && crate::crop_ui::press(app) { + ctx.request_repaint(); + } + // Capture intent at the press, before egui's drag threshold or click replay on release: + // Type transforms keep Command; selections keep Add/Subtract if Shift/Alt is released. + let capture_press = + tool.is_type() || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee | Tool::ObjectSelection); + let tool_press = egui::Id::unique(("tool-pointer-press-modifiers", idx)); + if capture_press + && let Some((p, press_mods)) = ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers } if rect.contains(*pos) => Some((*pos, *modifiers)), + _ => None, + }) + }) + { + let press_mods = crate::workspace_ui::sticky_mods(app, press_mods); + ctx.data_mut(|d| d.insert_temp(tool_press, press_mods)); + if tool.is_type() && press_mods.command && app.ui.text_edit.is_some() { + let d = xf.to_doc(p); + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); + } + } + + handle_canvas_tool_menus(app, input, mods, &mut buttons); + handle_canvas_tool_navigation(app, ui, view, input, &mut buttons); + handle_canvas_tool_stroke(app, ui, input, mods, capture_press, tool_press, &mut buttons); + handle_canvas_tool_clicks(app, ui, view, input, mods, tool_press, &buttons); +} + +fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_>, mods: egui::Modifiers, buttons: &mut crate::paint_mouse::Buttons) { + let ctx = input.ctx; + let response = input.response; + let xf = input.xf; + let tool = input.tool; + let transform_owns_pointer = input.transform_owns_pointer; + // Right-click while transforming: switch the box's mode (Free Transform, Scale, Rotate, + // Skew, Distort, Perspective, Warp), or rotate or flip the box. + let transforming = app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()); + if response.secondary_clicked() + && transforming + && let Some(p) = response.interact_pointer_pos() + { + crate::canvas_tool_menu::open_transform(app, &ctx, [p.x, p.y]); + } + let lasso_retracted = response.secondary_clicked() + && match tool { + Tool::Lasso | Tool::FreeformPen => crate::lasso_ui::undo_last_vertex(app), + Tool::PolygonLasso => polygon_retract(app), + _ => false, + }; + // The Lasso (and the Freeform Pen, which draws the same way) reads its own presses and + // drops the moves of a drag it didn't start, so an open Free Transform box takes the + // usual drag path instead (#2153). + if crate::lasso_ui::owns(tool) && !transform_owns_pointer { + crate::lasso_ui::canvas_input(app, &ctx, &xf, &response); + (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); + } + // Right-click on a guide where it could be dragged (the Move tool, or ⌘ with a selection + // tool): select it and open the guide menu, as Photoshop does. + let guide_menu = response.secondary_clicked() + && !lasso_retracted + && !transforming + && response.interact_pointer_pos().is_some_and(|p| crate::canvas_tool_menu::open_guide(app, &ctx, tool, mods, [p.x, p.y], xf.to_doc(p))); + // Right-click with the Move tool, or ⌘/Ctrl+right-click: the layers under the pointer. + if response.secondary_clicked() + && !lasso_retracted + && !transforming + && !guide_menu + && crate::layer_pick_ui::is_gesture(tool, mods) + && let Some(p) = response.interact_pointer_pos() + { + let d = xf.to_doc(p); + app.ui.canvas_tool_menu = None; + // No layers there (the pasteboard, with the Move tool): its colour menu instead. + if !crate::layer_pick_ui::open(app, &ctx, [p.x, p.y], d[0], d[1]) && !mods.command && crate::canvas_tool_menu::pasteboard_at(app, tool, d) { + crate::canvas_tool_menu::open_pasteboard(app, &ctx, tool, [p.x, p.y]); + } + } + if response.secondary_clicked() + && !lasso_retracted + && !transforming + && !guide_menu + && !crate::layer_pick_ui::is_gesture(tool, mods) + && let Some(p) = response.interact_pointer_pos() + { + // A pending crop: its menu, also outside the image, where the frame can reach (#6561). + // Outside the image: the pasteboard colour menu (#2462), else the tool's own. The view + // menu belongs to the selected Zoom or Hand, not to Space or a held zoom key. A crop + // frame or Straighten line still dragged by the left button gets no menu over it: the + // gesture and the held button both, as either alone can outlive a lost release. A + // finger held still (egui's press-and-hold right-click) is down too, but drags nothing. + let crop_gesture = tool == Tool::Crop + && !response.long_touched() + && (app.crop.drag.is_some() || app.crop.straighten.line.is_some()) + && ctx.input(|i| i.pointer.primary_down()); + if crop_gesture || crate::canvas_tool_menu::open_crop(app, &ctx, tool, [p.x, p.y]) { + } else if crate::canvas_tool_menu::pasteboard_at(app, tool, xf.to_doc(p)) { + crate::canvas_tool_menu::open_pasteboard(app, &ctx, tool, [p.x, p.y]); + } else if crate::canvas_tool_menu::is_view_tool(tool) { + if tool == app.ui.tool { + crate::canvas_tool_menu::open_view(app, &ctx, tool, [p.x, p.y], xf.to_doc(p)); + } + } else { + crate::canvas_tool_menu::open_at(app, &ctx, tool, [p.x, p.y], Some(xf.to_doc(p))); + } + } +} + +fn handle_canvas_tool_navigation( + app: &mut PhotocraftApp, + _ui: &mut egui::Ui, + view: &mut View, + input: &CanvasToolInput<'_>, + buttons: &mut crate::paint_mouse::Buttons, +) { + let ctx = input.ctx; + let response = input.response; + let xf = input.xf; + let tool = input.tool; + let idx = input.idx; + let primary = input.primary; + let transform_owns_pointer = input.transform_owns_pointer; + let hand_pan = input.hand_pan; + let ppp = input.ppp; + let zoom_out = input.zoom_out; + // The (temporary) Hand pans above; its gestures never reach the tool underneath. While a + // Free Transform box is open the Hand does not pan, so the box gets these events (#2302). + if hand_pan { + (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); + } + // Rotate View: drag around the view centre. Compass clicks are not a rotate drag. + let over_compass = crate::rotate_view::compass_visible(view.rotation) + && response.interact_pointer_pos().is_some_and(|p| crate::rotate_view::compass_rect(xf.rect).contains(p)); + if tool == Tool::RotateView && !over_compass && crate::rotate_view::drag(&ctx, view, &xf, &buttons, response.interact_pointer_pos()) { + (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); + } + // Animated Zoom: a Zoom press held still zooms continuously (zoom_hold.rs); while it does, + // 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 = false; + let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); + if crate::zoom_hold::update(&ctx, 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); + } + } + // Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below. + // Like the Hand, the selected Zoom yields to an open Free Transform box (#4799). + if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, &ctx, view, &xf, &buttons, response.interact_pointer_pos()) { + (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); + } +} + +fn handle_canvas_tool_stroke( + app: &mut PhotocraftApp, + ui: &mut egui::Ui, + input: &CanvasToolInput<'_>, + mods: egui::Modifiers, + capture_press: bool, + tool_press: egui::Id, + buttons: &mut crate::paint_mouse::Buttons, +) { + let ctx = input.ctx; + let response = input.response; + let xf = input.xf; + let rect = input.rect; + let full = input.full; + let tool = input.tool; + // A drag is only recognised once the pointer has moved past egui's click distance: the + // gesture starts where the button went down, not where it is now (#123). + let gesture_active_before = app.drag.is_some(); + // Stroke timing: egui's events carry no timestamps, so a press takes the frame time and + // the moves below are spread between the previous point and this frame (`spread_ms`). + let now_ms = ui.input(|i| i.time) * 1000.0; + app.stylus.clock_ms = now_ms; + // Live painting tools start on the press, not once the pointer passes egui's click + // distance: the first dab shows at once. The drag recognised later continues that stroke, + // and a click (or a long press that never moved) just ends it. + let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); + let right_down = ui.input(|i| i.pointer.secondary_down()) || physical_right; + if strokes_live(tool) + && !right_down + && app.drag.is_none() + && response.is_pointer_button_down_on() + && ui.input(|i| i.pointer.primary_pressed()) + && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)) + { + let d = xf.to_doc(p); + // The press's own modifiers: a ⇧ that arrives with the click still connects the line. + let press_mods = ui.input(|i| pointer_button_modifiers(&i.events, PointerButton::Primary)).unwrap_or(mods); + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); + app.press_stroke = app.drag.is_some(); + } + let press_stroke = app.press_stroke; + // A live tool's press that went to the ⌥ eyedropper keeps sampling for the whole press: the + // drag recognised later must not decide again with ⌥ already let go and paint (#7802). + if press_stroke || (strokes_live(tool) && (app.alt_sampling || app.mixer_sampling)) { + buttons.started = false; + } + if buttons.started + && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) + { + if tool == Tool::Move && app.ui.transform.is_none() { + begin_transform_controls_at(app, &ctx, &xf, p); + } + let d = xf.to_doc(p); + let press_mods = if capture_press { ctx.data(|d| d.get_temp(tool_press)).unwrap_or(mods) } else { mods }; + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); + } + // A stroke started on the press takes its moves from the press on, not only once egui + // recognises a drag (past its click distance): otherwise the first few points are lost + // and the stroke starts with a straight segment and no pressure ramp. + let press_stroke_moving = press_stroke && app.drag.is_some(); + if buttons.dragged || buttons.stopped || press_stroke_moving { + // Feed every pointer move the OS delivered this frame, not just the latest position, so + // a fast stroke is sampled densely and renders as a smooth curve instead of a coarse + // polyline. egui-winit pushes one `PointerMoved` per `CursorMoved`, and they accumulate + // while a frame is slow, so reading them all recovers the moves a per-frame + // `interact_pointer_pos()` would drop. Only freehand tools take the whole batch; the + // rest follow the pointer's latest position. The moves are bounded to the gesture's own + // press..release interval (`pointer_moves`), so the start and stop frames keep their + // valid samples without leaking a move from outside the gesture. + let events = ui.input(|i| i.events.clone()); + let button = if response.dragged_by(PointerButton::Secondary) + || response.drag_started_by(PointerButton::Secondary) + || response.drag_stopped_by(PointerButton::Secondary) + { + PointerButton::Secondary + } else { + PointerButton::Primary + }; + let press_this_frame = events.iter().any(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: true, .. } if *b == button)); + let down_at_start = !press_this_frame && (gesture_active_before || buttons.started); + let mut positions = if app.brush_resize.is_some() { + response.interact_pointer_pos().into_iter().collect() + } else if freehand_tool(tool) { + pointer_moves(&events, button, down_at_start) + } else if buttons.dragged { + response.interact_pointer_pos().into_iter().collect() + } else { + Vec::new() + }; + // A frame with no raw move still tracks a held gesture (a still pointer, a modifier + // change): fall back to the latest position, as the old code always did. + if positions.is_empty() + && (buttons.dragged || press_stroke_moving) + && let Some(p) = response.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos())) + { + positions.push(p); + } + app.defer_live_stroke = true; + let base = app.stylus.last_point_ms().map_or(now_ms, |t| t.min(now_ms)); + let n = positions.len(); + for (k, p) in positions.into_iter().enumerate() { + app.stylus.clock_ms = spread_ms(base, now_ms, k, n); + // This move's share of the pen samples the frame brought (pressure, tilt, rotation). + app.stylus.select(k, n); + let d = xf.to_doc(p); + tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods); + } + app.stylus.clear_selection(); + app.stylus.clock_ms = now_ms; + // A held pen keeps the clock running for airbrush build-up and smoothing catch-up. + if app.drag.is_some() && stroke_wants_time(app) { + ctx.request_repaint_after(std::time::Duration::from_millis(HOLD_REPEAT_MS as u64)); + } + app.defer_live_stroke = false; + // One live-stroke update for the whole frame, not one per recovered sample. + feed_live_stroke(app); + crate::magnetic_lasso_ui::flush(app); + } + if buttons.stopped { + // The live painting press already created the stroke and this release commits it. + // egui may also report clicked on the same release; replaying that click paints a + // second full-pressure dab over the real (possibly light-pressure) pen dab. + if press_stroke { + buttons.clicked = false; + } + let at = response.interact_pointer_pos(); + // #6286: a guide let go over a ruler is removed, whichever ruler it is. Tested here in + // screen space, where the rulers are: on the guide's own axis the release can still be + // inside the document, which is what `finish_drag` sees. + if app.guide_drag.is_some() { + let on_ruler = at.is_some_and(|p| crate::rulers::dropped_on_a_ruler(app, full, p)); + if let Some(g) = app.guide_drag.as_mut() { + g.over_ruler = on_ruler; + } + } + let p = at.map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]]))); + if let Some(d) = p { + tap_at_peak_pressure(app); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods); + } + } + // A stroke started on the press ends with the release, whether egui saw a drag, a click, + // or neither (a long press that never moved). + if press_stroke && !buttons.stopped && ui.input(|i| i.pointer.primary_released()) { + buttons.clicked = false; + let p = response.interact_pointer_pos().map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]]))); + if let Some(d) = p + && app.drag.is_some() + { + tap_at_peak_pressure(app); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods); + } + } + if press_stroke && (app.drag.is_none() || !ui.input(|i| i.pointer.primary_down())) { + app.press_stroke = false; + } +} + +fn handle_canvas_tool_clicks( + app: &mut PhotocraftApp, + ui: &mut egui::Ui, + view: &mut View, + input: &CanvasToolInput<'_>, + mods: egui::Modifiers, + tool_press: egui::Id, + buttons: &crate::paint_mouse::Buttons, +) { + let ctx = input.ctx; + let response = input.response; + let xf = input.xf; + let rect = input.rect; + let tool = input.tool; + let transform_owns_pointer = input.transform_owns_pointer; + let ppp = input.ppp; + let zoom_out = input.zoom_out; + let display_zoom = input.display_zoom; + if buttons.clicked + && let Some(p) = response.interact_pointer_pos() + { + let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; + let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); + let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { + ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) + } else { + click_mods + }; + let d = xf.to_doc(p); + match tool { + Tool::Zoom if !transform_owns_pointer => { + let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); + let center = app.session.prefs().tools.zoom_clicked_point_to_center; + let doc_anchor = xf.to_doc(p); + let screen_anchor = p; + zoom_about(view, &xf, p, nz, center, ppp); + view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_zoom); + view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); + } + // A click with the (temporary) Hand does nothing, never the tool underneath. + Tool::Hand | Tool::RotateView => {} + // Double-clicking closes the polygonal lasso: the first click placed the last + // vertex (or already closed it), so the second never starts a new polygon. egui + // reports it as a triple click when a vertex went down shortly before. + Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app), + // The same for the Magnetic Lasso: along the edges, or straight with ⌥. + Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt), + // The first click placed (or grabbed) the point; the second toggles it. + Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), + // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. + Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { + if let Err(e) = crate::menus::invoke(app, &ctx, "edit.preferences.guidesGridAndSlices", json!({})) { + app.ui.status = e; + } + } + _ => { + if tool == Tool::Move && app.ui.transform.is_none() { + begin_transform_controls_at(app, &ctx, &xf, p); + } + // If this tool was not handled on pointer-down, fall back to a + // click-sized gesture while preserving pen pressure (mouse stays at 1). + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods); + tap_at_peak_pressure(app); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods); + } + } + } + // Magnetic Lasso: between clicks the border follows the pointer with the button up. + if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && response.hovered() { + let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); + app.defer_live_stroke = true; + for p in moves.into_iter().filter(|p| rect.contains(*p)) { + let d = xf.to_doc(p); + tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods); + } + app.defer_live_stroke = false; + crate::magnetic_lasso_ui::flush(app); + } + // Move tool: a double-click on type edits it, as in Photoshop (#1132). Only the selected + // Move tool, not ⌘ held over another tool; an open transform box keeps its double-click + // (commit, below). + if tool == Tool::Move + && app.ui.tool == Tool::Move + && app.ui.transform.is_none() + && response.double_clicked() + && let Some(p) = response.interact_pointer_pos() + { + let d = xf.to_doc(p); + crate::type_tool::edit_at(app, d[0], d[1]); + } + if app.ui.transform.is_some() && response.double_clicked() { + crate::transform_tool::commit(app); + } + if crate::cam_transform::active(app) && response.double_clicked() { + crate::cam_transform::commit(app); + } + // Crop: a double-click inside the frame commits it, as ↵ does (#1792). + if tool == Tool::Crop && response.double_clicked() && response.interact_pointer_pos().is_some_and(|p| crate::crop_ui::commits_at(app, xf.to_doc(p))) { + commit_crop(app); + } + // Type: 2 clicks select a word, 3 the line, 4 the paragraph, 5 all text (Photoshop). + if tool.is_type() + && response.clicked() + && let Some(p) = response.interact_pointer_pos() + { + if crate::type_transform::visible(app, crate::workspace_ui::sticky_mods(app, mods)) { + app.type_clicks = None; + } else { + let n = if response.triple_clicked() { + 3 + } else if response.double_clicked() { + 2 + } else { + 1 + }; + let d = xf.to_doc(p); + crate::type_tool::multi_click(app, n, d[0], d[1]); + } + } +} + +struct CanvasOverlayInput<'a> { + ctx: &'a egui::Context, + painter: &'a egui::Painter, + xf: &'a ViewXform, + response: &'a egui::Response, + doc: &'a std::sync::Arc, + tool: Tool, + idx: usize, + output: Option, + border: photocraft_engine::prefs::CanvasBorder, + beyond: bool, + edge_rect: Rect, + panning: bool, + zoom_out: &'a dyn Fn(bool) -> bool, +} + +fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, input: &CanvasOverlayInput<'_>) { + let ctx = input.ctx; + let painter = input.painter; + let xf = input.xf; + let response = input.response; + let doc = input.doc; + let idx = input.idx; + let border = input.border; + let beyond = input.beyond; + let edge_rect = input.edge_rect; + // The transform preview is image content: it goes under the grid and guides, which + // stay visible across a layer being transformed (#5086); the box is drawn later. + crate::transform_tool::draw_content(app, &painter, &xf); + // So are Puppet Warp's, Perspective Warp's and Vanishing Point's warped pixels (#7781). + crate::distort_ui::draw_content(app, &painter, &xf); + if app.ui.extras.grid && app.ui.view.extras { + crate::rulers::draw_grid(app, &painter, &xf, &doc); + } + if app.ui.view.shows(app.ui.view.show.canvas_guides) || crate::guide_layout_ui::preview(app, &doc).is_some() { + crate::rulers::draw_guides(app, &painter, &xf, &doc); + } + // The pending crop frame shows on its own document only, not on the other tiles (#1918). + let foreign_crop = if app.session.active_index() == Some(idx) { None } else { app.ui.crop_rect.take() }; + draw_drag_preview(app, &painter, &xf); + if app.session.active_index() == Some(idx) { + crate::move_box::draw(app, &painter, &xf); + } + if foreign_crop.is_some() { + app.ui.crop_rect = foreign_crop; + } + crate::zoom_tool::draw(&ctx, &painter); + let resizing = crate::brush_resize::draw(app, &painter, &xf); + draw_transform_controls(app, &painter, &xf); + crate::move_hover::draw(app, &painter, &xf, idx, response.hover_pos()); + crate::object_finder::draw(app, &painter, &xf, idx, response.hover_pos()); + crate::layer_pick_ui::show(app, &ctx); + let shown = app.ui.views.get(idx).cloned(); + crate::canvas_tool_menu::show(app, &ctx); + // A view menu row (Zoom In, Fit on Screen…) changed the camera: it wins over this + // frame's copy, which is written back at the end. + if let Some(now) = app.ui.views.get(idx) + && Some(now) != shown.as_ref() + { + *view = now.clone(); + ctx.request_repaint(); + } + crate::snap_ui::draw(app, &painter, &xf); + crate::move_distance::draw(app, &painter, &xf, idx, response.hover_pos()); + // The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview), + // nor while the Crop tool hides everything outside its box (Show Cropped Area off). + if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond && !crate::crop_shield::hides_outside(app) { + painter.rect_stroke(edge_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside); + } + crate::type_tool::draw_overlay(app, &painter, &xf); + crate::transform_tool::draw_overlay(app, &painter, &xf); + crate::cam_transform::draw(app, &painter, &xf); + crate::cam_preview::wake(app, painter.ctx()); + crate::distort_ui::draw_overlay(app, &painter, &xf); + crate::perspective_crop_ui::draw_overlay(app, &painter, &xf); + crate::retouch_ui::draw_source_marker(app, &painter, &xf); + crate::vector_ui::draw_overlay(app, &painter, &xf, &doc); + crate::symmetry_ui::draw(app, &painter, &xf); + crate::analysis_ui::draw_overlay(app, &painter, &xf); + crate::gradient_ui::draw_overlay(app, &painter, &xf); + crate::slice_ui::draw_overlay(app, &painter, &xf); + crate::frame_tool::draw_overlay(app, &painter, &xf); + crate::artboard_tool::draw_overlay(app, &painter, &xf); + + draw_canvas_tool_cursor(app, ui, input, resizing); +} + +fn draw_canvas_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &CanvasOverlayInput<'_>, resizing: bool) { + let ctx = input.ctx; + let xf = input.xf; + let response = input.response; + let tool = input.tool; + let panning = input.panning; + // Tool cursors (Photoshop-style). + let guide_hover = response.hover_pos().and_then(|p| { + let d = xf.to_doc(p); + if tool == Tool::Move { + return crate::rulers::guide_at(app, d[0], d[1]); + } + command_guide_at(app, tool, d, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))) + }); + if panning { + // The fist set with the pan above stays (#2196). + } else if crate::tool_cursor::pointer_elsewhere(&ctx, &crate::panel_docking::native_viewports(app, &ctx)) { + // The pointer is over a floating panel's own window; this window's last position of + // it is stale, so no tool cursor or brush outline is painted at it. + } else if let Some((vertical, _)) = guide_hover { + ui.ctx().set_cursor_icon(crate::rulers::guide_cursor(&xf, vertical)); + } else if let Some((p, mods, c)) = response.hover_pos().and_then(|p| { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + let c = crate::transform_tool::cursor(app, &xf, xf.to_doc(p), mods)?; + Some((p, mods, c)) + }) { + ui.ctx().set_cursor_icon(c); + // CursorIcon::None hides the pointer; the curved arrow has to be drawn or the + // rotate zone looks like a plain cursor (#4050). + let d = xf.to_doc(p); + if let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { + let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; + crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + } else if c == egui::CursorIcon::None { + // Likewise the distort and skew pointers over a handle (#5405). + crate::transform_tool::draw_handle_cursor(app, &ctx, &xf, p, mods); + } + } else if let Some(c) = response.hover_pos().and_then(|p| crate::symmetry_ui::cursor(app, &xf, xf.to_doc(p))) { + ui.ctx().set_cursor_icon(c); + } else if let Some(c) = response.hover_pos().and_then(|p| crate::cam_transform::cursor(app, &ctx, &xf, p)) { + ui.ctx().set_cursor_icon(c); + } else if let Some(p) = response.hover_pos().filter(|p| crate::corner_radius::hovers(app, xf.to_doc(*p))) { + // Over a live rectangle's corner widget (or dragging one): the arrow with a rounded + // corner badge, as Photoshop's corner radius cursor. + ui.ctx().set_cursor_icon(egui::CursorIcon::Default); + crate::icons::cursor_badge(&ctx, "scan", p); + } else if let Some((r, p, c)) = response + .hover_pos() + .filter(|_| !transform_controls_several(app)) + .and_then(|p| transform_controls_rect(app, &xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c)))) + { + // The Move tool draws handles without opening a Free Transform session. + // Give them their resize/rotate cursors before the first pointer press (#2871). + ui.ctx().set_cursor_icon(c); + if let Some(toward) = transform_controls_turn(r, p) { + crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + } + } else if let Some(c) = response.hover_pos().filter(|_| tool.is_type()).and_then(|p| { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + crate::type_transform::cursor(app, &ctx, &xf, p, mods) + }) { + ui.ctx().set_cursor_icon(c); + } else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Artboard).and_then(|p| crate::artboard_tool::cursor(app, &xf, xf.to_doc(p))) { + ui.ctx().set_cursor_icon(c); + } else if let Some((p, c)) = response.hover_pos().filter(|_| tool == Tool::Crop).and_then(|p| Some((p, crate::crop_ui::cursor(app, xf.to_doc(p))?))) { + ui.ctx().set_cursor_icon(c); + let d = xf.to_doc(p); + if let Some(k) = crate::crop_ui::turn_cursor_dir(app, d) { + let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; + crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + } + } else if let Some(p) = response.hover_pos() + && let Some(c) = selection_cursor(app, tool, xf.to_doc(p), crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))) + { + // Over a selection (Photoshop's cursors): the move cursor where a press drags the + // outline (#1428), the arrow with a badge for what a press does to the selected + // pixels, a hollow arrowhead while they are dragged, a plain arrow over a floating + // piece. + let icon = match c { + SelCursor::Outline => egui::CursorIcon::Move, + SelCursor::Dragging => { + // The tip of the arrowhead is at (4, 4) of its 24-unit box. + crate::icons::cursor(ui.ctx(), "mouse-pointer-2", p, vec2(4.0, 4.0) / 24.0, 18.0); + egui::CursorIcon::None + } + SelCursor::Piece => egui::CursorIcon::Default, + SelCursor::Cut => { + crate::icons::cursor_badge(ui.ctx(), "scissors", p); + egui::CursorIcon::Default + } + SelCursor::Copy => { + crate::icons::cursor_copy_badge(ui.ctx(), p); + egui::CursorIcon::Default + } + }; + ui.ctx().set_cursor_icon(icon); + } else if let Some(p) = response.hover_pos() { + draw_default_tool_cursor(app, ui, input, resizing, p); + } +} + +fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &CanvasOverlayInput<'_>, resizing: bool, p: Pos2) { + let painter = input.painter; + let xf = input.xf; + let response = input.response; + let tool = input.tool; + let output = input.output; + let zoom_out = input.zoom_out; + + let alt = ui.input(|i| i.modifiers.alt); + if !resizing && !alt && !app.ui.shell.sticky_alt { + draw_clone_preview(app, &painter, &xf, xf.to_doc(p), output); + } + // The Type tool over a path shows Photoshop's area-type or type-on-a-path pointer (#218). + // Not while a type edit is open or a text box is dragged out, nor over type a click + // would edit (`hover_path_target`). + let type_path = if matches!(tool, Tool::Type | Tool::VerticalType) { + let [x, y] = xf.to_doc(p); + let shift = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)).shift; + crate::type_tool::hover_path_target(app, x, y, shift) + } else { + None + }; + let icon = match tool { + // Resizing the brush: the circle stays where the drag began (`brush_resize`). + t if resizing && crate::brush_resize::applies(t) => egui::CursorIcon::None, + // ⌥ turns a painting tool into the Eyedropper (`alt_eyedropper`): its cursor too, + // unless Preferences › Cursors › Other Cursors asks for the precise crosshair. + t if app.alt_sampling + || (app.drag.is_none() + && !app.services.right_button_down.as_ref().is_some_and(|f| f()) + && alt_samples(t, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)))) => + { + // While it samples (button held), the comparison ring replaces the cursor (#213). + if let Some(icon) = eyedropper_ring(app, &painter, &xf, p, response.is_pointer_button_down_on()) { + icon + } else if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { + egui::CursorIcon::Crosshair + } else { + pipette_cursor(ui.ctx(), p) + } + } + t if t.is_brushlike() || t == Tool::QuickSelection => { + // Preferences › Cursors: brush tip outline (normal = the 50% contour, or + // full size), precise crosshair, or the standard pointer. + use photocraft_engine::prefs::PaintingCursor; + let cur = app.session.prefs().cursors.clone(); + // ⇪ forces the precise crosshair, whatever the cursor preference (#1758). + if app.caps_lock { + crate::tool_cursor::crosshair(&painter, p, 6.0, 0.0) + } else { + let painting = app.drag.is_some(); + let brush = &app.session.tools.brush; + let full = (brush.size / 2.0 * xf.zoom).max(1.0); + match cur.painting { + PaintingCursor::Standard => egui::CursorIcon::Default, + PaintingCursor::Precise => crate::tool_cursor::crosshair(&painter, p, 6.0, 0.0), + _ if painting && cur.show_only_crosshair_while_painting => crate::tool_cursor::crosshair(&painter, p, 5.0, 0.0), + // The Pencil (and the Eraser in Pencil mode): the outline of the + // whole pixels its dab fills, on the pixel grid. A round tip is a + // disc, a tiny one the whole square (#2662). The Block-mode Eraser: + // its square, 16 screen pixels at any zoom (#2770). + _ if tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool) || crate::eraser_ui::block_mode(app, tool) => { + let block = crate::eraser_ui::block_mode(app, tool); + let size = if block { crate::eraser_ui::block_size(app) } else { brush.size }; + let ppp = painter.ctx().pixels_per_point(); + let sq = pencil_cursor_rect(&xf, xf.to_doc(p), size, ppp); + let px = 1.0 / ppp; + let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(230))); + if !block && pencil_tip_is_round(size) { + let r = sq.width() / 2.0; + painter.circle_stroke(sq.center(), r + px / 2.0, dark); + painter.circle_stroke(sq.center(), (r - px / 2.0).max(0.0), light); + } else { + painter.rect_stroke(sq, 0.0, dark, egui::StrokeKind::Outside); + painter.rect_stroke(sq, 0.0, light, egui::StrokeKind::Inside); + } + // Too small to see where it is: the hotspot as well. + if cur.show_crosshair_in_brush_tip || sq.width() < 6.0 { + crate::tool_cursor::crosshair(&painter, p, 4.0, 0.0); + } + egui::CursorIcon::None + } + // A shaped tip (sampled bitmap, or a rotated/flattened round tip) + // traces its outline, turned and flipped with the view; a plain round + // tip keeps the circle. + _ => { + let centre = brush_tip_centre(tool, alt || app.ui.shell.sticky_alt, cur.show_crosshair_in_brush_tip); + let axes = crate::brush_cursor::pen_axes(&xf, brush, app.stylus.sample()); + crate::brush_cursor::cursor(&painter, p, brush, full, axes, cur.painting == PaintingCursor::NormalTip, centre) + } + } + } + } + // The Eyedropper: the comparison ring follows the pointer while it samples (#213); + // otherwise its pipette, or the crosshair for precise Other Cursors. + Tool::Eyedropper => { + if let Some(icon) = eyedropper_ring(app, &painter, &xf, p, response.is_pointer_button_down_on()) { + icon + } else if precise_other_cursor(app) { + egui::CursorIcon::Crosshair + } else { + pipette_cursor(ui.ctx(), p) + } + } + // The Color Sampler: a pipette, or the crosshair for precise Other Cursors. + Tool::ColorSampler => { + if precise_other_cursor(app) { + egui::CursorIcon::Crosshair + } else { + pipette_cursor(ui.ctx(), p) + } + } + // The Paint Bucket: a bucket, or the crosshair for precise Other Cursors (#3968). + Tool::PaintBucket => { + if precise_other_cursor(app) { + egui::CursorIcon::Crosshair + } else { + paint_bucket_cursor(ui.ctx(), p) + } + } + // Over the first anchor, the close-path pointer (#4596), before the pens' own cursors. + Tool::Pen | Tool::CurvaturePen + if { + let [x, y] = xf.to_doc(p); + crate::vector_ui::closes_path_at(app, tool, x, y) + } => + { + crate::tool_cursor::close_path(&painter, p) + } + // The pen tools: their own icon with its nib on the point, or the crosshair for + // precise Other Cursors (#4639). + Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { + if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { pen_cursor(ui.ctx(), tool, p) } + } + // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. + Tool::Move | Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask + if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise => + { + egui::CursorIcon::Crosshair + } + // Photoshop's Move tool keeps the standard arrow pointer (#5646): the movable + // layer under it is marked by the hover outline, not by a different cursor. + Tool::Move => egui::CursorIcon::Default, + // Dragging is handled with the pan itself, above. + Tool::Hand => crate::tool_cursor::hand(ui.ctx(), false), + Tool::RotateView => crate::rotate_view::cursor(response.dragged()), + Tool::Zoom => crate::tool_cursor::zoom(ui.ctx(), zoom_out(alt)), + Tool::Type | Tool::VerticalType if type_path.is_some() => match type_path { + Some(crate::type_tool::PathClick::Area { .. }) => crate::tool_cursor::area_type(&painter, p), + _ => crate::tool_cursor::path_type(&painter, p), + }, + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => egui::CursorIcon::Text, + Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, &painter, p, xf.zoom), + Tool::RedEye => { + let pupil = app.ui.tool_options.red_eye_pupil_size.clamp(1.0, 100.0); + let r_doc = photocraft_algo::redeye::search_radius(pupil); + let r = (r_doc * xf.zoom).max(2.0); + painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140))); + painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220))); + for (w, c) in [(2.5, Color32::from_black_alpha(140)), (1.0, Color32::from_white_alpha(220))] { + painter.line_segment([p - vec2(3.0, 0.0), p + vec2(3.0, 0.0)], Stroke::new(w, c)); + painter.line_segment([p - vec2(0.0, 3.0), p + vec2(0.0, 3.0)], Stroke::new(w, c)); + } + egui::CursorIcon::None + } + _ => egui::CursorIcon::Crosshair, + }; + let icon = visible_crosshair(icon, &painter, p, cfg!(not(target_arch = "wasm32"))); + ui.ctx().set_cursor_icon(icon); + // Selection tools: + / − / × badge for the effective mode (#170). A gesture keeps the + // mode it started with (⇧ then constrains the marquee instead of adding). + let held = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + let mods = app.drag.as_ref().map_or(held, |d| d.modifiers); + if let Some(b) = crate::tool_feedback::badge(app, tool, mods) { + crate::tool_feedback::draw_badge(&painter, p, b, tool == Tool::QuickSelection); + } + // ⇧ after a stroke: the straight line a click would paint (#257). + crate::stroke_constraint::draw_line_preview(app, &painter, &xf, p, tool, held.shift); +} + 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 +1692,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 +1719,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 +1770,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 @@ -881,379 +1837,23 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::layer_picker::sample_at(app, d[0], d[1]); } } else if primary && !stroke_dismissal { - let mods = ui.input(|i| i.modifiers); - // An ⌥-click the window manager took never arrives; say so (alt_grab.rs). - crate::alt_grab::watch(app, &ctx, egui::Id::unique(("pc-alt-grab", idx)), rect, tool, !under_dialog); - // Tools follow the left button; the right one opens the Brush Preset picker or erases - // (Preferences › Tools, `paint_mouse`). - crate::paint_mouse::sync_tool_brush(app); - let mut buttons = crate::paint_mouse::canvas_buttons(app, &response, tool); - // The Crop tool's frame is edited from the press (before egui's drag threshold), so the - // pixels past the canvas show at once, as in Photoshop. - if tool == Tool::Crop && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down()) && crate::crop_ui::press(app) { - ctx.request_repaint(); - } - // Capture intent at the press, before egui's drag threshold or click replay on release: - // Type transforms keep Command; selections keep Add/Subtract if Shift/Alt is released. - let capture_press = tool.is_type() - || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee | Tool::ObjectSelection); - let tool_press = egui::Id::unique(("tool-pointer-press-modifiers", idx)); - if capture_press - && let Some((p, press_mods)) = ui.input(|i| { - i.events.iter().find_map(|e| match e { - egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers } if rect.contains(*pos) => { - Some((*pos, *modifiers)) - } - _ => None, - }) - }) - { - let press_mods = crate::workspace_ui::sticky_mods(app, press_mods); - ctx.data_mut(|d| d.insert_temp(tool_press, press_mods)); - if tool.is_type() && press_mods.command && app.ui.text_edit.is_some() { - let d = xf.to_doc(p); - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); - } - } - // Right-click while transforming: switch the box's mode (Free Transform, Scale, Rotate, - // Skew, Distort, Perspective, Warp), or rotate or flip the box. - let transforming = app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()); - if response.secondary_clicked() - && transforming - && let Some(p) = response.interact_pointer_pos() - { - crate::canvas_tool_menu::open_transform(app, &ctx, [p.x, p.y]); - } - let lasso_retracted = response.secondary_clicked() - && match tool { - Tool::Lasso | Tool::FreeformPen => crate::lasso_ui::undo_last_vertex(app), - Tool::PolygonLasso => polygon_retract(app), - _ => false, - }; - // The Lasso (and the Freeform Pen, which draws the same way) reads its own presses and - // drops the moves of a drag it didn't start, so an open Free Transform box takes the - // usual drag path instead (#2153). - if crate::lasso_ui::owns(tool) && !transform_owns_pointer { - crate::lasso_ui::canvas_input(app, &ctx, &xf, &response); - (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); - } - // Right-click on a guide where it could be dragged (the Move tool, or ⌘ with a selection - // tool): select it and open the guide menu, as Photoshop does. - let guide_menu = response.secondary_clicked() - && !lasso_retracted - && !transforming - && response.interact_pointer_pos().is_some_and(|p| crate::canvas_tool_menu::open_guide(app, &ctx, tool, mods, [p.x, p.y], xf.to_doc(p))); - // Right-click with the Move tool, or ⌘/Ctrl+right-click: the layers under the pointer. - if response.secondary_clicked() - && !lasso_retracted - && !transforming - && !guide_menu - && crate::layer_pick_ui::is_gesture(tool, mods) - && let Some(p) = response.interact_pointer_pos() - { - let d = xf.to_doc(p); - app.ui.canvas_tool_menu = None; - // No layers there (the pasteboard, with the Move tool): its colour menu instead. - if !crate::layer_pick_ui::open(app, &ctx, [p.x, p.y], d[0], d[1]) && !mods.command && crate::canvas_tool_menu::pasteboard_at(app, tool, d) { - crate::canvas_tool_menu::open_pasteboard(app, &ctx, tool, [p.x, p.y]); - } - } - if response.secondary_clicked() - && !lasso_retracted - && !transforming - && !guide_menu - && !crate::layer_pick_ui::is_gesture(tool, mods) - && let Some(p) = response.interact_pointer_pos() - { - // A pending crop: its menu, also outside the image, where the frame can reach (#6561). - // Outside the image: the pasteboard colour menu (#2462), else the tool's own. The view - // menu belongs to the selected Zoom or Hand, not to Space or a held zoom key. A crop - // frame or Straighten line still dragged by the left button gets no menu over it: the - // gesture and the held button both, as either alone can outlive a lost release. A - // finger held still (egui's press-and-hold right-click) is down too, but drags nothing. - let crop_gesture = tool == Tool::Crop - && !response.long_touched() - && (app.crop.drag.is_some() || app.crop.straighten.line.is_some()) - && ctx.input(|i| i.pointer.primary_down()); - if crop_gesture || crate::canvas_tool_menu::open_crop(app, &ctx, tool, [p.x, p.y]) { - } else if crate::canvas_tool_menu::pasteboard_at(app, tool, xf.to_doc(p)) { - crate::canvas_tool_menu::open_pasteboard(app, &ctx, tool, [p.x, p.y]); - } else if crate::canvas_tool_menu::is_view_tool(tool) { - if tool == app.ui.tool { - crate::canvas_tool_menu::open_view(app, &ctx, tool, [p.x, p.y], xf.to_doc(p)); - } - } else { - crate::canvas_tool_menu::open_at(app, &ctx, tool, [p.x, p.y], Some(xf.to_doc(p))); - } - } - // The (temporary) Hand pans above; its gestures never reach the tool underneath. While a - // Free Transform box is open the Hand does not pan, so the box gets these events (#2302). - if hand_pan { - (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); - } - // Rotate View: drag around the view centre. Compass clicks are not a rotate drag. - let over_compass = crate::rotate_view::compass_visible(view.rotation) - && response.interact_pointer_pos().is_some_and(|p| crate::rotate_view::compass_rect(xf.rect).contains(p)); - if tool == Tool::RotateView && !over_compass && crate::rotate_view::drag(&ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) { - (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); - } - // Animated Zoom: a Zoom press held still zooms continuously (zoom_hold.rs); while it does, - // 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 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); - } - } - // Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below. - // Like the Hand, the selected Zoom yields to an open Free Transform box (#4799). - if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) { - (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); - } - // A drag is only recognised once the pointer has moved past egui's click distance: the - // gesture starts where the button went down, not where it is now (#123). - let gesture_active_before = app.drag.is_some(); - // Stroke timing: egui's events carry no timestamps, so a press takes the frame time and - // the moves below are spread between the previous point and this frame (`spread_ms`). - let now_ms = ui.input(|i| i.time) * 1000.0; - app.stylus.clock_ms = now_ms; - // Live painting tools start on the press, not once the pointer passes egui's click - // distance: the first dab shows at once. The drag recognised later continues that stroke, - // and a click (or a long press that never moved) just ends it. - let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); - let right_down = ui.input(|i| i.pointer.secondary_down()) || physical_right; - if strokes_live(tool) - && !right_down - && app.drag.is_none() - && response.is_pointer_button_down_on() - && ui.input(|i| i.pointer.primary_pressed()) - && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)) - { - let d = xf.to_doc(p); - // The press's own modifiers: a ⇧ that arrives with the click still connects the line. - let press_mods = ui.input(|i| pointer_button_modifiers(&i.events, PointerButton::Primary)).unwrap_or(mods); - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); - app.press_stroke = app.drag.is_some(); - } - let press_stroke = app.press_stroke; - // A live tool's press that went to the ⌥ eyedropper keeps sampling for the whole press: the - // drag recognised later must not decide again with ⌥ already let go and paint (#7802). - if press_stroke || (strokes_live(tool) && (app.alt_sampling || app.mixer_sampling)) { - buttons.started = false; - } - if buttons.started - && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) - { - if tool == Tool::Move && app.ui.transform.is_none() { - begin_transform_controls_at(app, &ctx, &xf, p); - } - let d = xf.to_doc(p); - let press_mods = if capture_press { ctx.data(|d| d.get_temp(tool_press)).unwrap_or(mods) } else { mods }; - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); - } - // A stroke started on the press takes its moves from the press on, not only once egui - // recognises a drag (past its click distance): otherwise the first few points are lost - // and the stroke starts with a straight segment and no pressure ramp. - let press_stroke_moving = press_stroke && app.drag.is_some(); - if buttons.dragged || buttons.stopped || press_stroke_moving { - // Feed every pointer move the OS delivered this frame, not just the latest position, so - // a fast stroke is sampled densely and renders as a smooth curve instead of a coarse - // polyline. egui-winit pushes one `PointerMoved` per `CursorMoved`, and they accumulate - // while a frame is slow, so reading them all recovers the moves a per-frame - // `interact_pointer_pos()` would drop. Only freehand tools take the whole batch; the - // rest follow the pointer's latest position. The moves are bounded to the gesture's own - // press..release interval (`pointer_moves`), so the start and stop frames keep their - // valid samples without leaking a move from outside the gesture. - let events = ui.input(|i| i.events.clone()); - let button = if response.dragged_by(PointerButton::Secondary) - || response.drag_started_by(PointerButton::Secondary) - || response.drag_stopped_by(PointerButton::Secondary) - { - PointerButton::Secondary - } else { - PointerButton::Primary - }; - let press_this_frame = events.iter().any(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: true, .. } if *b == button)); - let down_at_start = !press_this_frame && (gesture_active_before || buttons.started); - let mut positions = if app.brush_resize.is_some() { - response.interact_pointer_pos().into_iter().collect() - } else if freehand_tool(tool) { - pointer_moves(&events, button, down_at_start) - } else if buttons.dragged { - response.interact_pointer_pos().into_iter().collect() - } else { - Vec::new() - }; - // A frame with no raw move still tracks a held gesture (a still pointer, a modifier - // change): fall back to the latest position, as the old code always did. - if positions.is_empty() - && (buttons.dragged || press_stroke_moving) - && let Some(p) = response.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos())) - { - positions.push(p); - } - app.defer_live_stroke = true; - let base = app.stylus.last_point_ms().map_or(now_ms, |t| t.min(now_ms)); - let n = positions.len(); - for (k, p) in positions.into_iter().enumerate() { - app.stylus.clock_ms = spread_ms(base, now_ms, k, n); - // This move's share of the pen samples the frame brought (pressure, tilt, rotation). - app.stylus.select(k, n); - let d = xf.to_doc(p); - tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods); - } - app.stylus.clear_selection(); - app.stylus.clock_ms = now_ms; - // A held pen keeps the clock running for airbrush build-up and smoothing catch-up. - if app.drag.is_some() && stroke_wants_time(app) { - ctx.request_repaint_after(std::time::Duration::from_millis(HOLD_REPEAT_MS as u64)); - } - app.defer_live_stroke = false; - // One live-stroke update for the whole frame, not one per recovered sample. - feed_live_stroke(app); - crate::magnetic_lasso_ui::flush(app); - } - if buttons.stopped { - // The live painting press already created the stroke and this release commits it. - // egui may also report clicked on the same release; replaying that click paints a - // second full-pressure dab over the real (possibly light-pressure) pen dab. - if press_stroke { - buttons.clicked = false; - } - let at = response.interact_pointer_pos(); - // #6286: a guide let go over a ruler is removed, whichever ruler it is. Tested here in - // screen space, where the rulers are: on the guide's own axis the release can still be - // inside the document, which is what `finish_drag` sees. - if app.guide_drag.is_some() { - let on_ruler = at.is_some_and(|p| crate::rulers::dropped_on_a_ruler(app, full, p)); - if let Some(g) = app.guide_drag.as_mut() { - g.over_ruler = on_ruler; - } - } - let p = at.map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]]))); - if let Some(d) = p { - tap_at_peak_pressure(app); - tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods); - } - } - // A stroke started on the press ends with the release, whether egui saw a drag, a click, - // or neither (a long press that never moved). - if press_stroke && !buttons.stopped && ui.input(|i| i.pointer.primary_released()) { - buttons.clicked = false; - let p = response.interact_pointer_pos().map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]]))); - if let Some(d) = p - && app.drag.is_some() - { - tap_at_peak_pressure(app); - tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods); - } - } - if press_stroke && (app.drag.is_none() || !ui.input(|i| i.pointer.primary_down())) { - app.press_stroke = false; - } - if buttons.clicked - && let Some(p) = response.interact_pointer_pos() - { - let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; - let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); - let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { - ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) - } else { - click_mods - }; - let d = xf.to_doc(p); - match tool { - Tool::Zoom if !transform_owns_pointer => { - let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); - let center = app.session.prefs().tools.zoom_clicked_point_to_center; - let doc_anchor = xf.to_doc(p); - let screen_anchor = p; - zoom_about(&mut view, &xf, p, nz, center, ppp); - view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_view.zoom); - view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); - } - // A click with the (temporary) Hand does nothing, never the tool underneath. - Tool::Hand | Tool::RotateView => {} - // Double-clicking closes the polygonal lasso: the first click placed the last - // vertex (or already closed it), so the second never starts a new polygon. egui - // reports it as a triple click when a vertex went down shortly before. - Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app), - // The same for the Magnetic Lasso: along the edges, or straight with ⌥. - Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt), - // The first click placed (or grabbed) the point; the second toggles it. - Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), - // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. - Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { - if let Err(e) = crate::menus::invoke(app, &ctx, "edit.preferences.guidesGridAndSlices", json!({})) { - app.ui.status = e; - } - } - _ => { - if tool == Tool::Move && app.ui.transform.is_none() { - begin_transform_controls_at(app, &ctx, &xf, p); - } - // If this tool was not handled on pointer-down, fall back to a - // click-sized gesture while preserving pen pressure (mouse stays at 1). - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods); - tap_at_peak_pressure(app); - tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods); - } - } - } - // Magnetic Lasso: between clicks the border follows the pointer with the button up. - if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && response.hovered() { - let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); - app.defer_live_stroke = true; - for p in moves.into_iter().filter(|p| rect.contains(*p)) { - let d = xf.to_doc(p); - tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods); - } - app.defer_live_stroke = false; - crate::magnetic_lasso_ui::flush(app); - } - // Move tool: a double-click on type edits it, as in Photoshop (#1132). Only the selected - // Move tool, not ⌘ held over another tool; an open transform box keeps its double-click - // (commit, below). - if tool == Tool::Move - && app.ui.tool == Tool::Move - && app.ui.transform.is_none() - && response.double_clicked() - && let Some(p) = response.interact_pointer_pos() - { - let d = xf.to_doc(p); - crate::type_tool::edit_at(app, d[0], d[1]); - } - if app.ui.transform.is_some() && response.double_clicked() { - crate::transform_tool::commit(app); - } - if crate::cam_transform::active(app) && response.double_clicked() { - crate::cam_transform::commit(app); - } - // Crop: a double-click inside the frame commits it, as ↵ does (#1792). - if tool == Tool::Crop && response.double_clicked() && response.interact_pointer_pos().is_some_and(|p| crate::crop_ui::commits_at(app, xf.to_doc(p))) { - commit_crop(app); - } - // Type: 2 clicks select a word, 3 the line, 4 the paragraph, 5 all text (Photoshop). - if tool.is_type() - && response.clicked() - && let Some(p) = response.interact_pointer_pos() - { - if crate::type_transform::visible(app, crate::workspace_ui::sticky_mods(app, mods)) { - app.type_clicks = None; - } else { - let n = if response.triple_clicked() { - 3 - } else if response.double_clicked() { - 2 - } else { - 1 - }; - let d = xf.to_doc(p); - crate::type_tool::multi_click(app, n, d[0], d[1]); - } - } + let input = CanvasToolInput { + ctx: &ctx, + response: &response, + xf: &xf, + rect, + full, + tool, + idx, + primary, + transform_owns_pointer, + hand_pan, + ppp, + under_dialog, + zoom_out: &zoom_out, + display_zoom: display_view.zoom, + }; + handle_primary_canvas_input(app, ui, &mut view, &input); } if crop_camera && let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) { if now.center != center { @@ -1274,335 +1874,28 @@ 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. let panning = hand_pan && response.dragged(); if primary { - // The transform preview is image content: it goes under the grid and guides, which - // stay visible across a layer being transformed (#5086); the box is drawn later. - crate::transform_tool::draw_content(app, &painter, &xf); - // So are Puppet Warp's, Perspective Warp's and Vanishing Point's warped pixels (#7781). - crate::distort_ui::draw_content(app, &painter, &xf); - if app.ui.extras.grid && app.ui.view.extras { - crate::rulers::draw_grid(app, &painter, &xf, &doc); - } - if app.ui.view.shows(app.ui.view.show.canvas_guides) || crate::guide_layout_ui::preview(app, &doc).is_some() { - crate::rulers::draw_guides(app, &painter, &xf, &doc); - } - // The pending crop frame shows on its own document only, not on the other tiles (#1918). - let foreign_crop = if app.session.active_index() == Some(idx) { None } else { app.ui.crop_rect.take() }; - draw_drag_preview(app, &painter, &xf); - if app.session.active_index() == Some(idx) { - crate::move_box::draw(app, &painter, &xf); - } - if foreign_crop.is_some() { - app.ui.crop_rect = foreign_crop; - } - crate::zoom_tool::draw(&ctx, &painter); - let resizing = crate::brush_resize::draw(app, &painter, &xf); - draw_transform_controls(app, &painter, &xf); - crate::move_hover::draw(app, &painter, &xf, idx, response.hover_pos()); - crate::object_finder::draw(app, &painter, &xf, idx, response.hover_pos()); - crate::layer_pick_ui::show(app, &ctx); - let shown = app.ui.views.get(idx).cloned(); - crate::canvas_tool_menu::show(app, &ctx); - // A view menu row (Zoom In, Fit on Screen…) changed the camera: it wins over this - // frame's copy, which is written back at the end. - if let Some(now) = app.ui.views.get(idx) - && Some(now) != shown.as_ref() - { - view = now.clone(); - ctx.request_repaint(); - } - crate::snap_ui::draw(app, &painter, &xf); - crate::move_distance::draw(app, &painter, &xf, idx, response.hover_pos()); - // The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview), - // nor while the Crop tool hides everything outside its box (Show Cropped Area off). - if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond && !crate::crop_shield::hides_outside(app) { - painter.rect_stroke(edge_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside); - } - crate::type_tool::draw_overlay(app, &painter, &xf); - crate::transform_tool::draw_overlay(app, &painter, &xf); - crate::cam_transform::draw(app, &painter, &xf); - crate::cam_preview::wake(app, painter.ctx()); - crate::distort_ui::draw_overlay(app, &painter, &xf); - crate::perspective_crop_ui::draw_overlay(app, &painter, &xf); - crate::retouch_ui::draw_source_marker(app, &painter, &xf); - crate::vector_ui::draw_overlay(app, &painter, &xf, &doc); - crate::symmetry_ui::draw(app, &painter, &xf); - crate::analysis_ui::draw_overlay(app, &painter, &xf); - crate::gradient_ui::draw_overlay(app, &painter, &xf); - crate::slice_ui::draw_overlay(app, &painter, &xf); - crate::frame_tool::draw_overlay(app, &painter, &xf); - crate::artboard_tool::draw_overlay(app, &painter, &xf); - // Tool cursors (Photoshop-style). - let guide_hover = response.hover_pos().and_then(|p| { - let d = xf.to_doc(p); - if tool == Tool::Move { - return crate::rulers::guide_at(app, d[0], d[1]); - } - command_guide_at(app, tool, d, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))) - }); - if panning { - // The fist set with the pan above stays (#2196). - } else if crate::tool_cursor::pointer_elsewhere(&ctx, &crate::panel_docking::native_viewports(app, &ctx)) { - // The pointer is over a floating panel's own window; this window's last position of - // it is stale, so no tool cursor or brush outline is painted at it. - } else if let Some((vertical, _)) = guide_hover { - ui.ctx().set_cursor_icon(crate::rulers::guide_cursor(&xf, vertical)); - } else if let Some((p, mods, c)) = response.hover_pos().and_then(|p| { - let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - let c = crate::transform_tool::cursor(app, &xf, xf.to_doc(p), mods)?; - Some((p, mods, c)) - }) { - ui.ctx().set_cursor_icon(c); - // CursorIcon::None hides the pointer; the curved arrow has to be drawn or the - // rotate zone looks like a plain cursor (#4050). - let d = xf.to_doc(p); - if let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { - let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; - crate::crop_ui::draw_turn_cursor(&ctx, p, toward); - } else if c == egui::CursorIcon::None { - // Likewise the distort and skew pointers over a handle (#5405). - crate::transform_tool::draw_handle_cursor(app, &ctx, &xf, p, mods); - } - } else if let Some(c) = response.hover_pos().and_then(|p| crate::symmetry_ui::cursor(app, &xf, xf.to_doc(p))) { - ui.ctx().set_cursor_icon(c); - } else if let Some(c) = response.hover_pos().and_then(|p| crate::cam_transform::cursor(app, &ctx, &xf, p)) { - ui.ctx().set_cursor_icon(c); - } else if let Some(p) = response.hover_pos().filter(|p| crate::corner_radius::hovers(app, xf.to_doc(*p))) { - // Over a live rectangle's corner widget (or dragging one): the arrow with a rounded - // corner badge, as Photoshop's corner radius cursor. - ui.ctx().set_cursor_icon(egui::CursorIcon::Default); - crate::icons::cursor_badge(&ctx, "scan", p); - } else if let Some((r, p, c)) = response - .hover_pos() - .filter(|_| !transform_controls_several(app)) - .and_then(|p| transform_controls_rect(app, &xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c)))) - { - // The Move tool draws handles without opening a Free Transform session. - // Give them their resize/rotate cursors before the first pointer press (#2871). - ui.ctx().set_cursor_icon(c); - if let Some(toward) = transform_controls_turn(r, p) { - crate::crop_ui::draw_turn_cursor(&ctx, p, toward); - } - } else if let Some(c) = response.hover_pos().filter(|_| tool.is_type()).and_then(|p| { - let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - crate::type_transform::cursor(app, &ctx, &xf, p, mods) - }) { - ui.ctx().set_cursor_icon(c); - } else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Artboard).and_then(|p| crate::artboard_tool::cursor(app, &xf, xf.to_doc(p))) { - ui.ctx().set_cursor_icon(c); - } else if let Some((p, c)) = response.hover_pos().filter(|_| tool == Tool::Crop).and_then(|p| Some((p, crate::crop_ui::cursor(app, xf.to_doc(p))?))) { - ui.ctx().set_cursor_icon(c); - let d = xf.to_doc(p); - if let Some(k) = crate::crop_ui::turn_cursor_dir(app, d) { - let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; - crate::crop_ui::draw_turn_cursor(&ctx, p, toward); - } - } else if let Some(p) = response.hover_pos() - && let Some(c) = selection_cursor(app, tool, xf.to_doc(p), crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))) - { - // Over a selection (Photoshop's cursors): the move cursor where a press drags the - // outline (#1428), the arrow with a badge for what a press does to the selected - // pixels, a hollow arrowhead while they are dragged, a plain arrow over a floating - // piece. - let icon = match c { - SelCursor::Outline => egui::CursorIcon::Move, - SelCursor::Dragging => { - // The tip of the arrowhead is at (4, 4) of its 24-unit box. - crate::icons::cursor(ui.ctx(), "mouse-pointer-2", p, vec2(4.0, 4.0) / 24.0, 18.0); - egui::CursorIcon::None - } - SelCursor::Piece => egui::CursorIcon::Default, - SelCursor::Cut => { - crate::icons::cursor_badge(ui.ctx(), "scissors", p); - egui::CursorIcon::Default - } - SelCursor::Copy => { - crate::icons::cursor_copy_badge(ui.ctx(), p); - egui::CursorIcon::Default - } - }; - ui.ctx().set_cursor_icon(icon); - } else if let Some(p) = response.hover_pos() { - let alt = ui.input(|i| i.modifiers.alt); - if !resizing && !alt && !app.ui.shell.sticky_alt { - draw_clone_preview(app, &painter, &xf, xf.to_doc(p), output); - } - // The Type tool over a path shows Photoshop's area-type or type-on-a-path pointer (#218). - // Not while a type edit is open or a text box is dragged out, nor over type a click - // would edit (`hover_path_target`). - let type_path = if matches!(tool, Tool::Type | Tool::VerticalType) { - let [x, y] = xf.to_doc(p); - let shift = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)).shift; - crate::type_tool::hover_path_target(app, x, y, shift) - } else { - None - }; - let icon = match tool { - // Resizing the brush: the circle stays where the drag began (`brush_resize`). - t if resizing && crate::brush_resize::applies(t) => egui::CursorIcon::None, - // ⌥ turns a painting tool into the Eyedropper (`alt_eyedropper`): its cursor too, - // unless Preferences › Cursors › Other Cursors asks for the precise crosshair. - t if app.alt_sampling - || (app.drag.is_none() - && !app.services.right_button_down.as_ref().is_some_and(|f| f()) - && alt_samples(t, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)))) => - { - // While it samples (button held), the comparison ring replaces the cursor (#213). - if let Some(icon) = eyedropper_ring(app, &painter, &xf, p, response.is_pointer_button_down_on()) { - icon - } else if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { - egui::CursorIcon::Crosshair - } else { - pipette_cursor(ui.ctx(), p) - } - } - t if t.is_brushlike() || t == Tool::QuickSelection => { - // Preferences › Cursors: brush tip outline (normal = the 50% contour, or - // full size), precise crosshair, or the standard pointer. - use photocraft_engine::prefs::PaintingCursor; - let cur = app.session.prefs().cursors.clone(); - // ⇪ forces the precise crosshair, whatever the cursor preference (#1758). - if app.caps_lock { - crate::tool_cursor::crosshair(&painter, p, 6.0, 0.0) - } else { - let painting = app.drag.is_some(); - let brush = &app.session.tools.brush; - let full = (brush.size / 2.0 * xf.zoom).max(1.0); - match cur.painting { - PaintingCursor::Standard => egui::CursorIcon::Default, - PaintingCursor::Precise => crate::tool_cursor::crosshair(&painter, p, 6.0, 0.0), - _ if painting && cur.show_only_crosshair_while_painting => crate::tool_cursor::crosshair(&painter, p, 5.0, 0.0), - // The Pencil (and the Eraser in Pencil mode): the outline of the - // whole pixels its dab fills, on the pixel grid. A round tip is a - // disc, a tiny one the whole square (#2662). The Block-mode Eraser: - // its square, 16 screen pixels at any zoom (#2770). - _ if tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool) || crate::eraser_ui::block_mode(app, tool) => { - let block = crate::eraser_ui::block_mode(app, tool); - let size = if block { crate::eraser_ui::block_size(app) } else { brush.size }; - let ppp = painter.ctx().pixels_per_point(); - let sq = pencil_cursor_rect(&xf, xf.to_doc(p), size, ppp); - let px = 1.0 / ppp; - let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(230))); - if !block && pencil_tip_is_round(size) { - let r = sq.width() / 2.0; - painter.circle_stroke(sq.center(), r + px / 2.0, dark); - painter.circle_stroke(sq.center(), (r - px / 2.0).max(0.0), light); - } else { - painter.rect_stroke(sq, 0.0, dark, egui::StrokeKind::Outside); - painter.rect_stroke(sq, 0.0, light, egui::StrokeKind::Inside); - } - // Too small to see where it is: the hotspot as well. - if cur.show_crosshair_in_brush_tip || sq.width() < 6.0 { - crate::tool_cursor::crosshair(&painter, p, 4.0, 0.0); - } - egui::CursorIcon::None - } - // A shaped tip (sampled bitmap, or a rotated/flattened round tip) - // traces its outline, turned and flipped with the view; a plain round - // tip keeps the circle. - _ => { - let centre = brush_tip_centre(tool, alt || app.ui.shell.sticky_alt, cur.show_crosshair_in_brush_tip); - let axes = crate::brush_cursor::pen_axes(&xf, brush, app.stylus.sample()); - crate::brush_cursor::cursor(&painter, p, brush, full, axes, cur.painting == PaintingCursor::NormalTip, centre) - } - } - } - } - // The Eyedropper: the comparison ring follows the pointer while it samples (#213); - // otherwise its pipette, or the crosshair for precise Other Cursors. - Tool::Eyedropper => { - if let Some(icon) = eyedropper_ring(app, &painter, &xf, p, response.is_pointer_button_down_on()) { - icon - } else if precise_other_cursor(app) { - egui::CursorIcon::Crosshair - } else { - pipette_cursor(ui.ctx(), p) - } - } - // The Color Sampler: a pipette, or the crosshair for precise Other Cursors. - Tool::ColorSampler => { - if precise_other_cursor(app) { - egui::CursorIcon::Crosshair - } else { - pipette_cursor(ui.ctx(), p) - } - } - // The Paint Bucket: a bucket, or the crosshair for precise Other Cursors (#3968). - Tool::PaintBucket => { - if precise_other_cursor(app) { - egui::CursorIcon::Crosshair - } else { - paint_bucket_cursor(ui.ctx(), p) - } - } - // Over the first anchor, the close-path pointer (#4596), before the pens' own cursors. - Tool::Pen | Tool::CurvaturePen - if { - let [x, y] = xf.to_doc(p); - crate::vector_ui::closes_path_at(app, tool, x, y) - } => - { - crate::tool_cursor::close_path(&painter, p) - } - // The pen tools: their own icon with its nib on the point, or the crosshair for - // precise Other Cursors (#4639). - Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { - if precise_other_cursor(app) { - egui::CursorIcon::Crosshair - } else { - pen_cursor(ui.ctx(), tool, p) - } - } - // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. - Tool::Move | Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask - if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise => - { - egui::CursorIcon::Crosshair - } - // Photoshop's Move tool keeps the standard arrow pointer (#5646): the movable - // layer under it is marked by the hover outline, not by a different cursor. - Tool::Move => egui::CursorIcon::Default, - // Dragging is handled with the pan itself, above. - Tool::Hand => crate::tool_cursor::hand(ui.ctx(), false), - Tool::RotateView => crate::rotate_view::cursor(response.dragged()), - Tool::Zoom => crate::tool_cursor::zoom(ui.ctx(), zoom_out(alt)), - Tool::Type | Tool::VerticalType if type_path.is_some() => match type_path { - Some(crate::type_tool::PathClick::Area { .. }) => crate::tool_cursor::area_type(&painter, p), - _ => crate::tool_cursor::path_type(&painter, p), - }, - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => egui::CursorIcon::Text, - Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, &painter, p, xf.zoom), - Tool::RedEye => { - let pupil = app.ui.tool_options.red_eye_pupil_size.clamp(1.0, 100.0); - let r_doc = photocraft_algo::redeye::search_radius(pupil); - let r = (r_doc * xf.zoom).max(2.0); - painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140))); - painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220))); - for (w, c) in [(2.5, Color32::from_black_alpha(140)), (1.0, Color32::from_white_alpha(220))] { - painter.line_segment([p - vec2(3.0, 0.0), p + vec2(3.0, 0.0)], Stroke::new(w, c)); - painter.line_segment([p - vec2(0.0, 3.0), p + vec2(0.0, 3.0)], Stroke::new(w, c)); - } - egui::CursorIcon::None - } - _ => egui::CursorIcon::Crosshair, - }; - let icon = visible_crosshair(icon, &painter, p, cfg!(not(target_arch = "wasm32"))); - ui.ctx().set_cursor_icon(icon); - // Selection tools: + / − / × badge for the effective mode (#170). A gesture keeps the - // mode it started with (⇧ then constrains the marquee instead of adding). - let held = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - let mods = app.drag.as_ref().map_or(held, |d| d.modifiers); - if let Some(b) = crate::tool_feedback::badge(app, tool, mods) { - crate::tool_feedback::draw_badge(&painter, p, b, tool == Tool::QuickSelection); - } - // ⇧ after a stroke: the straight line a click would paint (#257). - crate::stroke_constraint::draw_line_preview(app, &painter, &xf, p, tool, held.shift); - } + let input = CanvasOverlayInput { + ctx: &ctx, + painter: &painter, + xf: &xf, + response: &response, + doc: &doc, + tool, + idx, + output, + border, + beyond, + edge_rect, + panning, + zoom_out: &zoom_out, + }; + paint_primary_overlays(app, ui, &mut view, &input); } app.tool_override = None; if let Some(b) = layer_edges_rect(app, idx) { 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..a7d3f8dc94 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 @@ -125,7 +125,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e let buffer = photocraft_compose::flatten(&doc); (std::sync::Arc::new(doc), buffer) }); - crate::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 } + crate::dialogs::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 } }) { app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request.clone(), result: None, committing: false }); crate::notices::error(app, error); 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/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a90df6af98..f213a67d9d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -285,7 +285,7 @@ fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { std::thread::sleep(std::time::Duration::from_millis(1)); } let _ = told.send(job.cancelled()); - crate::filter_preview_worker::Computed { result: None, ms: 0.0 } + crate::dialogs::filter_preview_worker::Computed { result: None, ms: 0.0 } }) .unwrap(); // The slider moves on and stops: once the value settles, the stale preview is cancelled @@ -352,7 +352,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn let buffer = photocraft_compose::flatten(&d); (std::sync::Arc::new(d), buffer) }); - crate::filter_preview_worker::Computed { result, ms: 0.0 } + crate::dialogs::filter_preview_worker::Computed { result, ms: 0.0 } }) .expect("the worker starts"); (release, radius) @@ -482,7 +482,7 @@ fn a_mid_drag_empty_result_leaves_the_preview_alone() { app.filter_preview_worker .start(key, ctx.clone(), move |_| { wait.recv_timeout(std::time::Duration::from_secs(60)).expect("released"); - crate::filter_preview_worker::Computed { result: None, ms: 0.0 } + crate::dialogs::filter_preview_worker::Computed { result: None, ms: 0.0 } }) .expect("the worker starts"); app.ui.dialogs[0].fields.insert("radius".into(), json!(moved + 4.0)); 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)] From bba45115faf376a782b8ae73af54f32011eec686 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 03/35] Refactor UI dialogs for strict Clippy checks --- .../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 ++++++++------- crates/ui-egui/src/dialogs/camera_raw_ui.rs | 1 + .../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/gallery_ui.rs | 2 +- crates/ui-egui/src/dialogs/liquify_ui.rs | 110 ++++++++++-------- 22 files changed, 151 insertions(+), 108 deletions(-) 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..b40e1f8ed2 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.rs b/crates/ui-egui/src/dialogs/camera_raw_ui.rs index e920b95da8..1b71ef3306 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui.rs @@ -19,6 +19,7 @@ use photocraft_algo::camera_raw::{CameraRaw, Wheel, curve_lut}; use photocraft_algo::histogram::RgbHistogram; use crate::camera_raw_scope_ui::{MAX_SAMPLERS, ToneZone}; + use photocraft_doc::LayerId; use photocraft_geom::Rect; use serde_json::{Value, json}; 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/gallery_ui.rs b/crates/ui-egui/src/dialogs/gallery_ui.rs index d37eec865d..2f2269b892 100644 --- a/crates/ui-egui/src/dialogs/gallery_ui.rs +++ b/crates/ui-egui/src/dialogs/gallery_ui.rs @@ -582,7 +582,7 @@ fn poll_job(d: &mut GalleryDialog, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] fn start_job(d: &mut GalleryDialog, ctx: &egui::Context, key: u64, vis: Rect, k: u32, params: &Value, now: f64) { if let Some(job) = &d.job { - let settled = d.latest.is_some_and(|(k0, t)| k0 == key && now - t >= crate::filter_preview_worker::SETTLE_MS); + let settled = d.latest.is_some_and(|(k0, t)| k0 == key && now - t >= crate::dialogs::filter_preview_worker::SETTLE_MS); if job.key != key && settled { job.ctl.cancel(); } diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index 5d4da05bff..29536064a5 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -885,6 +885,68 @@ 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 +986,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 +1091,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)]), From 97fc920872233795b8db1c91822d8a489c5df406 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 04/35] Refactor UI input for strict Clippy checks --- crates/ui-egui/src/input/shortcuts.rs | 201 ++++++++++++++++---------- 1 file changed, 123 insertions(+), 78 deletions(-) diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 807f748a49..40ebeb1804 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,17 +684,17 @@ 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)) { @@ -657,79 +702,63 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { 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 +768,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 +780,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 +797,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 +806,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 +858,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 +894,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)] From 211d4824c8c708ef38c8d0ccac6c2d4d5e10d016 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 05/35] Refactor UI menus for strict Clippy checks --- crates/ui-egui/src/menus/bar.rs | 2 +- crates/ui-egui/src/menus/invoke.rs | 689 ++++++++++-------- 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 +- 8 files changed, 385 insertions(+), 318 deletions(-) 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..cf7529a439 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,56 +273,40 @@ 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) } - "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params), - "window.newWindowForDocument" => { - let doc = app.session.active_index().ok_or("no document")?; - let wid = app.ui.alloc_id(); - let view = app.ui.views[doc].clone(); - app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); - Ok(json!({"window": wid})) - } - "window.theme.toggle" => { - crate::prefs_ui::cycle_appearance(app, ctx); - Ok(Value::Null) - } - "view.darkenInterface" | "view.lightenInterface" => { - crate::prefs_ui::step_brightness(app, ctx, id == "view.lightenInterface")?; - Ok(json!({"theme": app.ui.theme.id()})) - } - "window.theme.system" => { - app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"}))?; - crate::prefs_ui::sync_appearance(app, ctx); - Ok(Value::Null) - } - "window.theme.pro" - | "window.theme.proMedium" - | "window.theme.proLightGray" - | "window.theme.proLight" - | "window.theme.studio" - | "window.theme.studioLight" - | "window.theme.classic" - | "window.theme.solarizedDark" - | "window.theme.adwaita" - | "window.theme.adwaitaDark" - | "window.theme.breezeLight" - | "window.theme.breezeDark" - | "window.theme.softLight" - | "window.theme.softDark" => { - let k = crate::theme::ThemeKind::from_name(&id["window.theme.".len()..]).unwrap_or_default(); - app.set_theme(ctx, k); - Ok(Value::Null) - } - // The macOS app menu's Language (`native_menu::language_node`). - i if i.starts_with(crate::native_menu::LANGUAGE_PREFIX) => { - let code = &i[crate::native_menu::LANGUAGE_PREFIX.len()..]; - if code != "auto" && !crate::i18n::Lang::all().any(|l| l.code() == code) { - return Err(format!("unknown UI language `{code}`")); - } - app.run("prefs.set", json!({"values": {"interface.language": code}})) - } + _ => 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); + } + if let Some(result) = invoke_window_command(app, ctx, id) { + return result; + } + if let Some(result) = invoke_export_command(app, id, ¶ms)? { + return result; + } + if let Some(result) = invoke_type_command(app, ctx, id, ¶ms) { + return result; + } + if let Some(result) = invoke_view_command(app, ctx, id, ¶ms) { + return result; + } + if let Some(result) = invoke_view_command(app, ctx, id, ¶ms) { + return result; + } + match id { "edit.search" => { app.ui.palette_open = !app.ui.palette_open; Ok(Value::Null) @@ -329,39 +318,6 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: let dialog = app.ui.open_dialog(DialogKind::About, fields); Ok(json!({"dialog": dialog, "info": crate::gpu_status::system_info_json(app)})) } - "file.export.exportAs" => Ok(json!({"dialog": crate::export_dialog::open(app)?})), - "file.export.quickExportAsPng" => crate::export_dialog::quick_export_png(app), - // Render Video exports a sequence of frames into a folder, not a named file. - // Keep explicit directory arguments from automation and the control channel unchanged. - "file.export.renderVideo" if params.get("dir").is_none() => { - #[cfg(target_arch = "wasm32")] - { - Err("Render Video to a local directory is unavailable on the web".into()) - } - #[cfg(not(target_arch = "wasm32"))] - { - let doc = app.session.active().ok_or("no document")?.doc.id; - let mut render_params = params.as_object().cloned().unwrap_or_default(); - app.ask_folder(move |app, dir| { - render_params.insert("dir".into(), json!(dir)); - app.with_document(doc, |app| app.run("file.export.renderVideo", Value::Object(render_params))) - }) - } - } - // Layer › Export As… / Quick Export as PNG: the export pipeline on just the active layer. - l if matches!(l, "layer.exportAs" | "layer.quickExportAsPng") && params.as_object().is_none_or(|o| o.is_empty()) => { - let layer = app.session.active().and_then(|d| d.active_layer).ok_or("no active layer")?; - if l == "layer.exportAs" { - // Several layers (artboards, say) selected: one file each (#3629). - let layers = app.session.active().map(|d| d.selected_layers()).unwrap_or_default(); - if layers.len() > 1 { - return Ok(json!({"dialog": crate::export_dialog::open_layers(app, &layers)?})); - } - Ok(json!({"dialog": crate::export_dialog::open_layer(app, layer)?})) - } else { - crate::export_dialog::quick_export_selected_layers_png(app) - } - } "layer.smartFilter.blendingOptions" if params.get("blend").is_none() && params.get("opacity").is_none() => { let st = app.session.active().ok_or("no document open")?; let layer = params.get("layer").and_then(Value::as_u64).map(photocraft_doc::LayerId).or(st.active_layer).ok_or("no layer selected")?; @@ -377,36 +333,6 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => { crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string()) } - // ⇧⌘> / ⇧⌘<: the selected characters while typing, else the whole type layer. - "type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore" if params.as_object().is_none_or(|o| o.is_empty()) => { - let p = crate::type_tool::with_target(app, json!({})).ok_or("the active layer is not a type layer")?; - app.run(id, p) - } - // Formatting menus follow an inline text selection when editing. Outside an edit, - // snapshot the selected type layers; explicit automation targets retain their scope. - t if (t.starts_with("type.antiAlias.") - || t.starts_with("type.orientation.") - || t.starts_with("type.openType.") - || matches!(t, "type.warpText" | "type.loadDefaultTypeStyles")) - && params.get("layer").is_none() - && params.get("layers").is_none() - && params.get("range").is_none() => - { - let Some(mut p) = crate::type_tool::formatting_params(app) else { return app.run(id, params) }; - if let Some(props) = params.as_object() { - for (key, value) in props { - p[key] = value.clone(); - } - } - app.run(id, p) - } - "type.editText" => { - crate::type_tool::edit_active(app)?; - if let Some(focus) = ctx.memory(|m| m.focused()) { - ctx.memory_mut(|m| m.surrender_focus(focus)); - } - Ok(Value::Null) - } // Only interactive creation opens the Color Picker; it creates the layer on OK, // so Cancel leaves neither an orphan layer nor an undo/redo history entry. // Explicit parameters continue straight to the engine. @@ -485,23 +411,6 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "select.transformSelection" if params.as_object().is_none_or(|o| o.is_empty()) => { crate::transform_tool::begin_selection(app, ctx).map(|_| json!({"transform": app.ui.transform})) } - // While editing type, the clipboard rows and Select > All work on the text (#1355, #2893). - "edit.cut" if app.ui.text_edit.is_some() => { - crate::type_tool::cut_selection(app, ctx); - Ok(Value::Null) - } - "edit.copy" if app.ui.text_edit.is_some() => { - crate::type_tool::copy_selection(app, ctx); - Ok(Value::Null) - } - "edit.paste" if app.ui.text_edit.is_some() => { - crate::type_tool::request_paste(ctx); - Ok(Value::Null) - } - "select.all" if app.ui.text_edit.is_some() => { - crate::type_tool::select_all(app); - Ok(Value::Null) - } "edit.paste" if params.as_object().is_none_or(|o| o.is_empty()) => { // Photoshop: paste in place when the copied area is visible, else centred in the view; // images from other apps are always centred. @@ -523,138 +432,8 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: }; app.run("edit.paste", p) } - "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => { - let e = &mut app.ui.extras; - let slot = match id { - "view.rulers" => &mut e.rulers, - "view.show.grid" => &mut e.grid, - "view.show.guides" => &mut e.guides, - "view.snap" => &mut e.snap, - _ => &mut e.lock_guides, - }; - *slot = !*slot; - let on = *slot; - if id == "view.show.grid" && on { - // Like the other Show items, enabling Grid also restores hidden Extras. - app.ui.view.extras = true; - } - if id == "view.rulers" { - crate::prefs_ui::remember_rulers(app, on); - } - Ok(json!(on)) - } - "edit.freeTransform" - | "edit.transform.scale" - | "edit.transform.rotate" - | "edit.transform.skew" - | "edit.transform.distort" - | "edit.transform.perspective" => { - // While a box is up, Scale / Rotate / Skew / Distort / Perspective (and Free Transform) - // switch its mode; otherwise they start one in that mode. - if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { - return Err(crate::transform_tool::CAS_ONLY_SCALES.into()); - } - if app.ui.transform.is_none() { - crate::transform_tool::begin(app, ctx)?; - } - if let Some(t) = app.ui.transform.as_mut() { - t.mode = crate::state::TransformMode::for_command(id); - } - Ok(json!({"transform": app.ui.transform})) - } - "edit.freeTransformCopy" => crate::transform_tool::begin_copy(app, ctx).map(|_| json!({"transform": app.ui.transform})), - // Edit › Transform › Warp from the menu: interactive Warp mode (with params: the engine). - "edit.transform.warp" | "layer.smartObjects.warp" if params.as_object().is_none_or(|o| o.is_empty()) => { - crate::transform_tool::begin_warp(app, ctx).map(|_| json!({"transform": app.ui.transform})) - } - // Split warps edit the mesh of an active Warp session. - "edit.transform.splitWarpCrosswise" - | "edit.transform.splitWarpHorizontally" - | "edit.transform.splitWarpVertically" - | "edit.transform.removeWarpSplit" - if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() => - { - let at = params.get("at").and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])); - crate::transform_tool::split(app, id, at).map(|_| json!({"transform": app.ui.transform})) - } - "edit.transform.warpGrid" if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() => { - crate::transform_tool::edit_session_warp(app, id, ¶ms).map(|_| json!({"transform": app.ui.transform})) - } // Layer › New › Layer… (⇧⌘N) asks first, as in Photoshop; with params it runs as is. crate::new_layer_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::new_layer_ui::open(app)?})), - sz if crate::sizing::is_sizing(sz) && params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::sizing::open(app, sz).ok_or("no document")?})) - } - "view.newGuide" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::new_guide_ui::open(app)})), - fl if crate::filter_dialog::has_dialog(fl) && params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::filter_dialog::open(app, fl)})) - } - a if crate::adjust_dialog::has_dialog(a) && params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::adjust_dialog::open(app, a).ok_or("no document")?})) - } - "window.togglePanels" => { - // Tab hides the Tools panel, the options bar and the dock; Tab again shows what it hid. - if app.ui.view.hides_chrome() { - // Full Screen Mode: Tab only shows or hides the chrome for now (#6760); the panels' - // own state, `hidden_by_tab` included, stays as it was before entering. - app.ui.panels.full_screen_chrome = !app.ui.panels.full_screen_chrome; - return Ok(Value::Null); - } - let p = &mut app.ui.panels; - match p.hidden_by_tab.take() { - Some([toolbar, options, dock]) if !(p.toolbar || p.options_bar || p.dock) => { - (p.toolbar, p.options_bar, p.dock) = (toolbar, options, dock); - } - _ if p.toolbar || p.options_bar || p.dock => { - p.hidden_by_tab = Some([p.toolbar, p.options_bar, p.dock]); - (p.toolbar, p.options_bar, p.dock) = (false, false, false); - } - _ => (p.toolbar, p.options_bar, p.dock) = (true, true, true), - } - Ok(Value::Null) - } - "window.nextDocument" | "window.previousDocument" => { - // Tabs are in document order, so the next tab is the next document, wrapping around. - let n = app.session.documents().len(); - let at = app.session.active_index().ok_or("no document open")?; - let to = if id == "window.nextDocument" { (at + 1) % n } else { (at + n - 1) % n }; - app.session.set_active(to); - app.jobs.focus = None; - Ok(json!({"document": to})) - } - id if let Some(index) = id.strip_prefix(DOCUMENT_ITEM) => { - let n = app.session.documents().len(); - let to = index.parse::().ok().filter(|i| *i < n).ok_or("no such document")?; - app.session.set_active(to); - app.jobs.focus = None; - Ok(json!({"document": to})) - } - t if t.starts_with("window.toggle.") => { - // A shown but collapsed dock group is expanded rather than hidden (#129). - if let Some(g) = crate::dock::Group::from_key(&t["window.toggle.".len()..]).filter(|g| g.shown(&app.ui.panels) && app.ui.dock.is_collapsed(*g)) { - crate::dock::reveal(app, g); - return Ok(Value::Null); - } - let p = &mut app.ui.panels; - let slot = match &t["window.toggle.".len()..] { - "layers" => &mut p.layers, - "history" => &mut p.history, - "properties" => &mut p.properties, - "color" => &mut p.color, - "navigator" => &mut p.navigator, - "toolbar" => &mut p.toolbar, - "options" => &mut p.options_bar, - "brushSettings" => &mut p.brush_settings, - "brushes" => &mut p.brushes, - "dock" => &mut p.dock, - _ => return Err(format!("unknown panel in {t}")), - }; - *slot = !*slot; - if let Some(g) = crate::dock::Group::from_key(&t["window.toggle.".len()..]).filter(|g| g.shown(&app.ui.panels)) { - crate::dock::reveal(app, g); - } - Ok(Value::Null) - } // Layer › Layer Style › … opens the Layer Style dialog on that effect. ls if params.as_object().is_none_or(|o| o.is_empty()) && ls.strip_prefix("layer.layerStyle.").is_some_and(|k| crate::layer_style::KINDS.iter().any(|(kind, _)| *kind == k)) => @@ -670,6 +449,294 @@ fn open_path(app: &mut PhotocraftApp, path: &str) -> Result { app.open_path(path).map(|w| json!({"warnings": w})) } +fn invoke_export_command(app: &mut PhotocraftApp, id: &str, params: &Value) -> Result>, String> { + let result = match id { + "file.export.exportAs" => Some(Ok(json!({"dialog": crate::export_dialog::open(app)?}))), + "file.export.quickExportAsPng" => Some(crate::export_dialog::quick_export_png(app)), + "file.export.renderVideo" if params.get("dir").is_none() => { + #[cfg(target_arch = "wasm32")] + { + Some(Err("Render Video to a local directory is unavailable on the web".into())) + } + #[cfg(not(target_arch = "wasm32"))] + { + let document = app.session.active().ok_or("no document")?.doc.id; + let mut render_params = params.as_object().cloned().unwrap_or_default(); + Some(app.ask_folder(move |app, dir| { + render_params.insert("dir".into(), json!(dir)); + app.with_document(document, |app| app.run("file.export.renderVideo", Value::Object(render_params))) + })) + } + } + layer if matches!(layer, "layer.exportAs" | "layer.quickExportAsPng") && params.as_object().is_none_or(|object| object.is_empty()) => { + let selected = app.session.active().and_then(|document| document.active_layer).ok_or("no active layer")?; + if layer == "layer.exportAs" { + let layers = app.session.active().map(|document| document.selected_layers()).unwrap_or_default(); + if layers.len() > 1 { + Some(Ok(json!({"dialog": crate::export_dialog::open_layers(app, &layers)?}))) + } else { + Some(Ok(json!({"dialog": crate::export_dialog::open_layer(app, selected)?}))) + } + } else { + Some(crate::export_dialog::quick_export_selected_layers_png(app)) + } + } + _ => None, + }; + Ok(result) +} + +fn invoke_type_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + match id { + "type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore" + if params.as_object().is_none_or(|object| object.is_empty()) => + { + Some((|| { + let target = type_command_target(app).ok_or("the active layer is not a type layer")?; + app.run(id, target) + })()) + } + command + if (command.starts_with("type.antiAlias.") + || command.starts_with("type.orientation.") + || command.starts_with("type.openType.") + || matches!(command, "type.warpText" | "type.loadDefaultTypeStyles")) + && params.get("layer").is_none() + && params.get("layers").is_none() + && params.get("range").is_none() => + { + Some((|| { + let Some(mut target) = crate::type_tool::formatting_params(app) else { return app.run(id, params.clone()) }; + if let Some(properties) = params.as_object() { + for (key, value) in properties { + target[key] = value.clone(); + } + } + app.run(id, target) + })()) + } + "type.editText" => Some((|| { + crate::type_tool::edit_active(app)?; + if let Some(focus) = ctx.memory(|memory| memory.focused()) { + ctx.memory_mut(|memory| memory.surrender_focus(focus)); + } + Ok(Value::Null) + })()), + "edit.cut" if app.ui.text_edit.is_some() => { + crate::type_tool::cut_selection(app, ctx); + Some(Ok(Value::Null)) + } + "edit.copy" if app.ui.text_edit.is_some() => { + crate::type_tool::copy_selection(app, ctx); + Some(Ok(Value::Null)) + } + "edit.paste" if app.ui.text_edit.is_some() => { + crate::type_tool::request_paste(ctx); + Some(Ok(Value::Null)) + } + "select.all" if app.ui.text_edit.is_some() => { + crate::type_tool::select_all(app); + Some(Ok(Value::Null)) + } + _ => None, + } +} + +fn type_command_target(app: &PhotocraftApp) -> Option { + let (layer, range) = crate::type_tool::target(app)?; + let mut params = json!({"layer": layer}); + if let Some(range) = range { + params["range"] = json!(range); + } + if let Some(session) = app.ui.text_edit.as_ref().map(|edit| edit.session.clone()) { + params["coalesce"] = json!(session); + } + Some(params) +} + +fn invoke_view_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + match id { + "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => Some(app.run(id, params.clone())), + "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => { + let extras = &mut app.ui.extras; + let slot = match id { + "view.rulers" => &mut extras.rulers, + "view.show.grid" => &mut extras.grid, + "view.show.guides" => &mut extras.guides, + "view.snap" => &mut extras.snap, + _ => &mut extras.lock_guides, + }; + *slot = !*slot; + let enabled = *slot; + if id == "view.show.grid" && enabled { + app.ui.view.extras = true; + } + if id == "view.rulers" { + crate::prefs_ui::remember_rulers(app, enabled); + } + Some(Ok(json!(enabled))) + } + "edit.freeTransform" + | "edit.transform.scale" + | "edit.transform.rotate" + | "edit.transform.skew" + | "edit.transform.distort" + | "edit.transform.perspective" => Some((|| { + if app.ui.transform.as_ref().is_some_and(|transform| transform.content_aware.is_some()) { + return Err(crate::transform_tool::CAS_ONLY_SCALES.into()); + } + if app.ui.transform.is_none() { + crate::transform_tool::begin(app, ctx)?; + } + if let Some(transform) = app.ui.transform.as_mut() { + transform.mode = crate::state::TransformMode::for_command(id); + } + Ok(json!({"transform": app.ui.transform})) + })()), + "edit.freeTransformCopy" => Some(crate::transform_tool::begin_copy(app, ctx).map(|_| json!({"transform": app.ui.transform}))), + "edit.transform.warp" | "layer.smartObjects.warp" if params.as_object().is_none_or(|object| object.is_empty()) => { + Some(crate::transform_tool::begin_warp(app, ctx).map(|_| json!({"transform": app.ui.transform}))) + } + "edit.transform.splitWarpCrosswise" + | "edit.transform.splitWarpHorizontally" + | "edit.transform.splitWarpVertically" + | "edit.transform.removeWarpSplit" + if app.ui.transform.as_ref().is_some_and(|transform| transform.warp.is_some()) && params.get("warp").is_none() => + { + let at = params.get("at").and_then(Value::as_array).and_then(|array| Some([array.first()?.as_f64()?, array.get(1)?.as_f64()?])); + Some(crate::transform_tool::split(app, id, at).map(|_| json!({"transform": app.ui.transform}))) + } + "edit.transform.warpGrid" if app.ui.transform.as_ref().is_some_and(|transform| transform.warp.is_some()) && params.get("warp").is_none() => { + Some(crate::transform_tool::edit_session_warp(app, id, params).map(|_| json!({"transform": app.ui.transform}))) + } + sz if crate::sizing::is_sizing(sz) && params.as_object().is_none_or(|object| object.is_empty()) => { + Some(crate::sizing::open(app, sz).map(|dialog| json!({"dialog": dialog})).ok_or_else(|| "no document".to_string())) + } + "view.newGuide" if params.as_object().is_none_or(|object| object.is_empty()) => Some(Ok(json!({"dialog": crate::new_guide_ui::open(app)}))), + fl if crate::filter_dialog::has_dialog(fl) && params.as_object().is_none_or(|object| object.is_empty()) => { + Some(Ok(json!({"dialog": crate::filter_dialog::open(app, fl)}))) + } + a if crate::adjust_dialog::has_dialog(a) && params.as_object().is_none_or(|object| object.is_empty()) => { + Some(crate::adjust_dialog::open(app, a).map(|dialog| json!({"dialog": dialog})).ok_or_else(|| "no document".to_string())) + } + _ => None, + } +} + +fn invoke_window_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) -> Option> { + match id { + "window.newWindowForDocument" => Some((|| { + let doc = app.session.active_index().ok_or("no document")?; + let wid = app.ui.alloc_id(); + let view = app.ui.views[doc].clone(); + app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); + Ok(json!({"window": wid})) + })()), + "window.theme.toggle" => { + crate::prefs_ui::cycle_appearance(app, ctx); + Some(Ok(Value::Null)) + } + "view.darkenInterface" | "view.lightenInterface" => { + Some(crate::prefs_ui::step_brightness(app, ctx, id == "view.lightenInterface").map(|()| json!({"theme": app.ui.theme.id()}))) + } + "window.theme.system" => Some(app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"})).map(|_| { + crate::prefs_ui::sync_appearance(app, ctx); + Value::Null + })), + "window.theme.pro" + | "window.theme.proMedium" + | "window.theme.proLightGray" + | "window.theme.proLight" + | "window.theme.studio" + | "window.theme.studioLight" + | "window.theme.classic" + | "window.theme.solarizedDark" + | "window.theme.adwaita" + | "window.theme.adwaitaDark" + | "window.theme.breezeLight" + | "window.theme.breezeDark" + | "window.theme.softLight" + | "window.theme.softDark" => { + let theme = crate::theme::ThemeKind::from_name(&id["window.theme.".len()..]).unwrap_or_default(); + app.set_theme(ctx, theme); + Some(Ok(Value::Null)) + } + _ if id.starts_with(crate::native_menu::LANGUAGE_PREFIX) => { + let code = &id[crate::native_menu::LANGUAGE_PREFIX.len()..]; + if code != "auto" && !crate::i18n::Lang::all().any(|lang| lang.code() == code) { + Some(Err(format!("unknown UI language `{code}`"))) + } else { + Some(app.run("prefs.set", json!({"values": {"interface.language": code}}))) + } + } + "window.togglePanels" => Some(toggle_panels(app)), + "window.nextDocument" | "window.previousDocument" => Some((|| { + let count = app.session.documents().len(); + let active = app.session.active_index().ok_or("no document open")?; + let next = if id == "window.nextDocument" { (active + 1) % count } else { (active + count - 1) % count }; + app.session.set_active(next); + app.jobs.focus = None; + Ok(json!({"document": next})) + })()), + _ if id.starts_with(DOCUMENT_ITEM) => Some((|| { + let count = app.session.documents().len(); + let next = + id.strip_prefix(DOCUMENT_ITEM).ok_or("no such document")?.parse::().ok().filter(|index| *index < count).ok_or("no such document")?; + app.session.set_active(next); + app.jobs.focus = None; + Ok(json!({"document": next})) + })()), + _ if id.starts_with("window.toggle.") => Some(toggle_panel(app, id)), + _ => None, + } +} + +fn toggle_panels(app: &mut PhotocraftApp) -> Result { + if app.ui.view.hides_chrome() { + app.ui.panels.full_screen_chrome = !app.ui.panels.full_screen_chrome; + return Ok(Value::Null); + } + let panels = &mut app.ui.panels; + match panels.hidden_by_tab.take() { + Some([toolbar, options, dock]) if !(panels.toolbar || panels.options_bar || panels.dock) => { + (panels.toolbar, panels.options_bar, panels.dock) = (toolbar, options, dock); + } + _ if panels.toolbar || panels.options_bar || panels.dock => { + panels.hidden_by_tab = Some([panels.toolbar, panels.options_bar, panels.dock]); + (panels.toolbar, panels.options_bar, panels.dock) = (false, false, false); + } + _ => (panels.toolbar, panels.options_bar, panels.dock) = (true, true, true), + } + Ok(Value::Null) +} + +fn toggle_panel(app: &mut PhotocraftApp, id: &str) -> Result { + let key = &id["window.toggle.".len()..]; + if let Some(group) = crate::dock::Group::from_key(key).filter(|group| group.shown(&app.ui.panels) && app.ui.dock.is_collapsed(*group)) { + crate::dock::reveal(app, group); + return Ok(Value::Null); + } + let panels = &mut app.ui.panels; + let slot = match key { + "layers" => &mut panels.layers, + "history" => &mut panels.history, + "properties" => &mut panels.properties, + "color" => &mut panels.color, + "navigator" => &mut panels.navigator, + "toolbar" => &mut panels.toolbar, + "options" => &mut panels.options_bar, + "brushSettings" => &mut panels.brush_settings, + "brushes" => &mut panels.brushes, + "dock" => &mut panels.dock, + _ => return Err(format!("unknown panel in {id}")), + }; + *slot = !*slot; + if let Some(group) = crate::dock::Group::from_key(key).filter(|group| group.shown(&app.ui.panels)) { + crate::dock::reveal(app, group); + } + Ok(Value::Null) +} + /// Workspace presets (Window → Workspace): which panels are visible. pub fn apply_workspace(app: &mut PhotocraftApp) { // Saved workspaces (Window › Workspace › New Workspace…) restore their own layout. 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 { From 79e9fa6f7c40860feb2b367f704957ba455fdb37 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 06/35] Refactor UI panels for strict Clippy checks --- crates/ui-egui/src/panels/actions.rs | 288 ++--- 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 | 59 +- crates/ui-egui/src/panels/layers.rs | 2 +- crates/ui-egui/src/panels/navigator.rs | 2 +- crates/ui-egui/src/panels/options_bar.rs | 991 +++++++++--------- 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 +- 18 files changed, 781 insertions(+), 701 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index a4a5969544..004d152185 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -11,6 +11,7 @@ use serde_json::{Value, json}; use photocraft_engine::actions_cmds::{self, Action}; use crate::PhotocraftApp; +use crate::icons; use crate::theme::Tokens; /// Which row is selected and which rows are expanded. The action list itself is @@ -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)) { @@ -1060,56 +1079,11 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } if expanded { - for (step, (id, params)) in steps.iter().enumerate() { - let (r, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click_and_drag()); - if reveal == Some((i, step + 1)) { - ui.scroll_to_rect(r, Some(egui::Align::BOTTOM)); - } - let label = step_label(id, params); - let selected = app.ui.actions.selected == Some(i) && app.ui.actions.selected_step == Some(step); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &label)); - if selected { - ui.painter().rect_filled(r, 0.0, t.row_selected); - } else if response.hovered() { - ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5)); - } - if let Some(change) = drag_row(ui, &response, DragRow { action: i, step: Some(step) }, &t) { - moved = Some(change); - } - let on = !disabled.contains(&step); - let color = if on { t.text_dim } else { t.text_faint }; - ui.painter().text(pos2(x0 + 62.0, r.center().y), Align2::LEFT_CENTER, &label, egui::FontId::proportional(11.5), color); - // Photoshop's check column: unchecked steps are skipped by playback, Batch and droplets. - let check = ui.interact( - Rect::from_center_size(pos2(x0 + 30.0, r.center().y), vec2(16.0, 16.0)), - ui.scope_id().with(("action-step-check", i, step)), - Sense::click(), - ); - check.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, on, format!("{}: {label}", tl!("Include in playback")))); - paint_check(ui, check.rect, on, &t); - // Photoshop's dialog column: playback shows the step's dialog, seeded with its - // recorded values, and continues when it is confirmed. - let with_dialog = dialogs.contains(&step); - let dialog = ui.interact( - Rect::from_center_size(pos2(x0 + 46.0, r.center().y), vec2(16.0, 16.0)), - ui.scope_id().with(("action-step-dialog", i, step)), - Sense::click(), - ); - // A toggle button, not a check box, so the check column stays the only CheckBox role. - dialog.widget_info(|| { - egui::WidgetInfo::selected(egui::Role::Button, true, with_dialog, format!("{}: {label}", tl!("Show dialog during playback"))) - }); - crate::icons::paint(ui, dialog.rect, "message-square", 11.0, if with_dialog { t.icon } else { t.text_faint.gamma_multiply(0.45) }); - let dialog = dialog.on_hover_text(tl!("Show dialog during playback")); - if check.on_hover_text(tl!("Include in playback")).clicked() { - toggled = Some((i, step)); - } else if dialog.clicked() { - dialog_toggled = Some((i, step)); - } else if response.clicked() { - app.ui.actions.selected = Some(i); - app.ui.actions.selected_step = Some(step); - } - } + let context = StepRowsContext { action: i, x0, steps, disabled, dialogs, reveal, tokens: &t }; + let events = draw_step_rows(app, ui, &context); + moved = moved.or(events.moved); + toggled = toggled.or(events.toggled); + dialog_toggled = dialog_toggled.or(events.dialog_toggled); } } }); @@ -1190,5 +1164,83 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +struct StepRowsContext<'a> { + action: usize, + x0: f32, + steps: &'a [(String, Value)], + disabled: &'a std::collections::BTreeSet, + dialogs: &'a std::collections::BTreeSet, + reveal: Option<(usize, usize)>, + tokens: &'a Tokens, +} + +#[derive(Default)] +struct StepRowEvents { + moved: Option<(DragRow, usize)>, + toggled: Option<(usize, usize)>, + dialog_toggled: Option<(usize, usize)>, +} + +fn draw_step_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, context: &StepRowsContext<'_>) -> StepRowEvents { + let mut events = StepRowEvents::default(); + for (step, (id, params)) in context.steps.iter().enumerate() { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click_and_drag()); + if context.reveal == Some((context.action, step + 1)) { + ui.scroll_to_rect(rect, Some(egui::Align::BOTTOM)); + } + let label = step_label(id, params); + draw_step_label(app, ui, rect, &response, step, &label, context); + events.moved = drag_row(ui, &response, DragRow { action: context.action, step: Some(step) }, context.tokens).or(events.moved); + let (check, dialog) = draw_step_controls(ui, rect, step, &label, context); + if check.clicked() { + events.toggled = Some((context.action, step)); + } else if dialog.clicked() { + events.dialog_toggled = Some((context.action, step)); + } else if response.clicked() { + app.ui.actions.selected = Some(context.action); + app.ui.actions.selected_step = Some(step); + } + } + events +} + +fn draw_step_label(app: &PhotocraftApp, ui: &egui::Ui, rect: Rect, response: &egui::Response, step: usize, label: &str, context: &StepRowsContext<'_>) { + let selected = app.ui.actions.selected == Some(context.action) && app.ui.actions.selected_step == Some(step); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, label)); + if selected { + ui.painter().rect_filled(rect, 0.0, context.tokens.row_selected); + } else if response.hovered() { + ui.painter().rect_filled(response.rect, 0.0, context.tokens.hover.gamma_multiply(0.5)); + } + let color = if context.disabled.contains(&step) { context.tokens.text_faint } else { context.tokens.text_dim }; + ui.painter().text(pos2(context.x0 + 62.0, rect.center().y), Align2::LEFT_CENTER, label, egui::FontId::proportional(11.5), color); +} + +fn draw_step_controls(ui: &mut egui::Ui, rect: Rect, step: usize, label: &str, context: &StepRowsContext<'_>) -> (egui::Response, egui::Response) { + let on = !context.disabled.contains(&step); + let check = ui.interact( + Rect::from_center_size(pos2(context.x0 + 30.0, rect.center().y), vec2(16.0, 16.0)), + ui.scope_id().with(("action-step-check", context.action, step)), + Sense::click(), + ); + check.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, on, format!("{}: {label}", tl!("Include in playback")))); + paint_check(ui, check.rect, on, context.tokens); + let with_dialog = context.dialogs.contains(&step); + let dialog = ui.interact( + Rect::from_center_size(pos2(context.x0 + 46.0, rect.center().y), vec2(16.0, 16.0)), + ui.scope_id().with(("action-step-dialog", context.action, step)), + Sense::click(), + ); + dialog.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, with_dialog, format!("{}: {label}", tl!("Show dialog during playback")))); + crate::icons::paint( + ui, + dialog.rect, + "message-square", + 11.0, + if with_dialog { context.tokens.icon } else { context.tokens.text_faint.gamma_multiply(0.45) }, + ); + (check.on_hover_text(tl!("Include in playback")), dialog.on_hover_text(tl!("Show dialog during playback"))) +} + #[cfg(test)] mod tests; 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..5f182c13a5 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. @@ -55,28 +57,51 @@ fn eye_sweep(ctx: &egui::Context, l: &Layer, row: Rect, eye: &egui::Response, ac let set = |visible: bool, key: u64| ("layer.setProps".to_string(), json!({"layer": l.id.0, "visible": visible, "coalesce": format!("layer-eye-sweep:{key}")})); if eye.drag_started() { - let sweep = EyeSweep { visible: !l.visible, key: ctx.cumulative_pass_nr(), swept: vec![l.id.0] }; - actions.push(set(sweep.visible, sweep.key)); - ctx.data_mut(|d| d.insert_temp(id, sweep)); + start_eye_sweep(ctx, l, id, actions, &set); + } else { + continue_eye_sweep(ctx, l, row, id, actions, &set); + } +} + +fn start_eye_sweep(ctx: &egui::Context, layer: &Layer, id: egui::Id, actions: &mut Vec<(String, Value)>, set: &impl Fn(bool, u64) -> (String, Value)) { + let sweep = EyeSweep { visible: !layer.visible, key: ctx.cumulative_pass_nr(), swept: vec![layer.id.0] }; + actions.push(set(sweep.visible, sweep.key)); + ctx.data_mut(|data| data.insert_temp(id, sweep)); +} + +fn continue_eye_sweep( + ctx: &egui::Context, + layer: &Layer, + row: Rect, + id: egui::Id, + actions: &mut Vec<(String, Value)>, + set: &impl Fn(bool, u64) -> (String, Value), +) { + let Some(mut sweep) = ctx.data(|data| data.get_temp::(id)) else { return }; + if !sweep_pointer_down(ctx) { + ctx.data_mut(|data| data.remove::(id)); return; } - let Some(mut sweep) = ctx.data(|d| d.get_temp::(id)) else { return }; - let (down, pos, delta) = ctx.input(|i| (i.pointer.primary_down(), i.pointer.interact_pos(), i.pointer.delta())); - if !down { - ctx.data_mut(|d| d.remove::(id)); + let Some((y0, y1)) = swept_pointer_range(ctx) else { return }; + if y1 < row.top() || y0 >= row.bottom() || sweep.swept.contains(&layer.id.0) { return; } - // Everything the pointer passed since the last frame, so a fast drag skips no row. - let Some(p) = pos else { return }; - let (y0, y1) = ((p.y - delta.y).min(p.y), (p.y - delta.y).max(p.y)); - if y1 < row.top() || y0 >= row.bottom() || sweep.swept.contains(&l.id.0) { - return; - } - if l.visible != sweep.visible { + if layer.visible != sweep.visible { actions.push(set(sweep.visible, sweep.key)); } - sweep.swept.push(l.id.0); - ctx.data_mut(|d| d.insert_temp(id, sweep)); + sweep.swept.push(layer.id.0); + ctx.data_mut(|data| data.insert_temp(id, sweep)); +} + +fn sweep_pointer_down(ctx: &egui::Context) -> bool { + ctx.input(|input| input.pointer.primary_down()) +} + +/// The pointer segment between frames catches rows even when a fast drag skips them visually. +fn swept_pointer_range(ctx: &egui::Context) -> Option<(f32, f32)> { + let (position, delta) = ctx.input(|input| (input.pointer.interact_pos(), input.pointer.delta())); + let p = position?; + Some(((p.y - delta.y).min(p.y), (p.y - delta.y).max(p.y))) } /// Marker in the clipped row's existing 12-point slot, beside its thumbnail. 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..48f1ba9962 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 super::{BlendMode, Color32, PhotocraftApp, RichText, Sense, Tokens, Tool, Value, icons, json, vec2, widgets}; +use photocraft_paint::BrushSettings; // 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,488 @@ 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 From dccf6182eb2780a3489c327f8b208cdcd7ff0d85 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 07/35] Refactor UI support for strict Clippy checks --- crates/ui-egui/src/control/dispatch.rs | 2 +- crates/ui-egui/src/control/params.rs | 2 +- crates/ui-egui/src/i18n/tests.rs | 8 + crates/ui-egui/src/lib.rs | 5 +- .../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 +++++++++++++--- 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 +- 31 files changed, 374 insertions(+), 172 deletions(-) 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/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/lib.rs b/crates/ui-egui/src/lib.rs index 190d9e5603..a1954b3d49 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -127,9 +127,8 @@ pub use dialogs::export_dialog; pub use dialogs::file_ui; pub use dialogs::fill_ui; pub use dialogs::filter_dialog; -use dialogs::filter_preview_ui; #[cfg(not(target_arch = "wasm32"))] -use dialogs::filter_preview_worker; +use dialogs::filter_preview_ui; pub use dialogs::gallery_ui; pub use dialogs::guide_layout_ui; pub use dialogs::history_options_ui; @@ -473,7 +472,7 @@ pub struct PhotocraftApp { pub(crate) filter_preview: Option, pub(crate) smart_filter_targets: smart_filter_dialog::Targets, #[cfg(not(target_arch = "wasm32"))] - filter_preview_worker: filter_preview_worker::Worker, + filter_preview_worker: crate::dialogs::filter_preview_worker::Worker, /// Full CPU canvas redraws running in the background, by document (#4024). pub(crate) redraws: std::collections::HashMap, /// The last finished background redraws, for going back to a state drawn a moment ago (#6528). 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/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 { From 32f884d75ce171358d843c6ccaec24ed70e2c257 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:05 +0000 Subject: [PATCH 08/35] Refactor UI tools for strict Clippy checks --- .../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 +- crates/ui-egui/src/tools/type_tool.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 | 8 +- 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 | 317 ++++++++++-------- 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 +- crates/ui-egui/src/tools/vector_ui.rs | 5 +- .../ui-egui/src/tools/vector_ui/curvature.rs | 2 +- crates/ui-egui/src/tools/vector_ui/options.rs | 2 +- crates/ui-egui/src/tools/vector_ui/overlay.rs | 11 +- .../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 +- 30 files changed, 359 insertions(+), 276 deletions(-) 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.rs b/crates/ui-egui/src/tools/type_tool.rs index d5a1bc6b77..bd1de4cf2d 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -34,7 +34,7 @@ mod pointer; #[cfg(test)] use defaults::{apply, default_style_params, default_styles, shown_scale}; pub use defaults::{foreground_changed, open_color_picker}; -pub(crate) use defaults::{formatting_params, target, target_text, type_unit, with_target}; +pub(crate) use defaults::{formatting_params, target, target_text, type_unit}; #[cfg(test)] pub(crate) use editing::{CharToggle, step_char_metric, toggle_char_style, toggle_hyphenate}; pub use editing::{cancel, commit, commit_with, edit_active, edit_at, end_if_left}; 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..266bdb6f02 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. @@ -283,8 +283,10 @@ pub(crate) struct FontLibrary { /// target's whole text, on one line and at most 60 characters. `None` without a type target or /// with blank text (the preview then shows its sample). pub(super) fn preview_text(app: &PhotocraftApp) -> Option { - let (layer, range) = target(app)?; - let text = &text_layer(&app.session.active()?.doc, LayerId(layer))?.text; + let (layer, range) = defaults::target(app)?; + let text = &crate::type_tool::text_layer(&app.session.active()?.doc, crate::type_tool::LayerId(layer))?.text; + use crate::type_tool::defaults; + let chosen: String = match range { Some([a, b]) => text.chars().skip(a).take(b.saturating_sub(a)).collect(), None => text.clone(), 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..e262571746 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. @@ -138,14 +138,6 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { let is_key = matches!(ev, egui::Event::Key { .. }); let text = if is_key { current_text(app, id).unwrap_or_default() } else { String::new() }; let n = if is_key { text.chars().count() } else { 0 }; - let set = |app: &mut PhotocraftApp, caret: usize, extend: bool| { - if let Some(e) = app.ui.text_edit.as_mut() { - e.caret = caret.min(n); - if !extend { - e.anchor = e.caret; - } - } - }; handled[k] = true; match ev { egui::Event::Text(s) => insert_typed(app, s), @@ -199,133 +191,9 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } egui::Event::Cut => cut_selection(app, ctx), egui::Event::Key { key, pressed: true, modifiers: m, .. } => { - use egui::Key; - let key = &flow_key(*key, vertical_flow); - match key { - // Photoshop's type formatting keys act on the selected characters and win - // over the global ⇧⌘K/U/B/I (Color Settings, Desaturate, Auto Color, Inverse) - // while typing. Each press is one history step. - Key::K | Key::U | Key::B | Key::I | Key::Slash | Key::Questionmark if m.command && m.shift && !m.alt => { - let which = match key { - Key::K => CharToggle::AllCaps, - Key::U => CharToggle::Underline, - Key::B => CharToggle::FauxBold, - Key::I => CharToggle::FauxItalic, - _ => CharToggle::Strikethrough, - }; - toggle_char_style(app, which); - } - Key::H if m.command && m.shift && m.alt => toggle_hyphenate(app), - // ⌥↑/↓ leading -/+2 pt, ⇧⌥↑/↓ baseline shift +/-2 pt (10 with ⌘/Ctrl). - Key::ArrowUp | Key::ArrowDown if m.alt => { - let step = if m.command { 10.0 } else { 2.0 }; - let up = *key == Key::ArrowUp; - if m.shift { - step_char_metric(app, "baselineShiftBy", if up { step } else { -step }); - } else { - step_char_metric(app, "leadingBy", if up { -step } else { step }); - } - } - // ⌥←/→ over a selection tracks it by -/+20 (100 with ⌘/Ctrl). - Key::ArrowLeft | Key::ArrowRight if m.alt && !m.shift && a != b => { - let step = if m.command { 100.0 } else { 20.0 }; - step_char_metric(app, "trackingBy", if *key == Key::ArrowRight { step } else { -step }); - } - Key::Backspace | Key::Delete => { - if a == b { - let fwd = *key == Key::Delete; - let to = match (fwd, m.alt, m.command) { - (false, _, true) => line_edge(app, id, a, false), - (false, true, _) => word_boundary(&text, a, false), - (false, _, _) => a.saturating_sub(1), - (true, true, _) => word_boundary(&text, a, true), - (true, _, _) => (a + 1).min(n), - }; - if to != a { - if let Some(e) = app.ui.text_edit.as_mut() { - e.anchor = to; - } - insert(app, ""); - } - } else { - insert(app, ""); - } - } - // Photoshop: Alt/Option+←/→ at a collapsed caret kerns the pair before it by - // 20/1000 em (100 with ⌘/Ctrl), one history step per press. - Key::ArrowLeft | Key::ArrowRight if m.alt && !m.shift && a == b => { - let step = if m.command { 100.0 } else { 20.0 }; - kern_pair(app, id, ed.caret, if *key == Key::ArrowRight { step } else { -step }); - } - Key::ArrowLeft | Key::ArrowRight => { - let fwd = *key == Key::ArrowRight; - // Word movement: ⌘/Ctrl (Photoshop's; Alt is kerning), and Alt+Shift - // extends the selection by words; Home/End go to the line edges. - let to = if m.command || m.alt { - word_boundary(&text, ed.caret, fwd) - } else if a != b && !m.shift { - if fwd { b } else { a } - } else if fwd { - ed.caret + 1 - } else { - ed.caret.saturating_sub(1) - }; - set(app, to, m.shift); - } - Key::ArrowUp | Key::ArrowDown => { - let to = if m.command { - if *key == Key::ArrowUp { 0 } else { n } - } else { - line_step(app, id, ed.caret, if *key == Key::ArrowUp { -1 } else { 1 }) - }; - set(app, to, m.shift); - } - Key::Home | Key::End => { - let to = line_edge(app, id, ed.caret, *key == Key::End); - set(app, to, m.shift); - } - Key::Enter if m.command => commit_with(app, *m), - Key::Enter => insert(app, "\n"), - // Photoshop types a tab character; layout advances it to the next tab stop. - Key::Tab if !m.command && !m.alt && !m.shift => { - // egui queues focus navigation before this handler runs; consuming the - // key alone would let the menu bar take focus after the first tab (#8889). - ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); - insert(app, "\t"); - } - Key::Escape if crate::type_transform::active(app) => crate::type_transform::cancel_drag(app), - // The Type Mask tools: Escape always cancels, leaving the selection as it was. - Key::Escape if ed.mask => cancel(app), - // Preferences ▸ Type: with "Use Escape to Commit" off, Escape cancels the - // session (undoes it, removing a just-created layer) like the Cancel button. - Key::Escape if app.session.prefs().type_.use_esc_to_commit => commit(app), - Key::Escape => cancel(app), - Key::A if m.command => { - if let Some(e) = app.ui.text_edit.as_mut() { - e.anchor = 0; - e.caret = n; - } - } - // Photoshop: while editing type, ⌘/Ctrl+T shows or hides the Character panel - // (Free Transform of the layer being typed into is not what it means here). - Key::T if m.command && !m.shift && !m.alt => { - let _ = crate::menus::invoke(app, ctx, "window.panel.character", json!({})); - } - // Other command shortcuts (⌘Z, ⌘S, …) pass through to the menus. - _ if m.command => { - if *key == Key::Z { - crate::type_transform::cancel_drag(app); - } - if reset_guarded(app, ctx.viewport_id()) || app.type_ime.incoming.is_some() { - interrupt_action(app, ctx.viewport_id()); - custom_mutations = false; - deferred_custom = true; - suspend_reset(app, ctx); - } - handled[k] = false; - } - _ => {} - } + let edit = KeyEditContext { id, vertical_flow, edit: &ed, selection: (a, b), text: &text, char_count: n }; + let mut flow = EventFlow { handled: &mut handled, index: k, custom_mutations: &mut custom_mutations, deferred_custom: &mut deferred_custom }; + handle_pressed_key(app, ctx, key, m, &edit, &mut flow); } egui::Event::Key { pressed: false, modifiers: m, .. } => handled[k] = !m.command, _ => handled[k] = false, @@ -345,3 +213,180 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } app.ui.text_edit.is_some() } + +struct KeyEditContext<'a> { + id: LayerId, + vertical_flow: bool, + edit: &'a crate::state::TextEdit, + selection: (usize, usize), + text: &'a str, + char_count: usize, +} + +struct EventFlow<'a> { + handled: &'a mut [bool], + index: usize, + custom_mutations: &'a mut bool, + deferred_custom: &'a mut bool, +} + +fn handle_pressed_key( + app: &mut PhotocraftApp, + ctx: &egui::Context, + raw_key: &egui::Key, + modifiers: &egui::Modifiers, + edit: &KeyEditContext<'_>, + flow: &mut EventFlow<'_>, +) { + let key = flow_key(*raw_key, edit.vertical_flow); + if handle_style_key(app, key, modifiers, edit) || handle_delete_key(app, key, modifiers, edit) || handle_move_key(app, key, modifiers, edit) { + return; + } + + use egui::Key; + match key { + Key::Enter if modifiers.command => commit_with(app, *modifiers), + Key::Enter => insert(app, "\n"), + Key::Tab if !modifiers.command && !modifiers.alt && !modifiers.shift => { + ctx.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); + insert(app, "\t"); + } + Key::Escape if crate::type_transform::active(app) => crate::type_transform::cancel_drag(app), + Key::Escape if edit.edit.mask => cancel(app), + Key::Escape if app.session.prefs().type_.use_esc_to_commit => commit(app), + Key::Escape => cancel(app), + Key::A if modifiers.command => { + if let Some(state) = app.ui.text_edit.as_mut() { + state.anchor = 0; + state.caret = edit.char_count; + } + } + Key::T if modifiers.command && !modifiers.shift && !modifiers.alt => { + let _ = crate::menus::invoke(app, ctx, "window.panel.character", json!({})); + } + _ if modifiers.command => { + if key == Key::Z { + crate::type_transform::cancel_drag(app); + } + if reset_guarded(app, ctx.viewport_id()) || app.type_ime.incoming.is_some() { + interrupt_action(app, ctx.viewport_id()); + *flow.custom_mutations = false; + *flow.deferred_custom = true; + suspend_reset(app, ctx); + } + flow.handled[flow.index] = false; + } + _ => {} + } +} + +fn handle_style_key(app: &mut PhotocraftApp, key: egui::Key, modifiers: &egui::Modifiers, edit: &KeyEditContext<'_>) -> bool { + use egui::Key; + match key { + Key::K | Key::U | Key::B | Key::I | Key::Slash | Key::Questionmark if modifiers.command && modifiers.shift && !modifiers.alt => { + let style = match key { + Key::K => CharToggle::AllCaps, + Key::U => CharToggle::Underline, + Key::B => CharToggle::FauxBold, + Key::I => CharToggle::FauxItalic, + _ => CharToggle::Strikethrough, + }; + toggle_char_style(app, style); + true + } + Key::H if modifiers.command && modifiers.shift && modifiers.alt => { + toggle_hyphenate(app); + true + } + Key::ArrowUp | Key::ArrowDown if modifiers.alt => { + let amount = if modifiers.command { 10.0 } else { 2.0 }; + let up = key == Key::ArrowUp; + let (property, delta) = + if modifiers.shift { ("baselineShiftBy", if up { amount } else { -amount }) } else { ("leadingBy", if up { -amount } else { amount }) }; + step_char_metric(app, property, delta); + true + } + Key::ArrowLeft | Key::ArrowRight if modifiers.alt && !modifiers.shift && edit.selection.0 != edit.selection.1 => { + let amount = if modifiers.command { 100.0 } else { 20.0 }; + let delta = if key == Key::ArrowRight { amount } else { -amount }; + step_char_metric(app, "trackingBy", delta); + true + } + Key::ArrowLeft | Key::ArrowRight if modifiers.alt && !modifiers.shift && edit.selection.0 == edit.selection.1 => { + let amount = if modifiers.command { 100.0 } else { 20.0 }; + let delta = if key == Key::ArrowRight { amount } else { -amount }; + kern_pair(app, edit.id, edit.edit.caret, delta); + true + } + _ => false, + } +} + +fn handle_delete_key(app: &mut PhotocraftApp, key: egui::Key, modifiers: &egui::Modifiers, edit: &KeyEditContext<'_>) -> bool { + use egui::Key; + if !matches!(key, Key::Backspace | Key::Delete) { + return false; + } + let (start, end) = edit.selection; + if start == end { + let forward = key == Key::Delete; + let to = match (forward, modifiers.alt, modifiers.command) { + (false, _, true) => line_edge(app, edit.id, start, false), + (false, true, _) => word_boundary(edit.text, start, false), + (false, _, _) => start.saturating_sub(1), + (true, true, _) => word_boundary(edit.text, start, true), + (true, _, _) => (start + 1).min(edit.char_count), + }; + if to != start { + if let Some(state) = app.ui.text_edit.as_mut() { + state.anchor = to; + } + insert(app, ""); + } + } else { + insert(app, ""); + } + true +} + +fn handle_move_key(app: &mut PhotocraftApp, key: egui::Key, modifiers: &egui::Modifiers, edit: &KeyEditContext<'_>) -> bool { + use egui::Key; + let caret = edit.edit.caret; + let (start, end) = edit.selection; + let destination = match key { + Key::ArrowLeft | Key::ArrowRight => { + let forward = key == Key::ArrowRight; + Some(if modifiers.command || modifiers.alt { + word_boundary(edit.text, caret, forward) + } else if start != end && !modifiers.shift { + if forward { end } else { start } + } else if forward { + caret + 1 + } else { + caret.saturating_sub(1) + }) + } + Key::ArrowUp | Key::ArrowDown => Some(if modifiers.command { + if key == Key::ArrowUp { 0 } else { edit.char_count } + } else { + line_step(app, edit.id, caret, if key == Key::ArrowUp { -1 } else { 1 }) + }), + Key::Home | Key::End => Some(line_edge(app, edit.id, caret, key == Key::End)), + _ => None, + }; + if let Some(destination) = destination { + set_caret(app, edit.char_count, destination, modifiers.shift); + true + } else { + false + } +} + +fn set_caret(app: &mut PhotocraftApp, char_count: usize, caret: usize, extend: bool) { + if let Some(state) = app.ui.text_edit.as_mut() { + state.caret = caret.min(char_count); + if !extend { + state.anchor = state.caret; + } + } +} 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.rs b/crates/ui-egui/src/tools/vector_ui.rs index 301db9b63b..c86ad3a1cd 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -2,7 +2,9 @@ //! Direct Selection (A) lives in `direct_select`. //! All edits go through the engine's `shape.*` / `path.*` commands. -use egui::{Color32, Pos2, Rect, Sense, Stroke, pos2, vec2}; +#[cfg(test)] +use egui::Pos2; +use egui::{Color32, Rect, Sense, Stroke, pos2, vec2}; use photocraft_doc::vector::Path; use photocraft_doc::{Document, LayerContent}; use photocraft_geom::Affine; @@ -41,7 +43,6 @@ use path_ops::target_path; pub use path_ops::{active_path_name, path_selection_finish, path_to_selection, pick_shape_at, selected_document_path, takes_path_mask, with_active_path}; pub(crate) use path_ops::{ active_shape_path, active_type_path, delete_key_deletes_work_path, deselect_loaded_path, free_transform_path, targeted_vector_mask, work_path_shown, - work_path_shown_in, }; #[cfg(test)] use paths_panel::path_context_actions; 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/overlay.rs b/crates/ui-egui/src/tools/vector_ui/overlay.rs index 9649b1365d..7e2b6ab4e6 100644 --- a/crates/ui-egui/src/tools/vector_ui/overlay.rs +++ b/crates/ui-egui/src/tools/vector_ui/overlay.rs @@ -1,7 +1,14 @@ use super::curvature::curvature_refresh; -use super::path_ops::{active_type_path, targeted_vector_mask}; +use super::path_ops::{active_type_path, targeted_vector_mask, work_path_shown_in}; use super::pen::{closing, over_first_anchor, shift_45}; -use super::*; +use egui::{Color32, Pos2, Rect, Stroke, pos2, vec2}; +use photocraft_doc::vector::Path; +use photocraft_doc::{Document, LayerContent}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::Tool; +use crate::theme::Tokens; // --------------------------------------------------------------------------------------------- // Drawing 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) From 8bc939cf3ba73712c78fd278802c66f4e10623ba Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 09/35] Refactor algo for strict Clippy checks --- crates/algo/examples/bench_filters2.rs | 5 +- crates/algo/src/artistic_fx.rs | 61 ++- crates/algo/src/blur/motion_fft.rs | 208 ++++++---- crates/algo/src/inpaint.rs | 229 ++++++----- crates/algo/src/inpaint/common.rs | 2 +- crates/algo/src/inpaint/solver.rs | 2 +- crates/algo/src/inpaint/sources.rs | 2 +- crates/algo/src/inpaint/synthesis.rs | 2 +- crates/algo/src/panorama/blend.rs | 2 +- crates/algo/src/pixelate/cells.rs | 147 ++++--- crates/algo/src/render2.rs | 524 ++++++++++++++----------- crates/algo/src/shape_blur.rs | 137 ++++--- crates/algo/src/sharpen/exact.rs | 102 +++-- crates/algo/src/sharpen/fft.rs | 257 +++++++----- crates/algo/src/stylize2/extrude.rs | 274 ++++++++----- 15 files changed, 1200 insertions(+), 754 deletions(-) diff --git a/crates/algo/examples/bench_filters2.rs b/crates/algo/examples/bench_filters2.rs index f6b34aca28..3b9aacae24 100644 --- a/crates/algo/examples/bench_filters2.rs +++ b/crates/algo/examples/bench_filters2.rs @@ -4,7 +4,10 @@ //! //! `--json` writes the report `cargo xtask perf` reads: `{"rows": [{"name", "samples_ms"}]}`. //! `--quick` runs the list on a 1500×1000 layer instead, for `cargo xtask perf --quick`. -use photocraft_algo::*; +use photocraft_algo::{ + BlurPath, BlurQuality, BlurShape, DepthSource, Distribution, FieldPin, FilterParams, IrisPin, Light, SmartBlurMode, SpinPin, TextureChannel, apply, + output_area, +}; use photocraft_color::PixelFormat; use photocraft_geom::Rect; use photocraft_raster::Surface; diff --git a/crates/algo/src/artistic_fx.rs b/crates/algo/src/artistic_fx.rs index 1cca6c9468..ca346a1f05 100644 --- a/crates/algo/src/artistic_fx.rs +++ b/crates/algo/src/artistic_fx.rs @@ -555,13 +555,20 @@ pub(crate) fn run(effects: &[GalleryEffect], src: &Image, out: Rect, ctx: &Ctx) res } -/// Applies one gallery effect to the working window in place. +/// Applies one gallery effect to the working window in place. Each category handles its own +/// filters and reports whether the effect was one of them. fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) { + let handled = + apply_artistic(e, win) || apply_brush_strokes(e, win) || apply_distort(e, win) || apply_sketch(e, win, ctx) || apply_stylize_texture(e, win, ctx); + debug_assert!(handled, "every gallery filter belongs to a category"); +} + +/// Artistic filters: the painterly looks of the gallery. +fn apply_artistic(e: &GalleryEffect, win: &mut Win) -> bool { let g = |k: &str| e.get(k); let (w, h) = (win.w, win.h); let (fg, bg) = (rgb(e.foreground), rgb(e.background)); match e.filter { - // ---------------- Artistic ---------------- F::ColoredPencil => { let pw = g("pencilWidth"); let pressure = g("strokePressure") / 15.0; @@ -745,7 +752,16 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) { win.c[i] = map(saturate(win.c[i], 1.2), |v| clamp01(v * k + n).powf(1.1 + sh * 0.6)); } } - // ---------------- Brush Strokes ---------------- + _ => return false, + } + true +} + +/// Brush Strokes filters. +fn apply_brush_strokes(e: &GalleryEffect, win: &mut Win) -> bool { + let g = |k: &str| e.get(k); + let (w, h) = (win.w, win.h); + match e.filter { F::AccentedEdges => { let mut l = win.lum(); blur1(&mut l, w, h, 0.4 + g("smoothness") * 0.3); @@ -859,7 +875,17 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) { *p = map(*p, |v| clamp01((v - 0.5) * (1.0 + con) + 0.5) * (1.0 - ink * 0.9 * (0.5 + con))); } } - // ---------------- Distort ---------------- + _ => return false, + } + true +} + +/// Distort filters. +fn apply_distort(e: &GalleryEffect, win: &mut Win) -> bool { + let g = |k: &str| e.get(k); + let (w, h) = (win.w, win.h); + let bg = rgb(e.background); + match e.filter { F::DiffuseGlow => { let (gr, ga, ca) = (g("graininess") / 10.0, g("glowAmount") / 20.0, g("clearAmount") / 20.0); let thr = 0.2 + ca * 0.7; @@ -903,7 +929,17 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) { win.c[i] = src.sample(x as f32 + 0.5 + dx, y as f32 + 0.5 + dy); } } - // ---------------- Sketch ---------------- + _ => return false, + } + true +} + +/// Sketch filters (foreground is ink, background is paper). +fn apply_sketch(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) -> bool { + let g = |k: &str| e.get(k); + let (w, h) = (win.w, win.h); + let (fg, bg) = (rgb(e.foreground), rgb(e.background)); + match e.filter { F::BasRelief => { let mut l = win.lum(); let orig = l.clone(); @@ -1107,7 +1143,17 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) { win.c[i] = map(win.c[i], |v| (v * (0.85 + 0.25 * fib) - 0.5) * (co * 1.6 + 0.2) + 0.5 + (br - 0.5) * 0.8); } } - // ---------------- Stylize ---------------- + _ => return false, + } + true +} + +/// Stylize and Texture filters. +fn apply_stylize_texture(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) -> bool { + let g = |k: &str| e.get(k); + let (w, h) = (win.w, win.h); + let (fg, bg) = (rgb(e.foreground), rgb(e.background)); + match e.filter { F::GlowingEdges => { blur3(&mut win.c, w, h, 0.3 + g("smoothness") * 0.25); let mut e3 = vec![[0.0f32; 3]; win.c.len()]; @@ -1123,7 +1169,6 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) { *p = map(*q, |v| clamp01(v * k)); } } - // ---------------- Texture ---------------- F::Craquelure => { let (sp, dep, bri) = (g("crackSpacing"), g("crackDepth") / 10.0, g("crackBrightness") / 10.0); let cell = sp * 1.3 + 1.0; @@ -1239,7 +1284,9 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) { } } F::Texturizer => texturize(win, e.choice("texture"), g("scaling"), g("relief"), e.choice("light"), e.flag("invert")), + _ => return false, } + true } fn normalize3(v: [f32; 3]) -> [f32; 3] { diff --git a/crates/algo/src/blur/motion_fft.rs b/crates/algo/src/blur/motion_fft.rs index 9da1b1a1b7..a0bf9dce6a 100644 --- a/crates/algo/src/blur/motion_fft.rs +++ b/crates/algo/src/blur/motion_fft.rs @@ -361,23 +361,7 @@ impl Plan { { return None; } - let mut scales = [0.0f64; 5]; - for (i, pixel) in src.data.chunks_exact(src.ch).enumerate() { - if i % 4096 == 0 && ctl.cancelled() { - return None; - } - if pixel.iter().any(|value| !value.is_finite() || value.abs() > MAX_SAMPLE) - || (alpha && !pixel.last().is_some_and(|value| (0.0..=1.0).contains(value))) - { - return None; - } - let a = if alpha { *pixel.last()? } else { 1.0 }; - for (c, &value) in pixel.iter().enumerate() { - let value = if alpha && c + 1 < src.ch { value * a } else { value }; - let scale = scales.get_mut(c)?; - *scale = scale.max(f64::from(value.abs())); - } - } + let scales = channel_scales(src, alpha, ctl)?; let mut result = buffer(ow.checked_mul(oh)?.checked_mul(src.ch)?, 0.0f64)?; let read = self.read_rect(out)?; let used = read.intersect(&src.rect); @@ -393,81 +377,18 @@ impl Plan { if ctl.cancelled() { return None; } + let pair = ChannelPair { src, alpha, scales: &scales, channel }; data.fill(Number::default()); - for y in used.y0..used.y1 { - if (y - used.y0) % 8 == 0 && ctl.cancelled() { - return None; - } - let source_start = - usize::try_from(y - src.rect.y0).ok()?.checked_mul(sw)?.checked_add(usize::try_from(used.x0 - src.rect.x0).ok()?)?.checked_mul(src.ch)?; - let source_len = usize::try_from(used.x1 - used.x0).ok()?.checked_mul(src.ch)?; - let row = src.data.get(source_start..source_start.checked_add(source_len)?)?; - let start = usize::try_from(y - read.y0).ok()?.checked_mul(self.width)?.checked_add(usize::try_from(used.x0 - read.x0).ok()?)?; - let dst = data.get_mut(start..start.checked_add(source_len / src.ch)?)?; - for (pixel, dst) in row.chunks_exact(src.ch).zip(dst) { - let a = if alpha { *pixel.last()? } else { 1.0 }; - // Normalize each channel separately before packing a pair. - // Otherwise a bright HDR colour's FFT residual could swamp - // a small alpha channel sharing the imaginary component. - let sample = |c: usize| -> f64 { - match (pixel.get(c), scales.get(c)) { - (Some(&value), Some(&scale)) if scale > 0.0 => f64::from(if alpha && c + 1 < src.ch { value * a } else { value }) / scale, - _ => 0.0, - } - }; - *dst = Number::new(sample(channel), sample(channel + 1)); - } - } + self.pack_channel_pair(&pair, used, read, &mut data, ctl)?; self.transform(&mut data, &mut transposed, &mut scratch, false, ctl)?; for (value, kernel) in data.iter_mut().zip(&self.kernel) { *value *= kernel; } self.transform(&mut data, &mut transposed, &mut scratch, true, ctl)?; - let x0 = usize::try_from(-self.min_x).ok()?; - let y0 = usize::try_from(-self.min_y).ok()?; - for (y, dst) in result.chunks_exact_mut(ow * src.ch).enumerate() { - let start = y.checked_add(y0)?.checked_mul(self.width)?.checked_add(x0)?; - let values = data.get(start..start.checked_add(ow)?)?; - for (pixel, value) in dst.chunks_exact_mut(src.ch).zip(values) { - *pixel.get_mut(channel)? = value.re * norm * scales.get(channel)?; - if let Some(next) = pixel.get_mut(channel + 1) { - *next = value.im * norm * scales.get(channel + 1)?; - } - } - } + self.unpack_channel_pair(&pair, &data, &mut result, ow, norm)?; } if alpha { - // The row kernel accumulates in f32. Recompute very small alpha - // near its cutoff so a different summation order cannot expose colour. - let uncertainty = f64::from(self.distance.abs().ceil()) * f64::from(f32::EPSILON) * scales.get(src.ch - 1)?; - for (i, pixel) in result.chunks_exact_mut(src.ch).enumerate() { - if i % 16 == 0 && ctl.cancelled() { - return None; - } - let a = pixel.last_mut()?; - // Valid alpha is nonnegative. Remove transform roundoff at - // zero to keep fully transparent regions empty. - if a.abs() < 1e-14 * scales.get(src.ch - 1)? { - *a = 0.0; - } - *a = a.clamp(0.0, 1.0); - let a = *a; - // The row kernel's f32 sum can straddle the cutoff at long distances. - // Keep its branch and straight colour exactly for that narrow - // range, rather than amplifying a tiny alpha difference. - if a > 0.0 && (a <= 1.01e-7 + uncertainty || (0.99e-7..=1.01e-7).contains(&(a as f32))) { - let x = out.x0.checked_add(i32::try_from(i % ow).ok()?)?; - let y = out.y0.checked_add(i32::try_from(i / ow).ok()?)?; - let original = sample_row_point(src, x, y, alpha, &self.taps, ctl)?; - for (dst, value) in pixel.iter_mut().zip(original) { - *dst = f64::from(value); - } - continue; - } - for value in pixel.iter_mut().take(src.ch - 1) { - *value = if a as f32 > 1e-7 { *value / a } else { 0.0 }; - } - } + self.restore_small_alpha(src, out, ow, &scales, &mut result, ctl)?; } let mut output = buffer(result.len(), 0.0f32)?; for (dst, value) in output.iter_mut().zip(result) { @@ -475,6 +396,125 @@ impl Plan { } Some(output) } + + /// Packs the pair of channels into the real and imaginary parts of `data`, over the source + /// rows that fall inside the transform tile, each channel normalised by its own scale. + fn pack_channel_pair(&self, pair: &ChannelPair, used: Rect, read: Rect, data: &mut [Number], ctl: &Interrupt) -> Option<()> { + let ChannelPair { src, alpha, scales, channel } = *pair; + let (sw, _) = dimensions(src.rect)?; + for y in used.y0..used.y1 { + if (y - used.y0) % 8 == 0 && ctl.cancelled() { + return None; + } + let source_start = + usize::try_from(y - src.rect.y0).ok()?.checked_mul(sw)?.checked_add(usize::try_from(used.x0 - src.rect.x0).ok()?)?.checked_mul(src.ch)?; + let source_len = usize::try_from(used.x1 - used.x0).ok()?.checked_mul(src.ch)?; + let row = src.data.get(source_start..source_start.checked_add(source_len)?)?; + let start = usize::try_from(y - read.y0).ok()?.checked_mul(self.width)?.checked_add(usize::try_from(used.x0 - read.x0).ok()?)?; + let dst = data.get_mut(start..start.checked_add(source_len / src.ch)?)?; + for (pixel, dst) in row.chunks_exact(src.ch).zip(dst) { + let a = if alpha { *pixel.last()? } else { 1.0 }; + // Normalize each channel separately before packing a pair. + // Otherwise a bright HDR colour's FFT residual could swamp + // a small alpha channel sharing the imaginary component. + let sample = |c: usize| -> f64 { + match (pixel.get(c), scales.get(c)) { + (Some(&value), Some(&scale)) if scale > 0.0 => f64::from(if alpha && c + 1 < src.ch { value * a } else { value }) / scale, + _ => 0.0, + } + }; + *dst = Number::new(sample(channel), sample(channel + 1)); + } + } + Some(()) + } + + /// Writes the filtered pair of channels from `data` into the output pixels, undoing the + /// per-channel normalisation. + fn unpack_channel_pair(&self, pair: &ChannelPair, data: &[Number], result: &mut [f64], ow: usize, norm: f64) -> Option<()> { + let ChannelPair { src, scales, channel, .. } = *pair; + let x0 = usize::try_from(-self.min_x).ok()?; + let y0 = usize::try_from(-self.min_y).ok()?; + for (y, dst) in result.chunks_exact_mut(ow * src.ch).enumerate() { + let start = y.checked_add(y0)?.checked_mul(self.width)?.checked_add(x0)?; + let values = data.get(start..start.checked_add(ow)?)?; + for (pixel, value) in dst.chunks_exact_mut(src.ch).zip(values) { + *pixel.get_mut(channel)? = value.re * norm * scales.get(channel)?; + if let Some(next) = pixel.get_mut(channel + 1) { + *next = value.im * norm * scales.get(channel + 1)?; + } + } + } + Some(()) + } + + /// Straightens the colour of the filtered pixels by their alpha, taking care of the pixels + /// whose alpha is at the cutoff. + fn restore_small_alpha(&self, src: &Image, out: Rect, ow: usize, scales: &[f64; 5], result: &mut [f64], ctl: &Interrupt) -> Option<()> { + // The row kernel accumulates in f32. Recompute very small alpha + // near its cutoff so a different summation order cannot expose colour. + let uncertainty = f64::from(self.distance.abs().ceil()) * f64::from(f32::EPSILON) * scales.get(src.ch - 1)?; + for (i, pixel) in result.chunks_exact_mut(src.ch).enumerate() { + if i % 16 == 0 && ctl.cancelled() { + return None; + } + let a = pixel.last_mut()?; + // Valid alpha is nonnegative. Remove transform roundoff at + // zero to keep fully transparent regions empty. + if a.abs() < 1e-14 * scales.get(src.ch - 1)? { + *a = 0.0; + } + *a = a.clamp(0.0, 1.0); + let a = *a; + // The row kernel's f32 sum can straddle the cutoff at long distances. + // Keep its branch and straight colour exactly for that narrow + // range, rather than amplifying a tiny alpha difference. + if a > 0.0 && (a <= 1.01e-7 + uncertainty || (0.99e-7..=1.01e-7).contains(&(a as f32))) { + let x = out.x0.checked_add(i32::try_from(i % ow).ok()?)?; + let y = out.y0.checked_add(i32::try_from(i / ow).ok()?)?; + let original = sample_row_point(src, x, y, true, &self.taps, ctl)?; + for (dst, value) in pixel.iter_mut().zip(original) { + *dst = f64::from(value); + } + continue; + } + for value in pixel.iter_mut().take(src.ch - 1) { + *value = if a as f32 > 1e-7 { *value / a } else { 0.0 }; + } + } + Some(()) + } +} + +/// One pair of channels (packed as real and imaginary parts) of a filter call. +#[derive(Clone, Copy)] +struct ChannelPair<'a> { + src: &'a Image, + alpha: bool, + scales: &'a [f64; 5], + channel: usize, +} + +/// Per-channel peak magnitude of the (alpha-premultiplied) samples. `None` when a sample is not +/// finite, is too large, or its alpha is outside 0..=1, and when cancelled. +fn channel_scales(src: &Image, alpha: bool, ctl: &Interrupt) -> Option<[f64; 5]> { + let mut scales = [0.0f64; 5]; + for (i, pixel) in src.data.chunks_exact(src.ch).enumerate() { + if i % 4096 == 0 && ctl.cancelled() { + return None; + } + if pixel.iter().any(|value| !value.is_finite() || value.abs() > MAX_SAMPLE) || (alpha && !pixel.last().is_some_and(|value| (0.0..=1.0).contains(value))) + { + return None; + } + let a = if alpha { *pixel.last()? } else { 1.0 }; + for (c, &value) in pixel.iter().enumerate() { + let value = if alpha && c + 1 < src.ch { value * a } else { value }; + let scale = scales.get_mut(c)?; + *scale = scale.max(f64::from(value.abs())); + } + } + Some(scales) } #[cfg(test)] diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rs index 87b8407a95..c781140ac3 100644 --- a/crates/algo/src/inpaint.rs +++ b/crates/algo/src/inpaint.rs @@ -167,29 +167,7 @@ fn complete_cow<'a>( } let r = p.patch_radius.max(1); let psz = 2 * r + 1; - // Pyramid: shrink until the hole is about four patches across (a deeper pyramid decides the - // structure where the texture has averaged out, and fills flat). A thin hole stops while it - // is still about two patches thick: through it, not along it, is what counts (#1366). - let mut levels = vec![Level { w, h, img, px: Cow::Borrowed(px) }]; - let mut boxes = vec![hb0]; - let mut ext = hb0.width().max(hb0.height()); - let thickness = hole_thickness(w, hb0, px); - let thin = thickness.saturating_mul(THIN_RATIO) <= ext; - if thin { - ext = thickness; - } - let mut exts = vec![ext]; - while let Some(l) = levels.last() { - ctl.check()?; - if ext <= if thin { 2 * psz } else { 4 * psz } || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz { - break; - } - let d = downsample(l, ch); - levels.push(d); - boxes.push(boxes[boxes.len() - 1].half()); - ext = ext.div_ceil(2); - exts.push(ext); - } + let Pyramid { mut levels, boxes, exts, thin } = build_pyramid(Level { w, h, img, px: Cow::Borrowed(px) }, ch, hb0, psz, ctl)?; let nlev = levels.len(); // The coarser level's result. let mut prev: Option = None; @@ -209,15 +187,7 @@ fn complete_cow<'a>( return Ok(Err(limg)); } // The level's own pixels to fill (at level 0 the caller's, or a copy made in parallel). - let mut limg = match limg { - Cow::Owned(v) => v, - Cow::Borrowed(b) => { - const CHUNK: usize = 1 << 16; - let mut v = vec![0.0f32; b.len()]; - par::chunks_mut(&mut v, CHUNK, true, |i, d| d.copy_from_slice(&b[i * CHUNK..i * CHUNK + d.len()])); - v - } - }; + let mut limg = into_owned_pixels(limg); let targets = targets_around(lw, r, &lpx, hb, tb); ctl.check()?; // Initialise the hole: at the coarsest level peeled from its edge inwards (or a membrane @@ -225,40 +195,13 @@ fn complete_cow<'a>( // its scaled-up matches. let coarser = prev.take(); match &coarser { - Some(c) => { - let (pw, ph) = (c.w, c.h); - for y in hb.y0..hb.y1 { - for x in hb.x0..hb.x1 { - if lpx[y * lw + x] == Px::Hole { - let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1)); - let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch); - limg[d..d + ch].copy_from_slice(&c.img[s..s + ch]); - } - } - } - } + Some(c) => copy_up_coarser(&mut limg, &lpx, lw, ch, hb, c), // A thin hole, when peeling it would take too long, takes the membrane below: a few // patches thick here, a membrane across it is its surroundings. None if sources.len() > 0 && (!thin || peel_affordable(lw, &lpx, hb, sources.len())) => { onion_peel(lw, lh, ch, ri, &mut limg, &lpx, hb, &sources.all(&valid, lw), ctl)? } - None => { - let mut unknown: Vec = lpx.iter().map(|k| matches!(k, Px::Hole | Px::Void)).collect(); - // Across a thin hole the membrane starts a patch radius out, past the - // anti-aliased fringe or halo that a selection drawn close to the object leaves. - if thin { - let hole: Vec = lpx.iter().map(|k| *k == Px::Hole).collect(); - for (u, d) in unknown.iter_mut().zip(crate::selection::edt(&hole, lw, lh)) { - *u |= d <= r as f32; - } - } - let m = membrane_fill(lw, lh, ch, &limg, &unknown); - for (i, k) in lpx.iter().enumerate() { - if *k == Px::Hole { - limg[i * ch..(i + 1) * ch].copy_from_slice(&m[i * ch..(i + 1) * ch]); - } - } - } + None => fill_hole_with_membrane(&mut limg, &lpx, (lw, lh, ch), r, thin), } if sources.len() == 0 { prev = Some(Coarser { w: lw, h: lh, img: limg, field: Vec::new(), tbox: tb }); @@ -290,36 +233,7 @@ fn complete_cow<'a>( // NNF init: the coarser level's matches scaled up where they land on a valid source, // random otherwise. let mut rng = Rng::new(p.seed ^ (li as u64) << 20); - let tw = tb.width(); - let mut nnf = vec![(0i32, 0i32); tb.area()]; - let mut upsampled = false; - for y in tb.y0..tb.y1 { - if y % 32 == 0 { - ctl.check()?; - } - for x in tb.x0..tb.x1 { - let k = (y - tb.y0) * tw + (x - tb.x0); - if !solver.targets[k] { - continue; - } - let mut cand = None; - if let Some(c) = &coarser - && !c.field.is_empty() - { - let (cx, cy) = ((x / 2).min(c.w - 1), (y / 2).min(c.h - 1)); - let (sx, sy) = c.field_at(cx, cy); - if sx != i32::MIN { - // The same displacement, twice as long. - let c = (x as i32 + 2 * (sx - cx as i32), y as i32 + 2 * (sy - cy as i32)); - if solver.is_valid(c.0, c.1) { - cand = Some(c); - } - } - } - upsampled |= cand.is_some(); - nnf[k] = cand.unwrap_or_else(|| sources.nth((rng.next() % sources.len() as u64) as usize, &solver.valid, lw)); - } - } + let (mut nnf, upsampled) = seed_matches(&solver, coarser.as_ref(), &sources, &mut rng, lw, tb, ctl)?; // The coarser level has given all it had. drop(coarser); let mut cost = vec![f32::INFINITY; tb.area()]; @@ -370,5 +284,138 @@ fn complete_cow<'a>( Ok(prev.map(|c| c.img).ok_or(Cow::Owned(Vec::new()))) } +/// The levels of the completion, finest first, with the hole's bounds and extent at each. +struct Pyramid<'a> { + levels: Vec>, + boxes: Vec, + exts: Vec, + /// The hole is a thin one: its thickness, not its length, decides how deep to go. + thin: bool, +} + +/// Shrinks the image until the hole is about four patches across (a deeper pyramid decides the +/// structure where the texture has averaged out, and fills flat). A thin hole stops while it is +/// still about two patches thick: through it, not along it, is what counts (#1366). +fn build_pyramid<'a>( + first: Level<'a>, + ch: usize, + hb0: common::Bounds, + psz: usize, + ctl: &photocraft_raster::Interrupt, +) -> Result, photocraft_raster::Cancelled> { + let thickness = hole_thickness(first.w, hb0, &first.px); + let mut levels = vec![first]; + let mut boxes = vec![hb0]; + let mut ext = hb0.width().max(hb0.height()); + let thin = thickness.saturating_mul(THIN_RATIO) <= ext; + if thin { + ext = thickness; + } + let mut exts = vec![ext]; + while let Some(l) = levels.last() { + ctl.check()?; + if ext <= if thin { 2 * psz } else { 4 * psz } || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz { + break; + } + let d = downsample(l, ch); + levels.push(d); + boxes.push(boxes[boxes.len() - 1].half()); + ext = ext.div_ceil(2); + exts.push(ext); + } + Ok(Pyramid { levels, boxes, exts, thin }) +} + +/// The level's own pixels to fill: the caller's, or a copy made in parallel. +fn into_owned_pixels(img: Cow<'_, [f32]>) -> Vec { + match img { + Cow::Owned(v) => v, + Cow::Borrowed(b) => { + const CHUNK: usize = 1 << 16; + let mut v = vec![0.0f32; b.len()]; + par::chunks_mut(&mut v, CHUNK, true, |i, d| d.copy_from_slice(&b[i * CHUNK..i * CHUNK + d.len()])); + v + } + } +} + +/// Starts the hole from the coarser level's pixels, scaled up. +fn copy_up_coarser(img: &mut [f32], px: &[Px], w: usize, ch: usize, hb: common::Bounds, c: &Coarser) { + let (pw, ph) = (c.w, c.h); + for y in hb.y0..hb.y1 { + for x in hb.x0..hb.x1 { + if px[y * w + x] == Px::Hole { + let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1)); + let (d, s) = ((y * w + x) * ch, (sy * pw + sx) * ch); + img[d..d + ch].copy_from_slice(&c.img[s..s + ch]); + } + } + } +} + +/// Starts the hole as a membrane over its surroundings, for where nothing can be copied. `dims` +/// is the level's width, height and channel count. +fn fill_hole_with_membrane(img: &mut [f32], px: &[Px], dims: (usize, usize, usize), r: usize, thin: bool) { + let (w, h, ch) = dims; + let mut unknown: Vec = px.iter().map(|k| matches!(k, Px::Hole | Px::Void)).collect(); + // Across a thin hole the membrane starts a patch radius out, past the + // anti-aliased fringe or halo that a selection drawn close to the object leaves. + if thin { + let hole: Vec = px.iter().map(|k| *k == Px::Hole).collect(); + for (u, d) in unknown.iter_mut().zip(crate::selection::edt(&hole, w, h)) { + *u |= d <= r as f32; + } + } + let m = membrane_fill(w, h, ch, img, &unknown); + for (i, k) in px.iter().enumerate() { + if *k == Px::Hole { + img[i * ch..(i + 1) * ch].copy_from_slice(&m[i * ch..(i + 1) * ch]); + } + } +} + +/// The coarser level's match for `(x, y)`, scaled up, where it lands on a valid source. +fn upscaled_match(solver: &Solver, c: &Coarser, x: usize, y: usize) -> Option<(i32, i32)> { + let (cx, cy) = ((x / 2).min(c.w - 1), (y / 2).min(c.h - 1)); + let (sx, sy) = c.field_at(cx, cy); + if sx == i32::MIN { + return None; + } + // The same displacement, twice as long. + let m = (x as i32 + 2 * (sx - cx as i32), y as i32 + 2 * (sy - cy as i32)); + solver.is_valid(m.0, m.1).then_some(m) +} + +/// NNF init: the coarser level's matches scaled up where they land on a valid source, random +/// otherwise. Also says whether any came from the coarser level. +fn seed_matches( + solver: &Solver, + coarser: Option<&Coarser>, + sources: &Sources, + rng: &mut Rng, + lw: usize, + tb: common::Bounds, + ctl: &photocraft_raster::Interrupt, +) -> Result<(Vec<(i32, i32)>, bool), photocraft_raster::Cancelled> { + let tw = tb.width(); + let mut nnf = vec![(0i32, 0i32); tb.area()]; + let mut upsampled = false; + for y in tb.y0..tb.y1 { + if y % 32 == 0 { + ctl.check()?; + } + for x in tb.x0..tb.x1 { + let k = (y - tb.y0) * tw + (x - tb.x0); + if !solver.targets[k] { + continue; + } + let cand = coarser.filter(|c| !c.field.is_empty()).and_then(|c| upscaled_match(solver, c, x, y)); + upsampled |= cand.is_some(); + nnf[k] = cand.unwrap_or_else(|| sources.nth((rng.next() % sources.len() as u64) as usize, &solver.valid, lw)); + } + } + Ok((nnf, upsampled)) +} + #[cfg(test)] mod tests; diff --git a/crates/algo/src/inpaint/common.rs b/crates/algo/src/inpaint/common.rs index bbbcc8df26..16989a6079 100644 --- a/crates/algo/src/inpaint/common.rs +++ b/crates/algo/src/inpaint/common.rs @@ -1,4 +1,4 @@ -use super::*; +use super::Cow; /// Below this many cells a pass runs on the calling thread (thread hand-off costs more than it /// saves). Every pass gives the same result either way. diff --git a/crates/algo/src/inpaint/solver.rs b/crates/algo/src/inpaint/solver.rs index b5cc82915d..67e0e2645e 100644 --- a/crates/algo/src/inpaint/solver.rs +++ b/crates/algo/src/inpaint/solver.rs @@ -1,5 +1,5 @@ use super::common::{Adapt, Bounds, PAR_MIN_PATCHES, Px, Rng}; -use super::*; +use super::par; /// Most channels whose moments the colour adaptation fits (the rest are copied as they are). const MOM_CH: usize = 8; diff --git a/crates/algo/src/inpaint/sources.rs b/crates/algo/src/inpaint/sources.rs index a3f390cfc3..fcc255e49a 100644 --- a/crates/algo/src/inpaint/sources.rs +++ b/crates/algo/src/inpaint/sources.rs @@ -1,5 +1,5 @@ use super::common::{Bounds, Level, PAR_MIN, Px}; -use super::*; +use super::{Cow, par}; /// Half-size level: a cell is a hole if any of its pixels is; else it averages its non-void /// pixels, and may be copied from only if all of them may. diff --git a/crates/algo/src/inpaint/synthesis.rs b/crates/algo/src/inpaint/synthesis.rs index 0c3bf9c375..cd0452ab4c 100644 --- a/crates/algo/src/inpaint/synthesis.rs +++ b/crates/algo/src/inpaint/synthesis.rs @@ -1,7 +1,7 @@ use super::common::{Bounds, Px, Rng}; use super::solver::{Best, LANES, known_sse, known_sse_any, known_sse_lanes, least_sum}; use super::sources::{hole_bbox, integral, window_count}; -use super::*; +use super::{HoleIntegral, membrane_fill, par}; /// Fill the hole from its edge inwards, one ring at a time: each pixel takes the centre of the /// source patch that best matches what is already known around it (the first in `sources` of diff --git a/crates/algo/src/panorama/blend.rs b/crates/algo/src/panorama/blend.rs index 1aaa821c14..034e5ed96d 100644 --- a/crates/algo/src/panorama/blend.rs +++ b/crates/algo/src/panorama/blend.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Normal, Placement, par_map, par_rows}; // ---------- photometric ---------- diff --git a/crates/algo/src/pixelate/cells.rs b/crates/algo/src/pixelate/cells.rs index ebf326fbde..0d88fbc77e 100644 --- a/crates/algo/src/pixelate/cells.rs +++ b/crates/algo/src/pixelate/cells.rs @@ -1,6 +1,6 @@ //! Reuse the jittered lattice in cell space. Raster work stays in the original //! row/candidate order, including f32 ties and boundary-cell average additions. -use super::*; +use super::{Ctx, Image, MAXC, Rect, cell_point, hash01, native, ncol, subtractive}; #[derive(Clone, Copy)] struct Site { @@ -348,76 +348,101 @@ fn pointillize_grid(src: &Image, out: Rect, ctx: &Ctx, cell: f32, background: [f let mut owners = vec![u32::MAX; width]; for (row, pixels) in result.chunks_exact_mut(stride).enumerate() { let y = out.y0.checked_add(i32::try_from(row).ok()?)?; - let fy = y as f32 + 0.5; let cy = key(y, origin.1, cell); depths.fill(-0.5); owners.fill(u32::MAX); if cell >= 32.0 && out.width() <= 2048 { - for &(cx, x0, x1) in &base_runs { - let ids = grid.neighbours(cx, cy)?; - let start = usize::try_from(x0.checked_sub(out.x0)?).ok()?; - let end = usize::try_from(x1.checked_sub(out.x0)?).ok()?; - certified_span::(grid, &ids, x0, y, owners.get_mut(start..end)?, depths.get_mut(start..end)?)?; - } + certified_row(grid, &base_runs, out, cy, y, &mut owners, &mut depths)?; } else { - for gy in cy.checked_sub(1)?..=cy.checked_add(1)? { - let row = usize::try_from(gy.checked_sub(grid.y0)?).ok()?.checked_mul(grid.width)?; - // Global gy/gx order is the original dy/dx tie order at every pixel. - for (column, &(x0, x1)) in columns.iter().enumerate() { - if x0 >= x1 { - continue; - } - let i = row.checked_add(column)?; - let site = grid.sites.get(i)?; - let dy2 = (site.point.1 - fy).powi(2); - let reach = f64::from(site.radius) + 1.5; - let square = reach * reach - f64::from(dy2); - if square < 0.0 { - continue; - } - // The extra pixel covers subtraction/square/sqrt rounding for - // the bounded coordinates/radii above. The exact old depth - // comparison still decides every candidate that survives. - let reach_x = square.max(0.0).sqrt() + 1.0; - let lo = ((f64::from(site.point.0) - 0.5 - reach_x).floor() as i32).max(x0); - let hi = ((f64::from(site.point.0) - 0.5 + reach_x).ceil() as i32).min(x1); - if lo >= hi { - continue; - } - let start = usize::try_from(lo.checked_sub(out.x0)?).ok()?; - let end = usize::try_from(hi.checked_sub(out.x0)?).ok()?; - for (offset, (depth, owner)) in depths.get_mut(start..end)?.iter_mut().zip(owners.get_mut(start..end)?).enumerate() { - let fx = (lo + offset as i32) as f32 + 0.5; - let d = ((site.point.0 - fx).powi(2) + dy2).sqrt(); - let candidate = site.radius - d; - if candidate > *depth { - *depth = candidate; - *owner = i as u32; - } - } - } - } - } - for ((pixel, &depth), &owner) in pixels.chunks_exact_mut(n).zip(&depths).zip(&owners) { - let a_orig = if ctx.alpha { *pixel.get(n - 1)? } else { 1.0 }; - let mut canvas = bg; - if ctx.alpha { - *canvas.get_mut(n - 1)? = a_orig.max(bg.get(n - 1)?.min(1.0)); - } - if owner != u32::MAX { - let i = owner as usize; - let k = (depth + 0.5).clamp(0.0, 1.0); - let dot = grid.sites.get(i)?; - for (c, value) in canvas.iter_mut().enumerate().take(n) { - *value += (*dot.color.get(c)? - *value) * k; - } - } - pixel.copy_from_slice(canvas.get(..n)?); + scan_row(grid, &columns, out, cy, y, &mut owners, &mut depths)?; } + composite_row(pixels, &depths, &owners, grid, ctx, bg)?; } Some(result) } +/// Resolve one output row's dot owners through the certified run spans. +fn certified_row(grid: &Grid, base_runs: &[(i32, i32, i32)], out: Rect, cy: i32, y: i32, owners: &mut [u32], depths: &mut [f32]) -> Option<()> { + for &(cx, x0, x1) in base_runs { + let ids = grid.neighbours(cx, cy)?; + let start = usize::try_from(x0.checked_sub(out.x0)?).ok()?; + let end = usize::try_from(x1.checked_sub(out.x0)?).ok()?; + certified_span::(grid, &ids, x0, y, owners.get_mut(start..end)?, depths.get_mut(start..end)?)?; + } + Some(()) +} + +/// Resolve one output row's dot owners by scanning the 3x3 neighbouring cells. +fn scan_row(grid: &Grid, columns: &[(i32, i32)], out: Rect, cy: i32, y: i32, owners: &mut [u32], depths: &mut [f32]) -> Option<()> { + let fy = y as f32 + 0.5; + for gy in cy.checked_sub(1)?..=cy.checked_add(1)? { + let row = usize::try_from(gy.checked_sub(grid.y0)?).ok()?.checked_mul(grid.width)?; + // Global gy/gx order is the original dy/dx tie order at every pixel. + for (column, &span) in columns.iter().enumerate() { + if span.0 >= span.1 { + continue; + } + let i = row.checked_add(column)?; + scan_site(grid, i, fy, span, out, owners, depths)?; + } + } + Some(()) +} + +/// Let one site claim the pixels of the current row it reaches within `[x0, x1)`. +fn scan_site(grid: &Grid, i: usize, fy: f32, (x0, x1): (i32, i32), out: Rect, owners: &mut [u32], depths: &mut [f32]) -> Option<()> { + let site = grid.sites.get(i)?; + let dy2 = (site.point.1 - fy).powi(2); + let reach = f64::from(site.radius) + 1.5; + let square = reach * reach - f64::from(dy2); + if square < 0.0 { + return Some(()); + } + // The extra pixel covers subtraction/square/sqrt rounding for + // the bounded coordinates/radii above. The exact old depth + // comparison still decides every candidate that survives. + let reach_x = square.max(0.0).sqrt() + 1.0; + let lo = ((f64::from(site.point.0) - 0.5 - reach_x).floor() as i32).max(x0); + let hi = ((f64::from(site.point.0) - 0.5 + reach_x).ceil() as i32).min(x1); + if lo >= hi { + return Some(()); + } + let start = usize::try_from(lo.checked_sub(out.x0)?).ok()?; + let end = usize::try_from(hi.checked_sub(out.x0)?).ok()?; + for (offset, (depth, owner)) in depths.get_mut(start..end)?.iter_mut().zip(owners.get_mut(start..end)?).enumerate() { + let fx = (lo + offset as i32) as f32 + 0.5; + let d = ((site.point.0 - fx).powi(2) + dy2).sqrt(); + let candidate = site.radius - d; + if candidate > *depth { + *depth = candidate; + *owner = i as u32; + } + } + Some(()) +} + +/// Blend each pixel of a row with the background and its owning dot colour. +fn composite_row(pixels: &mut [f32], depths: &[f32], owners: &[u32], grid: &Grid, ctx: &Ctx, bg: [f32; 8]) -> Option<()> { + let n = pixels.len() / depths.len().max(1); + for ((pixel, &depth), &owner) in pixels.chunks_exact_mut(n).zip(depths).zip(owners) { + let a_orig = if ctx.alpha { *pixel.get(n - 1)? } else { 1.0 }; + let mut canvas = bg; + if ctx.alpha { + *canvas.get_mut(n - 1)? = a_orig.max(bg.get(n - 1)?.min(1.0)); + } + if owner != u32::MAX { + let i = owner as usize; + let k = (depth + 0.5).clamp(0.0, 1.0); + let dot = grid.sites.get(i)?; + for (c, value) in canvas.iter_mut().enumerate().take(n) { + *value += (*dot.color.get(c)? - *value) * k; + } + } + pixel.copy_from_slice(canvas.get(..n)?); + } + Some(()) +} + /// The filters sample cell centres, not a dense neighbourhood. On ordinary /// tiles read those sparse samples directly; keep only the original output /// pixels for alpha and selection mixing. Crystallize boundary tiles still diff --git a/crates/algo/src/render2.rs b/crates/algo/src/render2.rs index 19a4b8218d..cf1585115c 100644 --- a/crates/algo/src/render2.rs +++ b/crates/algo/src/render2.rs @@ -1236,256 +1236,320 @@ fn star(out: &mut Vec, c: (f32, f32), r: f32, points: usize, col: [f32; 4] } } -/// Builds picture-frame primitives inside `canvas`. -pub fn picture_frame(spec: &FrameSpec, canvas: Rect) -> Vec { - let mut out = Vec::new(); - let short = (canvas.width().min(canvas.height()) as f32).max(8.0); - let margin = short * spec.margin.clamp(0.0, 30.0) / 100.0; - let unit = short * (0.008 + spec.size.clamp(1.0, 100.0) / 100.0 * 0.05); - let thick = (unit * 0.04 + short * 0.00012 * spec.thickness.clamp(1.0, 100.0)).max(0.6); - let spacing = unit * (4.0 - 3.2 * spec.arrangement.clamp(1.0, 100.0) / 100.0); - let inset = margin + unit; - let b = Border { - x0: canvas.x0 as f32 + inset, - y0: canvas.y0 as f32 + inset, - w: (canvas.width() as f32 - 2.0 * inset).max(1.0), - h: (canvas.height() as f32 - 2.0 * inset).max(1.0), - }; - let total = b.len(); - let count = (total / spacing).round().max(4.0) as usize; - let step = total / count as f32; - let mut rng = Rng::new(spec.seed, 0xF8A3E + spec.frame as u64); - let (vine, fl, lf) = (spec.vine_color, spec.flower_color, spec.leaf_color); - let style = FRAME_STYLES[(spec.frame.clamp(1, FRAME_STYLES.len() as u32) - 1) as usize]; - let lines = spec.lines.clamp(1, 5) as usize; - let white = [1.0, 1.0, 1.0, 1.0]; - let yellow = [0.98, 0.82, 0.2, 1.0]; - // A wavy vine along the border. - let vine_path = |out: &mut Vec, amp: f32, wl: f32, col: [f32; 4], r: f32| { - let n = (total / 3.0).ceil().max(8.0) as usize; +/// Resolved geometry and palette shared by every picture-frame style. +struct FrameLayout { + b: Border, + unit: f32, + thick: f32, + spacing: f32, + total: f32, + count: usize, + step: f32, + lines: usize, + vine: [f32; 4], + fl: [f32; 4], + lf: [f32; 4], + style: &'static str, +} + +const FRAME_WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; +const FRAME_YELLOW: [f32; 4] = [0.98, 0.82, 0.2, 1.0]; + +fn wave_off(s: f32, amp: f32, wl: f32) -> f32 { + amp * (s / wl * std::f32::consts::TAU).sin() +} + +impl FrameLayout { + fn new(spec: &FrameSpec, canvas: Rect) -> Self { + let short = (canvas.width().min(canvas.height()) as f32).max(8.0); + let margin = short * spec.margin.clamp(0.0, 30.0) / 100.0; + let unit = short * (0.008 + spec.size.clamp(1.0, 100.0) / 100.0 * 0.05); + let thick = (unit * 0.04 + short * 0.00012 * spec.thickness.clamp(1.0, 100.0)).max(0.6); + let spacing = unit * (4.0 - 3.2 * spec.arrangement.clamp(1.0, 100.0) / 100.0); + let inset = margin + unit; + let b = Border { + x0: canvas.x0 as f32 + inset, + y0: canvas.y0 as f32 + inset, + w: (canvas.width() as f32 - 2.0 * inset).max(1.0), + h: (canvas.height() as f32 - 2.0 * inset).max(1.0), + }; + let total = b.len(); + let count = (total / spacing).round().max(4.0) as usize; + Self { + b, + unit, + thick, + spacing, + total, + count, + step: total / count as f32, + lines: spec.lines.clamp(1, 5) as usize, + vine: spec.vine_color, + fl: spec.flower_color, + lf: spec.leaf_color, + style: FRAME_STYLES[(spec.frame.clamp(1, FRAME_STYLES.len() as u32) - 1) as usize], + } + } + + /// A wavy vine along the border. + fn vine_path(&self, out: &mut Vec, amp: f32, wl: f32, col: [f32; 4], r: f32) { + let n = (self.total / 3.0).ceil().max(8.0) as usize; let mut prev: Option<(f32, f32)> = None; for k in 0..=n { - let s = k as f32 / n as f32 * total; - let (p, _, nn) = b.at(s); - let o = amp * (s / wl * std::f32::consts::TAU).sin(); + let s = k as f32 / n as f32 * self.total; + let (p, _, nn) = self.b.at(s); + let o = wave_off(s, amp, wl); let q = (p.0 + nn.0 * o, p.1 + nn.1 * o); if let Some(pp) = prev { out.push(Prim::capsule(pp, q, r, r, col, col)); } prev = Some(q); } - }; - let wave_off = |s: f32, amp: f32, wl: f32| amp * (s / wl * std::f32::consts::TAU).sin(); - match style { - "vineWithFlowers" | "vineWithLeaves" | "ivy" | "roses" | "daisies" | "berries" => { - let amp = unit * 0.5; - let wl = step * 2.0; - vine_path(&mut out, amp, wl, vine, thick); - for k in 0..count { - let s = k as f32 * step + step * 0.5; - let (p, t, nn) = b.at(s); - let o = wave_off(s, amp, wl); - let q = (p.0 + nn.0 * o, p.1 + nn.1 * o); - let side = if k % 2 == 0 { 1.0 } else { -1.0 }; - let ta = t.1.atan2(t.0); - let la = ta + side * 0.9 + rng.sym() * 0.3; - let ll = unit * rng.range(0.9, 1.2); - match style { - "vineWithFlowers" => { - leaf(&mut out, q, la, ll, lf); - if k % 2 == 0 { - let c = (q.0 + nn.0 * unit * 0.7 * side, q.1 + nn.1 * unit * 0.7 * side); - flower(&mut out, c, unit * 0.65, 5, fl, yellow, rng.f() * 6.3); - } - } - "vineWithLeaves" => { - leaf(&mut out, q, la, ll, lf); - leaf(&mut out, q, ta - side * 0.9, ll * 0.8, lf); - } - "ivy" => { - for j in 0..3 { - let a = la + (j as f32 - 1.0) * 0.7; - leaf(&mut out, q, a, ll * 0.75, shade([lf[0], lf[1], lf[2]], 0.75 + 0.15 * j as f32)); - } - } - "roses" => { - leaf(&mut out, q, la, ll, lf); - if k % 3 == 0 { - let r = unit * 0.7; - for (j, f) in [1.0f32, 0.75, 0.5, 0.28].iter().enumerate() { - let c = shade([fl[0], fl[1], fl[2]], 0.75 + 0.1 * j as f32); - out.push(Prim::ellipse(q, r * f, r * f * 0.9, rng.f() * 3.0, c, shade([fl[0], fl[1], fl[2]], 0.55))); - } - } - } - "daisies" => { - leaf(&mut out, q, la, ll * 0.8, lf); - if k % 2 == 1 { - flower(&mut out, q, unit * 0.6, 12, white, yellow, rng.f()); - } - } - _ => { - leaf(&mut out, q, la, ll, lf); - for _ in 0..3 { - let c = (q.0 + rng.sym() * unit * 0.4, q.1 + rng.sym() * unit * 0.4); - out.push(Prim::ellipse(c, unit * 0.2, unit * 0.2, 0.0, shade([fl[0], fl[1], fl[2]], 1.2), shade([fl[0], fl[1], fl[2]], 0.6))); - } - } - } - } - } - "bamboo" => { - for edge in 0..4 { - let (s0, l) = match edge { - 0 => (0.0, b.w), - 1 => (b.w, b.h), - 2 => (b.w + b.h, b.w), - _ => (2.0 * b.w + b.h, b.h), - }; - let (a, _, _) = b.at(s0 + 0.01); - let (z, _, _) = b.at(s0 + l - 0.01); - let joints = (l / (spacing * 2.0)).round().max(1.0) as usize; - for j in 0..joints { - let f0 = j as f32 / joints as f32; - let f1 = (j + 1) as f32 / joints as f32; - let p0 = (a.0 + (z.0 - a.0) * f0, a.1 + (z.1 - a.1) * f0); - let p1 = (a.0 + (z.0 - a.0) * f1, a.1 + (z.1 - a.1) * f1); - out.push(Prim::capsule(p0, p1, unit * 0.35, unit * 0.35, vine, shade([vine[0], vine[1], vine[2]], 0.8))); - out.push(Prim::disc(p1, unit * 0.4, shade([vine[0], vine[1], vine[2]], 0.7))); - } - // A few leaves per edge. - for _ in 0..(joints / 2).max(1) { - let f = rng.f(); - let p = (a.0 + (z.0 - a.0) * f, a.1 + (z.1 - a.1) * f); - leaf(&mut out, p, rng.f() * 6.3, unit * 1.4, lf); - } - } - } - "waves" | "zigzag" | "doubleLine" | "rope" => { - for li in 0..lines { - let off = (li as f32 - (lines - 1) as f32 / 2.0) * thick * 4.0; - let n = (total / 2.0).ceil().max(8.0) as usize; - let mut prev: Option<(f32, f32)> = None; - for k in 0..=n { - let s = k as f32 / n as f32 * total; - let (p, _, nn) = b.at(s); - let o = off - + match style { - "waves" => wave_off(s + li as f32 * step * 0.25, unit * 0.4, step), - "zigzag" => { - let ph = (s / step).fract(); - unit * 0.4 * (4.0 * (ph - 0.5).abs() - 1.0) - } - _ => 0.0, - }; - let q = (p.0 + nn.0 * o, p.1 + nn.1 * o); - if style == "rope" { - if k % 2 == 0 { - let (_, t, _) = b.at(s); - out.push(Prim::ellipse( - q, - unit * 0.45, - unit * 0.2, - t.1.atan2(t.0) + 0.7, - shade([vine[0], vine[1], vine[2]], 1.1), - shade([vine[0], vine[1], vine[2]], 0.65), - )); - } - } else if let Some(pp) = prev { - out.push(Prim::capsule(pp, q, thick, thick, vine, vine)); - } - prev = Some(q); - } - if style == "doubleLine" { - // A second rule inside each line and corner squares. - let inner = Border { - x0: b.x0 + unit * 0.6 + off, - y0: b.y0 + unit * 0.6 + off, - w: b.w - 2.0 * (unit * 0.6 + off), - h: b.h - 2.0 * (unit * 0.6 + off), - }; - for e in 0..4 { - let (p, _, _) = inner.at([0.0, inner.w, inner.w + inner.h, 2.0 * inner.w + inner.h][e]); - let (q, _, _) = inner.at([inner.w, inner.w + inner.h, 2.0 * inner.w + inner.h, inner.len() - 0.001][e]); - out.push(Prim::capsule(p, q, thick * 0.6, thick * 0.6, vine, vine)); - } - } - } - if style == "doubleLine" { - for e in 0..4 { - let (p, _, _) = b.at([0.0, b.w, b.w + b.h, 2.0 * b.w + b.h][e]); - out.push(Prim::ellipse(p, unit * 0.45, unit * 0.45, std::f32::consts::FRAC_PI_4, fl, fl)); - } - } - } - "dots" | "scallops" | "snowflakes" | "stars" | "hearts" => { - for k in 0..count { - let s = k as f32 * step; - let (p, t, nn) = b.at(s); - let ta = t.1.atan2(t.0); - match style { - "dots" => { - let r = unit * if k % 2 == 0 { 0.4 } else { 0.22 }; - out.push(Prim::ellipse(p, r, r, 0.0, shade([fl[0], fl[1], fl[2]], 1.15), shade([fl[0], fl[1], fl[2]], 0.75))); - } - "scallops" => { - let (c0, _, _) = b.at(s - step * 0.5); - let mid = ((c0.0 + p.0) / 2.0, (c0.1 + p.1) / 2.0); - let n = 8; - for j in 0..n { - let a0 = std::f32::consts::PI * j as f32 / n as f32; - let a1 = std::f32::consts::PI * (j + 1) as f32 / n as f32; - let r = step * 0.5; - let pt = |a: f32| (mid.0 - t.0 * r * a.cos() - nn.0 * r * a.sin(), mid.1 - t.1 * r * a.cos() - nn.1 * r * a.sin()); - out.push(Prim::capsule(pt(a0), pt(a1), thick, thick, vine, vine)); - } - } - "snowflakes" => { - let r = unit * 0.6; - let c = [0.85, 0.92, 1.0, 1.0]; - for j in 0..6 { - let a = ta + j as f32 * std::f32::consts::FRAC_PI_3; - let e = (p.0 + a.cos() * r, p.1 + a.sin() * r); - out.push(Prim::capsule(p, e, (thick * 0.6).max(0.6), (thick * 0.4).max(0.5), c, c)); - let m = (p.0 + a.cos() * r * 0.6, p.1 + a.sin() * r * 0.6); - for sd in [-0.7f32, 0.7] { - let b2 = (m.0 + (a + sd).cos() * r * 0.3, m.1 + (a + sd).sin() * r * 0.3); - out.push(Prim::capsule(m, b2, (thick * 0.4).max(0.5), 0.4, c, c)); - } - } - } - "stars" => star(&mut out, p, unit * 0.55, 5, if k % 2 == 0 { yellow } else { fl }, ta - std::f32::consts::FRAC_PI_2), - _ => { - // Heart: two lobes and a point towards the inside. - let r = unit * 0.3; - let (tx, ty) = t; - let l = (p.0 - tx * r * 0.8 - nn.0 * r * 0.3, p.1 - ty * r * 0.8 - nn.1 * r * 0.3); - let rr = (p.0 + tx * r * 0.8 - nn.0 * r * 0.3, p.1 + ty * r * 0.8 - nn.1 * r * 0.3); - let tip = (p.0 + nn.0 * r * 1.6, p.1 + nn.1 * r * 1.6); - out.push(Prim::capsule(l, tip, r, 0.6, fl, fl)); - out.push(Prim::capsule(rr, tip, r, 0.6, fl, fl)); - } - } - } - } - _ => {} } - // Fade: lower the opacity of ornaments that reach further inside. - let fade = spec.fade.clamp(0.0, 100.0) / 100.0; - if fade > 0.0 { + + /// Vine styles: a wavy stem with a leaf cluster or bloom at each step. + fn vine_styles(&self, out: &mut Vec, rng: &mut Rng) { + let (unit, step, fl, lf) = (self.unit, self.step, self.fl, self.lf); + let amp = unit * 0.5; + let wl = step * 2.0; + self.vine_path(out, amp, wl, self.vine, self.thick); + for k in 0..self.count { + let s = k as f32 * step + step * 0.5; + let (p, t, nn) = self.b.at(s); + let o = wave_off(s, amp, wl); + let q = (p.0 + nn.0 * o, p.1 + nn.1 * o); + let side = if k % 2 == 0 { 1.0 } else { -1.0 }; + let ta = t.1.atan2(t.0); + let la = ta + side * 0.9 + rng.sym() * 0.3; + let ll = unit * rng.range(0.9, 1.2); + match self.style { + "vineWithFlowers" => { + leaf(out, q, la, ll, lf); + if k % 2 == 0 { + let c = (q.0 + nn.0 * unit * 0.7 * side, q.1 + nn.1 * unit * 0.7 * side); + flower(out, c, unit * 0.65, 5, fl, FRAME_YELLOW, rng.f() * 6.3); + } + } + "vineWithLeaves" => { + leaf(out, q, la, ll, lf); + leaf(out, q, ta - side * 0.9, ll * 0.8, lf); + } + "ivy" => { + for j in 0..3 { + let a = la + (j as f32 - 1.0) * 0.7; + leaf(out, q, a, ll * 0.75, shade([lf[0], lf[1], lf[2]], 0.75 + 0.15 * j as f32)); + } + } + "roses" => { + leaf(out, q, la, ll, lf); + if k % 3 == 0 { + let r = unit * 0.7; + for (j, f) in [1.0f32, 0.75, 0.5, 0.28].iter().enumerate() { + let c = shade([fl[0], fl[1], fl[2]], 0.75 + 0.1 * j as f32); + out.push(Prim::ellipse(q, r * f, r * f * 0.9, rng.f() * 3.0, c, shade([fl[0], fl[1], fl[2]], 0.55))); + } + } + } + "daisies" => { + leaf(out, q, la, ll * 0.8, lf); + if k % 2 == 1 { + flower(out, q, unit * 0.6, 12, FRAME_WHITE, FRAME_YELLOW, rng.f()); + } + } + _ => { + leaf(out, q, la, ll, lf); + for _ in 0..3 { + let c = (q.0 + rng.sym() * unit * 0.4, q.1 + rng.sym() * unit * 0.4); + out.push(Prim::ellipse(c, unit * 0.2, unit * 0.2, 0.0, shade([fl[0], fl[1], fl[2]], 1.2), shade([fl[0], fl[1], fl[2]], 0.6))); + } + } + } + } + } + + /// Bamboo: jointed canes along each edge with a few leaves. + fn bamboo(&self, out: &mut Vec, rng: &mut Rng) { + let (b, unit, vine) = (&self.b, self.unit, self.vine); + for edge in 0..4 { + let (s0, l) = match edge { + 0 => (0.0, b.w), + 1 => (b.w, b.h), + 2 => (b.w + b.h, b.w), + _ => (2.0 * b.w + b.h, b.h), + }; + let (a, _, _) = b.at(s0 + 0.01); + let (z, _, _) = b.at(s0 + l - 0.01); + let joints = (l / (self.spacing * 2.0)).round().max(1.0) as usize; + for j in 0..joints { + let f0 = j as f32 / joints as f32; + let f1 = (j + 1) as f32 / joints as f32; + let p0 = (a.0 + (z.0 - a.0) * f0, a.1 + (z.1 - a.1) * f0); + let p1 = (a.0 + (z.0 - a.0) * f1, a.1 + (z.1 - a.1) * f1); + out.push(Prim::capsule(p0, p1, unit * 0.35, unit * 0.35, vine, shade([vine[0], vine[1], vine[2]], 0.8))); + out.push(Prim::disc(p1, unit * 0.4, shade([vine[0], vine[1], vine[2]], 0.7))); + } + // A few leaves per edge. + for _ in 0..(joints / 2).max(1) { + let f = rng.f(); + let p = (a.0 + (z.0 - a.0) * f, a.1 + (z.1 - a.1) * f); + leaf(out, p, rng.f() * 6.3, unit * 1.4, self.lf); + } + } + } + + /// Continuous rule styles: waves, zigzag, double line and rope. + fn rule_styles(&self, out: &mut Vec) { + let (b, unit, thick, step, vine) = (&self.b, self.unit, self.thick, self.step, self.vine); + for li in 0..self.lines { + let off = (li as f32 - (self.lines - 1) as f32 / 2.0) * thick * 4.0; + let n = (self.total / 2.0).ceil().max(8.0) as usize; + let mut prev: Option<(f32, f32)> = None; + for k in 0..=n { + let s = k as f32 / n as f32 * self.total; + let (p, _, nn) = b.at(s); + let o = off + + match self.style { + "waves" => wave_off(s + li as f32 * step * 0.25, unit * 0.4, step), + "zigzag" => { + let ph = (s / step).fract(); + unit * 0.4 * (4.0 * (ph - 0.5).abs() - 1.0) + } + _ => 0.0, + }; + let q = (p.0 + nn.0 * o, p.1 + nn.1 * o); + if self.style == "rope" { + if k % 2 == 0 { + let (_, t, _) = b.at(s); + out.push(Prim::ellipse( + q, + unit * 0.45, + unit * 0.2, + t.1.atan2(t.0) + 0.7, + shade([vine[0], vine[1], vine[2]], 1.1), + shade([vine[0], vine[1], vine[2]], 0.65), + )); + } + } else if let Some(pp) = prev { + out.push(Prim::capsule(pp, q, thick, thick, vine, vine)); + } + prev = Some(q); + } + if self.style == "doubleLine" { + self.inner_rule(out, off); + } + } + if self.style == "doubleLine" { + for e in 0..4 { + let (p, _, _) = b.at([0.0, b.w, b.w + b.h, 2.0 * b.w + b.h][e]); + out.push(Prim::ellipse(p, unit * 0.45, unit * 0.45, std::f32::consts::FRAC_PI_4, self.fl, self.fl)); + } + } + } + + /// A second rule inside each double line. + fn inner_rule(&self, out: &mut Vec, off: f32) { + let (b, unit) = (&self.b, self.unit); + let inner = Border { x0: b.x0 + unit * 0.6 + off, y0: b.y0 + unit * 0.6 + off, w: b.w - 2.0 * (unit * 0.6 + off), h: b.h - 2.0 * (unit * 0.6 + off) }; + for e in 0..4 { + let (p, _, _) = inner.at([0.0, inner.w, inner.w + inner.h, 2.0 * inner.w + inner.h][e]); + let (q, _, _) = inner.at([inner.w, inner.w + inner.h, 2.0 * inner.w + inner.h, inner.len() - 0.001][e]); + out.push(Prim::capsule(p, q, self.thick * 0.6, self.thick * 0.6, self.vine, self.vine)); + } + } + + /// Evenly spaced motif styles: dots, scallops, snowflakes, stars and hearts. + fn motif_styles(&self, out: &mut Vec) { + let (unit, fl) = (self.unit, self.fl); + for k in 0..self.count { + let s = k as f32 * self.step; + let (p, t, nn) = self.b.at(s); + let ta = t.1.atan2(t.0); + match self.style { + "dots" => { + let r = unit * if k % 2 == 0 { 0.4 } else { 0.22 }; + out.push(Prim::ellipse(p, r, r, 0.0, shade([fl[0], fl[1], fl[2]], 1.15), shade([fl[0], fl[1], fl[2]], 0.75))); + } + "scallops" => self.scallop(out, s, p, t, nn), + "snowflakes" => self.snowflake(out, p, ta), + "stars" => star(out, p, unit * 0.55, 5, if k % 2 == 0 { FRAME_YELLOW } else { fl }, ta - std::f32::consts::FRAC_PI_2), + _ => self.heart(out, p, t, nn), + } + } + } + + fn scallop(&self, out: &mut Vec, s: f32, p: (f32, f32), t: (f32, f32), nn: (f32, f32)) { + let (c0, _, _) = self.b.at(s - self.step * 0.5); + let mid = ((c0.0 + p.0) / 2.0, (c0.1 + p.1) / 2.0); + let n = 8; + for j in 0..n { + let a0 = std::f32::consts::PI * j as f32 / n as f32; + let a1 = std::f32::consts::PI * (j + 1) as f32 / n as f32; + let r = self.step * 0.5; + let pt = |a: f32| (mid.0 - t.0 * r * a.cos() - nn.0 * r * a.sin(), mid.1 - t.1 * r * a.cos() - nn.1 * r * a.sin()); + out.push(Prim::capsule(pt(a0), pt(a1), self.thick, self.thick, self.vine, self.vine)); + } + } + + fn snowflake(&self, out: &mut Vec, p: (f32, f32), ta: f32) { + let thick = self.thick; + let r = self.unit * 0.6; + let c = [0.85, 0.92, 1.0, 1.0]; + for j in 0..6 { + let a = ta + j as f32 * std::f32::consts::FRAC_PI_3; + let e = (p.0 + a.cos() * r, p.1 + a.sin() * r); + out.push(Prim::capsule(p, e, (thick * 0.6).max(0.6), (thick * 0.4).max(0.5), c, c)); + let m = (p.0 + a.cos() * r * 0.6, p.1 + a.sin() * r * 0.6); + for sd in [-0.7f32, 0.7] { + let b2 = (m.0 + (a + sd).cos() * r * 0.3, m.1 + (a + sd).sin() * r * 0.3); + out.push(Prim::capsule(m, b2, (thick * 0.4).max(0.5), 0.4, c, c)); + } + } + } + + /// Heart: two lobes and a point towards the inside. + fn heart(&self, out: &mut Vec, p: (f32, f32), t: (f32, f32), nn: (f32, f32)) { + let r = self.unit * 0.3; + let (tx, ty) = t; + let l = (p.0 - tx * r * 0.8 - nn.0 * r * 0.3, p.1 - ty * r * 0.8 - nn.1 * r * 0.3); + let rr = (p.0 + tx * r * 0.8 - nn.0 * r * 0.3, p.1 + ty * r * 0.8 - nn.1 * r * 0.3); + let tip = (p.0 + nn.0 * r * 1.6, p.1 + nn.1 * r * 1.6); + out.push(Prim::capsule(l, tip, r, 0.6, self.fl, self.fl)); + out.push(Prim::capsule(rr, tip, r, 0.6, self.fl, self.fl)); + } + + /// Fade: lower the opacity of ornaments that reach further inside. + fn apply_fade(&self, out: &mut [Prim], fade: f32, canvas: Rect) { let cx = canvas.x0 as f32 + canvas.width() as f32 / 2.0; let cy = canvas.y0 as f32 + canvas.height() as f32 / 2.0; - for p in &mut out { + for p in out { let c = match p.shape { Shape::Capsule { a, .. } => a, Shape::Ellipse { c, .. } => c, }; - let edge = ((c.0 - cx).abs() / (b.w / 2.0)).max((c.1 - cy).abs() / (b.h / 2.0)).clamp(0.0, 1.0); + let edge = ((c.0 - cx).abs() / (self.b.w / 2.0)).max((c.1 - cy).abs() / (self.b.h / 2.0)).clamp(0.0, 1.0); let k = 1.0 - fade * (1.0 - edge) * 8.0; p.c0[3] *= k.clamp(0.0, 1.0); p.c1[3] *= k.clamp(0.0, 1.0); } } +} + +/// Builds picture-frame primitives inside `canvas`. +pub fn picture_frame(spec: &FrameSpec, canvas: Rect) -> Vec { + let mut out = Vec::new(); + let layout = FrameLayout::new(spec, canvas); + let mut rng = Rng::new(spec.seed, 0xF8A3E + spec.frame as u64); + match layout.style { + "vineWithFlowers" | "vineWithLeaves" | "ivy" | "roses" | "daisies" | "berries" => layout.vine_styles(&mut out, &mut rng), + "bamboo" => layout.bamboo(&mut out, &mut rng), + "waves" | "zigzag" | "doubleLine" | "rope" => layout.rule_styles(&mut out), + "dots" | "scallops" | "snowflakes" | "stars" | "hearts" => layout.motif_styles(&mut out), + _ => {} + } + let fade = spec.fade.clamp(0.0, 100.0) / 100.0; + if fade > 0.0 { + layout.apply_fade(&mut out, fade, canvas); + } out } diff --git a/crates/algo/src/shape_blur.rs b/crates/algo/src/shape_blur.rs index 26e9ad15bc..5b262afdcb 100644 --- a/crates/algo/src/shape_blur.rs +++ b/crates/algo/src/shape_blur.rs @@ -51,63 +51,14 @@ impl Prepared { if prefix_len > MAX_SAMPLES || output_len > MAX_SAMPLES { return None; } - let mut prefix = Vec::new(); - prefix.try_reserve_exact(prefix_len).ok()?; - prefix.resize(prefix_len, 0.0f64); - if input_row != 0 { - for (s, d) in src.data.chunks_exact(input_row).zip(prefix.chunks_exact_mut(stride)) { - let mut sum = [0.0f64; crate::fxutil::MAXC]; - for (px, dst) in s.chunks_exact(n).zip(d.get_mut(n..)?.chunks_exact_mut(n)) { - let alpha = if ctx.alpha { *px.last()? } else { 1.0 }; - for (c, ((v, sum), dst)) in px.iter().zip(sum.iter_mut()).zip(dst).enumerate() { - // Multiplication stays f32, exactly as premul_window. - let v = if ctx.alpha && c + 1 < n { *v * alpha } else { *v }; - *sum += f64::from(v); - *dst = *sum; - } - } - } - } + let prefix = Prefix::build(src, ctx, n, stride, prefix_len)?; let mut result = Vec::new(); result.try_reserve_exact(output_len).ok()?; let mut acc = Vec::new(); acc.try_reserve_exact(row_len).ok()?; acc.resize(row_len, 0.0f64); - let x = i64::from(out.x0) - i64::from(src.rect.x0); for y in out.y0..out.y1 { - acc.fill(0.0); - for &(dy, a, b) in &self.spans.rows { - let yy = i64::from(y) - i64::from(src.rect.y0) + i64::from(dy); - let Ok(yy) = usize::try_from(yy) else { - continue; - }; - if yy >= h { - continue; - } - let row = prefix.get(yy.checked_mul(stride)?..yy.checked_add(1)?.checked_mul(stride)?)?; - let lo = x + i64::from(a); - let hi = x + i64::from(b) + 1; - let end = out.width() as i64; - if lo >= 0 && hi + end <= w as i64 { - let start_lo = usize::try_from(lo).ok()?.checked_mul(n)?; - let start_hi = usize::try_from(hi).ok()?.checked_mul(n)?; - let low = row.get(start_lo..start_lo.checked_add(row_len)?)?; - let high = row.get(start_hi..start_hi.checked_add(row_len)?)?; - for ((acc, hi), lo) in acc.iter_mut().zip(high).zip(low) { - *acc += hi - lo; - } - } else { - // Direct kernel callers may omit the halo or request pixels outside src. - // Retain the scalar kernel's zero extension and fixed normalization. - for (i, px) in acc.chunks_exact_mut(n).enumerate() { - let low = (lo + i as i64).clamp(0, w as i64) as usize * n; - let high = (hi + i as i64).clamp(0, w as i64) as usize * n; - for ((acc, hi), lo) in px.iter_mut().zip(row.get(high..high + n)?).zip(row.get(low..low + n)?) { - *acc += hi - lo; - } - } - } - } + self.accumulate_row(&prefix, src, out, y, &mut acc)?; for px in acc.chunks_exact(n) { let mut sample = [0.0f32; crate::fxutil::MAXC]; let sample = sample.get_mut(..n)?; @@ -120,4 +71,88 @@ impl Prepared { } Some(result) } + + /// Sum every kernel row's window for output row `y` into `acc`. + fn accumulate_row(&self, prefix: &Prefix, src: &Image, out: Rect, y: i32, acc: &mut [f64]) -> Option<()> { + let x = i64::from(out.x0) - i64::from(src.rect.x0); + acc.fill(0.0); + for &(dy, a, b) in &self.spans.rows { + let yy = i64::from(y) - i64::from(src.rect.y0) + i64::from(dy); + let Ok(yy) = usize::try_from(yy) else { + continue; + }; + if yy >= prefix.h { + continue; + } + let row = prefix.row(yy)?; + prefix.add_window(row, acc, x + i64::from(a), x + i64::from(b) + 1, out.width() as i64)?; + } + Some(()) + } +} + +/// Per-row running channel sums (premultiplied when alpha is present), one +/// extra leading column per row so any window is a difference of two entries. +struct Prefix { + data: Vec, + stride: usize, + n: usize, + w: usize, + h: usize, +} + +impl Prefix { + fn build(src: &Image, ctx: &Ctx, n: usize, stride: usize, len: usize) -> Option { + let w = src.rect.width() as usize; + let h = src.rect.height() as usize; + let input_row = w.checked_mul(n)?; + let mut data = Vec::new(); + data.try_reserve_exact(len).ok()?; + data.resize(len, 0.0f64); + if input_row != 0 { + for (s, d) in src.data.chunks_exact(input_row).zip(data.chunks_exact_mut(stride)) { + let mut sum = [0.0f64; crate::fxutil::MAXC]; + for (px, dst) in s.chunks_exact(n).zip(d.get_mut(n..)?.chunks_exact_mut(n)) { + let alpha = if ctx.alpha { *px.last()? } else { 1.0 }; + for (c, ((v, sum), dst)) in px.iter().zip(sum.iter_mut()).zip(dst).enumerate() { + // Multiplication stays f32, exactly as premul_window. + let v = if ctx.alpha && c + 1 < n { *v * alpha } else { *v }; + *sum += f64::from(v); + *dst = *sum; + } + } + } + } + Some(Self { data, stride, n, w, h }) + } + + fn row(&self, y: usize) -> Option<&[f64]> { + self.data.get(y.checked_mul(self.stride)?..y.checked_add(1)?.checked_mul(self.stride)?) + } + + /// Add the `[lo, hi)` window difference of `row` for `acc.len() / n` output pixels. + fn add_window(&self, row: &[f64], acc: &mut [f64], lo: i64, hi: i64, end: i64) -> Option<()> { + let (n, w) = (self.n, self.w); + let row_len = acc.len(); + if lo >= 0 && hi + end <= w as i64 { + let start_lo = usize::try_from(lo).ok()?.checked_mul(n)?; + let start_hi = usize::try_from(hi).ok()?.checked_mul(n)?; + let low = row.get(start_lo..start_lo.checked_add(row_len)?)?; + let high = row.get(start_hi..start_hi.checked_add(row_len)?)?; + for ((acc, hi), lo) in acc.iter_mut().zip(high).zip(low) { + *acc += hi - lo; + } + } else { + // Direct kernel callers may omit the halo or request pixels outside src. + // Retain the scalar kernel's zero extension and fixed normalization. + for (i, px) in acc.chunks_exact_mut(n).enumerate() { + let low = (lo + i as i64).clamp(0, w as i64) as usize * n; + let high = (hi + i as i64).clamp(0, w as i64) as usize * n; + for ((acc, hi), lo) in px.iter_mut().zip(row.get(high..high + n)?).zip(row.get(low..low + n)?) { + *acc += hi - lo; + } + } + } + Some(()) + } } diff --git a/crates/algo/src/sharpen/exact.rs b/crates/algo/src/sharpen/exact.rs index 7d74bc538f..07ecba08bc 100644 --- a/crates/algo/src/sharpen/exact.rs +++ b/crates/algo/src/sharpen/exact.rs @@ -77,58 +77,94 @@ pub(crate) fn run(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, t let row_len = ow.checked_mul(n)?; let th = oh.checked_add(2 * r)?; let ww = ow.checked_add(2 * r)?; - let (x0, x1, y0) = (out.x0.checked_sub(r as i32)?, out.x1.checked_add(r as i32)?, out.y0.checked_sub(r as i32)?); + let pass = Pass { src, out, ctx, kernel: &kernel, ctl, n, row_len }; let mut row = zeros(ww.checked_mul(n)?)?; let mut tmp = zeros(row_len.checked_mul(th)?)?; let mut result = zeros(row_len.checked_mul(oh)?)?; - for (y, dst) in tmp.chunks_exact_mut(row_len).enumerate() { - if ctl.cancelled() { - return None; - } - read_row(src, x0, x1, y0.checked_add(y as i32)?, &mut row)?; - premultiply(&mut row, n, ctx.alpha); - // Tap-major traversal exposes contiguous independent samples to LLVM. No - // reduction, tap merging, symmetry or fused multiply-add changes the sums. - for (i, weight) in kernel.iter().enumerate() { - let start = i.checked_mul(n)?; - let samples = row.get(start..start.checked_add(row_len)?)?; - for (d, s) in dst.iter_mut().zip(samples) { - *d += s * weight; + pass.horizontal(&mut row, &mut tmp)?; + pass.vertical(&tmp, &mut row, &mut result, amount / 100.0, threshold / 255.0)?; + Some(result) +} + +/// The shared inputs of the two separable blur passes. +struct Pass<'a> { + src: &'a Image, + out: Rect, + ctx: &'a Ctx, + kernel: &'a [f32], + ctl: &'a Interrupt<'a>, + n: usize, + row_len: usize, +} + +impl Pass<'_> { + /// Blur horizontally every source row the output (plus kernel halo) needs. + fn horizontal(&self, row: &mut [f32], tmp: &mut [f32]) -> Option<()> { + let (n, row_len) = (self.n, self.row_len); + let r = self.kernel.len() / 2; + let (x0, x1, y0) = (self.out.x0.checked_sub(r as i32)?, self.out.x1.checked_add(r as i32)?, self.out.y0.checked_sub(r as i32)?); + for (y, dst) in tmp.chunks_exact_mut(row_len).enumerate() { + if self.ctl.cancelled() { + return None; + } + read_row(self.src, x0, x1, y0.checked_add(y as i32)?, row)?; + premultiply(row, n, self.ctx.alpha); + // Tap-major traversal exposes contiguous independent samples to LLVM. No + // reduction, tap merging, symmetry or fused multiply-add changes the sums. + for (i, weight) in self.kernel.iter().enumerate() { + let start = i.checked_mul(n)?; + let samples = row.get(start..start.checked_add(row_len)?)?; + for (d, s) in dst.iter_mut().zip(samples) { + *d += s * weight; + } } } + Some(()) } - let (amount, threshold) = (amount / 100.0, threshold / 255.0); - let cc = n - usize::from(ctx.alpha); - for (y, dst) in result.chunks_exact_mut(row_len).enumerate() { - if ctl.cancelled() { - return None; - } - for (i, weight) in kernel.iter().enumerate() { - let start = y.checked_add(i)?.checked_mul(row_len)?; - let samples = tmp.get(start..start.checked_add(row_len)?)?; - for (d, s) in dst.iter_mut().zip(samples) { - *d += s * weight; + + /// Blur vertically and blend each output row against its original pixels. + /// `originals` is scratch space reused for the source row being compared. + fn vertical(&self, tmp: &[f32], originals: &mut [f32], result: &mut [f32], amount: f32, threshold: f32) -> Option<()> { + let row_len = self.row_len; + for (y, dst) in result.chunks_exact_mut(row_len).enumerate() { + if self.ctl.cancelled() { + return None; } + for (i, weight) in self.kernel.iter().enumerate() { + let start = y.checked_add(i)?.checked_mul(row_len)?; + let samples = tmp.get(start..start.checked_add(row_len)?)?; + for (d, s) in dst.iter_mut().zip(samples) { + *d += s * weight; + } + } + let originals = originals.get_mut(..row_len)?; + read_row(self.src, self.out.x0, self.out.x1, self.out.y0.checked_add(y as i32)?, originals)?; + self.sharpen_row(dst, originals, amount, threshold)?; } - let originals = row.get_mut(..row_len)?; - read_row(src, out.x0, out.x1, out.y0.checked_add(y as i32)?, originals)?; - for (blurred, original) in dst.chunks_exact_mut(n).zip(originals.chunks_exact(n)) { - if ctx.alpha && *original.last()? <= 0.0 { + Some(()) + } + + /// Replace each blurred pixel by the thresholded unsharp-mask value. + fn sharpen_row(&self, blurred_row: &mut [f32], originals: &[f32], amount: f32, threshold: f32) -> Option<()> { + let (n, alpha) = (self.n, self.ctx.alpha); + let cc = n - usize::from(alpha); + for (blurred, original) in blurred_row.chunks_exact_mut(n).zip(originals.chunks_exact(n)) { + if alpha && *original.last()? <= 0.0 { blurred.copy_from_slice(original); continue; } - let a = if ctx.alpha { *blurred.last()? } else { 1.0 }; + let a = if alpha { *blurred.last()? } else { 1.0 }; for (b, o) in blurred.iter_mut().zip(original).take(cc) { // Keep the original unpremultiply cut-off and division, followed by // the threshold epsilon and inclusive comparison, at every depth. - let b_value = if ctx.alpha { if a > 1e-7 { *b / a } else { 0.0 } } else { *b }; + let b_value = if alpha { if a > 1e-7 { *b / a } else { 0.0 } } else { *b }; let d = o - b_value; *b = if d.abs() + 1e-6 >= threshold { o + amount * d } else { *o }; } - if ctx.alpha { + if alpha { *blurred.last_mut()? = *original.last()?; } } + Some(()) } - Some(result) } diff --git a/crates/algo/src/sharpen/fft.rs b/crates/algo/src/sharpen/fft.rs index 6fdf18c8b0..57758b06d2 100644 --- a/crates/algo/src/sharpen/fft.rs +++ b/crates/algo/src/sharpen/fft.rs @@ -128,9 +128,9 @@ fn run(surface: &Surface, area: Rect, amount: f32, radius: f32, selection: Optio let resident = samples.checked_mul(4)?; let mut planner = FftPlanner::::new(); let horizontal = Plan::new(w.checked_add(2 * r)?, &kernel, &mut planner)?; - let vertical = Plan::new(h.checked_add(2 * r)?, &kernel, &mut planner)?; + let vertical_plan = Plan::new(h.checked_add(2 * r)?, &kernel, &mut planner)?; // A conservative allowance includes FFT plans/twiddles in addition to spectra. - let plans = horizontal.size.checked_add(vertical.size)?.checked_mul(256)?; + let plans = horizontal.size.checked_add(vertical_plan.size)?.checked_mul(256)?; let resident = resident.checked_add(plans)?; let workers = rayon::current_num_threads().max(1); let horizontal_worker = read_width.checked_mul(n)?.checked_mul(4)?.checked_add(horizontal.size.checked_add(horizontal.scratch)?.checked_mul(16)?)?; @@ -139,7 +139,7 @@ fn run(surface: &Surface, area: Rect, amount: f32, radius: f32, selection: Optio .checked_mul(n)? .checked_mul(4)? .checked_add(STRIPE.checked_mul(h)?.checked_mul(n)?.checked_mul(12)?)? - .checked_add(vertical.size.checked_add(vertical.scratch)?.checked_mul(16)?)?; + .checked_add(vertical_plan.size.checked_add(vertical_plan.scratch)?.checked_mul(16)?)?; let group = group_size(resident, horizontal_worker.max(vertical_worker), w.div_ceil(STRIPE), workers)?; let mut tmp = buffer(samples, 0.0f32)?; let finished = AtomicUsize::new(0); @@ -210,98 +210,29 @@ fn run(surface: &Surface, area: Rect, amount: f32, radius: f32, selection: Optio } let mut out = surface.clone(); let count = w.div_ceil(STRIPE); + let vertical = VerticalPass { + surface, + selection, + tmp: &tmp, + plan: &vertical_plan, + ctl, + area, + n, + w, + h, + rows, + row_len, + r, + y0, + read_y0, + read_y1, + alpha, + amount, + kernel_len: kernel.len(), + }; for first in (0..count).step_by(group) { let end = first.checked_add(group)?.min(count); - let results: Option> = (first..end) - .into_par_iter() - .map(|index| { - if ctl.cancelled() { - return None; - } - let x = index.checked_mul(STRIPE)?; - let width = STRIPE.min(w.checked_sub(x)?); - let mut columns = buffer(width.checked_mul(rows)?.checked_mul(n)?, 0.0f32)?; - for (y, row) in tmp.chunks_exact(row_len).enumerate() { - if y % 64 == 0 && ctl.cancelled() { - return None; - } - for (c, px) in row.get(x * n..(x + width) * n)?.chunks_exact(n).enumerate() { - let start = (c * rows + y) * n; - columns.get_mut(start..start + n)?.copy_from_slice(px); - } - } - let rect = Rect::new(area.x0.checked_add(x as i32)?, area.y0, area.x0.checked_add((x + width) as i32)?, area.y1); - let len = width.checked_mul(h)?.checked_mul(n)?; - let mut result = buffer(len, 0.0f32)?; - let mut original = buffer(len, 0.0f32)?; - surface.read_region_into(rect, &mut original); - let (mut data, mut scratch) = vertical.work()?; - for (c, samples) in columns.chunks_exact(rows * n).enumerate() { - if ctl.cancelled() { - return None; - } - let mut scales = [0.0f64; crate::fxutil::MAXC]; - for px in samples.chunks_exact(n) { - for (s, v) in scales.iter_mut().zip(px) { - *s = s.max(f64::from(v.abs())); - } - } - for channel in (0..n).step_by(2) { - if ctl.cancelled() { - return None; - } - data.fill(Number::default()); - for (i, d) in data.iter_mut().take(h + 2 * r).enumerate() { - let sy = y0.checked_add(i as i32)?.clamp(read_y0, read_y1.checked_sub(1)?); - let start = usize::try_from(sy - read_y0).ok()?.checked_mul(n)?; - let px = samples.get(start..start + n)?; - let sample = |c: usize| -> f64 { - match (px.get(c), scales.get(c)) { - (Some(v), Some(s)) if *s > 0.0 => f64::from(*v) / s, - _ => 0.0, - } - }; - *d = Number::new(sample(channel), sample(channel + 1)); - } - vertical.convolve(&mut data, &mut scratch)?; - for (y, d) in data.get(2 * r..2 * r + h)?.iter().enumerate() { - let start = (y * width + c) * n; - *result.get_mut(start + channel)? = (d.re * scales.get(channel)?) as f32; - if let Some(v) = result.get_mut(start + channel + 1).filter(|_| channel + 1 < n) { - *v = (d.im * scales.get(channel + 1)?) as f32; - } - } - } - } - for (px, o) in result.chunks_exact_mut(n).zip(original.chunks_exact(n)) { - if alpha && *o.last()? <= 0.0 { - px.copy_from_slice(o); - continue; - } - let a = if alpha { *px.last()? } else { 1.0 }; - // Near the original unpremultiply cutoff, cancellation/FFT noise - // or f32 sum order can expose colour. Decline the whole fast path. - let uncertainty = 4.0 * kernel.len() as f32 * f32::EPSILON; - if alpha && a <= 1e-7 + uncertainty { - return None; - } - for (v, o) in px.iter_mut().zip(o).take(n - usize::from(alpha)) { - let b = if alpha { *v / a } else { *v }; - *v = o + amount / 100.0 * (o - b); - if !v.is_finite() { - return None; - } - } - if alpha { - *px.last_mut()? = *o.last()?; - } - } - if let Some(sel) = selection { - crate::mix_selection(&mut result, rect, sel, &Image { rect, ch: n, data: original }, alpha); - } - Some((rect, result)) - }) - .collect(); + let results: Option> = (first..end).into_par_iter().map(|index| vertical.stripe(index)).collect(); for (rect, data) in results? { if ctl.cancelled() { return None; @@ -321,5 +252,145 @@ fn run(surface: &Surface, area: Rect, amount: f32, radius: f32, selection: Optio Some(out) } +/// Everything the vertical pass needs to turn one stripe of horizontally +/// convolved columns into finished, sharpened output pixels. +struct VerticalPass<'a> { + surface: &'a Surface, + selection: Option<&'a Surface>, + tmp: &'a [f32], + plan: &'a Plan, + ctl: &'a Interrupt<'a>, + area: Rect, + n: usize, + w: usize, + h: usize, + rows: usize, + row_len: usize, + r: usize, + y0: i32, + read_y0: i32, + read_y1: i32, + alpha: bool, + amount: f32, + kernel_len: usize, +} + +/// Channel `c` of `px` scaled into [-1, 1], or zero when the column is all zero. +fn normalized(px: &[f32], scales: &[f64], c: usize) -> f64 { + match (px.get(c), scales.get(c)) { + (Some(v), Some(s)) if *s > 0.0 => f64::from(*v) / s, + _ => 0.0, + } +} + +impl VerticalPass<'_> { + /// Process the `index`th stripe of columns, returning its rect and pixels. + fn stripe(&self, index: usize) -> Option<(Rect, Vec)> { + let (ctl, n, h) = (self.ctl, self.n, self.h); + if ctl.cancelled() { + return None; + } + let x = index.checked_mul(STRIPE)?; + let width = STRIPE.min(self.w.checked_sub(x)?); + let columns = self.gather_columns(x, width)?; + let rect = Rect::new(self.area.x0.checked_add(x as i32)?, self.area.y0, self.area.x0.checked_add((x + width) as i32)?, self.area.y1); + let len = width.checked_mul(h)?.checked_mul(n)?; + let mut result = buffer(len, 0.0f32)?; + let mut original = buffer(len, 0.0f32)?; + self.surface.read_region_into(rect, &mut original); + let (mut data, mut scratch) = self.plan.work()?; + for (c, samples) in columns.chunks_exact(self.rows * n).enumerate() { + if ctl.cancelled() { + return None; + } + self.convolve_column(samples, c, width, (&mut data, &mut scratch), &mut result)?; + } + self.sharpen(&mut result, &original)?; + if let Some(sel) = self.selection { + crate::mix_selection(&mut result, rect, sel, &Image { rect, ch: n, data: original }, self.alpha); + } + Some((rect, result)) + } + + /// Transpose the stripe at `x` of the horizontal results into column-major order. + fn gather_columns(&self, x: usize, width: usize) -> Option> { + let (n, rows) = (self.n, self.rows); + let mut columns = buffer(width.checked_mul(rows)?.checked_mul(n)?, 0.0f32)?; + for (y, row) in self.tmp.chunks_exact(self.row_len).enumerate() { + if y % 64 == 0 && self.ctl.cancelled() { + return None; + } + for (c, px) in row.get(x * n..(x + width) * n)?.chunks_exact(n).enumerate() { + let start = (c * rows + y) * n; + columns.get_mut(start..start + n)?.copy_from_slice(px); + } + } + Some(columns) + } + + /// Convolve one gathered column, two channels per complex FFT, into `result`. + fn convolve_column(&self, samples: &[f32], c: usize, width: usize, work: (&mut [Number], &mut [Number]), result: &mut [f32]) -> Option<()> { + let (n, h, r) = (self.n, self.h, self.r); + let (data, scratch) = work; + let mut scales = [0.0f64; crate::fxutil::MAXC]; + for px in samples.chunks_exact(n) { + for (s, v) in scales.iter_mut().zip(px) { + *s = s.max(f64::from(v.abs())); + } + } + for channel in (0..n).step_by(2) { + if self.ctl.cancelled() { + return None; + } + data.fill(Number::default()); + for (i, d) in data.iter_mut().take(h + 2 * r).enumerate() { + let sy = self.y0.checked_add(i as i32)?.clamp(self.read_y0, self.read_y1.checked_sub(1)?); + let start = usize::try_from(sy - self.read_y0).ok()?.checked_mul(n)?; + let px = samples.get(start..start + n)?; + *d = Number::new(normalized(px, &scales, channel), normalized(px, &scales, channel + 1)); + } + self.plan.convolve(data, scratch)?; + for (y, d) in data.get(2 * r..2 * r + h)?.iter().enumerate() { + let start = (y * width + c) * n; + *result.get_mut(start + channel)? = (d.re * scales.get(channel)?) as f32; + if let Some(v) = result.get_mut(start + channel + 1).filter(|_| channel + 1 < n) { + *v = (d.im * scales.get(channel + 1)?) as f32; + } + } + } + Some(()) + } + + /// Turn the blurred stripe into the unsharp-masked result against `original`. + /// Declines (`None`) wherever the fast path cannot match the exact kernel. + fn sharpen(&self, result: &mut [f32], original: &[f32]) -> Option<()> { + let (n, alpha) = (self.n, self.alpha); + for (px, o) in result.chunks_exact_mut(n).zip(original.chunks_exact(n)) { + if alpha && *o.last()? <= 0.0 { + px.copy_from_slice(o); + continue; + } + let a = if alpha { *px.last()? } else { 1.0 }; + // Near the original unpremultiply cutoff, cancellation/FFT noise + // or f32 sum order can expose colour. Decline the whole fast path. + let uncertainty = 4.0 * self.kernel_len as f32 * f32::EPSILON; + if alpha && a <= 1e-7 + uncertainty { + return None; + } + for (v, o) in px.iter_mut().zip(o).take(n - usize::from(alpha)) { + let b = if alpha { *v / a } else { *v }; + *v = o + self.amount / 100.0 * (o - b); + if !v.is_finite() { + return None; + } + } + if alpha { + *px.last_mut()? = *o.last()?; + } + } + Some(()) + } +} + #[cfg(test)] mod tests; diff --git a/crates/algo/src/stylize2/extrude.rs b/crates/algo/src/stylize2/extrude.rs index 78a3df273b..ae70351c09 100644 --- a/crates/algo/src/stylize2/extrude.rs +++ b/crates/algo/src/stylize2/extrude.rs @@ -20,7 +20,6 @@ pub(super) fn blocks(src: &Image, out: Rect, ctx: &Ctx, spec: &ExtrudeSpec) -> O if [b.x0, b.y0, b.x1, b.y1, out.x0, out.y0, out.x1, out.y1].iter().any(|v| v.unsigned_abs() > MAX_COORD as u32) { return None; } - let n = src.ch; let w = out.width() as usize; let count = w.checked_mul(out.height() as usize)?; if count > MAX_PIXELS { @@ -44,111 +43,190 @@ pub(super) fn blocks(src: &Image, out: Rect, ctx: &Ctx, spec: &ExtrudeSpec) -> O if i64::from(cx1 - cx0 + 1).checked_mul(i64::from(cy1 - cy0 + 1))? > MAX_CELLS { return None; } - let (bcx, bcy) = ((b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0); - let half_diag = ((b.width() as f32).hypot(b.height() as f32) / 2.0).max(1.0); - let half = cs as f32 / 2.0; - let cc = ncol(ctx, n); - let sub = subtractive(ctx); + let pass = BlockPass { + src, + out, + ctx, + spec, + b, + area, + cs, + k, + reach, + centre: ((b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0), + half_diag: ((b.width() as f32).hypot(b.height() as f32) / 2.0).max(1.0), + half: cs as f32 / 2.0, + }; // Ascending gy, then gx, is the tie order of every pixel's old candidate search. for cy in cy0..=cy1 { for cx in cx0..=cx1 { - let r = Rect::new(b.x0 + cx * cs, b.y0 + cy * cs, b.x0 + (cx + 1) * cs, b.y0 + (cy + 1) * cs); - let clipped = r.intersect(&b); - if spec.mask_incomplete && clipped != r { - continue; - } - let mut col = [0.0f32; MAXC]; - let mut cnt = 0.0; - let step = (cs / 8).max(1) as usize; - for yy in (clipped.y0..clipped.y1).step_by(step) { - for xx in (clipped.x0..clipped.x1).step_by(step) { - let a = if ctx.alpha { src.get(xx, yy, n - 1) } else { 1.0 }; - for (c, v) in col.iter_mut().enumerate().take(n) { - let s = src.get(xx, yy, c); - *v += if ctx.alpha && c < n - 1 { s * a } else { s }; - } - cnt += 1.0; - } - } - if cnt > 0.0 { - for v in col.iter_mut().take(n) { - *v /= cnt; - } - } - unpremul_px(&mut col[..n], ctx.alpha); - let h = if spec.level_based { luma(ctx, &col[..n]).clamp(0.0, 1.0) } else { hash01(cx, cy, 21, spec.seed) }; - if !h.is_finite() { - return None; - } - let (mx, my) = (r.x0 as f32 + half, r.y0 as f32 + half); - let off = reach * h / half_diag; - let (ox, oy) = ((mx - bcx) * off, (my - bcy) * off); - // Two extra pixels conservatively cover rounding in the unchanged interval test. - let sweep = Rect::new( - (mx.min(mx + ox) - half).floor() as i32 - 2, - (my.min(my + oy) - half).floor() as i32 - 2, - (mx.max(mx + ox) + half).ceil() as i32 + 2, - (my.max(my + oy) + half).ceil() as i32 + 2, - ) - .intersect(&area); - for y in sweep.y0..sweep.y1 { - let gy = (y - b.y0).div_euclid(cs); - if (cy - gy).abs() > k { - continue; - } - let fy = y as f32 + 0.5; - let Some(iy) = interval(fy, my, oy, half) else { continue }; - for x in sweep.x0..sweep.x1 { - if (cx - (x - b.x0).div_euclid(cs)).abs() > k { - continue; - } - let i = (y - out.y0) as usize * w + (x - out.x0) as usize; - let height = heights.get_mut(i)?; - if *height >= h { - continue; - } - let fx = x as f32 + 0.5; - let Some(ix) = interval(fx, mx, ox, half) else { continue }; - let (lo, hi) = (ix.0.max(iy.0), ix.1.min(iy.1)); - if lo > hi { - continue; - } - *height = h; - let face = if hi >= 1.0 { - 0 - } else if ix.1 < iy.1 { - if ox > 0.0 { 1 } else { 2 } - } else if oy > 0.0 { - 3 - } else { - 4 - }; - let px = res.get_mut(i * n..(i + 1) * n)?; - if face == 0 && !spec.solid_front { - let (sx, sy) = ((fx - (mx - bcx) * off).floor() as i32, (fy - (my - bcy) * off).floor() as i32); - read_px(src, sx.clamp(r.x0, r.x1 - 1), sy.clamp(r.y0, r.y1 - 1), px); - } else { - let shade = match face { - 0 => 1.0, - 1 => 0.85, - 2 => 0.55, - 3 => 0.95, - _ => 0.45, - }; - for (v, c) in px.iter_mut().zip(&col).take(cc) { - *v = if sub { 1.0 - (1.0 - *c) * shade } else { *c * shade }.clamp(0.0, 1.0); - } - if ctx.alpha { - *px.last_mut()? = col.get(n - 1).copied()?; - } - } - } - } + pass.paint_cell(cx, cy, &mut heights, &mut res)?; } } Some(res) } +/// The constants shared by every swept block of one `blocks` call. +struct BlockPass<'a> { + src: &'a Image, + out: Rect, + ctx: &'a Ctx, + spec: &'a ExtrudeSpec, + b: Rect, + area: Rect, + cs: i32, + k: i32, + reach: f32, + centre: (f32, f32), + half_diag: f32, + half: f32, +} + +/// One cell's flat colour and where its extruded block sweeps to. +struct Block { + r: Rect, + cx: i32, + m: (f32, f32), + o: (f32, f32), + off: f32, + h: f32, + col: [f32; MAXC], +} + +impl BlockPass<'_> { + /// Average the (premultiplied) source over `clipped`, sampling every `step` pixels. + fn cell_colour(&self, clipped: Rect) -> [f32; MAXC] { + let (src, ctx, n) = (self.src, self.ctx, self.src.ch); + let mut col = [0.0f32; MAXC]; + let mut cnt = 0.0; + let step = (self.cs / 8).max(1) as usize; + for yy in (clipped.y0..clipped.y1).step_by(step) { + for xx in (clipped.x0..clipped.x1).step_by(step) { + let a = if ctx.alpha { src.get(xx, yy, n - 1) } else { 1.0 }; + for (c, v) in col.iter_mut().enumerate().take(n) { + let s = src.get(xx, yy, c); + *v += if ctx.alpha && c < n - 1 { s * a } else { s }; + } + cnt += 1.0; + } + } + if cnt > 0.0 { + for v in col.iter_mut().take(n) { + *v /= cnt; + } + } + unpremul_px(&mut col[..n], ctx.alpha); + col + } + + /// Rasterize the block of grid cell (`cx`, `cy`) over the pixels it can hit. + fn paint_cell(&self, cx: i32, cy: i32, heights: &mut [f32], res: &mut [f32]) -> Option<()> { + let (b, cs, half) = (self.b, self.cs, self.half); + let r = Rect::new(b.x0 + cx * cs, b.y0 + cy * cs, b.x0 + (cx + 1) * cs, b.y0 + (cy + 1) * cs); + let clipped = r.intersect(&b); + if self.spec.mask_incomplete && clipped != r { + return Some(()); + } + let col = self.cell_colour(clipped); + let n = self.src.ch; + let h = if self.spec.level_based { luma(self.ctx, &col[..n]).clamp(0.0, 1.0) } else { hash01(cx, cy, 21, self.spec.seed) }; + if !h.is_finite() { + return None; + } + let (mx, my) = (r.x0 as f32 + half, r.y0 as f32 + half); + let off = self.reach * h / self.half_diag; + let o = ((mx - self.centre.0) * off, (my - self.centre.1) * off); + // Two extra pixels conservatively cover rounding in the unchanged interval test. + let sweep = Rect::new( + (mx.min(mx + o.0) - half).floor() as i32 - 2, + (my.min(my + o.1) - half).floor() as i32 - 2, + (mx.max(mx + o.0) + half).ceil() as i32 + 2, + (my.max(my + o.1) + half).ceil() as i32 + 2, + ) + .intersect(&self.area); + let block = Block { r, cx, m: (mx, my), o, off, h, col }; + for y in sweep.y0..sweep.y1 { + let gy = (y - b.y0).div_euclid(cs); + if (cy - gy).abs() > self.k { + continue; + } + for x in sweep.x0..sweep.x1 { + self.paint_pixel(&block, x, y, heights, res)?; + } + } + Some(()) + } + + /// Paint pixel (`x`, `y`) if `block` covers it and is taller than what is there. + fn paint_pixel(&self, block: &Block, x: i32, y: i32, heights: &mut [f32], res: &mut [f32]) -> Option<()> { + let (b, cs, half, n) = (self.b, self.cs, self.half, self.src.ch); + let (mx, my) = block.m; + let (ox, oy) = block.o; + if (block.cx - (x - b.x0).div_euclid(cs)).abs() > self.k { + return Some(()); + } + let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5); + let i = (y - self.out.y0) as usize * self.out.width() as usize + (x - self.out.x0) as usize; + let height = heights.get_mut(i)?; + if *height >= block.h { + return Some(()); + } + let Some(iy) = interval(fy, my, oy, half) else { return Some(()) }; + let Some(ix) = interval(fx, mx, ox, half) else { return Some(()) }; + let (lo, hi) = (ix.0.max(iy.0), ix.1.min(iy.1)); + if lo > hi { + return Some(()); + } + *height = block.h; + let face = block_face(hi, ix.1 < iy.1, ox, oy); + let px = res.get_mut(i * n..(i + 1) * n)?; + self.write_face(block, face, (fx, fy), px) + } + + /// Write `face` of `block` into pixel `px` centred at `(fx, fy)`: the front + /// face shows the shifted source, every face can instead be flat-shaded. + fn write_face(&self, block: &Block, face: u8, (fx, fy): (f32, f32), px: &mut [f32]) -> Option<()> { + let n = self.src.ch; + if face == 0 && !self.spec.solid_front { + let (sx, sy) = ((fx - (block.m.0 - self.centre.0) * block.off).floor() as i32, (fy - (block.m.1 - self.centre.1) * block.off).floor() as i32); + read_px(self.src, sx.clamp(block.r.x0, block.r.x1 - 1), sy.clamp(block.r.y0, block.r.y1 - 1), px); + } else { + let shade = face_shade(face); + let sub = subtractive(self.ctx); + for (v, c) in px.iter_mut().zip(&block.col).take(ncol(self.ctx, n)) { + *v = if sub { 1.0 - (1.0 - *c) * shade } else { *c * shade }.clamp(0.0, 1.0); + } + if self.ctx.alpha { + *px.last_mut()? = block.col.get(n - 1).copied()?; + } + } + Some(()) + } +} + +/// Which face of the swept block a pixel shows: 0 front, 1/2 right/left, 3/4 bottom/top. +fn block_face(hi: f32, x_exits_first: bool, ox: f32, oy: f32) -> u8 { + if hi >= 1.0 { + 0 + } else if x_exits_first { + if ox > 0.0 { 1 } else { 2 } + } else if oy > 0.0 { + 3 + } else { + 4 + } +} + +fn face_shade(face: u8) -> f32 { + match face { + 0 => 1.0, + 1 => 0.85, + 2 => 0.55, + 3 => 0.95, + _ => 0.45, + } +} + fn interval(p: f32, m: f32, o: f32, half: f32) -> Option<(f32, f32)> { if o.abs() < 1e-6 { return ((p - m).abs() <= half).then_some((0.0, 1.0)); From ddaf29933598d07fbaafbef47cd2e1cd418cc291 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 10/35] Refactor automation for strict Clippy checks --- 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 ++++ 4 files changed, 11 insertions(+), 4 deletions(-) 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}"); From 9a348da8bb98b2cc57770ed7ca397a8d12b638bb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 11/35] Refactor codecs for strict Clippy checks --- crates/codecs/src/codecs/tiff.rs | 2 +- crates/codecs/src/codecs/tiff/bands.rs | 2 +- crates/codecs/src/codecs/tiff/decode.rs | 211 +++++++++++++----------- crates/codecs/src/codecs/tiff/encode.rs | 7 +- crates/codecs/src/codecs/tiff/tags.rs | 2 +- crates/codecs/src/codecs/vp8.rs | 121 +++++++------- crates/codecs/src/codecs/vp8/predict.rs | 4 +- 7 files changed, 192 insertions(+), 157 deletions(-) diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs index 1db3b0c44c..e3ccfbc952 100644 --- a/crates/codecs/src/codecs/tiff.rs +++ b/crates/codecs/src/codecs/tiff.rs @@ -27,7 +27,7 @@ //! (see [`writes_little_endian`]), which the layer data must match. use std::borrow::Cow; -use std::io::{self, Cursor, Read, Seek, SeekFrom}; +use std::io::{self, Read, Seek, SeekFrom}; use half::f16; use tiff::decoder::{ChunkType, Decoder}; diff --git a/crates/codecs/src/codecs/tiff/bands.rs b/crates/codecs/src/codecs/tiff/bands.rs index fe35cc98d2..8eaeadf8a6 100644 --- a/crates/codecs/src/codecs/tiff/bands.rs +++ b/crates/codecs/src/codecs/tiff/bands.rs @@ -1,5 +1,5 @@ use super::decode::{Layout, Patched, Src, is_eof}; -use super::*; +use super::{CodecError, Decoder, SampleType, err, f16, map_err}; /// The a* and b* samples (1 and 2 of every pixel) of a Lab image between the file's encoding and /// PhotoCraft's (8 bits: `a + 128`; 16 bits: `(a + 128) · 257`). In the file, CIELab holds them diff --git a/crates/codecs/src/codecs/tiff/decode.rs b/crates/codecs/src/codecs/tiff/decode.rs index 4b5d38cb59..0872739f3e 100644 --- a/crates/codecs/src/codecs/tiff/decode.rs +++ b/crates/codecs/src/codecs/tiff/decode.rs @@ -1,6 +1,9 @@ use super::bands::{convert_ab, decode_bands, extra_sample_indices, split_extra_samples, zeroed}; use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS, photoshop_tags}; -use super::*; +use super::{ + ChannelLayout, ChunkType, CodecError, DecodeWarning, Decoder, ExifDirs, File, Ifd, Image, Limits, Metadata, Read, SampleType, Seek, SeekFrom, Tag, + camera_raw, err, ifd, io, map_err, tiff_exif, +}; /// Decodes the page Photoshop would open: the first full-resolution directory. pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { @@ -235,6 +238,112 @@ pub(super) fn is_eof(e: &tiff::TiffError) -> bool { matches!(e, tiff::TiffError::IoError(io) if io.kind() == io::ErrorKind::UnexpectedEof) } +/// The sample type of a (SampleFormat, BitsPerSample) pair. +fn sample_src(format: u64, bits: u64) -> Result { + Ok(match (format, bits) { + (1, 1 | 2 | 4) => Src::Bits(bits as u8), + (1, 8) => Src::U8, + (1, 16) => Src::U16, + (1, 32) => Src::U32, + (1, 64) => Src::U64, + (3, 16) => Src::F16, + (3, 32) => Src::F32, + (3, 64) => Src::F64, + (2, _) => return Err(CodecError::unsupported(F, "signed integer samples")), + _ => return Err(CodecError::unsupported(F, format!("{bits}-bit samples (sample format {format})"))), + }) +} + +/// The ColorMap of a palette image as RGB entries. +fn read_palette(f: &File<'_>, dir: &Ifd, spp: u64, bits: u64, src: Src) -> Result, CodecError> { + if spp != 1 || !matches!(src, Src::Bits(_) | Src::U8 | Src::U16) { + return Err(CodecError::unsupported(F, format!("palette image with {spp} samples of {bits} bits"))); + } + let n = 1u64 << bits; + let map = dir.get(ifd::TAG_COLOR_MAP).filter(|e| e.ty == 3 && e.count == 3 * n).ok_or_else(|| err("palette image without a valid ColorMap"))?; + let at = |i: u64| f.uint(map, i).and_then(|v| u16::try_from(v).ok()); + let table: Option> = (0..n).map(|i| Some([at(i)?, at(n + i)?, at(2 * n + i)?])).collect(); + table.ok_or_else(|| err("palette ColorMap cut off")) +} + +/// The layout of a multiband read that was asked for every sample. +fn multiband_layout(photometric: u64, has_alpha: bool, gray_alpha: bool) -> ChannelLayout { + match (photometric, has_alpha) { + (2 | 8 | 9, true) => ChannelLayout::Rgba, + (2 | 8 | 9, false) => ChannelLayout::Rgb, + (5, true) => ChannelLayout::CmykA, + (5, false) => ChannelLayout::Cmyk, + _ if gray_alpha => ChannelLayout::GrayA, + _ => ChannelLayout::Gray, + } +} + +/// The chunk tables must match the geometry. Checked in 64 bits, before the `tiff` crate does +/// the same arithmetic in narrower types. +fn check_chunk_tables(f: &File<'_>, dir: &Ifd, (w, h): (u32, u32), spp: u64, planar: bool, tiled: bool) -> Result<(u64, u64), CodecError> { + let need = |tag: u16, name: &str| f.tag_uint(dir, tag).ok_or_else(|| err(format!("missing or unreadable {name}"))); + let (cw, ch) = if tiled { + let tw = need(ifd::TAG_TILE_WIDTH, "TileWidth")?; + let tl = need(ifd::TAG_TILE_LENGTH, "TileLength")?; + (tw, tl) + } else { + (u64::from(w), f.tag_uint(dir, ifd::TAG_ROWS_PER_STRIP).unwrap_or(u64::from(h)).min(u64::from(h))) + }; + if cw == 0 || ch == 0 { + return Err(err("zero tile or strip size")); + } + // The chunk tables must match the geometry. Checked here, in 64 bits, before the `tiff` + // crate does the same arithmetic in narrower types. + let planes_in_file = if planar { spp } else { 1 }; + let expected = u64::from(w) + .div_ceil(cw) + .checked_mul(u64::from(h).div_ceil(ch)) + .and_then(|n| n.checked_mul(planes_in_file)) + .filter(|&n| n <= u64::from(u32::MAX)) + .ok_or_else(|| err("too many strips or tiles"))?; + let (offsets_tag, counts_tag) = if tiled { (324, 325) } else { (273, 279) }; + let counts = (dir.get(offsets_tag).map(|e| e.count), dir.get(counts_tag).map(|e| e.count)); + if counts != (Some(expected), Some(expected)) { + return Err(err(format!("{expected} strips or tiles expected, the tables list {counts:?}"))); + } + Ok((cw, ch)) +} + +/// Byte patches the `tiff` crate reads through: the directory is seen as the last of its chain, +/// and PhotometricInterpretation is handed over as black-is-zero (or RGB for Lab) when asked to. +fn header_patches( + f: &File<'_>, + dir: &Ifd, + photometric_entry: Option, + patch_photometric: bool, + lab_only: bool, +) -> Result)>, CodecError> { + let mut patches: Vec<(u64, Vec)> = Vec::new(); + let encode_u = |v: u64, len: usize| -> Vec { + let b = if f.le { v.to_le_bytes() } else { v.to_be_bytes() }; + if f.le { b.get(..len).map(<[u8]>::to_vec).unwrap_or_default() } else { b.get(8 - len..).map(<[u8]>::to_vec).unwrap_or_default() } + }; + if f.big { + patches.push((8, encode_u(dir.at, 8))); + } else { + let at = u32::try_from(dir.at).map_err(|_| err("directory offset out of range"))?; + patches.push((4, encode_u(u64::from(at), 4))); + } + // The directory is seen as the last of its chain: the chain was walked already, and a + // cycle through it must not fail this page. + patches.push((dir.next_at, vec![0; if f.big { 8 } else { 4 }])); + if patch_photometric { + let e = photometric_entry.ok_or_else(|| err("missing PhotometricInterpretation"))?; + let len = match e.ty { + 3 if e.count == 1 => 2, + 4 if e.count == 1 => 4, + _ => return Err(err("malformed PhotometricInterpretation")), + }; + patches.push((e.value_at, encode_u(if lab_only { 2 } else { 1 }, len))); + } + Ok(patches) +} + /// Decodes the pixels of one directory. fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result { // The values the `tiff` crate reads must exist: a count past the end of the file is @@ -263,59 +372,13 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result Src::Bits(bits as u8), - (1, 8) => Src::U8, - (1, 16) => Src::U16, - (1, 32) => Src::U32, - (1, 64) => Src::U64, - (3, 16) => Src::F16, - (3, 32) => Src::F32, - (3, 64) => Src::F64, - (2, _) => return Err(CodecError::unsupported(F, "signed integer samples")), - _ => return Err(CodecError::unsupported(F, format!("{bits}-bit samples (sample format {format})"))), - }; - + let (cw, ch) = check_chunk_tables(f, dir, (w, h), spp, planar, tiled)?; + let src = sample_src(format, bits)?; // WhiteIsZero and palette images are handed to the `tiff` crate as BlackIsZero: it then // returns the stored samples, and the interpretation is applied here (for every depth and // with alpha, which the crate's own inversion does not cover). let invert = photometric == 0; - let palette = if photometric == 3 { - if spp != 1 || !matches!(src, Src::Bits(_) | Src::U8 | Src::U16) { - return Err(CodecError::unsupported(F, format!("palette image with {spp} samples of {bits} bits"))); - } - let n = 1u64 << bits; - let map = dir.get(ifd::TAG_COLOR_MAP).filter(|e| e.ty == 3 && e.count == 3 * n).ok_or_else(|| err("palette image without a valid ColorMap"))?; - let at = |i: u64| f.uint(map, i).and_then(|v| u16::try_from(v).ok()); - let table: Option> = (0..n).map(|i| Some([at(i)?, at(n + i)?, at(2 * n + i)?])).collect(); - Some(table.ok_or_else(|| err("palette ColorMap cut off"))?) - } else { - None - }; + let palette = if photometric == 3 { Some(read_palette(f, dir, spp, bits, src)?) } else { None }; // CIE L*a*b*: CIELab (8; a* and b* signed) and ICCLab (9; a* and b* offset) are handed to the // `tiff` crate as RGB, then labelled Lab with a* and b* in PhotoCraft's encoding // (`convert_ab`). @@ -337,29 +400,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result color.saturating_add(usize::from(alpha_at.is_some())); let all_samples = palette.is_none() && matches!(photometric, 2 | 5 | 8 | 9) && (alpha_at.is_some_and(|a| a > 0) || (!planar && unused)); - let mut patches: Vec<(u64, Vec)> = Vec::new(); - let encode_u = |v: u64, len: usize| -> Vec { - let b = if f.le { v.to_le_bytes() } else { v.to_be_bytes() }; - if f.le { b.get(..len).map(<[u8]>::to_vec).unwrap_or_default() } else { b.get(8 - len..).map(<[u8]>::to_vec).unwrap_or_default() } - }; - if f.big { - patches.push((8, encode_u(dir.at, 8))); - } else { - let at = u32::try_from(dir.at).map_err(|_| err("directory offset out of range"))?; - patches.push((4, encode_u(u64::from(at), 4))); - } - // The directory is seen as the last of its chain: the chain was walked already, and a - // cycle through it must not fail this page. - patches.push((dir.next_at, vec![0; if f.big { 8 } else { 4 }])); - if invert || palette.is_some() || all_samples || lab { - let e = photometric_entry.ok_or_else(|| err("missing PhotometricInterpretation"))?; - let len = match e.ty { - 3 if e.count == 1 => 2, - 4 if e.count == 1 => 4, - _ => return Err(err("malformed PhotometricInterpretation")), - }; - patches.push((e.value_at, encode_u(if lab && !all_samples { 2 } else { 1 }, len))); - } + let patches = header_patches(f, dir, photometric_entry, invert || palette.is_some() || all_samples || lab, lab && !all_samples)?; let tl = { let mut l = tiff::decoder::Limits::default(); @@ -380,29 +421,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result (ChannelLayout::Gray, 1), tiff::ColorType::Multiband { num_samples, .. } if all_samples => { // Lab reads as RGB here and is relabelled below. - let layout = match photometric { - 2 | 8 | 9 => { - if alpha_at.is_some() { - ChannelLayout::Rgba - } else { - ChannelLayout::Rgb - } - } - 5 => { - if alpha_at.is_some() { - ChannelLayout::CmykA - } else { - ChannelLayout::Cmyk - } - } - _ => { - if gray_alpha { - ChannelLayout::GrayA - } else { - ChannelLayout::Gray - } - } - }; + let layout = multiband_layout(photometric, alpha_at.is_some(), gray_alpha); (layout, usize::from(num_samples)) } tiff::ColorType::Multiband { num_samples, .. } if photometric <= 1 => { diff --git a/crates/codecs/src/codecs/tiff/encode.rs b/crates/codecs/src/codecs/tiff/encode.rs index d71c32efde..a0b7539b86 100644 --- a/crates/codecs/src/codecs/tiff/encode.rs +++ b/crates/codecs/src/codecs/tiff/encode.rs @@ -1,6 +1,11 @@ use super::bands::convert_ab; use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS}; -use super::*; +use super::{ + ChannelLayout, CmykA16, CmykA32F, CodecError, Cow, EncodeOptions, ExifDirs, GrayA8, GrayA16, GrayA32F, Image, Lab8, Lab16, LabA8, LabA16, + PhotometricInterpretation, Plan, Rational, ResolutionUnit, SampleFormat, SampleType, Tag, TiffColorType, TiffCompression, TiffEncoder, TiffKind, + TiffKindBig, TiffKindStandard, TiffValue, Type, colortype, io, tiff_exif, +}; +use std::io::Cursor; // --------------------------------------------------------------------------- // Encoding diff --git a/crates/codecs/src/codecs/tiff/tags.rs b/crates/codecs/src/codecs/tiff/tags.rs index df110f777a..a41b154137 100644 --- a/crates/codecs/src/codecs/tiff/tags.rs +++ b/crates/codecs/src/codecs/tiff/tags.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Format, Tag}; pub(super) const F: Format = Format::Tiff; diff --git a/crates/codecs/src/codecs/vp8.rs b/crates/codecs/src/codecs/vp8.rs index ba75bdd3e9..a24fb727cc 100644 --- a/crates/codecs/src/codecs/vp8.rs +++ b/crates/codecs/src/codecs/vp8.rs @@ -19,7 +19,11 @@ mod transform; use bool_encoder::BoolEncoder; use predict::{Plane, SubEdges, predict_block, predict_sub}; -use tables::*; +use tables::{ + AC_QLOOKUP, B_DC_PRED, B_HE_PRED, B_PRED, B_TM_PRED, B_VE_PRED, BMODE_TREE, CAT_BASE, COEFF_BANDS, COEFF_TREE, COEFF_UPDATE_PROBS, DC_PRED, DC_QLOOKUP, + DCT_0, DCT_1, DCT_2, DCT_3, DCT_4, DCT_CAT1, DCT_CAT2, DCT_CAT3, DCT_CAT4, DCT_CAT5, DCT_CAT6, DCT_EOB, DEFAULT_COEFF_PROBS, H_PRED, KF_BMODE_PROBS, + KF_UV_MODE_PROB, KF_YMODE_PROB, KF_YMODE_TREE, PCAT, TM_PRED, UV_MODE_TREE, V_PRED, ZIGZAG, +}; use transform::{fdct, fwht, idct, iwht}; /// The largest dimension a VP8 frame header can hold (14 bits). @@ -353,6 +357,65 @@ impl<'a> Encoder<'a> { .sum() } + /// Chroma of one macroblock: one mode for both planes; returns it with the U and V blocks. + fn encode_chroma(&mut self, mbx: usize, mby: usize) -> (u8, Vec, Vec) { + let (cx0, cy0) = (mbx * 8, mby * 8); + let mut src_u = [0i32; 64]; + let mut src_v = [0i32; 64]; + for r in 0..8 { + for c in 0..8 { + src_u[r * 8 + c] = self.src_c(&self.src.u, cx0 + c, cy0 + r); + src_v[r * 8 + c] = self.src_c(&self.src.v, cx0 + c, cy0 + r); + } + } + let mut uv_mode = DC_PRED; + let mut uv_best = u64::MAX; + let mut pred_u = [0u8; 64]; + let mut pred_v = [0u8; 64]; + let mut pu = [0u8; 64]; + let mut pv = [0u8; 64]; + for mode in [DC_PRED, V_PRED, H_PRED, TM_PRED] { + predict_block(&self.rec_u, cx0, cy0, 8, mode, &mut pu); + predict_block(&self.rec_v, cx0, cy0, 8, mode, &mut pv); + let e = Self::sse(&pu, &src_u) + Self::sse(&pv, &src_v); + if e < uv_best { + uv_best = e; + uv_mode = mode; + pred_u = pu; + pred_v = pv; + } + } + let mut u_blocks = Vec::with_capacity(4); + let mut v_blocks = Vec::with_capacity(4); + for (plane_src, pred, blocks, is_u) in [(&src_u, &pred_u, &mut u_blocks, true), (&src_v, &pred_v, &mut v_blocks, false)] { + for b in 0..4 { + let mut residual = [0i32; 16]; + for r in 0..4 { + for c in 0..4 { + let i = ((b >> 1) * 4 + r) * 8 + (b & 1) * 4 + c; + residual[r * 4 + c] = plane_src[i] - i32::from(pred[i]); + } + } + let (quantized, dequantized) = Self::code_block(&residual, self.q.uv_dc, self.q.uv_ac, true); + let recon = idct(&dequantized); + let (bx, by) = (cx0 + (b & 1) * 4, cy0 + (b >> 1) * 4); + for r in 0..4 { + for c in 0..4 { + let i = ((b >> 1) * 4 + r) * 8 + (b & 1) * 4 + c; + let value = (i32::from(pred[i]) + recon[r * 4 + c]).clamp(0, 255) as u8; + if is_u { + self.rec_u.set(bx + c, by + r, value); + } else { + self.rec_v.set(bx + c, by + r, value); + } + } + } + blocks.push(Block::from_raster(&quantized, 0)); + } + } + (uv_mode, u_blocks, v_blocks) + } + // Sub-block indices address several arrays by geometry; ranges read better than iterators here. #[allow(clippy::needless_range_loop)] fn encode_macroblock(&mut self, mbx: usize, mby: usize) { @@ -476,61 +539,7 @@ impl<'a> Encoder<'a> { (best_mode, Some(Block::from_raster(&y2_q, 0)), blocks) }; - // Chroma: one mode for both planes. - let (cx0, cy0) = (mbx * 8, mby * 8); - let mut src_u = [0i32; 64]; - let mut src_v = [0i32; 64]; - for r in 0..8 { - for c in 0..8 { - src_u[r * 8 + c] = self.src_c(&self.src.u, cx0 + c, cy0 + r); - src_v[r * 8 + c] = self.src_c(&self.src.v, cx0 + c, cy0 + r); - } - } - let mut uv_mode = DC_PRED; - let mut uv_best = u64::MAX; - let mut pred_u = [0u8; 64]; - let mut pred_v = [0u8; 64]; - let mut pu = [0u8; 64]; - let mut pv = [0u8; 64]; - for mode in [DC_PRED, V_PRED, H_PRED, TM_PRED] { - predict_block(&self.rec_u, cx0, cy0, 8, mode, &mut pu); - predict_block(&self.rec_v, cx0, cy0, 8, mode, &mut pv); - let e = Self::sse(&pu, &src_u) + Self::sse(&pv, &src_v); - if e < uv_best { - uv_best = e; - uv_mode = mode; - pred_u = pu; - pred_v = pv; - } - } - let mut u_blocks = Vec::with_capacity(4); - let mut v_blocks = Vec::with_capacity(4); - for (plane_src, pred, blocks, is_u) in [(&src_u, &pred_u, &mut u_blocks, true), (&src_v, &pred_v, &mut v_blocks, false)] { - for b in 0..4 { - let mut residual = [0i32; 16]; - for r in 0..4 { - for c in 0..4 { - let i = ((b >> 1) * 4 + r) * 8 + (b & 1) * 4 + c; - residual[r * 4 + c] = plane_src[i] - i32::from(pred[i]); - } - } - let (quantized, dequantized) = Self::code_block(&residual, self.q.uv_dc, self.q.uv_ac, true); - let recon = idct(&dequantized); - let (bx, by) = (cx0 + (b & 1) * 4, cy0 + (b >> 1) * 4); - for r in 0..4 { - for c in 0..4 { - let i = ((b >> 1) * 4 + r) * 8 + (b & 1) * 4 + c; - let value = (i32::from(pred[i]) + recon[r * 4 + c]).clamp(0, 255) as u8; - if is_u { - self.rec_u.set(bx + c, by + r, value); - } else { - self.rec_v.set(bx + c, by + r, value); - } - } - } - blocks.push(Block::from_raster(&quantized, 0)); - } - } + let (uv_mode, u_blocks, v_blocks) = self.encode_chroma(mbx, mby); let skip = y2.as_ref().is_none_or(|b| !b.has_coeffs()) && y_blocks.iter().all(|b| !b.has_coeffs()) diff --git a/crates/codecs/src/codecs/vp8/predict.rs b/crates/codecs/src/codecs/vp8/predict.rs index 47319fdd7a..7ddea04238 100644 --- a/crates/codecs/src/codecs/vp8/predict.rs +++ b/crates/codecs/src/codecs/vp8/predict.rs @@ -2,7 +2,9 @@ //! sub-block modes. Predictions read the frame's *unfiltered* reconstruction, which is what the //! decoder predicts from too (the loop filter runs on the finished frame). -use super::tables::*; +#[cfg(test)] +use super::tables::{B_DC_PRED, DC_PRED}; +use super::tables::{B_HD_PRED, B_HE_PRED, B_HU_PRED, B_LD_PRED, B_RD_PRED, B_TM_PRED, B_VE_PRED, B_VL_PRED, B_VR_PRED, H_PRED, TM_PRED, V_PRED}; /// A plane of the reconstruction with the virtual border VP8 defines: the row above the frame /// reads as 127, the column left of it as 129, and the pixel above-left of the frame as 127. From f0ffcef216ef1c537bbee8f28338e410b9f0115a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 12/35] Refactor compose for strict Clippy checks --- crates/compose/src/adjust/channels.rs | 2 +- crates/compose/src/adjust/color.rs | 2 +- crates/compose/src/adjust/tone.rs | 2 +- crates/compose/src/composite.rs | 2 +- crates/compose/src/content.rs | 2 +- crates/compose/src/ctx.rs | 2 +- crates/compose/src/effects/bevel.rs | 2 +- crates/compose/src/effects/blur.rs | 2 +- crates/compose/src/effects/composite.rs | 595 +++++++++++++++--------- crates/compose/src/effects/distance.rs | 2 +- crates/compose/src/effects/paint.rs | 5 +- crates/compose/src/extents.rs | 2 +- crates/compose/src/fx_cache.rs | 2 +- crates/compose/src/reduced.rs | 2 +- crates/compose/src/render.rs | 2 +- 15 files changed, 384 insertions(+), 242 deletions(-) diff --git a/crates/compose/src/adjust/channels.rs b/crates/compose/src/adjust/channels.rs index 4b7d42b92a..2371754077 100644 --- a/crates/compose/src/adjust/channels.rs +++ b/crates/compose/src/adjust/channels.rs @@ -1,6 +1,6 @@ use super::color::{bayer4, gradient}; use super::tone::{LUT_SIZE, lut, map_rgb, modern_brightness, modern_contrast, modern_lut, posterize_in, tone_luts_depth}; -use super::*; +use super::{Adjustment, Buffer, ColorMode, LEGACY_PIVOT, SampleType, ToneSpace, Transfer, apply_depth, lab_to_srgb, rgb_to_gray, srgb_to_lab}; /// Legacy Brightness/Contrast on a 32-bit document's samples: unclipped, with contrast pivoting at /// 127 of 255 (photoshop corpus rgb32 and gray32 brightness-contrast-legacy.psd: every pixel diff --git a/crates/compose/src/adjust/color.rs b/crates/compose/src/adjust/color.rs index f47d1154f0..94a57717ce 100644 --- a/crates/compose/src/adjust/color.rs +++ b/crates/compose/src/adjust/color.rs @@ -1,5 +1,5 @@ use super::tone::LUT_SIZE; -use super::*; +use super::{D50, HueRange, SRGB_TO_XYZ_D50, SampleType, Transfer, XYZ_D50_TO_SRGB, mat3_mul, srgb_to_linear}; /// Hue/Saturation's range edits as three hue-indexed tables (hue shift in degrees, saturation and /// lightness as fractions), sampled at hue `k / (len - 1)` turns. Ranges add up where they overlap. diff --git a/crates/compose/src/adjust/tone.rs b/crates/compose/src/adjust/tone.rs index 3659748392..5debc98a83 100644 --- a/crates/compose/src/adjust/tone.rs +++ b/crates/compose/src/adjust/tone.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Adjustment, Buffer, ColorMode, CurvePoint, LevelsChannel, SampleType, ToneSpace, lab_to_srgb, srgb_to_lab}; /// Float RGB curve channels with no edit must preserve samples outside the LUT domain; edited /// ones extend past it (see [`float_tone_extrapolates`]). diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index ab5be3e67c..bc0de2ffc2 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -2,7 +2,7 @@ use super::content::{channel_weights, empty_in, recycle_buffer, render_content, use super::ctx::Ctx; use super::extents::{effects_frame, mask_k, mask_vals, shapeless_stroke_bounds}; use super::fx_cache::effect_maps; -use super::*; +use super::{BlendMode, Buffer, Fill, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split}; /// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer). pub(crate) fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index 4f9999fe6e..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::*; +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/ctx.rs b/crates/compose/src/ctx.rs index 38c150db55..f54c79865b 100644 --- a/crates/compose/src/ctx.rs +++ b/crates/compose/src/ctx.rs @@ -1,6 +1,6 @@ use super::content::empty_in; use super::fx_cache::{effect_maps, fx_over_budget, layer_identity}; -use super::*; +use super::{Buffer, Document, Layer, LayerContent, Rect, adjust, advanced, effects, pattern}; type VectorMaskSlot = std::sync::Arc>; diff --git a/crates/compose/src/effects/bevel.rs b/crates/compose/src/effects/bevel.rs index ec038d842f..6d2352622d 100644 --- a/crates/compose/src/effects/bevel.rs +++ b/crates/compose/src/effects/bevel.rs @@ -1,7 +1,7 @@ use super::blur::tent; use super::distance::{INSIDE_EPS, bevel_dists, par_fill, par_units}; use super::paint::{apply_lut, bevel_contour_lut, contour_lut, lut_at, offset, satin_lut}; -use super::*; +use super::{Bevel, BevelStyle, BevelTechnique, GlobalLight, Map, Pattern, Placement, PreparedPatterns, Rect}; /// Where a bevel's maps paint: inside the shape (with the layer), outside it (onto the /// backdrop), or both (emboss styles: maps 0–1 inside, 2–3 outside). diff --git a/crates/compose/src/effects/blur.rs b/crates/compose/src/effects/blur.rs index 686870523d..edea7285d2 100644 --- a/crates/compose/src/effects/blur.rs +++ b/crates/compose/src/effects/blur.rs @@ -1,5 +1,5 @@ use super::distance::{Metric, dist_outside_by}; -use super::*; +use super::{MAX_REACH, Map}; /// The soft falloff of an effect of `size` pixels: two box passes of width `size` (a tent), /// as Photoshop does. Fitted on psd-tools layer_effects.psd against the earlier Gaussian diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index cf6402f1ca..36dcc4a2ed 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -1,7 +1,10 @@ use super::bevel::{BevelPaint, TextureCtx, bevel_geom, bevel_maps, satin_map}; use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local_coverage, stroke_outside_exact}; use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; -use super::*; +use super::{ + BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, PreparedPatterns, Rect, + StrokePosition, psblend, +}; /// Build every effect map for `layer` from its alpha `shape` over `rect`. pub fn build_maps(layer: &Layer, shape: Vec, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps { @@ -176,230 +179,355 @@ pub(crate) fn composite_with_effects_prepared( patterns: &PreparedPatterns<'_>, vstroke: Option>, ) { - let big = content.rect; - let (w, h) = (big.width() as usize, big.height() as usize); - // The effect shape: the content's alpha (with a split-off vector stroke, `content` is the - // unmasked fill and the mask applies to fill ∪ stroke), joined with a filled shape's outline. - let kmask = |i: usize| vstroke.as_ref().and_then(|v| v.mask).and_then(|m| m.get(i)).copied().unwrap_or(1.0); - let union = |i: usize, a: f32| vstroke.as_ref().and_then(|v| v.stroke.px.get(i)).map_or(a, |s| kmask(i) * (a + s[3] * (1.0 - a))); - // Transparency Shapes Layer off: the shape is the whole layer (its masks, as the maps were - // built), and the content's own transparency acts like fill opacity within it. - let shapeless = !layer.advanced.transparency_shapes; - let shape = if shapeless { - maps.crop(&maps.shape, big, 0.0) - } else if maps.outline { - let o = maps.crop(&maps.shape, big, 0.0); - Map { w, h, v: o.v.iter().zip(&content.px).enumerate().map(|(i, (o, p))| o.max(union(i, p[3]))).collect() } - } else { - Map { w, h, v: content.px.iter().enumerate().map(|(i, p)| union(i, p[3])).collect() } - }; - let relative = shapeless || maps.outline || vstroke.is_some(); - let fx = |i: usize, k: usize| maps.crop(&maps.per[i][k], big, 0.0); - // Layer bounds (gradients aligned with the layer use the whole layer, - // independent of the render rect). - let sb = layer_bounds; - // Linked patterns tile from the effects reference point (else the layer's top-left). - let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); + let pass = EffectPass::new(layer, maps, content.rect, layer_bounds, patterns, vstroke.as_ref()); + let big = pass.big; + let shape = pass.effect_shape(content); let rect = backdrop.rect; let before = backdrop.clone(); // Exterior effects are painted on a backdrop copy extended to `big`. let mut work = Buffer::transparent(big); for y in rect.y0.max(big.y0)..rect.y1.min(big.y1) { for x in rect.x0.max(big.x0)..rect.x1.min(big.x1) { - work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] = before.get(x, y); - } - } - let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); - // Multiple instances: the first listed is on top, so paint in reverse. - let rev = || items.iter().copied().enumerate().rev(); - - for (i, e) in rev() { - if let Effect::DropShadow(s) = e { - let mut m = fx(i, 0); - if s.knocks_out { - // The layer hides the shadow beneath it where its fill is see-through (at 100 % - // fill in a normal mode it covers it anyway; at 0 % the shape shows the bare - // backdrop), and wholly in a mode that blends with it ([`shadow_see_through`]). - knock_out_exterior(&mut m, &shape, 1.0 - shadow_see_through(layer)); - } - paint_color(&mut work, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - for (i, e) in rev() { - if let Effect::OuterGlow(g) = e { - let mut m = fx(i, 0); - // The glow is behind the shape, not painted across its interior when Fill is 0 %. - // Preserve the existing anti-aliased edge when the fill is fully opaque. - knock_out_exterior(&mut m, &shape, layer.fill_opacity); - paint_glow(&mut work, &m, g, sb, anchor, big, patterns); + work.px[((y - big.y0) as usize) * pass.w + (x - big.x0) as usize] = before.get(x, y); } } + pass.paint_exterior(&mut work, &shape); // The layer: content at fill opacity, then interior effects. Interior effects are painted // relative to the layer's shape (alpha = coverage within the shape), then the shape's alpha // applies: a colour overlay at 100 % replaces the colour of a half-transparent edge pixel and // keeps its alpha, as in Photoshop. - let fill = layer.fill_opacity; - // Blend Interior Effects as Group: the interior effects (overlays, satin, inner glow) are - // combined with the content first, and fill opacity applies to the combination. - let interior_group = layer.advanced.blend_interior && fill < 1.0; - let content_fill = if interior_group { 1.0 } else { fill }; - let inside = |a: f32| a > INSIDE_EPS; - // Within an outline (or a split-off vector stroke) the content's own transparency (a fading - // gradient fill) acts like fill opacity: the effects still cover the whole shape. - let lay_alpha = |i: usize, p: &[f32; 4], a: f32| { - if !inside(a) { - 0.0 - } else if relative { - content_fill * (kmask(i) * p[3] / a).min(1.0) - } else { - content_fill - } - }; - let mut lay = Buffer { rect: big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() }; let gamma = crate::text_gamma(layer); let premerge = premerges_layer(layer); + let mut lay = pass.layer_pixels(content, &shape); if premerge { for (lp, wp) in lay.px.iter_mut().zip(&work.px) { *lp = psblend::composite_gamma(layer.blend, *wp, *lp, 1.0, gamma); } } - let rel = |m: Map| -> Map { - let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); - Map { w: m.w, h: m.h, v } - }; - let full = Map { w, h, v: shape.v.iter().map(|a| if inside(*a) { 1.0 } else { 0.0 }).collect() }; - for (_, e) in rev() { - if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e { - paint_pattern(&mut lay, &full, patterns, name, id, Placement::anchored(anchor, *link, *phase, *scale, *angle), big, common.blend, common.opacity); - } - } - for (_, e) in rev() { - if let Effect::GradientOverlay { common, gradient, .. } = e { - paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, anchor, big, common.blend, common.opacity, patterns) - } - } - for (_, e) in rev() { - if let Effect::ColorOverlay { common, color } = e { - paint_color(&mut lay, &full, rgb(color), common.blend, common.opacity); - } - } - for (i, e) in rev() { - if let Effect::Satin(s) = e { - let m = rel(fx(i, 0)); - paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - for (i, e) in rev() { - if let Effect::InnerGlow(g) = e { - paint_glow(&mut lay, &rel(fx(i, 0)), g, sb, anchor, big, patterns); - } - } - if interior_group { - for p in &mut lay.px { - p[3] *= fill.max(0.0); - } - } - for (i, e) in rev() { - if let Effect::InnerShadow(s) = e { - let m = rel(fx(i, 0)); - paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - // A stroked shape's vector stroke: Photoshop draws it above the fill's clipped layers and - // interior effects, below the stroke effect (psd-tools stroke-composite). - if let Some(vs) = &vstroke { - for (i, ((p, s), a)) in lay.px.iter_mut().zip(&vs.stroke.px).zip(&shape.v).enumerate() { - if s[3] > 0.0 && inside(*a) { - *p = psblend::composite(BlendMode::Normal, *p, [s[0], s[1], s[2], fill * (kmask(i) * s[3] / a).min(1.0)], 1.0); - } - } - } - // Strokes. Inside parts are painted over the layer (bottom instance first); outside parts - // are slid beneath it, so the first listed (top) instance is processed first. - let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect(); - let ready = !strokes.is_empty(); - let din = if ready { maps.din.as_ref().map(|a| maps.crop_vec(a, big, 0.0)).unwrap_or_default() } else { Vec::new() }; - // A stroke's outer edge picks the chamfer or the exact field by its width - // ([`stroke_outside_exact`]); both are cropped here, and only the ones a stroke needs exist. - let crop_out = |v: &Option>| v.as_ref().map(|b| maps.crop_vec(b, big, FAR)); - let (dout, dout_exact, vdout, vdout_exact) = - if ready { (crop_out(&maps.dout), crop_out(&maps.dout_exact), crop_out(&maps.vdout), crop_out(&maps.vdout_exact)) } else { (None, None, None, None) }; - let widths = stroke_widths; - // A gradient stroke aligned with the layer spans the stroke's own extent. - let frame = |st: &photocraft_doc::StrokeFx| maps.stroke_frame(st).unwrap_or(sb); - for st in strokes.iter().rev().copied() { - let (in_w, _) = widths(st); - if in_w <= 0.0 { - continue; - } - let mut m = Map::new(w, h, 0.0); - for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) { - *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; - } - paint_fx(&mut lay, &m, &st.paint, frame(st), anchor, big, st.common.blend, st.common.opacity, patterns); - } - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Inner - { - let (hi, sh) = (rel(fx(i, 0)), rel(fx(i, 1))); - paint_color(&mut lay, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut lay, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } + let strokes: Vec<&photocraft_doc::StrokeFx> = pass.items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect(); + let fields = pass.stroke_fields(!strokes.is_empty()); + pass.paint_interior(&mut lay, &shape); + pass.paint_vector_stroke(&mut lay, &shape); + pass.paint_inside_strokes(&mut lay, &shape, &strokes, &fields); + pass.paint_bevel(&mut lay, BevelPaint::Inner, Some(&shape)); // The shape's own alpha. for (p, a) in lay.px.iter_mut().zip(&shape.v) { p[3] *= a.min(1.0); } - // Shape layers without a filled outline stroke their vector outline, estimated from local - // coverage; every other layer strokes its shape. The width then picks the field. - let vector_outline = vector_shape && !maps.outline; - // Outside parts lie beneath the layer and blend onto the backdrop with their own mode. A - // higher stroke covers the ones below it (Photoshop: a Multiply stroke listed above a wider - // Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's share is its - // coverage × opacity not yet taken by strokes above; for Normal strokes this equals stacking - // them top over bottom. - if strokes.iter().any(|st| widths(st).1 > 0.0) { + pass.paint_outside_strokes(&mut work, &lay, &shape, &strokes, &fields); + pass.paint_bevel(&mut work, BevelPaint::Outer, None); + + // Layer (with interior effects) onto the exterior result, in the layer's mode. + let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; + for (wp, lp) in work.px.iter_mut().zip(&lay.px) { + if lp[3] > 0.0 { + *wp = psblend::composite_gamma(mode, *wp, *lp, 1.0, gamma); + } + } + // Emboss styles shade the composited layer (their maps cover inside and outside). Painting + // them into the layer before its (text-gamma) composite left a type layer's lit top edges up + // to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255). + pass.paint_bevel(&mut work, BevelPaint::Both, None); + pass.write_back(backdrop, &before, &work); +} + +/// `true` where the effect shape covers a pixel enough for interior effects to paint. +fn inside(a: f32) -> bool { + a > INSIDE_EPS +} + +/// An effect map as a fraction of the shape's own coverage. +fn relative_to_shape(m: Map, shape: &Map) -> Map { + let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); + Map { w: m.w, h: m.h, v } +} + +/// A stroke's distance fields, cropped to the render region; only the ones a stroke needs exist. +#[derive(Default)] +struct StrokeFields { + /// Distance inside the shape. + din: Vec, + dout: Option>, + dout_exact: Option>, + vdout: Option>, + vdout_exact: Option>, +} + +/// What compositing one layer's effects shares between its stages. +struct EffectPass<'a> { + layer: &'a Layer, + maps: &'a FxMaps, + patterns: &'a PreparedPatterns<'a>, + vstroke: Option<&'a VectorStroke<'a>>, + /// The region effects are painted over: the content's rect. + big: Rect, + w: usize, + h: usize, + /// Layer bounds (gradients aligned with the layer use the whole layer, independent of the + /// render rect). + sb: Rect, + /// Linked patterns tile from the effects reference point (else the layer's top-left). + anchor: (f64, f64), + /// The enabled effects. Multiple instances: the first listed is on top, so paint in reverse. + items: Vec<&'a Effect>, +} + +impl<'a> EffectPass<'a> { + fn new( + layer: &'a Layer, + maps: &'a FxMaps, + big: Rect, + layer_bounds: Rect, + patterns: &'a PreparedPatterns<'a>, + vstroke: Option<&'a VectorStroke<'a>>, + ) -> Self { + let sb = layer_bounds; + Self { + layer, + maps, + patterns, + vstroke, + big, + w: big.width() as usize, + h: big.height() as usize, + sb, + anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))), + items: layer.effects.items.iter().filter(|e| e.enabled()).collect(), + } + } + + /// The enabled effects with their indexes, last listed first. + fn rev(&self) -> impl Iterator + '_ { + self.items.iter().copied().enumerate().rev() + } + + /// Effect `i`'s map `k`, cropped to the region. + fn fx(&self, i: usize, k: usize) -> Map { + self.maps.crop(&self.maps.per[i][k], self.big, 0.0) + } + + /// The vector stroke's layer-mask value at pixel `i` (1 with no mask). + fn kmask(&self, i: usize) -> f32 { + self.vstroke.and_then(|v| v.mask).and_then(|m| m.get(i)).copied().unwrap_or(1.0) + } + + /// Alpha `a` of pixel `i` joined with the vector stroke's. + fn union(&self, i: usize, a: f32) -> f32 { + self.vstroke.and_then(|v| v.stroke.px.get(i)).map_or(a, |s| self.kmask(i) * (a + s[3] * (1.0 - a))) + } + + /// Within an outline (or a split-off vector stroke), or without Transparency Shapes Layer, + /// the content's own transparency acts like fill opacity: the effects still cover the whole + /// shape. + fn relative(&self) -> bool { + !self.layer.advanced.transparency_shapes || self.maps.outline || self.vstroke.is_some() + } + + /// The effect shape: the content's alpha (with a split-off vector stroke, `content` is the + /// unmasked fill and the mask applies to fill ∪ stroke), joined with a filled shape's outline. + fn effect_shape(&self, content: &Buffer) -> Map { + let (w, h, big) = (self.w, self.h, self.big); + // Transparency Shapes Layer off: the shape is the whole layer (its masks, as the maps were + // built), and the content's own transparency acts like fill opacity within it. + if !self.layer.advanced.transparency_shapes { + self.maps.crop(&self.maps.shape, big, 0.0) + } else if self.maps.outline { + let o = self.maps.crop(&self.maps.shape, big, 0.0); + Map { w, h, v: o.v.iter().zip(&content.px).enumerate().map(|(i, (o, p))| o.max(self.union(i, p[3]))).collect() } + } else { + Map { w, h, v: content.px.iter().enumerate().map(|(i, p)| self.union(i, p[3])).collect() } + } + } + + /// Paints the effects behind the layer: drop shadows, then outer glows. + fn paint_exterior(&self, work: &mut Buffer, shape: &Map) { + for (i, e) in self.rev() { + if let Effect::DropShadow(s) = e { + let mut m = self.fx(i, 0); + if s.knocks_out { + // The layer hides the shadow beneath it where its fill is see-through (at 100 % + // fill in a normal mode it covers it anyway; at 0 % the shape shows the bare + // backdrop), and wholly in a mode that blends with it ([`shadow_see_through`]). + knock_out_exterior(&mut m, shape, 1.0 - shadow_see_through(self.layer)); + } + paint_color(work, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + for (i, e) in self.rev() { + if let Effect::OuterGlow(g) = e { + let mut m = self.fx(i, 0); + // The glow is behind the shape, not painted across its interior when Fill is 0 %. + // Preserve the existing anti-aliased edge when the fill is fully opaque. + knock_out_exterior(&mut m, shape, self.layer.fill_opacity); + paint_glow(work, &m, g, self.sb, self.anchor, self.big, self.patterns); + } + } + } + + /// Blend Interior Effects as Group: the interior effects (overlays, satin, inner glow) are + /// combined with the content first, and fill opacity applies to the combination. + fn interior_group(&self) -> bool { + self.layer.advanced.blend_interior && self.layer.fill_opacity < 1.0 + } + + /// The layer's own pixels at fill opacity, with their alpha made relative to `shape`. + fn layer_pixels(&self, content: &Buffer, shape: &Map) -> Buffer { + let content_fill = if self.interior_group() { 1.0 } else { self.layer.fill_opacity }; + let relative = self.relative(); + let lay_alpha = |i: usize, p: &[f32; 4], a: f32| { + if !inside(a) { + 0.0 + } else if relative { + content_fill * (self.kmask(i) * p[3] / a).min(1.0) + } else { + content_fill + } + }; + Buffer { rect: self.big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() } + } + + /// Paints the interior effects other than strokes and bevels: overlays, satin, inner glow + /// and inner shadow. + fn paint_interior(&self, lay: &mut Buffer, shape: &Map) { + let (w, h, big, sb, anchor, patterns) = (self.w, self.h, self.big, self.sb, self.anchor, self.patterns); + let full = Map { w, h, v: shape.v.iter().map(|a| if inside(*a) { 1.0 } else { 0.0 }).collect() }; + for (_, e) in self.rev() { + if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e { + paint_pattern(lay, &full, patterns, name, id, Placement::anchored(anchor, *link, *phase, *scale, *angle), big, common.blend, common.opacity); + } + } + for (_, e) in self.rev() { + if let Effect::GradientOverlay { common, gradient, .. } = e { + paint_fx(lay, &full, &FxPaint::Gradient(gradient.clone()), sb, anchor, big, common.blend, common.opacity, patterns) + } + } + for (_, e) in self.rev() { + if let Effect::ColorOverlay { common, color } = e { + paint_color(lay, &full, rgb(color), common.blend, common.opacity); + } + } + for (i, e) in self.rev() { + if let Effect::Satin(s) = e { + let m = relative_to_shape(self.fx(i, 0), shape); + paint_color(lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + for (i, e) in self.rev() { + if let Effect::InnerGlow(g) = e { + paint_glow(lay, &relative_to_shape(self.fx(i, 0), shape), g, sb, anchor, big, patterns); + } + } + if self.interior_group() { + for p in &mut lay.px { + p[3] *= self.layer.fill_opacity.max(0.0); + } + } + for (i, e) in self.rev() { + if let Effect::InnerShadow(s) = e { + let m = relative_to_shape(self.fx(i, 0), shape); + paint_color(lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + } + + /// A stroked shape's vector stroke: Photoshop draws it above the fill's clipped layers and + /// interior effects, below the stroke effect (psd-tools stroke-composite). + fn paint_vector_stroke(&self, lay: &mut Buffer, shape: &Map) { + let Some(vs) = self.vstroke else { + return; + }; + let fill = self.layer.fill_opacity; + for (i, ((p, s), a)) in lay.px.iter_mut().zip(&vs.stroke.px).zip(&shape.v).enumerate() { + if s[3] > 0.0 && inside(*a) { + *p = psblend::composite(BlendMode::Normal, *p, [s[0], s[1], s[2], fill * (self.kmask(i) * s[3] / a).min(1.0)], 1.0); + } + } + } + + /// The distance fields the strokes need, cropped to the region; empty unless `ready` (the + /// layer has a stroke). + /// + /// A stroke's outer edge picks the chamfer or the exact field by its width + /// ([`stroke_outside_exact`]); both are cropped here, and only the ones a stroke needs exist. + fn stroke_fields(&self, ready: bool) -> StrokeFields { + if !ready { + return StrokeFields::default(); + } + let (maps, big) = (self.maps, self.big); + let crop_out = |v: &Option>| v.as_ref().map(|b| maps.crop_vec(b, big, FAR)); + StrokeFields { + din: maps.din.as_ref().map(|a| maps.crop_vec(a, big, 0.0)).unwrap_or_default(), + dout: crop_out(&maps.dout), + dout_exact: crop_out(&maps.dout_exact), + vdout: crop_out(&maps.vdout), + vdout_exact: crop_out(&maps.vdout_exact), + } + } + + /// A gradient stroke aligned with the layer spans the stroke's own extent. + fn stroke_frame(&self, st: &photocraft_doc::StrokeFx) -> Rect { + self.maps.stroke_frame(st).unwrap_or(self.sb) + } + + /// Strokes. Inside parts are painted over the layer (bottom instance first); outside parts + /// are slid beneath it, so the first listed (top) instance is processed first. + fn paint_inside_strokes(&self, lay: &mut Buffer, shape: &Map, strokes: &[&photocraft_doc::StrokeFx], fields: &StrokeFields) { + for st in strokes.iter().rev().copied() { + let (in_w, _) = stroke_widths(st); + if in_w <= 0.0 { + continue; + } + let mut m = Map::new(self.w, self.h, 0.0); + for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) { + *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; + } + paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns); + } + } + + /// Bevel and emboss effects whose paint is `kind`. Inner ones paint into the layer relative + /// to its `shape`; the others paint the maps as they are. + fn paint_bevel(&self, target: &mut Buffer, kind: BevelPaint, shape: Option<&Map>) { + for (i, e) in self.rev() { + if let Effect::BevelEmboss(b) = e + && self.maps.bevel_paint[i] == kind + { + let map = |k: usize| match shape { + Some(shape) => relative_to_shape(self.fx(i, k), shape), + None => self.fx(i, k), + }; + paint_color(target, &map(0), rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); + paint_color(target, &map(1), rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + } + } + } + + /// The outside parts of the strokes, blended onto the backdrop beneath the layer with their + /// own mode. A higher stroke covers the ones below it (Photoshop: a Multiply stroke listed + /// above a wider Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's + /// share is its coverage × opacity not yet taken by strokes above; for Normal strokes this + /// equals stacking them top over bottom. + fn paint_outside_strokes(&self, work: &mut Buffer, lay: &Buffer, shape: &Map, strokes: &[&photocraft_doc::StrokeFx], fields: &StrokeFields) { + if !strokes.iter().any(|st| stroke_widths(st).1 > 0.0) { + return; + } + let (w, h) = (self.w, self.h); let base = work.clone(); let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended let mut cover = vec![0.0f32; w * h]; for st in strokes.iter().copied() { - let (_, out_w) = widths(st); + let (_, out_w) = stroke_widths(st); if out_w <= 0.0 { continue; } - // Shape layers: Photoshop strokes the vector outline (estimated from local coverage - // for unfilled shapes); the stroke never shows through the shape's pixels. Along a - // filled shape's outline it covers the part of each edge pixel outside the path. - let exact = stroke_outside_exact(out_w); - let d: &[f32] = if vector_outline { - (if exact { vdout_exact.as_deref() } else { vdout.as_deref() }).unwrap_or_default() - } else if exact { - dout_exact.as_deref().unwrap_or_default() - } else { - dout.as_deref().unwrap_or_default() - }; - let mut share = vec![0.0f32; w * h]; - for (i, sh) in share.iter_mut().enumerate() { - let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0); - let k = - if inside(shape.v[i]) { if vector_shape && !maps.outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band }; - let mut k = k * st.common.opacity; - if st.common.blend == BlendMode::Dissolve { - let (x, y) = (i64::from(big.x0) + (i % w) as i64, i64::from(big.y0) + (i / w) as i64); - k = if k > 0.0 && dissolves_in(x, y, k) { 1.0 } else { 0.0 }; - } - *sh = k * (1.0 - cover[i]); - cover[i] += *sh; - } + let share = self.outside_share(st, out_w, shape, lay, fields, &mut cover); // The stroke blended over the backdrop at full coverage. let mut blended = base.clone(); let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() }; // The share already carries the Dissolve choice, so the paint itself composites as Normal. let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; - paint_fx(&mut blended, &ones, &st.paint, frame(st), anchor, big, paint_blend, 1.0, patterns); + paint_fx(&mut blended, &ones, &st.paint, self.stroke_frame(st), self.anchor, self.big, paint_blend, 1.0, self.patterns); for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) { if *s > 0.0 { for c in 0..3 { @@ -420,48 +548,59 @@ pub(crate) fn composite_with_effects_prepared( } } } - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Outer - { - let (hi, sh) = (fx(i, 0), fx(i, 1)); - paint_color(&mut work, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut work, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + + /// The share of each pixel an outside stroke `st` (outside width `out_w`) takes: its coverage + /// × opacity not yet taken by the strokes above, which `cover` accumulates. + fn outside_share(&self, st: &photocraft_doc::StrokeFx, out_w: f32, shape: &Map, lay: &Buffer, fields: &StrokeFields, cover: &mut [f32]) -> Vec { + let (w, big) = (self.w, self.big); + // Shape layers without a filled outline stroke their vector outline, estimated from local + // coverage; every other layer strokes its shape. The width then picks the field. + let vector_shape = matches!(self.layer.content, photocraft_doc::LayerContent::Shape(_)); + let vector_outline = vector_shape && !self.maps.outline; + // Shape layers: Photoshop strokes the vector outline (estimated from local coverage + // for unfilled shapes); the stroke never shows through the shape's pixels. Along a + // filled shape's outline it covers the part of each edge pixel outside the path. + let exact = stroke_outside_exact(out_w); + let d: &[f32] = match (vector_outline, exact) { + (true, true) => fields.vdout_exact.as_deref(), + (true, false) => fields.vdout.as_deref(), + (false, true) => fields.dout_exact.as_deref(), + (false, false) => fields.dout.as_deref(), } + .unwrap_or_default(); + let mut share = vec![0.0f32; w * self.h]; + for (i, sh) in share.iter_mut().enumerate() { + let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0); + let k = if inside(shape.v[i]) { if vector_outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band }; + let mut k = k * st.common.opacity; + if st.common.blend == BlendMode::Dissolve { + let (x, y) = (i64::from(big.x0) + (i % w) as i64, i64::from(big.y0) + (i / w) as i64); + k = if k > 0.0 && dissolves_in(x, y, k) { 1.0 } else { 0.0 }; + } + *sh = k * (1.0 - cover[i]); + cover[i] += *sh; + } + share } - // Layer (with interior effects) onto the exterior result, in the layer's mode. - let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; - for (wp, lp) in work.px.iter_mut().zip(&lay.px) { - if lp[3] > 0.0 { - *wp = psblend::composite_gamma(mode, *wp, *lp, 1.0, gamma); - } - } - // Emboss styles shade the composited layer (their maps cover inside and outside). Painting - // them into the layer before its (text-gamma) composite left a type layer's lit top edges up - // to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255). - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Both - { - paint_color(&mut work, &fx(i, 0), rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut work, &fx(i, 1), rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } - // Layer opacity applies to the whole stack. - let op = layer.opacity; - for y in rect.y0..rect.y1 { - for x in rect.x0..rect.x1 { - let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; - let a = before.px[i]; - let b = if x >= big.x0 && x < big.x1 && y >= big.y0 && y < big.y1 { work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] } else { a }; - backdrop.px[i] = if layer.blend == BlendMode::Dissolve { - // Dissolve applies layer opacity to the completed interior/exterior effect - // stack as pixel coverage, not continuous gray interpolation (#3051). - if crate::dissolve_noise(x, y) < op { b } else { a } - } else { - mix_premul(a, b, op) - }; + /// Writes the finished stack `work` into `backdrop` (over `before`) at layer opacity. + fn write_back(&self, backdrop: &mut Buffer, before: &Buffer, work: &Buffer) { + let (big, w) = (self.big, self.w); + let rect = backdrop.rect; + let op = self.layer.opacity; + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; + let a = before.px[i]; + let b = if x >= big.x0 && x < big.x1 && y >= big.y0 && y < big.y1 { work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] } else { a }; + backdrop.px[i] = if self.layer.blend == BlendMode::Dissolve { + // Dissolve applies layer opacity to the completed interior/exterior effect + // stack as pixel coverage, not continuous gray interpolation (#3051). + if crate::dissolve_noise(x, y) < op { b } else { a } + } else { + mix_premul(a, b, op) + }; + } } } } diff --git a/crates/compose/src/effects/distance.rs b/crates/compose/src/effects/distance.rs index 8581e1c821..ed92d9f973 100644 --- a/crates/compose/src/effects/distance.rs +++ b/crates/compose/src/effects/distance.rs @@ -1,4 +1,4 @@ -use super::*; +use super::Map; /// 1D squared distance transform (Felzenszwalb & Huttenlocher). fn dt1(f: &[f32], out: &mut [f32], v: &mut [usize], z: &mut [f32], near: &mut [usize]) { diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index 9b17749049..6bd78df7de 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -1,6 +1,9 @@ use super::blur::{blur, dilate}; use super::distance::{dist_inside, dist_outside}; -use super::*; +use super::{ + BlendMode, Buffer, Contour, Effect, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Map, Placement, PreparedPatterns, Rect, + Shadow, psblend, +}; pub(super) fn contour_lut(c: &Contour) -> Option> { match c { diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index c85dcd5a53..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::*; +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/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 1907a565f1..43e524d37f 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -1,7 +1,7 @@ use super::composite::texture_ctx; use super::ctx::{Ctx, PREPARE_DEPTH}; use super::extents::{effect_shape, effect_source_bounds}; -use super::*; +use super::{Layer, LayerContent, Rect, Surface, advanced, effects}; // --------------------------------------------------------------------------------------------- // Layer-effect map cache diff --git a/crates/compose/src/reduced.rs b/crates/compose/src/reduced.rs index 479bf1655f..1249df6437 100644 --- a/crates/compose/src/reduced.rs +++ b/crates/compose/src/reduced.rs @@ -1,7 +1,7 @@ use super::content::RENDER_TILE; use super::ctx::Ctx; use super::render::{band_rows_for, render, render_bands, render_tiled_with}; -use super::*; +use super::{Buffer, Document, Rect, Rgba8Image, pattern, proxy, uniform}; /// Documents above this many pixels get thumbnails from a proxy (see [`proxy`]) when that is /// faithful; smaller ones are reduced from the exact composite. diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index 33b17d25b8..b739d3f42a 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -1,7 +1,7 @@ use super::composite::composite_stack_at; use super::content::RENDER_TILE; use super::ctx::{Ctx, RenderVectorMasks, prepare_effects, prepare_tones}; -use super::*; +use super::{Buffer, Document, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, native_lab, pattern, psblend}; /// Every layer the compositor draws, groups before their children: hidden layers and everything /// inside hidden groups are left out. From af45d71447d699af9154230d9e3121c617516297 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 13/35] Refactor engine for strict Clippy checks --- 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 +- 83 files changed, 674 insertions(+), 514 deletions(-) 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. From 169bbdfa22e7efb0826af087ab6ffba670a4a592 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 14/35] Refactor format for strict Clippy checks --- crates/format/src/convert.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index 8b26f17940..a093bd10e0 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -11,7 +11,10 @@ use photocraft_doc::{ use photocraft_geom::{TILE_SIZE, TileCoord}; use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel}; -use crate::manifest::*; +use crate::manifest::{ + ChannelM, CompAppearanceM, CompStateM, ContentM, DocM, EffectsM, FillCacheM, Hash, LayerCompM, LayerM, MaskM, MetadataM, NamedPathM, PatternM, + SmartSourceM, SurfaceM, TileRef, +}; use crate::{FormatError, Result}; /// Deepest group nesting a bundle may hold — the one nesting limit every consumer of the layer From 2ed75b4ec382ccc95ae3a211cbf0f5abf98b880d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 15/35] Refactor geom for strict Clippy checks --- crates/geom/src/warp.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index 90c70cc30f..8c1320cf6a 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -836,15 +836,8 @@ impl BezierMesh { *f = f.max((1.0 - interior) * w); } // Every control point moves with the anchor it is closest to. - for j in 0..self.ny() { - for i in 0..nx { - let (ai, aj) = (((i + 1) / 3).min(cols), ((j + 1) / 3).min(rows)); - let k = share[aj * (cols + 1) + ai]; - let p = &mut self.points[j * nx + i]; - p[0] += d[0] * k; - p[1] += d[1] * k; - } - } + let ny = self.ny(); + move_control_points(&mut self.points, nx, ny, cols, rows, &share, d); // Close the gap exactly, with three groups of control points that share the work: // - the four inner points of the grabbed patch (all of it in the middle of the patch, // little near a grid line, where they barely reach the surface); @@ -1022,6 +1015,18 @@ impl BezierMesh { } } +fn move_control_points(points: &mut [[f64; 2]], nx: usize, ny: usize, cols: usize, rows: usize, shares: &[f64], delta: [f64; 2]) { + for j in 0..ny { + for i in 0..nx { + let (ai, aj) = (((i + 1) / 3).min(cols), ((j + 1) / 3).min(rows)); + let share = shares[aj * (cols + 1) + ai]; + let point = &mut points[j * nx + i]; + point[0] += delta[0] * share; + point[1] += delta[1] * share; + } + } +} + /// A complete warp: what Photoshop's `warp` descriptor stores, plus the custom mesh. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] From 6ebc0180da928646d683e244f147620cd8baba43 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 16/35] Refactor gpu for strict Clippy checks --- crates/gpu/src/batch.rs | 2 +- crates/gpu/src/cells.rs | 2 +- crates/gpu/src/convert.rs | 2 +- crates/gpu/src/encode.rs | 2 +- crates/gpu/src/fx.rs | 171 ++++++++++----------- crates/gpu/src/fx_passes.rs | 2 +- crates/gpu/src/kit.rs | 2 +- crates/gpu/src/paging.rs | 2 +- crates/gpu/src/plan/lower.rs | 2 +- crates/gpu/src/plan/planner.rs | 271 +++++++++++++++++++++++++++------ crates/gpu/src/plan/types.rs | 2 +- crates/gpu/src/readback.rs | 2 +- crates/gpu/src/setup.rs | 4 +- crates/gpu/src/textures.rs | 2 +- 14 files changed, 326 insertions(+), 142 deletions(-) diff --git a/crates/gpu/src/batch.rs b/crates/gpu/src/batch.rs index 988a580cc4..700ed8361f 100644 --- a/crates/gpu/src/batch.rs +++ b/crates/gpu/src/batch.rs @@ -1,6 +1,6 @@ use super::convert::{W, words}; use super::textures::Resident; -use super::*; +use super::{DeviceHealth, F, I, Kernel, Plan, Rect, TILE_SIZE, TileCoord, U, plan, timing}; /// The uniform record of a pass. pub(crate) fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { diff --git a/crates/gpu/src/cells.rs b/crates/gpu/src/cells.rs index 8d8a44ec97..ab3c451bed 100644 --- a/crates/gpu/src/cells.rs +++ b/crates/gpu/src/cells.rs @@ -4,7 +4,7 @@ use super::convert::{convert_tile, convert_tiles, keep_overlap, put_tiles, words use super::kit::{Bound, FrameRes, texture_group, uniform_group}; use super::paging::cell_rect; use super::textures::{CachedPattern, Cell, ChunkOut, ResKey, Resident, ResidentRef, Stats, Tex, TexKind}; -use super::*; +use super::{Arc, Compositor, DocId, HashMap, I, Kernel, Pattern, Plan, Rect, Role, Surface, TILE_SIZE, TileCoord, plan}; impl Compositor { /// Bring the pages of `cell` that `plan` samples up to date and resolve its effect maps. diff --git a/crates/gpu/src/convert.rs b/crates/gpu/src/convert.rs index 6b0a7e6f98..9dbfc81814 100644 --- a/crates/gpu/src/convert.rs +++ b/crates/gpu/src/convert.rs @@ -1,6 +1,6 @@ use super::batch::write_tile; use super::textures::{Resident, TexKind}; -use super::*; +use super::{Arc, F, HashMap, I, PixelFormat, Rect, SampleType, Surface, TILE_SIZE, Tile, TileCoord, U, fx}; /// Distinct tiles converted per parallel batch: bounds the converted bytes held at once (64 tiles /// of a 16-bit page are 32 MiB). diff --git a/crates/gpu/src/encode.rs b/crates/gpu/src/encode.rs index 037a4cc80d..cfa4bbd723 100644 --- a/crates/gpu/src/encode.rs +++ b/crates/gpu/src/encode.rs @@ -4,7 +4,7 @@ use super::convert::lut_texture; use super::kit::FrameRes; use super::paging::{OVER_BUDGET, cell_rect, first_error, grid_rect_count, grid_rects, lru_victims, scoped_work, uniform_buffer_len}; use super::textures::{ChunkOut, FxKey, ResKey, Resident, Stats}; -use super::*; +use super::{Compositor, Document, LayerId, Plan, Rect, Surface, Unsupported, plan, timing}; impl Compositor { /// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 34982cd2be..7d56fe7378 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -301,71 +301,96 @@ pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> Ma program_with(e, light, vector_shape, &[], (0.0, 0.0)) } +fn shadow_program(b: &mut B, s: &photocraft_doc::Shadow, inner: bool, light: &GlobalLight) -> usize { + let angle = if s.use_global_light { light.angle } else { s.angle }; + let (dx, dy) = offset(angle, s.distance); + let src = b.shift(In::Shape, dx, dy, if inner { 1.0 } else { 0.0 }, inner); + let (r, bw) = photocraft_compose::effects::spread_split(s.size, s.spread); + let mut m = src; + if r > 0.0 { + let f = b.field(if inner { FieldKind::ChokeInside } else { FieldKind::StrokeOutside }, r); + let d = if dx == 0.0 && dy == 0.0 { + f + } else { + b.push(stage(Kernel::MShift, Some(f), None, [dx, dy, if inner { -0.5 } else { 1e10 }, 0.0], dx.abs().max(dy.abs()) as i32)) + }; + m = b.dilate(src, d, r); + } + let m = b.blur(m, bw); + b.finish(m, None, false, &s.contour, inner, 0); + 1 +} + +fn glow_program(b: &mut B, g: &photocraft_doc::Glow, inner: bool) -> usize { + let center = inner && g.source == GlowSource::Center; + match g.technique { + GlowTechnique::Precise => { + let d = b.field(if inner { FieldKind::Inside } else { FieldKind::Outside }, g.size); + let solid = g.size * g.spread; + let soft = (g.size + 1.0 - solid).max(1e-3); + let m = b.push(stage(Kernel::MGlow, Some(d), None, [solid, soft, 0.0, 0.0], 0)); + b.finish_glow(m, photocraft_compose::effects::glow_lut(g), inner, center); + } + GlowTechnique::Softer => { + let m = softer_glow_map(b, g, inner); + b.finish_glow(m, photocraft_compose::effects::glow_lut(g), inner, center); + } + } + 1 +} + +fn softer_glow_map(b: &mut B, g: &photocraft_doc::Glow, inner: bool) -> In { + let src = if inner { b.shift(In::Shape, 0.0, 0.0, 0.0, true) } else { In::Shape }; + let (r, bw) = photocraft_compose::effects::spread_split(g.size, g.spread); + let mut map = src; + if r > 0.0 { + let distance = b.field(if inner { FieldKind::ChokeInside } else { FieldKind::StrokeOutside }, r); + map = b.dilate(src, distance, r); + } + b.blur(map, bw) +} + +fn satin_program(b: &mut B, s: &photocraft_doc::Satin) -> usize { + let (dx, dy) = offset(s.angle, photocraft_compose::effects::satin_distance(s)); + let a = b.shift(In::Shape, dx, dy, 0.0, false); + let a = b.conv(a, photocraft_compose::effects::tent_kernel(s.size)); + let c = b.shift(In::Shape, -dx, -dy, 0.0, false); + let c = b.conv(c, photocraft_compose::effects::tent_kernel(s.size)); + b.finish_lut(a, Some(c), s.invert, photocraft_compose::effects::satin_lut(&s.contour), true, 0); + 1 +} + +fn stroke_program(b: &mut B, st: &photocraft_doc::StrokeFx, vector_shape: bool) -> usize { + let (in_w, out_w) = stroke_widths(st); + if out_w > 0.0 { + let kind = match (vector_shape, photocraft_compose::effects::stroke_outside_exact(out_w)) { + (true, true) => FieldKind::StrokeOutsideVector, + (true, false) => FieldKind::StrokeOutsideVectorChamfer, + (false, true) => FieldKind::StrokeOutsideExact, + (false, false) => FieldKind::StrokeOutside, + }; + let d = b.field(kind, out_w); + let mut s = stage(Kernel::MStroke, Some(d), None, [out_w, 0.0, 0.0, 0.0], 0); + s.out = Some(0); + b.stages.push(s); + } + if in_w > 0.0 { + let d = b.field(FieldKind::StrokeInside, in_w); + let mut s = stage(Kernel::MStroke, Some(d), None, [in_w, 0.0, 0.0, 0.0], 0); + s.out = Some(1); + b.stages.push(s); + } + 2 +} + /// The map program of one enabled effect (`build_maps`); bevel textures tile `patterns` from /// `anchor` (`effects::TextureCtx`). pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { let mut b = B { stages: Vec::new(), fields: Vec::new() }; let maps = match e { - Effect::DropShadow(s) | Effect::InnerShadow(s) => { - // shadow_map - let inner = matches!(e, Effect::InnerShadow(_)); - let angle = if s.use_global_light { light.angle } else { s.angle }; - let (dx, dy) = offset(angle, s.distance); - let src = b.shift(In::Shape, dx, dy, if inner { 1.0 } else { 0.0 }, inner); - let (r, bw) = photocraft_compose::effects::spread_split(s.size, s.spread); - let mut m = src; - if r > 0.0 { - // dist_outside of the shifted map is the shifted field (integer offsets; shifted-in - // pixels are far away for a drop shadow, inside for an inner shadow). - let f = b.field(if inner { FieldKind::ChokeInside } else { FieldKind::StrokeOutside }, r); - let d = if dx == 0.0 && dy == 0.0 { - f - } else { - b.push(stage(Kernel::MShift, Some(f), None, [dx, dy, if inner { -0.5 } else { 1e10 }, 0.0], dx.abs().max(dy.abs()) as i32)) - }; - m = b.dilate(src, d, r); - } - let m = b.blur(m, bw); - b.finish(m, None, false, &s.contour, inner, 0); - 1 - } - Effect::OuterGlow(g) | Effect::InnerGlow(g) => { - // glow_map - let inner = matches!(e, Effect::InnerGlow(_)); - let center = inner && g.source == GlowSource::Center; - match g.technique { - GlowTechnique::Precise => { - let d = b.field(if inner { FieldKind::Inside } else { FieldKind::Outside }, g.size); - let solid = g.size * g.spread; - let soft = (g.size + 1.0 - solid).max(1e-3); - let m = b.push(stage(Kernel::MGlow, Some(d), None, [solid, soft, 0.0, 0.0], 0)); - b.finish_glow(m, photocraft_compose::effects::glow_lut(g), inner, center); - } - GlowTechnique::Softer => { - // Inner glows (edge, and centre as 1 - the edge result) spread 1 - alpha. - let src = if inner { b.shift(In::Shape, 0.0, 0.0, 0.0, true) } else { In::Shape }; - let (r, bw) = photocraft_compose::effects::spread_split(g.size, g.spread); - let mut m = src; - if r > 0.0 { - let d = b.field(if inner { FieldKind::ChokeInside } else { FieldKind::StrokeOutside }, r); - m = b.dilate(src, d, r); - } - let m = b.blur(m, bw); - b.finish_glow(m, photocraft_compose::effects::glow_lut(g), inner, center); - } - } - 1 - } - Effect::Satin(s) => { - // satin_map - let (dx, dy) = offset(s.angle, photocraft_compose::effects::satin_distance(s)); - let a = b.shift(In::Shape, dx, dy, 0.0, false); - let a = b.conv(a, photocraft_compose::effects::tent_kernel(s.size)); - let c = b.shift(In::Shape, -dx, -dy, 0.0, false); - let c = b.conv(c, photocraft_compose::effects::tent_kernel(s.size)); - b.finish_lut(a, Some(c), s.invert, photocraft_compose::effects::satin_lut(&s.contour), true, 0); - 1 - } + Effect::DropShadow(s) | Effect::InnerShadow(s) => shadow_program(&mut b, s, matches!(e, Effect::InnerShadow(_)), light), + Effect::OuterGlow(g) | Effect::InnerGlow(g) => glow_program(&mut b, g, matches!(e, Effect::InnerGlow(_))), + Effect::Satin(s) => satin_program(&mut b, s), Effect::BevelEmboss(bv) => { // bevel_maps: height map (tent blur of the shape, or chiselled distance ramps), then // highlight / shadow shading inside and / or outside the shape. @@ -434,31 +459,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, } out } - Effect::Stroke(st) => { - // composite_with_effects' stroke bands (maps 0 outside, 1 inside) - let (in_w, out_w) = stroke_widths(st); - if out_w > 0.0 { - // Narrow strokes keep the fitted chamfer, wide ones the exact transform (#3646); - // the CPU picks the same field by the same width (`stroke_outside_exact`). - let kind = match (vector_shape, photocraft_compose::effects::stroke_outside_exact(out_w)) { - (true, true) => FieldKind::StrokeOutsideVector, - (true, false) => FieldKind::StrokeOutsideVectorChamfer, - (false, true) => FieldKind::StrokeOutsideExact, - (false, false) => FieldKind::StrokeOutside, - }; - let d = b.field(kind, out_w); - let mut s = stage(Kernel::MStroke, Some(d), None, [out_w, 0.0, 0.0, 0.0], 0); - s.out = Some(0); - b.stages.push(s); - } - if in_w > 0.0 { - let d = b.field(FieldKind::StrokeInside, in_w); - let mut s = stage(Kernel::MStroke, Some(d), None, [in_w, 0.0, 0.0, 0.0], 0); - s.out = Some(1); - b.stages.push(s); - } - 2 - } + Effect::Stroke(st) => stroke_program(&mut b, st, vector_shape), Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::PatternOverlay { .. } => return MapProgram::empty(), }; let mut h = std::collections::hash_map::DefaultHasher::new(); diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index a549979f63..f3f5ce6da3 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -3,7 +3,7 @@ use super::consts::{MAP16, MAP32}; use super::kit::MapDraw; use super::paging::field_reaches; use super::textures::{FxEntry, FxKey, ProgState, Stats, Tex}; -use super::*; +use super::{Arc, Compositor, Document, FieldKind, HashMap, LayerContent, Rect, Unsupported, fx, plan}; impl Compositor { /// Build or update the effect maps of one layer over `region`: its whole effect region, or diff --git a/crates/gpu/src/kit.rs b/crates/gpu/src/kit.rs index 2de048a2e2..6ac1b76dc3 100644 --- a/crates/gpu/src/kit.rs +++ b/crates/gpu/src/kit.rs @@ -1,7 +1,7 @@ use super::consts::{CHUNK_UNIFORM, OP_UNIFORM, STRIDE}; use super::convert::{lut_texture, words}; use super::textures::{ResKey, ResidentRef}; -use super::*; +use super::{Arc, HashMap, I, Kernel, NonZeroU64, Rect}; /// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted). #[derive(Clone)] diff --git a/crates/gpu/src/paging.rs b/crates/gpu/src/paging.rs index c6d4b61563..b07f8e8db4 100644 --- a/crates/gpu/src/paging.rs +++ b/crates/gpu/src/paging.rs @@ -1,6 +1,6 @@ use super::consts::STRIDE; use super::textures::Cell; -use super::*; +use super::{DeviceHealth, FieldKind, HashMap, Rect, Unsupported, fx}; /// Document pixels of page cell `c`. pub(crate) fn cell_rect(c: Cell, page: u32) -> Rect { diff --git a/crates/gpu/src/plan/lower.rs b/crates/gpu/src/plan/lower.rs index 42dd17e099..a38cdde867 100644 --- a/crates/gpu/src/plan/lower.rs +++ b/crates/gpu/src/plan/lower.rs @@ -1,5 +1,5 @@ use super::types::Unsupported; -use super::*; +use super::{Adjustment, BlendMode, Fill, Gradient, Layer, LayerContent, Pattern, StrokePosition, ToneSpace, Transfer, adjust, lut3d_len}; /// Paint source of an effect. pub(super) enum Paint<'a> { diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index 27d7bf589a..88de5a81b4 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -2,7 +2,7 @@ use super::lower::{ Paint, adjustment_on_gpu, adjustment_program, check_gradient_stops, gradient_rows, placement, single_content_pass, stroke_widths, style_index, }; use super::types::{Checkpoint, DocCtx, FxLayer, Kernel, MapRef, MaskUse, Pass, Role, SurfaceRef, TexUse, Unsupported}; -use super::*; +use super::{Adjustment, BlendMode, Effect, Fill, FxPaint, Glow, Layer, LayerContent, LayerId, Plan, Rect, Slot, Surface, bounds, has_effects}; pub(super) struct Planner<'a> { passes: Vec>, @@ -29,6 +29,27 @@ enum Cov { One, } +struct EffectState<'a> { + layer: &'a Layer, + items: Vec<&'a Effect>, + rev: Vec<(usize, &'a Effect)>, + fx: usize, + content: Slot, + lay_src: Slot, + vstroke: Option, + backdrop: Slot, + w: Slot, + l: Slot, + clip: Rect, + sb: Rect, + anchor: (f64, f64), + outline: bool, + relative: bool, + vector_shape: bool, + atop: bool, + premerge: bool, +} + /// Shader flags for effect passes (keep in sync with compose.wgsl). Coverage `m` of a paint, with /// `a` the layer's alpha and `inside` = `a > 0.5/255`: /// knockout `m × (1 − a × k)` (k in `p4.w`); gate `inside ? m : 0`; rel `inside ? min(m / a, 1) : 0`; @@ -133,6 +154,28 @@ pub const INIT_OUTLINE: i32 = 7; /// `MapRef::item` of the layer's effect shape (`compose::layer_shape`) instead of an effect map. pub const SHAPE_MAP: usize = usize::MAX; +fn check_effect_gradients(items: &[&Effect]) -> Result<(), Unsupported> { + for effect in items { + let gradient = match effect { + Effect::GradientOverlay { gradient, .. } => Some(gradient), + Effect::Stroke(stroke) => match &stroke.paint { + FxPaint::Gradient(g) => Some(g), + _ => None, + }, + Effect::OuterGlow(glow) | Effect::InnerGlow(glow) => match &glow.paint { + FxPaint::Gradient(g) => Some(g), + _ => None, + }, + _ => None, + }; + if let Some(gradient) = gradient { + check_gradient_stops(&gradient.stops)?; + check_gradient_stops(&gradient.opacity_stops)?; + } + } + Ok(()) +} + impl<'a> Planner<'a> { pub(super) fn new(cx: DocCtx<'a>) -> Self { Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), cx, fx: Vec::new(), checkpoints: Vec::new(), visits: 0 } @@ -724,10 +767,11 @@ impl<'a> Planner<'a> { Ok(self.emit(p)) } - /// `composite_with_effects` (atop = false) or the clipped-layer variant of `composite_atop` - /// (atop = true: effects over the base treated as opaque, keeping the base's alpha). + /// Plans enabled layer effects in the same phase order as the CPU compositor. /// Consumes `backdrop`. fn effects(&mut self, layer: &'a Layer, clipped: &[&'a Layer], backdrop: Slot, atop: bool) -> Result { + let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + check_effect_gradients(&items)?; let canvas = self.cx.canvas; let region = bounds::effect_region(layer, canvas); let sb = photocraft_compose::paint_bounds(layer).unwrap_or_else(|| bounds::layer_bounds(layer, canvas)); @@ -792,44 +836,67 @@ impl<'a> Planner<'a> { content = self.emit(p); } - let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - for e in &items { - let gradient = match e { - Effect::GradientOverlay { gradient, .. } => Some(gradient), - Effect::Stroke(s) => match &s.paint { - FxPaint::Gradient(g) => Some(g), - _ => None, - }, - Effect::OuterGlow(g) | Effect::InnerGlow(g) => match &g.paint { - FxPaint::Gradient(g) => Some(g), - _ => None, - }, - _ => None, - }; - if let Some(g) = gradient { - check_gradient_stops(&g.stops)?; - check_gradient_stops(&g.opacity_stops)?; - } - } // Linked patterns tile from the effects reference point (else the layer's top-left). + let premerge = photocraft_compose::effects::premerges_layer(layer); let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && !outline; - let map = |item: usize, map: usize| MapRef { fx, item, map }; - let rev: Vec<(usize, &'a Effect)> = items.iter().copied().enumerate().rev().collect(); - let init = |s: &mut Self, src: Slot, b: Option, kind: i32, opacity: f32| { - let mut p = Pass::new(Kernel::FxInit, 0); - p.a = Some(src); - p.b = b; - p.adjust_kind = kind; - p.opacity = opacity; - p.clip = Some(clip); - s.emit(p) + let rev = items.iter().copied().enumerate().rev().collect(); + let mut work = EffectState { + layer, + items, + rev, + fx, + content, + lay_src, + vstroke, + backdrop, + w: backdrop, + l: lay_src, + clip, + sb, + anchor, + outline, + relative, + vector_shape, + atop, + premerge, }; + if let Some(merged) = self.effect_exterior(&mut work) { + self.release(work.content); + return Ok(merged); + } + self.effect_layer_base(&mut work); + self.effect_paints(&mut work); + self.effect_vector_stroke(&mut work); + self.effect_inside_strokes(&mut work); + self.effect_inner_bevel(&mut work); + self.effect_alpha(&mut work); + self.effect_outside_strokes(&mut work); + self.effect_outer_bevel(&mut work); + let merged = self.effect_merge(&mut work); + self.release(work.content); + Ok(self.write_back(work.backdrop, merged, work.clip)) + } + fn effect_exterior(&mut self, work: &mut EffectState<'a>) -> Option { + let layer = work.layer; + let items = work.items.clone(); + let rev = work.rev.clone(); + let fx = work.fx; + let content = work.content; + let lay_src = work.lay_src; + let backdrop = work.backdrop; + let clip = work.clip; + let sb = work.sb; + let atop = work.atop; + let relative = work.relative; + let premerge = work.premerge; + let anchor = work.anchor; + let map = |item: usize, map: usize| MapRef { fx, item, map }; // Exterior effects over the backdrop (an opaque copy of it for clipped layers). let mut w = if atop { let b = self.retain(backdrop); - init(self, b, None, INIT_OPAQUE, 1.0) + self.fx_init(clip, b, None, INIT_OPAQUE, 1.0) } else { self.retain(backdrop) }; @@ -866,7 +933,6 @@ impl<'a> Planner<'a> { // Only exterior effects (drop shadows, outer glows): nothing is painted between the // layer's colour inside its shape and the shape's alpha, so the merge derives both from // the shape (`F_LAYER_SHAPE`) instead of two passes building the layer. - let premerge = photocraft_compose::effects::premerges_layer(layer); if !relative && !premerge && items.iter().all(|e| matches!(e, Effect::DropShadow(_) | Effect::OuterGlow(_))) { let mut p = Pass::new(Kernel::FxMerge, 0); p.a = Some(w); @@ -879,16 +945,28 @@ impl<'a> Planner<'a> { p.extra[3] = photocraft_compose::text_gamma(layer); p.clip = Some(clip); let merged = self.emit(p); - self.release(content); - return Ok(self.write_back(backdrop, merged, clip)); + let merged = self.write_back(backdrop, merged, clip); + return Some(merged); } + work.w = w; + None + } + + fn effect_layer_base(&mut self, work: &mut EffectState<'a>) { + let layer = work.layer; + let content = work.content; + let lay_src = work.lay_src; + let w = work.w; + let clip = work.clip; + let relative = work.relative; + let premerge = work.premerge; // The layer: its colour at fill opacity inside its shape; interior effects are painted // relative to the shape (coverage within it), then the shape's alpha applies. let mut l = if relative { let c = self.retain(content); - init(self, lay_src, Some(c), INIT_RELATIVE, layer.fill_opacity) + self.fx_init(clip, lay_src, Some(c), INIT_RELATIVE, layer.fill_opacity) } else { - init(self, lay_src, None, INIT_INSIDE, layer.fill_opacity) + self.fx_init(clip, lay_src, None, INIT_INSIDE, layer.fill_opacity) }; // Blend Interior Effects as Group off: the layer merges in its mode first and the // interior effects paint over the result (`effects::premerges_layer`). @@ -902,6 +980,18 @@ impl<'a> Planner<'a> { p.clip = Some(clip); l = self.emit(p); } + work.l = l; + } + + fn effect_paints(&mut self, work: &mut EffectState<'a>) { + let rev = work.rev.clone(); + let fx = work.fx; + let content = work.content; + let mut l = work.l; + let clip = work.clip; + let sb = work.sb; + let anchor = work.anchor; + let map = |item: usize, map: usize| MapRef { fx, item, map }; for &(_, e) in &rev { if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) @@ -936,6 +1026,15 @@ impl<'a> Planner<'a> { l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); } } + work.l = l; + } + + fn effect_vector_stroke(&mut self, work: &mut EffectState<'a>) { + let layer = work.layer; + let content = work.content; + let mut l = work.l; + let vstroke = work.vstroke; + let clip = work.clip; if let Some(s) = vstroke { let mut p = Pass::new(Kernel::FxInit, 0); p.a = Some(l); @@ -946,6 +1045,19 @@ impl<'a> Planner<'a> { p.clip = Some(clip); l = self.emit(p); } + work.l = l; + } + + fn effect_inside_strokes(&mut self, work: &mut EffectState<'a>) { + let layer = work.layer; + let rev = work.rev.clone(); + let fx = work.fx; + let content = work.content; + let mut l = work.l; + let clip = work.clip; + let sb = work.sb; + let anchor = work.anchor; + let map = |item: usize, map: usize| MapRef { fx, item, map }; // Inside stroke parts are painted over the layer (bottom instance first). for &(i, e) in &rev { if let Effect::Stroke(st) = e { @@ -966,6 +1078,17 @@ impl<'a> Planner<'a> { } } } + work.l = l; + } + + fn effect_inner_bevel(&mut self, work: &mut EffectState<'a>) { + let rev = work.rev.clone(); + let fx = work.fx; + let content = work.content; + let mut l = work.l; + let clip = work.clip; + let sb = work.sb; + let map = |item: usize, map: usize| MapRef { fx, item, map }; let bevel_paint = |b: &photocraft_doc::Bevel| photocraft_compose::effects::bevel_geom(b).paint; for &(i, e) in &rev { if let Effect::BevelEmboss(b) = e @@ -985,9 +1108,32 @@ impl<'a> Planner<'a> { l = self.paint(l, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, F_REL, clip, sb); } } + work.l = l; + } + + fn effect_alpha(&mut self, work: &mut EffectState<'a>) { + let content = work.content; + let mut l = work.l; + let clip = work.clip; // The shape's own alpha. let c = self.retain(content); - l = init(self, l, Some(c), INIT_ALPHA, 1.0); + l = self.fx_init(clip, l, Some(c), INIT_ALPHA, 1.0); + work.l = l; + } + + fn effect_outside_strokes(&mut self, work: &mut EffectState<'a>) { + let layer = work.layer; + let items = work.items.clone(); + let fx = work.fx; + let content = work.content; + let mut w = work.w; + let l = work.l; + let clip = work.clip; + let sb = work.sb; + let anchor = work.anchor; + let outline = work.outline; + let vector_shape = work.vector_shape; + let map = |item: usize, map: usize| MapRef { fx, item, map }; // Outside stroke parts lie beneath the layer and blend onto the exterior result with their // own mode; a higher stroke covers the ones below it (each takes its coverage × opacity // not yet taken above it, blended over the result as it was before the strokes). @@ -1004,7 +1150,7 @@ impl<'a> Planner<'a> { // The layer's alpha rides along the coverage: `effects::outline_share`, and for // pixel layers the stroke's share beneath a partly covering layer (fill < 100 %). let ll = self.retain(l); - cover = Some(init(self, ll, None, INIT_COVER, 1.0)); + cover = Some(self.fx_init(clip, ll, None, INIT_COVER, 1.0)); } for (n, &(i, st)) in outs.iter().enumerate() { let paint = self.fx_paint(&st.paint, anchor); @@ -1046,6 +1192,18 @@ impl<'a> Planner<'a> { p.clip = Some(clip); w = self.emit(p); } + work.w = w; + } + + fn effect_outer_bevel(&mut self, work: &mut EffectState<'a>) { + let rev = work.rev.clone(); + let bevel_paint = |b: &photocraft_doc::Bevel| photocraft_compose::effects::bevel_geom(b).paint; + let fx = work.fx; + let content = work.content; + let mut w = work.w; + let clip = work.clip; + let sb = work.sb; + let map = |item: usize, map: usize| MapRef { fx, item, map }; for &(i, e) in &rev { if let Effect::BevelEmboss(b) = e && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Outer @@ -1066,13 +1224,30 @@ impl<'a> Planner<'a> { } } + work.w = w; + } + + fn effect_merge(&mut self, work: &mut EffectState<'a>) -> Slot { + let layer = work.layer; + let rev = work.rev.clone(); + let fx = work.fx; + let content = work.content; + let w = work.w; + let l = work.l; + let backdrop = work.backdrop; + let clip = work.clip; + let sb = work.sb; + let atop = work.atop; + let premerge = work.premerge; + let bevel_paint = |b: &photocraft_doc::Bevel| photocraft_compose::effects::bevel_geom(b).paint; + let map = |item: usize, map: usize| MapRef { fx, item, map }; let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; let late: Vec<(usize, &'a photocraft_doc::Bevel)> = rev .iter() .filter_map(|&(i, e)| if let Effect::BevelEmboss(b) = e { Some((i, b)) } else { None }) .filter(|(_, b)| bevel_paint(b) == photocraft_compose::effects::BevelPaint::Both) .collect(); - let merged = if late.is_empty() { + if late.is_empty() { let mut p = Pass::new(Kernel::FxMerge, 0); p.a = Some(w); p.b = Some(l); @@ -1110,11 +1285,17 @@ impl<'a> Planner<'a> { p.flags = if atop { F_ATOP } else { 0 } | F_NO_LAYER; p.clip = Some(clip); self.emit(p) - }; - self.release(content); + } + } - // Write the clipped result back into the backdrop (in place when nothing else holds it). - Ok(self.write_back(backdrop, merged, clip)) + fn fx_init(&mut self, clip: Rect, src: Slot, b: Option, kind: i32, opacity: f32) -> Slot { + let mut pass = Pass::new(Kernel::FxInit, 0); + pass.a = Some(src); + pass.b = b; + pass.adjust_kind = kind; + pass.opacity = opacity; + pass.clip = Some(clip); + self.emit(pass) } fn fx_paint(&self, p: &'a FxPaint, anchor: (f64, f64)) -> Paint<'a> { diff --git a/crates/gpu/src/plan/types.rs b/crates/gpu/src/plan/types.rs index e83fac8c8c..13005dbba2 100644 --- a/crates/gpu/src/plan/types.rs +++ b/crates/gpu/src/plan/types.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{BlendMode, Document, GlobalLight, Layer, LayerId, Pattern, Rect, Slot, Surface, Transfer}; /// Pipeline (fragment entry point) of a pass. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] diff --git a/crates/gpu/src/readback.rs b/crates/gpu/src/readback.rs index 14dd73a831..9abf5f071e 100644 --- a/crates/gpu/src/readback.rs +++ b/crates/gpu/src/readback.rs @@ -1,5 +1,5 @@ use super::textures::Stats; -use super::*; +use super::{Compositor, Document, Rect, Unsupported}; /// Blocking readback of a composite (native tests and tools). #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs index 30d04d872e..c5b5c90384 100644 --- a/crates/gpu/src/setup.rs +++ b/crates/gpu/src/setup.rs @@ -3,7 +3,9 @@ use super::consts::{ACC_FORMAT, CHUNK, CHUNK_UNIFORM, FX_BUDGET, MAP16, MAP32, O use super::kit::{Kit, SHADER, tex_entry, uniform_entry}; use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; use super::textures::{FxEntry, Resident, Tex, TexKind}; -use super::*; +use super::{ + Compositor, DeviceHealth, DocId, Document, Fault, HashMap, Kernel, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing, +}; impl Compositor { /// Create a compositor with the default accumulation format ([`ACC_FORMAT`]). diff --git a/crates/gpu/src/textures.rs b/crates/gpu/src/textures.rs index 1b28f61150..5b52dfefaa 100644 --- a/crates/gpu/src/textures.rs +++ b/crates/gpu/src/textures.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Arc, DocId, FieldKind, HashMap, LayerId, PixelFormat, Rect, Role, SampleType, Tile, TileCoord, fx, timing}; /// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the /// texture's origin. From 2a3135d796c0f9ace7ef6d1dc47e61a1ca847462 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 17/35] Refactor io for strict Clippy checks --- crates/io/examples/bench_abr.rs | 2 +- crates/io/examples/gen_abr_library.rs | 2 +- crates/io/examples/oracle_diff.rs | 469 ++++++------ crates/io/src/adjust_map/tests.rs | 54 +- crates/io/src/flat.rs | 27 +- crates/io/src/lib.rs | 6 +- crates/io/src/multichannel_map.rs | 6 +- crates/io/src/psd_export/document.rs | 322 ++++---- crates/io/src/psd_export/estimate.rs | 38 +- crates/io/src/psd_export/merged.rs | 4 +- crates/io/src/psd_export/resources.rs | 2 +- crates/io/src/psd_export/smart.rs | 2 +- crates/io/src/psd_export/tests.rs | 2 +- crates/io/src/psd_import.rs | 798 ++++++++++---------- crates/io/src/smart_map/export.rs | 5 +- crates/io/src/smart_map/import.rs | 53 +- crates/io/src/smart_map/placed.rs | 2 +- crates/io/src/xcf.rs | 106 +-- crates/io/tests/it/cmyk_composite_export.rs | 43 +- crates/io/tests/it/common/mod.rs | 28 +- crates/io/tests/it/tiff_layers.rs | 140 ++-- 21 files changed, 1174 insertions(+), 937 deletions(-) diff --git a/crates/io/examples/bench_abr.rs b/crates/io/examples/bench_abr.rs index 0811cb0ae8..17d4740962 100644 --- a/crates/io/examples/bench_abr.rs +++ b/crates/io/examples/bench_abr.rs @@ -62,7 +62,7 @@ fn main() { // `--write `: also save a small showcase file (procedural tips) for UI snapshots. let args: Vec = std::env::args().collect(); if let Some(path) = args.iter().position(|a| a == "--write").and_then(|i| args.get(i + 1)) { - use photocraft_paint::procedural::*; + use photocraft_paint::procedural::{charcoal_tip, leaf_tip, sponge_tip, star_tip}; let tips = [("Leafy", leaf_tip(96)), ("Charcoal Stick", charcoal_tip(96, 3)), ("Sea Sponge", sponge_tip(96, 5)), ("Star Burst", star_tip(96))]; let samples: Vec = tips .iter() diff --git a/crates/io/examples/gen_abr_library.rs b/crates/io/examples/gen_abr_library.rs index cbb2ad303c..c19e4a85d8 100644 --- a/crates/io/examples/gen_abr_library.rs +++ b/crates/io/examples/gen_abr_library.rs @@ -13,7 +13,7 @@ //! `--raw` store tips uncompressed (bigger files). Each file stays under the reader's decoded cap (1 GiB; 512 MiB on 32-bit). #![allow(clippy::unwrap_used, clippy::expect_used)] -use photocraft_paint::procedural::*; +use photocraft_paint::procedural::{bristle_tip, chalk_tip, charcoal_tip, grass_tip, leaf_tip, rake_tip, spatter_tip, sponge_tip, star_tip}; use photocraft_paint::tile::GrayTile; use photocraft_psd::abr::{AbrSample, MAX_TOTAL_BYTES, write_v6}; use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs index fddef567a9..cc4b5aa0de 100644 --- a/crates/io/examples/oracle_diff.rs +++ b/crates/io/examples/oracle_diff.rs @@ -22,9 +22,244 @@ fn main() { corpus_summary(std::path::Path::new(&path)); return; } - let bytes = std::fs::read(&path).unwrap(); + run_file(&path); +} + +fn run_file(path: &str) { + let bytes = std::fs::read(path).unwrap(); let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); - let mut imp = photocraft_io::import(&path, &bytes).unwrap(); + let mut imp = photocraft_io::import(path, &bytes).unwrap(); + configure_visibility(&mut imp.document.layers); + let doc = &imp.document; + println!("mode {:?} depth {:?} layers {} warnings {:?} light {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings, doc.global_light); + print_layer_details(doc); + dump_filter_effects(&file); + let ours = photocraft_compose::flatten(doc).px; + let merged = photocraft_io::merged_composite(&file).unwrap(); + compare_modes(doc, &ours, &merged); +} + +fn compare_modes(doc: &photocraft_doc::Document, ours: &[[f32; 4]], merged: &[[f32; 4]]) { + if std::env::args().nth(3).as_deref() == Some("png") { + write_comparison_png(doc, ours, merged); + return; + } + if std::env::args().nth(3).as_deref() == Some("dump") { + // dump prefix: raw little-endian f32 RGBA (straight) planes for offline fitting: + // prefix_ours.f32, prefix_ps.f32, prefix_L.f32 (each top-level layer's own pixels, + // masks not applied) and prefix.txt (width, height, layer names). + let out = std::env::args().nth(4).expect("prefix"); + let wr = |name: String, px: &[[f32; 4]]| { + let bytes: Vec = px.iter().flat_map(|p| p.iter().flat_map(|v| v.to_le_bytes())).collect(); + std::fs::write(name, bytes).unwrap(); + }; + wr(format!("{out}_ours.f32"), ours); + wr(format!("{out}_ps.f32"), merged); + let mut meta = format!("{} {}\n", doc.size.width, doc.size.height); + for (i, l) in doc.layers.iter().enumerate() { + let b = photocraft_compose::surface_to_buffer( + l.surface().unwrap_or(&photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8)), + doc.bounds(), + ); + wr(format!("{out}_L{i}.f32"), &b.px); + meta += &format!("{i} {}\n", l.name); + } + std::fs::write(format!("{out}.txt"), meta).unwrap(); + return; + } + if std::env::args().nth(3).as_deref() == Some("layerpx") { + // layerpx x y: each layer's own pixel (0-255). + let x: i32 = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); + let y: i32 = std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0); + for l in doc.walk() { + if let Some(s) = l.2.surface() { + println!("{:?}: {:?}", l.2.name, s.pixel(x, y).iter().map(|v| (v * 255.0 * 100.0).round() / 100.0).collect::>()); + } + } + return; + } + if std::env::args().nth(3).as_deref() == Some("grid") { + // grid x0 y0 x1 y1 [channel]: ours / photoshop values (0-255, premultiplied colour). + let w = doc.size.width as usize; + let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); + let ch: usize = std::env::args().nth(8).and_then(|s| s.parse().ok()).unwrap_or(3); + for (label, img) in [("ours", &ours), ("ps", &merged)] { + println!("{label} (channel {ch}):"); + for y in a[1]..a[3] { + let row: Vec = (a[0]..a[2]) + .map(|x| { + let p = img[y * w + x]; + let v = if ch == 3 { p[3] } else { p[ch] * p[3] }; + format!("{:4}", (v * 255.0).round()) + }) + .collect(); + println!(" y={y:4} {}", row.join("")); + } + } + return; + } + if std::env::args().nth(3).as_deref() == Some("bylayer") { + // Max error and bad-pixel count inside each layer's bounds grown by its effects' reach + // (regions overlap; a quick way to tell which layer or effect is off). + let (w, h) = (doc.size.width as i32, doc.size.height as i32); + for (_, _, l) in doc.walk() { + let Some(sf) = l.surface() else { continue }; + let cb = sf.content_bounds(); + let mut b = photocraft_geom::Rect::new(i32::MAX, i32::MAX, i32::MIN, i32::MIN); + for y in cb.y0..cb.y1 { + for x in cb.x0..cb.x1 { + let p = sf.pixel(x, y); + if p[p.len() - 1] > 0.0 { + b = photocraft_geom::Rect::new(b.x0.min(x), b.y0.min(y), b.x1.max(x + 1), b.y1.max(y + 1)); + } + } + } + if b.x0 > b.x1 { + continue; + } + let m = photocraft_compose::effects::margin(l); + let r = photocraft_geom::Rect::new((b.x0 - m).max(0), (b.y0 - m).max(0), (b.x1 + m).min(w), (b.y1 + m).min(h)); + let (mut worst, mut at, mut bad) = (0.0f32, (0, 0), 0usize); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let i = (y * w + x) as usize; + let (a, b) = (ours[i], merged[i]); + let d = (0..3).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max); + if d > 2.0 / 255.0 { + bad += 1; + } + if d > worst { + (worst, at) = (d, (x, y)); + } + } + } + let fx: Vec<&str> = l.effects.items.iter().filter(|e| e.enabled()).map(|e| e.label()).collect(); + println!("{:<32} {:>6.1} at {:?} bad {:>6} {:?} {:?}", l.name, worst * 255.0, at, bad, l.blend, fx); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("worst") { + // The N worst pixels (premultiplied max channel error), with coordinates. + let w = doc.size.width as usize; + let n: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(20); + let mut v: Vec<(f32, usize)> = ours + .iter() + .zip(merged) + .enumerate() + .map(|(i, (a, b))| ((0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max), i)) + .collect(); + v.sort_by(|a, b| b.0.total_cmp(&a.0)); + for (d, i) in v.into_iter().take(n) { + let (a, b) = (ours[i], merged[i]); + println!("({:4},{:4}) d={:5.1} ours {:?} ps {:?}", i % w, i / w, d * 255.0, a.map(|v| (v * 255.0).round()), b.map(|v| (v * 255.0).round())); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("row") { + let w = doc.size.width as usize; + let y: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); + let (x0, x1): (usize, usize) = + (std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0), std::env::args().nth(6).and_then(|s| s.parse().ok()).unwrap_or(w)); + for x in (x0..x1).step_by(((x1 - x0) / 20).max(1)) { + let (a, b) = (ours[y * w + x], merged[y * w + x]); + println!("x={x:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("solve") { + // solve layer-name x0 y0 x1 y1: per pixel the layer's content alpha `l`, its shape's path + // coverage `cov`, Photoshop's alpha `A` and the alpha `s` an effect beneath the layer + // would need (A = s + l (1 - s)) over a transparent backdrop. + let name = std::env::args().nth(4).expect("layer name"); + let a: Vec = (5..9).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); + let w = doc.size.width as usize; + let l = doc.walk().into_iter().map(|t| t.2).find(|l| l.name == name).expect("layer"); + let r = photocraft_geom::Rect::new(a[0], a[1], a[2], a[3]); + let cov = match &l.content { + photocraft_doc::LayerContent::Shape(sh) => photocraft_vector::path_coverage(&sh.path, r), + _ => vec![0.0; r.width() as usize * r.height() as usize], + }; + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let la = l.surface().map_or(0.0, |s| s.pixel(x, y)[3]); + let c = cov[((y - r.y0) * r.width() as i32 + x - r.x0) as usize]; + let p = merged[y as usize * w + x as usize]; + let o = ours[y as usize * w + x as usize]; + let s = if la < 1.0 { (p[3] - la) / (1.0 - la) } else { f32::NAN }; + println!("({x:3},{y:3}) l {la:.3} cov {c:.3} A {:.3} ours {:.3} s {s:.3} ps {:?}", p[3], o[3], p.map(|v| (v * 255.0).round())); + } + } + return; + } + if std::env::args().nth(3).as_deref() == Some("line") { + // line x0 y0 x1 y1: every pixel on the segment, straight RGBA 0-255, ours | ps. + let w = doc.size.width as usize; + let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); + let n = (a[2] - a[0]).abs().max((a[3] - a[1]).abs()).max(1); + for k in 0..=n { + let (x, y) = ((a[0] + (a[2] - a[0]) * k / n) as usize, (a[1] + (a[3] - a[1]) * k / n) as usize); + let (o, p) = (ours[y * w + x], merged[y * w + x]); + println!("({x:4},{y:4}) ours {:?} ps {:?}", o.map(|v| (v * 255.0).round()), p.map(|v| (v * 255.0).round())); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("col") { + let (w, h) = (doc.size.width as usize, doc.size.height as usize); + let x = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(w / 2); + for k in 0..=16 { + let y = ((h - 1) * k / 16).min(h - 1); + let (a, b) = (ours[y * w + x], merged[y * w + x]); + println!("y={y:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); + } + return; + } + let n = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(8usize); + for (i, (a, b)) in ours.iter().zip(merged).enumerate().take(n) { + println!("{i:4}: ours {:?}\n ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); + } +} + +fn write_comparison_png(doc: &photocraft_doc::Document, ours: &[[f32; 4]], merged: &[[f32; 4]]) { + // ours | photoshop | diff heatmap, side by side (over white). + let out = std::env::args().nth(4).expect("out.png"); + let (w, h) = (doc.size.width as usize, doc.size.height as usize); + let mut img = vec![0u8; w * 3 * h * 4]; + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + for y in 0..h { + for x in 0..w { + let (a, b) = (ours[y * w + x], merged[y * w + x]); + let over = |p: [f32; 4]| [p[0] * p[3] + 1.0 - p[3], p[1] * p[3] + 1.0 - p[3], p[2] * p[3] + 1.0 - p[3]]; + let (oa, ob) = (over(a), over(b)); + let d = (0..3).map(|c| (oa[c] - ob[c]).abs()).fold(0.0f32, f32::max); + let heat = [q((d * 4.0).min(1.0)), q((1.0 - d * 4.0).max(0.0) * 0.3), 0]; + for (k, px) in [[q(oa[0]), q(oa[1]), q(oa[2])], [q(ob[0]), q(ob[1]), q(ob[2])], heat].iter().enumerate() { + let o = (y * w * 3 + k * w + x) * 4; + img[o..o + 3].copy_from_slice(px); + img[o + 3] = 255; + } + } + } + // SCALE=n: nearest-neighbour upscale (small files). + let k: usize = std::env::var("SCALE").ok().and_then(|s| s.parse().ok()).unwrap_or(1).clamp(1, 16); + let (img, w, h) = if k > 1 { + let mut big = vec![0u8; w * 3 * k * h * k * 4]; + for y in 0..h * k { + for x in 0..w * 3 * k { + let (s, d) = (((y / k) * w * 3 + x / k) * 4, (y * w * 3 * k + x) * 4); + big[d..d + 4].copy_from_slice(&img[s..s + 4]); + } + } + (big, w * k, h * k) + } else { + (img, w, h) + }; + let image = + photocraft_codecs::Image::from_raw((w * 3) as u32, h as u32, photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8, img).unwrap(); + std::fs::write(&out, photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + println!("wrote {out}"); +} + +fn configure_visibility(layers: &mut [photocraft_doc::Layer]) { if std::env::var_os("HIDE_ADJ").is_some() { // Composite without adjustment layers (their input, for fitting transfer curves). fn hide(ls: &mut [photocraft_doc::Layer]) { @@ -37,18 +272,19 @@ fn main() { } } } - hide(&mut imp.document.layers); + hide(layers); } if let Some(keep) = std::env::var_os("ONLY") { // Hide every top-level layer but the bottom one and those named in ONLY (comma-separated). let keep = keep.to_string_lossy().to_string(); let names: Vec<&str> = keep.split(',').collect(); - for l in imp.document.layers.iter_mut().skip(1) { + for l in layers.iter_mut().skip(1) { l.visible = names.contains(&l.name.as_str()); } } - let doc = &imp.document; - println!("mode {:?} depth {:?} layers {} warnings {:?} light {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings, doc.global_light); +} + +fn print_layer_details(doc: &photocraft_doc::Document) { for l in doc.walk() { let l = l.2; println!( @@ -184,6 +420,9 @@ fn main() { } } } +} + +fn dump_filter_effects(file: &photocraft_psd::PsdFile) { if std::env::var_os("DUMP_FX").is_some() { fn walk(d: &photocraft_psd::descriptor::Descriptor, depth: usize) { for (k, v) in &d.items { @@ -219,222 +458,6 @@ fn main() { } } } - let ours = photocraft_compose::flatten(doc).px; - let merged = photocraft_io::merged_composite(&file).unwrap(); - if std::env::args().nth(3).as_deref() == Some("png") { - // ours | photoshop | diff heatmap, side by side (over white). - let out = std::env::args().nth(4).expect("out.png"); - let (w, h) = (doc.size.width as usize, doc.size.height as usize); - let mut img = vec![0u8; w * 3 * h * 4]; - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - for y in 0..h { - for x in 0..w { - let (a, b) = (ours[y * w + x], merged[y * w + x]); - let over = |p: [f32; 4]| [p[0] * p[3] + 1.0 - p[3], p[1] * p[3] + 1.0 - p[3], p[2] * p[3] + 1.0 - p[3]]; - let (oa, ob) = (over(a), over(b)); - let d = (0..3).map(|c| (oa[c] - ob[c]).abs()).fold(0.0f32, f32::max); - let heat = [q((d * 4.0).min(1.0)), q((1.0 - d * 4.0).max(0.0) * 0.3), 0]; - for (k, px) in [[q(oa[0]), q(oa[1]), q(oa[2])], [q(ob[0]), q(ob[1]), q(ob[2])], heat].iter().enumerate() { - let o = (y * w * 3 + k * w + x) * 4; - img[o..o + 3].copy_from_slice(px); - img[o + 3] = 255; - } - } - } - // SCALE=n: nearest-neighbour upscale (small files). - let k: usize = std::env::var("SCALE").ok().and_then(|s| s.parse().ok()).unwrap_or(1).clamp(1, 16); - let (img, w, h) = if k > 1 { - let mut big = vec![0u8; w * 3 * k * h * k * 4]; - for y in 0..h * k { - for x in 0..w * 3 * k { - let (s, d) = (((y / k) * w * 3 + x / k) * 4, (y * w * 3 * k + x) * 4); - big[d..d + 4].copy_from_slice(&img[s..s + 4]); - } - } - (big, w * k, h * k) - } else { - (img, w, h) - }; - let image = - photocraft_codecs::Image::from_raw((w * 3) as u32, h as u32, photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8, img) - .unwrap(); - std::fs::write(&out, photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - println!("wrote {out}"); - return; - } - if std::env::args().nth(3).as_deref() == Some("dump") { - // dump prefix: raw little-endian f32 RGBA (straight) planes for offline fitting: - // prefix_ours.f32, prefix_ps.f32, prefix_L.f32 (each top-level layer's own pixels, - // masks not applied) and prefix.txt (width, height, layer names). - let out = std::env::args().nth(4).expect("prefix"); - let wr = |name: String, px: &[[f32; 4]]| { - let bytes: Vec = px.iter().flat_map(|p| p.iter().flat_map(|v| v.to_le_bytes())).collect(); - std::fs::write(name, bytes).unwrap(); - }; - wr(format!("{out}_ours.f32"), &ours); - wr(format!("{out}_ps.f32"), &merged); - let mut meta = format!("{} {}\n", doc.size.width, doc.size.height); - for (i, l) in doc.layers.iter().enumerate() { - let b = photocraft_compose::surface_to_buffer( - l.surface().unwrap_or(&photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8)), - doc.bounds(), - ); - wr(format!("{out}_L{i}.f32"), &b.px); - meta += &format!("{i} {}\n", l.name); - } - std::fs::write(format!("{out}.txt"), meta).unwrap(); - return; - } - if std::env::args().nth(3).as_deref() == Some("layerpx") { - // layerpx x y: each layer's own pixel (0-255). - let x: i32 = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); - let y: i32 = std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0); - for l in doc.walk() { - if let Some(s) = l.2.surface() { - println!("{:?}: {:?}", l.2.name, s.pixel(x, y).iter().map(|v| (v * 255.0 * 100.0).round() / 100.0).collect::>()); - } - } - return; - } - if std::env::args().nth(3).as_deref() == Some("grid") { - // grid x0 y0 x1 y1 [channel]: ours / photoshop values (0-255, premultiplied colour). - let w = doc.size.width as usize; - let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); - let ch: usize = std::env::args().nth(8).and_then(|s| s.parse().ok()).unwrap_or(3); - for (label, img) in [("ours", &ours), ("ps", &merged)] { - println!("{label} (channel {ch}):"); - for y in a[1]..a[3] { - let row: Vec = (a[0]..a[2]) - .map(|x| { - let p = img[y * w + x]; - let v = if ch == 3 { p[3] } else { p[ch] * p[3] }; - format!("{:4}", (v * 255.0).round()) - }) - .collect(); - println!(" y={y:4} {}", row.join("")); - } - } - return; - } - if std::env::args().nth(3).as_deref() == Some("bylayer") { - // Max error and bad-pixel count inside each layer's bounds grown by its effects' reach - // (regions overlap; a quick way to tell which layer or effect is off). - let (w, h) = (doc.size.width as i32, doc.size.height as i32); - for (_, _, l) in doc.walk() { - let Some(sf) = l.surface() else { continue }; - let cb = sf.content_bounds(); - let mut b = photocraft_geom::Rect::new(i32::MAX, i32::MAX, i32::MIN, i32::MIN); - for y in cb.y0..cb.y1 { - for x in cb.x0..cb.x1 { - let p = sf.pixel(x, y); - if p[p.len() - 1] > 0.0 { - b = photocraft_geom::Rect::new(b.x0.min(x), b.y0.min(y), b.x1.max(x + 1), b.y1.max(y + 1)); - } - } - } - if b.x0 > b.x1 { - continue; - } - let m = photocraft_compose::effects::margin(l); - let r = photocraft_geom::Rect::new((b.x0 - m).max(0), (b.y0 - m).max(0), (b.x1 + m).min(w), (b.y1 + m).min(h)); - let (mut worst, mut at, mut bad) = (0.0f32, (0, 0), 0usize); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let i = (y * w + x) as usize; - let (a, b) = (ours[i], merged[i]); - let d = (0..3).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max); - if d > 2.0 / 255.0 { - bad += 1; - } - if d > worst { - (worst, at) = (d, (x, y)); - } - } - } - let fx: Vec<&str> = l.effects.items.iter().filter(|e| e.enabled()).map(|e| e.label()).collect(); - println!("{:<32} {:>6.1} at {:?} bad {:>6} {:?} {:?}", l.name, worst * 255.0, at, bad, l.blend, fx); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("worst") { - // The N worst pixels (premultiplied max channel error), with coordinates. - let w = doc.size.width as usize; - let n: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(20); - let mut v: Vec<(f32, usize)> = ours - .iter() - .zip(&merged) - .enumerate() - .map(|(i, (a, b))| ((0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max), i)) - .collect(); - v.sort_by(|a, b| b.0.total_cmp(&a.0)); - for (d, i) in v.into_iter().take(n) { - let (a, b) = (ours[i], merged[i]); - println!("({:4},{:4}) d={:5.1} ours {:?} ps {:?}", i % w, i / w, d * 255.0, a.map(|v| (v * 255.0).round()), b.map(|v| (v * 255.0).round())); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("row") { - let w = doc.size.width as usize; - let y: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); - let (x0, x1): (usize, usize) = - (std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0), std::env::args().nth(6).and_then(|s| s.parse().ok()).unwrap_or(w)); - for x in (x0..x1).step_by(((x1 - x0) / 20).max(1)) { - let (a, b) = (ours[y * w + x], merged[y * w + x]); - println!("x={x:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("solve") { - // solve layer-name x0 y0 x1 y1: per pixel the layer's content alpha `l`, its shape's path - // coverage `cov`, Photoshop's alpha `A` and the alpha `s` an effect beneath the layer - // would need (A = s + l (1 - s)) over a transparent backdrop. - let name = std::env::args().nth(4).expect("layer name"); - let a: Vec = (5..9).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); - let w = doc.size.width as usize; - let l = doc.walk().into_iter().map(|t| t.2).find(|l| l.name == name).expect("layer"); - let r = photocraft_geom::Rect::new(a[0], a[1], a[2], a[3]); - let cov = match &l.content { - photocraft_doc::LayerContent::Shape(sh) => photocraft_vector::path_coverage(&sh.path, r), - _ => vec![0.0; r.width() as usize * r.height() as usize], - }; - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let la = l.surface().map_or(0.0, |s| s.pixel(x, y)[3]); - let c = cov[((y - r.y0) * r.width() as i32 + x - r.x0) as usize]; - let p = merged[y as usize * w + x as usize]; - let o = ours[y as usize * w + x as usize]; - let s = if la < 1.0 { (p[3] - la) / (1.0 - la) } else { f32::NAN }; - println!("({x:3},{y:3}) l {la:.3} cov {c:.3} A {:.3} ours {:.3} s {s:.3} ps {:?}", p[3], o[3], p.map(|v| (v * 255.0).round())); - } - } - return; - } - if std::env::args().nth(3).as_deref() == Some("line") { - // line x0 y0 x1 y1: every pixel on the segment, straight RGBA 0-255, ours | ps. - let w = doc.size.width as usize; - let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); - let n = (a[2] - a[0]).abs().max((a[3] - a[1]).abs()).max(1); - for k in 0..=n { - let (x, y) = ((a[0] + (a[2] - a[0]) * k / n) as usize, (a[1] + (a[3] - a[1]) * k / n) as usize); - let (o, p) = (ours[y * w + x], merged[y * w + x]); - println!("({x:4},{y:4}) ours {:?} ps {:?}", o.map(|v| (v * 255.0).round()), p.map(|v| (v * 255.0).round())); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("col") { - let (w, h) = (doc.size.width as usize, doc.size.height as usize); - let x = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(w / 2); - for k in 0..=16 { - let y = ((h - 1) * k / 16).min(h - 1); - let (a, b) = (ours[y * w + x], merged[y * w + x]); - println!("y={y:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); - } - return; - } - let n = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(8usize); - for (i, (a, b)) in ours.iter().zip(&merged).enumerate().take(n) { - println!("{i:4}: ours {:?}\n ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); - } } /// The corpus oracle table (as `tests/it/corpus.rs`), files in parallel, without a test build. @@ -467,7 +490,7 @@ fn corpus_summary(root: &std::path::Path) { let ours = photocraft_compose::flatten(&imp.document).px; let mut m = 0.0f32; let mut bad = 0usize; - for (a, b) in ours.iter().zip(&merged) { + for (a, b) in ours.iter().zip(merged) { let d = (0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max); m = m.max(d); if (0..4).any(|c| (a[c] * a[3] - b[c] * b[3]).abs() > TOL) { diff --git a/crates/io/src/adjust_map/tests.rs b/crates/io/src/adjust_map/tests.rs index 62236782d7..c369327d86 100644 --- a/crates/io/src/adjust_map/tests.rs +++ b/crates/io/src/adjust_map/tests.rs @@ -425,25 +425,43 @@ fn color_lookup_default_domains_stay_supported() { #[test] fn malformed_falls_back_to_unsupported() { - assert!(matches!(parse(b"levl", &[0, 2, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"curv", &[0, 0, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"thrs", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"blnc", &[0; 18], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"vibA", &[0, 0, 0, 15, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"blwh", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"mixr", &[0, 2, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // A CMYK mixer (black source used) stays raw in CMYK documents; our own RGB layout maps. + malformed_adjustments_are_unsupported(); + malformed_channel_mixers_are_unsupported(); + malformed_photo_filters_are_unsupported(); + arbitrary_adjustment_bytes_do_not_panic(); +} + +fn malformed_adjustments_are_unsupported() { + for (key, bytes) in [ + (&b"levl"[..], &[0, 2, 1][..]), + (&b"curv"[..], &[0, 0, 9][..]), + (&b"thrs"[..], &[][..]), + (&b"blnc"[..], &[0; 18][..]), + (&b"vibA"[..], &[0, 0, 0, 15, 0][..]), + (&b"blwh"[..], &[][..]), + (&b"mixr"[..], &[0, 2, 0, 0][..]), + ] { + let key: &[u8; 4] = key.try_into().unwrap_or(b"????"); + assert!(matches!(parse(key, bytes, None, Channels::Rgb), Adjustment::Unsupported { .. }), "{key:?}"); + } +} + +fn malformed_channel_mixers_are_unsupported() { let mut cmyk = i16s(&[1, 0]); for r in 0..4 { cmyk.extend(i16s(&std::array::from_fn::(|k| if k == r { 100 } else { 0 }))); } - assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Cmyk), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Other), Adjustment::Unsupported { .. })); + for channels in [Channels::Cmyk, Channels::Other] { + assert!(matches!(parse(b"mixr", &cmyk, None, channels), Adjustment::Unsupported { .. })); + } let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false }); - assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Cmyk), Adjustment::ChannelMixer { .. })); - assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Other), Adjustment::ChannelMixer { .. })); + for channels in [Channels::Cmyk, Channels::Other] { + assert!(matches!(parse(b"mixr", &ours[0].1, None, channels), Adjustment::ChannelMixer { .. })); + } assert!(matches!(parse(b"mixr", &[0, 1, 0, 0, 0, 100], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Photo Filter: unknown version, HSB colour space, out-of-range version-3 XYZ, truncated. +} + +fn malformed_photo_filters_are_unsupported() { assert!(matches!(parse(b"phfl", &[0, 4, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); assert!(matches!(parse(b"phfl", &[0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); for bad in [[200_000u32, 0, 0], [0, u32::MAX, 0]] { @@ -455,12 +473,14 @@ fn malformed_falls_back_to_unsupported() { assert!(matches!(parse(b"phfl", &xyz, None, Channels::Rgb), Adjustment::Unsupported { .. })); } assert!(matches!(parse(b"phfl", &[0, 2, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Arbitrary bytes never panic, whatever the key. +} + +fn arbitrary_adjustment_bytes_do_not_panic() { for key in ADJUSTMENT_KEYS { for len in 0..64usize { - let d: Vec = (0..len).map(|i| (i * 37 + len) as u8).collect(); - let _ = parse(key, &d, Some(&d), Channels::Rgb); - let _ = parse(key, &d, None, Channels::Other); + let data: Vec = (0..len).map(|i| (i * 37 + len) as u8).collect(); + let _ = parse(key, &data, Some(&data), Channels::Rgb); + let _ = parse(key, &data, None, Channels::Other); } } } diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 55f602a6e9..fd1ec54cf3 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -11,7 +11,32 @@ use photocraft_raster::Surface; use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed}; /// Bytes per band when converting or exporting a band of rows at a time. -const BAND_BYTES: usize = 32 << 20; +pub const BAND_BYTES: usize = 32 << 20; + +/// Row ranges for bands covering a layer region, aligned to tile rows. +#[allow(dead_code)] +pub fn band_rows(top: i32, h: usize, row_bytes: usize) -> Vec<(usize, usize)> { + const MAX_BAND_BYTES: usize = 32 << 20; + let _top = top.max(0) as usize; + let row_bytes = row_bytes.max(1); + let h_rows = h; + let mut bands = Vec::new(); + let mut cursor = 0_usize; + while cursor < h_rows { + let remaining = h_rows - cursor; + let max_by_bytes = MAX_BAND_BYTES / row_bytes; + let candidate = std::cmp::max(1, std::cmp::min(remaining, max_by_bytes)); + let band_rows = if cursor == 0 || cursor.is_multiple_of(TILE_SIZE as usize) { + candidate + } else { + let tile_boundary = (TILE_SIZE as usize) - (cursor % (TILE_SIZE as usize)); + std::cmp::min(candidate, tile_boundary) + }; + bands.push((cursor, cursor + band_rows)); + cursor += band_rows; + } + bands +} /// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens /// layered (see [`crate::tiff_layers`]). diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 612cd6dd3b..77beb6cde2 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -84,8 +84,8 @@ use photocraft_psd::{PsdError, PsdFile}; pub use adjust_map::ADJUSTMENT_KEYS; pub use flat::{ - DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, document_to_image, file_encoding, import_gif_frames, import_tiff_page, import_webp_frames, - tga_alpha_channel_to_transparency, tga_default_bits, + BAND_BYTES, DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, band_rows, document_to_image, file_encoding, import_gif_frames, import_tiff_page, + import_webp_frames, tga_alpha_channel_to_transparency, tga_default_bits, }; pub use psd_export::{PsdExportOptions, document_to_psd, document_to_psd_with}; pub use psd_import::{psd_to_document, psd_to_document_with}; @@ -404,7 +404,7 @@ fn import_psd( // The file became unreadable while its layers were read from it (`import_file_for_open_with`): // the open fails, rather than opening with those layers empty. if let Some(e) = read_error { - return Err(IoError::Read(e)); + return Err(IoError::Read(e.to_string())); } *damaged = psd_damaged; document.name = name.to_string(); diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index 441e2295a9..2b6f4b9b54 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -196,8 +196,10 @@ pub(crate) fn layerless_file( image_data, write_as_psb: false, }; - if let Some(limit) = size_limit { - warnings.extend(crate::psd_export::fit_psd_size(&mut file, limit)); + if let Some(limit) = size_limit + && let Some(warning) = crate::psd_export::fit_psd_size(&mut file, limit) + { + warnings.push(warning); } crate::psd_export::sign_global_blocks(&mut file); file diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index 396d830423..c9e68fd028 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -1,8 +1,13 @@ +use super::PSD_MAX_FILE_SIZE; use super::estimate::{MERGED_RENDERED, MERGED_WEIGHT, fit_psd_size, psd_version, sign_global_blocks}; use super::merged::{cmyk_of, merged_planes, placeholder_planes}; use super::resources::{global_block, guides_resource, keep_imported_resource, legacy_name, pascal_names_resource, path_resources, unicode_names_resource}; use super::smart::{SmartOut, link_group_resource}; -use super::*; +use super::{ + ColorMode, Compression, Document, Ex, GlobalLayerMask, Header, ImageData, ImageResource, Interrupt, LayerContent, LayerInfo, LayerInfoPlacement, + MaskParameters, PixelFormat, PsdExportOptions, PsdFile, PsdMode, ResolutionInfo, SampleType, TaggedBlock, deinterleave, ids, psd_background, psd_depth, + psd_mode, q255, version_info_resource, +}; /// Converts a document to a PSD file model (see [`document_to_psd_with`]). pub fn document_to_psd(doc: &Document) -> PsdFile { @@ -13,14 +18,14 @@ pub fn document_to_psd(doc: &Document) -> PsdFile { /// anything that could not be represented. The merged composite is rendered /// with `photocraft_compose::flatten`. pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, &Interrupt::NONE) + document_to_psd_sized(doc, opts, 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE) } /// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after /// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops /// early and returns an **incomplete** model: callers check `ctl` and discard it. pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, ctl) + document_to_psd_sized(doc, opts, 0, ctl, PSD_MAX_FILE_SIZE) } /// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. @@ -28,9 +33,8 @@ pub(super) fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, de document_to_psd_sized(doc, opts, depth, ctl, PSD_MAX_FILE_SIZE) } -/// [`document_to_psd_nested`] with the largest file kept as PSD (lowered by tests). +/// Export with a caller-selected PSD size limit; the test suite lowers it to exercise promotion. pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt, size_limit: u64) -> (PsdFile, Vec) { - // Without `size_limit_psb` the encoded size never changes the version, in every mode. let layerless_limit = opts.size_limit_psb.then_some(size_limit); if doc.mode == ColorMode::Multichannel { return crate::multichannel_map::document_to_psd(doc, opts.force_psb, layerless_limit); @@ -39,6 +43,17 @@ pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, dep return file; } let fmt = doc.pixel_format(); + export_supported_document(doc, opts, depth, ctl, fmt, size_limit) +} + +fn export_supported_document( + doc: &Document, + opts: &PsdExportOptions, + depth: u32, + ctl: &Interrupt, + fmt: PixelFormat, + size_limit: u64, +) -> (PsdFile, Vec) { // A Duotone is written over its grey plate with its inks: the block it was imported with, // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop // has only 8-bit Duotone: it refuses to open a 16-bit one. @@ -74,70 +89,8 @@ pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, dep patterns: doc.patterns.clone(), background: psd_background(doc), }; - if big && !opts.force_psb { - ex.warnings.push("document exceeds 30000 px; written as PSB".into()); - } - if fmt.mode != doc.mode && duotone_inks.is_none() { - ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); - } - // Assign layer ids up front (stable across round trips): keep unique - // `psd_id`s, number the rest after them; dividers come after all. - { - let walk = doc.walk(); - let mut used = std::collections::HashSet::new(); - for (_, _, l) in &walk { - if let Some(id) = l.psd_id - && used.insert(id) - { - ex.layer_ids.insert(l.id, id); - } - } - let mut next = 1u32; - for (_, _, l) in &walk { - if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { - while used.contains(&next) { - next += 1; - } - used.insert(next); - e.insert(next); - } - } - ex.next_id = used.iter().copied().max().unwrap_or(0); - ex.used_ids = used; - // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the - // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — - // and new layers get numbers past every kept one and every object in the file's `Txt2`. - // Kept numbers are claimed first: a layer added below others must not take a number a - // layer above it keeps, or each of those would be renumbered onto its neighbour's object - // and take its style (#7773); nor may it land on a deleted layer's object. - let mut used_txt = std::collections::HashSet::new(); - ex.text_index = Default::default(); - let mut fresh = Vec::new(); - for (_, _, l) in &walk { - let LayerContent::Text(t) = &l.content else { - continue; - }; - match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { - Some(i) if used_txt.insert(i) => { - ex.text_index.insert(l.id, i); - } - _ => fresh.push(l.id), - } - } - let objects = - doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); - let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); - if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { - next_txt = 0; - } - for id in fresh { - while used_txt.contains(&next_txt) { - next_txt += 1; - } - used_txt.insert(next_txt); - ex.text_index.insert(id, next_txt); - } - } + add_format_warnings(doc, opts, fmt, big, duotone_inks.is_some(), &mut ex.warnings); + index_layer_ids_and_text(doc, &mut ex); // Progress: one unit per layer record, then the merged composite (#3389). let records = doc.walk().len() as f32; let units = records + MERGED_WEIGHT; @@ -150,66 +103,11 @@ pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, dep }; let space = photocraft_compose::cmyk_space(doc); photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); + drop(tick); + ctl.progress(layers_share); - // Without Maximize Compatibility the merged image is a white placeholder and the composite - // isn't rendered at all. A document without layer records keeps the real image: its pixels - // live nowhere else. So does a Duotone: it opens flattened from that image (its layer records - // are not read back). - let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone_inks.is_some(); - let (mut planes, has_alpha) = if real_merged { - // Merged composite, rendered and encoded in bands (no full-size float composite). Matting - // against white only changes pixels with alpha < 1; if some are slightly translucent but - // all round to opaque (so no alpha channel is written), encode once more without the matte. - let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; - let (mut planes, has_alpha, translucent) = - crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl)); - if !has_alpha && translucent && opts.merged_matte { - planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; - } - (planes, has_alpha) - } else { - (placeholder_planes(doc, &fmt), false) - }; - let n = doc.size.area() as usize; - if !has_alpha { - planes.truncate(cc * n * sample.bytes()); - } - let canvas = doc.bounds(); - let max_extra = 56 - cc - usize::from(has_alpha); - if doc.channels.len() > max_extra { - ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); - } - let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); - // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by - // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does. - let quick_mask_id = match &doc.quick_mask { - Some(q) if extra.len() < max_extra => { - extra.push(q); - Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) - } - Some(_) => { - ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); - None - } - None => None, - }; - for a in &extra { - let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() }; - let mut bytes = s.to_interleaved(canvas); - // Spot ink as Photoshop stores it (0 = solid); an alpha channel stays straight. - if a.spot.is_some() { - crate::channel_map::photoshop_spot_plane(&mut bytes, sample); - } - planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); - } - let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; - let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) }; - let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); - let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; - let image_data = ImageData::encode(mcomp, &planes, &header) - .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData::new(Compression::Raw, planes)); - ctl.progress(1.0); + let merged = prepare_merged_planes(doc, &mut ex, opts, ctl, fmt, duotone_inks.is_some(), layers_share); + let MergedExport { header, image_data, extra, has_alpha, quick_mask_id, real_merged } = merged; // Resources. let mut resources = vec![ @@ -285,7 +183,6 @@ pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, dep if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { continue; } - // The signature follows the final version (see `sign_global_blocks`). let block = global_block(sig, key, &data); // A kept merged-transparency marker describes the opened file's composite. Over an opaque // one it would make the first alpha channel read back as the transparency, and vanish. @@ -379,13 +276,176 @@ pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, dep image_data, write_as_psb: false, }; - if opts.size_limit_psb { - ex.warnings.extend(fit_psd_size(&mut file, size_limit)); + if opts.size_limit_psb + && let Some(warning) = fit_psd_size(&mut file, size_limit) + { + ex.warnings.push(warning); } sign_global_blocks(&mut file); (file, ex.warnings) } +fn add_format_warnings(doc: &Document, opts: &PsdExportOptions, fmt: PixelFormat, big: bool, has_duotone: bool, warnings: &mut Vec) { + if big && !opts.force_psb { + warnings.push("document exceeds 30000 px; written as PSB".into()); + } + if fmt.mode != doc.mode && !has_duotone { + warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); + } +} + +struct MergedExport<'a> { + header: Header, + image_data: ImageData, + extra: Vec<&'a photocraft_doc::AlphaChannel>, + has_alpha: bool, + quick_mask_id: Option, + real_merged: bool, +} + +fn prepare_merged_planes<'a>( + doc: &'a Document, + ex: &mut Ex, + opts: &PsdExportOptions, + ctl: &Interrupt, + fmt: PixelFormat, + duotone: bool, + layers_share: f32, +) -> MergedExport<'a> { + let sample = fmt.sample; + let cc = fmt.mode.color_channels(); + let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone; + let (mut planes, has_alpha) = merged_image(doc, opts, ctl, &fmt, real_merged, layers_share); + if !has_alpha { + planes.truncate(cc * doc.size.area() as usize * sample.bytes()); + } + let (extra, quick_mask_id) = append_extra_channels(doc, ex, &mut planes, has_alpha, sample); + let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; + let mode = if duotone { PsdMode::Duotone } else { psd_mode(fmt.mode) }; + let header = Header::new(ex.version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); + let compression = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; + let image_data = ImageData::encode(compression, &planes, &header).or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)).unwrap_or(ImageData { + compression: Compression::Raw, + data: planes, + stored: None, + }); + ctl.progress(1.0); + MergedExport { header, image_data, extra, has_alpha, quick_mask_id, real_merged } +} + +fn append_extra_channels<'a>( + doc: &'a Document, + ex: &mut Ex, + planes: &mut Vec, + has_alpha: bool, + sample: SampleType, +) -> (Vec<&'a photocraft_doc::AlphaChannel>, Option) { + let cc = ex.cc; + let max_extra = 56 - cc - usize::from(has_alpha); + if doc.channels.len() > max_extra { + ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); + } + let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); + let quick_mask_id = match &doc.quick_mask { + Some(q) if extra.len() < max_extra => { + extra.push(q); + Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) + } + Some(_) => { + ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); + None + } + None => None, + }; + let canvas = doc.bounds(); + for channel in &extra { + let surface = if channel.surface.format() != ex.mask_fmt { channel.surface.convert(ex.mask_fmt) } else { channel.surface.clone() }; + let mut bytes = surface.to_interleaved(canvas); + if channel.spot.is_some() { + crate::channel_map::photoshop_spot_plane(&mut bytes, sample); + } + planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); + } + (extra, quick_mask_id) +} + +fn merged_image(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt, fmt: &PixelFormat, real_merged: bool, layers_share: f32) -> (Vec, bool) { + if !real_merged { + return (placeholder_planes(doc, fmt), false); + } + // Merged composite, rendered and encoded in bands (no full-size float composite). Matting + // against white only changes pixels with alpha < 1; if some are slightly translucent but + // all round to opaque (so no alpha channel is written), encode once more without the matte. + let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; + let (mut planes, has_alpha, translucent) = + crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, fmt, cmyk_of(fmt), opts.merged_matte, ctl)); + if !has_alpha && translucent && opts.merged_matte { + planes = merged_planes(doc, fmt, cmyk_of(fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; + } + (planes, has_alpha) +} + +fn index_layer_ids_and_text(doc: &Document, ex: &mut Ex) { + // Assign layer ids up front (stable across round trips): keep unique + // `psd_id`s, number the rest after them; dividers come after all. + { + let walk = doc.walk(); + let mut used = std::collections::HashSet::new(); + for (_, _, l) in &walk { + if let Some(id) = l.psd_id + && used.insert(id) + { + ex.layer_ids.insert(l.id, id); + } + } + let mut next = 1u32; + for (_, _, l) in &walk { + if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { + while used.contains(&next) { + next += 1; + } + used.insert(next); + e.insert(next); + } + } + ex.next_id = used.iter().copied().max().unwrap_or(0); + ex.used_ids = used; + // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the + // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — + // and new layers get numbers past every kept one and every object in the file's `Txt2`. + // Kept numbers are claimed first: a layer added below others must not take a number a + // layer above it keeps, or each of those would be renumbered onto its neighbour's object + // and take its style (#7773); nor may it land on a deleted layer's object. + let mut used_txt = std::collections::HashSet::new(); + ex.text_index = Default::default(); + let mut fresh = Vec::new(); + for (_, _, l) in &walk { + let LayerContent::Text(t) = &l.content else { + continue; + }; + match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { + Some(i) if used_txt.insert(i) => { + ex.text_index.insert(l.id, i); + } + _ => fresh.push(l.id), + } + } + let objects = + doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); + let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); + if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { + next_txt = 0; + } + for id in fresh { + while used_txt.contains(&next_txt) { + next_txt += 1; + } + used_txt.insert(next_txt); + ex.text_index.insert(id, next_txt); + } + } +} + /// PSD mask parameters for a user mask's and a vector mask's (density, feather); `None` when /// every value is the default (density 1, feather 0). pub(super) fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Option { diff --git a/crates/io/src/psd_export/estimate.rs b/crates/io/src/psd_export/estimate.rs index 1f9250678b..e93e7827fc 100644 --- a/crates/io/src/psd_export/estimate.rs +++ b/crates/io/src/psd_export/estimate.rs @@ -1,19 +1,10 @@ -use super::*; - -/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it -/// (all layers composited) and encoding its planes cost about two full-canvas layers. -pub(super) const MERGED_WEIGHT: f32 = 2.0; - -/// The part of the merged composite's share filled once its bands are rendered and converted; the -/// rest is compressing its planes. -pub(super) const MERGED_RENDERED: f32 = 0.8; +use super::{Document, PSD_SAVE_HEADROOM}; +use photocraft_psd::{PsdFile, Version, file::LayerInfoPlacement}; /// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD /// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by -/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way -/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, -/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read -/// the length as 4 bytes and refuse the whole file (#7937). +/// Photoshop as "not compatible with this version". The other way round, a PSB block with an +/// 8-byte length is `8B64`, as Photoshop writes it. pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { match version { Version::Psd if sig == *b"8B64" => *b"8BIM", @@ -22,6 +13,12 @@ pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [ } } +/// How much of a PSD conversion the merged composite weighs, in layer records. +pub(super) const MERGED_WEIGHT: f32 = 2.0; + +/// The part of the merged composite's share filled once its bands are rendered and converted. +pub(super) const MERGED_RENDERED: f32 = 0.8; + /// The version a document is encoded as: PSB when asked for or past PSD's 30000 px; otherwise /// PSD, which [`fit_psd_size`] turns into PSB once the encoded file proves too large. pub(crate) fn psd_version(doc: &Document, force_psb: bool) -> Version { @@ -29,22 +26,16 @@ pub(crate) fn psd_version(doc: &Document, force_psb: bool) -> Version { if force_psb || exceeds_dimensions { Version::Psb } else { Version::Psd } } -/// Keeps an encoded PSD whose file fits `limit` (less [`PSD_SAVE_HEADROOM`]) and turns a larger -/// one into PSB (#212, #5285). The decision is made on the exact length of the file as it will be -/// written, not on the raw pixel size: RLE usually packs the channels far below it. Promoting -/// re-encodes nothing (only the RLE row-count tables widen, see [`PsdFile::promote_to_psb`]). -/// Returns a warning when the version changed or could not be changed. +/// Promote files that exceed the PSD limit, accounting for the preview appended by the save. pub(crate) fn fit_psd_size(file: &mut PsdFile, limit: u64) -> Option { - if file.written_version().is_psb() { + if file.written_version() == Version::Psb { return None; } - // A length that cannot be computed (it overflows) cannot fit either. if file.encoded_len().is_ok_and(|len| len.saturating_add(PSD_SAVE_HEADROOM) <= limit) { return None; } match file.promote_to_psb() { Ok(()) => { - // Photoshop pads the layer info to 4 bytes; the padding depends on the version. let padded = file.layer_info.as_ref().is_some_and(|info| info.padding.is_some()); if matches!(file.layer_info_placement, LayerInfoPlacement::Section) && padded @@ -55,12 +46,11 @@ pub(crate) fn fit_psd_size(file: &mut PsdFile, limit: u64) -> Option { } Some("encoded size exceeds 2 GB; written as PSB".into()) } - Err(e) => Some(format!("encoded size exceeds 2 GB, but the file could not be written as PSB: {e}")), + Err(error) => Some(format!("encoded size exceeds 2 GB, but the file could not be written as PSB: {error}")), } } -/// Signs every global block for the version `file` is written as ([`block_signature`]): run -/// after [`fit_psd_size`], which may turn a PSD into a PSB. +/// Signs every global block for the version the file is written as. pub(crate) fn sign_global_blocks(file: &mut PsdFile) { let version = file.written_version(); for block in &mut file.global_blocks { diff --git a/crates/io/src/psd_export/merged.rs b/crates/io/src/psd_export/merged.rs index 51b2face36..94b7bc4014 100644 --- a/crates/io/src/psd_export/merged.rs +++ b/crates/io/src/psd_export/merged.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{ColorMode, Document, Interrupt, PixelFormat, SampleType, encode_be, q255}; pub(super) fn cmyk_of(fmt: &PixelFormat) -> bool { fmt.mode == ColorMode::Cmyk @@ -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/io/src/psd_export/resources.rs b/crates/io/src/psd_export/resources.rs index 4ab5210e94..09d9e67d22 100644 --- a/crates/io/src/psd_export/resources.rs +++ b/crates/io/src/psd_export/resources.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Document, ImageResource, TaggedBlock}; pub(crate) fn legacy_name(s: &str) -> Vec { s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() diff --git a/crates/io/src/psd_export/smart.rs b/crates/io/src/psd_export/smart.rs index 264a2ab8ab..10833c7033 100644 --- a/crates/io/src/psd_export/smart.rs +++ b/crates/io/src/psd_export/smart.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Document, Layer, LayerContent, SmartContentsId, Surface}; /// An embedded smart-object source as written to `lnk2`. #[derive(Clone, Debug)] diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index af7c8a2241..413aa85ebf 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -486,7 +486,7 @@ fn every_mode_promoted_by_size_signs_long_blocks_8b64() { assert_eq!(big.decode_merged().unwrap(), small.decode_merged().unwrap(), "{psd_mode:?}"); // Without `size_limit_psb` no mode is promoted by its size, the layerless ones included. let opts = PsdExportOptions { size_limit_psb: false, ..PsdExportOptions::default() }; - let (kept, warnings) = document_to_psd_sized(&doc, &opts, 0, &Interrupt::NONE, len + PSD_SAVE_HEADROOM - 1); + let (kept, warnings) = document_to_psd_sized(&doc, &opts, 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE); assert_eq!((kept.written_version(), kept.header.color_mode), (Version::Psd, psd_mode), "{psd_mode:?}: {warnings:?}"); assert!(!warnings.iter().any(|w| w.contains("written as PSB")), "{psd_mode:?}: {warnings:?}"); } diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 28073ad4e0..de1ca2c7c3 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -47,7 +47,7 @@ pub(crate) const REGENERATED: [&[u8; 4]; 9] = [b"luni", b"lyid", b"lsct", b"lsdk pub(crate) struct Ctx<'a> { pub file: &'a PsdFile, - /// The file's global blocks, as the document keeps them. + /// Global blocks shared with the document. pub global: Vec, pub fmt: PixelFormat, pub mask_fmt: PixelFormat, @@ -56,8 +56,7 @@ pub(crate) struct Ctx<'a> { pub warnings: Vec, /// Decoding encountered damaged PSD data; interactive opens ask whether to continue. pub damaged: bool, - /// Reading the file's channel data failed (it is read as it is decoded: see - /// `PsdFile::from_source`): the open fails with it, rather than leaving layers empty. + /// Failure to read source channel data, which must fail the open. pub read_error: Option, /// Document resolution (type sizes are converted to points with it). pub dpi: f32, @@ -80,7 +79,7 @@ pub(crate) struct Ctx<'a> { pub ctl: photocraft_raster::Interrupt<'a>, /// Layer records decoded so far, out of `total` (progress). pub done: usize, - /// Tiles of one pixel value, shared by every surface the import decodes. + /// Uniform tiles shared across imported layers. pub uniform: photocraft_raster::TileInterner, pub total: usize, } @@ -109,6 +108,14 @@ fn band_rows(top: i32, h: usize, row_bytes: usize) -> Vec<(usize, usize)> { out } +fn import_format(file: &PsdFile) -> (ColorMode, bool, bool, SampleType) { + let mode = doc_mode(file.header.color_mode).unwrap_or(ColorMode::Rgb); + let layered = matches!(mode, ColorMode::Grayscale | ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Lab) && file.header.depth != 1; + let multichannel = mode == ColorMode::Multichannel && file.header.depth != 1; + let depth = if layered || multichannel { sample_for_depth(file.header.depth) } else { SampleType::U8 }; + (mode, layered, multichannel, depth) +} + fn doc_mode(m: PsdMode) -> Option { Some(match m { PsdMode::Bitmap => ColorMode::Bitmap, @@ -158,6 +165,18 @@ fn soft_shape_fill(rec: &LayerRecord, has_vector: bool, fill_key: Option<&[u8; 4 pattern.then_some((fill, soft)) } +#[derive(Clone, Copy)] +struct DecodedImport<'a> { + file: &'a PsdFile, + merged: &'a Option>>, + sizes: Option<(usize, usize)>, + canvas: Rect, + layered: bool, + multichannel: bool, + depth: SampleType, + fmt: PixelFormat, +} + /// Where a placed layer's source goes: read from `SoLd`/`SoLE`, or from a CS2 `PlLd` record. /// An empty `id` leaves the contents unavailable (the stored pixels stay the rendering). #[derive(Default)] @@ -508,69 +527,7 @@ impl Ctx<'_> { LayerContent::Raster(self.record_surface(rec, &name)) } } else if let Some(k) = smart_key { - let Placement { id, transform, perspective, warp } = match rec.block(k) { - Some(b) if k == b"PlLd" => self.plld_placement(&b.data, &name), - Some(b) => { - let (id, transform) = blocks::parse_smart(k, &b.data); - // Distort / Perspective: the fourth corner (the affine `transform` drops it). - let perspective = blocks::parse_smart_perspective(k, &b.data); - Placement { id, transform, perspective, warp: blocks::parse_placed_warp(k, &b.data) } - } - None => Placement::default(), - }; - let contents_id = - if id.is_empty() { SmartContentsId::fresh() } else { *self.smart_contents.entry(id.clone()).or_insert_with(SmartContentsId::fresh) }; - // Smart filters (`filterFX` in the placed-layer data) and their mask (`FEid`). - let placed = rec.block(b"SoLd").or_else(|| rec.block(b"SoLE")).and_then(|b| crate::smart_map::parse_sold(&b.data)); - let stack = placed.as_ref().and_then(|p| p.stack.clone()).unwrap_or_default(); - let filter_mask = match &placed { - Some(p) if !stack.filters.is_empty() => self.filter_mask(&p.placed, &stack, &name), - _ => None, - }; - // Photoshop stores the filtered pixels without the filter mask and mixes the unfiltered - // ones (`FEid`) back in through it; our smart objects hold the mixed result. - let stored = self.record_surface(rec, &name); - let shown = stack.enabled && stack.filters.iter().any(|f| f.visible); - let cache = match (&placed, filter_mask.as_ref().filter(|m| m.enabled && shown)) { - (Some(p), Some(m)) => { - let unfiltered = match self.unfiltered.get(&p.placed) { - Some(done) => done.clone(), - None => { - // Every distinct source is kept until the import ends, so what they add up to is - // bounded: past the limit the layer keeps its stored pixels, unmixed. - let item = self.filter_effects.iter().find(|i| i.id == p.placed); - let cost = item - .and_then(|i| i.rect.size().ok()) - .map_or(0, |(w, h)| (w as u64).saturating_mul(h as u64).saturating_mul(self.fmt.bytes_per_pixel() as u64)); - let fits = self.unfiltered_bytes.saturating_add(cost) <= MAX_UNFILTERED_BYTES; - let made = item.filter(|_| fits).and_then(|i| crate::smart_map::unfiltered_from_item(i, self.fmt)); - if made.is_some() { - self.unfiltered_bytes += cost; - } - self.unfiltered.insert(p.placed.clone(), made.clone()); - made - } - }; - match unfiltered { - Some(u) => photocraft_compose::filter_mask::mix(&u, &stored, m), - None => stored, - } - } - _ => stored, - }; - LayerContent::Smart(SmartObject { - contents_id, - source: SmartSource::Linked { path: id }, - transform, - smart_filters: stack.filters, - cache: Some(cache), - psd_raw: principal(k), - filters_enabled: stack.enabled, - filter_mask, - warp, - stack_mode: None, - perspective, - }) + self.smart_content(rec, &name, k, &principal) } else if let Some((f, soft)) = soft_shape_fill(rec, vector_key.is_some(), fill_key) { // A pattern-filled shape is a pattern fill layer seen through its vector mask (soft // or not). Unless that mask is soft, the stored pixels stay its rendering (a soft @@ -638,6 +595,71 @@ impl Ctx<'_> { l } + fn smart_content(&mut self, rec: &LayerRecord, name: &str, k: &[u8; 4], principal: &impl Fn(&[u8; 4]) -> Option>>) -> LayerContent { + let Placement { id, transform, perspective, warp } = match rec.block(k) { + Some(b) if k == b"PlLd" => self.plld_placement(&b.data, name), + Some(b) => { + let (id, transform) = blocks::parse_smart(k, &b.data); + // Distort / Perspective: the fourth corner (the affine `transform` drops it). + let perspective = blocks::parse_smart_perspective(k, &b.data); + Placement { id, transform, perspective, warp: blocks::parse_placed_warp(k, &b.data) } + } + None => Placement::default(), + }; + let contents_id = if id.is_empty() { SmartContentsId::fresh() } else { *self.smart_contents.entry(id.clone()).or_insert_with(SmartContentsId::fresh) }; + // Smart filters (`filterFX` in the placed-layer data) and their mask (`FEid`). + let placed = rec.block(b"SoLd").or_else(|| rec.block(b"SoLE")).and_then(|b| crate::smart_map::parse_sold(&b.data)); + let stack = placed.as_ref().and_then(|p| p.stack.clone()).unwrap_or_default(); + let filter_mask = match &placed { + Some(p) if !stack.filters.is_empty() => self.filter_mask(&p.placed, &stack, name), + _ => None, + }; + // Photoshop stores the filtered pixels without the filter mask and mixes the unfiltered + // ones (`FEid`) back in through it; our smart objects hold the mixed result. + let stored = self.record_surface(rec, name); + let shown = stack.enabled && stack.filters.iter().any(|f| f.visible); + let cache = match (&placed, filter_mask.as_ref().filter(|m| m.enabled && shown)) { + (Some(p), Some(m)) => { + let unfiltered = match self.unfiltered.get(&p.placed) { + Some(done) => done.clone(), + None => { + // Every distinct source is kept until the import ends, so what they add up to is + // bounded: past the limit the layer keeps its stored pixels, unmixed. + let item = self.filter_effects.iter().find(|i| i.id == p.placed); + let cost = item + .and_then(|i| i.rect.size().ok()) + .map_or(0, |(w, h)| (w as u64).saturating_mul(h as u64).saturating_mul(self.fmt.bytes_per_pixel() as u64)); + let fits = self.unfiltered_bytes.saturating_add(cost) <= MAX_UNFILTERED_BYTES; + let made = item.filter(|_| fits).and_then(|i| crate::smart_map::unfiltered_from_item(i, self.fmt)); + if made.is_some() { + self.unfiltered_bytes += cost; + } + self.unfiltered.insert(p.placed.clone(), made.clone()); + made + } + }; + match unfiltered { + Some(u) => photocraft_compose::filter_mask::mix(&u, &stored, m), + None => stored, + } + } + _ => stored, + }; + LayerContent::Smart(SmartObject { + contents_id, + source: SmartSource::Linked { path: id }, + transform, + smart_filters: stack.filters, + cache: Some(cache), + psd_raw: principal(k), + filters_enabled: stack.enabled, + filter_mask, + warp, + stack_mode: None, + perspective, + }) + } + /// Typed vector mask from `vsms`/`vmsk` (non-shape layers). A user mask that Photoshop /// rendered from the vector data (flag bit 3, no separate real mask) is dropped: the /// compositor rasterizes the vector mask itself. @@ -688,9 +710,7 @@ impl Ctx<'_> { let sd = rec.section_divider(); let expanded = sd.is_none_or(|s| s.kind != photocraft_psd::SectionType::ClosedFolder); let artboard = crate::comps_map::ARTBOARD_KEYS.iter().find_map(|k| rec.block(k)).and_then(|b| crate::comps_map::parse_artboard(&b.data)); - // A Photoshop Frame's stroke: `vstk` on the frame group, in a shape's layout. - let frame_stroke = rec.block(b"vstk").and_then(|b| crate::vector_map::parse_vstk(&b.data, self.dpi)).and_then(|v| v.stroke); - let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard, frame_stroke })); + let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard, frame_stroke: None })); l.psd_blocks = preserved_blocks(rec); self.apply_common(&mut l, rec, sd.and_then(|s| s.blend_mode)); self.apply_vector_mask(&mut l, rec); @@ -940,6 +960,28 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt) psd_to_document_decoded(file, ctl, None) } +/// [`psd_to_document_decoded_integrity`] taking the file: its global blocks move into the +/// document rather than being copied (an embedded smart object's `lnk2` block can be most of a +/// file). The file's channel data may still be in its source ([`PsdFile::from_source`]): the +/// fourth value is a failure to read it, which fails the open (a layer is never left empty +/// because its file became unreadable while it opened). +pub(crate) fn psd_to_document_owned( + mut file: PsdFile, + ctl: &photocraft_raster::Interrupt, + decoded: Option>>, +) -> Option<(Document, Vec, bool, Option)> { + let global = file + .global_blocks + .iter_mut() + .map(|b| { + // A layer block is still read by `unreadable_layer_block` (to say why it failed). + let data = if matches!(&b.key, b"Lr16" | b"Lr32" | b"Layr") { b.data.clone() } else { std::mem::take(&mut b.data) }; + (b.signature, b.key, Arc::new(data)) + }) + .collect(); + psd_to_document_global(&file, ctl, decoded, global) +} + /// Whether `file` stores spot planes the way earlier PhotoCraft versions (releases 0.1.0 to /// 0.16.0) wrote them: straight (the maximum = solid ink), the opposite of Photoshop, which /// stores 0 = solid ink in every PSD and TIFF it saves. Their files are recognised by three @@ -1019,6 +1061,73 @@ pub(crate) fn can_recover_layers(file: &PsdFile) -> bool { matches!(file.header.color_mode, PsdMode::Grayscale | PsdMode::Rgb | PsdMode::Cmyk | PsdMode::Lab) && file.header.depth != 1 && !file.layers().is_empty() } +fn read_initial_metadata(file: &PsdFile, global: &[PsdGlobalBlock], doc: &mut Document, layered: bool, multichannel: bool, warnings: &mut Vec) -> bool { + let header = &file.header; + for resource in &file.resources { + match resource.id { + ids::RESOLUTION_INFO => { + if let Ok(info) = photocraft_psd::ResolutionInfo::from_bytes(&resource.data) { + let (x, y) = (info.h_res(), info.v_res()); + doc.resolution_dpi = x as f32; + warnings.extend(crate::unequal_resolution_warning(x, y)); + } + } + ids::ICC_PROFILE => doc.icc_profile = Some(Arc::new(resource.data.clone())), + ids::XMP => doc.metadata.xmp = Some(String::from_utf8_lossy(&resource.data).into()), + ids::EXIF => doc.metadata.exif = Some(Arc::new(resource.data.clone())), + 1032 => parse_guides(&resource.data, doc), + ids::GLOBAL_ANGLE | ids::GLOBAL_ALTITUDE => { + if let Some(bytes) = resource.data.get(..4) { + let value = i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as f32; + if resource.id == ids::GLOBAL_ANGLE { + doc.global_light.angle = value; + } else { + doc.global_light.altitude = value; + } + } + } + id if crate::vector_map::SAVED_PATHS.contains(&id) => match crate::vector_map::path_from_resource(&resource.data, header.width, header.height) { + Some(path) => doc.paths.push(photocraft_doc::NamedPath { + name: String::from_utf8_lossy(&resource.name).into_owned(), + path, + psd_raw: Some(Arc::new(resource.data.clone())), + }), + None => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&resource.name).into_owned(), Arc::new(resource.data.clone()))), + }, + crate::vector_map::WORK_PATH => doc.work_path = crate::vector_map::path_from_resource(&resource.data, header.width, header.height), + crate::vector_map::CLIPPING_PATH => { + let len = usize::from(resource.data.first().copied().unwrap_or(0)); + let name = resource.data.get(1..1 + len).map(|bytes| String::from_utf8_lossy(bytes).into_owned()).unwrap_or_default(); + doc.clipping_path = Some(photocraft_doc::ClippingPath { name, flatness: 0.0 }); + doc.metadata.psd_resources.push((resource.id, String::from_utf8_lossy(&resource.name).into_owned(), Arc::new(resource.data.clone()))); + } + crate::channel_map::ALPHA_IDENTIFIERS if !multichannel => {} + id if MAPPED_RESOURCES.contains(&id) => {} + id => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&resource.name).into_owned(), Arc::new(resource.data.clone()))), + } + } + crate::guides_map::apply_colors(doc); + doc.metadata.psd_global_blocks.extend(global.iter().cloned()); + let mut damaged = false; + if let Some((block, error)) = file.unreadable_layer_block() { + damaged = true; + warnings.push(format!( + "the layers ({} block) could not be read ({error}); only the merged image was opened. Saving as PSD replaces the unreadable layer data", + block.key_str() + )); + } + doc.patterns = crate::pattern_map::from_global_blocks(doc); + doc.notes = crate::annotations_map::notes_from_blocks(doc); + if crate::annotations_map::anno_unreadable(doc) { + warnings.push("the notes (Anno block) could not be read; they are kept unchanged on PSD save unless a note is added".into()); + } + if let Some(scale) = crate::annotations_map::raw_scale(doc) { + doc.measurement.scale = scale; + } + let _ = layered; + damaged +} + /// [`psd_to_document_with`] with the merged image already decoded (by /// [`PsdFile::from_bytes_and_merged`] with [`merged_needed`]), so it is not decoded again. pub(crate) fn psd_to_document_decoded( @@ -1038,29 +1147,7 @@ pub(crate) fn psd_to_document_decoded_integrity( decoded: Option>>, ) -> Option<(Document, Vec, bool)> { let global = file.global_blocks.iter().map(|b| (b.signature, b.key, Arc::new(b.data.clone()))).collect(); - psd_to_document_global(file, ctl, decoded, global).map(|(document, warnings, damaged, _)| (document, warnings, damaged)) -} - -/// [`psd_to_document_decoded_integrity`] taking the file: its global blocks move into the -/// document rather than being copied (an embedded smart object's `lnk2` block can be most of a -/// file). The file's channel data may still be in its source ([`PsdFile::from_source`]): the -/// fourth value is a failure to read it, which fails the open (a layer is never left empty -/// because its file became unreadable while it opened). -pub(crate) fn psd_to_document_owned( - mut file: PsdFile, - ctl: &photocraft_raster::Interrupt, - decoded: Option>>, -) -> Option<(Document, Vec, bool, Option)> { - let global = file - .global_blocks - .iter_mut() - .map(|b| { - // A layer block is still read by `unreadable_layer_block` (to say why it failed). - let data = if matches!(&b.key, b"Lr16" | b"Lr32" | b"Layr") { b.data.clone() } else { std::mem::take(&mut b.data) }; - (b.signature, b.key, Arc::new(data)) - }) - .collect(); - psd_to_document_global(&file, ctl, decoded, global) + psd_to_document_global(file, ctl, decoded, global).map(|(doc, warnings, damaged, _)| (doc, warnings, damaged)) } fn psd_to_document_global( @@ -1069,91 +1156,14 @@ fn psd_to_document_global( decoded: Option>>, global: Vec, ) -> Option<(Document, Vec, bool, Option)> { + let (mode, layered, multichannel, depth) = import_format(file); let h = &file.header; let mut warnings = Vec::new(); - let mode = doc_mode(h.color_mode).unwrap_or_else(|| { + if doc_mode(h.color_mode).is_none() { warnings.push(format!("unknown color mode {}; importing as RGB", h.color_mode.as_u16())); - ColorMode::Rgb - }); - let layered = matches!(mode, ColorMode::Grayscale | ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Lab) && h.depth != 1; - let multichannel = mode == ColorMode::Multichannel && h.depth != 1; - let depth = if layered || multichannel { sample_for_depth(h.depth) } else { SampleType::U8 }; + } let mut doc = Document::new("Untitled", Size::new(h.width, h.height), mode, depth); - - // Resources. - for r in &file.resources { - match r.id { - ids::RESOLUTION_INFO => { - if let Ok(ri) = photocraft_psd::ResolutionInfo::from_bytes(&r.data) { - // Fixed 16.16 hRes/vRes are pixels per inch. The unit shorts only - // say how to show that number (1 = px/in, 2 = px/cm). - let (x, y) = (ri.h_res(), ri.v_res()); - doc.resolution_dpi = x as f32; - warnings.extend(crate::unequal_resolution_warning(x, y)); - } - } - ids::ICC_PROFILE => doc.icc_profile = Some(Arc::new(r.data.clone())), - ids::XMP => doc.metadata.xmp = Some(String::from_utf8_lossy(&r.data).into()), - ids::EXIF => doc.metadata.exif = Some(Arc::new(r.data.clone())), - 1032 => parse_guides(&r.data, &mut doc), - ids::GLOBAL_ANGLE | ids::GLOBAL_ALTITUDE => { - if let Some(b) = r.data.get(..4) { - let v = i32::from_be_bytes([b[0], b[1], b[2], b[3]]) as f32; - if r.id == ids::GLOBAL_ANGLE { - doc.global_light.angle = v; - } else { - doc.global_light.altitude = v; - } - } - } - id if crate::vector_map::SAVED_PATHS.contains(&id) => match crate::vector_map::path_from_resource(&r.data, h.width, h.height) { - Some(path) => doc.paths.push(photocraft_doc::NamedPath { - name: String::from_utf8_lossy(&r.name).into_owned(), - path, - psd_raw: Some(Arc::new(r.data.clone())), - }), - None => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))), - }, - crate::vector_map::WORK_PATH => { - doc.work_path = crate::vector_map::path_from_resource(&r.data, h.width, h.height); - } - crate::vector_map::CLIPPING_PATH => { - // Kept raw (layout beyond the name is not modelled); the name is exposed. - let n = usize::from(r.data.first().copied().unwrap_or(0)); - let name = r.data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); - doc.clipping_path = Some(photocraft_doc::ClippingPath { name, flatness: 0.0 }); - doc.metadata.psd_resources.push((r.id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))); - } - // Resource 1053 is written afresh with the extra channels on every save, so a kept copy - // would be new metadata after each round trip. Multichannel has no such rewrite: the - // imported bytes are the channel ids, copied back while they still match. - crate::channel_map::ALPHA_IDENTIFIERS if !multichannel => {} - id if MAPPED_RESOURCES.contains(&id) => {} - id => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))), - } - } - crate::guides_map::apply_colors(&mut doc); - doc.metadata.psd_global_blocks.extend(global.iter().cloned()); - // A 16/32-bit file whose layer block can't be parsed would otherwise open as a flattened - // file without a word (#2700). The raw block is kept, but a PSD save writes the document's - // own layers in its place (see `psd_export`). - let mut damaged = false; - if let Some((b, e)) = file.unreadable_layer_block() { - damaged = true; - warnings.push(format!( - "the layers ({} block) could not be read ({e}); only the merged image was opened. Saving as PSD replaces the unreadable layer data", - b.key_str() - )); - } - doc.patterns = crate::pattern_map::from_global_blocks(&doc); - // Notes (`Anno`) and the measurement scale (resource 1074); raw data stays for verbatim export. - doc.notes = crate::annotations_map::notes_from_blocks(&doc); - if crate::annotations_map::anno_unreadable(&doc) { - warnings.push("the notes (Anno block) could not be read; they are kept unchanged on PSD save unless a note is added".into()); - } - if let Some(scale) = crate::annotations_map::raw_scale(&doc) { - doc.measurement.scale = scale; - } + let damaged = read_initial_metadata(file, &global, &mut doc, layered, multichannel, &mut warnings); let fmt = doc.pixel_format(); let cc = fmt.mode.color_channels(); @@ -1180,7 +1190,7 @@ fn psd_to_document_global( uniform: Default::default(), total: file.layers().len(), }; - for (_, key, data) in cx.global.clone().iter().filter(|(_, k, _)| matches!(k, b"FEid" | b"FXid")) { + for (_, key, data) in cx.global.clone().iter().filter(|(_, key, _)| matches!(key, b"FEid" | b"FXid")) { // Smart-filter caches can be large: a cancelled open stops between blocks. if ctl.cancelled() { return None; @@ -1199,222 +1209,18 @@ fn psd_to_document_global( // budget while `w * hh` does not fit a 32-bit `usize` (wasm32). let sizes = w.checked_mul(hh).zip(h.row_bytes().checked_mul(hh)); let canvas = Rect::new(0, 0, h.width as i32, h.height as i32); - // The merged composite is decoded only when something consumes it: a flattened or - // multichannel file (it *is* the image), or extra alpha/spot channels behind the colour - // ones. A normal layered Photoshop save carries a merged composite nobody reads - roughly - // half the file's bytes, decoded and thrown away on every open before this. - let merged = if merged_needed(file) { - let m = decoded.unwrap_or_else(|| file.decode_merged()); - if ctl.cancelled() { - return None; - } - ctl.progress(0.1); - if let Err(e) = &m { - cx.warn_unreadable_data(format!("merged image could not be decoded: {e}")); - if can_recover_layers(file) { - cx.warn_unreadable_data("extra alpha/spot channels in the merged image could not be recovered"); - } - } - Some(m) - } else { - if let Some(Err(e)) = decoded { - cx.warn_unreadable_data(format!("merged image could not be decoded; opened the available layers instead: {e}")); - } - None - }; + let merged = decode_merged(file, decoded, ctl, &mut cx)?; + import_decoded_content(DecodedImport { file, merged: &merged, sizes, canvas, layered, multichannel, depth, fmt }, &mut doc, &mut cx); + finish_import(doc, cx, ctl) +} - if multichannel { - // Ink channels only (no layers); see `multichannel_map`. - if let Some(Ok(all)) = &merged { - let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default(); - crate::multichannel_map::import(file, all, &mut doc, &names, &mut cx.warnings); - } - if !file.layers().is_empty() { - cx.warn(format!("Multichannel documents have no layers: {} layer records were not imported", file.layers().len())); - } - } else if layered { - // Capped like `build` (#2940): a group past the document's nesting cap keeps no children, - // so no file can make this tree, or anything walking or dropping it, recurse deeper. - let tree = file.layer_tree_max_depth(photocraft_doc::MAX_GROUP_DEPTH); - // Colours stored in the document's CMYK space (Gradient Map stops…) convert through - // its own profile, as the compositor and the PSD writer read them. - let space = photocraft_compose::cmyk_space(&doc); - doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)); - // Photoshop's Background: the bottom record stored without a transparency channel (-1), - // locked whatever its (localized) name and whether or not the file carries an `lspf` - // block. Its name is kept. - mark_background(file, &mut doc.layers); - // Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked). - if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) = - file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed) - { - apply_link_groups(&tree, &mut doc.layers, &groups); - } - if doc.layers.is_empty() - && let Some(Ok(all)) = &merged - // Always `Some` here: a decoded 8/16/32-bit plane holds at least `w * hh` bytes. - && let Some((n, plane)) = sizes - { - // Flattened file: the merged image becomes the background layer. - let alpha_idx = if file.merged_has_alpha() { Some(cc) } else { None }; - let mut planes: Vec> = (0..cc).map(|c| merged_plane(all, c, plane)).collect(); - planes.push(alpha_idx.and_then(|a| merged_plane(all, a, plane))); - let mut fill = vec![zero_sample(depth); cc]; - fill.push(max_sample(depth)); - let mut inv = vec![cx.cmyk; cc]; - inv.push(false); - let mut bytes = interleave(&planes, &fill, n, depth, &inv); - if fmt.mode == ColorMode::Lab && depth == SampleType::U16 { - crate::pixels::lab16_chroma(&mut bytes, cc + 1, true); - } - let mut s = Surface::from_interleaved(fmt, canvas, &bytes); - if alpha_idx.is_some() { - // Undo Photoshop's white matting of the merged image. - // A band of tile rows at a time (no full-size float copy of the image). - let white = photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 1.0, 1.0]); - let mut vals = Vec::new(); - let mut y = canvas.y0; - while y < canvas.y1 { - let band = Rect::new(canvas.x0, y, canvas.x1, y.saturating_add(TILE_SIZE).min(canvas.y1)); - s.read_region_into(band, &mut vals); - for px in vals.chunks_exact_mut(cc + 1) { - let a = px[cc]; - for c in 0..cc { - px[c] = if a <= 0.0 { 0.0 } else { crate::pixels::unmatte(px[c], a, white[c]) }; - } - } - s.write_region(band, &vals); - y = band.y1; - } - } - s.prune(); - let mut bg = Layer::new("Background", LayerContent::Raster(s)); - if alpha_idx.is_none() { - bg.locks.transparency = true; - bg.locks.position = true; - } - doc.layers.push(bg); - } - } else { - if !file.layers().is_empty() { - cx.warn(format!("{:?} documents are imported flattened: {} layer records were not imported", h.color_mode, file.layers().len())); - } else { - cx.warn(format!("{:?} {}-bit document converted to {:?} 8-bit for editing", h.color_mode, h.depth, fmt.mode)); - } - if h.color_mode == PsdMode::Indexed && file.color_mode_data.len() >= 768 { - // Planar palette: 256 reds, 256 greens, 256 blues (the Color Table). - let m = &file.color_mode_data; - // Resource 1046 says how many entries are used, 1047 which one is transparent. - let u16_of = |id: u16| file.resource(id).and_then(|r| r.data.get(..2)).map(|b| u16::from_be_bytes([b[0], b[1]])); - let count = u16_of(crate::palette_map::COLOR_TABLE_COUNT).map_or(256, usize::from).clamp(1, 256); - let colors = (0..count).map(|i| [m[i], m[256 + i], m[512 + i]]).collect(); - let transparent = u16_of(crate::palette_map::TRANSPARENCY_INDEX).filter(|&i| usize::from(i) < count).map(|i| i as u8); - doc.color_table = Some(photocraft_doc::ColorTable { colors, transparent }); - } else if h.color_mode == PsdMode::Duotone && !file.color_mode_data.is_empty() { - // The inks (`duotone_map`); the block is also kept raw, written back while they stay - // unedited. An ink whose colour is unknown (a colour book without its Lab equivalent) - // would show black and darken the image: the grey plate is shown instead, as before. - let mut unknown = false; - let alternate = file.resource(crate::duotone_map::ALTERNATE_DUOTONE_COLORS).map(|r| r.data.as_slice()); - let inks = crate::duotone_map::parse(&file.color_mode_data, alternate, &mut unknown).filter(|_| !unknown); - if inks.is_none() { - cx.warn("duotone inks are not interpreted (shown as grayscale)"); - } - let inks = inks.unwrap_or_else(|| vec![photocraft_doc::DuotoneInk::new("Black", [0.0; 3])]); - doc.duotone = Some(photocraft_doc::Duotone { inks, psd_raw: Some(file.color_mode_data.as_slice().into()) }); - } else if !file.color_mode_data.is_empty() { - cx.warn("color mode data is not preserved"); - } - match flat_composite(file, merged.as_ref(), photocraft_psd::compression::MAX_DECODED_BYTES) { - Ok(mut img) => { - // Resource 1047: pixels of the transparent entry are transparent. - if h.color_mode == PsdMode::Indexed - && let Some(t) = doc.color_table.as_ref().and_then(|t| t.transparent) - && let Some(Ok(all)) = &merged - && let Some(indices) = sizes.and_then(|(_, plane)| merged_plane(all, 0, plane)) - { - for (px, &i) in img.data.as_chunks_mut::<4>().0.iter_mut().zip(indices) { - if i == t { - px[3] = 0; - } - } - } - let mut s = Surface::new(fmt); - write_rgba8(&mut s, canvas, &img.data); - drop(img); - s.prune(); - doc.layers.push(flat_background(s)); - } - // A merged image that failed to decode was reported above. - Err(_) if matches!(merged, Some(Err(_))) => {} - Err(e) => cx.warn_unreadable_data(format!("the image could not be read: {e}")), - } - } - - // Extra (alpha / spot) channels of the merged image. - if layered - && let Some(Ok(all)) = &merged - && let Some((n, plane)) = sizes - { - let first = cc + usize::from(file.merged_has_alpha()); - let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default(); - // Photoshop lists every extra channel, the merged transparency first when there is one. - let skip = usize::from(file.merged_has_alpha() && names.len() == usize::from(h.channels).saturating_sub(cc)); - let names = names.get(skip..).unwrap_or_default(); - // Which planes hold spot ink in Photoshop's polarity (0 = solid): the DisplayInfo records - // the channel options are read from below, the transparency's first when `skip` is 1. - // A file from an earlier PhotoCraft stores them straight and is read as it was written, - // past the channels of the Photoshop file it opened, if any. - let straight_from = if earlier_photocraft_spot_planes(file) { photoshop_identified_channels(file) } else { usize::MAX }; - let photoshop_spots = if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) { - crate::channel_map::spot_flags(&r.data, true, skip) - } else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) { - crate::channel_map::spot_flags(&r.data, false, skip) - } else { - Vec::new() - }; - for (k, idx) in (first..usize::from(h.channels)).enumerate() { - let Some(p) = merged_plane(all, idx, plane) else { - cx.warn_unreadable_data(format!("merged extra channel {idx} is incomplete and was not imported")); - break; - }; - let mut raw = be_to_ne_plane(p, depth, n); - if k < straight_from && photoshop_spots.get(k).copied().unwrap_or(false) { - crate::channel_map::photoshop_spot_plane(&mut raw, depth); - } - let mut s = Surface::new(cx.mask_fmt); - s.write_interleaved(canvas, &raw); - s.prune(); - let name = names.get(k).cloned().unwrap_or_else(|| format!("Alpha {}", k + 1)); - doc.channels.push(AlphaChannel::new(name, s)); - } - // Channel options (overlay colour, opacity, colour indicates) and spot inks. - if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) { - crate::channel_map::apply_display_info(&r.data, true, skip, &mut doc.channels); - } else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) { - crate::channel_map::apply_display_info(&r.data, false, skip, &mut doc.channels); - } - // Saved in Quick Mask mode: that channel becomes the document's Quick Mask again. - if let Some(r) = file.resource(crate::channel_map::QUICK_MASK_INFO) - && r.data.len() >= 2 - && let Some(k) = usize::from(u16::from_be_bytes([r.data[0], r.data[1]])).checked_sub(first) - && k < doc.channels.len() - { - doc.quick_mask = Some(doc.channels.remove(k)); - } - } - - // Layer comps (resource 1065 + per-layer `cmls`); the raw data stays for verbatim export. - let raw_comps = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == crate::comps_map::LAYER_COMPS).map(|(_, _, d)| d.clone()); - let comp_warnings; - (doc.layer_comps, doc.last_applied_comp, doc.last_document_state, comp_warnings) = - crate::comps_map::decode_comps(raw_comps.as_deref().map(Vec::as_slice), &doc); - cx.warnings.extend(comp_warnings); - // Slices (resource 1050), after layer ids are known; the raw data stays for verbatim export. +fn finish_import(mut doc: Document, mut cx: Ctx<'_>, ctl: &photocraft_raster::Interrupt) -> Option<(Document, Vec, bool, Option)> { + let raw_comps = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == crate::comps_map::LAYER_COMPS).map(|(_, _, data)| data.clone()); + let (comps, applied, state, warnings) = crate::comps_map::decode_comps(raw_comps.as_deref().map(Vec::as_slice), &doc); + (doc.layer_comps, doc.last_applied_comp, doc.last_document_state) = (comps, applied, state); + cx.warnings.extend(warnings); crate::slices_map::import(&mut doc); - // Character and paragraph styles from the type layers' engine data. cx.warnings.extend(crate::text_styles_map::import(&mut doc)); - if ctl.cancelled() { return None; } @@ -1422,5 +1228,221 @@ fn psd_to_document_global( Some((doc, cx.warnings, cx.damaged, cx.read_error)) } +fn decode_merged( + file: &PsdFile, + decoded: Option>>, + ctl: &photocraft_raster::Interrupt, + cx: &mut Ctx<'_>, +) -> Option>>> { + if merged_needed(file) { + let merged = decoded.unwrap_or_else(|| file.decode_merged()); + if ctl.cancelled() { + return None; + } + ctl.progress(0.1); + if let Err(error) = &merged { + cx.warn_unreadable_data(format!("merged image could not be decoded: {error}")); + if can_recover_layers(file) { + cx.warn_unreadable_data("extra alpha/spot channels in the merged image could not be recovered"); + } + } + Some(Some(merged)) + } else { + if let Some(Err(error)) = decoded { + cx.warn_unreadable_data(format!("merged image could not be decoded; opened the available layers instead: {error}")); + } + Some(None) + } +} + +fn import_decoded_content(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_>) { + if import.multichannel { + import_multichannel(import.file, import.merged, doc, cx); + } else if import.layered { + import_layered(import, doc, cx); + } else { + import_flattened(import.file, import.merged, import.sizes, import.canvas, import.fmt, doc, cx); + } + import_extra_channels(import, doc, cx); +} + +fn import_multichannel(file: &PsdFile, merged: &Option>>, doc: &mut Document, cx: &mut Ctx<'_>) { + if let Some(Ok(all)) = merged { + let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default(); + crate::multichannel_map::import(file, all, doc, &names, &mut cx.warnings); + } + if !file.layers().is_empty() { + cx.warn(format!("Multichannel documents have no layers: {} layer records were not imported", file.layers().len())); + } +} + +fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_>) { + let DecodedImport { file, merged, sizes, canvas, depth, fmt, .. } = import; + let cc = fmt.mode.color_channels(); + let tree = file.layer_tree_max_depth(photocraft_doc::MAX_GROUP_DEPTH); + let space = photocraft_compose::cmyk_space(doc); + doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)); + mark_background(file, &mut doc.layers); + if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) = + file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed) + { + apply_link_groups(&tree, &mut doc.layers, &groups); + } + let Some((n, plane)) = sizes else { return }; + let Some(Ok(all)) = merged else { return }; + if !doc.layers.is_empty() { + return; + } + let alpha_idx = file.merged_has_alpha().then_some(cc); + let mut planes: Vec> = (0..cc).map(|c| merged_plane(all, c, plane)).collect(); + planes.push(alpha_idx.and_then(|a| merged_plane(all, a, plane))); + let mut fill = vec![zero_sample(depth); cc]; + fill.push(max_sample(depth)); + let mut inv = vec![cx.cmyk; cc]; + inv.push(false); + let mut bytes = interleave(&planes, &fill, n, depth, &inv); + if fmt.mode == ColorMode::Lab && depth == SampleType::U16 { + crate::pixels::lab16_chroma(&mut bytes, cc + 1, true); + } + let mut surface = Surface::from_interleaved(fmt, canvas, &bytes); + if alpha_idx.is_some() { + let white = photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 1.0, 1.0]); + let mut vals = Vec::new(); + let mut y = canvas.y0; + while y < canvas.y1 { + let band = Rect::new(canvas.x0, y, canvas.x1, y.saturating_add(TILE_SIZE).min(canvas.y1)); + surface.read_region_into(band, &mut vals); + for px in vals.chunks_exact_mut(cc + 1) { + let a = px[cc]; + for c in 0..cc { + px[c] = if a <= 0.0 { 0.0 } else { crate::pixels::unmatte(px[c], a, white[c]) }; + } + } + surface.write_region(band, &vals); + y = band.y1; + } + } + surface.prune(); + let mut bg = Layer::new("Background", LayerContent::Raster(surface)); + if alpha_idx.is_none() { + bg.locks.transparency = true; + bg.locks.position = true; + } + doc.layers.push(bg); +} + +fn import_flattened( + file: &PsdFile, + merged: &Option>>, + sizes: Option<(usize, usize)>, + canvas: Rect, + fmt: PixelFormat, + doc: &mut Document, + cx: &mut Ctx<'_>, +) { + let h = &file.header; + if !file.layers().is_empty() { + cx.warn(format!("{:?} documents are imported flattened: {} layer records were not imported", h.color_mode, file.layers().len())); + } else { + cx.warn(format!("{:?} {}-bit document converted to {:?} 8-bit for editing", h.color_mode, h.depth, fmt.mode)); + } + if h.color_mode == PsdMode::Indexed && file.color_mode_data.len() >= 768 { + let m = &file.color_mode_data; + let u16_of = |id: u16| file.resource(id).and_then(|r| r.data.get(..2)).map(|b| u16::from_be_bytes([b[0], b[1]])); + let count = u16_of(crate::palette_map::COLOR_TABLE_COUNT).map_or(256, usize::from).clamp(1, 256); + let colors = (0..count).map(|i| [m[i], m[256 + i], m[512 + i]]).collect(); + let transparent = u16_of(crate::palette_map::TRANSPARENCY_INDEX).filter(|&i| usize::from(i) < count).map(|i| i as u8); + doc.color_table = Some(photocraft_doc::ColorTable { colors, transparent }); + } else if h.color_mode == PsdMode::Duotone && !file.color_mode_data.is_empty() { + let mut unknown = false; + let alternate = file.resource(crate::duotone_map::ALTERNATE_DUOTONE_COLORS).map(|r| r.data.as_slice()); + let inks = crate::duotone_map::parse(&file.color_mode_data, alternate, &mut unknown).filter(|_| !unknown); + if inks.is_none() { + cx.warn("duotone inks are not interpreted (shown as grayscale)"); + } + let inks = inks.unwrap_or_else(|| vec![photocraft_doc::DuotoneInk::new("Black", [0.0; 3])]); + doc.duotone = Some(photocraft_doc::Duotone { inks, psd_raw: Some(file.color_mode_data.as_slice().into()) }); + } else if !file.color_mode_data.is_empty() { + cx.warn("color mode data is not preserved"); + } + match flat_composite(file, merged.as_ref(), photocraft_psd::compression::MAX_DECODED_BYTES) { + Ok(mut img) => { + if h.color_mode == PsdMode::Indexed + && let Some(t) = doc.color_table.as_ref().and_then(|t| t.transparent) + && let Some(Ok(all)) = merged + && let Some(indices) = sizes.and_then(|(_, plane)| merged_plane(all, 0, plane)) + { + for (px, &i) in img.data.as_chunks_mut::<4>().0.iter_mut().zip(indices) { + if i == t { + px[3] = 0; + } + } + } + let mut surface = Surface::new(fmt); + write_rgba8(&mut surface, canvas, &img.data); + drop(img); + surface.prune(); + doc.layers.push(flat_background(surface)); + } + Err(_) if matches!(merged, Some(Err(_))) => {} + Err(error) => cx.warn_unreadable_data(format!("the image could not be read: {error}")), + } +} + +fn import_extra_channels(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_>) { + // Extra (alpha / spot) channels of the merged image. + if !import.layered { + return; + } + let DecodedImport { file, merged, sizes, canvas, depth, .. } = import; + let Some(Ok(all)) = merged else { return }; + let Some((n, plane)) = sizes else { return }; + let cc = cx.cc; + let first = cc + usize::from(file.merged_has_alpha()); + let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default(); + // Photoshop lists every extra channel, the merged transparency first when there is one. + let skip = usize::from(file.merged_has_alpha() && names.len() == usize::from(file.header.channels).saturating_sub(cc)); + let names = names.get(skip..).unwrap_or_default(); + // Which planes hold spot ink in Photoshop's polarity (0 = solid): the DisplayInfo records + // the channel options are read from below, the transparency's first when `skip` is 1. + // A file from an earlier PhotoCraft stores them straight as it was written, + // past the channels of the Photoshop file it opened, if any. + let straight_from = if earlier_photocraft_spot_planes(file) { photoshop_identified_channels(file) } else { usize::MAX }; + let photoshop_spots = if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) { + crate::channel_map::spot_flags(&r.data, true, skip) + } else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) { + crate::channel_map::spot_flags(&r.data, false, skip) + } else { + Vec::new() + }; + for (k, idx) in (first..usize::from(file.header.channels)).enumerate() { + let Some(p) = merged_plane(all, idx, plane) else { + cx.warn_unreadable_data(format!("merged extra channel {idx} is incomplete and was not imported")); + break; + }; + let mut raw = be_to_ne_plane(p, depth, n); + if k < straight_from && photoshop_spots.get(k).copied().unwrap_or(false) { + crate::channel_map::photoshop_spot_plane(&mut raw, depth); + } + let mut s = Surface::new(cx.mask_fmt); + s.write_interleaved(canvas, &raw); + s.prune(); + let name = names.get(k).cloned().unwrap_or_else(|| format!("Alpha {}", k + 1)); + doc.channels.push(AlphaChannel::new(name, s)); + } + if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) { + crate::channel_map::apply_display_info(&r.data, true, skip, &mut doc.channels); + } else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) { + crate::channel_map::apply_display_info(&r.data, false, skip, &mut doc.channels); + } + if let Some(r) = file.resource(crate::channel_map::QUICK_MASK_INFO) + && r.data.len() >= 2 + && let Some(k) = usize::from(u16::from_be_bytes([r.data[0], r.data[1]])).checked_sub(first) + && k < doc.channels.len() + { + doc.quick_mask = Some(doc.channels.remove(k)); + } +} + #[cfg(test)] mod tests; diff --git a/crates/io/src/smart_map/export.rs b/crates/io/src/smart_map/export.rs index 7020fabec1..e057a7032f 100644 --- a/crates/io/src/smart_map/export.rs +++ b/crates/io/src/smart_map/export.rs @@ -5,7 +5,10 @@ use super::import::{ colour_rgbc, enum_param, from_hex, gallery_item, known_by_command, pf_range, pi_range, seed_param, }; use super::placed::enumv; -use super::*; +use super::{ + Class, Descriptor, FilterStack, Id, J, ReferenceItem, SmartFilter, UNSUPPORTED_FILTER, UnicodeString, Value, camera_raw, displace, hue_sat, + perspective_warp, +}; // ---------- writing ---------- diff --git a/crates/io/src/smart_map/import.rs b/crates/io/src/smart_map/import.rs index 41fce38a0d..55bd79ec06 100644 --- a/crates/io/src/smart_map/import.rs +++ b/crates/io/src/smart_map/import.rs @@ -1,6 +1,9 @@ use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc, whole}; use super::placed::enumv; -use super::*; +use super::{ + BlendMode, Descriptor, Id, J, Map, ReferenceItem, SmartFilter, UNSUPPORTED_FILTER, UnicodeString, Value, bool_or, camera_raw, displace, enum_of, get_desc, + hue_sat, json, num, perspective_warp, text_of, +}; // ---------- the filters we model ---------- @@ -464,12 +467,20 @@ const WAVE_KEYS: [&str; 10] = ["Wvtp", "NmbG", "WLMn", "WLMx", "AmMn", "AmMx", " /// Tiles its colours). pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descriptor) -> Option<(&'static str, J)> { let k = KNOWN.iter().find(|k| k.class == class)?; - let params = match (class, f) { - ("adaptCorrect" | "Invr", None) => json!({}), - (c, None) if NO_OPTIONS.contains(&c) => json!({}), - (_, None) => return None, - // Exactly the settings Photoshop writes (and we write back); an extra or repeated one keeps - // the filter verbatim rather than lose it on save. + let params = match f { + None if class == "adaptCorrect" || class == "Invr" || NO_OPTIONS.contains(&class) => json!({}), + None => return None, + Some(f) => distort_filter_params(class, f) + .or_else(|| blur_filter_params(class, f)) + .or_else(|| pixel_filter_params(class, f, item)) + .or_else(|| stylize_filter_params(class, f, item)) + .or_else(|| other_filter_params(class, f))?, + }; + Some((k.command, params)) +} + +fn distort_filter_params(class: &str, f: &Descriptor) -> Option { + Some(match (class, Some(f)) { ("Pnch", Some(f)) if exact_keys(f, &["Amnt"]) => json!({"amount": int(f, "Amnt")?}), ("Twrl", Some(f)) if exact_keys(f, &["Angl"]) => json!({"angle": int(f, "Angl")?}), ("Rple", Some(f)) if exact_keys(f, &["Amnt", "RplS"]) => json!({"amount": int(f, "Amnt")?, "size": enum_name(f, "RplS", "RplS", &RIPPLE_SIZE)?}), @@ -499,6 +510,12 @@ pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descripto "seed": (int(f, "RndS")? as u32), }) } + _ => return None, + }) +} + +fn blur_filter_params(class: &str, f: &Descriptor) -> Option { + Some(match (class, Some(f)) { ("GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm ", Some(f)) => json!({"radius": px(f, "Rds ")?}), ("MtnB", Some(f)) => json!({"angle": int(f, "Angl")?, "distance": px(f, "Dstn")?}), ("UnsM", Some(f)) => json!({"amount": px(f, "Amnt")?, "radius": px(f, "Rds ")?, "threshold": int(f, "Thsh")?}), @@ -529,6 +546,12 @@ pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descripto "method": enum_name(f, "BlrM", "BlrM", &RADIAL_METHOD)?, "quality": enum_name(f, "BlrQ", "BlrQ", &RADIAL_QUALITY)?, }), + _ => return None, + }) +} + +fn pixel_filter_params(class: &str, f: &Descriptor, item: &Descriptor) -> Option { + Some(match (class, Some(f)) { ("Msc ", Some(f)) => json!({"cellSize": px(f, "ClSz")?}), ("Mztn", Some(f)) if only_keys(f, &["MztT"]) => json!({"type": enum_name(f, "MztT", "MztT", &MEZZOTINT_TYPES)?}), ("ClrH", Some(f)) => color_halftone_params(f)?, @@ -551,6 +574,12 @@ pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descripto } p } + _ => return None, + }) +} + +fn stylize_filter_params(class: &str, f: &Descriptor, item: &Descriptor) -> Option { + Some(match (class, Some(f)) { ("Wnd ", Some(f)) => json!({ "method": enum_from(f, "WndM", "WndM", &WIND_METHODS)?, "direction": enum_from(f, "Drct", "Drct", &WIND_DIRECTIONS)?, @@ -564,6 +593,12 @@ pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descripto "maskIncompleteBlocks": bool_at(f, "ExtM")?, }), ("Tls ", Some(f)) => tiles_params(f, item)?, + _ => return None, + }) +} + +fn other_filter_params(class: &str, f: &Descriptor) -> Option { + Some(match (class, Some(f)) { ("Ofst", Some(f)) if only_keys(f, &["Hrzn", "Vrtc", "Fl "]) => { json!({"horizontal": int(f, "Hrzn")?, "vertical": int(f, "Vrtc")?, "undefinedAreas": enum_from(f, "Fl ", "FlMd", &OFFSET_FILL)?}) } @@ -578,10 +613,8 @@ pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descripto ("Lvls", Some(f)) => levels_params(f)?, ("Crvs", Some(f)) => curves_params(f)?, _ => return None, - }; - Some((k.command, params)) + }) } - // ---------- Filter Gallery ---------- // // Filter › Filter Gallery stores its effect stack in a `GEfc` filter (filterID `GEfc`). Photoshop diff --git a/crates/io/src/smart_map/placed.rs b/crates/io/src/smart_map/placed.rs index 9bdb52bc1c..20079f9840 100644 --- a/crates/io/src/smart_map/placed.rs +++ b/crates/io/src/smart_map/placed.rs @@ -1,5 +1,5 @@ use super::export::{set, set_before, unit}; -use super::*; +use super::{Affine, BezierMesh, Descriptor, Id, ObjectArray, UnicodeString, Value, VersionedDescriptor, Warp, WarpStyle, get_desc, num, text_of}; /// Everything needed to write the placed-layer blocks of a smart object. #[derive(Clone, Debug)] diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index 5ec8b5edb2..e9a6b92a21 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -593,49 +593,19 @@ fn write_pixels(surface: &mut Surface, px: &Pixels, x: i32, y: i32) -> Result<() Ok(()) } -/// Imports an XCF file (already inflated when it was gzipped). -pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result { - if !is_xcf(bytes) { - return Err(invalid("not an XCF file")); - } - let mut c = Cursor { b: bytes, pos: MAGIC.len(), wide: false }; - let tag = c.take(5)?; - let version = match tag { - b"file\0" => 0, - [b'v', a, b, d, 0] if a.is_ascii_digit() && b.is_ascii_digit() && d.is_ascii_digit() => { - u32::from(a - b'0') * 100 + u32::from(b - b'0') * 10 + u32::from(d - b'0') - } - _ => return Err(invalid("unknown XCF version tag")), - }; - c.wide = version >= 11; - let mut warnings = Warnings::default(); - if version > KNOWN_VERSION { - warnings.note(&format!("XCF version {version} is newer than this reader (version {KNOWN_VERSION}); unknown parts were skipped")); - } - let (w, h, base_type) = (c.u32()?, c.u32()?, c.u32()?); - if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { - return Err(invalid(format!("canvas {w}x{h} must be 1 to {MAX_SIDE} pixels a side"))); - } - if (w as usize).saturating_mul(h as usize).saturating_mul(16) > MAX_PIXEL_BYTES { - return Err(invalid("the canvas exceeds the 1 GiB pixel limit")); - } - let precision = if version >= 4 { Precision::from_header(version, c.u32()?)? } else { Precision::GAMMA8 }; - let mode = match base_type { - 0 => ColorMode::Rgb, - 1 => ColorMode::Grayscale, - 2 => ColorMode::Rgb, - t => return Err(invalid(format!("unknown image type {t}"))), - }; - let depth = precision.depth(); - if base_type == 2 { - warnings.note("the indexed image opens as RGB"); - } - if !precision.float && precision.bytes == 4 { - warnings.note("32-bit integer samples open as 16-bit"); - } +struct ImageMetadata { + compression: Compression, + colormap: Vec<[u8; 3]>, + resolution: Option<(f32, f32)>, + guides: Vec<(i32, u8)>, + icc: Option>, + comment: Option, + path_count: usize, +} +fn read_image_metadata(c: &mut Cursor<'_>) -> Result { // Image properties. - let image_props = props(&mut c)?; + let image_props = props(c)?; let mut compression = Compression::None; let mut colormap = Vec::new(); let mut resolution = None; @@ -683,6 +653,52 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result) -> Result { + if !is_xcf(bytes) { + return Err(invalid("not an XCF file")); + } + let mut c = Cursor { b: bytes, pos: MAGIC.len(), wide: false }; + let tag = c.take(5)?; + let version = match tag { + b"file\0" => 0, + [b'v', a, b, d, 0] if a.is_ascii_digit() && b.is_ascii_digit() && d.is_ascii_digit() => { + u32::from(a - b'0') * 100 + u32::from(b - b'0') * 10 + u32::from(d - b'0') + } + _ => return Err(invalid("unknown XCF version tag")), + }; + c.wide = version >= 11; + let mut warnings = Warnings::default(); + if version > KNOWN_VERSION { + warnings.note(&format!("XCF version {version} is newer than this reader (version {KNOWN_VERSION}); unknown parts were skipped")); + } + let (w, h, base_type) = (c.u32()?, c.u32()?, c.u32()?); + if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { + return Err(invalid(format!("canvas {w}x{h} must be 1 to {MAX_SIDE} pixels a side"))); + } + if (w as usize).saturating_mul(h as usize).saturating_mul(16) > MAX_PIXEL_BYTES { + return Err(invalid("the canvas exceeds the 1 GiB pixel limit")); + } + let precision = if version >= 4 { Precision::from_header(version, c.u32()?)? } else { Precision::GAMMA8 }; + let mode = match base_type { + 0 => ColorMode::Rgb, + 1 => ColorMode::Grayscale, + 2 => ColorMode::Rgb, + t => return Err(invalid(format!("unknown image type {t}"))), + }; + let depth = precision.depth(); + if base_type == 2 { + warnings.note("the indexed image opens as RGB"); + } + if !precision.float && precision.bytes == 4 { + warnings.note("32-bit integer samples open as 16-bit"); + } + + let ImageMetadata { compression, colormap, resolution, guides, icc, comment, mut path_count } = read_image_metadata(&mut c)?; + let mut layer_ptrs = Vec::new(); loop { let p = c.ptr()?; @@ -814,6 +830,12 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result 0 { image.warnings.note(&format!("{path_count} path(s) were not imported")); } + add_document_warnings(&mut image, &document, precision, linear_compositing); + ctl.progress(1.0); + Ok(ImportResult { document, warnings: image.warnings.finish(), source_read_only: true, preview_only: false }) +} + +fn add_document_warnings(image: &mut Image<'_>, document: &Document, precision: Precision, linear_compositing: bool) { // GIMP clips a layer in any mode but Normal to the layers beneath it, so it shows nothing where // they are transparent; PhotoCraft (like Photoshop) shows it there. Only tell when there is // transparency to show through: a bottom layer that is not opaque. @@ -832,8 +854,6 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result().0.iter().enumerate() { + match i % 48 { + 0..16 => assert_eq!(px[4], 1.0, "{context}: opaque region"), + 16..32 => assert!((px[4] - 0.5).abs() <= tolerance, "{context}: translucent region: {px:?}"), + _ => assert_eq!(px[4], 0.0, "{context}: empty region"), + } + } +} + +fn compare_flat_and_layered_mixed_cmyk_regions() { let custom = photocraft_cms::synth::cmyk_profile(&photocraft_cms::synth::CmykParams { description: "Mixed regions uncoated".into(), tvi: [0.26, 0.26, 0.26, 0.3], @@ -123,15 +147,8 @@ fn flat_and_layered_tiff_agree_for_mixed_cmyk_regions() { assert_eq!(reference.icc.as_deref(), profile.as_deref().map(Vec::as_slice), "{context}"); assert!(image.meta.photoshop_layers.is_none(), "{context}"); assert!(reference.meta.photoshop_layers.is_some(), "{context}"); - for (decoded, bytes) in [(&image, &flat.bytes), (&reference, &layered.bytes)] { - assert_eq!(decoded.dimensions(), (48, 16), "{context}"); - assert_eq!(decoded.layout(), if opaque { ChannelLayout::Cmyk } else { ChannelLayout::CmykA }, "{context}"); - assert_eq!(decoded.sample_type(), sample, "{context}"); - assert_eq!(decoded.meta.dpi, Some((300.0, 300.0)), "{context}"); - assert_eq!(tag(bytes, 262), Some(5), "{context}"); - assert_eq!(tag(bytes, 277), Some(if opaque { 4 } else { 5 }), "{context}"); - assert_eq!(tag(bytes, 338), if opaque { None } else { Some(2) }, "{context}"); - } + assert_tiff_layout(&image, &flat.bytes, opaque, sample, &context); + assert_tiff_layout(&reference, &layered.bytes, opaque, sample, &context); // The PSD-backed layered path inverts CMYK samples twice, so allow one stored level. let tolerance = match depth { SampleType::U8 => 1.0 / 255.0, @@ -144,13 +161,7 @@ fn flat_and_layered_tiff_agree_for_mixed_cmyk_regions() { let difference = actual.iter().zip(&expected).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); assert!(difference <= tolerance + 1e-6, "{context}: maximum sample difference {difference}"); if !opaque { - for (i, px) in actual.as_chunks::<5>().0.iter().enumerate() { - match i % 48 { - 0..16 => assert_eq!(px[4], 1.0, "{context}: opaque region"), - 16..32 => assert!((px[4] - 0.5).abs() <= tolerance, "{context}: translucent region: {px:?}"), - _ => assert_eq!(px[4], 0.0, "{context}: empty region"), - } - } + assert_mixed_region_alpha(&actual, tolerance, &context); } let back = photocraft_io::import("regions.tiff", &flat.bytes).unwrap().document; assert_eq!((back.mode, back.depth), (ColorMode::Cmyk, depth), "{context}"); diff --git a/crates/io/tests/it/common/mod.rs b/crates/io/tests/it/common/mod.rs index c964b08b82..7bb010f1be 100644 --- a/crates/io/tests/it/common/mod.rs +++ b/crates/io/tests/it/common/mod.rs @@ -236,6 +236,12 @@ fn color_close(a: &Color, b: &Color, ctx: &str) { pub fn assert_layers_eq(a: &Layer, b: &Layer, path: &str) { let ctx = format!("{path}/{}", a.name); + assert_layer_properties(a, b, &ctx); + assert_layer_mask_eq(a, b, &ctx); + assert_layer_content_eq(a, b, &ctx); +} + +fn assert_layer_properties(a: &Layer, b: &Layer, ctx: &str) { assert_eq!(a.name, b.name, "{ctx}: name"); assert_eq!(a.visible, b.visible, "{ctx}: visible"); assert_eq!(a.locks, b.locks, "{ctx}: locks"); @@ -259,6 +265,9 @@ pub fn assert_layers_eq(a: &Layer, b: &Layer, path: &str) { let other = b.fill_cache.as_ref().expect("fill cache kept"); surface_eq(&fc.surface, &other.surface, &format!("{ctx}: fill cache")); } +} + +fn assert_layer_mask_eq(a: &Layer, b: &Layer, ctx: &str) { match (&a.mask, &b.mask) { (None, None) => {} (Some(x), Some(y)) => { @@ -270,28 +279,27 @@ pub fn assert_layers_eq(a: &Layer, b: &Layer, path: &str) { } _ => panic!("{ctx}: mask presence differs"), } +} + +fn assert_layer_content_eq(a: &Layer, b: &Layer, ctx: &str) { match (&a.content, &b.content) { - (LayerContent::Raster(x), LayerContent::Raster(y)) => surface_eq(x, y, &ctx), + (LayerContent::Raster(x), LayerContent::Raster(y)) => surface_eq(x, y, ctx), (LayerContent::Group(x), LayerContent::Group(y)) => { assert_eq!(x.expanded, y.expanded, "{ctx}: expanded"); assert_eq!(x.children.len(), y.children.len(), "{ctx}: child count"); for (p, q) in x.children.iter().zip(&y.children) { - assert_layers_eq(p, q, &ctx); + assert_layers_eq(p, q, ctx); } } (LayerContent::Adjustment(x), LayerContent::Adjustment(y)) => assert_eq!(x, y, "{ctx}: adjustment"), - (LayerContent::Fill(Fill::Solid(x)), LayerContent::Fill(Fill::Solid(y))) => color_close(x, y, &ctx), + (LayerContent::Fill(Fill::Solid(x)), LayerContent::Fill(Fill::Solid(y))) => color_close(x, y, ctx), (LayerContent::Fill(x), LayerContent::Fill(y)) => assert_eq!(x, y, "{ctx}: fill"), (LayerContent::Text(x), LayerContent::Text(y)) => { assert_eq!(x.text, y.text, "{ctx}: text"); - surface_eq(x.cache.as_ref().unwrap(), y.cache.as_ref().unwrap(), &ctx); - } - (LayerContent::Shape(x), LayerContent::Shape(y)) => { - surface_eq(x.cache.as_ref().unwrap(), y.cache.as_ref().unwrap(), &ctx); - } - (LayerContent::Smart(x), LayerContent::Smart(y)) => { - surface_eq(x.cache.as_ref().unwrap(), y.cache.as_ref().unwrap(), &ctx); + surface_eq(x.cache.as_ref().unwrap(), y.cache.as_ref().unwrap(), ctx); } + (LayerContent::Shape(x), LayerContent::Shape(y)) => surface_eq(x.cache.as_ref().unwrap(), y.cache.as_ref().unwrap(), ctx), + (LayerContent::Smart(x), LayerContent::Smart(y)) => surface_eq(x.cache.as_ref().unwrap(), y.cache.as_ref().unwrap(), ctx), (x, y) => panic!("{ctx}: kind {} vs {}", x.kind_name(), y.kind_name()), } } diff --git a/crates/io/tests/it/tiff_layers.rs b/crates/io/tests/it/tiff_layers.rs index 11e37591bc..70ec2fef2e 100644 --- a/crates/io/tests/it/tiff_layers.rs +++ b/crates/io/tests/it/tiff_layers.rs @@ -468,7 +468,6 @@ fn dtf_like_spot_is_written_in_full() { use photocraft_color::{Color, PixelFormat}; use photocraft_doc::{AlphaChannel, Layer}; use photocraft_geom::{Rect, Size}; - use photocraft_psd::tiff::resources_from_bytes; use photocraft_raster::Surface; let (w, h) = (900u32, 360u32); @@ -501,77 +500,96 @@ fn dtf_like_spot_is_written_in_full() { channel.spot = Some((Color::rgb(1.0, 0.0, 0.0), 0.6)); doc.channels.push(channel); + verify_dtf_exports(&doc, &spot_bytes, w, h); +} + +fn assert_spot_resources(resources: &[u8], name: &str) { + use photocraft_psd::tiff::resources_from_bytes; + let (blocks, warnings) = resources_from_bytes(resources).unwrap(); + assert!(warnings.is_empty(), "{name} {warnings:?}"); + let block = |id: u16| blocks.iter().find(|b| b.id == id).unwrap_or_else(|| panic!("{name} missing {id}")); + // "Spot Color 1" is 12 characters: Photoshop stores 13 bytes and pads the 8BIM block, not the string. + assert_eq!(block(1006).data, b"\x0cSpot Color 1", "{name}"); + assert_eq!(block(1045).data.len(), 30, "{name}"); + let info = &block(1077).data; + assert_eq!(info.len(), 17, "{name}"); + assert_eq!(u16::from_be_bytes([info[14], info[15]]), 60, "{name} solidity"); + assert_eq!(info[16], 2, "{name} spot kind"); + // Photoshop numbers a new document's channels from 3. + assert_eq!(block(1053).data, 3u32.to_be_bytes(), "{name} channel id"); +} + +fn verify_dtf_samples(bytes: &[u8], stored_spot: &[u8], w: u32, h: u32, name: &str) -> Vec { + let img = photocraft_codecs::decode(bytes).unwrap(); + assert!(!img.layout().has_alpha(), "{name}: {:?}", img.layout()); + assert_eq!(img.layout().color_channels(), 3, "{name}"); + assert_eq!(img.meta.extra_samples.len(), 1, "{name}"); + assert_eq!(img.meta.extra_samples[0].kind, 0, "{name}"); + assert_eq!(img.meta.extra_samples[0].data, stored_spot, "{name} own decoder"); + let (spp, bps, extra, rows, samples) = independent_samples(bytes); + assert_eq!(spp, 4, "{name}"); + assert_eq!(bps, vec![8, 8, 8, 8], "{name}"); + assert_eq!(extra, vec![0], "{name} ExtraSamples"); + assert!(rows > 0 && rows < h, "{name} rows_per_strip {rows}"); + assert_plane(&samples, 4, 3, stored_spot); + let at = (10 * w as usize + 10) * 4; + assert_eq!(&samples[at..at + 3], &[255, 255, 255], "{name} matted rgb"); + samples +} + +fn assert_dtf_channel(back: &Document, spot_bytes: &[u8], w: u32, h: u32, name: &str) { + use photocraft_geom::Rect; + assert_eq!(back.channels.len(), 1, "{name}"); + assert_eq!(back.channels[0].name, "Spot Color 1"); + let (ink, sol) = back.channels[0].spot.expect("spot"); + assert_eq!(ink.to_rgb(), [1.0, 0.0, 0.0], "{name}"); + assert!((sol - 0.6).abs() < 1e-4, "{name}"); + let area = Rect::new(0, 0, w as i32, h as i32); + assert_eq!(back.channels[0].surface.to_interleaved(area), spot_bytes, "{name} reimport"); +} + +fn verify_dtf_layers(bytes: &[u8], layer_tag: Option>, back: &Document, layers: bool, name: &str) { + if layers { + let layer_tag = layer_tag.expect("layer tag"); + let (isd, w) = ImageSourceData::from_bytes(&layer_tag).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let info = isd.layer_info.expect("layers"); + assert!(!info.merged_alpha, "{name}"); + assert!(info.layers.iter().all(|l| l.flags.0 & 0x08 != 0), "{name} photoshop flag"); + assert!(info.layers.iter().all(|l| l.blocks.iter().any(|b| &b.key == b"lnsr")), "{name} lnsr"); + let mask = isd.global_layer_mask.expect("LMsk"); + assert_eq!(mask.data.len(), 14, "{name}"); + assert_eq!(mask.opacity(), Some(50)); + assert_eq!(mask.kind(), Some(128)); + assert_photoshop_layered_tiff(bytes, true); + assert_eq!(back.layers.len(), 2, "{name}"); + let ink = back.layers.iter().find(|l| l.name == "Ink").expect("ink layer"); + let px = ink.surface().expect("ink pixels").pixel(100, 100); + assert!((px[3] - 0.5).abs() < 0.02, "{name} layer alpha {px:?}"); + let outside = ink.surface().expect("ink pixels").pixel(0, 0); + assert!(outside[3] < 0.02, "{name} transparent pixel {outside:?}"); + } else { + assert!(layer_tag.is_none(), "{name}"); + } +} + +fn verify_dtf_exports(doc: &Document, spot_bytes: &[u8], w: u32, h: u32) { let mut seen = Vec::new(); for (name, layers) in [("flat", false), ("layered", true)] { let opts = ExportOptions { tiff_layers: layers, ..ExportOptions::default() }; - let r = export(&doc, "dtf.tif", &opts).unwrap(); + let r = export(doc, "dtf.tif", &opts).unwrap(); assert!(!r.warnings.iter().any(|w| w.contains("not written")), "{name}: {:?}", r.warnings); - let img = photocraft_codecs::decode(&r.bytes).unwrap(); - assert!(!img.layout().has_alpha(), "{name}: {:?}", img.layout()); - assert_eq!(img.layout().color_channels(), 3, "{name}"); - assert_eq!(img.meta.extra_samples.len(), 1, "{name}"); - assert_eq!(img.meta.extra_samples[0].kind, 0, "{name}"); // Photoshop stores spot ink inverted: document 255 (solid) is file 0. let stored_spot: Vec = spot_bytes.iter().map(|b| 255 - b).collect(); - assert_eq!(img.meta.extra_samples[0].data, stored_spot, "{name} own decoder"); - let (spp, bps, extra, rows, samples) = independent_samples(&r.bytes); - assert_eq!(spp, 4, "{name}"); - assert_eq!(bps, vec![8, 8, 8, 8], "{name}"); - assert_eq!(extra, vec![0], "{name} ExtraSamples"); - assert!(rows > 0 && rows < h, "{name} rows_per_strip {rows}"); - assert_plane(&samples, 4, 3, &stored_spot); + let samples = verify_dtf_samples(&r.bytes, &stored_spot, w, h, name); seen.push(samples.clone()); - - // Outside the artwork the composite is matted to white (Save Transparency off). The - // spot at that pixel is not zero, so a reader that binds the name to the alpha fails. - let at = (10 * w as usize + 10) * 4; - assert_eq!(&samples[at..at + 3], &[255, 255, 255], "{name} matted rgb"); let (resources, layer_tag) = tags(&r.bytes); - let resources = resources.expect("photoshop resources"); - let (blocks, warnings) = resources_from_bytes(&resources).unwrap(); - assert!(warnings.is_empty(), "{name} {warnings:?}"); - let block = |id: u16| blocks.iter().find(|b| b.id == id).unwrap_or_else(|| panic!("{name} missing {id}")); - // "Spot Color 1" is 12 characters: Photoshop stores 13 bytes and pads the 8BIM block, not the string. - assert_eq!(block(1006).data, b"\x0cSpot Color 1", "{name}"); - assert_eq!(block(1045).data.len(), 30, "{name}"); - let info = &block(1077).data; - assert_eq!(info.len(), 17, "{name}"); - assert_eq!(u16::from_be_bytes([info[14], info[15]]), 60, "{name} solidity"); - assert_eq!(info[16], 2, "{name} spot kind"); - // Photoshop numbers a new document's channels from 3. - assert_eq!(block(1053).data, 3u32.to_be_bytes(), "{name} channel id"); + assert_spot_resources(&resources.expect("photoshop resources"), name); let back = import("dtf.tif", &r.bytes).unwrap().document; - assert_eq!(back.channels.len(), 1, "{name}"); - assert_eq!(back.channels[0].name, "Spot Color 1"); - let (ink, sol) = back.channels[0].spot.expect("spot"); - assert_eq!(ink.to_rgb(), [1.0, 0.0, 0.0], "{name}"); - assert!((sol - 0.6).abs() < 1e-4, "{name}"); - let area = Rect::new(0, 0, w as i32, h as i32); - assert_eq!(back.channels[0].surface.to_interleaved(area), spot_bytes, "{name} reimport"); - if layers { - let layer_tag = layer_tag.expect("layer tag"); - let (isd, w) = ImageSourceData::from_bytes(&layer_tag).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let info = isd.layer_info.expect("layers"); - assert!(!info.merged_alpha, "{name}"); - assert!(info.layers.iter().all(|l| l.flags.0 & 0x08 != 0), "{name} photoshop flag"); - assert!(info.layers.iter().all(|l| l.blocks.iter().any(|b| &b.key == b"lnsr")), "{name} lnsr"); - let mask = isd.global_layer_mask.expect("LMsk"); - assert_eq!(mask.data.len(), 14, "{name}"); - assert_eq!(mask.opacity(), Some(50)); - assert_eq!(mask.kind(), Some(128)); - assert_photoshop_layered_tiff(&r.bytes, true); - assert_eq!(back.layers.len(), 2, "{name}"); - let ink = back.layers.iter().find(|l| l.name == "Ink").expect("ink layer"); - let px = ink.surface().expect("ink pixels").pixel(100, 100); - assert!((px[3] - 0.5).abs() < 0.02, "{name} layer alpha {px:?}"); - let outside = ink.surface().expect("ink pixels").pixel(0, 0); - assert!(outside[3] < 0.02, "{name} transparent pixel {outside:?}"); - } else { - assert!(layer_tag.is_none(), "{name}"); - } + assert_dtf_channel(&back, spot_bytes, w, h, name); + verify_dtf_layers(&r.bytes, layer_tag, &back, layers, name); } assert_eq!(seen[0], seen[1], "flat and layered IFD samples differ"); } From 2b0b11848c74dfd5bf17c2a49c7307a862c2604c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 18/35] Refactor paint for strict Clippy checks --- crates/paint/examples/bench_brush.rs | 2 +- crates/paint/src/presets.rs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/paint/examples/bench_brush.rs b/crates/paint/examples/bench_brush.rs index a9360b45fb..efd9c010f1 100644 --- a/crates/paint/examples/bench_brush.rs +++ b/crates/paint/examples/bench_brush.rs @@ -8,7 +8,7 @@ use std::time::Instant; use photocraft_color::{PixelFormat, SampleType}; use photocraft_geom::Rect; -use photocraft_paint::*; +use photocraft_paint::{BrushSettings, Dynamic, Scattering, ShapeDynamics, StrokePoint, StrokeRenderer, Texture, presets}; use photocraft_raster::Surface; fn run(fmt: PixelFormat, label: &str, brush: &BrushSettings) { diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index dd87d2554e..e40902a78f 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -4,7 +4,10 @@ //! Special Effects. Every preset is plain [`BrushSettings`] data, so it serialises, journals and //! can be edited like any user preset. -use crate::brush::*; +use crate::brush::{ + BrushPreset, BrushSettings, ColorDynamics, Control, DualBrush, Dynamic, MaskMode, Pattern, PatternStyle, Scattering, ShapeDynamics, Smoothing, Texture, + TipShape, Transfer, +}; use crate::procedural::{bristle_tip, chalk_tip, charcoal_tip, grass_tip, leaf_tip, rake_tip, spatter_tip, sponge_tip, star_tip}; /// Preset groups, in panel order. From ba25f585bd688983f80bba4d872b6e54345afc7e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 19/35] Refactor psd for strict Clippy checks --- crates/psd/examples/bench_layer_block.rs | 2 +- crates/psd/src/tiff/transcode.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/psd/examples/bench_layer_block.rs b/crates/psd/examples/bench_layer_block.rs index 2b48de1d28..4e48f4b3dc 100644 --- a/crates/psd/examples/bench_layer_block.rs +++ b/crates/psd/examples/bench_layer_block.rs @@ -1,6 +1,6 @@ //! Serialization of one 24 MP raw RGB layer in Lr16/Lr32, without compression or disk I/O. //! Run with `cargo run --release -p photocraft-psd --example bench_layer_block`. -use photocraft_psd::*; +use photocraft_psd::{ChannelData, ColorMode, Compression, Header, ImageData, LayerInfo, LayerInfoPlacement, LayerRecord, Rect, Result, Version, testgen}; use std::hint::black_box; use std::time::Instant; diff --git a/crates/psd/src/tiff/transcode.rs b/crates/psd/src/tiff/transcode.rs index c006dc4fa0..31d12b702f 100644 --- a/crates/psd/src/tiff/transcode.rs +++ b/crates/psd/src/tiff/transcode.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{ByteOrder, LayerMask, MAX_DEPTH, PsdError, Reader, Result, TaggedBlock, Version, mask_parameter_bytes, uses_long_length}; /// Converts the tagged blocks after the 37724 header string from `from` to `to`. pub fn transcode_blocks(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { From 52800a7b3dec235cac5f51456617b16a4dcd3342 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 20/35] Refactor raw for strict Clippy checks --- crates/raw/src/testgen/dng.rs | 334 +++++++++++++++++++--------------- 1 file changed, 190 insertions(+), 144 deletions(-) diff --git a/crates/raw/src/testgen/dng.rs b/crates/raw/src/testgen/dng.rs index 02a8d7b621..f9d252c391 100644 --- a/crates/raw/src/testgen/dng.rs +++ b/crates/raw/src/testgen/dng.rs @@ -182,6 +182,29 @@ impl DngSpec { pub fn build(&self) -> Vec { let mut t = TiffBuilder { big_endian: self.big_endian, ..Default::default() }; + let mut raw = self.raw_base_tags(); + self.push_storage_tags(&mut t, &mut raw); + self.push_geometry_tags(&mut raw); + if let Some(o) = &self.opcode_list2 { + raw.push((51009, Val::Undefined(o.clone()))); + } + if let Some(l) = &self.linearization { + raw.push((50712, Val::Short(l.clone()))); + } + raw.extend(self.raw_extra.iter().cloned()); + let raw_ifd = t.ifd(raw); + // IFD0: a tiny RGB thumbnail plus the DNG metadata. + let thumb = t.blob(vec![128; 3 * 4]); + let mut ifd0 = self.ifd0_base_tags(thumb, raw_ifd); + self.push_color_tags(&mut ifd0); + ifd0.extend(self.ifd0_extra.iter().cloned()); + let i0 = t.ifd(ifd0); + t.chain = vec![i0]; + t.build() + } + + /// The raw IFD's tags that don't depend on how the image is stored. + fn raw_base_tags(&self) -> Vec<(u16, Val)> { let mut raw: Vec<(u16, Val)> = vec![ (254, Val::Long(vec![0])), (256, Val::Long(vec![self.width as u32])), @@ -202,166 +225,162 @@ impl DngSpec { raw.push((50710, Val::Byte(vec![0, 1, 2]))); raw.push((50711, Val::Short(vec![1]))); } + raw + } + + /// Encodes the image per `storage` into `t`'s blobs and adds the compression and + /// strip or tile tags that point at them. + fn push_storage_tags(&self, t: &mut TiffBuilder, raw: &mut Vec<(u16, Val)>) { match self.storage { DngStorage::DeflateStrips { rows, predictor } => { - use std::io::Write; - let mut offs = Vec::new(); - let mut lens = Vec::new(); - for y in (0..self.height).step_by(rows) { - let r = (y + rows).min(self.height) - y; - let n = self.width * self.samples; - let mut v: Vec = self.data[y * n..(y + r) * n].to_vec(); - if predictor == 2 { - // Horizontal differencing on the sample values, before byte packing - // (the reader undoes predictor after unpacking, per row, per channel). - let plane = if self.samples.is_multiple_of(3) { 3 } else { 1 }; - for row in v.chunks_mut(n) { - for i in (plane..row.len()).rev() { - row[i] = row[i].wrapping_sub(row[i - plane]); - } - } - } - // Pack the delta'd values with the file's byte order and bit depth. - let bytes: Vec = match self.bits { - 8 => v.iter().map(|&x| x as u8).collect(), - 16 => v.iter().flat_map(|&x| if self.big_endian { x.to_be_bytes() } else { x.to_le_bytes() }).collect(), - _ => v.iter().flat_map(|x| x.to_le_bytes()).collect(), - }; - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); - e.write_all(&bytes).expect("zlib"); - let z = e.finish().expect("zlib"); - lens.push(z.len() as u32); - offs.push(t.blob(z)); - } + let (offs, lens) = self.strip_blobs(t, rows, |y, r| self.deflate_strip(y, r, predictor)); raw.push((259, Val::Short(vec![8]))); raw.push((317, Val::Short(vec![predictor]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); + push_strip_tags(raw, rows, offs, lens); } DngStorage::Strips { rows } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); - for y in (0..self.height).step_by(rows) { - let b = self.pack(y..(y + rows).min(self.height)); - lens.push(b.len() as u32); - offs.push(t.blob(b)); - } + let (offs, lens) = self.strip_blobs(t, rows, |y, r| self.pack(y..y + r)); raw.push((259, Val::Short(vec![1]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); + push_strip_tags(raw, rows, offs, lens); } DngStorage::LossyJpegTiles { width: tw, height: th } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); let s = self.samples; - for ty in (0..self.height).step_by(th) { - for tx in (0..self.width).step_by(tw) { - // Edge tiles are padded by repeating the last row / column. - let mut tile = vec![0u8; tw * th * s]; - for y in 0..th { - for x in 0..tw { - let sy = (ty + y).min(self.height - 1); - let sx = (tx + x).min(self.width - 1); - for c in 0..s { - tile[(y * tw + x) * s + c] = self.sample8(self.data[(sy * self.width + sx) * s + c]); - } - } - } - let j = self.lossy_segments.get(offs.len()).cloned().unwrap_or_else(|| baseline_jpeg(&tile, tw, th, s)); - lens.push(j.len() as u32); - offs.push(t.blob(j)); - } - } + let (offs, lens) = self.tile_blobs(t, tw, th, |tile_no, tile: Vec| { + self.lossy_segments.get(tile_no).cloned().unwrap_or_else(|| baseline_jpeg(&tile, tw, th, s)) + }); raw.push((259, Val::Short(vec![34892]))); - raw.push((322, Val::Long(vec![tw as u32]))); - raw.push((323, Val::Long(vec![th as u32]))); - raw.push((324, Val::Blobs(offs))); - raw.push((325, Val::Long(lens))); + push_tile_tags(raw, tw, th, offs, lens); } DngStorage::LossyJpegStrips { rows } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); let n = self.width * self.samples; - for y in (0..self.height).step_by(rows) { - let r = (y + rows).min(self.height) - y; + let (offs, lens) = self.strip_blobs(t, rows, |y, r| { let strip: Vec = self.data[y * n..(y + r) * n].iter().map(|&v| self.sample8(v)).collect(); - let j = self.lossy_segments.get(offs.len()).cloned().unwrap_or_else(|| baseline_jpeg(&strip, self.width, r, self.samples)); - lens.push(j.len() as u32); - offs.push(t.blob(j)); - } + let strip_no = y / rows; + self.lossy_segments.get(strip_no).cloned().unwrap_or_else(|| baseline_jpeg(&strip, self.width, r, self.samples)) + }); raw.push((259, Val::Short(vec![34892]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); + push_strip_tags(raw, rows, offs, lens); } DngStorage::Lj92Strips { rows } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); - for y in (0..self.height).step_by(rows) { - let r = (y + rows).min(self.height) - y; - let n = self.width * self.samples; - let j = lj92_encode(&self.data[y * n..(y + r) * n], self.width, r, self.samples, self.bits as u8, 1, None); - lens.push(j.len() as u32); - offs.push(t.blob(j)); - } + let n = self.width * self.samples; + let (offs, lens) = + self.strip_blobs(t, rows, |y, r| lj92_encode(&self.data[y * n..(y + r) * n], self.width, r, self.samples, self.bits as u8, 1, None)); raw.push((259, Val::Short(vec![7]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); + push_strip_tags(raw, rows, offs, lens); } DngStorage::Lj92Tiles { width: tw, height: th } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); let s = self.samples; - for ty in (0..self.height).step_by(th) { - for tx in (0..self.width).step_by(tw) { - // Edge tiles are padded by repeating the last row / column. - let mut tile = vec![0u16; tw * th * s]; - for y in 0..th { - for x in 0..tw { - let sy = (ty + y).min(self.height - 1); - let sx = (tx + x).min(self.width - 1); - for c in 0..s { - tile[(y * tw + x) * s + c] = self.data[(sy * self.width + sx) * s + c]; - } - } - } - // CFA tiles as Adobe writes them: half width, 2 components. - let j = if s == 1 && tw % 2 == 0 { - lj92_encode(&tile, tw / 2, th, 2, self.bits as u8, 1, None) - } else { - lj92_encode(&tile, tw, th, s, self.bits as u8, 1, None) - }; - lens.push(j.len() as u32); - offs.push(t.blob(j)); + let (offs, lens) = self.tile_blobs(t, tw, th, |_, tile: Vec| { + // CFA tiles as Adobe writes them: half width, 2 components. + if s == 1 && tw % 2 == 0 { + lj92_encode(&tile, tw / 2, th, 2, self.bits as u8, 1, None) + } else { + lj92_encode(&tile, tw, th, s, self.bits as u8, 1, None) } - } + }); raw.push((259, Val::Short(vec![7]))); - raw.push((322, Val::Long(vec![tw as u32]))); - raw.push((323, Val::Long(vec![th as u32]))); - raw.push((324, Val::Blobs(offs))); - raw.push((325, Val::Long(lens))); + push_tile_tags(raw, tw, th, offs, lens); } DngStorage::JxlStrips { rows } => { - let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect(); - let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect(); + let (offs, lens) = self.jxl_blobs(t); raw.push((259, Val::Short(vec![52546]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); + push_strip_tags(raw, rows, offs, lens); } DngStorage::JxlTiles { width: tw, height: th } => { - let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect(); - let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect(); + let (offs, lens) = self.jxl_blobs(t); raw.push((259, Val::Short(vec![52546]))); - raw.push((322, Val::Long(vec![tw as u32]))); - raw.push((323, Val::Long(vec![th as u32]))); - raw.push((324, Val::Blobs(offs))); - raw.push((325, Val::Long(lens))); + push_tile_tags(raw, tw, th, offs, lens); } } + } + + /// One blob per strip of `rows` rows: `encode(first_row, rows_in_strip)` gives its bytes. + /// Returns the blob handles and lengths. + fn strip_blobs(&self, t: &mut TiffBuilder, rows: usize, mut encode: impl FnMut(usize, usize) -> Vec) -> (Vec, Vec) { + let mut offs = Vec::new(); + let mut lens = Vec::new(); + for y in (0..self.height).step_by(rows) { + let r = (y + rows).min(self.height) - y; + let bytes = encode(y, r); + lens.push(bytes.len() as u32); + offs.push(t.blob(bytes)); + } + (offs, lens) + } + + /// One blob per `tw`×`th` tile, in row-major tile order: `encode(tile_number, samples)`. + fn tile_blobs( + &self, + t: &mut TiffBuilder, + tw: usize, + th: usize, + mut encode: impl FnMut(usize, Vec) -> Vec, + ) -> (Vec, Vec) { + let mut offs = Vec::new(); + let mut lens = Vec::new(); + for ty in (0..self.height).step_by(th) { + for tx in (0..self.width).step_by(tw) { + let bytes = encode(offs.len(), self.tile_samples(tx, ty, tw, th)); + lens.push(bytes.len() as u32); + offs.push(t.blob(bytes)); + } + } + (offs, lens) + } + + /// The samples of the tile at (`tx`, `ty`). Edge tiles are padded by repeating the last row + /// / column. + fn tile_samples(&self, tx: usize, ty: usize, tw: usize, th: usize) -> Vec { + let s = self.samples; + let mut tile = vec![T::default(); tw * th * s]; + for y in 0..th { + for x in 0..tw { + let sy = (ty + y).min(self.height - 1); + let sx = (tx + x).min(self.width - 1); + for c in 0..s { + tile[(y * tw + x) * s + c] = T::from_sample(self, self.data[(sy * self.width + sx) * s + c]); + } + } + } + tile + } + + /// A deflated strip of `r` rows from row `y`, optionally with the horizontal-differencing + /// predictor applied. + fn deflate_strip(&self, y: usize, r: usize, predictor: u16) -> Vec { + use std::io::Write; + let n = self.width * self.samples; + let mut v: Vec = self.data[y * n..(y + r) * n].to_vec(); + if predictor == 2 { + // Horizontal differencing on the sample values, before byte packing + // (the reader undoes predictor after unpacking, per row, per channel). + let plane = if self.samples.is_multiple_of(3) { 3 } else { 1 }; + for row in v.chunks_mut(n) { + for i in (plane..row.len()).rev() { + row[i] = row[i].wrapping_sub(row[i - plane]); + } + } + } + // Pack the delta'd values with the file's byte order and bit depth. + let bytes: Vec = match self.bits { + 8 => v.iter().map(|&x| x as u8).collect(), + 16 => v.iter().flat_map(|&x| if self.big_endian { x.to_be_bytes() } else { x.to_le_bytes() }).collect(), + _ => v.iter().flat_map(|x| x.to_le_bytes()).collect(), + }; + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + e.write_all(&bytes).expect("zlib"); + e.finish().expect("zlib") + } + + /// The pre-encoded JPEG XL segments as blobs. + fn jxl_blobs(&self, t: &mut TiffBuilder) -> (Vec, Vec) { + let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect(); + let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect(); + (offs, lens) + } + + /// Active area and default crop tags. + fn push_geometry_tags(&self, raw: &mut Vec<(u16, Val)>) { if let Some(a) = self.active_area { raw.push((50829, Val::Long(a.to_vec()))); } @@ -374,17 +393,12 @@ impl DngSpec { } else if let Some(size) = self.default_crop_size_only { raw.push((50720, Val::Long(size.to_vec()))); } - if let Some(o) = &self.opcode_list2 { - raw.push((51009, Val::Undefined(o.clone()))); - } - if let Some(l) = &self.linearization { - raw.push((50712, Val::Short(l.clone()))); - } - raw.extend(self.raw_extra.iter().cloned()); - let raw_ifd = t.ifd(raw); - // IFD0: a tiny RGB thumbnail plus the DNG metadata. - let thumb = t.blob(vec![128; 3 * 4]); - let mut ifd0: Vec<(u16, Val)> = vec![ + } + + /// IFD0's tags before the colour metadata: the thumbnail strip `thumb`, identity, orientation + /// and the sub-IFD `raw_ifd`. + fn ifd0_base_tags(&self, thumb: usize, raw_ifd: usize) -> Vec<(u16, Val)> { + vec![ (254, Val::Long(vec![1])), (256, Val::Long(vec![2])), (257, Val::Long(vec![2])), @@ -401,7 +415,11 @@ impl DngSpec { (330, Val::Ifds(vec![raw_ifd])), (50706, Val::Byte(vec![1, 4, 0, 0])), (50708, Val::Ascii(format!("{} {}", self.make, self.model))), - ]; + ] + } + + /// Colour matrices, white balance, exposure and the profile gain table. + fn push_color_tags(&self, ifd0: &mut Vec<(u16, Val)>) { let m = |v: &[f64; 9]| Val::SRational(v.iter().map(|&x| srat(x)).collect()); if let Some((ill, cm)) = &self.color_matrix1 { ifd0.push((50721, m(cm))); @@ -426,13 +444,41 @@ impl DngSpec { if let Some(m) = &self.profile_gain_table_map { ifd0.push((52525, Val::Undefined(m.clone()))); } - ifd0.extend(self.ifd0_extra.iter().cloned()); - let i0 = t.ifd(ifd0); - t.chain = vec![i0]; - t.build() } } +/// How a tile's samples are stored: raw 16-bit values, or the 8-bit samples of a lossy JPEG. +trait TileSample { + fn from_sample(spec: &DngSpec, v: u16) -> Self; +} + +impl TileSample for u16 { + fn from_sample(_: &DngSpec, v: u16) -> Self { + v + } +} + +impl TileSample for u8 { + fn from_sample(spec: &DngSpec, v: u16) -> Self { + spec.sample8(v) + } +} + +/// Strip layout tags for the blobs `offs` (lengths `lens`). +fn push_strip_tags(raw: &mut Vec<(u16, Val)>, rows: usize, offs: Vec, lens: Vec) { + raw.push((278, Val::Long(vec![rows as u32]))); + raw.push((273, Val::Blobs(offs))); + raw.push((279, Val::Long(lens))); +} + +/// Tile layout tags for the blobs `offs` (lengths `lens`). +fn push_tile_tags(raw: &mut Vec<(u16, Val)>, tw: usize, th: usize, offs: Vec, lens: Vec) { + raw.push((322, Val::Long(vec![tw as u32]))); + raw.push((323, Val::Long(vec![th as u32]))); + raw.push((324, Val::Blobs(offs))); + raw.push((325, Val::Long(lens))); +} + /// An OpcodeList2 with one GainMap over active-area rectangle `area` (top, /// left, bottom, right), every `pitch` rows and columns, from a 2×2 grid of /// gains spanning the image (relative coordinates 0..1). From 6b397ff7c09cff92d6d8e683e4a11d13687dbf07 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:06 +0000 Subject: [PATCH 21/35] Refactor tablet for strict Clippy checks --- crates/tablet/Cargo.toml | 7 +++++-- crates/tablet/src/appkit.rs | 10 ++++++++-- crates/tablet/src/macos.rs | 5 ++++- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/tablet/Cargo.toml b/crates/tablet/Cargo.toml index 83e29c4d68..c4d1c8d6bf 100644 --- a/crates/tablet/Cargo.toml +++ b/crates/tablet/Cargo.toml @@ -13,8 +13,11 @@ description = "Pen tablet pressure, tilt, rotation and eraser end on macOS (AppK unsafe_code = "deny" [lints.clippy] -dbg_macro = "warn" -todo = "warn" + cognitive_complexity = "deny" + too_many_arguments = "deny" + wildcard_imports = "deny" + dbg_macro = "warn" + todo = "warn" # Already in Cargo.lock (eframe/wgpu/fmv-macos-events and winit pull them in); pinned exactly: # review the diff before bumping. diff --git a/crates/tablet/src/appkit.rs b/crates/tablet/src/appkit.rs index 2d00c093ca..15557040c1 100644 --- a/crates/tablet/src/appkit.rs +++ b/crates/tablet/src/appkit.rs @@ -68,7 +68,10 @@ pub struct RawEvent { /// The mask of event types [`State::handle`] maps (`NSEventMask` bits are `1 << type`). pub fn event_mask() -> u64 { - use event_type::*; + use event_type::{ + LEFT_MOUSE_DOWN, LEFT_MOUSE_DRAGGED, LEFT_MOUSE_UP, MOUSE_MOVED, OTHER_MOUSE_DOWN, OTHER_MOUSE_DRAGGED, OTHER_MOUSE_UP, RIGHT_MOUSE_DOWN, + RIGHT_MOUSE_DRAGGED, RIGHT_MOUSE_UP, TABLET_POINT, TABLET_PROXIMITY, + }; [ LEFT_MOUSE_DOWN, LEFT_MOUSE_UP, @@ -97,7 +100,10 @@ pub struct State { impl State { /// Map one event. pub fn handle(&mut self, e: &RawEvent) -> Update { - use event_type::*; + use event_type::{ + LEFT_MOUSE_DOWN, LEFT_MOUSE_DRAGGED, LEFT_MOUSE_UP, MOUSE_MOVED, OTHER_MOUSE_DOWN, OTHER_MOUSE_DRAGGED, OTHER_MOUSE_UP, RIGHT_MOUSE_DOWN, + RIGHT_MOUSE_DRAGGED, RIGHT_MOUSE_UP, TABLET_POINT, TABLET_PROXIMITY, + }; let mouse = matches!( e.kind, LEFT_MOUSE_DOWN diff --git a/crates/tablet/src/macos.rs b/crates/tablet/src/macos.rs index 0dccadc0cd..746de23ccd 100644 --- a/crates/tablet/src/macos.rs +++ b/crates/tablet/src/macos.rs @@ -92,7 +92,10 @@ fn read(e: &NSEvent) -> RawEvent { } fn is_mouse(kind: usize) -> bool { - use crate::appkit::event_type::*; + use crate::appkit::event_type::{ + LEFT_MOUSE_DOWN, LEFT_MOUSE_DRAGGED, LEFT_MOUSE_UP, MOUSE_MOVED, OTHER_MOUSE_DOWN, OTHER_MOUSE_DRAGGED, OTHER_MOUSE_UP, RIGHT_MOUSE_DOWN, + RIGHT_MOUSE_DRAGGED, RIGHT_MOUSE_UP, + }; matches!( kind, LEFT_MOUSE_DOWN From 9800f56dfbdf2dc287f025ee8ecda13aa775dec4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:07 +0000 Subject: [PATCH 22/35] Refactor text for strict Clippy checks --- crates/text/src/layout.rs | 751 ++++----------------------- crates/text/src/layout/area.rs | 2 +- crates/text/src/layout/lines.rs | 522 +++++++++++++++++++ crates/text/src/layout/navigate.rs | 2 +- crates/text/src/layout/paragraphs.rs | 2 +- crates/text/src/layout/shaping.rs | 438 ++++++++++++++++ crates/text/src/layout/style.rs | 5 +- crates/text/src/layout/vertical.rs | 2 +- crates/text/src/psd/build.rs | 5 +- crates/text/src/psd/edit.rs | 2 +- crates/text/src/psd/import.rs | 5 +- 11 files changed, 1071 insertions(+), 665 deletions(-) create mode 100644 crates/text/src/layout/lines.rs create mode 100644 crates/text/src/layout/shaping.rs diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 7dadaf1bd5..d31b888fad 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -17,36 +17,33 @@ use std::borrow::Cow; use std::ops::Range; -use parley::{ - Alignment, AlignmentOptions, FontData, FontFamily, FontFeatures, FontStyle, FontVariations, FontWeight, IndentOptions, Layout, LayoutContext, - PositionedLayoutItem, StyleProperty, -}; +use parley::{FontData, FontFamily, FontFeatures, FontStyle, FontVariations, FontWeight, Layout, LayoutContext, PositionedLayoutItem, StyleProperty}; use photocraft_doc::TextLayer; -use photocraft_doc::text::{Caps, CharStyle, FontBaseline, Kerning, Orientation, ParagraphStyle, TextAlign, TextDirection, TextShape}; +use photocraft_doc::text::{Caps, CharStyle, FontBaseline, Kerning, Orientation, ParagraphStyle, TextShape}; use skrifa::raw::types::Tag; use crate::fonts::FontDb; mod area; +mod lines; mod navigate; mod paragraphs; +mod shaping; mod style; mod vertical; #[cfg(test)] pub(crate) use area::AREA_PASSES; -use area::{LineMetrics, MAX_AREA_PASSES, area_metrics, break_area, line_metrics}; pub use navigate::{byte_index, char_index, hit_char, line_edge, line_index, line_step, text_point_inside, word_boundary}; +use paragraphs::next_tab_stop; pub use paragraphs::{DEFAULT_TAB_STOP_PT, split_paragraphs}; -use paragraphs::{next_tab_stop, strip_break, tab_widths}; +use shaping::{Para, resolve_run_styles, running_starts, small_caps_modes}; +use style::SmallCapsMode; +#[cfg(test)] +use style::{SMCP_PROBES, feature_list, small_caps_mode, variation_list}; #[cfg(test)] -use style::{SMCP_PROBES, variation_list}; -use style::{ - SYNTHETIC_SMALL_CAPS_SCALE, SmallCapsMode, drawn_style, effective_horizontal_scale, feature_list, first_ascent, probe_smcp, small_caps_mode, style_props, -}; pub(crate) use style::{hangul_runs, squeeze_punctuation, synthetic_bold}; pub use vertical::{VClass, vertical_class}; -use vertical::{VGlyph, VMetrics}; /// Index of the run containing byte offset `off`, given each run's start offset (non-decreasing): /// the last run starting at or before `off`, or 0 when none does. Binary search, so a layer with @@ -270,29 +267,6 @@ pub(crate) struct Layouter { optical: crate::optical::Cache, } -/// A cluster of a line in visual order, for kerning. -struct KernSlot { - /// Index of the run in the paragraph layout. - run: usize, - /// Byte offset in the paragraph text. - start: usize, - first: Option, - last: Option, - font: FontData, - coords: Vec, - size: f32, - rtl: bool, - blank: bool, - /// Advance along the line (px, horizontal scale included). - advance: f32, - /// What horizontal scale adds to the shaped advance (px; negative below 100%). - growth: f32, - /// A tab, shaped as a space; it advances to the next tab stop. - tab: bool, - /// Vertical type, upright glyph (its outline doesn't run along the column). - upright: bool, -} - impl Layouter { pub fn new() -> Self { Self { lcx: LayoutContext::new(), optical: crate::optical::Cache::default() } @@ -304,48 +278,9 @@ impl Layouter { let paras = t.paragraph_runs(); let vertical = t.orientation == Orientation::Vertical; let mut out = TextLayout { px_per_pt: k, vertical, ..Default::default() }; - // Resolve families (PostScript names from PSDs, unknown families). - for r in &runs { - let mut s = r.style.clone(); - if let Some(ps) = s.postscript_name.clone() - && !fonts.faces(&s.font_family).iter().any(|f| f.postscript_name.as_deref() == Some(&ps)) - { - let f = fonts.resolve_postscript(&ps); - // An exact face match wins; a guessed family only fills a missing family. - if f.exact || (!fonts.has_family(&s.font_family) && fonts.has_family(&f.family)) { - s.font_family = f.family; - s.weight = f.weight; - s.italic = f.italic; - } - } - // Drawn with a fallback for now; a host that serves this family fetches it (`served`). - if !fonts.has_family(&s.font_family) { - crate::served::request(&s.font_family); - } - fonts.select_named_face(&mut s); - drawn_style(&mut s); - out.styles.push(s); - } - let run_starts: Vec = runs - .iter() - .scan(0, |a, r| { - let s = *a; - *a += r.len; - Some(s) - }) - .collect(); - let style_at = |off: usize| run_index_at(&run_starts, off); - let para_starts: Vec = paras - .iter() - .scan(0, |a, r| { - let s = *a; - *a += r.len; - Some(s) - }) - .collect(); - let para_style_at = |off: usize| ¶s[para_starts.iter().rposition(|&s| s <= off).unwrap_or(0)].style; - - let text = &t.text; + let styles = resolve_run_styles(fonts, &runs); + let run_starts = running_starts(runs.iter().map(|r| r.len)); + let para_starts = running_starts(paras.iter().map(|r| r.len)); let (box_rect, is_box) = match t.shape { TextShape::Box { x, y, width, height } => ((x, y, width, height), true), // Path text is laid out as one point-text line, then bent onto the path. Area text @@ -358,591 +293,93 @@ impl Layouter { TextShape::Area { path } => crate::area::AreaShape::new(path, vertical), _ => None, }; - // Box and area text wrap, align within their lines and hide what doesn't fit. - let wraps = is_box || area.is_some(); - let mut prev_baseline: Option = None; - let mut pending_space = 0.0f32; - let mut stop = false; - // Fixed for the whole layout, and the font probe only matters for styles that use small - // caps. A real `smcp` substitution must receive lowercase source text; only the fallback - // path uppercases it and scales it down. - let small_caps: Vec = out - .styles - .iter() - .map(|style| match style.caps { - Caps::SmallCaps => small_caps_mode(style.caps, probe_smcp(fonts, style)), - _ => SmallCapsMode::None, - }) - .collect(); - for (pi, prange) in split_paragraphs(text).into_iter().enumerate() { - if stop { + let small_caps = small_caps_modes(fonts, &styles); + let env = Env { + text: &t.text, + runs: &runs, + styles: &styles, + run_starts: &run_starts, + small_caps: &small_caps, + k, + vertical, + is_box, + // Box and area text wrap, align within their lines and hide what doesn't fit. + wraps: is_box || area.is_some(), + box_rect, + area, + }; + let mut flow = Flow::default(); + for (pi, prange) in split_paragraphs(&t.text).into_iter().enumerate() { + if flow.stop { break; } - let ps = para_style_at(prange.start).clone(); - let content_end = strip_break(text, &prange); - let content = &text[prange.start..content_end]; - let prefix = match ps.direction { - TextDirection::Auto => "", - TextDirection::Ltr => LRM, - TextDirection::Rtl => RLM, - }; - let mut ptext = String::with_capacity(prefix.len() + content.len()); - ptext.push_str(prefix); - // Ranges in `ptext` for lowercase characters rendered as synthetic small caps. - // They have the same UTF-8 length as their uppercase form, so the layer's byte-based - // run and caret offsets remain unchanged. - let mut synthetic_small_caps: Vec<(Range, f32)> = Vec::new(); - // Offsets in `ptext` of the spaces standing in for tabs. - let mut tabs: Vec = Vec::new(); - let tab_px = DEFAULT_TAB_STOP_PT * k; - for (i, ch) in content.char_indices() { - // A forced line break ends the line but not the paragraph. The line breaker knows - // it as a newline, which has the same length, so text offsets don't move. - if ch == FORCED_LINE_BREAK { - ptext.push('\n'); - continue; - } - // Imported PSD text can contain literal tab controls. Font shaping may - // render those as .notdef boxes; a space preserves the one-byte source - // and style/caret offsets while supplying a real whitespace advance. The space - // is widened to its tab stop after line breaking (`tab_px` below). - if ch == '\t' { - tabs.push(ptext.len()); - ptext.push(' '); - continue; - } - let style = &out.styles[style_at(prange.start + i)]; - let caps = style.caps; - if caps == Caps::AllCaps || small_caps[style_at(prange.start + i)] == SmallCapsMode::Synthetic { - let up: String = ch.to_uppercase().collect(); - if up.len() == ch.len_utf8() { - ptext.push_str(&up); - if caps == Caps::SmallCaps && ch.is_lowercase() { - let end = ptext.len(); - synthetic_small_caps.push((end - up.len()..end, style.size_pt * k * SYNTHETIC_SMALL_CAPS_SCALE)); - } - continue; - } - } - ptext.push(ch); - } - let first_style = &out.styles[style_at(prange.start)]; - let first_px = first_style.size_pt * k; - // Scripts the loaded fonts may lack (Arabic, Japanese, …): a host serving a font for them - // fetches it (`served`); it joins the fallback stack once it arrives. - crate::served::request_for_text(&ptext); - let fallback: Vec = fonts.fallback_stack().map(str::to_string).collect(); - let si0 = style_at(prange.start); - let si_end = run_starts.partition_point(|&rs| rs < content_end).max(si0 + 1).min(out.styles.len()); - // Shapes the paragraph, each tab widened by its letter spacing in `tab_spacing` (px). - let build = |lcx: &mut LayoutContext, fcx: &mut parley::FontContext, tab_spacing: &[f32]| -> Layout { - let mut b = lcx.ranged_builder(fcx, &ptext, 1.0, false); - // Paragraph-start style as the default (covers the direction mark and empty - // paragraphs), then every run piece intersecting this paragraph. - for p in style_props(&out.styles[si0], k, &fallback, si0 as u32, small_caps[si0]) { - b.push_default(p); - } - // Paragraph text breaks a word wider than the box at the box edge, as Photoshop - // does (#6694): parley's default only breaks at UAX #14 opportunities and lets the - // word run out of the box. Point text has no width to overflow. - if is_box { - b.push_default(StyleProperty::OverflowWrap(parley::style::OverflowWrap::BreakWord)); - } - for (ri, st) in out.styles.iter().enumerate().take(si_end).skip(si0) { - let rs = run_starts[ri]; - let (a, z) = (rs.max(prange.start), (rs + runs[ri].len).min(content_end)); - if a >= z { - continue; - } - let range = (a - prange.start + prefix.len())..(z - prange.start + prefix.len()); - for p in style_props(st, k, &fallback, ri as u32, small_caps[ri]) { - b.push(p, range.clone()); - } - if vertical { - // Upright pieces get the vertical alternates and their class in the brush. - let piece = ptext.get(range.clone()).unwrap_or(""); - let mut seg: Option<(usize, VClass)> = None; - let flush = |b: &mut parley::RangedBuilder<'_, RunBrush>, from: usize, to: usize, cls: VClass| { - if cls == VClass::Rotate || from >= to { - return; - } - let mut feats = feature_list(st, small_caps[ri]); - feats.push("\"vert\" 1".into()); - let r = (range.start + from)..(range.start + to); - b.push(StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), r.clone()); - b.push(StyleProperty::Brush(RunBrush(ri as u32, cls as u8)), r); - }; - for (i, ch) in piece.char_indices() { - let cls = vertical_class(ch); - match seg { - Some((_, c)) if c == cls => {} - Some((from, c)) => { - flush(&mut b, from, i, c); - seg = Some((i, cls)); - } - None => seg = Some((i, cls)), - } - } - if let Some((from, c)) = seg { - flush(&mut b, from, piece.len(), c); - } - } - } - for (range, size) in &synthetic_small_caps { - b.push(StyleProperty::FontSize(*size), range.clone()); - } - // Korean breaks lines at spaces, between words, as Photoshop sets it; Unicode's - // default rules break between any two Hangul syllables, mid-word (#5959). - for range in hangul_runs(&ptext) { - b.push(StyleProperty::WordBreak(parley::WordBreak::KeepAll), range); - } - for (&at, &spacing) in tabs.iter().zip(tab_spacing) { - b.push(StyleProperty::LetterSpacing(spacing), at..at + 1); - } - b.build(&ptext) - }; - let indent_start = ps.start_indent_pt * k; - let indent_end = ps.end_indent_pt * k; - let first_indent = ps.first_line_indent_pt * k; - // Box extent along the lines: width, or height for vertical type (columns). - let (line_origin, line_len) = if vertical { (box_rect.1, box_rect.3) } else { (box_rect.0, box_rect.2) }; - let avail = if is_box { Some((line_len - indent_start - indent_end).max(1.0)) } else { None }; - // Horizontal scale is applied after shaping, so paragraph text breaks at the box - // (or area span) width divided by it (#5565). Mixed scales break at the largest, so - // no line overflows the box. - let break_scale = if wraps { - (si0..si_end) - .filter(|&ri| { - let rs = run_starts.get(ri).copied().unwrap_or(0); - let end = rs.saturating_add(runs.get(ri).map_or(0, |r| r.len)); - ri == si0 || (rs.max(prange.start) < end.min(content_end)) - }) - .filter_map(|ri| out.styles.get(ri)) - .map(effective_horizontal_scale) - .fold(0.0f32, f32::max) - } else { - 1.0 - }; - let break_scale = if break_scale > 0.0 { break_scale } else { 1.0 }; - // Area type: the first row goes no higher than one leading (plus paragraph spacing) - // below the previous paragraph's last line. - let space_before = if prev_baseline.is_some() { ps.space_before_pt * k } else { 0.0 }; - let area_from = |m: LineMetrics| match (&area, prev_baseline) { - (Some(_), Some(b)) => b + m.leading + pending_space + space_before, - (Some(a), None) => a.bounds[1] + m.ascent, - (None, _) => 0.0, - }; - // Line-breaking passes left for this paragraph's area type (see `break_area`). - let area_budget = std::cell::Cell::new(MAX_AREA_PASSES); - let break_lines = |layout: &mut Layout| -> (Vec, bool) { - if first_indent != 0.0 { - layout.set_text_indent(first_indent / break_scale, IndentOptions::default()); - } - let Some(a) = &area else { - layout.break_all_lines(avail.map(|a| a / break_scale)); - return (Vec::new(), false); - }; - // Plan every row with the paragraph's real line metrics (its tallest font and - // largest leading, measured on the unwrapped paragraph), so no wrapped line comes - // out taller than the row it was planned in and no second plan is needed. - layout.break_all_lines(None); - let m = area_metrics(layout, &out.styles, &ps, k, first_style, vertical); - break_area(layout, a, area_from(m), m, (indent_start, indent_end), first_px, break_scale, &area_budget) - }; - // Paragraph text: a tab is never wider than a space plus one tab interval, so breaking - // lines at that width keeps the expanded tabs inside the box, but can wrap early. - // Break again with the tab widths that layout gives until they agree; if they don't - // settle, keep the safe layout. - let wide = if wraps { tab_px } else { 0.0 }; - let mut layout = build(&mut self.lcx, &mut fonts.fcx, &vec![wide; tabs.len()]); - let (mut area_slots, mut area_full) = break_lines(&mut layout); - if wraps && !tabs.is_empty() { - let first = tab_widths(&layout, &tabs, &out.styles, indent_start, first_indent, tab_px); - let mut want: Vec = first.iter().map(|t| t.width).collect(); - for _ in 0..4 { - let spacing: Vec = first.iter().zip(&want).map(|(t, w)| w / t.scale - (t.advance - tab_px)).collect(); - let mut next = build(&mut self.lcx, &mut fonts.fcx, &spacing); - let (next_slots, next_full) = break_lines(&mut next); - let got: Vec = tab_widths(&next, &tabs, &out.styles, indent_start, first_indent, tab_px).iter().map(|t| t.width).collect(); - if got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 0.01) { - layout = next; - area_slots = next_slots; - area_full = next_full; - break; - } - want = got; - } - } - let alignment = if wraps { - match ps.align { - TextAlign::Left => Alignment::Left, - TextAlign::Center => Alignment::Center, - TextAlign::Right => Alignment::Right, - _ => Alignment::Justify, - } - } else { - Alignment::Left - }; - layout.align(alignment, AlignmentOptions { align_when_overflowing: !wraps }); - - // Stack lines. - if prev_baseline.is_some() { - pending_space += ps.space_before_pt * k; - } - let nlines = layout.len(); - for (li, line) in layout.lines().enumerate() { - // Area type: the slot the breaker gave this line. - let slot = area_slots.get(li).copied(); - if area.is_some() && slot.is_none() { - stop = true; - break; - } - let m = *line.metrics(); - let LineMetrics { ascent, descent, leading } = line_metrics(&line, &out.styles, &ps, k, first_style, vertical); - let baseline = match (slot, prev_baseline) { - (Some(s), _) => s.baseline, - // The first column's right edge touches the box's right edge. - // (In vertical type the ascent is half the column width.) - (None, None) if is_box && vertical => -(box_rect.0 + box_rect.2) + ascent, - // Photoshop's "first baseline: ascent": the top of the tallest ascender - // (height of 'd') touches the box top, not the font's hhea ascent. - (None, None) if is_box => box_rect.1 + first_ascent(&line).unwrap_or(ascent), - (None, None) => 0.0, - (None, Some(b)) => b + leading + pending_space, - }; - pending_space = 0.0; - // Photoshop keeps a horizontal line whose baseline is inside the box and lets - // its descenders hang below the bottom edge (#1317: three 35 pt lines in a - // 91.3 pt box, the last baseline at 88). Requiring the descent to fit dropped - // that line. - let overflow = if vertical { baseline + descent > -box_rect.0 + 0.5 } else { baseline > box_rect.1 + box_rect.3 + 0.5 }; - if is_box && overflow { - stop = true; - break; - } - prev_baseline = Some(baseline); - let last_line = li + 1 == nlines; - let adv = m.advance - m.trailing_whitespace; - let map = |o: usize| (prange.start + o.saturating_sub(prefix.len())).min(content_end); - - // Kerning after each cluster (px), per run in visual cluster order: manual - // kerning plus optical pair kerning. Applied after shaping (like horizontal - // scale) in line space, so it moves the following glyphs, carets and the line - // extent; in vertical type that is along the column. Optical kerning measures - // horizontal outlines, so it applies to rotated (Latin) glyphs only there. - let mut slots: Vec = Vec::new(); - let mut line_runs: Vec = Vec::new(); - for item in line.items() { - let PositionedLayoutItem::GlyphRun(gr) = item else { - continue; - }; - let run = gr.run(); - if line_runs.contains(&run.index()) { - continue; - } - line_runs.push(run.index()); - let hs = out.styles.get(gr.style().brush.0 as usize).map_or(1.0, |st| if st.horizontal_scale > 0.0 { st.horizontal_scale } else { 1.0 }); - for c in run.visual_clusters() { - let mut gl = c.glyphs(); - let first = gl.next().map(|g| g.id); - let last = gl.last().map(|g| g.id).or(first); - slots.push(KernSlot { - run: run.index(), - start: c.text_range().start, - first, - last, - font: run.font().clone(), - coords: run.normalized_coords().to_vec(), - size: run.font_size(), - rtl: c.is_rtl(), - blank: first.is_none() || c.is_space_or_nbsp() || c.text_range().end <= prefix.len(), - upright: vertical && c.first_style().brush.1 != VClass::Rotate as u8, - advance: c.advance() * hs, - growth: c.advance() * (hs - 1.0), - tab: tabs.binary_search(&c.text_range().start).is_ok(), - }); - } - } - let mut kern_px: Vec = vec![0.0; slots.len()]; - for j in 0..slots.len().saturating_sub(1) { - let (a, b) = (&slots[j], &slots[j + 1]); - if a.start < prefix.len() { - continue; - } - let st = &out.styles[style_at(map(a.start))]; - let next = &out.styles[style_at(map(b.start))]; - let mut units = if st.kern.is_finite() { st.kern } else { 0.0 }; - // Optical pairs: both characters optical (a mode change splits shaping - // runs, which ends automatic kerning, as with Metrics). - if st.kerning == Kerning::Optical - && next.kerning == Kerning::Optical - && st.kern == 0.0 - && next.kern == 0.0 - && !a.rtl - && !b.rtl - && !a.blank - && !b.blank - && !a.upright - && !b.upright - && a.font.data.id() == b.font.data.id() - && a.font.index == b.font.index - && a.coords == b.coords - && (a.size - b.size).abs() < 1e-3 - && let (Some(l), Some(r)) = (a.last, b.first) - { - let coords: Vec = - a.coords.iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); - if let Some(k) = self.optical.pair(a.font.data.id(), a.font.data.as_ref(), a.font.index, &coords, l, r) { - units += k + crate::optical::size_adjust(st.size_pt); - } - } - kern_px[j] = units / 1000.0 * a.size; - } - // Tabs: the "kerning" after a tab takes the pen to the next stop, measured from - // the anchor or the box edge as if the line were left-aligned (alignment then - // moves the whole line). - let mut pos = indent_start + if li == 0 { first_indent } else { 0.0 }; - let mut trailing_tabs = 0.0f32; - let mut trailing_growth = 0.0f32; - for (j, s) in slots.iter().enumerate() { - // Trailing whitespace is outside the line's extent (`adv`). - let trailing = s.blank && slots[j + 1..].iter().all(|n| n.blank); - if trailing { - trailing_growth += s.growth; - } - if s.tab { - kern_px[j] = next_tab_stop(pos, tab_px) - pos - s.advance; - if slots[j + 1..].iter().all(|n| n.blank) { - trailing_tabs += kern_px[j]; - } - } - pos += s.advance + kern_px.get(j).copied().unwrap_or(0.0); - } - let line_kern: f32 = kern_px.iter().sum::() - trailing_tabs; - // Per run on the line: (run index, glyph → slot, glyphs emitted, first slot whose - // kerning isn't applied yet). - let mut cursors: Vec<(usize, Vec, usize, usize)> = Vec::new(); - for item in line.items() { - let PositionedLayoutItem::GlyphRun(gr) = item else { - continue; - }; - let run = gr.run(); - if cursors.iter().any(|c| c.0 == run.index()) { - continue; - } - let base = slots.iter().position(|s| s.run == run.index()).unwrap_or(0); - let mut g2s = Vec::new(); - for (ci, c) in run.visual_clusters().enumerate() { - g2s.extend(c.glyphs().map(|_| base + ci)); - } - cursors.push((run.index(), g2s, 0, base)); - } - // Parley aligned box lines without the kerning. - let kern_align = if wraps { - match ps.align { - TextAlign::Center => line_kern / 2.0, - TextAlign::Right => line_kern, - _ => 0.0, - } - } else { - 0.0 - }; - // Box and area lines start at their box or span edge; the line's own width - // (`line_avail`) takes the justify-last-line slack. - let line_avail = slot.map(|s| s.width).or(avail); - let dx = if wraps { - let origin = slot.map_or(line_origin, |s| s.x); - let base = origin + indent_start - kern_align; - let slack = line_avail.unwrap_or(0.0) - adv * break_scale - line_kern; - // Parley aligned the unscaled line in `avail / break_scale`: scale its - // indent and alignment offset back to the box. - let scaled_offset = m.offset * (break_scale - 1.0); - base + if last_line { - match ps.align { - TextAlign::JustifyCenter => slack * 0.5 - m.offset, - TextAlign::JustifyRight => slack - m.offset, - _ => scaled_offset, - } - } else { - scaled_offset - } - } else { - let target = match ps.align { - TextAlign::Center | TextAlign::JustifyCenter => -(adv + line_kern) / 2.0, - TextAlign::Right | TextAlign::JustifyRight => -(adv + line_kern), - _ => indent_start, - }; - target - m.offset - }; - let justify_all = wraps && last_line && ps.align == TextAlign::JustifyAll; - let line_index = out.lines.len(); - let lr = line.text_range(); - let g0 = out.glyphs.len(); - let c0 = out.clusters.len(); - let mut vinfo: Vec = Vec::new(); - let mut extra = 0.0f32; // horizontal-scale growth and kerning along the line - let mut seen_runs: Vec = Vec::new(); - for item in line.items() { - let PositionedLayoutItem::GlyphRun(gr) = item else { - continue; - }; - let run = gr.run(); - let si = gr.style().brush.0; - let st = &out.styles[si as usize]; - let hs = if st.horizontal_scale > 0.0 { st.horizontal_scale } else { 1.0 }; - let synth = run.synthesis(); - let face = out.faces.len() as u32; - out.faces.push(GlyphFace { - font: run.font().clone(), - coords: run.normalized_coords().to_vec(), - size_px: run.font_size(), - embolden: synthetic_bold(synth.embolden(), st.weight, run.font_attrs().weight.value()), - skew_deg: synth.skew().unwrap_or(0.0), - }); - let run_x0 = dx + gr.offset() + extra; - if !seen_runs.contains(&run.index()) { - seen_runs.push(run.index()); - let mut cx = run_x0; - let base = slots.iter().position(|s| s.run == run.index()).unwrap_or(0); - for (ci, c) in run.visual_clusters().enumerate() { - let a = c.advance() * hs + kern_px.get(base + ci).copied().unwrap_or(0.0); - let r = c.text_range(); - if r.end > prefix.len() || prefix.is_empty() { - out.clusters.push(ClusterInfo { range: map(r.start)..map(r.end), x: cx, advance: a, line: line_index, rtl: c.is_rtl() }); - } - cx += a; - } - } - let rm = run.metrics(); - let vm = if vertical { Some(VMetrics::new(run.font(), run.normalized_coords(), run.font_size())) } else { None }; - let class = gr.style().brush.1; - // Glyphs of the run's own characters (not substituted by `vert`). - let plain: Vec = match (&vm, class) { - (Some(v), 2) => ptext.get(run.text_range()).unwrap_or("").chars().filter_map(|c| v.cmap(c)).collect(), - _ => Vec::new(), - }; - let mut pen = gr.offset(); - let mut cursor = cursors.iter_mut().find(|c| c.0 == run.index()); - for g in gr.glyphs() { - // Kerning of the clusters before this glyph's cluster. - if let Some(c) = cursor.as_deref_mut() { - if let Some(&slot) = c.1.get(c.2) { - while c.3 < slot { - extra += kern_px.get(c.3).copied().unwrap_or(0.0); - c.3 += 1; - } - } - c.2 += 1; - } - out.glyphs.push(PlacedGlyph { - face, - id: g.id, - x: dx + pen + g.x + extra, - y: baseline + g.y, - style: si, - orient: GlyphOrient::Horizontal, - }); - if let Some(v) = &vm { - let upright = class == 1 || (class == 2 && !plain.contains(&g.id)); - vinfo.push(VGlyph { - upright, - advance: g.advance * hs, - origin: if upright { v.origin(g.id) } else { 0.0 }, - // Rotated text is centred on the column: its baseline sits - // (ascent − descent) / 2 from the centre line. - centre: (rm.ascent - rm.descent) * 0.5, - }); - } - extra += g.advance * (hs - 1.0); - pen += g.advance; - } - // The run's last glyph: its remaining clusters' kerning follows it. - if let Some(c) = cursor - && c.2 >= c.1.len() - { - let end = slots.iter().rposition(|s| s.run == c.0).map_or(c.3, |p| p + 1); - while c.3 < end { - extra += kern_px.get(c.3).copied().unwrap_or(0.0); - c.3 += 1; - } - } - let run_x1 = dx + gr.offset() + gr.advance() + extra; - let shift = st.baseline_shift_pt * k; - if vertical { - // Underline to the right of the column, strikethrough through its centre - // (stored directly in text space). - let half = run.font_size() * 0.5; - let mut push = |v0: f32, v1: f32| out.decorations.push(DecorationRect { x0: -v1, y0: run_x0, x1: -v0, y1: run_x1, style: si }); - if gr.style().underline.is_some() { - let v1 = baseline - half; - push(v1 - rm.underline_size.max(1.0), v1); - } - if gr.style().strikethrough.is_some() { - let sz = rm.strikethrough_size.max(1.0); - push(baseline - sz * 0.5, baseline + sz * 0.5); - } - } else if gr.style().underline.is_some() { - let y0 = baseline - rm.underline_offset - shift; - out.decorations.push(DecorationRect { x0: run_x0, y0, x1: run_x1, y1: y0 + rm.underline_size.max(1.0), style: si }); - } - if !vertical && gr.style().strikethrough.is_some() { - let y0 = baseline - rm.strikethrough_offset - shift; - out.decorations.push(DecorationRect { x0: run_x0, y0, x1: run_x1, y1: y0 + rm.strikethrough_size.max(1.0), style: si }); - } - } - if vertical { - extra -= squeeze_punctuation(text, &mut out.clusters[c0..], &mut out.glyphs[g0..]); - } - if justify_all { - let slack = line_avail.unwrap_or(0.0) - (adv + extra); - let n = out.clusters.len() - c0; - if n > 1 && slack > 0.0 { - let step = slack / (n - 1) as f32; - let starts: Vec = out.clusters[c0..].iter().map(|c| c.x).collect(); - for (i, c) in out.clusters[c0..].iter_mut().enumerate() { - c.x += step * i as f32; - } - for g in &mut out.glyphs[g0..] { - let i = starts.iter().rposition(|&s| s <= g.x + 1e-3).unwrap_or(0); - g.x += step * i as f32; - } - extra += slack; - } - } - if vertical { - // Line space → text space (90° clockwise); upright glyphs centred on the column. - for (g, v) in out.glyphs[g0..].iter_mut().zip(&vinfo) { - let (u, cross) = (g.x, g.y); - if v.upright { - g.x = -baseline - v.advance * 0.5; - g.y = u + v.origin; - g.orient = GlyphOrient::Upright; - } else { - g.x = -(cross + v.centre); - g.y = u; - g.orient = GlyphOrient::Rotated; - } - } - } - let x0 = dx + m.offset; - out.lines.push(LineInfo { - range: map(lr.start)..map(lr.end).min(content_end), - baseline, - x0, - x1: x0 + adv + extra - trailing_tabs - trailing_growth, - ascent, - descent, - paragraph: pi, - }); - } - if area_full { - // The shape is full: later paragraphs are hidden too. - stop = true; - } - pending_space += ps.space_after_pt * k; + let ps = paras[para_starts.iter().rposition(|&s| s <= prange.start).unwrap_or(0)].style.clone(); + self.layout_paragraph(fonts, &mut out, &mut flow, Para::new(&env, fonts, pi, prange, ps)); } + out.styles = styles; out } + + /// Breaks one paragraph and stacks its lines below the previous paragraph's. + fn layout_paragraph(&mut self, fonts: &mut FontDb, out: &mut TextLayout, flow: &mut Flow, para: Para<'_>) { + let env = para.env; + let (mut layout, area_slots, area_full) = para.break_paragraph(&mut self.lcx, &mut fonts.fcx, flow); + layout.align(para.alignment(), para.align_options()); + if flow.prev_baseline.is_some() { + flow.pending_space += para.ps.space_before_pt * env.k; + } + let nlines = layout.len(); + for (li, line) in layout.lines().enumerate() { + // Area type: the slot the breaker gave this line. + let slot = area_slots.get(li).copied(); + if env.area.is_some() && slot.is_none() { + flow.stop = true; + break; + } + let Some(frame) = para.frame_line(&line, li, nlines, slot, flow) else { + flow.stop = true; + break; + }; + para.place_line(&mut self.optical, out, &line, &frame); + } + if area_full { + // The shape is full: later paragraphs are hidden too. + flow.stop = true; + } + flow.pending_space += para.ps.space_after_pt * env.k; + } +} + +/// What a layout run shares between its paragraphs. +struct Env<'a> { + text: &'a str, + runs: &'a [photocraft_doc::text::TextRun], + styles: &'a [CharStyle], + /// Start offset of each run. + run_starts: &'a [usize], + small_caps: &'a [SmallCapsMode], + k: f32, + vertical: bool, + is_box: bool, + /// Box and area text wrap, align within their lines and hide what doesn't fit. + wraps: bool, + box_rect: (f32, f32, f32, f32), + area: Option, +} + +impl Env<'_> { + /// Index of the run (and style) containing byte offset `off`. + fn style_at(&self, off: usize) -> usize { + run_index_at(self.run_starts, off) + } +} + +/// Where the previous paragraph left off. +#[derive(Default)] +struct Flow { + prev_baseline: Option, + pending_space: f32, + stop: bool, } /// Where one line of area type goes: its baseline, the left edge of its span, and the width diff --git a/crates/text/src/layout/area.rs b/crates/text/src/layout/area.rs index d91d497e26..f6dbe9cf69 100644 --- a/crates/text/src/layout/area.rs +++ b/crates/text/src/layout/area.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{CharStyle, Layout, ParagraphStyle, PositionedLayoutItem, RunBrush, Slot}; /// A line's ascent, descent and leading (px); for area type, the largest over a paragraph. #[derive(Clone, Copy, Debug)] diff --git a/crates/text/src/layout/lines.rs b/crates/text/src/layout/lines.rs new file mode 100644 index 0000000000..ec42eba987 --- /dev/null +++ b/crates/text/src/layout/lines.rs @@ -0,0 +1,522 @@ +//! Placing one broken line of a paragraph: kerning and tab stops, glyph and cluster positions, +//! decorations, and the line's vertical-type and justification adjustments. + +use parley::{PositionedLayoutItem, Run}; +use photocraft_doc::text::{CharStyle, Kerning, TextAlign}; +use skrifa::instance::NormalizedCoord; + +use super::area::{LineMetrics, line_metrics}; +use super::shaping::Para; +use super::style::{first_ascent, squeeze_punctuation, synthetic_bold}; +use super::vertical::{VGlyph, VMetrics}; +use super::{ClusterInfo, DecorationRect, Flow, GlyphFace, GlyphOrient, LineInfo, PlacedGlyph, RunBrush, Slot, TextLayout, VClass}; + +type Line<'a> = parley::Line<'a, RunBrush>; +type GlyphRun<'a> = parley::GlyphRun<'a, RunBrush>; + +/// A cluster of a line in visual order, for kerning. +struct KernSlot { + /// Index of the run in the paragraph layout. + run: usize, + /// Byte offset in the paragraph text. + start: usize, + first: Option, + last: Option, + font: parley::FontData, + coords: Vec, + size: f32, + rtl: bool, + blank: bool, + /// Advance along the line (px, horizontal scale included). + advance: f32, + /// What horizontal scale adds to the shaped advance (px; negative below 100%). + growth: f32, + /// A tab, shaped as a space; it advances to the next tab stop. + tab: bool, + /// Vertical type, upright glyph (its outline doesn't run along the column). + upright: bool, +} + +/// Where a line sits in its paragraph and on the page. +pub(super) struct LineFrame { + pub(super) index: usize, + pub(super) last: bool, + /// The slot the area breaker gave this line. + pub(super) slot: Option, + pub(super) baseline: f32, + pub(super) ascent: f32, + pub(super) descent: f32, +} + +/// The clusters of one run, for applying kerning as glyphs are emitted. +struct KernCursor { + run: usize, + /// Slot of the cluster each glyph of the run belongs to. + glyph_slot: Vec, + /// Glyphs emitted so far. + emitted: usize, + /// First slot whose kerning isn't applied yet. + applied: usize, +} + +impl KernCursor { + /// Kerning of the clusters before the next glyph's cluster. + fn before_glyph(&mut self, kern_px: &[f32], extra: &mut f32) { + if let Some(&slot) = self.glyph_slot.get(self.emitted) { + while self.applied < slot { + *extra += kern_px.get(self.applied).copied().unwrap_or(0.0); + self.applied += 1; + } + } + self.emitted += 1; + } + + /// After the run's last glyph: its remaining clusters' kerning follows it. + fn after_run(&mut self, slots: &[KernSlot], kern_px: &[f32], extra: &mut f32) { + if self.emitted < self.glyph_slot.len() { + return; + } + let end = slots.iter().rposition(|s| s.run == self.run).map_or(self.applied, |p| p + 1); + while self.applied < end { + *extra += kern_px.get(self.applied).copied().unwrap_or(0.0); + self.applied += 1; + } + } +} + +/// What is accumulated while a line's glyph runs are emitted. +struct LineState { + cursors: Vec, + seen_runs: Vec, + vinfo: Vec, + /// Horizontal-scale growth and kerning along the line. + extra: f32, +} + +/// Fixed facts about the line being emitted. +struct LineCtx<'a> { + dx: f32, + baseline: f32, + slots: &'a [KernSlot], + kern_px: &'a [f32], + line_index: usize, +} + +/// The horizontal extent of one glyph run on the line. +struct RunSpan { + x0: f32, + x1: f32, + style: u32, +} + +/// A run style's horizontal scale; unset (zero or negative) is 100%. +fn scale_of(st: &CharStyle) -> f32 { + if st.horizontal_scale > 0.0 { st.horizontal_scale } else { 1.0 } +} + +/// The clusters of `line` in visual order, per run. +fn collect_kern_slots(line: &Line<'_>, para: &Para<'_>) -> Vec { + let env = para.env; + let mut slots: Vec = Vec::new(); + let mut line_runs: Vec = Vec::new(); + for item in line.items() { + let PositionedLayoutItem::GlyphRun(gr) = item else { + continue; + }; + let run = gr.run(); + if line_runs.contains(&run.index()) { + continue; + } + line_runs.push(run.index()); + let hs = env.styles.get(gr.style().brush.0 as usize).map_or(1.0, scale_of); + for c in run.visual_clusters() { + let mut gl = c.glyphs(); + let first = gl.next().map(|g| g.id); + let last = gl.last().map(|g| g.id).or(first); + slots.push(KernSlot { + run: run.index(), + start: c.text_range().start, + first, + last, + font: run.font().clone(), + coords: run.normalized_coords().to_vec(), + size: run.font_size(), + rtl: c.is_rtl(), + blank: first.is_none() || c.is_space_or_nbsp() || c.text_range().end <= para.prefix.len(), + upright: env.vertical && c.first_style().brush.1 != VClass::Rotate as u8, + advance: c.advance() * hs, + growth: c.advance() * (hs - 1.0), + tab: para.tabs.binary_search(&c.text_range().start).is_ok(), + }); + } + } + slots +} + +/// Both characters of a pair kern optically: a mode change splits shaping runs, which ends +/// automatic kerning, as with Metrics. +fn optical_pair(st: &CharStyle, next: &CharStyle, a: &KernSlot, b: &KernSlot) -> bool { + st.kerning == Kerning::Optical + && next.kerning == Kerning::Optical + && st.kern == 0.0 + && next.kern == 0.0 + && !a.rtl + && !b.rtl + && !a.blank + && !b.blank + && !a.upright + && !b.upright + && a.font.data.id() == b.font.data.id() + && a.font.index == b.font.index + && a.coords == b.coords + && (a.size - b.size).abs() < 1e-3 +} + +/// Optical kerning between two adjacent clusters (font units, with the size adjustment), if the +/// font has the pair. +fn optical_kern(optical: &mut crate::optical::Cache, st: &CharStyle, a: &KernSlot, b: &KernSlot) -> Option { + let (l, r) = (a.last?, b.first?); + let coords: Vec = a.coords.iter().map(|&c| NormalizedCoord::from_bits(c)).collect(); + let k = optical.pair(a.font.data.id(), a.font.data.as_ref(), a.font.index, &coords, l, r)?; + Some(k + crate::optical::size_adjust(st.size_pt)) +} + +/// One kerning cursor per run on `line`. +fn kern_cursors(line: &Line<'_>, slots: &[KernSlot]) -> Vec { + let mut cursors: Vec = Vec::new(); + for item in line.items() { + let PositionedLayoutItem::GlyphRun(gr) = item else { + continue; + }; + let run = gr.run(); + if cursors.iter().any(|c| c.run == run.index()) { + continue; + } + let base = slots.iter().position(|s| s.run == run.index()).unwrap_or(0); + cursors.push(KernCursor { run: run.index(), glyph_slot: glyph_slots(run, base), emitted: 0, applied: base }); + } + cursors +} + +/// For each glyph of `run`, the slot of its cluster (the run's clusters start at slot `base`). +fn glyph_slots(run: &Run<'_, RunBrush>, base: usize) -> Vec { + let mut g2s = Vec::new(); + for (ci, c) in run.visual_clusters().enumerate() { + g2s.extend(c.glyphs().map(|_| base + ci)); + } + g2s +} + +/// Distributes `slack` between the clusters of the line from `c0` (and their glyphs from `g0`); +/// returns what was added to the line's length. +fn justify_line(out: &mut TextLayout, c0: usize, g0: usize, slack: f32) -> f32 { + let n = out.clusters.len() - c0; + if n <= 1 || slack <= 0.0 { + return 0.0; + } + let step = slack / (n - 1) as f32; + let starts: Vec = out.clusters[c0..].iter().map(|c| c.x).collect(); + for (i, c) in out.clusters[c0..].iter_mut().enumerate() { + c.x += step * i as f32; + } + for g in &mut out.glyphs[g0..] { + let i = starts.iter().rposition(|&s| s <= g.x + 1e-3).unwrap_or(0); + g.x += step * i as f32; + } + slack +} + +/// Line space → text space (90° clockwise); upright glyphs centred on the column. +fn rotate_to_text_space(glyphs: &mut [PlacedGlyph], vinfo: &[VGlyph], baseline: f32) { + for (g, v) in glyphs.iter_mut().zip(vinfo) { + let (u, cross) = (g.x, g.y); + if v.upright { + g.x = -baseline - v.advance * 0.5; + g.y = u + v.origin; + g.orient = GlyphOrient::Upright; + } else { + g.x = -(cross + v.centre); + g.y = u; + g.orient = GlyphOrient::Rotated; + } + } +} + +/// Underline and strikethrough rects of one run. +fn push_decorations(out: &mut TextLayout, vertical: bool, gr: &GlyphRun<'_>, baseline: f32, shift: f32, span: &RunSpan) { + let rm = gr.run().metrics(); + let (x0, x1, si) = (span.x0, span.x1, span.style); + if vertical { + // Underline to the right of the column, strikethrough through its centre + // (stored directly in text space). + let half = gr.run().font_size() * 0.5; + let mut push = |v0: f32, v1: f32| out.decorations.push(DecorationRect { x0: -v1, y0: x0, x1: -v0, y1: x1, style: si }); + if gr.style().underline.is_some() { + let v1 = baseline - half; + push(v1 - rm.underline_size.max(1.0), v1); + } + if gr.style().strikethrough.is_some() { + let sz = rm.strikethrough_size.max(1.0); + push(baseline - sz * 0.5, baseline + sz * 0.5); + } + return; + } + if gr.style().underline.is_some() { + let y0 = baseline - rm.underline_offset - shift; + out.decorations.push(DecorationRect { x0, y0, x1, y1: y0 + rm.underline_size.max(1.0), style: si }); + } + if gr.style().strikethrough.is_some() { + let y0 = baseline - rm.strikethrough_offset - shift; + out.decorations.push(DecorationRect { x0, y0, x1, y1: y0 + rm.strikethrough_size.max(1.0), style: si }); + } +} + +impl Para<'_> { + /// Kerning after each cluster (px): manual kerning plus optical pair kerning. Applied after + /// shaping (like horizontal scale) in line space, so it moves the following glyphs, carets and + /// the line extent; in vertical type that is along the column. Optical kerning measures + /// horizontal outlines, so it applies to rotated (Latin) glyphs only there. + fn kerning(&self, optical: &mut crate::optical::Cache, slots: &[KernSlot]) -> Vec { + let env = self.env; + let mut kern_px: Vec = vec![0.0; slots.len()]; + for j in 0..slots.len().saturating_sub(1) { + let (a, b) = (&slots[j], &slots[j + 1]); + if a.start < self.prefix.len() { + continue; + } + let st = &env.styles[env.style_at(self.map_offset(a.start))]; + let next = &env.styles[env.style_at(self.map_offset(b.start))]; + let mut units = if st.kern.is_finite() { st.kern } else { 0.0 }; + if optical_pair(st, next, a, b) { + units += optical_kern(optical, st, a, b).unwrap_or(0.0); + } + kern_px[j] = units / 1000.0 * a.size; + } + kern_px + } + + /// Tabs: the "kerning" after a tab takes the pen to the next stop, measured from the anchor or + /// the box edge as if the line were left-aligned (alignment then moves the whole line). + /// Returns the tab width and horizontal-scale growth in the line's trailing whitespace, which + /// is outside its extent. + fn apply_tab_stops(&self, slots: &[KernSlot], kern_px: &mut [f32], line_index: usize) -> (f32, f32) { + let mut pos = self.indent_start + if line_index == 0 { self.first_indent } else { 0.0 }; + let mut trailing_tabs = 0.0f32; + let mut trailing_growth = 0.0f32; + for (j, s) in slots.iter().enumerate() { + let rest_blank = slots[j + 1..].iter().all(|n| n.blank); + if s.blank && rest_blank { + trailing_growth += s.growth; + } + if s.tab { + kern_px[j] = super::next_tab_stop(pos, self.tab_px) - pos - s.advance; + if rest_blank { + trailing_tabs += kern_px[j]; + } + } + pos += s.advance + kern_px.get(j).copied().unwrap_or(0.0); + } + (trailing_tabs, trailing_growth) + } + + /// Where the line starts along its extent: box and area lines at their box or span edge, + /// point lines around the anchor. + fn line_start(&self, f: &LineFrame, offset: f32, adv: f32, line_kern: f32) -> f32 { + if !self.env.wraps { + let target = match self.ps.align { + TextAlign::Center | TextAlign::JustifyCenter => -(adv + line_kern) / 2.0, + TextAlign::Right | TextAlign::JustifyRight => -(adv + line_kern), + _ => self.indent_start, + }; + return target - offset; + } + // Parley aligned box lines without the kerning. + let kern_align = match self.ps.align { + TextAlign::Center => line_kern / 2.0, + TextAlign::Right => line_kern, + _ => 0.0, + }; + let origin = f.slot.map_or(self.line_origin, |s| s.x); + let base = origin + self.indent_start - kern_align; + // The line's own width takes the justify-last-line slack. + let slack = self.line_avail(f).unwrap_or(0.0) - adv * self.break_scale - line_kern; + // Parley aligned the unscaled line in `avail / break_scale`: scale its + // indent and alignment offset back to the box. + let scaled_offset = offset * (self.break_scale - 1.0); + base + if f.last { + match self.ps.align { + TextAlign::JustifyCenter => slack * 0.5 - offset, + TextAlign::JustifyRight => slack - offset, + _ => scaled_offset, + } + } else { + scaled_offset + } + } + + /// The width the line may fill: its area slot's, else the box's. + fn line_avail(&self, f: &LineFrame) -> Option { + f.slot.map(|s| s.width).or(self.avail) + } + + /// Where line `index` of `nlines` goes, advancing `flow` past it; `None` if a box clips it. + pub(super) fn frame_line(&self, line: &Line<'_>, index: usize, nlines: usize, slot: Option, flow: &mut Flow) -> Option { + let env = self.env; + let LineMetrics { ascent, descent, leading } = line_metrics(line, env.styles, &self.ps, env.k, self.first_style(), env.vertical); + let (box_x, box_y, box_w, box_h) = env.box_rect; + let baseline = match (slot, flow.prev_baseline) { + (Some(s), _) => s.baseline, + // The first column's right edge touches the box's right edge. + // (In vertical type the ascent is half the column width.) + (None, None) if env.is_box && env.vertical => -(box_x + box_w) + ascent, + // Photoshop's "first baseline: ascent": the top of the tallest ascender + // (height of 'd') touches the box top, not the font's hhea ascent. + (None, None) if env.is_box => box_y + first_ascent(line).unwrap_or(ascent), + (None, None) => 0.0, + (None, Some(b)) => b + leading + flow.pending_space, + }; + flow.pending_space = 0.0; + // Photoshop keeps a horizontal line whose baseline is inside the box and lets + // its descenders hang below the bottom edge (#1317: three 35 pt lines in a + // 91.3 pt box, the last baseline at 88). Requiring the descent to fit dropped + // that line. + let overflow = if env.vertical { baseline + descent > -box_x + 0.5 } else { baseline > box_y + box_h + 0.5 }; + if env.is_box && overflow { + return None; + } + flow.prev_baseline = Some(baseline); + Some(LineFrame { index, last: index + 1 == nlines, slot, baseline, ascent, descent }) + } + + /// Appends one line's clusters, glyphs, decorations and `LineInfo` to `out`. + pub(super) fn place_line(&self, optical: &mut crate::optical::Cache, out: &mut TextLayout, line: &Line<'_>, f: &LineFrame) { + let env = self.env; + let m = *line.metrics(); + let adv = m.advance - m.trailing_whitespace; + let slots = collect_kern_slots(line, self); + let mut kern_px = self.kerning(optical, &slots); + let (trailing_tabs, trailing_growth) = self.apply_tab_stops(&slots, &mut kern_px, f.index); + let line_kern: f32 = kern_px.iter().sum::() - trailing_tabs; + let dx = self.line_start(f, m.offset, adv, line_kern); + let lc = LineCtx { dx, baseline: f.baseline, slots: &slots, kern_px: &kern_px, line_index: out.lines.len() }; + let (g0, c0) = (out.glyphs.len(), out.clusters.len()); + let mut state = LineState { cursors: kern_cursors(line, &slots), seen_runs: Vec::new(), vinfo: Vec::new(), extra: 0.0 }; + for item in line.items() { + if let PositionedLayoutItem::GlyphRun(gr) = item { + self.emit_run(out, &lc, &mut state, &gr); + } + } + if env.vertical { + state.extra -= squeeze_punctuation(env.text, &mut out.clusters[c0..], &mut out.glyphs[g0..]); + } + if env.wraps && f.last && self.ps.align == TextAlign::JustifyAll { + let slack = self.line_avail(f).unwrap_or(0.0) - (adv + state.extra); + state.extra += justify_line(out, c0, g0, slack); + } + if env.vertical { + rotate_to_text_space(&mut out.glyphs[g0..], &state.vinfo, f.baseline); + } + let lr = line.text_range(); + let x0 = dx + m.offset; + out.lines.push(LineInfo { + range: self.map_offset(lr.start)..self.map_offset(lr.end).min(self.content_end), + baseline: f.baseline, + x0, + x1: x0 + adv + state.extra - trailing_tabs - trailing_growth, + ascent: f.ascent, + descent: f.descent, + paragraph: self.index, + }); + } + + /// Emits one glyph run of the line: its face, clusters (once per shaping run), glyphs and + /// decorations. + fn emit_run(&self, out: &mut TextLayout, lc: &LineCtx<'_>, state: &mut LineState, gr: &GlyphRun<'_>) { + let env = self.env; + let run = gr.run(); + let si = gr.style().brush.0; + let st = &env.styles[si as usize]; + let hs = scale_of(st); + let synth = run.synthesis(); + let face = out.faces.len() as u32; + out.faces.push(GlyphFace { + font: run.font().clone(), + coords: run.normalized_coords().to_vec(), + size_px: run.font_size(), + embolden: synthetic_bold(synth.embolden(), st.weight, run.font_attrs().weight.value()), + skew_deg: synth.skew().unwrap_or(0.0), + }); + let run_x0 = lc.dx + gr.offset() + state.extra; + if !state.seen_runs.contains(&run.index()) { + state.seen_runs.push(run.index()); + self.push_clusters(out, lc, run, hs, run_x0); + } + self.push_glyphs(out, lc, state, gr, face, hs); + let span = RunSpan { x0: run_x0, x1: lc.dx + gr.offset() + gr.advance() + state.extra, style: si }; + push_decorations(out, env.vertical, gr, lc.baseline, st.baseline_shift_pt * env.k, &span); + } + + /// The caret clusters of a shaping run, with kerning and horizontal scale in their advances. + fn push_clusters(&self, out: &mut TextLayout, lc: &LineCtx<'_>, run: &Run<'_, RunBrush>, hs: f32, run_x0: f32) { + let mut cx = run_x0; + let base = lc.slots.iter().position(|s| s.run == run.index()).unwrap_or(0); + for (ci, c) in run.visual_clusters().enumerate() { + let a = c.advance() * hs + lc.kern_px.get(base + ci).copied().unwrap_or(0.0); + let r = c.text_range(); + if r.end > self.prefix.len() || self.prefix.is_empty() { + out.clusters.push(ClusterInfo { + range: self.map_offset(r.start)..self.map_offset(r.end), + x: cx, + advance: a, + line: lc.line_index, + rtl: c.is_rtl(), + }); + } + cx += a; + } + } + + /// The glyphs of one run, with the kerning of the clusters before each. + fn push_glyphs(&self, out: &mut TextLayout, lc: &LineCtx<'_>, state: &mut LineState, gr: &GlyphRun<'_>, face: u32, hs: f32) { + let run = gr.run(); + let rm = run.metrics(); + let vm = if self.env.vertical { Some(VMetrics::new(run.font(), run.normalized_coords(), run.font_size())) } else { None }; + let class = gr.style().brush.1; + // Glyphs of the run's own characters (not substituted by `vert`). + let plain: Vec = match (&vm, class) { + (Some(v), 2) => self.text_of(run.text_range()).chars().filter_map(|c| v.cmap(c)).collect(), + _ => Vec::new(), + }; + let mut pen = gr.offset(); + let mut cursor = state.cursors.iter_mut().find(|c| c.run == run.index()); + for g in gr.glyphs() { + if let Some(c) = cursor.as_deref_mut() { + c.before_glyph(lc.kern_px, &mut state.extra); + } + out.glyphs.push(PlacedGlyph { + face, + id: g.id, + x: lc.dx + pen + g.x + state.extra, + y: lc.baseline + g.y, + style: gr.style().brush.0, + orient: GlyphOrient::Horizontal, + }); + if let Some(v) = &vm { + let upright = class == 1 || (class == 2 && !plain.contains(&g.id)); + state.vinfo.push(VGlyph { + upright, + advance: g.advance * hs, + origin: if upright { v.origin(g.id) } else { 0.0 }, + // Rotated text is centred on the column: its baseline sits + // (ascent − descent) / 2 from the centre line. + centre: (rm.ascent - rm.descent) * 0.5, + }); + } + state.extra += g.advance * (hs - 1.0); + pen += g.advance; + } + if let Some(c) = cursor { + c.after_run(lc.slots, lc.kern_px, &mut state.extra); + } + } +} diff --git a/crates/text/src/layout/navigate.rs b/crates/text/src/layout/navigate.rs index e7d9c00333..e87bf9b086 100644 --- a/crates/text/src/layout/navigate.rs +++ b/crates/text/src/layout/navigate.rs @@ -1,4 +1,4 @@ -use super::*; +use super::TextLayout; /// Byte offset of character `index` (the text length when `index` is past the end). pub fn byte_index(text: &str, index: usize) -> usize { diff --git a/crates/text/src/layout/paragraphs.rs b/crates/text/src/layout/paragraphs.rs index 2be1fbbc5a..9d9e017d1c 100644 --- a/crates/text/src/layout/paragraphs.rs +++ b/crates/text/src/layout/paragraphs.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{CharStyle, Layout, PositionedLayoutItem, Range, RunBrush}; /// Photoshop's default tab stops: every half inch, measured from the anchor of point text or the /// left edge of a paragraph box. PSD type carries no custom tab stops, so these are the only ones. diff --git a/crates/text/src/layout/shaping.rs b/crates/text/src/layout/shaping.rs new file mode 100644 index 0000000000..283c7e2ef3 --- /dev/null +++ b/crates/text/src/layout/shaping.rs @@ -0,0 +1,438 @@ +//! Per-paragraph preparation of a text layer's layout: the paragraph's shaped text (prefix, case +//! mapping, tabs), the parley shaping pass over it, and its line breaking. + +use std::borrow::Cow; +use std::cell::Cell; +use std::ops::Range; + +use parley::{Alignment, AlignmentOptions, FontFeatures, Layout, LayoutContext, StyleProperty}; +use photocraft_doc::text::{CharStyle, ParagraphStyle, TextAlign, TextDirection}; + +use super::area::{LineMetrics, MAX_AREA_PASSES, area_metrics, break_area}; +use super::paragraphs::{TabWidth, strip_break, tab_widths}; +use super::style::{ + SYNTHETIC_SMALL_CAPS_SCALE, SmallCapsMode, drawn_style, effective_horizontal_scale, feature_list, hangul_runs, probe_smcp, small_caps_mode, style_props, +}; +use super::vertical::vertical_class; +use super::{Env, FORCED_LINE_BREAK, Flow, LRM, RLM, RunBrush, Slot, VClass}; +use crate::fonts::FontDb; +use crate::layout::DEFAULT_TAB_STOP_PT; + +/// The character styles of `runs`, with families resolved (PostScript names from PSDs, unknown +/// families) and drawn the way they are laid out. +pub(super) fn resolve_run_styles(fonts: &mut FontDb, runs: &[photocraft_doc::text::TextRun]) -> Vec { + runs.iter() + .map(|r| { + let mut s = r.style.clone(); + adopt_postscript_face(fonts, &mut s); + // Drawn with a fallback for now; a host that serves this family fetches it (`served`). + if !fonts.has_family(&s.font_family) { + crate::served::request(&s.font_family); + } + fonts.select_named_face(&mut s); + drawn_style(&mut s); + s + }) + .collect() +} + +/// A style naming a PostScript face the family doesn't carry takes the family the face resolves to. +fn adopt_postscript_face(fonts: &mut FontDb, s: &mut CharStyle) { + let Some(ps) = s.postscript_name.clone() else { + return; + }; + if fonts.faces(&s.font_family).iter().any(|f| f.postscript_name.as_deref() == Some(&ps)) { + return; + } + let f = fonts.resolve_postscript(&ps); + // An exact face match wins; a guessed family only fills a missing family. + if f.exact || (!fonts.has_family(&s.font_family) && fonts.has_family(&f.family)) { + s.font_family = f.family; + s.weight = f.weight; + s.italic = f.italic; + } +} + +/// Start offset of each item, given the items' lengths. +pub(super) fn running_starts(lens: impl Iterator) -> Vec { + lens.scan(0, |a, len| { + let s = *a; + *a += len; + Some(s) + }) + .collect() +} + +/// How each style sets small caps. Fixed for the whole layout, and the font probe only matters for +/// styles that use small caps. A real `smcp` substitution must receive lowercase source text; only +/// the fallback path uppercases it and scales it down. +pub(super) fn small_caps_modes(fonts: &mut FontDb, styles: &[CharStyle]) -> Vec { + styles + .iter() + .map(|style| match style.caps { + photocraft_doc::text::Caps::SmallCaps => small_caps_mode(style.caps, probe_smcp(fonts, style)), + _ => SmallCapsMode::None, + }) + .collect() +} + +/// The text handed to the shaper for one paragraph. +struct ParaText { + ptext: String, + /// Ranges in `ptext` for lowercase characters rendered as synthetic small caps. They have the + /// same UTF-8 length as their uppercase form, so the layer's byte-based run and caret offsets + /// remain unchanged. + synthetic_small_caps: Vec<(Range, f32)>, + /// Offsets in `ptext` of the spaces standing in for tabs. + tabs: Vec, +} + +/// The shaped text of the paragraph at `range` (`content_end` excludes its break), led by `prefix`. +fn paragraph_text(env: &Env<'_>, prefix: &str, range: &Range, content_end: usize) -> ParaText { + let content = &env.text[range.start..content_end]; + let mut ptext = String::with_capacity(prefix.len() + content.len()); + ptext.push_str(prefix); + let mut synthetic_small_caps = Vec::new(); + let mut tabs = Vec::new(); + for (i, ch) in content.char_indices() { + // A forced line break ends the line but not the paragraph. The line breaker knows + // it as a newline, which has the same length, so text offsets don't move. + if ch == FORCED_LINE_BREAK { + ptext.push('\n'); + continue; + } + // Imported PSD text can contain literal tab controls. Font shaping may + // render those as .notdef boxes; a space preserves the one-byte source + // and style/caret offsets while supplying a real whitespace advance. The space + // is widened to its tab stop after line breaking (`tab_px`). + if ch == '\t' { + tabs.push(ptext.len()); + ptext.push(' '); + continue; + } + let si = env.style_at(range.start + i); + let synthetic = env.small_caps[si] == SmallCapsMode::Synthetic; + push_cased(&mut ptext, &mut synthetic_small_caps, ch, &env.styles[si], synthetic, env.k); + } + ParaText { ptext, synthetic_small_caps, tabs } +} + +/// Appends `ch` as its style sets it: uppercased for all caps and synthetic small caps (when the +/// uppercase form has the same length, so offsets don't move), recording small-cap pieces. +fn push_cased(ptext: &mut String, small_caps: &mut Vec<(Range, f32)>, ch: char, style: &CharStyle, synthetic: bool, k: f32) { + let caps = style.caps; + if caps == photocraft_doc::text::Caps::AllCaps || synthetic { + let up: String = ch.to_uppercase().collect(); + if up.len() == ch.len_utf8() { + ptext.push_str(&up); + if caps == photocraft_doc::text::Caps::SmallCaps && ch.is_lowercase() { + let end = ptext.len(); + small_caps.push((end - up.len()..end, style.size_pt * k * SYNTHETIC_SMALL_CAPS_SCALE)); + } + return; + } + } + ptext.push(ch); +} + +/// One run piece of vertical type, whose upright stretches get the vertical alternates and their +/// class in the brush. +struct VerticalPiece<'a> { + style: &'a CharStyle, + run: usize, + small_caps: SmallCapsMode, + /// Offset of the piece in the paragraph text. + start: usize, +} + +impl VerticalPiece<'_> { + fn push_upright(&self, b: &mut parley::RangedBuilder<'_, RunBrush>, from: usize, to: usize, cls: VClass) { + if cls == VClass::Rotate || from >= to { + return; + } + let mut feats = feature_list(self.style, self.small_caps); + feats.push("\"vert\" 1".into()); + let r = (self.start + from)..(self.start + to); + b.push(StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), r.clone()); + b.push(StyleProperty::Brush(RunBrush(self.run as u32, cls as u8)), r); + } + + /// Splits `piece` into stretches of one vertical class and styles each. + fn push_all(&self, b: &mut parley::RangedBuilder<'_, RunBrush>, piece: &str) { + let mut seg: Option<(usize, VClass)> = None; + for (i, ch) in piece.char_indices() { + let cls = vertical_class(ch); + match seg { + Some((_, c)) if c == cls => {} + Some((from, c)) => { + self.push_upright(b, from, i, c); + seg = Some((i, cls)); + } + None => seg = Some((i, cls)), + } + } + if let Some((from, c)) = seg { + self.push_upright(b, from, piece.len(), c); + } + } +} + +/// What line placement needs of one paragraph: its text, styles, indents and the extents its lines +/// break at. +pub(super) struct Para<'a> { + pub(super) env: &'a Env<'a>, + pub(super) index: usize, + pub(super) ps: ParagraphStyle, + pub(super) start: usize, + pub(super) content_end: usize, + pub(super) prefix: &'static str, + ptext: String, + synthetic_small_caps: Vec<(Range, f32)>, + /// Offsets in the paragraph text of the spaces standing in for tabs. + pub(super) tabs: Vec, + /// Runs intersecting the paragraph: `si0..si_end`. + si0: usize, + si_end: usize, + fallback: Vec, + pub(super) indent_start: f32, + indent_end: f32, + pub(super) first_indent: f32, + /// Box extent along the lines: where they start. + pub(super) line_origin: f32, + /// Box extent along the lines, less the indents; `None` for point text. + pub(super) avail: Option, + pub(super) break_scale: f32, + pub(super) tab_px: f32, + /// Line-breaking passes left for this paragraph's area type (see `break_area`). + area_budget: Cell, +} + +impl<'a> Para<'a> { + pub(super) fn new(env: &'a Env<'a>, fonts: &FontDb, index: usize, range: Range, ps: ParagraphStyle) -> Self { + let k = env.k; + let content_end = strip_break(env.text, &range); + let prefix = match ps.direction { + TextDirection::Auto => "", + TextDirection::Ltr => LRM, + TextDirection::Rtl => RLM, + }; + let ParaText { ptext, synthetic_small_caps, tabs } = paragraph_text(env, prefix, &range, content_end); + // Scripts the loaded fonts may lack (Arabic, Japanese, …): a host serving a font for them + // fetches it (`served`); it joins the fallback stack once it arrives. + crate::served::request_for_text(&ptext); + let fallback = fonts.fallback_stack().map(str::to_string).collect(); + let si0 = env.style_at(range.start); + let si_end = env.run_starts.partition_point(|&rs| rs < content_end).max(si0 + 1).min(env.styles.len()); + let indent_start = ps.start_indent_pt * k; + let indent_end = ps.end_indent_pt * k; + let first_indent = ps.first_line_indent_pt * k; + // Box extent along the lines: width, or height for vertical type (columns). + let (box_x, box_y, box_w, box_h) = env.box_rect; + let (line_origin, line_len) = if env.vertical { (box_y, box_h) } else { (box_x, box_w) }; + let avail = if env.is_box { Some((line_len - indent_start - indent_end).max(1.0)) } else { None }; + let mut para = Self { + env, + index, + ps, + start: range.start, + content_end, + prefix, + ptext, + synthetic_small_caps, + tabs, + si0, + si_end, + fallback, + indent_start, + indent_end, + first_indent, + line_origin, + avail, + break_scale: 1.0, + tab_px: DEFAULT_TAB_STOP_PT * k, + area_budget: Cell::new(MAX_AREA_PASSES), + }; + para.break_scale = para.horizontal_break_scale(); + para + } + + pub(super) fn first_style(&self) -> &'a CharStyle { + &self.env.styles[self.si0] + } + + /// Text offset of the paragraph text's byte `o`, as the layer's text offset. + pub(super) fn map_offset(&self, o: usize) -> usize { + (self.start + o.saturating_sub(self.prefix.len())).min(self.content_end) + } + + /// The paragraph text up to the end of the run piece at text range `range`. + pub(super) fn text_of(&self, range: Range) -> &str { + self.ptext.get(range).unwrap_or("") + } + + /// Horizontal scale is applied after shaping, so paragraph text breaks at the box (or area span) + /// width divided by it (#5565). Mixed scales break at the largest, so no line overflows the box. + fn horizontal_break_scale(&self) -> f32 { + let env = self.env; + if !env.wraps { + return 1.0; + } + let scale = (self.si0..self.si_end) + .filter(|&ri| { + let rs = env.run_starts.get(ri).copied().unwrap_or(0); + let end = rs.saturating_add(env.runs.get(ri).map_or(0, |r| r.len)); + ri == self.si0 || (rs.max(self.start) < end.min(self.content_end)) + }) + .filter_map(|ri| env.styles.get(ri)) + .map(effective_horizontal_scale) + .fold(0.0f32, f32::max); + if scale > 0.0 { scale } else { 1.0 } + } + + /// Shapes the paragraph, each tab widened by its letter spacing in `tab_spacing` (px). + fn shape(&self, lcx: &mut LayoutContext, fcx: &mut parley::FontContext, tab_spacing: &[f32]) -> Layout { + let env = self.env; + let mut b = lcx.ranged_builder(fcx, &self.ptext, 1.0, false); + // Paragraph-start style as the default (covers the direction mark and empty + // paragraphs), then every run piece intersecting this paragraph. + for p in style_props(&env.styles[self.si0], env.k, &self.fallback, self.si0 as u32, env.small_caps[self.si0]) { + b.push_default(p); + } + // Paragraph text breaks a word wider than the box at the box edge, as Photoshop + // does (#6694): parley's default only breaks at UAX #14 opportunities and lets the + // word run out of the box. Point text has no width to overflow. + if env.is_box { + b.push_default(StyleProperty::OverflowWrap(parley::style::OverflowWrap::BreakWord)); + } + for ri in self.si0..self.si_end { + self.push_run_piece(&mut b, ri); + } + for (range, size) in &self.synthetic_small_caps { + b.push(StyleProperty::FontSize(*size), range.clone()); + } + // Korean breaks lines at spaces, between words, as Photoshop sets it; Unicode's + // default rules break between any two Hangul syllables, mid-word (#5959). + for range in hangul_runs(&self.ptext) { + b.push(StyleProperty::WordBreak(parley::WordBreak::KeepAll), range); + } + for (&at, &spacing) in self.tabs.iter().zip(tab_spacing) { + b.push(StyleProperty::LetterSpacing(spacing), at..at + 1); + } + b.build(&self.ptext) + } + + /// Styles the part of run `ri` inside this paragraph. + fn push_run_piece(&self, b: &mut parley::RangedBuilder<'_, RunBrush>, ri: usize) { + let env = self.env; + let rs = env.run_starts[ri]; + let (a, z) = (rs.max(self.start), (rs + env.runs[ri].len).min(self.content_end)); + if a >= z { + return; + } + let range = (a - self.start + self.prefix.len())..(z - self.start + self.prefix.len()); + for p in style_props(&env.styles[ri], env.k, &self.fallback, ri as u32, env.small_caps[ri]) { + b.push(p, range.clone()); + } + if env.vertical { + let piece = VerticalPiece { style: &env.styles[ri], run: ri, small_caps: env.small_caps[ri], start: range.start }; + piece.push_all(b, self.text_of(range)); + } + } + + /// Where an area paragraph's first row goes: no higher than one leading (plus paragraph + /// spacing) below the previous paragraph's last line. + fn area_origin(&self, m: LineMetrics, flow: &Flow) -> f32 { + let space_before = if flow.prev_baseline.is_some() { self.ps.space_before_pt * self.env.k } else { 0.0 }; + match (&self.env.area, flow.prev_baseline) { + (Some(_), Some(b)) => b + m.leading + flow.pending_space + space_before, + (Some(a), None) => a.bounds[1] + m.ascent, + (None, _) => 0.0, + } + } + + /// Breaks `layout` into lines; for area type also returns each line's slot and whether the + /// shape ran full. + fn break_lines(&self, layout: &mut Layout, flow: &Flow) -> (Vec, bool) { + let env = self.env; + if self.first_indent != 0.0 { + layout.set_text_indent(self.first_indent / self.break_scale, parley::IndentOptions::default()); + } + let Some(a) = &env.area else { + layout.break_all_lines(self.avail.map(|a| a / self.break_scale)); + return (Vec::new(), false); + }; + // Plan every row with the paragraph's real line metrics (its tallest font and + // largest leading, measured on the unwrapped paragraph), so no wrapped line comes + // out taller than the row it was planned in and no second plan is needed. + layout.break_all_lines(None); + let m = area_metrics(layout, env.styles, &self.ps, env.k, self.first_style(), env.vertical); + let from = self.area_origin(m, flow); + let first_px = self.first_style().size_pt * env.k; + break_area(layout, a, from, m, (self.indent_start, self.indent_end), first_px, self.break_scale, &self.area_budget) + } + + /// The widths of the tabs on the broken lines of `layout`. + fn tab_widths(&self, layout: &Layout) -> Vec { + tab_widths(layout, &self.tabs, self.env.styles, self.indent_start, self.first_indent, self.tab_px) + } + + /// Shapes and breaks the paragraph into lines (and area slots). + /// + /// A tab is never wider than a space plus one tab interval, so breaking lines at that width + /// keeps the expanded tabs inside the box, but can wrap early. Break again with the tab widths + /// that layout gives until they agree; if they don't settle, keep the safe layout. + pub(super) fn break_paragraph(&self, lcx: &mut LayoutContext, fcx: &mut parley::FontContext, flow: &Flow) -> (Layout, Vec, bool) { + let wide = if self.env.wraps { self.tab_px } else { 0.0 }; + let mut layout = self.shape(lcx, fcx, &vec![wide; self.tabs.len()]); + let (mut slots, mut full) = self.break_lines(&mut layout, flow); + if self.env.wraps + && !self.tabs.is_empty() + && let Some((settled, settled_slots, settled_full)) = self.settle_tabs(lcx, fcx, &layout, flow) + { + layout = settled; + slots = settled_slots; + full = settled_full; + } + (layout, slots, full) + } + + /// Re-breaks until the tab widths the layout gives agree with the ones it was shaped for. + fn settle_tabs( + &self, + lcx: &mut LayoutContext, + fcx: &mut parley::FontContext, + layout: &Layout, + flow: &Flow, + ) -> Option<(Layout, Vec, bool)> { + let first = self.tab_widths(layout); + let mut want: Vec = first.iter().map(|t| t.width).collect(); + for _ in 0..4 { + let spacing: Vec = first.iter().zip(&want).map(|(t, w)| w / t.scale - (t.advance - self.tab_px)).collect(); + let mut next = self.shape(lcx, fcx, &spacing); + let (next_slots, next_full) = self.break_lines(&mut next, flow); + let got: Vec = self.tab_widths(&next).iter().map(|t| t.width).collect(); + if got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 0.01) { + return Some((next, next_slots, next_full)); + } + want = got; + } + None + } + + /// How parley aligns the paragraph's lines. + pub(super) fn alignment(&self) -> Alignment { + if !self.env.wraps { + return Alignment::Left; + } + match self.ps.align { + TextAlign::Left => Alignment::Left, + TextAlign::Center => Alignment::Center, + TextAlign::Right => Alignment::Right, + _ => Alignment::Justify, + } + } + + pub(super) fn align_options(&self) -> AlignmentOptions { + AlignmentOptions { align_when_overflowing: !self.env.wraps } + } +} diff --git a/crates/text/src/layout/style.rs b/crates/text/src/layout/style.rs index fc5b775a7d..e4edac49ae 100644 --- a/crates/text/src/layout/style.rs +++ b/crates/text/src/layout/style.rs @@ -1,5 +1,8 @@ use super::paragraphs::quote; -use super::*; +use super::{ + Caps, CharStyle, ClusterInfo, Cow, FontBaseline, FontDb, FontFamily, FontFeatures, FontStyle, FontVariations, FontWeight, Kerning, PlacedGlyph, RunBrush, + StyleProperty, Tag, +}; /// Photoshop synthesizes small caps for faces without an OpenType `smcp` table. Keep the same /// readable hierarchy for every font instead of silently rendering lowercase text unchanged. diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index beabcfbf05..31d21f3d32 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -1,4 +1,4 @@ -use super::*; +use super::FontData; /// How a character is set in vertical type (a simplification of Unicode's /// `Vertical_Orientation`, UAX #50). diff --git a/crates/text/src/psd/build.rs b/crates/text/src/psd/build.rs index 658e15bd18..e4097c7de8 100644 --- a/crates/text/src/psd/build.rs +++ b/crates/text/src/psd/build.rs @@ -1,6 +1,9 @@ use super::edit::{TEMPLATE_NODES, edited_object, fits, is_stub, names_one_frame, new_object, pad_frames, td_edited_object, with_modes}; use super::import::{OPENTYPE_KEYS, TXT2_FEATURES, TXT2_STYLISTIC_SETS, kern_units, manual, object_frame, pair_runs, parse_txt2, postscript_for, real}; -use super::*; +use super::{ + AntiAlias, Caps, CharStyle, Color, ColorMode, D, Descriptor, E, FontBaseline, Id, Kerning, Orientation, ParagraphStyle, TextAlign, TextLayer, TextShape, + TySh, UnicodeString, ed, engine_data, enum_value, enumv, parse_tysh, write_tysh, +}; /// A fill colour as EngineData and `Txt2` store it: the colour type (0 gray, 1 RGB, 2 CMYK) and /// its values, alpha first. diff --git a/crates/text/src/psd/edit.rs b/crates/text/src/psd/edit.rs index c2a1afae29..1b1b90e0ff 100644 --- a/crates/text/src/psd/edit.rs +++ b/crates/text/src/psd/edit.rs @@ -1,6 +1,6 @@ use super::build::{MAX_TEXT_INDEX, utf16_len}; use super::import::parse_txt2; -use super::*; +use super::{D, E, Id, parse_tysh, write_tysh}; /// The most values a `Txt2` object may hold to serve as the template for new objects. Photoshop's /// own objects hold a few hundred (611 at most in the file from #7698). diff --git a/crates/text/src/psd/import.rs b/crates/text/src/psd/import.rs index 858561a9db..374c7408e5 100644 --- a/crates/text/src/psd/import.rs +++ b/crates/text/src/psd/import.rs @@ -1,5 +1,8 @@ use super::build::engine_antialias; -use super::*; +use super::{ + Affine, AntiAlias, Caps, CharStyle, Color, ColorMode, D, Descriptor, E, FontBaseline, Kerning, Orientation, ParagraphRun, ParagraphStyle, Point, TextAlign, + TextLayer, TextRun, TextShape, TextWarp, TySh, dnum, ed, engine_data, enum_value, guess_from_postscript, parse_tysh, +}; /// Parses the document's `Txt2` block (Photoshop's text engine data for all type layers). pub fn parse_txt2(data: &[u8]) -> Option { From 604da9d06bae19144aa35c93c37351af19dd23c0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 23:47:07 +0000 Subject: [PATCH 23/35] Enforce workspace Clippy standards and document lint policy --- AGENTS.md | 2 +- Cargo.toml | 3 +++ clippy.toml | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 172bc7bd70..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 crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new crates start with it. +- **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/Cargo.toml b/Cargo.toml index 1bf644923d..e7a70d55b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,6 +76,9 @@ web-time = "1" unsafe_code = "forbid" [workspace.lints.clippy] +cognitive_complexity = "deny" +too_many_arguments = "deny" +wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" diff --git a/clippy.toml b/clippy.toml index 287e14edc1..3522a15b69 100644 --- a/clippy.toml +++ b/clippy.toml @@ -5,3 +5,4 @@ allow-indexing-slicing-in-tests = true disallowed-types = [ { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, ] +cognitive-complexity-threshold = 30 From a703ea2781670d3a2560c54eb2b6d12de42848f5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:06:42 +0000 Subject: [PATCH 24/35] Restore wasm builds of ui-egui after the Clippy refactor --- crates/ui-egui/src/dialogs/camera_raw_ui/proxy.rs | 4 +++- crates/ui-egui/src/lib.rs | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) 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 46a82b140f..de5e054cb7 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,7 @@ +#[cfg(not(target_arch = "wasm32"))] +use super::PARALLEL_MIN_PIXELS; use super::open::raw_stage; -use super::{CameraRaw, CameraRawDialog, PARALLEL_MIN_PIXELS, RgbHistogram}; +use super::{CameraRaw, CameraRawDialog, 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/lib.rs b/crates/ui-egui/src/lib.rs index a1954b3d49..c1476bc9ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -127,7 +127,6 @@ pub use dialogs::export_dialog; pub use dialogs::file_ui; pub use dialogs::fill_ui; pub use dialogs::filter_dialog; -#[cfg(not(target_arch = "wasm32"))] use dialogs::filter_preview_ui; pub use dialogs::gallery_ui; pub use dialogs::guide_layout_ui; From 1a6d8ec9e3a91a6f36b466ee46b4f705e7116400 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:06:42 +0000 Subject: [PATCH 25/35] Refactor ui-egui control dispatch for strict Clippy checks --- crates/ui-egui/src/control/dispatch.rs | 2226 ++++++++++++++---------- 1 file changed, 1296 insertions(+), 930 deletions(-) diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index f7b87f6e9c..f3e2756071 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -5,76 +5,36 @@ use super::params::{ }; use super::{ControlRequest, DialogKind, Outcome, PhotocraftApp, SHELL_DIALOG, Tool, ToolEvent, Value, json, run_waiting, tool_event, wrap}; +/// A domain handler: `Some` when it owns the request's method, `None` to let the next one try. +type Handler = fn(&mut PhotocraftApp, &egui::Context, &ControlRequest) -> Option; + pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { - let p = &req.params; - let s = |k: &str| p.get(k).and_then(Value::as_str); - let u = |k: &str| p.get(k).and_then(Value::as_u64); - let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true); - match req.method.as_str() { - "ui.context.choose" => { - let Some(id) = s("id") else { return err("missing `id`") }; - let Some(menu) = app.ui.canvas_tool_menu.as_ref() else { return err("no canvas context menu is open") }; - if !crate::canvas_tool_menu::available(app, menu, id) { - return err("context action is unavailable"); - } - // A pasteboard row changes a preference: the policy sees the `prefs.set` it runs. - let (command, params) = crate::canvas_tool_menu::engine_call(app, menu, id); - if let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(&command, ¶ms) - { - return err(error); - } - crate::canvas_tool_menu::choose(app, ctx, id); - ok(json!({"command": id, "dialog": app.ui.dialogs.last().map(|d| d.id)})) - } - "engine.execute" | "ui.menu.invoke" => { - let Some(id) = s("command").or(s("id")) else { return err("missing `command`") }; - let params = p.get("params").cloned().unwrap_or(json!({})); - // A control-channel menu click must respect the same modal gate as the native menu. - // The documented `ui` requests of Camera Raw and the full-window workspaces operate - // the already-open one rather than click a menu. Only that continuation may pass its - // own modal gate. engine.execute is deliberately not subject to the UI's menu-click semantics. - let open_modal = if app.camera_raw.is_some() { Some("filter.cameraRaw") } else { crate::distort_ui::modal_workspace(app) }; - let continuation = open_modal == Some(id) - && params.as_object().is_some_and(|fields| fields.len() == 1 && fields.get("ui").is_some_and(Value::is_object)) - && app.ui.dialogs.is_empty() - && app.discard.is_none() - && !crate::crop_ui::blocks(app, id); - if req.method == "ui.menu.invoke" && !continuation && !crate::menus::modal_allows(app, id) { - return err("menu command is unavailable while a modal dialog is open"); - } - if let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(id, ¶ms) - { - return err(error); - } - // `engine.execute` is programmatic: engine commands run directly with their default - // params and never open a dialog (an agent would otherwise get a modal instead of a - // result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog. - if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() { - return run_waiting(app, wait, |app| app.run(id, params)); - } - run_waiting(app, wait, |app| crate::menus::invoke(app, ctx, id, params)) - } + const HANDLERS: [Handler; 5] = [engine_methods, shell_methods, dialog_methods, input_methods, app_methods]; + HANDLERS.iter().find_map(|handler| handler(app, ctx, req)).unwrap_or_else(|| err(format!("unknown method `{}`", req.method))) +} + +fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { + p.get(key).and_then(Value::as_str) +} + +fn u64_param(p: &Value, key: &str) -> Option { + p.get(key).and_then(Value::as_u64) +} + +fn wait_param(p: &Value) -> bool { + p.get("wait").and_then(Value::as_bool).unwrap_or(true) +} + +// ---- engine commands, menus and jobs ---- + +fn engine_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Option { + Some(match req.method.as_str() { + "ui.context.choose" => context_choose(app, ctx, &req.params), + "engine.execute" | "ui.menu.invoke" => execute_command(app, ctx, req), "engine.commands" => wrap(app.run("command.list", json!({}))), // Background jobs (#210): running ones with progress, then the last few that ended. "jobs.list" => wrap(app.session.execute("jobs.list", json!({})).map_err(|e| e.to_string())), - "jobs.cancel" => { - let all = p.get("job").is_none_or(Value::is_null); - match p.get("job").and_then(Value::as_u64) { - Some(j) if app.session.job(photocraft_engine::jobs::JobId(j)).is_some() => { - let cancelled = crate::jobs_ui::cancel(app, photocraft_engine::jobs::JobId(j)); - ok(json!({"cancelled": usize::from(cancelled)})) - } - Some(j) => err(format!("no running job {j}")), - None if all => { - let ids: Vec<_> = app.session.jobs().into_iter().map(|j| j.id).collect(); - let cancelled = ids.into_iter().filter(|j| crate::jobs_ui::cancel(app, *j)).count(); - ok(json!({"cancelled": cancelled})) - } - None => err("`job` must be a job id"), - } - } + "jobs.cancel" => jobs_cancel(app, &req.params), "ui.menu.list" => { // Report the same enablement the native menu shows, so a listed item is invokable. let mut items = crate::menus::menu_items(app); @@ -84,526 +44,786 @@ pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Contr ok(serde_json::to_value(items).unwrap_or_default()) } "ui.inspect" => ok(inspect(app, ctx)), - "ui.set" => { - if let Some(field) = p.as_object().and_then(|o| o.keys().find(|k| !UI_SET_FIELDS.contains(&k.as_str()))) { - return err(format!("unknown field `{field}` (fields: {})", UI_SET_FIELDS.join(", "))); + _ => return None, + }) +} + +fn context_choose(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { + let Some(id) = str_param(p, "id") else { return err("missing `id`") }; + let Some(menu) = app.ui.canvas_tool_menu.as_ref() else { return err("no canvas context menu is open") }; + if !crate::canvas_tool_menu::available(app, menu, id) { + return err("context action is unavailable"); + } + // A pasteboard row changes a preference: the policy sees the `prefs.set` it runs. + let (command, params) = crate::canvas_tool_menu::engine_call(app, menu, id); + if let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(&command, ¶ms) + { + return err(error); + } + crate::canvas_tool_menu::choose(app, ctx, id); + ok(json!({"command": id, "dialog": app.ui.dialogs.last().map(|d| d.id)})) +} + +fn execute_command(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + let p = &req.params; + let Some(id) = str_param(p, "command").or(str_param(p, "id")) else { return err("missing `command`") }; + let params = p.get("params").cloned().unwrap_or(json!({})); + let wait = wait_param(p); + // A control-channel menu click must respect the same modal gate as the native menu. + // The documented `ui` requests of Camera Raw and the full-window workspaces operate + // the already-open one rather than click a menu. Only that continuation may pass its + // own modal gate. engine.execute is deliberately not subject to the UI's menu-click semantics. + let open_modal = if app.camera_raw.is_some() { Some("filter.cameraRaw") } else { crate::distort_ui::modal_workspace(app) }; + let continuation = open_modal == Some(id) + && params.as_object().is_some_and(|fields| fields.len() == 1 && fields.get("ui").is_some_and(Value::is_object)) + && app.ui.dialogs.is_empty() + && app.discard.is_none() + && !crate::crop_ui::blocks(app, id); + if req.method == "ui.menu.invoke" && !continuation && !crate::menus::modal_allows(app, id) { + return err("menu command is unavailable while a modal dialog is open"); + } + if let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(id, ¶ms) + { + return err(error); + } + // `engine.execute` is programmatic: engine commands run directly with their default + // params and never open a dialog (an agent would otherwise get a modal instead of a + // result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog. + if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() { + return run_waiting(app, wait, |app| app.run(id, params)); + } + run_waiting(app, wait, |app| crate::menus::invoke(app, ctx, id, params)) +} + +fn jobs_cancel(app: &mut PhotocraftApp, p: &Value) -> Outcome { + let all = p.get("job").is_none_or(Value::is_null); + match p.get("job").and_then(Value::as_u64) { + Some(j) if app.session.job(photocraft_engine::jobs::JobId(j)).is_some() => { + let cancelled = crate::jobs_ui::cancel(app, photocraft_engine::jobs::JobId(j)); + ok(json!({"cancelled": usize::from(cancelled)})) + } + Some(j) => err(format!("no running job {j}")), + None if all => { + let ids: Vec<_> = app.session.jobs().into_iter().map(|j| j.id).collect(); + let cancelled = ids.into_iter().filter(|j| crate::jobs_ui::cancel(app, *j)).count(); + ok(json!({"cancelled": cancelled})) + } + None => err("`job` must be a job id"), + } +} + +// ---- the shell: view state, windows, GPU, focus, screenshots ---- + +fn shell_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Option { + let p = &req.params; + Some(match req.method.as_str() { + "ui.set" => ui_set(app, ctx, p), + "ui.window.open" => { + if let Some(d) = u64_param(p, "document") + && !app.session.set_active(d as usize) + { + return Some(err(format!("no document {d}"))); } - let gradient_blend = if let Some(value) = p.get("gradientBlendMode") { - let Some(name) = value.as_str() else { return err("gradientBlendMode must be a blend mode name") }; - let Some(mode) = photocraft_engine::commands::blend_from_str(name).filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m)) else { - return err(format!("unknown gradient blend mode `{name}`")); - }; - Some(mode) + wrap(crate::menus::invoke(app, ctx, "window.newWindowForDocument", json!({}))) + } + "ui.window.close" => { + let Some(id) = u64_param(p, "window") else { return Some(err("missing `window`")) }; + let before = app.ui.windows.len(); + app.ui.windows.retain(|w| w.id != id); + if app.ui.windows.len() < before { ok(Value::Null) } else { err(format!("no window {id}")) } + } + "ui.resize" => { + let (w, h) = (p.get("width").and_then(Value::as_f64).unwrap_or(1280.0), p.get("height").and_then(Value::as_f64).unwrap_or(800.0)); + ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w as f32, h as f32))); + ok(Value::Null) + } + "ui.gpu.simulateLoss" => simulate_gpu_loss(app, ctx, p), + "ui.focus" => { + ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + ctx.request_repaint(); + ok(Value::Null) + } + "ui.screenshot" => screenshot(app, ctx, p), + _ => return None, + }) +} + +fn simulate_gpu_loss(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { + if p.get("destroy").and_then(Value::as_bool).unwrap_or(false) { + let destroyed = app.destroy_window_device(); + ctx.request_repaint(); + return ok(json!({"destroyed": destroyed})); + } + let error = p.get("error").and_then(Value::as_bool).unwrap_or(false); + let fault = if error { + photocraft_gpu::Fault::Error("simulated error (ui.gpu.simulateLoss)".into()) + } else { + photocraft_gpu::Fault::Lost("simulated (ui.gpu.simulateLoss)".into()) + }; + let active = match app.gpu_health() { + Some(h) => { + h.mark(fault); + true + } + None => false, + }; + app.check_gpu(ctx); + ctx.request_repaint(); + ok(json!({"wasActive": active, "gpuInfo": app.perf.gpu_info})) +} + +fn screenshot(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { + let parsed = + input_object(p, None, &["path", "focus"]).and_then(|p| Ok((input_choice(&p, "path", "path", &[])?.map(str::to_string), bool_field(&p, "focus")?))); + let (path, focus) = match parsed { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + // Occluded windows don't render on macOS, so the screenshot would never arrive: raise first. + if focus.unwrap_or(true) { + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + // The capture itself is admitted by `PhotocraftApp::drain_control` (budget and + // geometry) and issued from a later `App::ui` pass once open/close animations + // (modals, popups) have settled (see `screenshot.rs`). + let token = app.ui.alloc_id(); + ctx.request_repaint(); + Outcome::Screenshot { token, path } +} + +// ---- ui.set: every field is validated and materialized into a `UiSet` before the first one is applied ---- + +fn ui_set(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { + if let Some(field) = p.as_object().and_then(|o| o.keys().find(|k| !UI_SET_FIELDS.contains(&k.as_str()))) { + return err(format!("unknown field `{field}` (fields: {})", UI_SET_FIELDS.join(", "))); + } + // Everything is validated and materialized before the first field is applied, so a + // rejected call applies none of its fields (#412's guarantee, down to the values + // and nested keys). + wrap(UiSet::parse(app, p).and_then(|set| set.apply(app, ctx, p))) +} + +struct UiSet { + tools: ToolSet, + crop: CropSet, + panels: PanelSet, + view: ViewSet, + theme: Option, + brush: BrushSet, + legacy_update: Option, +} + +impl UiSet { + fn parse(app: &PhotocraftApp, p: &Value) -> std::result::Result { + let tools = ToolSet::parse(app, p)?; + let crop = CropSet::parse(app, p)?; + let panels = PanelSet::parse(app, p)?; + let view = ViewSet::parse(app, p)?; + let theme = theme_param(p)?; + let brush = BrushSet::parse(app, p)?; + let bridge_pro = matches!(theme.unwrap_or(app.ui.theme), crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium); + let legacy_update = + crate::panel_docking::prepare_legacy_update(app, p, panels.panels.as_ref(), panels.dock_tabs.as_ref(), panels.dock.as_ref(), bridge_pro)?; + Ok(Self { tools, crop, panels, view, theme, brush, legacy_update }) + } + + /// Apply (nothing but the final `brushSize` command can fail). + fn apply(mut self, app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> std::result::Result { + self.tools.apply(app); + self.crop.apply(app); + self.panels.apply_options(app); + if let Some(k) = self.theme { + app.set_theme(ctx, k); + } + self.panels.apply_dock(app); + if let Some(update) = self.legacy_update { + crate::panel_docking::commit_legacy_update(app, update, p); + } + self.panels.apply_color_and_width(app, ctx); + self.view.apply(app); + self.brush.apply(app)?; + Ok(Value::Null) + } +} + +fn theme_param(p: &Value) -> std::result::Result, String> { + let Some(name) = str_param(p, "theme") else { return Ok(None) }; + crate::theme::ThemeKind::from_name(name).map(Some).ok_or_else(|| { + let names: Vec<_> = crate::theme::ThemeKind::ALL.iter().map(|k| k.id()).collect(); + format!("unknown theme `{name}` ({})", names.join(", ")) + }) +} + +// -- tools: stroke, tool, gradient, eyedropper, Content-Aware Move, tile grid, layer filter -- + +struct ToolSet { + gradient_blend: Option, + shape_stroke: Option>, + tool: Option, + gradient_classic: Option, + stroke_trace: Option<&'static str>, + eyedropper_size: Option, + eyedropper_sample: Option, + eyedropper_ring: Option, + cam_transform_on_drop: Option, + tile_grid: Option, + layer_filter: Option, +} + +impl ToolSet { + fn parse(app: &PhotocraftApp, p: &Value) -> std::result::Result { + Ok(Self { + gradient_blend: gradient_blend_param(p)?, + shape_stroke: shape_stroke_param(app, p)?, + tool: tool_param(p)?, + gradient_classic: bool_field(p, "gradientClassic")?, + stroke_trace: stroke_trace_param(p)?, + // The Eyedropper's options bar (#1649): Sample Size, Sample, Show Sampling Ring. + eyedropper_size: eyedropper_size_param(p)?, + eyedropper_sample: eyedropper_sample_param(p)?, + eyedropper_ring: bool_field(p, "eyedropperRing")?, + // Content-Aware Move's Transform On Drop checkbox. + cam_transform_on_drop: bool_field(p, "camTransformOnDrop")?, + // Developer overlay of the active layer's storage tiles (tile_overlay.rs). + tile_grid: bool_field(p, "tileGrid")?, + layer_filter: p.get("layerFilter").map(|v| crate::layer_filter_ui::patched(&app.ui, v)).transpose()?, + }) + } + + fn apply(self, app: &mut PhotocraftApp) { + if let Some(stroke) = &self.shape_stroke { + if let Some(stroke) = stroke { + app.ui.tool_options.stroke_width = stroke.width; + app.ui.tool_options.shape_stroke = crate::shape_stroke_ui::StrokeOptions::from(stroke); } else { - None - }; - // Everything is validated and materialized before the first field is applied, so a - // rejected call applies none of its fields (#412's guarantee, down to the values - // and nested keys). - let applied = (|| -> std::result::Result { - let shape_stroke = match p.get("shapeStroke") { - Some(v) => { - if let Some(object) = v.as_object() { - let keys = ["width", "opacity", "align", "cap", "join", "miterLimit", "dashes", "dashOffset"]; - if let Some(key) = object.keys().find(|key| !keys.contains(&key.as_str())) { - return Err(format!("unknown shapeStroke field `{key}`")); - } - } - let o = &app.ui.tool_options; - let base = o.shape_stroke.stroke(o.stroke_width, photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)); - Some(photocraft_engine::vector_cmds::parse_stroke(v, Some(base), photocraft_doc::Color::BLACK)?) - } - None => None, - }; - let tool = match s("tool") { - Some(t) => Tool::from_name(t).map(Some).ok_or_else(|| format!("unknown tool `{t}`"))?, - None => None, - }; - let gradient_classic = bool_field(p, "gradientClassic")?; - // The stroke latency trace (`stroke_trace`), at runtime: on (stderr) or off. A CSV - // file is only for the user's own launch (`--stroke-trace `): a path over the - // control channel would write outside the automation write root. - let stroke_trace = match p.get("strokeTrace") { - None | Some(Value::Null) => None, - Some(Value::Bool(b)) => Some(if *b { "stderr" } else { "off" }), - Some(Value::String(v)) => match v.trim() { - "stderr" | "on" | "true" => Some("stderr"), - "off" | "false" => Some("off"), - _ => return Err("strokeTrace must be true, false, \"stderr\" or \"off\"; a CSV file is set at launch (--stroke-trace )".into()), - }, - Some(_) => return Err("strokeTrace must be true, false, \"stderr\" or \"off\"".into()), - }; - // The Eyedropper's options bar (#1649): Sample Size, Sample, Show Sampling Ring. - let eyedropper_size = match p.get("eyedropperSampleSize") { - Some(v) => Some( - photocraft_engine::sample_cmds::size_param("ui.set", &json!({"size": v})) - .map_err(|_| format!("eyedropperSampleSize must be \"point\" or one of {:?}", photocraft_engine::sample_cmds::SAMPLE_SIZES))?, - ), - None => None, - }; - let eyedropper_sample = match p.get("eyedropperSample") { - Some(v) => { - let ids: Vec<&str> = photocraft_engine::sample_cmds::SampleLayers::ALL.iter().map(|(_, n)| *n).collect(); - let id = v.as_str().filter(|id| ids.contains(id)).ok_or_else(|| format!("eyedropperSample must be one of {}", ids.join(", ")))?; - Some(id.to_string()) - } - None => None, - }; - let eyedropper_ring = bool_field(p, "eyedropperRing")?; - // Content-Aware Move's Transform On Drop checkbox. - let cam_transform_on_drop = bool_field(p, "camTransformOnDrop")?; - // Developer overlay of the active layer's storage tiles (tile_overlay.rs). - let tile_grid = bool_field(p, "tileGrid")?; - let layer_filter = p.get("layerFilter").map(|v| crate::layer_filter_ui::patched(&app.ui, v)).transpose()?; - // The Crop tool's overlay menu (#1919). - let crop_overlay = match p.get("cropOverlay") { - Some(v) => Some(v.as_str().and_then(crate::crop_overlay::CropOverlay::from_id).ok_or_else(|| { - let ids: Vec<&str> = crate::crop_overlay::CropOverlay::ALL.iter().map(|k| k.id()).collect(); - format!("cropOverlay must be one of {}", ids.join(", ")) - })?), - None => None, - }; - let crop_overlay_show = match p.get("cropOverlayShow") { - Some(v) => Some( - v.as_str() - .and_then(crate::crop_overlay::OverlayShow::from_id) - .ok_or_else(|| "cropOverlayShow must be one of auto, always, never".to_string())?, - ), - None => None, - }; - let crop_overlay_orientation = match uint_field(p, "cropOverlayOrientation")? { - Some(o) if o < 4 => Some(o as u8), - Some(_) => return Err("cropOverlayOrientation must be 0, 1, 2 or 3".into()), - None => None, - }; - // The Crop tool's Fill (#3823): "background" (Background (Default)) or "contentAware". - let crop_content_aware = match p.get("cropFill") { - Some(v) => Some(match v.as_str() { - Some("background") => false, - Some("contentAware") => true, - _ => return Err("cropFill must be \"background\" or \"contentAware\"".into()), - }), - None => None, - }; - // The Crop tool's gear menu: Show Cropped Area and the shield (#1919). - let crop_shield = merged_object(&app.ui.tool_options.crop_shield, p.get("cropShield"), "cropShield")?; - if crop_shield.as_ref().is_some_and(|s| !(0.0..=100.0).contains(&s.opacity)) { - return Err("cropShield.opacity must be 0..100".into()); - } - // The Histogram panel: its options, the dragged tonal range ([from, to] levels or - // null) and Uncached Refresh. - let histogram_panel = merged_object(&app.ui.histogram_panel, p.get("histogramPanel"), "histogramPanel")?; - let histogram_range = match p.get("histogramRange") { - Some(v) => Some( - serde_json::from_value::>(v.clone()) - .map_err(|_| "histogramRange must be [from, to] levels 0..255, or null".to_string())?, - ), - None => None, - }; - let histogram_refresh = bool_field(p, "histogramRefresh")?; - let panels = merged_object(&app.ui.panels, p.get("panels"), "panels")?; - let mask_target = bool_field(p, "maskTarget")?; - let updates_open = bool_field(p, "updatesOpen")?; - let vector_mask_target = bool_field(p, "vectorMaskTarget")?; - // Target the active smart object's filter mask (FILE-215-3): it needs smart filters. - let filter_mask_target = bool_field(p, "filterMaskTarget")?; - if filter_mask_target == Some(true) { - let st = app.session.active().ok_or("filterMaskTarget needs an open document")?; - let l = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("filterMaskTarget needs an active layer")?; - if !matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty()) { - return Err("filterMaskTarget needs an active smart object with smart filters".into()); - } - use photocraft_engine::channel_cmds::ChannelTarget; - let composite = matches!(st.channel_view.target, ChannelTarget::Composite | ChannelTarget::LayerMask | ChannelTarget::VectorMask); - if !composite || st.doc.quick_mask.is_some() { - return Err("filterMaskTarget can't be set while a single channel or Quick Mask is targeted".into()); - } - } - let selection_mode = uint_field(p, "selectionMode")?; - let dock_tabs = merged_object(&app.ui.dock_tabs, p.get("dockTabs"), "dockTabs")?; - let dock = whole_object(&app.ui.dock, p.get("dock"), "dock")?; - // Which chip the Color panel edits. - let color_panel = merged_object(&app.ui.color_panel, p.get("colorPanel"), "colorPanel")?; - let dock_width = f32_field(p, "dockWidth")?; - let zoom = f32_field(p, "zoom")?; - let rotation = f32_field(p, "rotation")?; - if rotation.is_some() && app.session.active_index().is_none() { - return Err("no document open".into()); - } - let center = match p.get("center") { - Some(v) => { - let a = v.as_array().ok_or_else(|| "center must be [x, y]".to_string())?; - if a.len() != 2 { - return Err("center must be exactly [x, y]".into()); - } - let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) else { - return Err("center must be [x, y] of two numbers".into()); - }; - if !f32_range(&x) || !f32_range(&y) { - return Err("center must be finite numbers within f32 range".into()); - } - Some([x as f32, y as f32]) - } - None => None, - }; - let fit = bool_field(p, "fit")? == Some(true); - let theme = match s("theme") { - Some(name) => { - let kind = crate::theme::ThemeKind::from_name(name).ok_or_else(|| { - let names: Vec<_> = crate::theme::ThemeKind::ALL.iter().map(|k| k.id()).collect(); - format!("unknown theme `{name}` ({})", names.join(", ")) - })?; - Some(kind) - } - None => None, - }; - let brush_section = uint_field(p, "brushSection")?; - let brush_tab = uint_field(p, "brushTab")?; - let brushes_view = match p.get("brushesView") { - Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("brushesView: {e} (list, grid)"))?, - None => None, - }; - // The three parts of the picker's cards. At least one stays on (a rejected call - // leaves them all alone). - let brush_picker_name = bool_field(p, "brushPickerName")?; - let brush_picker_stroke = bool_field(p, "brushPickerStroke")?; - let brush_picker_tip = bool_field(p, "brushPickerTip")?; - if [brush_picker_name, brush_picker_stroke, brush_picker_tip].iter().any(Option::is_some) { - let on = [ - brush_picker_name.unwrap_or(app.ui.brush_picker_list.show_name), - brush_picker_stroke.unwrap_or(app.ui.brush_picker_list.show_stroke), - brush_picker_tip.unwrap_or(app.ui.brush_picker_list.show_tip), - ]; - if !on.iter().any(|b| *b) { - return Err("brushPickerName, brushPickerStroke and brushPickerTip: at least one must stay on".into()); - } - } - // The picker footer slider: the preset cards' size scale (1 standard; 0.30 and - // below the tips drop their size numbers). - let brush_picker_scale = match num_field(p, "brushPickerScale")? { - Some(s) if !(0.15..=2.0).contains(&s) => return Err("brushPickerScale must be between 0.15 and 2".into()), - Some(s) => Some(s as f32), - None => None, - }; - // `Some(None)` is an explicit null, which closes the picker (a missing field - // leaves it alone). - let brush_picker = match p.get("brushPicker") { - Some(v) => { - let at = serde_json::from_value::>(v.clone()) - .map_err(|_| "brushPicker must be [x, y] in screen points, or null to close it".to_string())?; - if at.is_some_and(|[x, y]| !x.is_finite() || !y.is_finite()) { - return Err("brushPicker must be [x, y] in screen points, or null to close it".into()); - } - Some(at) - } - None => None, - }; - // brushSize rides the journaled `tools.setBrush` command (#744). Numeric values - // are validated here so the command cannot fail after other fields were - // applied; non-numeric values keep the API's historical silent no-op. - let brush_size: Option = match p.get("brushSize").and_then(Value::as_f64) { - Some(size) => { - if !size.is_finite() || size > f64::from(photocraft_paint::MAX_BRUSH_SIZE) { - return Err(format!("brushSize must be finite and at most {} px", photocraft_paint::MAX_BRUSH_SIZE)); - } - Some(size) - } - None => None, - }; - - let bridge_pro = matches!(theme.unwrap_or(app.ui.theme), crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium); - let legacy_update = crate::panel_docking::prepare_legacy_update(app, p, panels.as_ref(), dock_tabs.as_ref(), dock.as_ref(), bridge_pro)?; - - // Apply (nothing below can fail). - if let Some(stroke) = shape_stroke { - if let Some(stroke) = stroke { - app.ui.tool_options.stroke_width = stroke.width; - app.ui.tool_options.shape_stroke = crate::shape_stroke_ui::StrokeOptions::from(&stroke); - } else { - app.ui.tool_options.stroke_width = 0.0; - } - } - if let Some(t) = tool { - crate::tool_memory::select(app, t); - // Each tool keeps its own brush (#218), so switch it in before `brushSize` - // below sets the new tool's size. - crate::paint_mouse::sync_tool_brush(app); - } - let gradient_before = app.ui.tool_options.clone(); - if let Some(mode) = gradient_blend { - app.ui.tool_options.gradient_blend_mode = mode; - } - if let Some(v) = &stroke_trace { - app.stroke_trace.set(v); - } - if let Some(classic) = gradient_classic { - app.ui.tool_options.gradient_classic = classic; - } - if gradient_blend.is_some() { - crate::gradient_ui::options_changed(app, &gradient_before); - } - if let Some(size) = eyedropper_size { - app.ui.tool_options.eyedropper_size = size; - } - if let Some(id) = eyedropper_sample { - app.ui.tool_options.eyedropper_sample = id; - } - if let Some(ring) = eyedropper_ring { - app.ui.tool_options.eyedropper_ring = ring; - } - if let Some(on) = cam_transform_on_drop { - app.ui.tool_options.cam_transform_on_drop = on; - } - if let Some(on) = tile_grid { - app.ui.view.tile_grid = on; - } - if let Some(f) = layer_filter { - crate::layer_filter_ui::apply(&mut app.ui, f); - } - if let Some(h) = histogram_panel { - app.ui.histogram_panel = h; - crate::histogram_panel::persist_options(app); - } - if let Some(r) = histogram_range { - app.ui.histogram_range = r; - } - if histogram_refresh == Some(true) { - crate::histogram_panel::uncached_refresh(app); - } - if let Some(k) = crop_overlay { - app.ui.tool_options.crop_overlay = k; - } - if let Some(on) = crop_content_aware { - app.ui.tool_options.crop_content_aware = on; - } - if let Some(v) = crop_overlay_show { - app.ui.tool_options.crop_overlay_show = v; - } - if let Some(o) = crop_overlay_orientation { - app.ui.tool_options.crop_overlay_orientation = o; - } - if let Some(s) = crop_shield { - app.ui.tool_options.crop_shield = s; - } - if let Some(v) = panels { - app.ui.panels = v; - } - if let Some(m) = mask_target { - app.end_filter_mask_view(); - app.ui.filter_mask_target = None; - app.ui.mask_target = m; - app.ui.properties_layer = None; - app.ui.vector_mask_target &= !m; - app.sync_mask_targets(); - } - if let Some(open) = updates_open { - app.ui.updates_open = open; - } - if let Some(m) = vector_mask_target { - app.end_filter_mask_view(); - app.ui.filter_mask_target = None; - app.ui.vector_mask_target = m; - app.ui.mask_target &= !m; - app.sync_mask_targets(); - } - if let Some(m) = filter_mask_target { - let layer = if m { app.session.active().and_then(|st| st.active_layer).map(|id| id.0) } else { None }; - app.select_filter_mask_target(layer); - } - // Selection tools' options-bar mode: 0 New, 1 Add, 2 Subtract, 3 Intersect. - if let Some(m) = selection_mode { - app.ui.selection_mode = m.min(3) as u8; - } - if let Some(k) = theme { - app.set_theme(ctx, k); - } - if let Some(v) = dock_tabs { - app.ui.dock_tabs = v; - } - // Dock group order, heights and collapsed groups (see `dock::DockLayout`). - if let Some(v) = dock { - app.ui.dock = v; - } - if let Some(update) = legacy_update { - crate::panel_docking::commit_legacy_update(app, update, p); - } - if let Some(v) = color_panel { - app.ui.color_panel = v; - } - // Right dock width in points (clamped to the dock's 250..=520 range), applied next frame. - if let Some(w) = dock_width { - crate::panels::request_dock_width(ctx, w as f32); - } - if let Some(i) = app.session.active_index() { - if zoom.is_some() || center.is_some() || rotation.is_some() || fit { - app.ui.views[i].zoom_animating = false; - app.ui.views[i].zoom_anchor = None; - } - if let Some(z) = zoom { - let size = app.session.documents().get(i).map_or([0, 0], |st| [st.doc.size.width, st.doc.size.height]); - app.ui.views[i].zoom = crate::zoom_levels::clamp(z as f32, size); - app.ui.views[i].fit_pending = false; - app.ui.views[i].fill_pending = false; - } - if let Some(c) = center { - app.ui.views[i].center = c; - app.ui.views[i].fit_pending = false; - app.ui.views[i].fill_pending = false; - } - if fit { - app.ui.views[i].fit_pending = true; - app.ui.views[i].fill_pending = false; - } - if let Some(r) = rotation { - app.ui.views[i].rotation = crate::rotate_view::wrap_deg(r as f32); - } - } - if let Some(i) = brush_section { - app.ui.brush_section = (i as usize).min(crate::brush_panel::SECTIONS.len() - 1); - } - if let Some(i) = brush_tab { - app.ui.brush_tab = (i as usize).min(1); - } - if let Some(v) = brushes_view { - app.ui.brushes_panel.view = v; - } - if let Some(v) = brush_picker_name { - app.ui.brush_picker_list.show_name = v; - } - if let Some(v) = brush_picker_stroke { - app.ui.brush_picker_list.show_stroke = v; - } - if let Some(v) = brush_picker_tip { - app.ui.brush_picker_list.show_tip = v; - } - if let Some(v) = brush_picker_scale { - app.ui.brush_picker_list.scale = v; - } - if let Some(at) = brush_picker { - app.ui.brush_picker = at; - } - // Which chip the Color panel edits. - if let Some(c) = color_panel { - app.ui.color_panel = c; - } - if let Some(size) = brush_size { - app.run("tools.setBrush", json!({"brush": {"size": size}})).map_err(|e| e.to_string())?; - } - Ok(Value::Null) - })(); - wrap(applied) - } - "ui.dialog.open" => { - let kind = match s("kind").unwrap_or("") { - "newDocument" | "NewDocument" => DialogKind::NewDocument, - "about" | "About" => DialogKind::About, - "layerStyle" | "LayerStyle" => { - return match crate::layer_style::open(app, s("effect")) { - Some(id) => ok(json!({"dialog": id})), - None => err("no active layer"), - }; - } - "colorPicker" | "ColorPicker" => { - if let Some(style) = p.get("textStyle") { - if ["parent", "effect", "field", "target"].iter().any(|key| p.get(*key).is_some()) { - return err("textStyle cannot be combined with another picker target"); - } - let Some(style) = style.as_object().filter(|s| s.keys().all(|k| k == "kind" || k == "id")) else { - return err("textStyle needs kind and id only"); - }; - let Some(kind) = style.get("kind").cloned().and_then(|v| serde_json::from_value::(v).ok()) - else { - return err("textStyle kind must be character or paragraph"); - }; - let Some(id) = style.get("id").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()) else { - return err("textStyle id must be a u32 integer"); - }; - return match crate::type_panels_ui::color_picker::open(app, kind, id) { - Ok(id) => ok(json!({"dialog": id})), - Err(error) => err(error), - }; - } - if p.get("parent").is_some() { - let (Some(parent), Some(effect), Some(field)) = (u("parent"), s("effect"), s("field")) else { - return err("need integer `parent` and string `effect` and `field`"); - }; - return match crate::layer_style::color_picker::open(app, parent, effect, field) { - Ok(id) => ok(json!({"dialog": id})), - Err(error) => err(error), - }; - } - if p.get("effect").is_some() || p.get("field").is_some() { - return err("Layer Style color pickers need `parent`"); - } - let target = if s("target") == Some("background") { "background" } else { "foreground" }; - return ok(json!({"dialog": crate::color_picker_ui::open(app, target)})); - } - // The Crop tool's New / Delete Crop Preset… (#1919). - "newCropPreset" => { - return match crate::crop_presets::open_new(app) { - Some(id) => ok(json!({"dialog": id})), - None => err("nothing to save: set W and H (W x H x Resolution) or a ratio first"), - }; - } - "deleteCropPreset" => { - return match crate::crop_presets::open_delete(app) { - Some(id) => ok(json!({"dialog": id})), - None => err("no crop presets are saved"), - }; - } - "command" | "Command" => { - let Some(cmd) = s("command") else { return err("command dialogs need `command`") }; - let label = photocraft_engine::commands::find(cmd).map(|c| c.label).unwrap_or(cmd); - return ok(json!({"dialog": crate::dialogs::open_command_dialog(app, cmd, label)})); - } - other => return err(format!("unknown dialog kind `{other}`")), - }; - let mut fields = if kind == DialogKind::NewDocument { app.new_document_fields() } else { Default::default() }; - if let Some(f) = p.get("fields").and_then(Value::as_object) { - if let Some(marker) = f.keys().find(|k| crate::dialogs::is_route_marker(k)) { - return err(format!("`{marker}` is set only by the dialog it belongs to")); - } - fields.extend(f.clone()); + app.ui.tool_options.stroke_width = 0.0; } - ok(json!({"dialog": app.ui.open_dialog(kind, fields)})) } + if let Some(t) = self.tool { + crate::tool_memory::select(app, t); + // Each tool keeps its own brush (#218), so switch it in before `brushSize` + // sets the new tool's size. + crate::paint_mouse::sync_tool_brush(app); + } + self.apply_gradient_and_trace(app); + if let Some(size) = self.eyedropper_size { + app.ui.tool_options.eyedropper_size = size; + } + if let Some(id) = self.eyedropper_sample { + app.ui.tool_options.eyedropper_sample = id; + } + if let Some(ring) = self.eyedropper_ring { + app.ui.tool_options.eyedropper_ring = ring; + } + if let Some(on) = self.cam_transform_on_drop { + app.ui.tool_options.cam_transform_on_drop = on; + } + if let Some(on) = self.tile_grid { + app.ui.view.tile_grid = on; + } + if let Some(f) = self.layer_filter { + crate::layer_filter_ui::apply(&mut app.ui, f); + } + } + + fn apply_gradient_and_trace(&self, app: &mut PhotocraftApp) { + let gradient_before = app.ui.tool_options.clone(); + if let Some(mode) = self.gradient_blend { + app.ui.tool_options.gradient_blend_mode = mode; + } + if let Some(v) = &self.stroke_trace { + app.stroke_trace.set(v); + } + if let Some(classic) = self.gradient_classic { + app.ui.tool_options.gradient_classic = classic; + } + if self.gradient_blend.is_some() { + crate::gradient_ui::options_changed(app, &gradient_before); + } + } +} + +fn gradient_blend_param(p: &Value) -> std::result::Result, String> { + let Some(value) = p.get("gradientBlendMode") else { return Ok(None) }; + let Some(name) = value.as_str() else { return Err("gradientBlendMode must be a blend mode name".into()) }; + photocraft_engine::commands::blend_from_str(name) + .filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m)) + .map(Some) + .ok_or_else(|| format!("unknown gradient blend mode `{name}`")) +} + +fn shape_stroke_param(app: &PhotocraftApp, p: &Value) -> std::result::Result>, String> { + let Some(v) = p.get("shapeStroke") else { return Ok(None) }; + if let Some(object) = v.as_object() { + let keys = ["width", "opacity", "align", "cap", "join", "miterLimit", "dashes", "dashOffset"]; + if let Some(key) = object.keys().find(|key| !keys.contains(&key.as_str())) { + return Err(format!("unknown shapeStroke field `{key}`")); + } + } + let o = &app.ui.tool_options; + let base = o.shape_stroke.stroke(o.stroke_width, photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)); + Ok(Some(photocraft_engine::vector_cmds::parse_stroke(v, Some(base), photocraft_doc::Color::BLACK)?)) +} + +fn tool_param(p: &Value) -> std::result::Result, String> { + match str_param(p, "tool") { + Some(t) => Tool::from_name(t).map(Some).ok_or_else(|| format!("unknown tool `{t}`")), + None => Ok(None), + } +} + +/// The stroke latency trace (`stroke_trace`), at runtime: on (stderr) or off. A CSV +/// file is only for the user's own launch (`--stroke-trace `): a path over the +/// control channel would write outside the automation write root. +fn stroke_trace_param(p: &Value) -> std::result::Result, String> { + match p.get("strokeTrace") { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(if *b { "stderr" } else { "off" })), + Some(Value::String(v)) => match v.trim() { + "stderr" | "on" | "true" => Ok(Some("stderr")), + "off" | "false" => Ok(Some("off")), + _ => Err("strokeTrace must be true, false, \"stderr\" or \"off\"; a CSV file is set at launch (--stroke-trace )".into()), + }, + Some(_) => Err("strokeTrace must be true, false, \"stderr\" or \"off\"".into()), + } +} + +fn eyedropper_size_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("eyedropperSampleSize") else { return Ok(None) }; + photocraft_engine::sample_cmds::size_param("ui.set", &json!({"size": v})) + .map(Some) + .map_err(|_| format!("eyedropperSampleSize must be \"point\" or one of {:?}", photocraft_engine::sample_cmds::SAMPLE_SIZES)) +} + +fn eyedropper_sample_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("eyedropperSample") else { return Ok(None) }; + let ids: Vec<&str> = photocraft_engine::sample_cmds::SampleLayers::ALL.iter().map(|(_, n)| *n).collect(); + let id = v.as_str().filter(|id| ids.contains(id)).ok_or_else(|| format!("eyedropperSample must be one of {}", ids.join(", ")))?; + Ok(Some(id.to_string())) +} + +// -- the Crop tool's overlay, Fill and gear menu -- + +struct CropSet { + overlay: Option, + overlay_show: Option, + orientation: Option, + content_aware: Option, + shield: Option, +} + +impl CropSet { + fn parse(app: &PhotocraftApp, p: &Value) -> std::result::Result { + // The Crop tool's overlay menu (#1919). + let overlay = crop_overlay_param(p)?; + let overlay_show = crop_overlay_show_param(p)?; + let orientation = crop_orientation_param(p)?; + // The Crop tool's Fill (#3823): "background" (Background (Default)) or "contentAware". + let content_aware = crop_fill_param(p)?; + // The Crop tool's gear menu: Show Cropped Area and the shield (#1919). + let shield = merged_object(&app.ui.tool_options.crop_shield, p.get("cropShield"), "cropShield")?; + if shield.as_ref().is_some_and(|s| !(0.0..=100.0).contains(&s.opacity)) { + return Err("cropShield.opacity must be 0..100".into()); + } + Ok(Self { overlay, overlay_show, orientation, content_aware, shield }) + } + + fn apply(self, app: &mut PhotocraftApp) { + let o = &mut app.ui.tool_options; + if let Some(k) = self.overlay { + o.crop_overlay = k; + } + if let Some(on) = self.content_aware { + o.crop_content_aware = on; + } + if let Some(v) = self.overlay_show { + o.crop_overlay_show = v; + } + if let Some(v) = self.orientation { + o.crop_overlay_orientation = v; + } + if let Some(s) = self.shield { + o.crop_shield = s; + } + } +} + +fn crop_overlay_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("cropOverlay") else { return Ok(None) }; + v.as_str().and_then(crate::crop_overlay::CropOverlay::from_id).map(Some).ok_or_else(|| { + let ids: Vec<&str> = crate::crop_overlay::CropOverlay::ALL.iter().map(|k| k.id()).collect(); + format!("cropOverlay must be one of {}", ids.join(", ")) + }) +} + +fn crop_overlay_show_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("cropOverlayShow") else { return Ok(None) }; + v.as_str().and_then(crate::crop_overlay::OverlayShow::from_id).map(Some).ok_or_else(|| "cropOverlayShow must be one of auto, always, never".to_string()) +} + +fn crop_orientation_param(p: &Value) -> std::result::Result, String> { + match uint_field(p, "cropOverlayOrientation")? { + Some(o) if o < 4 => Ok(Some(o as u8)), + Some(_) => Err("cropOverlayOrientation must be 0, 1, 2 or 3".into()), + None => Ok(None), + } +} + +fn crop_fill_param(p: &Value) -> std::result::Result, String> { + match p.get("cropFill") { + Some(v) => match v.as_str() { + Some("background") => Ok(Some(false)), + Some("contentAware") => Ok(Some(true)), + _ => Err("cropFill must be \"background\" or \"contentAware\"".into()), + }, + None => Ok(None), + } +} + +// -- panels: Histogram, masks targets, docking, Color panel -- + +struct PanelSet { + histogram_panel: Option, + histogram_range: Option>, + histogram_refresh: Option, + panels: Option, + mask_target: Option, + updates_open: Option, + vector_mask_target: Option, + filter_mask_target: Option, + selection_mode: Option, + dock_tabs: Option, + dock: Option, + color_panel: Option, + dock_width: Option, +} + +impl PanelSet { + fn parse(app: &PhotocraftApp, p: &Value) -> std::result::Result { + Ok(Self { + // The Histogram panel: its options, the dragged tonal range ([from, to] levels or + // null) and Uncached Refresh. + histogram_panel: merged_object(&app.ui.histogram_panel, p.get("histogramPanel"), "histogramPanel")?, + histogram_range: histogram_range_param(p)?, + histogram_refresh: bool_field(p, "histogramRefresh")?, + panels: merged_object(&app.ui.panels, p.get("panels"), "panels")?, + mask_target: bool_field(p, "maskTarget")?, + updates_open: bool_field(p, "updatesOpen")?, + vector_mask_target: bool_field(p, "vectorMaskTarget")?, + filter_mask_target: filter_mask_target_param(app, p)?, + selection_mode: uint_field(p, "selectionMode")?, + dock_tabs: merged_object(&app.ui.dock_tabs, p.get("dockTabs"), "dockTabs")?, + dock: whole_object(&app.ui.dock, p.get("dock"), "dock")?, + // Which chip the Color panel edits. + color_panel: merged_object(&app.ui.color_panel, p.get("colorPanel"), "colorPanel")?, + dock_width: f32_field(p, "dockWidth")?, + }) + } + + /// Everything that precedes the theme. + fn apply_options(&mut self, app: &mut PhotocraftApp) { + self.apply_histogram(app); + if let Some(v) = self.panels.take() { + app.ui.panels = v; + } + self.apply_mask_targets(app); + // Selection tools' options-bar mode: 0 New, 1 Add, 2 Subtract, 3 Intersect. + if let Some(m) = self.selection_mode { + app.ui.selection_mode = m.min(3) as u8; + } + } + + fn apply_histogram(&mut self, app: &mut PhotocraftApp) { + if let Some(h) = self.histogram_panel.take() { + app.ui.histogram_panel = h; + crate::histogram_panel::persist_options(app); + } + if let Some(r) = self.histogram_range { + app.ui.histogram_range = r; + } + if self.histogram_refresh == Some(true) { + crate::histogram_panel::uncached_refresh(app); + } + } + + fn apply_mask_targets(&self, app: &mut PhotocraftApp) { + if let Some(m) = self.mask_target { + app.end_filter_mask_view(); + app.ui.filter_mask_target = None; + app.ui.mask_target = m; + app.ui.properties_layer = None; + app.ui.vector_mask_target &= !m; + app.sync_mask_targets(); + } + if let Some(open) = self.updates_open { + app.ui.updates_open = open; + } + if let Some(m) = self.vector_mask_target { + app.end_filter_mask_view(); + app.ui.filter_mask_target = None; + app.ui.vector_mask_target = m; + app.ui.mask_target &= !m; + app.sync_mask_targets(); + } + if let Some(m) = self.filter_mask_target { + let layer = if m { app.session.active().and_then(|st| st.active_layer).map(|id| id.0) } else { None }; + app.select_filter_mask_target(layer); + } + } + + fn apply_dock(&mut self, app: &mut PhotocraftApp) { + if let Some(v) = self.dock_tabs.take() { + app.ui.dock_tabs = v; + } + // Dock group order, heights and collapsed groups (see `dock::DockLayout`). + if let Some(v) = self.dock.take() { + app.ui.dock = v; + } + } + + fn apply_color_and_width(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) { + if let Some(v) = self.color_panel.take() { + app.ui.color_panel = v; + } + // Right dock width in points (clamped to the dock's 250..=520 range), applied next frame. + if let Some(w) = self.dock_width { + crate::panels::request_dock_width(ctx, w as f32); + } + } +} + +fn histogram_range_param(p: &Value) -> std::result::Result>, String> { + let Some(v) = p.get("histogramRange") else { return Ok(None) }; + serde_json::from_value::>(v.clone()).map(Some).map_err(|_| "histogramRange must be [from, to] levels 0..255, or null".to_string()) +} + +/// Target the active smart object's filter mask (FILE-215-3): it needs smart filters. +fn filter_mask_target_param(app: &PhotocraftApp, p: &Value) -> std::result::Result, String> { + let target = bool_field(p, "filterMaskTarget")?; + if target == Some(true) { + check_filter_mask_target(app)?; + } + Ok(target) +} + +fn check_filter_mask_target(app: &PhotocraftApp) -> std::result::Result<(), String> { + use photocraft_engine::channel_cmds::ChannelTarget; + let st = app.session.active().ok_or("filterMaskTarget needs an open document")?; + let l = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("filterMaskTarget needs an active layer")?; + if !matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty()) { + return Err("filterMaskTarget needs an active smart object with smart filters".into()); + } + let composite = matches!(st.channel_view.target, ChannelTarget::Composite | ChannelTarget::LayerMask | ChannelTarget::VectorMask); + if !composite || st.doc.quick_mask.is_some() { + return Err("filterMaskTarget can't be set while a single channel or Quick Mask is targeted".into()); + } + Ok(()) +} + +// -- the document view: zoom, centre, rotation, fit -- + +struct ViewSet { + zoom: Option, + rotation: Option, + center: Option<[f32; 2]>, + fit: bool, +} + +impl ViewSet { + fn parse(app: &PhotocraftApp, p: &Value) -> std::result::Result { + let zoom = f32_field(p, "zoom")?; + let rotation = f32_field(p, "rotation")?; + if rotation.is_some() && app.session.active_index().is_none() { + return Err("no document open".into()); + } + let center = center_param(p)?; + let fit = bool_field(p, "fit")? == Some(true); + Ok(Self { zoom, rotation, center, fit }) + } + + fn apply(&self, app: &mut PhotocraftApp) { + let Some(i) = app.session.active_index() else { return }; + if self.zoom.is_some() || self.center.is_some() || self.rotation.is_some() || self.fit { + app.ui.views[i].zoom_animating = false; + app.ui.views[i].zoom_anchor = None; + } + if let Some(z) = self.zoom { + let size = app.session.documents().get(i).map_or([0, 0], |st| [st.doc.size.width, st.doc.size.height]); + app.ui.views[i].zoom = crate::zoom_levels::clamp(z as f32, size); + app.ui.views[i].fit_pending = false; + app.ui.views[i].fill_pending = false; + } + if let Some(c) = self.center { + app.ui.views[i].center = c; + app.ui.views[i].fit_pending = false; + app.ui.views[i].fill_pending = false; + } + if self.fit { + app.ui.views[i].fit_pending = true; + app.ui.views[i].fill_pending = false; + } + if let Some(r) = self.rotation { + app.ui.views[i].rotation = crate::rotate_view::wrap_deg(r as f32); + } + } +} + +fn center_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("center") else { return Ok(None) }; + let a = v.as_array().ok_or_else(|| "center must be [x, y]".to_string())?; + if a.len() != 2 { + return Err("center must be exactly [x, y]".into()); + } + let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) else { + return Err("center must be [x, y] of two numbers".into()); + }; + if !f32_range(&x) || !f32_range(&y) { + return Err("center must be finite numbers within f32 range".into()); + } + Ok(Some([x as f32, y as f32])) +} + +// -- brushes: sections, picker, size -- + +struct BrushSet { + section: Option, + tab: Option, + brushes_view: Option, + picker_name: Option, + picker_stroke: Option, + picker_tip: Option, + picker_scale: Option, + picker: Option>, + size: Option, +} + +impl BrushSet { + fn parse(app: &PhotocraftApp, p: &Value) -> std::result::Result { + let section = uint_field(p, "brushSection")?; + let tab = uint_field(p, "brushTab")?; + let brushes_view = brushes_view_param(p)?; + // The three parts of the picker's cards. At least one stays on (a rejected call + // leaves them all alone). + let picker_name = bool_field(p, "brushPickerName")?; + let picker_stroke = bool_field(p, "brushPickerStroke")?; + let picker_tip = bool_field(p, "brushPickerTip")?; + check_picker_parts(app, [picker_name, picker_stroke, picker_tip])?; + Ok(Self { + section, + tab, + brushes_view, + picker_name, + picker_stroke, + picker_tip, + picker_scale: picker_scale_param(p)?, + picker: picker_param(p)?, + size: brush_size_param(p)?, + }) + } + + fn apply(&self, app: &mut PhotocraftApp) -> std::result::Result<(), String> { + if let Some(i) = self.section { + app.ui.brush_section = (i as usize).min(crate::brush_panel::SECTIONS.len() - 1); + } + if let Some(i) = self.tab { + app.ui.brush_tab = (i as usize).min(1); + } + if let Some(v) = self.brushes_view { + app.ui.brushes_panel.view = v; + } + self.apply_picker(app); + if let Some(size) = self.size { + app.run("tools.setBrush", json!({"brush": {"size": size}})).map_err(|e| e.to_string())?; + } + Ok(()) + } + + fn apply_picker(&self, app: &mut PhotocraftApp) { + let list = &mut app.ui.brush_picker_list; + if let Some(v) = self.picker_name { + list.show_name = v; + } + if let Some(v) = self.picker_stroke { + list.show_stroke = v; + } + if let Some(v) = self.picker_tip { + list.show_tip = v; + } + if let Some(v) = self.picker_scale { + list.scale = v; + } + if let Some(at) = self.picker { + app.ui.brush_picker = at; + } + } +} + +fn brushes_view_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("brushesView") else { return Ok(None) }; + serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("brushesView: {e} (list, grid)")) +} + +fn check_picker_parts(app: &PhotocraftApp, parts: [Option; 3]) -> std::result::Result<(), String> { + if parts.iter().all(Option::is_none) { + return Ok(()); + } + let list = &app.ui.brush_picker_list; + let on = [parts[0].unwrap_or(list.show_name), parts[1].unwrap_or(list.show_stroke), parts[2].unwrap_or(list.show_tip)]; + if on.iter().any(|b| *b) { Ok(()) } else { Err("brushPickerName, brushPickerStroke and brushPickerTip: at least one must stay on".into()) } +} + +/// The picker footer slider: the preset cards' size scale (1 standard; 0.30 and +/// below the tips drop their size numbers). +fn picker_scale_param(p: &Value) -> std::result::Result, String> { + match num_field(p, "brushPickerScale")? { + Some(s) if !(0.15..=2.0).contains(&s) => Err("brushPickerScale must be between 0.15 and 2".into()), + Some(s) => Ok(Some(s as f32)), + None => Ok(None), + } +} + +/// `Some(None)` is an explicit null, which closes the picker (a missing field leaves it alone). +fn picker_param(p: &Value) -> std::result::Result>, String> { + let Some(v) = p.get("brushPicker") else { return Ok(None) }; + let at = + serde_json::from_value::>(v.clone()).map_err(|_| "brushPicker must be [x, y] in screen points, or null to close it".to_string())?; + if at.is_some_and(|[x, y]| !x.is_finite() || !y.is_finite()) { + return Err("brushPicker must be [x, y] in screen points, or null to close it".into()); + } + Ok(Some(at)) +} + +/// brushSize rides the journaled `tools.setBrush` command (#744). Numeric values +/// are validated here so the command cannot fail after other fields were +/// applied; non-numeric values keep the API's historical silent no-op. +fn brush_size_param(p: &Value) -> std::result::Result, String> { + let Some(size) = p.get("brushSize").and_then(Value::as_f64) else { return Ok(None) }; + if !size.is_finite() || size > f64::from(photocraft_paint::MAX_BRUSH_SIZE) { + return Err(format!("brushSize must be finite and at most {} px", photocraft_paint::MAX_BRUSH_SIZE)); + } + Ok(Some(size)) +} + +// ---- dialogs ---- + +fn dialog_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Option { + let p = &req.params; + let s = |k: &str| str_param(p, k); + let u = |k: &str| u64_param(p, k); + Some(match req.method.as_str() { + "ui.dialog.open" => dialog_open(app, p), // The shell's own dialog (Window › Workspace, View › Pixel Aspect Ratio › Custom, Show // Extras Options, 32-bit Preview Options), listed by ui.inspect with the id "shell". - "ui.dialog.set" if s("dialog") == Some(SHELL_DIALOG) => { - let Some(field) = s("field") else { return err("need `dialog` and `field`") }; - let value = p.get("value").cloned().unwrap_or(Value::Null); - match app.ui.shell.dialog.as_mut() { - Some((_, fields)) => { - fields.insert(field.to_string(), value); - ok(Value::Null) - } - None => err("no shell dialog is open"), - } - } - "ui.dialog.confirm" if s("dialog") == Some(SHELL_DIALOG) => { - let Some((kind, fields)) = app.ui.shell.dialog.clone() else { return err("no shell dialog is open") }; - if let Some((command, params)) = crate::workspace_ui::dialog_command(&kind, &fields) - && let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(command, ¶ms) - { - return err(error); - } - wrap(crate::workspace_ui::confirm(app, ctx)) - } + "ui.dialog.set" if s("dialog") == Some(SHELL_DIALOG) => shell_dialog_set(app, p), + "ui.dialog.confirm" if s("dialog") == Some(SHELL_DIALOG) => shell_dialog_confirm(app, ctx), "ui.dialog.apply" if s("dialog") == Some(SHELL_DIALOG) => err("`ui.dialog.apply` is for Preferences; use `ui.dialog.confirm`"), // The unsaved-changes prompt (closing, Revert, quitting), listed by ui.inspect with the // id "discard" (#4920): confirm takes a `choice` (save, dontSave, cancel; default save). - "ui.dialog.confirm" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => { - let choice = s("choice").unwrap_or("save"); - if choice != "cancel" - && let Some((command, params)) = crate::discard_ui::pending_command(app) - && let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(&command, ¶ms) - { - return err(error); - } - wrap(crate::discard_ui::answer_control(app, ctx, choice)) - } + "ui.dialog.confirm" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => discard_dialog_confirm(app, ctx, s("choice").unwrap_or("save")), "ui.dialog.cancel" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => wrap(crate::discard_ui::answer_control(app, ctx, "cancel")), "ui.dialog.set" | "ui.dialog.apply" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => { err("the unsaved-changes prompt has no fields; use `ui.dialog.confirm` with a `choice`") @@ -612,42 +832,9 @@ pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Contr Some(_) => ok(Value::Null), None => err("no such dialog"), }, - "ui.dialog.set" => { - let (Some(id), Some(field)) = (u("dialog"), s("field")) else { return err("need `dialog` and `field`") }; - let value = p.get("value").cloned().unwrap_or(Value::Null); - match app.ui.dialog_mut(id) { - // A continuation belongs to the dialog that paused it, even when another - // action has a valid token. Replacing it would resume or cancel that action. - Some(_) if field == crate::actions::RESUME => err("the paused action token is read-only"), - // A marker picks the handler OK runs: a dialog keeps the ones it was opened with. - Some(d) if !d.fields.contains_key(field) && crate::dialogs::is_route_marker(field) => { - err(format!("`{field}` is set only by the dialog it belongs to")) - } - Some(d) => { - d.fields.insert(field.to_string(), value); - ok(Value::Null) - } - None => err(format!("no dialog {id}")), - } - } + "ui.dialog.set" => dialog_set(app, p), "ui.dialog.confirm" | "ui.dialog.apply" => match u("dialog") { - Some(id) => { - let command = app.ui.dialogs.iter().find(|dialog| dialog.id == id).and_then(|dialog| { - if req.method == "ui.dialog.apply" { - dialog.fields.get("values").map(|values| ("prefs.set".to_string(), json!({"path": "", "value": values}))) - } else { - dialog.fields.get("__command").and_then(Value::as_str).map(|command| (command.to_string(), Value::Object(dialog.fields.clone()))) - } - }); - if let Some((command, params)) = command - && let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(&command, ¶ms) - { - return err(error); - } - let apply = req.method == "ui.dialog.apply"; - run_waiting(app, wait, |app| if apply { crate::prefs_ui::apply(app, id) } else { crate::dialogs::confirm(app, id) }) - } + Some(id) => dialog_confirm_or_apply(app, req, id), None => err("missing `dialog`"), }, "ui.dialog.cancel" => match u("dialog") { @@ -657,341 +844,477 @@ pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Contr }, None => err("missing `dialog`"), }, - "ui.window.open" => { - if let Some(d) = u("document") - && !app.session.set_active(d as usize) - { - return err(format!("no document {d}")); - } - wrap(crate::menus::invoke(app, ctx, "window.newWindowForDocument", json!({}))) + _ => return None, + }) +} + +fn dialog_open(app: &mut PhotocraftApp, p: &Value) -> Outcome { + let kind = match str_param(p, "kind").unwrap_or("") { + "newDocument" | "NewDocument" => DialogKind::NewDocument, + "about" | "About" => DialogKind::About, + "colorPicker" | "ColorPicker" => return color_picker_dialog(app, p), + other => return open_named_dialog(app, p, other), + }; + let mut fields = if kind == DialogKind::NewDocument { app.new_document_fields() } else { Default::default() }; + if let Some(f) = p.get("fields").and_then(Value::as_object) { + if let Some(marker) = f.keys().find(|k| crate::dialogs::is_route_marker(k)) { + return err(format!("`{marker}` is set only by the dialog it belongs to")); } - "ui.window.close" => { - let Some(id) = u("window") else { return err("missing `window`") }; - let before = app.ui.windows.len(); - app.ui.windows.retain(|w| w.id != id); - if app.ui.windows.len() < before { ok(Value::Null) } else { err(format!("no window {id}")) } + fields.extend(f.clone()); + } + ok(json!({"dialog": app.ui.open_dialog(kind, fields)})) +} + +/// The dialog kinds that open through their own module rather than `open_dialog`. +fn open_named_dialog(app: &mut PhotocraftApp, p: &Value, kind: &str) -> Outcome { + let opened = |id: Option, missing: &str| match id { + Some(id) => ok(json!({"dialog": id})), + None => err(missing), + }; + match kind { + "layerStyle" | "LayerStyle" => opened(crate::layer_style::open(app, str_param(p, "effect")), "no active layer"), + // The Crop tool's New / Delete Crop Preset… (#1919). + "newCropPreset" => opened(crate::crop_presets::open_new(app), "nothing to save: set W and H (W x H x Resolution) or a ratio first"), + "deleteCropPreset" => opened(crate::crop_presets::open_delete(app), "no crop presets are saved"), + "command" | "Command" => { + let Some(cmd) = str_param(p, "command") else { return err("command dialogs need `command`") }; + let label = photocraft_engine::commands::find(cmd).map(|c| c.label).unwrap_or(cmd); + ok(json!({"dialog": crate::dialogs::open_command_dialog(app, cmd, label)})) } - "ui.pointer" => { - // Every field and event is validated before the first event runs, so a rejected call - // changes nothing (#2449). - let parsed = (|| -> std::result::Result<_, String> { - let fields = ["events", "tool", "modifiers", "button", "shift", "alt", "command", "ctrl", "space"]; - let p = input_object(p, None, &fields)?; - let tool = match input_choice(&p, "tool", "tool", &[])? { - Some(t) => Some(Tool::from_name(t).ok_or_else(|| format!("unknown tool `{t}`"))?), - None => None, - }; - let button = input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left").to_string(); - // Modifier flags may be top-level or grouped under "modifiers". - let m = input_modifiers(&p, &POINTER_MODIFIERS)?; - let Some(events) = p.get("events") else { return Err("missing `events`".into()) }; - let Some(events) = events.as_array() else { return Err("events must be an array".into()) }; - let mut parsed = Vec::with_capacity(events.len()); - for (i, e) in events.iter().enumerate() { - let name = format!("events[{i}]"); - let e = input_object(e, Some(&name), &["kind", "x", "y", "pressure", "tiltX", "tiltY", "rotation"])?; - let num = |k: &str, range| input_number(&e, k, &format!("{name}.{k}"), range); - let (x, y) = (num("x", None)?.unwrap_or(0.0), num("y", None)?.unwrap_or(0.0)); - let pr = num("pressure", Some((0.0, 1.0)))?.unwrap_or(1.0) as f32; - let ev = match input_choice(&e, "kind", &format!("{name}.kind"), &["down", "move", "up"])?.unwrap_or("move") { - "down" => ToolEvent::Down { x, y, pressure: pr }, - "up" => ToolEvent::Up { x, y }, - _ => ToolEvent::Move { x, y, pressure: pr }, - }; - let tilt = |k: &str, range| num(k, Some(range)).map(|v| v.map(|v| v as f32)); - let pen = (tilt("tiltX", (-90.0, 90.0))?, tilt("tiltY", (-90.0, 90.0))?, tilt("rotation", (0.0, 360.0))?); - parsed.push((ev, x, y, pr, pen)); - } - Ok((tool, button, m, parsed)) - })(); - let (tool, button, m, events) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - let secondary = matches!(button.as_str(), "secondary" | "right"); - let mods = modifiers_from(&m); - if let Some(t) = tool { - crate::tool_memory::select(app, t); - } - // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape - // being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be - // top-level or grouped under "modifiers". - let space = p.get("modifiers").unwrap_or(p).get("space").and_then(Value::as_bool).unwrap_or(false); - crate::crop_ui::set_space(app, space); - for (ev, x, y, pr, pen) in events { - // With the Color Picker on top the image is its eyedropper, as for the mouse. - if crate::color_picker_ui::top(app).is_some() { - if !matches!(ev, ToolEvent::Up { .. }) { - crate::color_picker_ui::sample_at(app, x, y); - } - continue; - } - // Curves' modal eyedroppers use document coordinates here, matching the native - // canvas path after its ViewXform conversion. Sample on press only. - if !secondary && crate::adjust_dialog::picker_armed(app) { - if matches!(ev, ToolEvent::Down { .. }) { - crate::adjust_dialog::sample_at(app, x, y); - } - continue; - } - // ⌘/Ctrl-click with Curves open adds a point at the pixel's tone, on press only (#7325). - if !secondary && !space && button != "middle" && mods.command && crate::adjust_dialog::curves_on_top(app) { - if matches!(ev, ToolEvent::Down { .. }) { - crate::adjust_dialog::add_point_at(app, ctx, x, y, mods.shift); - } - continue; - } - // A Properties Levels/Curves eyedropper owns the primary button the same way. - if app.ui.dialogs.is_empty() && !matches!(s("button"), Some("secondary" | "right")) && crate::layer_picker::armed(app).is_some() { - if matches!(ev, ToolEvent::Down { .. }) { - crate::layer_picker::sample_at(app, x, y); - } - continue; - } - // The dialog owns all pointer events, including Up: no underlying brush stroke - // or context menu may leak through while inspecting a Color Range preview. - if app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields)) { - let down = matches!(ev, ToolEvent::Down { .. }); - let up = matches!(ev, ToolEvent::Up { .. }); - let held = app.ui.dialogs.last().and_then(|d| d.fields.get("__pointerDown")).and_then(Value::as_bool).unwrap_or(false); - if let Some(d) = app.ui.dialogs.last_mut() { - d.fields.insert("__pointerDown".into(), json!(!up && (down || held))); - } - if !up && (down || held) && !space && !secondary && button != "middle" { - crate::color_range_ui::pick_top(app, [x, y], mods); - } - continue; - } - if secondary { - let down = matches!(ev, ToolEvent::Down { .. }); - // Right-click while transforming: the box's menu, as on the canvas. - if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()) { - if down { - crate::canvas_tool_menu::open_transform(app, ctx, screen_point(app, x, y)); - } - continue; - } - // Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there. - if crate::layer_pick_ui::is_gesture(app.ui.tool, mods) { - if down { - app.ui.canvas_tool_menu = None; - crate::layer_pick_ui::open(app, ctx, screen_point(app, x, y), x, y); - } - continue; - } - // No menu over the agent's own crop frame or Straighten line still being - // dragged, also the first one on the default frame (nothing pending yet). - if app.ui.tool == crate::state::Tool::Crop && (app.crop.drag.is_some() || app.crop.straighten.line.is_some()) { - continue; - } - if app.ui.tool == crate::state::Tool::Crop && crate::crop_ui::pending(app) { - if down { - crate::canvas_tool_menu::open_crop(app, ctx, app.ui.tool, screen_point(app, x, y)); - } - continue; - } - if crate::canvas_tool_menu::pasteboard_at(app, app.ui.tool, [x, y]) { - if down { - crate::canvas_tool_menu::open_pasteboard(app, ctx, app.ui.tool, screen_point(app, x, y)); - } - continue; - } - if crate::canvas_tool_menu::is_view_tool(app.ui.tool) { - if down { - crate::canvas_tool_menu::open_view(app, ctx, app.ui.tool, screen_point(app, x, y), [x, y]); - } - continue; - } - if crate::canvas_tool_menu::applies(app.ui.tool) - || crate::canvas_tool_menu::editing_text(app, app.ui.tool) - || crate::canvas_tool_menu::type_layer_at(app, app.ui.tool, [x, y]).is_some() - { - if down { - crate::canvas_tool_menu::open_at(app, ctx, app.ui.tool, screen_point(app, x, y), Some([x, y])); - } - continue; - } - if !crate::paint_mouse::pointer_secondary(app, ctx, down, mods, screen_point(app, x, y)) { - continue; - } - } - // A simulated pen: tilt/rotation reach the stroke like a real stylus's (see `stylus`). - if pen != (None, None, None) { - let (tilt_x, tilt_y, rotation) = (pen.0.unwrap_or(0.0), pen.1.unwrap_or(0.0), pen.2.unwrap_or(0.0)); - app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: pr, tilt_x, tilt_y, rotation, eraser: false })); - } - if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { - d.reposition = space; - } - // A Crop drag in the default mode turns and pans the view with the image: its - // points are read as the view showed them at the press (`crop_mode`). - let ev = match ev { - ToolEvent::Move { x, y, pressure } => { - let [x, y] = crate::crop_mode::control_point(app, [x, y]); - ToolEvent::Move { x, y, pressure } - } - ToolEvent::Up { x, y } => { - let [x, y] = crate::crop_mode::control_point(app, [x, y]); - ToolEvent::Up { x, y } - } - down => down, - }; - tool_event(app, ev, mods); - } - app.stylus.feed.set(None); - ok(json!({"status": app.ui.status})) + other => err(format!("unknown dialog kind `{other}`")), + } +} + +fn color_picker_dialog(app: &mut PhotocraftApp, p: &Value) -> Outcome { + if let Some(style) = p.get("textStyle") { + return text_style_color_picker(app, p, style); + } + if p.get("parent").is_some() { + let (Some(parent), Some(effect), Some(field)) = (u64_param(p, "parent"), str_param(p, "effect"), str_param(p, "field")) else { + return err("need integer `parent` and string `effect` and `field`"); + }; + return match crate::layer_style::color_picker::open(app, parent, effect, field) { + Ok(id) => ok(json!({"dialog": id})), + Err(error) => err(error), + }; + } + if p.get("effect").is_some() || p.get("field").is_some() { + return err("Layer Style color pickers need `parent`"); + } + let target = if str_param(p, "target") == Some("background") { "background" } else { "foreground" }; + ok(json!({"dialog": crate::color_picker_ui::open(app, target)})) +} + +fn text_style_color_picker(app: &mut PhotocraftApp, p: &Value, style: &Value) -> Outcome { + if ["parent", "effect", "field", "target"].iter().any(|key| p.get(*key).is_some()) { + return err("textStyle cannot be combined with another picker target"); + } + let Some(style) = style.as_object().filter(|s| s.keys().all(|k| k == "kind" || k == "id")) else { + return err("textStyle needs kind and id only"); + }; + let Some(kind) = style.get("kind").cloned().and_then(|v| serde_json::from_value::(v).ok()) else { + return err("textStyle kind must be character or paragraph"); + }; + let Some(id) = style.get("id").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()) else { + return err("textStyle id must be a u32 integer"); + }; + match crate::type_panels_ui::color_picker::open(app, kind, id) { + Ok(id) => ok(json!({"dialog": id})), + Err(error) => err(error), + } +} + +fn shell_dialog_set(app: &mut PhotocraftApp, p: &Value) -> Outcome { + let Some(field) = str_param(p, "field") else { return err("need `dialog` and `field`") }; + let value = p.get("value").cloned().unwrap_or(Value::Null); + match app.ui.shell.dialog.as_mut() { + Some((_, fields)) => { + fields.insert(field.to_string(), value); + ok(Value::Null) } - "ui.click" | "ui.move" => { - let click = req.method == "ui.click"; - let fields: &[&str] = if click { &["x", "y", "button", "count"] } else { &["x", "y"] }; - let parsed = (|| -> std::result::Result<_, String> { - let p = input_object(p, None, fields)?; - // Screen coordinates in points (as reported by ui.inspect window size). - let x = input_number(&p, "x", "x", None)?.unwrap_or(0.0) as f32; - let y = input_number(&p, "y", "y", None)?.unwrap_or(0.0) as f32; - let button = match input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left") { - "right" | "secondary" => egui::PointerButton::Secondary, - "middle" => egui::PointerButton::Middle, - _ => egui::PointerButton::Primary, - }; - let clicks = if click { uint_field(&p, "count")?.unwrap_or(1) } else { 0 }; - if clicks > MAX_CLICKS { - return Err(format!("`count` must be at most {MAX_CLICKS} (got {clicks})")); - } - Ok((egui::pos2(x, y), button, clicks)) - })(); - let (pos, button, clicks) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - app.synthetic.push(egui::Event::PointerMoved(pos)); - for _ in 0..clicks { - app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: Default::default() }); - app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: Default::default() }); - } - ctx.request_repaint(); - Outcome::AfterInput + None => err("no shell dialog is open"), + } +} + +fn shell_dialog_confirm(app: &mut PhotocraftApp, ctx: &egui::Context) -> Outcome { + let Some((kind, fields)) = app.ui.shell.dialog.clone() else { return err("no shell dialog is open") }; + if let Some((command, params)) = crate::workspace_ui::dialog_command(&kind, &fields) + && let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(command, ¶ms) + { + return err(error); + } + wrap(crate::workspace_ui::confirm(app, ctx)) +} + +fn discard_dialog_confirm(app: &mut PhotocraftApp, ctx: &egui::Context, choice: &str) -> Outcome { + if choice != "cancel" + && let Some((command, params)) = crate::discard_ui::pending_command(app) + && let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(&command, ¶ms) + { + return err(error); + } + wrap(crate::discard_ui::answer_control(app, ctx, choice)) +} + +fn dialog_set(app: &mut PhotocraftApp, p: &Value) -> Outcome { + let (Some(id), Some(field)) = (u64_param(p, "dialog"), str_param(p, "field")) else { return err("need `dialog` and `field`") }; + let value = p.get("value").cloned().unwrap_or(Value::Null); + match app.ui.dialog_mut(id) { + // A continuation belongs to the dialog that paused it, even when another + // action has a valid token. Replacing it would resume or cancel that action. + Some(_) if field == crate::actions::RESUME => err("the paused action token is read-only"), + // A marker picks the handler OK runs: a dialog keeps the ones it was opened with. + Some(d) if !d.fields.contains_key(field) && crate::dialogs::is_route_marker(field) => err(format!("`{field}` is set only by the dialog it belongs to")), + Some(d) => { + d.fields.insert(field.to_string(), value); + ok(Value::Null) } - "ui.key" => { - let parsed = (|| -> std::result::Result<_, String> { - let p = input_object(p, None, &["key", "modifiers", "shift", "alt", "command", "ctrl"])?; - let Some(name) = input_choice(&p, "key", "key", &[])? else { return Err("missing `key`".into()) }; - let key = egui::Key::from_name(name).ok_or_else(|| format!("unknown key `{name}`"))?; - // Modifier flags may be top-level or grouped under "modifiers". - Ok((key, input_modifiers(&p, &KEY_MODIFIERS)?)) - })(); - let (key, m) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - let modifiers = modifiers_from(&m); - app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); - app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }); - ctx.request_repaint(); - Outcome::AfterInput + None => err(format!("no dialog {id}")), + } +} + +fn dialog_confirm_or_apply(app: &mut PhotocraftApp, req: &ControlRequest, id: u64) -> Outcome { + let apply = req.method == "ui.dialog.apply"; + let command = app.ui.dialogs.iter().find(|dialog| dialog.id == id).and_then(|dialog| { + if apply { + dialog.fields.get("values").map(|values| ("prefs.set".to_string(), json!({"path": "", "value": values}))) + } else { + dialog.fields.get("__command").and_then(Value::as_str).map(|command| (command.to_string(), Value::Object(dialog.fields.clone()))) } + }); + if let Some((command, params)) = command + && let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(&command, ¶ms) + { + return err(error); + } + run_waiting(app, wait_param(&req.params), |app| if apply { crate::prefs_ui::apply(app, id) } else { crate::dialogs::confirm(app, id) }) +} + +// ---- synthetic input: pointer events, clicks, keys, text ---- + +fn input_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Option { + let p = &req.params; + Some(match req.method.as_str() { + "ui.pointer" => pointer(app, ctx, p), + "ui.click" | "ui.move" => click(app, ctx, p, req.method == "ui.click"), + "ui.key" => key(app, ctx, p), "ui.type" => { - let Some(text) = s("text") else { return err("missing `text`") }; + let Some(text) = str_param(p, "text") else { return Some(err("missing `text`")) }; app.synthetic.push(egui::Event::Text(text.to_string())); ctx.request_repaint(); Outcome::AfterInput } - "ui.resize" => { - let (w, h) = (p.get("width").and_then(Value::as_f64).unwrap_or(1280.0), p.get("height").and_then(Value::as_f64).unwrap_or(800.0)); - ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w as f32, h as f32))); - ok(Value::Null) + _ => return None, + }) +} + +fn click(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value, click: bool) -> Outcome { + let fields: &[&str] = if click { &["x", "y", "button", "count"] } else { &["x", "y"] }; + let parsed = (|| -> std::result::Result<_, String> { + let p = input_object(p, None, fields)?; + // Screen coordinates in points (as reported by ui.inspect window size). + let x = input_number(&p, "x", "x", None)?.unwrap_or(0.0) as f32; + let y = input_number(&p, "y", "y", None)?.unwrap_or(0.0) as f32; + let button = match input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left") { + "right" | "secondary" => egui::PointerButton::Secondary, + "middle" => egui::PointerButton::Middle, + _ => egui::PointerButton::Primary, + }; + let clicks = if click { uint_field(&p, "count")?.unwrap_or(1) } else { 0 }; + if clicks > MAX_CLICKS { + return Err(format!("`count` must be at most {MAX_CLICKS} (got {clicks})")); } - "ui.gpu.simulateLoss" => { - if p.get("destroy").and_then(Value::as_bool).unwrap_or(false) { - let destroyed = app.destroy_window_device(); - ctx.request_repaint(); - return ok(json!({"destroyed": destroyed})); - } - let error = p.get("error").and_then(Value::as_bool).unwrap_or(false); - let fault = if error { - photocraft_gpu::Fault::Error("simulated error (ui.gpu.simulateLoss)".into()) - } else { - photocraft_gpu::Fault::Lost("simulated (ui.gpu.simulateLoss)".into()) - }; - let active = match app.gpu_health() { - Some(h) => { - h.mark(fault); - true - } - None => false, - }; - app.check_gpu(ctx); - ctx.request_repaint(); - ok(json!({"wasActive": active, "gpuInfo": app.perf.gpu_info})) + Ok((egui::pos2(x, y), button, clicks)) + })(); + let (pos, button, clicks) = match parsed { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + app.synthetic.push(egui::Event::PointerMoved(pos)); + for _ in 0..clicks { + app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: Default::default() }); + app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: Default::default() }); + } + ctx.request_repaint(); + Outcome::AfterInput +} + +fn key(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { + let parsed = (|| -> std::result::Result<_, String> { + let p = input_object(p, None, &["key", "modifiers", "shift", "alt", "command", "ctrl"])?; + let Some(name) = input_choice(&p, "key", "key", &[])? else { return Err("missing `key`".into()) }; + let key = egui::Key::from_name(name).ok_or_else(|| format!("unknown key `{name}`"))?; + // Modifier flags may be top-level or grouped under "modifiers". + Ok((key, input_modifiers(&p, &KEY_MODIFIERS)?)) + })(); + let (key, m) = match parsed { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + let modifiers = modifiers_from(&m); + app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }); + ctx.request_repaint(); + Outcome::AfterInput +} + +/// Simulated pen tilt/rotation of one `ui.pointer` event. +type Pen = (Option, Option, Option); + +/// One validated `ui.pointer` event. +struct PointerSample { + ev: ToolEvent, + x: f64, + y: f64, + pressure: f32, + pen: Pen, +} + +struct ParsedPointer { + tool: Option, + button: String, + modifiers: Value, + events: Vec, +} + +/// The gesture shared by every event of one `ui.pointer` call. +struct PointerGesture { + secondary: bool, + middle: bool, + space: bool, + mods: egui::Modifiers, +} + +fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { + // Every field and event is validated before the first event runs, so a rejected call + // changes nothing (#2449). + let parsed = match parse_pointer(p) { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + if let Some(t) = parsed.tool { + crate::tool_memory::select(app, t); + } + // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape + // being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be + // top-level or grouped under "modifiers". + let space = p.get("modifiers").unwrap_or(p).get("space").and_then(Value::as_bool).unwrap_or(false); + crate::crop_ui::set_space(app, space); + let gesture = PointerGesture { + secondary: matches!(parsed.button.as_str(), "secondary" | "right"), + middle: parsed.button == "middle", + space, + mods: modifiers_from(&parsed.modifiers), + }; + for sample in parsed.events { + if !pointer_event_intercepted(app, ctx, &gesture, &sample) { + forward_pointer_event(app, &gesture, sample); } - "ui.focus" => { - ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); - ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - ctx.request_repaint(); - ok(Value::Null) + } + app.stylus.feed.set(None); + ok(json!({"status": app.ui.status})) +} + +fn parse_pointer(p: &Value) -> std::result::Result { + let fields = ["events", "tool", "modifiers", "button", "shift", "alt", "command", "ctrl", "space"]; + let p = input_object(p, None, &fields)?; + let tool = match input_choice(&p, "tool", "tool", &[])? { + Some(t) => Some(Tool::from_name(t).ok_or_else(|| format!("unknown tool `{t}`"))?), + None => None, + }; + let button = input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left").to_string(); + // Modifier flags may be top-level or grouped under "modifiers". + let modifiers = input_modifiers(&p, &POINTER_MODIFIERS)?; + let Some(events) = p.get("events") else { return Err("missing `events`".into()) }; + let Some(events) = events.as_array() else { return Err("events must be an array".into()) }; + let events = events.iter().enumerate().map(|(i, e)| parse_pointer_event(i, e)).collect::, _>>()?; + Ok(ParsedPointer { tool, button, modifiers, events }) +} + +fn parse_pointer_event(i: usize, e: &Value) -> std::result::Result { + let name = format!("events[{i}]"); + let e = input_object(e, Some(&name), &["kind", "x", "y", "pressure", "tiltX", "tiltY", "rotation"])?; + let num = |k: &str, range| input_number(&e, k, &format!("{name}.{k}"), range); + let (x, y) = (num("x", None)?.unwrap_or(0.0), num("y", None)?.unwrap_or(0.0)); + let pressure = num("pressure", Some((0.0, 1.0)))?.unwrap_or(1.0) as f32; + let ev = match input_choice(&e, "kind", &format!("{name}.kind"), &["down", "move", "up"])?.unwrap_or("move") { + "down" => ToolEvent::Down { x, y, pressure }, + "up" => ToolEvent::Up { x, y }, + _ => ToolEvent::Move { x, y, pressure }, + }; + let tilt = |k: &str, range| num(k, Some(range)).map(|v| v.map(|v| v as f32)); + let pen = (tilt("tiltX", (-90.0, 90.0))?, tilt("tiltY", (-90.0, 90.0))?, tilt("rotation", (0.0, 360.0))?); + Ok(PointerSample { ev, x, y, pressure, pen }) +} + +/// Whether a modal tool, picker or context menu took the event instead of the canvas. +fn pointer_event_intercepted(app: &mut PhotocraftApp, ctx: &egui::Context, g: &PointerGesture, s: &PointerSample) -> bool { + pointer_eyedropper_took(app, ctx, g, s) || color_range_took(app, g, s) || (g.secondary && secondary_menu_took(app, ctx, g, s)) +} + +fn pointer_eyedropper_took(app: &mut PhotocraftApp, ctx: &egui::Context, g: &PointerGesture, s: &PointerSample) -> bool { + let (x, y) = (s.x, s.y); + let down = matches!(s.ev, ToolEvent::Down { .. }); + // With the Color Picker on top the image is its eyedropper, as for the mouse. + if crate::color_picker_ui::top(app).is_some() { + if !matches!(s.ev, ToolEvent::Up { .. }) { + crate::color_picker_ui::sample_at(app, x, y); } - "ui.screenshot" => { - let parsed = input_object(p, None, &["path", "focus"]) - .and_then(|p| Ok((input_choice(&p, "path", "path", &[])?.map(str::to_string), bool_field(&p, "focus")?))); - let (path, focus) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - // Occluded windows don't render on macOS, so the screenshot would never arrive: raise first. - if focus.unwrap_or(true) { - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - } - // The capture itself is admitted by `PhotocraftApp::drain_control` (budget and - // geometry) and issued from a later `App::ui` pass once open/close animations - // (modals, popups) have settled (see `screenshot.rs`). - let token = app.ui.alloc_id(); - ctx.request_repaint(); - Outcome::Screenshot { token, path } + return true; + } + // Curves' modal eyedroppers use document coordinates here, matching the native + // canvas path after its ViewXform conversion. Sample on press only. + if !g.secondary && crate::adjust_dialog::picker_armed(app) { + if down { + crate::adjust_dialog::sample_at(app, x, y); } - "app.open" => match s("path") { - Some(path) => { - // Directory .pcraft (the native on-disk form) loads through a capability-scoped - // source; the single-file (zip) form falls back to the bytes path, as do all - // other formats. - if path.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case(photocraft_format::EXTENSION)) - && let Some(open) = app.services.automation_open_pcraft.as_mut() - { - match open(path) { - Ok(Some((name, doc))) => { - app.session.add_document(doc, None); - // Recent files, but no save-back target: the capability writer - // replaces files, never directories. - app.push_recent(path); - app.sync_views(); - app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &name)]); - app.ui.status_error = false; - return ok(json!({"path": path, "name": name, "warnings": []})); - } - Ok(None) => {} // a regular file: the bytes path reads the zip form - Err(e) => return err(e), - } - } - let opened = match app.services.automation_read.as_mut() { - Some(read) => read(path), - None => Err("automation read authority is not configured".into()), - }; - wrap(opened.and_then(|(name, bytes)| { - let name = app.open_name(&name); - let warnings = app.open_automation_bytes(&name, &bytes)?; - // Brushes/gradients go to the preset libraries: no document, no Open Recent entry. - if !crate::preset_files_ui::is_preset_file(&name) { - app.opened_from(path); - } - Ok(json!({"path": path, "name": name, "warnings": warnings})) - })) - } + return true; + } + // ⌘/Ctrl-click with Curves open adds a point at the pixel's tone, on press only (#7325). + if !g.secondary && !g.space && !g.middle && g.mods.command && crate::adjust_dialog::curves_on_top(app) { + if down { + crate::adjust_dialog::add_point_at(app, ctx, x, y, g.mods.shift); + } + return true; + } + // A Properties Levels/Curves eyedropper owns the primary button the same way. + if app.ui.dialogs.is_empty() && !g.secondary && crate::layer_picker::armed(app).is_some() { + if down { + crate::layer_picker::sample_at(app, x, y); + } + return true; + } + false +} + +/// The dialog owns all pointer events, including Up: no underlying brush stroke +/// or context menu may leak through while inspecting a Color Range preview. +fn color_range_took(app: &mut PhotocraftApp, g: &PointerGesture, s: &PointerSample) -> bool { + if !app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields)) { + return false; + } + let down = matches!(s.ev, ToolEvent::Down { .. }); + let up = matches!(s.ev, ToolEvent::Up { .. }); + let held = app.ui.dialogs.last().and_then(|d| d.fields.get("__pointerDown")).and_then(Value::as_bool).unwrap_or(false); + if let Some(d) = app.ui.dialogs.last_mut() { + d.fields.insert("__pointerDown".into(), json!(!up && (down || held))); + } + if !up && (down || held) && !g.space && !g.secondary && !g.middle { + crate::color_range_ui::pick_top(app, [s.x, s.y], g.mods); + } + true +} + +/// Right-click: the transform box's menu, the layer list, or a canvas menu. Whether it opens +/// only on the press, the event is consumed either way. +fn secondary_menu_took(app: &mut PhotocraftApp, ctx: &egui::Context, g: &PointerGesture, s: &PointerSample) -> bool { + secondary_transform_or_crop_took(app, ctx, g, s) || secondary_canvas_menu_took(app, ctx, g, s) +} + +fn secondary_transform_or_crop_took(app: &mut PhotocraftApp, ctx: &egui::Context, g: &PointerGesture, s: &PointerSample) -> bool { + let (x, y) = (s.x, s.y); + let down = matches!(s.ev, ToolEvent::Down { .. }); + // Right-click while transforming: the box's menu, as on the canvas. + if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()) { + if down { + crate::canvas_tool_menu::open_transform(app, ctx, screen_point(app, x, y)); + } + return true; + } + // Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there. + if crate::layer_pick_ui::is_gesture(app.ui.tool, g.mods) { + if down { + app.ui.canvas_tool_menu = None; + crate::layer_pick_ui::open(app, ctx, screen_point(app, x, y), x, y); + } + return true; + } + if app.ui.tool != crate::state::Tool::Crop { + return false; + } + // No menu over the agent's own crop frame or Straighten line still being + // dragged, also the first one on the default frame (nothing pending yet). + if app.crop.drag.is_some() || app.crop.straighten.line.is_some() { + return true; + } + if crate::crop_ui::pending(app) { + if down { + crate::canvas_tool_menu::open_crop(app, ctx, app.ui.tool, screen_point(app, x, y)); + } + return true; + } + false +} + +fn secondary_canvas_menu_took(app: &mut PhotocraftApp, ctx: &egui::Context, g: &PointerGesture, s: &PointerSample) -> bool { + let (x, y) = (s.x, s.y); + let down = matches!(s.ev, ToolEvent::Down { .. }); + if crate::canvas_tool_menu::pasteboard_at(app, app.ui.tool, [x, y]) { + if down { + crate::canvas_tool_menu::open_pasteboard(app, ctx, app.ui.tool, screen_point(app, x, y)); + } + return true; + } + if crate::canvas_tool_menu::is_view_tool(app.ui.tool) { + if down { + crate::canvas_tool_menu::open_view(app, ctx, app.ui.tool, screen_point(app, x, y), [x, y]); + } + return true; + } + if crate::canvas_tool_menu::applies(app.ui.tool) + || crate::canvas_tool_menu::editing_text(app, app.ui.tool) + || crate::canvas_tool_menu::type_layer_at(app, app.ui.tool, [x, y]).is_some() + { + if down { + crate::canvas_tool_menu::open_at(app, ctx, app.ui.tool, screen_point(app, x, y), Some([x, y])); + } + return true; + } + !crate::paint_mouse::pointer_secondary(app, ctx, down, g.mods, screen_point(app, x, y)) +} + +/// Hand an event nothing intercepted to the active tool. +fn forward_pointer_event(app: &mut PhotocraftApp, g: &PointerGesture, s: PointerSample) { + // A simulated pen: tilt/rotation reach the stroke like a real stylus's (see `stylus`). + if s.pen != (None, None, None) { + let (tilt_x, tilt_y, rotation) = (s.pen.0.unwrap_or(0.0), s.pen.1.unwrap_or(0.0), s.pen.2.unwrap_or(0.0)); + app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: s.pressure, tilt_x, tilt_y, rotation, eraser: false })); + } + if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { + d.reposition = g.space; + } + // A Crop drag in the default mode turns and pans the view with the image: its + // points are read as the view showed them at the press (`crop_mode`). + let ev = match s.ev { + ToolEvent::Move { x, y, pressure } => { + let [x, y] = crate::crop_mode::control_point(app, [x, y]); + ToolEvent::Move { x, y, pressure } + } + ToolEvent::Up { x, y } => { + let [x, y] = crate::crop_mode::control_point(app, [x, y]); + ToolEvent::Up { x, y } + } + down => down, + }; + tool_event(app, ev, g.mods); +} + +// ---- the application: open, save, quit ---- + +fn app_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Option { + let p = &req.params; + Some(match req.method.as_str() { + "app.open" => match str_param(p, "path") { + Some(path) => app_open(app, path), None => err("missing `path`"), }, "app.save" => match crate::FormatChoices::from_params(p, "app.save") { Ok(choices) => { - let path = s("path").map(str::to_string); - run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, choices)) + let path = str_param(p, "path").map(str::to_string); + run_waiting(app, wait_param(p), move |app| app.save_automation_with(path, choices)) } Err(e) => err(e), }, @@ -1000,6 +1323,49 @@ pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Contr ctx.send_viewport_cmd(egui::ViewportCommand::Close); ok(Value::Null) } - other => err(format!("unknown method `{other}`")), + _ => return None, + }) +} + +fn app_open(app: &mut PhotocraftApp, path: &str) -> Outcome { + if let Some(outcome) = open_pcraft_directory(app, path) { + return outcome; + } + let opened = match app.services.automation_read.as_mut() { + Some(read) => read(path), + None => Err("automation read authority is not configured".into()), + }; + wrap(opened.and_then(|(name, bytes)| { + let name = app.open_name(&name); + let warnings = app.open_automation_bytes(&name, &bytes)?; + // Brushes/gradients go to the preset libraries: no document, no Open Recent entry. + if !crate::preset_files_ui::is_preset_file(&name) { + app.opened_from(path); + } + Ok(json!({"path": path, "name": name, "warnings": warnings})) + })) +} + +/// Directory .pcraft (the native on-disk form) loads through a capability-scoped +/// source; the single-file (zip) form falls back to the bytes path, as do all +/// other formats. `None` means "not a directory .pcraft". +fn open_pcraft_directory(app: &mut PhotocraftApp, path: &str) -> Option { + if !path.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case(photocraft_format::EXTENSION)) { + return None; + } + let open = app.services.automation_open_pcraft.as_mut()?; + match open(path) { + Ok(Some((name, doc))) => { + app.session.add_document(doc, None); + // Recent files, but no save-back target: the capability writer + // replaces files, never directories. + app.push_recent(path); + app.sync_views(); + app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &name)]); + app.ui.status_error = false; + Some(ok(json!({"path": path, "name": name, "warnings": []}))) + } + Ok(None) => None, // a regular file: the bytes path reads the zip form + Err(e) => Some(err(e)), } } From de9636f56eff9e185060ce85fadfb974c4ca47be Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:06:42 +0000 Subject: [PATCH 26/35] Refactor ui-egui dialogs for strict Clippy checks --- crates/ui-egui/src/dialogs.rs | 686 ++++++++++++---------- crates/ui-egui/src/dialogs/caf_ui/view.rs | 285 ++++----- 2 files changed, 533 insertions(+), 438 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ef22e21c76..a14b42c37f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -267,6 +267,263 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { crate::icons::button(&mut child, "x", CLOSE_BOX_SIZE, false, tl!("Close")).clicked() } +/// The dialog's contents under the title rule, picked by its kind and the marker field that routes +/// it. Returns `Some(true)` / `Some(false)` when the body itself answered OK / Cancel. +/// The body of a command dialog: the first handler whose marker the fields carry. The prompts and +/// small editors come first; the rest are in `command_body_more`. +fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id, interactive: bool) -> Option { + let mut outcome: Option = None; + match d.kind { + _ if crate::open_prompt::owns_damage(fields) => crate::open_prompt::damage_body(ui, fields), + _ if crate::guide_layout_ui::owns(fields) => outcome = crate::guide_layout_ui::body(app, ui, fields, interactive), + _ if crate::brush_preset_dialog::owns(fields) => outcome = crate::brush_preset_dialog::body(app, ui, fields, interactive), + _ if crate::fill_ui::owns(fields) => crate::fill_ui::body(app, ui, fields), + _ if crate::pattern_fill_ui::owns(fields) => crate::pattern_fill_ui::body(app, ui, fields), + _ if crate::stroke_ui::owns(fields) => crate::stroke_ui::body(ui, fields), + _ if crate::new_group_ui::owns(fields) => crate::new_group_ui::body(ui, fields), + _ if crate::snapshot_dialog::owns(fields) => crate::snapshot_dialog::body(ui, fields), + _ if crate::channel_options_ui::owns(fields) => crate::channel_options_ui::body(ui, fields), + _ if crate::channel_options_ui::owns_new_spot(fields) => crate::channel_options_ui::new_spot_body(ui, fields), + _ if crate::shape_dialog::owns(fields) => crate::shape_dialog::body(app, ui, fields), + _ if crate::delete_layer_prompt::owns(fields) => crate::delete_layer_prompt::body(ui, fields), + _ if crate::disk_change_prompt::owns(fields) => crate::disk_change_prompt::body(ui, fields), + _ if crate::replace_prompt::owns(fields) => crate::replace_prompt::body(ui, fields), + _ if crate::actions::owns_insert_stop(fields) => crate::actions::insert_stop_body(ui, fields), + _ if crate::new_layer_ui::owns(fields) => crate::new_layer_ui::body(ui, fields), + _ if crate::mask_trash_prompt::owns(fields) => crate::mask_trash_prompt::body(ui, fields), + _ if crate::rasterize_prompt::owns(fields) => crate::rasterize_prompt::body(ui, fields), + _ if crate::duplicate_layer_ui::owns(fields) => crate::duplicate_layer_ui::body(app, ui, fields), + _ if crate::stack_dialog::owns(fields) => crate::stack_dialog::body(app, ui, fields, d.id), + _ if crate::tool_reset::owns(fields) => crate::tool_reset::body(ui), + _ if crate::crop_presets::owns(fields) => crate::crop_presets::body(app, ui, fields), + _ if crate::variables_ui::owns(fields) => crate::variables_ui::body(app, ui, fields), + _ => return command_body_more(app, ui, d, fields, id), + } + outcome +} + +/// The rest of the command dialogs: files, colour, export, sizing, filters and forms. +fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id) -> Option { + let mut outcome: Option = None; + match d.kind { + _ if crate::file_ui::owns(fields) => crate::file_ui::body(app, ui, fields, d.id), + _ if crate::color_picker_ui::owns(fields) => { + outcome = crate::color_picker_ui::body(ui, fields); + crate::color_picker_ui::take_add_swatch(app, fields); + if let Some(web) = fields.get("__webOnly").and_then(Value::as_bool) { + app.ui.color_panel.web_only = web; + } + } + _ if crate::color_range_ui::owns(fields) => crate::color_range_ui::body(app, ui, fields), + _ if crate::prefs_ui::owns(fields) => crate::prefs_ui::body(app, ui, fields), + _ if fields.contains_key("__export") => crate::export_dialog::body(app, ui, fields), + // Image Size and Canvas Size open on Width, selected (#2329). + _ if fields.contains_key("__sizing") => first_field_focused(ui, id, |ui| crate::sizing::body(ui, fields)), + _ if crate::smart_filter_dialog::owns(fields) => crate::smart_filter_dialog::body(app, ui, fields), + _ if crate::adjust_dialog::owns(fields) => crate::adjust_dialog::body(app, ui, fields), + _ if crate::blur_pins::owns(fields) => crate::blur_pins::body(ui, fields), + _ if fields.contains_key("__filter") => filter_body(app, ui, d, fields, id), + _ if crate::new_guide_ui::owns(fields) => crate::new_guide_ui::body(ui, fields), + _ if fields.contains_key("__form") => crate::view_cmds::form_body(ui, fields), + _ => {} + } + outcome +} + +fn dialog_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id, interactive: bool) -> Option { + let mut outcome: Option = None; + match d.kind { + DialogKind::NewDocument => { + if crate::new_doc_ui::body(app, ui, fields) { + outcome = Some(true); + } + } + DialogKind::About if fields.get("systemInfo").and_then(Value::as_bool) == Some(true) => { + let lines = crate::gpu_status::system_info_ui(app); + for l in &lines { + ui.add(egui::Label::new(egui::RichText::new(l).font(crate::theme::mono(12.0))).selectable(true)); + } + ui.add_space(8.0); + if crate::widgets::secondary_button(ui, tl!("Copy"), 84.0).clicked() { + ui.ctx().copy_text(crate::gpu_status::system_info(app).join("\n")); + } + } + DialogKind::About => { + // Tabs About · Contributors · Models (craftrules standards/contributors.md). The + // tab is a dialog field, so automation can switch it with `ui.dialog.set`. + let tab = about_tab(fields); + let mut chosen = tab; + ui.horizontal(|ui| { + for (key, label) in [("about", tl!("About")), ("contributors", tl!("Contributors")), ("models", tl!("Models"))] { + if crate::widgets::pill_tab(ui, label, tab == key).clicked() { + chosen = key; + } + } + }); + if chosen != tab { + fields.insert("tab".into(), json!(chosen)); + } + ui.add_space(8.0); + about_tab_body(app, ui, chosen); + } + DialogKind::Command => outcome = command_body(app, ui, d, fields, id, interactive), + DialogKind::LayerStyle => crate::layer_style::body(app, ui, fields), + DialogKind::Error => { + ui.label(fields.get("message").and_then(Value::as_str).unwrap_or("Error")); + } + } + outcome +} + +/// A filter-style dialog: scrolling parameters with the in-dialog preview window under them. +fn filter_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id) { + // Color Settings: the monitor profile in use can change while it is open. + if fields.get("__command").and_then(Value::as_str) == Some("edit.colorSettings") { + fields.insert("__note".into(), Value::String(crate::monitor_status::note(app))); + } + // Long parameter lists (Flame, Lighting Effects) scroll, so the title and the + // OK / Cancel buttons stay inside a small window. The preview window below the + // parameters reserves its own space (#3769). + let room = (ui.ctx().content_rect().height() - DIALOG_CHROME - crate::filter_preview_ui::reserved_height(fields)).max(120.0); + let body = |ui: &mut egui::Ui, fields: &mut serde_json::Map| { + egui::ScrollArea::vertical().id_salt(id.with("body")).max_height(room).show(ui, |ui| { + if crate::bitmap_dialog::owns(fields) { + crate::bitmap_dialog::body(app, ui, fields); + } else { + crate::filter_dialog::body(ui, fields); + } + }); + // The in-dialog preview window sits under the scrolling parameters (#3769), + // so it never shifts them. + crate::filter_preview_ui::window(app, d.id, ui, fields); + }; + // Select and Mask leaves the keyboard to its view keys (F, X, O, V…). + if crate::select_mask_view::owns(fields) { + body(ui, fields); + } else { + first_field_focused(ui, id, |ui| body(ui, fields)); + } +} + +/// The OK / Cancel row (with Apply, Alternate or Reset where the dialog has them), drawn in the +/// right-to-left layout. Returns what the buttons (or Enter) answered and whether Apply was hit. +/// `popup_blocks_enter` is true when a web dialog has a popup open, which keeps Enter for the popup. +fn button_row( + app: &mut PhotocraftApp, + ui: &mut egui::Ui, + d: &Dialog, + fields: &mut Fields, + id: egui::Id, + interactive: bool, + popup_blocks_enter: bool, +) -> (Option, bool) { + let mut outcome: Option = None; + let mut apply_requested = false; + if matches!(d.kind, DialogKind::About | DialogKind::Error) { + // ↩ is OK too, as on every other dialog (#4872), from the frame after the + // alert appeared: the ↩ that raised it (committing a locked layer's Free + // Transform, say) must not close it again at once. + let seen = id.with("alert-seen"); + let shown_before = ui.ctx().data(|m| m.get_temp::(seen).unwrap_or(false)); + ui.ctx().data_mut(|m| m.insert_temp(seen, true)); + let enter = interactive && shown_before && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() || enter { + outcome = Some(false); + } + } else { + let ok_label = ok_label(d); + // Dialogs that need an input first (a preset name, a selection) grey OK out. + let can_ok = crate::crop_presets::can_confirm(app, fields) && crate::stack_dialog::can_confirm(fields); + let ok = DialogButton::new(ButtonRole::Default, ok_label, 84.0).enabled(can_ok); + // Photoshop: holding Alt turns Cancel into Reset (the dialog stays open). + // Dialogs opt in via `dialog_alt_reset::supported` (per marker). + let reset = ui.input(|i| i.modifiers.alt) && crate::dialog_alt_reset::supported(fields); + let cancel_label = if reset { + tl!("Reset") + } else if d.kind == DialogKind::NewDocument { + tl!("Close") + } else { + tl!("Cancel") + }; + let cancel = DialogButton::new(ButtonRole::Cancel, cancel_label, 84.0); + let clicked = if d.kind == DialogKind::Command && crate::prefs_ui::is_preferences(fields) { + let changed = crate::prefs_ui::preferences_changed(app, fields); + dialog_buttons(ui, &[ok, cancel, DialogButton::new(ButtonRole::Apply, tl!("Apply"), 84.0).enabled(changed)]) + } else if crate::mask_trash_prompt::owns(fields) && !crate::mask_trash_prompt::is_vector(fields) { + // Photoshop: Apply / Cancel / Delete. Delete answers with the choice set. + let apply = DialogButton::new(ButtonRole::Default, tl!("Apply"), 84.0).enabled(crate::mask_trash_prompt::can_apply(fields)); + let delete = DialogButton::new(ButtonRole::Alternate, tl!("Delete"), 84.0); + let hit = dialog_buttons(ui, &[apply, cancel, delete]); + if hit == Some(ButtonRole::Alternate) { + fields.insert("choice".into(), json!("delete")); + } else if hit == Some(ButtonRole::Default) { + fields.insert("choice".into(), json!("apply")); + } + hit + } else if crate::rasterize_prompt::is_filter(fields) { + // Photoshop: Convert to Smart Object / Rasterize / Cancel (#4303). + let rasterize = DialogButton::new(ButtonRole::Default, tl!("Rasterize"), 84.0); + let hit = if crate::rasterize_prompt::offers_smart_object(fields) { + let convert = DialogButton::new(ButtonRole::Alternate, tl!("Convert to Smart Object"), 160.0); + dialog_buttons(ui, &[rasterize, cancel, convert]) + } else { + dialog_buttons(ui, &[rasterize, cancel]) + }; + if hit == Some(ButtonRole::Alternate) { + fields.insert("choice".into(), json!("smartObject")); + } else if hit == Some(ButtonRole::Default) { + fields.insert("choice".into(), json!("rasterize")); + } + hit + } else { + dialog_buttons(ui, &[ok, cancel]) + }; + match clicked { + Some(ButtonRole::Cancel) if reset => crate::dialog_alt_reset::apply(app, ui.ctx(), fields), + Some(ButtonRole::Cancel) => outcome = Some(false), + Some(ButtonRole::Apply) => apply_requested = true, + Some(_) => outcome = Some(true), + None if interactive && can_ok && !popup_blocks_enter && ui.input(|i| i.key_pressed(egui::Key::Enter)) => outcome = Some(true), + None => {} + } + } + (outcome, apply_requested) +} + +/// The default button's label: what OK means for this dialog. +fn ok_label(d: &Dialog) -> &'static str { + if d.kind == DialogKind::NewDocument { + tl!("Create") + } else if crate::open_prompt::owns_damage(&d.fields) { + tl!("Continue") + } else if crate::delete_layer_prompt::owns(&d.fields) { + tl!("Delete") + } else if crate::disk_change_prompt::owns(&d.fields) || crate::replace_prompt::owns(&d.fields) { + tl!("Replace") + } else if d.fields.contains_key("__export") { + tl!("Export") + } else { + crate::file_ui::ok_label(&d.fields).unwrap_or(tl!("OK")) + } +} + +/// The widest a dialog grows when its body names no width of its own. +fn default_max_width(d: &Dialog, compact: bool, curves: bool, about_tabs: bool, available: f32) -> f32 { + if d.kind == DialogKind::NewDocument { + 800.0 + } else if about_tabs { + 700.0 + } else if d.kind == DialogKind::LayerStyle || d.fields.contains_key("__export") || crate::color_picker_ui::owns(&d.fields) { + 600.0 + } else if compact { + 260.0 + } else if curves { + available.max(300.0) + } else { + 440.0 + } +} + pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::layer_style::color_picker::prune(app); crate::type_panels_ui::color_picker::prune(app); @@ -353,19 +610,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if about_tabs { ui.set_min_width(700.0); } - ui.set_max_width(wide.unwrap_or(if d.kind == DialogKind::NewDocument { - 800.0 - } else if about_tabs { - 700.0 - } else if d.kind == DialogKind::LayerStyle || d.fields.contains_key("__export") || crate::color_picker_ui::owns(&d.fields) { - 600.0 - } else if compact { - 260.0 - } else if curves { - available.x.max(300.0) - } else { - 440.0 - })); + ui.set_max_width(wide.unwrap_or_else(|| default_max_width(&d, compact, curves, about_tabs, available.x))); if web { ui.set_max_width(available.x); ui.set_min_size(available); @@ -399,116 +644,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::widgets::hairline(ui); ui.add_space(8.0); crate::field_tab::begin(ui.ctx()); - match d.kind { - DialogKind::NewDocument => { - if crate::new_doc_ui::body(app, ui, &mut fields) { - outcome = Some(true); - } - } - DialogKind::About if fields.get("systemInfo").and_then(Value::as_bool) == Some(true) => { - let lines = crate::gpu_status::system_info_ui(app); - for l in &lines { - ui.add(egui::Label::new(egui::RichText::new(l).font(crate::theme::mono(12.0))).selectable(true)); - } - ui.add_space(8.0); - if crate::widgets::secondary_button(ui, tl!("Copy"), 84.0).clicked() { - ui.ctx().copy_text(crate::gpu_status::system_info(app).join("\n")); - } - } - DialogKind::About => { - // Tabs About · Contributors · Models (craftrules standards/contributors.md). The - // tab is a dialog field, so automation can switch it with `ui.dialog.set`. - let tab = about_tab(&fields); - let mut chosen = tab; - ui.horizontal(|ui| { - for (key, label) in [("about", tl!("About")), ("contributors", tl!("Contributors")), ("models", tl!("Models"))] { - if crate::widgets::pill_tab(ui, label, tab == key).clicked() { - chosen = key; - } - } - }); - if chosen != tab { - fields.insert("tab".into(), json!(chosen)); - } - ui.add_space(8.0); - about_tab_body(app, ui, chosen); - } - DialogKind::Command if crate::open_prompt::owns_damage(&fields) => crate::open_prompt::damage_body(ui, &fields), - DialogKind::Command if crate::guide_layout_ui::owns(&fields) => outcome = crate::guide_layout_ui::body(app, ui, &mut fields, interactive), - DialogKind::Command if crate::brush_preset_dialog::owns(&fields) => { - outcome = crate::brush_preset_dialog::body(app, ui, &mut fields, interactive) - } - DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields), - DialogKind::Command if crate::pattern_fill_ui::owns(&fields) => crate::pattern_fill_ui::body(app, ui, &mut fields), - DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields), - DialogKind::Command if crate::new_group_ui::owns(&fields) => crate::new_group_ui::body(ui, &mut fields), - DialogKind::Command if crate::snapshot_dialog::owns(&fields) => crate::snapshot_dialog::body(ui, &mut fields), - DialogKind::Command if crate::channel_options_ui::owns(&fields) => crate::channel_options_ui::body(ui, &mut fields), - DialogKind::Command if crate::channel_options_ui::owns_new_spot(&fields) => crate::channel_options_ui::new_spot_body(ui, &mut fields), - DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields), - DialogKind::Command if crate::delete_layer_prompt::owns(&fields) => crate::delete_layer_prompt::body(ui, &mut fields), - DialogKind::Command if crate::disk_change_prompt::owns(&fields) => crate::disk_change_prompt::body(ui, &fields), - DialogKind::Command if crate::replace_prompt::owns(&fields) => crate::replace_prompt::body(ui, &fields), - DialogKind::Command if crate::actions::owns_insert_stop(&fields) => crate::actions::insert_stop_body(ui, &mut fields), - DialogKind::Command if crate::new_layer_ui::owns(&fields) => crate::new_layer_ui::body(ui, &mut fields), - DialogKind::Command if crate::mask_trash_prompt::owns(&fields) => crate::mask_trash_prompt::body(ui, &fields), - DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields), - DialogKind::Command if crate::duplicate_layer_ui::owns(&fields) => crate::duplicate_layer_ui::body(app, ui, &mut fields), - DialogKind::Command if crate::stack_dialog::owns(&fields) => crate::stack_dialog::body(app, ui, &mut fields, d.id), - DialogKind::Command if crate::tool_reset::owns(&fields) => crate::tool_reset::body(ui), - DialogKind::Command if crate::crop_presets::owns(&fields) => crate::crop_presets::body(app, ui, &mut fields), - DialogKind::Command if crate::variables_ui::owns(&fields) => crate::variables_ui::body(app, ui, &mut fields), - DialogKind::Command if crate::file_ui::owns(&fields) => crate::file_ui::body(app, ui, &mut fields, d.id), - DialogKind::Command if crate::color_picker_ui::owns(&fields) => { - outcome = crate::color_picker_ui::body(ui, &mut fields); - crate::color_picker_ui::take_add_swatch(app, &mut fields); - if let Some(web) = fields.get("__webOnly").and_then(Value::as_bool) { - app.ui.color_panel.web_only = web; - } - } - DialogKind::Command if crate::color_range_ui::owns(&fields) => crate::color_range_ui::body(app, ui, &mut fields), - DialogKind::Command if crate::prefs_ui::owns(&fields) => crate::prefs_ui::body(app, ui, &mut fields), - DialogKind::Command if fields.contains_key("__export") => crate::export_dialog::body(app, ui, &mut fields), - // Image Size and Canvas Size open on Width, selected (#2329). - DialogKind::Command if fields.contains_key("__sizing") => first_field_focused(ui, id, |ui| crate::sizing::body(ui, &mut fields)), - DialogKind::Command if crate::smart_filter_dialog::owns(&fields) => crate::smart_filter_dialog::body(app, ui, &mut fields), - DialogKind::Command if crate::adjust_dialog::owns(&fields) => crate::adjust_dialog::body(app, ui, &mut fields), - DialogKind::Command if crate::blur_pins::owns(&fields) => crate::blur_pins::body(ui, &mut fields), - DialogKind::Command if fields.contains_key("__filter") => { - // Color Settings: the monitor profile in use can change while it is open. - if fields.get("__command").and_then(Value::as_str) == Some("edit.colorSettings") { - fields.insert("__note".into(), Value::String(crate::monitor_status::note(app))); - } - // Long parameter lists (Flame, Lighting Effects) scroll, so the title and the - // OK / Cancel buttons stay inside a small window. The preview window below the - // parameters reserves its own space (#3769). - let room = (ctx.content_rect().height() - DIALOG_CHROME - crate::filter_preview_ui::reserved_height(&fields)).max(120.0); - let body = |ui: &mut egui::Ui, fields: &mut serde_json::Map| { - egui::ScrollArea::vertical().id_salt(id.with("body")).max_height(room).show(ui, |ui| { - if crate::bitmap_dialog::owns(fields) { - crate::bitmap_dialog::body(app, ui, fields); - } else { - crate::filter_dialog::body(ui, fields); - } - }); - // The in-dialog preview window sits under the scrolling parameters (#3769), - // so it never shifts them. - crate::filter_preview_ui::window(app, d.id, ui, fields); - }; - // Select and Mask leaves the keyboard to its view keys (F, X, O, V…). - if crate::select_mask_view::owns(&fields) { - body(ui, &mut fields); - } else { - first_field_focused(ui, id, |ui| body(ui, &mut fields)); - } - } - DialogKind::Command if crate::new_guide_ui::owns(&fields) => crate::new_guide_ui::body(ui, &mut fields), - DialogKind::Command if fields.contains_key("__form") => crate::view_cmds::form_body(ui, &mut fields), - DialogKind::Command => {} - DialogKind::LayerStyle => crate::layer_style::body(app, ui, &mut fields), - DialogKind::Error => { - ui.label(fields.get("message").and_then(Value::as_str).unwrap_or("Error")); - } + if let Some(done) = dialog_body(app, ui, &d, &mut fields, id, interactive) { + outcome = Some(done); } crate::field_tab::end(ui.ctx(), tab); if let Some(Value::String(key)) = fields.remove(BROWSE_FIELD) { @@ -530,92 +667,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // (larger) size, so a dialog whose body gets shorter would never shrink back. ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { ui.spacing_mut().item_spacing.x = 10.0; - if matches!(d.kind, DialogKind::About | DialogKind::Error) { - // ↩ is OK too, as on every other dialog (#4872), from the frame after the - // alert appeared: the ↩ that raised it (committing a locked layer's Free - // Transform, say) must not close it again at once. - let seen = id.with("alert-seen"); - let shown_before = ui.ctx().data(|m| m.get_temp::(seen).unwrap_or(false)); - ui.ctx().data_mut(|m| m.insert_temp(seen, true)); - let enter = interactive && shown_before && ui.input(|i| i.key_pressed(egui::Key::Enter)); - if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() || enter { - outcome = Some(false); - } - } else { - let ok_label = if d.kind == DialogKind::NewDocument { - tl!("Create") - } else if crate::open_prompt::owns_damage(&d.fields) { - tl!("Continue") - } else if crate::delete_layer_prompt::owns(&d.fields) { - tl!("Delete") - } else if crate::disk_change_prompt::owns(&d.fields) || crate::replace_prompt::owns(&d.fields) { - tl!("Replace") - } else if d.fields.contains_key("__export") { - tl!("Export") - } else { - crate::file_ui::ok_label(&d.fields).unwrap_or(tl!("OK")) - }; - // Dialogs that need an input first (a preset name, a selection) grey OK out. - let can_ok = crate::crop_presets::can_confirm(app, &fields) && crate::stack_dialog::can_confirm(&fields); - let ok = DialogButton::new(ButtonRole::Default, ok_label, 84.0).enabled(can_ok); - // Photoshop: holding Alt turns Cancel into Reset (the dialog stays open). - // Dialogs opt in via `dialog_alt_reset::supported` (per marker). - let reset = ui.input(|i| i.modifiers.alt) && crate::dialog_alt_reset::supported(&fields); - let cancel_label = if reset { - tl!("Reset") - } else if d.kind == DialogKind::NewDocument { - tl!("Close") - } else { - tl!("Cancel") - }; - let cancel = DialogButton::new(ButtonRole::Cancel, cancel_label, 84.0); - let clicked = if d.kind == DialogKind::Command && crate::prefs_ui::is_preferences(&fields) { - let changed = crate::prefs_ui::preferences_changed(app, &fields); - dialog_buttons(ui, &[ok, cancel, DialogButton::new(ButtonRole::Apply, tl!("Apply"), 84.0).enabled(changed)]) - } else if crate::mask_trash_prompt::owns(&fields) && !crate::mask_trash_prompt::is_vector(&fields) { - // Photoshop: Apply / Cancel / Delete. Delete answers with the choice set. - let apply = DialogButton::new(ButtonRole::Default, tl!("Apply"), 84.0).enabled(crate::mask_trash_prompt::can_apply(&fields)); - let delete = DialogButton::new(ButtonRole::Alternate, tl!("Delete"), 84.0); - let hit = dialog_buttons(ui, &[apply, cancel, delete]); - if hit == Some(ButtonRole::Alternate) { - fields.insert("choice".into(), json!("delete")); - } else if hit == Some(ButtonRole::Default) { - fields.insert("choice".into(), json!("apply")); - } - hit - } else if crate::rasterize_prompt::is_filter(&fields) { - // Photoshop: Convert to Smart Object / Rasterize / Cancel (#4303). - let rasterize = DialogButton::new(ButtonRole::Default, tl!("Rasterize"), 84.0); - let hit = if crate::rasterize_prompt::offers_smart_object(&fields) { - let convert = DialogButton::new(ButtonRole::Alternate, tl!("Convert to Smart Object"), 160.0); - dialog_buttons(ui, &[rasterize, cancel, convert]) - } else { - dialog_buttons(ui, &[rasterize, cancel]) - }; - if hit == Some(ButtonRole::Alternate) { - fields.insert("choice".into(), json!("smartObject")); - } else if hit == Some(ButtonRole::Default) { - fields.insert("choice".into(), json!("rasterize")); - } - hit - } else { - dialog_buttons(ui, &[ok, cancel]) - }; - match clicked { - Some(ButtonRole::Cancel) if reset => crate::dialog_alt_reset::apply(app, ui.ctx(), &mut fields), - Some(ButtonRole::Cancel) => outcome = Some(false), - Some(ButtonRole::Apply) => apply_requested = true, - Some(_) => outcome = Some(true), - None if interactive - && can_ok - && (!web || (!web_popup_open && !egui::Popup::is_any_open(ui.ctx()))) - && ui.input(|i| i.key_pressed(egui::Key::Enter)) => - { - outcome = Some(true) - } - None => {} - } - } + let (done, apply) = button_row(app, ui, &d, &mut fields, id, interactive, web && (web_popup_open || egui::Popup::is_any_open(ui.ctx()))); + outcome = done.or(outcome); + apply_requested |= apply; }); } // The frame around the content (Frame::popup's margin and stroke). @@ -806,8 +860,74 @@ fn file_command(fields: &Fields) -> Option<&'static str> { } } -/// Confirm a dialog: run its action and close it. Used by the OK button and by automation. -pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { +/// Confirm a command dialog no specific handler owns: run its `__command` with the dialog's +/// parameters, then settle the filter preview and the playing action. +fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result { + let Some(cmd) = d.fields.get("__command").and_then(Value::as_str).map(str::to_string) else { + app.filter_preview = None; + crate::actions::abandoned(app, &d.fields); + return Err("dialog has no command".into()); + }; + if crate::filter_dialog::needs_displace_map(&cmd, &crate::filter_dialog::params_of(&d.fields)) { + app.filter_preview = None; + let result = crate::filter_dialog::ask_displace_map(app, cmd, d.fields.clone()); + if result.is_err() { + crate::actions::abandoned(app, &d.fields); + } else { + // Cancel and an unavailable picker finish before the Displace callback + // runs. Observe the whole file-dialog result, including those exits. + app.after_file_dialog(move |app, result| { + if result.is_err() { + crate::actions::abandoned(app, &d.fields); + } + result + }); + } + return result; + } + let (cmd, params) = match crate::smart_ui::confirm_command(app, &d.fields, cmd, crate::filter_dialog::params_of(&d.fields)) { + Ok(edit) => edit, + Err(e) => { + app.filter_preview = None; + return Err(e); + } + }; + let result = app.run(&cmd, params.clone()); + // A filter that runs as a background job keeps its preview on screen until the job + // lands (`canvas::committed_filter_preview`) instead of flashing the unfiltered image. + let running = + app.session.active().is_some_and(|st| app.filter_preview.as_ref().is_some_and(|p| p.key.doc == st.doc.id) && app.session.job_on(st.doc.id).is_some()); + match app.filter_preview.as_mut() { + Some(p) if result.is_ok() && running => p.committing = true, + _ => app.filter_preview = None, + } + if result.is_ok() + && cmd == "path.toSelection" + && d.fields.contains_key("__deselectPath") + && let Some(name) = params.get("name").and_then(Value::as_str) + { + crate::vector_ui::deselect_loaded_path(app, name); + } + if result.is_ok() && cmd == "view.newGuideLayout" { + app.ui.view.guide_layout = params; + } + if result.is_ok() { + if crate::adjust_dialog::owns(&d.fields) { + crate::adjust_dialog::remember(app, &d.fields); + } else { + crate::filter_dialog::remember(app, &cmd, &d.fields); + } + // A step dialog of a playing action: the action continues after it. + crate::actions::resume(app, &d.fields)?; + } else { + crate::actions::abandoned(app, &d.fields); + } + result +} + +/// The checks before a dialog is confirmed: no open child picker, the automation gate for a handler +/// that touches files itself, and a valid guide layout. +fn confirm_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(), String> { if crate::layer_style::color_picker::has_child(app, id) { return Err("confirm or cancel the Layer Style color picker first".into()); } @@ -826,6 +946,56 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { } crate::guide_layout_ui::validate(app, &d.fields)?; } + Ok(()) +} + +/// Confirm a dialog: run its action and close it. Used by the OK button and by automation. +/// Confirm a command dialog through the first handler whose marker its fields carry; the prompts +/// and small editors are here, the rest in `confirm_command_more`. +fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result { + match d.kind { + _ if crate::open_prompt::owns_damage(&d.fields) => crate::open_prompt::answer_damage(app, true), + _ if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields), + _ if crate::brush_preset_dialog::owns(&d.fields) => crate::brush_preset_dialog::confirm(app, &d.fields), + _ if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields), + _ if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields), + _ if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields), + _ if crate::new_group_ui::owns(&d.fields) => crate::new_group_ui::confirm(app, &d.fields), + _ if crate::snapshot_dialog::owns(&d.fields) => crate::snapshot_dialog::confirm(app, &d.fields), + _ if crate::channel_options_ui::owns(&d.fields) => crate::channel_options_ui::confirm(app, &d.fields), + _ if crate::channel_options_ui::owns_new_spot(&d.fields) => crate::channel_options_ui::confirm_new_spot(app, &d.fields), + _ if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields), + _ if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields), + _ if crate::disk_change_prompt::owns(&d.fields) => crate::disk_change_prompt::confirm(app, &d.fields), + _ if crate::replace_prompt::owns(&d.fields) => crate::replace_prompt::confirm(app), + _ if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_confirm(app, &d.fields), + _ if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields), + _ if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields), + _ if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields), + _ if crate::duplicate_layer_ui::owns(&d.fields) => crate::duplicate_layer_ui::confirm(app, &d.fields), + _ if crate::stack_dialog::owns(&d.fields) => crate::stack_dialog::confirm(app, &d.fields), + _ if crate::tool_reset::owns(&d.fields) => crate::tool_reset::confirm(app), + _ if crate::crop_presets::owns(&d.fields) => crate::crop_presets::confirm(app, &d.fields), + _ if crate::variables_ui::owns(&d.fields) => crate::variables_ui::confirm(app, &d.fields), + _ => confirm_command_more(app, d), + } +} + +/// The rest of the command dialogs: files, colour, preferences and export, then any other command. +fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result { + match d.kind { + _ if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields), + _ if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields), + _ if crate::color_picker_ui::owns(&d.fields) => crate::color_picker_ui::confirm(app, &d.fields), + _ if crate::color_range_ui::owns(&d.fields) => crate::color_range_ui::confirm(app, &d.fields), + _ if crate::prefs_ui::owns(&d.fields) => crate::prefs_ui::confirm(app, &d.fields), + _ if d.fields.contains_key("__export") => crate::export_dialog::confirm(app, &d.fields), + _ => confirm_generic_command(app, d), + } +} + +pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { + confirm_preflight(app, id)?; let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; match d.kind { DialogKind::NewDocument => { @@ -840,99 +1010,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { } r } - DialogKind::Command if crate::open_prompt::owns_damage(&d.fields) => crate::open_prompt::answer_damage(app, true), - DialogKind::Command if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields), - DialogKind::Command if crate::brush_preset_dialog::owns(&d.fields) => crate::brush_preset_dialog::confirm(app, &d.fields), - DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields), - DialogKind::Command if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields), - DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields), - DialogKind::Command if crate::new_group_ui::owns(&d.fields) => crate::new_group_ui::confirm(app, &d.fields), - DialogKind::Command if crate::snapshot_dialog::owns(&d.fields) => crate::snapshot_dialog::confirm(app, &d.fields), - DialogKind::Command if crate::channel_options_ui::owns(&d.fields) => crate::channel_options_ui::confirm(app, &d.fields), - DialogKind::Command if crate::channel_options_ui::owns_new_spot(&d.fields) => crate::channel_options_ui::confirm_new_spot(app, &d.fields), - DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields), - DialogKind::Command if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields), - DialogKind::Command if crate::disk_change_prompt::owns(&d.fields) => crate::disk_change_prompt::confirm(app, &d.fields), - DialogKind::Command if crate::replace_prompt::owns(&d.fields) => crate::replace_prompt::confirm(app), - DialogKind::Command if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_confirm(app, &d.fields), - DialogKind::Command if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields), - DialogKind::Command if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields), - DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields), - DialogKind::Command if crate::duplicate_layer_ui::owns(&d.fields) => crate::duplicate_layer_ui::confirm(app, &d.fields), - DialogKind::Command if crate::stack_dialog::owns(&d.fields) => crate::stack_dialog::confirm(app, &d.fields), - DialogKind::Command if crate::tool_reset::owns(&d.fields) => crate::tool_reset::confirm(app), - DialogKind::Command if crate::crop_presets::owns(&d.fields) => crate::crop_presets::confirm(app, &d.fields), - DialogKind::Command if crate::variables_ui::owns(&d.fields) => crate::variables_ui::confirm(app, &d.fields), - DialogKind::Command if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields), - DialogKind::Command if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields), - DialogKind::Command if crate::color_picker_ui::owns(&d.fields) => crate::color_picker_ui::confirm(app, &d.fields), - DialogKind::Command if crate::color_range_ui::owns(&d.fields) => crate::color_range_ui::confirm(app, &d.fields), - DialogKind::Command if crate::prefs_ui::owns(&d.fields) => crate::prefs_ui::confirm(app, &d.fields), - DialogKind::Command if d.fields.contains_key("__export") => crate::export_dialog::confirm(app, &d.fields), - DialogKind::Command => { - let Some(cmd) = d.fields.get("__command").and_then(Value::as_str).map(str::to_string) else { - app.filter_preview = None; - crate::actions::abandoned(app, &d.fields); - return Err("dialog has no command".into()); - }; - if crate::filter_dialog::needs_displace_map(&cmd, &crate::filter_dialog::params_of(&d.fields)) { - app.filter_preview = None; - let result = crate::filter_dialog::ask_displace_map(app, cmd, d.fields.clone()); - if result.is_err() { - crate::actions::abandoned(app, &d.fields); - } else { - // Cancel and an unavailable picker finish before the Displace callback - // runs. Observe the whole file-dialog result, including those exits. - app.after_file_dialog(move |app, result| { - if result.is_err() { - crate::actions::abandoned(app, &d.fields); - } - result - }); - } - return result; - } - let (cmd, params) = match crate::smart_ui::confirm_command(app, &d.fields, cmd, crate::filter_dialog::params_of(&d.fields)) { - Ok(edit) => edit, - Err(e) => { - app.filter_preview = None; - return Err(e); - } - }; - let result = app.run(&cmd, params.clone()); - // A filter that runs as a background job keeps its preview on screen until the job - // lands (`canvas::committed_filter_preview`) instead of flashing the unfiltered image. - let running = app - .session - .active() - .is_some_and(|st| app.filter_preview.as_ref().is_some_and(|p| p.key.doc == st.doc.id) && app.session.job_on(st.doc.id).is_some()); - match app.filter_preview.as_mut() { - Some(p) if result.is_ok() && running => p.committing = true, - _ => app.filter_preview = None, - } - if result.is_ok() - && cmd == "path.toSelection" - && d.fields.contains_key("__deselectPath") - && let Some(name) = params.get("name").and_then(Value::as_str) - { - crate::vector_ui::deselect_loaded_path(app, name); - } - if result.is_ok() && cmd == "view.newGuideLayout" { - app.ui.view.guide_layout = params; - } - if result.is_ok() { - if crate::adjust_dialog::owns(&d.fields) { - crate::adjust_dialog::remember(app, &d.fields); - } else { - crate::filter_dialog::remember(app, &cmd, &d.fields); - } - // A step dialog of a playing action: the action continues after it. - crate::actions::resume(app, &d.fields)?; - } else { - crate::actions::abandoned(app, &d.fields); - } - result - } + DialogKind::Command => confirm_command(app, d), DialogKind::LayerStyle => crate::layer_style::confirm(app, &d.fields), DialogKind::About | DialogKind::Error => Ok(Value::Null), } diff --git a/crates/ui-egui/src/dialogs/caf_ui/view.rs b/crates/ui-egui/src/dialogs/caf_ui/view.rs index b40e1f8ed2..a2124c9ef5 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/view.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/view.rs @@ -114,6 +114,153 @@ pub(super) fn view_image(app: &PhotocraftApp) -> Option { Some(crate::canvas::display_image(display.as_deref(), &buf)) } +/// The Content-Aware Fill panel's scrolling settings: sampling area, fill and output options. +fn caf_props_panel( + ui: &mut egui::Ui, + w: &mut CafWorkspace, + t: &Tokens, + reset_what: &mut Option<&str>, + new_sampling: &mut Option<&str>, + rebase_needed: &mut bool, +) { + ui.spacing_mut().item_spacing.y = 6.0; + egui::CollapsingHeader::new(tl!("Sampling Area Overlay")).id_salt("caf-overlay").default_open(false).show(ui, |ui| { + widgets::checkbox(ui, &mut w.opts.show_overlay, tl!("Show Sampling Area")); + widgets::slider_row(ui, tl!("Opacity"), &mut w.opts.opacity, 0.0..=100.0, "%", None); + ui.horizontal(|ui| { + ui.label(tl!("Color")); + widgets::color_edit_button_srgb(ui, &mut w.opts.color); + ui.add_space(8.0); + ui.label(tl!("Indicates")); + widgets::dropdown( + ui, + "caf-indicates", + tl!("Indicates"), + &mut w.opts.excluded, + &[(false, tl!("Sampling Area")), (true, tl!("Excluded Area"))], + 120.0, + ); + }); + }); + widgets::hairline(ui); + ui.horizontal(|ui| { + widgets::section_label(ui, tl!("Sampling Area Options")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { + *reset_what = Some("sampling"); + } + }); + }); + ui.horizontal(|ui| { + for (k, l) in [("auto", tl!("Auto")), ("rectangular", tl!("Rectangular")), ("custom", tl!("Custom"))] { + if ui.selectable_label(w.opts.sampling == k, l).clicked() && w.opts.sampling != k { + *new_sampling = Some(k); + } + } + }); + if widgets::checkbox(ui, &mut w.opts.sample_all, tl!("Sample All Layers")).changed() { + *rebase_needed = true; + } + widgets::hairline(ui); + ui.horizontal(|ui| { + widgets::section_label(ui, tl!("Fill Settings")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { + *reset_what = Some("fill"); + } + }); + }); + ui.horizontal(|ui| { + ui.label(tl!("Color Adaptation")); + let o = [ + ("none".to_string(), tl!("None")), + ("default".to_string(), tl!("Default")), + ("high".to_string(), tl!("High")), + ("veryHigh".to_string(), tl!("Very High")), + ]; + widgets::dropdown(ui, "caf-color", tl!("Color Adaptation"), &mut w.opts.color_adaptation, &o, 110.0); + }); + ui.horizontal(|ui| { + ui.label(tl!("Rotation Adaptation")); + let o = [ + ("none".to_string(), tl!("None")), + ("low".to_string(), tl!("Low")), + ("medium".to_string(), tl!("Medium")), + ("high".to_string(), tl!("High")), + ("full".to_string(), tl!("Full")), + ]; + widgets::dropdown(ui, "caf-rotation", tl!("Rotation Adaptation"), &mut w.opts.rotation, &o, 110.0); + }); + ui.horizontal(|ui| { + widgets::checkbox(ui, &mut w.opts.scale, tl!("Scale")); + widgets::checkbox(ui, &mut w.opts.mirror, tl!("Mirror")); + }); + widgets::hairline(ui); + widgets::section_label(ui, tl!("Output Settings")); + ui.horizontal(|ui| { + ui.label(tl!("Output To")); + let o = [("current".to_string(), tl!("Current Layer")), ("new".to_string(), tl!("New Layer")), ("duplicate".to_string(), tl!("Duplicate Layer"))]; + widgets::dropdown(ui, "caf-output", tl!("Output To"), &mut w.opts.output, &o, 140.0); + }); + if let Some(e) = w.error.as_ref().or(w.preview.error.as_ref()) { + ui.label(egui::RichText::new(e.as_str()).color(t.danger).size(11.0)); + } +} + +/// The Preview panel: the sampled result in its own pan / zoom view, and the zoom row under it. +fn caf_preview_panel(ui: &mut egui::Ui, painter: &egui::Painter, t: &Tokens, w: &mut CafWorkspace, pv_rect: ERect) { + painter.rect_filled(pv_rect, 0.0, t.dock); + painter.line_segment([pv_rect.left_top(), pv_rect.left_bottom()], Stroke::new(1.0, t.separator)); + painter.text(pv_rect.left_top() + vec2(12.0, 10.0), Align2::LEFT_TOP, tl!("Preview"), FontId::proportional(12.0), t.text); + let pv_area = ERect::from_min_max(pv_rect.min + vec2(0.0, 30.0), pv_rect.max - vec2(0.0, 44.0)); + painter.rect_filled(pv_area, 0.0, t.canvas); + if w.preview.zoom <= 0.0 { + // Opens framed on the sampling window, as Photoshop's. + let win = w.base.window; + if !win.is_empty() { + w.preview.zoom = (pv_area.width() / win.width().max(win.height()) as f32).clamp(0.01, 32.0); + w.preview.center = [f64::from(win.x0 + win.x1) / 2.0, f64::from(win.y0 + win.y1) / 2.0]; + } + } + let pv = View { area: pv_area, zoom: w.preview.zoom.max(0.01), center: w.preview.center }; + let pclip = painter.with_clip_rect(pv_area); + let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + let img_rect = pv.rect(w.canvas); + widgets::checker(&pclip, img_rect.intersect(pv_area), 8.0); + if let Some(tex) = &w.image_tex { + pclip.image(tex.id(), img_rect, uv, Color32::WHITE); + } + if let Some((tex, r)) = &w.preview.tex { + pclip.image(tex.id(), pv.rect(*r), uv, Color32::WHITE); + } + if w.preview.shown != w.preview.want { + // Being recomputed: a spinner in the corner. + let sp = ERect::from_min_size(pv_area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0)); + ui.put(sp, egui::Spinner::new().size(16.0)); + } + let presp = ui.interact(pv_area, egui::Id::unique("caf-preview-view"), Sense::click_and_drag()); + if presp.dragged() { + let d = presp.drag_delta(); + w.preview.center = [w.preview.center[0] - f64::from(d.x / pv.zoom), w.preview.center[1] - f64::from(d.y / pv.zoom)]; + } + if presp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll != 0.0 { + w.preview.zoom = (w.preview.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); + } + } + let zrow = ERect::from_min_size(pos2(pv_rect.left() + 10.0, pv_rect.bottom() - 38.0), vec2(PREVIEW_W - 20.0, 30.0)); + let mut zr = ui.new_child(egui::UiBuilder::new().max_rect(zrow).layout(egui::Layout::left_to_right(egui::Align::Center))); + let mut pct = (w.preview.zoom * 100.0).round(); + if widgets::value_field(&mut zr, &mut pct, 1.0..=3200.0, "%", 64.0).accessible_name(tl!("Zoom")).changed() { + w.preview.zoom = pct / 100.0; + } + let mut lz = pct.max(1.0).ln(); + if zr.add(egui::Slider::new(&mut lz, 0.0..=3200f32.ln()).show_value(false)).accessible_name(tl!("Zoom")).changed() { + w.preview.zoom = lz.exp() / 100.0; + } +} + /// Draws the workspace (a full-window layer over the app). pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // An Apply (or anything else) changed the document: refresh. @@ -177,91 +324,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); let mut props = ui.new_child(egui::UiBuilder::new().max_rect(ERect::from_min_max(right.min + vec2(14.0, 12.0), pos2(right.right() - 14.0, right.bottom() - 60.0)))); - egui::ScrollArea::vertical().id_salt("caf-props").show(&mut props, |ui| { - ui.spacing_mut().item_spacing.y = 6.0; - egui::CollapsingHeader::new(tl!("Sampling Area Overlay")).id_salt("caf-overlay").default_open(false).show(ui, |ui| { - widgets::checkbox(ui, &mut w.opts.show_overlay, tl!("Show Sampling Area")); - widgets::slider_row(ui, tl!("Opacity"), &mut w.opts.opacity, 0.0..=100.0, "%", None); - ui.horizontal(|ui| { - ui.label(tl!("Color")); - widgets::color_edit_button_srgb(ui, &mut w.opts.color); - ui.add_space(8.0); - ui.label(tl!("Indicates")); - widgets::dropdown( - ui, - "caf-indicates", - tl!("Indicates"), - &mut w.opts.excluded, - &[(false, tl!("Sampling Area")), (true, tl!("Excluded Area"))], - 120.0, - ); - }); - }); - widgets::hairline(ui); - ui.horizontal(|ui| { - widgets::section_label(ui, tl!("Sampling Area Options")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { - reset_what = Some("sampling"); - } - }); - }); - ui.horizontal(|ui| { - for (k, l) in [("auto", tl!("Auto")), ("rectangular", tl!("Rectangular")), ("custom", tl!("Custom"))] { - if ui.selectable_label(w.opts.sampling == k, l).clicked() && w.opts.sampling != k { - new_sampling = Some(k); - } - } - }); - if widgets::checkbox(ui, &mut w.opts.sample_all, tl!("Sample All Layers")).changed() { - rebase_needed = true; - } - widgets::hairline(ui); - ui.horizontal(|ui| { - widgets::section_label(ui, tl!("Fill Settings")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { - reset_what = Some("fill"); - } - }); - }); - ui.horizontal(|ui| { - ui.label(tl!("Color Adaptation")); - let o = [ - ("none".to_string(), tl!("None")), - ("default".to_string(), tl!("Default")), - ("high".to_string(), tl!("High")), - ("veryHigh".to_string(), tl!("Very High")), - ]; - widgets::dropdown(ui, "caf-color", tl!("Color Adaptation"), &mut w.opts.color_adaptation, &o, 110.0); - }); - ui.horizontal(|ui| { - ui.label(tl!("Rotation Adaptation")); - let o = [ - ("none".to_string(), tl!("None")), - ("low".to_string(), tl!("Low")), - ("medium".to_string(), tl!("Medium")), - ("high".to_string(), tl!("High")), - ("full".to_string(), tl!("Full")), - ]; - widgets::dropdown(ui, "caf-rotation", tl!("Rotation Adaptation"), &mut w.opts.rotation, &o, 110.0); - }); - ui.horizontal(|ui| { - widgets::checkbox(ui, &mut w.opts.scale, tl!("Scale")); - widgets::checkbox(ui, &mut w.opts.mirror, tl!("Mirror")); - }); - widgets::hairline(ui); - widgets::section_label(ui, tl!("Output Settings")); - ui.horizontal(|ui| { - ui.label(tl!("Output To")); - let o = - [("current".to_string(), tl!("Current Layer")), ("new".to_string(), tl!("New Layer")), ("duplicate".to_string(), tl!("Duplicate Layer"))]; - widgets::dropdown(ui, "caf-output", tl!("Output To"), &mut w.opts.output, &o, 140.0); - }); - if let Some(e) = w.error.as_ref().or(w.preview.error.as_ref()) { - ui.label(egui::RichText::new(e.as_str()).color(t.danger).size(11.0)); - } - }); + egui::ScrollArea::vertical() + .id_salt("caf-props") + .show(&mut props, |ui| caf_props_panel(ui, w, &t, &mut reset_what, &mut new_sampling, &mut rebase_needed)); // Footer, in Photoshop's order on every platform: reset all at the left, then OK, Apply, // Cancel against the right edge. let foot = ERect::from_min_size(pos2(right.left() + 10.0, right.bottom() - 48.0), vec2(PANEL_W - 20.0, 32.0)); @@ -280,56 +345,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } // The Preview panel. let pv_rect = ERect::from_min_size(pos2(right.left() - PREVIEW_W, body.top()), vec2(PREVIEW_W, body.height())); - painter.rect_filled(pv_rect, 0.0, t.dock); - painter.line_segment([pv_rect.left_top(), pv_rect.left_bottom()], Stroke::new(1.0, t.separator)); - painter.text(pv_rect.left_top() + vec2(12.0, 10.0), Align2::LEFT_TOP, tl!("Preview"), FontId::proportional(12.0), t.text); - let pv_area = ERect::from_min_max(pv_rect.min + vec2(0.0, 30.0), pv_rect.max - vec2(0.0, 44.0)); - painter.rect_filled(pv_area, 0.0, t.canvas); - if w.preview.zoom <= 0.0 { - // Opens framed on the sampling window, as Photoshop's. - let win = w.base.window; - if !win.is_empty() { - w.preview.zoom = (pv_area.width() / win.width().max(win.height()) as f32).clamp(0.01, 32.0); - w.preview.center = [f64::from(win.x0 + win.x1) / 2.0, f64::from(win.y0 + win.y1) / 2.0]; - } - } - let pv = View { area: pv_area, zoom: w.preview.zoom.max(0.01), center: w.preview.center }; - let pclip = painter.with_clip_rect(pv_area); let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - let img_rect = pv.rect(w.canvas); - widgets::checker(&pclip, img_rect.intersect(pv_area), 8.0); - if let Some(tex) = &w.image_tex { - pclip.image(tex.id(), img_rect, uv, Color32::WHITE); - } - if let Some((tex, r)) = &w.preview.tex { - pclip.image(tex.id(), pv.rect(*r), uv, Color32::WHITE); - } - if w.preview.shown != w.preview.want { - // Being recomputed: a spinner in the corner. - let sp = ERect::from_min_size(pv_area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0)); - ui.put(sp, egui::Spinner::new().size(16.0)); - } - let presp = ui.interact(pv_area, egui::Id::unique("caf-preview-view"), Sense::click_and_drag()); - if presp.dragged() { - let d = presp.drag_delta(); - w.preview.center = [w.preview.center[0] - f64::from(d.x / pv.zoom), w.preview.center[1] - f64::from(d.y / pv.zoom)]; - } - if presp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); - if scroll != 0.0 { - w.preview.zoom = (w.preview.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); - } - } - let zrow = ERect::from_min_size(pos2(pv_rect.left() + 10.0, pv_rect.bottom() - 38.0), vec2(PREVIEW_W - 20.0, 30.0)); - let mut zr = ui.new_child(egui::UiBuilder::new().max_rect(zrow).layout(egui::Layout::left_to_right(egui::Align::Center))); - let mut pct = (w.preview.zoom * 100.0).round(); - if widgets::value_field(&mut zr, &mut pct, 1.0..=3200.0, "%", 64.0).accessible_name(tl!("Zoom")).changed() { - w.preview.zoom = pct / 100.0; - } - let mut lz = pct.max(1.0).ln(); - if zr.add(egui::Slider::new(&mut lz, 0.0..=3200f32.ln()).show_value(false)).accessible_name(tl!("Zoom")).changed() { - w.preview.zoom = lz.exp() / 100.0; - } + caf_preview_panel(ui, &painter, &t, w, pv_rect); // The document view. let area = ERect::from_min_max(pos2(left.right(), body.top()), pos2(pv_rect.left(), body.bottom())); painter.rect_filled(area, 0.0, t.canvas); From 267fb55e0fd9ede99a930c5970c4e2845a23347c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:06:42 +0000 Subject: [PATCH 27/35] Refactor ui-egui canvas and options bar for strict Clippy checks --- crates/ui-egui/src/canvas.rs | 421 +++++++++++++---------- crates/ui-egui/src/panels/options_bar.rs | 243 ++++++++----- 2 files changed, 393 insertions(+), 271 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index bfddadad51..3da8e617da 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -780,11 +780,11 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: let under_dialog = input.under_dialog; let mods = ui.input(|i| i.modifiers); // An ⌥-click the window manager took never arrives; say so (alt_grab.rs). - crate::alt_grab::watch(app, &ctx, egui::Id::unique(("pc-alt-grab", idx)), rect, tool, !under_dialog); + crate::alt_grab::watch(app, ctx, egui::Id::unique(("pc-alt-grab", idx)), rect, tool, !under_dialog); // Tools follow the left button; the right one opens the Brush Preset picker or erases // (Preferences › Tools, `paint_mouse`). crate::paint_mouse::sync_tool_brush(app); - let mut buttons = crate::paint_mouse::canvas_buttons(app, &response, tool); + let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool); // The Crop tool's frame is edited from the press (before egui's drag threshold), so the // pixels past the canvas show at once, as in Photoshop. if tool == Tool::Crop && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down()) && crate::crop_ui::press(app) { @@ -830,7 +830,7 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> && transforming && let Some(p) = response.interact_pointer_pos() { - crate::canvas_tool_menu::open_transform(app, &ctx, [p.x, p.y]); + crate::canvas_tool_menu::open_transform(app, ctx, [p.x, p.y]); } let lasso_retracted = response.secondary_clicked() && match tool { @@ -842,7 +842,7 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> // drops the moves of a drag it didn't start, so an open Free Transform box takes the // usual drag path instead (#2153). if crate::lasso_ui::owns(tool) && !transform_owns_pointer { - crate::lasso_ui::canvas_input(app, &ctx, &xf, &response); + crate::lasso_ui::canvas_input(app, ctx, xf, response); (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); } // Right-click on a guide where it could be dragged (the Move tool, or ⌘ with a selection @@ -850,7 +850,7 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> let guide_menu = response.secondary_clicked() && !lasso_retracted && !transforming - && response.interact_pointer_pos().is_some_and(|p| crate::canvas_tool_menu::open_guide(app, &ctx, tool, mods, [p.x, p.y], xf.to_doc(p))); + && response.interact_pointer_pos().is_some_and(|p| crate::canvas_tool_menu::open_guide(app, ctx, tool, mods, [p.x, p.y], xf.to_doc(p))); // Right-click with the Move tool, or ⌘/Ctrl+right-click: the layers under the pointer. if response.secondary_clicked() && !lasso_retracted @@ -862,8 +862,8 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> let d = xf.to_doc(p); app.ui.canvas_tool_menu = None; // No layers there (the pasteboard, with the Move tool): its colour menu instead. - if !crate::layer_pick_ui::open(app, &ctx, [p.x, p.y], d[0], d[1]) && !mods.command && crate::canvas_tool_menu::pasteboard_at(app, tool, d) { - crate::canvas_tool_menu::open_pasteboard(app, &ctx, tool, [p.x, p.y]); + if !crate::layer_pick_ui::open(app, ctx, [p.x, p.y], d[0], d[1]) && !mods.command && crate::canvas_tool_menu::pasteboard_at(app, tool, d) { + crate::canvas_tool_menu::open_pasteboard(app, ctx, tool, [p.x, p.y]); } } if response.secondary_clicked() @@ -883,15 +883,15 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> && !response.long_touched() && (app.crop.drag.is_some() || app.crop.straighten.line.is_some()) && ctx.input(|i| i.pointer.primary_down()); - if crop_gesture || crate::canvas_tool_menu::open_crop(app, &ctx, tool, [p.x, p.y]) { + if crop_gesture || crate::canvas_tool_menu::open_crop(app, ctx, tool, [p.x, p.y]) { } else if crate::canvas_tool_menu::pasteboard_at(app, tool, xf.to_doc(p)) { - crate::canvas_tool_menu::open_pasteboard(app, &ctx, tool, [p.x, p.y]); + crate::canvas_tool_menu::open_pasteboard(app, ctx, tool, [p.x, p.y]); } else if crate::canvas_tool_menu::is_view_tool(tool) { if tool == app.ui.tool { - crate::canvas_tool_menu::open_view(app, &ctx, tool, [p.x, p.y], xf.to_doc(p)); + crate::canvas_tool_menu::open_view(app, ctx, tool, [p.x, p.y], xf.to_doc(p)); } } else { - crate::canvas_tool_menu::open_at(app, &ctx, tool, [p.x, p.y], Some(xf.to_doc(p))); + crate::canvas_tool_menu::open_at(app, ctx, tool, [p.x, p.y], Some(xf.to_doc(p))); } } } @@ -921,7 +921,7 @@ fn handle_canvas_tool_navigation( // Rotate View: drag around the view centre. Compass clicks are not a rotate drag. let over_compass = crate::rotate_view::compass_visible(view.rotation) && response.interact_pointer_pos().is_some_and(|p| crate::rotate_view::compass_rect(xf.rect).contains(p)); - if tool == Tool::RotateView && !over_compass && crate::rotate_view::drag(&ctx, view, &xf, &buttons, response.interact_pointer_pos()) { + if tool == Tool::RotateView && !over_compass && crate::rotate_view::drag(ctx, view, xf, buttons, response.interact_pointer_pos()) { (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); } // Animated Zoom: a Zoom press held still zooms continuously (zoom_hold.rs); while it does, @@ -930,13 +930,13 @@ fn handle_canvas_tool_navigation( let out = zoom_out(_ui.input(|i| i.modifiers.alt)); let on_canvas = false; let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); - if crate::zoom_hold::update(&ctx, view, &xf, app.session.prefs().general.animated_zoom, out, ppp, on_canvas, hold) { + if crate::zoom_hold::update(ctx, 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); } } // Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below. // Like the Hand, the selected Zoom yields to an open Free Transform box (#4799). - if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, &ctx, view, &xf, &buttons, response.interact_pointer_pos()) { + if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, ctx, view, xf, buttons, response.interact_pointer_pos()) { (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); } } @@ -991,7 +991,7 @@ fn handle_canvas_tool_stroke( && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) { if tool == Tool::Move && app.ui.transform.is_none() { - begin_transform_controls_at(app, &ctx, &xf, p); + begin_transform_controls_at(app, ctx, xf, p); } let d = xf.to_doc(p); let press_mods = if capture_press { ctx.data(|d| d.get_temp(tool_press)).unwrap_or(mods) } else { mods }; @@ -1134,7 +1134,7 @@ fn handle_canvas_tool_clicks( let center = app.session.prefs().tools.zoom_clicked_point_to_center; let doc_anchor = xf.to_doc(p); let screen_anchor = p; - zoom_about(view, &xf, p, nz, center, ppp); + zoom_about(view, xf, p, nz, center, ppp); view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_zoom); view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); } @@ -1150,13 +1150,13 @@ fn handle_canvas_tool_clicks( Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { - if let Err(e) = crate::menus::invoke(app, &ctx, "edit.preferences.guidesGridAndSlices", json!({})) { + if let Err(e) = crate::menus::invoke(app, ctx, "edit.preferences.guidesGridAndSlices", json!({})) { app.ui.status = e; } } _ => { if tool == Tool::Move && app.ui.transform.is_none() { - begin_transform_controls_at(app, &ctx, &xf, p); + begin_transform_controls_at(app, ctx, xf, p); } // If this tool was not handled on pointer-down, fall back to a // click-sized gesture while preserving pen pressure (mouse stays at 1). @@ -1248,32 +1248,32 @@ fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut let edge_rect = input.edge_rect; // The transform preview is image content: it goes under the grid and guides, which // stay visible across a layer being transformed (#5086); the box is drawn later. - crate::transform_tool::draw_content(app, &painter, &xf); + crate::transform_tool::draw_content(app, painter, xf); // So are Puppet Warp's, Perspective Warp's and Vanishing Point's warped pixels (#7781). - crate::distort_ui::draw_content(app, &painter, &xf); + crate::distort_ui::draw_content(app, painter, xf); if app.ui.extras.grid && app.ui.view.extras { - crate::rulers::draw_grid(app, &painter, &xf, &doc); + crate::rulers::draw_grid(app, painter, xf, doc); } - if app.ui.view.shows(app.ui.view.show.canvas_guides) || crate::guide_layout_ui::preview(app, &doc).is_some() { - crate::rulers::draw_guides(app, &painter, &xf, &doc); + if app.ui.view.shows(app.ui.view.show.canvas_guides) || crate::guide_layout_ui::preview(app, doc).is_some() { + crate::rulers::draw_guides(app, painter, xf, doc); } // The pending crop frame shows on its own document only, not on the other tiles (#1918). let foreign_crop = if app.session.active_index() == Some(idx) { None } else { app.ui.crop_rect.take() }; - draw_drag_preview(app, &painter, &xf); + draw_drag_preview(app, painter, xf); if app.session.active_index() == Some(idx) { - crate::move_box::draw(app, &painter, &xf); + crate::move_box::draw(app, painter, xf); } if foreign_crop.is_some() { app.ui.crop_rect = foreign_crop; } - crate::zoom_tool::draw(&ctx, &painter); - let resizing = crate::brush_resize::draw(app, &painter, &xf); - draw_transform_controls(app, &painter, &xf); - crate::move_hover::draw(app, &painter, &xf, idx, response.hover_pos()); - crate::object_finder::draw(app, &painter, &xf, idx, response.hover_pos()); - crate::layer_pick_ui::show(app, &ctx); + crate::zoom_tool::draw(ctx, painter); + let resizing = crate::brush_resize::draw(app, painter, xf); + draw_transform_controls(app, painter, xf); + crate::move_hover::draw(app, painter, xf, idx, response.hover_pos()); + crate::object_finder::draw(app, painter, xf, idx, response.hover_pos()); + crate::layer_pick_ui::show(app, ctx); let shown = app.ui.views.get(idx).cloned(); - crate::canvas_tool_menu::show(app, &ctx); + crate::canvas_tool_menu::show(app, ctx); // A view menu row (Zoom In, Fit on Screen…) changed the camera: it wins over this // frame's copy, which is written back at the end. if let Some(now) = app.ui.views.get(idx) @@ -1282,27 +1282,27 @@ fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut *view = now.clone(); ctx.request_repaint(); } - crate::snap_ui::draw(app, &painter, &xf); - crate::move_distance::draw(app, &painter, &xf, idx, response.hover_pos()); + crate::snap_ui::draw(app, painter, xf); + crate::move_distance::draw(app, painter, xf, idx, response.hover_pos()); // The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview), // nor while the Crop tool hides everything outside its box (Show Cropped Area off). if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond && !crate::crop_shield::hides_outside(app) { painter.rect_stroke(edge_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside); } - crate::type_tool::draw_overlay(app, &painter, &xf); - crate::transform_tool::draw_overlay(app, &painter, &xf); - crate::cam_transform::draw(app, &painter, &xf); + crate::type_tool::draw_overlay(app, painter, xf); + crate::transform_tool::draw_overlay(app, painter, xf); + crate::cam_transform::draw(app, painter, xf); crate::cam_preview::wake(app, painter.ctx()); - crate::distort_ui::draw_overlay(app, &painter, &xf); - crate::perspective_crop_ui::draw_overlay(app, &painter, &xf); - crate::retouch_ui::draw_source_marker(app, &painter, &xf); - crate::vector_ui::draw_overlay(app, &painter, &xf, &doc); - crate::symmetry_ui::draw(app, &painter, &xf); - crate::analysis_ui::draw_overlay(app, &painter, &xf); - crate::gradient_ui::draw_overlay(app, &painter, &xf); - crate::slice_ui::draw_overlay(app, &painter, &xf); - crate::frame_tool::draw_overlay(app, &painter, &xf); - crate::artboard_tool::draw_overlay(app, &painter, &xf); + crate::distort_ui::draw_overlay(app, painter, xf); + crate::perspective_crop_ui::draw_overlay(app, painter, xf); + crate::retouch_ui::draw_source_marker(app, painter, xf); + crate::vector_ui::draw_overlay(app, painter, xf, doc); + crate::symmetry_ui::draw(app, painter, xf); + crate::analysis_ui::draw_overlay(app, painter, xf); + crate::gradient_ui::draw_overlay(app, painter, xf); + crate::slice_ui::draw_overlay(app, painter, xf); + crate::frame_tool::draw_overlay(app, painter, xf); + crate::artboard_tool::draw_overlay(app, painter, xf); draw_canvas_tool_cursor(app, ui, input, resizing); } @@ -1323,14 +1323,14 @@ fn draw_canvas_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &C }); if panning { // The fist set with the pan above stays (#2196). - } else if crate::tool_cursor::pointer_elsewhere(&ctx, &crate::panel_docking::native_viewports(app, &ctx)) { + } else if crate::tool_cursor::pointer_elsewhere(ctx, &crate::panel_docking::native_viewports(app, ctx)) { // The pointer is over a floating panel's own window; this window's last position of // it is stale, so no tool cursor or brush outline is painted at it. } else if let Some((vertical, _)) = guide_hover { - ui.ctx().set_cursor_icon(crate::rulers::guide_cursor(&xf, vertical)); + ui.ctx().set_cursor_icon(crate::rulers::guide_cursor(xf, vertical)); } else if let Some((p, mods, c)) = response.hover_pos().and_then(|p| { let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - let c = crate::transform_tool::cursor(app, &xf, xf.to_doc(p), mods)?; + let c = crate::transform_tool::cursor(app, xf, xf.to_doc(p), mods)?; Some((p, mods, c)) }) { ui.ctx().set_cursor_icon(c); @@ -1339,44 +1339,44 @@ fn draw_canvas_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &C let d = xf.to_doc(p); if let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; - crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + crate::crop_ui::draw_turn_cursor(ctx, p, toward); } else if c == egui::CursorIcon::None { // Likewise the distort and skew pointers over a handle (#5405). - crate::transform_tool::draw_handle_cursor(app, &ctx, &xf, p, mods); + crate::transform_tool::draw_handle_cursor(app, ctx, xf, p, mods); } - } else if let Some(c) = response.hover_pos().and_then(|p| crate::symmetry_ui::cursor(app, &xf, xf.to_doc(p))) { + } else if let Some(c) = response.hover_pos().and_then(|p| crate::symmetry_ui::cursor(app, xf, xf.to_doc(p))) { ui.ctx().set_cursor_icon(c); - } else if let Some(c) = response.hover_pos().and_then(|p| crate::cam_transform::cursor(app, &ctx, &xf, p)) { + } else if let Some(c) = response.hover_pos().and_then(|p| crate::cam_transform::cursor(app, ctx, xf, p)) { ui.ctx().set_cursor_icon(c); } else if let Some(p) = response.hover_pos().filter(|p| crate::corner_radius::hovers(app, xf.to_doc(*p))) { // Over a live rectangle's corner widget (or dragging one): the arrow with a rounded // corner badge, as Photoshop's corner radius cursor. ui.ctx().set_cursor_icon(egui::CursorIcon::Default); - crate::icons::cursor_badge(&ctx, "scan", p); + crate::icons::cursor_badge(ctx, "scan", p); } else if let Some((r, p, c)) = response .hover_pos() .filter(|_| !transform_controls_several(app)) - .and_then(|p| transform_controls_rect(app, &xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c)))) + .and_then(|p| transform_controls_rect(app, xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c)))) { // The Move tool draws handles without opening a Free Transform session. // Give them their resize/rotate cursors before the first pointer press (#2871). ui.ctx().set_cursor_icon(c); if let Some(toward) = transform_controls_turn(r, p) { - crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + crate::crop_ui::draw_turn_cursor(ctx, p, toward); } } else if let Some(c) = response.hover_pos().filter(|_| tool.is_type()).and_then(|p| { let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - crate::type_transform::cursor(app, &ctx, &xf, p, mods) + crate::type_transform::cursor(app, ctx, xf, p, mods) }) { ui.ctx().set_cursor_icon(c); - } else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Artboard).and_then(|p| crate::artboard_tool::cursor(app, &xf, xf.to_doc(p))) { + } else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Artboard).and_then(|p| crate::artboard_tool::cursor(app, xf, xf.to_doc(p))) { ui.ctx().set_cursor_icon(c); } else if let Some((p, c)) = response.hover_pos().filter(|_| tool == Tool::Crop).and_then(|p| Some((p, crate::crop_ui::cursor(app, xf.to_doc(p))?))) { ui.ctx().set_cursor_icon(c); let d = xf.to_doc(p); if let Some(k) = crate::crop_ui::turn_cursor_dir(app, d) { let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; - crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + crate::crop_ui::draw_turn_cursor(ctx, p, toward); } } else if let Some(p) = response.hover_pos() && let Some(c) = selection_cursor(app, tool, xf.to_doc(p), crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))) @@ -1418,7 +1418,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & let alt = ui.input(|i| i.modifiers.alt); if !resizing && !alt && !app.ui.shell.sticky_alt { - draw_clone_preview(app, &painter, &xf, xf.to_doc(p), output); + draw_clone_preview(app, painter, xf, xf.to_doc(p), output); } // The Type tool over a path shows Photoshop's area-type or type-on-a-path pointer (#218). // Not while a type edit is open or a text box is dragged out, nor over type a click @@ -1441,7 +1441,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & && alt_samples(t, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)))) => { // While it samples (button held), the comparison ring replaces the cursor (#213). - if let Some(icon) = eyedropper_ring(app, &painter, &xf, p, response.is_pointer_button_down_on()) { + if let Some(icon) = eyedropper_ring(app, painter, xf, p, response.is_pointer_button_down_on()) { icon } else if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { egui::CursorIcon::Crosshair @@ -1456,15 +1456,15 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & let cur = app.session.prefs().cursors.clone(); // ⇪ forces the precise crosshair, whatever the cursor preference (#1758). if app.caps_lock { - crate::tool_cursor::crosshair(&painter, p, 6.0, 0.0) + crate::tool_cursor::crosshair(painter, p, 6.0, 0.0) } else { let painting = app.drag.is_some(); let brush = &app.session.tools.brush; let full = (brush.size / 2.0 * xf.zoom).max(1.0); match cur.painting { PaintingCursor::Standard => egui::CursorIcon::Default, - PaintingCursor::Precise => crate::tool_cursor::crosshair(&painter, p, 6.0, 0.0), - _ if painting && cur.show_only_crosshair_while_painting => crate::tool_cursor::crosshair(&painter, p, 5.0, 0.0), + PaintingCursor::Precise => crate::tool_cursor::crosshair(painter, p, 6.0, 0.0), + _ if painting && cur.show_only_crosshair_while_painting => crate::tool_cursor::crosshair(painter, p, 5.0, 0.0), // The Pencil (and the Eraser in Pencil mode): the outline of the // whole pixels its dab fills, on the pixel grid. A round tip is a // disc, a tiny one the whole square (#2662). The Block-mode Eraser: @@ -1473,7 +1473,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & let block = crate::eraser_ui::block_mode(app, tool); let size = if block { crate::eraser_ui::block_size(app) } else { brush.size }; let ppp = painter.ctx().pixels_per_point(); - let sq = pencil_cursor_rect(&xf, xf.to_doc(p), size, ppp); + let sq = pencil_cursor_rect(xf, xf.to_doc(p), size, ppp); let px = 1.0 / ppp; let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(230))); if !block && pencil_tip_is_round(size) { @@ -1486,7 +1486,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } // Too small to see where it is: the hotspot as well. if cur.show_crosshair_in_brush_tip || sq.width() < 6.0 { - crate::tool_cursor::crosshair(&painter, p, 4.0, 0.0); + crate::tool_cursor::crosshair(painter, p, 4.0, 0.0); } egui::CursorIcon::None } @@ -1495,8 +1495,8 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & // tip keeps the circle. _ => { let centre = brush_tip_centre(tool, alt || app.ui.shell.sticky_alt, cur.show_crosshair_in_brush_tip); - let axes = crate::brush_cursor::pen_axes(&xf, brush, app.stylus.sample()); - crate::brush_cursor::cursor(&painter, p, brush, full, axes, cur.painting == PaintingCursor::NormalTip, centre) + let axes = crate::brush_cursor::pen_axes(xf, brush, app.stylus.sample()); + crate::brush_cursor::cursor(painter, p, brush, full, axes, cur.painting == PaintingCursor::NormalTip, centre) } } } @@ -1504,7 +1504,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & // The Eyedropper: the comparison ring follows the pointer while it samples (#213); // otherwise its pipette, or the crosshair for precise Other Cursors. Tool::Eyedropper => { - if let Some(icon) = eyedropper_ring(app, &painter, &xf, p, response.is_pointer_button_down_on()) { + if let Some(icon) = eyedropper_ring(app, painter, xf, p, response.is_pointer_button_down_on()) { icon } else if precise_other_cursor(app) { egui::CursorIcon::Crosshair @@ -1535,7 +1535,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & crate::vector_ui::closes_path_at(app, tool, x, y) } => { - crate::tool_cursor::close_path(&painter, p) + crate::tool_cursor::close_path(painter, p) } // The pen tools: their own icon with its nib on the point, or the crosshair for // precise Other Cursors (#4639). @@ -1556,11 +1556,11 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & Tool::RotateView => crate::rotate_view::cursor(response.dragged()), Tool::Zoom => crate::tool_cursor::zoom(ui.ctx(), zoom_out(alt)), Tool::Type | Tool::VerticalType if type_path.is_some() => match type_path { - Some(crate::type_tool::PathClick::Area { .. }) => crate::tool_cursor::area_type(&painter, p), - _ => crate::tool_cursor::path_type(&painter, p), + Some(crate::type_tool::PathClick::Area { .. }) => crate::tool_cursor::area_type(painter, p), + _ => crate::tool_cursor::path_type(painter, p), }, Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => egui::CursorIcon::Text, - Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, &painter, p, xf.zoom), + Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, painter, p, xf.zoom), Tool::RedEye => { let pupil = app.ui.tool_options.red_eye_pupil_size.clamp(1.0, 100.0); let r_doc = photocraft_algo::redeye::search_radius(pupil); @@ -1575,17 +1575,164 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } _ => egui::CursorIcon::Crosshair, }; - let icon = visible_crosshair(icon, &painter, p, cfg!(not(target_arch = "wasm32"))); + let icon = visible_crosshair(icon, painter, p, cfg!(not(target_arch = "wasm32"))); ui.ctx().set_cursor_icon(icon); // Selection tools: + / − / × badge for the effective mode (#170). A gesture keeps the // mode it started with (⇧ then constrains the marquee instead of adding). let held = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); let mods = app.drag.as_ref().map_or(held, |d| d.modifiers); if let Some(b) = crate::tool_feedback::badge(app, tool, mods) { - crate::tool_feedback::draw_badge(&painter, p, b, tool == Tool::QuickSelection); + crate::tool_feedback::draw_badge(painter, p, b, tool == Tool::QuickSelection); } // ⇧ after a stroke: the straight line a click would paint (#257). - crate::stroke_constraint::draw_line_preview(app, &painter, &xf, p, tool, held.shift); + crate::stroke_constraint::draw_line_preview(app, painter, xf, p, tool, held.shift); +} + +struct CanvasTailInput<'a> { + ctx: &'a egui::Context, + painter: &'a egui::Painter, + response: &'a egui::Response, + doc: &'a std::sync::Arc, + xf: ViewXform, + rect: Rect, + full: Rect, + idx: usize, + primary: bool, + tool: Tool, + middle: bool, + flip: bool, + aspect: f32, + bars_id: egui::Id, + layer_edges: egui::layers::ShapeIdx, + camera: Option<([f32; 2], f32)>, +} + +fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, input: &CanvasTailInput<'_>) { + let ctx = input.ctx; + let painter = input.painter; + let response = input.response; + let doc = input.doc; + let xf = input.xf; + let rect = input.rect; + let full = input.full; + let idx = input.idx; + let primary = input.primary; + let tool = input.tool; + let middle = input.middle; + let flip = input.flip; + let aspect = input.aspect; + let bars_id = input.bars_id; + let layer_edges = input.layer_edges; + let camera = input.camera; + app.tool_override = None; + if let Some(b) = layer_edges_rect(app, idx) { + painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); + } + // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the + // drag's next move then extends into what scrolled in. + if primary + && app.drag.is_some() + && tool != Tool::Hand + && !middle + && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) + { + let step = crate::canvas_autoscroll::edge_step(p, rect, ui.input(|i| i.stable_dt)); + if crate::canvas_autoscroll::scroll(view, step, xf) { + ctx.request_repaint(); + } + } + // Scrollbars (scrollbars.rs): drawn over the canvas edges, they take the pointer there. + let t0 = crate::gpu_canvas::now_ms(); + let before = view.center; + let over_bars = app.ui.view.shows_scrollbars() + && crate::scrollbars::show(ui, rect, view, flip, aspect, app.session.prefs().tools.overscroll, egui::Id::unique(("pc-canvas", idx))); + ctx.data_mut(|d| d.insert_temp(bars_id, over_bars)); + if view.center != before { + ctx.request_repaint(); + } + if primary { + app.perf.span("scrollbars", crate::gpu_canvas::now_ms() - t0); + app.hover_doc = response.hover_pos().map(|p| xf.to_doc(p)); + } + if primary && app.ui.extras.rulers { + let before = app.guide_drag; + crate::rulers::draw_rulers(app, ui, full, &xf); + // A guide dragged out of a ruler moved after this frame drew it: draw it again where it is. + if app.guide_drag != before { + ctx.request_repaint(); + } + } else if app.ui.extras.rulers { + crate::rulers::paint_rulers(app, ui, full, &xf, doc); + } + // After the ruler drags above, so the readout shows where the guide is now, and not after a + // release ended the drag. + if app.session.active_index() == Some(idx) { + crate::rulers::draw_guide_drag_readout(app, ctx); + } + crate::rotate_view::overlay(app, ctx, painter, &xf, view, response); + if primary { + // Tool input can change the stored camera while navigation edits the local view. + // Merge changed camera values so write-back preserves tool-driven pan and rotation. + if let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) { + if now.center != center { + view.center = now.center; + ctx.request_repaint(); + } + if now.rotation != rotation { + view.rotation = now.rotation; + ctx.request_repaint(); + } + } + app.ui.views[idx] = (*view).clone(); + } +} + +/// A Properties Levels/Curves eyedropper (layer_picker.rs) owns the image until Esc or another +/// tool; Space and the middle button still pan. It samples on the press. +fn layer_picker_eyedropper(app: &mut PhotocraftApp, ui: &egui::Ui, ctx: &egui::Context, response: &egui::Response, xf: &ViewXform) { + if response.hovered() + && let Some(p) = ui.input(|i| i.pointer.hover_pos()) + { + 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 response.is_pointer_button_down_on() + && ui.input(|i| i.pointer.primary_pressed()) + && let Some(p) = ui.input(|i| i.pointer.interact_pos()) + { + let d = xf.to_doc(p); + crate::layer_picker::sample_at(app, d[0], d[1]); + } +} + +/// Per-frame reconciliation of the camera with its document: resize re-centre, pending fit/fill, +/// and the overscroll clamp. Returns the pixel aspect the view is drawn with. +fn sync_view_to_document(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, doc: &Document, rect: Rect, ppp: f32) -> f32 { + let size = [doc.size.width, doc.size.height]; + if view.doc_size != size { + // Like Photoshop: keep the zoom level, re-centre the resized document. + if view.doc_size != [0, 0] { + view.center = [size[0] as f32 / 2.0, size[1] as f32 / 2.0]; + } + view.doc_size = size; + } + // View › Pixel Aspect Ratio Correction: document pixels are shown this much wider. + let aspect = app.ui.view.display_aspect(); + if view.fit_pending && rect.width() > 50.0 { + fit_view(view, doc, rect.size(), ppp, aspect); + } + if view.fill_pending && rect.width() > 50.0 { + fill_view(view, doc, rect.size(), ppp, aspect); + } + // Preferences › Tools › Overscroll off: clamp before anything is drawn (scrollbars.rs). + if !app.session.prefs().tools.overscroll && crate::scrollbars::clamp_view_with_aspect(view, rect.size(), ppp, aspect) { + view.zoom_anchor = None; + ctx.request_repaint(); + } + aspect } pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View { @@ -1644,26 +1791,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } let doc = app.session.documents()[idx].doc.clone(); let size = [doc.size.width, doc.size.height]; - if view.doc_size != size { - // Like Photoshop: keep the zoom level, re-centre the resized document. - if view.doc_size != [0, 0] { - view.center = [size[0] as f32 / 2.0, size[1] as f32 / 2.0]; - } - view.doc_size = size; - } - // View › Pixel Aspect Ratio Correction: document pixels are shown this much wider. - let aspect = app.ui.view.display_aspect(); - if view.fit_pending && rect.width() > 50.0 { - fit_view(&mut view, &doc, rect.size(), ppp, aspect); - } - if view.fill_pending && rect.width() > 50.0 { - fill_view(&mut view, &doc, rect.size(), ppp, aspect); - } - // Preferences › Tools › Overscroll off: clamp before anything is drawn (scrollbars.rs). - if !app.session.prefs().tools.overscroll && crate::scrollbars::clamp_view_with_aspect(&mut view, rect.size(), ppp, aspect) { - view.zoom_anchor = None; - ctx.request_repaint(); - } + let aspect = sync_view_to_document(app, &ctx, &mut view, &doc, rect, ppp); let flip = app.ui.view.flip_horizontal; // Document rendering follows the target; only shader uniforms and overlay geometry ease. let target_xf = ViewXform { rect, zoom: view.zoom / ppp, center: view.center, flip, rotation: view.rotation, aspect }; @@ -1818,24 +1946,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // The tool cursors below are skipped while panning: the fist is set here (#2196). ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, true)); } else if primary && !stroke_dismissal && temporary.is_none() && !middle && crate::layer_picker::armed(app).is_some() { - // A Properties Levels/Curves eyedropper (layer_picker.rs) owns the image until Esc or another - // tool; Space and the middle button still pan. It samples on the press. - if response.hovered() - && let Some(p) = ui.input(|i| i.pointer.hover_pos()) - { - 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 response.is_pointer_button_down_on() - && ui.input(|i| i.pointer.primary_pressed()) - && let Some(p) = ui.input(|i| i.pointer.interact_pos()) - { - let d = xf.to_doc(p); - crate::layer_picker::sample_at(app, d[0], d[1]); - } + layer_picker_eyedropper(app, ui, &ctx, &response, &xf); } else if primary && !stroke_dismissal { let input = CanvasToolInput { ctx: &ctx, @@ -1897,67 +2008,25 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: }; paint_primary_overlays(app, ui, &mut view, &input); } - app.tool_override = None; - if let Some(b) = layer_edges_rect(app, idx) { - painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); - } - // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the - // drag's next move then extends into what scrolled in. - if primary - && app.drag.is_some() - && tool != Tool::Hand - && !middle - && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) - { - let step = crate::canvas_autoscroll::edge_step(p, rect, ui.input(|i| i.stable_dt)); - if crate::canvas_autoscroll::scroll(&mut view, step, xf) { - ctx.request_repaint(); - } - } - // Scrollbars (scrollbars.rs): drawn over the canvas edges, they take the pointer there. - let t0 = crate::gpu_canvas::now_ms(); - let before = view.center; - let over_bars = app.ui.view.shows_scrollbars() - && crate::scrollbars::show(ui, rect, &mut view, flip, aspect, app.session.prefs().tools.overscroll, egui::Id::unique(("pc-canvas", idx))); - ctx.data_mut(|d| d.insert_temp(bars_id, over_bars)); - if view.center != before { - ctx.request_repaint(); - } - if primary { - app.perf.span("scrollbars", crate::gpu_canvas::now_ms() - t0); - app.hover_doc = response.hover_pos().map(|p| xf.to_doc(p)); - } - if primary && app.ui.extras.rulers { - let before = app.guide_drag; - crate::rulers::draw_rulers(app, ui, full, &xf); - // A guide dragged out of a ruler moved after this frame drew it: draw it again where it is. - if app.guide_drag != before { - ctx.request_repaint(); - } - } else if app.ui.extras.rulers { - crate::rulers::paint_rulers(app, ui, full, &xf, &doc); - } - // After the ruler drags above, so the readout shows where the guide is now, and not after a - // release ended the drag. - if app.session.active_index() == Some(idx) { - crate::rulers::draw_guide_drag_readout(app, &ctx); - } - crate::rotate_view::overlay(app, &ctx, &painter, &xf, &mut view, &response); - if primary { - // Tool input can change the stored camera while navigation edits the local view. - // Merge changed camera values so write-back preserves tool-driven pan and rotation. - if let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) { - if now.center != center { - view.center = now.center; - ctx.request_repaint(); - } - if now.rotation != rotation { - view.rotation = now.rotation; - ctx.request_repaint(); - } - } - app.ui.views[idx] = view.clone(); - } + let tail = CanvasTailInput { + ctx: &ctx, + painter: &painter, + response: &response, + doc: &doc, + xf, + rect, + full, + idx, + primary, + tool, + middle, + flip, + aspect, + bars_id, + layer_edges, + camera, + }; + finish_canvas_view(app, ui, &mut view, &tail); view } diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 48f1ba9962..e03fa24e7a 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -146,7 +146,8 @@ 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) { +/// Brush family options share the same per-tool settings model. +fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, 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). @@ -257,103 +258,119 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, widgets::vline(ui, 22.0); widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers")); } + _ => {} + } +} + +/// Marquee tools: selection mode, feather, anti-alias, style and fixed size. +fn marquee_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + 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); +} + +/// Lasso family: selection mode, feather, anti-alias, magnetic settings and the drawing hints. +fn lasso_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + 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"))], + ), + ); + } +} + +/// Selection and paint tools expose their controls as a family of options rows. +fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) { + match app.ui.tool { 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); + marquee_options(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"))], - ), - ); - } + lasso_options(app, ui); } Tool::MagicWand => { selection_mode_buttons(app, ui); @@ -528,6 +545,42 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, } // 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), + _ => {} + } +} + +fn is_selection_options_tool(tool: Tool) -> bool { + matches!( + tool, + Tool::RectMarquee + | Tool::EllipseMarquee + | Tool::SingleRowMarquee + | Tool::SingleColumnMarquee + | Tool::Lasso + | Tool::PolygonLasso + | Tool::MagneticLasso + | Tool::MagicWand + | Tool::PaintBucket + | Tool::Gradient + | Tool::PerspectiveCrop + | Tool::Crop + | Tool::Type + | Tool::VerticalType + | Tool::HorizontalTypeMask + | Tool::VerticalTypeMask + ) +} + +fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, tool: Tool, b: &mut BrushSettings) { + if matches!(app.ui.tool, Tool::Brush | Tool::Eraser | Tool::Pencil | Tool::MixerBrush) { + brush_specific_options(app, ui, t, b); + return; + } + if is_selection_options_tool(app.ui.tool) { + selection_specific_options(app, ui, tool); + return; + } + match app.ui.tool { Tool::Move => { let o = &mut app.ui.tool_options; widgets::checkbox(ui, &mut o.move_auto_select, tl!("Auto-Select:")); From f2ac9d28b75423b1d1eb664a6a357cd65ec9cb0f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:06:43 +0000 Subject: [PATCH 28/35] Refactor ui-egui layer and channel panels for strict Clippy checks --- crates/ui-egui/src/panels/actions.rs | 37 +- crates/ui-egui/src/panels/channels_panel.rs | 416 ++++++++++++-------- crates/ui-egui/src/panels/layer_row.rs | 315 +++++++++------ 3 files changed, 470 insertions(+), 298 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 004d152185..33dddb9a39 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -956,22 +956,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if rows.is_empty() { ui.label(egui::RichText::new(tl!("Record ● a sequence of edits, then play ▶ it on any document.")).color(t.text_faint).size(11.5)); } - if egui::DragAndDrop::has_payload_of_type::(ui.ctx()) { - let clip = ui.clip_rect(); - if let Some(p) = ui.input(|i| i.pointer.hover_pos()).filter(|p| clip.contains(*p)) { - let delta = if p.y < clip.top() + 22.0 { - 8.0 - } else if p.y > clip.bottom() - 22.0 { - -8.0 - } else { - 0.0 - }; - if delta != 0.0 { - ui.scroll_with_delta(vec2(0.0, delta)); - ui.ctx().request_repaint(); - } - } - } + scroll_actions_during_drag(ui); let mut shown_set: Option<&str> = None; for i in display_order(&rows) { let Row { name, steps, disabled, dialogs, set, color: swatch } = &rows[i]; @@ -1164,6 +1149,26 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +fn scroll_actions_during_drag(ui: &mut egui::Ui) { + if !egui::DragAndDrop::has_payload_of_type::(ui.ctx()) { + return; + } + let clip = ui.clip_rect(); + let Some(pointer) = ui.input(|input| input.pointer.hover_pos()).filter(|p| clip.contains(*p)) else { return }; + let delta = if pointer.y < clip.top() + 22.0 { + 8.0 + } else if pointer.y > clip.bottom() - 22.0 { + -8.0 + } else { + 0.0 + }; + if delta == 0.0 { + return; + } + ui.scroll_with_delta(vec2(0.0, delta)); + ui.ctx().request_repaint(); +} + struct StepRowsContext<'a> { action: usize, x0: f32, diff --git a/crates/ui-egui/src/panels/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs index f073cf8f3c..90cd489542 100644 --- a/crates/ui-egui/src/panels/channels_panel.rs +++ b/crates/ui-egui/src/panels/channels_panel.rs @@ -46,6 +46,241 @@ pub fn load_operation(m: egui::Modifiers) -> &'static str { } } +struct RowPresentationContext<'a> { + doc: &'a photocraft_doc::Document, + view: &'a photocraft_engine::channel_cmds::ChannelView, + mode: photocraft_doc::ColorMode, + colors: usize, + gray_view: bool, + quick: bool, + mask_targeted: bool, + masked: Option<&'a photocraft_doc::Layer>, + shown_colors: usize, +} + +struct RowPresentation { + name: String, + thumb_idx: usize, + slot: Option, + visible: bool, + selected: bool, +} + +struct RowInteractions<'a> { + row: Row, + name: &'a str, + cell: Rect, + rect: Rect, + text_pos: egui::Pos2, + response: &'a egui::Response, + eye_response: &'a egui::Response, + ctx: &'a egui::Context, + doc: &'a photocraft_doc::Document, + masked: Option<&'a photocraft_doc::Layer>, + actions: &'a mut Vec<(String, Value)>, + mask_click: &'a mut Option, +} + +fn handle_row_interactions(ui: &mut egui::Ui, mut row: RowInteractions<'_>) { + let rename_id = egui::Id::unique(("chan-rename", row.doc.id.0, format!("{:?}", row.row.reference()))); + handle_channel_row_click(ui, &mut row); + handle_channel_row_double_click(ui, &mut row, rename_id); + row.response.context_menu(|ui| draw_row_menu(ui, row.row, row.doc, row.masked, row.actions)); +} + +fn handle_channel_row_click(ui: &egui::Ui, row: &mut RowInteractions<'_>) { + if !row.response.clicked() || row.eye_response.clicked() { + return; + } + let modifiers = ui.input(|input| input.modifiers); + if modifiers.command { + let channel = if row.row == Row::LayerMask { json!("mask") } else { row.row.reference() }; + let layer = row.masked.map(|layer| layer.id.0); + let operation = load_operation(modifiers); + let params = if row.row == Row::LayerMask { + json!({ "channel": channel, "layer": layer, "operation": operation }) + } else { + json!({ "channel": channel, "operation": operation }) + }; + row.actions.push(("select.loadSelection".into(), params)); + return; + } + if row.row == Row::LayerMask { + *row.mask_click = Some(true); + row.actions.push(("channel.target".into(), json!({ "channel": "mask" }))); + return; + } + if matches!(row.row, Row::Composite | Row::Color(_)) { + *row.mask_click = Some(false); + } + let target = if row.row == Row::QuickMask { json!("composite") } else { row.row.reference() }; + row.actions.push(("channel.target".into(), json!({ "channel": target }))); +} + +fn handle_channel_row_double_click(ui: &mut egui::Ui, row: &mut RowInteractions<'_>, rename_id: egui::Id) { + let on_thumb = row.response.interact_pointer_pos().is_some_and(|p| p.x < row.cell.right() + 4.0); + match row.row { + Row::QuickMask if row.response.double_clicked() => row.actions.push(("ui.channelOptions".into(), json!("quickMask"))), + Row::LayerMask if row.response.double_clicked() => row.actions.push(("ui.channelOptions".into(), json!("mask"))), + Row::Alpha(index) => { + handle_alpha_double_click(ui, row, index, on_thumb, rename_id); + } + _ => {} + } +} + +fn handle_alpha_double_click(ui: &mut egui::Ui, row: &mut RowInteractions<'_>, index: usize, on_thumb: bool, rename_id: egui::Id) { + if row.response.double_clicked() { + if on_thumb { + row.actions.push(("ui.channelOptions".into(), json!(index))); + } else { + row.ctx.data_mut(|data| data.insert_temp(rename_id, row.name.to_owned())); + } + } + let Some(mut text) = row.ctx.data(|data| data.get_temp::(rename_id)) else { return }; + let edit_rect = Rect::from_min_max(pos2(row.text_pos.x - 3.0, row.rect.center().y - 11.0), pos2(row.rect.right() - 36.0, row.rect.center().y + 11.0)); + let edit = ui.put(edit_rect, egui::TextEdit::singleline(&mut text).font(egui::FontId::proportional(12.5))).accessible_name(tl!("Name")); + if !edit.has_focus() && !edit.lost_focus() { + edit.request_focus(); + } + let (enter, escape) = ui.input(|input| (input.key_pressed(egui::Key::Enter), input.key_pressed(egui::Key::Escape))); + if escape || enter || edit.lost_focus() { + row.ctx.data_mut(|data| data.remove::(rename_id)); + if !escape && !text.trim().is_empty() && text != row.name { + row.actions.push(("channel.rename".into(), json!({ "channel": index, "name": text.trim() }))); + } + } else { + row.ctx.data_mut(|data| data.insert_temp(rename_id, text)); + } +} + +fn draw_row_menu(ui: &mut egui::Ui, row: Row, doc: &photocraft_doc::Document, masked: Option<&photocraft_doc::Layer>, actions: &mut Vec<(String, Value)>) { + crate::widgets::menu_scroll(ui, |ui| { + ui.set_min_width(210.0); + match row { + Row::Alpha(index) => draw_alpha_menu(ui, index, &doc.channels[index], actions), + Row::QuickMask => draw_quick_mask_menu(ui, doc, actions), + Row::Composite | Row::Color(_) => item(ui, actions, "Duplicate Channel", "channel.duplicate", json!({ "channel": row.reference() })), + Row::LayerMask => draw_mask_menu(ui, masked, actions), + } + ui.separator(); + item(ui, actions, "New Channel…", "channel.new", json!({})); + item(ui, actions, "New Spot Channel…", "ui.newSpotChannel", json!({})); + ui.separator(); + item(ui, actions, "Split Channels", "channel.split", json!({})); + item(ui, actions, "Merge Channels…", "channel.merge", json!({})); + }); +} + +fn draw_alpha_menu(ui: &mut egui::Ui, index: usize, channel: &photocraft_doc::AlphaChannel, actions: &mut Vec<(String, Value)>) { + item(ui, actions, "Duplicate Channel", "channel.duplicate", json!({ "channel": index })); + item(ui, actions, "Delete Channel", "channel.delete", json!({ "channel": index })); + item(ui, actions, "Rename Channel…", "ui.renameChannel", json!(index)); + item(ui, actions, "Channel Options…", "ui.channelOptions", json!(index)); + ui.separator(); + if channel.spot.is_some() { + item(ui, actions, "Merge Spot Channel", "channel.mergeSpot", json!({ "channel": index })); + item(ui, actions, "Convert to Alpha Channel", "channel.options", json!({ "channel": index, "indicates": "masked" })); + } else { + indicates_items(ui, actions, json!(index), channel.indicates); + overlay_colors(ui, actions, json!(index)); + } +} + +fn draw_quick_mask_menu(ui: &mut egui::Ui, doc: &photocraft_doc::Document, actions: &mut Vec<(String, Value)>) { + item(ui, actions, "Exit Quick Mask", "select.editInQuickMaskMode", json!({ "on": false })); + item(ui, actions, "Quick Mask Options…", "ui.channelOptions", json!("quickMask")); + indicates_items(ui, actions, json!("quickMask"), doc.quick_mask.as_ref().map(|mask| mask.indicates).unwrap_or_default()); + overlay_colors(ui, actions, json!("quickMask")); +} + +fn draw_mask_menu(ui: &mut egui::Ui, masked: Option<&photocraft_doc::Layer>, actions: &mut Vec<(String, Value)>) { + let enabled = masked.and_then(|layer| layer.mask.as_ref()).is_none_or(|mask| mask.enabled); + item(ui, actions, crate::layer_menu_ui::mask_toggle_label(enabled), "layer.layerMask.enabled", json!({})); + item(ui, actions, "Delete Layer Mask", "layer.layerMask.delete", json!({})); + item(ui, actions, "Layer Mask Display Options…", "ui.channelOptions", json!("mask")); +} + +/// The slot a channel dragged over `row` would take (0 = first alpha) and where its line goes. +fn drop_insertion(row: Row, pointer_y: f32, rect: Rect, alpha_count: usize) -> (usize, f32) { + match row { + Row::Alpha(j) if pointer_y < rect.center().y => (j, rect.top()), + Row::Alpha(j) => (j + 1, rect.bottom()), + Row::QuickMask => (alpha_count, rect.top()), + // Above the alpha channels: Photoshop puts it first among them. + Row::Composite | Row::Color(_) | Row::LayerMask => (0, f32::NAN), + } +} + +/// What clicking `row`'s eye asks for. +fn eye_action(row: Row, visible: bool, gray_view: bool, layer_id: Option) -> (String, Value) { + let view_cmd = photocraft_engine::mask_view_cmds::ID.to_string(); + match row { + // The mask's eye: the overlay on, or the mask view off. + Row::LayerMask => (view_cmd, json!({ "layer": layer_id, "mode": if visible { "off" } else { "overlay" } })), + // Showing the composite again over a gray mask view keeps the mask as an overlay. + Row::Composite if gray_view => (view_cmd, json!({ "layer": layer_id, "mode": "overlay" })), + _ => ("channel.setVisible".into(), json!({ "channel": row.reference(), "visible": !visible })), + } +} + +fn paint_row_background(painter: &egui::Painter, t: &Tokens, rect: Rect, selected: bool, hovered: bool) { + let radius = if t.pro { 0.0 } else { t.radius }; + if selected { + painter.rect_filled(rect, radius, if t.pro { t.row_selected } else { t.hover }); + } else if hovered { + painter.rect_filled(rect, radius, t.hover.gamma_multiply(0.5)); + } + if t.pro { + painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); + painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); + } +} + +/// Spot channels: a swatch of the ink on the thumbnail corner. +fn paint_spot_swatch(painter: &egui::Painter, thumb: Rect, spot: Option<(photocraft_doc::Color, f32)>) { + let Some((ink, _)) = spot else { return }; + let c = ink.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8); + painter.rect_filled(Rect::from_min_size(thumb.right_bottom() - vec2(9.0, 9.0), vec2(9.0, 9.0)), 0.0, Color32::from_rgb(c[0], c[1], c[2])); +} + +fn row_presentation(row: Row, context: &RowPresentationContext<'_>, mask_visible: bool) -> RowPresentation { + let (name, thumb_idx, slot, visible, selected) = match row { + Row::Composite => ( + channel_cmds::composite_name(context.mode).to_string(), + 0, + Some(2), + context.view.visible_colors(context.colors) == context.colors && !context.gray_view, + context.view.target == ChannelTarget::Composite && !context.quick && !context.mask_targeted, + ), + Row::Color(k) => ( + channel_cmds::color_names(context.mode)[k].to_string(), + 1 + k, + Some(3 + k), + context.view.color_visible(k) && !context.gray_view, + (context.view.target == ChannelTarget::Composite && !context.quick && !context.mask_targeted) || context.view.target == ChannelTarget::Color(k), + ), + Row::Alpha(i) => ( + context.doc.channels[i].name.clone(), + 1 + context.shown_colors + i, + Some(3 + context.shown_colors + i).filter(|s| *s <= 9), + context.view.alpha_shown(i), + context.view.target == ChannelTarget::Alpha(i), + ), + Row::QuickMask => ( + "Quick Mask".to_string(), + 1 + context.shown_colors + context.doc.channels.len(), + None, + !context.view.quick_mask_hidden, + context.view.target == ChannelTarget::Composite, + ), + Row::LayerMask => { + (context.masked.map_or_else(String::new, |layer| format!("{} Mask", layer.name)), usize::MAX, None, mask_visible, context.mask_targeted) + } + }; + RowPresentation { name, thumb_idx, slot, visible, selected } +} + pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { @@ -101,40 +336,13 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let pointer = ctx.input(|i| i.pointer.interact_pos()); let released = ctx.input(|i| i.pointer.any_released()); let alpha_count = doc.channels.len(); + let row_context = RowPresentationContext { doc: &doc, view: &view, mode, colors, gray_view, quick, mask_targeted, masked, shown_colors }; // The slot the dragged channel would take (0 = first alpha) and where its line goes. let mut insertion: Option<(usize, f32)> = None; let mut alphas_top: Option = None; egui::ScrollArea::vertical().max_height(rows_h).min_scrolled_height(if fill { rows_h } else { 0.0 }).auto_shrink([false, !fill]).show(ui, |ui| { for row in rows { - let (name, thumb_idx, slot, visible, selected) = match row { - Row::Composite => ( - channel_cmds::composite_name(mode).to_string(), - 0, - Some(2), - view.visible_colors(colors) == colors && !gray_view, - view.target == ChannelTarget::Composite && !quick && !mask_targeted, - ), - Row::Color(k) => ( - channel_cmds::color_names(mode)[k].to_string(), - 1 + k, - Some(3 + k), - view.color_visible(k) && !gray_view, - (view.target == ChannelTarget::Composite && !quick && !mask_targeted) || view.target == ChannelTarget::Color(k), - ), - Row::Alpha(i) => ( - doc.channels[i].name.clone(), - 1 + shown_colors + i, - Some(3 + shown_colors + i).filter(|s| *s <= 9), - view.alpha_shown(i), - view.target == ChannelTarget::Alpha(i), - ), - Row::QuickMask => { - ("Quick Mask".to_string(), 1 + shown_colors + doc.channels.len(), None, !view.quick_mask_hidden, view.target == ChannelTarget::Composite) - } - Row::LayerMask => { - (masked.as_ref().map(|l| format!("{} Mask", l.name)).unwrap_or_default(), usize::MAX, None, mask_view.is_some(), mask_targeted) - } - }; + let RowPresentation { name, thumb_idx, slot, visible, selected } = row_presentation(row, &row_context, mask_view.is_some()); let row_h = if t.pro { 36.0 } else { 40.0 }; let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click_and_drag()); if let Row::Alpha(0) = row { @@ -143,27 +351,13 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if dragged_alpha.is_some() && let Some(p) = pointer.filter(|p| rect.contains(*p)) { - insertion = match row { - Row::Alpha(j) if p.y < rect.center().y => Some((j, rect.top())), - Row::Alpha(j) => Some((j + 1, rect.bottom())), - Row::QuickMask => Some((alpha_count, rect.top())), - // Above the alpha channels: Photoshop puts it first among them. - Row::Composite | Row::Color(_) | Row::LayerMask => Some((0, f32::NAN)), - }; + insertion = Some(drop_insertion(row, p.y, rect, alpha_count)); } if resp.drag_started() { ctx.data_mut(|d| d.insert_temp(drag_id(), (row, name.clone()))); } let painter = ui.painter_at(rect.expand(1.0)); - if selected { - painter.rect_filled(rect, if t.pro { 0.0 } else { t.radius }, if t.pro { t.row_selected } else { t.hover }); - } else if resp.hovered() { - painter.rect_filled(rect, if t.pro { 0.0 } else { t.radius }, t.hover.gamma_multiply(0.5)); - } - if t.pro { - painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); - painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); - } + paint_row_background(&painter, &t, rect, selected, resp.hovered()); let eye = Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 11.0), vec2(22.0, 22.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("chan-eye", format!("{:?}", row.reference()))), Sense::click()); // Like Photoshop, the temporary mask row's eye is empty until the mask is shown. @@ -174,14 +368,7 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { eye_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Visibility {name}"))); let layer_id = masked.as_ref().map(|l| l.id.0); if eye_resp.clicked() { - let view_cmd = photocraft_engine::mask_view_cmds::ID.to_string(); - match row { - // The mask's eye: the overlay on, or the mask view off. - Row::LayerMask => actions.push((view_cmd, json!({ "layer": layer_id, "mode": if visible { "off" } else { "overlay" } }))), - // Showing the composite again over a gray mask view keeps the mask as an overlay. - Row::Composite if gray_view => actions.push((view_cmd, json!({ "layer": layer_id, "mode": "overlay" }))), - _ => actions.push(("channel.setVisible".into(), json!({ "channel": row.reference(), "visible": !visible }))), - } + actions.push(eye_action(row, visible, gray_view, layer_id)); } let ts = if t.pro { 28.0 } else { 30.0 }; let cell = Rect::from_min_size(pos2(rect.left() + 36.0, rect.center().y - ts / 2.0), vec2(ts, ts)); @@ -195,11 +382,8 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Rows are painted: name them for screen readers and UI tests. resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &name)); // Spot channels: a swatch of the ink on the thumbnail corner. - if let Row::Alpha(i) = row - && let Some((ink, _)) = doc.channels[i].spot - { - let c = ink.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8); - painter.rect_filled(Rect::from_min_size(thumb.right_bottom() - vec2(9.0, 9.0), vec2(9.0, 9.0)), 0.0, Color32::from_rgb(c[0], c[1], c[2])); + if let Row::Alpha(i) = row { + paint_spot_swatch(&painter, thumb, doc.channels[i].spot); } painter.rect_stroke(thumb, 0.0, Stroke::new(1.0, if t.pro { Color32::from_gray(20) } else { t.field_border }), StrokeKind::Outside); let italic = matches!(row, Row::QuickMask | Row::LayerMask) || matches!(row, Row::Alpha(i) if doc.channels[i].spot.is_some()); @@ -223,105 +407,23 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { t.text_faint, ); } - let rename_id = egui::Id::unique(("chan-rename", doc.id.0, format!("{:?}", row.reference()))); - if resp.clicked() && !eye_resp.clicked() { - let m = ui.input(|i| i.modifiers); - if m.command && row == Row::LayerMask { - let layer = masked.as_ref().map(|l| l.id.0); - actions.push(("select.loadSelection".into(), json!({ "channel": "mask", "layer": layer, "operation": load_operation(m) }))); - } else if m.command { - actions.push(("select.loadSelection".into(), json!({ "channel": row.reference(), "operation": load_operation(m) }))); - } else if row == Row::LayerMask { - // Targets the mask, as clicking its thumbnail in the Layers panel does. - mask_click = Some(true); - actions.push(("channel.target".into(), json!({ "channel": "mask" }))); - } else { - if matches!(row, Row::Composite | Row::Color(_)) { - mask_click = Some(false); - } - let target = if row == Row::QuickMask { json!("composite") } else { row.reference() }; - actions.push(("channel.target".into(), json!({ "channel": target }))); - } - } - // Like Photoshop: double-clicking the thumbnail opens Channel Options (where an alpha - // channel becomes a spot channel, #3761), double-clicking the name renames it. - let on_thumb = resp.interact_pointer_pos().is_some_and(|p| p.x < cell.right() + 4.0); - if row == Row::QuickMask && resp.double_clicked() { - actions.push(("ui.channelOptions".into(), json!("quickMask"))); - } - // The layer mask's row: Layer Mask Display Options (the rubylith's colour, opacity). - if row == Row::LayerMask && resp.double_clicked() { - actions.push(("ui.channelOptions".into(), json!("mask"))); - } - if let Row::Alpha(i) = row { - if resp.double_clicked() && on_thumb { - actions.push(("ui.channelOptions".into(), json!(i))); - } else if resp.double_clicked() { - ctx.data_mut(|d| d.insert_temp(rename_id, name.clone())); - } - if let Some(mut text) = ctx.data(|d| d.get_temp::(rename_id)) { - let edit_rect = Rect::from_min_max(pos2(text_pos.x - 3.0, rect.center().y - 11.0), pos2(rect.right() - 36.0, rect.center().y + 11.0)); - let te = ui.put(edit_rect, egui::TextEdit::singleline(&mut text).font(egui::FontId::proportional(12.5))).accessible_name(tl!("Name")); - if !te.has_focus() && !te.lost_focus() { - te.request_focus(); - } - let (enter, esc) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape))); - if esc { - ctx.data_mut(|d| d.remove::(rename_id)); - } else if enter || te.lost_focus() { - ctx.data_mut(|d| d.remove::(rename_id)); - if !text.trim().is_empty() && text != name { - actions.push(("channel.rename".into(), json!({ "channel": i, "name": text.trim() }))); - } - } else { - ctx.data_mut(|d| d.insert_temp(rename_id, text)); - } - } - } - resp.context_menu(|ui| { - crate::widgets::menu_scroll(ui, |ui| { - ui.set_min_width(210.0); - let a = &mut actions; - match row { - Row::Alpha(i) => { - let ch = &doc.channels[i]; - item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": i })); - item(ui, a, "Delete Channel", "channel.delete", json!({ "channel": i })); - item(ui, a, "Rename Channel…", "ui.renameChannel", json!(i)); - item(ui, a, "Channel Options…", "ui.channelOptions", json!(i)); - ui.separator(); - if ch.spot.is_some() { - item(ui, a, "Merge Spot Channel", "channel.mergeSpot", json!({ "channel": i })); - item(ui, a, "Convert to Alpha Channel", "channel.options", json!({ "channel": i, "indicates": "masked" })); - } else { - indicates_items(ui, a, json!(i), ch.indicates); - overlay_colors(ui, a, json!(i)); - } - } - Row::QuickMask => { - item(ui, a, "Exit Quick Mask", "select.editInQuickMaskMode", json!({ "on": false })); - item(ui, a, "Quick Mask Options…", "ui.channelOptions", json!("quickMask")); - indicates_items(ui, a, json!("quickMask"), doc.quick_mask.as_ref().map(|q| q.indicates).unwrap_or_default()); - overlay_colors(ui, a, json!("quickMask")); - } - Row::Composite | Row::Color(_) => { - item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": row.reference() })); - } - Row::LayerMask => { - let enabled = masked.as_ref().and_then(|l| l.mask.as_ref()).is_none_or(|m| m.enabled); - item(ui, a, crate::layer_menu_ui::mask_toggle_label(enabled), "layer.layerMask.enabled", json!({})); - item(ui, a, "Delete Layer Mask", "layer.layerMask.delete", json!({})); - item(ui, a, "Layer Mask Display Options…", "ui.channelOptions", json!("mask")); - } - } - ui.separator(); - item(ui, a, "New Channel…", "channel.new", json!({})); - item(ui, a, "New Spot Channel…", "ui.newSpotChannel", json!({})); - ui.separator(); - item(ui, a, "Split Channels", "channel.split", json!({})); - item(ui, a, "Merge Channels…", "channel.merge", json!({})); - }); - }); + handle_row_interactions( + ui, + RowInteractions { + row, + name: &name, + cell, + rect, + text_pos, + response: &resp, + eye_response: &eye_resp, + ctx: &ctx, + doc: &doc, + masked, + actions: &mut actions, + mask_click: &mut mask_click, + }, + ); } if let (Some(from), Some((slot, y))) = (dragged_alpha, insertion) { let y = if y.is_nan() { alphas_top.unwrap_or(y) } else { y }; diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index 5f182c13a5..6bc0ac85b2 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -159,51 +159,9 @@ pub(super) fn layer_row( if resp.hovered() { app.hover_layer = Some(l.id); } - if t.pro { - if selected { - painter.rect_filled(rect, 0.0, t.row_selected); - } else if is_hovered { - painter.rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); - painter.rect_filled(rect, 0.0, t.accent.gamma_multiply(0.12)); - } - } else if selected { - painter.rect_filled(rect, t.radius, t.hover); - painter.rect_stroke(rect, t.radius, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - } else if is_hovered { - painter.rect_filled(rect, t.radius, t.hover.gamma_multiply(0.5)); - painter.rect_filled(rect, t.radius, t.accent.gamma_multiply(0.12)); - } - let eye_cell = Rect::from_min_max(rect.left_top(), pos2((rect.left() + 30.0).min(rect.right()), rect.bottom())); - if let Some((_, background)) = t.layer_label_colors(l.label) { - painter.rect_filled(eye_cell, 0.0, background); - } - if t.pro { - // Paint dividers over the label so the eye column stays distinct. - painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); - painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); - } + paint_row_background(&painter, &t, l, rect, selected, is_hovered); let mut x = rect.left() + 6.0; - // The whole eye column takes drags too (so a drag starting on it never reorders the row): dragging down - // the eyes gives every row swept over the visibility the first eye toggled to (#8467). - let eye_resp = ui.interact(eye_cell, ui.scope_id().with(("eye", l.id.0)), Sense::click_and_drag()); - // A hidden layer's eye box is left empty (still clickable; the whole column takes the click, #8467). - if l.visible { - // Centre the drawing in the column while preserving the visibility hit area. - icons::paint(ui, eye_cell, "eye", 15.0, t.layer_label_icon(l.label)); - } - eye_sweep(ctx, l, rect, &eye_resp, actions); - if eye_resp.clicked() { - // ⌥-click shows only this layer; ⌥-click it again to restore the others. - if ui.input(|i| i.modifiers.alt) { - actions.push(("layer.showOnly".into(), json!({"layer": l.id.0}))); - } else { - actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "visible": !l.visible}))); - } - } - eye_resp.context_menu(|ui| { - crate::widgets::style_spectrum_popup_menu(ui); - crate::layer_menu_ui::color_choices(app, ui, l, row.multi && selected, actions); - }); + let eye_resp = eye_column(app, ui, l, row, rect, actions); // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes // the indentation first, then the thumbnails (a layer with two masks has three). let others = 6.0 @@ -230,25 +188,8 @@ pub(super) fn layer_row( } // With thumbnails disabled the labels and disclosure controls remain interactive. let masks = if ts > 0.0 { crate::mask_thumbs_ui::paint(app, ctx, ui, &painter, doc, l, &mut x, rect.center().y, ts, actions) } else { Default::default() }; - let mask_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Pixel); - let vector_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Vector); - // Photoshop frames the targeted thumbnail (pixels, mask or vector mask) of the active layer - // with corner brackets. - if row.primary && ts > 0.0 { - let target = if app.ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() { - // The Smart Filters row's filter mask thumbnail carries the brackets. - None - } else if app.ui.vector_mask_target && vector_rect.is_some() { - vector_rect - } else if app.ui.mask_target { - mask_rect.or(Some(thumb)) - } else { - Some(thumb) - }; - if let Some(r) = target { - crate::mask_thumbs_ui::paint_brackets(&painter, r, t.text); - } - } + let rc = RowCtx { l, doc, row, rect, ts, thumb, resp: &resp, masks: &masks }; + paint_target_brackets(app, &painter, &t, &rc); // Right-hand indicators first; the name gets what is left and ends in "…" (#144). let fx_open = app.session.active().is_none_or(|d| !d.fx_collapsed.contains(&l.id)); let (name_right, indicators, fx_toggled) = crate::layer_row_ui::indicators(ui, &painter, rect, x, l, fx_open, actions); @@ -266,26 +207,7 @@ pub(super) fn layer_row( { actions.push(simple_lock_toggle(doc.is_background(l.id), l, &json!({"layer": l.id.0}))); } - let name_color = if l.visible { t.text } else { t.text_faint }; - let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) }; - // Photoshop before 2026 set the Background layer's name in italics; 2026 sets it upright. - let italic = !t.pro && doc.is_background(l.id); - // Photoshop rows show only the name; the kind sub-label is a Studio-theme addition. - let is_pixel = t.pro || ts == 0.0 || matches!(l.content, LayerContent::Raster(_)); - let name_rect = crate::layer_row_ui::truncated(&painter, &l.name, font, name_color, italic, name_right - x).map(|galley| { - let text_pos = pos2(x, rect.center().y - galley.size().y / 2.0 - if is_pixel { 0.0 } else { 7.0 }); - let r = Rect::from_min_size(text_pos, galley.size()); - painter.galley(text_pos, galley, name_color); - r - }); - if !is_pixel { - let sub = match &l.content { - LayerContent::Adjustment(a) => tl!(a.label()).to_string(), - LayerContent::Group(g) => crate::i18n::trn(crate::i18n::current(), g.children.len() as u64, "Group · {n} layer", "Group · {n} layers"), - other => tl!(other.kind_name()).to_string(), - }; - crate::layer_row_ui::label(&painter, x, rect.center().y + 8.0, name_right, &sub, egui::FontId::proportional(11.0), t.text_faint); - } + let name_rect = paint_row_name(&painter, &t, &rc, x, name_right); crate::layer_row_ui::record( ctx, crate::layer_row_ui::RowRects { layer: l.id.0, row: rect, thumbnail: (ts > 0.0).then_some(thumb), name: name_rect, indicators }, @@ -321,43 +243,7 @@ pub(super) fn layer_row( } else if let Some(cmd) = mask_toggle { actions.push(cmd); } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked { - let m = ui.input(|i| i.modifiers); - let pos = resp.interact_pointer_pos(); - let on_thumb = ts > 0.0 && pos.is_some_and(|p| thumb.expand(2.0).contains(p)); - // ⌘-click on the Background thumbnail stands in for the plain click (there is no - // transparency to load): it selects the Background alone, not toggled into the set. - let mode = if m.command && on_thumb && doc.is_background(l.id) { "replace" } else { select_mode(m) }; - actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode}))); - crate::smart_ui::deselect(ctx, doc.id); - // A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row - // defaults to its mask, but clicking its content thumbnail must leave the mask target. - let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p)); - let on_vector = pos.and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Vector); - // Clicking the layer thumbnail leaves mask view (#196). - let viewing = app.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.layer == l.id); - if let Some(v) = viewing.filter(|_| on_thumb) { - let mask = if v.filter { "filter" } else { "layer" }; - actions.push((photocraft_engine::mask_view_cmds::ID.into(), json!({"layer": l.id.0, "mode": "off", "mask": mask}))); - } - let content_less = matches!(l.content, LayerContent::Adjustment(_) | LayerContent::Fill(_)); - if on_vector { - // The vector mask thumbnail targets the vector mask: the path tools edit it and the - // Paths panel selects the layer's path. - app.ui.selected_path = Some("layer".into()); - actions.push(("ui.vectorMaskTarget".into(), json!(true))); - } else if on_mask || (content_less && l.mask.is_some() && !on_thumb) { - if on_mask { - // The mask thumbnail also switches Properties to the mask (#3369). - app.ui.properties_layer = None; - } - actions.push(("ui.maskTarget".into(), json!(true))); - } else if on_thumb || !row.primary { - actions.push(("ui.maskTarget".into(), json!(false))); - } - // ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does. - if on_thumb && m.alt && !m.shift && !m.command { - actions.push(("view.fitLayersOnScreen".into(), Value::Null)); - } + select_row_on_click(app, ui, &rc, actions); } // Double-click: the name renames in place (over the row's full height, not just the glyphs: // #651); the Background, which can't be renamed while it's locked, becomes a normal layer; an @@ -365,6 +251,184 @@ pub(super) fn layer_row( // #2812) and a Smart Object thumbnail its contents, and a type thumbnail edits its text; // anywhere else on the row opens Layer Style (#350, #537). // The first click already made this the active layer. + handle_row_double_click(app, ui.ctx(), &rc, name_rect, actions); + let edit_rect = Rect::from_min_max(pos2(x - 3.0, rect.center().y - 11.0), pos2(name_right.max(x + 40.0), rect.center().y + 11.0)); + if let Some(done) = crate::layer_row_ui::rename_field(ui, l.id.0, edit_rect) { + actions.push(done); + } + row_context_menu(app, ui, &rc, &eye_resp, actions); + rect +} + +/// What the row helpers share once the row's thumbnails are laid out. +struct RowCtx<'a> { + l: &'a Layer, + doc: &'a photocraft_doc::Document, + row: RowSel, + rect: Rect, + ts: f32, + thumb: Rect, + resp: &'a egui::Response, + masks: &'a crate::mask_thumbs_ui::MaskRects, +} + +fn eye_cell(rect: Rect) -> Rect { + Rect::from_min_max(rect.left_top(), pos2((rect.left() + 30.0).min(rect.right()), rect.bottom())) +} + +/// The row's fill (selection / hover), the label colour behind the eye column and the pro dividers. +fn paint_row_background(painter: &egui::Painter, t: &Tokens, l: &Layer, rect: Rect, selected: bool, is_hovered: bool) { + if t.pro { + if selected { + painter.rect_filled(rect, 0.0, t.row_selected); + } else if is_hovered { + painter.rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); + painter.rect_filled(rect, 0.0, t.accent.gamma_multiply(0.12)); + } + } else if selected { + painter.rect_filled(rect, t.radius, t.hover); + painter.rect_stroke(rect, t.radius, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + } else if is_hovered { + painter.rect_filled(rect, t.radius, t.hover.gamma_multiply(0.5)); + painter.rect_filled(rect, t.radius, t.accent.gamma_multiply(0.12)); + } + let eye_cell = eye_cell(rect); + if let Some((_, background)) = t.layer_label_colors(l.label) { + painter.rect_filled(eye_cell, 0.0, background); + } + if t.pro { + // Paint dividers over the label so the eye column stays distinct. + painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); + painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); + } +} + +/// The eye column: visibility toggle (⌥ shows only this layer), sweep-drag and its colour menu. +fn eye_column(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, row: RowSel, rect: Rect, actions: &mut Vec<(String, Value)>) -> egui::Response { + let ctx = &ui.ctx().clone(); + let t = Tokens::get(ctx); + let selected = row.selected; + let eye_cell = eye_cell(rect); + // The whole eye column takes drags too (so a drag starting on it never reorders the row): dragging down + // the eyes gives every row swept over the visibility the first eye toggled to (#8467). + let eye_resp = ui.interact(eye_cell, ui.scope_id().with(("eye", l.id.0)), Sense::click_and_drag()); + // A hidden layer's eye box is left empty (still clickable; the whole column takes the click, #8467). + if l.visible { + // Centre the drawing in the column while preserving the visibility hit area. + icons::paint(ui, eye_cell, "eye", 15.0, t.layer_label_icon(l.label)); + } + eye_sweep(ctx, l, rect, &eye_resp, actions); + if eye_resp.clicked() { + // ⌥-click shows only this layer; ⌥-click it again to restore the others. + if ui.input(|i| i.modifiers.alt) { + actions.push(("layer.showOnly".into(), json!({"layer": l.id.0}))); + } else { + actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "visible": !l.visible}))); + } + } + eye_resp.context_menu(|ui| { + crate::widgets::style_spectrum_popup_menu(ui); + crate::layer_menu_ui::color_choices(app, ui, l, row.multi && selected, actions); + }); + eye_resp +} + +fn paint_target_brackets(app: &PhotocraftApp, painter: &egui::Painter, t: &Tokens, rc: &RowCtx<'_>) { + let (l, thumb) = (rc.l, rc.thumb); + let mask_rect = rc.masks.thumb(crate::mask_thumbs_ui::MaskKind::Pixel); + let vector_rect = rc.masks.thumb(crate::mask_thumbs_ui::MaskKind::Vector); + // Photoshop frames the targeted thumbnail (pixels, mask or vector mask) of the active layer + // with corner brackets. + if rc.row.primary && rc.ts > 0.0 { + let target = if app.ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() { + // The Smart Filters row's filter mask thumbnail carries the brackets. + None + } else if app.ui.vector_mask_target && vector_rect.is_some() { + vector_rect + } else if app.ui.mask_target { + mask_rect.or(Some(thumb)) + } else { + Some(thumb) + }; + if let Some(r) = target { + crate::mask_thumbs_ui::paint_brackets(painter, r, t.text); + } + } +} + +/// The layer name (and the kind sub-label of non-pixel rows); returns the name's rect. +fn paint_row_name(painter: &egui::Painter, t: &Tokens, rc: &RowCtx<'_>, x: f32, name_right: f32) -> Option { + let (l, doc, rect, ts, selected) = (rc.l, rc.doc, rc.rect, rc.ts, rc.row.selected); + let name_color = if l.visible { t.text } else { t.text_faint }; + let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) }; + // Photoshop before 2026 set the Background layer's name in italics; 2026 sets it upright. + let italic = !t.pro && doc.is_background(l.id); + // Photoshop rows show only the name; the kind sub-label is a Studio-theme addition. + let is_pixel = t.pro || ts == 0.0 || matches!(l.content, LayerContent::Raster(_)); + let name_rect = crate::layer_row_ui::truncated(painter, &l.name, font, name_color, italic, name_right - x).map(|galley| { + let text_pos = pos2(x, rect.center().y - galley.size().y / 2.0 - if is_pixel { 0.0 } else { 7.0 }); + let r = Rect::from_min_size(text_pos, galley.size()); + painter.galley(text_pos, galley, name_color); + r + }); + if !is_pixel { + let sub = match &l.content { + LayerContent::Adjustment(a) => tl!(a.label()).to_string(), + LayerContent::Group(g) => crate::i18n::trn(crate::i18n::current(), g.children.len() as u64, "Group · {n} layer", "Group · {n} layers"), + other => tl!(other.kind_name()).to_string(), + }; + crate::layer_row_ui::label(painter, x, rect.center().y + 8.0, name_right, &sub, egui::FontId::proportional(11.0), t.text_faint); + } + name_rect +} + +/// A plain click on the row: select the layer and retarget pixels / mask / vector mask. +fn select_row_on_click(app: &mut PhotocraftApp, ui: &egui::Ui, rc: &RowCtx<'_>, actions: &mut Vec<(String, Value)>) { + let (l, doc, resp, masks, row, ts, thumb) = (rc.l, rc.doc, rc.resp, rc.masks, rc.row, rc.ts, rc.thumb); + let ctx = ui.ctx(); + let mask_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Pixel); + let m = ui.input(|i| i.modifiers); + let pos = resp.interact_pointer_pos(); + let on_thumb = ts > 0.0 && pos.is_some_and(|p| thumb.expand(2.0).contains(p)); + // ⌘-click on the Background thumbnail stands in for the plain click (there is no + // transparency to load): it selects the Background alone, not toggled into the set. + let mode = if m.command && on_thumb && doc.is_background(l.id) { "replace" } else { select_mode(m) }; + actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode}))); + crate::smart_ui::deselect(ctx, doc.id); + // A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row + // defaults to its mask, but clicking its content thumbnail must leave the mask target. + let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p)); + let on_vector = pos.and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Vector); + // Clicking the layer thumbnail leaves mask view (#196). + let viewing = app.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.layer == l.id); + if let Some(v) = viewing.filter(|_| on_thumb) { + let mask = if v.filter { "filter" } else { "layer" }; + actions.push((photocraft_engine::mask_view_cmds::ID.into(), json!({"layer": l.id.0, "mode": "off", "mask": mask}))); + } + let content_less = matches!(l.content, LayerContent::Adjustment(_) | LayerContent::Fill(_)); + if on_vector { + // The vector mask thumbnail targets the vector mask: the path tools edit it and the + // Paths panel selects the layer's path. + app.ui.selected_path = Some("layer".into()); + actions.push(("ui.vectorMaskTarget".into(), json!(true))); + } else if on_mask || (content_less && l.mask.is_some() && !on_thumb) { + if on_mask { + // The mask thumbnail also switches Properties to the mask (#3369). + app.ui.properties_layer = None; + } + actions.push(("ui.maskTarget".into(), json!(true))); + } else if on_thumb || !row.primary { + actions.push(("ui.maskTarget".into(), json!(false))); + } + // ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does. + if on_thumb && m.alt && !m.shift && !m.command { + actions.push(("view.fitLayersOnScreen".into(), Value::Null)); + } +} + +/// Double-click: rename, un-background, open the thumbnail's settings or the row's Layer Style. +fn handle_row_double_click(app: &mut PhotocraftApp, ctx: &egui::Context, rc: &RowCtx<'_>, name_rect: Option, actions: &mut Vec<(String, Value)>) { + let (l, doc, resp, masks, ts, thumb, rect) = (rc.l, rc.doc, rc.resp, rc.masks, rc.ts, rc.thumb, rc.rect); if resp.double_clicked() { let pos = resp.interact_pointer_pos(); let on = |r: Rect| pos.is_some_and(|p| r.expand(2.0).contains(p)); @@ -400,10 +464,12 @@ pub(super) fn layer_row( } } } - let edit_rect = Rect::from_min_max(pos2(x - 3.0, rect.center().y - 11.0), pos2(name_right.max(x + 40.0), rect.center().y + 11.0)); - if let Some(done) = crate::layer_row_ui::rename_field(ui, l.id.0, edit_rect) { - actions.push(done); - } +} + +/// The visibility icon has its own color menu, and the layer-mask thumbnail its mask menu (#4575). +fn row_context_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, rc: &RowCtx<'_>, eye_resp: &egui::Response, actions: &mut Vec<(String, Value)>) { + let (l, resp, masks, row) = (rc.l, rc.resp, rc.masks, rc.row); + let (ctx, selected) = (&ui.ctx().clone(), row.selected); // The visibility icon has its own color menu, and the layer-mask thumbnail its mask menu // (#4575); elsewhere use the full layer menu. let on_mask_id = ui.scope_id().with(("mask-menu", l.id.0)); @@ -427,7 +493,6 @@ pub(super) fn layer_row( } }); } - rect } /// Screen rect and UVs for a layer thumbnail: the document-shaped part of the square cell and of From 5ad52e6b85f7c66275aeb5110d2db95e1688ead3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:06:43 +0000 Subject: [PATCH 29/35] Remove duplicated view-command and type-target code in ui-egui --- crates/ui-egui/src/menus/invoke.rs | 3 --- crates/ui-egui/src/tools/type_tool/defaults.rs | 14 -------------- 2 files changed, 17 deletions(-) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index cf7529a439..a829dae69a 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -303,9 +303,6 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: if let Some(result) = invoke_view_command(app, ctx, id, ¶ms) { return result; } - if let Some(result) = invoke_view_command(app, ctx, id, ¶ms) { - return result; - } match id { "edit.search" => { app.ui.palette_open = !app.ui.palette_open; diff --git a/crates/ui-egui/src/tools/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs index 6c4b5a2ebe..203c3e9e93 100644 --- a/crates/ui-egui/src/tools/type_tool/defaults.rs +++ b/crates/ui-egui/src/tools/type_tool/defaults.rs @@ -219,20 +219,6 @@ pub(super) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, props: serde_j let _ = app.run("type.setStyle", p); } -/// `props` aimed at the type target: its layer, the selected characters while typing, and the -/// typing session's undo step. `None` without a type target. -pub(crate) fn with_target(app: &PhotocraftApp, mut props: serde_json::Value) -> Option { - let (layer, range) = target(app)?; - props["layer"] = json!(layer); - if let Some(r) = range { - props["range"] = json!(r); - } - if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()) { - props["coalesce"] = json!(key); - } - Some(props) -} - /// Open the shared Color Picker with a snapshot of the text target. Sampling or cancelling /// the dialog never changes the text selection, tool colours, or document history. pub fn open_color_picker(app: &mut PhotocraftApp, rgb: [f32; 3]) -> u64 { From a9fa2d46731c61c7984e21e649264ff8e4c7b0ed Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:06:43 +0000 Subject: [PATCH 30/35] Refactor photocraft app startup for strict Clippy checks --- apps/photocraft/src/main.rs | 262 ++++++++++++++++++++---------------- 1 file changed, 146 insertions(+), 116 deletions(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index a4fe847cda..d1a3b68d3b 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -193,6 +193,143 @@ fn at_least_min_size(mut builder: egui::ViewportBuilder) -> egui::ViewportBuilde builder } +/// Attach the log file under the settings directory. Called after the arguments are parsed, so +/// `--version` and usage errors leave no file behind. Records logged until now are written first. +fn attach_log_file(logger: Option<&'static logging::AppLogger>) { + if let (Some(logger), Some(dir)) = (logger, services::config_dir()) { + match logger.attach_dir(&dir.join("logs")) { + Ok(path) => log::info!("PhotoCraft {}, log file {}", photocraft_engine::build_info::long_version(), path.display()), + // Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics. + Err(e) => log::warn!("no log file: {e}"), + } + } +} + +/// One PhotoCraft per user (#3708). Only with the per-user settings folder (a portable copy's may +/// be shared between users), and not for automation, `--new-instance` or per-process options. +/// `Break` when the files were handed to the running PhotoCraft and this launch is done. +#[cfg(not(target_os = "macos"))] +fn claim_single_instance( + files: &[String], + new_instance: bool, + control: bool, + unreadable_paths: bool, + mut launch_options: Vec, +) -> std::ops::ControlFlow<(), Option> { + use std::ops::ControlFlow::{Break, Continue}; + let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok(); + // A variable documented as the equivalent of a per-launch flag counts as that flag: a + // launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it + // keeps its own process instead of handing its files over and being ignored. + launch_options.extend_from_slice(&single_instance::env_launch_options()); + let context = single_instance::LaunchContext { + per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform, + new_instance_flag: new_instance, + new_instance_env: new_instance_env.as_deref(), + control, + unreadable_paths, + launch_options: &launch_options, + }; + match (single_instance::skip_reason(&context), services::config_dir()) { + (Some(reason), _) => { + log::info!("running as a separate PhotoCraft: {reason}"); + Continue(None) + } + (None, None) => Continue(None), + (None, Some(dir)) => { + let paths: Vec = files.iter().map(|f| single_instance::absolute(f)).collect(); + match single_instance::claim(&dir, &paths) { + single_instance::Launch::Forwarded => { + log::info!("handed {} file(s) to the running PhotoCraft", paths.len()); + Break(()) + } + single_instance::Launch::Primary(primary) => Continue(Some(primary)), + single_instance::Launch::Standalone(reason) => { + log::warn!("starting a separate PhotoCraft: {reason}"); + Continue(None) + } + } + } + } +} + +/// The display server to open the window on: Xwayland for a pen on Wayland, which gives this app +/// no pen input (#639). Exits with the package to install when its libraries are missing. +#[cfg(target_os = "linux")] +fn linux_display_session() -> linux_libs::DisplaySession { + let session = tablet::display_session(); + // Preferences › Performance › Linux display server = X11: Xwayland on a Wayland session too, + // where native file drops work (winit 0.30 has none on Wayland, #386). Only when Xwayland can + // run the window ($DISPLAY set, X11 libraries installed); otherwise the session's own. + let session = if session == linux_libs::DisplaySession::Wayland + && gpu_startup::read_display_server(services::prefs_file().as_deref()) == photocraft_engine::prefs::LinuxDisplayServer::X11 + && std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()) + && linux_libs::available(linux_libs::DisplaySession::X11) + { + eprintln!("photocraft: opening the window through Xwayland (Preferences › Performance › Linux display server)"); + linux_libs::DisplaySession::X11 + } else { + session + }; + // winit and wgpu dlopen the windowing and GPU libraries, and some of those crates panic when + // one is missing (issue #201). Name the package to install and exit instead. + if let Err(message) = linux_libs::preflight(session) { + eprint!("{message}"); + std::process::exit(1); + } + session +} + +/// The control server's port, token and workspace, when it is on (exits 2 on a bad configuration). +fn control_setup( + cli_port: Option, + auth: photocraft_automation::args::ControlArgs, + automation: &photocraft_automation::args::AutomationArgs, +) -> Option<(u16, String, photocraft_automation::workspace::AuthorizedWorkspace)> { + let (port, warning) = control_port_for(cli_port, &integrations(services::prefs_file().as_deref())); + if let Some(warning) = &warning { + eprint!("{warning}"); + } + let port = port?; + let (supplied, token_file) = (auth.control_token, auth.control_token_file); + let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) { + Ok(token) => token, + Err(e) => { + eprintln!("photocraft: cannot configure control authentication: {e}"); + std::process::exit(2); + } + }; + if let Some(path) = token_file { + eprintln!("photocraft: control token file: {}", path.display()); + } else if supplied.is_none() { + eprintln!("photocraft: control token: {token}"); + } else { + eprintln!("photocraft: using supplied control token"); + } + let workspace = match automation.workspace() { + Ok(workspace) => workspace, + Err(error) => { + eprintln!("photocraft: cannot configure automation workspace: {error}"); + std::process::exit(2); + } + }; + Some((port, token, workspace)) +} + +/// Record this start's backend in the GPU startup marker, if the marker is locked. +fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup::Plan) { + if let Some(s) = sentinel.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_mut() { + let backend = match &plan.env { + Some(v) => format!("env:{v}"), + None => plan.backend.name().to_string(), + }; + let marker = gpu_startup::Marker { backend, version: photocraft_engine::build_info::long_version().to_string(), ..Default::default() }; + if let Err(e) = s.write(marker) { + log::warn!("GPU startup marker: {e}"); + } + } +} + fn main() -> eframe::Result { // First, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); @@ -228,15 +365,7 @@ fn main() -> eframe::Result { mut launch_options, } = launch; - // The log file lives under the settings directory; opened after the arguments, so `--version` - // and usage errors leave no file behind. Records logged until now are written to it first. - if let (Some(logger), Some(dir)) = (logger, services::config_dir()) { - match logger.attach_dir(&dir.join("logs")) { - Ok(path) => log::info!("PhotoCraft {}, log file {}", photocraft_engine::build_info::long_version(), path.display()), - // Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics. - Err(e) => log::warn!("no log file: {e}"), - } - } + attach_log_file(logger); // An adapter named in the environment is chosen at startup, which a forwarded launch never reaches. let rendering_mode = gpu_startup::read_rendering_prefs(services::prefs_file().as_deref()).1; @@ -244,114 +373,24 @@ fn main() -> eframe::Result { launch_options.push(launch_args::PerProcess::GpuAdapterEnv); } // One PhotoCraft per user (#3708): files opened from Explorer or a file manager while it runs - // become tabs in its window. Only with the per-user settings folder (a portable copy's may be - // shared between users), and not for automation, `--new-instance` or per-process options. + // become tabs in its window. Lives until the event loop returns, then `shutdown` lets the next + // launch become the primary. #[cfg(not(target_os = "macos"))] - let single_instance = { - let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok(); - // A variable documented as the equivalent of a per-launch flag counts as that flag: a - // launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it - // keeps its own process instead of handing its files over and being ignored. - // Folded in here, inside the block that only non-macOS builds compile, so the binding - // above keeps its `mut` off macOS, where nothing is folded in. - let mut launch_options = launch_options; - launch_options.extend_from_slice(&single_instance::env_launch_options()); - let context = single_instance::LaunchContext { - per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform, - new_instance_flag: new_instance, - new_instance_env: new_instance_env.as_deref(), - control: control_port.is_some(), - unreadable_paths: !unreadable_paths.is_empty(), - launch_options: &launch_options, - }; - match (single_instance::skip_reason(&context), services::config_dir()) { - (Some(reason), _) => { - log::info!("running as a separate PhotoCraft: {reason}"); - None - } - (None, None) => None, - (None, Some(dir)) => { - let paths: Vec = files.iter().map(|f| single_instance::absolute(f)).collect(); - match single_instance::claim(&dir, &paths) { - single_instance::Launch::Forwarded => { - log::info!("handed {} file(s) to the running PhotoCraft", paths.len()); - return Ok(()); - } - single_instance::Launch::Primary(primary) => Some(primary), - single_instance::Launch::Standalone(reason) => { - log::warn!("starting a separate PhotoCraft: {reason}"); - None - } - } - } - } + let single_instance = match claim_single_instance(&files, new_instance, control_port.is_some(), !unreadable_paths.is_empty(), launch_options) { + std::ops::ControlFlow::Break(()) => return Ok(()), + std::ops::ControlFlow::Continue(primary) => primary, }; - // Lives until the event loop returns, then `shutdown` lets the next launch become the primary. #[cfg(not(target_os = "macos"))] let single_instance = &single_instance; #[cfg(target_os = "macos")] let _ = (new_instance, &launch_options); - // The display server to open the window on: Xwayland for a pen on Wayland, which gives this - // app no pen input (#639). #[cfg(target_os = "linux")] let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok()); #[cfg(target_os = "linux")] - let session = tablet::display_session(); - // Preferences › Performance › Linux display server = X11: Xwayland on a Wayland session too, - // where native file drops work (winit 0.30 has none on Wayland, #386). Only when Xwayland can - // run the window ($DISPLAY set, X11 libraries installed); otherwise the session's own. - #[cfg(target_os = "linux")] - let session = if session == linux_libs::DisplaySession::Wayland - && gpu_startup::read_display_server(services::prefs_file().as_deref()) == photocraft_engine::prefs::LinuxDisplayServer::X11 - && std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()) - && linux_libs::available(linux_libs::DisplaySession::X11) - { - eprintln!("photocraft: opening the window through Xwayland (Preferences › Performance › Linux display server)"); - linux_libs::DisplaySession::X11 - } else { - session - }; + let session = linux_display_session(); - // winit and wgpu dlopen the windowing and GPU libraries, and some of those crates panic when - // one is missing (issue #201). Name the package to install and exit instead. - #[cfg(target_os = "linux")] - if let Err(message) = linux_libs::preflight(session) { - eprint!("{message}"); - std::process::exit(1); - } - - let (control_port, control_pref_warning) = control_port_for(control_port, &integrations(services::prefs_file().as_deref())); - if let Some(warning) = &control_pref_warning { - eprint!("{warning}"); - } - let control = if let Some(port) = control_port { - let (supplied, token_file) = (auth.control_token, auth.control_token_file); - let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) { - Ok(token) => token, - Err(e) => { - eprintln!("photocraft: cannot configure control authentication: {e}"); - std::process::exit(2); - } - }; - if let Some(path) = token_file { - eprintln!("photocraft: control token file: {}", path.display()); - } else if supplied.is_none() { - eprintln!("photocraft: control token: {token}"); - } else { - eprintln!("photocraft: using supplied control token"); - } - let workspace = match automation.workspace() { - Ok(workspace) => workspace, - Err(error) => { - eprintln!("photocraft: cannot configure automation workspace: {error}"); - std::process::exit(2); - } - }; - Some((port, token, workspace)) - } else { - None - }; + let control = control_setup(control_port, auth, &automation); // Finder / Dock / Open With deliver files as Apple events, not arguments; catch the one that // launched us as well as later ones. Lives until the event loop returns. #[cfg(target_os = "macos")] @@ -409,16 +448,7 @@ fn main() -> eframe::Result { log::warn!("the previous start didn't finish (GPU backend {}, adapter {:?}); {}", m.backend, m.adapter, plan.reason.as_deref().unwrap_or("")); } let sentinel: gpu_startup::SharedSentinel = std::sync::Arc::new(std::sync::Mutex::new(sentinel)); - if let Some(s) = sentinel.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_mut() { - let backend = match &plan.env { - Some(v) => format!("env:{v}"), - None => plan.backend.name().to_string(), - }; - let marker = gpu_startup::Marker { backend, version: photocraft_engine::build_info::long_version().to_string(), ..Default::default() }; - if let Err(e) = s.write(marker) { - log::warn!("GPU startup marker: {e}"); - } - } + write_start_marker(&sentinel, &plan); let gpu_note: std::sync::Arc>> = Default::default(); // The adapter's real texture limits (egui asks for 8192 px), so big documents stay on the GPU. let wanted_adapter = From 1a3415608b92ed87872e1e1450ab34978b784fec Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:49:51 +0000 Subject: [PATCH 31/35] Restore the PSD frame stroke import after the io refactor --- crates/io/src/psd_import.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index de1ca2c7c3..5cdc63c454 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -710,7 +710,9 @@ impl Ctx<'_> { let sd = rec.section_divider(); let expanded = sd.is_none_or(|s| s.kind != photocraft_psd::SectionType::ClosedFolder); let artboard = crate::comps_map::ARTBOARD_KEYS.iter().find_map(|k| rec.block(k)).and_then(|b| crate::comps_map::parse_artboard(&b.data)); - let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard, frame_stroke: None })); + // A Photoshop Frame's stroke: `vstk` on the frame group, in a shape's layout. + let frame_stroke = rec.block(b"vstk").and_then(|b| crate::vector_map::parse_vstk(&b.data, self.dpi)).and_then(|v| v.stroke); + let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard, frame_stroke })); l.psd_blocks = preserved_blocks(rec); self.apply_common(&mut l, rec, sd.and_then(|s| s.blend_mode)); self.apply_vector_mask(&mut l, rec); From c726a14f0f3434aba493f6b068537861225633f6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 01:49:51 +0000 Subject: [PATCH 32/35] Restore the Animated Zoom hold gating in canvas navigation --- crates/ui-egui/src/canvas.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3da8e617da..5be4230fbb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -898,7 +898,7 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> fn handle_canvas_tool_navigation( app: &mut PhotocraftApp, - _ui: &mut egui::Ui, + ui: &mut egui::Ui, view: &mut View, input: &CanvasToolInput<'_>, buttons: &mut crate::paint_mouse::Buttons, @@ -927,8 +927,8 @@ fn handle_canvas_tool_navigation( // Animated Zoom: a Zoom press held still zooms continuously (zoom_hold.rs); while it does, // 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 = false; + let out = zoom_out(ui.input(|i| i.modifiers.alt)); + let on_canvas = !input.under_dialog && !over_compass && response.is_pointer_button_down_on(); let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); if crate::zoom_hold::update(ctx, 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); From 63eb3eabe41985350e81074305c571d521edc1bc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 02:13:42 +0000 Subject: [PATCH 33/35] Drop the unused band_rows export and its dead_code allow from io --- crates/io/src/flat.rs | 27 +-------------------------- crates/io/src/lib.rs | 4 ++-- 2 files changed, 3 insertions(+), 28 deletions(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index fd1ec54cf3..55f602a6e9 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -11,32 +11,7 @@ use photocraft_raster::Surface; use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed}; /// Bytes per band when converting or exporting a band of rows at a time. -pub const BAND_BYTES: usize = 32 << 20; - -/// Row ranges for bands covering a layer region, aligned to tile rows. -#[allow(dead_code)] -pub fn band_rows(top: i32, h: usize, row_bytes: usize) -> Vec<(usize, usize)> { - const MAX_BAND_BYTES: usize = 32 << 20; - let _top = top.max(0) as usize; - let row_bytes = row_bytes.max(1); - let h_rows = h; - let mut bands = Vec::new(); - let mut cursor = 0_usize; - while cursor < h_rows { - let remaining = h_rows - cursor; - let max_by_bytes = MAX_BAND_BYTES / row_bytes; - let candidate = std::cmp::max(1, std::cmp::min(remaining, max_by_bytes)); - let band_rows = if cursor == 0 || cursor.is_multiple_of(TILE_SIZE as usize) { - candidate - } else { - let tile_boundary = (TILE_SIZE as usize) - (cursor % (TILE_SIZE as usize)); - std::cmp::min(candidate, tile_boundary) - }; - bands.push((cursor, cursor + band_rows)); - cursor += band_rows; - } - bands -} +const BAND_BYTES: usize = 32 << 20; /// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens /// layered (see [`crate::tiff_layers`]). diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 77beb6cde2..0a184bda79 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -84,8 +84,8 @@ use photocraft_psd::{PsdError, PsdFile}; pub use adjust_map::ADJUSTMENT_KEYS; pub use flat::{ - BAND_BYTES, DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, band_rows, document_to_image, file_encoding, import_gif_frames, import_tiff_page, - import_webp_frames, tga_alpha_channel_to_transparency, tga_default_bits, + DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, document_to_image, file_encoding, import_gif_frames, import_tiff_page, import_webp_frames, + tga_alpha_channel_to_transparency, tga_default_bits, }; pub use psd_export::{PsdExportOptions, document_to_psd, document_to_psd_with}; pub use psd_import::{psd_to_document, psd_to_document_with}; From 163caeb86bd3dd4fb050963f5f3ba8048129a845 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 02:13:42 +0000 Subject: [PATCH 34/35] Make the PSD size-limit test fail when a size-based PSB promotion happens --- crates/io/src/psd_export/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 413aa85ebf..af7c8a2241 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -486,7 +486,7 @@ fn every_mode_promoted_by_size_signs_long_blocks_8b64() { assert_eq!(big.decode_merged().unwrap(), small.decode_merged().unwrap(), "{psd_mode:?}"); // Without `size_limit_psb` no mode is promoted by its size, the layerless ones included. let opts = PsdExportOptions { size_limit_psb: false, ..PsdExportOptions::default() }; - let (kept, warnings) = document_to_psd_sized(&doc, &opts, 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE); + let (kept, warnings) = document_to_psd_sized(&doc, &opts, 0, &Interrupt::NONE, len + PSD_SAVE_HEADROOM - 1); assert_eq!((kept.written_version(), kept.header.color_mode), (Version::Psd, psd_mode), "{psd_mode:?}: {warnings:?}"); assert!(!warnings.iter().any(|w| w.contains("written as PSB")), "{psd_mode:?}: {warnings:?}"); } From ab9b27b80d104f8be50b949749991bbba08ebdb6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 02:13:42 +0000 Subject: [PATCH 35/35] Restore rationale comments dropped by the Clippy refactors --- crates/gpu/src/fx.rs | 2 ++ crates/io/src/psd_export/estimate.rs | 10 +++++++--- crates/io/src/psd_import.rs | 3 +++ crates/text/src/layout/lines.rs | 3 +++ crates/ui-egui/src/menus/invoke.rs | 7 +++++++ crates/ui-egui/src/panels/actions.rs | 1 + crates/ui-egui/src/panels/channels_panel.rs | 2 ++ crates/ui-egui/src/tools/type_tool/keys.rs | 2 ++ 8 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 7d56fe7378..79d8ce0046 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -363,6 +363,8 @@ fn satin_program(b: &mut B, s: &photocraft_doc::Satin) -> usize { fn stroke_program(b: &mut B, st: &photocraft_doc::StrokeFx, vector_shape: bool) -> usize { let (in_w, out_w) = stroke_widths(st); if out_w > 0.0 { + // Narrow strokes keep the fitted chamfer, wide ones the exact transform (#3646); + // the CPU picks the same field by the same width (`stroke_outside_exact`). let kind = match (vector_shape, photocraft_compose::effects::stroke_outside_exact(out_w)) { (true, true) => FieldKind::StrokeOutsideVector, (true, false) => FieldKind::StrokeOutsideVectorChamfer, diff --git a/crates/io/src/psd_export/estimate.rs b/crates/io/src/psd_export/estimate.rs index e93e7827fc..bb2d9b1c59 100644 --- a/crates/io/src/psd_export/estimate.rs +++ b/crates/io/src/psd_export/estimate.rs @@ -3,8 +3,10 @@ use photocraft_psd::{PsdFile, Version, file::LayerInfoPlacement}; /// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD /// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by -/// Photoshop as "not compatible with this version". The other way round, a PSB block with an -/// 8-byte length is `8B64`, as Photoshop writes it. +/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way +/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, +/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read +/// the length as 4 bytes and refuse the whole file (#7937). pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { match version { Version::Psd if sig == *b"8B64" => *b"8BIM", @@ -26,7 +28,9 @@ pub(crate) fn psd_version(doc: &Document, force_psb: bool) -> Version { if force_psb || exceeds_dimensions { Version::Psb } else { Version::Psd } } -/// Promote files that exceed the PSD limit, accounting for the preview appended by the save. +/// Promote files that exceed the PSD limit, accounting for the preview appended by the save +/// (#212, #5285). The decision is made on the exact length of the file as it will be written, +/// not on the raw pixel size: RLE usually packs the channels far below it. pub(crate) fn fit_psd_size(file: &mut PsdFile, limit: u64) -> Option { if file.written_version() == Version::Psb { return None; diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 5cdc63c454..633d7f19c2 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -1110,6 +1110,9 @@ fn read_initial_metadata(file: &PsdFile, global: &[PsdGlobalBlock], doc: &mut Do } crate::guides_map::apply_colors(doc); doc.metadata.psd_global_blocks.extend(global.iter().cloned()); + // A 16/32-bit file whose layer block can't be parsed would otherwise open as a flattened + // file without a word (#2700). The raw block is kept, but a PSD save writes the document's + // own layers in its place (see `psd_export`). let mut damaged = false; if let Some((block, error)) = file.unreadable_layer_block() { damaged = true; diff --git a/crates/text/src/layout/lines.rs b/crates/text/src/layout/lines.rs index ec42eba987..b8943ef609 100644 --- a/crates/text/src/layout/lines.rs +++ b/crates/text/src/layout/lines.rs @@ -380,6 +380,9 @@ impl Para<'_> { // its descenders hang below the bottom edge (#1317: three 35 pt lines in a // 91.3 pt box, the last baseline at 88). Requiring the descent to fit dropped // that line. + // Photoshop keeps a horizontal line whose baseline is inside the box and lets its + // descenders hang below the bottom edge (#1317: three 35 pt lines in a 91.3 pt box, the + // last baseline at 88). Requiring the descent to fit dropped that line. let overflow = if env.vertical { baseline + descent > -box_x + 0.5 } else { baseline > box_y + box_h + 0.5 }; if env.is_box && overflow { return None; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index a829dae69a..850ac92fdd 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -184,6 +184,8 @@ fn invoke_shell_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, fn invoke_file_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Result, String> { let result = 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.clone()), // Layer › Rename Layer from a menu starts in-place renaming in the Layers panel. "layer.renameLayer" if params.get("name").is_none() => { @@ -468,6 +470,7 @@ fn invoke_export_command(app: &mut PhotocraftApp, id: &str, params: &Value) -> R layer if matches!(layer, "layer.exportAs" | "layer.quickExportAsPng") && params.as_object().is_none_or(|object| object.is_empty()) => { let selected = app.session.active().and_then(|document| document.active_layer).ok_or("no active layer")?; if layer == "layer.exportAs" { + // Several layers (artboards, say) selected: one file each (#3629). let layers = app.session.active().map(|document| document.selected_layers()).unwrap_or_default(); if layers.len() > 1 { Some(Ok(json!({"dialog": crate::export_dialog::open_layers(app, &layers)?}))) @@ -519,6 +522,7 @@ fn invoke_type_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p } Ok(Value::Null) })()), + // While editing type, the clipboard rows and Select > All work on the text (#1355, #2893). "edit.cut" if app.ui.text_edit.is_some() => { crate::type_tool::cut_selection(app, ctx); Some(Ok(Value::Null)) @@ -690,6 +694,8 @@ fn invoke_window_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) fn toggle_panels(app: &mut PhotocraftApp) -> Result { if app.ui.view.hides_chrome() { + // Full Screen Mode: Tab only shows or hides the chrome for now (#6760); the panels' + // own state, `hidden_by_tab` included, stays as it was before entering. app.ui.panels.full_screen_chrome = !app.ui.panels.full_screen_chrome; return Ok(Value::Null); } @@ -709,6 +715,7 @@ fn toggle_panels(app: &mut PhotocraftApp) -> Result { fn toggle_panel(app: &mut PhotocraftApp, id: &str) -> Result { let key = &id["window.toggle.".len()..]; + // A shown but collapsed dock group is expanded rather than hidden (#129). if let Some(group) = crate::dock::Group::from_key(key).filter(|group| group.shown(&app.ui.panels) && app.ui.dock.is_collapsed(*group)) { crate::dock::reveal(app, group); return Ok(Value::Null); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 33dddb9a39..092ada6a43 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -865,6 +865,7 @@ fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index 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(); + // 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 number in std::iter::once(0).chain(1..=12) { let label = if number == 0 { tl!("None").to_string() } else { format!("F{number}") }; diff --git a/crates/ui-egui/src/panels/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs index 90cd489542..912d82c298 100644 --- a/crates/ui-egui/src/panels/channels_panel.rs +++ b/crates/ui-egui/src/panels/channels_panel.rs @@ -118,6 +118,8 @@ fn handle_channel_row_click(ui: &egui::Ui, row: &mut RowInteractions<'_>) { } fn handle_channel_row_double_click(ui: &mut egui::Ui, row: &mut RowInteractions<'_>, rename_id: egui::Id) { + // Like Photoshop: double-clicking the thumbnail opens Channel Options (where an alpha + // channel becomes a spot channel, #3761), double-clicking the name renames it. let on_thumb = row.response.interact_pointer_pos().is_some_and(|p| p.x < row.cell.right() + 4.0); match row.row { Row::QuickMask if row.response.double_clicked() => row.actions.push(("ui.channelOptions".into(), json!("quickMask"))), diff --git a/crates/ui-egui/src/tools/type_tool/keys.rs b/crates/ui-egui/src/tools/type_tool/keys.rs index e262571746..deb10f77a1 100644 --- a/crates/ui-egui/src/tools/type_tool/keys.rs +++ b/crates/ui-egui/src/tools/type_tool/keys.rs @@ -248,6 +248,8 @@ fn handle_pressed_key( Key::Enter if modifiers.command => commit_with(app, *modifiers), Key::Enter => insert(app, "\n"), Key::Tab if !modifiers.command && !modifiers.alt && !modifiers.shift => { + // egui queues focus navigation before this handler runs; consuming the + // key alone would let the menu bar take focus after the first tab (#8889). ctx.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); insert(app, "\t"); }