Skip to content

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

Rebuild unrecorded Gradient Overlays from their end colours

Yonghyuk Choibea003acd8fe
diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rs
index 62efbf34d..4e3f32a97 100644
--- a/crates/doc/src/effects.rs
+++ b/crates/doc/src/effects.rs
@@ -39,6 +39,7 @@ pub struct Gradient {
/// Editable colour stops behind a Gradient Overlay's baked render stops.
/// Older documents have no interpolation record and keep their existing appearance.
+/// Writers must rebake `gradient.stops` from this record, or clear it when replacing the curve.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GradientInterpolation {
pub method: String,
diff --git a/crates/engine/src/layer_style/gradient_overlay.rs b/crates/engine/src/layer_style/gradient_overlay.rs
index e46109d86..9caf82f71 100644
--- a/crates/engine/src/layer_style/gradient_overlay.rs
+++ b/crates/engine/src/layer_style/gradient_overlay.rs
@@ -19,6 +19,7 @@ fn edit_endpoint(stop: Option<&mut (f32, Color)>, params: &Value, key: &str) {
}
}
+/// Edits recorded source stops, initializing legacy curves from their end colours.
pub(super) fn overlay(gradient: &mut Gradient, interpolation: &mut Option<GradientInterpolation>, params: &Value) {
// Reset to Default restores the factory's unbaked interpolation too.
if params.get("method").and_then(Value::as_str) == Some("custom") {
@@ -37,7 +38,9 @@ pub(super) fn overlay(gradient: &mut Gradient, interpolation: &mut Option<Gradie
let source = interpolation.get_or_insert_with(|| GradientInterpolation {
method: requested.unwrap_or("classic").to_ascii_lowercase(),
smoothness: 100.0,
- stops: gradient.stops.clone(),
+ // Without a source record, intermediate stops may be baked samples (PSD import or
+ // older method commands). Keep the legacy rebuild-from-ends behaviour on first choice.
+ stops: vec![(0.0, gradient.stops.first().map_or(Color::BLACK, |s| s.1)), (1.0, gradient.stops.last().map_or(Color::WHITE, |s| s.1))],
});
if let Some(method) = requested {
source.method = method.to_ascii_lowercase();
@@ -66,8 +69,66 @@ pub(super) fn overlay(gradient: &mut Gradient, interpolation: &mut Option<Gradie
#[cfg(test)]
mod tests {
use super::*;
+ use photocraft_color::BlendMode;
+ use photocraft_doc::{Effect, FxCommon};
+ use photocraft_io::{GradientMethod, bake_gradient};
use serde_json::json;
+ #[test]
+ fn choosing_a_method_on_a_baked_overlay_rebuilds_from_its_end_colours() {
+ let ends = vec![(0.0, Color::BLACK), (1.0, Color::WHITE)];
+ for imported_method in [GradientMethod::Perceptual, GradientMethod::Smooth] {
+ let gradient = Gradient {
+ stops: bake_gradient(ends.clone(), &[0.5], 1.0, imported_method),
+ opacity_stops: vec![(0.0, 0.25), (0.6, 0.8), (1.0, 0.5)],
+ align: false,
+ offset: (0.2, -0.1),
+ ..Gradient::default()
+ };
+ assert!(gradient.stops.len() > 2);
+ let source_ends = vec![(0.0, gradient.stops.first().unwrap().1), (1.0, gradient.stops.last().unwrap().1)];
+ let mut fx =
+ Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: gradient.clone(), dither: true, interpolation: None };
+ super::super::overlay_effect(&mut fx, &json!({"method": "linear"}));
+ let mut expected = gradient;
+ expected.stops = bake_gradient(source_ends.clone(), &[0.5], 1.0, GradientMethod::Linear);
+ assert_eq!(
+ fx,
+ Effect::GradientOverlay {
+ common: FxCommon::new(BlendMode::Normal, 1.0),
+ gradient: expected,
+ dither: true,
+ interpolation: Some(GradientInterpolation { method: "linear".into(), smoothness: 100.0, stops: source_ends }),
+ }
+ );
+ }
+ }
+
+ #[test]
+ fn endpoint_edits_after_selecting_a_method_recolour_the_whole_baked_overlay() {
+ for same_edit in [false, true] {
+ let mut fx = Effect::GradientOverlay {
+ common: FxCommon::new(BlendMode::Normal, 1.0),
+ gradient: Gradient {
+ stops: bake_gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], &[0.5], 1.0, GradientMethod::Smooth),
+ ..Gradient::default()
+ },
+ dither: false,
+ interpolation: None,
+ };
+ if same_edit {
+ super::super::overlay_effect(&mut fx, &json!({"method": "classic", "from": "#ff0000", "to": "#0000ff"}));
+ } else {
+ super::super::overlay_effect(&mut fx, &json!({"method": "classic"}));
+ super::super::overlay_effect(&mut fx, &json!({"from": "#ff0000", "to": "#0000ff"}));
+ }
+ let ends = vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))];
+ let Effect::GradientOverlay { gradient, interpolation, .. } = fx else { panic!("expected overlay") };
+ assert_eq!(gradient.stops, bake_gradient(ends.clone(), &[0.5], 1.0, GradientMethod::Classic));
+ assert_eq!(interpolation.unwrap().stops, ends);
+ }
+ }
+
#[test]
fn changing_method_keeps_all_source_stops_and_transparency() {
let mut gradient = Gradient {
@@ -78,7 +139,8 @@ mod tests {
..Gradient::default()
};
let original = gradient.clone();
- let mut source = None;
+ let mut source = Some(GradientInterpolation { method: "classic".into(), smoothness: 100.0, stops: original.stops.clone() });
+ gradient.stops = bake_gradient(original.stops.clone(), &[0.5, 0.5], 1.0, GradientMethod::Classic);
for method in ["classic", "smooth", "perceptual", "linear", "classic"] {
overlay(&mut gradient, &mut source, &json!({"method": method}));
let source = source.as_ref().unwrap();
@@ -90,6 +152,11 @@ mod tests {
assert_eq!(gradient.align, original.align);
assert_eq!(gradient.offset, original.offset);
}
+ overlay(&mut gradient, &mut source, &json!({"from": "#112233", "to": "#445566"}));
+ let source = source.unwrap();
+ assert_eq!(source.stops.len(), 3);
+ assert_eq!(source.stops[1], original.stops[1], "endpoint edits preserve the middle source stop");
+ assert_eq!(gradient.stops, bake_gradient(source.stops, &[0.5, 0.5], 1.0, GradientMethod::Classic));
}
#[test]
diff --git a/crates/ui-egui/src/layer_style/gradient_method_tests.rs b/crates/ui-egui/src/layer_style/gradient_method_tests.rs
index ef5d062f9..2578c1ab5 100644
--- a/crates/ui-egui/src/layer_style/gradient_method_tests.rs
+++ b/crates/ui-egui/src/layer_style/gradient_method_tests.rs
@@ -68,3 +68,49 @@ fn all_four_methods_roundtrip_through_the_dialog() {
assert_eq!(effect(&app), &before);
}
}
+
+#[test]
+fn baked_overlay_is_unchanged_until_method_selection_then_edits_the_whole_curve() {
+ use photocraft_color::Color;
+ use photocraft_io::{GradientMethod, bake_gradient};
+
+ let mut app = app();
+ app.run("layer.layerStyle.gradientOverlay", json!({})).unwrap();
+ // PSD import and older method commands leave a baked curve without a source record.
+ let state = app.session.active_mut().unwrap();
+ let fx = &mut std::sync::Arc::make_mut(&mut state.doc).layer_mut(state.active_layer.unwrap()).unwrap().effects.items[0];
+ let Effect::GradientOverlay { gradient, interpolation, .. } = fx else { panic!("expected overlay") };
+ gradient.stops = bake_gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], &[0.5], 1.0, GradientMethod::Smooth);
+ *interpolation = None;
+ let source_ends = vec![(0.0, gradient.stops.first().unwrap().1), (1.0, gradient.stops.last().unwrap().1)];
+
+ let original = effect(&app).clone();
+ let mut pending = fields(&app);
+ let id = pending["effects"][0]["id"].as_str().unwrap().to_string();
+ assert_eq!(pending["effects"][0]["params"]["method"], "custom");
+ confirm(&mut app, &pending).unwrap();
+ assert_eq!(effect(&app), &original);
+
+ set_param(&mut pending, &id, "method", json!("linear"));
+ confirm(&mut app, &pending).unwrap();
+ let selected = effect(&app).clone();
+ let Effect::GradientOverlay { gradient, interpolation, .. } = &selected else { panic!("expected overlay") };
+ assert_eq!(gradient.stops, bake_gradient(source_ends, &[0.5], 1.0, GradientMethod::Linear));
+ assert_eq!(interpolation.as_ref().unwrap().stops.len(), 2);
+
+ let mut reopened = fields(&app);
+ assert_eq!(reopened["effects"][0]["params"]["method"], "linear");
+ set_param(&mut reopened, &id, "from", json!("#ff0000"));
+ set_param(&mut reopened, &id, "to", json!("#0000ff"));
+ confirm(&mut app, &reopened).unwrap();
+ let edited = effect(&app).clone();
+ let Effect::GradientOverlay { gradient, .. } = &edited else { panic!("expected overlay") };
+ assert_eq!(gradient.stops, bake_gradient(vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], &[0.5], 1.0, GradientMethod::Linear));
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(effect(&app), &selected);
+ app.run("edit.redo", json!({})).unwrap();
+ assert_eq!(effect(&app), &edited);
+ let reopened = fields(&app);
+ confirm(&mut app, &reopened).unwrap();
+ assert_eq!(effect(&app), &edited);
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 2ed97cae6..55ca0c25e 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -67,7 +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 and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. 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.
+ - 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 all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. 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.