Merge remote-tracking branch 'origin/main' into pr-14454

This commit is contained in:
David Mann
2026-11-21 19:34:49 +01:00
126 changed files with 2671 additions and 732 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",
+5 -1
View File
@@ -429,6 +429,9 @@ pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>)
Ok(opened.map(|doc| (name, doc)))
}) as photocraft_ui_egui::AutomationOpenPcraftFn
});
let locate = workspace.clone().map(|workspace| {
Box::new(move |path: &str| workspace.location(path).map(|location| location.to_string_lossy().into_owned())) as photocraft_ui_egui::AutomationLocateFn
});
let save = workspace.clone().map(|workspace| {
std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| {
save_through(doc, path, settings, ctl, |p, encoded, _| workspace.write_stream(p, &mut |w| encoded.write_to(w)).map_err(|e| e.to_string()))
@@ -441,7 +444,7 @@ pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>)
photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string())
}) as photocraft_ui_egui::AutomationCommandFn
});
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize }
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, locate, save, command, authorize }
}
/// What agent requests may read, write and run with the agent settings' folders
@@ -486,6 +489,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wa
automation_read: automation.read,
automation_write: automation.write,
automation_open_pcraft: automation.open_pcraft,
automation_locate: automation.locate,
automation_save: automation.save,
automation_command: automation.command,
automation_authorize: automation.authorize,
+3
View File
@@ -355,3 +355,6 @@ real_name = "Sven Lafebre"
[people.kirubhakaran12]
sync_github_name = true
[people.MMexicann]
display_name = "mexicann"
+12
View File
@@ -103,6 +103,18 @@ impl AuthorizedWorkspace {
Ok((bytes, save_path))
}
/// Where the file or `.pcraft` folder that `path` names is on disk: below the first read
/// root that holds it (the root `read` and `open_pcraft` pick), as that root was configured
/// at launch. Open Recent lists this, since the person reopens the file outside automation,
/// where a root-relative request path names nothing. It grants no access.
pub fn location(&self, path: &str) -> Option<PathBuf> {
self.read.iter().find_map(|root| {
let relative = scoped_path(path, root).ok()??;
root.dir.metadata(&relative).ok()?;
Some(root.configured_path.join(relative))
})
}
fn open_read(&self, path: &str) -> Result<(cap_std::fs::File, &RootCapability), AutomationError> {
if self.read.is_empty() {
return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent")));
+19
View File
@@ -64,6 +64,25 @@ fn read_growth_is_rejected_at_the_observed_length() {
assert!(read_to_observed_length(&mut empty, 0).is_err());
}
#[test]
fn location_names_the_file_below_the_root_that_holds_it() {
let (library, work, _) = roots("location");
std::fs::create_dir_all(work.join("shots")).unwrap();
std::fs::write(work.join("shots/a.png"), b"a").unwrap();
std::fs::write(library.join("same.png"), b"first").unwrap();
std::fs::write(work.join("same.png"), b"second").unwrap();
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap();
// A root-relative request names the file below the root that holds it, as an absolute path.
assert_eq!(workspace.location("shots/a.png"), Some(work.join("shots").join("a.png")));
// The first root that holds the name wins, as for `read`.
assert_eq!(workspace.location("same.png"), Some(library.join("same.png")));
// An absolute request below a root keeps naming that file.
assert_eq!(workspace.location(&work.join("same.png").to_string_lossy()), Some(work.join("same.png")));
assert_eq!(workspace.location("missing.png"), None);
assert_eq!(workspace.location("../outside.png"), None, "a path escaping the roots has no location");
assert_eq!(AuthorizedWorkspace::default().location("shots/a.png"), None, "no read root, no location");
}
#[test]
fn open_pcraft_loads_a_directory_below_the_read_root() {
let (inside, _, workspace) = roots("pcraft-dir");
+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.
+35 -32
View File
@@ -700,49 +700,52 @@ fn chisel_fields_do_not_depend_on_the_threads() {
#[test]
fn bevel_maps_do_not_depend_on_the_threads() {
// Every style and technique, softened or not, and a texture; one thread (in order) is the reference.
let mut patchy = aa_disc(101, 101, 40.0);
// Compact anti-aliased fixtures keep curved, rounded, clipped oblique and patchy edges.
// Dimensions above 16 and below 64 exercise multi-row groups with 2 threads and
// one row per group with 8. Odd extents also leave a short final group.
let mut patchy = aa_disc(51, 51, 18.0);
let patchy_width = patchy.w;
for (i, v) in patchy.v.iter_mut().enumerate() {
if (i % 101 / 13 + i / 101 / 17) % 5 == 0 {
if (i % patchy_width / 7 + i / patchy_width / 9).is_multiple_of(5) {
*v *= 0.6;
}
}
let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy];
let shapes = [aa_disc(49, 47, 13.0), aa_round_rect(61, 47, 10.0, 9.0, 51.0, 38.0, 8.0), aa_bar(47, 63, 60.0, 74.0, 15.0), patchy];
let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]);
sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]);
let pats = [Pattern::new("stripes", sf, 4, 4)];
let light = GlobalLight::default();
let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss];
for (k, shape) in shapes.iter().enumerate() {
let techniques = [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft];
let settings = [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)];
for (shape_index, shape) in shapes.iter().enumerate() {
let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) };
for style in styles {
for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] {
for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] {
let mut b = bevel_of(style, technique);
(b.size, b.soften) = (size, soften);
if textured {
b.texture = Some(photocraft_doc::BevelTexture {
name: "stripes".into(),
id: String::new(),
scale: 1.0,
depth: 1.0,
invert: false,
link: true,
phase: (0.0, 0.0),
});
}
let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0;
let one = with_threads(1, run);
// 2 threads give groups of several units with a short last one, 16 one unit a group: the two ways `par_units` splits work (#15652).
for threads in [2, 16] {
let many = with_threads(threads, run);
assert_eq!(one.len(), many.len());
for (j, (a, m)) in one.iter().zip(&many).enumerate() {
assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads");
}
}
}
for (style_index, style) in styles.into_iter().enumerate() {
// Rotate each set through shapes. Stepping the settings twice as fast as
// the techniques across styles also gives every technique each setting.
let technique = techniques[(shape_index + style_index) % techniques.len()];
let (size, soften, textured) = settings[(shape_index + 2 * style_index) % settings.len()];
let threads = [2, 8][(shape_index + style_index) % 2];
let mut b = bevel_of(style, technique);
(b.size, b.soften) = (size, soften);
if textured {
b.texture = Some(photocraft_doc::BevelTexture {
name: "stripes".into(),
id: String::new(),
scale: 1.0,
depth: 1.0,
invert: false,
link: true,
phase: (0.0, 0.0),
});
}
let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0;
let one = with_threads(1, run);
let many = with_threads(threads, run);
assert_eq!(one.len(), many.len());
for (j, (a, m)) in one.iter().zip(&many).enumerate() {
assert_eq!(bits(&a.v), bits(&m.v), "shape {shape_index}, {style:?} {technique:?} size {size} map {j} on {threads} threads");
}
}
}
+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
View File
@@ -435,6 +435,10 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
}
let has_clear = transparency && px.iter().any(|q| q[3] < 0.5);
let mut pal = quantize::build_palette(&px, kind, if has_clear { colors.saturating_sub(1).max(2) } else { colors }, forced).map_err(|e| bad(CMD, e))?;
// Exact must reserve one palette slot for clear pixels.
if kind == PaletteKind::Exact && has_clear && pal.len() >= 256 {
return Err(bad(CMD, "Exact with transparency needs 255 or fewer opaque palette colours plus one transparent entry"));
}
let transparent = if has_clear && pal.len() < 256 {
pal.push([255, 255, 255]);
Some(pal.len() - 1)
+99
View File
@@ -439,6 +439,105 @@ fn indexed_matte_without_transparency_fills_clear_pixels_and_rejects_bad_input_a
assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, None);
}
#[test]
fn indexed_exact_rejects_full_opaque_palette_with_clear_pixels_atomically() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 257, "height": 1, "background": "transparent"})).unwrap();
paint(&mut s, |x, _| if x < 256 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] });
let before = doc(&s).layers[0].surface().unwrap().to_interleaved(doc(&s).bounds());
let history = s.active().unwrap().history.past_len();
let revision = s.active().unwrap().revision;
let error = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap_err();
let message = error.to_string();
assert!(message.contains("255") && message.contains("transparent entry"), "{message}");
assert_eq!(doc(&s).mode, ColorMode::Rgb);
assert!(doc(&s).color_table.is_none());
assert_eq!(doc(&s).layers[0].surface().unwrap().to_interleaved(doc(&s).bounds()), before);
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.active().unwrap().revision, revision);
}
#[test]
fn indexed_exact_reserves_transparency_only_when_needed_and_available() {
for (opaque, clear) in [(255u32, true), (256, false)] {
let mut s = Session::new();
s.execute("file.new", json!({"width": opaque + u32::from(clear), "height": 1, "background": "transparent"})).unwrap();
paint(&mut s, |x, _| if x < opaque as i32 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] });
let result = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Indexed);
let table = doc(&s).color_table.as_ref().unwrap();
assert_eq!(table.colors.len(), 256);
assert_eq!(table.transparent, if clear { Some(255) } else { None });
assert_eq!(result["transparentIndex"], if clear { json!(255) } else { Value::Null });
let surface = doc(&s).layers[0].surface().unwrap();
for x in 0..opaque as i32 {
let gray = x as f32 / 255.0;
assert_eq!(surface.rgba(x, 0), [gray, gray, gray, 1.0]);
}
if clear {
assert_eq!(surface.rgba(opaque as i32, 0)[3], 0.0);
}
}
}
#[test]
fn indexed_exact_failure_restores_a_floating_copy_and_redo() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 258, "height": 1, "background": "transparent"})).unwrap();
paint(&mut s, |x, _| if x < 256 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] });
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
s.edit("redo marker", |doc, _| {
doc.name.push_str(" changed");
Ok(())
})
.unwrap();
assert!(s.undo());
s.execute("select.float", json!({"dx": 256, "copy": true})).unwrap();
let before = s.active().unwrap().clone();
assert!(before.history.can_redo());
let piece = crate::float_cmds::floating(&before).unwrap();
let pixels = before.doc.layers[0].surface().unwrap().to_interleaved(before.doc.bounds());
let error = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap_err();
assert!(error.to_string().contains("255"), "{error}");
let after = s.active().unwrap();
let restored = crate::float_cmds::floating(after).unwrap();
assert_eq!(after.doc.id, before.doc.id);
assert_eq!(after.doc.mode, ColorMode::Rgb);
assert!(std::sync::Arc::ptr_eq(&after.doc, &before.doc));
assert_eq!(after.doc.layers[0].surface().unwrap().to_interleaved(after.doc.bounds()), pixels);
assert_eq!((restored.layer, restored.offset, restored.revision, restored.moved), (piece.layer, piece.offset, piece.revision, piece.moved));
assert!(std::sync::Arc::ptr_eq(&restored.parts, &piece.parts));
assert_eq!(after.revision, before.revision);
assert_eq!(after.history.past_len(), before.history.past_len());
assert!(after.history.can_redo());
assert_eq!(after.active_layer, before.active_layer);
assert_eq!(after.selected_layers, before.selected_layers);
}
#[test]
fn indexed_exact_success_drops_the_floating_copy_before_counting_colours() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 257, "height": 1, "background": "transparent"})).unwrap();
paint(&mut s, |x, _| if x < 256 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] });
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
s.execute("select.float", json!({"dx": 256, "copy": true})).unwrap();
let history = s.active().unwrap().history.past_len();
let result = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Indexed);
assert_eq!(doc(&s).color_table.as_ref().unwrap().colors.len(), 256);
assert_eq!(result["transparentIndex"], Value::Null);
assert!(crate::float_cmds::floating(s.active().unwrap()).is_none());
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(256, 0), [0.0, 0.0, 0.0, 1.0]);
assert_eq!(s.active().unwrap().history.past_len(), history + 2, "drop and conversion remain separate history steps");
assert!(s.undo());
assert_eq!(doc(&s).mode, ColorMode::Rgb);
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(256, 0)[3], 1.0);
assert!(s.undo());
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(256, 0)[3], 0.0);
assert_eq!(s.active().unwrap().history.past_len(), history);
}
#[test]
fn indexed_exact_transparency_and_sources() {
// Two colours + transparency: exact palette with a transparent entry.
+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 {
@@ -229,6 +229,10 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {
f.params = photocraft_io::smart_map::displace_without_map(&f.params);
}
}
// As applying it does: the re-render can't read the document's alpha channels.
if f.command == "filter.blur.lensBlur" && f.params.get("depthMap").and_then(Value::as_str) == Some("channel") {
return Err(EngineError::Other(crate::filters::LENS_BLUR_CHANNEL_ON_SMART.into()));
}
// Authorize the underlying command with the complete merged params, including paths
// already stored in the document, before committing the edit or starting a worker.
if let Some(gate) = authorize {
+28
View File
@@ -1667,3 +1667,31 @@ fn set_params_replace_drops_a_shape_blur_radius_it_leaves_out() {
s.execute("layer.smartFilter.setParams", json!({"params": {"shape": "circle"}, "replace": true})).unwrap();
assert!(params(&s).get("radius").is_none(), "replaced: {}", params(&s));
}
/// A smart filter re-renders from its params alone, without the document's alpha channels (#7400): Lens Blur refuses an
/// alpha channel as its depth on a Smart Object, both when it is applied and when a recorded filter's params are edited
/// (merged or replaced), and the refused edit changes neither the filter nor the history.
#[test]
fn lens_blur_smart_filter_refuses_an_alpha_channel_depth_on_edit() {
let mut s = session(8);
paint(&mut s);
s.execute("select.all", json!({})).unwrap();
s.execute("select.saveSelection", json!({"name": "Depth"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("filter.convertForSmartFilters", json!({})).unwrap();
let channel = json!({"radius": 4, "depthMap": "channel", "depthChannel": 0});
let applied = s.execute("filter.blur.lensBlur", channel.clone()).unwrap_err().to_string();
assert!(applied.contains("rasterize the layer first"), "{applied}");
s.execute("filter.blur.lensBlur", json!({"radius": 4, "depthMap": "transparency"})).unwrap();
let recorded = active_smart(&s).smart_filters[0].params.clone();
let steps = s.active().unwrap().history.past_len();
for replace in [false, true] {
let e = s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": channel, "replace": replace})).unwrap_err().to_string();
assert!(e.contains("rasterize the layer first"), "replace={replace}: {e}");
assert_eq!(active_smart(&s).smart_filters[0].params, recorded, "replace={replace}");
assert_eq!(s.active().unwrap().history.past_len(), steps, "replace={replace}");
}
// Sources that need no channel stay editable.
s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"depthMap": "none"}})).unwrap();
assert_eq!(active_smart(&s).smart_filters[0].params["depthMap"], json!("none"));
}
+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,
}
+6 -1
View File
@@ -76,6 +76,11 @@ fn preset(id: &str) -> Option<(&'static str, FilterParams)> {
})
}
/// Why Lens Blur refuses an alpha channel as its depth on a Smart Object: a smart filter re-renders from its params
/// alone, without the document's channels, so the depth would be lost (#7400). Applying it and editing a recorded
/// filter's params both refuse it.
pub(crate) const LENS_BLUR_CHANNEL_ON_SMART: &str = "Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first";
/// Builds the algorithm parameters for a filter command id from JSON params
/// (Photoshop dialog units). Stored smart filters and previews retain their tolerant decoding;
/// new command invocations pass through `validate_params` before any document changes.
@@ -339,7 +344,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
// A smart filter re-renders from its params alone, without the document's
// channels, so Lens Blur's alpha-channel depth would be lost (#7400).
if matches!(fp, FilterParams::LensBlur { depth: algo::DepthSource::Channel, .. }) {
return Err(EngineError::Other("Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first".into()));
return Err(EngineError::Other(LENS_BLUR_CHANNEL_ON_SMART.into()));
}
// A smart filter re-renders from its params alone: a Displace map read from an
// open document, which the re-render can't read again, is kept in them, as
+39 -7
View File
@@ -1721,6 +1721,29 @@ impl Session {
// authorization, validation, floating-selection and admission failures.
let live_commit = self.live_commit.take();
self.sync_scratch_state();
// A refused Exact conversion must also undo its automatic floating-selection drop.
let checkpoint = if id == "image.mode.indexedColor" && params.get("palette").and_then(Value::as_str) == Some("exact") {
self.active.and_then(|index| {
self.docs
.get(index)
.filter(|state| crate::float_cmds::floating(state).is_some())
.map(|state| (index, state.clone(), self.action_history.clone()))
})
} else {
None
};
let result = self.dispatch_with_commit(id, params, background, live_commit);
if result.is_err()
&& let Some((index, state, action_history)) = checkpoint
&& self.docs.get(index).is_some_and(|current| current.doc.id == state.doc.id)
{
self.docs[index] = state;
self.action_history = action_history;
}
result
}
fn dispatch_with_commit(&mut self, id: &str, params: Value, background: bool, live_commit: Option<crate::brush_cmds::LiveCommit>) -> Result<Started> {
let spec = crate::registry::spec(id)?;
// Params are named fields: anything but an object (or null, meaning none) is a caller
// mistake, not "use every default".
@@ -1874,7 +1897,6 @@ impl Session {
} else if !st.fx_collapsed.contains(&layer_id) {
st.fx_collapsed.push(layer_id);
}
st.note_disclosure_change();
}
self.after_command(id, params, spec.journal, automation, Some(nested_from), pre_selected.as_deref(), &record_before);
Ok(Started::Done(v))
@@ -1898,7 +1920,11 @@ impl Session {
/// keeps the damage it reported. Debug and test builds also count a whole-document redraw of
/// a small change ([`Session::whole_redraws`]).
pub(crate) fn note_command_damage(&mut self, id: &str, before: &Arc<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 +1957,13 @@ impl Session {
/// stroke on a layer with a Gradient Overlay reports the stroke, but the gradient is laid out
/// again over the whole grown layer (#4053). `before` is the active document before.
fn add_relayout_damage(&mut self, before: &Arc<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 +2000,12 @@ impl Session {
pre_selected: Option<&[LayerId]>,
before: &crate::actions_record::Before,
) {
// A layer-mask view ends when another layer becomes active (#196).
if let Some(st) = self.active_mut() {
crate::mask_view_cmds::fix(st);
// A layer-mask view ends when another layer becomes active (#196). Borrowed to change only when it does: the
// borrow moves the document's `Tracked` revision, and this runs after every command.
if self.active().is_some_and(crate::mask_view_cmds::stale)
&& let Some(st) = self.active_mut()
{
st.channel_view.layer_mask = None;
}
crate::edit_menu_cmds::after_command(self, id, &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,
+48
View File
@@ -165,6 +165,54 @@ fn active_unimplemented_controls_and_malformed_curves_stay_opaque() {
}
}
#[test]
fn psd_reopen_keeps_editable_camera_raw_and_preserves_active_unsupported_optics() {
use std::sync::Arc;
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource};
use photocraft_geom::{Affine, Size};
use photocraft_raster::Surface;
let size = Size::new(2, 2);
let mut source = Document::new("contents", size, ColorMode::Rgb, SampleType::U8);
let mut pixels = Surface::new(source.pixel_format());
pixels.fill_rect(source.bounds(), &[0.25, 0.50, 0.75, 1.0]);
source.layers.push(Layer::new("synthetic pixels", LayerContent::Raster(pixels.clone())));
let bytes = Arc::new(photocraft_format::save_to_bytes(&source, &Default::default()).unwrap());
// Use the existing generated descriptor, not the optional external PSD. Nonzero MDis cannot
// be rendered by the editable Camera Raw filter and must survive even when the layer is saved.
for optics in [false, true] {
let mut item = source_item();
if optics {
let mut settings = get_desc(&item, "Fltr").unwrap().clone();
set(&mut settings, "MDis", Value::Integer(17));
set(&mut item, "Fltr", Value::Descriptor(settings));
}
let mut smart =
SmartObject::new(SmartSource::Embedded { file_name: "contents.pcraft".into(), bytes: bytes.clone() }, Affine::IDENTITY, Some(pixels.clone()));
smart.smart_filters.push(filter_from_item(&item));
let mut doc = Document::new("camera raw compatibility", size, ColorMode::Rgb, SampleType::U8);
doc.layers.push(Layer::new("edited", LayerContent::Smart(smart)));
let saved = crate::export(&doc, "psd", &Default::default()).unwrap();
let reopened = crate::import("saved.psd", &saved.bytes).unwrap().document;
let layer = reopened.layers.iter().find(|layer| layer.name == "edited").unwrap();
let LayerContent::Smart(smart) = &layer.content else { panic!("the Camera Raw layer must reopen as a smart object") };
let [filter] = smart.smart_filters.as_slice() else { panic!("expected the saved Camera Raw filter") };
if optics {
assert_eq!(filter.command, UNSUPPORTED_FILTER);
} else {
assert_eq!(filter.command, COMMAND);
let settings: CameraRaw = serde_json::from_value(filter.params.clone()).unwrap();
assert!((settings.exposure - 1.15).abs() < 1e-6);
}
let roundtripped = item_for_filter(filter).unwrap();
assert_eq!(get_desc(&roundtripped, "Fltr"), get_desc(&item, "Fltr"));
}
}
#[test]
#[ignore = "requires a user-supplied Camera Raw PSD"]
fn all_sliders_fixture() {
+21 -4
View File
@@ -26,6 +26,18 @@ fn require_scratch(expected: bool) -> Result<(), IoError> {
Ok(())
}
/// Interleaved F32 gray + alpha samples as F32 RGBA, the gray value in R, G and B.
fn gray_alpha_to_rgba(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len().saturating_mul(2));
for [gray, alpha] in data.as_chunks::<4>().0.as_chunks::<2>().0 {
out.extend_from_slice(gray);
out.extend_from_slice(gray);
out.extend_from_slice(gray);
out.extend_from_slice(alpha);
}
out
}
/// Decode a single-part flat scanline EXR from `source` one compression block at a time.
/// `Ok(None)`: the header is not one the band decoder takes (multi-part, deep, tiled, custom
/// chromaticities, over its block limits or malformed by its stricter checks); the caller
@@ -41,7 +53,9 @@ pub(crate) fn import<R: Read + Seek>(source: R, ctl: &Interrupt<'_>) -> Result<O
Err(_) => return Ok(None),
};
let info = decoder.info();
let mode = if info.gray { ColorMode::Grayscale } else { ColorMode::Rgb };
// Every EXR opens as RGB 32-bit, as in the reference application: a luminance or single
// data channel (decoded as gray) fills R, G and B alike (#14069).
let mode = ColorMode::Rgb;
let fmt = PixelFormat::new(mode, SampleType::F32, true);
let scratch_expected = photocraft_raster::spill::enabled();
if !scratch_expected {
@@ -76,7 +90,11 @@ pub(crate) fn import<R: Read + Seek>(source: R, ctl: &Interrupt<'_>) -> Result<O
missing.saturating_mul((TILE_SIZE as u64).pow(2)).saturating_mul(fmt.bytes_per_pixel() as u64),
)?;
}
surface.write_interleaved(rect, &band.data);
if info.gray {
surface.write_interleaved(rect, &gray_alpha_to_rgba(&band.data));
} else {
surface.write_interleaved(rect, &band.data);
}
require_scratch(scratch_expected)?;
done += 1;
ctl.progress(0.05 + 0.9 * done as f32 / info.blocks.max(1) as f32);
@@ -95,8 +113,7 @@ pub(crate) fn import<R: Read + Seek>(source: R, ctl: &Interrupt<'_>) -> Result<O
layer.locks.position = true;
}
document.layers.push(layer);
document.icc_profile =
Some(if mode == ColorMode::Rgb { craft_cms::Builtin::LinearSrgb.profile().to_bytes() } else { craft_cms::builtin::linear_gray().to_bytes() });
document.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes());
let warnings = if info.all_half { vec!["16-bit float samples are stored as 32-bit float".into()] } else { Vec::new() };
ctl.progress(1.0);
Ok(Some(ImportResult { document, warnings, source_read_only: false, preview_only: false }))
+14 -25
View File
@@ -165,24 +165,19 @@ pub struct Selection {
pub precomp: bool,
}
/// An image as an importable layer: F16 becomes F32 (lossless, warned once by the caller),
/// the layout matches the document's, the surface is built a band of rows at a time. The
/// returned mode tells the caller whether this layer is grayscale.
fn layer_surface(img: &Image, max: &mut (u32, u32)) -> Result<(Surface, ColorMode), IoError> {
let (layout, mode) = if matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA) {
(ChannelLayout::GrayA, ColorMode::Grayscale)
} else {
(ChannelLayout::Rgba, ColorMode::Rgb)
};
/// An image as an importable layer: F16 becomes F32 (lossless, warned once by the caller), the
/// layout is RGBA (a gray part or group fills R, G and B alike, as every EXR opens as RGB,
/// #14069), the surface is built a band of rows at a time.
fn layer_surface(img: &Image, max: &mut (u32, u32)) -> Result<Surface, IoError> {
max.0 = max.0.max(img.width());
max.1 = max.1.max(img.height());
let converted = img.convert(layout, SampleType::F32);
image_surface(&converted, layout, SampleType::F32).map(|s| (s, mode))
let converted = img.convert(ChannelLayout::Rgba, SampleType::F32);
image_surface(&converted, ChannelLayout::Rgba, SampleType::F32)
}
/// Imports the chosen entries as the layers of one document: parts whole, groups from their
/// own channels, F16 kept losslessly as F32, the linear-light EXR values tagged linear sRGB
/// or linear gray.
/// own channels, F16 kept losslessly as F32, the document RGB and the linear-light EXR values
/// tagged linear sRGB.
/// `precomp` adds the additive sum of the file's AOV groups as a top layer and fails,
/// naming the missing AOVs, when the light-path set is incomplete.
pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result<ImportResult, IoError> {
@@ -230,7 +225,6 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result<ImportResult,
// channels.
let mut layers: Vec<Layer> = Vec::new();
let mut warnings: Vec<String> = Vec::new();
let mut gray_only = true;
let mut max = (1u32, 1u32);
let mut f16_seen = false;
@@ -239,8 +233,7 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result<ImportResult,
if img.sample_type() == SampleType::F16 {
f16_seen = true;
}
let (surface, mode) = layer_surface(&img, &mut max)?;
gray_only &= mode == ColorMode::Grayscale;
let surface = layer_surface(&img, &mut max)?;
layers.push(Layer::new(part_display_name(part), LayerContent::Raster(surface)));
}
for group in &chosen_groups {
@@ -251,14 +244,12 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result<ImportResult,
if img.sample_type() == SampleType::F16 {
f16_seen = true;
}
let (surface, mode) = layer_surface(&img, &mut max)?;
gray_only &= mode == ColorMode::Grayscale;
let surface = layer_surface(&img, &mut max)?;
layers.push(Layer::new(group.prefix.clone(), LayerContent::Raster(surface)));
}
if sel.precomp {
let layer = precomp_layer(bytes, &all_groups, &opts, &mut max, &mut warnings)?;
gray_only = false; // the precomp is an RGB layer by construction
layers.push(layer);
}
@@ -268,12 +259,10 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result<ImportResult,
if f16_seen {
warnings.push("16-bit float samples are stored as 32-bit float".to_string());
}
let mode = if gray_only { ColorMode::Grayscale } else { ColorMode::Rgb };
let mut doc = Document::new(name, Size::new(max.0, max.1), mode, DocSample::F32);
let mut doc = Document::new(name, Size::new(max.0, max.1), ColorMode::Rgb, DocSample::F32);
doc.layers = layers.into();
// OpenEXR holds linear, scene-referred values (Y is linear luminance): use the profile
// matching the selected parts' mode, as File › Open does.
doc.icc_profile = Some(if gray_only { craft_cms::builtin::linear_gray().to_bytes() } else { Builtin::LinearSrgb.profile().to_bytes() });
// OpenEXR holds linear, scene-referred values: tag them linear sRGB, as File › Open does.
doc.icc_profile = Some(Builtin::LinearSrgb.profile().to_bytes());
Ok(ImportResult { document: doc, warnings, source_read_only: false, preview_only: false })
}
@@ -334,7 +323,7 @@ fn precomp_layer(bytes: &[u8], all_groups: &[Group], opts: &DecodeOptions, max:
let img = Image::from_f32(w, h, ChannelLayout::Rgba, &out)?;
max.0 = max.0.max(w);
max.1 = max.1.max(h);
let (surface, _) = layer_surface(&img, max)?;
let surface = layer_surface(&img, max)?;
warnings.push("beauty (precomp) is the additive sum of the file's AOVs; alpha is the maximum coverage".to_string());
Ok(Layer::new("beauty (precomp)", LayerContent::Raster(surface)))
}
@@ -0,0 +1,135 @@
//! #14069: an EXR with only luminance or single data channels opens as an RGB 32-bit document
//! tagged linear sRGB, R = G = B = the file's value (above 1 kept), alpha kept; RGB files are
//! unchanged.
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::Document;
use photocraft_geom::Rect;
use photocraft_io::{ImportOptions, ImportResult, exr_parts, import, import_file};
use photocraft_raster::Interrupt;
const W: u32 = 32;
const H: u32 = 16;
/// A minimal uncompressed scanline EXR, `W` x `H`, FLOAT channels; each channel is `left` in
/// columns 0..16 and `right` in 16..32. Hand-written so channel names like `Z` are possible.
fn exr(channels: &[(&str, f32, f32)]) -> Vec<u8> {
let mut chans: Vec<&(&str, f32, f32)> = channels.iter().collect();
chans.sort_by_key(|c| c.0);
let mut out = vec![0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0];
let mut attr = |name: &str, kind: &str, value: &[u8]| {
out.extend(name.bytes().chain([0]).chain(kind.bytes()).chain([0]));
out.extend((value.len() as i32).to_le_bytes());
out.extend(value);
};
let mut chlist = Vec::new();
for (name, _, _) in &chans {
chlist.extend(name.bytes().chain([0]));
chlist.extend(2i32.to_le_bytes()); // FLOAT
chlist.extend([0, 0, 0, 0]); // pLinear + reserved
chlist.extend(1i32.to_le_bytes());
chlist.extend(1i32.to_le_bytes());
}
chlist.push(0);
let window: Vec<u8> = [0i32, 0, W as i32 - 1, H as i32 - 1].iter().flat_map(|v| v.to_le_bytes()).collect();
attr("channels", "chlist", &chlist);
attr("compression", "compression", &[0]);
attr("dataWindow", "box2i", &window);
attr("displayWindow", "box2i", &window);
attr("lineOrder", "lineOrder", &[0]);
attr("pixelAspectRatio", "float", &1f32.to_le_bytes());
attr("screenWindowCenter", "v2f", &[0; 8]);
attr("screenWindowWidth", "float", &1f32.to_le_bytes());
out.push(0);
let line_bytes = 4 * W as usize * chans.len();
let table_end = out.len() + 8 * H as usize;
for y in 0..H as usize {
out.extend(((table_end + y * (8 + line_bytes)) as u64).to_le_bytes());
}
for y in 0..H as i32 {
out.extend(y.to_le_bytes());
out.extend((line_bytes as i32).to_le_bytes());
for (_, left, right) in &chans {
for x in 0..W {
out.extend(if x < 16 { left } else { right }.to_le_bytes());
}
}
}
out
}
fn y_only() -> Vec<u8> {
exr(&[("Y", 0.7, 0.2)])
}
fn z_only() -> Vec<u8> {
exr(&[("Z", 5.0, 0.25)])
}
fn y_a() -> Vec<u8> {
exr(&[("Y", 0.7, 0.2), ("A", 1.0, 0.5)])
}
fn rgba() -> Vec<u8> {
exr(&[("R", 0.8, 0.1), ("G", 0.4, 0.1), ("B", 0.2, 0.1), ("A", 1.0, 0.5)])
}
/// File > Open: the file from disk.
fn open_file(tag: &str, bytes: &[u8]) -> ImportResult {
let path = std::env::temp_dir().join(format!("photocraft-14069-{tag}-{}.exr", std::process::id()));
std::fs::write(&path, bytes).unwrap();
let result = import_file("f.exr", &path, &ImportOptions::default(), &Interrupt::NONE);
let _ = std::fs::remove_file(&path);
result.unwrap()
}
/// File > Open EXR Parts... with every listed entry chosen.
fn open_parts(bytes: &[u8]) -> ImportResult {
let entries = exr_parts::entries(bytes).unwrap();
let selection = exr_parts::Selection { parts: entries.iter().map(|e| e.name.clone()).collect(), groups: vec![], view: "both".into(), precomp: false };
exr_parts::import("p", bytes, &selection).unwrap()
}
fn px(doc: &Document, x: i32, y: i32) -> Vec<f32> {
doc.layers[0].surface().unwrap().read_region(Rect::from_xywh(x, y, 1, 1))
}
/// RGB 32-bit, linear sRGB, (4,4) = `left`, (24,4) = `right` as RGBA.
fn assert_rgb(route: &str, r: &ImportResult, left: [f32; 4], right: [f32; 4]) {
let d = &r.document;
assert_eq!((d.mode, d.depth), (ColorMode::Rgb, SampleType::F32), "{route}: mode and depth");
assert_eq!(d.icc_profile, Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()), "{route}: linear sRGB, not linear gray");
assert_eq!(px(d, 4, 4), left, "{route}: left half");
assert_eq!(px(d, 24, 4), right, "{route}: right half");
}
#[test]
fn luminance_exr_opens_as_rgb_through_file_open() {
assert_rgb("Y File > Open", &open_file("y", &y_only()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 1.0]);
assert_rgb("Z File > Open", &open_file("z", &z_only()), [5.0, 5.0, 5.0, 1.0], [0.25, 0.25, 0.25, 1.0]);
assert_rgb("Y+A File > Open", &open_file("ya", &y_a()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 0.5]);
}
#[test]
fn luminance_and_data_exr_open_as_rgb_through_open_exr_parts() {
assert_rgb("Y parts", &open_parts(&y_only()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 1.0]);
assert_rgb("Z parts", &open_parts(&z_only()), [5.0, 5.0, 5.0, 1.0], [0.25, 0.25, 0.25, 1.0]);
assert_rgb("Y+A parts", &open_parts(&y_a()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 0.5]);
}
#[test]
fn rgba_exr_opens_as_before() {
let left = [0.8, 0.4, 0.2, 1.0];
let right = [0.1, 0.1, 0.1, 0.5];
assert_rgb("RGBA File > Open", &open_file("rgba", &rgba()), left, right);
assert_rgb("RGBA parts", &open_parts(&rgba()), left, right);
assert_rgb("RGBA bytes", &import("f.exr", &rgba()).unwrap(), left, right);
}
/// Open point: the whole-file decoder in `flat.rs` (the bytes import, and File > Open's
/// fallback for headers the band decoder refuses) still maps a gray EXR to Grayscale. That file
/// is outside this item's scope until the epic owner agrees.
#[test]
#[ignore = "flat.rs still opens gray EXRs as Grayscale (#14069 open point)"]
fn luminance_exr_opens_as_rgb_through_whole_file_decoder() {
assert_rgb("Y bytes", &import("f.exr", &y_only()).unwrap(), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 1.0]);
assert_rgb("Z bytes", &import("f.exr", &z_only()).unwrap(), [5.0, 5.0, 5.0, 1.0], [0.25, 0.25, 0.25, 1.0]);
assert_rgb("Y+A bytes", &import("f.exr", &y_a()).unwrap(), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 0.5]);
}
+33 -18
View File
@@ -4,7 +4,8 @@ use craft_cms::{Builtin, ColorSpace, Intent, Profile, Transform};
use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType as CodecSample};
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::Document;
use photocraft_io::{ExportOptions, ImportResult, export, exr_parts, import};
use photocraft_io::{ExportOptions, ImportOptions, ImportResult, export, exr_parts, import, import_file};
use photocraft_raster::Interrupt;
fn exr(layout: ChannelLayout, depth: CodecSample) -> Vec<u8> {
// Exactly representable in half precision, including negative and HDR luminance.
@@ -36,34 +37,48 @@ fn samples(doc: &Document) -> Vec<f32> {
doc.layers[0].surface().unwrap().read_region(doc.bounds())
}
/// File > Open of the file from disk (the band decoder).
fn opened(bytes: &[u8]) -> ImportResult {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("photocraft-exr-part-profile-{}-{n}.exr", std::process::id()));
std::fs::write(&path, bytes).unwrap();
let result = import_file("ordinary.exr", &path, &ImportOptions::default(), &Interrupt::NONE);
let _ = std::fs::remove_file(&path);
result.unwrap()
}
/// A gray part opens as RGB 32-bit linear sRGB like File > Open (#14069).
#[test]
fn selected_gray_exr_part_keeps_linear_profile_and_float_samples() {
for depth in [CodecSample::F16, CodecSample::F32] {
for layout in [ChannelLayout::Gray, ChannelLayout::GrayA] {
let bytes = exr(layout, depth);
let selected = selected_part(&bytes);
let ordinary = import("ordinary.exr", &bytes).unwrap();
let ordinary = opened(&bytes);
let doc = &selected.document;
assert_eq!((doc.mode, doc.depth), (ColorMode::Grayscale, SampleType::F32));
assert_eq!((doc.mode, doc.depth), (ColorMode::Rgb, SampleType::F32));
assert_eq!(doc.size, ordinary.document.size);
assert_eq!(selected.warnings, ordinary.warnings);
assert_eq!(selected.warnings.len(), usize::from(depth == CodecSample::F16));
let expected = codecs::decode(&bytes).unwrap().convert(ChannelLayout::GrayA, CodecSample::F32).to_f32_samples().unwrap();
assert_eq!(samples(doc), expected, "{layout:?} {depth:?}: samples and alpha stay unchanged");
let expected = codecs::decode(&bytes).unwrap().convert(ChannelLayout::Rgba, CodecSample::F32).to_f32_samples().unwrap();
assert_eq!(samples(doc), expected, "{layout:?} {depth:?}: gray in R, G and B; alpha unchanged");
assert_eq!(samples(doc), samples(&ordinary.document));
assert_eq!(doc.icc_profile, Some(craft_cms::builtin::linear_gray().to_bytes()), "{layout:?} {depth:?}: linear luminance");
assert_eq!(doc.icc_profile, Some(Builtin::LinearSrgb.profile().to_bytes()), "{layout:?} {depth:?}: linear light");
assert_eq!(doc.icc_profile, ordinary.document.icc_profile);
// The tagged samples convert to display gray, rather than being interpreted as sGray.
// The tagged samples convert to display sRGB, rather than being interpreted as sRGB.
let profile = Profile::parse(doc.icc_profile.as_deref().unwrap()).unwrap();
assert_eq!(profile.color_space, ColorSpace::Gray);
let transform = Transform::new(&profile, Builtin::SGray.profile(), Intent::RelativeColorimetric, false).unwrap();
assert_eq!(profile.color_space, ColorSpace::Rgb);
let transform = Transform::new(&profile, Builtin::Srgb.profile(), Intent::RelativeColorimetric, false).unwrap();
let mut display = samples(doc);
transform.apply(&mut display, 2).unwrap();
transform.apply(&mut display, 4).unwrap();
for i in [1, 2] {
let expected_gray = photocraft_color::convert::linear_to_srgb(expected[i * 2]);
assert!((display[i * 2] - expected_gray).abs() < 1e-4, "{layout:?} {depth:?}: display gray");
assert_eq!(display[i * 2 + 1], expected[i * 2 + 1], "alpha is not gamma encoded");
let expected_gray = photocraft_color::convert::linear_to_srgb(expected[i * 4]);
for c in 0..3 {
assert!((display[i * 4 + c] - expected_gray).abs() < 1e-4, "{layout:?} {depth:?}: display gray");
}
assert_eq!(display[i * 4 + 3], expected[i * 4 + 3], "alpha is not gamma encoded");
}
}
}
@@ -75,7 +90,7 @@ fn selected_gray_exr_part_exports_like_ordinary_import() {
for layout in [ChannelLayout::Gray, ChannelLayout::GrayA] {
let bytes = exr(layout, depth);
let selected = selected_part(&bytes).document;
let ordinary = import("ordinary.exr", &bytes).unwrap().document;
let ordinary = opened(&bytes).document;
for ext in ["exr", "tga"] {
let output = export(&selected, ext, &ExportOptions::default()).unwrap();
let control = export(&ordinary, ext, &ExportOptions::default()).unwrap();
@@ -83,15 +98,15 @@ fn selected_gray_exr_part_exports_like_ordinary_import() {
let control = codecs::decode(&control.bytes).unwrap();
assert_eq!(output.layout(), control.layout());
assert_eq!(output.to_normalized(), control.to_normalized(), "{layout:?} {depth:?} {ext}: same colours as File > Open");
let output = output.convert(ChannelLayout::GrayA, CodecSample::F32).to_f32_samples().unwrap();
let output = output.convert(ChannelLayout::Rgba, CodecSample::F32).to_f32_samples().unwrap();
let original = samples(&selected);
if ext == "exr" {
assert_eq!(output, original, "linear EXR samples, including negative/HDR and alpha, survive re-export");
} else {
for i in [1, 2] {
let expected = photocraft_color::convert::linear_to_srgb(original[i * 2]);
assert!((output[i * 2] - expected).abs() <= 1.0 / 255.0, "TGA uses display-encoded gray");
assert!((output[i * 2 + 1] - original[i * 2 + 1]).abs() <= 1.0 / 255.0, "TGA preserves alpha");
let expected = photocraft_color::convert::linear_to_srgb(original[i * 4]);
assert!((output[i * 4] - expected).abs() <= 1.0 / 255.0, "TGA uses display-encoded values");
assert!((output[i * 4 + 3] - original[i * 4 + 3]).abs() <= 1.0 / 255.0, "TGA preserves alpha");
}
}
}
+1
View File
@@ -24,6 +24,7 @@ mod deflate_compatibility;
mod effects_multi;
mod exif_resolution;
mod export_progress;
mod exr_open_luminance_rgb_tests;
mod exr_part_profile;
mod flat;
mod flat_export_renderer;
+14 -2
View File
@@ -4,8 +4,13 @@ use photocraft_raster::Interrupt;
use std::sync::atomic::{AtomicBool, Ordering};
fn fixture(layout: ChannelLayout, sample: SampleType, compression: ExrCompression) -> Vec<u8> {
fixture_as(layout, layout, sample, compression)
}
/// The `layout` fixture's samples written with the channels of `stored`.
fn fixture_as(layout: ChannelLayout, stored: ChannelLayout, sample: SampleType, compression: ExrCompression) -> Vec<u8> {
let values: Vec<f32> = (0..31 * 35 * layout.channels()).map(|i| [-0.25, 4.0, 0.0, 0.0001, 0.5][i % 5]).collect();
let image = Image::from_f32(31, 35, layout, &values).unwrap().convert(layout, sample);
let image = Image::from_f32(31, 35, layout, &values).unwrap().convert(stored, sample);
photocraft_codecs::encode(&image, Format::OpenExr, &EncodeOptions { exr_compression: compression, ..Default::default() }).unwrap()
}
@@ -22,7 +27,14 @@ fn native_scanline_import_preserves_hdr_document_and_cancels_without_publication
for compression in [ExrCompression::None, ExrCompression::Rle, ExrCompression::Zip1, ExrCompression::Zip16, ExrCompression::Piz] {
let bytes = fixture(layout, sample, compression);
std::fs::write(&path, &bytes).unwrap();
let reference = photocraft_io::import("HDR", &bytes).unwrap();
// Every EXR opens as RGB (#14069); the whole-file decoder still opens gray
// as Grayscale, so a gray file is compared with its RGB twin.
let rgb = match layout {
ChannelLayout::Gray => ChannelLayout::Rgb,
ChannelLayout::GrayA => ChannelLayout::Rgba,
other => other,
};
let reference = photocraft_io::import("HDR", &fixture_as(layout, rgb, sample, compression)).unwrap();
let actual = open(&path, &Interrupt::NONE).unwrap();
{
let a = &actual.document;
+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,
+14 -1
View File
@@ -37,7 +37,8 @@ fn fbm(x: f32, y: f32, size: f32, cells: i32, octaves: u32, salt: u64) -> f32 {
pub fn pattern(style: PatternStyle, size: u32, seed: u32) -> PatternImage {
let n = size.clamp(8, 1024) as usize;
let s = n as f32;
let salt = u64::from(seed) * 0x0100_0000_01B3 + 17;
// Seed hashing wraps so every u32 seed also works in checked builds.
let salt = u64::from(seed).wrapping_mul(0x0100_0000_01B3).wrapping_add(17);
let mut data = vec![0.0f32; n * n];
for y in 0..n {
for x in 0..n {
@@ -281,6 +282,18 @@ mod tests {
assert!(seam < 0.08, "{seam}");
}
#[test]
fn patterns_accept_full_seed_range() {
for seed in [0, 1, (1 << 24) - 1, 1 << 24, u32::MAX] {
for style in [PatternStyle::Noise, PatternStyle::Paper, PatternStyle::Canvas, PatternStyle::Dots] {
let p = pattern(style, 8, seed);
assert_eq!((p.width, p.height, p.data.len()), (8, 8, 64));
assert!(p.data.iter().all(|v| (0.0..=1.0).contains(v)), "{style:?} seed {seed}");
assert_eq!(p.data, pattern(style, 8, seed).data);
}
}
}
#[test]
fn tips_have_paint() {
for t in [
+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
}
+69 -60
View File
@@ -19,7 +19,7 @@ use craft::i18n::Direction;
use craft::keymap::Overrides;
use craft::theme::{AppDefaults, AppSizes, ComponentSet, ModeChoice, Size, SuiteChoice, ThemeId, ThemePair, resolve_sized};
use craft::theme_store::{SelectionChange, SuiteClient};
use craft::ui::contract::Tracked;
use craft::ui::contract::{MemoProps, Tracked};
use craft::ui::dialog::DialogHost;
use craft::ui::fonts::UiFonts;
use craft::ui::runtime::commands::{AppCatalog, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Fired, NavCommand};
@@ -546,97 +546,106 @@ impl Framework {
}
}
/// One source's command states.
pub(crate) type SourceStates = Vec<(CommandRef, CommandState)>;
/// The id a command source's states are derived under.
pub(crate) fn states_id(source: &'static str) -> egui::Id {
egui::Id::unique(("photocraft-states", source))
}
/// `build`'s states for `source`, derived from `facts`: the kept `Arc` while the facts are unchanged, else a new build.
/// The facts can hold only checked inputs, but nothing checks that they hold everything `build` reads: a read they
/// leave out keeps stale states, which the held-equals-fresh trial catches.
pub(crate) fn derived_states<K: MemoProps>(app: &PhotocraftApp, source: &'static str, facts: &K, build: impl FnOnce() -> SourceStates) -> Arc<SourceStates> {
craft::ui::runtime::derived::derived(app.ctx(), states_id(source), facts, build)
}
/// The states of a source that has no command states: one shared empty list, whatever the source's name.
pub(crate) fn no_states(app: &PhotocraftApp, _name: &'static str) -> Arc<SourceStates> {
derived_states(app, "none", &(), Vec::new)
}
/// A source's states for the coming frame, derived under the source's name ([`states_id`]) from what they read.
pub(crate) type StatesOf = fn(&PhotocraftApp, &'static str) -> Arc<SourceStates>;
/// One user of the framework's command sets: the states its commands show and the runner of the
/// ones it fires.
pub(crate) struct CommandSource {
/// The states of the source's commands for the coming frame.
states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>,
/// What `states` reads, for a source whose every input is a plain value or a revision that moves exactly when
/// the data changes: the states are computed again only when the key changes. `None`: computed every frame,
/// because what the source reads has no such revision yet.
key: Option<fn(&PhotocraftApp) -> StatesKey>,
/// The name the source's states are derived under.
pub(crate) name: &'static str,
/// The states of the source's commands.
pub(crate) states: StatesOf,
/// Runs `command` when it is this source's; whether it was.
run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool,
}
/// Every command source, in the order [`run_command`] tries them. The theme has no entry: it has
/// no command state, and its picks run through `menus::invoke`.
/// Every command source besides the panels' ([`crate::panels::registry::PANELS`], one source each), in the order
/// [`run_command`] tries them after the panels. The theme has no entry: it has no command state, and its picks run
/// through `menus::invoke`.
pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[
CommandSource { states: crate::panels::registry::states, key: None, run: crate::panels::registry::run_fired },
CommandSource { states: tool_states, key: Some(tool_states_key), run: run_tool },
CommandSource { states: crate::workspace_ui::states, key: None, run: crate::workspace_ui::run_fired },
CommandSource { states: crate::slice_ui::command_states, key: Some(crate::slice_ui::command_states_key), run: crate::slice_ui::run_fired },
CommandSource { states: crate::align_bar::command_states, key: None, run: crate::align_bar::run_fired },
CommandSource { states: crate::artboard_tool::command_states, key: Some(crate::artboard_tool::command_states_key), run: crate::artboard_tool::run_fired },
CommandSource { name: "tool", states: tool_states, run: run_tool },
CommandSource { name: "workspace", states: crate::workspace_ui::source_states, run: crate::workspace_ui::run_fired },
CommandSource { name: "slice", states: crate::slice_ui::source_states, run: crate::slice_ui::run_fired },
CommandSource { name: "align", states: crate::align_bar::source_states, run: crate::align_bar::run_fired },
CommandSource { name: "artboard", states: crate::artboard_tool::source_states, run: crate::artboard_tool::run_fired },
// Space+F: the pasteboard colour keys of the held Hand.
CommandSource { states: |_| Vec::new(), key: Some(|_| StatesKey::default()), run: crate::canvas_tool_menu::run_canvas_color },
CommandSource { name: "canvasColor", states: no_states, run: crate::canvas_tool_menu::run_canvas_color },
// The options bar's engine-command buttons: their commands run through `shortcuts::handle`.
CommandSource { states: crate::panels::options_bar::selection::command_states, key: None, run: |_, _, _| false },
CommandSource { name: "selection", states: crate::panels::options_bar::selection::source_states, run: |_, _, _| false },
];
/// The key of a [`CommandSource`]'s states: the plain values and exact revisions they are computed from, so equal
/// keys mean equal states.
pub(crate) type StatesKey = [u64; 4];
/// Every source by its name, with its states: the command sources, then the panels, each under its panel id. A later
/// source's state wins for a command two sources name.
pub(crate) fn sources() -> impl Iterator<Item = (&'static str, StatesOf)> {
let panels = crate::panels::registry::PANELS.iter().map(|panel| (panel.id, panel.states));
COMMAND_SOURCES.iter().map(|source| (source.name, source.states)).chain(panels)
}
/// The states each [`CommandSource`] last computed, by its place in [`COMMAND_SOURCES`], with their key, and the one
/// list of all of them the runtime reads.
/// Every source's states, in [`sources`]' order.
fn source_states(app: &PhotocraftApp) -> impl Iterator<Item = Arc<SourceStates>> + '_ {
sources().map(move |(name, states)| states(app, name))
}
/// The states each source last gave, in [`source_states`]' order, and the one list of all of them the runtime reads.
#[derive(Default)]
pub(crate) struct HeldStates {
kept: Vec<Option<KeptStates>>,
kept: Vec<Arc<SourceStates>>,
/// Every source's states, written only when one source's list changes: the runtime reads them again only when
/// the revision moves.
pub(crate) states: Tracked<CommandStates>,
/// How many times each source computed its states, for the count trials.
#[cfg(test)]
pub(crate) runs: Vec<usize>,
}
/// One source's states and the key they were computed at (`None` for a source without a key).
#[derive(Clone)]
struct KeptStates {
key: Option<StatesKey>,
states: Vec<(CommandRef, CommandState)>,
}
/// The tool commands: the current tool's row is checked.
fn tool_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> {
fn build_tool_states(app: &PhotocraftApp) -> SourceStates {
Tool::ALL.iter().map(|&tool| (CommandRef::from(crate::panels::tool_commands::command_of(tool)), CommandState::new().checked(app.ui.tool == tool))).collect()
}
/// What [`tool_states`] reads: the tool.
fn tool_states_key(app: &PhotocraftApp) -> StatesKey {
[app.ui.tool as u64, 0, 0, 0]
/// [`build_tool_states`], derived from the tool.
fn tool_states(app: &PhotocraftApp, name: &'static str) -> Arc<SourceStates> {
derived_states(app, name, &(app.ui.tool as u64), || build_tool_states(app))
}
/// Brings the held states up to date for the coming frame. A keyed source runs only when its key changed since it last
/// ran; a source without a key runs every frame. The held list is written only when a source's states differ from the
/// ones it last gave.
/// Brings the held states up to date for the coming frame. A source whose states are the `Arc` it last gave costs a
/// pointer compare; the held list is written only when a source's states differ by value from the ones it last gave.
fn command_states(app: &PhotocraftApp, held: &mut HeldStates) {
held.kept.resize(COMMAND_SOURCES.len(), None);
#[cfg(test)]
held.runs.resize(COMMAND_SOURCES.len(), 0);
let mut changed = false;
for (at, source) in COMMAND_SOURCES.iter().enumerate() {
let key = source.key.map(|key| key(app));
if key.is_some() && held.kept[at].as_ref().is_some_and(|kept| kept.key == key) {
continue;
}
#[cfg(test)]
{
held.runs[at] += 1;
}
let states = (source.states)(app);
match &mut held.kept[at] {
Some(kept) if kept.states == states => kept.key = key,
slot => {
*slot = Some(KeptStates { key, states });
for (at, states) in source_states(app).enumerate() {
match held.kept.get_mut(at) {
Some(kept) if Arc::ptr_eq(kept, &states) => {}
Some(kept) => {
changed |= **kept != *states;
*kept = states;
}
None => {
held.kept.push(states);
changed = true;
}
}
}
if changed {
let mut states = CommandStates::new();
for (command, state) in held.kept.iter().flatten().flat_map(|kept| &kept.states) {
for (command, state) in held.kept.iter().flat_map(|kept| kept.iter()) {
states.set(command.clone(), state.clone());
}
*held.states = states;
@@ -655,9 +664,9 @@ fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef)
true
}
/// Runs `command` through the first source that owns it; whether one did.
/// Runs `command` through the first source that owns it, the panels first; whether one did.
pub(crate) fn run_command(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool {
COMMAND_SOURCES.iter().any(|source| (source.run)(app, ctx, command))
crate::panels::registry::run_fired(app, ctx, command) || COMMAND_SOURCES.iter().any(|source| (source.run)(app, ctx, command))
}
impl PhotocraftApp {
@@ -1,18 +1,12 @@
//! Count trials: the command catalog, the keymap overrides and the keyed command states are built only when what
//! they read changes.
//! Count trials: the command catalog and the keymap overrides are built only when what they read changes.
use craft::automation::actions::ActionStep;
use serde_json::json;
use super::{COMMAND_SOURCES, PhotocraftApp};
use super::PhotocraftApp;
use crate::canvas::testing;
use crate::state::Tool;
/// The places of the keyed sources in [`COMMAND_SOURCES`].
const TOOL_SOURCE: usize = 1;
const SLICE_SOURCE: usize = 3;
const ARTBOARD_SOURCE: usize = 5;
fn app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
testing::frame(&mut app);
@@ -24,22 +18,6 @@ fn builds(app: &PhotocraftApp) -> (usize, usize) {
(app.framework.catalog_builds, app.framework.overrides_builds)
}
/// How many times each keyed command source computed its states, by its place in [`COMMAND_SOURCES`]; `None` for a
/// source that computes them every frame.
fn keyed_runs(app: &PhotocraftApp) -> Vec<Option<usize>> {
COMMAND_SOURCES.iter().zip(&app.framework.held_states.runs).map(|(source, &runs)| source.key.map(|_| runs)).collect()
}
/// The revision of the states the runtime reads.
fn held_revision(app: &PhotocraftApp) -> craft::ui::contract::Revision {
app.framework.held_states.states.revision()
}
/// The keyed sources that computed their states between `before` and `after`.
fn ran(before: &[Option<usize>], after: &[Option<usize>]) -> Vec<usize> {
before.iter().zip(after).enumerate().filter(|(_, (was, now))| was.is_some() && was != now).map(|(at, _)| at).collect()
}
fn frames(app: &mut PhotocraftApp, n: usize) {
for _ in 0..n {
testing::frame(app);
@@ -91,51 +69,3 @@ fn the_catalog_is_built_only_when_its_inputs_change() {
assert_eq!(builds(&app), (2, 3), "a step edit builds nothing");
assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog keeps its generation");
}
#[test]
fn keyed_command_states_run_only_when_their_key_changes() {
let mut app = app();
assert_eq!((COMMAND_SOURCES[TOOL_SOURCE].states)(&app).len(), Tool::ALL.len(), "TOOL_SOURCE names the tool commands");
let before = keyed_runs(&app);
assert!(before.iter().flatten().all(|&runs| runs == 1), "the first frame computes every keyed source once");
let revision = held_revision(&app);
frames(&mut app, 100);
assert_eq!(keyed_runs(&app), before, "idle frames compute no keyed source");
assert_eq!(held_revision(&app), revision, "idle frames write no states");
let other = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush };
crate::tool_memory::select(&mut app, other);
frames(&mut app, 2);
assert_ne!(held_revision(&app), revision, "a tool change writes the states");
let revision = held_revision(&app);
frames(&mut app, 10);
assert_eq!(held_revision(&app), revision, "the frames after the tool change write no states");
let after = keyed_runs(&app);
for (at, (was, now)) in before.iter().zip(&after).enumerate() {
let moved = usize::from(at == TOOL_SOURCE);
assert_eq!(now.map(|n| n - was.unwrap_or_default()), was.map(|_| moved), "source {at} after a tool change");
}
let before = keyed_runs(&app);
app.ui.artboard_tool.adding = true;
frames(&mut app, 2);
assert_eq!(ran(&before, &keyed_runs(&app)), [ARTBOARD_SOURCE], "the placing mode");
let before = keyed_runs(&app);
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
frames(&mut app, 2);
let after = keyed_runs(&app);
assert!(ran(&before, &after).contains(&SLICE_SOURCE) && ran(&before, &after).contains(&ARTBOARD_SOURCE), "a document opens");
let has_doc = |app: &PhotocraftApp| (COMMAND_SOURCES[ARTBOARD_SOURCE].states)(app)[0].1.is_enabled();
assert!(has_doc(&app));
let before = keyed_runs(&app);
app.ui.slices.selected = Some(1);
frames(&mut app, 2);
let selected = keyed_runs(&app);
assert_eq!(ran(&before, &selected), [SLICE_SOURCE], "the selected slice");
app.session.file_menu.slices_locked = true;
frames(&mut app, 2);
assert_eq!(ran(&selected, &keyed_runs(&app)), [SLICE_SOURCE], "the slice lock");
}
+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;
}
+84 -10
View File
@@ -659,6 +659,21 @@ fn a_secondary_canvas_hand_pans_while_a_transform_is_open() {
assert_eq!(box_key(&app), box_before, "the drag didn't touch the box");
}
/// The canvas can paint a batch as a nested list, which keeps its place in egui's final paint order.
fn flattened_paint_shapes(output: &egui::FullOutput) -> Vec<&egui::Shape> {
fn open<'a>(shape: &'a egui::Shape, into: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(list) => list.iter().for_each(|shape| open(shape, into)),
shape => into.push(shape),
}
}
let mut shapes = Vec::new();
for clipped in &output.shapes {
open(&clipped.shape, &mut shapes);
}
shapes
}
#[test]
fn guides_draw_over_the_transform_preview_and_under_its_box() {
// #5086: a guide crossing a layer under Free Transform was hidden behind the preview of
@@ -692,16 +707,7 @@ fn guides_draw_over_the_transform_preview_and_under_its_box() {
// At 100 % centred on the document, screen and document coordinates coincide.
let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0));
let near = |r: Rect| (r.min - layer.min).length() < 1.0 && (r.max - layer.max).length() < 1.0;
fn open<'a>(shape: &'a egui::Shape, into: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(list) => list.iter().for_each(|shape| open(shape, into)),
shape => into.push(shape),
}
}
let mut shapes = Vec::new();
for clipped in &out.shapes {
open(&clipped.shape, &mut shapes);
}
let shapes = flattened_paint_shapes(&out);
let position = |pred: &dyn Fn(&egui::Shape) -> bool| shapes.iter().position(|s| pred(s));
// The moving pixels: the mesh that spans the layer's box.
let preview = position(&|s| matches!(s, egui::Shape::Mesh(m) if near(m.calc_bounds())));
@@ -716,6 +722,74 @@ fn guides_draw_over_the_transform_preview_and_under_its_box() {
assert!(guide < frame, "the box ({frame}) draws over the guide ({guide})");
}
#[test]
fn marching_ants_draw_over_a_guide_on_the_selection_edge() {
use craft::behavior::kurbo::Point;
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let ctx = app.ctx().clone();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap();
app.run("view.newGuide", json!({"orientation": "vertical", "position": 100})).unwrap();
app.ui.tool = Tool::RectMarquee;
app.ui.extras.rulers = false;
app.ui.extras.grid = false;
app.ui.extras.guides = true;
app.ui.view.extras = true;
app.ui.view.show.canvas_guides = true;
app.ui.view.show.selection_edges = true;
app.sync_views();
let mut view = app.ui.views[0].clone();
view.zoom = 1.0;
view.center = [200.0, 150.0];
view.clear_pending();
let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0));
let draw = |app: &mut PhotocraftApp| {
let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() };
let mut output = ctx.run_ui(input, |ui| {
canvas_view(app, ui, CanvasHost::main(0), rect, view.clone(), true);
});
output.textures_delta.clear();
output
};
let output = draw(&mut app);
let shown = active_view(&app).expect("the canvas view");
let edge = Rect::from_two_pos(shown.to_screen(Point::new(100.0, 100.0)), shown.to_screen(Point::new(100.0, 160.0)));
let pixel = output.pixels_per_point.recip();
let is_guide = |shape: &egui::Shape| {
let egui::Shape::LineSegment { points, .. } = shape else { return false };
points.iter().all(|p| (p.x - edge.left()).abs() <= pixel)
&& points[0].y.min(points[1].y) < edge.top() - pixel
&& points[0].y.max(points[1].y) > edge.bottom() + pixel
};
let is_ants = |shape: &egui::Shape| {
let bounds = match shape {
egui::Shape::Mesh(mesh) => mesh.calc_bounds(),
egui::Shape::Rect(rect) => rect.rect,
egui::Shape::LineSegment { points, .. } => Rect::from_two_pos(points[0], points[1]),
_ => return false,
};
// A strip or dash on the selection edge, allowing for the framework's device-pixel snap.
bounds.height() > 0.0
&& bounds.width() <= 2.0 * pixel
&& (bounds.center().x - edge.left()).abs() <= pixel
&& bounds.top() >= edge.top() - pixel
&& bounds.bottom() <= edge.bottom() + 2.0 * pixel
};
let shapes = flattened_paint_shapes(&output);
let guide = shapes.iter().position(|shape| is_guide(shape)).expect("the guide spanning the selection");
let ants = shapes.iter().position(|shape| is_ants(shape)).expect("the ants along the left edge");
assert!(guide < ants, "the guide ({guide}) paints before the ants ({ants})");
app.ui.view.show.selection_edges = false;
let output = draw(&mut app);
let shapes = flattened_paint_shapes(&output);
assert!(shapes.iter().any(|shape| is_guide(shape)), "hiding selection edges leaves the guide");
assert!(!shapes.iter().any(|shape| is_ants(shape)), "the edge paint belongs to the ants");
}
#[test]
fn layer_style_dialog_previews_live_and_cancel_restores() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+3 -3
View File
@@ -21,7 +21,7 @@ pub(crate) fn show_frame(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui:
Some(app.canvas_tools.crop.tool.show_frame(ui, rect, &run.input(&ctx)))
}
/// Applies what the pass reported to the document and the crop options.
pub(crate) fn finish(app: &mut PhotocraftApp, output: CropOutput) {
crate::crop_ui::finish(app, output);
/// Applies what the pass reported while the live Crop tool is still held by the canvas rig.
pub(crate) fn finish(app: &mut PhotocraftApp, tool: &mut CropTool, output: CropOutput) {
crate::crop_ui::finish(app, tool, output);
}
+1 -1
View File
@@ -670,7 +670,7 @@ fn with_rig<R>(
if let Some(tool) = crop_tool {
tools.crop.tool = tool;
}
crop::finish(app, output);
crop::finish(app, &mut tools.crop.tool, output);
}
result
}
+147
View File
@@ -0,0 +1,147 @@
//! Count trials for the command states the runtime reads (#15709): every source's states are a value derived from
//! what they read, so an idle frame builds none, an edit builds only the sources that read what it changed, and the
//! held states always equal a fresh build of every source.
use craft::behavior::geometry::CropBox;
use craft::behavior::kurbo::Rect as DocRect;
use craft::ui::runtime::commands::{CommandRef, CommandStates};
use craft::ui::runtime::measure::last_frame_derived_builds;
use egui_kittest::Harness;
use serde_json::json;
use crate::PhotocraftApp;
use crate::app::framework::{sources, states_id};
use crate::state::Tool;
type H = Harness<'static, Box<PhotocraftApp>>;
/// The sources whose states follow the enable rules, which read the document, the session and the tool.
pub(crate) const RULES: [&str; 5] = ["align", "selection", "history", "layers", "channels"];
/// The app with one new document holding a pixel layer, settled.
fn harness() -> H {
harness_of(|s| {
s.execute("file.new", json!({"width": 200, "height": 100})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
})
}
/// The app with the session `open` makes, the Brush tool picked, settled.
fn harness_of(open: impl FnOnce(&mut photocraft_engine::Session) + 'static) -> H {
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut s = photocraft_engine::Session::new();
open(&mut s);
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), s, crate::Services::default());
app.ui.tool = Tool::Brush;
app
});
h.run_steps(8);
h
}
/// The sources the last frame built states for, in the framework's order.
fn built(h: &H) -> Vec<&'static str> {
let builds = last_frame_derived_builds(&h.ctx);
sources().map(|(name, _)| name).filter(|name| builds.iter().any(|(id, _)| *id == states_id(name))).collect()
}
/// Runs one frame after `change` and checks which sources it built.
fn builds_only(h: &mut H, what: &str, change: impl FnOnce(&mut PhotocraftApp), expected: &[&str]) {
h.run_steps(2);
change(h.state_mut());
h.run_steps(1);
let mut expected = expected.to_vec();
expected.sort_by_key(|source| sources().position(|(name, _)| name == *source));
assert_eq!(built(h), expected, "{what} builds only the sources that read it");
}
#[test]
fn an_idle_frame_builds_no_command_states() {
let mut h = harness();
for frame in 0..10 {
h.run_steps(1);
assert_eq!(built(&h), Vec::<&str>::new(), "idle frame {frame} builds no source");
}
}
#[test]
fn an_edit_builds_only_the_sources_that_read_it() {
let mut h = harness();
builds_only(
&mut h,
"the brush texture",
|app| {
let on = app.session.tools.brush.texture.enabled;
app.session.tools.brush.texture.enabled = !on;
},
&["brushSettings"],
);
builds_only(&mut h, "a tool", |app| crate::tool_memory::select(app, Tool::Hand), &[&["tool"][..], &RULES].concat());
builds_only(&mut h, "the artboard placing mode", |app| app.ui.artboard_tool.adding = true, &["artboard"]);
builds_only(&mut h, "the selected slice", |app| app.ui.slices.selected = Some(1), &["slice"]);
// View › Lock Slices reads the lock, so the rule-holding sources build with the slice states.
builds_only(&mut h, "the slice lock", |app| app.session.file_menu.slices_locked = true, &[&["slice"][..], &RULES].concat());
builds_only(
&mut h,
"a new layer",
|app| {
app.run("layer.new.layer", json!({})).unwrap();
},
&[&["slice"][..], &RULES].concat(),
);
}
#[test]
fn a_document_opening_builds_the_slice_and_artboard_states() {
let mut h = harness_of(|_| {});
h.run_steps(2);
h.state_mut().run("file.new", json!({"width": 64, "height": 64})).unwrap();
h.run_steps(1);
let built = built(&h);
assert!(built.contains(&"slice") && built.contains(&"artboard"), "a document opens: {built:?}");
let add_new = CommandRef::from(craft::draw::ui::artboard::ArtboardCommand::AddNew);
let artboard = h.state().framework.held_states.states.get(&add_new).cloned();
assert!(artboard.is_some_and(|state| state.is_enabled()), "Add New Artboard is on with a document");
}
/// Checks that every held state is the one its source builds afresh: the sources are asked again through a new context,
/// whose derived store is empty, so each builds from the app's state as it is now.
fn held_is_fresh(h: &mut H, step: &str) {
h.run_steps(2);
let app = h.state_mut();
let fresh = egui::Context::default();
PhotocraftApp::setup_context(&fresh, Default::default());
let own = std::mem::replace(&mut app.ctx, fresh);
let built: Vec<_> = sources().map(|(name, states)| (name, states(app, name))).collect();
app.ctx = own;
let mut held = (*app.framework.held_states.states).clone();
for (name, states) in built {
for (command, state) in states.iter() {
assert!(held.remove(command).as_ref() == Some(state), "after {step}, the {name} state of {command:?} is a fresh build");
}
}
assert!(held == CommandStates::new(), "after {step}, every held state has a source");
}
#[test]
fn the_held_command_states_equal_a_fresh_build_after_each_step() {
let mut h = harness();
held_is_fresh(&mut h, "settling");
crate::tool_memory::select(h.state_mut(), Tool::Move);
held_is_fresh(&mut h, "a tool");
h.state_mut().session.tools.brush.texture.enabled = true;
held_is_fresh(&mut h, "the brush texture");
h.state_mut().run("layer.new.layer", json!({})).unwrap();
held_is_fresh(&mut h, "a new layer");
h.state_mut().run("layer.layerMask.revealAll", json!({})).unwrap();
h.state_mut().ui.mask_target = true;
held_is_fresh(&mut h, "a mask target");
crate::workspace_ui::save(h.state_mut(), "Trial").unwrap();
held_is_fresh(&mut h, "a new workspace");
crate::tool_memory::select(h.state_mut(), Tool::Crop);
h.run_steps(2);
h.state_mut().canvas_tools.crop.tool.crop_to(CropBox::new(DocRect::new(10.0, 10.0, 100.0, 60.0), 0.0));
held_is_fresh(&mut h, "a pending crop");
assert!(crate::crop_ui::pending(h.state()), "the crop is pending");
}
+12 -2
View File
@@ -1362,7 +1362,8 @@ fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Reply {
let warnings = app.open_automation_bytes_with_approval(&name, &bytes, approved)?;
// Brushes/gradients go to the preset libraries: no document, no Open Recent entry.
if !crate::preset_files_ui::is_preset_file(&name) {
app.opened_from(path);
let recent = automation_location(app, path);
app.opened_from_listed(path, recent.as_deref());
if let Some(state) = app.session.active_mut()
&& state.path.is_some()
{
@@ -1373,6 +1374,13 @@ fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Reply {
}))
}
/// Where the file an automation open read is on disk, for Open Recent. The request path is
/// relative to an automation root, so it names nothing when the person reopens it from Open
/// Recent or Home; without a location the open is not listed there.
fn automation_location(app: &PhotocraftApp, path: &str) -> Option<String> {
app.services.automation_locate.as_ref().and_then(|locate| locate(path))
}
/// Directory .pcraft (the native on-disk form) loads through a capability-scoped
/// source; the single-file (zip) form falls back to the bytes path, as do all
/// other formats. `None` means "not a directory .pcraft".
@@ -1386,7 +1394,9 @@ fn open_pcraft_directory(app: &mut PhotocraftApp, path: &str) -> Option<Reply> {
app.session.add_document(doc, None);
// Recent files, but no save-back target: the capability writer
// replaces files, never directories.
app.push_recent(path);
if let Some(recent) = automation_location(app, path) {
app.push_recent(&recent);
}
app.sync_views();
app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &name)]);
app.ui.status_error = false;
+35 -3
View File
@@ -1198,6 +1198,34 @@ fn automation_save_passes_dds_options_without_asking() {
assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing");
}
#[test]
fn an_automation_open_without_a_location_is_not_listed_in_open_recent() {
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::Document;
use photocraft_geom::Size;
let services = crate::Services {
import: Some(Box::new(|name: &str, _b: &[u8], _opts: &photocraft_io::ImportOptions| {
Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new()))
})),
automation_read: Some(Box::new(|path: &str| {
Ok(crate::AutomationReadResult {
name: path.rsplit('/').next().unwrap_or(path).to_string(),
bytes: b"x".to_vec(),
save_path: Some(path.to_string()),
})
})),
..Default::default()
};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
let ctx = app.ctx().clone();
let r = call(&mut app, &ctx, "app.open", json!({"path": "shots/gk_25.png"}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("shots/gk_25.png"), "the save-back target stays the root-relative path");
// A root-relative path names no file for Open Recent or Home, so nothing is listed.
assert!(app.ui.recent_files.is_empty(), "{:?}", app.ui.recent_files);
}
#[test]
fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
use photocraft_color::{ColorMode, SampleType};
@@ -1234,6 +1262,7 @@ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
save_path: Some(path.to_string()),
})
})),
automation_locate: Some(Box::new(|path: &str| Some(format!("/work/{path}")))),
automation_write: Some(Box::new(move |path: &str, _b: &[u8]| {
w.borrow_mut().push(path.to_string());
Ok(())
@@ -1245,7 +1274,8 @@ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
assert_eq!(r["result"]["warnings"], json!(["Adjustment layer flattened"]), "{r}");
assert_eq!(r["result"]["name"], "warn.psd");
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("in/warn.psd"));
assert_eq!(*app.ui.recent_files, vec!["in/warn.psd".to_string()]);
// Open Recent lists where the file is, not the root-relative request path, which names nothing outside automation.
assert_eq!(*app.ui.recent_files, vec!["/work/in/warn.psd".to_string()]);
let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"}));
assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}");
assert_eq!(*written.borrow(), vec!["out.png".to_string()]);
@@ -1457,6 +1487,7 @@ fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() {
Err(format!("no such path: {path}"))
}
})),
automation_locate: Some(Box::new(|path: &str| Some(format!("/work/{path}")))),
..Default::default()
};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
@@ -1465,7 +1496,7 @@ fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() {
let r = call(&mut app, &ctx, "app.open", json!({"path": "native.pcraft"}));
assert_eq!(r["result"], json!({"path": "native.pcraft", "name": "native.pcraft", "warnings": []}), "{r}");
assert_eq!(app.session.active().unwrap().doc.name, "Native");
assert_eq!(*app.ui.recent_files, vec!["native.pcraft".to_string()], "the open is recorded in recent files");
assert_eq!(*app.ui.recent_files, vec!["/work/native.pcraft".to_string()], "the open is recorded in recent files, where it is on disk");
assert_eq!(app.session.active().unwrap().path, None, "no save-back target: the automation writer replaces files, never directories");
let r = call(&mut app, &ctx, "app.save", json!({}));
assert!(r["error"].as_str().unwrap().contains("pass `path`"), "an in-place save is refused up front: {r}");
@@ -2120,6 +2151,7 @@ fn automation_library_open_requires_explicit_save_as_before_implicit_save() {
save_path: path.starts_with("work/").then(|| path.to_owned()),
})
})),
automation_locate: Some(Box::new(|path: &str| Some(format!("/roots/{path}")))),
automation_write: Some(Box::new(move |path: &str, _: &[u8]| {
if path == "failed.psd" {
return Err("test write failure".into());
@@ -2135,7 +2167,7 @@ fn automation_library_open_requires_explicit_save_as_before_implicit_save() {
let opened = call(&mut app, &ctx, "app.open", json!({"path": "library/same.psd"}));
assert_eq!(opened["ok"], true, "{opened}");
assert_eq!(app.session.active().unwrap().path, None);
assert_eq!(*app.ui.recent_files, vec!["library/same.psd"]);
assert_eq!(*app.ui.recent_files, vec!["/roots/library/same.psd"]);
app.run("layer.new.layer", json!({"name": "edit"})).unwrap();
assert!(app.session.active().unwrap().is_dirty());
let refused = call(&mut app, &ctx, "app.save", json!({}));
@@ -16,6 +16,18 @@ fn asked(bits: Option<u8>) -> Vec<u8> {
serde_json::to_vec(&bits).unwrap()
}
/// Records the Targa options on each write without encoding or touching the filesystem.
fn targa_writes(app: &mut PhotocraftApp) -> Writes {
let writes: Writes = Rc::default();
let written = writes.clone();
app.services.export = Some(Box::new(|_, _, settings| Ok((asked(settings.tga_bits.map(TgaBits::bits)), Vec::new()))));
app.services.write = Some(Box::new(move |path, bytes| {
written.borrow_mut().push((path.to_string(), bytes.to_vec()));
Ok(())
}));
writes
}
/// One 8×8 RGB document (with an "Alpha 1" channel when `alpha_channel`) whose exports record
/// their Targa bits, in a harness running the dialogs and answering a save dialog with `to`.
fn targa_app(alpha_channel: bool, to: &str) -> (Prompted, Writes) {
@@ -24,13 +36,7 @@ fn targa_app(alpha_channel: bool, to: &str) -> (Prompted, Writes) {
app.run("select.all", json!({})).unwrap();
app.run("select.saveSelection", json!({})).unwrap();
}
let writes: Writes = Rc::default();
let written = writes.clone();
app.services.export = Some(Box::new(|_, _, settings| Ok((asked(settings.tga_bits.map(TgaBits::bits)), Vec::new()))));
app.services.write = Some(Box::new(move |path, bytes| {
written.borrow_mut().push((path.to_string(), bytes.to_vec()));
Ok(())
}));
let writes = targa_writes(&mut app);
let h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).with_context(app.ctx().clone()).build_ui_state(
|ui, app| {
crate::dialogs::run(app, ui);
@@ -76,6 +82,43 @@ fn targa_options_writes_the_choice_or_cancels() {
assert_eq!(writes.borrow().as_slice(), &[("t.tga".to_string(), asked(Some(24)))]);
}
/// With the real window key handling running, Targa Options owns the first Escape.
#[test]
fn escape_cancels_targa_options_before_deselecting() {
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_max_steps(64).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro());
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
app
});
let writes = targa_writes(h.state_mut());
h.run_steps(4);
h.state_mut().run("select.all", json!({})).unwrap();
let st = h.state().session.active().unwrap();
let (selection, history) = (st.doc.selection.clone().expect("Select All created a selection"), st.history.past_len());
h.state_mut().save_as(Some("t.tga".into())).unwrap();
h.run_steps(2);
assert_eq!(parked(&h), Some(("t.tga".to_string(), false)));
let dialog = h.state().framework.dialogs.open_dialogs().last().expect("Targa Options is open").id;
h.key_press(Key::Escape);
h.run_steps(4);
assert!(h.state().framework.dialogs.get_dyn(dialog).is_none(), "Escape closes Targa Options");
assert!(parked(&h).is_none(), "Escape cancels the parked save");
assert!(writes.borrow().is_empty(), "the cancelled save writes nothing");
let st = h.state().session.active().unwrap();
assert_eq!(st.path, None, "the cancelled save leaves the document unsaved");
assert_eq!(st.doc.selection.as_ref(), Some(&selection), "the dialog's Escape leaves the selection intact");
assert_eq!(st.history.past_len(), history, "the dialog's Escape leaves document history intact");
h.key_press(Key::Escape);
h.run_steps(4);
let st = h.state().session.active().unwrap();
assert!(st.doc.selection.is_none(), "once the dialog is gone, Escape reaches the window and deselects");
assert_eq!(st.history.past_len(), history + 1, "only the second Escape edits the document");
}
/// Scripts choose with `tgaBits` and are never asked; a grayscale Targa (8-bit, nothing to choose)
/// and other formats aren't asked either.
#[test]
+24
View File
@@ -109,6 +109,30 @@ fn a_plane_and_ok_paste_in_one_step() {
assert!(l.rgba(230, 20)[0] < 0.5, "outside the plane");
}
#[test]
fn vanishing_point_cancel_leaves_pending_paste_unapplied() {
let mut app = app_with_layer();
copy_red_square(&mut app);
let st = app.session.active().unwrap();
let (original, steps, revision) = (st.doc.clone(), st.history.past_len(), st.revision);
let mut h = open(app);
set(&mut h, json!({"planes": [floor()]}));
let pending = describe(h.state()).expect("Vanishing Point is open");
assert_eq!(pending["paste"].as_array().map(Vec::len), Some(1), "OK would paste onto the plane");
let dialog = h.state().vanishing.as_ref().unwrap().dialog;
let ctx = h.ctx.clone();
crate::control::dialogs::workspace_ui(h.state_mut(), &ctx, VP, &json!({"cancel": true})).unwrap();
h.run_steps(4);
let app = h.state();
assert!(app.framework.dialogs.get_dyn(dialog).is_none(), "Cancel closes the dialog");
assert!(app.vanishing.is_none(), "Cancel drops the workspace");
let st = app.session.active().unwrap();
assert_eq!(st.doc, original, "Cancel leaves the document unchanged");
assert_eq!((st.history.past_len(), st.revision), (steps, revision), "Cancel does not edit the document or its history");
}
#[test]
fn a_torn_wall_and_clone_strokes_are_one_step_and_preview_on_the_source() {
let mut app = app_with_layer();
+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}));
+170
View File
@@ -0,0 +1,170 @@
//! Count trials for the documents the session holds in a `Tracked` (#15709): a job that applies to a document in the
//! background moves only that document's revision and builds nothing keyed on the active one, an idle frame and a
//! preference write that keeps the history limits move no document's revision, and a view-only write that leaves the
//! edit revision alone still moves the tracked one and rebuilds what shows it.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use craft::ui::runtime::measure::last_frame_derived_builds;
use egui_kittest::Harness;
use photocraft_engine::channel_cmds::ChannelTarget;
use photocraft_engine::jobs::Started;
use serde_json::json;
use crate::PhotocraftApp;
use crate::app::framework::states_id;
type H = Harness<'static, Box<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 `builds` built the value derived under `id`.
fn count(builds: &[(egui::Id, u32)], id: egui::Id) -> u32 {
builds.iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum()
}
/// How many times the last frame built the value derived under `id`.
fn builds(h: &H, id: egui::Id) -> u32 {
count(&last_frame_derived_builds(&h.ctx), id)
}
/// Runs `frames` frames and gives every build they made, frame after frame.
fn builds_over(h: &mut H, frames: usize) -> Vec<(egui::Id, u32)> {
let mut all = Vec::new();
for _ in 0..frames {
h.run_steps(1);
all.extend(last_frame_derived_builds(&h.ctx));
}
all
}
/// The command sources that hold the active document.
const DOCUMENT_SOURCES: [&str; 6] = ["slice", "align", "selection", "history", "layers", "channels"];
/// Every open document's `Tracked` revision.
fn revisions(h: &H) -> Vec<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();
// Builds are summed over a few frames, so one a frame late counts too.
let job_frames = builds_over(&mut h, 4);
let after = revisions(&h);
assert_ne!(after[0], before[0], "the job's apply moves A's revision");
assert_eq!(after[1], before[1], "and leaves B's");
assert_eq!(count(&job_frames, crate::panels::layers_tree::model_id()), 0, "B's Layers model builds nothing");
assert_eq!(count(&job_frames, states_id("slice")), 0, "B's slice states build nothing");
// The job's end and Edit › Fade's document are rule inputs: the menu model and each rule-holding source build once.
assert_eq!(count(&job_frames, crate::menus::model_id()), 1, "the job's apply and end build the menu model once");
for source in crate::command_state_trials::RULES {
assert_eq!(count(&job_frames, states_id(source)), 1, "the job's apply and end build the {source} states once");
}
let idle = builds_over(&mut h, 4);
assert_eq!(count(&idle, crate::menus::model_id()), 0, "the frames after the job build no menu model");
assert_eq!(count(&idle, crate::panels::layers_tree::model_id()), 0, "the frames after the job build no Layers model");
for (name, _) in crate::app::framework::sources() {
assert_eq!(count(&idle, states_id(name)), 0, "the frames after the job build no {name} states");
}
h.state_mut().session.set_active(0);
h.run_steps(1);
assert_eq!(builds(&h, crate::panels::layers_tree::model_id()), 1, "switching to A builds its Layers model once");
for source in DOCUMENT_SOURCES {
assert_eq!(builds(&h, states_id(source)), 1, "switching to A builds the {source} states once");
}
}
#[test]
fn an_idle_frame_moves_no_documents_revision() {
let mut h = harness();
h.state_mut().run("window.toggle.history", json!({"show": true})).unwrap();
h.state_mut().run("window.toggle.navigator", json!({"show": true})).unwrap();
h.run_steps(8);
let settled = revisions(&h);
for frame in 0..10 {
h.run_steps(1);
assert_eq!(revisions(&h), settled, "idle frame {frame} moves no document's revision");
}
}
#[test]
fn a_preference_write_that_keeps_the_history_limits_moves_no_documents_revision() {
let mut h = harness();
let settled = revisions(&h);
let on = h.state().session.prefs().script_events.enabled;
h.state_mut().session.edit_prefs(|prefs| prefs.script_events.enabled = !on);
assert_eq!(revisions(&h), settled, "a preference write that keeps the history limits moves no document's revision");
let states = h.state().session.prefs().performance.history_states;
h.state_mut().session.edit_prefs(|prefs| prefs.performance.history_states = states + 1);
assert!(revisions(&h).iter().zip(&settled).all(|(now, was)| now != was), "a new history limit moves every document's revision");
}
#[test]
fn targeting_a_mask_over_colour_rows_rebuilds_the_channels_states() {
let mut h = harness();
h.state_mut().run("layer.layerMask.revealAll", json!({})).unwrap();
h.state_mut().session.active_mut().unwrap().channel_view.target = ChannelTarget::Color(0);
h.run_steps(4);
let st = h.state().session.active_tracked().unwrap();
let (edits, tracked) = (st.revision, st.revision());
h.state_mut().target_mask_over_colour_rows();
let st = h.state().session.active_tracked().unwrap();
assert_eq!(st.channel_view.target, ChannelTarget::LayerMask, "the mask is the target");
assert_eq!(st.revision, edits, "a view change is no edit step");
assert_ne!(st.revision(), tracked, "but it moves the tracked revision views key on");
h.run_steps(1);
assert_eq!(builds(&h, states_id("channels")), 1, "the Channels states follow it");
}
+10 -1
View File
@@ -230,6 +230,13 @@ impl PhotocraftApp {
/// Record that the active document was just opened from `path`: File › Save writes back to it
/// (unless it's a template or derivative preview) and it goes to the top of Open Recent.
pub(crate) fn opened_from(&mut self, path: &str) {
self.opened_from_listed(path, Some(path));
}
/// [`Self::opened_from`], with `recent` the path Open Recent lists for it (`None`: not listed).
/// An automation open is requested by a root-relative path, which names nothing outside
/// automation, so it lists where the file is on disk instead.
pub(crate) fn opened_from_listed(&mut self, path: &str, recent: Option<&str>) {
if !is_template(path)
&& let Some(st) = self.session.active_mut()
&& !st.source_read_only
@@ -238,7 +245,9 @@ impl PhotocraftApp {
let doc = st.doc.id;
self.remember_stamp(doc, path);
}
self.push_recent(path);
if let Some(recent) = recent {
self.push_recent(recent);
}
}
/// The name a file called `name` opens under: its own, or the first free "Untitled-N" for a
+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)
}
}
+10 -6
View File
@@ -707,17 +707,20 @@ fn run_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Fired) {
// The Delete key is Edit › Clear, or deletes the layers when nothing is selected (`delete_key_command`).
let id = if id == EditCommands::Delete.id() { "edit.clear" } else { id };
let id = clip_key_command(app, delete_key_command(app, id.to_string()));
dispatch_as(app, ctx, &id, f.alt_variant);
// A key that runs another command (Delete, the clip keys) runs it without the fired command's parameters.
let command = if id == f.command.id { f.command.clone() } else { CommandRef::new(id) };
dispatch_as(app, ctx, &command, f.alt_variant);
}
/// Run a shortcut's command like its menu item (dialogs included), or say why it can't run.
pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) {
dispatch_as(app, ctx, id, false);
dispatch_as(app, ctx, &CommandRef::new(id), false);
}
/// [`dispatch`]; with `last`, an adjustment dialog opens at its last confirmed settings and New Layer makes the
/// layer without its dialog.
fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: bool) {
/// [`dispatch`] of a fired command, its parameters included (an Appearance or Language row's choice); with `last`, an
/// adjustment dialog opens at its last confirmed settings and New Layer makes the layer without its dialog.
fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef, last: bool) {
let id = command.id.as_str();
let action = id.strip_prefix(crate::actions::SHORTCUT_PREFIX);
let command_id = if action.is_some() { "actions.play" } else { id };
// A key saved for an action that was since deleted or renamed names no action.
@@ -746,7 +749,8 @@ fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: boo
let opened = if last { crate::adjust_dialog::open_last(app, id) } else { crate::adjust_dialog::open(app, id) };
opened.map(|_| serde_json::Value::Null)
} else {
crate::menus::invoke(app, ctx, id, json!({}))
let params = if command.params.is_null() { json!({}) } else { command.params.clone() };
crate::menus::invoke(app, ctx, id, params)
};
match r {
Ok(_) => Outcome::Ran,
+9 -7
View File
@@ -236,11 +236,11 @@ pub(crate) use services::SAVE_OPTIONS_OPEN;
#[cfg(test)]
pub(crate) use services::saved_revision_after_write;
pub use services::{
AdoptAutosaveFn, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationServices, AutomationWriteFn,
AutosaveFn, AutosaveResultsFn, CapsLockFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn,
ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn,
Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, RecoverFn, Recoverable, RightButtonDownFn,
SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
AdoptAutosaveFn, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationLocateFn, AutomationOpenPcraftFn, AutomationReadFn,
AutomationServices, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn,
CursorPosFn, DiscardAutosaveFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp,
FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, RecoverFn,
Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
};
pub(crate) use services::{opaque_layer, saves_flat_in_place};
pub use text::cjk_fonts;
@@ -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`).
@@ -950,8 +948,12 @@ mod brush_settle_trials;
#[cfg(test)]
mod chrome_settle_trials;
#[cfg(test)]
mod command_state_trials;
#[cfg(test)]
mod doc_revision_trials;
#[cfg(test)]
mod doc_tracked_trials;
#[cfg(test)]
mod drag_settle_trials;
#[cfg(test)]
mod layer_thumb_bounds_tests;
+29
View File
@@ -6,6 +6,7 @@
use craft::ui::runtime::measure::{MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_key_bytes};
use egui::{Event, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT as _, Queryable as _};
use serde_json::json;
use crate::PhotocraftApp;
@@ -156,3 +157,31 @@ fn the_held_menu_model_equals_a_fresh_build_after_each_step() {
h.state_mut().session.saved_to("/tmp/Renamed.psd".into());
held_is_fresh(&mut h, "a save that renames the document");
}
#[test]
fn the_status_bar_sits_inside_the_window_when_its_views_run_and_replay() {
let mut h = harness(1, 0, 0);
let screen = h.ctx.content_rect();
// The status bar's zoom field: the lowest node named Zoom that shows the percentage as its value.
let field = |h: &H| {
h.query_all_by_label("Zoom")
.filter(|n| {
let a = n.accesskit_node();
a.role() != egui::accesskit::Role::Slider && a.value().is_some() && a.bounding_box().is_some()
})
.map(|n| n.rect())
.max_by(|a, b| a.bottom().total_cmp(&b.bottom()))
};
// A settled frame replays the bar's views; a status message runs its body again.
for step in ["settled", "a status message"] {
if step == "a status message" {
h.state_mut().ui.status = "Saved".into();
}
h.run_steps(2);
let Some(field) = field(&h) else { panic!("{step}: the status bar shows its zoom field") };
assert!(
field.bottom() <= screen.bottom() && field.top() >= screen.bottom() - 40.0,
"{step}: the zoom field {field:?} sits in the status bar inside the window {screen:?}, not moved down past its edge"
);
}
}
+3
View File
@@ -109,6 +109,9 @@ pub(crate) const DOCUMENT_ITEM: &str = "window.document.";
#[cfg(test)]
mod tests;
#[cfg(test)]
mod appearance_menu_trials;
#[cfg(test)]
mod open_recent_position_tests;
@@ -0,0 +1,118 @@
//! The Appearance and Language menus in the whole app: a pick changes the theme the framework draws with and the
//! language, whether it comes from a click on the in-window bar or from the macOS menu, which fires the row's command.
//! Both menus work with or without a document open.
use craft::keymap::CommandRef;
use craft::menu::{LANGUAGE_COMMAND, ThemeChoice};
use craft::ui::runtime::commands::{FireSource, fire};
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{AccessKitNode, Queryable};
use crate::PhotocraftApp;
use crate::theme::AppTheme;
/// The whole app, empty or with one document open.
fn harness(document: bool) -> Harness<'static, Box<PhotocraftApp>> {
let mut session = photocraft_engine::Session::new();
if document {
session.execute("file.new", serde_json::json!({"width": 64, "height": 48})).unwrap();
}
crate::shortcut_dispatch::tests::app_harness(PhotocraftApp::new(session, crate::Services::default()))
}
/// The theme the framework's root takes each frame (`frame_input`) and the panel fill the theme installs.
fn shown(h: &Harness<'_, Box<PhotocraftApp>>) -> (String, bool, egui::Color32) {
let theme = &h.state().ui.theme;
(theme.id().as_str().to_string(), theme.is_dark(), h.ctx.global_style().visuals.panel_fill)
}
/// Classic in light mode: a light theme of its own row, unlike the dark theme the app starts with.
fn classic() -> (AppTheme, ThemeChoice) {
let theme = AppTheme::classic();
let choice = ThemeChoice::theme(theme.id().clone(), false);
(theme, choice)
}
/// Runs the frames that take a fired command and show its result.
fn settle(h: &mut Harness<'_, Box<PhotocraftApp>>) {
h.run_steps(6);
}
/// The centre of the top-most menu title or row labelled `label`.
fn top(h: &Harness<'_, Box<PhotocraftApp>>, label: &str) -> egui::Pos2 {
let named = |node: &AccessKitNode<'_>| {
node.label().as_deref() == Some(label) && matches!(node.role(), Role::MenuItem | Role::MenuItemRadio | Role::MenuItemCheckBox)
};
let node = h.get_all_by(named).min_by(|a, b| a.rect().min.y.total_cmp(&b.rect().min.y)).unwrap_or_else(|| panic!("no menu row {label}"));
node.rect().center()
}
/// Moves the pointer over the top-most node labelled `label`.
fn hover_top(h: &mut Harness<'_, Box<PhotocraftApp>>, label: &str) {
let at = top(h, label);
h.event(egui::Event::PointerMoved(at));
settle(h);
}
/// Clicks the top-most node labelled `label` with the pointer, a frame for the press and one for the release.
fn click_top(h: &mut Harness<'_, Box<PhotocraftApp>>, label: &str) {
let at = top(h, label);
h.event(egui::Event::PointerMoved(at));
h.step();
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
h.step();
}
settle(h);
}
/// Asserts the app shows Classic light after a pick, with the panel fill it installs.
fn assert_classic(h: &Harness<'_, Box<PhotocraftApp>>, before: &(String, bool, egui::Color32), document: bool) {
let (theme, _) = classic();
let after = shown(h);
assert_eq!((after.0.as_str(), after.1), (theme.id().as_str(), false), "document {document}; status: {}", h.state().ui.status);
assert_ne!(after.2, before.2, "document {document}: the panels take the theme's fill");
assert_eq!(after.2, theme.tokens().chrome, "document {document}");
}
#[test]
fn a_theme_fired_from_the_menu_shows_it() {
for document in [true, false] {
let mut h = harness(document);
let (theme, choice) = classic();
let before = shown(&h);
assert_ne!(before.0, theme.id().as_str(), "the app starts on another theme");
assert!(fire(&h.ctx.clone(), choice.command(), FireSource::Menu), "the runtime takes the menu's theme row");
settle(&mut h);
assert_classic(&h, &before, document);
}
}
#[test]
fn a_theme_clicked_in_the_window_menu_shows_it() {
for document in [true, false] {
let mut h = harness(document);
let (theme, _) = classic();
let before = shown(&h);
click_top(&mut h, "Window");
hover_top(&mut h, "Appearance");
let name = h.state().framework.theme_name(theme.id(), false);
click_top(&mut h, &name);
assert_classic(&h, &before, document);
}
}
#[test]
fn a_language_fired_from_the_menu_is_saved() {
// A language other than English where the build has the catalogs; English (from Automatic) where it has only that.
let code = crate::i18n::Lang::all().map(crate::i18n::Lang::code).find(|code| *code != "en").unwrap_or("en");
for document in [true, false] {
let mut h = harness(document);
assert_eq!(h.state().session.prefs().interface.language, "auto");
let row = CommandRef::with_params(LANGUAGE_COMMAND, serde_json::json!({"lang": code}));
assert!(fire(&h.ctx.clone(), row, FireSource::Menu), "the runtime takes the menu's language row");
settle(&mut h);
assert_eq!(h.state().session.prefs().interface.language, code, "document {document}; status: {}", h.state().ui.status);
}
}
+74 -36
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;
@@ -18,10 +19,19 @@ pub(crate) struct MenuFacts<'a> {
language: &'static str,
/// The keymap's overrides and catalog generations: the rows show its chords.
keymap: (u64, u64),
rules: RuleFacts<'a>,
prefs: PrefFacts<'a>,
shown: ShownFacts<'a>,
}
/// What the enable rules read ([`super::is_enabled`], `Session::is_enabled`): the documents, the session and the shell
/// state they ask about. A command source whose states follow the rules holds these; the menu model holds them with
/// what its rows show.
#[derive(MemoProps)]
pub(crate) struct RuleFacts<'a> {
documents: Documents<'a>,
session: SessionFacts,
prefs: PrefFacts<'a>,
ui: UiFacts<'a>,
ui: UiRuleFacts<'a>,
}
/// The open documents and the active one.
@@ -31,10 +41,9 @@ struct Documents<'a> {
generation: u64,
active_generation: u64,
active_index: Option<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.
@@ -65,6 +74,8 @@ struct SessionFacts {
actions: (u64, Option<(usize, usize)>, u8),
/// Edit › Undo's label when it undoes an Actions library change.
undo_label: Option<&'static str>,
/// The installed plug-ins' revision: a plug-in's menu item needs it installed.
plugins: u64,
}
/// The preferences the rows show.
@@ -81,9 +92,9 @@ struct PrefFacts<'a> {
favorite_themes: &'a Vec<String>,
}
/// The shell's state the rows show.
/// The shell's state the rules read.
#[derive(MemoProps)]
struct UiFacts<'a> {
struct UiRuleFacts<'a> {
tool: u64,
/// The open Free Transform: its undo steps' and phase's revision, Content-Aware Scale, its layer count and a
/// running commit.
@@ -101,6 +112,19 @@ struct UiFacts<'a> {
/// a brush resize.
modal: (usize, bool, Option<&'static str>, bool, bool),
selected_guide: bool,
/// Save, Paste and Place Embedded ask which services this platform has: export, the clipboard image and files.
services: (bool, bool, bool),
/// The locked workspace greys the panel commands that move, float or close panels.
workspaces_locked: bool,
/// Window › Arrange: the docked and floating document windows.
document_windows: (usize, usize),
/// File › Automate › Batch: an action is selected in the Actions panel.
batch_action: bool,
}
/// The shell's state the rows show beside the rules: ticks, labels and the lists they name.
#[derive(MemoProps)]
struct ShownFacts<'a> {
extras: crate::state::Extras,
view: &'a crate::view_cmds::ViewOptions,
/// The options, status, menu and contextual task bars.
@@ -113,25 +137,55 @@ struct UiFacts<'a> {
ticks: Arc<Vec<bool>>,
recent_files: &'a Tracked<Vec<String>>,
workspaces: &'a Tracked<crate::workspace_ui::Workspaces>,
/// Save and Paste rules ask which services this platform has.
services: (bool, bool),
}
impl<'a> MenuFacts<'a> {
/// The facts of `app`'s current state.
pub(crate) fn of(app: &'a PhotocraftApp) -> MenuFacts<'a> {
let s = &app.session;
let active = s.active();
let prefs = s.prefs();
let prefs = app.session.prefs();
let ui = &app.ui;
MenuFacts {
language: crate::i18n::current().code(),
keymap: app.framework.keymap_inputs(),
rules: RuleFacts::of(app),
prefs: PrefFacts {
language: &prefs.interface.language,
hidden: &prefs.menus.hidden,
colors: &prefs.menus.colors,
show_menu_colors: prefs.interface.show_menu_colors,
quick_export: prefs.export.quick_export_format.name(),
font_preview: prefs.type_.font_preview.name(),
generator: prefs.plug_ins.generator_enabled,
appearance: prefs.interface.appearance_mode.name(),
favorite_themes: &prefs.interface.favorite_themes,
},
shown: ShownFacts {
extras: ui.extras,
view: &ui.view,
bars: (ui.panels.options_bar, ui.panels.status_bar, ui.panels.menu_bar, ui.panels.context_task_bar),
palette: ui.palette.open,
theme: (ui.theme.id().as_str(), ui.theme.is_dark()),
arrangement: ui.document_windows.arrangement,
ticks: window_ticks(app),
recent_files: &ui.recent_files,
workspaces: &app.workspaces,
},
}
}
}
impl<'a> RuleFacts<'a> {
/// What the rules read in `app`'s current state.
pub(crate) fn of(app: &'a PhotocraftApp) -> RuleFacts<'a> {
let s = &app.session;
let active = s.active();
let ui = &app.ui;
RuleFacts {
documents: Documents {
generation: s.documents_generation(),
active_generation: s.active_generation(),
active_index: s.active_index(),
active: active.map(|d| (d.doc.id, d.revision)),
active: s.active_tracked(),
jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)),
smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)),
fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)),
@@ -150,19 +204,9 @@ impl<'a> MenuFacts<'a> {
mask_targeted: s.tools.mask_targeted,
actions: (s.actions.list.revision(), s.actions.recording, s.actions.playing),
undo_label: crate::actions::library::edit_undo_label(app),
plugins: photocraft_plugins::registry::revision(),
},
prefs: PrefFacts {
language: &prefs.interface.language,
hidden: &prefs.menus.hidden,
colors: &prefs.menus.colors,
show_menu_colors: prefs.interface.show_menu_colors,
quick_export: prefs.export.quick_export_format.name(),
font_preview: prefs.type_.font_preview.name(),
generator: prefs.plug_ins.generator_enabled,
appearance: prefs.interface.appearance_mode.name(),
favorite_themes: &prefs.interface.favorite_themes,
},
ui: UiFacts {
ui: UiRuleFacts {
tool: ui.tool as u64,
transform: ui
.transform
@@ -181,16 +225,10 @@ impl<'a> MenuFacts<'a> {
app.brush_resize.active(),
),
selected_guide: crate::guide_select::selected(app).is_some(),
extras: ui.extras,
view: &ui.view,
bars: (ui.panels.options_bar, ui.panels.status_bar, ui.panels.menu_bar, ui.panels.context_task_bar),
palette: ui.palette.open,
theme: (ui.theme.id().as_str(), ui.theme.is_dark()),
arrangement: ui.document_windows.arrangement,
ticks: window_ticks(app),
recent_files: &ui.recent_files,
workspaces: &app.workspaces,
services: (app.services.export.is_some(), app.services.clipboard_get_image.is_some()),
services: (app.services.export.is_some(), app.services.clipboard_get_image.is_some(), app.services.files.is_some()),
workspaces_locked: app.workspaces.set.locked,
document_windows: (ui.document_windows.docked.len(), ui.document_windows.floating.len()),
batch_action: crate::actions::selected_action(app).is_some(),
},
}
}
+4
View File
@@ -1,3 +1,5 @@
use craft::menu::{LANGUAGE_COMMAND, THEME_COMMAND};
use super::invoke::{panel_alias, proof_preset, workspace_id};
use super::{DOCUMENT_ITEM, PhotocraftApp, Value};
@@ -72,6 +74,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
i if crate::links::url_for(i).is_some() => true,
// Interface brightness works with or without a document, as in Photoshop.
"view.darkenInterface" | "view.lightenInterface" => true,
// Appearance and Language rows: the theme and the language change with or without a document.
THEME_COMMAND | LANGUAGE_COMMAND => true,
"file.save" | "file.saveAs" | "file.export.exportAs" | "file.export.quickExportAsPng" => {
app.session.active().is_some() && app.services.export.is_some()
}
@@ -211,6 +211,42 @@ fn command_dialogs_open_and_refuse() {
assert!(app.ui.views.is_empty() && app.session.documents().is_empty());
}
/// Fit Image's dialog bounds apply before the command, where a zero side would mean unconstrained.
#[test]
fn fit_image_validates_dialog_bounds_before_one_undoable_resize() {
let (mut app, ctx) = app_with(1);
let id = open_form(&mut app, &ctx, "file.automate.fitImage");
let opening = fields(&app, id);
let original = app.session.active().unwrap();
let (size, steps, revision) = (original.doc.size, original.history.past_len(), original.revision);
for key in ["width", "height"] {
for value in [json!(0), json!(300_001), json!("abc")] {
assert!(app.framework.dialogs.set_json_field(&ctx, id, key, value.clone()).is_err(), "{key} accepted {value}");
assert_eq!(fields(&app, id), opening);
}
}
set(&mut app, &ctx, id, "width", json!(1));
set(&mut app, &ctx, id, "height", json!(300_000));
let accepted = fields(&app, id);
assert_eq!(accepted["width"].as_f64(), Some(1.0));
assert_eq!(accepted["height"].as_f64(), Some(300_000.0));
set(&mut app, &ctx, id, "width", json!(80));
set(&mut app, &ctx, id, "height", json!(40));
let staged = app.session.active().unwrap();
assert_eq!((staged.doc.size, staged.history.past_len(), staged.revision), (size, steps, revision));
confirm(&mut app, &ctx, id).unwrap();
let resized = app.session.active().unwrap();
assert_eq!((resized.doc.size.width, resized.doc.size.height), (50, 40));
assert_eq!(resized.history.past_len(), steps + 1);
assert_eq!(resized.history.undo_label(), Some("Image Size"));
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.active().unwrap().doc.size, size);
}
#[test]
fn data_sets_as_files_enablement_respects_target_platform() {
let (app, _) = app_with(1);
+5
View File
@@ -321,6 +321,11 @@ pub fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> {
workspace_states(&app.workspaces.set).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect()
}
/// [`states`], derived from the workspaces.
pub fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc<crate::app::framework::SourceStates> {
crate::app::framework::derived_states(app, name, &app.workspaces, || states(app))
}
// ---------------------------------------------------------------------------------------------------------------
// Menu commands.
// ---------------------------------------------------------------------------------------------------------------
+25
View File
@@ -52,6 +52,31 @@ pub(crate) fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> {
.collect()
}
/// What [`states`] reads: the list, the menu's facts and the panel's state.
#[derive(craft::ui::contract::MemoProps)]
struct StatesFacts<'a> {
list: u64,
recording: bool,
path_selected: bool,
waiting: bool,
tool_recording: bool,
panel: &'a craft::automation::ui::actions::ActionsPanelState,
}
/// [`states`], derived from [`StatesFacts`].
pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc<crate::app::framework::SourceStates> {
let menu = facts(app);
let facts = StatesFacts {
list: app.session.actions.list.revision(),
recording: menu.recording,
path_selected: menu.path_selected,
waiting: menu.waiting,
tool_recording: menu.tool_recording,
panel: &app.ui.actions.panel,
};
crate::app::framework::derived_states(app, name, &facts, || states(app))
}
/// Runs a fired command of the Actions panel; `false` for a command of another set. Its event goes through the one
/// mapping that every Actions event takes.
pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool {
+5
View File
@@ -224,6 +224,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta
]
}
/// [`command_states`], derived from the brush.
pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc<crate::app::framework::SourceStates> {
crate::app::framework::derived_states(app, name, &app.session.tools.brush, || command_states(app))
}
/// Runs a fired menu command; false for a command this panel does not own.
pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool {
let Some(command) = BrushSettingsCommand::from_ref(command) else { return false };

Some files were not shown because too many files have changed in this diff Show More