diff --git a/Cargo.lock b/Cargo.lock index cc668196ee..ac35cf8938 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6460,6 +6460,8 @@ name = "photocraft-color" version = "0.23.1" dependencies = [ "craft-cms", + "craft-tracked", + "craft-ui-macros", "serde", ] @@ -6571,6 +6573,8 @@ dependencies = [ name = "photocraft-geom" version = "0.23.1" dependencies = [ + "craft-tracked", + "craft-ui-macros", "serde", ] @@ -6661,6 +6665,8 @@ dependencies = [ name = "photocraft-ops" version = "0.23.1" dependencies = [ + "craft-tracked", + "craft-ui-macros", "photocraft-doc", ] @@ -6701,6 +6707,8 @@ dependencies = [ name = "photocraft-raster" version = "0.23.1" dependencies = [ + "craft-tracked", + "craft-ui-macros", "crc32fast", "lz4_flex", "photocraft-color", diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index df5d12cb34..a424eb6b2d 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -10,3 +10,6 @@ workspace = true [dependencies] craft-cms = { workspace = true } serde = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 7b26f06a4f..43861a5c21 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum BlendMode { /// Groups only: children blend directly into the group's backdrop. PassThrough, diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 281c3e01b9..bb95599702 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -24,7 +24,7 @@ pub fn dither_noise(x: i32, y: i32) -> f32 { use serde::{Deserialize, Serialize}; /// Storage type of one channel sample. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum SampleType { U8, U16, @@ -47,7 +47,7 @@ impl SampleType { } /// Document colour model (Photoshop "Image → Mode"). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum ColorMode { Bitmap, Grayscale, @@ -74,7 +74,7 @@ impl ColorMode { } /// Layout of a pixel: colour model, sample type, and whether an alpha channel follows the colour channels. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct PixelFormat { pub mode: ColorMode, pub sample: SampleType, @@ -161,7 +161,7 @@ pub fn write_sample(bytes: &mut [u8], sample: SampleType, index: usize, v: f32) } /// A colour value in the document's model with alpha, as normalised floats. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Color { pub mode: ColorMode, /// Up to 4 colour components (unused ones are 0) followed by nothing; alpha kept separately. diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 296cbe090d..f6a95a38c9 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -13,6 +13,6 @@ photocraft-color = { workspace = true } photocraft-raster = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -# LayerId is plain data (the Layers panel keys its rows by it): the marker and its derive, without the UI. +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. craft-tracked = { workspace = true } craft-ui-macros = { workspace = true } diff --git a/crates/doc/src/adjust.rs b/crates/doc/src/adjust.rs index 78603f6ae1..fc8d78a611 100644 --- a/crates/doc/src/adjust.rs +++ b/crates/doc/src/adjust.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use std::sync::Arc; -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct CurvePoint { pub input: f32, pub output: f32, @@ -18,7 +18,7 @@ pub fn is_identity_curve(points: &[CurvePoint]) -> bool { } /// A 3D LUT file format (Photoshop's `LUTFormat`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LutFormat { #[serde(rename = "cube")] Cube, @@ -29,7 +29,7 @@ pub enum LutFormat { } /// A Color Lookup's LUT file as loaded: its format and bytes. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct LutSource { pub format: LutFormat, pub bytes: Arc>, @@ -92,7 +92,7 @@ pub fn lut3d_len(size: u32) -> Option { usize::try_from(size).ok()?.checked_pow(3)?.checked_mul(3) } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct LevelsChannel { pub in_black: f32, pub in_white: f32, @@ -111,7 +111,7 @@ impl Default for LevelsChannel { /// happens in display RGB; `Cmyk` and `Lab` records are applied to the pixel converted into that /// space (the same conversions the document's surfaces use), so ink and Lab channel edits behave /// like Photoshop's in CMYK and Lab documents. Grayscale documents use `Rgb` with the master record. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum ToneSpace { /// `per_channel` = red, green, blue. #[default] @@ -125,7 +125,7 @@ pub enum ToneSpace { } /// One of Hue/Saturation's six colour ranges (reds, yellows, greens, cyans, blues, magentas). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct HueRange { /// Hue shift in degrees (-180..=180). pub hue: f32, @@ -197,7 +197,7 @@ fn default_hue_ranges() -> [HueRange; 6] { /// A gradient as Photoshop's Gradient Editor holds it (#8351): a few colour stops, a midpoint /// on each segment, Smoothness and the interpolation method, which renderers bake into dense /// linear stops. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GradientSource { /// Colour stops (location 0..1, sRGB), in location order. pub stops: Vec<(f32, [f32; 3])>, @@ -211,7 +211,7 @@ pub struct GradientSource { } /// Photoshop adjustment layers (Layer → New Adjustment Layer). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Adjustment { BrightnessContrast { brightness: f32, diff --git a/crates/doc/src/advanced.rs b/crates/doc/src/advanced.rs index 073b6f8b85..5e70185404 100644 --- a/crates/doc/src/advanced.rs +++ b/crates/doc/src/advanced.rs @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; /// Blending Options › Advanced Blending › Knockout: which layers beneath this one its shape /// punches through. Fill opacity controls the strength (0 % fill shows the knocked-out area bare). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum Knockout { /// The layer blends with everything beneath it (the default). @@ -68,7 +68,7 @@ impl Knockout { } /// The Advanced Blending switches of a layer (see the module docs). `Default` is Photoshop's. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct AdvancedBlending { /// Knockout: None / Shallow / Deep. PSD `knko`. diff --git a/crates/doc/src/analysis.rs b/crates/doc/src/analysis.rs index 9b1d8efdb0..2975210d57 100644 --- a/crates/doc/src/analysis.rs +++ b/crates/doc/src/analysis.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; /// Image › Analysis › Set Measurement Scale: `pixel_length` pixels equal `logical_length` /// `units`. The default is 1 pixel = 1 pixel. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct MeasurementScale { pub pixel_length: f64, @@ -37,7 +37,7 @@ impl MeasurementScale { } /// One Count tool group: its numbered markers (document pixel coordinates, in click order). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct CountGroup { pub name: String, @@ -57,7 +57,7 @@ impl Default for CountGroup { /// The Ruler tool line, optionally with a protractor second arm (⌥-drag from an end point). /// `start` is the vertex the angle is measured at when there is a protractor. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Ruler { pub start: [f64; 2], pub end: [f64; 2], @@ -66,7 +66,7 @@ pub struct Ruler { } /// Measurement settings and marks of a document. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct Measurement { pub scale: MeasurementScale, @@ -87,7 +87,7 @@ impl Measurement { } /// A Note tool annotation (PSD `Anno` text annotation). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct Note { pub author: String, diff --git a/crates/doc/src/blend_if.rs b/crates/doc/src/blend_if.rs index ce7c279e9f..117d08adce 100644 --- a/crates/doc/src/blend_if.rs +++ b/crates/doc/src/blend_if.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// One Blend If slider pair: `black` = (low, high), `white` = (low, high), all on 0..=255. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BlendRange { pub black: [u8; 2], pub white: [u8; 2], @@ -75,7 +75,7 @@ impl BlendRange { /// A layer's Blend If settings. `ranges[0]` is the "Gray" entry (composite of the colour /// channels), then one entry per colour channel of the document's mode (R, G, B / C, M, Y, K / /// L, a, b / Gray), each as `[this layer, underlying layer]`. Empty = every pixel blends. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BlendIf { pub ranges: Vec<[BlendRange; 2]>, } diff --git a/crates/doc/src/comps.rs b/crates/doc/src/comps.rs index 796baa7d43..98dcbe17d4 100644 --- a/crates/doc/src/comps.rs +++ b/crates/doc/src/comps.rs @@ -15,7 +15,7 @@ use crate::{Document, Effects, Layer, LayerContent, LayerId}; /// One layer's state as captured by a comp. `None` = not recorded (PSD comps record only what /// their capture flags asked for). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct CompLayerState { pub layer: LayerId, pub visible: Option, @@ -26,7 +26,7 @@ pub struct CompLayerState { } /// Layer › Layer Style state captured by "Appearance". -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct CompAppearance { pub blend: BlendMode, pub opacity: f32, @@ -34,7 +34,7 @@ pub struct CompAppearance { pub effects: Effects, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct LayerComp { /// Stable id (the PSD `compID`). Never 0: Photoshop uses 0 for the Last Document State. pub id: u32, @@ -107,7 +107,7 @@ pub fn next_comp_id(doc: &Document) -> u32 { } /// What an artboard paints behind its contents. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum ArtboardBackground { #[default] @@ -151,7 +151,7 @@ impl ArtboardBackground { /// An artboard: a top-level group that clips its children to `rect` and paints `background` /// behind them (Layer › New › Artboard). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Artboard { /// The board in document pixels. pub rect: Rect, diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rs index a71aa883dd..a6836523a3 100644 --- a/crates/doc/src/effects.rs +++ b/crates/doc/src/effects.rs @@ -15,7 +15,7 @@ use crate::adjust::CurvePoint; pub const PATTERN_SCALE_RANGE: (f32, f32) = (0.01, 10.0); /// Gradient geometry (fill layers, gradient overlays, gradient strokes). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum GradientStyle { #[default] Linear, @@ -26,7 +26,7 @@ pub enum GradientStyle { } /// A gradient: colour stops plus transparency stops (both at `0..=1`). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Gradient { pub stops: Vec<(f32, Color)>, /// Opacity stops; empty means fully opaque. @@ -44,7 +44,7 @@ pub struct Gradient { /// Editable colour stops behind a Gradient Overlay's baked render stops. /// Older documents have no interpolation record and keep their existing appearance. /// Writers must rebake `gradient.stops` from this record, or clear it when replacing the curve. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GradientInterpolation { pub method: String, pub smoothness: f32, @@ -67,7 +67,7 @@ impl Default for Gradient { } /// Effect contour (transfer curve applied to the effect's coverage). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Contour { #[default] Linear, @@ -93,7 +93,7 @@ impl Contour { } /// Paint used by strokes and glows. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum FxPaint { Color(Color), Gradient(Gradient), @@ -106,7 +106,7 @@ pub enum FxPaint { } /// Blend mode + opacity + enabled, shared by every effect. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct FxCommon { pub enabled: bool, pub blend: BlendMode, @@ -119,7 +119,7 @@ impl FxCommon { } } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Shadow { pub common: FxCommon, pub color: Color, @@ -136,21 +136,21 @@ pub struct Shadow { pub knocks_out: bool, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum GlowTechnique { #[default] Softer, Precise, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum GlowSource { Center, #[default] Edge, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Glow { pub common: FxCommon, pub paint: FxPaint, @@ -167,14 +167,14 @@ pub struct Glow { pub source: GlowSource, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum StrokePosition { Outside, Inside, Center, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct StrokeFx { pub common: FxCommon, pub size: f32, @@ -185,7 +185,7 @@ pub struct StrokeFx { pub overprint: bool, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Satin { pub common: FxCommon, pub color: Color, @@ -197,7 +197,7 @@ pub struct Satin { pub invert: bool, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum BevelStyle { OuterBevel, #[default] @@ -207,7 +207,7 @@ pub enum BevelStyle { StrokeEmboss, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum BevelTechnique { #[default] Smooth, @@ -215,7 +215,7 @@ pub enum BevelTechnique { ChiselSoft, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Bevel { pub enabled: bool, pub style: BevelStyle, @@ -246,7 +246,7 @@ pub struct Bevel { } /// The Contour element of Bevel & Emboss. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BevelContour { pub contour: Contour, /// Range `0..=1` (Photoshop's default 50 %): the part of the bevel the contour spans. @@ -261,7 +261,7 @@ impl Default for BevelContour { } /// The Texture element of Bevel & Emboss. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BevelTexture { pub name: String, pub id: String, @@ -277,7 +277,7 @@ pub struct BevelTexture { /// One layer effect. Several instances of the same kind are allowed /// (Photoshop's multiple strokes/shadows/overlays). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Effect { DropShadow(Shadow), InnerShadow(Shadow), @@ -409,7 +409,7 @@ pub fn yes() -> bool { } /// Document-wide light used by effects with `use_global_light`. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GlobalLight { pub angle: f32, pub altitude: f32, diff --git a/crates/doc/src/frame.rs b/crates/doc/src/frame.rs index 251671111b..97e507270b 100644 --- a/crates/doc/src/frame.rs +++ b/crates/doc/src/frame.rs @@ -4,7 +4,7 @@ use crate::{Path, ShapeLayer, ShapeStroke}; use photocraft_geom::{Affine, Point, Rect}; use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Frame { pub path: Path, pub transform: Affine, diff --git a/crates/doc/src/import_conversion.rs b/crates/doc/src/import_conversion.rs index 8383564794..2846f3f52f 100644 --- a/crates/doc/src/import_conversion.rs +++ b/crates/doc/src/import_conversion.rs @@ -22,13 +22,13 @@ const TARGET_BYTES: usize = 128; const ATTACHMENT_BYTES: usize = 160; /// An optional future report is retained without interpreting its record or binary payloads. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum ImportConversion { Report(ConversionReport), Opaque { schema_version: u32, record: Arc>, attachments: Vec>> }, } -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct ConversionReport { pub source_format: String, @@ -40,7 +40,7 @@ pub struct ConversionReport { pub attachments: Vec, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct ConversionEntry { pub feature_code: String, @@ -55,7 +55,7 @@ pub struct ConversionEntry { pub attachments: Vec, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "snake_case")] pub enum ConversionDisposition { NativeEquivalent, @@ -64,7 +64,7 @@ pub enum ConversionDisposition { SkippedNonessential, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "snake_case")] pub enum ConversionReason { NativePolicy, @@ -77,7 +77,7 @@ pub enum ConversionReason { } /// Ordinals/paths identify the source snapshot, including duplicate display names. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct SourceItemRef { pub kind: String, @@ -90,7 +90,7 @@ pub struct SourceItemRef { } /// Import-time references may become stale; they are never remapped into live instructions. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct NativeTargetRef { pub layer_id: Option, @@ -102,7 +102,7 @@ pub struct NativeTargetRef { pub label: String, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct RetainedImportData { pub owner: SourceItemRef, @@ -113,7 +113,7 @@ pub struct RetainedImportData { pub bytes: Arc>, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum ConversionValidationError { Limit(&'static str), Invalid(&'static str), diff --git a/crates/doc/src/layer_tree.rs b/crates/doc/src/layer_tree.rs index b6b8614002..3ea7c6aa30 100644 --- a/crates/doc/src/layer_tree.rs +++ b/crates/doc/src/layer_tree.rs @@ -135,6 +135,12 @@ impl DerefMut for LayerTree { } } +// The index is a pure function of `layers`: every write goes through `DerefMut`, which drops it, `Clone` starts +// without it, and every lookup answers the same whether it is built or not. Its one observable trace is +// `LayerIndex::serial`, a rebuild probe for tests that no view reads. So a shared reference can't change what readers +// see, and a `Tracked` document's revision covers the tree. +impl craft_tracked::PlainData for LayerTree {} + impl Clone for LayerTree { fn clone(&self) -> Self { Self { layers: self.layers.clone(), index: OnceLock::new() } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 79df00ab90..20b279ba14 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -69,7 +69,7 @@ impl LayerId { } /// Identity of the source contents shared by smart-object instances, independent of their bytes. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct SmartContentsId(pub u64); impl SmartContentsId { @@ -93,7 +93,7 @@ impl DocId { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Locks { pub transparency: bool, pub pixels: bool, @@ -141,7 +141,7 @@ impl Locks { } /// Photoshop layer colour labels. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LabelColor { #[default] None, @@ -245,7 +245,7 @@ mod label_color_tests { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct LayerMask { /// Grayscale surface; untouched pixels read as `default` (0 = hide, 1 = reveal). pub surface: Surface, @@ -295,7 +295,7 @@ impl LayerMask { } /// Layer styles. Parsed PSD effect data is kept raw until the effects engine lands (M9). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui_macros::PlainData)] pub struct Effects { pub enabled: bool, pub items: Vec, @@ -327,7 +327,7 @@ pub fn walks() -> u64 { WALKS.with(std::cell::Cell::get) } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Group { pub children: Vec, pub expanded: bool, @@ -339,7 +339,7 @@ pub struct Group { pub frame_stroke: Option, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Fill { Solid(Color), /// Gradient between stops at `angle` degrees (`style` geometry, optionally reversed), laid @@ -444,7 +444,7 @@ impl std::hash::Hash for Fill { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct TextLayer { pub text: String, pub font_family: String, @@ -559,13 +559,13 @@ fn normalize_runs(text: &str, runs: Vec<(usize, S)>, base: S) -> Vec<( /// A bounded display preview for an embedded native vector, bound to its exact source bytes. /// The SVG is display data only; saving the object retains the native source format. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct VectorPreview { pub source_hash: [u8; 32], pub svg: Arc>, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct SmartObject { /// Ordinary layer duplicates share this identity; independent contents receive a fresh one. pub contents_id: SmartContentsId, @@ -624,16 +624,17 @@ impl SmartObject { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum SmartSource { Embedded { file_name: String, bytes: Arc> }, Linked { path: String }, } /// A filter applied non-destructively: a command id plus its parameters (data, not code). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct SmartFilter { pub command: String, + #[plain_data(assume = "JSON value: plain data")] pub params: serde_json::Value, pub blend: BlendMode, pub opacity: f32, @@ -645,7 +646,7 @@ pub struct SmartFilter { /// Used by the compositor instead of rendering [`Fill`] itself, but only while /// `fill` still equals the layer's current fill (editing the fill invalidates /// the cache automatically). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct FillCache { /// The fill these pixels were rendered for. pub fill: Fill, @@ -653,7 +654,7 @@ pub struct FillCache { pub surface: Surface, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum LayerContent { Raster(Surface), Group(Group), @@ -686,7 +687,7 @@ impl LayerContent { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Layer { pub id: LayerId, pub name: String, @@ -836,7 +837,7 @@ impl Layer { /// Ruler guides in document pixels. f64 like the rest of the view geometry: a guide placed in /// ruler units (1 cm at 300 ppi is 118.110236… px) or read from a PSD's 1/32 px positions keeps /// its exact place. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Guides { pub horizontal: Vec, pub vertical: Vec, @@ -849,7 +850,7 @@ pub struct Guides { /// One guide's own colour. It is keyed by orientation and position, not by index, so code that /// drops or reorders guide positions (crop, artboards, guide layouts) can never move a colour onto /// another guide: a guide whose entry no longer matches simply uses the preference colour. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GuideColor { pub vertical: bool, pub position: f64, @@ -879,7 +880,7 @@ impl Guides { } /// Which areas an alpha channel's overlay colour marks (Channel Options › Color Indicates). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum ColorIndicates { /// Colour shows over black (unselected) pixels: Photoshop's default. @@ -892,7 +893,7 @@ pub enum ColorIndicates { /// An extra (alpha or spot) channel, also used for the temporary Quick Mask channel. /// /// The surface is grayscale at the document depth; white = selected (1.0), black = masked. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct AlphaChannel { pub name: String, pub surface: Surface, @@ -923,7 +924,7 @@ impl AlphaChannel { /// A raw PSD global tagged block: (signature, key, data). pub type PsdGlobalBlock = ([u8; 4], [u8; 4], Arc>); -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui_macros::PlainData)] pub struct Metadata { /// Historical conversion information; never consulted by native rendering or editing. /// Shared so document/history clones do not duplicate report entries, strings or retained payloads. @@ -942,7 +943,7 @@ pub struct Metadata { pub psd_global_blocks: Vec, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Document { pub id: DocId, pub name: String, @@ -1014,7 +1015,7 @@ pub struct Document { /// The encoder settings a document's file was opened or saved with: what File › Save and the /// Save As defaults reuse for that format. Empty for a new document or a file without lossy /// options. Qualities are on the codecs' 1–100 scale. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct FileEncoding { /// JPEG quality (estimated from the file's quantisation tables on open). diff --git a/crates/doc/src/mode.rs b/crates/doc/src/mode.rs index 3fecadd2b7..9980c49ed5 100644 --- a/crates/doc/src/mode.rs +++ b/crates/doc/src/mode.rs @@ -14,7 +14,7 @@ use crate::LayerId; use crate::adjust::CurvePoint; /// Image › Mode › Color Table: the palette of an Indexed Color document (at most 256 entries). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ColorTable { /// sRGB 8-bit entries. pub colors: Vec<[u8; 3]>, @@ -53,7 +53,7 @@ impl ColorTable { /// pixel copy while the layer is unchanged. A save keeps the indices only while they hold, and an /// open pairs them with the layer it loads: identical tiles load as one, so loaded pixels can't /// prove they are unchanged. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct ColorIndices { /// The layer the indices are for. pub layer: LayerId, @@ -91,7 +91,7 @@ impl ColorIndices { } /// One Duotone ink: its display colour and the curve mapping gray density to ink density. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct DuotoneInk { pub name: String, /// Display colour of the solid ink (sRGB 0..=1). @@ -107,7 +107,7 @@ impl DuotoneInk { } /// Image › Mode › Duotone: 1–4 inks (Monotone, Duotone, Tritone, Quadtone) printed over paper. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Duotone { pub inks: Vec, /// The PSD colour-mode data this came from, written back unchanged while the inks are unedited. @@ -172,7 +172,7 @@ fn curve_eval(pts: &[CurvePoint], x: f32) -> f32 { } /// Layer › Smart Objects › Stack Mode: a per-pixel statistic over the smart object's layers. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum StackMode { Entropy, Kurtosis, diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index 185ddb9ccb..d07fb34ab9 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -14,7 +14,7 @@ pub const MAX_EDGE: u32 = 30_000; pub const MAX_PAINT_PIXELS: u64 = 1 << 26; /// A bounded, cancellable pattern hash could not be completed. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum PatternBuildError { InvalidDimensions, ScratchLimit { required: usize, available: usize }, @@ -58,7 +58,7 @@ pub const BAND_ROWS: u32 = 256; /// One pattern tile. Pixels cover `0..width × 0..height` of `surface`, in any pixel format /// (depth and colour model are the pattern's own, as in Photoshop). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Pattern { /// Unique id (a UUID string, as Photoshop's `Idnt`). pub id: String, diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rs index 6bfb9b1577..b1a7509d85 100644 --- a/crates/doc/src/slices.rs +++ b/crates/doc/src/slices.rs @@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize}; use crate::{Document, LayerId}; /// Where a slice comes from (PSD `ESliceOrigin`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum SliceOrigin { /// Fills the canvas around user and layer slices; regenerated, never edited. @@ -50,7 +50,7 @@ impl SliceOrigin { } /// Slice Options › Slice Type. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum SliceKind { /// Exported as an image file. @@ -96,7 +96,7 @@ impl SliceKind { } /// One slice and its Slice Options. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct Slice { /// Stable id (PSD `sliceID`), unique within the document. @@ -126,7 +126,7 @@ pub struct Slice { } /// The document's slices (PSD resource 1050). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct Slices { /// Group name (PSD: the base name, usually the document name). @@ -154,7 +154,7 @@ impl Slices { /// A slice as shown and exported: user/layer slices plus generated auto slices, numbered the way /// Photoshop numbers them (top-to-bottom, left-to-right, from 1). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct ResolvedSlice { /// 1-based display number. pub number: usize, diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index f6c8619f5a..e24f267d6d 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -13,7 +13,7 @@ use photocraft_color::Color; use serde::{Deserialize, Serialize}; /// Kerning mode (Photoshop: Metrics, Optical, 0). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Kerning { /// Font kerning (`kern` feature). #[default] @@ -24,7 +24,7 @@ pub enum Kerning { Off, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Caps { #[default] Normal, @@ -34,7 +34,7 @@ pub enum Caps { /// Superscript / subscript (Photoshop's `FontBaseline`). The run is drawn smaller and raised or /// lowered; `size_pt` and `baseline_shift_pt` keep their own values. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum FontBaseline { #[default] Normal, @@ -43,21 +43,21 @@ pub enum FontBaseline { } /// An OpenType feature setting, e.g. `{ tag: "ss01", value: 1 }`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct FontFeature { pub tag: String, pub value: u16, } /// A variable-font axis setting, e.g. `{ axis: "wght", value: 650.0 }`. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct FontVariation { pub axis: String, pub value: f32, } /// Character style (Photoshop's Character panel). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct CharStyle { /// Family name ("Inter"). Empty = the default family. @@ -147,13 +147,13 @@ impl Default for CharStyle { } /// A character style applied to `len` UTF-8 bytes. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct TextRun { pub len: usize, pub style: CharStyle, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum TextAlign { #[default] Left, @@ -175,7 +175,7 @@ impl TextAlign { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum TextDirection { /// From the first strong character (Unicode bidi rules). #[default] @@ -185,7 +185,7 @@ pub enum TextDirection { } /// Paragraph style (Photoshop's Paragraph panel). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct ParagraphStyle { pub align: TextAlign, @@ -221,7 +221,7 @@ impl Default for ParagraphStyle { } /// A paragraph style applied to `len` UTF-8 bytes (whole paragraphs, including the break). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ParagraphRun { pub len: usize, pub style: ParagraphStyle, @@ -230,7 +230,7 @@ pub struct ParagraphRun { /// Point text grows from its anchor (text-space origin = first baseline at the anchor); /// paragraph (box) text wraps inside a rectangle; path text runs along a curve; area text /// wraps inside a closed path. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum TextShape { #[default] Point, @@ -258,7 +258,7 @@ pub enum TextShape { Area { path: super::vector::Path }, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Orientation { #[default] Horizontal, @@ -266,7 +266,7 @@ pub enum Orientation { Vertical, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum AntiAlias { None, Sharp, @@ -283,7 +283,7 @@ pub enum AntiAlias { /// Warp text settings (Photoshop `warp` descriptor), applied to the glyph outlines by /// `photocraft-text` (see its `warp` module) and round-tripped through PSD. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct TextWarp { /// `warpNone`, `warpArc`, `warpFlag`, … pub style: String, diff --git a/crates/doc/src/text_styles.rs b/crates/doc/src/text_styles.rs index bb85ef2f27..8a5f386351 100644 --- a/crates/doc/src/text_styles.rs +++ b/crates/doc/src/text_styles.rs @@ -28,31 +28,34 @@ pub type StyleAttrs = Map; const REF_KEY: &str = "style_sheet"; /// A named character style. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct CharacterStyleDef { /// Stable id (≥ 1), referenced by [`CharStyle::style_sheet`]. pub id: u32, pub name: String, /// Character attributes this style sets (others come from the paragraph style). + #[plain_data(assume = "JSON values: plain data")] pub attrs: StyleAttrs, } /// A named paragraph style (or Basic Paragraph). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct ParagraphStyleDef { /// Stable id (≥ 1; Basic Paragraph is 0), referenced by [`ParagraphStyle::style_sheet`]. pub id: u32, pub name: String, /// Paragraph attributes this style sets. + #[plain_data(assume = "JSON values: plain data")] pub para_attrs: StyleAttrs, /// Character attributes this style sets (the basis of every run in its paragraphs). + #[plain_data(assume = "JSON values: plain data")] pub char_attrs: StyleAttrs, } /// The document's named type styles. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct TextStyles { /// Character styles in panel order ("None" is implicit and first). @@ -63,6 +66,7 @@ pub struct TextStyles { pub basic: ParagraphStyleDef, /// Style sheets of the PSD text engine this document was read from (`ResourceDict` /// `StyleSheetSet` / `ParagraphSheetSet`), kept so unmapped data survives a round trip. + #[plain_data(assume = "JSON value: plain data")] pub psd_raw: Option, } diff --git a/crates/doc/src/variables.rs b/crates/doc/src/variables.rs index 83f0e5f5a9..88385ee62b 100644 --- a/crates/doc/src/variables.rs +++ b/crates/doc/src/variables.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; use crate::LayerId; /// All variable definitions and data sets for a document. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Variables { /// Variable definitions, each bound to a layer. #[serde(default)] @@ -27,7 +27,7 @@ pub struct Variables { } /// One named variable bound to a layer. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct VariableDef { /// Unique variable name (matched by data-set values and CSV headers). pub name: String, @@ -38,7 +38,7 @@ pub struct VariableDef { } /// The aspect of a layer a variable controls (Photoshop's three variable types). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(tag = "type", rename_all = "camelCase")] pub enum VarKind { /// Show or hide the layer. @@ -58,7 +58,7 @@ pub enum VarKind { } /// How a replacement image is scaled into the layer bounds (Photoshop's "Method"). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum PixelMethod { /// Scale to fit inside the bounds, keeping aspect (default). @@ -73,7 +73,7 @@ pub enum PixelMethod { } /// Where a replacement image sits within the layer bounds. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum PixelAlign { TopLeft, @@ -89,7 +89,7 @@ pub enum PixelAlign { } /// A named row of values, one per variable (keyed by variable name). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct DataSet { pub name: String, /// Variable name → value. A variable with no entry keeps the document's current value. @@ -98,7 +98,7 @@ pub struct DataSet { } /// One variable's value within a data set. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct DataValue { /// Which variable (by name). pub variable: String, @@ -107,7 +107,7 @@ pub struct DataValue { } /// The payload of a [`DataValue`], matched to the variable's [`VarKind`]. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(tag = "kind", content = "value", rename_all = "camelCase")] pub enum Value { /// For a Visibility variable. diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index 0f6b4af7e2..3220eccb16 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize}; use crate::{Fill, Surface}; /// A Bézier knot (anchor + two control points). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Knot { pub anchor: Point, /// Control point of the segment arriving at this knot. @@ -50,7 +50,7 @@ impl Knot { } /// How a subpath combines with the subpaths before it (Photoshop's path operations). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum PathOp { /// Combine shapes (union). #[default] @@ -68,14 +68,14 @@ pub enum PathOp { } /// Winding rule used to fill each subpath. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum FillRule { #[default] NonZero, EvenOdd, } -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Subpath { pub closed: bool, pub knots: Vec, @@ -114,7 +114,7 @@ impl Subpath { } /// A vector path: subpaths plus how they are filled and combined. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Path { pub subpaths: Vec, #[serde(default)] @@ -167,7 +167,7 @@ impl Path { } /// A document-level path (Paths panel entry). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui_macros::PlainData)] pub struct NamedPath { pub name: String, pub path: Path, @@ -176,7 +176,7 @@ pub struct NamedPath { } /// The document's clipping path (PSD resource 2999): which saved path clips on export. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ClippingPath { pub name: String, /// Output flatness in device pixels (0 = printer default). @@ -184,7 +184,7 @@ pub struct ClippingPath { } /// A layer's vector mask (Layer › Vector Mask). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct VectorMask { pub path: Path, pub enabled: bool, @@ -204,7 +204,7 @@ impl VectorMask { } /// Where a stroke sits relative to the path. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum StrokeAlign { Inside, #[default] @@ -212,7 +212,7 @@ pub enum StrokeAlign { Outside, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LineCap { #[default] Butt, @@ -220,7 +220,7 @@ pub enum LineCap { Square, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LineJoin { #[default] Miter, @@ -229,7 +229,7 @@ pub enum LineJoin { } /// Shape stroke (Photoshop's shape "Stroke" options, not the layer-style stroke). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct ShapeStroke { /// Width in px. @@ -291,7 +291,7 @@ impl ShapeStroke { } /// Parametric ("live") shape the path was generated from, kept for re-editing (Properties panel). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum LiveShape { /// Rectangle `[x, y, w, h]` with corner radii `[tl, tr, br, bl]` (all zero = sharp). @@ -341,7 +341,7 @@ pub enum LiveShape { } /// A shape layer: a filled and/or stroked path. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct ShapeLayer { pub path: Path, /// `None` = no fill (Photoshop's fill "none"). diff --git a/crates/doc/src/video.rs b/crates/doc/src/video.rs index f93a32173e..b0d29d79b2 100644 --- a/crates/doc/src/video.rs +++ b/crates/doc/src/video.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use photocraft_raster::Surface; /// Where a video layer's footage came from. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum VideoSource { /// Created blank (Layer › Video Layers › New Blank Video Layer). Blank, @@ -20,7 +20,7 @@ pub enum VideoSource { /// /// Frames are full raster surfaces held in memory and saved in native documents. The /// optional original footage is kept separately from painted frames for comparison/restore. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct VideoData { pub frames: Vec, /// Immutable original footage of a file-backed sequence. COW surfaces share unchanged @@ -57,7 +57,7 @@ impl PartialEq for VideoData { } /// The document timeline. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Timeline { /// Frames per second. pub fps: f32, diff --git a/crates/engine/src/cmd/channel_cmds/view.rs b/crates/engine/src/cmd/channel_cmds/view.rs index 067d05e08e..d37a93e357 100644 --- a/crates/engine/src/cmd/channel_cmds/view.rs +++ b/crates/engine/src/cmd/channel_cmds/view.rs @@ -5,7 +5,7 @@ use super::{AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, // View state /// What pixel commands edit (Channels panel click / ⌘2…⌘9). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase", tag = "kind", content = "index")] pub enum ChannelTarget { /// The layers (all colour channels). In Quick Mask mode this edits the Quick Mask. @@ -22,7 +22,7 @@ pub enum ChannelTarget { } /// Per-document Channels panel state: the target and the eye toggles. Not part of history. -#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct ChannelView { pub target: ChannelTarget, diff --git a/crates/engine/src/cmd/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs index a70ae99f7e..2fdfad4eec 100644 --- a/crates/engine/src/cmd/edit_cmds.rs +++ b/crates/engine/src/cmd/edit_cmds.rs @@ -26,14 +26,11 @@ pub struct Clip { pub svg: Option>>, /// Native colour indices for a multi-component clip, in channel order. Singletons are grayscale. pub components: Option>, - #[plain_data(assume = "raster tiles: shared copy-on-write pixels, paged to disk unseen; a shared reference can't change them")] pub surface: Surface, - #[plain_data(assume = "geometry: plain numbers")] pub bounds: Rect, /// The copied layer itself, when Copy took a whole layer that Paste should recreate rather /// than rasterize (see [`whole_layer`]): a scratch document in the source's colour holding it. /// `surface` still holds its pixels, for Paste Into, masks, channels and other apps. - #[plain_data(assume = "the scratch document is replaced, never changed in place")] pub layers: Option>, /// The source document's resolution (ppi): File › New from the clipboard takes it, as /// Photoshop's Clipboard preset does. None for an image from another app. @@ -44,7 +41,6 @@ pub struct Clip { /// The artboard the pixels were copied from (its id and rect at the time), when they came /// from one: Paste into another board of the same document keeps their place on the board /// ([`board_shift`], #8788). None outside boards, across several, or for a copied board. - #[plain_data(assume = "a layer id and its rect: plain numbers")] pub board: Option<(LayerId, Rect)>, } diff --git a/crates/engine/src/cmd/edit_menu_cmds/purge.rs b/crates/engine/src/cmd/edit_menu_cmds/purge.rs index 3cc6aee5b3..8f84de4fe7 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/purge.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/purge.rs @@ -3,7 +3,7 @@ use super::{Result, Session, Value, json}; // ------------------------------------------------------------------ Purge fn history_bytes(s: &Session, all: bool) -> usize { - let docs: Vec<&crate::DocState> = if all { s.documents().iter().collect() } else { s.active().into_iter().collect() }; + let docs: Vec<&crate::DocState> = if all { s.documents().iter().map(|st| &**st).collect() } else { s.active().into_iter().collect() }; // Purge keeps the snapshots, so the tiles they share with the states aren't freed. docs.iter() .map(|d| { diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 6700353339..68d55fe0e9 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -137,7 +137,7 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { let inputs = batch_inputs_tree(p, cmd, &output)?; process_tree(s, &inputs, &output, format, save, TreeNaming::Unique, &process) } else { - let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().collect() }; + let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().map(|st| &**st).collect() }; if documents.is_empty() { return Err(EngineError::NoDocument); } @@ -227,7 +227,7 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) - "folder" => ProcessorInputs::Folder(batch_inputs_tree(p, IMAGE_PROCESSOR, output)?), "current" => ProcessorInputs::Documents(vec![s.active().ok_or(EngineError::NoDocument)?]), _ if s.documents().is_empty() => return Err(EngineError::NoDocument), - _ => ProcessorInputs::Documents(s.documents().iter().collect()), + _ => ProcessorInputs::Documents(s.documents().iter().map(|st| &**st).collect()), }; let mut files = Vec::new(); let mut errors = Vec::new(); diff --git a/crates/engine/src/cmd/float_cmds.rs b/crates/engine/src/cmd/float_cmds.rs index 2853788b02..9a06516353 100644 --- a/crates/engine/src/cmd/float_cmds.rs +++ b/crates/engine/src/cmd/float_cmds.rs @@ -28,7 +28,7 @@ use crate::{DocState, EngineError, Result, Session}; /// A layer split by its selection: the layer with the selected pixels cut out, and the cut pixels /// (cropped to the selection). Splitting touches only the selection's area, and placing the piece /// ([`CutParts::moved`]) only the piece's: the cut-out layer's other tiles are shared. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct CutParts { pub layer: LayerId, rest: Surface, @@ -258,7 +258,7 @@ fn cut_piece(base: &Surface, sel: &Surface, b: photocraft_geom::Rect, with_alpha } /// A piece floating `offset` whole pixels from where it was cut, over document `revision`. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct Floating { pub layer: LayerId, pub offset: (i32, i32), @@ -392,11 +392,18 @@ pub(crate) fn drops_for(s: &Session, id: &str) -> bool { /// Before any command (`Session::dispatch`): Undo puts a floating piece back (and is used up: /// returns its result); every other command but the floating ones drops it first. pub(crate) fn before_command(s: &mut Session, id: &str) -> Result> { - let Some(st) = s.active_mut() else { return Ok(None) }; + // Runs before every command: read through `active`, and borrow the document to change only to drop a stale + // float, since the borrow moves its `Tracked` revision. + let Some(st) = s.active() else { return Ok(None) }; if floating(st).is_none() { - st.floating = None; + if st.floating.is_some() + && let Some(st) = s.active_mut() + { + st.floating = None; + } return Ok(None); } + let Some(st) = s.active_mut() else { return Ok(None) }; match id { // Edit › Undo and the History panel's Step Backward step back over the move itself. "edit.undo" | "history.stepBackward" => { diff --git a/crates/engine/src/cmd/fx_view_cmds.rs b/crates/engine/src/cmd/fx_view_cmds.rs index 58bac49b32..7031d4c7b6 100644 --- a/crates/engine/src/cmd/fx_view_cmds.rs +++ b/crates/engine/src/cmd/fx_view_cmds.rs @@ -64,7 +64,6 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { if !expanded { st.fx_collapsed.extend(targets.iter().copied()); } - st.note_disclosure_change(); Ok(json!({"expanded": expanded, "layers": targets.len()})) } @@ -104,7 +103,7 @@ mod tests { } /// Smart Filters hide and show with the layer's effects, as view state: no document edit, revision or history step; - /// the Layers view revision, which the Layers panel's rows follow, moves. + /// the document's `Tracked` revision, which the Layers panel's rows follow, moves. #[test] fn smart_filters_share_the_effects_disclosure_without_an_edit() { let (mut s, a, b) = session(); @@ -113,7 +112,7 @@ mod tests { s.execute("image.adjustments.invert", json!({})).unwrap(); let smart = s.active().unwrap().active_layer.unwrap(); let doc = s.active().unwrap().doc.clone(); - let revisions = |s: &Session| s.active().map(|st| (st.revision, st.layers_view_revision())).unwrap(); + let revisions = |s: &Session| s.active_tracked().map(|st| (st.revision, st.revision().count)).unwrap(); let before = revisions(&s); let steps = s.active().unwrap().history.past_len(); s.execute(ID, json!({"layer": smart.0, "expanded": false})).unwrap(); @@ -121,7 +120,7 @@ mod tests { assert!(open(&s, b)); assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); let after = revisions(&s); - assert!(after.0 == before.0 && after.1 > before.1, "the Layers view revision only: {before:?} -> {after:?}"); + assert!(after.0 == before.0 && after.1 > before.1, "the tracked revision only: {before:?} -> {after:?}"); assert_eq!(s.active().unwrap().history.past_len(), steps); s.execute(ID, json!({"expanded": false, "all": true})).unwrap(); assert!(!open(&s, smart.0) && !open(&s, b)); diff --git a/crates/engine/src/cmd/group_view_cmds.rs b/crates/engine/src/cmd/group_view_cmds.rs index df742dbae0..6e004dbedc 100644 --- a/crates/engine/src/cmd/group_view_cmds.rs +++ b/crates/engine/src/cmd/group_view_cmds.rs @@ -77,7 +77,6 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { _ => return Err(EngineError::NoLayer(id)), } }; - st.note_disclosure_change(); Ok(json!({"expanded": expanded, "groups": changed})) } @@ -121,10 +120,10 @@ mod tests { st.saved_revision = st.revision; let undo_steps = s.active().unwrap().history.entries().len(); assert!(expanded(&s, inner) && expanded(&s, outer)); - let (revision, view) = s.active().map(|st| (st.revision, st.layers_view_revision())).unwrap(); + let (revision, view) = s.active_tracked().map(|st| (st.revision, st.revision())).unwrap(); assert_eq!(s.execute(ID, json!({"layer": inner})).unwrap()["expanded"], false); - let st = s.active().unwrap(); - assert!(st.revision == revision && st.layers_view_revision() > view, "the Layers view revision only: the Layers panel's rows follow it"); + let st = s.active_tracked().unwrap(); + assert!(st.revision == revision && st.revision() != view, "the tracked revision only: the Layers panel's rows follow it"); assert!(!expanded(&s, inner) && expanded(&s, outer)); assert_eq!(s.active().unwrap().history.entries().len(), undo_steps, "no history step"); assert_eq!(s.active().unwrap().saved_revision, s.active().unwrap().revision, "still clean"); diff --git a/crates/engine/src/cmd/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs index 30cacb8a5d..0a5c2f186a 100644 --- a/crates/engine/src/cmd/history_cmds.rs +++ b/crates/engine/src/cmd/history_cmds.rs @@ -24,7 +24,7 @@ use crate::image_cmds::reidentify_copied_layers; use crate::{EngineError, Result, Session}; /// A History panel snapshot: the document as it was when taken, and the layers it targeted. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct Snapshot { pub id: u64, pub name: String, diff --git a/crates/engine/src/cmd/mask_view_cmds.rs b/crates/engine/src/cmd/mask_view_cmds.rs index 14778a98bf..4c23aa71b9 100644 --- a/crates/engine/src/cmd/mask_view_cmds.rs +++ b/crates/engine/src/cmd/mask_view_cmds.rs @@ -24,7 +24,7 @@ pub const ID: &str = "view.layerMask"; pub const OVERLAY_ID: &str = "layer.toggleMaskOverlay"; /// How a shown layer mask is drawn. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum MaskViewMode { /// The mask alone, as a grayscale image (⌥-click). @@ -34,7 +34,7 @@ pub enum MaskViewMode { } /// Which layer's mask is shown, and how. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, craft_ui_macros::PlainData)] pub struct LayerMaskView { pub layer: LayerId, pub mode: MaskViewMode, @@ -71,11 +71,16 @@ pub fn current(st: &DocState) -> Option { /// Drop a mask view that no longer applies (another layer became active, the layer or its mask /// was deleted, undo). pub(crate) fn fix(st: &mut DocState) { - if st.channel_view.layer_mask.is_some() && current(st).is_none() { + if stale(st) { st.channel_view.layer_mask = None; } } +/// Whether `st` keeps a layer-mask view that no longer applies ([`fix`] ends it). +pub(crate) fn stale(st: &DocState) -> bool { + st.channel_view.layer_mask.is_some() && current(st).is_none() +} + fn mode_name(v: Option) -> &'static str { match v.map(|v| v.mode) { None => "off", diff --git a/crates/engine/src/cmd/slice_cmds.rs b/crates/engine/src/cmd/slice_cmds.rs index 9826c2322a..33360ce68e 100644 --- a/crates/engine/src/cmd/slice_cmds.rs +++ b/crates/engine/src/cmd/slice_cmds.rs @@ -92,9 +92,10 @@ fn layer_slice_rect(doc: &Document, s: &Slice) -> Option { } /// Re-fits layer-based slices of the active document to their layers; drops slices whose layer -/// was deleted (as Photoshop does). Not a history step. +/// was deleted (as Photoshop does). Not a history step. Runs after every command, so it reads through `active` and +/// borrows the document to change only when a slice moves: the borrow moves its `Tracked` revision. pub(crate) fn refresh(s: &mut Session) { - let Some(st) = s.active_mut() else { return }; + let Some(st) = s.active() else { return }; if !st.doc.slices.list.iter().any(|sl| sl.origin == SliceOrigin::Layer) { return; } @@ -109,6 +110,7 @@ pub(crate) fn refresh(s: &mut Session) { if changes.is_empty() { return; } + let Some(st) = s.active_mut() else { return }; let doc = Arc::make_mut(st.doc_mut()); for (id, r) in changes { match r { diff --git a/crates/engine/src/cmd/symmetry_cmds.rs b/crates/engine/src/cmd/symmetry_cmds.rs index 4b93d797de..97781c3ff3 100644 --- a/crates/engine/src/cmd/symmetry_cmds.rs +++ b/crates/engine/src/cmd/symmetry_cmds.rs @@ -14,14 +14,14 @@ use crate::{EngineError, Result, Session, commands::CommandSpec}; const MAX_SEGMENTS: usize = 1024; const SAMPLES_PER_CURVE: usize = 12; -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct SymmetryAxis { pub source: String, pub segments: Vec<[[f64; 2]; 2]>, } /// Per-document painting tool state, never stored in the document's paths or pixels. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum PaintingSymmetry { Path(SymmetryAxis), Preset(PresetSymmetry), diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index c8b9a2eea1..8ed80a30df 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -1,21 +1,21 @@ use super::{Arc, Document, History, LayerId, LayerTarget, channel_cmds, float_cmds, history_cmds, layer_multi_cmds, symmetry_cmds}; -/// Per-document editing state. -#[derive(Clone, Debug)] +/// Per-document editing state. Plain data: the session holds each in a `Tracked`, whose revision moves with every +/// write, view state included. +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct DocState { inputs: DocStateInputs, - selected_cache: std::sync::OnceLock>, + selected_cache: SelectedOrder, pub history: History, /// Anchor of range selection (the last plainly or command-clicked layer). pub layer_anchor: Option, pub path: Option, /// An Affinity document (or its preview) must not acquire the native source as its Save path. pub source_read_only: bool, - /// Increments on every change; UIs re-render when it moves. + /// Counts the edit steps: save state ([`Self::is_dirty`]) and damage measure from it. Views key on the `Tracked` + /// revision the session holds the state in, which also moves with view state. pub revision: u64, pub saved_revision: u64, - /// Native save cache shared with this document's workers, released with the editing state. - pub pcraft_cache: photocraft_io::PcraftExportCache, /// How much of `revision` came from view-only changes (channel eyes, targeting): pixel caches can ignore those. pub view_revision: u64, /// Area changed since revision [`DocState::damage_from`] (None = assume everything changed): @@ -38,8 +38,6 @@ pub struct DocState { /// Layers panel: layers whose effects list is collapsed under their row (the fx triangle; /// view state, not history). Effects lists start open. pub fx_collapsed: Vec, - /// See [`DocState::layers_view_revision`]. - layers_view_revision: u64, /// ⌥-click on a layer's eye (`layer.showOnly`): the layer shown alone and every layer's /// visibility before, so the next ⌥-click restores it (view state, not history). pub show_only: Option<(LayerId, Vec<(LayerId, bool)>)>, @@ -76,7 +74,7 @@ pub struct DocState { } /// Read-only document and layer selection inputs. Mutations go through `DocState` methods. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct DocStateInputs { /// The current document. pub doc: Arc, @@ -86,6 +84,15 @@ pub struct DocStateInputs { pub selected_layers: Vec, } +/// The selected layers in document order ([`DocState::selected_layers`]), built on the first read after a write. +#[derive(Clone, Debug, Default)] +struct SelectedOrder(std::sync::OnceLock>); + +// The order is a pure function of the document and the raw selection: every write to either goes through a +// `DocState` method that drops it (`doc_mut`, `set_active_layer`, `selection_mut`), and readers get the same answer +// whether it is built or not. So a shared reference can't change what readers see. +impl craft_tracked::PlainData for SelectedOrder {} + impl std::ops::Deref for DocState { type Target = DocStateInputs; fn deref(&self) -> &Self::Target { @@ -124,14 +131,13 @@ impl DocState { let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; Self { inputs: DocStateInputs { doc, active_layer, selected_layers: active_layer.into_iter().collect() }, - selected_cache: std::sync::OnceLock::new(), + selected_cache: SelectedOrder::default(), history, layer_anchor: active_layer, path, source_read_only: false, revision: 1, saved_revision: 1, - pcraft_cache: Default::default(), view_revision: 0, last_damage: None, damage_span: None, @@ -141,7 +147,6 @@ impl DocState { isolated_layers: Vec::new(), symmetry: None, fx_collapsed: Vec::new(), - layers_view_revision: 0, show_only: None, floating: None, color_samplers: Vec::new(), @@ -179,7 +184,7 @@ impl DocState { } /// Mutable access invalidates the ordered selection, including on document replacement. pub fn doc_mut(&mut self) -> &mut Arc { - self.selected_cache.take(); + self.selected_cache.0.take(); &mut self.inputs.doc } /// The active layer, if any. @@ -189,7 +194,7 @@ impl DocState { /// Set the active layer and invalidate the held ordered selection. pub fn set_active_layer(&mut self, active: Option) { if self.inputs.active_layer != active { - self.selected_cache.take(); + self.selected_cache.0.take(); self.inputs.active_layer = active; } } @@ -199,14 +204,14 @@ impl DocState { } /// Mutate the raw selection, invalidating the held ordered selection before access. pub fn selection_mut(&mut self) -> &mut Vec { - self.selected_cache.take(); + self.selected_cache.0.take(); &mut self.inputs.selected_layers } /// Selected layers in bottom-to-top document order, including the active layer. /// Missing IDs are skipped; if the active layer is not in the raw selection, only it is used. /// The first read after a mutation builds the held slice; later reads reuse it. pub fn selected_layers(&self) -> &[LayerId] { - self.selected_cache.get_or_init(|| selected_in(&self.inputs.doc, self.inputs.active_layer, &self.inputs.selected_layers)) + self.selected_cache.0.get_or_init(|| selected_in(&self.inputs.doc, self.inputs.active_layer, &self.inputs.selected_layers)) } pub fn is_layer_selected(&self, id: LayerId) -> bool { self.active_layer == Some(id) || (self.active_layer.is_some_and(|a| self.selected_layers.contains(&a)) && self.selected_layers.contains(&id)) @@ -314,15 +319,6 @@ impl DocState { self.last_damage = Some(photocraft_geom::Rect::EMPTY); self.record_damage(); } - /// Moves when an effects list or a group in the Layers panel opens or closes. That is view - /// state, not an edit, so [`DocState::revision`] stays; the Layers panel's rows key on this. - pub fn layers_view_revision(&self) -> u64 { - self.layers_view_revision - } - /// Count an effects list or group opened or closed (see [`Self::layers_view_revision`]). - pub(crate) fn note_disclosure_change(&mut self) { - self.layers_view_revision += 1; - } /// Move to the next revision for a view-only change (channel eyes, a history state deleted, /// Layers panel isolation): readers keyed on the revision follow it, pixel caches ignore it /// through `view_revision`, and no pixels need drawing again. `keep_clean` as for @@ -471,19 +467,14 @@ impl Default for ToolState { /// copies them (Paste Layer Style puts them all on each target). #[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct CopiedStyle { - #[plain_data(assume = "document effects: plain values")] pub effects: photocraft_doc::Effects, - #[plain_data(assume = "an enum")] pub blend: photocraft_color::BlendMode, pub fill: f32, - #[plain_data(assume = "document blending options: plain values")] pub advanced: photocraft_doc::AdvancedBlending, - #[plain_data(assume = "document blend ranges: plain values")] pub blend_if: photocraft_doc::BlendIf, pub excluded_channels: u32, /// The colour mode it was copied in: Blend If's channel ranges and the channel restrictions /// only carry over to a document in the same mode. - #[plain_data(assume = "an enum")] pub mode: photocraft_color::ColorMode, } diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index c4071c213e..53b0e343bd 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1897,7 +1897,6 @@ impl Session { } else if !st.fx_collapsed.contains(&layer_id) { st.fx_collapsed.push(layer_id); } - st.note_disclosure_change(); } self.after_command(id, params, spec.journal, automation, Some(nested_from), pre_selected.as_deref(), &record_before); Ok(Started::Done(v)) @@ -1921,7 +1920,11 @@ impl Session { /// keeps the damage it reported. Debug and test builds also count a whole-document redraw of /// a small change ([`Session::whole_redraws`]). pub(crate) fn note_command_damage(&mut self, id: &str, before: &Arc, from: u64) { - let Some(st) = self.active_mut().filter(|st| st.doc.id == before.id && st.revision > from) else { return }; + // Read first: the borrow moves the document's `Tracked` revision, and this runs after every command. + if !self.active().is_some_and(|st| st.doc.id == before.id && st.revision > from) { + return; + } + let Some(st) = self.active_mut() else { return }; if st.revision - from > 1 { st.last_damage = crate::layer_multi_cmds::step_damage(before, &st.doc); st.damage_span = Some((from, st.revision)); @@ -1954,10 +1957,13 @@ impl Session { /// stroke on a layer with a Gradient Overlay reports the stroke, but the gradient is laid out /// again over the whole grown layer (#4053). `before` is the active document before. fn add_relayout_damage(&mut self, before: &Arc) { - let Some(st) = self.active_mut().filter(|st| st.doc.id == before.id && !Arc::ptr_eq(&st.doc, before)) else { return }; + // Read first: the borrow moves the document's `Tracked` revision, and this runs after every command. + let Some(st) = self.active().filter(|st| st.doc.id == before.id && !Arc::ptr_eq(&st.doc, before)) else { return }; let Some(d) = st.last_damage.filter(|d| !d.is_empty()) else { return }; let extra = photocraft_compose::relayout_damage(before, &st.doc); - if !extra.is_empty() { + if !extra.is_empty() + && let Some(st) = self.active_mut() + { st.last_damage = Some(d.union(&extra)); st.record_damage(); } @@ -1994,9 +2000,12 @@ impl Session { pre_selected: Option<&[LayerId]>, before: &crate::actions_record::Before, ) { - // A layer-mask view ends when another layer becomes active (#196). - if let Some(st) = self.active_mut() { - crate::mask_view_cmds::fix(st); + // A layer-mask view ends when another layer becomes active (#196). Borrowed to change only when it does: the + // borrow moves the document's `Tracked` revision, and this runs after every command. + if self.active().is_some_and(crate::mask_view_cmds::stale) + && let Some(st) = self.active_mut() + { + st.channel_view.layer_mask = None; } crate::edit_menu_cmds::after_command(self, id, ¶ms); crate::automate_cmds::after_command(self, id); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 29d4327180..71ceb89ee6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -202,7 +202,10 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do #[derive(Default)] pub struct Session { - docs: Vec, + /// The open documents, each in a `Tracked`: views key on its revision, which every write moves. + docs: Vec>, + /// Each open document's native save cache, shared with its save workers; dropped when the document closes. + pcraft_caches: std::collections::HashMap, documents_generation: u64, /// Override Open belongs only to one Batch scratch session, never to caller preferences. pub(crate) batch_open: Option, @@ -313,8 +316,8 @@ pub struct Session { /// The stamps being taken on a worker thread ([`Session::start_link_scan`]). pub link_scan: Option, /// Each open document's linked smart objects' files that were not there when last looked at - /// ([`Session::missing_links`]). - link_missing: std::collections::HashSet<(u64, String)>, + /// ([`Session::missing_links`]). Written only when the set changes, so its revision says when the list did. + link_missing: craft_tracked::Tracked>, /// Select Subject's last result, reused while the pixels are unchanged (#2865). subject_cache: smartselect_cmds::SubjectCache, /// Object Selection's Object Finder results (#4087), shared by the hover preview and the diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 893933fd80..7cbb1cff09 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -99,7 +99,9 @@ impl Session { // Nothing to look at: no links, or none that is followed. None of them is listed as // missing either, so a link added back isn't shown missing before its first look. if files.iter().all(|(_, file, _)| file.is_none()) { - self.link_missing.retain(|(d, _)| *d != doc); + if self.link_missing.iter().any(|(d, _)| *d == doc) { + self.link_missing.retain(|(d, _)| *d != doc); + } return; } let slot: LinkScan = Arc::default(); @@ -121,20 +123,27 @@ impl Session { self.link_missing.iter().filter(|(d, _)| *d == doc).map(|(_, p)| p.clone()).collect() } + /// Moves whenever the missing linked files ([`Self::missing_links`]) of any open document change. + pub fn missing_links_revision(&self) -> craft_tracked::Revision { + self.link_missing.revision() + } + /// Remember which of document `doc`'s files in `now` were not there, and forget the files of /// closed documents. The web app has no files to look at, so it lists none. fn note_missing_links(&mut self, doc: u64, now: &[(String, Vec, Option)]) { let open: HashSet = self.documents().iter().map(|d| d.doc.id.0).collect(); - self.link_missing.retain(|(d, _)| *d != doc && open.contains(d)); - if cfg!(target_arch = "wasm32") { - return; - } - let document = self.active().and_then(|st| st.path.clone()); - for (path, _, stamp) in now { - if stamp.is_none() && crate::doc_path::resolve_in(path, document.as_deref().map(std::path::Path::new)).is_ok() { - self.link_missing.insert((doc, path.clone())); + let mut missing: HashSet<(u64, String)> = self.link_missing.iter().filter(|(d, _)| *d != doc && open.contains(d)).cloned().collect(); + if !cfg!(target_arch = "wasm32") { + let document = self.active().and_then(|st| st.path.clone()); + for (path, _, stamp) in now { + if stamp.is_none() && crate::doc_path::resolve_in(path, document.as_deref().map(std::path::Path::new)).is_ok() { + missing.insert((doc, path.clone())); + } } } + if *self.link_missing != missing { + *self.link_missing = missing; + } } /// Apply a finished look (`None` while there is none, or it is still running). diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 23a0a97042..bd1e3e41ed 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1970,11 +1970,15 @@ impl Session { let bytes = self.prefs().performance.history_cap_bytes(); let budget = self.prefs().performance.effect_cache_budget_bytes(); let non_linear = self.prefs().history_options.allow_non_linear_history; + // A document is written only when its limits change: every write moves its `Tracked` revision. for st in &mut self.docs { - st.history.max_states = n; - st.history.max_bytes = bytes; - st.history.non_linear = non_linear; - st.trim_history(); + let history = &st.history; + if (history.max_states, history.max_bytes, history.non_linear) != (n, bytes, non_linear) { + st.history.max_states = n; + st.history.max_bytes = bytes; + st.history.non_linear = non_linear; + st.trim_history(); + } } photocraft_compose::set_effect_cache_budget(budget); crate::transform_cmds::set_budget(u64::from(self.prefs().performance.effective_memory_usage_mb()) << 20); diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 4e2bb9e926..ad40728e5b 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -94,7 +94,6 @@ pub struct PresetState { #[plain_data(assume = "craft-color-ui swatch groups: plain values and strings")] pub swatches: Vec, /// The user contour library of the Layer Style dialog (`layer.layerStyle.contours.*`). - #[plain_data(assume = "document contours: plain numbers")] pub contours: Vec, } diff --git a/crates/engine/src/presets/clone_source.rs b/crates/engine/src/presets/clone_source.rs index d7193364bc..2ba36df475 100644 --- a/crates/engine/src/presets/clone_source.rs +++ b/crates/engine/src/presets/clone_source.rs @@ -432,7 +432,7 @@ fn set(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, "document requires a source point")); } let index = value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "document must be an open document index"))?; - Some(s.documents().get(index).ok_or_else(|| bad(CMD, "the source document is not open"))?) + Some(&**s.documents().get(index).ok_or_else(|| bad(CMD, "the source document is not open"))?) } }; let (document, active_layer) = (doc.map(|st| st.doc.id), doc.and_then(|st| st.active_layer).map(|id| id.0)); diff --git a/crates/engine/src/presets/shapes.rs b/crates/engine/src/presets/shapes.rs index 42237eb3e0..7b4c99edb3 100644 --- a/crates/engine/src/presets/shapes.rs +++ b/crates/engine/src/presets/shapes.rs @@ -28,7 +28,6 @@ pub const CUSTOM_GROUP: &str = "Custom Shapes"; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ShapePreset { pub name: String, - #[plain_data(assume = "a document path: plain geometry")] pub path: Path, /// An imported library's opaque identity; old and locally drawn presets need none. #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs index 2523faa11e..e2ae82e52d 100644 --- a/crates/engine/src/presets/styles.rs +++ b/crates/engine/src/presets/styles.rs @@ -19,11 +19,9 @@ use crate::{EngineError, Result, Session}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct StylePreset { pub name: String, - #[plain_data(assume = "document effects: plain values")] pub effects: Vec, /// Blending options saved with the style ("Include Layer Blending Options"). #[serde(default)] - #[plain_data(assume = "an enum")] pub blend: Option, #[serde(default)] pub fill_opacity: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2c173d63b9..fb78e9c494 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -23,7 +23,7 @@ impl Session { Self::default() } - pub fn documents(&self) -> &[DocState] { + pub fn documents(&self) -> &[craft_tracked::Tracked] { &self.docs } @@ -37,11 +37,28 @@ impl Session { } pub fn active(&self) -> Option<&DocState> { + self.active_tracked().map(|st| &**st) + } + + /// The active document as the session tracks it, for views that key on its revision. + pub fn active_tracked(&self) -> Option<&craft_tracked::Tracked> { self.active.and_then(|i| self.docs.get(i)) } + /// The active document to change: the borrow moves its `Tracked` revision, so a caller that may write nothing + /// reads through [`Self::active`] first. pub fn active_mut(&mut self) -> Option<&mut DocState> { - self.active.and_then(|i| self.docs.get_mut(i)) + self.active.and_then(|i| self.docs.get_mut(i)).map(|st| &mut **st) + } + + /// The open document with this id as the session tracks it, active or not. + pub fn tracked(&self, id: photocraft_doc::DocId) -> Option<&craft_tracked::Tracked> { + self.docs.iter().find(|d| d.doc.id == id) + } + + /// The native save cache of the open document `id`, which its save workers share. + pub fn pcraft_cache(&self, id: photocraft_doc::DocId) -> Option<&photocraft_io::PcraftExportCache> { + self.pcraft_caches.get(&id) } /// Completes a successful save of the active document: the file becomes its path and names it, and its revision is @@ -56,7 +73,7 @@ impl Session { /// The open document with this id, active or not. pub fn document_mut(&mut self, id: photocraft_doc::DocId) -> Option<&mut DocState> { - self.docs.iter_mut().find(|d| d.doc.id == id) + self.docs.iter_mut().find(|d| d.doc.id == id).map(|st| &mut **st) } /// Monotonic active-document generation. It changes when a different document becomes @@ -208,7 +225,8 @@ impl Session { if !self.prefs.get().history_options.automatically_create_first_snapshot { st.snapshots_mut().clear(); } - self.docs.push(st); + self.pcraft_caches.insert(st.doc.id, Default::default()); + self.docs.push(craft_tracked::Tracked::new(st)); self.documents_generation = self.documents_generation.wrapping_add(1); let i = self.docs.len() - 1; self.active = Some(i); @@ -246,10 +264,13 @@ impl Session { self.subject_cache.forget_doc(id); self.object_finder.forget_doc(id); self.presets.clone.forget_doc(id); - self.link_missing.retain(|(d, _)| *d != id.0); + if self.link_missing.iter().any(|(d, _)| *d == id.0) { + self.link_missing.retain(|(d, _)| *d != id.0); + } self.link_scan = None; } - let d = self.docs.remove(index); + let d = self.docs.remove(index).into_inner(); + self.pcraft_caches.remove(&d.doc.id); self.documents_generation = self.documents_generation.wrapping_add(1); self.open_document_order.retain(|&id| id != d.doc.id); self.active = if self.docs.is_empty() { diff --git a/crates/geom/Cargo.toml b/crates/geom/Cargo.toml index 2c3541d35d..faae7413d0 100644 --- a/crates/geom/Cargo.toml +++ b/crates/geom/Cargo.toml @@ -9,3 +9,6 @@ workspace = true [dependencies] serde = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 44a078dd36..50919c0eb5 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -12,7 +12,7 @@ pub mod warp; /// Edge length of a raster tile in pixels. pub const TILE_SIZE: i32 = 256; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Size { pub width: u32, pub height: u32, @@ -31,7 +31,7 @@ impl Size { } /// Integer rectangle, half-open: `[x0, x1) × [y0, y1)`. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Rect { pub x0: i32, pub y0: i32, @@ -116,7 +116,7 @@ impl Rect { } /// Index of a tile in the infinite tile grid. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct TileCoord { pub tx: i32, pub ty: i32, @@ -136,7 +136,7 @@ impl TileCoord { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Point { pub x: f64, pub y: f64, @@ -149,7 +149,7 @@ impl Point { } /// 2D affine transform `[a c e; b d f; 0 0 1]` (column vectors). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Affine { pub m: [f64; 6], } diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index e6bf592606..8a9b9a82e0 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -20,7 +20,7 @@ use std::f64::consts::PI; use serde::{Deserialize, Serialize}; /// Warp style: none, a custom mesh, or one of Photoshop's presets (menu order). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum WarpStyle { #[default] @@ -161,7 +161,7 @@ impl WarpStyle { } /// A preset style prepared for one box: its control grid and the box it bends. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, craft_ui_macros::PlainData)] pub struct StyleWarp { /// The 4 × 4 Bezier control grid in box units (0..1, y down), row-major. grid: Grid, @@ -529,7 +529,7 @@ const BERN_INV: [[f64; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [-5.0 / 6.0, 3.0, -1.5, 1 /// `us`/`vs` are the patch boundaries in the box's normalised coordinates (`0..=1`, increasing, /// first 0 and last 1). Control points are a `(3·(us.len()-1)+1) × (3·(vs.len()-1)+1)` grid in /// row-major order, in output (document) coordinates; neighbouring patches share their edge row. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BezierMesh { pub us: Vec, pub vs: Vec, @@ -1029,7 +1029,7 @@ fn move_control_points(points: &mut [[f64; 2]], nx: usize, ny: usize, cols: usiz } /// A complete warp: what Photoshop's `warp` descriptor stores, plus the custom mesh. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct Warp { pub style: WarpStyle, diff --git a/crates/ops/Cargo.toml b/crates/ops/Cargo.toml index 7a15a111aa..6f19afa707 100644 --- a/crates/ops/Cargo.toml +++ b/crates/ops/Cargo.toml @@ -9,3 +9,6 @@ workspace = true [dependencies] photocraft-doc = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 0e647b1490..f9a10d53e5 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -22,13 +22,13 @@ mod tiles; /// bring them back with the state's document, as the reference app does. Selecting layers is not /// a step of its own, so the session updates the current state's target with /// [`History::set_current_layers`] just before recording the next step (#1356). -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui_macros::PlainData)] pub struct LayerTarget { pub active: Option, pub selected: Vec, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct HistoryState { pub label: String, pub doc: Arc, @@ -42,13 +42,13 @@ pub struct HistoryState { } /// The context in which a selected action row must remain available after it is folded away. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub enum ActionBrushSource { Current(HistoryState), Cleared(HistoryState), } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct History { /// Past states; the last one is the state *before* the current document. undo: VecDeque, @@ -96,7 +96,7 @@ pub struct History { static NEXT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); /// What [`History::rollback`] needs to take the most recent [`History::record`] back. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] struct LastRecord { visibility_capture_before: Option>>, /// The document it replaced (the state a rollback makes current again). @@ -113,7 +113,7 @@ struct LastRecord { /// The undo and redo states [`History::clear_states`] removed, and the History Brush source set /// before it. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] struct Cleared { undo: VecDeque, redo: Vec, diff --git a/crates/ops/src/tiles.rs b/crates/ops/src/tiles.rs index 64da14929e..8eab8dce95 100644 --- a/crates/ops/src/tiles.rs +++ b/crates/ops/src/tiles.rs @@ -5,7 +5,7 @@ use photocraft_doc::{Document, LayerContent, SmartSource, Surface}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, craft_ui_macros::PlainData)] pub(crate) struct Tiles { refs: HashMap, bytes: u128, diff --git a/crates/paint/src/symmetry.rs b/crates/paint/src/symmetry.rs index 6adf8a382f..54c9c5f3b9 100644 --- a/crates/paint/src/symmetry.rs +++ b/crates/paint/src/symmetry.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; pub const MAX_COORDINATE: f64 = 1_000_000.0; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "lowercase")] pub enum SymmetryMode { Vertical, @@ -29,7 +29,7 @@ impl SymmetryMode { } } -#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, craft_ui_macros::PlainData)] pub struct PresetSymmetry { pub mode: SymmetryMode, pub center: [f64; 2], diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index f319dcee81..7a8bf6ea11 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -11,6 +11,9 @@ workspace = true photocraft-geom = { workspace = true } photocraft-color = { workspace = true } serde = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } crc32fast = "1" lz4_flex = { version = "0.11", default-features = false, features = ["std", "safe-encode", "safe-decode"] } diff --git a/crates/raster/src/interrupt.rs b/crates/raster/src/interrupt.rs index 2a5521331b..745fc6607b 100644 --- a/crates/raster/src/interrupt.rs +++ b/crates/raster/src/interrupt.rs @@ -65,7 +65,7 @@ impl<'a> Interrupt<'a> { } /// Returned by an operation that stopped because its [`Interrupt`] was cancelled. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub struct Cancelled; impl std::fmt::Display for Cancelled { diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 59474e6ab5..68940781de 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -35,7 +35,7 @@ pub fn stored_tiles_bytes(tiles: u64, fmt: &PixelFormat) -> u64 { } /// A checked surface allocation could not be represented or reserved. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum AllocationError { ScratchRead(String), SizeOverflow, @@ -63,7 +63,7 @@ impl fmt::Display for AllocationError { impl std::error::Error for AllocationError {} /// Failure to prepare an interruptible row write. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum RowWriteError { Allocation(AllocationError), Cancelled(Cancelled), @@ -226,6 +226,13 @@ impl Tile { } } +// The cell moves the bytes between memory and the scratch disk behind `&self`, and the pixels stay the same: an +// eviction compresses and drops them under the write lock, a reload restores the same bytes, and only `&mut` writes +// (`bytes_mut`) change them. The exception is a scratch read error: `bytes` then returns a zero placeholder, and a +// later successful reload returns the real pixels, both through `&self`. Both transitions move +// `spill::read_error_generation`, so views that show document pixels also key on it. +impl craft_tracked::PlainData for Tile {} + impl Clone for Tile { fn clone(&self) -> Self { match self.try_bytes() { @@ -317,6 +324,10 @@ pub struct Surface { tiles: BTreeMap>, } +// `generation` names the current pixels: a read assigns the number once, and every write goes through `&mut` +// (`note_mutation`), which clears it. A shared reference can't change the pixels or which number names them. +impl craft_tracked::PlainData for Surface {} + impl Clone for Surface { fn clone(&self) -> Self { // Read first so the clone and the original share one number: they hold the same pixels. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a7ae862e55..4e61d8a721 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -71,7 +71,6 @@ impl PhotocraftApp { texture_serials: Default::default(), menu_model: None, toolbar_slots: Default::default(), - layers_tree: None, dock_model: Default::default(), move_preview: None, move_hover: None, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 651c6023d8..4716314e04 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -542,7 +542,7 @@ impl PhotocraftApp { settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless); settings.webp_quality = e.webp_quality.map(|q| q.min(100)); settings.document_path = st.path.as_deref().map(std::path::PathBuf::from); - settings.pcraft_cache = Some(st.pcraft_cache.clone()); + settings.pcraft_cache = self.session.pcraft_cache(st.doc.id).cloned(); } settings } diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 020f2b5575..2dcba65340 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -19,7 +19,7 @@ use craft::i18n::Direction; use craft::keymap::Overrides; use craft::theme::{AppDefaults, AppSizes, ComponentSet, ModeChoice, Size, SuiteChoice, ThemeId, ThemePair, resolve_sized}; use craft::theme_store::{SelectionChange, SuiteClient}; -use craft::ui::contract::Tracked; +use craft::ui::contract::{MemoProps, Tracked}; use craft::ui::dialog::DialogHost; use craft::ui::fonts::UiFonts; use craft::ui::runtime::commands::{AppCatalog, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Fired, NavCommand}; @@ -546,97 +546,106 @@ impl Framework { } } +/// One source's command states. +pub(crate) type SourceStates = Vec<(CommandRef, CommandState)>; + +/// The id a command source's states are derived under. +pub(crate) fn states_id(source: &'static str) -> egui::Id { + egui::Id::unique(("photocraft-states", source)) +} + +/// `build`'s states for `source`, derived from `facts`: the kept `Arc` while the facts are unchanged, else a new build. +/// The facts can hold only checked inputs, but nothing checks that they hold everything `build` reads: a read they +/// leave out keeps stale states, which the held-equals-fresh trial catches. +pub(crate) fn derived_states(app: &PhotocraftApp, source: &'static str, facts: &K, build: impl FnOnce() -> SourceStates) -> Arc { + craft::ui::runtime::derived::derived(app.ctx(), states_id(source), facts, build) +} + +/// The states of a source that has no command states: one shared empty list, whatever the source's name. +pub(crate) fn no_states(app: &PhotocraftApp, _name: &'static str) -> Arc { + derived_states(app, "none", &(), Vec::new) +} + +/// A source's states for the coming frame, derived under the source's name ([`states_id`]) from what they read. +pub(crate) type StatesOf = fn(&PhotocraftApp, &'static str) -> Arc; + /// One user of the framework's command sets: the states its commands show and the runner of the /// ones it fires. pub(crate) struct CommandSource { - /// The states of the source's commands for the coming frame. - states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>, - /// What `states` reads, for a source whose every input is a plain value or a revision that moves exactly when - /// the data changes: the states are computed again only when the key changes. `None`: computed every frame, - /// because what the source reads has no such revision yet. - key: Option StatesKey>, + /// The name the source's states are derived under. + pub(crate) name: &'static str, + /// The states of the source's commands. + pub(crate) states: StatesOf, /// Runs `command` when it is this source's; whether it was. run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool, } -/// Every command source, in the order [`run_command`] tries them. The theme has no entry: it has -/// no command state, and its picks run through `menus::invoke`. +/// Every command source besides the panels' ([`crate::panels::registry::PANELS`], one source each), in the order +/// [`run_command`] tries them after the panels. The theme has no entry: it has no command state, and its picks run +/// through `menus::invoke`. pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[ - CommandSource { states: crate::panels::registry::states, key: None, run: crate::panels::registry::run_fired }, - CommandSource { states: tool_states, key: Some(tool_states_key), run: run_tool }, - CommandSource { states: crate::workspace_ui::states, key: None, run: crate::workspace_ui::run_fired }, - CommandSource { states: crate::slice_ui::command_states, key: Some(crate::slice_ui::command_states_key), run: crate::slice_ui::run_fired }, - CommandSource { states: crate::align_bar::command_states, key: None, run: crate::align_bar::run_fired }, - CommandSource { states: crate::artboard_tool::command_states, key: Some(crate::artboard_tool::command_states_key), run: crate::artboard_tool::run_fired }, + CommandSource { name: "tool", states: tool_states, run: run_tool }, + CommandSource { name: "workspace", states: crate::workspace_ui::source_states, run: crate::workspace_ui::run_fired }, + CommandSource { name: "slice", states: crate::slice_ui::source_states, run: crate::slice_ui::run_fired }, + CommandSource { name: "align", states: crate::align_bar::source_states, run: crate::align_bar::run_fired }, + CommandSource { name: "artboard", states: crate::artboard_tool::source_states, run: crate::artboard_tool::run_fired }, // Space+F: the pasteboard colour keys of the held Hand. - CommandSource { states: |_| Vec::new(), key: Some(|_| StatesKey::default()), run: crate::canvas_tool_menu::run_canvas_color }, + CommandSource { name: "canvasColor", states: no_states, run: crate::canvas_tool_menu::run_canvas_color }, // The options bar's engine-command buttons: their commands run through `shortcuts::handle`. - CommandSource { states: crate::panels::options_bar::selection::command_states, key: None, run: |_, _, _| false }, + CommandSource { name: "selection", states: crate::panels::options_bar::selection::source_states, run: |_, _, _| false }, ]; -/// The key of a [`CommandSource`]'s states: the plain values and exact revisions they are computed from, so equal -/// keys mean equal states. -pub(crate) type StatesKey = [u64; 4]; +/// Every source by its name, with its states: the command sources, then the panels, each under its panel id. A later +/// source's state wins for a command two sources name. +pub(crate) fn sources() -> impl Iterator { + let panels = crate::panels::registry::PANELS.iter().map(|panel| (panel.id, panel.states)); + COMMAND_SOURCES.iter().map(|source| (source.name, source.states)).chain(panels) +} -/// The states each [`CommandSource`] last computed, by its place in [`COMMAND_SOURCES`], with their key, and the one -/// list of all of them the runtime reads. +/// Every source's states, in [`sources`]' order. +fn source_states(app: &PhotocraftApp) -> impl Iterator> + '_ { + sources().map(move |(name, states)| states(app, name)) +} + +/// The states each source last gave, in [`source_states`]' order, and the one list of all of them the runtime reads. #[derive(Default)] pub(crate) struct HeldStates { - kept: Vec>, + kept: Vec>, /// Every source's states, written only when one source's list changes: the runtime reads them again only when /// the revision moves. pub(crate) states: Tracked, - /// How many times each source computed its states, for the count trials. - #[cfg(test)] - pub(crate) runs: Vec, -} - -/// One source's states and the key they were computed at (`None` for a source without a key). -#[derive(Clone)] -struct KeptStates { - key: Option, - states: Vec<(CommandRef, CommandState)>, } /// The tool commands: the current tool's row is checked. -fn tool_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { +fn build_tool_states(app: &PhotocraftApp) -> SourceStates { Tool::ALL.iter().map(|&tool| (CommandRef::from(crate::panels::tool_commands::command_of(tool)), CommandState::new().checked(app.ui.tool == tool))).collect() } -/// What [`tool_states`] reads: the tool. -fn tool_states_key(app: &PhotocraftApp) -> StatesKey { - [app.ui.tool as u64, 0, 0, 0] +/// [`build_tool_states`], derived from the tool. +fn tool_states(app: &PhotocraftApp, name: &'static str) -> Arc { + derived_states(app, name, &(app.ui.tool as u64), || build_tool_states(app)) } -/// Brings the held states up to date for the coming frame. A keyed source runs only when its key changed since it last -/// ran; a source without a key runs every frame. The held list is written only when a source's states differ from the -/// ones it last gave. +/// Brings the held states up to date for the coming frame. A source whose states are the `Arc` it last gave costs a +/// pointer compare; the held list is written only when a source's states differ by value from the ones it last gave. fn command_states(app: &PhotocraftApp, held: &mut HeldStates) { - held.kept.resize(COMMAND_SOURCES.len(), None); - #[cfg(test)] - held.runs.resize(COMMAND_SOURCES.len(), 0); let mut changed = false; - for (at, source) in COMMAND_SOURCES.iter().enumerate() { - let key = source.key.map(|key| key(app)); - if key.is_some() && held.kept[at].as_ref().is_some_and(|kept| kept.key == key) { - continue; - } - #[cfg(test)] - { - held.runs[at] += 1; - } - let states = (source.states)(app); - match &mut held.kept[at] { - Some(kept) if kept.states == states => kept.key = key, - slot => { - *slot = Some(KeptStates { key, states }); + for (at, states) in source_states(app).enumerate() { + match held.kept.get_mut(at) { + Some(kept) if Arc::ptr_eq(kept, &states) => {} + Some(kept) => { + changed |= **kept != *states; + *kept = states; + } + None => { + held.kept.push(states); changed = true; } } } if changed { let mut states = CommandStates::new(); - for (command, state) in held.kept.iter().flatten().flat_map(|kept| &kept.states) { + for (command, state) in held.kept.iter().flat_map(|kept| kept.iter()) { states.set(command.clone(), state.clone()); } *held.states = states; @@ -655,9 +664,9 @@ fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) true } -/// Runs `command` through the first source that owns it; whether one did. +/// Runs `command` through the first source that owns it, the panels first; whether one did. pub(crate) fn run_command(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { - COMMAND_SOURCES.iter().any(|source| (source.run)(app, ctx, command)) + crate::panels::registry::run_fired(app, ctx, command) || COMMAND_SOURCES.iter().any(|source| (source.run)(app, ctx, command)) } impl PhotocraftApp { diff --git a/crates/ui-egui/src/app/framework/catalog_tests.rs b/crates/ui-egui/src/app/framework/catalog_tests.rs index 7c5ed7e939..7599ab9c1d 100644 --- a/crates/ui-egui/src/app/framework/catalog_tests.rs +++ b/crates/ui-egui/src/app/framework/catalog_tests.rs @@ -1,18 +1,12 @@ -//! Count trials: the command catalog, the keymap overrides and the keyed command states are built only when what -//! they read changes. +//! Count trials: the command catalog and the keymap overrides are built only when what they read changes. use craft::automation::actions::ActionStep; use serde_json::json; -use super::{COMMAND_SOURCES, PhotocraftApp}; +use super::PhotocraftApp; use crate::canvas::testing; use crate::state::Tool; -/// The places of the keyed sources in [`COMMAND_SOURCES`]. -const TOOL_SOURCE: usize = 1; -const SLICE_SOURCE: usize = 3; -const ARTBOARD_SOURCE: usize = 5; - fn app() -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); testing::frame(&mut app); @@ -24,22 +18,6 @@ fn builds(app: &PhotocraftApp) -> (usize, usize) { (app.framework.catalog_builds, app.framework.overrides_builds) } -/// How many times each keyed command source computed its states, by its place in [`COMMAND_SOURCES`]; `None` for a -/// source that computes them every frame. -fn keyed_runs(app: &PhotocraftApp) -> Vec> { - COMMAND_SOURCES.iter().zip(&app.framework.held_states.runs).map(|(source, &runs)| source.key.map(|_| runs)).collect() -} - -/// The revision of the states the runtime reads. -fn held_revision(app: &PhotocraftApp) -> craft::ui::contract::Revision { - app.framework.held_states.states.revision() -} - -/// The keyed sources that computed their states between `before` and `after`. -fn ran(before: &[Option], after: &[Option]) -> Vec { - before.iter().zip(after).enumerate().filter(|(_, (was, now))| was.is_some() && was != now).map(|(at, _)| at).collect() -} - fn frames(app: &mut PhotocraftApp, n: usize) { for _ in 0..n { testing::frame(app); @@ -91,51 +69,3 @@ fn the_catalog_is_built_only_when_its_inputs_change() { assert_eq!(builds(&app), (2, 3), "a step edit builds nothing"); assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog keeps its generation"); } - -#[test] -fn keyed_command_states_run_only_when_their_key_changes() { - let mut app = app(); - assert_eq!((COMMAND_SOURCES[TOOL_SOURCE].states)(&app).len(), Tool::ALL.len(), "TOOL_SOURCE names the tool commands"); - let before = keyed_runs(&app); - assert!(before.iter().flatten().all(|&runs| runs == 1), "the first frame computes every keyed source once"); - - let revision = held_revision(&app); - frames(&mut app, 100); - assert_eq!(keyed_runs(&app), before, "idle frames compute no keyed source"); - assert_eq!(held_revision(&app), revision, "idle frames write no states"); - - let other = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; - crate::tool_memory::select(&mut app, other); - frames(&mut app, 2); - assert_ne!(held_revision(&app), revision, "a tool change writes the states"); - let revision = held_revision(&app); - frames(&mut app, 10); - assert_eq!(held_revision(&app), revision, "the frames after the tool change write no states"); - let after = keyed_runs(&app); - for (at, (was, now)) in before.iter().zip(&after).enumerate() { - let moved = usize::from(at == TOOL_SOURCE); - assert_eq!(now.map(|n| n - was.unwrap_or_default()), was.map(|_| moved), "source {at} after a tool change"); - } - - let before = keyed_runs(&app); - app.ui.artboard_tool.adding = true; - frames(&mut app, 2); - assert_eq!(ran(&before, &keyed_runs(&app)), [ARTBOARD_SOURCE], "the placing mode"); - - let before = keyed_runs(&app); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - frames(&mut app, 2); - let after = keyed_runs(&app); - assert!(ran(&before, &after).contains(&SLICE_SOURCE) && ran(&before, &after).contains(&ARTBOARD_SOURCE), "a document opens"); - let has_doc = |app: &PhotocraftApp| (COMMAND_SOURCES[ARTBOARD_SOURCE].states)(app)[0].1.is_enabled(); - assert!(has_doc(&app)); - - let before = keyed_runs(&app); - app.ui.slices.selected = Some(1); - frames(&mut app, 2); - let selected = keyed_runs(&app); - assert_eq!(ran(&before, &selected), [SLICE_SOURCE], "the selected slice"); - app.session.file_menu.slices_locked = true; - frames(&mut app, 2); - assert_eq!(ran(&selected, &keyed_runs(&app)), [SLICE_SOURCE], "the slice lock"); -} diff --git a/crates/ui-egui/src/app/targets.rs b/crates/ui-egui/src/app/targets.rs index e642ddb7dd..51fac77346 100644 --- a/crates/ui-egui/src/app/targets.rs +++ b/crates/ui-egui/src/app/targets.rs @@ -129,10 +129,14 @@ impl PhotocraftApp { /// menu commands and the engine all edit the mask. A view change only: no command, no step. pub(crate) fn target_mask_over_colour_rows(&mut self) { use photocraft_engine::channel_cmds::ChannelTarget; - let Some(st) = self.session.active_mut() else { return }; + let Some(st) = self.session.active() else { return }; let raster_with_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some() && matches!(l.content, photocraft_doc::LayerContent::Raster(_))); - if matches!(st.channel_view.target, ChannelTarget::Color(_)) && photocraft_engine::mask_view_cmds::current(st).is_none() && raster_with_mask { + if matches!(st.channel_view.target, ChannelTarget::Color(_)) + && photocraft_engine::mask_view_cmds::current(st).is_none() + && raster_with_mask + && let Some(st) = self.session.active_mut() + { let v = &mut st.channel_view; v.target = ChannelTarget::LayerMask; v.selected_colors.clear(); @@ -144,7 +148,10 @@ impl PhotocraftApp { /// active layer (a shape layer's path is its content, not a mask). Targeting a mask or the /// pixels brings back that target's foreground/background pair, as in Photoshop (#2166). pub(crate) fn sync_mask_targets(&mut self) { - if let Some(st) = self.session.active_mut() { + // Read through `active`, and borrow the document to change only for the one write below: the borrow moves its + // `Tracked` revision, and this runs after every command and control request. + let mut untarget_mask = false; + if let Some(st) = self.session.active() { use photocraft_engine::channel_cmds::ChannelTarget; let channel = st.channel_view.target; match photocraft_engine::mask_view_cmds::current(st) { @@ -177,13 +184,14 @@ impl PhotocraftApp { if self.ui.mask_target && st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) { self.ui.mask_target = false; } - if !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask { - st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; - } + untarget_mask = !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask; if !self.ui.mask_target || self.ui.properties_layer != st.active_layer.map(|l| l.0) { self.ui.properties_layer = None; } } + if untarget_mask && let Some(st) = self.session.active_mut() { + st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; + } if self.ui.filter_mask_target.is_some() && !self.filter_mask_targeted() { self.ui.filter_mask_target = None; } diff --git a/crates/ui-egui/src/command_state_trials.rs b/crates/ui-egui/src/command_state_trials.rs new file mode 100644 index 0000000000..1d0c0d81f0 --- /dev/null +++ b/crates/ui-egui/src/command_state_trials.rs @@ -0,0 +1,147 @@ +//! Count trials for the command states the runtime reads (#15709): every source's states are a value derived from +//! what they read, so an idle frame builds none, an edit builds only the sources that read what it changed, and the +//! held states always equal a fresh build of every source. + +use craft::behavior::geometry::CropBox; +use craft::behavior::kurbo::Rect as DocRect; +use craft::ui::runtime::commands::{CommandRef, CommandStates}; +use craft::ui::runtime::measure::last_frame_derived_builds; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::app::framework::{sources, states_id}; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +/// The sources whose states follow the enable rules, which read the document, the session and the tool. +pub(crate) const RULES: [&str; 5] = ["align", "selection", "history", "layers", "channels"]; + +/// The app with one new document holding a pixel layer, settled. +fn harness() -> H { + harness_of(|s| { + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + }) +} + +/// The app with the session `open` makes, the Brush tool picked, settled. +fn harness_of(open: impl FnOnce(&mut photocraft_engine::Session) + 'static) -> H { + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut s = photocraft_engine::Session::new(); + open(&mut s); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), s, crate::Services::default()); + app.ui.tool = Tool::Brush; + app + }); + h.run_steps(8); + h +} + +/// The sources the last frame built states for, in the framework's order. +fn built(h: &H) -> Vec<&'static str> { + let builds = last_frame_derived_builds(&h.ctx); + sources().map(|(name, _)| name).filter(|name| builds.iter().any(|(id, _)| *id == states_id(name))).collect() +} + +/// Runs one frame after `change` and checks which sources it built. +fn builds_only(h: &mut H, what: &str, change: impl FnOnce(&mut PhotocraftApp), expected: &[&str]) { + h.run_steps(2); + change(h.state_mut()); + h.run_steps(1); + let mut expected = expected.to_vec(); + expected.sort_by_key(|source| sources().position(|(name, _)| name == *source)); + assert_eq!(built(h), expected, "{what} builds only the sources that read it"); +} + +#[test] +fn an_idle_frame_builds_no_command_states() { + let mut h = harness(); + for frame in 0..10 { + h.run_steps(1); + assert_eq!(built(&h), Vec::<&str>::new(), "idle frame {frame} builds no source"); + } +} + +#[test] +fn an_edit_builds_only_the_sources_that_read_it() { + let mut h = harness(); + builds_only( + &mut h, + "the brush texture", + |app| { + let on = app.session.tools.brush.texture.enabled; + app.session.tools.brush.texture.enabled = !on; + }, + &["brushSettings"], + ); + builds_only(&mut h, "a tool", |app| crate::tool_memory::select(app, Tool::Hand), &[&["tool"][..], &RULES].concat()); + builds_only(&mut h, "the artboard placing mode", |app| app.ui.artboard_tool.adding = true, &["artboard"]); + builds_only(&mut h, "the selected slice", |app| app.ui.slices.selected = Some(1), &["slice"]); + // View › Lock Slices reads the lock, so the rule-holding sources build with the slice states. + builds_only(&mut h, "the slice lock", |app| app.session.file_menu.slices_locked = true, &[&["slice"][..], &RULES].concat()); + builds_only( + &mut h, + "a new layer", + |app| { + app.run("layer.new.layer", json!({})).unwrap(); + }, + &[&["slice"][..], &RULES].concat(), + ); +} + +#[test] +fn a_document_opening_builds_the_slice_and_artboard_states() { + let mut h = harness_of(|_| {}); + h.run_steps(2); + h.state_mut().run("file.new", json!({"width": 64, "height": 64})).unwrap(); + h.run_steps(1); + let built = built(&h); + assert!(built.contains(&"slice") && built.contains(&"artboard"), "a document opens: {built:?}"); + let add_new = CommandRef::from(craft::draw::ui::artboard::ArtboardCommand::AddNew); + let artboard = h.state().framework.held_states.states.get(&add_new).cloned(); + assert!(artboard.is_some_and(|state| state.is_enabled()), "Add New Artboard is on with a document"); +} + +/// Checks that every held state is the one its source builds afresh: the sources are asked again through a new context, +/// whose derived store is empty, so each builds from the app's state as it is now. +fn held_is_fresh(h: &mut H, step: &str) { + h.run_steps(2); + let app = h.state_mut(); + let fresh = egui::Context::default(); + PhotocraftApp::setup_context(&fresh, Default::default()); + let own = std::mem::replace(&mut app.ctx, fresh); + let built: Vec<_> = sources().map(|(name, states)| (name, states(app, name))).collect(); + app.ctx = own; + let mut held = (*app.framework.held_states.states).clone(); + for (name, states) in built { + for (command, state) in states.iter() { + assert!(held.remove(command).as_ref() == Some(state), "after {step}, the {name} state of {command:?} is a fresh build"); + } + } + assert!(held == CommandStates::new(), "after {step}, every held state has a source"); +} + +#[test] +fn the_held_command_states_equal_a_fresh_build_after_each_step() { + let mut h = harness(); + held_is_fresh(&mut h, "settling"); + crate::tool_memory::select(h.state_mut(), Tool::Move); + held_is_fresh(&mut h, "a tool"); + h.state_mut().session.tools.brush.texture.enabled = true; + held_is_fresh(&mut h, "the brush texture"); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + held_is_fresh(&mut h, "a new layer"); + h.state_mut().run("layer.layerMask.revealAll", json!({})).unwrap(); + h.state_mut().ui.mask_target = true; + held_is_fresh(&mut h, "a mask target"); + crate::workspace_ui::save(h.state_mut(), "Trial").unwrap(); + held_is_fresh(&mut h, "a new workspace"); + crate::tool_memory::select(h.state_mut(), Tool::Crop); + h.run_steps(2); + h.state_mut().canvas_tools.crop.tool.crop_to(CropBox::new(DocRect::new(10.0, 10.0, 100.0, 60.0), 0.0)); + held_is_fresh(&mut h, "a pending crop"); + assert!(crate::crop_ui::pending(h.state()), "the crop is pending"); +} diff --git a/crates/ui-egui/src/doc_revision_trials.rs b/crates/ui-egui/src/doc_revision_trials.rs index 8dd27fd436..2ffdbaf5d5 100644 --- a/crates/ui-egui/src/doc_revision_trials.rs +++ b/crates/ui-egui/src/doc_revision_trials.rs @@ -4,6 +4,7 @@ use craft::layers::ui::thumbs::{LayerThumb, ThumbContents}; use craft::ui::primitives::textures::{ThumbRequest, ThumbSource}; +use craft::ui::runtime::measure::last_frame_derived_builds; use egui_kittest::Harness; use photocraft_doc::{Fill, Layer, LayerContent, LayerId, PixelFormat}; use photocraft_engine::Session; @@ -96,8 +97,8 @@ fn thumbnail_revisions_follow_only_their_own_layer() { ); } -/// The Layers panel walks its rows again only when their revision moves: a rename and both disclosure toggles (a -/// layer's effects list, a group) move it, idle frames don't. +/// The Layers panel's model is built again only when what its rows show changed: a rename and both disclosure toggles +/// (a layer's effects list, a group) build it once, idle frames don't. #[test] fn layers_rows_follow_renames_and_both_toggles() { let mut s = Session::new(); @@ -112,19 +113,20 @@ fn layers_rows_follow_renames_and_both_toggles() { }) .unwrap(); let mut h = harness(s); - // The panel's model, which the app holds across passes and replaces only when what the rows show changed. - let revision = |h: &H| h.state().layers_tree.as_ref().map(|model| model.revision()); + let builds = |h: &H| { + let id = crate::panels::layers_tree::model_id(); + last_frame_derived_builds(&h.ctx).iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum::() + }; h.run_steps(2); - let start = revision(&h); - assert!(start.is_some()); - h.run_steps(10); - assert_eq!(revision(&h), start, "idle frames keep the rows"); + for frame in 0..10 { + h.run_steps(1); + assert_eq!(builds(&h), 0, "idle frame {frame} keeps the rows"); + } let moves = |h: &mut H, command: &str, params: serde_json::Value| { - let before = revision(h); h.state_mut().run(command, params).unwrap(); - h.run_steps(2); - assert_ne!(revision(h), before, "{command} moves the rows' revision"); + h.run_steps(1); + assert_eq!(builds(h), 1, "{command} builds the rows once"); }; moves(&mut h, "layer.renameLayer", json!({"layer": a.0, "name": "Renamed"})); moves(&mut h, "layer.setEffectsExpanded", json!({"layer": a.0, "expanded": false})); diff --git a/crates/ui-egui/src/doc_tracked_trials.rs b/crates/ui-egui/src/doc_tracked_trials.rs new file mode 100644 index 0000000000..9e18d08c79 --- /dev/null +++ b/crates/ui-egui/src/doc_tracked_trials.rs @@ -0,0 +1,170 @@ +//! Count trials for the documents the session holds in a `Tracked` (#15709): a job that applies to a document in the +//! background moves only that document's revision and builds nothing keyed on the active one, an idle frame and a +//! preference write that keeps the history limits move no document's revision, and a view-only write that leaves the +//! edit revision alone still moves the tracked one and rebuilds what shows it. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use craft::ui::runtime::measure::last_frame_derived_builds; +use egui_kittest::Harness; +use photocraft_engine::channel_cmds::ChannelTarget; +use photocraft_engine::jobs::Started; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::app::framework::states_id; + +type H = Harness<'static, Box>; + +/// The app with two new documents, A (index 0) and B (index 1), each with a pixel layer, B active, settled. +fn harness() -> H { + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut s = photocraft_engine::Session::new(); + for _ in 0..2 { + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + } + PhotocraftApp::with_context(cc.egui_ctx.clone(), s, crate::Services::default()) + }); + h.run_steps(8); + h +} + +/// How many times `builds` built the value derived under `id`. +fn count(builds: &[(egui::Id, u32)], id: egui::Id) -> u32 { + builds.iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum() +} + +/// How many times the last frame built the value derived under `id`. +fn builds(h: &H, id: egui::Id) -> u32 { + count(&last_frame_derived_builds(&h.ctx), id) +} + +/// Runs `frames` frames and gives every build they made, frame after frame. +fn builds_over(h: &mut H, frames: usize) -> Vec<(egui::Id, u32)> { + let mut all = Vec::new(); + for _ in 0..frames { + h.run_steps(1); + all.extend(last_frame_derived_builds(&h.ctx)); + } + all +} + +/// The command sources that hold the active document. +const DOCUMENT_SOURCES: [&str; 6] = ["slice", "align", "selection", "history", "layers", "channels"]; + +/// Every open document's `Tracked` revision. +fn revisions(h: &H) -> Vec { + h.state().session.documents().iter().map(|st| st.revision()).collect() +} + +#[test] +fn a_job_on_another_document_builds_nothing_keyed_on_the_active_one() { + let mut h = harness(); + // A filter job on A, held until B is the active document. + h.state_mut().session.set_active(0); + let gate = Arc::new(AtomicBool::new(false)); + let open = Arc::clone(&gate); + let started = h + .state_mut() + .session + .start_job( + "filter.blur.gaussianBlur", + json!({"radius": 2}), + "Deferred Blur", + true, + move |job| { + while !open.load(Ordering::Relaxed) { + job.check()?; + std::thread::sleep(std::time::Duration::from_millis(1)); + } + Ok(()) + }, + |s, ()| { + s.edit("Deferred Blur", |doc, active| { + let layer = active.ok_or_else(|| photocraft_engine::EngineError::Other("no active layer".into()))?; + let surface = doc.layer_mut(layer).and_then(|l| l.surface_mut()).ok_or(photocraft_engine::EngineError::NoLayer(layer))?; + surface.fill_rect(photocraft_geom::Rect::new(0, 0, 1, 1), &[0.4, 0.3, 0.2, 1.0]); + Ok(()) + })?; + Ok(json!({})) + }, + ) + .unwrap(); + let Started::Job(job) = started else { panic!("the job ran inline") }; + h.state_mut().session.set_active(1); + h.run_steps(4); + + let before = revisions(&h); + gate.store(true, Ordering::Relaxed); + h.state_mut().session.wait_job(job).unwrap(); + // Builds are summed over a few frames, so one a frame late counts too. + let job_frames = builds_over(&mut h, 4); + let after = revisions(&h); + assert_ne!(after[0], before[0], "the job's apply moves A's revision"); + assert_eq!(after[1], before[1], "and leaves B's"); + assert_eq!(count(&job_frames, crate::panels::layers_tree::model_id()), 0, "B's Layers model builds nothing"); + assert_eq!(count(&job_frames, states_id("slice")), 0, "B's slice states build nothing"); + // The job's end and Edit › Fade's document are rule inputs: the menu model and each rule-holding source build once. + assert_eq!(count(&job_frames, crate::menus::model_id()), 1, "the job's apply and end build the menu model once"); + for source in crate::command_state_trials::RULES { + assert_eq!(count(&job_frames, states_id(source)), 1, "the job's apply and end build the {source} states once"); + } + let idle = builds_over(&mut h, 4); + assert_eq!(count(&idle, crate::menus::model_id()), 0, "the frames after the job build no menu model"); + assert_eq!(count(&idle, crate::panels::layers_tree::model_id()), 0, "the frames after the job build no Layers model"); + for (name, _) in crate::app::framework::sources() { + assert_eq!(count(&idle, states_id(name)), 0, "the frames after the job build no {name} states"); + } + + h.state_mut().session.set_active(0); + h.run_steps(1); + assert_eq!(builds(&h, crate::panels::layers_tree::model_id()), 1, "switching to A builds its Layers model once"); + for source in DOCUMENT_SOURCES { + assert_eq!(builds(&h, states_id(source)), 1, "switching to A builds the {source} states once"); + } +} + +#[test] +fn an_idle_frame_moves_no_documents_revision() { + let mut h = harness(); + h.state_mut().run("window.toggle.history", json!({"show": true})).unwrap(); + h.state_mut().run("window.toggle.navigator", json!({"show": true})).unwrap(); + h.run_steps(8); + let settled = revisions(&h); + for frame in 0..10 { + h.run_steps(1); + assert_eq!(revisions(&h), settled, "idle frame {frame} moves no document's revision"); + } +} + +#[test] +fn a_preference_write_that_keeps_the_history_limits_moves_no_documents_revision() { + let mut h = harness(); + let settled = revisions(&h); + let on = h.state().session.prefs().script_events.enabled; + h.state_mut().session.edit_prefs(|prefs| prefs.script_events.enabled = !on); + assert_eq!(revisions(&h), settled, "a preference write that keeps the history limits moves no document's revision"); + let states = h.state().session.prefs().performance.history_states; + h.state_mut().session.edit_prefs(|prefs| prefs.performance.history_states = states + 1); + assert!(revisions(&h).iter().zip(&settled).all(|(now, was)| now != was), "a new history limit moves every document's revision"); +} + +#[test] +fn targeting_a_mask_over_colour_rows_rebuilds_the_channels_states() { + let mut h = harness(); + h.state_mut().run("layer.layerMask.revealAll", json!({})).unwrap(); + h.state_mut().session.active_mut().unwrap().channel_view.target = ChannelTarget::Color(0); + h.run_steps(4); + let st = h.state().session.active_tracked().unwrap(); + let (edits, tracked) = (st.revision, st.revision()); + h.state_mut().target_mask_over_colour_rows(); + let st = h.state().session.active_tracked().unwrap(); + assert_eq!(st.channel_view.target, ChannelTarget::LayerMask, "the mask is the target"); + assert_eq!(st.revision, edits, "a view change is no edit step"); + assert_ne!(st.revision(), tracked, "but it moves the tracked revision views key on"); + h.run_steps(1); + assert_eq!(builds(&h, states_id("channels")), 1, "the Channels states follow it"); +} diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 9518515318..dc64309867 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -132,7 +132,7 @@ fn lock(cache: &Mutex) -> MutexGuard<'_, ThumbnailCache> { /// The recent files' thumbnail source for one pass: the open documents (their live pictures), the shared version /// cache and whether the window gained focus this pass. pub(crate) struct RecentThumbs<'a> { - docs: &'a [photocraft_engine::DocState], + docs: &'a [craft::ui::contract::Tracked], cache: &'a Mutex, ctx: egui::Context, focus_gained: bool, @@ -154,7 +154,7 @@ pub(crate) fn thumbnails(ctx: &egui::Context) -> Thumbnails { impl RecentThumbs<'_> { /// The open document whose path is `path`. fn open_doc(&self, path: &str) -> Option<&photocraft_engine::DocState> { - self.docs.iter().find(|d| d.path.as_deref().is_some_and(|p| paths_match(p, path))) + self.docs.iter().find(|d| d.path.as_deref().is_some_and(|p| paths_match(p, path))).map(|st| &**st) } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d5dd2fe885..5f849c8e9d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -358,8 +358,6 @@ pub struct PhotocraftApp { pub(crate) menu_model: Option, /// The toolbar's slots for the stored layout (`tool_commands::ToolbarSlots`). pub(crate) toolbar_slots: panels::tool_commands::ToolbarSlots, - /// The Layers panel's model, held across passes (`layers_tree::PhotoLayers::held`). - pub(crate) layers_tree: Option>, /// The dock's spec model and kept panels (`panel_docking::DockModel`). pub(crate) dock_model: panels::panel_docking::DockModel, /// Move tool drag shown live (`move_ui`). @@ -950,8 +948,12 @@ mod brush_settle_trials; #[cfg(test)] mod chrome_settle_trials; #[cfg(test)] +mod command_state_trials; +#[cfg(test)] mod doc_revision_trials; #[cfg(test)] +mod doc_tracked_trials; +#[cfg(test)] mod drag_settle_trials; #[cfg(test)] mod layer_thumb_bounds_tests; diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index 87dde76f10..936d742d50 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use craft::ui::contract::{MemoProps, Revision, Tracked}; use photocraft_doc::DocId; +use photocraft_engine::DocState; use crate::PhotocraftApp; @@ -18,10 +19,19 @@ pub(crate) struct MenuFacts<'a> { language: &'static str, /// The keymap's overrides and catalog generations: the rows show its chords. keymap: (u64, u64), + rules: RuleFacts<'a>, + prefs: PrefFacts<'a>, + shown: ShownFacts<'a>, +} + +/// What the enable rules read ([`super::is_enabled`], `Session::is_enabled`): the documents, the session and the shell +/// state they ask about. A command source whose states follow the rules holds these; the menu model holds them with +/// what its rows show. +#[derive(MemoProps)] +pub(crate) struct RuleFacts<'a> { documents: Documents<'a>, session: SessionFacts, - prefs: PrefFacts<'a>, - ui: UiFacts<'a>, + ui: UiRuleFacts<'a>, } /// The open documents and the active one. @@ -31,10 +41,9 @@ struct Documents<'a> { generation: u64, active_generation: u64, active_index: Option, - /// The active document and its revision, which moves with every change to it: its content, layers, selection, - /// history, mode and mask state, which most rules read. - #[memo_props(hash = "a plain model id")] - active: Option<(DocId, u64)>, + /// The active document, by its `Tracked` revision, which moves with every change to it: its content, layers, + /// selection, history, mode, mask and view state, which most rules read. + active: Option<&'a Tracked>, /// A running job greys the commands that would change its document. jobs: (bool, Option), /// Smart Objects › Edit Contents' parent: whether the active document is a smart object's contents. @@ -65,6 +74,8 @@ struct SessionFacts { actions: (u64, Option<(usize, usize)>, u8), /// Edit › Undo's label when it undoes an Actions library change. undo_label: Option<&'static str>, + /// The installed plug-ins' revision: a plug-in's menu item needs it installed. + plugins: u64, } /// The preferences the rows show. @@ -81,9 +92,9 @@ struct PrefFacts<'a> { favorite_themes: &'a Vec, } -/// The shell's state the rows show. +/// The shell's state the rules read. #[derive(MemoProps)] -struct UiFacts<'a> { +struct UiRuleFacts<'a> { tool: u64, /// The open Free Transform: its undo steps' and phase's revision, Content-Aware Scale, its layer count and a /// running commit. @@ -101,6 +112,19 @@ struct UiFacts<'a> { /// a brush resize. modal: (usize, bool, Option<&'static str>, bool, bool), selected_guide: bool, + /// Save, Paste and Place Embedded ask which services this platform has: export, the clipboard image and files. + services: (bool, bool, bool), + /// The locked workspace greys the panel commands that move, float or close panels. + workspaces_locked: bool, + /// Window › Arrange: the docked and floating document windows. + document_windows: (usize, usize), + /// File › Automate › Batch: an action is selected in the Actions panel. + batch_action: bool, +} + +/// The shell's state the rows show beside the rules: ticks, labels and the lists they name. +#[derive(MemoProps)] +struct ShownFacts<'a> { extras: crate::state::Extras, view: &'a crate::view_cmds::ViewOptions, /// The options, status, menu and contextual task bars. @@ -113,25 +137,55 @@ struct UiFacts<'a> { ticks: Arc>, recent_files: &'a Tracked>, workspaces: &'a Tracked, - /// Save and Paste rules ask which services this platform has. - services: (bool, bool), } impl<'a> MenuFacts<'a> { /// The facts of `app`'s current state. pub(crate) fn of(app: &'a PhotocraftApp) -> MenuFacts<'a> { - let s = &app.session; - let active = s.active(); - let prefs = s.prefs(); + let prefs = app.session.prefs(); let ui = &app.ui; MenuFacts { language: crate::i18n::current().code(), keymap: app.framework.keymap_inputs(), + rules: RuleFacts::of(app), + prefs: PrefFacts { + language: &prefs.interface.language, + hidden: &prefs.menus.hidden, + colors: &prefs.menus.colors, + show_menu_colors: prefs.interface.show_menu_colors, + quick_export: prefs.export.quick_export_format.name(), + font_preview: prefs.type_.font_preview.name(), + generator: prefs.plug_ins.generator_enabled, + appearance: prefs.interface.appearance_mode.name(), + favorite_themes: &prefs.interface.favorite_themes, + }, + shown: ShownFacts { + extras: ui.extras, + view: &ui.view, + bars: (ui.panels.options_bar, ui.panels.status_bar, ui.panels.menu_bar, ui.panels.context_task_bar), + palette: ui.palette.open, + theme: (ui.theme.id().as_str(), ui.theme.is_dark()), + arrangement: ui.document_windows.arrangement, + ticks: window_ticks(app), + recent_files: &ui.recent_files, + workspaces: &app.workspaces, + }, + } + } +} + +impl<'a> RuleFacts<'a> { + /// What the rules read in `app`'s current state. + pub(crate) fn of(app: &'a PhotocraftApp) -> RuleFacts<'a> { + let s = &app.session; + let active = s.active(); + let ui = &app.ui; + RuleFacts { documents: Documents { generation: s.documents_generation(), active_generation: s.active_generation(), active_index: s.active_index(), - active: active.map(|d| (d.doc.id, d.revision)), + active: s.active_tracked(), jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)), smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)), fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)), @@ -150,19 +204,9 @@ impl<'a> MenuFacts<'a> { mask_targeted: s.tools.mask_targeted, actions: (s.actions.list.revision(), s.actions.recording, s.actions.playing), undo_label: crate::actions::library::edit_undo_label(app), + plugins: photocraft_plugins::registry::revision(), }, - prefs: PrefFacts { - language: &prefs.interface.language, - hidden: &prefs.menus.hidden, - colors: &prefs.menus.colors, - show_menu_colors: prefs.interface.show_menu_colors, - quick_export: prefs.export.quick_export_format.name(), - font_preview: prefs.type_.font_preview.name(), - generator: prefs.plug_ins.generator_enabled, - appearance: prefs.interface.appearance_mode.name(), - favorite_themes: &prefs.interface.favorite_themes, - }, - ui: UiFacts { + ui: UiRuleFacts { tool: ui.tool as u64, transform: ui .transform @@ -181,16 +225,10 @@ impl<'a> MenuFacts<'a> { app.brush_resize.active(), ), selected_guide: crate::guide_select::selected(app).is_some(), - extras: ui.extras, - view: &ui.view, - bars: (ui.panels.options_bar, ui.panels.status_bar, ui.panels.menu_bar, ui.panels.context_task_bar), - palette: ui.palette.open, - theme: (ui.theme.id().as_str(), ui.theme.is_dark()), - arrangement: ui.document_windows.arrangement, - ticks: window_ticks(app), - recent_files: &ui.recent_files, - workspaces: &app.workspaces, - services: (app.services.export.is_some(), app.services.clipboard_get_image.is_some()), + services: (app.services.export.is_some(), app.services.clipboard_get_image.is_some(), app.services.files.is_some()), + workspaces_locked: app.workspaces.set.locked, + document_windows: (ui.document_windows.docked.len(), ui.document_windows.floating.len()), + batch_action: crate::actions::selected_action(app).is_some(), }, } } diff --git a/crates/ui-egui/src/menus/workspace_ui.rs b/crates/ui-egui/src/menus/workspace_ui.rs index 56b31618b6..80ae255718 100644 --- a/crates/ui-egui/src/menus/workspace_ui.rs +++ b/crates/ui-egui/src/menus/workspace_ui.rs @@ -321,6 +321,11 @@ pub fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { workspace_states(&app.workspaces.set).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect() } +/// [`states`], derived from the workspaces. +pub fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &app.workspaces, || states(app)) +} + // --------------------------------------------------------------------------------------------------------------- // Menu commands. // --------------------------------------------------------------------------------------------------------------- diff --git a/crates/ui-egui/src/panels/actions/menu.rs b/crates/ui-egui/src/panels/actions/menu.rs index 64d33fcb4c..6961d913f7 100644 --- a/crates/ui-egui/src/panels/actions/menu.rs +++ b/crates/ui-egui/src/panels/actions/menu.rs @@ -52,6 +52,31 @@ pub(crate) fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { .collect() } +/// What [`states`] reads: the list, the menu's facts and the panel's state. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + list: u64, + recording: bool, + path_selected: bool, + waiting: bool, + tool_recording: bool, + panel: &'a craft::automation::ui::actions::ActionsPanelState, +} + +/// [`states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let menu = facts(app); + let facts = StatesFacts { + list: app.session.actions.list.revision(), + recording: menu.recording, + path_selected: menu.path_selected, + waiting: menu.waiting, + tool_recording: menu.tool_recording, + panel: &app.ui.actions.panel, + }; + crate::app::framework::derived_states(app, name, &facts, || states(app)) +} + /// Runs a fired command of the Actions panel; `false` for a command of another set. Its event goes through the one /// mapping that every Actions event takes. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/panels/brush_panel.rs b/crates/ui-egui/src/panels/brush_panel.rs index f90d1e1531..d5213c150e 100644 --- a/crates/ui-egui/src/panels/brush_panel.rs +++ b/crates/ui-egui/src/panels/brush_panel.rs @@ -224,6 +224,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta ] } +/// [`command_states`], derived from the brush. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &app.session.tools.brush, || command_states(app)) +} + /// Runs a fired menu command; false for a command this panel does not own. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = BrushSettingsCommand::from_ref(command) else { return false }; diff --git a/crates/ui-egui/src/panels/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs index 284940c03c..2d4dc86584 100644 --- a/crates/ui-egui/src/panels/channels_panel.rs +++ b/crates/ui-egui/src/panels/channels_panel.rs @@ -460,6 +460,19 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } +/// What [`command_states`] reads: the rules (the active document and its channel view among them) and the mask target. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + rules: crate::menus::facts::RuleFacts<'a>, + mask_target: bool, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { rules: crate::menus::facts::RuleFacts::of(app), mask_target: app.ui.mask_target }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs a fired command of the Channels set; false for another set's command. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = ChannelsCommands::from_ref(command) else { return false }; diff --git a/crates/ui-egui/src/panels/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs index 8996cd1991..65cb782240 100644 --- a/crates/ui-egui/src/panels/histogram_panel.rs +++ b/crates/ui-egui/src/panels/histogram_panel.rs @@ -642,6 +642,13 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } +/// [`command_states`], derived from the panel's settings and whether a document with a selection is open. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let active = app.session.active(); + let facts = (&app.ui.histogram, active.is_some(), active.is_some_and(|st| st.doc.selection.is_some())); + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs a scope command the menu or a key fired: the settings change, then they persist; Uncached Refresh recounts. /// Returns whether the command belongs to this panel. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/panels/history_menu_ui.rs b/crates/ui-egui/src/panels/history_menu_ui.rs index b3f859a00a..305e438b6a 100644 --- a/crates/ui-egui/src/panels/history_menu_ui.rs +++ b/crates/ui-egui/src/panels/history_menu_ui.rs @@ -56,6 +56,21 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta ITEMS.iter().flatten().map(|&id| (CommandRef::new(id), CommandState::new().enabled(command_state(app, resolve(id, snapshot).0)))).collect() } +/// What [`command_states`] reads: the rules (the Pen and Crop histories and an open Free Transform among them) and the +/// snapshot selected in the panel. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + rules: crate::menus::facts::RuleFacts<'a>, + #[memo_props(hash = "a plain model id, a snapshot id and the history spot: plain values")] + snapshot: &'a Option<(photocraft_doc::DocId, u64, crate::panels::history::HistorySpot)>, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { rules: crate::menus::facts::RuleFacts::of(app), snapshot: &app.ui.history_snapshot }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs the item `command` and reports whether it is one of this menu's. History Options… opens its /// dialog, as the menu bar's command does. Step Backward/Forward over a Pen path step it as Edit › /// Undo/Redo do (`vector_ui::pen_history_step`). diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index b75b5acc25..0cb7ef055c 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -19,16 +19,15 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { use craft::ui::contract::Bind; use craft::ui::primitives::textures::{ThumbnailOptions, Thumbnails}; - use super::layers_tree::{self, PhotoLayers, PhotoThumbs}; + use super::layers_tree::{self, PhotoThumbs}; // A Move-way pick of a layer opens its groups only when the Move option says so (#11381). let reveal = crate::layer_reveal::take(app); let ctx = ui.ctx().clone(); // Thumbnail Contents is the clip preference alone, so the panel reads it each pass. app.ui.layers_settings.options.thumbnail_contents = crate::layers_panel_ui::thumbnail_contents(app); - // Taken out of the app for the pass; a move keeps its revision. - let held = app.layers_tree.take(); - let Some(st) = app.session.active() else { + let Some(st) = app.session.active_tracked() else { + layers_tree::no_model(app); let _ = Notice::new(Tone::Neutral, tl!("No document")).layout(NoticeLayout::Centred).show(ui); return; }; @@ -39,14 +38,15 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let mut filter = app.ui.layer_filter.clone(); let before = filter.clone(); let picked = crate::smart_ui::selected(&app.smart_filter_picks, &st.doc, st.active_layer); - let tree = PhotoLayers::new(app, st, &filter, foreign, picked).held(held); + let model = layers_tree::model(app, st, &filter, foreign, picked); + let Some(tree) = &*model else { return }; let thumbs = Thumbnails::>::in_context(&ctx, "photocraft-layer-thumbs", ThumbnailOptions::new()); let source = PhotoThumbs::new(app, &st.doc); - let mut panel = LayersPanel::new(&tree) + let mut panel = LayersPanel::new(tree) .settings(settings) .thumbnails(&thumbs, &source) .filter(Bind::bound(&mut filter)) - .row_menu(|target| layers_tree::row_menu(app, &tree, target)) + .row_menu(|target| layers_tree::row_menu(app, tree, target)) .document(st.doc.id); if let Some((id, groups)) = reveal { panel = panel.reveal(id, groups); @@ -61,7 +61,6 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { panel = panel.start_rename(id); } let out = panel.show(ui); - app.layers_tree = Some(tree); app.find_layers_focus = false; app.layers_rename = None; if filter != before { diff --git a/crates/ui-egui/src/panels/layers_panel_ui.rs b/crates/ui-egui/src/panels/layers_panel_ui.rs index 4e62eb18a2..17988d94e9 100644 --- a/crates/ui-egui/src/panels/layers_panel_ui.rs +++ b/crates/ui-egui/src/panels/layers_panel_ui.rs @@ -165,6 +165,27 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta states } +/// What [`command_states`] reads: the rules (the document's selection among them), the filter bar, the clip +/// preference's value and the UI language, which Duplicate Layers…' title is translated into. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + rules: crate::menus::facts::RuleFacts<'a>, + language: &'static str, + show_filters: bool, + clip: bool, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { + rules: crate::menus::facts::RuleFacts::of(app), + language: crate::i18n::current().code(), + show_filters: app.ui.layers_settings.show_filters, + clip: app.session.prefs().interface.clip_thumbnails_to_layer_bounds, + }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs a fired settings command of the panel menu. `false` for every other command: PhotoCraft's `layer.arrange.*` /// bindings stay the one path of the stacking keys, and the catalogue commands run through the menus. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 7753d129a1..2524a2a54a 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -13,7 +13,7 @@ use craft::layers::ui::tree::{ SubRows, ThumbBadge, }; use craft::theme::LabelColor as UiLabel; -use craft::ui::contract::{Entry, PlainData, ReorderMove, Tracked}; +use craft::ui::contract::{Entry, MemoProps, PlainData, ReorderMove, Tracked}; use craft::ui::list::ThumbSize; use craft::ui::patterns::blend_keys::{BlendKeyEntry, blend_entries}; use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, thumb_image}; @@ -79,12 +79,92 @@ pub(crate) fn listed_filter(app: &PhotocraftApp) -> Option { + doc: &'a Tracked, + filter: &'a LayerFilter, + #[memo_props(hash = "craft-layers part: a fieldless enum")] + target: LayerPart, + mask_target: bool, + vector_mask_target: bool, + link_enabled: bool, + #[memo_props(hash = "a plain model id")] + hovered: Option, + working_text: Option, + /// The missing linked files of the open documents (the Smart Object filter). + missing: craft::ui::contract::Revision, + foreign_drag: bool, + picked: Option, +} + +/// The id the Layers panel's model is derived under. +pub(crate) fn model_id() -> egui::Id { + egui::Id::unique("photocraft-layers-model") +} + +/// The value the Layers panel's model is derived as: `None` while no document is open. +pub(crate) type Model = Option>; + +/// The Layers panel's model of the active document `st`, derived from what it is built from: built again only when +/// one of [`LayersFacts`] changed. A new build is a new `Tracked`, so the panel's key moves exactly then. It is always +/// `Some`. +pub(crate) fn model( + app: &PhotocraftApp, + st: &Tracked, + filter: &LayerFilter, + foreign_drag: bool, + picked: Option, +) -> Arc { + let facts = LayersFacts { + doc: st, + filter, + target: edit_target(app, st), + mask_target: app.ui.mask_target, + vector_mask_target: app.ui.vector_mask_target, + link_enabled: app.session.is_enabled("layer.linkLayers"), + hovered: app.canvas_hover_layer, + working_text: working_text(app), + missing: app.session.missing_links_revision(), + foreign_drag, + picked, + }; + craft::ui::runtime::derived::derived(app.ctx(), model_id(), &facts, || Some(Tracked::new(PhotoLayers::new(app, st, filter, foreign_drag, picked)))) +} + +/// Derives the model as `None` while no document is open: the kept model, which holds the document it showed, is +/// replaced in the pass that finds the document gone. +pub(crate) fn no_model(app: &PhotocraftApp) { + let _ = craft::ui::runtime::derived::derived(app.ctx(), model_id(), &(), || Model::None); +} + +/// A Type Mask session's working text, which the panel never lists. +fn working_text(app: &PhotocraftApp) -> Option { + app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| ed.layer) +} + +/// The part of the active layer edits go to ([`LayerTree::selection`]). +fn edit_target(app: &PhotocraftApp, st: &DocState) -> LayerPart { + let ui = &app.ui; + match st.active_layer.and_then(|id| st.doc.layer(id)) { + Some(l) if l.frame.is_some() => match crate::frame_tool::target(app, l) { + crate::frame_tool::Target::Frame => LayerPart::FrameShape, + crate::frame_tool::Target::Content => LayerPart::FrameContent, + crate::frame_tool::Target::Both => LayerPart::Pixels, + }, + Some(l) if ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() => LayerPart::FilterMask, + Some(l) if ui.vector_mask_target && l.vector_mask.is_some() => LayerPart::VectorMask, + Some(l) if ui.mask_target && l.mask.is_some() => LayerPart::LayerMask, + _ => LayerPart::Pixels, + } +} + /// The Layers panel's model of the active document: the document, the parts of its state the rows show and what the /// app decides for them (the edit target, the hovered layer, the filter's answers). Plain data: the panel holds it in a -/// `Tracked`, and the host writes a new one only when what it holds changed ([`PhotoLayers::held`]). +/// `Tracked`, derived from [`LayersFacts`] ([`model`]). #[derive(Clone, PlainData)] pub(crate) struct PhotoLayers { - #[plain_data(assume = "the document is replaced, never changed in place, while an Arc to it is shared")] doc: Arc, active_layer: Option, selected: Vec, @@ -110,39 +190,15 @@ pub(crate) struct PhotoLayers { picked: Option, } -/// Equal when they show the same: the same document value (one `Arc`) and the same state. -impl PartialEq for PhotoLayers { - fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.doc, &other.doc) - && (&self.active_layer, &self.selected, &self.isolated_layers, &self.fx_collapsed, &self.filter, self.target) - == (&other.active_layer, &other.selected, &other.isolated_layers, &other.fx_collapsed, &other.filter, other.target) - && (self.mask_target, self.vector_mask_target, self.link_enabled, self.hovered, self.working_text, self.foreign_drag, self.picked) - == (other.mask_target, other.vector_mask_target, other.link_enabled, other.hovered, other.working_text, other.foreign_drag, other.picked) - && self.empty == other.empty - && self.missing == other.missing - } -} - impl PhotoLayers { pub(crate) fn new(app: &PhotocraftApp, st: &DocState, filter: &LayerFilter, foreign_drag: bool, picked: Option) -> Self { - let working_text = app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| ed.layer); let empty = match (filter.by, filter.attribute) { (FilterBy::Attribute, LayerAttribute::Empty | LayerAttribute::NotEmpty) => crate::layer_filter_ui::attribute::empty_layers(app), _ => None, }; let missing = if filter.by == FilterBy::SmartObject { app.session.missing_links() } else { HashSet::new() }; let ui = &app.ui; - let target = match st.active_layer.and_then(|id| st.doc.layer(id)) { - Some(l) if l.frame.is_some() => match crate::frame_tool::target(app, l) { - crate::frame_tool::Target::Frame => LayerPart::FrameShape, - crate::frame_tool::Target::Content => LayerPart::FrameContent, - crate::frame_tool::Target::Both => LayerPart::Pixels, - }, - Some(l) if ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() => LayerPart::FilterMask, - Some(l) if ui.vector_mask_target && l.vector_mask.is_some() => LayerPart::VectorMask, - Some(l) if ui.mask_target && l.mask.is_some() => LayerPart::LayerMask, - _ => LayerPart::Pixels, - }; + let target = edit_target(app, st); Self { doc: Arc::clone(&st.doc), active_layer: st.active_layer, @@ -155,7 +211,7 @@ impl PhotoLayers { vector_mask_target: ui.vector_mask_target, link_enabled: app.session.is_enabled("layer.linkLayers"), hovered: app.canvas_hover_layer, - working_text, + working_text: working_text(app), empty, missing, foreign_drag, @@ -163,15 +219,6 @@ impl PhotoLayers { } } - /// `self` in `held`: the held value while it is equal, else a new `Tracked`, so the panel's key moves only when - /// what it shows changed. - pub(crate) fn held(self, held: Option>) -> Tracked { - match held { - Some(held) if *held == self => held, - _ => Tracked::new(self), - } - } - fn doc(&self) -> &Document { &self.doc } diff --git a/crates/ui-egui/src/panels/options_bar/selection.rs b/crates/ui-egui/src/panels/options_bar/selection.rs index f9b8462b84..dab5347b65 100644 --- a/crates/ui-egui/src/panels/options_bar/selection.rs +++ b/crates/ui-egui/src/panels/options_bar/selection.rs @@ -117,6 +117,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta vec![(CommandRef::new(SELECT_AND_MASK), CommandState::new().enabled(crate::menus::is_enabled(app, SELECT_AND_MASK)))] } +/// [`command_states`], derived from what the rules read. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &crate::menus::facts::RuleFacts::of(app), || command_states(app)) +} + /// The Select and Mask… button; its enabled state is [`command_states`]'. fn select_and_mask(ui: &mut egui::Ui) { Button::command(SELECT_AND_MASK).show(ui); diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 480dbfaedc..78975d8024 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -445,6 +445,14 @@ pub(crate) fn styles_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandStat .collect() } +/// [`styles_states`], derived from what it reads: the presets the styles live in, the selected style and the browser's +/// view. +pub(crate) fn styles_source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let view = app.ui.presets_ui.browsers.get(STYLES.id).map_or(PresetView::Grid, |state| state.view); + let facts = (app.session.presets.revision(), app.ui.presets_ui.selected.get(STYLES.id), view); + crate::app::framework::derived_states(app, name, &facts, || styles_states(app)) +} + /// Runs a Styles panel menu command; `false` when `cmd` is not one of its commands. pub(crate) fn styles_run(app: &mut PhotocraftApp, ctx: &egui::Context, cmd: &CommandRef) -> bool { let Some(command) = PresetCommands::from_ref(cmd) else { return false }; diff --git a/crates/ui-egui/src/panels/preset_panels/clone_source.rs b/crates/ui-egui/src/panels/preset_panels/clone_source.rs index 5fb26441eb..20a7732aef 100644 --- a/crates/ui-egui/src/panels/preset_panels/clone_source.rs +++ b/crates/ui-egui/src/panels/preset_panels/clone_source.rs @@ -73,7 +73,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // The document the source was set in (the active one for slots set before slots remembered it). let source_doc = match slot.document { - Some(id) => slot.open_document().and_then(|_| app.session.documents().iter().find(|d| d.doc.id == id)), + Some(id) => slot.open_document().and_then(|_| app.session.documents().iter().find(|d| d.doc.id == id).map(|st| &**st)), None => app.session.active(), }; let source_line = match (slot.source, source_doc) { diff --git a/crates/ui-egui/src/panels/registry.rs b/crates/ui-egui/src/panels/registry.rs index fff40da505..00b1eed5d1 100644 --- a/crates/ui-egui/src/panels/registry.rs +++ b/crates/ui-egui/src/panels/registry.rs @@ -1,8 +1,9 @@ //! The panel registry: every panel PhotoCraft shows in its workspace, with its name, icon, size policy, body and //! panel menu, and the built-in workspaces those panels are arranged in. //! -//! The dock (`panel_docking`) reads a panel's spec and body from here; the command sources read each panel's menu -//! states and run its fired commands through [`states`] and [`run_fired`]. One arrangement serves every theme. +//! The dock (`panel_docking`) reads a panel's spec and body from here; the framework reads each panel's menu states as +//! a command source of its own ([`PanelEntry::states`]) and runs its fired commands through [`run_fired`]. One +//! arrangement serves every theme. use craft::behavior::Axis; use craft::behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; @@ -11,10 +12,13 @@ use craft::ui::contract::{Scroll, ShowContainer as _}; use craft::ui::docking::DockHeights; use craft::ui::layout_components::Stack; use craft::ui::menu::PanelRow; -use craft::ui::runtime::commands::{CommandRef, CommandSet as _, CommandState}; +use craft::ui::runtime::commands::{CommandRef, CommandSet as _}; use egui::{Rect, pos2, vec2}; +use std::sync::Arc; + use super::PhotocraftApp; +use crate::app::framework::{SourceStates, StatesOf, derived_states, no_states}; /// One registered panel. pub(crate) struct PanelEntry { @@ -34,8 +38,9 @@ pub(crate) struct PanelEntry { pub body: fn(&mut PhotocraftApp, &mut egui::Ui), /// The rows of the panel's menu, before the dock's own rows. pub rows: fn(&PhotocraftApp) -> Vec, - /// The state of each command the rows name, for a panel whose rows are a framework command set. - pub states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>, + /// The state of each command the rows name, for a panel whose rows are a framework command set: a value derived + /// under the panel's id from what the states read, so one panel's change builds only its own. + pub states: StatesOf, /// Runs a fired command of the panel's command set; `false` when the command is not the panel's. pub run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool, } @@ -57,10 +62,6 @@ fn no_rows(_: &PhotocraftApp) -> Vec { Vec::new() } -fn no_states(_: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { - Vec::new() -} - /// The body of a panel whose group view draws it. fn drawn_by_group_view(_: &mut PhotocraftApp, _: &mut egui::Ui) {} @@ -105,13 +106,13 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(COLOR_HEIGHTS), rows: |_| ColorPanelMenu::rows(), - states: color_states, + states: color_source_states, run: color_run, ..panel("color", || tl!("Color").to_string(), "palette", LEAST, super::color::panel) }, PanelEntry { rows: super::swatches_ui::panel_rows, - states: super::swatches_ui::command_states, + states: super::swatches_ui::source_states, run: super::swatches_ui::run_fired, ..panel("swatches", || tl!("Swatches").to_string(), "swatch_book", LEAST, super::swatches_ui::panel) }, @@ -140,7 +141,7 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(NAVIGATOR_HEIGHTS), ..panel("navigator", || tl!("Navigator").to_string(), "navigation", LEAST, super::navigator::navigator) }, PanelEntry { rows: super::histogram_panel::panel_rows, - states: super::histogram_panel::command_states, + states: super::histogram_panel::source_states, run: super::histogram_panel::run_fired, ..panel("histogram", || tl!("Histogram").to_string(), "chart_line", LEAST, |app, ui| scrolled(app, ui, super::histogram_panel::show)) }, @@ -148,13 +149,13 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(HISTORY_HEIGHTS), rows: super::history_menu_ui::panel_rows, - states: super::history_menu_ui::command_states, + states: super::history_menu_ui::source_states, run: super::history_menu_ui::run_fired, ..panel("history", || tl!("History").to_string(), "clock", LEAST, super::history::history) }, PanelEntry { rows: super::actions::menu::panel_rows, - states: super::actions::menu::states, + states: super::actions::menu::source_states, run: super::actions::menu::run_fired, ..panel("actions", || tl!("Actions").to_string(), "play", LEAST, super::actions::panel) }, @@ -166,13 +167,13 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(LAYERS_HEIGHTS), rows: super::layers_panel_ui::panel_rows, - states: super::layers_panel_ui::command_states, + states: super::layers_panel_ui::source_states, run: super::layers_panel_ui::run_fired, ..panel("layers", || tl!("Layers").to_string(), "layers", 110.0, super::layers::layers) }, PanelEntry { rows: super::channels_panel::panel_rows, - states: super::channels_panel::command_states, + states: super::channels_panel::source_states, run: super::channels_panel::run_fired, ..panel("channels", || tl!("Channels").to_string(), "squares_subtract", 110.0, super::channels_panel::show) }, @@ -180,7 +181,7 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(BRUSHES_HEIGHTS), ..panel("brushes", || tl!("Brushes").to_string(), "brush", 70.0, super::brush_panel::brushes::panel) }, PanelEntry { rows: super::preset_browser::styles_rows, - states: super::preset_browser::styles_states, + states: super::preset_browser::styles_source_states, run: super::preset_browser::styles_run, ..floating("styles", || tl!("Styles").to_string(), "sparkles", [300.0, 420.0], |app, ui| scrolled(app, ui, super::preset_panels::styles_panel)) }, @@ -215,7 +216,7 @@ pub(crate) static PANELS: &[PanelEntry] = &[ panel("timeline", || tl!("Timeline").to_string(), "split_horizontal", LEAST, super::timeline_ui::body), PanelEntry { rows: super::brush_panel::panel_rows, - states: super::brush_panel::command_states, + states: super::brush_panel::source_states, run: super::brush_panel::run_fired, ..floating("brushSettings", || tl!("Brush Settings").to_string(), "brush_cleaning", [520.0, 460.0], super::brush_settings::brush_settings) }, @@ -226,10 +227,15 @@ pub(crate) static PANELS: &[PanelEntry] = &[ ]; /// The Color panel menu's states, from the panel's own state. -fn color_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { +fn color_states(app: &PhotocraftApp) -> SourceStates { ColorPanelMenu::states(&app.ui.color_panel.panel).into_iter().map(|(command, state)| (command.into(), state)).collect() } +/// [`color_states`], derived from the panel's state. +fn color_source_states(app: &PhotocraftApp, name: &'static str) -> Arc { + derived_states(app, name, &app.ui.color_panel.panel, || color_states(app)) +} + /// Runs a fired Color panel menu command; Copy Color as HTML and Copy Color's Hex Code put their text on the /// clipboard. fn color_run(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { @@ -280,11 +286,6 @@ pub(crate) fn permissions(panel: &str) -> Permissions { } } -/// The state of every panel's menu commands. -pub(crate) fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { - PANELS.iter().flat_map(|panel| (panel.states)(app)).collect() -} - /// Runs a fired panel menu command through the panel whose command set it belongs to; `false` when none takes it. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { PANELS.iter().any(|panel| (panel.run)(app, ctx, command)) diff --git a/crates/ui-egui/src/panels/swatches_ui.rs b/crates/ui-egui/src/panels/swatches_ui.rs index bf9c1842aa..81fd58c88a 100644 --- a/crates/ui-egui/src/panels/swatches_ui.rs +++ b/crates/ui-egui/src/panels/swatches_ui.rs @@ -243,6 +243,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta SwatchesMenu::states(&app.session.presets.swatches).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect() } +/// [`command_states`], derived from the presets the swatches live in. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &app.session.presets.revision(), || command_states(app)) +} + /// Runs a fired command of the Swatches menu; false for another set's command. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = SwatchesCommand::from_ref(command) else { return false }; diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs index 4551cbe061..3ae0b08a8e 100644 --- a/crates/ui-egui/src/save_identity_tests.rs +++ b/crates/ui-egui/src/save_identity_tests.rs @@ -40,7 +40,7 @@ fn identity(app: &PhotocraftApp) -> (String, Option, u64, u64) { fn save_settings_share_only_the_open_documents_native_cache() { let mut app = app(); let first = app.save_settings().io_options().pcraft_cache.unwrap(); - assert_eq!(first, app.session.active().unwrap().pcraft_cache); + assert_eq!(Some(&first), app.session.pcraft_cache(app.session.active().unwrap().doc.id)); assert_eq!(first, app.save_settings().io_options().pcraft_cache.unwrap()); app.run("file.new", json!({"width": 2, "height": 2})).unwrap(); assert_ne!(first, app.save_settings().io_options().pcraft_cache.unwrap()); diff --git a/crates/ui-egui/src/tools/align_bar.rs b/crates/ui-egui/src/tools/align_bar.rs index b6a0dcf594..9eab1e26d8 100644 --- a/crates/ui-egui/src/tools/align_bar.rs +++ b/crates/ui-egui/src/tools/align_bar.rs @@ -47,6 +47,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta all().map(|action| (CommandRef::new(action.id()), CommandState::new().enabled(command_id(action).is_some_and(|id| app.session.is_enabled(id))))).collect() } +/// [`command_states`], derived from what the rules read. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &crate::menus::facts::RuleFacts::of(app), || command_states(app)) +} + /// Runs a fired `AlignAction`. False when `command` is not one of them. The context is the /// command-source shape's; these commands need none. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/tools/artboard_tool.rs b/crates/ui-egui/src/tools/artboard_tool.rs index 982ed64deb..925b9327d4 100644 --- a/crates/ui-egui/src/tools/artboard_tool.rs +++ b/crates/ui-egui/src/tools/artboard_tool.rs @@ -287,9 +287,10 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta vec![(ArtboardCommand::AddNew.into(), state)] } -/// What [`command_states`] reads: whether a document is open, and the placing mode. -pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { - [u64::from(app.session.active().is_some()), u64::from(app.ui.artboard_tool.adding), 0, 0] +/// [`command_states`], derived from what it reads: whether a document is open, and the placing mode. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = (app.session.active().is_some(), app.ui.artboard_tool.adding); + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) } /// Runs a fired Artboard command: Add New Artboard flips the placing mode and adds no board. `ctx` is the shape every diff --git a/crates/ui-egui/src/tools/slice_ui.rs b/crates/ui-egui/src/tools/slice_ui.rs index dd2d513fcd..4790f07919 100644 --- a/crates/ui-egui/src/tools/slice_ui.rs +++ b/crates/ui-egui/src/tools/slice_ui.rs @@ -317,12 +317,19 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } -/// What [`command_states`] reads: the active document and its revision (the selected slice resolves from its -/// slices), the selected slice's number and the lock. -pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { - let revision = app.session.active().map_or(u64::MAX, |st| st.revision); - let selected = app.ui.slices.selected.map_or(u64::MAX, |n| n as u64); - [app.session.active_generation(), revision, selected, u64::from(app.session.file_menu.slices_locked)] +/// What [`command_states`] reads: the active document (the selected slice resolves from its slices), the selected +/// slice's number and the lock. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + doc: Option<&'a craft::ui::contract::Tracked>, + selected: Option, + locked: bool, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { doc: app.session.active_tracked(), selected: app.ui.slices.selected, locked: app.session.file_menu.slices_locked }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) } /// Runs a fired slice command; whether it was one. diff --git a/crates/ui-egui/src/tools/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs index 12b004d2c2..3f8717dc3b 100644 --- a/crates/ui-egui/src/tools/type_tool/defaults.rs +++ b/crates/ui-egui/src/tools/type_tool/defaults.rs @@ -26,7 +26,7 @@ pub(crate) fn target_text(app: &PhotocraftApp) -> Option<&TextLayer> { /// document where the same layer id may name another layer, else the active one. pub(super) fn target_doc(app: &PhotocraftApp) -> Option<&photocraft_engine::DocState> { match &app.ui.text_edit { - Some(ed) => app.session.documents().get(edit_home(app, ed)?), + Some(ed) => app.session.documents().get(edit_home(app, ed)?).map(|st| &**st), None => app.session.active(), } }