Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Layer Style: complete multi-instance effects and dialog parity (#157) (#786)

Remidesboisb436950ae313
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs
index e8eb2b70e..33e83bb52 100644
--- a/crates/compose/src/effects.rs
+++ b/crates/compose/src/effects.rs
@@ -394,6 +394,35 @@ fn apply_lut(m: Map, l: Option<Vec<f32>>) -> Map {
}
}
+/// Deterministic per-pixel value in 0..=1, hashed from document coordinates
+/// (the same hash as the GPU's `dissolve_noise`), so the speckle is stable
+/// across renders, frames and tiles.
+pub fn hash_noise(x: i64, y: i64) -> f32 {
+ let mut h = (x as i32 as u32).wrapping_mul(0x8da6_b343) ^ (y as i32 as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9;
+ h ^= h >> 15;
+ h = h.wrapping_mul(0x2c1b_3c6d);
+ h ^= h >> 12;
+ (h & 0xffff) as f32 / 65536.0
+}
+
+/// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage,
+/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched.
+fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) {
+ if !amount.is_finite() || amount <= 0.0 {
+ return;
+ }
+ for y in 0..m.h {
+ for x in 0..m.w {
+ let v = &mut m.v[y * m.w + x];
+ if *v <= 0.0 {
+ continue;
+ }
+ let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32));
+ *v = (*v + (n - 0.5) * 2.0 * amount).clamp(0.0, 1.0);
+ }
+ }
+}
+
fn apply_contour(m: Map, c: &Contour) -> Map {
match contour_lut(c) {
None => m,
@@ -528,7 +557,7 @@ pub fn spread_split(size: f32, spread: f32) -> (f32, f32) {
((size * spread).round(), size * (1.0 - spread))
}
-fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool) -> Map {
+fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool, origin: (i32, i32)) -> Map {
let angle = if s.use_global_light { light.angle } else { s.angle };
let (dx, dy) = offset(angle, s.distance);
let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() };
@@ -537,6 +566,7 @@ fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool) -> Map
m = dilate(&m, r);
blur(&mut m, bw);
let mut m = apply_contour(m, &s.contour);
+ noise(&mut m, s.noise, origin.0, origin.1);
if inner {
for (v, a) in m.v.iter_mut().zip(&shape.v) {
*v *= a;
@@ -545,7 +575,7 @@ fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool) -> Map
m
}
-fn glow_map(shape: &Map, g: &Glow, inner: bool) -> Map {
+fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) -> Map {
let src = if inner {
match g.source {
GlowSource::Edge => shape.clone().map(|a| 1.0 - a),
@@ -582,6 +612,7 @@ fn glow_map(shape: &Map, g: &Glow, inner: bool) -> Map {
}
};
m = apply_lut(m, glow_lut(g));
+ noise(&mut m, g.noise, origin.0, origin.1);
if inner {
for (v, a) in m.v.iter_mut().zip(&shape.v) {
*v *= a;
@@ -1095,10 +1126,10 @@ pub(crate) fn build_maps_prepared(
.iter()
.enumerate()
.map(|(i, e)| match e {
- Effect::DropShadow(s) => vec![shadow_map(&shape, s, light, false)],
- Effect::InnerShadow(s) => vec![shadow_map(&shape, s, light, true)],
- Effect::OuterGlow(g) => vec![glow_map(&shape, g, false)],
- Effect::InnerGlow(g) => vec![glow_map(&shape, g, true)],
+ Effect::DropShadow(s) => vec![shadow_map(&shape, s, light, false, (rect.x0, rect.y0))],
+ Effect::InnerShadow(s) => vec![shadow_map(&shape, s, light, true, (rect.x0, rect.y0))],
+ Effect::OuterGlow(g) => vec![glow_map(&shape, g, false, (rect.x0, rect.y0))],
+ Effect::InnerGlow(g) => vec![glow_map(&shape, g, true, (rect.x0, rect.y0))],
Effect::Satin(s) => vec![satin_map(&shape, s)],
Effect::BevelEmboss(b) => {
let (maps, paint) = bevel_maps(&shape, b, light, tex, patterns);
@@ -1790,4 +1821,76 @@ mod tests {
let (dx, dy) = offset(120.0, 10.0);
assert_eq!((dx, dy), (5.0, 9.0));
}
+
+ fn square_shape(n: usize) -> Map {
+ let mut m = Map::new(n, n, 0.0);
+ for y in 5..n - 5 {
+ for x in 5..n - 5 {
+ m.v[y * n + x] = 1.0;
+ }
+ }
+ m
+ }
+
+ fn shadow(noise: f32, origin: (i32, i32)) -> Map {
+ let s = Shadow {
+ common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0),
+ color: photocraft_color::Color::BLACK,
+ angle: 0.0,
+ use_global_light: false,
+ distance: 0.0,
+ spread: 0.0,
+ size: 6.0,
+ contour: Contour::Linear,
+ anti_alias: false,
+ noise,
+ knocks_out: true,
+ };
+ shadow_map(&square_shape(40), &s, &GlobalLight::default(), false, origin)
+ }
+
+ #[test]
+ fn shadow_noise_speckles_soft_coverage_deterministically() {
+ let plain = shadow(0.0, (0, 0));
+ let noisy = shadow(0.5, (0, 0));
+ let again = shadow(0.5, (0, 0));
+ let (mut diff, mut identical) = (0.0f32, true);
+ for i in 0..plain.v.len() {
+ diff += (plain.v[i] - noisy.v[i]).abs();
+ if noisy.v[i] != again.v[i] {
+ identical = false;
+ }
+ }
+ assert!(diff > 5.0, "noise changes the soft band: {diff}");
+ assert!(identical, "same coords, same speckle");
+ // Every value stays a coverage.
+ assert!(noisy.v.iter().all(|v| (0.0..=1.0).contains(v)));
+ // The speckle moves with the document origin, not the tile.
+ let moved = shadow(0.5, (100, 100));
+ assert_ne!(noisy.v, moved.v, "hashed from document coordinates");
+ // Full noise can punch holes even in the solid part.
+ let heavy = shadow(1.0, (0, 0));
+ assert!(heavy.v.iter().any(|v| *v < 0.5) && heavy.v.iter().any(|v| *v > 0.5), "heavy noise spans the range",);
+ }
+
+ #[test]
+ fn glow_noise_follows_the_contour_and_range() {
+ let g = |noise: f32| Glow {
+ common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0),
+ paint: FxPaint::Color(photocraft_color::Color::WHITE),
+ technique: GlowTechnique::Softer,
+ spread: 0.0,
+ size: 6.0,
+ contour: Contour::Linear,
+ anti_alias: false,
+ range: 0.5,
+ jitter: 0.0,
+ noise,
+ source: GlowSource::Edge,
+ };
+ let plain = glow_map(&square_shape(40), &g(0.0), false, (0, 0));
+ let noisy = glow_map(&square_shape(40), &g(0.6), false, (0, 0));
+ let diff: f32 = plain.v.iter().zip(&noisy.v).map(|(a, b)| (a - b).abs()).sum();
+ assert!(diff > 5.0, "glow noise changes the coverage: {diff}");
+ }
}
diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs
index c6251cc0e..07e944c0b 100644
--- a/crates/engine/src/layer_style.rs
+++ b/crates/engine/src/layer_style.rs
@@ -1,6 +1,7 @@
//! `layer.layerStyle.*` commands: add/replace layer effects on a layer.
use photocraft_color::{BlendMode, Color};
+use photocraft_doc::adjust::CurvePoint;
use photocraft_doc::{
Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Satin, Shadow, StrokeFx,
StrokePosition,
@@ -8,6 +9,7 @@ use photocraft_doc::{
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
+use crate::presets::{always, bad};
use crate::{EngineError, Result, Session};
/// Parses a gradient style name (`linear`, `radial`, `angle`, `reflected`, `diamond`).
@@ -27,25 +29,29 @@ fn f(p: &Value, k: &str, d: f32) -> f32 {
fn b(p: &Value, k: &str, d: bool) -> bool {
p.get(k).and_then(Value::as_bool).unwrap_or(d)
}
-fn color(p: &Value, k: &str, d: [f32; 3]) -> Color {
- let c = match p.get(k) {
- Some(Value::Array(a)) if a.len() >= 3 => [0, 1, 2].map(|i| a[i].as_f64().unwrap_or(0.0) as f32),
+fn f_of(p: &Value, k: &str) -> Option<f32> {
+ p.get(k).and_then(Value::as_f64).map(|v| v as f32)
+}
+fn b_of(p: &Value, k: &str) -> Option<bool> {
+ p.get(k).and_then(Value::as_bool)
+}
+fn color_of(p: &Value, k: &str) -> Option<Color> {
+ match p.get(k) {
+ Some(Value::Array(a)) if a.len() >= 3 => {
+ Some(Color::rgb(a[0].as_f64().unwrap_or(0.0) as f32, a[1].as_f64().unwrap_or(0.0) as f32, a[2].as_f64().unwrap_or(0.0) as f32))
+ }
Some(Value::String(s)) => {
let s = s.trim_start_matches('#');
let h = |i: usize| s.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0);
- if s.len() >= 6 { [h(0), h(2), h(4)] } else { d }
+ (s.len() >= 6).then_some(Color::rgb(h(0), h(2), h(4)))
}
- _ => d,
- };
- Color::rgb(c[0], c[1], c[2])
-}
-fn common(p: &Value, blend: BlendMode, opacity: f32) -> FxCommon {
- FxCommon {
- enabled: b(p, "enabled", true),
- blend: p.get("blend").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(blend),
- opacity: (f(p, "opacity", opacity * 100.0) / 100.0).clamp(0.0, 1.0),
+ _ => None,
}
}
+fn color(p: &Value, k: &str, d: [f32; 3]) -> Color {
+ let c = color_of(p, k).map_or(d, |c| c.to_rgb());
+ Color::rgb(c[0], c[1], c[2])
+}
fn gradient(p: &Value) -> Gradient {
Gradient {
stops: vec![(0.0, color(p, "from", [0.0; 3])), (1.0, color(p, "to", [1.0; 3]))],
@@ -57,120 +63,481 @@ fn gradient(p: &Value) -> Gradient {
}
}
-/// Builds an effect of `kind` from JSON params (Photoshop units: opacity,
-/// spread, range in percent; sizes in px; angles in degrees).
-pub fn effect_from_params(kind: &str, p: &Value) -> Option<Effect> {
- let shadow = |blend: BlendMode, inner: bool| Shadow {
- common: common(p, blend, 0.75),
- color: color(p, "color", [0.0; 3]),
- angle: f(p, "angle", 120.0),
- use_global_light: b(p, "useGlobalLight", true),
- distance: f(p, "distance", 5.0),
- spread: f(p, if inner { "choke" } else { "spread" }, 0.0) / 100.0,
- size: f(p, "size", 5.0),
+/// Factory defaults for each effect kind, in the command's parameter units
+/// (what the Layer Style dialog starts a new effect from).
+pub fn effect_defaults(kind: &str) -> Value {
+ match kind {
+ "dropShadow" => {
+ json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "spread": 0, "size": 5, "contour": "Linear", "noise": 0, "knocksOut": true})
+ }
+ "innerShadow" => {
+ json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "choke": 0, "size": 5, "contour": "Linear", "noise": 0})
+ }
+ "outerGlow" => json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "spread": 0, "size": 5, "range": 50, "contour": "Linear", "noise": 0}),
+ "innerGlow" => json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "source": "edge", "choke": 0, "size": 5, "contour": "Linear", "noise": 0}),
+ "stroke" => json!({"size": 3, "position": "outside", "blend": "Normal", "opacity": 100, "color": "#000000"}),
+ "colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}),
+ "gradientOverlay" => {
+ json!({"blend": "Normal", "opacity": 100, "from": "#000000", "to": "#ffffff", "reverse": false, "style": "linear", "angle": 90, "scale": 100})
+ }
+ "patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}),
+ "bevelEmboss" => {
+ json!({"style": "inner", "depth": 100, "direction": "up", "size": 5, "soften": 0, "angle": 120, "useGlobalLight": true, "altitude": 30})
+ }
+ "satin" => json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 19, "distance": 11, "size": 14, "invert": true}),
+ _ => json!({}),
+ }
+}
+
+/// Built-in contour presets (our own transfer curves; imported PSD contours keep
+/// their own points). Points are (input, output) in 0..=1, sorted by input.
+pub const CONTOURS: &[(&str, &[(f32, f32)])] = &[
+ ("Linear", &[(0.0, 0.0), (1.0, 1.0)]),
+ ("Cone", &[(0.0, 0.0), (0.5, 1.0), (1.0, 1.0)]),
+ ("Cone (Inverted)", &[(0.0, 1.0), (0.5, 0.0), (1.0, 0.0)]),
+ ("Domed", &[(0.0, 0.0), (0.25, 1.0), (0.75, 1.0), (1.0, 0.0)]),
+ ("Domed (Inverted)", &[(0.0, 1.0), (0.25, 0.0), (0.75, 0.0), (1.0, 1.0)]),
+ ("Diagonal (Descending)", &[(0.0, 1.0), (1.0, 0.0)]),
+];
+
+/// The built-in contour called `name` (`Linear` is the identity); `None` for
+/// names we don't ship, so imported contours are carried rather than clobbered.
+pub fn builtin_contour(name: &str) -> Option<Contour> {
+ if name.eq_ignore_ascii_case("Linear") {
+ return Some(Contour::Linear);
+ }
+ CONTOURS.iter().skip(1).find(|(n, _)| *n == name).map(|(n, pts)| Contour::Custom {
+ name: (*n).to_string(),
+ points: pts.iter().map(|(input, output)| CurvePoint { input: *input, output: *output }).collect(),
+ })
+}
+
+/// The param naming a contour (`"Linear"` or a preset/custom contour's name).
+pub fn contour_param(c: &Contour) -> Value {
+ match c {
+ Contour::Linear => json!("Linear"),
+ Contour::Custom { name, .. } => json!(name),
+ }
+}
+
+/// An effect of `kind` with its factory settings (before params are applied).
+fn fresh_effect(kind: &str) -> Option<Effect> {
+ let shadow = |inner: bool| Shadow {
+ common: FxCommon::new(BlendMode::Multiply, 0.75),
+ color: Color::BLACK,
+ angle: 120.0,
+ use_global_light: true,
+ distance: 5.0,
+ spread: 0.0,
+ size: 5.0,
contour: Contour::Linear,
anti_alias: false,
- noise: f(p, "noise", 0.0) / 100.0,
- knocks_out: !inner && b(p, "knocksOut", true),
+ noise: 0.0,
+ knocks_out: !inner,
};
- let glow = |inner: bool| Glow {
- common: common(p, BlendMode::Screen, 0.75),
- paint: FxPaint::Color(color(p, "color", [1.0, 1.0, 190.0 / 255.0])),
- technique: if p.get("technique").and_then(Value::as_str) == Some("precise") { GlowTechnique::Precise } else { GlowTechnique::Softer },
- spread: f(p, if inner { "choke" } else { "spread" }, 0.0) / 100.0,
- size: f(p, "size", 5.0),
+ let glow = || Glow {
+ common: FxCommon::new(BlendMode::Screen, 0.75),
+ paint: FxPaint::Color(Color::rgb(1.0, 1.0, 190.0 / 255.0)),
+ technique: GlowTechnique::Softer,
+ spread: 0.0,
+ size: 5.0,
contour: Contour::Linear,
anti_alias: false,
- range: f(p, "range", 50.0) / 100.0,
+ range: 0.5,
jitter: 0.0,
noise: 0.0,
- source: if p.get("source").and_then(Value::as_str) == Some("center") { GlowSource::Center } else { GlowSource::Edge },
+ source: GlowSource::Edge,
};
Some(match kind {
- "dropShadow" => Effect::DropShadow(shadow(BlendMode::Multiply, false)),
- "innerShadow" => Effect::InnerShadow(shadow(BlendMode::Multiply, true)),
- "outerGlow" => Effect::OuterGlow(glow(false)),
- "innerGlow" => Effect::InnerGlow(glow(true)),
+ "dropShadow" => Effect::DropShadow(shadow(false)),
+ "innerShadow" => Effect::InnerShadow(shadow(true)),
+ "outerGlow" => Effect::OuterGlow(glow()),
+ "innerGlow" => Effect::InnerGlow(glow()),
"stroke" => Effect::Stroke(StrokeFx {
- common: common(p, BlendMode::Normal, 1.0),
- size: f(p, "size", 3.0),
- position: match p.get("position").and_then(Value::as_str) {
- Some("inside") => StrokePosition::Inside,
- Some("center") => StrokePosition::Center,
- _ => StrokePosition::Outside,
- },
- paint: if p.get("from").is_some() { FxPaint::Gradient(gradient(p)) } else { FxPaint::Color(color(p, "color", [1.0, 0.0, 0.0])) },
+ common: FxCommon::new(BlendMode::Normal, 1.0),
+ size: 3.0,
+ position: StrokePosition::Outside,
+ paint: FxPaint::Color(Color::rgb(1.0, 0.0, 0.0)),
}),
- "colorOverlay" => Effect::ColorOverlay { common: common(p, BlendMode::Normal, 1.0), color: color(p, "color", [1.0, 0.0, 0.0]) },
- "gradientOverlay" => Effect::GradientOverlay { common: common(p, BlendMode::Normal, 1.0), gradient: gradient(p), dither: false },
- // `name` carries the requested pattern key; `set_effect` resolves it (pattern_cmds).
+ "colorOverlay" => Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(1.0, 0.0, 0.0) },
+ "gradientOverlay" => Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false },
"patternOverlay" => Effect::PatternOverlay {
- common: common(p, BlendMode::Normal, 1.0),
- name: p.get("pattern").and_then(Value::as_str).unwrap_or("").to_string(),
+ common: FxCommon::new(BlendMode::Normal, 1.0),
+ name: String::new(),
id: String::new(),
- scale: (f(p, "scale", 100.0) / 100.0).clamp(0.01, 10.0),
- angle: f(p, "angle", 0.0),
- link: b(p, "link", true),
- phase: (f(p, "phaseX", 0.0), f(p, "phaseY", 0.0)),
+ scale: 1.0,
+ angle: 0.0,
+ link: true,
+ phase: (0.0, 0.0),
},
"satin" => Effect::Satin(Satin {
- common: common(p, BlendMode::Multiply, 0.5),
- color: color(p, "color", [0.0; 3]),
- angle: f(p, "angle", 19.0),
- distance: f(p, "distance", 11.0),
- size: f(p, "size", 14.0),
+ common: FxCommon::new(BlendMode::Multiply, 0.5),
+ color: Color::BLACK,
+ angle: 19.0,
+ distance: 11.0,
+ size: 14.0,
contour: Contour::Linear,
anti_alias: true,
- invert: b(p, "invert", true),
+ invert: true,
}),
"bevelEmboss" => Effect::BevelEmboss(Bevel {
- enabled: b(p, "enabled", true),
- style: match p.get("style").and_then(Value::as_str) {
- Some("outer") => BevelStyle::OuterBevel,
- Some("emboss") => BevelStyle::Emboss,
- Some("pillow") => BevelStyle::PillowEmboss,
- Some("stroke") => BevelStyle::StrokeEmboss,
- _ => BevelStyle::InnerBevel,
- },
- technique: match p.get("technique").and_then(Value::as_str) {
- Some("chiselHard") => BevelTechnique::ChiselHard,
- Some("chiselSoft") => BevelTechnique::ChiselSoft,
- _ => BevelTechnique::Smooth,
- },
- depth: f(p, "depth", 100.0) / 100.0,
- up: p.get("direction").and_then(Value::as_str) != Some("down"),
- size: f(p, "size", 5.0),
- soften: f(p, "soften", 0.0),
- angle: f(p, "angle", 120.0),
- altitude: f(p, "altitude", 30.0),
- use_global_light: b(p, "useGlobalLight", true),
+ enabled: true,
+ style: BevelStyle::InnerBevel,
+ technique: BevelTechnique::Smooth,
+ depth: 1.0,
+ up: true,
+ size: 5.0,
+ soften: 0.0,
+ angle: 120.0,
+ altitude: 30.0,
+ use_global_light: true,
gloss_contour: Contour::Linear,
highlight: FxCommon::new(BlendMode::Screen, 0.75),
highlight_color: Color::WHITE,
shadow: FxCommon::new(BlendMode::Multiply, 0.75),
shadow_color: Color::BLACK,
- contour: b(p, "contour", false).then(|| photocraft_doc::BevelContour {
- contour: Contour::Linear,
- range: (f(p, "contourRange", 50.0) / 100.0).clamp(0.01, 1.0),
- anti_alias: false,
- }),
- texture: p.get("texture").and_then(Value::as_str).filter(|t| !t.is_empty()).map(|t| photocraft_doc::BevelTexture {
- name: t.to_string(),
- id: t.to_string(),
- scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0),
- depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0),
- invert: b(p, "textureInvert", false),
- link: b(p, "textureLink", true),
- phase: (0.0, 0.0),
- }),
+ contour: None,
+ texture: None,
}),
_ => return None,
})
}
+/// Edits an existing gradient in place: only the end colours and geometry.
+/// Intermediate stops, opacity stops, alignment and offset survive a round trip.
+fn overlay_gradient(g: &mut Gradient, p: &Value) {
+ if let Some(c) = color_of(p, "from")
+ && let Some(first) = g.stops.first_mut()
+ {
+ first.1 = c;
+ }
+ if let Some(c) = color_of(p, "to")
+ && let Some(last) = g.stops.last_mut()
+ {
+ last.1 = c;
+ }
+ if let Some(s) = p.get("style").and_then(Value::as_str) {
+ g.style = gradient_style(s);
+ }
+ if let Some(x) = f_of(p, "angle") {
+ g.angle = x;
+ }
+ if let Some(x) = f_of(p, "scale") {
+ g.scale = (x / 100.0).clamp(0.01, 10.0);
+ }
+ if let Some(x) = b_of(p, "reverse") {
+ g.reverse = x;
+ }
+}
+
+/// Applies the params present in `p` onto an existing effect, in the command's
+/// parameter units. Absent (or unparseable) keys leave the effect unchanged, so
+/// a dialog round trip never touches what it doesn't model: an imported
+/// gradient stroke keeps its gradient while its opacity is edited.
+pub fn overlay_effect(fx: &mut Effect, p: &Value) {
+ fn set_color(p: &Value, k: &str, c: &mut Color) {
+ if let Some(x) = color_of(p, k) {
+ *c = x;
+ }
+ }
+ fn set_contour(p: &Value, c: &mut Contour) {
+ if let Some(name) = p.get("contour").and_then(Value::as_str)
+ && let Some(x) = builtin_contour(name)
+ {
+ *c = x;
+ }
+ }
+ fn common(c: &mut FxCommon, p: &Value) {
+ if let Some(x) = b_of(p, "enabled") {
+ c.enabled = x;
+ }
+ if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) {
+ c.blend = x;
+ }
+ if let Some(x) = f_of(p, "opacity") {
+ c.opacity = (x / 100.0).clamp(0.0, 1.0);
+ }
+ }
+ let inner_shadow = matches!(fx, Effect::InnerShadow(_));
+ let inner_glow = matches!(fx, Effect::InnerGlow(_));
+ match fx {
+ Effect::DropShadow(s) | Effect::InnerShadow(s) => {
+ let inner = inner_shadow;
+ common(&mut s.common, p);
+ set_color(p, "color", &mut s.color);
+ if let Some(x) = f_of(p, "angle") {
+ s.angle = x;
+ }
+ if let Some(x) = b_of(p, "useGlobalLight") {
+ s.use_global_light = x;
+ }
+ if let Some(x) = f_of(p, "distance") {
+ s.distance = x;
+ }
+ if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) {
+ s.spread = (x / 100.0).clamp(0.0, 1.0);
+ }
+ if let Some(x) = f_of(p, "size") {
+ s.size = x;
+ }
+ set_contour(p, &mut s.contour);
+ if let Some(x) = f_of(p, "noise") {
+ s.noise = (x / 100.0).clamp(0.0, 1.0);
+ }
+ if !inner && let Some(x) = b_of(p, "knocksOut") {
+ s.knocks_out = x;
+ }
+ }
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => {
+ let inner = inner_glow;
+ common(&mut g.common, p);
+ if let Some(c) = color_of(p, "color") {
+ g.paint = FxPaint::Color(c);
+ }
+ if let Some(t) = p.get("technique").and_then(Value::as_str) {
+ g.technique = if t == "precise" { GlowTechnique::Precise } else { GlowTechnique::Softer };
+ }
+ if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) {
+ g.spread = (x / 100.0).clamp(0.0, 1.0);
+ }
+ if let Some(x) = f_of(p, "size") {
+ g.size = x;
+ }
+ set_contour(p, &mut g.contour);
+ if let Some(x) = f_of(p, "range") {
+ g.range = (x / 100.0).clamp(0.01, 1.0);
+ }
+ if let Some(x) = f_of(p, "noise") {
+ g.noise = (x / 100.0).clamp(0.0, 1.0);
+ }
+ if inner && let Some(s) = p.get("source").and_then(Value::as_str) {
+ g.source = if s == "center" { GlowSource::Center } else { GlowSource::Edge };
+ }
+ }
+ Effect::Stroke(s) => {
+ common(&mut s.common, p);
+ if let Some(x) = f_of(p, "size") {
+ s.size = x;
+ }
+ if let Some(pos) = p.get("position").and_then(Value::as_str) {
+ s.position = match pos {
+ "inside" => StrokePosition::Inside,
+ "center" => StrokePosition::Center,
+ _ => StrokePosition::Outside,
+ };
+ }
+ if p.get("from").is_some() {
+ s.paint = FxPaint::Gradient(gradient(p));
+ } else if let Some(c) = color_of(p, "color") {
+ s.paint = FxPaint::Color(c);
+ }
+ }
+ Effect::ColorOverlay { common: c, color } => {
+ common(c, p);
+ set_color(p, "color", color);
+ }
+ Effect::GradientOverlay { common: c, gradient: g, dither } => {
+ common(c, p);
+ overlay_gradient(g, p);
+ if let Some(x) = b_of(p, "dither") {
+ *dither = x;
+ }
+ }
+ Effect::PatternOverlay { common: c, name, id, scale, angle, link, phase } => {
+ common(c, p);
+ if let Some(x) = p.get("pattern").and_then(Value::as_str) {
+ *name = x.to_string();
+ *id = String::new();
+ }
+ if let Some(x) = f_of(p, "scale") {
+ *scale = (x / 100.0).clamp(0.01, 10.0);
+ }
+ if let Some(x) = f_of(p, "angle") {
+ *angle = x;
+ }
+ if let Some(x) = b_of(p, "link") {
+ *link = x;
+ }
+ if let Some(x) = f_of(p, "phaseX") {
+ phase.0 = x;
+ }
+ if let Some(x) = f_of(p, "phaseY") {
+ phase.1 = x;
+ }
+ }
+ Effect::Satin(s) => {
+ common(&mut s.common, p);
+ set_color(p, "color", &mut s.color);
+ if let Some(x) = f_of(p, "angle") {
+ s.angle = x;
+ }
+ if let Some(x) = f_of(p, "distance") {
+ s.distance = x;
+ }
+ if let Some(x) = f_of(p, "size") {
+ s.size = x;
+ }
+ if let Some(x) = b_of(p, "invert") {
+ s.invert = x;
+ }
+ }
+ Effect::BevelEmboss(bv) => {
+ if let Some(x) = b_of(p, "enabled") {
+ bv.enabled = x;
+ }
+ if let Some(s) = p.get("style").and_then(Value::as_str) {
+ bv.style = match s {
+ "outer" => BevelStyle::OuterBevel,
+ "emboss" => BevelStyle::Emboss,
+ "pillow" => BevelStyle::PillowEmboss,
+ "stroke" => BevelStyle::StrokeEmboss,
+ _ => BevelStyle::InnerBevel,
+ };
+ }
+ if let Some(t) = p.get("technique").and_then(Value::as_str) {
+ bv.technique = match t {
+ "chiselHard" => BevelTechnique::ChiselHard,
+ "chiselSoft" => BevelTechnique::ChiselSoft,
+ _ => BevelTechnique::Smooth,
+ };
+ }
+ if let Some(x) = f_of(p, "depth") {
+ bv.depth = x / 100.0;
+ }
+ if let Some(d) = p.get("direction").and_then(Value::as_str) {
+ bv.up = d != "down";
+ }
+ if let Some(x) = f_of(p, "size") {
+ bv.size = x;
+ }
+ if let Some(x) = f_of(p, "soften") {
+ bv.soften = x;
+ }
+ if let Some(x) = f_of(p, "angle") {
+ bv.angle = x;
+ }
+ if let Some(x) = f_of(p, "altitude") {
+ bv.altitude = x;
+ }
+ if let Some(x) = b_of(p, "useGlobalLight") {
+ bv.use_global_light = x;
+ }
+ if let Some(x) = p.get("glossContour").and_then(Value::as_str)
+ && let Some(c) = builtin_contour(x)
+ {
+ bv.gloss_contour = c;
+ }
+ if let Some(x) = b_of(p, "contour") {
+ bv.contour = x.then(|| photocraft_doc::BevelContour {
+ contour: builtin_contour(p.get("contourName").and_then(Value::as_str).unwrap_or("Linear")).unwrap_or(Contour::Linear),
+ range: (f(p, "contourRange", 50.0) / 100.0).clamp(0.01, 1.0),
+ anti_alias: false,
+ });
+ } else if let Some(c) = &mut bv.contour
+ && let Some(x) = builtin_contour(p.get("contourName").and_then(Value::as_str).unwrap_or(""))
+ {
+ c.contour = x;
+ }
+ if let Some(t) = p.get("texture").and_then(Value::as_str).filter(|t| !t.is_empty()) {
+ bv.texture = Some(photocraft_doc::BevelTexture {
+ name: t.to_string(),
+ id: t.to_string(),
+ scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0),
+ depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0),
+ invert: b(p, "textureInvert", false),
+ link: b(p, "textureLink", true),
+ phase: (0.0, 0.0),
+ });
+ }
+ }
+ }
+}
+
+/// Builds an effect of `kind` from JSON params (Photoshop units: opacity,
+/// spread, range in percent; sizes in px; angles in degrees).
+pub fn effect_from_params(kind: &str, p: &Value) -> Option<Effect> {
+ let mut fx = fresh_effect(kind)?;
+ overlay_effect(&mut fx, p);
+ Some(fx)
+}
+
+/// The effect's kind as the commands and dialog name it.
+pub fn kind_of(e: &Effect) -> &'static str {
+ match e {
+ Effect::DropShadow(_) => "dropShadow",
+ Effect::InnerShadow(_) => "innerShadow",
+ Effect::OuterGlow(_) => "outerGlow",
+ Effect::InnerGlow(_) => "innerGlow",
+ Effect::Stroke(_) => "stroke",
+ Effect::ColorOverlay { .. } => "colorOverlay",
+ Effect::GradientOverlay { .. } => "gradientOverlay",
+ Effect::PatternOverlay { .. } => "patternOverlay",
+ Effect::Satin(_) => "satin",
+ Effect::BevelEmboss(_) => "bevelEmboss",
+ }
+}
+
fn same_kind(a: &Effect, b: &Effect) -> bool {
std::mem::discriminant(a) == std::mem::discriminant(b)
}
+/// Upper bound on the effects one `layer.layerStyle.replace` call accepts, so an
+/// automation mistake can't ask for an unbounded document change.
+const MAX_EFFECTS: usize = 256;
+
+/// Replaces a layer's whole effect list in one history step: the Layer Style dialog's
+/// apply. Each entry builds an effect from `params`, or edits the snapshot it carried
+/// (`fx`: the effect JSON as the dialog loaded it, kept verbatim for everything the
+/// dialog doesn't model) with the params present. Unknown kinds, kind/snapshot
+/// mismatches and malformed snapshots are errors, never panics.
+fn replace_effects(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.layerStyle.replace";
+ let id = match p.get("layer").and_then(Value::as_u64) {
+ Some(id) => photocraft_doc::LayerId(id),
+ None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?,
+ };
+ let entries = p.get("effects").and_then(Value::as_array).ok_or_else(|| bad(CMD, "need `effects`: [{kind, params, fx?}]"))?;
+ if entries.len() > MAX_EFFECTS {
+ return Err(bad(CMD, format!("at most {MAX_EFFECTS} effects")));
+ }
+ let mut list = Vec::with_capacity(entries.len());
+ let mut pats = Vec::new();
+ for e in entries {
+ let kind = e.get("kind").and_then(Value::as_str).ok_or_else(|| bad(CMD, "each effect needs a `kind` string"))?;
+ let params = match e.get("params") {
+ None | Some(Value::Null) => json!({}),
+ Some(Value::Object(_)) => e.get("params").cloned().unwrap_or_default(),
+ Some(_) => return Err(bad(CMD, "`params` must be an object")),
+ };
+ let fx = match e.get("fx") {
+ Some(fx_json) => {
+ let mut fx: Effect = serde_json::from_value(fx_json.clone()).map_err(|err| bad(CMD, format!("bad effect snapshot: {err}")))?;
+ if kind_of(&fx) != kind {
+ return Err(bad(CMD, format!("effect snapshot is a {}, not `{kind}`", kind_of(&fx))));
+ }
+ overlay_effect(&mut fx, &params);
+ fx
+ }
+ None => effect_from_params(kind, &params).ok_or_else(|| bad(CMD, format!("unknown effect {kind}")))?,
+ };
+ let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx)?;
+ if let Some(pat) = pat {
+ pats.push(pat);
+ }
+ list.push(fx);
+ }
+ let count = list.len();
+ let label = if list.is_empty() { "Clear Layer Style" } else { "Edit Layer Style" };
+ s.edit(label, |doc, _| {
+ for pat in &pats {
+ crate::pattern_cmds::ensure_in_doc(doc, pat);
+ }
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ l.effects.items = list;
+ l.effects.enabled = true;
+ Ok(())
+ })?;
+ Ok(json!({ "layer": id.0, "effects": count }))
+}
fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
let fx = effect_from_params(kind, p).ok_or_else(|| EngineError::Other(format!("unknown effect {kind}")))?;
@@ -196,6 +563,37 @@ fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
Ok(json!({ "layer": id.0 }))
}
+/// Stores the user default for one effect kind ("Make Default" in the Layer Style dialog).
+fn make_default(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.layerStyle.makeDefault";
+ let kind = req_str_kind(p, CMD)?;
+ let params = match p.get("params") {
+ Some(v) if v.is_object() => v.clone(),
+ _ => return Err(bad(CMD, "`params` must be an object")),
+ };
+ s.presets.layer_defaults.insert(kind.to_string(), params);
+ s.presets_changed();
+ Ok(json!({"kind": kind}))
+}
+
+/// The user default for one effect kind, else its factory defaults.
+fn default_for(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.layerStyle.defaultFor";
+ let kind = req_str_kind(p, CMD)?;
+ match s.presets.layer_defaults.get(kind) {
+ Some(v) if v.is_object() => Ok(json!({"params": v, "user": true})),
+ _ => Ok(json!({"params": effect_defaults(kind), "user": false})),
+ }
+}
+
+fn req_str_kind<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
+ let kind = p.get("kind").and_then(Value::as_str).ok_or_else(|| bad(cmd, "need `kind`"))?;
+ if effect_from_params(kind, &Value::Null).is_none() {
+ return Err(bad(cmd, format!("unknown effect {kind}")));
+ }
+ Ok(kind)
+}
+
fn has_layer(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into())
@@ -222,22 +620,22 @@ pub fn specs() -> Vec<CommandSpec> {
style_cmd!(
"dropShadow",
"Drop Shadow…",
- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="multiply","angle":deg=120,"useGlobalLight":bool,"distance":px=5,"spread":0..100,"size":px=5,"knocksOut":bool,"add":bool,"layer":id}"##
+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="multiply","angle":deg=120,"useGlobalLight":bool,"distance":px=5,"spread":0..100,"size":px=5,"contour":"Linear|Cone|Cone (Inverted)|Domed|Domed (Inverted)|Diagonal (Descending)"="Linear","noise":0..100,"knocksOut":bool,"add":bool,"layer":id}"##
),
style_cmd!(
"innerShadow",
"Inner Shadow…",
- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":deg,"distance":px,"choke":0..100,"size":px,"add":bool}"##
+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":deg,"distance":px,"choke":0..100,"size":px,"contour":name,"noise":0..100,"add":bool}"##
),
style_cmd!(
"outerGlow",
"Outer Glow…",
- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","spread":0..100,"size":px,"range":0..100,"add":bool}"##
+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","spread":0..100,"size":px,"range":0..100,"contour":name,"noise":0..100,"add":bool}"##
),
style_cmd!(
"innerGlow",
"Inner Glow…",
- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"add":bool}"##
+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"contour":name,"noise":0..100,"add":bool}"##
),
style_cmd!(
"stroke",
@@ -261,6 +659,36 @@ pub fn specs() -> Vec<CommandSpec> {
r##"{"style":"inner|outer|emboss|pillow|stroke","technique":"smooth|chiselHard|chiselSoft","contour":bool,"contourRange":1..100=50,"texture":pattern id|name?,"textureScale":1..1000=100,"textureDepth":-1000..1000=100,"textureInvert":bool,"textureLink":bool=true,"depth":1..1000=100,"direction":"up|down","size":px=5,"soften":px,"angle":deg,"altitude":deg,"add":bool}"##
),
style_cmd!("satin", "Satin…", r##"{"color":"#rrggbb","opacity":0..100=50,"blend":str,"angle":deg,"distance":px,"size":px,"invert":bool,"add":bool}"##),
+ CommandSpec {
+ id: "layer.layerStyle.replace",
+ label: "Edit Layer Style",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"layer":id,"effects":[{"kind":"dropShadow|innerShadow|outerGlow|innerGlow|stroke|colorOverlay|gradientOverlay|patternOverlay|satin|bevelEmboss","params":{…layer.layerStyle.<kind> params…},"fx":<effect snapshot carried through the Layer Style dialog, optional>}]} (replaces the layer's whole effect list; an entry with `fx` edits that effect with the params present, one without builds from params)"##,
+ enabled: has_layer,
+ run: replace_effects,
+ journal: true,
+ },
+ CommandSpec {
+ id: "layer.layerStyle.makeDefault",
+ label: "Make Layer Style Default",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"kind":"stroke|dropShadow|innerShadow|outerGlow|innerGlow|colorOverlay|gradientOverlay|patternOverlay|satin|bevelEmboss","params":{…param set…}} (stores the user default the Layer Style dialog's Reset to Default restores)"##,
+ enabled: always,
+ run: make_default,
+ journal: false,
+ },
+ CommandSpec {
+ id: "layer.layerStyle.defaultFor",
+ label: "Layer Style Default",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"kind":str} → {"params":{…},"user":bool} (the saved user default, else the factory defaults)"##,
+ enabled: always,
+ run: default_for,
+ journal: false,
+ },
CommandSpec {
id: "layer.layerStyle.clear",
label: "Clear Layer Style",
@@ -371,4 +799,180 @@ mod tests {
assert_eq!(gradient_style("diamond"), GradientStyle::Diamond);
assert_eq!(gradient_style("?"), GradientStyle::Linear);
}
+
+ fn snapshot(fx: &Effect) -> Value {
+ serde_json::to_value(fx).unwrap()
+ }
+
+ #[test]
+ fn every_kind_has_factory_defaults() {
+ for kind in
+ ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"]
+ {
+ assert!(effect_defaults(kind).as_object().is_some_and(|o| !o.is_empty()), "{kind}");
+ assert!(effect_from_params(kind, &json!({})).is_some(), "{kind}");
+ }
+ assert!(effect_from_params("nope", &json!({})).is_none());
+ }
+
+ #[test]
+ fn replace_builds_edits_and_preserves_instances() {
+ let mut s = session();
+ // Two strokes: the first edits a snapshot (params overlay), the second is fresh.
+ let first = Effect::Stroke(StrokeFx {
+ common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0),
+ size: 7.0,
+ position: StrokePosition::Outside,
+ paint: FxPaint::Gradient(Gradient { stops: vec![(0.0, Color::rgb(0.0, 0.0, 1.0)), (1.0, Color::WHITE)], ..Gradient::default() }),
+ });
+ let r = s
+ .execute(
+ "layer.layerStyle.replace",
+ json!({"effects": [
+ {"kind": "stroke", "fx": snapshot(&first), "params": {"opacity": 50}},
+ {"kind": "stroke", "params": {"size": 2, "color": "#ffffff"}},
+ ]}),
+ )
+ .unwrap();
+ assert_eq!(r["effects"], 2);
+ let fx = effects(&s);
+ assert_eq!(fx.len(), 2, "order preserved");
+ match (&fx[0], &fx[1]) {
+ (Effect::Stroke(a), Effect::Stroke(b)) => {
+ assert_eq!(a.common.opacity, 0.5);
+ // The overlay must not clobber the gradient paint it doesn't model.
+ assert!(matches!(&a.paint, FxPaint::Gradient(g) if g.stops.len() == 2 && g.stops[0].1 == Color::rgb(0.0, 0.0, 1.0)));
+ assert_eq!(b.size, 2.0);
+ assert_eq!(b.paint, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0)));
+ }
+ other => panic!("{other:?}"),
+ }
+ // Replacing with an empty list clears the layer.
+ s.execute("layer.layerStyle.replace", json!({"effects": []})).unwrap();
+ assert!(effects(&s).is_empty());
+ }
+
+ #[test]
+ fn replace_rejects_bad_entries_gracefully() {
+ let mut s = session();
+ let stroke = Effect::Stroke(StrokeFx {
+ common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0),
+ size: 3.0,
+ position: StrokePosition::Outside,
+ paint: FxPaint::Color(Color::BLACK),
+ });
+ for p in [
+ json!({}),
+ json!({"effects": "nope"}),
+ json!({"effects": [{"params": {}}]}),
+ json!({"effects": [{"kind": "nope"}]}),
+ json!({"effects": [{"kind": "stroke", "fx": {"Bogus": {}}}]}),
+ json!({"effects": [{"kind": "stroke", "fx": 3}]}),
+ json!({"effects": [{"kind": "dropShadow", "fx": snapshot(&stroke)}]}),
+ json!({"effects": [{"kind": "stroke", "fx": snapshot(&stroke), "params": "nope"}]}),
+ ] {
+ assert!(s.execute("layer.layerStyle.replace", p).is_err());
+ }
+ // A long list is refused, not run.
+ let many: Vec<_> = (0..257).map(|_| json!({"kind": "stroke"})).collect();
+ assert!(s.execute("layer.layerStyle.replace", json!({"effects": many})).is_err());
+ assert!(effects(&s).is_empty(), "nothing was applied");
+ }
+
+ #[test]
+ fn contour_and_noise_params_edit_existing_effects() {
+ let mut s = session();
+ s.execute("layer.layerStyle.dropShadow", json!({})).unwrap();
+ let before = effects(&s);
+ let Effect::DropShadow(_) = &before[0] else { panic!("{before:?}") };
+ let fx0 = snapshot(&before[0]);
+ // Unknown contour names are carried, not clobbered to Linear.
+ s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "dropShadow", "fx": fx0, "params": {"contour": "Cone", "noise": 30}}]})).unwrap();
+ let fx = effects(&s);
+ let Effect::DropShadow(sh) = &fx[0] else { panic!("{fx:?}") };
+ assert_eq!(sh.contour, builtin_contour("Cone").unwrap(), "known preset applies");
+ assert!((sh.noise - 0.3).abs() < 1e-6, "noise in percent");
+ // An imported contour with an unknown name survives the same round trip.
+ let imported = Contour::Custom {
+ name: "Photoshop contour".into(),
+ points: vec![photocraft_doc::adjust::CurvePoint { input: 0.0, output: 1.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }],
+ };
+ let mut carried = before[0].clone();
+ if let Effect::DropShadow(c) = &mut carried {
+ c.contour = imported.clone();
+ }
+ overlay_effect(&mut carried, &json!({"contour": "Photoshop contour"}));
+ let Effect::DropShadow(after) = &carried else { panic!() };
+ assert_eq!(after.contour, imported);
+ // Linear applies by name.
+ let mut back = carried;
+ overlay_effect(&mut back, &json!({"contour": "Linear"}));
+ let Effect::DropShadow(lin) = &back else { panic!() };
+ assert_eq!(lin.contour, Contour::Linear);
+ }
+
+ #[test]
+ fn make_default_then_reset_restores_it() {
+ let mut s = session();
+ // Factory default first: Reset without a saved default gives the factory set.
+ let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap();
+ assert_eq!(r["user"], json!(false));
+ assert_eq!(r["params"]["size"], json!(3));
+ s.execute(
+ "layer.layerStyle.makeDefault",
+ json!({"kind": "stroke", "params": {"size": 9, "position": "inside", "blend": "Normal", "opacity": 100, "color": "#000000"}}),
+ )
+ .unwrap();
+ let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap();
+ assert_eq!(r["user"], json!(true));
+ assert_eq!(r["params"]["size"], json!(9));
+ // Bad kinds and params are graceful errors.
+ assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "nope", "params": {}})).is_err());
+ assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": "x"})).is_err());
+ assert!(s.execute("layer.layerStyle.defaultFor", json!({"kind": "nope"})).is_err());
+ }
+
+ #[test]
+ fn layer_style_defaults_persist_with_presets() {
+ let mut s = session();
+ s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": {"size": 9}})).unwrap();
+ let blob = s.presets.to_json(&s);
+ let mut t = Session::new();
+ t.load_presets_json(blob);
+ let r = t.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap();
+ assert_eq!(r["user"], json!(true));
+ assert_eq!(r["params"]["size"], json!(9));
+ }
+
+ #[test]
+ fn double_stroke_bands_render_and_survive_an_edit() {
+ // The manga/typesetting case (#157): a 7 px white stroke under a 3 px black one.
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 48, "height": 48})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000", "position": "outside"})).unwrap();
+ s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "position": "outside", "add": true})).unwrap();
+ let px = |s: &mut Session, x: i32, y: i32| -> [f32; 4] {
+ let mut v: Vec<f32> = serde_json::from_value(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()).unwrap();
+ v.resize(4, 1.0);
+ [v[0], v[1], v[2], v[3]]
+ };
+ // Bands from the square edge outward: 0..3 px black (the first stroke renders on top),
+ // 3..7 px white, then the white background.
+ assert!(px(&mut s, 24, 24)[0] < 0.1, "the square is black");
+ assert!(px(&mut s, 24, 14)[0] < 0.1, "the first stroke covers the wider one");
+ assert!(px(&mut s, 24, 11)[0] > 0.9, "the second stroke shows outside it");
+ assert!(px(&mut s, 24, 5)[0] > 0.9, "background beyond both");
+ // A dialog round trip (replace with the same snapshots) keeps both bands.
+ let before = px(&mut s, 24, 14);
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let items = st.doc.layer(id).unwrap().effects.items.clone();
+ let entries: Vec<Value> = items.iter().map(|fx| json!({"kind": "stroke", "fx": serde_json::to_value(fx).unwrap(), "params": {}})).collect();
+ s.execute("layer.layerStyle.replace", json!({"layer": id.0, "effects": entries})).unwrap();
+ assert_eq!(px(&mut s, 24, 14), before, "both strokes render identically after the round trip");
+ }
}
diff --git a/crates/engine/src/presets/mod.rs b/crates/engine/src/presets/mod.rs
index a257866f4..e2a225895 100644
--- a/crates/engine/src/presets/mod.rs
+++ b/crates/engine/src/presets/mod.rs
@@ -27,6 +27,8 @@ pub mod tools;
#[cfg(test)]
mod tests;
+use std::collections::BTreeMap;
+
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -75,6 +77,9 @@ pub struct PresetState {
pub pattern: Option<String>,
pub tool_presets: Vec<tools::ToolPreset>,
pub clone: clone_source::CloneSources,
+ /// The user defaults "Make Default" in the Layer Style dialog saves
+ /// (effect kind → param set); "Reset to Default" restores them.
+ pub layer_defaults: BTreeMap<String, Value>,
/// Bumped on every preset change (UIs key thumbnail caches on it).
pub rev: u64,
}
@@ -90,6 +95,7 @@ impl Default for PresetState {
pattern: None,
tool_presets: tools::builtin(),
clone: Default::default(),
+ layer_defaults: BTreeMap::new(),
rev: 0,
}
}
@@ -112,6 +118,8 @@ struct Persisted {
tool_presets: Option<Vec<tools::ToolPreset>>,
#[serde(default)]
custom_shapes: Option<Vec<crate::edit_menu_cmds::CustomShape>>,
+ #[serde(default)]
+ layer_defaults: Option<BTreeMap<String, Value>>,
}
impl PresetState {
@@ -125,6 +133,7 @@ impl PresetState {
pattern_groups: Some(self.pattern_groups.clone()),
tool_presets: Some(self.tool_presets.clone()),
custom_shapes: Some(s.edit_state.custom_shapes.clone()),
+ layer_defaults: Some(self.layer_defaults.clone()),
};
serde_json::to_value(p).unwrap_or(Value::Null)
}
@@ -157,6 +166,9 @@ impl Session {
if let Some(c) = p.custom_shapes {
self.edit_state.custom_shapes = c;
}
+ if let Some(d) = p.layer_defaults {
+ st.layer_defaults = d;
+ }
self.presets.rev += 1;
}
diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs
index c028fcb04..a2c29a47c 100644
--- a/crates/engine/src/presets/styles.rs
+++ b/crates/engine/src/presets/styles.rs
@@ -143,7 +143,7 @@ pub fn builtin() -> Vec<Group<StylePreset>> {
]
}
-fn find_style<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<&'a StylePreset> {
+pub fn find_style<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<&'a StylePreset> {
let name = req_str(p, "preset", cmd)?;
let (gi, ii) = find(&s.presets.styles, name, str_param(p, "group")).ok_or_else(|| bad(cmd, format!("no style \"{name}\" (see style.presets.list)")))?;
Ok(&s.presets.styles[gi].items[ii])
@@ -229,11 +229,34 @@ fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
if !with_fx && !with_blend {
return Err(bad(CMD, "include effects and/or blending options"));
}
+ // An explicit effect list (the Layer Style dialog's pending state, in
+ // `layer.layerStyle.<kind>` param form) replaces the layer's own effects.
+ let listed = p
+ .get("effects")
+ .and_then(Value::as_array)
+ .map(|list| -> Result<Vec<Effect>> {
+ list.iter()
+ .map(|e| {
+ let kind = e.get(0).and_then(Value::as_str).ok_or_else(|| bad(CMD, "each effect is [kind, params]"))?;
+ effect_from_params(kind, e.get(1).unwrap_or(&Value::Null)).ok_or_else(|| bad(CMD, format!("unknown effect {kind}")))
+ })
+ .collect()
+ })
+ .transpose()?;
let style = StylePreset {
name: unique_name(&s.presets.styles, str_param(p, "name").unwrap_or("Style")),
- effects: if with_fx { l.effects.items.clone() } else { Vec::new() },
- blend: with_blend.then_some(l.blend),
- fill_opacity: with_blend.then_some(l.fill_opacity),
+ effects: match listed {
+ Some(fx) => fx,
+ None => {
+ if with_fx {
+ l.effects.items.clone()
+ } else {
+ Vec::new()
+ }
+ }
+ },
+ blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::blend_from_str).or_else(|| with_blend.then_some(l.blend)),
+ fill_opacity: p.get("fillOpacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.fill_opacity)),
};
let gi = group_index(&mut s.presets.styles, str_param(p, "group"));
let out = json!({"name": style.name, "group": s.presets.styles[gi].name, "effects": style.effects.len()});
@@ -334,7 +357,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "New Style…",
menu: &[],
shortcut: None,
- params: r##"{"name":str="Style","group":name?,"layer":id?,"includeEffects":bool=true,"includeBlending":bool=true} (from the layer's effects)"##,
+ params: r##"{"name":str="Style","group":name?,"layer":id?,"includeEffects":bool=true,"includeBlending":bool=true,"effects":[[kind, params]]? (explicit list, e.g. the Layer Style dialog's pending state; overrides includeEffects),"blend":str?,"fillOpacity":0..100? (override the layer's blending options)}"##,
enabled: has_layer,
run: new_preset,
journal: true,
diff --git a/crates/engine/src/presets/tests.rs b/crates/engine/src/presets/tests.rs
index a0afca461..afbdac3e0 100644
--- a/crates/engine/src/presets/tests.rs
+++ b/crates/engine/src/presets/tests.rs
@@ -18,6 +18,34 @@ fn layer_px(s: &Session, x: i32, y: i32) -> Vec<f32> {
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)
}
+// ------------------------------------------------------------------ styles
+
+#[test]
+fn style_preset_new_from_an_explicit_effect_list() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ // The Layer Style dialog's "New Style…" saves its pending state, not the layer.
+ let r = s
+ .execute(
+ "style.presets.new",
+ json!({"name": "Pending", "effects": [["stroke", {"size": 6, "color": "#123456"}]], "blend": "Multiply", "fillOpacity": 40}),
+ )
+ .unwrap();
+ assert_eq!(r["name"], json!("Pending"));
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("style.presets.apply", json!({"preset": "Pending"})).unwrap();
+ let d = s.active().unwrap();
+ let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
+ assert_eq!(l.effects.items.len(), 1);
+ assert!(matches!(&l.effects.items[0], photocraft_doc::Effect::Stroke(st) if st.size == 6.0));
+ assert_eq!(l.blend, photocraft_color::BlendMode::Multiply);
+ assert!((l.fill_opacity - 0.4).abs() < 1e-6);
+ // Malformed lists are graceful errors.
+ assert!(s.execute("style.presets.new", json!({"effects": [["nope", {}]]})).is_err());
+ assert!(s.execute("style.presets.new", json!({"effects": ["stroke"]})).is_err());
+}
+
// ------------------------------------------------------------------ gradients
#[test]
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 09d17cda0..891057405 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -735,6 +735,16 @@ impl Compositor {
}
}
for e in f.layer.effects.items.iter().filter(|e| e.enabled()) {
+ // Effect noise is speckled in the CPU maps; keep CPU and GPU identical by
+ // rendering noise-carrying effects on the CPU path.
+ let noisy = match e {
+ photocraft_doc::Effect::DropShadow(s) | photocraft_doc::Effect::InnerShadow(s) => s.noise > 0.0,
+ photocraft_doc::Effect::OuterGlow(g) | photocraft_doc::Effect::InnerGlow(g) => g.noise > 0.0,
+ _ => false,
+ };
+ if noisy {
+ return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name)));
+ }
for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages {
if s.lut.as_ref().is_some_and(|l| l.len() > 4096) {
return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name)));
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 97958c08b..9bce06ac5 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -486,10 +486,13 @@ fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>
}
// Layer Style dialog: show its effects live (Cancel just drops the preview).
let style = app.ui.dialogs.iter().find(|d| d.kind == crate::state::DialogKind::LayerStyle);
- if style.is_none() {
+ // The Preview checkbox off shows the document as it was when the dialog opened;
+ // edits still land in the dialog state and OK applies them whatever it says.
+ let preview_on = style.and_then(|d| d.fields.get("preview")).and_then(serde_json::Value::as_bool).unwrap_or(true);
+ if style.is_none() || !preview_on {
app.style_preview = None;
}
- if let Some(d) = style
+ if let Some(d) = style.filter(|_| preview_on)
&& app.session.active_index() == Some(idx)
{
let key = (crate::layer_style::preview_hash(&d.fields) ^ st.revision.wrapping_mul(0x9e37_79b9_7f4a_7c15)) | 1 << 63;
@@ -3267,7 +3270,10 @@ mod tests {
let id = crate::layer_style::open(&mut app, Some("colorOverlay")).unwrap();
let (shown, key) = display_doc(&mut app, 0);
assert_eq!((fx(&shown), fx(&app.session.documents()[0].doc)), (1, 0), "previewed, not committed");
- app.ui.dialog_mut(id).unwrap().fields.insert("on:stroke".into(), json!(true));
+ // Adding a stroke through the dialog's instance list re-renders the canvas.
+ if let Some(d) = app.ui.dialog_mut(id) {
+ d.fields["effects"].as_array_mut().unwrap().push(json!({"id": "fx9", "kind": "stroke", "on": true, "params": {"size": 3}}));
+ }
let (shown, key2) = display_doc(&mut app, 0);
assert_eq!(fx(&shown), 2);
assert_ne!(key, key2, "an edit re-renders the canvas");
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 238622075..667d471f0 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -159,7 +159,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
DialogKind::Command if fields.contains_key("__form") => crate::view_cmds::form_body(ui, &mut fields),
DialogKind::Command => {}
- DialogKind::LayerStyle => crate::layer_style::body(ui, &mut fields),
+ DialogKind::LayerStyle => crate::layer_style::body(app, ui, &mut fields),
DialogKind::Error => {
ui.label(fields.get("message").and_then(Value::as_str).unwrap_or("Error"));
}
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 9590be5ae..0efa32ce6 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -914,8 +914,6 @@
Create new pattern from the selection Vytvořit nový vzorek z výběru
Create new shape from the current path Vytvořit nový tvar z aktuální cesty
Create new snapshot Vytvořit nový snímek
- Create new style (from the selected type) Vytvořit nový styl (z vybraného textu)
- Create new style from the selected layer Vytvořit nový styl z vybrané vrstvy
Create new tool preset Vytvořit nové přednastavení nástroje
Crop Factor Crop faktor
Ctrl Ctrl
@@ -2065,6 +2063,16 @@ cameraRaw Color Barvy
Patch: Záplata:
Lasso around an area, then drag the selection Obtáhněte oblast lasem a pak přetáhněte výběr
Edit Type Upravit text
+
+
+ New Style… Nový styl…
+ Style {name} saved Styl {name} uložen
+
+ Create new style (from the selected type) Vytvořit nový styl (z vybraného textu)
+ Create new style from the selected layer Vytvořit nový styl z vybrané vrstvy
+
+ Make Default Nastavit jako výchozí
+ Reset to Default Obnovit výchozí
Full-resolution preview unavailable Náhled v plném rozlišení není dostupný
No patterns Žádné vzorky
Enable {name} Povolit {name}
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index e88cf5d75..4ae9ba059 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2124,5 +2124,10 @@
Don't show again Nicht mehr anzeigen
Save failed: {error} Speichern fehlgeschlagen: {error}
Save cancelled Speichern abgebrochen
+
+# Layer Style dialog: style presets and per-effect defaults
+ Style {name} saved Stil {name} gespeichert
+ Make Default Als Standard festlegen
+ Reset to Default Auf Standard zurücksetzen
Couldn't place {name}: {error} {name} konnte nicht platziert werden: {error}
Full-resolution preview unavailable Vorschau in voller Auflösung nicht verfügbar
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 5f3db45f7..ce91a49e6 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -899,8 +899,6 @@
Create new pattern from the selection Crear un patrón nuevo a partir de la selección
Create new shape from the current path Crear una forma nueva a partir del trazado actual
Create new snapshot Crear una instantánea nueva
- Create new style (from the selected type) Crear un estilo nuevo (del texto seleccionado)
- Create new style from the selected layer Crear un estilo nuevo a partir de la capa seleccionada
Create new tool preset Crear un preajuste de herramienta nuevo
Crop Factor Factor de recorte
Ctrl Ctrl
@@ -2073,7 +2071,6 @@
Auto Erase Borrado automático
Color Adaptation Adaptación de color
Preserve Transparency Conservar transparencia
- New Style… Nuevo estilo…
shortcut atajo
Saved Guardado
Arc Arco
@@ -2141,6 +2138,16 @@ cameraRaw Amount Cantidad
Patch: Parche:
Lasso around an area, then drag the selection Rodee un área con el lazo y arrastre la selección
Edit Type Editar texto
+
+
+ New Style… Nuevo estilo…
+ Style {name} saved Estilo {name} guardado
+
+ Create new style (from the selected type) Crear estilo nuevo (del texto seleccionado)
+ Create new style from the selected layer Crear estilo nuevo de la capa seleccionada
+
+ Make Default Predeterminar
+ Reset to Default Restablecer predeterminado
Full-resolution preview unavailable Vista previa a resolución completa no disponible
No patterns Sin motivos
Enable {name} Activar {name}
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 4161a5706..0e10773ec 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -889,8 +889,6 @@
Create new pattern from the selection Créer un nouveau motif à partir de la sélection
Create new shape from the current path Créer une nouvelle forme à partir du tracé actif
Create new snapshot Créer un nouvel instantané
- Create new style (from the selected type) Créer un nouveau style (d'après le texte sélectionné)
- Create new style from the selected layer Créer un nouveau style d'après le calque sélectionné
Create new tool preset Créer un nouveau préréglage d'outil
Crop Factor Facteur de recadrage
Ctrl Ctrl
@@ -2343,7 +2341,6 @@
Auto Erase Effacement automatique
Color Adaptation Adaptation des couleurs
Preserve Transparency Préserver la transparence
- New Style… Nouveau style…
shortcut raccourci
Go to Layer Aller au calque
Saved Enregistré
@@ -2500,6 +2497,16 @@ cameraRaw Blending Fusion
5 x 5 5 × 5
Grid: Grille :
Edit Type Modifier le texte
+
+
+ New Style… Nouveau style…
+ Style {name} saved Style {name} enregistré
+
+ Create new style (from the selected type) Créer un nouveau style (à partir du texte sélectionné)
+ Create new style from the selected layer Créer un nouveau style à partir du calque sélectionné
+
+ Make Default Définir par défaut
+ Reset to Default Rétablir par défaut
Full-resolution preview unavailable Aperçu en pleine résolution indisponible
No patterns Aucun motif
Enable {name} Activer {name}
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index b4a6524be..882861084 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -883,8 +883,6 @@
Create new pattern from the selection Buat pola baru dari seleksi
Create new shape from the current path Buat bentuk baru dari path saat ini
Create new snapshot Buat snapshot baru
- Create new style (from the selected type) Buat gaya baru (dari teks terpilih)
- Create new style from the selected layer Buat gaya baru dari layer terpilih
Create new tool preset Buat preset alat baru
Crop Factor Faktor Crop
Ctrl Ctrl
@@ -2334,7 +2332,6 @@
Auto Erase Hapus Otomatis
Color Adaptation Adaptasi Warna
Preserve Transparency Pertahankan Transparansi
- New Style… Gaya Baru…
shortcut pintasan
Go to Layer Ke Layer
Saved Tersimpan
@@ -2487,6 +2484,16 @@ cameraRaw Blending Pembauran
5 x 5 5 × 5
Grid: Kisi-kisi:
Edit Type Edit Teks
+
+
+ New Style… Gaya Baru…
+ Style {name} saved Gaya {name} disimpan
+
+ Create new style (from the selected type) Buat gaya baru (dari teks terpilih)
+ Create new style from the selected layer Buat gaya baru dari lapisan terpilih
+
+ Make Default Jadikan Default
+ Reset to Default Atur Ulang ke Default
Full-resolution preview unavailable Pratinjau resolusi penuh tidak tersedia
No patterns Tidak ada pola
Enable {name} Aktifkan {name}
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 070c31779..bd1e1ee37 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -904,8 +904,6 @@
Create new pattern from the selection 選択範囲から新規パターンを作成
Create new shape from the current path 現在のパスから新規シェイプを作成
Create new snapshot 新規スナップショットを作成
- Create new style (from the selected type) 新規スタイルを作成(選択した文字から)
- Create new style from the selected layer 選択したレイヤーから新規スタイルを作成
Create new tool preset 新規ツールプリセットを作成
Crop Factor 切り抜き係数
Ctrl Ctrl
@@ -2049,6 +2047,16 @@ cameraRaw Color カラー
Patch: パッチ:
Lasso around an area, then drag the selection 投げ縄で範囲を囲み、選択範囲をドラッグします
Edit Type 文字を編集
+
+
+ New Style… 新規スタイル…
+ Style {name} saved スタイル {name} を保存しました
+
+ Create new style (from the selected type) 新規スタイルを作成(選択したテキストから)
+ Create new style from the selected layer 選択したレイヤーから新規スタイルを作成
+
+ Make Default 既定に設定
+ Reset to Default 既定値に戻す
Vertical Type Tool 縦書き文字ツール
Full-resolution preview unavailable フル解像度のプレビューを利用できません
No patterns パターンなし
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index a486ca103..dee968020 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2036,6 +2036,13 @@ cameraRaw Color 색상
300% 300%
Full-resolution preview unavailable 전체 해상도 미리보기를 사용할 수 없습니다
+
+ New Style… 새 스타일…
+ Style {name} saved {name} 스타일을 저장했습니다
+
+ Make Default 기본값으로 만들기
+ Reset to Default 기본값으로 되돌리기
+
# Additional generated filter labels and Photoshop-aligned UI terminology.
@id select.all 모두 선택
No patterns 패턴 없음
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 167b573a0..d1ba290da 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2523,5 +2523,10 @@ cameraRaw Whites Brancos
Don't show again Não mostrar novamente
Save failed: {error} Falha ao salvar: {error}
Save cancelled Salvamento cancelado
+
+# Layer Style dialog: style presets and per-effect defaults
+ Style {name} saved Estilo {name} salvo
+ Make Default Definir como padrão
+ Reset to Default Restaurar padrão
Couldn't place {name}: {error} Não foi possível inserir {name}: {error}
Full-resolution preview unavailable Pré-visualização em resolução total indisponível
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 24229736a..026285dc7 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1444,8 +1444,6 @@
Drag on the image to add a constraint; Shift for horizontal/vertical; right-click to delete. Перетащите по изображению, чтобы добавить ограничение; Shift — горизонталь/вертикаль; правый клик — удалить.
Drag the arrow to set the angle, the dots to set the roundness Перетащите стрелку, чтобы задать угол, и точки — круглость
Create new pattern from the selection Создать новый паттерн из выделения
- Create new style (from the selected type) Создать новый стиль (из выбранного типа)
- Create new style from the selected layer Создать новый стиль из выбранного слоя
Create new gradient Создать новый градиент
Create new count group Создать новую группу счёта
Search commands, tools and panels… Поиск команд, инструментов и панелей…
@@ -1537,7 +1535,6 @@
Redefine style by current selection Переопределить стиль по текущему выделению
Duplicate style Дублировать стиль
Delete style Удалить стиль
- New Style… Новый стиль…
Style Options Параметры стиля
Style Options… Параметры стиля…
Close Style Options Закрыть параметры стиля
@@ -2343,6 +2340,16 @@ cameraRaw Roughness Неровность
Patch: Заплатка:
Lasso around an area, then drag the selection Обведите область лассо, затем перетащите выделение
Edit Type Редактировать текст
+
+
+ New Style… Новый стиль…
+ Style {name} saved Стиль {name} сохранён
+
+ Create new style (from the selected type) Создать стиль (из выделенного текста)
+ Create new style from the selected layer Создать стиль из выделенного слоя
+
+ Make Default Сделать по умолчанию
+ Reset to Default Сбросить к значению по умолчанию
Full-resolution preview unavailable Полноразмерный предпросмотр недоступен
No patterns Нет узоров
Enable {name} Включить {name}
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index fa0119123..cb0d48027 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -903,8 +903,6 @@
Create new pattern from the selection 从选区创建图案
Create new shape from the current path 从当前路径创建形状
Create new snapshot 创建快照
- Create new style (from the selected type) 创建样式(基于选中的文字)
- Create new style from the selected layer 从选中的图层创建样式
Create new tool preset 创建工具预设
Crop Factor 裁切系数
Ctrl Ctrl
@@ -2075,6 +2073,16 @@ cameraRaw Blending 混合
Details 详细信息
Rendering mode 渲染模式
Edit Type 编辑文字
+
+
+ New Style… 新建样式…
+ Style {name} saved 已保存样式 {name}
+
+ Create new style (from the selected type) 新建样式(基于所选文本)
+ Create new style from the selected layer 从所选图层新建样式
+
+ Make Default 设为默认
+ Reset to Default 重置为默认
Full-resolution preview unavailable 全分辨率预览不可用
No patterns 无图案
Enable {name} 启用{name}
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 251237693..ed3bc4edc 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -905,8 +905,6 @@
Create new pattern from the selection 從選取範圍建立新圖樣
Create new shape from the current path 從目前路徑建立新形狀
Create new snapshot 建立新快照
- Create new style (from the selected type) 建立新樣式 (依所選文字)
- Create new style from the selected layer 從所選圖層建立新樣式
Create new tool preset 建立新工具預設集
Crop Factor 裁切係數
Ctrl Ctrl
@@ -2044,6 +2042,16 @@ cameraRaw Blending 混合
Patch: 修補:
Lasso around an area, then drag the selection 用套索圈出區域,然後拖曳選取範圍
Edit Type 編輯文字
+
+
+ New Style… 新增樣式…
+ Style {name} saved 已儲存樣式 {name}
+
+ Create new style (from the selected type) 新增樣式(基於所選文字)
+ Create new style from the selected layer 從所選圖層新增樣式
+
+ Make Default 設為預設
+ Reset to Default 重設為預設
Full-resolution preview unavailable 無法使用完整解析度預覽
No patterns 無圖樣
Enable {name} 啟用{name}
diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs
index 2a3748bb5..49ba052cd 100644
--- a/crates/ui-egui/src/layer_style.rs
+++ b/crates/ui-egui/src/layer_style.rs
@@ -1,5 +1,15 @@
-//! Photoshop-style Layer Style dialog: effect list with checkboxes on the left, parameters on the right.
-//! State lives in the dialog's `fields` (JSON), so automation can drive it like any other dialog.
+//! Photoshop-style Layer Style dialog: one row per effect instance on the left,
+//! parameters on the right. State lives in the dialog's `fields` (JSON), so
+//! automation can drive it like any other dialog:
+//!
+//! - `layer`: layer id; `globalLight`: the document's light angle (degrees)
+//! - `selected`: `"blendingOptions"` or an instance id from `effects`
+//! - `effects`: `[{id, kind, on, params, fx?}]` in the layer's effect order.
+//! `fx` is the effect snapshot the dialog loaded: the apply edits that
+//! snapshot with `params` (engine-side overlay), so everything the dialog
+//! doesn't model — gradient strokes, imported contours, PSD data — survives.
+//! An entry without `fx` is a new instance built from `params`.
+//! - `p:blendingOptions`: the layer's blend mode, opacity and fill opacity.
use egui::{Color32, RichText, Sense, Stroke, StrokeKind, vec2};
use photocraft_doc::effects::{FxPaint, StrokePosition};
@@ -21,6 +31,8 @@ enum P {
}
/// Effect kinds in Photoshop's list order: (command kind, label, params).
+/// The Styles preset gallery page id.
+pub const STYLES_PAGE: &str = "styles";
/// The Blending Options page id (not an effect).
pub const BLENDING: &str = "blendingOptions";
@@ -37,12 +49,45 @@ pub const KINDS: &[(&str, &str)] = &[
("dropShadow", "Drop Shadow"),
];
+/// Effect kinds Photoshop offers several instances of (stored as `…Multi` lists in the PSD).
+const MULTI: &[&str] = &["stroke", "dropShadow", "innerShadow", "colorOverlay", "gradientOverlay"];
+
+fn multi(kind: &str) -> bool {
+ MULTI.contains(&kind)
+}
+
+fn kind_of(e: &Effect) -> &'static str {
+ photocraft_engine::layer_style::kind_of(e)
+}
+
+fn defaults(kind: &str) -> Value {
+ photocraft_engine::layer_style::effect_defaults(kind)
+}
+
+/// Factory params for a new instance, with the shared light angle filled in.
+fn fresh_params(kind: &str, light: f32) -> Value {
+ let mut p = defaults(kind);
+ if p.get("useGlobalLight").and_then(Value::as_bool) == Some(true) {
+ p["angle"] = json!(light);
+ }
+ p
+}
+
fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
const POS: &[(&str, &str)] = &[("outside", "Outside"), ("inside", "Inside"), ("center", "Center")];
const GSTYLE: &[(&str, &str)] = &[("linear", "Linear"), ("radial", "Radial"), ("angle", "Angle"), ("reflected", "Reflected"), ("diamond", "Diamond")];
const BSTYLE: &[(&str, &str)] = &[("inner", "Inner Bevel"), ("outer", "Outer Bevel"), ("emboss", "Emboss"), ("pillow", "Pillow Emboss")];
const DIR: &[(&str, &str)] = &[("up", "Up"), ("down", "Down")];
const SRC: &[(&str, &str)] = &[("edge", "Edge"), ("center", "Center")];
+ // The built-in contour presets (photocraft_engine::layer_style::CONTOURS).
+ const CONTOUR: &[(&str, &str)] = &[
+ ("Linear", "Linear"),
+ ("Cone", "Cone"),
+ ("Cone (Inverted)", "Cone (Inverted)"),
+ ("Domed", "Domed"),
+ ("Domed (Inverted)", "Domed (Inverted)"),
+ ("Diagonal (Descending)", "Diagonal (Descending)"),
+ ];
match kind {
"dropShadow" => &[
("blend", "Blend Mode", P::Blend),
@@ -53,6 +98,8 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
("distance", "Distance", P::Slider(0.0, 300.0, "px")),
("spread", "Spread", P::Slider(0.0, 100.0, "%")),
("size", "Size", P::Slider(0.0, 250.0, "px")),
+ ("contour", "Contour", P::Choice(CONTOUR)),
+ ("noise", "Noise", P::Slider(0.0, 100.0, "%")),
("knocksOut", "Layer Knocks Out Drop Shadow", P::Check),
],
"innerShadow" => &[
@@ -64,6 +111,8 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
("distance", "Distance", P::Slider(0.0, 300.0, "px")),
("choke", "Choke", P::Slider(0.0, 100.0, "%")),
("size", "Size", P::Slider(0.0, 250.0, "px")),
+ ("contour", "Contour", P::Choice(CONTOUR)),
+ ("noise", "Noise", P::Slider(0.0, 100.0, "%")),
],
"outerGlow" => &[
("blend", "Blend Mode", P::Blend),
@@ -72,6 +121,8 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
("spread", "Spread", P::Slider(0.0, 100.0, "%")),
("size", "Size", P::Slider(0.0, 250.0, "px")),
("range", "Range", P::Slider(1.0, 100.0, "%")),
+ ("contour", "Contour", P::Choice(CONTOUR)),
+ ("noise", "Noise", P::Slider(0.0, 100.0, "%")),
],
"innerGlow" => &[
("blend", "Blend Mode", P::Blend),
@@ -80,6 +131,8 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
("source", "Source", P::Choice(SRC)),
("choke", "Choke", P::Slider(0.0, 100.0, "%")),
("size", "Size", P::Slider(0.0, 250.0, "px")),
+ ("contour", "Contour", P::Choice(CONTOUR)),
+ ("noise", "Noise", P::Slider(0.0, 100.0, "%")),
],
"stroke" => &[
("size", "Size", P::Slider(1.0, 250.0, "px")),
@@ -135,57 +188,27 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
}
}
-fn defaults(kind: &str) -> Value {
- match kind {
- "dropShadow" => {
- json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "spread": 0, "size": 5, "knocksOut": true})
- }
- "innerShadow" => {
- json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "choke": 0, "size": 5})
- }
- "outerGlow" => json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "spread": 0, "size": 5, "range": 50}),
- "innerGlow" => json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "source": "edge", "choke": 0, "size": 5}),
- "stroke" => json!({"size": 3, "position": "outside", "blend": "Normal", "opacity": 100, "color": "#000000"}),
- "colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}),
- "gradientOverlay" => {
- json!({"blend": "Normal", "opacity": 100, "from": "#000000", "to": "#ffffff", "reverse": false, "style": "linear", "angle": 90, "scale": 100})
- }
- "patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}),
- "bevelEmboss" => {
- json!({"style": "inner", "depth": 100, "direction": "up", "size": 5, "soften": 0, "angle": 120, "useGlobalLight": true, "altitude": 30})
- }
- "satin" => json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 19, "distance": 11, "size": 14, "invert": true}),
- _ => json!({}),
- }
-}
-
fn hex(c: &photocraft_doc::Color) -> String {
let [r, g, b, _] = c.to_rgba8();
format!("#{r:02x}{g:02x}{b:02x}")
}
-fn kind_of(e: &Effect) -> &'static str {
- match e {
- Effect::DropShadow(_) => "dropShadow",
- Effect::InnerShadow(_) => "innerShadow",
- Effect::OuterGlow(_) => "outerGlow",
- Effect::InnerGlow(_) => "innerGlow",
- Effect::Stroke(_) => "stroke",
- Effect::ColorOverlay { .. } => "colorOverlay",
- Effect::GradientOverlay { .. } => "gradientOverlay",
- Effect::PatternOverlay { .. } => "patternOverlay",
- Effect::Satin(_) => "satin",
- Effect::BevelEmboss(_) => "bevelEmboss",
- }
-}
-
-/// Current values of an existing effect, in the command's parameter units.
+/// Current values of an existing effect, in the command's parameter units —
+/// only the keys this dialog models. Everything else (gradient strokes, multi-stop
+/// gradients, imported contours) is left out so the apply overlay can't clobber it.
/// `light` is the document's global light angle: an effect that uses it shows that angle.
fn values_of(e: &Effect, light: f32) -> Value {
let mut v = defaults(kind_of(e));
let set = |v: &mut Value, k: &str, x: Value| {
v[k] = x;
};
+ let drop_keys = |v: &mut Value, keys: &[&str]| {
+ if let Some(o) = v.as_object_mut() {
+ for k in keys {
+ o.remove(*k);
+ }
+ }
+ };
match e {
Effect::DropShadow(s) | Effect::InnerShadow(s) => {
set(&mut v, "blend", json!(s.common.blend.label()));
@@ -196,16 +219,25 @@ fn values_of(e: &Effect, light: f32) -> Value {
set(&mut v, "distance", json!(s.distance));
set(&mut v, if matches!(e, Effect::DropShadow(_)) { "spread" } else { "choke" }, json!((s.spread * 100.0).round()));
set(&mut v, "size", json!(s.size));
+ set(&mut v, "contour", photocraft_engine::layer_style::contour_param(&s.contour));
+ set(&mut v, "noise", json!((s.noise * 100.0).round()));
+ if matches!(e, Effect::DropShadow(_)) {
+ set(&mut v, "knocksOut", json!(s.knocks_out));
+ }
}
Effect::OuterGlow(g) | Effect::InnerGlow(g) => {
set(&mut v, "blend", json!(g.common.blend.label()));
set(&mut v, "opacity", json!((g.common.opacity * 100.0).round()));
if let FxPaint::Color(c) = &g.paint {
set(&mut v, "color", json!(hex(c)));
+ } else {
+ drop_keys(&mut v, &["color"]);
}
set(&mut v, if matches!(e, Effect::OuterGlow(_)) { "spread" } else { "choke" }, json!((g.spread * 100.0).round()));
set(&mut v, "size", json!(g.size));
set(&mut v, "range", json!((g.range * 100.0).round()));
+ set(&mut v, "contour", photocraft_engine::layer_style::contour_param(&g.contour));
+ set(&mut v, "noise", json!((g.noise * 100.0).round()));
}
Effect::Stroke(s) => {
set(&mut v, "blend", json!(s.common.blend.label()));
@@ -222,6 +254,10 @@ fn values_of(e: &Effect, light: f32) -> Value {
);
if let FxPaint::Color(c) = &s.paint {
set(&mut v, "color", json!(hex(c)));
+ } else {
+ // A gradient/pattern stroke: the dialog's colour field doesn't model
+ // the paint, so the key is left out and the snapshot carries it.
+ drop_keys(&mut v, &["color"]);
}
}
Effect::ColorOverlay { common, color } => {
@@ -229,9 +265,41 @@ fn values_of(e: &Effect, light: f32) -> Value {
set(&mut v, "opacity", json!((common.opacity * 100.0).round()));
set(&mut v, "color", json!(hex(color)));
}
- Effect::GradientOverlay { common, .. } => {
+ Effect::GradientOverlay { common, gradient: g, .. } => {
set(&mut v, "blend", json!(common.blend.label()));
set(&mut v, "opacity", json!((common.opacity * 100.0).round()));
+ // The From/To fields model a plain two-stop gradient; anything richer
+ // (more stops, transparency stops) is carried by the snapshot instead.
+ if g.stops.len() == 2 && g.opacity_stops.is_empty() {
+ set(&mut v, "from", json!(hex(&g.stops[0].1)));
+ set(&mut v, "to", json!(hex(&g.stops[1].1)));
+ set(&mut v, "reverse", json!(g.reverse));
+ set(
+ &mut v,
+ "style",
+ json!(match g.style {
+ photocraft_doc::effects::GradientStyle::Radial => "radial",
+ photocraft_doc::effects::GradientStyle::Angle => "angle",
+ photocraft_doc::effects::GradientStyle::Reflected => "reflected",
+ photocraft_doc::effects::GradientStyle::Diamond => "diamond",
+ photocraft_doc::effects::GradientStyle::Linear => "linear",
+ }),
+ );
+ set(&mut v, "angle", json!(g.angle));
+ set(&mut v, "scale", json!((g.scale * 100.0).round()));
+ } else {
+ drop_keys(&mut v, &["from", "to", "reverse", "style", "angle", "scale"]);
+ }
+ }
+ Effect::PatternOverlay { common, name, id, scale, angle, link, phase } => {
+ set(&mut v, "blend", json!(common.blend.label()));
+ set(&mut v, "opacity", json!((common.opacity * 100.0).round()));
+ set(&mut v, "pattern", json!(if id.is_empty() { name } else { id }));
+ set(&mut v, "scale", json!((scale * 100.0).round()));
+ set(&mut v, "angle", json!(angle));
+ set(&mut v, "link", json!(link));
+ set(&mut v, "phaseX", json!(phase.0));
+ set(&mut v, "phaseY", json!(phase.1));
}
Effect::Satin(s) => {
set(&mut v, "blend", json!(s.common.blend.label()));
@@ -241,61 +309,161 @@ fn values_of(e: &Effect, light: f32) -> Value {
set(&mut v, "distance", json!(s.distance));
set(&mut v, "size", json!(s.size));
set(&mut v, "invert", json!(s.invert));
+ set(&mut v, "contour", photocraft_engine::layer_style::contour_param(&s.contour));
}
Effect::BevelEmboss(b) => {
- set(&mut v, "depth", json!(b.depth));
+ set(
+ &mut v,
+ "style",
+ json!(match b.style {
+ photocraft_doc::effects::BevelStyle::OuterBevel => "outer",
+ photocraft_doc::effects::BevelStyle::Emboss => "emboss",
+ photocraft_doc::effects::BevelStyle::PillowEmboss => "pillow",
+ photocraft_doc::effects::BevelStyle::StrokeEmboss => "stroke",
+ photocraft_doc::effects::BevelStyle::InnerBevel => "inner",
+ }),
+ );
+ set(
+ &mut v,
+ "technique",
+ json!(match b.technique {
+ photocraft_doc::effects::BevelTechnique::ChiselHard => "chiselHard",
+ photocraft_doc::effects::BevelTechnique::ChiselSoft => "chiselSoft",
+ photocraft_doc::effects::BevelTechnique::Smooth => "smooth",
+ }),
+ );
+ set(&mut v, "depth", json!((b.depth * 100.0).round()));
set(&mut v, "size", json!(b.size));
set(&mut v, "soften", json!(b.soften));
set(&mut v, "angle", json!(if b.use_global_light { light } else { b.angle }));
set(&mut v, "useGlobalLight", json!(b.use_global_light));
set(&mut v, "altitude", json!(b.altitude));
set(&mut v, "direction", json!(if b.up { "up" } else { "down" }));
- }
- Effect::PatternOverlay { common, name, id, scale, angle, link, phase } => {
- set(&mut v, "blend", json!(common.blend.label()));
- set(&mut v, "opacity", json!((common.opacity * 100.0).round()));
- set(&mut v, "pattern", json!(if id.is_empty() { name } else { id }));
- set(&mut v, "scale", json!((scale * 100.0).round()));
- set(&mut v, "angle", json!(angle));
- set(&mut v, "link", json!(link));
- set(&mut v, "phaseX", json!(phase.0));
- set(&mut v, "phaseY", json!(phase.1));
+ set(&mut v, "glossContour", photocraft_engine::layer_style::contour_param(&b.gloss_contour));
}
}
v
}
-/// Dialog fields for a layer: selected kind, and per kind {enabled, params}.
-/// `light` is the document's global light angle, shown by effects that use it.
+/// The dialog's effect entries (JSON array of `{id, kind, on, params, fx?}`).
+fn effects_of(f: &Map<String, Value>) -> &[Value] {
+ f.get("effects").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
+}
+
+fn entry<'a>(f: &'a Map<String, Value>, id: &str) -> Option<&'a Value> {
+ effects_of(f).iter().find(|e| e.get("id").and_then(Value::as_str) == Some(id))
+}
+
+fn entry_mut<'a>(f: &'a mut Map<String, Value>, id: &str) -> Option<&'a mut Value> {
+ f.get_mut("effects").and_then(Value::as_array_mut).and_then(|a| a.iter_mut().find(|e| e.get("id").and_then(Value::as_str) == Some(id)))
+}
+
+/// Stores one edited parameter of an instance (or of the blending page).
+fn set_param(f: &mut Map<String, Value>, id: &str, key: &str, value: Value) {
+ if id == BLENDING || id == STYLES_PAGE {
+ if let Some(o) = f.get_mut("p:blendingOptions").and_then(Value::as_object_mut) {
+ o.insert(key.into(), value);
+ }
+ return;
+ }
+ if let Some(e) = entry_mut(f, id)
+ && let Some(o) = e.get_mut("params").and_then(Value::as_object_mut)
+ {
+ o.insert(key.into(), value);
+ }
+}
+
+/// A fresh instance id: one past the highest numbered `fxN` in the list.
+fn next_id(f: &Map<String, Value>) -> String {
+ let max = effects_of(f)
+ .iter()
+ .filter_map(|e| e.get("id").and_then(Value::as_str))
+ .filter_map(|id| id.strip_prefix("fx"))
+ .filter_map(|n| n.parse::<u64>().ok())
+ .max()
+ .unwrap_or(0);
+ format!("fx{}", max + 1)
+}
+
+/// Adds an instance of `kind`, right after the last one of its kind (the list,
+/// and so the rendered stack, keeps the layer's effect order), and selects it.
+fn add_instance(f: &mut Map<String, Value>, kind: &str) {
+ let light = f.get("globalLight").and_then(Value::as_f64).unwrap_or(120.0) as f32;
+ let id = next_id(f);
+ let new = json!({"id": id, "kind": kind, "on": true, "params": fresh_params(kind, light)});
+ if let Some(a) = f.get_mut("effects").and_then(Value::as_array_mut) {
+ let pos = a.iter().rposition(|e| e.get("kind").and_then(Value::as_str) == Some(kind)).map_or(a.len(), |i| i + 1);
+ a.insert(pos, new);
+ }
+ f.insert("selected".into(), json!(id));
+}
+
+/// Removes an instance; the selection moves to a sibling of the same kind,
+/// else to the blending page.
+fn remove_instance(f: &mut Map<String, Value>, id: &str) {
+ let kind = entry(f, id).and_then(|e| e.get("kind").and_then(Value::as_str)).map(str::to_string);
+ if let Some(a) = f.get_mut("effects").and_then(Value::as_array_mut) {
+ a.retain(|e| e.get("id").and_then(Value::as_str) != Some(id));
+ }
+ let selected = f.get("selected").and_then(Value::as_str).unwrap_or_default().to_string();
+ if selected == id {
+ let sibling = kind
+ .as_deref()
+ .and_then(|kind| effects_of(f).iter().find(|e| e.get("kind").and_then(Value::as_str) == Some(kind)))
+ .and_then(|e| e.get("id").and_then(Value::as_str))
+ .map(str::to_string);
+ f.insert("selected".into(), json!(sibling.unwrap_or_else(|| STYLES_PAGE.into())));
+ }
+}
+
+/// Dialog fields for a layer: one entry per effect instance (all of them, in
+/// the layer's order), the blending options and the selected page. `select`
+/// names a kind to open: its first instance is selected (and enabled), or one
+/// is created. `light` is the document's global light angle.
pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map<String, Value> {
let mut f = Map::new();
f.insert("layer".into(), json!(layer.id.0));
f.insert("globalLight".into(), json!(light));
+ f.insert("preview".into(), json!(true));
f.insert(
format!("p:{BLENDING}"),
json!({"blend": layer.blend.label(), "opacity": (layer.opacity * 100.0).round(), "fillOpacity": (layer.fill_opacity * 100.0).round()}),
);
- let mut first = None;
- for &(kind, _) in KINDS {
- let existing = layer.effects.items.iter().find(|e| kind_of(e) == kind);
- if existing.is_some() && first.is_none() {
- first = Some(kind);
- }
- f.insert(format!("on:{kind}"), json!(existing.is_some_and(|e| e.enabled())));
- let params = existing.map(|e| values_of(e, light)).unwrap_or_else(|| {
- let mut params = defaults(kind);
- if params.get("useGlobalLight").and_then(Value::as_bool) == Some(true) {
- params["angle"] = json!(light);
- }
- params
- });
- f.insert(format!("p:{kind}"), params);
- }
- let sel = select.or(first).unwrap_or("dropShadow");
- f.insert("selected".into(), json!(sel));
- if select.is_some() {
- f.insert(format!("on:{sel}"), json!(true));
+ let mut effects = Vec::new();
+ for (i, e) in layer.effects.items.iter().enumerate() {
+ effects.push(json!({
+ "id": format!("fx{}", i + 1),
+ "kind": kind_of(e),
+ "on": e.enabled(),
+ "params": values_of(e, light),
+ "fx": serde_json::to_value(e).unwrap_or(Value::Null),
+ }));
}
+ f.insert("effects".into(), Value::Array(effects));
+ let selected = match select {
+ None => effects_of(&f).first().and_then(|e| e.get("id").and_then(Value::as_str)).map(str::to_string).unwrap_or_else(|| "dropShadow".into()),
+ Some(STYLES_PAGE) => STYLES_PAGE.to_string(),
+ Some(BLENDING) => BLENDING.to_string(),
+ Some(kind) => {
+ let existing = effects_of(&f)
+ .iter()
+ .find(|e| e.get("kind").and_then(Value::as_str) == Some(kind))
+ .map(|e| e.get("id").and_then(Value::as_str).unwrap_or_default().to_string());
+ match existing {
+ Some(id) => {
+ if let Some(e) = entry_mut(&mut f, &id) {
+ e["on"] = json!(true);
+ }
+ id
+ }
+ None => {
+ add_instance(&mut f, kind);
+ f.get("selected").and_then(Value::as_str).unwrap_or_default().to_string()
+ }
+ }
+ }
+ };
+ f.insert("selected".into(), json!(selected));
f
}
@@ -321,7 +489,7 @@ pub fn pattern_list(app: &PhotocraftApp) -> Value {
Value::Array(out)
}
-/// Apply the dialog: replace the layer's effects with the enabled ones.
+/// Apply the dialog: replace the layer's effects with the dialog's instances.
pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
apply(f, |id, p| app.run(id, p))
}
@@ -329,18 +497,32 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
/// Every parameter group is edited as an object. Validate before preview or confirmation so
/// malformed values supplied through `ui.dialog.set` are reported before any command runs.
fn validate_params(f: &Map<String, Value>) -> Result<(), String> {
- for kind in std::iter::once(BLENDING).chain(KINDS.iter().map(|(kind, _)| *kind)) {
- let key = format!("p:{kind}");
- if let Some(value) = f.get(&key)
- && !value.is_object()
+ let key = format!("p:{BLENDING}");
+ if let Some(value) = f.get(&key)
+ && !value.is_object()
+ {
+ return Err(format!("invalid layer style parameters: `{key}` must be an object"));
+ }
+ let Some(effects) = f.get("effects") else { return Ok(()) };
+ let Some(effects) = effects.as_array() else {
+ return Err("invalid layer style parameters: `effects` must be an array".into());
+ };
+ for (i, e) in effects.iter().enumerate() {
+ let Some(e) = e.as_object() else {
+ return Err(format!("invalid layer style parameters: `effects[{i}]` must be an object"));
+ };
+ if let Some(params) = e.get("params")
+ && !params.is_object()
{
- return Err(format!("invalid layer style parameters: `{key}` must be an object"));
+ return Err(format!("invalid layer style parameters: `effects[{i}].params` must be an object"));
}
}
Ok(())
}
-/// Runs the dialog's commands through `run`: blending options, clear, then each enabled effect.
+/// Runs the dialog's commands through `run`: blending options, then the whole
+/// effect list in one `layer.layerStyle.replace` (instances keep their order;
+/// their snapshots carry what the dialog doesn't model).
fn apply(f: &Map<String, Value>, mut run: impl FnMut(&str, Value) -> Result<Value, String>) -> Result<Value, String> {
validate_params(f)?;
let layer = f.get("layer").cloned().unwrap_or(Value::Null);
@@ -352,23 +534,43 @@ fn apply(f: &Map<String, Value>, mut run: impl FnMut(&str, Value) -> Result<Valu
}
run("layer.layerStyle.blendingOptions", p)?;
}
- let _ = run("layer.layerStyle.clear", json!({"layer": layer}));
+ let mut entries = Vec::new();
+ for e in effects_of(f) {
+ let (Some(kind), Some(_)) = (e.get("kind").and_then(Value::as_str), e.get("id").and_then(Value::as_str)) else { continue };
+ let on = e.get("on").and_then(Value::as_bool).unwrap_or(true);
+ let params = e.get("params").cloned().unwrap_or_else(|| json!({}));
+ let mut params = params;
+ params["enabled"] = json!(on);
+ let entry = match e.get("fx").filter(|fx| fx.is_object()) {
+ Some(fx) => json!({"kind": kind, "fx": fx, "params": params}),
+ None => {
+ // A new instance: the page shows the factory defaults merged with
+ // the edits, and the engine builds from the full set.
+ let mut p = defaults(kind);
+ if let (Some(o), Some(pv)) = (p.as_object_mut(), params.as_object()) {
+ for (k, v) in pv {
+ o.insert(k.clone(), v.clone());
+ }
+ }
+ json!({"kind": kind, "params": p})
+ }
+ };
+ entries.push(entry);
+ }
+ run("layer.layerStyle.replace", json!({"layer": layer, "effects": entries}))?;
// An effect lit by the global light follows the document's light angle, so the Angle slider
// drives that shared angle rather than the per-effect angle the compositor ignores.
let mut light_angle: Option<f64> = None;
- for &(kind, _) in KINDS {
- if f.get(&format!("on:{kind}")).and_then(Value::as_bool) == Some(true) {
- let mut p = f.get(&format!("p:{kind}")).cloned().unwrap_or_else(|| json!({}));
- if let Some(params) = p.as_object_mut() {
- params.insert("layer".into(), layer.clone());
- }
- if p.get("useGlobalLight").and_then(Value::as_bool) == Some(true)
- && let Some(angle) = p.get("angle").and_then(Value::as_f64)
- && initial_light_angle.is_none_or(|initial| angle != initial)
- {
- light_angle = Some(angle);
- }
- run(&format!("layer.layerStyle.{kind}"), p)?;
+ for e in effects_of(f) {
+ if e.get("on").and_then(Value::as_bool) != Some(true) {
+ continue;
+ }
+ let params = e.get("params").cloned().unwrap_or_else(|| json!({}));
+ if params.get("useGlobalLight").and_then(Value::as_bool) == Some(true)
+ && let Some(angle) = params.get("angle").and_then(Value::as_f64)
+ && initial_light_angle.is_none_or(|initial| angle != initial)
+ {
+ light_angle = Some(angle);
}
}
if let Some(angle) = light_angle {
@@ -380,7 +582,7 @@ fn apply(f: &Map<String, Value>, mut run: impl FnMut(&str, Value) -> Result<Valu
/// Hash of the fields that change the rendered style (not the selected page).
pub fn preview_hash(f: &Map<String, Value>) -> u64 {
f.iter()
- .filter(|(k, _)| k.as_str() == "layer" || k.starts_with("on:") || k.starts_with("p:"))
+ .filter(|(k, _)| k.as_str() == "layer" || k.as_str() == "effects" || k.as_str() == "p:blendingOptions")
.flat_map(|(k, v)| k.bytes().chain(v.to_string().into_bytes()))
.fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ b as u64).wrapping_mul(0x100_0000_01b3))
}
@@ -398,149 +600,361 @@ pub fn preview_document(
s.active().map(|d| (*d.doc).clone()).ok_or_else(|| "no preview document".into())
}
+/// Applies a style preset to the dialog fields in-place without touching the document.
+/// Clicking Cancel leaves the document untouched; clicking OK commits.
+fn apply_style_preset(app: &PhotocraftApp, f: &mut Map<String, Value>, name: &str) {
+ let Ok(style) = photocraft_engine::presets::styles::find_style(&app.session, &json!({"preset": name}), "apply_style_preset") else { return };
+ let light = f.get("globalLight").and_then(Value::as_f64).unwrap_or(120.0) as f32;
+ let mut effects = Vec::new();
+ for (i, e) in style.effects.iter().enumerate() {
+ effects.push(json!({
+ "id": format!("fx{}", i + 1),
+ "kind": kind_of(e),
+ "on": e.enabled(),
+ "params": values_of(e, light),
+ "fx": serde_json::to_value(e).unwrap_or(Value::Null),
+ }));
+ }
+ f.insert("effects".into(), Value::Array(effects));
+ if let Some(b) = style.blend {
+ set_param(f, BLENDING, "blend", json!(b.label()));
+ }
+ if let Some(fo) = style.fill_opacity {
+ set_param(f, BLENDING, "fillOpacity", json!((fo * 100.0).round()));
+ }
+}
+
+/// Saves the dialog's pending state (enabled instances + blending page) as a style preset.
+fn save_new_style(app: &mut PhotocraftApp, f: &Map<String, Value>) {
+ let mut entries = Vec::new();
+ for e in effects_of(f) {
+ if e.get("on").and_then(Value::as_bool) != Some(true) {
+ continue;
+ }
+ let Some(kind) = e.get("kind").and_then(Value::as_str) else { continue };
+ let mut params = defaults(kind);
+ if let (Some(o), Some(pv)) = (params.as_object_mut(), e.get("params").and_then(Value::as_object)) {
+ for (k, v) in pv {
+ o.insert(k.clone(), v.clone());
+ }
+ }
+ entries.push(json!([kind, params]));
+ }
+ let bo = f.get("p:blendingOptions").cloned().unwrap_or_else(|| json!({}));
+ if let Ok(v) = app.run(
+ "style.presets.new",
+ json!({
+ "layer": f.get("layer").cloned().unwrap_or(Value::Null),
+ "effects": entries,
+ "blend": bo.get("blend").cloned().unwrap_or(Value::Null),
+ "fillOpacity": bo.get("fillOpacity").cloned().unwrap_or(Value::Null),
+ }),
+ ) {
+ app.ui.status = crate::i18n::fmt(tl!("Style {name} saved"), &[("name", v["name"].as_str().unwrap_or("Style"))]);
+ }
+}
+
/// Dialog body (left list, right parameters).
-pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
let t = Tokens::get(ui.ctx());
let selected = f.get("selected").and_then(Value::as_str).unwrap_or("dropShadow").to_string();
+ let mut style_click: Option<String> = None;
+ let mut new_style = false;
let invalid = validate_params(f).err();
ui.horizontal_top(|ui| {
// Left: effect list.
ui.vertical(|ui| {
ui.set_width(190.0);
- ui.label(RichText::new(tl!("Styles")).color(t.text_faint));
- // Blending Options page (layer blend mode, opacity and fill opacity).
- let bo = ui.add(
- egui::Label::new(RichText::new(tl!("Blending Options")).color(if selected == BLENDING { t.text } else { t.text_dim })).sense(Sense::click()),
- );
- if bo.clicked() {
- f.insert("selected".into(), json!(BLENDING));
- }
- ui.add_space(4.0);
- for &(kind, label) in KINDS {
+ // Styles & Blending Options rows (matching the effect row layout & padding).
+ for (id, label) in [(STYLES_PAGE, "Styles"), (BLENDING, "Blending Options")] {
+ let is_sel = selected == id;
let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 26.0), Sense::click());
- let is_sel = kind == selected;
if is_sel {
ui.painter().rect_filled(rect, t.radius_sm, t.row_selected.gamma_multiply(if t.pro { 1.0 } else { 0.0 }).max_alpha(t.hover));
} else if resp.hovered() {
ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5));
}
- let key = format!("on:{kind}");
- let mut on = f.get(&key).and_then(Value::as_bool).unwrap_or(false);
- let cb = egui::Rect::from_min_size(rect.min + vec2(6.0, 6.0), vec2(14.0, 14.0));
- let cresp = ui.interact(cb, ui.id().with(("fxcb", kind)), Sense::click());
- if on {
- ui.painter().rect_filled(cb, 2.0, t.accent);
- ui.painter().line_segment([cb.left_center() + vec2(3.0, 0.5), cb.center_bottom() + vec2(-1.0, -3.5)], Stroke::new(1.8, Color32::WHITE));
- ui.painter().line_segment([cb.center_bottom() + vec2(-1.0, -3.5), cb.right_top() + vec2(-3.0, 3.5)], Stroke::new(1.8, Color32::WHITE));
- } else {
- ui.painter().rect_stroke(cb, 2.0, Stroke::new(1.5, t.text_faint), StrokeKind::Inside);
- }
ui.painter().text(
rect.left_center() + vec2(28.0, 0.0),
egui::Align2::LEFT_CENTER,
tl!(label),
egui::FontId::proportional(12.5),
- if on || is_sel { t.text } else { t.text_dim },
+ if is_sel { t.text } else { t.text_dim },
);
- if cresp.clicked() {
- on = !on;
- f.insert(key, json!(on));
- f.insert("selected".into(), json!(kind));
- } else if resp.clicked() {
- f.insert("selected".into(), json!(kind));
- f.insert(key, json!(true));
+ if resp.clicked() {
+ f.insert("selected".into(), json!(id));
+ }
+ }
+ ui.add_space(4.0);
+ for &(kind, label) in KINDS {
+ let ids: Vec<String> = effects_of(f)
+ .iter()
+ .filter(|e| e.get("kind").and_then(Value::as_str) == Some(kind))
+ .filter_map(|e| e.get("id").and_then(Value::as_str).map(str::to_string))
+ .collect();
+ if ids.is_empty() {
+ // The effect isn't on the layer: a greyed row that adds it.
+ let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 26.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5));
+ }
+ ui.painter().text(
+ rect.left_center() + vec2(28.0, 0.0),
+ egui::Align2::LEFT_CENTER,
+ tl!(label),
+ egui::FontId::proportional(12.5),
+ t.text_faint,
+ );
+ if resp.clicked() {
+ add_instance(f, kind);
+ }
+ continue;
+ }
+ let count = ids.len();
+ for id in &ids {
+ let Some(e) = entry(f, id) else { continue };
+ let kind_label = KINDS.iter().find(|k| k.0 == kind).map(|k| k.1).unwrap_or(label);
+ let mut on = e.get("on").and_then(Value::as_bool).unwrap_or(false);
+ let is_sel = id == &selected;
+ let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 26.0), Sense::click());
+ if is_sel {
+ ui.painter().rect_filled(rect, t.radius_sm, t.row_selected.gamma_multiply(if t.pro { 1.0 } else { 0.0 }).max_alpha(t.hover));
+ } else if resp.hovered() {
+ ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5));
+ }
+ let cb = egui::Rect::from_min_size(rect.min + vec2(6.0, 6.0), vec2(14.0, 14.0));
+ let cresp = ui.interact(cb, ui.id().with(("fxcb", kind, id)), Sense::click());
+ if on {
+ ui.painter().rect_filled(cb, 2.0, t.accent);
+ ui.painter().line_segment([cb.left_center() + vec2(3.0, 0.5), cb.center_bottom() + vec2(-1.0, -3.5)], Stroke::new(1.8, Color32::WHITE));
+ ui.painter().line_segment([cb.center_bottom() + vec2(-1.0, -3.5), cb.right_top() + vec2(-3.0, 3.5)], Stroke::new(1.8, Color32::WHITE));
+ } else {
+ ui.painter().rect_stroke(cb, 2.0, Stroke::new(1.5, t.text_faint), StrokeKind::Inside);
+ }
+ ui.painter().text(
+ rect.left_center() + vec2(28.0, 0.0),
+ egui::Align2::LEFT_CENTER,
+ tl!(kind_label),
+ egui::FontId::proportional(12.5),
+ if on || is_sel { t.text } else { t.text_dim },
+ );
+ // + adds another instance; − removes one once there are several.
+ if multi(kind) {
+ let btn = |ui: &egui::Ui, at: egui::Pos2, glyph: &str, tag: &str| {
+ let r = egui::Rect::from_center_size(at, vec2(18.0, 18.0));
+ let hresp = ui.interact(r, ui.id().with(("fxbtn", tag, id)), Sense::click());
+ let col = if hresp.hovered() { t.accent } else { t.text_faint };
+ ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(13.0), col);
+ hresp.clicked()
+ };
+ if count > 1 && btn(ui, rect.right_center() - vec2(22.0, 0.0), "\u{2212}", "minus") {
+ remove_instance(f, id);
+ continue;
+ }
+ if btn(ui, rect.right_center() - vec2(8.0, 0.0), "+", "plus") {
+ add_instance(f, kind);
+ }
+ }
+ if cresp.clicked() {
+ on = !on;
+ if let Some(e) = entry_mut(f, id) {
+ e["on"] = json!(on);
+ }
+ f.insert("selected".into(), json!(id));
+ } else if resp.clicked() {
+ f.insert("selected".into(), json!(id));
+ }
}
}
});
widgets::vline(ui, 330.0);
- // Right: parameters of the selected effect.
+ // Right: parameters of the selected page.
ui.vertical(|ui| {
ui.set_width(330.0);
- let label = KINDS.iter().find(|k| k.0 == selected).map(|k| k.1).unwrap_or(if selected == BLENDING { "Blending Options" } else { "" });
- ui.label(RichText::new(tl!(&label)).font(crate::theme::semibold(14.0)).color(t.text));
+ if selected == STYLES_PAGE {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(tl!("Styles")).font(crate::theme::semibold(14.0)).color(t.text));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::widgets::secondary_button(ui, tl!("New Style…"), 100.0).clicked() {
+ new_style = true;
+ }
+ });
+ });
+ ui.add_space(8.0);
+ let ctx = ui.ctx().clone();
+ egui::ScrollArea::vertical().max_height(340.0).id_salt("layer-style-presets-main").show(ui, |ui| {
+ for group in &app.session.presets.styles {
+ ui.label(RichText::new(&group.name).size(12.0).color(t.text_dim));
+ ui.add_space(3.0);
+ ui.horizontal_wrapped(|ui| {
+ ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
+ for st in &group.items {
+ let tex = crate::preset_panels::style_texture(app, &ctx, st);
+ let (rect, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click());
+ ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
+ let (stroke, kind) = if resp.hovered() {
+ (Stroke::new(1.5, t.accent), egui::StrokeKind::Outside)
+ } else {
+ (Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside)
+ };
+ ui.painter().rect_stroke(rect, 2.0, stroke, kind);
+ if resp.on_hover_text(&st.name).clicked() {
+ style_click = Some(st.name.clone());
+ }
+ }
+ });
+ ui.add_space(10.0);
+ }
+ });
+ return;
+ }
+ let sel_kind: String = if selected == BLENDING {
+ BLENDING.to_string()
+ } else {
+ entry(f, &selected).and_then(|e| e.get("kind").and_then(Value::as_str)).unwrap_or("").to_string()
+ };
+ let label = KINDS.iter().find(|k| k.0 == sel_kind).map(|k| k.1).unwrap_or(if selected == BLENDING { "Blending Options" } else { "" });
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(tl!(&label)).font(crate::theme::semibold(14.0)).color(t.text));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let mut preview = f.get("preview").and_then(Value::as_bool).unwrap_or(true);
+ if widgets::checkbox(ui, &mut preview, tl!("Preview")).changed() {
+ f.insert("preview".into(), json!(preview));
+ }
+ });
+ });
ui.add_space(6.0);
- let pkey = format!("p:{selected}");
// Only reachable through `ui.dialog.set`: say what is wrong once, keep the bad value.
if let Some(error) = &invalid {
ui.colored_label(t.danger, error);
+ return;
}
- let params = f.get(&pkey).cloned().unwrap_or_else(|| defaults(&selected));
- if let Some(mut p) = params.as_object().map(|o| Value::Object(o.clone())) {
- for &(key, label, kind) in spec(&selected) {
- match kind {
- P::Slider(min, max, unit) => {
- let mut v = p.get(key).and_then(Value::as_f64).unwrap_or(min as f64) as f32;
- if widgets::slider_row(ui, label, &mut v, min..=max, unit, None).changed() {
- p[key] = json!(v.round());
- }
- }
- P::Color => {
- ui.horizontal(|ui| {
- ui.label(RichText::new(tl!(&label)).color(t.text_dim));
- let hexs = p.get(key).and_then(Value::as_str).unwrap_or("#000000").to_string();
- let mut c = parse_hex(&hexs);
- if ui.color_edit_button_srgba(&mut c).changed() {
- p[key] = json!(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b()));
- }
- });
- }
- P::Blend => {
- ui.horizontal(|ui| {
- ui.label(RichText::new(tl!(&label)).color(t.text_dim));
- let mut cur = p.get(key).and_then(Value::as_str).unwrap_or("Normal").to_string();
- let opts: Vec<(String, &str)> =
- photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect();
- if widgets::dropdown(ui, &format!("fx-blend-{selected}"), &mut cur, &opts, 150.0) {
- p[key] = json!(cur);
- }
- });
- }
- P::Choice(options) => {
- ui.horizontal(|ui| {
- ui.label(RichText::new(tl!(&label)).color(t.text_dim));
- let mut cur = p.get(key).and_then(Value::as_str).unwrap_or(options[0].0).to_string();
- let opts: Vec<(String, &str)> = options.iter().map(|(v, l)| (v.to_string(), *l)).collect();
- if widgets::dropdown(ui, &format!("fx-{selected}-{key}"), &mut cur, &opts, 150.0) {
- p[key] = json!(cur);
- }
- });
+ // The page shows the factory defaults under the instance's values,
+ // but only real edits reach the stored params.
+ let disp = if selected == BLENDING {
+ f.get("p:blendingOptions").cloned().unwrap_or_else(|| json!({}))
+ } else {
+ entry(f, &selected).and_then(|e| e.get("params").cloned()).unwrap_or_else(|| json!({}))
+ };
+ let Some(mut disp) = disp.as_object().map(|o| Value::Object(o.clone())) else { return };
+ if selected != BLENDING {
+ let base = defaults(&sel_kind);
+ if let (Some(o), Some(b)) = (disp.as_object_mut(), base.as_object()) {
+ for (k, v) in b {
+ o.entry(k.clone()).or_insert_with(|| v.clone());
+ }
+ }
+ }
+ for &(key, label, kind_p) in spec(&sel_kind) {
+ match kind_p {
+ P::Slider(min, max, unit) => {
+ let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(min as f64) as f32;
+ if widgets::slider_row(ui, label, &mut v, min..=max, unit, None).changed() {
+ let value = json!(v.round());
+ disp[key] = value.clone();
+ set_param(f, &selected, key, value);
}
- P::Pattern => {
- let list: Vec<(String, String)> = f
- .get("patternList")
- .and_then(Value::as_array)
- .map(|a| a.iter().filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))).collect())
+ }
+ P::Color => {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(tl!(&label)).color(t.text_dim));
+ let hexs = disp.get(key).and_then(Value::as_str).unwrap_or("#000000").to_string();
+ let mut c = parse_hex(&hexs);
+ if ui.color_edit_button_srgba(&mut c).changed() {
+ let value = json!(format!("#{r:02x}{g:02x}{b:02x}", r = c.r(), g = c.g(), b = c.b()));
+ disp[key] = value.clone();
+ set_param(f, &selected, key, value);
+ }
+ });
+ }
+ P::Blend => {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(tl!(&label)).color(t.text_dim));
+ let mut cur = disp.get(key).and_then(Value::as_str).unwrap_or("Normal").to_string();
+ let opts: Vec<(String, &str)> =
+ photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect();
+ if widgets::dropdown(ui, &format!("fx-blend-{sel_kind}"), &mut cur, &opts, 150.0) {
+ let value = json!(cur);
+ disp[key] = value.clone();
+ set_param(f, &selected, key, value);
+ }
+ });
+ }
+ P::Choice(options) => {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(tl!(&label)).color(t.text_dim));
+ let mut cur = disp.get(key).and_then(Value::as_str).unwrap_or(options[0].0).to_string();
+ let opts: Vec<(String, &str)> = options.iter().map(|(v, l)| (v.to_string(), *l)).collect();
+ if widgets::dropdown(ui, &format!("fx-{sel_kind}-{key}"), &mut cur, &opts, 150.0) {
+ let value = json!(cur);
+ disp[key] = value.clone();
+ set_param(f, &selected, key, value);
+ }
+ });
+ }
+ P::Pattern => {
+ let list: Vec<(String, String)> = f
+ .get("patternList")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))).collect())
+ .unwrap_or_default();
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(tl!(&label)).color(t.text_dim));
+ let mut cur = disp
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|c| !c.is_empty())
+ .map(str::to_string)
+ .or_else(|| list.first().map(|l| l.0.clone()))
.unwrap_or_default();
- ui.horizontal(|ui| {
- ui.label(RichText::new(tl!(&label)).color(t.text_dim));
- let mut cur = p
- .get(key)
- .and_then(Value::as_str)
- .filter(|c| !c.is_empty())
- .map(str::to_string)
- .or_else(|| list.first().map(|l| l.0.clone()))
- .unwrap_or_default();
- let opts: Vec<(String, &str)> = list.iter().map(|(id, n)| (id.clone(), n.as_str())).collect();
- if widgets::dropdown(ui, &format!("fx-{selected}-{key}"), &mut cur, &opts, 180.0)
- || p.get(key).and_then(Value::as_str).is_none_or(str::is_empty)
- {
- p[key] = json!(cur);
- }
- });
- }
- P::Check => {
- let mut b = p.get(key).and_then(Value::as_bool).unwrap_or(false);
- if widgets::checkbox(ui, &mut b, label).changed() {
- p[key] = json!(b);
+ let opts: Vec<(String, &str)> = list.iter().map(|(id, n)| (id.clone(), n.as_str())).collect();
+ if widgets::dropdown(ui, &format!("fx-{sel_kind}-{key}"), &mut cur, &opts, 180.0)
+ || disp.get(key).and_then(Value::as_str).is_none_or(str::is_empty)
+ {
+ let value = json!(cur);
+ disp[key] = value.clone();
+ set_param(f, &selected, key, value);
}
+ });
+ }
+ P::Check => {
+ let mut b = disp.get(key).and_then(Value::as_bool).unwrap_or(false);
+ if widgets::checkbox(ui, &mut b, label).changed() {
+ let value = json!(b);
+ disp[key] = value.clone();
+ set_param(f, &selected, key, value);
}
}
- ui.add_space(2.0);
}
- f.insert(pkey, p);
+ ui.add_space(2.0);
}
+ // Make Default stores this page as the user default; Reset to Default
+ // restores it (or the factory defaults before the first Make).
+ let page_kind = sel_kind != BLENDING && entry(f, &selected).is_some();
+ ui.add_space(4.0);
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
+ ui.add_enabled_ui(page_kind, |ui| {
+ if crate::widgets::secondary_button(ui, tl!("Reset to Default"), 130.0).clicked()
+ && let Ok(v) = app.run("layer.layerStyle.defaultFor", json!({"kind": sel_kind}))
+ && let Some(e) = entry_mut(f, &selected)
+ {
+ e["params"] = v["params"].clone();
+ }
+ if crate::widgets::secondary_button(ui, tl!("Make Default"), 110.0).clicked() {
+ let _ = app.run("layer.layerStyle.makeDefault", json!({"kind": sel_kind, "params": disp}));
+ }
+ });
+ });
});
});
+ // Style swatch clicks apply to the layer (Photoshop does this immediately);
+ // New Style… saves the dialog's pending state as a preset.
+ if let Some(name) = style_click {
+ apply_style_preset(app, f, &name);
+ }
+ if new_style {
+ save_new_style(app, f);
+ }
}
fn parse_hex(s: &str) -> Color32 {
@@ -563,6 +977,30 @@ impl MaxAlpha for Color32 {
#[cfg(test)]
mod tests {
use super::*;
+ use photocraft_doc::StrokeFx;
+
+ fn session() -> photocraft_engine::Session {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s
+ }
+
+ fn strokes_of(s: &photocraft_engine::Session) -> Vec<StrokeFx> {
+ let d = s.active().unwrap();
+ let id = d.active_layer.unwrap();
+ d.doc
+ .layer(id)
+ .unwrap()
+ .effects
+ .items
+ .iter()
+ .filter_map(|e| match e {
+ Effect::Stroke(st) => Some(st.clone()),
+ _ => None,
+ })
+ .collect()
+ }
#[test]
fn every_kind_has_spec_and_defaults() {
@@ -576,29 +1014,130 @@ mod tests {
}
#[test]
- fn initial_fields_select_requested_kind() {
+ fn initial_fields_lists_every_instance_and_selects() {
let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8);
let f = initial_fields(&l, Some("stroke"), 120.0);
assert_eq!(f["globalLight"], json!(120.0));
- assert_eq!(f["selected"], "stroke");
- assert_eq!(f["on:stroke"], true);
- assert_eq!(f["on:dropShadow"], false);
+ // The kind isn't on the layer yet: selecting it creates the instance.
+ assert_eq!(f["effects"].as_array().unwrap().len(), 1);
+ assert_eq!(f["effects"][0]["kind"], json!("stroke"));
+ assert_eq!(f["effects"][0]["on"], json!(true));
+ assert_eq!(f["selected"], json!("fx1"));
+ // Opening the blending page selects no instance.
+ let f = initial_fields(&l, Some(BLENDING), 120.0);
+ assert_eq!(f["selected"], json!(BLENDING));
+ assert!(effects_of(&f).is_empty());
+ }
+
+ #[test]
+ fn open_and_confirm_preserves_two_strokes() {
+ // The manga/typesetting case: a 3 px black stroke under a 7 px white one.
+ let mut s = session();
+ s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap();
+ s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "add": true})).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
+ assert_eq!(effects_of(&f).len(), 2, "both instances load");
+ // Confirm without touching anything: both strokes, same order and params.
+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
+ let strokes = strokes_of(&s);
+ assert_eq!(strokes.len(), 2);
+ assert_eq!((strokes[0].size, strokes[1].size), (3.0, 7.0));
+ assert_eq!(strokes[0].paint, FxPaint::Color(photocraft_color::Color::BLACK));
+ assert_eq!(strokes[1].paint, FxPaint::Color(photocraft_color::Color::WHITE));
+ }
+
+ #[test]
+ fn editing_one_instance_leaves_its_sibling_alone() {
+ let mut s = session();
+ s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap();
+ s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "add": true})).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
+ set_param(&mut f, "fx1", "size", json!(5));
+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
+ let strokes = strokes_of(&s);
+ assert_eq!(strokes.len(), 2);
+ assert_eq!(strokes[0].size, 5.0);
+ assert_eq!(strokes[1].size, 7.0, "the second stroke is untouched");
+ assert_eq!(strokes[1].paint, FxPaint::Color(photocraft_color::Color::WHITE));
+ }
+
+ #[test]
+ fn add_and_remove_instances() {
+ let mut s = session();
+ s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
+ add_instance(&mut f, "stroke");
+ add_instance(&mut f, "stroke");
+ assert_eq!(effects_of(&f).len(), 3);
+ assert_eq!(f["selected"], json!("fx3"));
+ remove_instance(&mut f, "fx2");
+ assert_eq!(effects_of(&f).len(), 2);
+ assert_eq!(f["selected"], json!("fx3"), "selection moves to a sibling");
+ remove_instance(&mut f, "fx3");
+ assert_eq!(f["selected"], json!("fx1"), "the last sibling takes over");
+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
+ let strokes = strokes_of(&s);
+ assert_eq!(strokes.len(), 1);
+ assert_eq!(strokes[0].size, 3.0);
+ }
+
+ #[test]
+ fn disabled_instances_are_kept() {
+ let mut s = session();
+ s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
+ if let Some(e) = entry_mut(&mut f, "fx1") {
+ e["on"] = json!(false);
+ }
+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
+ let d = s.active().unwrap();
+ let items = &d.doc.layer(id).unwrap().effects.items;
+ assert_eq!(items.len(), 1, "configured but switched off stays");
+ assert!(!items[0].enabled());
+ }
+
+ #[test]
+ fn gradient_strokes_survive_the_dialog() {
+ let mut s = session();
+ s.execute("layer.layerStyle.stroke", json!({"size": 4, "from": "#ff0000", "to": "#0000ff"})).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
+ // The dialog doesn't model the gradient, so no colour key is stored for it.
+ assert!(effects_of(&f)[0]["params"].get("color").is_none());
+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
+ let strokes = strokes_of(&s);
+ assert_eq!(strokes.len(), 1);
+ assert!(
+ matches!(&strokes[0].paint, FxPaint::Gradient(g) if g.stops.len() == 2
+ && g.stops[0].1 == photocraft_color::Color::rgb(1.0, 0.0, 0.0)
+ && g.stops[1].1 == photocraft_color::Color::rgb(0.0, 0.0, 1.0)),
+ "the gradient is carried, not reset",
+ );
}
#[test]
fn preview_applies_the_style_without_touching_the_document() {
- let mut s = photocraft_engine::Session::new();
- s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
- s.execute("layer.new.layer", json!({})).unwrap();
+ let s = session();
let st = s.active().unwrap();
- let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), Some("colorOverlay"), st.doc.global_light.angle);
+ let id = st.active_layer.unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("colorOverlay"), st.doc.global_light.angle);
+ add_instance(&mut f, "stroke");
let h = preview_hash(&f);
- f.insert("selected".into(), json!("stroke"));
+ f.insert("selected".into(), json!("fx2"));
assert_eq!(preview_hash(&f), h, "switching pages doesn't re-render");
- f.insert("on:stroke".into(), json!(true));
+ set_param(&mut f, "fx2", "size", json!(5));
assert_ne!(preview_hash(&f), h);
let shown = preview_document(&st.doc, &s.patterns, &f).unwrap();
- let fx = |d: &photocraft_doc::Document| d.layer(st.active_layer.unwrap()).unwrap().effects.items.len();
+ let fx = |doc: &photocraft_doc::Document| doc.layer(id).unwrap().effects.items.len();
assert_eq!((fx(&shown), fx(&st.doc)), (2, 0));
}
@@ -609,7 +1148,8 @@ mod tests {
s.execute("layer.new.layer", json!({})).unwrap();
let st = s.active().unwrap();
let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), Some("colorOverlay"), st.doc.global_light.angle);
- f.insert("p:colorOverlay".into(), json!("invalid"));
+ let id = f["selected"].as_str().unwrap().to_string();
+ entry_mut(&mut f, &id).unwrap()["params"] = json!("invalid");
assert!(preview_document(&st.doc, &s.patterns, &f).is_err());
}
@@ -617,8 +1157,7 @@ mod tests {
#[test]
fn apply_rejects_non_object_params_before_running_commands() {
let mut f = Map::new();
- f.insert("p:stroke".into(), json!([1, 2]));
- f.insert("on:stroke".into(), json!(true));
+ f.insert("effects".into(), json!([{"id": "fx1", "kind": "stroke", "on": true, "params": [1, 2]}]));
let mut calls = 0;
let result = apply(&f, |_, _| {
@@ -634,14 +1173,26 @@ mod tests {
fn body_keeps_invalid_params_and_renders_without_panicking() {
let ctx = egui::Context::default();
PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);
- let mut fields = Map::new();
- fields.insert("selected".into(), json!("dropShadow"));
- fields.insert("p:dropShadow".into(), json!(7));
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ for bad in [json!(7), json!(null), json!("x")] {
+ let mut fields = Map::new();
+ fields.insert("selected".into(), json!("fx1"));
+ fields.insert("effects".into(), json!([{"id": "fx1", "kind": "dropShadow", "on": true, "params": bad.clone()}]));
- let mut out = ctx.run_ui(Default::default(), |ui| body(ui, &mut fields));
- out.textures_delta.clear();
+ let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields));
+ out.textures_delta.clear();
- assert_eq!(fields.get("p:dropShadow"), Some(&json!(7)));
+ assert_eq!(entry(&fields, "fx1").unwrap()["params"], bad);
+ }
+ for bad in [json!(7), json!([1])] {
+ let mut fields = Map::new();
+ fields.insert("selected".into(), json!(BLENDING));
+ fields.insert("p:blendingOptions".into(), bad.clone());
+ fields.insert("effects".into(), bad.clone());
+ let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields));
+ out.textures_delta.clear();
+ assert_eq!(fields.get("p:blendingOptions"), Some(&bad));
+ }
}
#[test]
@@ -651,7 +1202,8 @@ mod tests {
app.run("layer.new.layer", json!({})).unwrap();
let layer = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().clone();
let mut invalid = initial_fields(&layer, Some("colorOverlay"), 0.0);
- invalid.insert("p:colorOverlay".into(), json!(null));
+ let id = invalid["selected"].as_str().unwrap().to_string();
+ entry_mut(&mut invalid, &id).unwrap()["params"] = json!(null);
assert!(confirm(&mut app, &invalid).is_err());
assert!(app.session.active().unwrap().doc.layer(layer.id).unwrap().effects.items.is_empty());
@@ -662,49 +1214,49 @@ mod tests {
#[test]
fn percent_fields_round_trip_through_the_engine() {
- let mut s = photocraft_engine::Session::new();
- s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
- s.execute("layer.new.layer", json!({})).unwrap();
+ let mut s = session();
s.execute("layer.layerStyle.outerGlow", json!({"spread": 6, "range": 40})).unwrap();
s.execute("layer.layerStyle.dropShadow", json!({"spread": 12, "add": true})).unwrap();
let st = s.active().unwrap();
- let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
- let f = initial_fields(l, None, st.doc.global_light.angle);
- assert_eq!(f["p:outerGlow"]["spread"], json!(6.0));
- assert_eq!(f["p:outerGlow"]["range"], json!(40.0));
- assert_eq!(f["p:dropShadow"]["spread"], json!(12.0));
+ let id = st.active_layer.unwrap();
+ let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
+ let fx = effects_of(&f);
+ assert_eq!(fx.len(), 2);
+ assert_eq!(fx[0]["params"]["spread"], json!(6.0));
+ assert_eq!(fx[0]["params"]["range"], json!(40.0));
+ assert_eq!(fx[1]["params"]["spread"], json!(12.0));
}
#[test]
fn drop_shadow_angle_reaches_the_effect() {
// #350: the Angle slider was dead — the dialog never sent `useGlobalLight`, so the engine
// defaulted it to true and the compositor used the fixed global light angle, ignoring the slider.
- let mut s = photocraft_engine::Session::new();
- s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
- s.execute("layer.new.layer", json!({})).unwrap();
- let id = s.active().unwrap().active_layer.unwrap();
+ let mut s = session();
let shadow = |s: &photocraft_engine::Session| {
- s.active().unwrap().doc.layer(id).unwrap().effects.items.iter().find_map(|e| match e {
+ let d = s.active().unwrap();
+ let id = d.active_layer.unwrap();
+ d.doc.layer(id).unwrap().effects.items.iter().find_map(|e| match e {
Effect::DropShadow(sh) => Some(sh.clone()),
_ => None,
})
};
// Use Global Light off: the per-effect angle is stored and used.
- let mut f = Map::new();
- f.insert("layer".into(), json!(id));
- f.insert("on:dropShadow".into(), json!(true));
- f.insert("p:dropShadow".into(), json!({"angle": 45.0, "useGlobalLight": false, "distance": 5, "size": 5}));
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle);
+ set_param(&mut f, "fx1", "angle", json!(45.0));
+ set_param(&mut f, "fx1", "useGlobalLight", json!(false));
apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
let eff = shadow(&s).unwrap();
assert!(!eff.use_global_light, "Use Global Light off keeps the per-effect angle");
assert_eq!(eff.angle, 45.0);
// Use Global Light on: the Angle slider drives the document's shared light angle.
- let mut f = Map::new();
- f.insert("layer".into(), json!(id));
- f.insert("on:dropShadow".into(), json!(true));
- f.insert("p:dropShadow".into(), json!({"angle": 30.0, "useGlobalLight": true, "distance": 5, "size": 5}));
+ let st = s.active().unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle);
+ set_param(&mut f, "fx1", "angle", json!(30.0));
+ set_param(&mut f, "fx1", "useGlobalLight", json!(true));
apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
assert_eq!(s.active().unwrap().doc.global_light.angle, 30.0, "the Angle slider moves the shared light");
assert!(shadow(&s).unwrap().use_global_light);
@@ -712,46 +1264,124 @@ mod tests {
// Reopening the dialog shows the effective angle and the checkbox state.
let st = s.active().unwrap();
let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
- assert_eq!(f["p:dropShadow"]["useGlobalLight"], json!(true));
- assert_eq!(f["p:dropShadow"]["angle"], json!(30.0));
+ let fx = effects_of(&f);
+ let shadow_entry = fx.iter().find(|e| e["kind"] == json!("dropShadow")).unwrap();
+ assert_eq!(shadow_entry["params"]["useGlobalLight"], json!(true));
+ assert_eq!(shadow_entry["params"]["angle"], json!(30.0));
}
#[test]
fn bevel_angle_change_is_not_overridden_by_unchanged_drop_shadow_angle() {
- let mut s = photocraft_engine::Session::new();
- s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
- s.execute("layer.new.layer", json!({})).unwrap();
- let (id, mut f, initial_light) = {
- let st = s.active().unwrap();
- let id = st.active_layer.unwrap();
- let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
- (id, f, st.doc.global_light.angle)
- };
- f.insert("on:bevelEmboss".into(), json!(true));
- f["p:bevelEmboss"]["angle"] = json!(45.0);
- f.insert("on:dropShadow".into(), json!(true));
- assert_eq!(f["p:dropShadow"]["angle"].as_f64(), Some(f64::from(initial_light)));
-
+ let mut s = session();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle);
+ add_instance(&mut f, "bevelEmboss");
+ set_param(&mut f, "fx1", "angle", json!(45.0));
+ add_instance(&mut f, "dropShadow");
apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
-
assert_eq!(s.active().unwrap().doc.global_light.angle, 45.0);
- assert_eq!(s.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 2);
+ let d = s.active().unwrap();
+ assert_eq!(d.doc.layer(id).unwrap().effects.items.len(), 2);
}
#[test]
fn unchanged_global_light_angle_is_not_applied() {
let layer = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8);
let mut f = initial_fields(&layer, None, 47.5);
- f.insert("on:bevelEmboss".into(), json!(true));
- assert_eq!(f["p:bevelEmboss"]["angle"].as_f64(), Some(47.5));
+ add_instance(&mut f, "bevelEmboss");
+ assert_eq!(effects_of(&f)[0]["params"]["angle"].as_f64(), Some(47.5), "a fresh effect starts from the shared light",);
let mut commands = Vec::new();
-
apply(&f, |cmd, _| {
commands.push(cmd.to_string());
Ok(Value::Null)
})
.unwrap();
-
assert!(!commands.iter().any(|cmd| cmd == "layer.layerStyle.globalLight"));
}
+
+ #[test]
+ fn preview_off_shows_the_original_until_reenabled() {
+ let mut s = session();
+ s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("colorOverlay"), st.doc.global_light.angle);
+ // Preview off is the dialog default's complement; edits still change the state.
+ f.insert("preview".into(), json!(false));
+ let h_off = preview_hash(&f);
+ set_param(&mut f, "fx1", "color", json!("#00ff00"));
+ assert_ne!(preview_hash(&f), h_off, "editing while preview is off still updates the dialog state");
+ // Re-enabling preview applies the pending state (the canvas reads `preview`; the
+ // scratch-session apply is the same one the checkbox-on path uses).
+ f.insert("preview".into(), json!(true));
+ let shown = preview_document(&st.doc, &s.patterns, &f).unwrap();
+ let d = s.active().unwrap();
+ let color = |doc: &photocraft_doc::Document| match &doc.layer(id).unwrap().effects.items[0] {
+ Effect::ColorOverlay { color, .. } => *color,
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(color(&shown), photocraft_color::Color::rgb(0.0, 1.0, 0.0));
+ assert_ne!(color(&d.doc), color(&shown), "the document itself is untouched until OK");
+ // OK commits regardless of the checkbox.
+ f.insert("preview".into(), json!(false));
+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();
+ let d = s.active().unwrap();
+ assert_eq!(color(&d.doc), photocraft_color::Color::rgb(0.0, 1.0, 0.0), "OK commits with Preview off");
+ }
+
+ #[test]
+ fn new_style_saves_pending_state_and_a_swatch_apply_restores_it() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ let id = app.session.active().unwrap().active_layer.unwrap();
+ let mut f = initial_fields(app.session.active().unwrap().doc.layer(id).unwrap(), Some("stroke"), 120.0);
+ set_param(&mut f, "fx1", "size", json!(9));
+ save_new_style(&mut app, &f);
+ let preset = app.session.presets.styles.iter().flat_map(|g| g.items.iter()).find(|st| st.name == "Style").expect("the preset is created");
+ assert_eq!(preset.effects.len(), 1, "only the enabled instance is saved");
+ // A second layer gets the pending style back through the swatch path.
+ app.run("layer.new.layer", json!({})).unwrap();
+ let mut f2 = initial_fields(app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap(), None, 120.0);
+ f2.insert("layer".into(), json!(app.session.active().unwrap().active_layer.unwrap().0));
+ apply_style_preset(&app, &mut f2, "Style");
+ // Swatch clicks update the dialog fields only; document is untouched until confirm.
+ assert_eq!(effects_of(&f2).len(), 1);
+ assert_eq!(effects_of(&f2)[0]["params"]["size"], json!(9.0));
+ // Confirming applies the style to the layer.
+ confirm(&mut app, &f2).unwrap();
+ let st = app.session.active().unwrap();
+ let strokes: Vec<f32> = st
+ .doc
+ .layer(app.session.active().unwrap().active_layer.unwrap())
+ .unwrap()
+ .effects
+ .items
+ .iter()
+ .filter_map(|e| match e {
+ Effect::Stroke(s) => Some(s.size),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(strokes, vec![9.0], "confirming commits the style preset to the layer");
+ }
+
+ #[test]
+ fn style_click_does_not_mutate_document_until_confirm() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ let id = app.session.active().unwrap().active_layer.unwrap();
+ let mut f = initial_fields(app.session.active().unwrap().doc.layer(id).unwrap(), Some(STYLES_PAGE), 120.0);
+ apply_style_preset(&app, &mut f, "Black Stroke");
+ // Document itself still has 0 effects.
+ assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 0);
+ // Dialog fields now have the preset loaded.
+ assert_eq!(effects_of(&f).len(), 1);
+ // Cancel discards dialog; document remains with 0 effects.
+ // Confirm commits the style.
+ confirm(&mut app, &f).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 1);
+ }
}
diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs
index 7820639da..94ee84b43 100644
--- a/crates/ui-egui/src/preset_panels.rs
+++ b/crates/ui-egui/src/preset_panels.rs
@@ -185,7 +185,7 @@ fn pattern_texture(ctx: &egui::Context, pat: &photocraft_doc::Pattern) -> Textur
})
}
-fn style_texture(app: &PhotocraftApp, ctx: &egui::Context, st: &photocraft_engine::presets::styles::StylePreset) -> TextureHandle {
+pub(crate) fn style_texture(app: &PhotocraftApp, ctx: &egui::Context, st: &photocraft_engine::presets::styles::StylePreset) -> TextureHandle {
let key = ("style", st.name.clone(), st.effects.len(), format!("{:?}{:?}", st.blend, st.fill_opacity));
cached_texture(ctx, key, || {
const S: u32 = 64;
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 9b9bf83f7..9b2289510 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -39,6 +39,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `ui.menu.invoke {id, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once
- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.
- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once
+ - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor`
- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) edits the sections in its `values` field. `ui.dialog.apply {dialog}` saves those values through `prefs.set` and keeps the same dialog and section open. `ui.dialog.confirm` saves and closes; `ui.dialog.cancel` discards only edits made since the last successful Apply. Invalid values return an error without closing the Apply dialog or changing the saved preferences. Settings marked for the next launch still require a restart.
- Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`).
- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.