Skip to content

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

Fix Classic Gradient transparency and open the Gradient Editor (#905)

jerrykimo17d72cf7712a
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index a2196eef5..9202ab39c 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -3071,11 +3071,9 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {
Tool::Gradient => {
if (end[0] - d.start[0]).abs() + (end[1] - d.start[1]).abs() >= 2.0 {
let o = app.ui.tool_options.clone();
- let fg = app.session.tools.foreground;
- let bg = app.session.tools.background;
let _ = app.run(
"paint.gradient",
- json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "colors": [hex(fg), hex(bg)], "opacity": o.fill_opacity, "mode": o.gradient_blend_mode.label(), "target": paint_target(app)}),
+ json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "opacity": o.fill_opacity, "mode": o.gradient_blend_mode.label(), "target": paint_target(app)}),
);
}
}
@@ -3191,12 +3189,6 @@ pub fn paint_target(app: &PhotocraftApp) -> serde_json::Value {
json!(if (app.ui.mask_target || viewing) && has_mask { "mask" } else { "pixels" })
}
-/// `#rrggbb` for an sRGB colour (the engine's colour parameter notation).
-fn hex(c: [f32; 4]) -> String {
- let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
- format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2]))
-}
-
#[cfg(test)]
mod tabs_tests;
diff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/gradient_ui.rs
index 4524fa546..c7347e7e3 100644
--- a/crates/ui-egui/src/gradient_ui.rs
+++ b/crates/ui-egui/src/gradient_ui.rs
@@ -562,11 +562,13 @@ pub fn paint_thumbnail(ui: &egui::Ui, layer: LayerId, f: &Fill, rect: Rect) -> b
true
}
-/// Options-bar swatch of the current gradient (live mode uses the Gradients panel selection).
-pub fn preset_swatch(ui: &mut egui::Ui, stops: &[(f32, [f32; 4])]) {
+/// Options-bar swatch of the current gradient. Both modes paint the selected preset (classic
+/// drags no longer replace it with opaque foreground/background colours), so both show it.
+pub fn preset_swatch(app: &PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
+ let stops = app.session.presets.gradient.resolve(app.session.tools.foreground, app.session.tools.background);
let (r, resp) = ui.allocate_exact_size(vec2(96.0, 20.0), Sense::hover());
- paint_ramp(ui.painter(), r, |u| photocraft_algo::paint::sample_stops(stops, u));
+ paint_ramp(ui.painter(), r, |u| photocraft_algo::paint::sample_stops(&stops, u));
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
let _ = resp.on_hover_text(tl!("The current gradient (pick one in Window › Gradients)"));
}
@@ -949,6 +951,65 @@ mod tests {
assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "no fill layer in classic mode");
}
+ #[test]
+ fn classic_drag_preserves_preset_transparency_at_all_depths() {
+ for depth in [8, 16, 32] {
+ for reverse in [false, true] {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 120, "depth": depth, "background": "transparent"})).unwrap();
+ app.ui.tool = Tool::Gradient;
+ app.ui.tool_options.gradient_classic = true;
+ app.ui.tool_options.gradient_reverse = reverse;
+ app.ui.tool_options.gradient_dither = false;
+ app.ui.tool_options.fill_opacity = 50.0;
+ app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0];
+ app.run("gradient.presets.select", json!({"preset": "Foreground to Transparent"})).unwrap();
+ let before = app.session.active().unwrap().history.past_len();
+ drag(&mut app, [20.0, 60.0], [180.0, 60.0]);
+ let st = app.session.active().unwrap();
+ let surface = st.doc.layers[0].surface().unwrap();
+ for x in [0, 100, 199] {
+ let u = ((x as f32 - 20.0) / 160.0).clamp(0.0, 1.0);
+ let expected = 0.5 * if reverse { u } else { 1.0 - u };
+ let px = surface.pixel(x, 60);
+ assert!((px[3] - expected).abs() < 0.01, "depth {depth}, reverse {reverse}, x {x}: {px:?}");
+ if expected > 0.01 {
+ assert!(px[0] > 0.99 && px[1] < 0.01 && px[2] < 0.01, "preset colour: {px:?}");
+ }
+ }
+ assert_eq!(st.history.past_len(), before + 1);
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.layers[0].surface().unwrap().pixel(100, 60)[3], 0.0);
+ app.run("gradient.presets.select", json!({"stops": [[0, "#00ff00"], [1, "#00ff00"]], "transparency": [[0, 60], [1, 20]]})).unwrap();
+ drag(&mut app, [20.0, 60.0], [180.0, 60.0]);
+ let px = app.session.active().unwrap().doc.layers[0].surface().unwrap().pixel(100, 60);
+ assert!((px[3] - 0.2).abs() < 0.01 && px[1] > 0.99 && px[0] < 0.01, "custom semi-transparent colour: {px:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn sidebar_transparent_preset_reaches_classic_canvas_over_existing_art() {
+ use egui_kittest::{Harness, kittest::Queryable};
+ let mut app = app_with_gradient("linear");
+ app.run("paint.gradient", json!({"from": [0, 0], "to": [199, 0], "colors": ["#ff0000", "#ff0000"]})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.ui.tool_options.gradient_classic = true;
+ app.ui.tool_options.gradient_dither = false;
+ let mut h = Harness::builder().with_size(vec2(420.0, 600.0)).build_ui_state(|ui, app| crate::preset_panels::gradients_panel(app, ui), app);
+ h.get_by_label("Foreground to Transparent").click();
+ h.run();
+ assert_eq!(h.state().session.presets.gradient.name, "Foreground to Transparent");
+ drag(h.state_mut(), [20.0, 60.0], [180.0, 60.0]);
+ let st = h.state().session.active().unwrap();
+ assert_eq!(st.doc.layers.len(), 2);
+ let surface = st.doc.layers[1].surface().unwrap();
+ assert!(surface.pixel(0, 60)[3] > 0.99);
+ assert!((surface.pixel(100, 60)[3] - 0.5).abs() < 0.01);
+ assert!(surface.pixel(199, 60)[3] < 0.01, "transparent end reveals existing art");
+ assert_eq!(st.doc.layers[0].surface().unwrap().pixel(100, 60), vec![1.0, 0.0, 0.0, 1.0], "existing art is unchanged");
+ }
+
#[test]
fn gradient_blend_mode_reaches_live_and_classic_drags() {
use photocraft_color::BlendMode;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index d3c80a88f..0fc0a0924 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -729,12 +729,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if widgets::dropdown(ui, "gradient-mode", &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) {
app.ui.tool_options.gradient_classic = classic;
}
- let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);
- if classic {
- gradient_swatch(ui, fg, bg);
- } else {
- crate::gradient_ui::preset_swatch(ui, &app.session.presets.gradient.resolve(fg, bg));
- }
+ crate::gradient_ui::preset_swatch(app, ui);
widgets::vline(ui, 22.0);
ui.spacing_mut().item_spacing.x = 2.0;
let before = app.ui.tool_options.clone();
@@ -2768,22 +2763,6 @@ fn selection_mode_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.spacing_mut().item_spacing.x = 8.0;
}
-/// Gradient picker swatch (foreground → background), Photoshop options-bar style.
-fn gradient_swatch(ui: &mut egui::Ui, a: [f32; 4], b: [f32; 4]) {
- let t = Tokens::get(ui.ctx());
- let (r, resp) = ui.allocate_exact_size(vec2(96.0, 20.0), Sense::click());
- let mut mesh = egui::Mesh::default();
- mesh.colored_vertex(r.left_top(), c32(a));
- mesh.colored_vertex(r.right_top(), c32(b));
- mesh.colored_vertex(r.right_bottom(), c32(b));
- mesh.colored_vertex(r.left_bottom(), c32(a));
- mesh.add_triangle(0, 1, 2);
- mesh.add_triangle(0, 2, 3);
- ui.painter().add(mesh);
- ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
- let _ = resp.on_hover_text(tl!("Click to edit the gradient"));
-}
-
#[cfg(test)]
mod color_tests {
use super::*;
diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs
index 15ac94f43..05c981e15 100644
--- a/crates/ui-egui/src/preset_panels.rs
+++ b/crates/ui-egui/src/preset_panels.rs
@@ -329,6 +329,7 @@ fn browser(
let (cx, cy) = ((ii % cols) as f32, (ii / cols) as f32);
let r = Rect::from_min_size(area.min + vec2(pad + cx * (cell.x + gap), cy * (cell.y + gap)), cell);
let resp = ui.interact(r, ui.id().with((panel, gi, ii)), Sense::click_and_drag());
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &it.name));
let is_sel = selected.as_deref() == Some(&it.key);
if list {
if is_sel {
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 42c3bbab0..4aac5e8e1 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -38,6 +38,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?}`: change UI state; any other field is an error, checked before anything changes (`theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour)
- `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.
+ Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them.
- `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.