diff --git a/.config/nextest.toml b/.config/nextest.toml index 9fd42ed9f3..d5f9f759e5 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -70,7 +70,7 @@ slow-timeout = { period = "15s", terminate-after = 6 } # times out. Each runs alone there. [[profile.ci.overrides]] platform = 'cfg(target_os = "windows")' -filter = '(package(photocraft-engine-core) | package(photocraft-engine)) & test(/content_aware_move/)' +filter = '(package(photocraft-engine-core) | package(photocraft-engine-paint) | package(photocraft-engine)) & test(/content_aware_move/)' threads-required = "num-test-threads" # Keep phase timings for the remaining expensive Windows GPU regressions visible. This does @@ -112,23 +112,23 @@ priority = 100 # 60 to 200 s filter = ''' (package(photocraft-gpu) & test(=camera_raw::clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages)) | - (package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::tests::a_coarse_preview_keeps_a_faint_sparse_selection)) | + (package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::tests::a_coarse_preview_keeps_a_faint_sparse_selection)) | (package(photocraft-engine) & test(=crop_content_aware_layers::unmeasured_active_targets_and_delete_off_keep_the_legacy_target)) | - (package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_flat_patch_matches_the_new_surroundings_at_color_ten)) | + (package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_flat_patch_matches_the_new_surroundings_at_color_ten)) | (package(photocraft-ui-egui) & test(=tools::type_tool::canvas_tests::every_paragraph_box_handle_resizes_the_box_with_snapping_on)) | (package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_gpu_2x)) | - (package(photocraft-engine-core) & test(=cmd::retouch_cmds::tests::content_aware_move_coarse_preview_handles_transform_extend_and_limits)) | + (package(photocraft-engine-paint) & test(=cmd::retouch_cmds::tests::content_aware_move_coarse_preview_handles_transform_extend_and_limits)) | (package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_cpu_2x)) | (package(photocraft-ui-egui) & test(=gpu_tests::drag_preview_canvas::marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x)) | (package(photocraft-gpu) & test(=camera_raw::shadows_and_highlights_with_per_pixel_stages)) | - (package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_brightness_change_shifts_the_middle_only_past_color_five)) | - (package(photocraft-engine-core) & test(=cmd::retouch_cmds::tests::content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths)) | + (package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_brightness_change_shifts_the_middle_only_past_color_five)) | + (package(photocraft-engine-paint) & test(=cmd::retouch_cmds::tests::content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths)) | (package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::live_tool_camera_navigation_is_visible_in_the_input_frame)) | (package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_0)) | (package(photocraft-ui-egui) & test(=gpu_tests::full_res_preview::adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off)) | (package(photocraft-ui-egui) & test(=input::hold_keys::tests::cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd)) | (package(photocraft-ui-egui) & test(=guide_cursor_tests::command_over_a_guide_takes_it_where_command_is_the_move_tool)) | (package(photocraft-gpu) & test(=parity::documents_larger_than_the_texture_limit)) | - (package(photocraft-engine-core) & test(=cmd::retouch_cmds::content_aware_move::tests::a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit)) + (package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::tests::a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit)) ''' priority = 50 diff --git a/Cargo.lock b/Cargo.lock index 5267f2df82..a4eb3d896e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6624,6 +6624,7 @@ dependencies = [ "photocraft-compose", "photocraft-doc", "photocraft-engine-core", + "photocraft-engine-paint", "photocraft-format", "photocraft-geom", "photocraft-io", @@ -6687,6 +6688,25 @@ dependencies = [ "winsafe", ] +[[package]] +name = "photocraft-engine-paint" +version = "0.23.1" +dependencies = [ + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ee30b17c2199b87b3c097729e60f6b1d9c8d1afe)", + "photocraft-algo", + "photocraft-color", + "photocraft-compose", + "photocraft-doc", + "photocraft-engine-core", + "photocraft-geom", + "photocraft-io", + "photocraft-paint", + "photocraft-raster", + "rayon", + "serde", + "serde_json", +] + [[package]] name = "photocraft-format" version = "0.23.1" diff --git a/Cargo.toml b/Cargo.toml index eae34e8bee..9cb7421438 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ photocraft-automation = { path = "crates/automation" } photocraft-plugins = { path = "crates/plugins" } photocraft-engine = { path = "crates/engine" } photocraft-engine-core = { path = "crates/engine-core" } +photocraft-engine-paint = { path = "crates/engine-paint" } photocraft-ui-egui = { path = "crates/ui-egui" } photocraft-testkit = { path = "crates/testkit" } photocraft-tablet = { path = "crates/tablet" } @@ -121,7 +122,7 @@ todo = "warn" # Every cl command selects these packages: each brings features the others lack, so a command that drops one # builds a second copy of egui, photocraft-io or craft-affinity and of everything above them. selection = [ - "photocraft-ui-egui", "photocraft-engine", "photocraft-engine-core", "photocraft", "photocraft-algo", "photocraft-automation", + "photocraft-ui-egui", "photocraft-engine", "photocraft-engine-core", "photocraft-engine-paint", "photocraft", "photocraft-algo", "photocraft-automation", "photocraft-text", "photocraft-tablet", "photocraft-cli", "photocraft-paint", "photocraft-io", "photocraft-gpu", ] # Crates whose new builds cl names after a command, besides the framework's. @@ -150,7 +151,8 @@ craft-imaging = ["default", "screen-testing", "ui"] [workspace.metadata.cl.default_seconds] "photocraft-ui-egui/photocraft_ui_egui" = 389.0 "photocraft-ui-egui/it" = 221.0 -"photocraft-engine-core/photocraft_engine_core" = 97.0 +"photocraft-engine-core/photocraft_engine_core" = 62.0 +"photocraft-engine-paint/photocraft_engine_paint" = 35.0 # Dependencies carry no debug info: their frames in a backtrace lose file:line, and the target dir # and link times shrink. The test profile inherits both settings. @@ -182,6 +184,8 @@ opt-level = 0 opt-level = 0 [profile.test.package.photocraft-engine-core] opt-level = 0 +[profile.test.package.photocraft-engine-paint] +opt-level = 0 # Only the exhaustive rounding proof needs maximum optimization; algo stays at its usual level. [profile.test.package.photocraft-oil-round-proof] diff --git a/crates/engine-core/src/allocation.rs b/crates/engine-core/src/allocation.rs index e2f84a71c8..299299a7d3 100644 --- a/crates/engine-core/src/allocation.rs +++ b/crates/engine-core/src/allocation.rs @@ -9,7 +9,7 @@ thread_local! { } /// Reserve and initialize a buffer without invoking the allocator's abort-on-OOM path. -pub(crate) fn filled(len: usize, value: T, purpose: &str) -> Result> { +pub fn filled(len: usize, value: T, purpose: &str) -> Result> { let mut out = capacity(len, purpose)?; out.resize(len, value); Ok(out) @@ -33,7 +33,7 @@ pub(crate) fn read_file_within(path: impl AsRef, max: u64) -> s } /// Reserve a vector for a known number of operation results. -pub(crate) fn capacity(len: usize, purpose: &str) -> Result> { +pub fn capacity(len: usize, purpose: &str) -> Result> { let bytes = len.checked_mul(std::mem::size_of::()).ok_or_else(|| error(purpose, "requested size overflowed"))?; #[cfg(any(test, feature = "failpoints"))] if failpoint_hits() { @@ -58,7 +58,7 @@ pub(crate) fn try_push(out: &mut Vec, value: T, purpose: &str) -> Result<( /// Check an operation boundary where downstream encoders/decoders allocate internally. /// The test-only failpoint lets command tests prove their transaction boundary. -pub(crate) fn checkpoint(purpose: &str) -> Result<()> { +pub fn checkpoint(purpose: &str) -> Result<()> { #[cfg(any(test, feature = "failpoints"))] if failpoint_hits() { return Err(error(purpose, "not enough memory")); @@ -68,7 +68,7 @@ pub(crate) fn checkpoint(purpose: &str) -> Result<()> { } /// Copy a region into an explicitly reserved buffer. -pub(crate) fn read_region(surface: &photocraft_raster::Surface, area: photocraft_geom::Rect, purpose: &str) -> Result> { +pub fn read_region(surface: &photocraft_raster::Surface, area: photocraft_geom::Rect, purpose: &str) -> Result> { let len = (area.width() as usize) .checked_mul(area.height() as usize) .and_then(|n| n.checked_mul(surface.channels())) @@ -82,11 +82,11 @@ pub(crate) fn read_region(surface: &photocraft_raster::Surface, area: photocraft /// the canvas) into flat arrays: the allowance Image Size resamples within. A document stores /// only the tiles it holds, so two distant tiles, or a huge empty canvas, make a small file whose /// content bounds would need far more than any machine has. -pub(crate) const MAX_DENSE_BYTES: u64 = crate::image_cmds::MAX_RESAMPLE_BYTES; +pub const MAX_DENSE_BYTES: u64 = crate::image_cmds::MAX_RESAMPLE_BYTES; /// Refuses, before anything is allocated, an operation that would hold `bytes_per_px` bytes of /// dense buffers for every pixel of `area` at once. -pub(crate) fn check_dense(area: photocraft_geom::Rect, bytes_per_px: u64, purpose: &str) -> Result<()> { +pub fn check_dense(area: photocraft_geom::Rect, bytes_per_px: u64, purpose: &str) -> Result<()> { let px = u64::from(area.width()).saturating_mul(u64::from(area.height())); let bytes = px.saturating_mul(bytes_per_px); if bytes <= MAX_DENSE_BYTES { @@ -101,7 +101,7 @@ pub(crate) fn check_dense(area: photocraft_geom::Rect, bytes_per_px: u64, purpos ))) } -pub(crate) fn error(purpose: &str, detail: &str) -> EngineError { +pub fn error(purpose: &str, detail: &str) -> EngineError { EngineError::Other(format!("not enough memory for {purpose} ({detail}); the document was not changed")) } diff --git a/crates/engine-core/src/brush_defs.rs b/crates/engine-core/src/brush_defs.rs new file mode 100644 index 0000000000..63c771643e --- /dev/null +++ b/crates/engine-core/src/brush_defs.rs @@ -0,0 +1,71 @@ +//! Brush settings checks and sampled tips, shared by the painting tools, Stroke Path and brush +//! preset imports. + +use photocraft_paint::{BrushSettings, GrayTile, TipShape}; + +use crate::{EngineError, Result}; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// Rejects brush sizes and Scatter amounts outside their documented ranges, before a brush is +/// stored or painted with. +pub fn validate_brush(brush: &BrushSettings, cmd: &str) -> Result<()> { + let max = photocraft_paint::MAX_BRUSH_SIZE; + if !brush.size.is_finite() || brush.size > max { + return Err(bad(cmd, format!("brush size must be finite and at most {max} px"))); + } + if brush.dual_brush.enabled && (!brush.dual_brush.size.is_finite() || brush.dual_brush.size > max) { + return Err(bad(cmd, format!("dual brush size must be finite and at most {max} px"))); + } + // Scatter may exceed 1 (100 %) but not the 1000 % maximum: a huge amount pushed dab centres to + // infinity (#977). `{:?}` keeps 1e38 short and shows infinity as `inf`. + let scatter_max = photocraft_paint::MAX_SCATTER; + let in_range = |v: f32| (0.0..=scatter_max).contains(&v); + let sc = brush.scattering.scatter.jitter; + if brush.scattering.enabled && !in_range(sc) { + return Err(bad(cmd, format!("scatter amount {sc:?} is out of range: it must be between 0 and {scatter_max} (1000 %)"))); + } + let ds = brush.dual_brush.scatter; + if brush.dual_brush.enabled && !in_range(ds) { + return Err(bad(cmd, format!("dual brush scatter amount {ds:?} is out of range: it must be between 0 and {scatter_max} (1000 %)"))); + } + Ok(()) +} + +/// Largest sampled tip side (like Photoshop's 5000 px limit, kept smaller for preset size). +pub const MAX_TIP: u32 = 2500; + +/// A sampled-tip brush from a paint-amount map (`w`×`h`, row-major, 0 = no paint, 1 = full): +/// cropped to the painted extent, at most [`MAX_TIP`] px a side. Shared by Define Brush Preset +/// and importing an image file as a brush (`brush.presets.importImage`). +pub fn sampled_brush(cmd: &str, v: &[f32], w: usize, h: usize) -> Result<(BrushSettings, u32, u32)> { + let at = |x: usize, y: usize| v.get(y * w + x).copied().unwrap_or(0.0); + // Crop to the painted extent. + let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0); + for y in 0..h { + for x in 0..w { + if at(x, y) > 1e-4 { + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x + 1); + y1 = y1.max(y + 1); + } + } + } + if x1 <= x0 || y1 <= y0 { + return Err(bad(cmd, "the pixels contain no paint (all white or transparent)")); + } + let (tw, th) = ((x1 - x0) as u32, (y1 - y0) as u32); + if tw.max(th) > MAX_TIP { + return Err(bad(cmd, format!("too large for a brush tip ({tw}×{th}; max {MAX_TIP} px)"))); + } + let mut data = Vec::with_capacity((tw * th) as usize); + for y in y0..y1 { + data.extend((x0..x1).map(|x| at(x, y))); + } + let tip = GrayTile::from_f32(tw, th, &data); + let brush = BrushSettings { tip: TipShape::Sampled(tip).into(), size: tw.max(th) as f32, spacing: 0.25, pressure_size: false, ..BrushSettings::default() }; + Ok((brush, tw, th)) +} diff --git a/crates/engine-core/src/cmd.rs b/crates/engine-core/src/cmd.rs index ac05cf2ad8..5d8f61bb22 100644 --- a/crates/engine-core/src/cmd.rs +++ b/crates/engine-core/src/cmd.rs @@ -9,12 +9,19 @@ use serde_json::{Value, json}; use crate::{EngineError, Result, Session, inspect, pixels}; -macro_rules! cmd { +/// A journaled [`CommandSpec`] from its id, label, menu path, shortcut, params, `enabled` and +/// `run`: the form the engine crates' command tables use, as `cmd!`. +#[macro_export] +macro_rules! command_spec { ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } + $crate::registry::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } }; } +macro_rules! cmd { + ($($spec:tt)*) => { $crate::command_spec!($($spec)*) }; +} + pub mod actions_cmds; pub mod actions_edit_cmds; pub mod adjust_cmds; @@ -144,14 +151,24 @@ pub mod wia_cmds; pub(crate) use adjust_params::inject_kind; use adjust_params::{adjust_mode, destructive_adjust, doc_mode, new_adjustment}; pub use adjust_params::{adjustment_from_params, adjustment_kind}; -pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface}; -use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_or_channel, has_selection}; -pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; +pub(crate) use enabled::{check_all_unlocked}; +pub use enabled::always; +pub use enabled::check_pixels_unlocked; +pub use enabled::is_mask_target; +pub use enabled::paint_surface; +use enabled::{can_redo, can_undo, has_doc, has_layer, has_selection}; +pub use enabled::has_pixel_or_channel; +pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, mask_new_layer}; +pub use layer_params::mask_at_depth; +pub use layer_params::selection_mask; +pub use layer_params::layer_param; pub(crate) use layer_references::{recorded_drop, recorded_layer}; use ops::{arrange, merge_group, move_mask, set_mask, set_mask_and_deselect}; pub(crate) use ops::{layer_copy, translate_layer, translate_layer_wrapped}; use params::{bad, set_clipped}; -pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param}; +pub(crate) use params::{check_f32_values, cmyk_param, int, int_i32, u32_id, u32_id_param}; +pub use params::color_param; +pub use params::parse_hex; pub use photocraft_color::blend::parse_blend; pub use crate::registry::{CommandSpec, list_entry, list_entry_matches, search_keywords}; diff --git a/crates/engine-core/src/cmd/channel_cmds.rs b/crates/engine-core/src/cmd/channel_cmds.rs index da0de44f0d..1046e328e3 100644 --- a/crates/engine-core/src/cmd/channel_cmds.rs +++ b/crates/engine-core/src/cmd/channel_cmds.rs @@ -138,12 +138,21 @@ pub(crate) use refs::source_spec; pub use refs::{Blending, ChanRef, parse_ref}; use selection::{load_selection, quick_mask, save_selection}; use spot::{is_flat, merge, merge_spot, mergeable, split}; +pub use targeting::{FILL_KEY_IDS, follows_filter_mask, follows_target, follows_vector_mask_target, gray_target, read_target_surface}; use targeting::{SLOT_KEY, target_cmd, target_slot}; pub(crate) use targeting::{ - Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target, invert_region, - is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_layer_mask, target_of, target_surface, targeted_channel, + channel_surface_for_filter, clear_channel, clear_color_channel, filter_mask_layer, invert_region, + is_spot_target, mask_target_enabled, routed, targeted_channel, }; -pub use targeting::{follows_filter_mask, follows_target, follows_vector_mask_target, gray_target, read_target_surface}; +pub use targeting::target_layer_mask; +pub use targeting::Target; +pub use targeting::color_restriction; +pub use targeting::edits_channel; +pub use targeting::inject_target; +pub use targeting::is_channel_target; +pub use targeting::restrict_to_color; +pub use targeting::target_of; +pub use targeting::target_surface; pub use tone_target::{ToneTarget, resolve_tone_target}; pub(crate) use view::fix_view; pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name}; diff --git a/crates/engine-core/src/cmd/channel_cmds/targeting.rs b/crates/engine-core/src/cmd/channel_cmds/targeting.rs index b4e7880c5e..356882a7c8 100644 --- a/crates/engine-core/src/cmd/channel_cmds/targeting.rs +++ b/crates/engine-core/src/cmd/channel_cmds/targeting.rs @@ -9,7 +9,7 @@ use super::{ColorMode, Document, EngineError, Layer, LayerId, Rect, Result, Sess /// Where a pixel command writes, from its `"target"` param. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Target { +pub enum Target { Pixels, Mask, /// A smart object's filter mask (`"target":"filterMask"`): where it is black the smart @@ -21,7 +21,7 @@ pub(crate) enum Target { /// An alpha index that cannot fit this platform stays an unaddressable alpha target. Using /// usize::MAX makes the later checked lookup fail instead of wrapping or falling back to pixels. -pub(crate) fn target_of(p: &Value) -> Target { +pub fn target_of(p: &Value) -> Target { match p.get("target") { Some(Value::String(s)) => match s.as_str() { "mask" => Target::Mask, @@ -35,7 +35,7 @@ pub(crate) fn target_of(p: &Value) -> Target { } /// The target is an alpha channel or the Quick Mask (no layer involved). -pub(crate) fn is_channel_target(p: &Value) -> bool { +pub fn is_channel_target(p: &Value) -> bool { matches!(target_of(p), Target::Alpha(_) | Target::QuickMask) } @@ -65,7 +65,7 @@ pub(crate) fn invert_region(s: &mut Surface, r: Rect) -> Result<()> { } /// The surface a pixel command writes to and whether the layer's transparency is locked. -pub(crate) fn target_surface<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result<(&'a mut Surface, bool)> { +pub fn target_surface<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result<(&'a mut Surface, bool)> { match target_of(p) { Target::Alpha(i) => { let n = doc.channels.len(); @@ -119,6 +119,11 @@ pub(crate) fn channel_surface_for_filter<'a>(doc: &'a mut Document, layer: Optio Ok(Some(surf)) } +/// The fill-key commands (Edit › Fill shortcuts with the foreground, background or history), +/// routed to the Channels panel target like `edit.fill`. +pub const FILL_KEY_IDS: [&str; 5] = + ["edit.fillForeground", "edit.fillBackground", "edit.fillForegroundPreserve", "edit.fillBackgroundPreserve", "edit.fillHistory"]; + /// Commands that edit a targeted layer mask in place of the layer: the Image › Adjustments table, /// the filters and the fills (Edit › Fill and its keys). A mask target enables them on any layer /// with a mask, so ⌘I inverts an adjustment layer's mask (#780) and Fill fills it (#2456) as in @@ -129,7 +134,7 @@ fn edits_mask(id: &str) -> bool { || id == "edit.fill" // Copying a targeted mask (#2928). || matches!(id, "edit.copy" | "edit.cut" | "edit.clear") - || crate::fill_key_cmds::IDS.contains(&id) + || FILL_KEY_IDS.contains(&id) } /// The precondition of `id` when `p` targets the active layer's mask (`"target":"mask"`): the @@ -237,7 +242,7 @@ pub(crate) fn routed(id: &str) -> bool { || matches!(id, "paint.magicEraser" | "paint.backgroundEraser" | "paint.colorReplacement" | "shape.paint" | "path.fill" | "path.stroke" | "edit.clear" | "edit.cut") || id.starts_with("image.adjustments.") || matches!(id, "edit.fill" | "image.applyImage") - || crate::fill_key_cmds::IDS.contains(&id) + || FILL_KEY_IDS.contains(&id) || PAINT_IDS.contains(&id) // Pasting into a targeted mask or channel (#1035); Copy takes a targeted mask (#2928). || id == "edit.copy" @@ -254,7 +259,7 @@ pub(crate) fn routed(id: &str) -> bool { } /// Fill in `"target"` from the targeted channel (or Quick Mask mode) when the caller gave none. -pub(crate) fn inject_target(s: &Session, id: &str, params: Value) -> Value { +pub fn inject_target(s: &Session, id: &str, params: Value) -> Value { if !routed(id) || params.get("target").is_some() { return params; } @@ -307,7 +312,7 @@ pub(crate) fn filter_mask_layer(s: &Session, id: &str, params: &Value) -> Option } /// The colour channel pixel commands are limited to, if a single colour channel is targeted. -pub(crate) fn color_restriction(s: &Session, id: &str, params: &Value) -> Option { +pub fn color_restriction(s: &Session, id: &str, params: &Value) -> Option { if !routed(id) || is_channel_target(params) || crate::commands::is_mask_target(params) { return None; } @@ -325,7 +330,7 @@ pub(crate) fn color_restriction(s: &Session, id: &str, params: &Value) -> Option /// After a pixel edit with colour channel `k` targeted, put the other channels (and the layer's /// transparency) of layer `id` back as they were. Only changed tiles are touched. -pub(crate) fn restrict_to_color(before: &Document, after: &mut Document, id: LayerId, colors: crate::color_channels::ColorChannels) -> Result<()> { +pub fn restrict_to_color(before: &Document, after: &mut Document, id: LayerId, colors: crate::color_channels::ColorChannels) -> Result<()> { let Some(old) = before.layer(id).and_then(Layer::surface) else { return Ok(()) }; let Some(new) = after.layer_mut(id).and_then(Layer::surface_mut) else { return Ok(()) }; let extent = before.bounds().union(&old.content_bounds()).union(&new.content_bounds()); @@ -387,12 +392,12 @@ pub(crate) fn clear_channel(doc: &mut Document, target: &Value, background: [f32 return Ok(()); } let (surf, _) = target_surface(doc, None, target)?; - crate::fill_cmds::fill_color(surf, area, [background[0], background[1], background[2], 1.0], sel.as_ref()) + crate::pixel_fill::fill_color(surf, area, [background[0], background[1], background[2], 1.0], sel.as_ref()) } /// The active document targets an alpha channel or is in Quick Mask mode, so pixel commands /// work without a pixel layer. -pub(crate) fn edits_channel(s: &Session) -> bool { +pub fn edits_channel(s: &Session) -> bool { s.active().is_some_and(|st| { st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite || matches!(st.channel_view.target, ChannelTarget::Alpha(i) if i < st.doc.channels.len()) @@ -400,7 +405,7 @@ pub(crate) fn edits_channel(s: &Session) -> bool { } /// Target the active layer's mask, as clicking its thumbnail does. -pub(crate) fn target_layer_mask(s: &mut Session) { +pub fn target_layer_mask(s: &mut Session) { target(s, ChannelTarget::LayerMask); } diff --git a/crates/engine-core/src/cmd/edit_cmds.rs b/crates/engine-core/src/cmd/edit_cmds.rs index 0de1f20a19..63278e0f8f 100644 --- a/crates/engine-core/src/cmd/edit_cmds.rs +++ b/crates/engine-core/src/cmd/edit_cmds.rs @@ -207,7 +207,7 @@ fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Result { if fmt.alpha && tr == tc.rect() && let Some(tile) = src.tile(tc) - && sel.is_none_or(|m| crate::fill_cmds::Mask::of(m, tc).full(tr)) + && sel.is_none_or(|m| crate::pixel_fill::Mask::of(m, tc).full(tr)) { // Reading and writing it back would give the same bytes. shared.push((tc, tile.clone())); @@ -451,7 +451,7 @@ pub(crate) fn clear_mask(doc: &mut Document, id: LayerId, background: [f32; 4], let canvas = doc.bounds(); let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas)); let mask = crate::commands::paint_surface(doc, id, params)?; - crate::fill_cmds::fill_color(mask, area, [background[0], background[1], background[2], 1.0], sel.as_ref()) + crate::pixel_fill::fill_color(mask, area, [background[0], background[1], background[2], 1.0], sel.as_ref()) } /// Cut / Clear on a layer: makes the selected pixels transparent. The Background can't hold @@ -652,7 +652,7 @@ pub(crate) fn paste_to_target(s: &mut Session, p: &Value, in_place: bool, limit: if spot { crate::channel_cmds::invert_region(surf, area)?; } - crate::fill_cmds::composite_over(surf, &src, area, limit)?; + crate::pixel_fill::composite_over(surf, &src, area, limit)?; if spot { crate::channel_cmds::invert_region(surf, area)?; } diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/content_aware.rs b/crates/engine-core/src/cmd/edit_menu_cmds/content_aware.rs index 5cc523e760..1dff46131b 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/content_aware.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/content_aware.rs @@ -239,7 +239,7 @@ pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str use photocraft_algo::content_aware::{auto_sampling_with, grow_mask, paint_strokes, polygon_mask}; use rayon::prelude::*; - use crate::fill_cmds::{read_window, read_window_mask}; + use crate::content_sampling::{read_window, read_window_mask}; let CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf } = caf_params(doc, id, p, cmd)?; let canvas = doc.bounds(); let cancel = || ctl.cancelled(); @@ -253,7 +253,7 @@ pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str FillEdit::Grow(_) => r, }); let er = reach.inflate(grow.saturating_add(1)).intersect(&canvas); - let (ew, eh) = crate::fill_cmds::window_size(er)?; + let (ew, eh) = crate::content_sampling::window_size(er)?; let ecover = read_window_mask(sel, er, &cancel).ok_or(EngineError::Cancelled)?; let mut ehole: Vec = ecover.par_iter().map(|c| *c > 0.0).collect(); for e in &edits { @@ -283,7 +283,7 @@ pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str let window = match sampling.as_str() { "rectangular" => match int(p, "margin") { Some(m) => hb.inflate(m.clamp(0, 100_000) as i32), - None => crate::fill_cmds::sampling_window(hb, canvas), + None => crate::content_sampling::sampling_window(hb, canvas), }, "custom" => match (custom_rect, custom_mask) { (Some(r), _) => r, @@ -292,7 +292,7 @@ pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str } .union(&hb) .inflate(4), - _ => crate::fill_cmds::sampling_window(hb, canvas), + _ => crate::content_sampling::sampling_window(hb, canvas), } .intersect(&canvas); // Strokes that add to the sampling area may reach past the window. @@ -307,11 +307,11 @@ pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str }; let n = fmt.channels(); // Refuse a window too large to read before allocating for it, whatever the sampling (#963). - let (w, h) = crate::fill_cmds::window_size(rect)?; + let (w, h) = crate::content_sampling::window_size(rect)?; let pixels = read_window(surf, rect, &cancel).ok_or(EngineError::Cancelled)?; let (img, layer_px) = if sample_all { stop()?; - (crate::retouch_cmds::composite_region(doc, Some(id), crate::retouch_cmds::SampleLayers::All, rect, fmt).data, Some(pixels)) + (crate::content_sampling::composite_region(doc, Some(id), crate::content_sampling::SampleLayers::All, rect, fmt).data, Some(pixels)) } else { (pixels, None) }; diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs index 1a6cef7845..9cfb32ead2 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs @@ -116,7 +116,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { "delete" => match kind.as_str() { "brushes" => { let gone = std::sync::Arc::make_mut(&mut *s.tools.presets).remove(i); - crate::brush_cmds::forget_deleted_preset(s, &gone.name); + crate::preset_store::forget_deleted_preset(s, &gone.name); } "patterns" => drop(s.patterns.items.remove(i)), _ => drop(s.edit_state.custom_shapes.remove(i)), diff --git a/crates/engine-core/src/cmd/enabled.rs b/crates/engine-core/src/cmd/enabled.rs index f7b4f00737..92112e7fc4 100644 --- a/crates/engine-core/src/cmd/enabled.rs +++ b/crates/engine-core/src/cmd/enabled.rs @@ -1,6 +1,6 @@ use super::{Document, EngineError, LayerContent, LayerId, Result, Session, Value}; -pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { +pub fn always(_: &Session) -> std::result::Result<(), String> { Ok(()) } @@ -23,29 +23,16 @@ pub(super) fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { } /// A pixel layer, or a targeted alpha channel / Quick Mask (adjustments and fills apply to it). -pub(super) fn has_pixel_or_channel(s: &Session) -> std::result::Result<(), String> { +pub fn has_pixel_or_channel(s: &Session) -> std::result::Result<(), String> { if crate::channel_cmds::edits_channel(s) { return Ok(()); } has_pixel_layer(s) } -/// A layer that can be painted: pixels, or any layer with a mask (paint with `"target":"mask"`). -pub(crate) fn has_paintable(s: &Session) -> std::result::Result<(), String> { - if crate::channel_cmds::edits_channel(s) { - return Ok(()); - } - let l = crate::active_layer_of(s)?; - if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { - Ok(()) - } else { - Err(format!("active layer is {} {} layer without a mask", l.content.article(), l.content.kind_name())) - } -} - /// Surface a paint command writes to: the layer's pixels, its mask with `"target":"mask"`, or a /// smart object's filter mask with `"target":"filterMask"`. -pub(crate) fn paint_surface<'a>(doc: &'a mut Document, id: LayerId, p: &Value) -> Result<&'a mut photocraft_raster::Surface> { +pub fn paint_surface<'a>(doc: &'a mut Document, id: LayerId, p: &Value) -> Result<&'a mut photocraft_raster::Surface> { if is_mask_target(p) { check_all_unlocked(doc, id)?; } else { @@ -72,7 +59,7 @@ pub(crate) fn check_all_unlocked(doc: &Document, id: LayerId) -> Result<()> { } /// Refuse a layer whose pixels are locked (directly or through a group), with Photoshop's message. -pub(crate) fn check_pixels_unlocked(doc: &Document, id: LayerId) -> Result<()> { +pub fn check_pixels_unlocked(doc: &Document, id: LayerId) -> Result<()> { let locks = doc.effective_locks(id); let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; if locks.pixels || locks.all { @@ -83,7 +70,7 @@ pub(crate) fn check_pixels_unlocked(doc: &Document, id: LayerId) -> Result<()> { /// The params target a grayscale mask of the layer: its layer mask (`"mask"`) or, on a smart /// object, its filter mask (`"filterMask"`). -pub(crate) fn is_mask_target(p: &Value) -> bool { +pub fn is_mask_target(p: &Value) -> bool { matches!(p.get("target").and_then(Value::as_str), Some("mask" | "filterMask")) } diff --git a/crates/engine-core/src/cmd/extra_cmds.rs b/crates/engine-core/src/cmd/extra_cmds.rs index 1d0726bea9..d9d03286af 100644 --- a/crates/engine-core/src/cmd/extra_cmds.rs +++ b/crates/engine-core/src/cmd/extra_cmds.rs @@ -224,7 +224,7 @@ fn stroke(s: &mut Session, p: &Value) -> Result { let (surf, lock) = crate::channel_cmds::target_surface(doc, Some(id), target)?; let area = band.content_bounds().intersect(&canvas); if !area.is_empty() { - crate::fill_cmds::blend_color_mask(surf, area, color, picked, &band, mode, opacity, preserve || lock)?; + crate::pixel_fill::blend_color_mask(surf, area, color, picked, &band, mode, opacity, preserve || lock)?; surf.prune(); } Ok(()) @@ -538,7 +538,7 @@ pub(crate) fn background_to_layer_for_mask(doc: &mut photocraft_doc::Document, i /// If `id` is the Background ([`photocraft_doc::Document::background`], whatever its name), turns /// it into a normal layer ("Layer 0"), as Photoshop does before an edit the Background can't /// take (moving, transforming, exposing transparency, a style). Other layers are left alone. -pub(crate) fn background_to_layer(doc: &mut photocraft_doc::Document, id: photocraft_doc::LayerId) { +pub fn background_to_layer(doc: &mut photocraft_doc::Document, id: photocraft_doc::LayerId) { if let Some(l) = doc.background_mut().filter(|l| l.id == id) { unlock_background(l); } diff --git a/crates/engine-core/src/cmd/float_cmds.rs b/crates/engine-core/src/cmd/float_cmds.rs index 37a6cbead8..9f46d14eab 100644 --- a/crates/engine-core/src/cmd/float_cmds.rs +++ b/crates/engine-core/src/cmd/float_cmds.rs @@ -135,7 +135,7 @@ impl CutParts { let mut out = self.rest.clone(); let piece = self.piece.translated(dx, dy, self.piece_bounds); if self.mask { - crate::fill_cmds::composite_over(&mut out, &piece, self.piece_bounds.translate(dx, dy), None)?; + crate::pixel_fill::composite_over(&mut out, &piece, self.piece_bounds.translate(dx, dy), None)?; } else { crate::transform_cmds::composite_over(&mut out, &piece); } @@ -183,7 +183,7 @@ fn cut_piece(base: &Surface, sel: &Surface, b: photocraft_geom::Rect, with_alpha .into_par_iter() .map(|tc| -> Result)>> { let tr = tc.rect().intersect(&b); - let mask = crate::fill_cmds::Mask::of(sel, tc); + let mask = crate::pixel_fill::Mask::of(sel, tc); if mask.empty(tr) { return Ok(None); } diff --git a/crates/engine-core/src/cmd/history_source_cmds.rs b/crates/engine-core/src/cmd/history_source_cmds.rs index 179bd39129..c7638e71c3 100644 --- a/crates/engine-core/src/cmd/history_source_cmds.rs +++ b/crates/engine-core/src/cmd/history_source_cmds.rs @@ -19,7 +19,7 @@ use std::sync::Arc; -use photocraft_doc::{ColorMode, Document}; +use photocraft_doc::Document; use serde_json::{Value, json}; use crate::commands::CommandSpec; @@ -49,7 +49,7 @@ pub fn source(st: &DocState) -> Option { } } -fn source_of(st: &DocState, src: HistorySource) -> Option> { +pub fn source_of(st: &DocState, src: HistorySource) -> Option> { match src { HistorySource::State(i) => st.history.row_doc(i, &st.doc), HistorySource::Snapshot(id) => st.snapshots().iter().find(|s| s.id == id).map(|s| s.doc.clone()), @@ -57,7 +57,7 @@ fn source_of(st: &DocState, src: HistorySource) -> Option> { } /// A `state` or `snapshot` param (`None` when neither is passed), checked against the document. -fn parse(st: &DocState, p: &Value, cmd: &str) -> Result> { +pub fn parse(st: &DocState, p: &Value, cmd: &str) -> Result> { let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; let get = |k: &str| p.get(k).filter(|v| !v.is_null()); let index = |k: &str, v: &Value| v.as_u64().ok_or_else(|| bad(format!("`{k}` must be a non-negative integer, not {v}"))); @@ -80,63 +80,6 @@ fn parse(st: &DocState, p: &Value, cmd: &str) -> Result> { } } -/// The document the History Brush and Fill › History paint from: the `state` (History panel row) -/// or `snapshot` passed, else the source set in the History panel. A source of another canvas -/// size is refused rather than painting shifted pixels (after Crop, Canvas Size or Image Size): -/// Photoshop refuses too, "the current canvas size does not match that of the history state" -/// (its message as users report it; Adobe's help doesn't document the case). -pub(crate) fn paint_source(st: &DocState, p: &Value, cmd: &str) -> Result> { - checked_source(st, p, cmd)?.map_err(|why| { - EngineError::Other(match why { - SourceRefusal::NoSource => "the History Brush source was deleted: set a new source in the History panel".into(), - SourceRefusal::CanvasSize { source } => format!( - "the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel", - st.doc.size.width, st.doc.size.height, source.width, source.height - ), - }) - }) -} - -/// Why [`checked_source`] found no source to paint from, so each tool can word it (#12638). -#[derive(Debug)] -pub(crate) enum SourceRefusal { - /// No `state` or `snapshot` passed, and the History panel's source was deleted. - NoSource, - /// The source has another canvas size than the document. - CanvasSize { source: photocraft_geom::Size }, -} - -/// [`paint_source`] with the refusal left to the caller: bad params and a `state` or `snapshot` -/// that is gone are errors, the two refusals the tools word themselves are the inner `Err`. -pub(crate) fn checked_source(st: &DocState, p: &Value, cmd: &str) -> Result, SourceRefusal>> { - let doc = match parse(st, p, cmd)? { - Some(src) => source_of(st, src).ok_or_else(|| EngineError::Other("that history state or snapshot is gone".into()))?, - None => match source(st).and_then(|src| source_of(st, src)) { - Some(doc) => doc, - None => return Ok(Err(SourceRefusal::NoSource)), - }, - }; - if doc.size != st.doc.size { - return Ok(Err(SourceRefusal::CanvasSize { source: doc.size })); - } - Ok(Ok(doc)) -} - -/// The History Brush's refusals after Image › Mode, with Photoshop's alert texts (#12842): only -/// the History Brush's pairs were measured (RGB to Grayscale, a depth change), so any other change, -/// or both at once, converts the source as before. Document modes are compared: the pixel format -/// reads Indexed and Multichannel as RGB. -pub(crate) fn refuse_other_format(st: &DocState, source: &Document) -> Result<()> { - let (mode_differs, depth_differs) = (source.mode != st.doc.mode, source.depth != st.doc.depth); - if source.mode == ColorMode::Rgb && st.doc.mode == ColorMode::Grayscale && !depth_differs { - return Err(EngineError::Other("Could not use the history brush because the current color mode does not match that of the history state.".into())); - } - if depth_differs && !mode_differs { - return Err(EngineError::Other("Could not use the history brush because the current bit depth does not match that of the history state.".into())); - } - Ok(()) -} - /// `history.setSource {state}` or `{snapshot}`: make a History panel row or a snapshot the History /// Brush's source. fn set_source(s: &mut Session, p: &Value) -> Result { @@ -416,7 +359,3 @@ mod tests { assert_eq!(s.execute(CMD, json!({"snapshot": 0})).unwrap()["snapshot"], 0); } } - -#[cfg(test)] -#[path = "history_brush_format_mismatch_tests.rs"] -mod history_brush_format_mismatch_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds.rs b/crates/engine-core/src/cmd/layer_multi_cmds.rs index 109a7204c8..06ebccac05 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds.rs @@ -21,13 +21,14 @@ mod structure; pub use crate::damage::{layer_bounds, same_pixels, selection_only_change, step_damage}; use align::{align, distribute}; use moves::link_groups; -pub(crate) use moves::shift_surface; +pub use moves::shift_surface; #[cfg(test)] pub(crate) use moves::with_links; pub use moves::{move_targets, move_to, moved, moved_target, moved_wrapping, moves_mask_alone, preview_move, translate, wrapped_delta}; pub(crate) use moves::{wrap_path, wrap_surface, wraps_linked_masks}; use selection::{doc_state, find_layers, select_all_layers, select_linked}; -pub(crate) use selection::{mask_targets, recorded_step, reselect, targets, top_level}; +pub(crate) use selection::{mask_targets, recorded_step, reselect, targets}; +pub use selection::top_level; pub use selection::{select, selected, set_selection}; pub(crate) use structure::{check_group_depth, deletion_neighbours, relink_copies}; pub use structure::{delete_selected, duplicate_selected, group_layers, set_visible_selected}; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/moves.rs b/crates/engine-core/src/cmd/layer_multi_cmds/moves.rs index 02fb8a5bee..d63ebf6c62 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/moves.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/moves.rs @@ -357,7 +357,7 @@ pub fn wrapped_delta(dx: i32, dy: i32, tile: photocraft_geom::Rect) -> (i32, i32 /// `photocraft_algo::resample::translate_surface` with the content scan cached per tile (a Move /// drag shifts the same layers every frame; scanning them each time cost more than the copy). -pub(crate) fn shift_surface(s: &photocraft_raster::Surface, dx: i32, dy: i32) -> photocraft_raster::Surface { +pub fn shift_surface(s: &photocraft_raster::Surface, dx: i32, dy: i32) -> photocraft_raster::Surface { s.translated(dx, dy, photocraft_compose::bounds::content_bounds(s)) } diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/selection.rs b/crates/engine-core/src/cmd/layer_multi_cmds/selection.rs index dc287e0ec0..845bd85031 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/selection.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/selection.rs @@ -41,7 +41,7 @@ pub(crate) fn mask_targets(s: &Session, p: &serde_json::Value) -> Result Vec { +pub fn top_level(doc: &Document, ids: &[LayerId]) -> Vec { doc.layers.index().roots(ids) } diff --git a/crates/engine-core/src/cmd/layer_params.rs b/crates/engine-core/src/cmd/layer_params.rs index 1f15afea2e..f901da1289 100644 --- a/crates/engine-core/src/cmd/layer_params.rs +++ b/crates/engine-core/src/cmd/layer_params.rs @@ -65,7 +65,7 @@ pub(crate) fn layer_listing(doc: &Document) -> String { } /// The layer a command targets: [`explicit_layer`], else the active layer. -pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { +pub fn layer_param(s: &Session, p: &Value) -> Result { match explicit_layer(s, p)? { Some(id) => Ok(id), None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), @@ -75,14 +75,14 @@ pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { /// The active selection as the mask of a layer being created, or None without a selection. /// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on /// the selected area only (#1250). [`mask_new_layer`] then drops the selection (#8801). -pub(crate) fn selection_mask(doc: &Document) -> Result> { +pub fn selection_mask(doc: &Document) -> Result> { doc.selection.as_ref().map(|sel| mask_at_depth(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() }, doc.depth)).transpose() } /// New pixel masks use the document's depth, as PSD saves/imports do. Otherwise a later soft /// brush stroke quantizes differently depending on whether the document reopened as PSD or /// native. Converting a selection keeps its coverage and does not alter the selection itself. -pub(crate) fn mask_at_depth(mut mask: LayerMask, depth: SampleType) -> Result { +pub fn mask_at_depth(mut mask: LayerMask, depth: SampleType) -> Result { let format = mask.surface.format().with_sample(depth); if mask.surface.format() != format { mask.surface = mask.surface.try_convert(format)?; diff --git a/crates/engine-core/src/cmd/mode_cmds.rs b/crates/engine-core/src/cmd/mode_cmds.rs index ab39dfc3a7..dd52aeba0e 100644 --- a/crates/engine-core/src/cmd/mode_cmds.rs +++ b/crates/engine-core/src/cmd/mode_cmds.rs @@ -14,7 +14,9 @@ use photocraft_algo::transform::{Homography, Interp}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::adjust::CurvePoint; use photocraft_doc::{ColorIndices, ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size}; -use photocraft_geom::{Affine, Rect}; +use photocraft_geom::Affine; +#[cfg(test)] +use photocraft_geom::Rect; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -608,62 +610,6 @@ fn color_table(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The colour table painting on `p`'s target must stay inside: an Indexed Color document's, -/// when the target is layer pixels (masks and channels are gray, not indexed). -pub(crate) fn paint_color_table(doc: &Document, p: &Value) -> Option { - let pixels = crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; - doc.color_table.clone().filter(|_| pixels && doc.mode == ColorMode::Indexed) -} - -/// The colour `c` paints as in a document with `table` (see [`keep_in_color_table`]). -pub(crate) fn table_color(table: &ColorTable, c: [f32; 4]) -> [f32; 4] { - let mut px = [c]; - if !table.colors.is_empty() { - quantize::quantize(&mut px, 1, &table.colors, Dither::None, 0.0, table.transparent.map(usize::from)); - } - let [c] = px; - c -} - -/// Map the pixels of `r` that the stroke changed (they differ from `pre`) to their nearest -/// colour-table entry, as the Indexed Color conversion does with no dither, so painting never -/// leaves the table (#8669). One tile at a time: a long stroke's bounds can span the canvas. -pub(crate) fn keep_in_color_table(table: &ColorTable, pre: &Surface, surf: &mut Surface, r: Rect) { - if table.colors.is_empty() { - return; - } - let fmt = surf.format(); - let n = fmt.channels(); - let mut enc = [0.0f32; 8]; - for tc in r.tiles() { - let t = tc.rect().intersect(&r); - if t.is_empty() || !surf.has_tiles_in(t) { - continue; - } - let (before, mut data) = (pre.read_region(t), surf.read_region(t)); - let (mut changed, mut px) = (Vec::new(), Vec::new()); - for (i, (q, b)) in data.chunks_exact(n).zip(before.chunks_exact(n)).enumerate() { - if q != b { - changed.push(i); - px.push(photocraft_raster::to_rgba(&fmt, q)); - } - } - if px.is_empty() { - continue; - } - let w = px.len(); - quantize::quantize(&mut px, w, &table.colors, Dither::None, 0.0, table.transparent.map(usize::from)); - let mut mapped = changed.into_iter().zip(px).peekable(); - for (i, q) in data.chunks_exact_mut(n).enumerate() { - if let Some((_, c)) = mapped.next_if(|(j, _)| *j == i) { - photocraft_raster::from_rgba_into(&fmt, c, &mut enc); - q.iter_mut().zip(enc).for_each(|(d, v)| *d = v); - } - } - surf.write_region(t, &data); - } -} - // ---------- Bitmap ---------- /// Bitmap's Output resolution range (ppi): what a new document may have. diff --git a/crates/engine-core/src/cmd/params.rs b/crates/engine-core/src/cmd/params.rs index b5e7e39975..62397642ce 100644 --- a/crates/engine-core/src/cmd/params.rs +++ b/crates/engine-core/src/cmd/params.rs @@ -82,7 +82,7 @@ pub(crate) fn cmyk_param(cmd: &str, p: &Value, key: &str) -> Result Result<[f32; 4]> { +pub fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> Result<[f32; 4]> { Ok(match p.get(key) { Some(Value::Array(a)) if a.len() >= 3 => { let mut out = [0.0, 0.0, 0.0, 1.0]; @@ -96,7 +96,7 @@ pub(crate) fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> }) } -pub(crate) fn parse_hex(s: &str) -> Option<[f32; 4]> { +pub fn parse_hex(s: &str) -> Option<[f32; 4]> { let s = s.trim_start_matches('#'); // `from_str_radix` accepts a leading '+', so "+f" would read as 0x0f. if !s.bytes().all(|c| c.is_ascii_hexdigit()) { diff --git a/crates/engine-core/src/cmd/pattern_cmds.rs b/crates/engine-core/src/cmd/pattern_cmds.rs index a03ae21d44..ff5a2eff61 100644 --- a/crates/engine-core/src/cmd/pattern_cmds.rs +++ b/crates/engine-core/src/cmd/pattern_cmds.rs @@ -87,7 +87,7 @@ pub fn resolve(s: &Session, key: &str) -> Option { full(s, library_pattern(s, key)?).ok() } -pub(crate) fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result { +pub fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result { let key = p.get("pattern").and_then(Value::as_str).unwrap_or(""); resolve_or_named(s, key, p).map_err(|e| bad(cmd, e)).and_then(|pat| paintable(cmd, pat)) } @@ -346,7 +346,7 @@ fn export(s: &mut Session, p: &Value) -> Result { /// A pattern's scale, angle, link and phase from `p`. The angle is normalised to (-180, 180]; /// a non-finite angle or a phase beyond ±`MAX_PHASE` is an error (it would render NaN). -pub(crate) fn placement(cmd: &str, p: &Value) -> Result<(f32, f32, bool, (f32, f32))> { +pub fn placement(cmd: &str, p: &Value) -> Result<(f32, f32, bool, (f32, f32))> { let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(100.0) as f32; let max = crate::pattern_fill_cmds::MAX_PHASE; let a = p.get("phase").and_then(Value::as_array); @@ -376,7 +376,7 @@ pub(crate) fn insert_fill_layer( // Like Photoshop, an empty pixel layer selected becomes the fill layer instead of getting one // above it; it keeps its place, opacity and blending, and a name the user gave it. if let Some(id) = *active - && crate::stamp_cmds::is_empty_pixel_layer(doc, id) + && crate::layer_place::is_empty_pixel_layer(doc, id) { let target = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if is_default_layer_name(&target.name) { diff --git a/crates/engine-core/src/cmd/preset_import_cmds.rs b/crates/engine-core/src/cmd/preset_import_cmds.rs index eec27cacf3..516ce12818 100644 --- a/crates/engine-core/src/cmd/preset_import_cmds.rs +++ b/crates/engine-core/src/cmd/preset_import_cmds.rs @@ -221,7 +221,7 @@ fn image_paint(doc: &photocraft_doc::Document, cmd: &str) -> Result<(Vec, u Ok(()) }); let area = bounds.ok_or_else(|| bad(cmd, "the image contains no paint (all white or transparent)"))?; - let max = crate::brush_cmds::MAX_TIP; + let max = crate::brush_defs::MAX_TIP; if area.width().max(area.height()) > max { return Err(bad(cmd, format!("the painted part of the image is too large for a brush tip ({}×{}; max {max} px)", area.width(), area.height()))); } @@ -263,7 +263,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result { }; let doc = crate::file_cmds::import(decode_name, &bytes)?; let (v, w, h) = image_paint(&doc, cmd)?; - let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?; + let (brush, tw, th) = crate::brush_defs::sampled_brush(cmd, &v, w, h)?; let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name); std::sync::Arc::make_mut(&mut *s.tools.presets).push(photocraft_paint::BrushPreset { name: name.clone(), diff --git a/crates/engine-core/src/cmd/selection_cmds.rs b/crates/engine-core/src/cmd/selection_cmds.rs index 895db32a14..388a8e6f64 100644 --- a/crates/engine-core/src/cmd/selection_cmds.rs +++ b/crates/engine-core/src/cmd/selection_cmds.rs @@ -123,7 +123,7 @@ fn shown_gray(s: &Session) -> Option<(Rect, Vec<[u8; 4]>)> { } /// 8-bit RGBA of the active layer (or the composite with `all_layers`) over the canvas. -pub(crate) fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[u8; 4]>)> { +pub fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[u8; 4]>)> { let d = s.active().ok_or(EngineError::NoDocument)?; let area = d.doc.bounds(); let layer = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface()); diff --git a/crates/engine-core/src/cmd/transform_cmds.rs b/crates/engine-core/src/cmd/transform_cmds.rs index 7882cf5b66..803c3ab8ef 100644 --- a/crates/engine-core/src/cmd/transform_cmds.rs +++ b/crates/engine-core/src/cmd/transform_cmds.rs @@ -76,7 +76,7 @@ pub(crate) fn whole_layer_bounds(doc: &Document, layer: &Layer) -> Rect { /// Warp a surface whose pixels outside the content read as `default` (masks, selections): /// warp the content with alpha, then flatten back onto the default value. -pub(crate) fn warp_gray(s: &Surface, h: &Homography, interp: Interp) -> Result { +pub fn warp_gray(s: &Surface, h: &Homography, interp: Interp) -> Result { let default = s.default_pixel().first().copied().unwrap_or(0.0); let fmt = s.format(); let src = s.content_bounds(); diff --git a/crates/engine-core/src/cmd/vector_cmds/paths.rs b/crates/engine-core/src/cmd/vector_cmds/paths.rs index 5bf9a6511a..fd1c3cfe84 100644 --- a/crates/engine-core/src/cmd/vector_cmds/paths.rs +++ b/crates/engine-core/src/cmd/vector_cmds/paths.rs @@ -625,7 +625,7 @@ pub(super) fn path_stroke(s: &mut Session, p: &Value) -> Result { return Err(bad("path.stroke", format!("unknown tool `{o}` ({})", tools.join("|")))); } } - crate::brush_cmds::validate_brush(&brush, "path.stroke")?; + crate::brush_defs::validate_brush(&brush, "path.stroke")?; let lines = vector::flatten_path(&path, 0.1); let id = layer_id(s, p)?; let bg = s.tools.background; diff --git a/crates/engine-core/src/color_channels.rs b/crates/engine-core/src/color_channels.rs index 2731e8ae78..c22ff8093d 100644 --- a/crates/engine-core/src/color_channels.rs +++ b/crates/engine-core/src/color_channels.rs @@ -11,7 +11,7 @@ mod tone; mod tone_dialog_tests; pub use crate::state::ColorChannels; -pub(crate) use crate::state::Restriction; +pub use crate::state::Restriction; /// An explicit colour target, checked before command dispatch and allocation. pub fn explicit(p: &Value, count: usize) -> Result> { diff --git a/crates/engine-core/src/content_sampling.rs b/crates/engine-core/src/content_sampling.rs new file mode 100644 index 0000000000..587fe36dbd --- /dev/null +++ b/crates/engine-core/src/content_sampling.rs @@ -0,0 +1,172 @@ +//! Sampling around an area to fill it from its surroundings: Content-Aware fill (Edit › Fill, the +//! Crop tool, the Content-Aware Fill workspace, the retouching tools) and the composite the +//! retouching tools sample. + +use photocraft_algo::content_aware::FillOptions; +use photocraft_color::PixelFormat; +use photocraft_doc::{Document, LayerId}; +use photocraft_geom::Rect; +use photocraft_paint::retouch::Region; +use photocraft_raster::{Surface, from_rgba_into, to_rgba}; + +use crate::pixel_fill::Source; +use crate::{EngineError, Result}; + +/// The selection filled from its surroundings (`photocraft_algo::content_aware`), as straight +/// RGBA over the sampling window. Only the selected pixels are used. +pub fn content_aware(surf: &Surface, sel: &Surface, canvas: Rect, options: &FillOptions) -> Result { + let hole_bounds = sel.content_bounds().intersect(&canvas); + if hole_bounds.is_empty() { + return Err(EngineError::Other("the selection is outside the canvas".into())); + } + let is_hole = |x: i32, y: i32| sel.sample_channel(x, y, 0) > 0.0; + let (window, filled) = content_aware_native_with_options(surf, hole_bounds, canvas, options, is_hole, |_, _| true)?; + let fmt = surf.format(); + let px = filled.chunks_exact(fmt.channels().max(1)).map(|c| to_rgba(&fmt, c)).collect(); + Ok(Source::Pixels(window, px)) +} + +/// The pixels `is_hole` picks inside `hole_bounds` filled from their surroundings +/// (`photocraft_algo::content_aware`): Photoshop's sampling window around `hole_bounds`, sampling +/// only the non-hole pixels `usable` allows. Returns the window and its pixels in the surface's +/// own channels (the hole filled, the rest as read). Shared by Edit › Fill › Content-Aware and the +/// Crop tool's Content-Aware fill (#3823). +pub fn content_aware_native( + surf: &Surface, + hole_bounds: Rect, + canvas: Rect, + color_adaptation: bool, + seed: u64, + is_hole: impl Fn(i32, i32) -> bool, + usable: impl Fn(i32, i32) -> bool, +) -> Result<(Rect, Vec)> { + content_aware_native_with_options(surf, hole_bounds, canvas, &content_aware_options(color_adaptation, seed), is_hole, usable) +} + +/// The adaptation defaults shared by Fill and Content-Aware Crop. +pub fn content_aware_options(color_adaptation: bool, seed: u64) -> FillOptions { + FillOptions { color_adaptation: photocraft_algo::content_aware::color_level(if color_adaptation { "default" } else { "none" }), seed, ..Default::default() } +} + +/// Fill the bounded sampling window with native channel values and the requested adaptations. +fn content_aware_native_with_options( + surf: &Surface, + hole_bounds: Rect, + canvas: Rect, + options: &FillOptions, + is_hole: impl Fn(i32, i32) -> bool, + usable: impl Fn(i32, i32) -> bool, +) -> Result<(Rect, Vec)> { + use photocraft_algo::content_aware::fill; + let window = sampling_window(hole_bounds, canvas); + let n = surf.format().channels(); + let (w, h) = window_size(window)?; + let img = crate::allocation::read_region(surf, window, "Content-Aware fill samples")?; + let len = w.checked_mul(h).ok_or_else(|| EngineError::Other("the area is too large for Content-Aware fill".into()))?; + let mut hole = crate::allocation::filled(len, false, "Content-Aware fill")?; + let mut source = crate::allocation::filled(len, false, "Content-Aware fill")?; + for (i, (hv, sv)) in hole.iter_mut().zip(source.iter_mut()).enumerate() { + let (x, y) = (window.x0 + (i % w) as i32, window.y0 + (i / w) as i32); + *hv = is_hole(x, y); + *sv = !*hv && usable(x, y); + } + if !source.iter().any(|s| *s) { + return Err(EngineError::Other("Content-Aware fill needs pixels outside the area to fill to sample from".into())); + } + if img.len() != len * n { + return Err(EngineError::Other("could not read the layer pixels".into())); + } + Ok((window, fill(w, h, n, &img, &hole, &source, options))) +} + +/// Photoshop's Content-Aware sampling window around the selection bounds `hole` +/// ([`photocraft_algo::content_aware::sampling_window`]): Edit › Fill, the workspace's Rectangular +/// and Auto areas and the retouching tools all copy from within it. Worked out in i64, so a loaded +/// document declaring an absurd selection can't overflow it (#963). +pub fn sampling_window(hole: Rect, canvas: Rect) -> Rect { + photocraft_algo::content_aware::sampling_window(hole.intersect(&canvas), canvas) +} + +/// The size of a Content-Aware sampling window, or an error for a window too large to read and +/// fill (#963). Same cap as other whole-image operations: refuse absurd windows instead of +/// allocating. +pub fn window_size(window: Rect) -> Result<(usize, usize)> { + let (w, h) = (window.width(), window.height()); + if u64::from(w) * u64::from(h) > 400_000_000 { + return Err(EngineError::Other("the selection is too large for Content-Aware fill".into())); + } + Ok((w as usize, h as usize)) +} + +/// [`Surface::read_region`] of `r`, read in parallel bands and asking `cancelled` before each +/// (`None` once it says so): a Content-Aware window can be tens of megapixels. +pub fn read_window(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option> { + use rayon::prelude::*; + const BAND: usize = 64; + let n = surf.channels(); + let (w, h) = (r.width() as usize, r.height() as usize); + let mut out = vec![0.0f32; w * h * n]; + if out.is_empty() { + return Some(out); + } + // Each worker reads its bands through one buffer of its own. + out.par_chunks_mut(BAND * w * n).enumerate().for_each_init(Vec::new, |buf, (i, chunk)| { + if cancelled() { + return; + } + let y0 = r.y0 + (i * BAND) as i32; + let band = Rect::new(r.x0, y0, r.x1, y0 + (chunk.len() / (w * n)) as i32); + surf.read_region_into(band, buf); + if buf.len() == chunk.len() { + chunk.copy_from_slice(buf); + } + }); + if cancelled() { None } else { Some(out) } +} + +/// Channel 0 of [`read_window`] (a selection's or an alpha channel's coverage). +pub fn read_window_mask(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option> { + use rayon::prelude::*; + let n = surf.channels().max(1); + let all = read_window(surf, r, cancelled)?; + if n == 1 { + return Some(all); + } + Some(all.par_chunks_exact(n).map(|px| px[0]).collect()) +} + +/// Which pixels the retouching tools (Clone Stamp, Healing Brush, Remove, Content-Aware Move) sample. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SampleLayers { + Current, + CurrentAndBelow, + All, +} + +/// Composite pixels of `rect` in `fmt` (native channels): the whole document, or the target layer +/// and everything below it. +pub fn composite_region(pre: &Document, id: Option, which: SampleLayers, rect: Rect, fmt: PixelFormat) -> Region { + let mut doc = pre.clone(); + if which == SampleLayers::CurrentAndBelow + && let Some(id) = id + { + // Hide everything composited after (above) the target in the bottom-to-top walk. + let walk: Vec<(Vec, LayerId)> = pre.walk().into_iter().map(|(p, _, l)| (p, l.id)).collect(); + if let Some(pos) = walk.iter().position(|(_, l)| *l == id) { + for (path, _) in &walk[pos + 1..] { + if let Some(l) = doc.layer_at_mut(path) { + l.visible = false; + } + } + } + } + let buf = photocraft_compose::render(&doc, rect); + let n = fmt.channels(); + let mut out = Region::new(rect, n); + let mut enc = [0.0f32; 8]; + for (i, px) in buf.px.iter().enumerate() { + from_rgba_into(&fmt, *px, &mut enc); + out.data[i * n..(i + 1) * n].copy_from_slice(&enc[..n]); + } + out +} diff --git a/crates/engine-core/src/crop_fill.rs b/crates/engine-core/src/crop_fill.rs index cbef2df1e7..6196288576 100644 --- a/crates/engine-core/src/crop_fill.rs +++ b/crates/engine-core/src/crop_fill.rs @@ -185,12 +185,12 @@ fn fill_layer(doc: &mut Document, id: Result, cov: &Coverage, own_pixel // added target may widen its sampling envelope; its hole and output stay unchanged. let usable = |x, y| label(x, y) == 0 && (!own_pixels || has_pixel(x, y)); let sampling_bounds = if let Some(donor_bounds) = donor_bounds { - let window = crate::fill_cmds::sampling_window(*bounds, canvas).intersect(&donor_bounds); + let window = crate::content_sampling::sampling_window(*bounds, canvas).intersect(&donor_bounds); if contains_donor(window, usable) { *bounds } else { widened_sampling_bounds(*bounds, donor_bounds, canvas, n)? } } else { *bounds }; - let (window, px) = crate::fill_cmds::content_aware_native( + let (window, px) = crate::content_sampling::content_aware_native( surf, sampling_bounds, canvas, @@ -239,7 +239,7 @@ fn contains_donor(bounds: Rect, usable: impl Fn(i32, i32) -> bool) -> bool { /// Widens the sampling envelope to include distant donors, after pricing the actual float read. fn widened_sampling_bounds(piece: Rect, donors: Rect, canvas: Rect, channels: usize) -> Result { let expanded = piece.union(&donors); - let window = crate::fill_cmds::sampling_window(expanded, canvas); + let window = crate::content_sampling::sampling_window(expanded, canvas); let bytes = (window.width() as usize) .checked_mul(window.height() as usize) .and_then(|pixels| pixels.checked_mul(channels)) diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 7ac2d13ae7..e9eba47283 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -268,13 +268,13 @@ impl DocState { } /// Record the current revision conservatively until its damage has been determined. - pub(crate) fn record_unknown_damage(&mut self) { + pub fn record_unknown_damage(&mut self) { self.last_damage = None; self.record_damage_span(self.revision.saturating_sub(1), self.revision, None); } /// Record the latest revision or command span after its damage has been determined. - pub(crate) fn record_damage(&mut self) { + pub fn record_damage(&mut self) { // Keep the effect reach at the time of the edit: later pixel-neutral revisions can // change which effects are visible without changing this already-painted damage. // The existing growth walk is recursive, so refuse a bounded answer on hostile depth. diff --git a/crates/engine-core/src/hooks.rs b/crates/engine-core/src/hooks.rs index 7f53e18cca..35c774d402 100644 --- a/crates/engine-core/src/hooks.rs +++ b/crates/engine-core/src/hooks.rs @@ -18,6 +18,8 @@ pub type RequestParams = fn(&Session, &str, &Value) -> Option; pub type Redirect = fn(&Session, &str, &Value) -> Option<(String, Value)>; /// Refuses params the command can't take. pub type CheckParams = fn(&Session, &str, &Value) -> Result<()>; +/// Refuses a command the session can't run now, after core's own admission checks. +pub type Admit = fn(&Session, &str, &Value) -> Result<()>; /// Runs once the params are valid, before the command: `Some` is the command's result, and the /// command itself doesn't run. pub type BeforeCommand = fn(&mut Session, &str, &CommandSpec, &Value) -> Result>; @@ -55,6 +57,9 @@ pub struct Hooks { pub redirect: Vec, /// After the documented-keys check, in `dispatch` and `precheck`; the first error refuses. pub check_params: Vec, + /// At the end of `admit` (in `precheck`, and in `dispatch` before and after a floating + /// selection drops); the first error refuses. + pub admit: Vec, /// Before the command runs; the first `Some` finishes it. pub before_command: Vec, /// After a successful run, each in turn. diff --git a/crates/engine-core/src/install.rs b/crates/engine-core/src/install.rs index 09c9c98af9..3f1eebd31b 100644 --- a/crates/engine-core/src/install.rs +++ b/crates/engine-core/src/install.rs @@ -1,6 +1,7 @@ -//! The engine's command registry: every command table, in registry order, and the install that -//! puts it in place for the process. Until the engine crates are cut out of this one, it holds -//! every engine command, and `photocraft_engine::install()` installs this list. +//! This crate's command tables, slots and hooks, and the install that puts them in place for a +//! process that uses core alone (core's own tests). Until the engine crates are all cut out of +//! this one it holds the commands of the crates still inside it; `photocraft_engine::install()` +//! installs these with every other engine crate's. use std::sync::OnceLock; @@ -10,14 +11,14 @@ use crate::registry::{self, Install, Table}; use crate::smartselect_cmds::{SmartSelectExt, SubjectCache}; use crate::{Result, Session}; -/// Every command table with its name, in registry order. The order is part of the behaviour -/// (menus list commands in it) and `command_ids.txt` pins it. The `table` fragments are grouped by -/// the crate that will own them; a menu split between owners has one fragment per contiguous run. +/// This crate's command tables with their names. The app's registry order comes from +/// `crates/engine/src/install/command_ids.txt`; here they stay in that order, so core alone lists +/// its commands as the app does. The `table` fragments are grouped by the crate that will own +/// them; a menu split between owners has one fragment per contiguous run. const TABLES: &[Table] = &[ ("store::file_menu", crate::cmd::table::store::file_menu::specs), ("core::file_menu", crate::cmd::table::core::file_menu::specs), ("core::edit_menu", crate::cmd::table::core::edit_menu::specs), - ("paint::edit_menu", crate::cmd::table::paint::edit_menu::specs), ("model::edit_menu", crate::cmd::table::model::edit_menu::specs), ("core::select_menu", crate::cmd::table::core::select_menu::specs), ("model::layer_menu", crate::cmd::table::model::layer_menu::specs_before_gradient), @@ -25,7 +26,6 @@ const TABLES: &[Table] = &[ ("model::layer_menu", crate::cmd::table::model::layer_menu::specs_after_gradient), ("model::image_menu", crate::cmd::table::model::image_menu::specs), ("image::image_menu", crate::cmd::table::image::image_menu::specs), - ("paint::stroke", crate::cmd::table::paint::stroke::specs), ("core::tools", crate::cmd::table::core::tools::specs), ("core::queries", crate::cmd::table::core::queries::specs), ("image::adjustments", crate::cmd::table::image::adjustments::specs), @@ -51,23 +51,17 @@ const TABLES: &[Table] = &[ ("edit_cmds", crate::edit_cmds::specs), ("smart_svg_cmds", crate::smart_svg_cmds::specs), ("color_cmds", crate::color_cmds::specs), - ("brush_cmds", crate::brush_cmds::specs), ("brush_preset_cmds", crate::brush_preset_cmds::specs), - ("eraser_cmds", crate::eraser_cmds::specs), ("preset_import_cmds", crate::preset_import_cmds::specs), ("style_asl_cmds", crate::style_asl_cmds::specs), ("atn_cmds", crate::atn_cmds::specs), ("actions_edit_cmds", crate::actions_edit_cmds::specs), ("swatch_cmds", crate::swatch_cmds::specs), - ("retouch_cmds", crate::retouch_cmds::specs), - ("adjustment_brush_cmds", crate::adjustment_brush_cmds::specs), - ("redeye_cmds", crate::redeye_cmds::specs), ("image_cmds", crate::image_cmds::specs), ("perspective_crop_cmds", crate::perspective_crop_cmds::specs), ("selection_cmds", crate::selection_cmds::specs), ("magnetic_cmds", crate::magnetic_cmds::specs), ("select_extra_cmds", crate::select_extra_cmds::specs), - ("paint_cmds", crate::paint_cmds::specs), ("extra_cmds", crate::extra_cmds::specs), ("background_cmds", crate::background_cmds::specs), ("file_cmds", crate::file_cmds::specs), @@ -82,12 +76,7 @@ const TABLES: &[Table] = &[ ("layer_copy_cmds", crate::layer_copy_cmds::specs), ("prefs", crate::prefs::specs), ("edit_menu_cmds", crate::edit_menu_cmds::specs), - ("fill_key_cmds", crate::fill_key_cmds::specs), ("sample_cmds", crate::sample_cmds::specs), - ("face_cmds", crate::face_cmds::specs), - ("sampler_cmds", crate::sampler_cmds::specs), - ("brush_key_cmds", crate::brush_key_cmds::specs), - ("stamp_cmds", crate::stamp_cmds::specs), ("align_cmds", crate::align_cmds::specs), ("photo_cmds", crate::photo_cmds::specs), ("lens_cmds", crate::lens_cmds::specs), @@ -123,7 +112,6 @@ const TABLES: &[Table] = &[ ("automate_cmds", crate::automate_cmds::specs), ("print_cmds", crate::print_cmds::specs), ("installed_profiles", crate::installed_profiles::specs), - ("pick_cmds", crate::pick_cmds::specs), ("layer_nav_cmds", crate::layer_nav_cmds::specs), ("frame_cmds", crate::frame_cmds::specs), ("migrate_cmds", crate::migrate_cmds::specs), @@ -143,6 +131,11 @@ const TABLES: &[Table] = &[ ("actions_cmds", crate::actions_cmds::specs), ]; +/// This crate's command tables, in registry order. +pub fn command_tables() -> &'static [Table] { + TABLES +} + /// Install this crate's commands for the process. Later calls return the first call's result. pub fn install() -> Result<()> { static INSTALLED: OnceLock> = OnceLock::new(); @@ -156,10 +149,10 @@ pub fn install() -> Result<()> { .clone() } -/// This crate's session slots and pipeline hooks, grouped by the crate that will own them. Until the -/// engine crates are cut out of this one, it holds every engine hook. A stage runs its hooks in the order written +/// This crate's session slots and pipeline hooks, grouped by the crate that will own them. Until the engine crates are +/// all cut out of this one, it holds their hooks. A stage runs its hooks in the order written /// here: store comes last so that `sync_preset_store` runs after the other after-command hooks. -fn register(install: &mut Install) { +pub fn register(install: &mut Install) { // Session slots, by owner crate. model: install.slot::(); // image @@ -190,9 +183,6 @@ fn register(install: &mut Install) { // An edited Edit Contents document updates its parent as it closes. hooks.document_closing.push(crate::smart_cmds::on_close); - // paint - hooks.coalesce_journal.push(crate::brush_cmds::coalesce_journal); - // image hooks.redirect.push(crate::filters::repeat_last_filter); hooks.check_params.push(|_, id, p| crate::filters::validate_params(id, p)); @@ -236,6 +226,3 @@ pub fn session() -> Session { let _ = install(); Session::new() } - -#[cfg(test)] -mod order_tests; diff --git a/crates/engine-core/src/install/order_tests.rs b/crates/engine-core/src/install/order_tests.rs deleted file mode 100644 index b8228063e2..0000000000 --- a/crates/engine-core/src/install/order_tests.rs +++ /dev/null @@ -1,35 +0,0 @@ -use super::TABLES; - -const HINT: &str = "\nadd the id to crates/engine-core/src/install/command_ids.txt, or run this test with PHOTOCRAFT_WRITE_COMMAND_IDS=1 and review the diff"; - -/// Menus, the Command Palette and the automation docs list commands in registry order, so the -/// order is part of the behaviour. `command_ids.txt` pins it; regenerate the file from main when -/// rebasing, adding each new command's id after its predecessor. With `PHOTOCRAFT_WRITE_COMMAND_IDS` -/// set, the test writes the file from the tables instead; review the diff before committing it. -#[test] -fn registered_command_ids_keep_their_order() { - let ids: Vec<&str> = TABLES.iter().flat_map(|(_, specs)| specs()).map(|c| c.id).collect(); - if std::env::var_os("PHOTOCRAFT_WRITE_COMMAND_IDS").is_some() { - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/install/command_ids.txt"); - std::fs::write(path, ids.iter().map(|id| format!("{id}\n")).collect::()).expect("write command_ids.txt"); - return; - } - let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect(); - if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) { - panic!("command {i} is {} where {} was registered{}{HINT}", ids[i], expected[i], table_of(i)); - } - assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}{HINT}", table_of(ids.len().min(expected.len()))); -} - -/// Names the table that registers command `index`, for the failure message. -fn table_of(index: usize) -> String { - let mut first = 0; - for (name, specs) in TABLES { - let len = specs().len(); - if index < first + len { - return format!(" (table `{name}`, commands {first}..{})", first + len); - } - first += len; - } - String::new() -} diff --git a/crates/engine-core/src/jobs.rs b/crates/engine-core/src/jobs.rs index 11bb0d7ddf..ba8b87aaca 100644 --- a/crates/engine-core/src/jobs.rs +++ b/crates/engine-core/src/jobs.rs @@ -1744,7 +1744,7 @@ impl Session { result } - fn dispatch_with_commit(&mut self, id: &str, params: Value, background: bool, live_commit: Option) -> Result { + fn dispatch_with_commit(&mut self, id: &str, params: Value, background: bool, live_commit: Option) -> Result { let spec = crate::registry::spec(id)?; let hooks = crate::registry::hooks(); // Params are named fields: anything but an object (or null, meaning none) is a caller diff --git a/crates/engine-core/src/layer_place.rs b/crates/engine-core/src/layer_place.rs index 6e0589f123..762daea8a7 100644 --- a/crates/engine-core/src/layer_place.rs +++ b/crates/engine-core/src/layer_place.rs @@ -96,6 +96,23 @@ pub fn insert_new(doc: &mut Document, anchor: Option, mut layer: Layer, id } +/// A plain, unlocked pixel layer with no pixels, mask, clipping or video: a layer Stamp Visible or a pattern fill fills instead of adding one. +/// Pixels it has only through a visible default pixel (no tiles stored) count as pixels. +pub fn is_empty_pixel_layer(doc: &Document, id: LayerId) -> bool { + let Some(l) = doc.layer(id) else { return false }; + let locks = doc.effective_locks(id); + // Only the default pixel's alpha counts: a mode or profile conversion keeps it transparent but + // gives its colour channels other values (no ink in CMYK, a neutral a/b in Lab). + matches!(&l.content, LayerContent::Raster(s) + if s.content_bounds().is_empty() && s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)) + && l.video.is_none() + && l.visible + && l.mask.is_none() + && l.vector_mask.is_none() + && !l.clipped + && !(locks.all || locks.pixels || locks.transparency) +} + /// The pixel holding the middle of `bounds`, which decides the board content is on: a new or /// pasted layer, or one the Move tool drops (auto-nesting). The edges are added before halving /// (halving each first put 9..11 at 9) and the sum is floored, not truncated toward zero (which diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index 2da881b44c..13ca77bb5d 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -11,11 +11,13 @@ mod action_history; mod actions_record; pub mod adjust_params; pub mod allocation; +pub mod brush_defs; pub mod build_info; mod canvas_geom; mod channel_clip; mod clip_group; pub mod color_channels; +pub mod content_sampling; mod crop_fill; mod damage; pub mod display_color; @@ -25,7 +27,7 @@ pub mod filters_ext; mod group_options; pub mod guide_layout; pub mod hidden_target; -mod hooks; +pub mod hooks; pub mod inspect; pub mod installed_profiles; pub mod jobs; @@ -40,6 +42,7 @@ pub mod new_layer; mod param_check; pub use param_check::is_incomplete; pub mod param_schema; +pub mod pixel_fill; mod pixels; pub mod prefs; pub mod preset_store; @@ -167,12 +170,14 @@ pub use cmd::vp_cmds; pub use cmd::warp_cmds; pub use cmd::web_cmds; pub use cmd::wia_cmds; +pub use state::LiveCommit; pub use doc_state::{CopiedStyle, DocState, DocStateInputs, PRECHECKED, ToolState, selected_in}; pub use error::{EngineError, Result}; -pub use install::{install, session}; +pub use install::{command_tables, install, register, session}; pub use session::move_item; use session::restore_target; -pub(crate) use session::{carry_visibility, fix_selection, visibility_changes}; +pub(crate) use session::{carry_visibility, visibility_changes}; +pub use session::fix_selection; /// A type layer for [`Session::refresh_type_layers`]: in the open document, or in its first /// History snapshot (the document as opened) when `first_snapshot`. The caller picks each against @@ -186,13 +191,13 @@ pub struct TypeLayerRef { /// The pixels of a raster layer (typically one a command just created), as an error instead /// of a panic if the layer has none. -pub(crate) fn pixels_mut(l: &mut photocraft_doc::Layer) -> Result<&mut photocraft_raster::Surface> { +pub fn pixels_mut(l: &mut photocraft_doc::Layer) -> Result<&mut photocraft_raster::Surface> { let id = l.id; l.surface_mut().ok_or_else(|| EngineError::Other(format!("layer {id:?} has no pixels"))) } /// The active document's active layer, for `enabled` predicates. -pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_doc::Layer, String> { +pub fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_doc::Layer, String> { let d = s.active().ok_or("no document open")?; d.active_layer.and_then(|id| d.doc.layer(id)).ok_or_else(|| "no active layer".into()) } @@ -305,8 +310,8 @@ pub struct Session { /// ([`LinkWatchExt::missing_links`](crate::link_watch::LinkWatchExt::missing_links)). Written only when the set changes, so its revision says when the list did. link_missing: craft_tracked::Tracked>, /// A finished live stroke offered to the `paint.stroke` / `paint.pencil` that commits it - /// ([`Session::offer_live_stroke`]). - pub(crate) live_commit: Option, + /// (`photocraft_engine_paint::brush_cmds::LiveStrokeExt` and `retouch_cmds::LiveRetouchExt` offer it). + pub live_commit: Option, /// Documents a background open decoded but held back until the user answers the profile /// prompt ([`ColorState::open_question`](color_cmds::ColorState::open_question)): `(id, /// document, source read-only)`. The shell takes them with [`Session::take_held_open`]. diff --git a/crates/engine-core/src/pixel_fill.rs b/crates/engine-core/src/pixel_fill.rs new file mode 100644 index 0000000000..682a6adfa9 --- /dev/null +++ b/crates/engine-core/src/pixel_fill.rs @@ -0,0 +1,269 @@ +//! Filling and blending pixels into a surface: Edit › Fill's compositing, which Edit › Clear, +//! Edit › Stroke, pastes into masks and channels, a floating selection and the painting tools share. + +use photocraft_color::BlendMode; +use photocraft_geom::{Rect, TILE_SIZE}; +use photocraft_raster::{Surface, from_rgba_into, to_rgba}; + +use crate::{EngineError, Result}; + +/// What a pixel of the filled area gets before blending. +pub enum Source { + Color([f32; 4]), + /// An opaque colour that was picked as CMYK inks: `rgba` is its sRGB stand-in (what other + /// colour models and blend modes use), `cmyk` the inks a CMYK target gets as they are. + Cmyk { + rgba: [f32; 4], + cmyk: [f32; 4], + }, + /// Straight RGBA per pixel of `rect` (row-major). + Pixels(Rect, Vec<[f32; 4]>), +} + +impl Source { + /// The straight RGBA the pixel at (`x`, `y`) gets before blending. + pub fn at(&self, x: i32, y: i32) -> [f32; 4] { + match self { + Source::Color(c) => *c, + Source::Cmyk { rgba, .. } => *rgba, + Source::Pixels(r, px) => { + if !r.contains(x, y) { + return [0.0; 4]; + } + let i = (y - r.y0) as usize * r.width() as usize + (x - r.x0) as usize; + px.get(i).copied().unwrap_or([0.0; 4]) + } + } + } +} + +/// `source`'s opaque colour as samples of `fmt` (alpha last, as in [`from_rgba_into`]), or `None` +/// for a source that is not one colour. A CMYK pick keeps its inks in a CMYK target. +pub fn encode_color(fmt: &photocraft_color::PixelFormat, source: &Source, enc: &mut [f32; 8]) -> Option { + let (rgba, cmyk) = match source { + Source::Color(c) if c[3] >= 1.0 => (*c, None), + Source::Cmyk { rgba, cmyk } => (*rgba, Some(*cmyk)), + _ => return None, + }; + let n = from_rgba_into(fmt, rgba, enc); + if let Some(k) = cmyk + && fmt.mode == photocraft_color::ColorMode::Cmyk + { + enc[..4].copy_from_slice(&k); + } + Some(n) +} + +/// `area` of `src` as straight RGBA, or an error naming `purpose` when it doesn't fit in memory. +pub fn read_rgba(src: &Surface, area: Rect, purpose: &str) -> Result> { + let len = (area.width() as usize) + .checked_mul(area.height() as usize) + .ok_or_else(|| EngineError::Other(format!("not enough memory for {purpose} (requested size overflowed); the document was not changed")))?; + let mut px = crate::allocation::filled(len, [0.0f32; 4], purpose)?; + src.read_rgba_into(area, &mut px); + Ok(px) +} + +/// `src` over `surf` across `area` (Normal, 100 %), each pixel weighted by `limit` when given: +/// a paste into a layer mask or channel, which keeps the pasted pixels' luminosity (#1035). +pub fn composite_over(surf: &mut Surface, src: &Surface, area: Rect, limit: Option<&Surface>) -> Result<()> { + let source = Source::Pixels(area, read_rgba(src, area, "pasting pixels")?); + blend_into(surf, area, &source, limit, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false }) +} + +/// `area` of `surf` filled with an opaque `color` (Normal, 100 %), weighted by `sel` when given: +/// Clear on a targeted alpha channel or the Quick Mask (#2734). +pub fn fill_color(surf: &mut Surface, area: Rect, color: [f32; 4], sel: Option<&Surface>) -> Result<()> { + blend_into(surf, area, &Source::Color(color), sel, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false }) +} + +/// Reuse Edit › Fill's compositing for Edit › Stroke. The stroke's rasterized band +/// is already a grayscale coverage mask; opacity, blend modes and alpha locking +/// must behave identically for both commands at 8/16/32-bit depth. +#[allow(clippy::too_many_arguments)] +pub fn blend_color_mask( + surf: &mut Surface, + area: Rect, + color: [f32; 4], + picked: Option<[f32; 4]>, + coverage: &Surface, + mode: BlendMode, + opacity: f32, + preserve_transparency: bool, +) -> Result<()> { + let source = match picked { + Some(cmyk) if color[3] >= 1.0 => Source::Cmyk { rgba: color, cmyk }, + _ => Source::Color(color), + }; + blend_into(surf, area, &source, Some(coverage), Blend { mode, opacity, keep_alpha: preserve_transparency, restore: false }) +} + +/// How the source goes onto the target. +#[derive(Clone, Copy)] +pub struct Blend { + pub mode: BlendMode, + pub opacity: f32, + /// Leave every pixel's alpha as it was (Preserve Transparency, or locked transparency). + pub keep_alpha: bool, + /// Normal mode replaces the pixels, transparency included (History: back to that state). + pub restore: bool, +} + +/// `d` moved towards `c` by `k`, in premultiplied space (straight RGBA in and out). +pub fn lerp(d: [f32; 4], c: [f32; 4], k: f32) -> [f32; 4] { + let a = d[3] * (1.0 - k) + c[3] * k; + if a <= 0.0 { + return [0.0; 4]; + } + let ch = |i: usize| (d[i] * d[3] * (1.0 - k) + c[i] * c[3] * k) / a; + [ch(0), ch(1), ch(2), a] +} + +/// Blend `source` into `surf` over `area`: per pixel, the selection coverage times the opacity, +/// in the blend mode. +/// Works tile by tile in parallel on the encoded pixels (no full-surface f32 round trip). +pub fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<&Surface>, b: Blend) -> Result<()> { + use rayon::prelude::*; + let fmt = surf.format(); + // An opaque colour in Normal mode at 100 % that may replace alpha: fully covered tiles become + // one shared solid tile (copy-on-write), which costs nothing per pixel. + let mut enc = [0.0f32; 8]; + let solid = match encode_color(&fmt, source, &mut enc) { + Some(n) if b.mode == BlendMode::Normal && b.opacity >= 1.0 && (!b.keep_alpha || !fmt.alpha) => Some(surf.solid_tile(enc.get(..n).unwrap_or(&[]))), + _ => None, + }; + let count = area.tiles().count(); + let done = crate::allocation::capacity(count, "blending pixels")?; + let tiles = surf + .try_take_tiles(area) + .map_err(|e| EngineError::Other(format!("not enough memory while preparing pixel tiles ({e}); the document was not changed")))?; + let done = std::sync::Mutex::new(done); + tiles.into_par_iter().try_for_each(|(tc, tile)| -> Result<()> { + let tr = tc.rect().intersect(&area); + let mask = sel.map(|m| Mask::of(m, tc)); + if let Some(s) = &solid + && tr == tc.rect() + && mask.as_ref().is_none_or(|m| m.full(tr)) + { + done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((tc, s.clone())); + return Ok(()); + } + // Nothing selected in this tile (or no opacity): `blend_tile` would leave every pixel as + // it is, so keep the tile itself rather than a copy the history would hold again (#4517). + if b.opacity <= 0.0 || mask.as_ref().is_some_and(|m| m.empty(tr)) { + done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((tc, tile)); + return Ok(()); + } + let mut tile = match std::sync::Arc::try_unwrap(tile) { + Ok(tile) => tile, + Err(tile) => tile + .try_clone() + .map_err(|e| EngineError::Other(format!("not enough memory while blending a pixel tile ({e}); the document was not changed")))?, + }; + blend_tile(&mut tile.bytes_mut(), &fmt, tc.rect(), tr, source, mask.as_ref(), b); + done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((tc, std::sync::Arc::new(tile))); + Ok(()) + })?; + let done = done.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner); + surf.put_tiles(done); + Ok(()) +} + +/// The selection's coverage over one tile (its channel 0). +pub struct Mask<'a> { + bytes: Option>, + default: &'a [u8], + fmt: photocraft_color::PixelFormat, + origin: Rect, +} + +impl<'a> Mask<'a> { + /// `sel` over the tile at `tc` (its default pixel where it has no tile there). + pub fn of(sel: &'a Surface, tc: photocraft_geom::TileCoord) -> Self { + Mask { bytes: sel.tile(tc).map(|t| t.bytes()), default: sel.default_bytes(), fmt: sel.format(), origin: tc.rect() } + } + pub fn at(&self, x: i32, y: i32) -> f32 { + let bytes = self.bytes.as_deref().unwrap_or(self.default); + let bpp = self.fmt.bytes_per_pixel(); + // A default-pixel mask is one pixel long: every position reads it. + let i = if bytes.len() == bpp { 0 } else { ((y - self.origin.y0) as usize * TILE_SIZE as usize + (x - self.origin.x0) as usize) * bpp }; + bytes.get(i..i + bpp).map_or(0.0, |px| photocraft_color::read_sample(px, self.fmt.sample, 0)) + } + /// Fully selected over `r`? + pub fn full(&self, r: Rect) -> bool { + (r.y0..r.y1).all(|y| (r.x0..r.x1).all(|x| self.at(x, y) >= 1.0)) + } + /// Whether nothing in `r` is selected. + pub fn empty(&self, r: Rect) -> bool { + (r.y0..r.y1).all(|y| (r.x0..r.x1).all(|x| self.at(x, y) <= 0.0)) + } +} + +/// Blend into one tile's encoded pixels (`bytes`, the tile at `origin`) over `tr`. +pub fn blend_tile(bytes: &mut [u8], fmt: &photocraft_color::PixelFormat, origin: Rect, tr: Rect, source: &Source, mask: Option<&Mask>, b: Blend) { + let Blend { mode, opacity, keep_alpha, restore } = b; + let n = fmt.channels(); + let bpp = fmt.bytes_per_pixel(); + let blend = if mode == BlendMode::Dissolve { BlendMode::Normal } else { mode }; + let mut px = [0.0f32; 8]; + let mut enc = [0.0f32; 8]; + // An opaque colour at full coverage in Normal mode just replaces the colour (and the alpha + // unless it is kept): copy its encoded bytes. + let opaque = match encode_color(fmt, source, &mut enc) { + Some(m) if mode == BlendMode::Normal => { + let mut bytes = vec![0u8; bpp]; + photocraft_raster::encode_pixel(fmt, enc.get(..m.min(n)).unwrap_or(&[]), &mut bytes); + // Keeping alpha: copy the colour samples only (alpha is the last sample). + let keep = if keep_alpha && fmt.alpha { bpp - bpp / n.max(1) } else { bpp }; + Some((bytes, keep)) + } + _ => None, + }; + for y in tr.y0..tr.y1 { + let row = (y - origin.y0) as usize * TILE_SIZE as usize; + for x in tr.x0..tr.x1 { + let mut k = mask.map_or(1.0, |m| m.at(x, y)) * opacity; + if k <= 0.0 { + continue; + } + let i = (row + (x - origin.x0) as usize) * bpp; + let Some(pb) = bytes.get_mut(i..i + bpp) else { continue }; + if k >= 1.0 + && let Some((enc_px, keep)) = &opaque + { + if let (Some(dst), Some(src)) = (pb.get_mut(..*keep), enc_px.get(..*keep)) { + dst.copy_from_slice(src); + } + continue; + } + for (c, v) in px.iter_mut().enumerate().take(n) { + *v = photocraft_color::read_sample(pb, fmt.sample, c); + } + let d = to_rgba(fmt, &px[..n.min(8)]); + let mut c = source.at(x, y); + if mode == BlendMode::Dissolve { + // Dissolve: each pixel is either fully painted or untouched, with the coverage as odds. + k = if photocraft_color::dither_noise(x, y) < c[3] * k { 1.0 } else { 0.0 }; + c[3] = 1.0; + if k <= 0.0 { + continue; + } + } + let keep = keep_alpha || !fmt.alpha; + let mut o = if restore && blend == BlendMode::Normal { + lerp(d, c, k) + } else if keep { + // Alpha kept: source atop, so a half-transparent pixel takes the new colour by the + // source alpha alone (#5783). + photocraft_color::blend::composite_atop(blend, d, c, k) + } else { + photocraft_color::blend::composite(blend, d, c, k) + }; + if keep { + o[3] = d[3]; + } + let m = from_rgba_into(fmt, o, &mut enc); + photocraft_raster::encode_pixel(fmt, enc.get(..m.min(n)).unwrap_or(&[]), pb); + } + } +} diff --git a/crates/engine-core/src/pixels.rs b/crates/engine-core/src/pixels.rs index ae27445174..61faa18a95 100644 --- a/crates/engine-core/src/pixels.rs +++ b/crates/engine-core/src/pixels.rs @@ -475,7 +475,7 @@ fn edit_tiles( .into_par_iter() .map(|tc| -> crate::Result>)>> { let tr = tc.rect().intersect(&area); - let mask = selection.map(|m| crate::fill_cmds::Mask::of(m, tc)); + let mask = selection.map(|m| crate::pixel_fill::Mask::of(m, tc)); let full = tr == tc.rect() && mask.as_ref().is_none_or(|m| m.full(tr)); let current = surf.tile(tc); match whole(full) { diff --git a/crates/engine-core/src/preset_store.rs b/crates/engine-core/src/preset_store.rs index 840a2f4497..3c41b5b8e1 100644 --- a/crates/engine-core/src/preset_store.rs +++ b/crates/engine-core/src/preset_store.rs @@ -508,6 +508,17 @@ pub struct TipCacheStats { pub limit: u64, } +/// After brush preset `name` was deleted (Delete Brush Preset, or Edit › Presets › Preset Manager): the current +/// brush no longer comes from a preset, and the library is saved. +pub fn forget_deleted_preset(s: &mut Session, name: &str) { + if s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(name)) { + s.tools.current_preset = None; + // The remembered brush names the preset it was picked from: the name went away. + s.tools.brush_changed(); + } + s.brush_presets_changed(); +} + /// The session's preset store (a session slot of this crate): `None` keeps presets session-only, as /// in headless and test sessions. The same store holds the Actions list. pub trait PresetStoreExt { diff --git a/crates/engine-core/src/presets/clone_source.rs b/crates/engine-core/src/presets/clone_source.rs index d82bf4c4e9..7b22e301da 100644 --- a/crates/engine-core/src/presets/clone_source.rs +++ b/crates/engine-core/src/presets/clone_source.rs @@ -25,7 +25,7 @@ use crate::{Result, Session}; pub const SLOTS: usize = 5; /// A stroke from a slot whose source document was closed. -pub(crate) const SOURCE_CLOSED: &str = "the clone source's document was closed: set a new source (Alt-click, or cloneSource.set)"; +pub const SOURCE_CLOSED: &str = "the clone source's document was closed: set a new source (Alt-click, or cloneSource.set)"; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct CloneSource { @@ -214,7 +214,7 @@ pub fn transform_matrix(scale: [f64; 2], rotation_deg: f64, flip_h: bool, flip_v /// Null optional coordinates are omitted. Geometry, sampling and commit metadata must agree /// on this decision so an empty optional field cannot switch the source document. -pub(crate) fn uses_slot(p: &Value) -> bool { +pub fn uses_slot(p: &Value) -> bool { ["source", "offset"].into_iter().all(|key| p.get(key).is_none_or(Value::is_null)) } diff --git a/crates/engine-core/src/registry.rs b/crates/engine-core/src/registry.rs index af7e12a389..b2862a6937 100644 --- a/crates/engine-core/src/registry.rs +++ b/crates/engine-core/src/registry.rs @@ -35,11 +35,16 @@ pub type Table = (&'static str, fn() -> Vec); /// What a process installs before its first session. #[derive(Default)] pub struct Install { - /// Registry order: these tables in turn, each in its own order. Menus, the Command Palette - /// and `command.list` list commands in it. + /// The commands: these tables in turn, each in its own order, which is the registry order + /// unless [`Self::order`] gives one. Menus, the Command Palette and `command.list` list + /// commands in registry order. pub commands: Vec, + /// The registry order across the tables of several crates: command ids, one per line. Commands + /// it lists come in its order, then any others in table order. The app's comes from + /// `crates/engine/src/install/command_ids.txt`. + pub order: Option<&'static str>, /// The pipeline hooks of the crates whose tables these are. - pub(crate) hooks: Hooks, + pub hooks: Hooks, /// The session slots of the crates whose tables these are, one per type. pub(crate) slots: Vec, } @@ -174,7 +179,7 @@ impl InstallCell { fn registry(&self) -> Result<&Registry> { let install = self.installed()?; - Ok(self.registry.get_or_init(|| Registry::new(build(&install.commands)))) + Ok(self.registry.get_or_init(|| Registry::new(build(&install.commands, install.order)))) } } @@ -198,13 +203,18 @@ impl Registry { } } -/// Every command of `tables`, in their order. -fn build(tables: &[Table]) -> Vec { +/// Every command of `tables`, in registry order: by `order` where it lists them, else in table order. +fn build(tables: &[Table], order: Option<&str>) -> Vec { let specs = tables.iter().flat_map(|(_, specs)| specs()); // The dispatch guard's unit test needs a command that panics on purpose (REL-3). #[cfg(test)] let specs = specs.chain(std::iter::once(test_panic_command())); - specs.collect() + let mut specs: Vec = specs.collect(); + if let Some(order) = order { + let rank: HashMap<&str, usize> = order.lines().enumerate().map(|(i, id)| (id, i)).collect(); + specs.sort_by_key(|c| rank.get(c.id).copied().unwrap_or(usize::MAX)); + } + specs } /// A command whose `run` panics on purpose, so the last-resort guard in `jobs::dispatch` @@ -251,4 +261,13 @@ mod tests { assert_eq!(conflict, EngineError::InstallConflict { at: 1, installed: "(none)".into(), requested: "b".into() }); assert_eq!(cell.registry().err(), Some(conflict), "every later lookup reports the conflict"); } + + #[test] + fn an_order_sorts_the_commands_of_several_tables_and_keeps_the_rest_after_them() { + let a: Table = ("a", || vec![spec("a.one"), spec("a.two")]); + let b: Table = ("b", || vec![spec("b.one"), spec("b.two")]); + let ids = |specs: Vec| specs.into_iter().map(|c| c.id).filter(|id| *id != "test.panic").collect::>(); + assert_eq!(ids(build(&[a, b], None)), ["a.one", "a.two", "b.one", "b.two"]); + assert_eq!(ids(build(&[a, b], Some("b.one\na.two\na.one\n"))), ["b.one", "a.two", "a.one", "b.two"]); + } } diff --git a/crates/engine-core/src/session.rs b/crates/engine-core/src/session.rs index 8489892b5b..09284479d6 100644 --- a/crates/engine-core/src/session.rs +++ b/crates/engine-core/src/session.rs @@ -1,8 +1,6 @@ use super::doc_state::DocState; use super::error::{EngineError, Result}; -use super::{ - Arc, Document, LayerId, LayerTarget, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, retouch_cmds, smart_cmds, type_cmds, -}; +use super::{Arc, Document, LayerId, LayerTarget, Session, Value, channel_cmds, commands, hidden_target, jobs, smart_cmds, type_cmds}; mod documents; mod execute; @@ -10,4 +8,5 @@ mod history; mod layers; pub use documents::move_item; -pub(crate) use history::{carry_visibility, fix_selection, restore_target, visibility_changes}; +pub(crate) use history::{carry_visibility, restore_target, visibility_changes}; +pub use history::fix_selection; diff --git a/crates/engine-core/src/session/execute.rs b/crates/engine-core/src/session/execute.rs index 284ea32e2b..6bbecf98ff 100644 --- a/crates/engine-core/src/session/execute.rs +++ b/crates/engine-core/src/session/execute.rs @@ -1,5 +1,5 @@ use super::history::{fix_selection, visibility_changes}; -use super::{Arc, Document, EngineError, LayerId, Result, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, retouch_cmds, smart_cmds}; +use super::{Arc, Document, EngineError, LayerId, Result, Session, Value, channel_cmds, commands, hidden_target, jobs, smart_cmds}; use crate::color_channels; impl Session { @@ -22,35 +22,6 @@ impl Session { } } - /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose - /// params match it exactly takes its pixels instead of rendering the stroke again (its result - /// then says `"fromLive": true`); any other command drops the offer. The command still runs - /// through the normal dispatch, so authorization, the journal and history are unchanged. - pub fn offer_live_stroke(&mut self, live: brush_cmds::LiveStroke) -> Result<()> { - self.live_commit = Some(live.into_commit()?); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Clone Stamp or History Brush stroke, taken by the - /// `paint.cloneStamp` / `paint.historyBrush` it was drawn for. Refused for the Healing Brush - /// (it blends on release) and when the brush, layer or clone source changed during the stroke. - pub fn offer_live_retouch(&mut self, live: retouch_cmds::LiveRetouch) -> Result<()> { - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, - /// taken by the command it was drawn for: the stroke's finishing dabs are run first. Refused - /// when the brush, tool options or layer changed during the stroke. - pub fn offer_live_dab(&mut self, live: retouch_cmds::LiveDab) -> Result<()> { - // A refused offer withdraws the previous one too. - self.live_commit = None; - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - /// Withdraw an offer the command didn't take. pub fn clear_live_stroke(&mut self) { self.live_commit = None; @@ -98,8 +69,8 @@ impl Session { /// What `dispatch` checks once the params are valid, before a floating selection drops (so a /// refused command leaves it floating) and again after: the precondition (on a named layer - /// for commands that take one), a job running on the document, a hidden target, the Magic - /// Eraser's colour-mode alert. The run params (the Channels panel's target filled in) when it + /// for commands that take one), a job running on the document, a hidden target, then the + /// engine crates' `admit` hooks (the Magic Eraser's colour-mode alert). The run params (the Channels panel's target filled in) when it /// may run. pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); @@ -116,12 +87,8 @@ impl Session { if let Some(why) = hidden_target::refusal(self, id, params) { return Err(EngineError::Other(why.into())); } - // The Magic Eraser's alert for an Indexed Color or Bitmap document (#12032), the same - // error its `run` gives: checked here too, so a floating selection stays floating (#13169). - if id == "paint.magicEraser" - && let Some(why) = self.active().and_then(|st| crate::eraser_cmds::magic_eraser_refusal(&st.doc)) - { - return Err(EngineError::Other(why.into())); + for admit in &crate::registry::hooks().admit { + admit(self, id, params)?; } Ok(run_params) } diff --git a/crates/engine-core/src/session/history.rs b/crates/engine-core/src/session/history.rs index cbfd25691c..6d5662f098 100644 --- a/crates/engine-core/src/session/history.rs +++ b/crates/engine-core/src/session/history.rs @@ -206,7 +206,7 @@ pub(crate) fn restore_target(st: &mut DocState, layers: LayerTarget) { /// Keep the layer selection valid after the document or the active layer changed: drop deleted /// layers, and collapse to the active layer when a command made a non-member active. -pub(crate) fn fix_selection(st: &mut DocState) { +pub fn fix_selection(st: &mut DocState) { let Some(active) = st.active_layer else { st.selection_mut().clear(); return; diff --git a/crates/engine-core/src/state.rs b/crates/engine-core/src/state.rs index 47589a06e8..24674e6eff 100644 --- a/crates/engine-core/src/state.rs +++ b/crates/engine-core/src/state.rs @@ -247,7 +247,7 @@ pub struct ColorChannels(u64); /// The colour channels the running command may change, on one layer. #[derive(Clone, Copy, Debug)] -pub(crate) struct Restriction { +pub struct Restriction { pub colors: ColorChannels, pub layer: photocraft_doc::LayerId, } @@ -286,21 +286,21 @@ impl ColorChannels { // --------------------------------------------------------------------------------------------- // Live strokes (`brush_cmds`) -/// A finished live stroke offered to its own commit ([`Session::offer_live_stroke`], -/// [`Session::offer_live_retouch`]): when the committing command matches it (same command, +/// A finished live stroke offered to its own commit (the paint crate's `offer_live_stroke` and +/// `offer_live_retouch`): when the committing command matches it (same command, /// document revision, params, seed and points), it takes these pixels instead of rendering the /// stroke again. pub struct LiveCommit { /// Mixer load before and after the stroke; transient, never serialized into the journal. - pub(crate) mixer: Option<(MixerState, MixerState)>, - pub(crate) cmd: String, - pub(crate) base: (photocraft_doc::DocId, u64), - pub(crate) params: Value, + pub mixer: Option<(MixerState, MixerState)>, + pub cmd: String, + pub base: (photocraft_doc::DocId, u64), + pub params: Value, /// The Brush's and Pencil's seed; the retouching tools have none. - pub(crate) seed: Option, - pub(crate) points: Vec, - pub(crate) surface: Surface, - pub(crate) bounds: Rect, + pub seed: Option, + pub points: Vec, + pub surface: Surface, + pub bounds: Rect, } impl LiveCommit { @@ -314,7 +314,8 @@ impl LiveCommit { p } - pub(crate) fn matches(&self, s: &Session, cmd: &str, p: &Value, pts: &[StrokePoint]) -> bool { + /// Whether a commit of `cmd` with `p` and `pts` on the session's active document takes these pixels. + pub fn matches(&self, s: &Session, cmd: &str, p: &Value, pts: &[StrokePoint]) -> bool { let base = s.active().map(|st| (st.doc.id, st.revision)); self.cmd == cmd && base == Some(self.base) diff --git a/crates/engine-paint/Cargo.toml b/crates/engine-paint/Cargo.toml new file mode 100644 index 0000000000..207bc66b0f --- /dev/null +++ b/crates/engine-paint/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "photocraft-engine-paint" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +# The painting commands of the engine (photocraft#15710): brushes, erasers, retouching, fills, +# gradients, red eye, samplers, stamps and the Move tool's picking. Built on photocraft-engine-core. +[dependencies] +photocraft-engine-core = { workspace = true } +craft-cms = { workspace = true } +photocraft-algo = { workspace = true } +photocraft-color = { workspace = true } +photocraft-compose = { workspace = true } +photocraft-doc = { workspace = true } +photocraft-geom = { workspace = true } +photocraft-io = { workspace = true } +photocraft-paint = { workspace = true } +photocraft-raster = { workspace = true } +rayon = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } + +# Core's allocation failpoints, which the brush and fill tests arm. +[dev-dependencies] +photocraft-engine-core = { workspace = true, features = ["failpoints"] } diff --git a/crates/engine-paint/src/cmd.rs b/crates/engine-paint/src/cmd.rs new file mode 100644 index 0000000000..d5d0373ae8 --- /dev/null +++ b/crates/engine-paint/src/cmd.rs @@ -0,0 +1,37 @@ +//! The painting commands, one module per tool family, and their command-table fragments. + +macro_rules! cmd { + ($($spec:tt)*) => { photocraft_engine_core::command_spec!($($spec)*) }; +} + +pub mod adjustment_brush_cmds; +#[cfg(test)] +mod adjustment_brush_cmds_tests; +pub mod brush_cmds; +pub mod brush_key_cmds; +pub mod eraser_cmds; +pub mod face_cmds; +pub mod fill_cmds; +pub mod fill_key_cmds; +#[cfg(test)] +mod gradient_alpha_method_tests; +pub mod paint_cmds; +pub mod pick_cmds; +pub mod redeye_cmds; +pub mod retouch_cmds; +pub mod sampler_cmds; +pub mod stamp_cmds; +pub mod table; + +/// A layer that can be painted: pixels, or any layer with a mask (paint with `"target":"mask"`). +pub(crate) fn has_paintable(s: &crate::Session) -> std::result::Result<(), String> { + if crate::channel_cmds::edits_channel(s) { + return Ok(()); + } + let l = crate::active_layer_of(s)?; + if matches!(l.content, photocraft_doc::LayerContent::Raster(_)) || l.mask.is_some() { + Ok(()) + } else { + Err(format!("active layer is {} {} layer without a mask", l.content.article(), l.content.kind_name())) + } +} diff --git a/crates/engine-paint/src/cmd/adjustment_brush_cmds.rs b/crates/engine-paint/src/cmd/adjustment_brush_cmds.rs index 71c364d886..b555469ac6 100644 --- a/crates/engine-paint/src/cmd/adjustment_brush_cmds.rs +++ b/crates/engine-paint/src/cmd/adjustment_brush_cmds.rs @@ -6,8 +6,8 @@ use photocraft_doc::{Adjustment, ColorMode, Layer, LayerContent, LayerMask, SampleType}; use serde_json::{Value, json}; -use crate::commands::adjust_params::adjustment_kind; -use crate::commands::layer_params::{mask_at_depth, selection_mask}; +use crate::commands::adjustment_kind; +use crate::commands::{mask_at_depth, selection_mask}; use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; diff --git a/crates/engine-paint/src/cmd/brush_cmds.rs b/crates/engine-paint/src/cmd/brush_cmds.rs index 8d87afccc3..59a335ed31 100644 --- a/crates/engine-paint/src/cmd/brush_cmds.rs +++ b/crates/engine-paint/src/cmd/brush_cmds.rs @@ -11,13 +11,18 @@ use photocraft_geom::Rect; use photocraft_paint::mixer::MixerSettings; use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; use photocraft_paint::tile::PREVIEW_SIDE; -use photocraft_paint::{ - BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke_clipped, -}; +use photocraft_paint::{BrushPreset, BrushSettings, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke_clipped}; +// The sampled-tip tile type, which the tests build tips from. +#[cfg(test)] +use photocraft_paint::GrayTile; use photocraft_raster::Surface; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, has_paintable, is_mask_target, paint_surface}; +pub use crate::brush_defs::MAX_TIP; +use crate::brush_defs::{sampled_brush, validate_brush}; +use crate::cmd::has_paintable; +use crate::commands::{CommandSpec, is_mask_target, paint_surface}; +use crate::preset_store::forget_deleted_preset; use crate::{EngineError, Result, Session}; fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -169,31 +174,6 @@ pub fn merge_brush(base: &BrushSettings, patch: &Value, cmd: &str) -> Result Result<()> { - let max = photocraft_paint::MAX_BRUSH_SIZE; - if !brush.size.is_finite() || brush.size > max { - return Err(bad(cmd, format!("brush size must be finite and at most {max} px"))); - } - if brush.dual_brush.enabled && (!brush.dual_brush.size.is_finite() || brush.dual_brush.size > max) { - return Err(bad(cmd, format!("dual brush size must be finite and at most {max} px"))); - } - // Scatter may exceed 1 (100 %) but not the 1000 % maximum: a huge amount pushed dab centres to - // infinity (#977). `{:?}` keeps 1e38 short and shows infinity as `inf`. - let scatter_max = photocraft_paint::MAX_SCATTER; - let in_range = |v: f32| (0.0..=scatter_max).contains(&v); - let sc = brush.scattering.scatter.jitter; - if brush.scattering.enabled && !in_range(sc) { - return Err(bad(cmd, format!("scatter amount {sc:?} is out of range: it must be between 0 and {scatter_max} (1000 %)"))); - } - let ds = brush.dual_brush.scatter; - if brush.dual_brush.enabled && !in_range(ds) { - return Err(bad(cmd, format!("dual brush scatter amount {ds:?} is out of range: it must be between 0 and {scatter_max} (1000 %)"))); - } - Ok(()) -} - fn find_preset<'a>(s: &'a Session, name: &str, cmd: &str) -> Result<&'a BrushPreset> { photocraft_paint::presets::find(&s.tools.presets, name).ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`"))) } @@ -302,7 +282,7 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS return Ok(l.bounds); } let sel = doc.selection.clone(); - let table = crate::mode_cmds::paint_color_table(doc, p); + let table = paint_color_table(doc, p); let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; let clip = paintable_area(canvas, surf); @@ -310,7 +290,7 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS erase_locked(&mut brush, lock, bg); if auto_erase { // A stroke in the table's colour starts on what the foreground painted as. - let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); + let fg = table.as_ref().map_or(fg, |t| table_color(t, fg)); // Not in #11940: Pencil Auto Erase keeps the plain background colour. apply_auto_erase(&mut brush, surf, pts.first(), fg, raw_bg); } @@ -340,7 +320,7 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS render_stroke_clipped(surf, &brush, &pts, sel.as_ref(), lock, zoom, Some(clip)) }; if let (Some(table), Some(pre)) = (&table, &unpainted) { - crate::mode_cmds::keep_in_color_table(table, pre, surf, damage); + keep_in_color_table(table, pre, surf, damage); } Ok(damage) }) @@ -583,13 +563,29 @@ fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pt } } let coverage = photocraft_algo::selection::mask_to_surface(&cov, bounds); - crate::fill_cmds::blend_color_mask(surf, bounds, color, picked, &coverage, mode, opacity, lock)?; + crate::pixel_fill::blend_color_mask(surf, bounds, color, picked, &coverage, mode, opacity, lock)?; Ok(bounds) }) })?; Ok(damage_json(s, dmg)) } +/// The session's offer of a finished live Brush, Eraser or Pencil stroke. +pub trait LiveStrokeExt { + /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose + /// params match it exactly takes its pixels instead of rendering the stroke again (its result + /// then says `"fromLive": true`); any other command drops the offer. The command still runs + /// through the normal dispatch, so authorization, the journal and history are unchanged. + fn offer_live_stroke(&mut self, live: LiveStroke) -> Result<()>; +} + +impl LiveStrokeExt for Session { + fn offer_live_stroke(&mut self, live: LiveStroke) -> Result<()> { + self.live_commit = Some(live.into_commit()?); + Ok(()) + } +} + /// A `paint.stroke` rendered while it is drawn, onto a copy of the active document, so the canvas /// shows the real dabs before the stroke commits. Committing the same params and points with /// `"seed": live.seed` gives the same pixels. @@ -623,7 +619,7 @@ pub struct LiveStroke { base: (photocraft_doc::DocId, u64), } -pub use crate::state::LiveCommit; +pub use photocraft_engine_core::LiveCommit; impl LiveStroke { /// Start from `paint.stroke` params; their `points` are rendered. @@ -650,14 +646,14 @@ impl LiveStroke { let base = (st.doc.id, st.revision); let mut doc = (*st.doc).clone(); let sel = doc.selection.clone(); - let table = crate::mode_cmds::paint_color_table(&doc, p); + let table = paint_color_table(&doc, p); let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?; let clip = paintable_area(canvas, surf); let bg = crate::color_cmds::swatch_in_doc(s, s.tools.background); erase_locked(&mut brush, lock, bg); if pencil && flag(p, "autoErase", false) { - let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); + let fg = table.as_ref().map_or(fg, |t| table_color(t, fg)); apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background); } let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); @@ -777,9 +773,9 @@ impl LiveStroke { Ok(dmg) })?; // The preview shows the pixels the commit keeps (see `stroke_with`). - if let Some(table) = crate::mode_cmds::paint_color_table(&self.doc, &self.params) { + if let Some(table) = paint_color_table(&self.doc, &self.params) { let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.layer, &self.params)?; - crate::mode_cmds::keep_in_color_table(&table, &self.pre, surf, dmg); + keep_in_color_table(&table, &self.pre, surf, dmg); } Ok(dmg) } @@ -1025,17 +1021,6 @@ fn presets_delete(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": s.tools.presets.len() })) } -/// After preset `name` was deleted (here or in Edit › Presets › Preset Manager): the current -/// brush no longer comes from a preset, and the library is saved. -pub(crate) fn forget_deleted_preset(s: &mut Session, name: &str) { - if s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(name)) { - s.tools.current_preset = None; - // The remembered brush names the preset it was picked from: the name went away. - s.tools.brush_changed(); - } - s.brush_presets_changed(); -} - /// Overwrite an existing preset with the current brush (or the current brush plus a `brush` /// patch), in place: no new preset, the position, name and group stay. The preset defaults to the /// one the current brush was picked from. A built-in that is updated becomes the user's preset @@ -1080,9 +1065,6 @@ fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> { Ok(()) } -/// Largest sampled tip side (like Photoshop's 5000 px limit, kept smaller for preset size). -pub const MAX_TIP: u32 = 2500; - fn define_from_selection(s: &mut Session, p: &Value) -> Result { define_from_selection_with_renderer(s, p, |doc, area, sink| photocraft_compose::try_render_bands(doc, area, 0, sink)) } @@ -1189,39 +1171,6 @@ fn define_from_selection_with_renderer( Ok(json!({ "name": name, "width": tw, "height": th })) } -/// A sampled-tip brush from a paint-amount map (`w`×`h`, row-major, 0 = no paint, 1 = full): -/// cropped to the painted extent, at most [`MAX_TIP`] px a side. Shared by Define Brush Preset -/// and importing an image file as a brush (`brush.presets.importImage`). -pub(crate) fn sampled_brush(cmd: &str, v: &[f32], w: usize, h: usize) -> Result<(BrushSettings, u32, u32)> { - let at = |x: usize, y: usize| v.get(y * w + x).copied().unwrap_or(0.0); - // Crop to the painted extent. - let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0); - for y in 0..h { - for x in 0..w { - if at(x, y) > 1e-4 { - x0 = x0.min(x); - y0 = y0.min(y); - x1 = x1.max(x + 1); - y1 = y1.max(y + 1); - } - } - } - if x1 <= x0 || y1 <= y0 { - return Err(bad(cmd, "the pixels contain no paint (all white or transparent)")); - } - let (tw, th) = ((x1 - x0) as u32, (y1 - y0) as u32); - if tw.max(th) > MAX_TIP { - return Err(bad(cmd, format!("too large for a brush tip ({tw}×{th}; max {MAX_TIP} px)"))); - } - let mut data = Vec::with_capacity((tw * th) as usize); - for y in y0..y1 { - data.extend((x0..x1).map(|x| at(x, y))); - } - let tip = GrayTile::from_f32(tw, th, &data); - let brush = BrushSettings { tip: TipShape::Sampled(tip).into(), size: tw.max(th) as f32, spacing: 0.25, pressure_size: false, ..BrushSettings::default() }; - Ok((brush, tw, th)) -} - pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result { let cmd = "tools.setBrush"; let mut b = (*s.tools.brush).clone(); @@ -1519,7 +1468,7 @@ pub fn specs() -> Vec { "paint.colorReplacement", "Color Replacement Tool", r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":1..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##, - crate::commands::has_paintable, + crate::cmd::has_paintable, color_replacement, true ), @@ -1555,6 +1504,62 @@ pub fn specs() -> Vec { ] } +/// The colour table painting on `p`'s target must stay inside: an Indexed Color document's, +/// when the target is layer pixels (masks and channels are gray, not indexed). +fn paint_color_table(doc: &photocraft_doc::Document, p: &Value) -> Option { + let pixels = crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; + doc.color_table.clone().filter(|_| pixels && doc.mode == photocraft_color::ColorMode::Indexed) +} + +/// The colour `c` paints as in a document with `table` (see [`keep_in_color_table`]). +fn table_color(table: &photocraft_doc::ColorTable, c: [f32; 4]) -> [f32; 4] { + let mut px = [c]; + if !table.colors.is_empty() { + photocraft_algo::quantize::quantize(&mut px, 1, &table.colors, photocraft_algo::quantize::Dither::None, 0.0, table.transparent.map(usize::from)); + } + let [c] = px; + c +} + +/// Map the pixels of `r` that the stroke changed (they differ from `pre`) to their nearest +/// colour-table entry, as the Indexed Color conversion does with no dither, so painting never +/// leaves the table (#8669). One tile at a time: a long stroke's bounds can span the canvas. +fn keep_in_color_table(table: &photocraft_doc::ColorTable, pre: &Surface, surf: &mut Surface, r: Rect) { + if table.colors.is_empty() { + return; + } + let fmt = surf.format(); + let n = fmt.channels(); + let mut enc = [0.0f32; 8]; + for tc in r.tiles() { + let t = tc.rect().intersect(&r); + if t.is_empty() || !surf.has_tiles_in(t) { + continue; + } + let (before, mut data) = (pre.read_region(t), surf.read_region(t)); + let (mut changed, mut px) = (Vec::new(), Vec::new()); + for (i, (q, b)) in data.chunks_exact(n).zip(before.chunks_exact(n)).enumerate() { + if q != b { + changed.push(i); + px.push(photocraft_raster::to_rgba(&fmt, q)); + } + } + if px.is_empty() { + continue; + } + let w = px.len(); + photocraft_algo::quantize::quantize(&mut px, w, &table.colors, photocraft_algo::quantize::Dither::None, 0.0, table.transparent.map(usize::from)); + let mut mapped = changed.into_iter().zip(px).peekable(); + for (i, q) in data.chunks_exact_mut(n).enumerate() { + if let Some((_, c)) = mapped.next_if(|(j, _)| *j == i) { + photocraft_raster::from_rgba_into(&fmt, c, &mut enc); + q.iter_mut().zip(enc).for_each(|(d, v)| *d = v); + } + } + surf.write_region(t, &data); + } +} + #[cfg(test)] mod tests; diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 2d16adb077..9d42630711 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -7,11 +7,16 @@ use photocraft_algo::content_aware::FillOptions; use photocraft_color::BlendMode; -use photocraft_geom::{Rect, TILE_SIZE}; -use photocraft_raster::{Surface, from_rgba_into, to_rgba}; +use photocraft_geom::Rect; +#[cfg(test)] +use photocraft_geom::TILE_SIZE; +#[cfg(test)] +use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::commands::{color_param, layer_param, parse_blend}; +use crate::content_sampling::{content_aware, content_aware_options}; +use crate::pixel_fill::{Blend, Source, blend_into, read_rgba}; use crate::{EngineError, Result, Session}; const CMD: &str = "edit.fill"; @@ -23,35 +28,6 @@ fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } } -/// What a pixel of the filled area gets before blending. -enum Source { - Color([f32; 4]), - /// An opaque colour that was picked as CMYK inks: `rgba` is its sRGB stand-in (what other - /// colour models and blend modes use), `cmyk` the inks a CMYK target gets as they are. - Cmyk { - rgba: [f32; 4], - cmyk: [f32; 4], - }, - /// Straight RGBA per pixel of `rect` (row-major). - Pixels(Rect, Vec<[f32; 4]>), -} - -impl Source { - fn at(&self, x: i32, y: i32) -> [f32; 4] { - match self { - Source::Color(c) => *c, - Source::Cmyk { rgba, .. } => *rgba, - Source::Pixels(r, px) => { - if !r.contains(x, y) { - return [0.0; 4]; - } - let i = (y - r.y0) as usize * r.width() as usize + (x - r.x0) as usize; - px.get(i).copied().unwrap_or([0.0; 4]) - } - } - } -} - /// The `contents` param; without one, `color` (the old `{"color": …}` form, foreground by default). fn contents(p: &Value) -> Result<&str> { match p.get("contents") { @@ -123,7 +99,7 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { } "history" => { // A History panel row `state` or a `snapshot`, else the History Brush's source. - let source_doc = crate::history_source_cmds::paint_source(st, p, CMD)?; + let source_doc = crate::history_source::paint_source(st, p, CMD)?; let src = crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) .map_err(|_| EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into()))?; Source::Pixels(area, read_rgba(src, area, "reading Fill's history source")?) @@ -171,358 +147,5 @@ fn color_source(s: &Session, c: [f32; 4]) -> Source { } } -/// `source`'s opaque colour as samples of `fmt` (alpha last, as in [`from_rgba_into`]), or `None` -/// for a source that is not one colour. A CMYK pick keeps its inks in a CMYK target. -fn encode_color(fmt: &photocraft_color::PixelFormat, source: &Source, enc: &mut [f32; 8]) -> Option { - let (rgba, cmyk) = match source { - Source::Color(c) if c[3] >= 1.0 => (*c, None), - Source::Cmyk { rgba, cmyk } => (*rgba, Some(*cmyk)), - _ => return None, - }; - let n = from_rgba_into(fmt, rgba, enc); - if let Some(k) = cmyk - && fmt.mode == photocraft_color::ColorMode::Cmyk - { - enc[..4].copy_from_slice(&k); - } - Some(n) -} - -fn read_rgba(src: &Surface, area: Rect, purpose: &str) -> Result> { - let len = (area.width() as usize) - .checked_mul(area.height() as usize) - .ok_or_else(|| EngineError::Other(format!("not enough memory for {purpose} (requested size overflowed); the document was not changed")))?; - let mut px = crate::allocation::filled(len, [0.0f32; 4], purpose)?; - src.read_rgba_into(area, &mut px); - Ok(px) -} - -/// `src` over `surf` across `area` (Normal, 100 %), each pixel weighted by `limit` when given: -/// a paste into a layer mask or channel, which keeps the pasted pixels' luminosity (#1035). -pub(crate) fn composite_over(surf: &mut Surface, src: &Surface, area: Rect, limit: Option<&Surface>) -> Result<()> { - let source = Source::Pixels(area, read_rgba(src, area, "pasting pixels")?); - blend_into(surf, area, &source, limit, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false }) -} - -/// `area` of `surf` filled with an opaque `color` (Normal, 100 %), weighted by `sel` when given: -/// Clear on a targeted alpha channel or the Quick Mask (#2734). -pub(crate) fn fill_color(surf: &mut Surface, area: Rect, color: [f32; 4], sel: Option<&Surface>) -> Result<()> { - blend_into(surf, area, &Source::Color(color), sel, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false }) -} - -/// Reuse Edit › Fill's compositing for Edit › Stroke. The stroke's rasterized band -/// is already a grayscale coverage mask; opacity, blend modes and alpha locking -/// must behave identically for both commands at 8/16/32-bit depth. -#[allow(clippy::too_many_arguments)] -pub(crate) fn blend_color_mask( - surf: &mut Surface, - area: Rect, - color: [f32; 4], - picked: Option<[f32; 4]>, - coverage: &Surface, - mode: BlendMode, - opacity: f32, - preserve_transparency: bool, -) -> Result<()> { - let source = match picked { - Some(cmyk) if color[3] >= 1.0 => Source::Cmyk { rgba: color, cmyk }, - _ => Source::Color(color), - }; - blend_into(surf, area, &source, Some(coverage), Blend { mode, opacity, keep_alpha: preserve_transparency, restore: false }) -} - -/// The selection filled from its surroundings (`photocraft_algo::content_aware`), as straight -/// RGBA over the sampling window. Only the selected pixels are used. -fn content_aware(surf: &Surface, sel: &Surface, canvas: Rect, options: &FillOptions) -> Result { - let hole_bounds = sel.content_bounds().intersect(&canvas); - if hole_bounds.is_empty() { - return Err(EngineError::Other("the selection is outside the canvas".into())); - } - let is_hole = |x: i32, y: i32| sel.sample_channel(x, y, 0) > 0.0; - let (window, filled) = content_aware_native_with_options(surf, hole_bounds, canvas, options, is_hole, |_, _| true)?; - let fmt = surf.format(); - let px = filled.chunks_exact(fmt.channels().max(1)).map(|c| to_rgba(&fmt, c)).collect(); - Ok(Source::Pixels(window, px)) -} - -/// The pixels `is_hole` picks inside `hole_bounds` filled from their surroundings -/// (`photocraft_algo::content_aware`): Photoshop's sampling window around `hole_bounds`, sampling -/// only the non-hole pixels `usable` allows. Returns the window and its pixels in the surface's -/// own channels (the hole filled, the rest as read). Shared by Edit › Fill › Content-Aware and the -/// Crop tool's Content-Aware fill (#3823). -pub(crate) fn content_aware_native( - surf: &Surface, - hole_bounds: Rect, - canvas: Rect, - color_adaptation: bool, - seed: u64, - is_hole: impl Fn(i32, i32) -> bool, - usable: impl Fn(i32, i32) -> bool, -) -> Result<(Rect, Vec)> { - content_aware_native_with_options(surf, hole_bounds, canvas, &content_aware_options(color_adaptation, seed), is_hole, usable) -} - -/// The adaptation defaults shared by Fill and Content-Aware Crop. -fn content_aware_options(color_adaptation: bool, seed: u64) -> FillOptions { - FillOptions { color_adaptation: photocraft_algo::content_aware::color_level(if color_adaptation { "default" } else { "none" }), seed, ..Default::default() } -} - -/// Fill the bounded sampling window with native channel values and the requested adaptations. -fn content_aware_native_with_options( - surf: &Surface, - hole_bounds: Rect, - canvas: Rect, - options: &FillOptions, - is_hole: impl Fn(i32, i32) -> bool, - usable: impl Fn(i32, i32) -> bool, -) -> Result<(Rect, Vec)> { - use photocraft_algo::content_aware::fill; - let window = sampling_window(hole_bounds, canvas); - let n = surf.format().channels(); - let (w, h) = window_size(window)?; - let img = crate::allocation::read_region(surf, window, "Content-Aware fill samples")?; - let len = w.checked_mul(h).ok_or_else(|| EngineError::Other("the area is too large for Content-Aware fill".into()))?; - let mut hole = crate::allocation::filled(len, false, "Content-Aware fill")?; - let mut source = crate::allocation::filled(len, false, "Content-Aware fill")?; - for (i, (hv, sv)) in hole.iter_mut().zip(source.iter_mut()).enumerate() { - let (x, y) = (window.x0 + (i % w) as i32, window.y0 + (i / w) as i32); - *hv = is_hole(x, y); - *sv = !*hv && usable(x, y); - } - if !source.iter().any(|s| *s) { - return Err(EngineError::Other("Content-Aware fill needs pixels outside the area to fill to sample from".into())); - } - if img.len() != len * n { - return Err(EngineError::Other("could not read the layer pixels".into())); - } - Ok((window, fill(w, h, n, &img, &hole, &source, options))) -} - -/// Photoshop's Content-Aware sampling window around the selection bounds `hole` -/// ([`photocraft_algo::content_aware::sampling_window`]): Edit › Fill, the workspace's Rectangular -/// and Auto areas and the retouching tools all copy from within it. Worked out in i64, so a loaded -/// document declaring an absurd selection can't overflow it (#963). -pub(crate) fn sampling_window(hole: Rect, canvas: Rect) -> Rect { - photocraft_algo::content_aware::sampling_window(hole.intersect(&canvas), canvas) -} - -/// The size of a Content-Aware sampling window, or an error for a window too large to read and -/// fill (#963). Same cap as other whole-image operations: refuse absurd windows instead of -/// allocating. -pub(crate) fn window_size(window: Rect) -> Result<(usize, usize)> { - let (w, h) = (window.width(), window.height()); - if u64::from(w) * u64::from(h) > 400_000_000 { - return Err(EngineError::Other("the selection is too large for Content-Aware fill".into())); - } - Ok((w as usize, h as usize)) -} - -/// [`Surface::read_region`] of `r`, read in parallel bands and asking `cancelled` before each -/// (`None` once it says so): a Content-Aware window can be tens of megapixels. -pub(crate) fn read_window(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option> { - use rayon::prelude::*; - const BAND: usize = 64; - let n = surf.channels(); - let (w, h) = (r.width() as usize, r.height() as usize); - let mut out = vec![0.0f32; w * h * n]; - if out.is_empty() { - return Some(out); - } - // Each worker reads its bands through one buffer of its own. - out.par_chunks_mut(BAND * w * n).enumerate().for_each_init(Vec::new, |buf, (i, chunk)| { - if cancelled() { - return; - } - let y0 = r.y0 + (i * BAND) as i32; - let band = Rect::new(r.x0, y0, r.x1, y0 + (chunk.len() / (w * n)) as i32); - surf.read_region_into(band, buf); - if buf.len() == chunk.len() { - chunk.copy_from_slice(buf); - } - }); - if cancelled() { None } else { Some(out) } -} - -/// Channel 0 of [`read_window`] (a selection's or an alpha channel's coverage). -pub(crate) fn read_window_mask(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option> { - use rayon::prelude::*; - let n = surf.channels().max(1); - let all = read_window(surf, r, cancelled)?; - if n == 1 { - return Some(all); - } - Some(all.par_chunks_exact(n).map(|px| px[0]).collect()) -} - -/// How the source goes onto the target. -#[derive(Clone, Copy)] -struct Blend { - mode: BlendMode, - opacity: f32, - /// Leave every pixel's alpha as it was (Preserve Transparency, or locked transparency). - keep_alpha: bool, - /// Normal mode replaces the pixels, transparency included (History: back to that state). - restore: bool, -} - -/// `d` moved towards `c` by `k`, in premultiplied space (straight RGBA in and out). -fn lerp(d: [f32; 4], c: [f32; 4], k: f32) -> [f32; 4] { - let a = d[3] * (1.0 - k) + c[3] * k; - if a <= 0.0 { - return [0.0; 4]; - } - let ch = |i: usize| (d[i] * d[3] * (1.0 - k) + c[i] * c[3] * k) / a; - [ch(0), ch(1), ch(2), a] -} - -/// Blend `source` into `surf` over `area`: per pixel, the selection coverage times the opacity, -/// in the blend mode. -/// Works tile by tile in parallel on the encoded pixels (no full-surface f32 round trip). -fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<&Surface>, b: Blend) -> Result<()> { - use rayon::prelude::*; - let fmt = surf.format(); - // An opaque colour in Normal mode at 100 % that may replace alpha: fully covered tiles become - // one shared solid tile (copy-on-write), which costs nothing per pixel. - let mut enc = [0.0f32; 8]; - let solid = match encode_color(&fmt, source, &mut enc) { - Some(n) if b.mode == BlendMode::Normal && b.opacity >= 1.0 && (!b.keep_alpha || !fmt.alpha) => Some(surf.solid_tile(enc.get(..n).unwrap_or(&[]))), - _ => None, - }; - let count = area.tiles().count(); - let done = crate::allocation::capacity(count, "blending pixels")?; - let tiles = surf - .try_take_tiles(area) - .map_err(|e| EngineError::Other(format!("not enough memory while preparing pixel tiles ({e}); the document was not changed")))?; - let done = std::sync::Mutex::new(done); - tiles.into_par_iter().try_for_each(|(tc, tile)| -> Result<()> { - let tr = tc.rect().intersect(&area); - let mask = sel.map(|m| Mask::of(m, tc)); - if let Some(s) = &solid - && tr == tc.rect() - && mask.as_ref().is_none_or(|m| m.full(tr)) - { - done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((tc, s.clone())); - return Ok(()); - } - // Nothing selected in this tile (or no opacity): `blend_tile` would leave every pixel as - // it is, so keep the tile itself rather than a copy the history would hold again (#4517). - if b.opacity <= 0.0 || mask.as_ref().is_some_and(|m| m.empty(tr)) { - done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((tc, tile)); - return Ok(()); - } - let mut tile = match std::sync::Arc::try_unwrap(tile) { - Ok(tile) => tile, - Err(tile) => tile - .try_clone() - .map_err(|e| EngineError::Other(format!("not enough memory while blending a pixel tile ({e}); the document was not changed")))?, - }; - blend_tile(&mut tile.bytes_mut(), &fmt, tc.rect(), tr, source, mask.as_ref(), b); - done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((tc, std::sync::Arc::new(tile))); - Ok(()) - })?; - let done = done.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner); - surf.put_tiles(done); - Ok(()) -} - -/// The selection's coverage over one tile (its channel 0). -pub(crate) struct Mask<'a> { - bytes: Option>, - default: &'a [u8], - fmt: photocraft_color::PixelFormat, - origin: Rect, -} - -impl<'a> Mask<'a> { - /// `sel` over the tile at `tc` (its default pixel where it has no tile there). - pub(crate) fn of(sel: &'a Surface, tc: photocraft_geom::TileCoord) -> Self { - Mask { bytes: sel.tile(tc).map(|t| t.bytes()), default: sel.default_bytes(), fmt: sel.format(), origin: tc.rect() } - } - pub(crate) fn at(&self, x: i32, y: i32) -> f32 { - let bytes = self.bytes.as_deref().unwrap_or(self.default); - let bpp = self.fmt.bytes_per_pixel(); - // A default-pixel mask is one pixel long: every position reads it. - let i = if bytes.len() == bpp { 0 } else { ((y - self.origin.y0) as usize * TILE_SIZE as usize + (x - self.origin.x0) as usize) * bpp }; - bytes.get(i..i + bpp).map_or(0.0, |px| photocraft_color::read_sample(px, self.fmt.sample, 0)) - } - /// Fully selected over `r`? - pub(crate) fn full(&self, r: Rect) -> bool { - (r.y0..r.y1).all(|y| (r.x0..r.x1).all(|x| self.at(x, y) >= 1.0)) - } - /// Whether nothing in `r` is selected. - pub(crate) fn empty(&self, r: Rect) -> bool { - (r.y0..r.y1).all(|y| (r.x0..r.x1).all(|x| self.at(x, y) <= 0.0)) - } -} - -/// Blend into one tile's encoded pixels (`bytes`, the tile at `origin`) over `tr`. -fn blend_tile(bytes: &mut [u8], fmt: &photocraft_color::PixelFormat, origin: Rect, tr: Rect, source: &Source, mask: Option<&Mask>, b: Blend) { - let Blend { mode, opacity, keep_alpha, restore } = b; - let n = fmt.channels(); - let bpp = fmt.bytes_per_pixel(); - let blend = if mode == BlendMode::Dissolve { BlendMode::Normal } else { mode }; - let mut px = [0.0f32; 8]; - let mut enc = [0.0f32; 8]; - // An opaque colour at full coverage in Normal mode just replaces the colour (and the alpha - // unless it is kept): copy its encoded bytes. - let opaque = match encode_color(fmt, source, &mut enc) { - Some(m) if mode == BlendMode::Normal => { - let mut bytes = vec![0u8; bpp]; - photocraft_raster::encode_pixel(fmt, enc.get(..m.min(n)).unwrap_or(&[]), &mut bytes); - // Keeping alpha: copy the colour samples only (alpha is the last sample). - let keep = if keep_alpha && fmt.alpha { bpp - bpp / n.max(1) } else { bpp }; - Some((bytes, keep)) - } - _ => None, - }; - for y in tr.y0..tr.y1 { - let row = (y - origin.y0) as usize * TILE_SIZE as usize; - for x in tr.x0..tr.x1 { - let mut k = mask.map_or(1.0, |m| m.at(x, y)) * opacity; - if k <= 0.0 { - continue; - } - let i = (row + (x - origin.x0) as usize) * bpp; - let Some(pb) = bytes.get_mut(i..i + bpp) else { continue }; - if k >= 1.0 - && let Some((enc_px, keep)) = &opaque - { - if let (Some(dst), Some(src)) = (pb.get_mut(..*keep), enc_px.get(..*keep)) { - dst.copy_from_slice(src); - } - continue; - } - for (c, v) in px.iter_mut().enumerate().take(n) { - *v = photocraft_color::read_sample(pb, fmt.sample, c); - } - let d = to_rgba(fmt, &px[..n.min(8)]); - let mut c = source.at(x, y); - if mode == BlendMode::Dissolve { - // Dissolve: each pixel is either fully painted or untouched, with the coverage as odds. - k = if photocraft_color::dither_noise(x, y) < c[3] * k { 1.0 } else { 0.0 }; - c[3] = 1.0; - if k <= 0.0 { - continue; - } - } - let keep = keep_alpha || !fmt.alpha; - let mut o = if restore && blend == BlendMode::Normal { - lerp(d, c, k) - } else if keep { - // Alpha kept: source atop, so a half-transparent pixel takes the new colour by the - // source alpha alone (#5783). - photocraft_color::blend::composite_atop(blend, d, c, k) - } else { - photocraft_color::blend::composite(blend, d, c, k) - }; - if keep { - o[3] = d[3]; - } - let m = from_rgba_into(fmt, o, &mut enc); - photocraft_raster::encode_pixel(fmt, enc.get(..m.min(n)).unwrap_or(&[]), pb); - } - } -} - #[cfg(test)] mod tests; diff --git a/crates/engine-paint/src/cmd/fill_key_cmds.rs b/crates/engine-paint/src/cmd/fill_key_cmds.rs index ea18dbf1e6..add495c26a 100644 --- a/crates/engine-paint/src/cmd/fill_key_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_key_cmds.rs @@ -15,8 +15,8 @@ use serde_json::{Map, Value, json}; use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; -/// The fill-key command ids (routed to the Channels panel target like `edit.fill`). -pub const IDS: [&str; 5] = ["edit.fillForeground", "edit.fillBackground", "edit.fillForegroundPreserve", "edit.fillBackgroundPreserve", "edit.fillHistory"]; +/// The fill-key command ids. +pub use crate::channel_cmds::FILL_KEY_IDS as IDS; const PARAMS: &str = r##"{"layer":id|name?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##; diff --git a/crates/engine-paint/src/cmd/paint_cmds.rs b/crates/engine-paint/src/cmd/paint_cmds.rs index a306db71a7..90c8399a42 100644 --- a/crates/engine-paint/src/cmd/paint_cmds.rs +++ b/crates/engine-paint/src/cmd/paint_cmds.rs @@ -266,7 +266,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"contents":"foreground|pattern"="foreground","color":"#rrggbb"=foreground,"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"opacity":1..100=100,"mode":"normal|multiply|…|clear (erases the filled area)"="normal","target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, - enabled: crate::commands::has_paintable, + enabled: crate::cmd::has_paintable, run: bucket, journal: true, }, @@ -276,7 +276,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"reverse":bool=false,"dither":bool=true,"opacity":1..100=100,"mode":"normal|multiply|…"="normal","layer":id? (default: the active layer; a layer name also works),"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, - enabled: crate::commands::has_paintable, + enabled: crate::cmd::has_paintable, run: gradient, journal: true, }, diff --git a/crates/engine-paint/src/cmd/redeye_cmds.rs b/crates/engine-paint/src/cmd/redeye_cmds.rs index 4024abdf96..ceaffa4fac 100644 --- a/crates/engine-paint/src/cmd/redeye_cmds.rs +++ b/crates/engine-paint/src/cmd/redeye_cmds.rs @@ -215,7 +215,7 @@ fn runs_unchanged(doc: &Document, id: Option, p: &Value, first: (i32, i } fn enabled(s: &Session) -> std::result::Result<(), String> { - crate::commands::has_paintable(s)?; + crate::cmd::has_paintable(s)?; if crate::channel_cmds::edits_channel(s) { return Ok(()); } diff --git a/crates/engine-paint/src/cmd/retouch_cmds.rs b/crates/engine-paint/src/cmd/retouch_cmds.rs index de0dd7d6f3..2024c65fa4 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds.rs @@ -189,7 +189,7 @@ fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, Option Result<()>; + + /// [`LiveStrokeExt::offer_live_stroke`](crate::brush_cmds::LiveStrokeExt::offer_live_stroke) + /// for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, taken by the command it was + /// drawn for: the stroke's finishing dabs are run first. Refused when the brush, tool options + /// or layer changed during the stroke. + fn offer_live_dab(&mut self, live: LiveDab) -> Result<()>; +} + +impl LiveRetouchExt for Session { + fn offer_live_retouch(&mut self, live: LiveRetouch) -> Result<()> { + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } + + fn offer_live_dab(&mut self, live: LiveDab) -> Result<()> { + // A refused offer withdraws the previous one too. + self.live_commit = None; + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } +} /// Retouching command specs. pub fn specs() -> Vec { diff --git a/crates/engine-paint/src/cmd/retouch_cmds/art_history.rs b/crates/engine-paint/src/cmd/retouch_cmds/art_history.rs index c20a26e165..fd62de9372 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/art_history.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/art_history.rs @@ -164,7 +164,7 @@ fn stamp_region( } /// The reference application's alerts for the refusals below (#12638); a hidden target is -/// [`crate::hidden_target::ART_HISTORY_HIDDEN`]. +/// [`photocraft_engine_core::hidden_target::ART_HISTORY_HIDDEN`]. pub const LOCKED: &str = "Could not use the art history brush because the layer is locked."; pub const GROUP: &str = "Could not use the art history brush because the pixels in a group cannot be edited without merging the group."; pub const LACKS_LAYER: &str = "Could not use the art history brush because the history state lacks a corresponding layer."; @@ -200,7 +200,7 @@ fn pixel_target(p: &Value) -> bool { /// bits ([`refuse_format`]), then a target layer the source state lacks. A mask or channel target /// keeps the History Brush's texts for the source refusals (not measured). fn source_surface(s: &Session, id: Option, p: &Value) -> Result { - use crate::history_source_cmds::{SourceRefusal, checked_source, paint_source}; + use crate::history_source::{SourceRefusal, checked_source, paint_source}; let st = s.active().ok_or(EngineError::NoDocument)?; let pixels = pixel_target(p); let doc = if pixels { diff --git a/crates/engine-paint/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine-paint/src/cmd/retouch_cmds/content_aware_move.rs index b269e69ec8..a70aa5b279 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/content_aware_move.rs @@ -309,14 +309,14 @@ fn erode(w: usize, h: usize, m: &[bool], r: usize) -> Vec { } /// Where a fill samples from around `r`: Photoshop's Content-Aware window -/// ([`crate::fill_cmds::sampling_window`]), at most [`MAX_MARGIN`] pixels around `r`. +/// ([`crate::content_sampling::sampling_window`]), at most [`MAX_MARGIN`] pixels around `r`. pub(super) fn window(r: Rect, canvas: Rect) -> Rect { window_within(r, canvas, MAX_MARGIN) } /// [`window`] with at most `margin` pixels around `r`. fn window_within(r: Rect, canvas: Rect, margin: i32) -> Rect { - crate::fill_cmds::sampling_window(r, canvas).intersect(&r.inflate(margin)) + crate::content_sampling::sampling_window(r, canvas).intersect(&r.inflate(margin)) } /// The pixels a step works on: the targeted surface, or with Sample All Layers the visible diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs index 9388258ef7..642f8cd211 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs @@ -113,11 +113,11 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { /// empty one, gives an error. pub(super) fn history_source(s: &Session, id: Option, p: &Value, cmd: &str) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; - let source_doc = crate::history_source_cmds::paint_source(st, p, cmd)?; + let source_doc = crate::history_source::paint_source(st, p, cmd)?; // Here, so the live preview refuses too. Only the History Brush: the Art History Brush and // Erase to History were not measured and keep converting. if cmd == "paint.historyBrush" && !flag(p, "eraseToHistory", false) { - crate::history_source_cmds::refuse_other_format(st, &source_doc)?; + crate::history_source::refuse_other_format(st, &source_doc)?; } let missing = || EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into()); match crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) { @@ -246,11 +246,11 @@ enum SpotType { /// /// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes /// its texture from around it, as Edit › Fill does from its window -/// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples. +/// ([`crate::content_sampling::sampling_window`] of the stroke's bounds), which is what this samples. fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result { let (bounds, cov) = coverage("paint.spotHealing", stroke)?; let size = stroke.brush.size; - let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds()); + let region_rect = crate::content_sampling::sampling_window(bounds, pre.bounds()); if region_rect.is_empty() { return Ok(Rect::EMPTY); } diff --git a/crates/engine-paint/src/cmd/retouch_cmds/sampling.rs b/crates/engine-paint/src/cmd/retouch_cmds/sampling.rs index 253f6648ad..71e0388c99 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/sampling.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/sampling.rs @@ -1,17 +1,11 @@ -use super::{Document, Footprint, LayerId, PixelFormat, Rect, Region, Result, Surface, Value, bad, flag, from_rgba_into, string, targets_pixels}; +pub(super) use crate::content_sampling::{SampleLayers, composite_region}; + +use super::{Document, Footprint, LayerId, PixelFormat, Rect, Region, Result, Surface, Value, bad, flag, string, targets_pixels}; // --------------------------------------------------------------------------------------------- // Sampling sources // --------------------------------------------------------------------------------------------- -/// Which pixels Clone Stamp / Healing Brush sample. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum SampleLayers { - Current, - CurrentAndBelow, - All, -} - pub(super) fn sample_layers(p: &Value, cmd: &str) -> Result { match string(p, "sampleLayer", "current") { "current" => Ok(SampleLayers::Current), @@ -21,34 +15,6 @@ pub(super) fn sample_layers(p: &Value, cmd: &str) -> Result { } } -/// Composite pixels of `rect` in `fmt` (native channels): the whole document, or the target layer -/// and everything below it. -pub(crate) fn composite_region(pre: &Document, id: Option, which: SampleLayers, rect: Rect, fmt: PixelFormat) -> Region { - let mut doc = pre.clone(); - if which == SampleLayers::CurrentAndBelow - && let Some(id) = id - { - // Hide everything composited after (above) the target in the bottom-to-top walk. - let walk: Vec<(Vec, LayerId)> = pre.walk().into_iter().map(|(p, _, l)| (p, l.id)).collect(); - if let Some(pos) = walk.iter().position(|(_, l)| *l == id) { - for (path, _) in &walk[pos + 1..] { - if let Some(l) = doc.layer_at_mut(path) { - l.visible = false; - } - } - } - } - let buf = photocraft_compose::render(&doc, rect); - let n = fmt.channels(); - let mut out = Region::new(rect, n); - let mut enc = [0.0f32; 8]; - for (i, px) in buf.px.iter().enumerate() { - from_rgba_into(&fmt, *px, &mut enc); - out.data[i * n..(i + 1) * n].copy_from_slice(&enc[..n]); - } - out -} - /// Pixels to sample at `rect` (document coordinates, already offset to the source position). pub(super) fn sample(pre: &Document, id: Option, surf: &Surface, which: SampleLayers, rect: Rect) -> Region { match which { diff --git a/crates/engine-paint/src/cmd/stamp_cmds.rs b/crates/engine-paint/src/cmd/stamp_cmds.rs index 38c2c5f7e3..048cc99519 100644 --- a/crates/engine-paint/src/cmd/stamp_cmds.rs +++ b/crates/engine-paint/src/cmd/stamp_cmds.rs @@ -18,6 +18,7 @@ use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use serde_json::{Value, json}; use crate::commands::CommandSpec; +use crate::layer_place::is_empty_pixel_layer; use crate::{EngineError, Result, Session}; fn has_doc(s: &Session) -> std::result::Result<(), String> { @@ -82,23 +83,6 @@ fn stamp_visible(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0 })) } -/// A plain, unlocked pixel layer with no pixels, mask, clipping or video: safe to stamp into. -/// Pixels it has only through a visible default pixel (no tiles stored) count as pixels. -pub(crate) fn is_empty_pixel_layer(doc: &Document, id: LayerId) -> bool { - let Some(l) = doc.layer(id) else { return false }; - let locks = doc.effective_locks(id); - // Only the default pixel's alpha counts: a mode or profile conversion keeps it transparent but - // gives its colour channels other values (no ink in CMYK, a neutral a/b in Lab). - matches!(&l.content, LayerContent::Raster(s) - if s.content_bounds().is_empty() && s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)) - && l.video.is_none() - && l.visible - && l.mask.is_none() - && l.vector_mask.is_none() - && !l.clipped - && !(locks.all || locks.pixels || locks.transparency) -} - fn stamp_down(s: &mut Session, p: &Value) -> Result { object(p, "layer.stampDown")?; let sel = crate::layer_multi_cmds::selected(s); diff --git a/crates/engine-paint/src/cmd/table.rs b/crates/engine-paint/src/cmd/table.rs new file mode 100644 index 0000000000..41e3d8270b --- /dev/null +++ b/crates/engine-paint/src/cmd/table.rs @@ -0,0 +1,3 @@ +//! This crate's command-table fragments (core's `cmd/table.rs` describes them). + +pub mod paint; diff --git a/crates/engine-paint/src/cmd/table/paint/stroke.rs b/crates/engine-paint/src/cmd/table/paint/stroke.rs index 0cb5b18c1e..9848f212c7 100644 --- a/crates/engine-paint/src/cmd/table/paint/stroke.rs +++ b/crates/engine-paint/src/cmd/table/paint/stroke.rs @@ -1,4 +1,5 @@ -use crate::commands::{CommandSpec, has_paintable}; +use crate::cmd::has_paintable; +use crate::commands::{CommandSpec}; /// Painting: the stroke command. pub fn specs() -> Vec { diff --git a/crates/engine-paint/src/history_source.rs b/crates/engine-paint/src/history_source.rs new file mode 100644 index 0000000000..12b626000a --- /dev/null +++ b/crates/engine-paint/src/history_source.rs @@ -0,0 +1,67 @@ +//! The History Brush's, the Art History Brush's and Fill › History's source document, checked +//! against the document they paint on. + +use std::sync::Arc; + +use photocraft_color::ColorMode; +use photocraft_doc::Document; +use serde_json::Value; + +use crate::{DocState, EngineError, Result, history_source_cmds}; + +/// The document the History Brush and Fill › History paint from: the `state` (History panel row) +/// or `snapshot` passed, else the source set in the History panel. A source of another canvas +/// size is refused rather than painting shifted pixels (after Crop, Canvas Size or Image Size): +/// Photoshop refuses too, "the current canvas size does not match that of the history state" +/// (its message as users report it; Adobe's help doesn't document the case). +pub fn paint_source(st: &DocState, p: &Value, cmd: &str) -> Result> { + checked_source(st, p, cmd)?.map_err(|why| { + EngineError::Other(match why { + SourceRefusal::NoSource => "the History Brush source was deleted: set a new source in the History panel".into(), + SourceRefusal::CanvasSize { source } => format!( + "the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel", + st.doc.size.width, st.doc.size.height, source.width, source.height + ), + }) + }) +} + +/// Why [`checked_source`] found no source to paint from, so each tool can word it (#12638). +#[derive(Debug)] +pub enum SourceRefusal { + /// No `state` or `snapshot` passed, and the History panel's source was deleted. + NoSource, + /// The source has another canvas size than the document. + CanvasSize { source: photocraft_geom::Size }, +} + +/// [`paint_source`] with the refusal left to the caller: bad params and a `state` or `snapshot` +/// that is gone are errors, the two refusals the tools word themselves are the inner `Err`. +pub fn checked_source(st: &DocState, p: &Value, cmd: &str) -> Result, SourceRefusal>> { + let doc = match history_source_cmds::parse(st, p, cmd)? { + Some(src) => history_source_cmds::source_of(st, src).ok_or_else(|| EngineError::Other("that history state or snapshot is gone".into()))?, + None => match history_source_cmds::source(st).and_then(|src| history_source_cmds::source_of(st, src)) { + Some(doc) => doc, + None => return Ok(Err(SourceRefusal::NoSource)), + }, + }; + if doc.size != st.doc.size { + return Ok(Err(SourceRefusal::CanvasSize { source: doc.size })); + } + Ok(Ok(doc)) +} + +/// The History Brush's refusals after Image › Mode, with Photoshop's alert texts (#12842): only +/// the History Brush's pairs were measured (RGB to Grayscale, a depth change), so any other change, +/// or both at once, converts the source as before. Document modes are compared: the pixel format +/// reads Indexed and Multichannel as RGB. +pub fn refuse_other_format(st: &DocState, source: &Document) -> Result<()> { + let (mode_differs, depth_differs) = (source.mode != st.doc.mode, source.depth != st.doc.depth); + if source.mode == ColorMode::Rgb && st.doc.mode == ColorMode::Grayscale && !depth_differs { + return Err(EngineError::Other("Could not use the history brush because the current color mode does not match that of the history state.".into())); + } + if depth_differs && !mode_differs { + return Err(EngineError::Other("Could not use the history brush because the current bit depth does not match that of the history state.".into())); + } + Ok(()) +} diff --git a/crates/engine-paint/src/install.rs b/crates/engine-paint/src/install.rs new file mode 100644 index 0000000000..f2d6381af4 --- /dev/null +++ b/crates/engine-paint/src/install.rs @@ -0,0 +1,69 @@ +//! This crate's command tables and hooks, and the install for a process that uses this crate +//! and core (this crate's own tests). `photocraft_engine::install()` installs them with every +//! other engine crate's. + +use std::sync::OnceLock; + +use photocraft_engine_core::registry::{self, Install, Table}; + +use crate::{Result, Session}; + +/// This crate's command tables with their names, in the app's registry order +/// (`crates/engine/src/install/command_ids.txt`). +const TABLES: &[Table] = &[ + ("paint::edit_menu", crate::cmd::table::paint::edit_menu::specs), + ("paint::stroke", crate::cmd::table::paint::stroke::specs), + ("brush_cmds", crate::brush_cmds::specs), + ("eraser_cmds", crate::eraser_cmds::specs), + ("retouch_cmds", crate::retouch_cmds::specs), + ("adjustment_brush_cmds", crate::adjustment_brush_cmds::specs), + ("redeye_cmds", crate::redeye_cmds::specs), + ("paint_cmds", crate::paint_cmds::specs), + ("fill_key_cmds", crate::fill_key_cmds::specs), + ("face_cmds", crate::face_cmds::specs), + ("sampler_cmds", crate::sampler_cmds::specs), + ("brush_key_cmds", crate::brush_key_cmds::specs), + ("stamp_cmds", crate::stamp_cmds::specs), + ("pick_cmds", crate::pick_cmds::specs), +]; + +/// This crate's command tables. +pub fn command_tables() -> &'static [Table] { + TABLES +} + +/// This crate's pipeline hooks. Each is the only hook of its stage, so the order the engine +/// crates' `register`s run in doesn't change what they do. +pub fn register(install: &mut Install) { + let hooks = &mut install.hooks; + hooks.coalesce_journal.push(crate::brush_cmds::coalesce_journal); + // The Magic Eraser's alert for an Indexed Color or Bitmap document (#12032), the same error + // its `run` gives: checked as the command is admitted too, so a floating selection stays + // floating (#13169). + hooks.admit.push(|s, id, _| match s.active().and_then(|st| crate::eraser_cmds::magic_eraser_refusal(&st.doc)) { + Some(why) if id == "paint.magicEraser" => Err(crate::EngineError::Other(why.into())), + _ => Ok(()), + }); +} + +/// Install core's commands and this crate's for the process. Later calls return the first call's result. +pub fn install() -> Result<()> { + static INSTALLED: OnceLock> = OnceLock::new(); + INSTALLED + .get_or_init(|| { + let mut install = Install::default(); + install.commands.extend_from_slice(photocraft_engine_core::command_tables()); + install.commands.extend_from_slice(TABLES); + photocraft_engine_core::register(&mut install); + register(&mut install); + registry::install(install) + }) + .clone() +} + +/// A session with core's commands and this crate's installed: what this crate's tests start from. +pub fn session() -> Session { + // A conflicting install reports itself at the session's first command. + let _ = install(); + Session::new() +} diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs new file mode 100644 index 0000000000..7cd9c1dce5 --- /dev/null +++ b/crates/engine-paint/src/lib.rs @@ -0,0 +1,45 @@ +//! The PhotoCraft engine's painting commands: brushes, the Mixer Brush, erasers, retouching tools, +//! fills, gradients, red eye, color samplers, stamps and the Move tool's layer picking. +//! +//! Built on [`photocraft_engine_core`]; [`install`] installs core's commands and this crate's, and +//! [`session`] makes a session after it. Apps use `photocraft-engine`, which installs every engine crate. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +// The core items this crate's code names as `crate::x`, so the code reads as it did inside core +// (photocraft#15710). +use photocraft_engine_core::{DocState, EngineError, Result, Session, active_layer_of, adjust_params, allocation, brush_defs, brush_preset_cmds, channel_cmds, color_channels, color_cmds, commands, content_sampling, extra_cmds, fix_selection, float_cmds, history_source_cmds, jobs, layer_multi_cmds, layer_place, pattern_cmds, pixel_fill, pixels_mut, preset_store, presets, sample_cmds, selection_cmds, symmetry_cmds, transform_cmds}; +#[cfg(test)] +use photocraft_engine_core::{command_specs, hidden_target, param_schema, prefs}; + +pub mod cmd; +mod history_source; +mod install; + +pub use cmd::adjustment_brush_cmds; +pub use cmd::brush_cmds; +pub use cmd::brush_key_cmds; +pub use cmd::eraser_cmds; +pub use cmd::face_cmds; +pub use cmd::fill_cmds; +pub use cmd::fill_key_cmds; +pub use cmd::paint_cmds; +pub use cmd::pick_cmds; +pub use cmd::redeye_cmds; +pub use cmd::retouch_cmds; +pub use cmd::sampler_cmds; +pub use cmd::stamp_cmds; +pub use install::{command_tables, install, register, session}; + +#[cfg(test)] +mod brush_clear_background_tests; +#[cfg(test)] +mod brush_pressure_size_default_tests; +#[cfg(test)] +mod eraser_gray_background_tests; +#[cfg(test)] +mod mixer_indexed_bitmap_tests; +#[cfg(test)] +mod mixer_toggle_commands_tests; +#[cfg(test)] +mod pencil_auto_erase_exact_tests; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 939f521977..cf8a11c4aa 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -16,9 +16,10 @@ path = "src/facade.rs" # Real-file corpus tests (opt-in; `cargo xtask test-corpus`). Fail when the corpus is missing. corpus = ["photocraft-engine-core/corpus"] -# The engine's code and dependencies live in photocraft-engine-core; this crate re-exports it. +# The engine's code and dependencies live in the engine crates; this crate re-exports them. [dependencies] photocraft-engine-core = { workspace = true } +photocraft-engine-paint = { workspace = true } # What tests/ and examples/ use. [dev-dependencies] diff --git a/crates/engine/src/facade.rs b/crates/engine/src/facade.rs index 7868a95c0f..e8a99be4fb 100644 --- a/crates/engine/src/facade.rs +++ b/crates/engine/src/facade.rs @@ -14,20 +14,27 @@ use std::ops::{Deref, DerefMut}; /// `CoreSession::new()` and `default()` install no commands: an app constructs [`Session`]. pub use photocraft_engine_core::Session as CoreSession; pub use photocraft_engine_core::*; +// The painting commands' modules, at the paths they had inside the engine. +pub use photocraft_engine_paint::{ + adjustment_brush_cmds, brush_cmds, brush_key_cmds, eraser_cmds, face_cmds, fill_cmds, fill_key_cmds, paint_cmds, pick_cmds, redeye_cmds, retouch_cmds, sampler_cmds, stamp_cmds, +}; + +mod install; + +pub use install::install; /// The engine's commands (`photocraft_engine_core::cmd`), with [`command_specs`](commands::command_specs) /// and [`find`](commands::find) installing every engine command first. pub mod commands { pub use crate::{command_specs, find}; pub use photocraft_engine_core::cmd::*; + pub use photocraft_engine_paint::cmd::{ + adjustment_brush_cmds, brush_cmds, brush_key_cmds, eraser_cmds, face_cmds, fill_cmds, fill_key_cmds, paint_cmds, pick_cmds, redeye_cmds, retouch_cmds, sampler_cmds, + stamp_cmds, + }; } pub use commands as cmd; -/// Install every engine command for this process. Later calls return the first call's result. -pub fn install() -> Result<()> { - photocraft_engine_core::install() -} - /// Every engine command in registry order, installed first: for callers that read the registry /// before any session exists (menus, docs, tests). pub fn command_specs() -> &'static [CommandSpec] { diff --git a/crates/engine/src/install.rs b/crates/engine/src/install.rs new file mode 100644 index 0000000000..a5ae8740c6 --- /dev/null +++ b/crates/engine/src/install.rs @@ -0,0 +1,37 @@ +//! Every engine crate's commands, session slots and pipeline hooks, installed together for the app. + +use std::sync::OnceLock; + +use photocraft_engine_core::registry::{self, Install, Table}; + +use crate::Result; + +/// The app's registry order: every engine command id, one per line. Menus, the Command Palette +/// and `command.list` list commands in it; a new command's id goes after its predecessor's. +const ORDER: &str = include_str!("install/command_ids.txt"); + +/// Every engine crate's command tables, core first, then the crates above it. +fn crate_tables() -> [&'static [Table]; 2] { + [photocraft_engine_core::command_tables(), photocraft_engine_paint::command_tables()] +} + +/// Install every engine command for this process. Later calls return the first call's result. +pub fn install() -> Result<()> { + static INSTALLED: OnceLock> = OnceLock::new(); + INSTALLED + .get_or_init(|| { + let mut install = Install::default(); + install.order = Some(ORDER); + for tables in crate_tables() { + install.commands.extend_from_slice(tables); + } + // Each stage runs its hooks in this order; core's own list keeps today's after-command order. + photocraft_engine_core::register(&mut install); + photocraft_engine_paint::register(&mut install); + registry::install(install) + }) + .clone() +} + +#[cfg(test)] +mod order_tests; diff --git a/crates/engine-core/src/install/command_ids.txt b/crates/engine/src/install/command_ids.txt similarity index 100% rename from crates/engine-core/src/install/command_ids.txt rename to crates/engine/src/install/command_ids.txt diff --git a/crates/engine/src/install/order_tests.rs b/crates/engine/src/install/order_tests.rs new file mode 100644 index 0000000000..cc12119b61 --- /dev/null +++ b/crates/engine/src/install/order_tests.rs @@ -0,0 +1,32 @@ +use super::crate_tables; + +const HINT: &str = + "\nadd the id to crates/engine/src/install/command_ids.txt after its predecessor, or run this test with PHOTOCRAFT_WRITE_COMMAND_IDS=1 and review the diff"; + +/// Menus, the Command Palette and the automation docs list commands in registry order, which +/// `command_ids.txt` sets. Every installed command has its line there, and every line names an +/// installed command. With `PHOTOCRAFT_WRITE_COMMAND_IDS` set, the test writes the file from the +/// registry instead (an unlisted command last); review the diff before committing it. +#[test] +fn every_command_has_its_place_in_the_registry_order() { + let ids: Vec<&str> = crate::command_specs().iter().map(|c| c.id).collect(); + if std::env::var_os("PHOTOCRAFT_WRITE_COMMAND_IDS").is_some() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/install/command_ids.txt"); + std::fs::write(path, ids.iter().map(|id| format!("{id}\n")).collect::()).expect("write command_ids.txt"); + return; + } + let listed: Vec<&str> = super::ORDER.lines().collect(); + for id in &ids { + assert!(listed.contains(id), "command {id} has no place in the order{}{HINT}", table_of(id)); + } + for id in &listed { + assert!(ids.contains(id), "command_ids.txt lists {id}, which no engine crate registers{HINT}"); + } + assert_eq!(ids, listed, "each command once, in the file's order{HINT}"); +} + +/// Names the table that registers command `id`, for the failure message. +fn table_of(id: &str) -> String { + let table = crate_tables().into_iter().flatten().find(|(_, specs)| specs().iter().any(|c| c.id == id)); + table.map_or_else(String::new, |(name, _)| format!(" (table `{name}`)")) +} diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 8f0a74ba3d..f49492d186 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -1,6 +1,6 @@ -use photocraft_engine::retouch_cmds::LiveRetouchExt; use photocraft_engine::brush_cmds::LiveStrokeExt; use photocraft_engine::presets::PresetsExt; +use photocraft_engine::retouch_cmds::LiveRetouchExt; use std::sync::Arc; use craft::behavior::PixelSize; diff --git a/crates/ui-egui/tests/it/display_names.rs b/crates/ui-egui/tests/it/display_names.rs index 15a6a07add..c65c1b58f5 100644 --- a/crates/ui-egui/tests/it/display_names.rs +++ b/crates/ui-egui/tests/it/display_names.rs @@ -21,7 +21,7 @@ const ALLOWED: &[&str] = &[ ]; // The only catalog rows that may say "Camera Raw": their English text names Photoshop's .xmp files. const ALLOWED_KEYS: &[&str] = &["Save these settings as a Camera Raw .xmp file", "Load settings from a Camera Raw .xmp file"]; -const ROOTS: &[&str] = &["src", "../engine/src", "../engine-core/src"]; +const ROOTS: &[&str] = &["src", "../engine/src", "../engine-core/src", "../engine-paint/src"]; fn is_word(c: char) -> bool { c.is_alphanumeric() || c == '_' diff --git a/docs/contributing.md b/docs/contributing.md index b4c7ea24f8..c02b60d0a3 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -15,7 +15,7 @@ 1. **Find the id.** Search `crates/ui-egui/src/menu_catalog.rs` for the Photoshop menu item. Using its id makes the menu item live with no UI work. Commands without a Photoshop menu entry use a descriptive id in the same style (`layer.smartFilter.delete`) and an empty menu path. 2. **Algorithm** goes in the lowest crate that fits (`algo` for imaging, `paint`, `vector`, `text`; colour management is `craft-cms` in craft-libs), with unit tests. It takes depth-agnostic surfaces (`photocraft-raster`), works per tile, and is deterministic (seeded randomness). -3. **Command** goes in an engine module (`crates/engine-core/src/_cmds.rs`) exposing `specs()`, registered by adding `("", crate::::specs)` to `TABLES` in `crates/engine-core/src/install.rs` (after the table it follows in the menus) and its ids to `crates/engine-core/src/install/command_ids.txt` (the order test says how). A command in a core menu goes in the owner fragment `crates/engine-core/src/cmd/table//.rs` instead. Fill in: +3. **Command** goes in an engine module (`crates/engine-core/src/_cmds.rs`, or `crates/engine-/src/cmd/_cmds.rs` for a crate cut out of core, such as `engine-paint`) exposing `specs()`, registered by adding `("", crate::::specs)` to `TABLES` in that crate's `install.rs`, and its ids to `crates/engine/src/install/command_ids.txt` after the command it follows in the menus: that file sets the registry order (the top crate's order test says how). A command in a core menu goes in the owner fragment `cmd/table//.rs` of its crate instead. Fill in: - `id`, `label`, `menu` path and Photoshop's default `shortcut`, - a params doc string such as `{"radius":px=4,"mode":"a|b"="a"}` (this is what agents read through `commands` / `command_list`), - an `enabled` predicate (greys the menu item out), diff --git a/scripts/engine_split/engine_cut.py b/scripts/engine_split/engine_cut.py index b98f0f147a..07eb055219 100755 --- a/scripts/engine_split/engine_cut.py +++ b/scripts/engine_split/engine_cut.py @@ -258,6 +258,9 @@ def import_names(crate, files=None): regions = test_regions(lib) if os.path.exists(lib) else {} files = files if files is not None else tree_files(crate_src(crate)) own = OWN | {u.split("/")[-1] for u in units(crate)} + if os.path.exists(lib): + # Modules the crate's root declares itself (beside the moved ones). + own |= {d.group(2) for d in MOD_DECL.finditer(mask(read(lib)))} used, in_code = set(), set() for f in files: masked = mask(read(f)) diff --git a/scripts/engine_split/install_tables.py b/scripts/engine_split/install_tables.py index 814903d35b..54ece8aa76 100644 --- a/scripts/engine_split/install_tables.py +++ b/scripts/engine_split/install_tables.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """Move a branch's added or removed command tables into the engine's install list. -The engine's command tables are listed, in registry order, in `TABLES` in -`crates/engine-core/src/install.rs` (`crates/engine/src/install.rs` before the crate split). Before that, `crates/engine/src/cmd.rs` listed them: first as +The engine's command tables are listed in `TABLES` in the `install.rs` of the engine crate that +holds their module (`crates/engine-/src/install.rs`, by `crates.tsv`; core's for a module of a +crate not cut out yet; `crates/engine/src/install.rs` before the crate split). Before that, `crates/engine/src/cmd.rs` listed them: first as `v.extend(::specs());` lines in `fn build()`, later as `("", ),` entries in `SPECS`. A branch that added or removed a table carries that edit in `cmd.rs`. This script applies it to `TABLES`: @@ -19,10 +20,14 @@ would be lost. Per table, compared between BASE and HEAD: Running it twice gives the same result. Anything it cannot place is listed at the end. Edits of inline commands are `table_fragments.py`'s; run both. """ -import argparse, re, subprocess, sys +import argparse, os, re, subprocess, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from engine_cut import units # noqa: E402 CMD = "crates/engine/src/cmd.rs" INSTALL = "crates/engine-core/src/install.rs" +CRATES = ("model", "store", "vector", "paint", "image", "files") INSTALL_BEFORE_SPLIT = "crates/engine/src/install.rs" EXTEND_RE = re.compile(r"^\s*v\.extend\(((?:crate::)?(?:cmd::)?)([a-z0-9_:]+?)::([a-z0-9_]+)\(\)\);", re.M) ENTRY_RE = re.compile(r'^\s*\("([^"]+)",\s*([A-Za-z0-9_:]+)\),', re.M) @@ -60,6 +65,16 @@ def tables(ref): return out +def install_file(path): + """The install.rs that lists the table at `path` (`crate::cmd::::specs` and the like).""" + module = path.split("::")[-2] if path.count("::") >= 2 else "" + for c in CRATES: + f = f"crates/engine-{c}/src/install.rs" + if os.path.exists(f) and any(u.split("/")[-1] == module or u == "cmd/table/" + module for u in units(c)): + return f + return INSTALL + + def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--base", required=True, help="the branch's merge-base with the old main") @@ -75,40 +90,37 @@ def main(): base = dict(tables(a.base)) head = tables(a.head) head_names = {n for n, _ in head} - text = open(INSTALL).read() - start = text.index("const TABLES:") - end = text.index("\n];", start) - lines = text[start:end].split("\n") - header, rows = lines[0], lines[1:] - names = lambda: [m.group(1) if (m := ENTRY_RE.match(r)) else None for r in rows] report = [] - for pos, (name, path) in enumerate(head): - if name in base or name in names(): - continue - pred = next((head[k][0] for k in range(pos - 1, -1, -1) if head[k][0] in names()), None) - current = names() - if pred is not None: - at = len(current) - current[::-1].index(pred) - else: - fragments = [i for i, r in enumerate(rows) if "crate::cmd::table::" in r] - if not fragments: - report.append(f"UNPLACED {name}: no predecessor in TABLES") + files = sorted({INSTALL} | {install_file(p) for _, p in head} | {install_file(p) for p in base.values()}) + for install in files: + text = open(install).read() + start = text.index("const TABLES:") + end = text.index("\n];", start) + lines = text[start:end].split("\n") + header, rows = lines[0], lines[1:] + names = lambda: [m.group(1) if (m := ENTRY_RE.match(r)) else None for r in rows] + for pos, (name, path) in enumerate(head): + if install_file(path) != install or name in base or name in names(): continue - at = fragments[-1] + 1 - pred = "the last table fragment" - rows.insert(at, f' ("{name}", {path}),') - report.append(f"added {name} ({path}) after {pred}") - for name in base: - if name not in head_names and name in names(): - rows = [r for r, n in zip(rows, names()) if n != name] - report.append(f"removed {name}") - text = text[:start] + "\n".join([header] + rows) + text[end:] - open(INSTALL, "w").write(text) + pred = next((head[k][0] for k in range(pos - 1, -1, -1) if head[k][0] in names()), None) + current = names() + if pred is not None: + at = len(current) - current[::-1].index(pred) + else: + at = len(rows) + pred = "the end of the list" + rows.insert(at, f' ("{name}", {path}),') + report.append(f"added {name} ({path}) to {install} after {pred}") + for name in base: + if name not in head_names and name in names(): + rows = [r for r, n in zip(rows, names()) if n != name] + report.append(f"removed {name} from {install}") + open(install, "w").write(text[:start] + "\n".join([header] + rows) + text[end:]) print("\n".join(report) or "nothing to do") if any(r.startswith("added") for r in report): print( - "next: run the test `install::order_tests` with PHOTOCRAFT_WRITE_COMMAND_IDS=1 to regenerate " - "install/command_ids.txt, and review its diff" + "next: add each new command's id to crates/engine/src/install/command_ids.txt after its " + "predecessor (it sets the registry order; the top crate's `install::order_tests` checks it)" ) return 1 if any(r.startswith("UNPLACED") for r in report) else 0 diff --git a/scripts/engine_split/table_fragments.py b/scripts/engine_split/table_fragments.py index 8b6f3cba09..5eba4ca92f 100644 --- a/scripts/engine_split/table_fragments.py +++ b/scripts/engine_split/table_fragments.py @@ -3,7 +3,7 @@ Before the table was split, `crates/engine/src/cmd.rs` held every core command in one `vec![...]` inside `fn build()`. The entries now live in `crates/engine-core/src/cmd/table//.rs`, and -`install/command_ids.txt` pins the registry order. A branch that edited the old table carries its +`crates/engine/src/install/command_ids.txt` sets the registry order. A branch that edited the old table carries its edits in `cmd.rs`. This script applies them to the fragments: python3 scripts/engine_split/table_fragments.py --base --head @@ -30,7 +30,9 @@ import argparse, os, re, subprocess, sys, tempfile CMD = "crates/engine/src/cmd.rs" TABLE = "crates/engine-core/src/cmd/table" -IDS = "crates/engine-core/src/install/command_ids.txt" +# The fragment directories of every engine crate (`cmd/table//`, in core until its crate is cut out). +TABLES = sorted(f"{d}/src/cmd/table" for d in (os.path.join("crates", c) for c in os.listdir("crates")) if os.path.basename(d).startswith("engine-") and os.path.isdir(f"{d}/src/cmd/table")) if os.path.isdir("crates") else [TABLE] +IDS = "crates/engine/src/install/command_ids.txt" ID_RE = re.compile(r'"([a-zA-Z]+\.[A-Za-z0-9.]+)"') @@ -92,9 +94,10 @@ class Fragments: def __init__(self): self.files = {} - for d, _, names in os.walk(TABLE): + walks = [(root, d, names) for root in TABLES for d, _, names in os.walk(root)] + for root, d, names in walks: for n in names: - if n.endswith(".rs") and os.path.dirname(os.path.join(d, n)) != TABLE: + if n.endswith(".rs") and os.path.dirname(os.path.join(d, n)) != root: p = os.path.join(d, n) if "vec![" in open(p).read(): self.files[p] = open(p).read() diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index cbe325066b..dd5e40023b 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -60,6 +60,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("ml", Class::Layer(4)), ("plugins", Class::Layer(4)), ("engine-core", Class::Layer(5)), + ("engine-paint", Class::Layer(5)), ("engine", Class::Layer(5)), ("ui-egui", Class::Layer(6)), ("automation", Class::Layer(6)), @@ -79,7 +80,7 @@ pub const TABLE: &[(&str, Class)] = &[ /// `geom`, which the §3 diagram draws on one line. The GPU backend (`gpu`) /// reuses the CPU reference (`compose`) for LUTs and parity tests. The engine's crates form one /// chain per leaf crate, from `engine-core` to the top crate `engine` (photocraft#15710). -pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["geom", "color", "raster"], &["compose", "gpu"], &["engine-core", "engine"]]; +pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["geom", "color", "raster"], &["compose", "gpu"], &["engine-core", "engine-paint", "engine"]]; fn intra_layer_allowed(from: &str, to: &str) -> bool { let (from, to) = (short_name(from), short_name(to));