Document state is Tracked (#15709)

This commit is contained in:
aiongg
2026-11-21 16:12:46 +00:00
parent 919e66b497
commit 72f7f93777
67 changed files with 597 additions and 326 deletions
Generated
+8
View File
@@ -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",
+3
View File
@@ -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 }
+1 -1
View File
@@ -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,
+4 -4
View File
@@ -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.
+1 -1
View File
@@ -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 }
+8 -8
View File
@@ -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<Vec<u8>>,
@@ -92,7 +92,7 @@ pub fn lut3d_len(size: u32) -> Option<usize> {
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,
+2 -2
View File
@@ -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`.
+5 -5
View File
@@ -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,
+2 -2
View File
@@ -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]>,
}
+5 -5
View File
@@ -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<bool>,
@@ -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,
+20 -20
View File
@@ -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,
+1 -1
View File
@@ -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,
+9 -9
View File
@@ -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<Vec<u8>>, attachments: Vec<Arc<Vec<u8>>> },
}
#[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<RetainedImportData>,
}
#[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<u32>,
}
#[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<LayerId>,
@@ -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<Vec<u8>>,
}
#[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),
+6
View File
@@ -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() }
+23 -22
View File
@@ -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<Effect>,
@@ -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<Layer>,
pub expanded: bool,
@@ -339,7 +339,7 @@ pub struct Group {
pub frame_stroke: Option<ShapeStroke>,
}
#[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<S: Clone>(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<Vec<u8>>,
}
#[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<Vec<u8>> },
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<f64>,
pub vertical: Vec<f64>,
@@ -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<Vec<u8>>);
#[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<PsdGlobalBlock>,
}
#[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).
+5 -5
View File
@@ -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<DuotoneInk>,
/// 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,
+2 -2
View File
@@ -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,
+5 -5
View File
@@ -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,
+15 -15
View File
@@ -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,
+7 -3
View File
@@ -28,31 +28,34 @@ pub type StyleAttrs = Map<String, Value>;
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<Value>,
}
+8 -8
View File
@@ -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.
+14 -14
View File
@@ -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<Knot>,
@@ -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<Subpath>,
#[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").
+3 -3
View File
@@ -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<Surface>,
/// 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,
+2 -2
View File
@@ -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,
-4
View File
@@ -26,14 +26,11 @@ pub struct Clip {
pub svg: Option<std::sync::Arc<Vec<u8>>>,
/// Native colour indices for a multi-component clip, in channel order. Singletons are grayscale.
pub components: Option<Vec<usize>>,
#[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<Box<Document>>,
/// 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)>,
}
@@ -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| {
@@ -137,7 +137,7 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
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();
+11 -4
View File
@@ -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<Option<Value>> {
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" => {
+3 -4
View File
@@ -64,7 +64,6 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result<Value> {
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));
+3 -4
View File
@@ -77,7 +77,6 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result<Value> {
_ => 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");
+1 -1
View File
@@ -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,
+8 -3
View File
@@ -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<LayerMaskView> {
/// 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<LayerMaskView>) -> &'static str {
match v.map(|v| v.mode) {
None => "off",
+4 -2
View File
@@ -92,9 +92,10 @@ fn layer_slice_rect(doc: &Document, s: &Slice) -> Option<Rect> {
}
/// 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 {
+2 -2
View File
@@ -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),
+21 -30
View File
@@ -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<Vec<LayerId>>,
selected_cache: SelectedOrder,
pub history: History,
/// Anchor of range selection (the last plainly or command-clicked layer).
pub layer_anchor: Option<LayerId>,
pub path: Option<String>,
/// 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<LayerId>,
/// 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<Document>,
@@ -86,6 +84,15 @@ pub struct DocStateInputs {
pub selected_layers: Vec<LayerId>,
}
/// 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<Vec<LayerId>>);
// 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<Document> {
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<LayerId>) {
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<LayerId> {
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,
}
+16 -7
View File
@@ -1874,7 +1874,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))
@@ -1898,7 +1897,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<Document>, 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));
@@ -1931,10 +1934,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<Document>) {
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();
}
@@ -1971,9 +1977,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, &params);
crate::automate_cmds::after_command(self, id);
+6 -3
View File
@@ -202,7 +202,10 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do
#[derive(Default)]
pub struct Session {
docs: Vec<DocState>,
/// The open documents, each in a `Tracked`: views key on its revision, which every write moves.
docs: Vec<craft_tracked::Tracked<DocState>>,
/// Each open document's native save cache, shared with its save workers; dropped when the document closes.
pcraft_caches: std::collections::HashMap<photocraft_doc::DocId, photocraft_io::PcraftExportCache>,
documents_generation: u64,
/// Override Open belongs only to one Batch scratch session, never to caller preferences.
pub(crate) batch_open: Option<file_cmds::BatchOpen>,
@@ -313,8 +316,8 @@ pub struct Session {
/// The stamps being taken on a worker thread ([`Session::start_link_scan`]).
pub link_scan: Option<link_watch::LinkScan>,
/// 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<std::collections::HashSet<(u64, String)>>,
/// 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
+18 -9
View File
@@ -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<u64>, Option<Stamp>)]) {
let open: HashSet<u64> = 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).
+8 -4
View File
@@ -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);
-1
View File
@@ -94,7 +94,6 @@ pub struct PresetState {
#[plain_data(assume = "craft-color-ui swatch groups: plain values and strings")]
pub swatches: Vec<swatches::SwatchGroup>,
/// The user contour library of the Layer Style dialog (`layer.layerStyle.contours.*`).
#[plain_data(assume = "document contours: plain numbers")]
pub contours: Vec<photocraft_doc::Contour>,
}
+1 -1
View File
@@ -432,7 +432,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
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));
-1
View File
@@ -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")]
-2
View File
@@ -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<Effect>,
/// Blending options saved with the style ("Include Layer Blending Options").
#[serde(default)]
#[plain_data(assume = "an enum")]
pub blend: Option<BlendMode>,
#[serde(default)]
pub fill_opacity: Option<f32>,
+27 -6
View File
@@ -23,7 +23,7 @@ impl Session {
Self::default()
}
pub fn documents(&self) -> &[DocState] {
pub fn documents(&self) -> &[craft_tracked::Tracked<DocState>] {
&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<DocState>> {
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<DocState>> {
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() {
+3
View File
@@ -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 }
+5 -5
View File
@@ -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],
}
+4 -4
View File
@@ -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<f64>,
pub vs: Vec<f64>,
@@ -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,
+3
View File
@@ -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 }
+6 -6
View File
@@ -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<LayerId>,
pub selected: Vec<LayerId>,
}
#[derive(Clone, Debug)]
#[derive(Clone, Debug, craft_ui_macros::PlainData)]
pub struct HistoryState {
pub label: String,
pub doc: Arc<Document>,
@@ -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<HistoryState>,
@@ -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<Arc<Vec<LayerId>>>,
/// 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<HistoryState>,
redo: Vec<HistoryState>,
+1 -1
View File
@@ -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<usize, (u128, usize)>,
bytes: u128,
+2 -2
View File
@@ -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],
+3
View File
@@ -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"] }
+1 -1
View File
@@ -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 {
+13 -2
View File
@@ -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<TileCoord, Arc<Tile>>,
}
// `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.
-1
View File
@@ -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,
+1 -1
View File
@@ -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
}
+14 -6
View File
@@ -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;
}
+13 -11
View File
@@ -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::<u32>()
};
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}));
+133
View File
@@ -0,0 +1,133 @@
//! 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.
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;
type H = Harness<'static, Box<PhotocraftApp>>;
/// 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 the last frame built the value derived under `id`.
fn builds(h: &H, id: egui::Id) -> u32 {
last_frame_derived_builds(&h.ctx).iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum()
}
/// Every open document's `Tracked` revision.
fn revisions(h: &H) -> Vec<craft::ui::contract::Revision> {
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();
h.run_steps(1);
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!(builds(&h, crate::panels::layers_tree::model_id()), 0, "B's Layers model builds nothing");
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");
}
#[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_moves_only_the_tracked_revision() {
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");
}
+2 -2
View File
@@ -132,7 +132,7 @@ fn lock(cache: &Mutex<ThumbnailCache>) -> 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<photocraft_engine::DocState>],
cache: &'a Mutex<ThumbnailCache>,
ctx: egui::Context,
focus_gained: bool,
@@ -154,7 +154,7 @@ pub(crate) fn thumbnails(ctx: &egui::Context) -> Thumbnails<ThumbKey> {
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)
}
}
+2 -2
View File
@@ -358,8 +358,6 @@ pub struct PhotocraftApp {
pub(crate) menu_model: Option<menus::MenuModel>,
/// 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<craft::ui::contract::Tracked<panels::layers_tree::PhotoLayers>>,
/// 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`).
@@ -952,6 +950,8 @@ mod chrome_settle_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;
+5 -5
View File
@@ -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;
@@ -31,10 +32,9 @@ struct Documents<'a> {
generation: u64,
active_generation: u64,
active_index: Option<usize>,
/// 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<DocState>>,
/// A running job greys the commands that would change its document.
jobs: (bool, Option<u64>),
/// Smart Objects › Edit Contents' parent: whether the active document is a smart object's contents.
@@ -131,7 +131,7 @@ impl<'a> MenuFacts<'a> {
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)),
+7 -8
View File
@@ -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::<LayerThumb<LayerId>>::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 {
+85 -38
View File
@@ -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<crate::smart_ui::Filt
PhotoLayers::new(app, st, &app.ui.layer_filter, false, picked).selected_filter()
}
/// What the Layers panel's model is built from ([`PhotoLayers::new`]): the document as the session tracks it, whose
/// revision moves with every change to it, view state included, and the app's answers for its rows.
#[derive(MemoProps)]
struct LayersFacts<'a> {
doc: &'a Tracked<DocState>,
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<LayerId>,
working_text: Option<u64>,
/// The missing linked files of the open documents (the Smart Object filter).
missing: craft::ui::contract::Revision,
foreign_drag: bool,
picked: Option<crate::smart_ui::FilterDrag>,
}
/// 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<Tracked<PhotoLayers>>;
/// 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<DocState>,
filter: &LayerFilter,
foreign_drag: bool,
picked: Option<crate::smart_ui::FilterDrag>,
) -> Arc<Model> {
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<u64> {
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<Document>,
active_layer: Option<LayerId>,
selected: Vec<LayerId>,
@@ -110,39 +190,15 @@ pub(crate) struct PhotoLayers {
picked: Option<crate::smart_ui::FilterDrag>,
}
/// 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<crate::smart_ui::FilterDrag>) -> 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<PhotoLayers>>) -> Tracked<PhotoLayers> {
match held {
Some(held) if *held == self => held,
_ => Tracked::new(self),
}
}
fn doc(&self) -> &Document {
&self.doc
}
@@ -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) {
+1 -1
View File
@@ -40,7 +40,7 @@ fn identity(app: &PhotocraftApp) -> (String, Option<String>, 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());
@@ -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(),
}
}