Skip to content

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

Gradient Overlay: expose interpolation methods and retain source stops

oRE-o8fb5d94d2b12
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index ddd487154..6588ced47 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1085,13 +1085,19 @@ fn glow_gradient_follows_the_shape() {
#[test]
fn gradient_overlay_follows_angle_and_reverse() {
let g = Gradient { stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], angle: 0.0, ..Gradient::default() };
- let d = fx_doc(vec![Effect::GradientOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), gradient: g.clone(), dither: false }]);
+ let d = fx_doc(vec![Effect::GradientOverlay {
+ common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0),
+ gradient: g.clone(),
+ dither: false,
+ interpolation: None,
+ }]);
let (l, r) = (px(&d, 10, 20), px(&d, 29, 20));
assert!(l[0] < 0.1 && r[0] > 0.9, "{l:?} {r:?}");
let d = fx_doc(vec![Effect::GradientOverlay {
common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0),
gradient: Gradient { reverse: true, style: GradientStyle::Linear, ..g },
dither: false,
+ interpolation: None,
}]);
assert!(px(&d, 10, 20)[0] > 0.9);
}
diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rs
index 6ae790e26..1f9e8a6a3 100644
--- a/crates/doc/src/effects.rs
+++ b/crates/doc/src/effects.rs
@@ -37,6 +37,15 @@ pub struct Gradient {
pub offset: (f32, f32),
}
+/// Editable colour stops behind a Gradient Overlay's baked render stops.
+/// Older documents have no interpolation record and keep their existing appearance.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct GradientInterpolation {
+ pub method: String,
+ pub smoothness: f32,
+ pub stops: Vec<(f32, Color)>,
+}
+
impl Default for Gradient {
fn default() -> Self {
Gradient {
@@ -272,6 +281,8 @@ pub enum Effect {
common: FxCommon,
gradient: Gradient,
dither: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ interpolation: Option<GradientInterpolation>,
},
PatternOverlay {
common: FxCommon,
@@ -307,7 +318,12 @@ impl Effect {
Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint(&mut g.paint),
Effect::Stroke(s) => paint(&mut s.paint),
Effect::ColorOverlay { color, .. } => cc(color),
- Effect::GradientOverlay { gradient, .. } => gradient.stops.iter_mut().for_each(|s| cc(&mut s.1)),
+ Effect::GradientOverlay { gradient, interpolation, .. } => {
+ gradient.stops.iter_mut().for_each(|s| cc(&mut s.1));
+ if let Some(source) = interpolation {
+ source.stops.iter_mut().for_each(|s| cc(&mut s.1));
+ }
+ }
Effect::Satin(s) => cc(&mut s.color),
Effect::BevelEmboss(b) => {
cc(&mut b.highlight_color);
diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs
index d3a6d3693..9dfc5a921 100644
--- a/crates/engine/src/color_cmds.rs
+++ b/crates/engine/src/color_cmds.rs
@@ -700,7 +700,12 @@ fn convert_layer_colors(l: &mut Layer, cc: &mut dyn FnMut(&mut Color)) {
Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint_colors(&mut g.paint, cc),
Effect::Stroke(s) => paint_colors(&mut s.paint, cc),
Effect::ColorOverlay { color, .. } => cc(color),
- Effect::GradientOverlay { gradient, .. } => gradient.stops.iter_mut().for_each(|s| cc(&mut s.1)),
+ Effect::GradientOverlay { gradient, interpolation, .. } => {
+ gradient.stops.iter_mut().for_each(|s| cc(&mut s.1));
+ if let Some(source) = interpolation {
+ source.stops.iter_mut().for_each(|s| cc(&mut s.1));
+ }
+ }
Effect::Satin(s) => cc(&mut s.color),
Effect::BevelEmboss(b) => {
cc(&mut b.highlight_color);
diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs
index 95b547685..538473817 100644
--- a/crates/engine/src/layer_style.rs
+++ b/crates/engine/src/layer_style.rs
@@ -12,6 +12,8 @@ use crate::commands::{CommandSpec, blend_from_str};
use crate::presets::{always, bad};
use crate::{EngineError, Result, Session};
+mod gradient_overlay;
+
/// Parses a gradient style name (`linear`, `radial`, `angle`, `reflected`, `diamond`).
pub fn gradient_style(s: &str) -> GradientStyle {
match s.to_ascii_lowercase().as_str() {
@@ -94,7 +96,7 @@ pub fn effect_defaults(kind: &str) -> Value {
"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})
+ json!({"blend": "Normal", "opacity": 100, "from": "#000000", "to": "#ffffff", "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "custom"})
}
"patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}),
"bevelEmboss" => {
@@ -512,7 +514,9 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
paint: FxPaint::Color(Color::rgb(1.0, 0.0, 0.0)),
}),
"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 },
+ "gradientOverlay" => {
+ Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None }
+ }
"patternOverlay" => Effect::PatternOverlay {
common: FxCommon::new(BlendMode::Normal, 1.0),
name: String::new(),
@@ -700,9 +704,9 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {
common(c, p);
set_color(p, "color", color);
}
- Effect::GradientOverlay { common: c, gradient: g, dither } => {
+ Effect::GradientOverlay { common: c, gradient: g, dither, interpolation } => {
common(c, p);
- overlay_gradient(g, p);
+ gradient_overlay::overlay(g, interpolation, p);
if let Some(x) = b_of(p, "dither") {
*dither = x;
}
@@ -1011,7 +1015,7 @@ pub fn specs() -> Vec<CommandSpec> {
style_cmd!(
"gradientOverlay",
"Gradient Overlay…",
- r##"{"from":"#rrggbb","to":"#rrggbb","method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"style":"linear|radial|angle|reflected|diamond","angle":deg=90,"scale":10..150=100,"reverse":bool,"opacity":0..100,"blend":str,"add":bool}"##
+ r##"{"from":"#rrggbb","to":"#rrggbb","method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted on new effects: straight stops; edits retain the recorded method),"smoothness":0..100=100,"style":"linear|radial|angle|reflected|diamond","angle":deg=90,"scale":10..150=100,"reverse":bool,"opacity":0..100,"blend":str,"add":bool}"##
),
style_cmd!(
"patternOverlay",
diff --git a/crates/engine/src/layer_style/gradient_overlay.rs b/crates/engine/src/layer_style/gradient_overlay.rs
new file mode 100644
index 000000000..45b4a6d86
--- /dev/null
+++ b/crates/engine/src/layer_style/gradient_overlay.rs
@@ -0,0 +1,126 @@
+//! Keep editable stops separate from the dense stops used by the compositors.
+
+use photocraft_doc::effects::GradientInterpolation;
+use photocraft_doc::{Color, Gradient};
+use serde_json::Value;
+
+use super::{color_of, f_of, overlay_gradient};
+
+fn edit_endpoint(stop: Option<&mut (f32, Color)>, params: &Value, key: &str) {
+ if let (Some(stop), Some(color)) = (stop, color_of(params, key)) {
+ // The dialog displays hex colours. Opening it must not quantize the saved source.
+ if !params.get(key).is_some_and(Value::is_string) || color.to_rgba8() != stop.1.to_rgba8() {
+ stop.1 = color;
+ }
+ }
+}
+
+pub(super) fn overlay(gradient: &mut Gradient, interpolation: &mut Option<GradientInterpolation>, params: &Value) {
+ let requested = params.get("method").and_then(Value::as_str).filter(|name| photocraft_io::GradientMethod::from_name(name).is_some());
+ if interpolation.is_none() && requested.is_none() {
+ overlay_gradient(gradient, params);
+ return;
+ }
+ let previous = interpolation.clone();
+ let source = interpolation.get_or_insert_with(|| GradientInterpolation {
+ method: requested.unwrap_or("classic").to_ascii_lowercase(),
+ smoothness: 100.0,
+ stops: gradient.stops.clone(),
+ });
+ if let Some(method) = requested {
+ source.method = method.to_ascii_lowercase();
+ }
+ if let Some(smoothness) = f_of(params, "smoothness").filter(|n| n.is_finite()) {
+ source.smoothness = smoothness.clamp(0.0, 100.0);
+ }
+ edit_endpoint(source.stops.first_mut(), params, "from");
+ edit_endpoint(source.stops.last_mut(), params, "to");
+ if previous.as_ref() != Some(source)
+ && let Some(method) = photocraft_io::GradientMethod::from_name(&source.method)
+ {
+ // Missing midpoint entries mean 50 %, including for multi-stop source gradients.
+ gradient.stops = photocraft_io::bake_gradient(source.stops.clone(), &[], source.smoothness / 100.0, method);
+ }
+ // Geometry edits must not replace just the ends of the baked curve.
+ let mut geometry = params.clone();
+ if let Some(object) = geometry.as_object_mut() {
+ for key in ["method", "smoothness", "from", "to"] {
+ object.remove(key);
+ }
+ }
+ overlay_gradient(gradient, &geometry);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn changing_method_keeps_all_source_stops_and_transparency() {
+ let mut gradient = Gradient {
+ stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.3, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))],
+ opacity_stops: vec![(0.0, 0.25), (1.0, 0.8)],
+ align: false,
+ offset: (0.2, -0.1),
+ ..Gradient::default()
+ };
+ let original = gradient.clone();
+ let mut source = None;
+ for method in ["classic", "smooth", "perceptual", "linear", "classic"] {
+ overlay(&mut gradient, &mut source, &json!({"method": method}));
+ let source = source.as_ref().unwrap();
+ assert_eq!(source.method, method);
+ assert_eq!(source.stops, original.stops);
+ let expected = photocraft_io::bake_gradient(original.stops.clone(), &[0.5, 0.5], 1.0, photocraft_io::GradientMethod::from_name(method).unwrap());
+ assert_eq!(gradient.stops, expected);
+ assert_eq!(gradient.opacity_stops, original.opacity_stops);
+ assert_eq!(gradient.align, original.align);
+ assert_eq!(gradient.offset, original.offset);
+ }
+ }
+
+ #[test]
+ fn colour_edit_rebakes_the_curve_and_geometry_edits_leave_it_exact() {
+ let mut gradient = Gradient::default();
+ let mut source = None;
+ overlay(&mut gradient, &mut source, &json!({"method": "smooth", "from": "#ff0000", "to": "#0000ff"}));
+ let before = gradient.stops.clone();
+ overlay(&mut gradient, &mut source, &json!({"from": "#00ff00", "angle": 45}));
+ assert_ne!(gradient.stops, before);
+ let expected = photocraft_io::bake_gradient(
+ vec![(0.0, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))],
+ &[0.5],
+ 1.0,
+ photocraft_io::GradientMethod::Smooth,
+ );
+ assert_eq!(gradient.stops, expected);
+ overlay(&mut gradient, &mut source, &json!({"angle": 90, "reverse": true, "scale": 75}));
+ assert_eq!(gradient.stops, expected);
+ assert_eq!(gradient.angle, 90.0);
+ assert!(gradient.reverse);
+ assert_eq!(gradient.scale, 0.75);
+ }
+
+ #[test]
+ fn reopening_does_not_quantize_source_colours_or_rebake() {
+ let mut gradient = Gradient::default();
+ let mut source = None;
+ overlay(&mut gradient, &mut source, &json!({"from": [0.123456, 0.234567, 0.345678], "method": "perceptual"}));
+ let before = (gradient.clone(), source.clone());
+ let [r, g, b, _] = source.as_ref().unwrap().stops[0].1.to_rgba8();
+ overlay(&mut gradient, &mut source, &json!({"from": format!("#{r:02x}{g:02x}{b:02x}"), "to": "#ffffff", "method": "perceptual", "smoothness": 100}));
+ assert_eq!((gradient, source), before);
+ }
+
+ #[test]
+ fn old_gradients_are_unchanged_until_a_method_is_chosen() {
+ let mut gradient = Gradient::default();
+ gradient.stops.insert(1, (0.4, Color::rgb(0.1, 0.9, 0.2)));
+ let original = gradient.clone();
+ let mut source = None;
+ overlay(&mut gradient, &mut source, &json!({"method": "custom", "opacity": 50}));
+ assert_eq!(gradient, original);
+ assert!(source.is_none());
+ }
+}
diff --git a/crates/format/tests/common/mod.rs b/crates/format/tests/common/mod.rs
index 8d5641d9c..0efa07393 100644
--- a/crates/format/tests/common/mod.rs
+++ b/crates/format/tests/common/mod.rs
@@ -66,7 +66,12 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
mask.linked = false;
paint.mask = Some(mask);
paint.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 0.8), color: Color::rgb(1.0, 0.2, 0.1) });
- paint.effects.items.push(Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 0.8), gradient: Gradient::default(), dither: true });
+ paint.effects.items.push(Effect::GradientOverlay {
+ common: FxCommon::new(BlendMode::Normal, 0.8),
+ gradient: Gradient::default(),
+ dither: true,
+ interpolation: None,
+ });
paint.effects.psd_raw = Some(blob(3, 64));
paint.psd_blocks.push((*b"vmsk", blob(4, 40)));
paint.psd_blocks.push((*b"lnsr", blob(5, 4)));
diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rs
index f78e93947..cb0b9bbf9 100644
--- a/crates/format/tests/roundtrip.rs
+++ b/crates/format/tests/roundtrip.rs
@@ -11,6 +11,46 @@ use photocraft_raster::Rgba8Image;
const MODES: [ColorMode; 4] = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab];
+#[test]
+fn gradient_overlay_interpolation_roundtrips_in_native_documents() {
+ use photocraft_doc::effects::GradientInterpolation;
+ use photocraft_doc::{Color, Effect, FxCommon, Gradient};
+
+ for mode in MODES {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut doc = rich_doc(mode, depth);
+ let source = GradientInterpolation {
+ method: "smooth".into(),
+ smoothness: 73.0,
+ stops: vec![(0.0, Color::rgb(0.123456, 0.4, 0.9)), (0.4, Color::WHITE), (1.0, Color::BLACK)],
+ };
+ let effect = Effect::GradientOverlay {
+ common: FxCommon::new(photocraft_doc::BlendMode::Normal, 1.0),
+ gradient: Gradient::default(),
+ dither: true,
+ interpolation: Some(source),
+ }
+ .in_mode(mode);
+ doc.layers.first_mut().unwrap().effects.items.push(effect);
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ assert_eq!(load_from_bytes(&bytes).unwrap(), doc);
+ }
+ }
+}
+
+#[test]
+fn old_effect_snapshots_need_no_interpolation_record() {
+ let effect = photocraft_doc::Effect::GradientOverlay {
+ common: photocraft_doc::FxCommon::new(photocraft_doc::BlendMode::Normal, 1.0),
+ gradient: photocraft_doc::Gradient::default(),
+ dither: false,
+ interpolation: None,
+ };
+ let json = serde_json::to_value(&effect).unwrap();
+ assert!(json["GradientOverlay"].get("interpolation").is_none());
+ assert_eq!(serde_json::from_value::<photocraft_doc::Effect>(json).unwrap(), effect);
+}
+
#[test]
fn custom_shape_stroke_roundtrip_keeps_every_style_field() {
for mode in MODES {
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 84d3d0e93..209d40bc0 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -854,7 +854,7 @@ fn hard_stop_effects_and_gradient_maps_request_cpu() {
}
let paint = FxPaint::Gradient(gradient.clone());
let effects = [
- Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient, dither: false },
+ Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient, dither: false, interpolation: None },
Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size: 1.0, position: StrokePosition::Inside, paint: paint.clone() }),
Effect::InnerGlow(glow(paint.clone(), GlowTechnique::Softer, 1.0, 0.0, GlowSource::Edge)),
Effect::OuterGlow(glow(paint, GlowTechnique::Softer, 1.0, 0.0, GlowSource::Edge)),
@@ -1464,6 +1464,7 @@ fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
common: FxCommon::new(BlendMode::Normal, 0.8),
gradient: Gradient { style: GradientStyle::Radial, ..gradient() },
dither: false,
+ interpolation: None,
}],
),
(
@@ -1535,7 +1536,7 @@ fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
invert: false,
}),
Effect::ColorOverlay { common: FxCommon::new(BlendMode::SoftLight, 0.5), color: Color::rgb(0.9, 0.3, 0.2) },
- Effect::GradientOverlay { common: FxCommon::new(BlendMode::Overlay, 0.4), gradient: gradient(), dither: false },
+ Effect::GradientOverlay { common: FxCommon::new(BlendMode::Overlay, 0.4), gradient: gradient(), dither: false, interpolation: None },
Effect::Stroke(stroke(3.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(0.0, 0.0, 0.0)))),
],
),
diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs
index 00815e2c8..cb374f935 100644
--- a/crates/io/src/effects_map.rs
+++ b/crates/io/src/effects_map.rs
@@ -263,7 +263,9 @@ fn parse_one(key: &str, d: &Descriptor) -> Option<Effect> {
"IrGl" => Effect::InnerGlow(parse_glow(d, true)),
"FrFX" => Effect::Stroke(parse_stroke(d)),
"SoFi" => Effect::ColorOverlay { common: common(d, BlendMode::Normal, 1.0), color: color(d, "Clr ") },
- "GrFl" => Effect::GradientOverlay { common: common(d, BlendMode::Normal, 1.0), gradient: gradient_from(d), dither: bool_of(d, "Dthr") },
+ "GrFl" => {
+ Effect::GradientOverlay { common: common(d, BlendMode::Normal, 1.0), gradient: gradient_from(d), dither: bool_of(d, "Dthr"), interpolation: None }
+ }
"patternFill" => {
let (name, id) = pattern_ref(d);
let (angle, link, phase) = pattern_placement(d);
@@ -425,7 +427,7 @@ fn write_one(e: &Effect) -> (&'static str, Descriptor) {
("FrFX", d)
}
Effect::ColorOverlay { common: c, color } => ("SoFi", with_common(Descriptor::new("SoFi"), c).with("Clr ", Value::Descriptor(color_to_desc(color)))),
- Effect::GradientOverlay { common: c, gradient, dither } => {
+ Effect::GradientOverlay { common: c, gradient, dither, .. } => {
("GrFl", gradient_keys(with_common(Descriptor::new("GrFl"), c), gradient).with("Dthr", Value::Boolean(*dither)))
}
Effect::PatternOverlay { common: c, name, id, scale, angle, link, phase } => (
@@ -688,7 +690,7 @@ mod tests {
paint: FxPaint::Gradient(g.clone()),
}),
Effect::ColorOverlay { common: FxCommon::new(BlendMode::Overlay, 0.5), color: Color::rgb(0.0, 0.0, 1.0) },
- Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: g, dither: true },
+ Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: g, dither: true, interpolation: None },
Effect::PatternOverlay {
common: FxCommon::new(BlendMode::Normal, 1.0),
name: "Bubbles".into(),
diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs
index d876c1827..fbc36898f 100644
--- a/crates/ui-egui/src/layer_style.rs
+++ b/crates/ui-egui/src/layer_style.rs
@@ -23,6 +23,8 @@ use crate::{PhotocraftApp, widgets};
pub(crate) mod color_picker;
mod contour;
+#[cfg(test)]
+mod gradient_method_tests;
#[derive(Clone, Copy)]
enum P {
@@ -30,6 +32,7 @@ enum P {
Color,
Blend,
Choice(&'static [(&'static str, &'static str)]),
+ GradientMethod,
Check,
Angle,
/// A pattern from the dialog's `patternList` field (`[[id, name], …]`).
@@ -153,6 +156,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
("style", "Style", P::Choice(GSTYLE)),
("angle", "Angle", P::Angle),
("scale", "Scale", P::Slider(10.0, 150.0, "%")),
+ ("method", "Method", P::GradientMethod),
],
"patternOverlay" => &[
("blend", "Blend Mode", P::Blend),
@@ -279,14 +283,21 @@ 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, gradient: g, .. } => {
+ Effect::GradientOverlay { common, gradient: g, interpolation, .. } => {
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)));
+ let stops = interpolation.as_ref().map_or(&g.stops, |source| &source.stops);
+ if let Some(source) = interpolation {
+ set(&mut v, "method", json!(source.method));
+ set(&mut v, "smoothness", json!(source.smoothness));
+ }
+ // Recorded interpolation exposes the original endpoint colours. Other rich
+ // imported curves are still carried by the snapshot, as before.
+ if (interpolation.is_some() || (stops.len() == 2 && g.opacity_stops.is_empty()))
+ && let (Some(first), Some(last)) = (stops.first(), stops.last())
+ {
+ set(&mut v, "from", json!(hex(&first.1)));
+ set(&mut v, "to", json!(hex(&last.1)));
set(&mut v, "reverse", json!(g.reverse));
set(
&mut v,
@@ -1019,6 +1030,44 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
}
});
}
+ P::GradientMethod => {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(tl!("Method")).color(t.text_dim));
+ let mut current = disp.get(key).and_then(Value::as_str).unwrap_or("custom").to_string();
+ let mut options = vec![
+ ("smooth".to_string(), "Smooth"),
+ ("perceptual".to_string(), "Perceptual"),
+ ("linear".to_string(), "Linear"),
+ ("classic".to_string(), "Classic"),
+ ];
+ // Old/imported curves have no method record. Preserve them until
+ // the user explicitly chooses an interpolation method.
+ if photocraft_io::GradientMethod::from_name(&current).is_none() {
+ current = "custom".into();
+ options.insert(0, ("custom".into(), "Custom"));
+ }
+ if widgets::dropdown(ui, "fx-gradientOverlay-method", &mut current, &options, 150.0) {
+ // The older dialog deliberately omits From/To for rich imported
+ // curves. Once a method is chosen, show the real source ends.
+ let snapshot = entry(f, &selected).and_then(|e| e.get("fx")).cloned();
+ if let Some(Effect::GradientOverlay { gradient, interpolation, .. }) =
+ snapshot.and_then(|v| serde_json::from_value::<Effect>(v).ok())
+ {
+ let stops = interpolation.as_ref().map_or(&gradient.stops, |source| &source.stops);
+ for (key, stop) in [("from", stops.first()), ("to", stops.last())] {
+ if entry(f, &selected).and_then(|e| e.get("params")).and_then(|p| p.get(key)).is_none()
+ && let Some(stop) = stop
+ {
+ set_param(f, &selected, key, json!(hex(&stop.1)));
+ }
+ }
+ }
+ let value = json!(current);
+ disp[key] = value.clone();
+ set_param(f, &selected, key, value);
+ }
+ });
+ }
P::Pattern => {
let list: Vec<(String, String)> = f
.get("patternList")
diff --git a/crates/ui-egui/src/layer_style/gradient_method_tests.rs b/crates/ui-egui/src/layer_style/gradient_method_tests.rs
new file mode 100644
index 000000000..52eb8b08d
--- /dev/null
+++ b/crates/ui-egui/src/layer_style/gradient_method_tests.rs
@@ -0,0 +1,64 @@
+use egui_kittest::kittest::Queryable;
+
+use super::*;
+
+fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ app
+}
+
+fn effect(app: &PhotocraftApp) -> &Effect {
+ let state = app.session.active().unwrap();
+ &state.doc.layer(state.active_layer.unwrap()).unwrap().effects.items[0]
+}
+
+fn fields(app: &PhotocraftApp) -> Map<String, Value> {
+ let state = app.session.active().unwrap();
+ initial_fields(state.doc.layer(state.active_layer.unwrap()).unwrap(), Some("gradientOverlay"), 120.0)
+}
+
+#[test]
+fn method_picker_is_pending_until_confirm_and_survives_reopening() {
+ let mut app = app();
+ app.run("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff"})).unwrap();
+ let original = effect(&app).clone();
+ let pending_fields = fields(&app);
+ let mut harness = egui_kittest::Harness::builder()
+ .with_size(vec2(1000.0, 1000.0))
+ .build_ui_state(|ui, state: &mut (PhotocraftApp, Map<String, Value>)| body(&mut state.0, ui, &mut state.1), (app, pending_fields));
+ PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]);
+ harness.run_steps(3);
+ harness.get_by_label("Custom").click();
+ harness.run_steps(2);
+ harness.get_by_label("Smooth").click();
+ harness.run_steps(2);
+ assert_eq!(effect(&harness.state().0), &original, "cancel can still discard all pending edits");
+ assert_eq!(harness.state().1["effects"][0]["params"]["method"], "smooth");
+ let (app, pending) = harness.state_mut();
+ confirm(app, pending).unwrap();
+ let saved = effect(app).clone();
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(effect(app), &original);
+ app.run("edit.redo", json!({})).unwrap();
+ assert_eq!(effect(app), &saved);
+ let reopened = fields(app);
+ assert_eq!(reopened["effects"][0]["params"]["method"], "smooth");
+ assert_eq!(reopened["effects"][0]["params"]["from"], "#ff0000");
+ confirm(app, &reopened).unwrap();
+ assert_eq!(effect(app), &saved, "OK without edits leaves the rendered curve exact");
+}
+
+#[test]
+fn all_four_methods_roundtrip_through_the_dialog() {
+ for method in ["classic", "linear", "perceptual", "smooth"] {
+ let mut app = app();
+ app.run("layer.layerStyle.gradientOverlay", json!({"from": [0.123456, 0.234567, 0.345678], "to": "#abcdef", "method": method})).unwrap();
+ let before = effect(&app).clone();
+ let fields = fields(&app);
+ assert_eq!(fields["effects"][0]["params"]["method"], method);
+ confirm(&mut app, &fields).unwrap();
+ assert_eq!(effect(&app), &before);
+ }
+}
diff --git a/crates/ui-egui/tests/support/layout_doc.rs b/crates/ui-egui/tests/support/layout_doc.rs
index f44fac16a..cce50ca5b 100644
--- a/crates/ui-egui/tests/support/layout_doc.rs
+++ b/crates/ui-egui/tests/support/layout_doc.rs
@@ -96,6 +96,7 @@ fn gradient_overlay(a: [f32; 3], b: [f32; 3]) -> Effect {
common: FxCommon::new(BlendMode::Normal, 0.6),
gradient: Gradient { stops: vec![(0.0, Color::rgb(a[0], a[1], a[2])), (1.0, Color::rgb(b[0], b[1], b[2]))], angle: 90.0, ..Default::default() },
dither: false,
+ interpolation: None,
}
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 15334ac3a..96200a8a7 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -67,6 +67,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it fails
- The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "dontSave" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered.
- 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`
+ - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains the full source colour-stop list; later endpoint edits rebuild the colour curve using that method. The source stops, smoothness and method survive dialog reopening, undo/redo, style presets and native `.pcraft` saves. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work.
- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). 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"]`).
- Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across.