Merge queue batch: 10 PRs (#16645, #15372, #16453, #16455, #16230, #17164, #16223, #17173, #16447, #14820)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-27 14:25:10 +01:00
commit d600edeaf4
35 files changed
+2186 -46

No files matched your search

+13 -3
View File
@@ -410,6 +410,11 @@ pub fn from_layers_defaults(s: &Session) -> Option<(String, [i64; 2])> {
Some((next_artboard_name(&d.doc), [w, h]))
}
/// The smallest width or height Artboard from Layers takes, in pixels (#14577).
pub const FROM_LAYERS_MIN: i64 = 4;
/// The largest width or height Artboard from Layers takes, in pixels (#14577).
pub const FROM_LAYERS_MAX: i64 = 32_000;
fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
let sel = crate::layer_multi_cmds::selected(s);
let d = s.active().ok_or(EngineError::NoDocument)?;
@@ -422,8 +427,9 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "the artboard width and height must not be negative"));
}
// A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps
// their bounds on that axis (#9087).
let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)];
// their bounds on that axis (#9087). As the dialog's fields do, a size outside 4..=32000 px
// is clamped to it (#14577).
let size = [int(p, "width"), int(p, "height")].map(|v| v.filter(|v| *v != 0).map(|v| v.clamp(FROM_LAYERS_MIN, FROM_LAYERS_MAX)));
let (gid, rect, shift) = s.edit("New Artboard From Layers", |doc, active| {
let ids = crate::layer_multi_cmds::top_level(doc, &sel);
if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) {
@@ -1421,7 +1427,7 @@ pub fn specs() -> Vec<CommandSpec> {
"layer.new.artboardFromLayers",
"Artboard from Layers…",
&["Layer", "New"],
r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 0 keeps their bounds) → {layer, rect}"##,
r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 4..32000 px, a size outside is clamped to it, 0 keeps their bounds) → {layer, rect}"##,
has_free_layers,
artboard_from_layers
),
@@ -1497,6 +1503,10 @@ mod include_name_tests;
#[path = "artboard_cmds/from_layers_history_name_tests.rs"]
mod from_layers_history_name_tests;
#[cfg(test)]
#[path = "artboard_cmds/from_layers_size_range_tests.rs"]
mod from_layers_size_range_tests;
#[cfg(test)]
#[path = "artboard_cmds/from_group_hidden_bounds_tests.rs"]
mod from_group_hidden_bounds_tests;
@@ -0,0 +1,67 @@
//! Artboard from Layers takes a width and height of 4 to 32000 px and clamps a scripted size
//! outside that range, as its dialog's fields do when you leave them (#14577). 0 or no size keeps
//! the selected layers' bounds on that axis.
use super::*;
use photocraft_geom::Rect;
/// 100 x 80 RGB at `depth` with a pixel layer "Red" holding a square at 10,10 to 30,30.
fn session(depth: u32) -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth, "background": "white"})).unwrap();
s.edit("Red", |doc, active| {
let fmt = doc.pixel_format();
let mut l = Layer::raster("Red", fmt);
l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 30), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
let id = doc.insert_above(None, l);
*active = Some(id);
Ok(id)
})
.unwrap();
s
}
/// The new board's `[x, y, width, height]` and the canvas size after Artboard from Layers.
fn board(depth: u32, params: Value) -> ([i64; 4], (u32, u32)) {
let mut s = session(depth);
let out = s.execute("layer.new.artboardFromLayers", params.clone()).unwrap_or_else(|e| panic!("{params} at {depth} bit: {e}"));
let rect: Vec<i64> = out["rect"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect();
let doc = &s.active().unwrap().doc;
(rect.try_into().unwrap(), (doc.size.width, doc.size.height))
}
#[test]
fn a_scripted_size_past_the_range_is_clamped_to_4_to_32000() {
for depth in [8, 16, 32] {
let (rect, canvas) = board(depth, json!({"width": 99999, "height": 1}));
assert_eq!(rect, [10, 10, 32_000, 4], "99999 -> 32000, 1 -> 4 at {depth} bit");
assert!(canvas.0 <= 32_100, "the canvas grows only to the clamped board at {depth} bit: {canvas:?}");
let (rect, _) = board(depth, json!({"width": 2, "height": 50_000}));
assert_eq!(rect, [10, 10, 4, 32_000], "2 -> 4, 50000 -> 32000 at {depth} bit");
}
}
#[test]
fn sizes_at_the_ends_of_the_range_are_kept() {
let (rect, _) = board(8, json!({"width": 4, "height": 32_000}));
assert_eq!(rect, [10, 10, 4, 32_000]);
let (rect, _) = board(8, json!({"width": 640, "height": 480}));
assert_eq!(rect, [10, 10, 640, 480]);
}
#[test]
fn zero_or_no_size_keeps_the_layers_bounds() {
for params in [json!({}), json!({"width": 0, "height": 0}), json!({"width": 0})] {
let (rect, _) = board(8, params.clone());
assert_eq!(rect, [10, 10, 20, 20], "{params}");
}
let (rect, _) = board(8, json!({"width": 0, "height": 1}));
assert_eq!(rect, [10, 10, 20, 4], "0 keeps the width, 1 is clamped to 4");
}
#[test]
fn a_negative_size_is_still_refused() {
let mut s = session(8);
let err = s.execute("layer.new.artboardFromLayers", json!({"width": -5})).unwrap_err();
assert!(err.to_string().contains("must not be negative"), "{err}");
}
+4 -1
View File
@@ -119,6 +119,9 @@ mod targeting;
mod tone_target;
mod view;
#[cfg(test)]
mod undo_channel_target_tests;
use calc::{apply_image, calculations};
use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible};
use planes::edit_mode;
@@ -147,8 +150,8 @@ pub(crate) use targeting::{
targeted_channel,
};
pub use tone_target::{ToneTarget, resolve_tone_target};
pub(crate) use view::fix_view;
pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name};
pub(crate) use view::{fix_view, restore_view_after_undo};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -2,6 +2,7 @@ use super::manage::gray_document;
use super::planes::{channel_format, edit_mode, next_alpha_name, plane_surface, read_plane, tone};
use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec};
use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface};
use super::view::{keep_view_for_undo, view_before_step};
use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel};
use photocraft_color::blend::blend_rgb;
@@ -151,6 +152,7 @@ pub(super) fn calculations(s: &mut Session, p: &Value) -> Result<Value> {
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
match p.get("result").and_then(Value::as_str).unwrap_or("newChannel") {
"newChannel" => {
let before = view_before_step(s);
let i = s.edit("Calculations", |doc, _| {
let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha"));
let area = doc.bounds();
@@ -158,6 +160,8 @@ pub(super) fn calculations(s: &mut Session, p: &Value) -> Result<Value> {
doc.channels.push(AlphaChannel::new(name, plane_surface(&out, area, fmt)));
Ok(doc.channels.len() - 1)
})?;
// Undo targets and shows what was before, as after New Channel (#14683).
keep_view_for_undo(s, before);
Ok(json!({ "channel": i }))
}
"newDocument" => {
@@ -2,7 +2,7 @@ use super::planes::{channel_format, color_count, edit_mode, next_alpha_name, pla
use super::refs::{ChanRef, alpha_index, bad, doc_index, gray_plane, parse_ref};
use super::selection::{uniform, unselected_surface};
use super::targeting::target;
use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, touch};
use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, keep_view_for_undo, touch, view_before_step};
use super::{
AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, EngineError, Layer, PixelFormat, Result, Session, Surface, Value, json, list, sel,
};
@@ -32,6 +32,7 @@ pub(super) fn new_channel(s: &mut Session, p: &Value) -> Result<Value> {
let indicates = indicates_param(p.get("indicates"));
let color = color_value("channel.new", p, "color")?;
let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
let before = view_before_step(s);
let i = s.edit("New Channel", |doc, _| {
let area = doc.bounds();
let fmt = channel_format(doc);
@@ -53,7 +54,8 @@ pub(super) fn new_channel(s: &mut Session, p: &Value) -> Result<Value> {
doc.channels.push(ch);
Ok(doc.channels.len() - 1)
})?;
// Photoshop targets and shows a new channel on its own.
// Photoshop targets and shows a new channel on its own; undo targets what was before.
keep_view_for_undo(s, before);
target(s, ChannelTarget::Alpha(i));
Ok(json!({ "channel": i }))
}
@@ -0,0 +1,121 @@
//! Undo of a step that targeted a new alpha channel brings back the channel view from before it:
//! the targeted colour channel and the eyes (#14683).
use super::*;
use crate::channel_cmds::ChannelView;
fn session() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 40, "height": 20})).unwrap();
s
}
fn view(s: &Session) -> ChannelView {
s.active().unwrap().channel_view.clone()
}
/// Red targeted (shown alone), then `command`, then undo: Red is the target again and the only
/// colour channel shown, as before the command.
fn undo_returns_to_red(command: &str, params: Value) {
let mut s = session();
s.execute("channel.target", json!({"channel": "red"})).unwrap();
let before = view(&s);
assert_eq!(before.target, ChannelTarget::Color(0));
s.execute(command, params).unwrap();
assert!(s.undo());
assert!(doc(&s).channels.is_empty());
let after = view(&s);
assert_eq!((after.target, &after.color_hidden), (before.target, &before.color_hidden), "{command}");
assert_eq!(channels_json(s.active().unwrap()), channels_json_of(before, &s), "{command}");
}
fn doc(s: &Session) -> &Document {
&s.active().unwrap().doc
}
/// The Channels panel as `view` would show the current document.
fn channels_json_of(view: ChannelView, s: &Session) -> Value {
let mut st = s.active().unwrap().clone();
st.channel_view = view;
channels_json(&st)
}
#[test]
fn undo_of_new_channel_targets_the_colour_channel_again() {
undo_returns_to_red("channel.new", json!({}));
}
#[test]
fn undo_of_calculations_new_channel_targets_the_colour_channel_again() {
undo_returns_to_red("image.calculations", json!({"result": "newChannel"}));
}
/// From the composite, undo returns to the composite with every colour channel shown, as today.
#[test]
fn undo_from_the_composite_keeps_working() {
for command in ["channel.new", "image.calculations"] {
let mut s = session();
let before = view(&s);
s.execute(command, json!({})).unwrap();
assert!(s.undo());
let after = view(&s);
assert_eq!(after.target, ChannelTarget::Composite, "{command}");
assert_eq!(channels_json(s.active().unwrap()), channels_json_of(before, &s), "{command}");
}
}
/// Redo brings the new channel back, and undo after it returns to Red again.
#[test]
fn undo_after_redo_returns_to_red_again() {
let mut s = session();
s.execute("channel.target", json!({"channel": "red"})).unwrap();
s.execute("channel.new", json!({})).unwrap();
assert!(s.undo());
assert!(s.redo());
assert_eq!(doc(&s).channels.len(), 1);
assert!(s.undo());
assert_eq!(view(&s).target, ChannelTarget::Color(0));
}
/// Other commands' undo leaves the channel view as it is: a selection made with Red targeted,
/// then Green targeted, undone, keeps Green.
#[test]
fn other_steps_do_not_restore_the_view() {
let mut s = session();
s.execute("channel.target", json!({"channel": "red"})).unwrap();
s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
s.execute("channel.target", json!({"channel": "green"})).unwrap();
assert!(s.undo());
assert_eq!(view(&s).target, ChannelTarget::Color(1));
}
/// New Channel from Red, undone, then a selection made from the same state with Green targeted:
/// undo of the selection lands on the state New Channel started from but undoes the selection, so
/// Green stays targeted.
#[test]
fn undo_of_a_later_step_from_the_same_state_keeps_the_target() {
let mut s = session();
s.execute("channel.target", json!({"channel": "red"})).unwrap();
s.execute("channel.new", json!({})).unwrap();
assert!(s.undo());
s.execute("channel.target", json!({"channel": "green"})).unwrap();
s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
assert!(s.undo());
assert_eq!(view(&s).target, ChannelTarget::Color(1));
}
/// The remembered view stays with the New Channel step: every undo of it, after any number of
/// redos, returns to Red.
#[test]
fn every_undo_of_new_channel_returns_to_red() {
let mut s = session();
s.execute("channel.target", json!({"channel": "red"})).unwrap();
s.execute("channel.new", json!({})).unwrap();
for round in 0..3 {
assert!(s.undo());
assert_eq!(view(&s).target, ChannelTarget::Color(0), "undo {round}");
s.execute("channel.target", json!({"channel": "blue"})).unwrap();
assert!(s.redo());
assert_eq!(doc(&s).channels.len(), 1);
}
}
@@ -1,5 +1,5 @@
use super::planes::color_count;
use super::{ColorMode, DocState, Document, Serialize};
use super::{ColorMode, DocState, Document, Serialize, Session};
// ---------------------------------------------------------------------------------------------
// View state
@@ -155,3 +155,34 @@ pub fn composite_name(mode: ColorMode) -> &'static str {
_ => "RGB",
}
}
// ---------------------------------------------------------------------------------------------
// Undo of a step that targets the channel it creates
/// Before New Channel or Calculations (Result: New Channel), which target the channel they make:
/// the history state the step starts from and the channel view then.
pub(super) fn view_before_step(s: &Session) -> Option<(u64, ChannelView)> {
let st = s.active()?;
Some((st.history.row_id(st.history.past_len())?, st.channel_view.clone()))
}
/// After that step: undoing it (leaving the state it made for the one it started from) brings
/// `before`'s view back (#14683). Kept for the step, so undo after redo brings it back again. The
/// views of steps history no longer holds are dropped.
pub(super) fn keep_view_for_undo(s: &mut Session, before: Option<(u64, ChannelView)>) {
let (Some(st), Some((from, view))) = (s.active_mut(), before) else { return };
let Some(to) = st.history.row_id(st.history.past_len()) else { return };
let history = &st.history;
st.undo_channel_views.retain(|(kept_from, kept_to, _)| *kept_to != to && history.row_of(*kept_from).is_some() && history.row_of(*kept_to).is_some());
st.undo_channel_views.push((from, to, view));
}
/// Undo just left the state `left` for the current one: when that undid a step with a kept view,
/// target and show the channels it did.
pub(crate) fn restore_view_after_undo(st: &mut DocState, left: Option<u64>) {
let Some(left) = left else { return };
let Some(id) = st.history.row_id(st.history.past_len()) else { return };
let Some((_, _, view)) = st.undo_channel_views.iter().find(|(from, to, _)| *from == id && *to == left) else { return };
st.channel_view = view.clone();
fix_view(st);
}
@@ -158,8 +158,8 @@ pub fn specs() -> Vec<CommandSpec> {
&["Layer", "New"],
None,
r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##,
has_layer,
group_layers
structure::can_group_from_layers,
structure::group_from_layers
),
spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)),
spec!(
@@ -183,3 +183,6 @@ mod layers_panel_parity_tests;
#[cfg(test)]
mod tile_damage_tests;
#[cfg(test)]
mod group_from_layers_background_tests;
@@ -0,0 +1,112 @@
//! Group from Layers is refused while the Background is among the selected layers (#14709), as
//! the menu rows already grey it. Layer > Group Layers keeps grouping it (not measured).
use super::*;
/// A 32 x 32 document with a white Background and the pixel layers Red, Green and Blue above it.
fn session() -> (Session, LayerId, [LayerId; 3]) {
let mut s = crate::session();
s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap();
let bg = s.active().unwrap().doc.layers[0].id;
assert!(s.active().unwrap().doc.is_background(bg));
let ids = ["Red", "Green", "Blue"].map(|name| LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap()));
(s, bg, ids)
}
fn select(s: &mut Session, ids: &[LayerId], active: LayerId) {
set_selection(s, ids.to_vec(), Some(active), Some(active)).unwrap();
}
/// Everything a refused command must leave alone: the layer tree, the selection and the history.
fn snapshot(s: &Session) -> (photocraft_doc::layer_tree::LayerTree, Vec<LayerId>, Option<LayerId>, Vec<String>) {
let d = s.active().unwrap();
(d.doc.layers.clone(), d.selected_layers().to_vec(), d.active_layer, d.history.entries())
}
fn enabled(s: &Session) -> std::result::Result<(), String> {
(crate::commands::find("layer.new.groupFromLayers").unwrap().enabled)(s)
}
fn refused(s: &mut Session, params: Value) {
let before = snapshot(s);
assert!(s.execute("layer.new.groupFromLayers", params.clone()).is_err(), "{params} must be refused");
assert!(snapshot(s) == before, "{params} changed the document");
assert!(s.active().unwrap().doc.background().is_some(), "the Background is still there");
}
#[test]
fn the_background_alone_is_refused() {
let (mut s, bg, _) = session();
select(&mut s, &[bg], bg);
assert!(enabled(&s).is_err(), "disabled with the Background selected");
refused(&mut s, json!({}));
refused(&mut s, json!({"name": "Set", "color": "red", "mode": "normal", "opacity": 50}));
}
#[test]
fn the_background_with_other_layers_is_refused() {
let (mut s, bg, [red, green, _]) = session();
for active in [red, bg] {
select(&mut s, &[bg, red], active);
assert!(enabled(&s).is_err(), "disabled with the Background and Red selected");
refused(&mut s, json!({}));
}
select(&mut s, &[bg, red, green], green);
refused(&mut s, json!({}));
}
#[test]
fn an_explicit_background_layer_is_refused() {
let (mut s, bg, [red, _, blue]) = session();
select(&mut s, &[blue], blue);
refused(&mut s, json!({"layer": bg.0}));
select(&mut s, &[red, blue], red);
refused(&mut s, json!({"layer": bg.0}));
select(&mut s, &[bg], bg);
refused(&mut s, json!({"layer": bg.0}));
}
#[test]
fn a_background_only_document_is_refused() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap();
assert_eq!(s.active().unwrap().doc.layers.len(), 1);
assert!(enabled(&s).is_err());
refused(&mut s, json!({}));
}
fn children(s: &Session, group: LayerId) -> Vec<LayerId> {
s.active().unwrap().doc.layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect()
}
#[test]
fn layers_without_the_background_still_group() {
let (mut s, bg, [red, green, blue]) = session();
select(&mut s, &[blue], blue);
assert!(enabled(&s).is_ok());
let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
assert_eq!(children(&s, g), vec![blue]);
select(&mut s, &[red, green], green);
let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
assert_eq!(children(&s, g), vec![red, green]);
assert!(s.active().unwrap().doc.is_background(bg), "the Background stays");
}
#[test]
fn an_explicit_layer_other_than_the_background_still_groups() {
let (mut s, bg, [red, _, blue]) = session();
select(&mut s, &[blue], blue);
let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"layer": red.0})).unwrap()["layer"].as_u64().unwrap());
assert_eq!(children(&s, g), vec![red]);
assert!(s.active().unwrap().doc.is_background(bg));
}
/// Layer > Group Layers with the Background selected is not measured: it keeps today's result.
#[test]
fn group_layers_keeps_grouping_the_background() {
let (mut s, bg, [red, ..]) = session();
select(&mut s, &[bg, red], red);
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
assert_eq!(children(&s, g), vec![bg, red]);
}
@@ -111,6 +111,32 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> {
Ok(())
}
/// Group from Layers is greyed while the Background is among the selected layers, as in the
/// menus (#14709).
pub(super) fn can_group_from_layers(s: &Session) -> std::result::Result<(), String> {
super::has_layer(s)?;
let d = s.active().ok_or("no document open")?;
if d.selected_layers().iter().any(|id| d.doc.is_background(*id)) {
return Err("the Background layer can't go into a group".into());
}
Ok(())
}
/// Group from Layers: [`group_layers`], refused with the Background among the layers it would
/// move, also when the `layer` param names it (#14709). Group Layers (⌘G) is not measured and
/// keeps grouping it.
pub(super) fn group_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
let ids = match crate::commands::explicit_layer(s, p)? {
Some(id) => vec![id],
None => selected(s),
};
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
if ids.iter().any(|id| doc.is_background(*id)) {
return Err(EngineError::Other("the Background layer can't go into a group".into()));
}
group_layers(s, p)
}
/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves
/// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is
/// preserved. The New Group dialog's colour, mode and opacity are set in the same history step.
@@ -1014,7 +1014,8 @@ fn a_locked_group_keeps_a_grouped_background_locked() {
let mut s = session(8);
let bg = doc(&s).layers[0].id;
s.execute("layer.select", json!({"layer": bg.0})).unwrap();
let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap();
// Group from Layers refuses the Background (#14709); Group Layers still groups it.
let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap();
s.execute("layer.select", json!({"layer": bg.0})).unwrap();
for (cmd, p) in [
+4
View File
@@ -31,6 +31,9 @@ pub struct DocState {
pub coalesce: Option<String>,
/// Channels panel: targeted channel and eye toggles (view state, not history).
pub channel_view: channel_cmds::ChannelView,
/// The channel views undo brings back, by the step they belong to: the ids of the history
/// states New Channel or Calculations started from and made (#14683). View state, not history.
pub(crate) undo_channel_views: Vec<(u64, u64, channel_cmds::ChannelView)>,
/// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state).
pub isolated_layers: Vec<LayerId>,
/// Painting symmetry preset or sampled path (tool state, not document pixels).
@@ -144,6 +147,7 @@ impl DocState {
damage_log: Default::default(),
coalesce: None,
channel_view,
undo_channel_views: Vec::new(),
isolated_layers: Vec::new(),
symmetry: None,
fx_collapsed: Vec::new(),
+19 -3
View File
@@ -164,7 +164,9 @@ pub fn effect_defaults(kind: &str) -> Value {
"stroke" => json!({"size": 1, "position": "inside", "blend": "Normal", "opacity": 100, "overprint": false, "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, "method": "custom"})
// The reference application's "Gray, White" with the Smooth method (#14900). The page
// edits the stop list; From/To name the same ends for callers that read them.
json!({"blend": "Normal", "opacity": 100, "from": "#d7d7d7", "to": "#ffffff", "stops": [[0, "#d7d7d7"], [1, "#ffffff"]], "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "smooth", "smoothness": 100})
}
"patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}),
"bevelEmboss" => {
@@ -553,6 +555,12 @@ pub fn contour_to_shc_all(list: &[&Contour]) -> Result<Vec<u8>> {
craft_psd::shc::write(&file).map_err(|e| EngineError::Other(format!("can't write the contour: {e}")))
}
/// A Gradient Overlay with `Gradient::default()` (black to white, straight stops) and no recorded
/// method: what a command that names its own colours or stops starts from.
fn blank_gradient_overlay() -> Effect {
Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None }
}
/// An effect of `kind` with its factory settings (before params are applied).
fn fresh_effect(kind: &str) -> Option<Effect> {
let shadow = |inner: bool| Shadow {
@@ -598,7 +606,10 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
}),
"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, interpolation: None }
// The factory values carry the recorded Smooth method, so build them like the page does.
let mut fx = blank_gradient_overlay();
overlay_effect(&mut fx, &effect_defaults(kind));
fx
}
"patternOverlay" => Effect::PatternOverlay {
common: FxCommon::new(BlendMode::Normal, 1.0),
@@ -974,7 +985,10 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {
/// spread, range in percent; sizes in px; angles in degrees).
pub fn effect_from_params(kind: &str, p: &Value) -> Option<Effect> {
crate::commands::check_f32_values("layer.layerStyle", p).ok()?;
let mut fx = fresh_effect(kind)?;
// A Gradient Overlay given its own colours or stops keeps today's straight stops unless the
// params pick a method; only the factory one (#14900) starts from the Smooth grey to white.
let mut fx =
if kind == "gradientOverlay" && ["from", "to", "stops"].iter().any(|k| p.get(k).is_some()) { blank_gradient_overlay() } else { fresh_effect(kind)? };
overlay_effect(&mut fx, p);
Some(fx)
}
@@ -1320,6 +1334,8 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result<Value> {
Ok(Value::Null)
}
#[cfg(test)]
mod gradient_overlay_defaults_tests;
#[cfg(test)]
mod satin_defaults_tests;
@@ -248,13 +248,18 @@ mod tests {
}
#[test]
fn reset_to_factory_defaults_removes_the_recorded_method() {
fn reset_to_factory_defaults_restores_the_factory_gradient_and_method() {
let mut gradient = Gradient::default();
let mut source = None;
overlay(&mut gradient, &mut source, &json!({"method": "smooth", "from": "#ff0000"}));
overlay(&mut gradient, &mut source, &json!({"method": "classic", "from": "#ff0000"}));
overlay(&mut gradient, &mut source, &super::super::effect_defaults("gradientOverlay"));
assert!(source.is_none());
assert_eq!(gradient, Gradient::default());
let Some(Effect::GradientOverlay { gradient: factory, interpolation: factory_source, .. }) =
super::super::effect_from_params("gradientOverlay", &json!({}))
else {
panic!("no factory overlay")
};
assert_eq!(source, factory_source, "#14900: the factory overlay records Smooth grey 215 to white");
assert_eq!(gradient, factory);
}
}
@@ -0,0 +1,149 @@
//! #14900: the Gradient Overlay page's factory values (Normal, 100 %, grey 215 to white, Method
//! Smooth, Smoothness 100 %, Linear, Angle 90, Scale 100) and the rule that an overlay already
//! stored keeps its own gradient and method. The measured column of the factory overlay sits
//! within 2 levels of the reference application's on the white test document.
use super::*;
use crate::Session;
use photocraft_doc::GradientStyle;
use photocraft_doc::effects::GradientInterpolation;
use serde_json::json;
const GREY_215: f32 = 215.0 / 255.0;
/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel
/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224.
fn test_document() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
// Edit > Fill lives in photocraft-engine-paint, so the rectangle is written directly.
let id = s.active().unwrap().active_layer.unwrap();
s.edit("orange", |doc, _| {
let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap();
let r = photocraft_geom::Rect::from_xywh(100, 75, 200, 150);
let px = photocraft_raster::from_rgba(&surf.format(), [1.0, 128.0 / 255.0, 0.0, 1.0]);
surf.write_region(r, &px.repeat(200 * 150));
Ok(())
})
.unwrap();
s
}
fn session() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s
}
/// The one effect the active layer carries.
fn only_effect(s: &Session) -> Effect {
let d = s.active().unwrap();
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
match l.effects.items.as_slice() {
[fx] => fx.clone(),
other => panic!("not one effect: {other:?}"),
}
}
fn close(a: &Color, rgb: [f32; 3]) -> bool {
a.to_rgb().iter().zip(rgb).all(|(x, y)| (x - y).abs() < 1e-3)
}
/// #14900: Layer > Layer Style > Gradient Overlay... seeds a new instance from `effect_defaults`
/// (the page reads its stop list, so the stops carry the colours as well as From/To).
#[test]
fn a_new_gradient_overlay_starts_at_the_factory_values() {
let d = effect_defaults("gradientOverlay");
assert_eq!(d["blend"], json!("Normal"), "blend");
assert_eq!(d["opacity"], json!(100), "opacity");
assert_eq!(d["stops"], json!([[0, "#d7d7d7"], [1, "#ffffff"]]), "stops");
assert_eq!((d["from"].as_str(), d["to"].as_str()), (Some("#d7d7d7"), Some("#ffffff")), "from / to");
assert_eq!(d["method"], json!("smooth"), "method");
assert_eq!(d["smoothness"], json!(100), "smoothness");
assert_eq!(d["reverse"], json!(false), "reverse");
assert_eq!(d["style"], json!("linear"), "style");
assert_eq!(d["angle"], json!(90), "angle");
assert_eq!(d["scale"], json!(100), "scale");
}
/// #14900: `layer.layerStyle.gradientOverlay` without colours or stops makes the factory overlay:
/// grey 215 to white with the Smooth method recorded, the rest at the page's values.
#[test]
fn a_gradient_overlay_command_without_colours_makes_the_factory_effect() {
let mut s = session();
s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap();
let Effect::GradientOverlay { common, gradient, dither, interpolation } = only_effect(&s) else { panic!("not a gradient overlay") };
assert_eq!((common.blend, common.opacity), (BlendMode::Normal, 1.0));
assert!(!dither, "dither");
let Some(GradientInterpolation { method, smoothness, stops }) = interpolation else { panic!("no recorded method") };
assert_eq!((method.as_str(), smoothness), ("smooth", 100.0));
assert_eq!(stops.len(), 2, "source stops {stops:?}");
assert!(stops[0].0 == 0.0 && close(&stops[0].1, [GREY_215; 3]), "first stop {:?}", stops[0]);
assert!(stops[1].0 == 1.0 && close(&stops[1].1, [1.0; 3]), "last stop {:?}", stops[1]);
assert!(close(&gradient.stops.first().unwrap().1, [GREY_215; 3]) && close(&gradient.stops.last().unwrap().1, [1.0; 3]), "baked ends");
assert!(gradient.stops.len() > 2, "the Smooth curve is baked, not straight: {:?}", gradient.stops);
assert_eq!((gradient.style, gradient.angle, gradient.scale, gradient.reverse, gradient.align), (GradientStyle::Linear, 90.0, 1.0, false, true));
// The dialog's OK on the factory values (its stop list, no From/To) builds the same effect.
let mut dialog = effect_defaults("gradientOverlay");
dialog.as_object_mut().unwrap().retain(|k, _| k != "from" && k != "to");
assert_eq!(effect_from_params("gradientOverlay", &json!({})), effect_from_params("gradientOverlay", &dialog));
}
/// #14900 measured: OK on the factory values over the white test document. Red channel at
/// x 200 down the rectangle; the reference application gives
/// `255 255 251 246 240 235 235 230 224 219 215 215`, each within 2 levels. Outside stays white.
#[test]
fn the_factory_gradient_overlay_paints_the_measured_column() {
let mut s = test_document();
s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap();
let d = s.active().unwrap();
let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px();
let level = |x: usize, y: usize, c: usize| (px[y * 400 + x][c] * 255.0).round() as i32;
let want = [(75, 255), (76, 255), (94, 251), (112, 246), (131, 240), (149, 235), (150, 235), (168, 230), (187, 224), (205, 219), (223, 215), (224, 215)];
let got: Vec<i32> = want.iter().map(|&(y, _)| level(200, y, 0)).collect();
for (&(y, w), g) in want.iter().zip(&got) {
assert!((g - w).abs() <= 2, "red at (200, {y}): {g}, the reference gives {w}; column {got:?}");
}
for (x, y) in [(200, 74), (200, 225), (99, 150), (300, 150)] {
assert_eq!([0, 1, 2].map(|c| level(x, y, c)), [255; 3], "outside the layer at ({x}, {y})");
}
}
/// #14900: Reset to Default reads the factory values through `layer.layerStyle.defaultFor` until a
/// Make Default stores other ones; the saved values keep winning.
#[test]
fn reset_to_default_restores_the_gradient_overlay_factory_values() {
let mut s = session();
let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap();
assert_eq!(d["user"], json!(false));
assert_eq!(d["params"], effect_defaults("gradientOverlay"));
assert_eq!((d["params"]["method"].as_str(), d["params"]["stops"][0][1].as_str()), (Some("smooth"), Some("#d7d7d7")));
s.execute("layer.layerStyle.makeDefault", json!({"kind": "gradientOverlay", "params": {"opacity": 40, "method": "linear"}})).unwrap();
let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap();
assert_eq!(saved["user"], json!(true));
assert_eq!((saved["params"]["opacity"].as_f64(), saved["params"]["method"].as_str()), (Some(40.0), Some("linear")), "a saved default still wins");
}
/// #14900: an overlay the document already carries (a PSD or `.pcraft` one, edited in the dialog)
/// keeps its gradient and method through `layer.layerStyle.replace`, and a command that names its
/// colours still gets those colours.
#[test]
fn a_stored_gradient_overlay_keeps_its_own_gradient_and_method() {
let mut s = session();
let stored = Effect::GradientOverlay {
common: FxCommon::new(BlendMode::Multiply, 0.5),
gradient: Gradient { stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], angle: 30.0, ..Gradient::default() },
dither: true,
interpolation: None,
};
let snapshot = serde_json::to_value(&stored).unwrap();
s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "gradientOverlay", "params": {}, "fx": snapshot}]})).unwrap();
assert_eq!(only_effect(&s), stored, "an edited effect list left the overlay alone");
s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff"})).unwrap();
let Effect::GradientOverlay { gradient, interpolation, .. } = only_effect(&s) else { panic!("not a gradient overlay") };
assert_eq!(interpolation, None, "named colours keep today's straight stops");
assert_eq!(gradient.stops, vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))]);
}
@@ -25,6 +25,7 @@ impl Session {
st.coalesce = None;
// The step being undone: the layers whose visibility it changed get it back.
let changed = st.history.current_visibility().to_vec();
let left = st.history.row_id(st.history.past_len());
let doc = st.doc.clone();
match st.history.undo(doc) {
// Undo Clear History: the list comes back, the document is the same one. Not an
@@ -55,6 +56,7 @@ impl Session {
let before = std::mem::replace(st.doc_mut(), d);
let keep_clean = st.keeps_clean(&before);
restore_target(st, layers);
channel_cmds::restore_view_after_undo(st, left);
st.bump_revision(keep_clean);
st.last_damage = damage;
st.record_damage();
+11 -7
View File
@@ -249,18 +249,22 @@ fn red_eye(s: &mut Session, p: &Value) -> Result<Value> {
let pupil = pupil_raw.clamp(1.0, 100.0);
let darken = darken.clamp(0.0, 100.0);
let id = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|d| d.active_layer) };
// The press point decides (#12576): a press outside the selection does nothing, not clipped, and
// like Photoshop it is silent (#13096): no pixels, no state, no message. Feathered (partly
// selected) and off-canvas presses were not measured and keep today's behaviour: any value above
// 0 counts as inside, and off-canvas presses are not checked.
if let (Some(&first), Some(d)) = (pts.first(), s.active())
&& d.doc.bounds().contains(first.0, first.1)
&& d.doc.selection.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0)
{
return Ok(json!({ "damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true }));
}
let (damage, total) = s.edit("Red Eye Removal Tool", |doc, active| {
let canvas = doc.bounds();
let sel = doc.selection.clone();
let layer = id.or(*active);
let (surf, lock) = crate::channel_cmds::target_surface(doc, layer, p)?;
let Some(&first) = pts.first() else { return Err(EngineError::Other(MISS.into())) };
// The press point decides (#12576): a press outside the selection is refused like a miss,
// not clipped. Feathered (partly selected) and off-canvas presses were not measured and keep
// today's behaviour: any value above 0 counts as inside, and off-canvas presses are not checked.
if canvas.contains(first.0, first.1) && sel.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0) {
return Err(EngineError::Other(MISS.into()));
}
// The Background always locks transparency, so only a click on a clear pixel counts.
let on_locked_clear = lock && surf.rgba(first.0, first.1)[3] <= 1.0e-5;
let mut total = 0u32;
@@ -286,7 +290,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Red Eye",
menu: &[],
shortcut: None,
params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n}"#,
params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n, "outsideSelection":true?}"#,
enabled,
run: red_eye,
journal: true,
@@ -127,7 +127,13 @@ fn refused_clicks_add_no_state() {
refused(&mut s, params, case);
}
s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap();
refused(&mut s, json!({"x": 8, "y": 8}), "a click outside the selection");
// #13096: a click outside the selection does nothing silently: an Ok with no state.
let (n, _) = last(&s);
let before = pixels(&s);
let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap();
assert_eq!((r["pixels"].as_u64(), r["outsideSelection"].as_bool()), (Some(0), Some(true)), "{r}");
assert_eq!(last(&s).0, n, "a click outside the selection: no state");
assert!(pixels(&s) == before, "a click outside the selection");
unchanged_state(&mut s, json!({"x": 44, "y": 44}), "a click inside the selection");
s.execute("select.deselect", json!({})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
@@ -1,5 +1,6 @@
//! #12576: a Red Eye press outside the selection does nothing and adds no History state; a press
//! inside it is clipped to the selection as before, and with no selection nothing changes.
//! #13096: the outside press is silent, an `Ok` that says so, not the miss error.
use serde_json::{Value, json};
@@ -23,7 +24,7 @@ fn eyes() -> Session {
/// The left half of eye B: x 450–499.
fn select_left_half_of_eye_b(s: &mut Session) {
s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 600})).unwrap();
s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 1000})).unwrap();
}
/// History length, and the Background's pixels as one value per channel.
@@ -53,10 +54,46 @@ fn a_press_outside_the_selection_changes_nothing_and_adds_no_state() {
let (states, cols, r) = press(&mut s, params.clone());
assert_eq!(cols, None, "{params}: pixels changed");
assert_eq!(states, 0, "{params}: a history state was added");
assert_eq!(r, Err(MISS.to_string()), "{params}");
let r = r.unwrap_or_else(|e| panic!("{params}: an outside press is not an error: {e}"));
assert_eq!(r, json!({"damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true}), "{params}");
}
}
#[test]
fn an_outside_press_is_silent_at_every_depth() {
for depth in [8, 16, 32] {
let mut s = crate::session();
s.execute("file.new", json!({"width": 64, "height": 64, "mode": "rgb", "depth": depth})).unwrap();
s.execute("edit.fill", json!({"color": "#d22828"})).unwrap();
s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap();
let n = s.active().unwrap().history.past_len();
let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap_or_else(|e| panic!("{depth} bit: {e}"));
assert_eq!(r["pixels"], 0, "{depth} bit");
assert_eq!(r["outsideSelection"], true, "{depth} bit");
assert_eq!(s.active().unwrap().history.past_len(), n, "{depth} bit: no state");
}
}
#[test]
fn a_miss_inside_the_selection_keeps_its_result() {
// On a dark blue patch inside the selection: the tool runs and leaves one unchanged state, as before.
let mut s = eyes();
s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 100})).unwrap();
s.execute("edit.fill", json!({"color": "#283c78"})).unwrap();
select_left_half_of_eye_b(&mut s);
let (states, cols, r) = press(&mut s, json!({"x": 475, "y": 40, "pupilSize": 1}));
let r = r.unwrap();
assert_eq!((r["pixels"].as_u64(), r.get("outsideSelection")), (Some(0), None), "{r}");
assert_eq!((states, cols), (1, None));
// On a clear pixel under Lock transparent pixels inside the selection: still the miss error.
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("layer.lockLayers", json!({"transparency": true})).unwrap();
let n = s.active().unwrap().history.past_len();
let r = s.execute("paint.redEye", json!({"x": 475, "y": 40, "pupilSize": 1})).map_err(|e| e.to_string());
assert_eq!(r, Err(MISS.to_string()));
assert_eq!(s.active().unwrap().history.past_len(), n);
}
#[test]
fn a_press_inside_the_selection_is_clipped_and_adds_one_state() {
// A batch whose first point is inside runs, and x 499.5 is still on the last selected column.
@@ -4,7 +4,7 @@ use super::{
Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag,
from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_blend, parse_brush, run_stroke, sponge, string, to_rgba,
};
use photocraft_algo::retouch::sponge_rgb;
use photocraft_algo::retouch::{luma, sponge_rgb, tone_curve};
use photocraft_color::{ColorMode, SampleType};
// ---------------------------------------------------------------------------------------------
@@ -185,6 +185,46 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + Send + '
})
}
/// Strength of [`linear_midtones`] per unit of Exposure.
const LINEAR_MIDTONES_STRENGTH: f32 = 1.34;
/// The Midtones Dodge (`burn = false`) or Burn curve for one linear value of a 32-bit document at
/// exposure `e` (0..1): `v ± 1.34·e·v²·(1 − v)^1.5`, each channel on its own. It is fitted to the
/// reference's 32-bit results (#12687), which tone the stored linear values: much gentler on the
/// mid tones than the 8-bit curve on gamma-encoded values, and the shadows are left alone. Black
/// and white stay put, values outside 0..1 (light above white) are kept as they are, and tones
/// stay in order at every exposure.
#[inline]
fn linear_midtones(v: f32, e: f32, burn: bool) -> f32 {
if !(v > 0.0 && v < 1.0) {
return v;
}
let d = LINEAR_MIDTONES_STRENGTH * e.clamp(0.0, 1.0) * v * v * (1.0 - v).powf(1.5);
if burn { v - d } else { v + d }
}
/// The 32-bit reference was measured at Exposure 50 % only (#12687); other exposures keep the
/// gamma curve.
const MEASURED_LINEAR_EXPOSURE: f32 = 0.5;
/// Dodge or Burn of a 32-bit colour with the curve the other bit depths use, except that light above
/// white isn't clipped: Protect Tones scales such a colour to its new luma without gamut
/// compression, which would pull it back to 1.0 (#12687). Such a colour whose luma isn't positive
/// (a negative channel outweighs it) can't be scaled by luma, so it takes the per-channel curve, as
/// with Protect Tones off, which keeps light above white too. Other colours get today's result.
#[inline]
fn dodge_burn_float(c: [f32; 3], e: f32, range: ToneRange, burn: bool, protect: bool) -> [f32; 3] {
if protect && c.iter().any(|&v| v > 1.0) {
let l = luma(c);
if l > 1e-6 {
let nl = tone_curve(l, e, range, burn);
return c.map(|v| v * nl / l);
}
return dodge_burn(c, e, range, burn, false);
}
dodge_burn(c, e, range, burn, protect)
}
fn tone_range(p: &Value, cmd: &str) -> Result<ToneRange> {
match string(p, "range", "midtones") {
"shadows" => Ok(ToneRange::Shadows),
@@ -305,6 +345,18 @@ impl DabTool {
pub(super) fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect {
let sp = spacing;
match self.clone() {
// A 32-bit RGB document holds linear values, which the reference's default Dodge tones
// with its own curve. Grayscale, the other ranges, Protect Tones off and the other
// exposures weren't measured there and keep the gamma curve, without clipping light
// above white.
Self::Tone { burn: false, range: ToneRange::Midtones, exposure, protect: true }
if fmt.sample == SampleType::F32 && fmt.mode == ColorMode::Rgb && (exposure - MEASURED_LINEAR_EXPOSURE).abs() < 1e-4 =>
{
tone_stroke(fmt, move |c| c.map(|v| linear_midtones(v, exposure, false)))
}
Self::Tone { burn, range, exposure, protect } if fmt.sample == SampleType::F32 => {
tone_stroke(fmt, move |c| dodge_burn_float(c, exposure, range, burn, protect))
}
Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)),
// Flow is already in the dab's coverage. The reference RGB response applies to integer
// RGB surfaces, including 16-bit. Float RGB and the other models use the legacy curve.
@@ -828,3 +880,7 @@ mod smudge_refuses_indexed_tests;
#[cfg(test)]
#[path = "smudge_mode_tests.rs"]
mod smudge_mode_tests;
#[cfg(test)]
#[path = "dodge_32bit_linear_tests.rs"]
mod dodge_32bit_linear_tests;
@@ -0,0 +1,187 @@
//! Dodge in a 32-bit document tones the linear values it holds, with the reference's curve
//! (#12687); 8- and 16-bit documents keep their results.
use crate::Session;
use photocraft_algo::retouch::{ToneRange, dodge_burn};
use photocraft_color::convert::linear_to_srgb;
use serde_json::{Value, json};
/// The reference's test colours (8-bit RGB): grey 32, 128 and 224, red, skin and pastel.
const PATCHES: [[u8; 3]; 6] = [[32, 32, 32], [128, 128, 128], [224, 224, 224], [200, 40, 40], [220, 170, 140], [180, 200, 230]];
const SIDE: i32 = 60;
/// An 8-bit RGB document of `PATCHES` side by side, converted to `depth` bits.
fn patches(depth: u32) -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": SIDE * PATCHES.len() as i32, "height": SIDE, "depth": 8, "mode": "rgb"})).unwrap();
s.edit("patches", |doc, active| {
let b = doc.bounds();
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let fmt = surf.format();
let mut data = Vec::new();
for _ in b.y0..b.y1 {
for x in b.x0..b.x1 {
let c = PATCHES[(x / SIDE) as usize].map(|v| f32::from(v) / 255.0);
data.extend(photocraft_raster::from_rgba(&fmt, [c[0], c[1], c[2], 1.0]));
}
}
surf.write_region(b, &data);
Ok(())
})
.unwrap();
if depth != 8 {
s.execute(&format!("image.mode.bits{depth}"), json!({})).unwrap();
}
s
}
fn rgb(s: &Session, x: i32, y: i32) -> [f32; 3] {
let d = s.active().unwrap();
let p = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y);
[p[0], p[1], p[2]]
}
/// One default Dodge click (Midtones, Protect Tones, 50 %) with a hard 40 px tip on each patch's
/// centre; the stored values there.
fn dodge_each(s: &mut Session, extra: Value) -> Vec<[f32; 3]> {
(0..PATCHES.len() as i32)
.map(|i| {
let (x, y) = (i * SIDE + SIDE / 2, SIDE / 2);
let mut p = json!({"points": [[x, y]], "size": 40, "hardness": 100});
if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) {
p.extend(e.clone());
}
s.execute("paint.dodge", p).unwrap();
rgb(s, x, y)
})
.collect()
}
/// A 32-bit document's linear values as 8-bit RGB, as the reference reads them.
fn as_8bit(c: [f32; 3]) -> [i32; 3] {
c.map(|v| (linear_to_srgb(v).clamp(0.0, 1.0) * 255.0).round() as i32)
}
#[test]
fn dodge_tones_linear_values_in_32_bit() {
// Measured in the reference: one default click in a 32-bit RGB document, read as 8-bit.
let expected = [[32, 32, 32], [134, 134, 134], [230, 230, 230], [210, 40, 40], [227, 177, 147], [191, 209, 235]];
let mut s = patches(32);
let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(as_8bit).collect();
for ((g, e), p) in got.iter().zip(expected).zip(PATCHES) {
assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() <= 2), "32-bit Dodge of {p:?}: got {g:?}, expected {e:?} (+-2); all: {got:?}");
}
}
#[test]
fn dodge_keeps_8_and_16_bit_results() {
// Pinned from main 406ac677e1: this change only adds the 32-bit path.
let mut s = patches(8);
let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 255.0).round() as u16)).collect();
assert_eq!(got, [[46, 46, 46], [161, 161, 161], [228, 228, 228], [255, 65, 65], [242, 187, 154], [191, 212, 244]]);
let mut s = patches(16);
let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 65535.0).round() as u16)).collect();
assert_eq!(got, [[11825, 11825, 11825], [41392, 41392, 41392], [58654, 58654, 58654], [65535, 16658, 16658], [62104, 47989, 39521], [49139, 54599, 62789]]);
}
/// Fill the first patch with light above white (4.0, 1.5, 0.2, linear).
fn above_white(s: &mut Session) {
s.edit("bright", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let r = photocraft_geom::Rect::new(0, 0, SIDE, SIDE);
let px = photocraft_raster::from_rgba(&surf.format(), [4.0, 1.5, 0.2, 1.0]);
surf.write_region(r, &px.repeat((SIDE * SIDE) as usize));
Ok(())
})
.unwrap();
}
#[test]
fn dodge_keeps_light_above_white_in_32_bit() {
let mut s = patches(32);
above_white(&mut s);
let c = dodge_each(&mut s, json!({}))[0];
assert_eq!([c[0], c[1]], [4.0, 1.5], "light above white must stay as it was: {c:?}");
assert!(c[2] > 0.2, "the in-range channel is still dodged: {c:?}");
}
#[test]
fn dodge_keeps_todays_curve_at_unmeasured_exposures_in_32_bit() {
// Only 50 % was measured in 32-bit; other exposures keep the gamma curve with Protect Tones'
// luma scaling, run on the stored values.
for exposure in [25, 100] {
let mut s = patches(32);
let before: Vec<_> = (0..PATCHES.len() as i32).map(|i| rgb(&s, i * SIDE + SIDE / 2, SIDE / 2)).collect();
let got = dodge_each(&mut s, json!({"exposure": exposure}));
for (g, o) in got.iter().zip(before) {
let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, true);
assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {g:?}, today's curve gives {e:?}");
}
}
}
#[test]
fn dodge_keeps_light_above_white_with_unmeasured_settings_in_32_bit() {
// The settings that keep today's curve must not clip light above white either.
for extra in [json!({"exposure": 100}), json!({"range": "shadows"}), json!({"range": "highlights"}), json!({"protectTones": false})] {
let mut s = patches(32);
above_white(&mut s);
let c = dodge_each(&mut s, extra.clone())[0];
assert!(c[0] >= 4.0 && c[1] >= 1.5, "Dodge with {extra} clipped light above white: {c:?}");
}
let mut s = crate::session();
s.execute("file.new", json!({"width": SIDE, "height": SIDE, "depth": 32, "mode": "gray"})).unwrap();
s.edit("bright", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let px = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]);
surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize));
Ok(())
})
.unwrap();
let before = rgb(&s, SIDE / 2, SIDE / 2)[0];
assert!(before > 1.0, "{before}");
s.execute("paint.dodge", json!({"points": [[SIDE / 2, SIDE / 2]], "size": 40, "hardness": 100})).unwrap();
let after = rgb(&s, SIDE / 2, SIDE / 2)[0];
assert!(after >= before, "32-bit Grayscale Dodge clipped {before} to {after}");
}
#[test]
fn dodge_keeps_light_above_white_when_luma_is_not_positive_in_32_bit() {
// A channel above white next to a negative one: luma <= 0, so Protect Tones can't scale the
// colour by luma. It takes the per-channel curve instead and keeps the light above white.
for exposure in [25, 100] {
for o in [[1.2f32, -0.7, 0.2], [1.01, -0.52, 0.02]] {
let mut s = patches(32);
s.edit("bright", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let px = photocraft_raster::from_rgba(&surf.format(), [o[0], o[1], o[2], 1.0]);
surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize));
Ok(())
})
.unwrap();
assert_eq!(rgb(&s, SIDE / 2, SIDE / 2), o);
let c = dodge_each(&mut s, json!({"exposure": exposure}))[0];
assert!(c[0] >= o[0], "{exposure} % Dodge of {o:?} clipped light above white: {c:?}");
let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, false);
assert!(c.iter().zip(e).all(|(c, e)| (c - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {c:?}, the per-channel curve gives {e:?}");
}
}
}
#[test]
fn dodge_keeps_tones_in_order_in_32_bit() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 256, "height": 8, "depth": 32, "mode": "rgb"})).unwrap();
s.edit("ramp", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let fmt = surf.format();
let data: Vec<f32> = (0..8).flat_map(|_| (0..256).flat_map(|x| photocraft_raster::from_rgba(&fmt, [x as f32 / 255.0; 4]))).collect();
surf.write_region(photocraft_geom::Rect::new(0, 0, 256, 8), &data);
Ok(())
})
.unwrap();
s.execute("paint.dodge", json!({"points": [[-20, 4], [276, 4]], "size": 40, "hardness": 100})).unwrap();
let row: Vec<f32> = (0..256).map(|x| rgb(&s, x, 4)[0]).collect();
assert!(row.windows(2).all(|w| w[1] >= w[0]), "{row:?}");
assert!(row.iter().all(|v| (0.0..=1.0).contains(v)) && row[0] == 0.0 && row[255] == 1.0, "{row:?}");
}
@@ -494,11 +494,12 @@ fn painting_a_group_is_refused_at_the_press_with_a_message() {
let seen = errors(&app).len();
app.ui.tool = tool;
tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, M);
// Brush, Classic gradient and Magic Eraser use the measured alerts (#11898, #12017, #12020).
// Brush, Classic gradient, Magic Eraser and Paint Bucket use the measured alerts (#11898, #12017, #12020, #12537).
let want = match tool {
Tool::Brush => "Could not use the brush tool because the pixels in a group cannot be edited without merging the group.".to_string(),
Tool::MagicEraser => "Could not use the magic eraser because the pixels in a group cannot be edited without merging the group.".to_string(),
Tool::Gradient => "Could not use the gradient tool because the pixels in a group cannot be edited without merging the group.".to_string(),
Tool::PaintBucket => "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group.".to_string(),
_ => format!("Could not use the {} because the target layer is a group.", tool.label()),
};
assert_eq!(errors(&app)[seen..], [want], "{tool:?}");
@@ -0,0 +1,339 @@
//! #14489: Image › Apply Image's Mask... checkbox and its group (Source, Layer, Channel, Invert).
//!
//! The five documents of the issue, opened in its order: "other" (RGB 8 bit, 300 x 200), "gray" (Grayscale 8 bit,
//! 400 x 300, left half black, right half white), "rgb16" (RGB 16 bit, 400 x 300), "source" (RGB 8 bit, 400 x 300,
//! Background 128 plus a layer "S1" white on the right half) and "target" (RGB 8 bit, 400 x 300; Background left half
//! 200/100/50, right half 50/150/250; layers "Top" and "Masked"; alpha channel "Alpha 1" white over (0,0)-(200,150)).
//! "target" is active, its Background targeted.
use super::params_for;
/// The dialog's row keys (shell keys: `__` keys never reach the command).
const MASK_ON: &str = "__mask";
const MASK_SOURCE: &str = "__maskSource";
const MASK_INVERT: &str = "__maskInvert";
fn mask_layer_key(index: usize) -> String {
format!("__maskLayer/{index}")
}
fn mask_channel_key(index: usize) -> String {
format!("__maskChannel/{index}")
}
use crate::PhotocraftApp;
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::ParamKind;
use serde_json::{Value, json};
const APPLY: &str = "image.applyImage";
fn run(app: &mut PhotocraftApp, id: &str, params: Value) {
app.run(id, params).unwrap_or_else(|e| panic!("{id}: {e}"));
}
/// Fills the rectangle `x, y, w, h` of the active layer with `color`.
fn fill(app: &mut PhotocraftApp, rect: [u32; 4], color: &str) {
run(app, "select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]}));
run(app, "edit.fill", json!({"color": color}));
run(app, "select.deselect", json!({}));
}
fn five_documents() -> (Box<PhotocraftApp>, egui::Context) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
run(&mut app, "file.new", json!({"width": 300, "height": 200, "name": "other"}));
run(&mut app, "file.new", json!({"width": 400, "height": 300, "mode": "gray", "background": "#000000", "name": "gray"}));
fill(&mut app, [200, 0, 200, 300], "#ffffff");
run(&mut app, "file.new", json!({"width": 400, "height": 300, "depth": 16, "background": "#404040", "name": "rgb16"}));
run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#808080", "name": "source"}));
run(&mut app, "layer.new.layer", json!({"name": "S1"}));
fill(&mut app, [200, 0, 200, 300], "#ffffff");
run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "target"}));
fill(&mut app, [200, 0, 200, 300], "#3296fa");
run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150}));
run(&mut app, "select.saveSelection", json!({"name": "Alpha 1"}));
run(&mut app, "select.deselect", json!({}));
run(&mut app, "layer.new.layer", json!({"name": "Top"}));
run(&mut app, "layer.new.layer", json!({"name": "Masked"}));
run(&mut app, "layer.select", json!({"name": "Background"}));
app.sync_views();
let ctx = app.ctx().clone();
(app, ctx)
}
fn frame(app: &mut PhotocraftApp, ctx: &egui::Context) {
let mut output = ctx.run_ui(Default::default(), |ui| {
let mut frame = eframe::Frame::_new_kittest();
app.logic_frame(ui.ctx(), &mut frame);
app.ui_frame(ui, &mut frame);
});
output.textures_delta.clear();
}
fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> DialogId {
let reply = crate::menus::invoke(app, ctx, APPLY, json!({})).unwrap();
let want = reply["dialog"].as_str().expect("the reply names a dialog").to_owned();
let id = app.framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|id| id.value().to_string() == want).expect("the dialog is open");
frame(app, ctx);
id
}
fn fields(app: &PhotocraftApp, id: DialogId) -> Value {
app.framework.dialogs.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields).expect("an open dialog")
}
fn set(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId, key: &str, value: Value) {
app.framework.dialogs.set_json_field(ctx, id, key, value).unwrap_or_else(|e| panic!("{key}: {e}"));
// The form brings its derived keys up to date at its next pass.
frame(app, ctx);
}
/// The `(id, label)` options of choice row `key`.
fn options(app: &mut PhotocraftApp, key: &str) -> Vec<(String, String)> {
let (params, _) = params_for(app, APPLY).expect("Apply Image has a form");
match &params.iter().find(|p| p.key == key).unwrap_or_else(|| panic!("no row {key}")).kind {
ParamKind::Choice { options, .. } => options.iter().map(|(id, label)| (id.clone(), label.as_str().to_owned())).collect(),
other => panic!("{key} is not a choice: {other:?}"),
}
}
fn ids(app: &mut PhotocraftApp, key: &str) -> Vec<String> {
options(app, key).into_iter().map(|(id, _)| id).collect()
}
fn index_of(app: &PhotocraftApp, name: &str) -> usize {
app.session.documents().iter().position(|st| st.doc.name == name).unwrap_or_else(|| panic!("no document {name}"))
}
/// The active layer's 8-bit RGB at `(x, y)`.
fn rgb(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] {
let st = app.session.active().unwrap();
let p = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y);
[0, 1, 2].map(|c| (p[c] * 255.0).round() as u8)
}
#[test]
fn mask_is_off_by_default_and_sends_no_mask() {
let (mut app, ctx) = five_documents();
let d = open(&mut app, &ctx);
let shown = fields(&app, d);
assert_eq!(shown[MASK_ON], false);
for key in ["maskDocument", "maskLayer", "maskChannel", "maskInvert"] {
assert!(shown.get(key).is_none(), "{key} is sent with Mask off: {shown}");
}
// Ticked, then unticked again: no mask either.
set(&mut app, &ctx, d, MASK_ON, json!(true));
assert!(fields(&app, d).get("maskChannel").is_some());
set(&mut app, &ctx, d, MASK_ON, json!(false));
assert!(fields(&app, d).get("maskChannel").is_none());
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
// The whole layer is the inverted target.
assert_eq!(rgb(&app, 50, 50), [55, 155, 205]);
assert_eq!(rgb(&app, 300, 50), [205, 105, 5]);
}
#[test]
fn mask_source_lists_same_size_and_depth_documents_in_open_order() {
let (mut app, ctx) = five_documents();
let names: Vec<String> = options(&mut app, MASK_SOURCE).into_iter().map(|(_, name)| name).collect();
assert_eq!(names, ["gray", "source", "target"]);
let d = open(&mut app, &ctx);
assert_eq!(fields(&app, d)[MASK_SOURCE], index_of(&app, "gray").to_string(), "the first document of the list");
}
#[test]
fn mask_layer_follows_the_mask_source() {
let (mut app, _) = five_documents();
let (gray, source, target) = (index_of(&app, "gray"), index_of(&app, "source"), index_of(&app, "target"));
assert_eq!(ids(&mut app, &mask_layer_key(gray)), ["Background"]);
assert_eq!(ids(&mut app, &mask_layer_key(source)), ["merged", "S1", "Background"]);
assert_eq!(ids(&mut app, &mask_layer_key(target)), ["merged", "Masked", "Top", "Background"]);
let (params, _) = params_for(&mut app, APPLY).unwrap();
let default = |key: &str| match &params.iter().find(|p| p.key == key).unwrap().kind {
ParamKind::Choice { default, .. } => default.clone(),
_ => None,
};
assert_eq!(default(&mask_layer_key(gray)).as_deref(), Some("Background"));
assert_eq!(default(&mask_layer_key(target)).as_deref(), Some("merged"));
// Documents of another size or bit depth have no rows.
let rgb16 = index_of(&app, "rgb16");
assert!(params.iter().all(|p| p.key != mask_layer_key(rgb16)));
}
#[test]
fn mask_channel_lists_gray_the_colours_and_the_alpha_channels() {
let (mut app, _) = five_documents();
let (gray, target) = (index_of(&app, "gray"), index_of(&app, "target"));
let labels = |list: Vec<(String, String)>| list.into_iter().map(|(_, label)| label).collect::<Vec<_>>();
assert_eq!(labels(options(&mut app, &mask_channel_key(gray))), ["Gray"]);
assert_eq!(labels(options(&mut app, &mask_channel_key(target))), ["Gray", "Red", "Green", "Blue", "Alpha 1"]);
// The composite keeps the engine's id; the engine reads a mask composite as luminosity.
assert_eq!(ids(&mut app, &mask_channel_key(target))[0], "RGB");
}
#[test]
fn ok_applies_through_the_chosen_mask_and_its_invert() {
let (mut app, ctx) = five_documents();
let target = index_of(&app, "target");
for (invert, at_50, at_300) in [(false, [55, 155, 205], [50, 150, 250]), (true, [200, 100, 50], [205, 105, 5])] {
let d = open(&mut app, &ctx);
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
set(&mut app, &ctx, d, MASK_ON, json!(true));
set(&mut app, &ctx, d, MASK_SOURCE, json!(target.to_string()));
set(&mut app, &ctx, d, &mask_channel_key(target), json!("Alpha 1"));
set(&mut app, &ctx, d, MASK_INVERT, json!(invert));
let sent = fields(&app, d);
assert_eq!(sent["maskDocument"], target);
assert_eq!(sent["maskLayer"], "merged");
assert_eq!(sent["maskChannel"], "Alpha 1");
// Invert is recorded only when it is on.
assert_eq!(sent.get("maskInvert").cloned(), invert.then_some(json!(true)));
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
assert_eq!(rgb(&app, 50, 50), at_50, "invert {invert}");
assert_eq!(rgb(&app, 300, 50), at_300, "invert {invert}");
run(&mut app, "edit.undo", json!({}));
}
}
#[test]
fn a_mask_from_another_document() {
let (mut app, ctx) = five_documents();
let gray = index_of(&app, "gray");
let d = open(&mut app, &ctx);
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
set(&mut app, &ctx, d, MASK_ON, json!(true));
assert_eq!(fields(&app, d)["maskDocument"], gray);
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
// "gray" is black on the left, white on the right.
assert_eq!(rgb(&app, 50, 50), [200, 100, 50]);
assert_eq!(rgb(&app, 300, 50), [205, 105, 5]);
run(&mut app, "edit.undo", json!({}));
// OK right after an edit, with no pass in between, sends the edited mask.
let d = open(&mut app, &ctx);
app.framework.dialogs.set_json_field(&ctx, d, MASK_INVERT, json!(true)).unwrap();
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
assert_eq!(rgb(&app, 50, 50), [55, 155, 205]);
assert_eq!(rgb(&app, 300, 50), [50, 150, 250]);
}
/// "clash" (RGB 8 bit, 400 x 300, Background 200/100/50): an alpha channel named "Red" white on the left half, and a
/// pixel layer named "merged" white on the right half above the Background, which is targeted.
fn names_like_the_built_in_choices() -> (Box<PhotocraftApp>, egui::Context, usize) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "clash"}));
run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300}));
run(&mut app, "select.saveSelection", json!({"name": "Red"}));
run(&mut app, "select.deselect", json!({}));
run(&mut app, "layer.new.layer", json!({"name": "merged"}));
fill(&mut app, [200, 0, 200, 300], "#ffffff");
run(&mut app, "layer.select", json!({"name": "Background"}));
app.sync_views();
let ctx = app.ctx().clone();
let clash = index_of(&app, "clash");
(app, ctx, clash)
}
/// The option id of row `key` at `position` of its list, after checking the list's labels and that no two options
/// share an id.
fn option_at(app: &mut PhotocraftApp, key: &str, labels: &[&str], position: usize) -> String {
let list = options(app, key);
assert_eq!(list.iter().map(|(_, label)| label.as_str()).collect::<Vec<_>>(), labels, "{key}");
let mut unique: Vec<&String> = list.iter().map(|(id, _)| id).collect();
unique.sort();
unique.dedup();
assert_eq!(unique.len(), list.len(), "{key} options share an id: {list:?}");
list[position].0.clone()
}
#[test]
fn a_mask_alpha_named_like_a_colour_channel_reads_the_alpha() {
let (mut app, ctx, clash) = names_like_the_built_in_choices();
let alpha = option_at(&mut app, &mask_channel_key(clash), &["Gray", "Red", "Green", "Blue", "Red"], 4);
let d = open(&mut app, &ctx);
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
set(&mut app, &ctx, d, MASK_ON, json!(true));
set(&mut app, &ctx, d, MASK_SOURCE, json!(clash.to_string()));
set(&mut app, &ctx, d, &mask_channel_key(clash), json!(alpha));
assert_eq!(fields(&app, d)["maskChannel"], json!({"alpha": 0}), "an explicit alpha selector");
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
// The alpha masks the left half in and the right half out; the red plane (200 everywhere) would mix both.
assert_eq!(rgb(&app, 50, 50), [55, 155, 205]);
assert_eq!(rgb(&app, 300, 50), [200, 100, 50]);
}
#[test]
fn a_mask_layer_named_merged_is_that_layer_not_the_composite() {
let (mut app, ctx, clash) = names_like_the_built_in_choices();
let layer = option_at(&mut app, &mask_layer_key(clash), &["Merged", "merged", "Background"], 1);
let d = open(&mut app, &ctx);
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
set(&mut app, &ctx, d, MASK_ON, json!(true));
set(&mut app, &ctx, d, MASK_SOURCE, json!(clash.to_string()));
set(&mut app, &ctx, d, &mask_layer_key(clash), json!(layer));
assert_eq!(fields(&app, d)["maskLayer"], json!({"name": "merged"}), "an explicit layer name selector");
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
let through_dialog = [rgb(&app, 50, 50), rgb(&app, 300, 50)];
run(&mut app, "edit.undo", json!({}));
// The same as the command with the layer named explicitly, and not the result of the composite as mask.
let mask = |layer: Value| json!({"sourceInvert": true, "blending": "normal", "mask": {"document": clash, "layer": layer, "channel": "RGB"}});
run(&mut app, APPLY, mask(json!({"name": "merged"})));
assert_eq!([rgb(&app, 50, 50), rgb(&app, 300, 50)], through_dialog);
run(&mut app, "edit.undo", json!({}));
run(&mut app, APPLY, mask(json!("merged")));
assert_ne!([rgb(&app, 50, 50), rgb(&app, 300, 50)], through_dialog, "the composite masks differently");
}
/// "sentinels" (RGB 8 bit, 400 x 300, Background 200/100/50, targeted): an alpha channel named "none" white on the left
/// half, and an alpha channel with no name white on the right half. The engine reads a mask channel "none" as no mask
/// and drops an empty one.
fn alphas_named_like_no_mask() -> (Box<PhotocraftApp>, egui::Context, usize) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "sentinels"}));
run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300}));
run(&mut app, "select.saveSelection", json!({"name": "none"}));
run(&mut app, "select.rect", json!({"x": 200, "y": 0, "width": 200, "height": 300}));
run(&mut app, "select.saveSelection", json!({"name": "unnamed"}));
run(&mut app, "select.deselect", json!({}));
// The commands refuse an empty name; a file can still bring one.
std::sync::Arc::make_mut(app.session.active_mut().unwrap().doc_mut()).channels[1].name = String::new();
app.sync_views();
let ctx = app.ctx().clone();
let doc = index_of(&app, "sentinels");
(app, ctx, doc)
}
/// Applies the inverted target with Normal through the mask alpha at `position` of the Channel list of "sentinels",
/// checking the selector the dialog sends.
fn apply_through_mask_alpha(position: usize, selector: Value) -> PhotocraftApp {
let (mut app, ctx, doc) = alphas_named_like_no_mask();
let alpha = option_at(&mut app, &mask_channel_key(doc), &["Gray", "Red", "Green", "Blue", "none", ""], position);
let d = open(&mut app, &ctx);
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
set(&mut app, &ctx, d, MASK_ON, json!(true));
set(&mut app, &ctx, d, MASK_SOURCE, json!(doc.to_string()));
set(&mut app, &ctx, d, &mask_channel_key(doc), json!(alpha));
assert_eq!(fields(&app, d)["maskChannel"], selector, "an explicit alpha selector");
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
*app
}
#[test]
fn a_mask_alpha_named_none_masks() {
let app = apply_through_mask_alpha(4, json!({"alpha": 0}));
// Only the left half, where the alpha is white, takes the inverted target; without a mask both halves would.
assert_eq!(rgb(&app, 50, 50), [55, 155, 205]);
assert_eq!(rgb(&app, 300, 50), [200, 100, 50]);
}
#[test]
fn a_mask_alpha_with_no_name_masks() {
let app = apply_through_mask_alpha(5, json!({"alpha": 1}));
assert_eq!(rgb(&app, 50, 50), [200, 100, 50]);
assert_eq!(rgb(&app, 300, 50), [55, 155, 205]);
}
+11 -2
View File
@@ -318,6 +318,12 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec<
let kind = if command == "layer.layerStyle.globalLight" { ParamKind::angle_in(min, max, default, 0) } else { ParamKind::angle(default) };
p = Param::new(p.key, p.label, kind);
}
// Artboard from Layers' Width and Height take 4 to 32000 px; a value typed outside is
// clamped when the field is left (#14577).
if command == "layer.new.artboardFromLayers" && matches!(p.key.as_str(), "width" | "height") {
use photocraft_engine::artboard_cmds::{FROM_LAYERS_MAX, FROM_LAYERS_MIN};
p = Param::new(p.key, p.label, ParamKind::int(Some(FROM_LAYERS_MIN), Some(FROM_LAYERS_MAX), 0));
}
if command == SCALE_EFFECTS && p.key == "scale" {
return scale_effects_row(p);
}
@@ -458,12 +464,13 @@ fn command_defaults(app: &PhotocraftApp, command: &str, params: &[Param]) -> Map
map.insert("name".into(), json!(photocraft_engine::pattern_cmds::default_name(&app.session)));
}
// The reference application's Artboard from Layers opens at the next Artboard N and the
// selected layers' size every time, never a remembered size; past the field's 30000 px
// selected layers' size every time, never a remembered size; past the field's 32000 px
// range, 0 keeps the bounds.
if command == "layer.new.artboardFromLayers"
&& let Some((name, [w, h])) = photocraft_engine::artboard_cmds::from_layers_defaults(&app.session)
{
let fits = w <= 30_000 && h <= 30_000;
let max = photocraft_engine::artboard_cmds::FROM_LAYERS_MAX;
let fits = w <= max && h <= max;
map.insert("name".into(), json!(name));
map.insert("width".into(), json!(if fits { w } else { 0 }));
map.insert("height".into(), json!(if fits { h } else { 0 }));
@@ -1419,6 +1426,8 @@ pub struct FilterPreviewKey {
pub scratch: u64,
}
#[cfg(test)]
mod artboard_from_layers_size_range_tests;
#[cfg(test)]
mod global_light_angle_range_tests;
#[cfg(test)]
@@ -0,0 +1,93 @@
//! #14577: Artboard from Layers' Width and Height take 4 to 32000 px. A value typed outside is
//! clamped when the field is left (Tab): 99999 becomes 32000, 1 becomes 4.
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::{PhotocraftApp, Services};
const CMD: &str = "layer.new.artboardFromLayers";
/// A 100 x 80 document whose new layer holds 20 x 30 px of red, with the dialog open over it.
fn dialog() -> (Harness<'static, Box<PhotocraftApp>>, craft::ui::dialog::DialogId) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 5, "width": 20, "height": 30})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
app.run("select.deselect", json!({})).unwrap();
let id = super::open(&mut app, CMD).unwrap();
let mut h = Harness::builder()
.with_context(app.ctx().clone())
.with_size(egui::vec2(1200.0, 900.0))
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro());
h.run_steps(4);
(h, id)
}
fn int(h: &Harness<'static, Box<PhotocraftApp>>, id: craft::ui::dialog::DialogId, key: &str) -> Option<i64> {
h.state().framework.dialogs.get_by_id::<HostedParamDialog>(id).and_then(|d| d.fields().int(key))
}
/// The open alerts' messages.
fn alerts(h: &Harness<'static, Box<PhotocraftApp>>) -> Vec<String> {
h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect()
}
/// Types `text` into the number field labelled `name` and leaves it with Tab.
fn type_and_tab(h: &mut Harness<'static, Box<PhotocraftApp>>, name: &str, text: &str) {
h.query_all_by_role(Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref().is_some_and(|l| l.trim_end_matches(':') == name))
.unwrap_or_else(|| panic!("the {name} field"))
.click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(3);
}
#[test]
fn width_and_height_clamp_to_4_to_32000_when_the_field_is_left() {
// (field, key, typed, kept)
for (name, key, typed, kept) in [("Width", "width", "99999", 32_000), ("Height", "height", "1", 4), ("Width", "width", "640", 640)] {
let (mut h, id) = dialog();
assert_eq!((int(&h, id, "width"), int(&h, id, "height")), (Some(20), Some(30)), "opens at the layers' size");
type_and_tab(&mut h, name, typed);
assert_eq!(int(&h, id, key), Some(kept), "{name} {typed}");
// The framework's range alert says the closest value was kept; OK on it keeps the value.
if typed.parse::<i64>().ok() != Some(kept) {
let shown = alerts(&h);
assert!(shown.iter().any(|m| m.starts_with("An integer between 4 and ") && m.contains("Closest value inserted")), "{name} {typed}: {shown:?}");
}
}
}
/// A union of 30000 to 32000 px fits the field now, so the dialog opens at it.
#[test]
fn a_union_up_to_32000_px_opens_at_its_size() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
app.run("file.new", json!({"width": 31_000, "height": 8})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
let id = super::open(&mut app, CMD).unwrap();
let f = app.framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone();
assert_eq!((f.int("width"), f.int("height")), (Some(31_000), Some(8)));
}
#[test]
fn a_union_wider_than_32000_px_still_opens_at_0_to_keep_the_bounds() {
// Not measured in the reference: today's 0 x 0 ("keep the layers' bounds") stays, now past 32000 px.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
app.run("file.new", json!({"width": 33_000, "height": 8})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
let id = super::open(&mut app, CMD).unwrap();
let f = app.framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone();
assert_eq!((f.int("width"), f.int("height")), (Some(0), Some(0)));
}
+47 -2
View File
@@ -29,6 +29,7 @@ use craft::ui::primitives::ContentPainterCx;
use craft::ui::primitives::FacePaint;
use craft::ui::primitives::textures::TextureCache;
use craft::ui::runtime::env::Env;
use craft::ui::runtime::memory::{SaveKey, run_value, set_run_value};
use egui::{ColorImage, Pos2, Rect, pos2};
use photocraft_doc::effects::{FxPaint, GlowSource, GlowTechnique, StrokePosition};
use photocraft_doc::{Document, Effect, Layer, LayerId};
@@ -50,6 +51,8 @@ mod gradient_field;
#[cfg(test)]
mod gradient_method_tests;
#[cfg(test)]
mod outer_glow_last_values_tests;
#[cfg(test)]
mod pattern_overlay_picker_tests;
/// The Styles preset gallery page id.
@@ -204,6 +207,11 @@ fn values_of(e: &Effect, light: f32) -> Value {
if let Some(source) = interpolation {
set(&mut v, "method", json!(source.method));
set(&mut v, "smoothness", json!(source.smoothness));
} else {
// No recorded method (a baked PSD curve): the factory Smooth (#14900) must not
// rebuild it on an unchanged OK, so the page shows its stops as they are.
set(&mut v, "method", json!("custom"));
drop_keys(&mut v, &["smoothness"]);
}
let (stops, opacity) = gradient_field::stops_to_json(&gradient_field::stops_of_doc(stops, &g.opacity_stops));
set(&mut v, gradient_field::KEY, stops);
@@ -494,6 +502,11 @@ pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option<DialogId> {
let keys = blend_keys();
let mut specs = specs(&keys, &user, light);
start_from_last_committed(app, &mut specs, light);
if let Some(spec) = specs.iter_mut().find(|spec| spec.kind == EffectKind::OuterGlow)
&& let Some(values) = run_value::<Option<Value>>(app.ctx(), &OUTER_GLOW_SESSION)
{
spec.defaults = style_params(spec.kind, &values, None).over(&spec.defaults);
}
let mut draft = LayerStyleDraft::new(draft_of(&layer, light, mode));
match select {
None => {
@@ -584,7 +597,29 @@ fn keep_last_committed(app: &PhotocraftApp, style: &LayerStyle) {
}
}
/// The starting values of a new Outer Glow live only in this app session (#14945).
const OUTER_GLOW_SESSION: SaveKey = SaveKey::new("photocraft.layerStyle.outerGlow.session");
/// Remember the last enabled glow added or edited by this confirmation, in the units shown by
/// the page. The original snapshot distinguishes an edit from an unchanged layer effect.
fn keep_outer_glow(app: &PhotocraftApp, layer: LayerId, style: &LayerStyle) {
let Some(layer) = app.session.active().and_then(|state| state.doc.layer(layer)) else { return };
let light = style.global_light;
let last = style.effects.iter().zip(&layer.effects.items).rev().find_map(|(draft, applied)| {
if draft.kind != EffectKind::OuterGlow || !applied.enabled() {
return None;
}
let values = values_of(applied, light);
let original = fx_of(&draft.params).and_then(|fx| serde_json::from_value::<Effect>(fx).ok());
original.is_none_or(|original| !original.enabled() || values_of(&original, light) != values).then_some(values)
});
if let Some(values) = last {
set_run_value(app.ctx(), &OUTER_GLOW_SESSION, Some(values));
}
}
/// The effect pages with the user's defaults (Make Default) over the factory ones.
/// Outer Glow starts at factory values after a restart; Reset still uses the saved default.
fn specs(keys: &HashMap<String, String>, user: &Map<String, Value>, light: f32) -> Vec<EffectSpec> {
KINDS
.iter()
@@ -601,7 +636,8 @@ fn specs(keys: &HashMap<String, String>, user: &Map<String, Value>, light: f32)
spec.fields.insert(after + 1, field);
}
}
spec.defaults = style_params(kind, &fresh_params(key, light, user.get(*key)), None).over(&spec.defaults);
let saved = if kind == EffectKind::OuterGlow { None } else { user.get(*key) };
spec.defaults = style_params(kind, &fresh_params(key, light, saved), None).over(&spec.defaults);
Some(spec)
})
.collect()
@@ -978,8 +1014,12 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
LayerStyleAsk::NewStyle => save_new_style(app, id, layer),
LayerStyleAsk::MakeDefault(kind, params) => {
// The stored defaults reach new instances from the next open and, through `set_defaults`, the open dialog.
match app.run("layer.layerStyle.makeDefault", json!({"kind": kind.key(), "params": style_params_json(&params)})) {
let values = style_params_json(&params);
match app.run("layer.layerStyle.makeDefault", json!({"kind": kind.key(), "params": values})) {
Ok(_) => {
if kind == EffectKind::OuterGlow {
set_run_value(app.ctx(), &OUTER_GLOW_SESSION, Some(values));
}
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedLayerStyle>(id) {
dialog.set_defaults(kind, params);
}
@@ -1006,6 +1046,7 @@ fn finish(app: &mut PhotocraftApp, doc: photocraft_doc::DocId, layer: LayerId, s
return fail(app, error);
}
keep_last_committed(app, style);
keep_outer_glow(app, layer, style);
}
/// Applies a style preset to the draft without touching the document: Cancel leaves the document
@@ -1056,6 +1097,10 @@ fn reset_to_default(app: &mut PhotocraftApp, dialog: DialogId, instance: EffectI
};
let Ok(v) = app.run("layer.layerStyle.defaultFor", json!({"kind": kind.key()})) else { return };
let mut values = v["params"].clone();
if kind == EffectKind::OuterGlow {
// A partial saved default should clear every field seeded from the last OK.
values = with_defaults(kind.key(), &values);
}
drop_from_to(&mut values);
if values.get("useGlobalLight").and_then(Value::as_bool) == Some(true)
&& let Some(o) = values.as_object_mut()
@@ -0,0 +1,170 @@
//! #14945: a new Outer Glow uses the last settings confirmed in Layer Style for this app session.
use craft::imaging::layer_style::{EffectKind, StyleValue};
use craft::theme::Srgba;
use egui_kittest::kittest::Queryable as _;
use photocraft_engine::prefs::SavedPrefsExt;
use serde_json::{Value, json};
use super::tests::{app_with_layer, cancel, draft, edit, first_of, harness};
use super::{DialogId, style_params_json};
use crate::PhotocraftApp;
const COMMAND: &str = "layer.layerStyle.outerGlow";
fn open_glow(app: &mut PhotocraftApp) -> DialogId {
let ctx = app.ctx().clone();
crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap();
app.layer_style_target.unwrap().0
}
fn values(app: &PhotocraftApp, id: DialogId) -> Value {
let glow = first_of(app, id, EffectKind::OuterGlow);
style_params_json(&draft(app, id).style.effect(glow).unwrap().params)
}
fn set_glow(app: &mut PhotocraftApp, id: DialogId, opacity: f64) {
let glow = first_of(app, id, EffectKind::OuterGlow);
edit(app, id, |draft| {
draft.set_param(glow, "blend", StyleValue::Text("Normal".into()));
draft.set_param(glow, "color", StyleValue::Color(Srgba::from_rgb_array([0.0; 3])));
draft.set_param(glow, "opacity", StyleValue::Number(opacity));
draft.set_param(glow, "size", StyleValue::Number(10.0));
});
}
fn confirm(app: &mut PhotocraftApp, id: DialogId) {
crate::dialogs::testing::confirm(app, id).unwrap();
assert!(!app.ui.status_error, "{}", app.ui.status);
}
fn other_document(app: &mut PhotocraftApp) {
app.run("file.new", json!({"width": 40, "height": 32})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
}
fn remember_glow(app: &mut PhotocraftApp) -> Value {
let id = open_glow(app);
set_glow(app, id, 100.0);
let remembered = values(app, id);
confirm(app, id);
other_document(app);
remembered
}
#[test]
fn a_new_outer_glow_reuses_the_confirmed_values_on_another_document() {
let mut app = app_with_layer(32);
let remembered = remember_glow(&mut app);
let id = open_glow(&mut app);
assert_eq!(values(&app, id), remembered);
confirm(&mut app, id);
let id = open_glow(&mut app);
assert_eq!(values(&app, id), remembered, "the seeded glow applies to the layer");
}
#[test]
fn cancelled_edits_and_an_unchanged_scripted_glow_leave_the_last_ok_alone() {
let mut app = app_with_layer(32);
let remembered = remember_glow(&mut app);
let pending = open_glow(&mut app);
set_glow(&mut app, pending, 40.0);
cancel(&mut app, pending);
app.run(COMMAND, json!({"blend": "Screen", "color": "#0000ff", "size": 21, "opacity": 60})).unwrap();
let scripted = open_glow(&mut app);
assert_eq!(values(&app, scripted)["color"], "#0000ff", "the existing layer effect supplies its own values");
confirm(&mut app, scripted);
other_document(&mut app);
let next = open_glow(&mut app);
assert_eq!(values(&app, next), remembered);
}
#[test]
fn editing_an_existing_outer_glow_updates_the_next_new_glow() {
let mut app = app_with_layer(32);
remember_glow(&mut app);
app.run(COMMAND, json!({"size": 21})).unwrap();
let id = open_glow(&mut app);
set_glow(&mut app, id, 50.0);
let edited = values(&app, id);
confirm(&mut app, id);
other_document(&mut app);
let next = open_glow(&mut app);
assert_eq!(values(&app, next), edited);
}
#[test]
fn reset_uses_factory_or_user_defaults_and_a_fresh_app_starts_at_factory() {
let mut app = app_with_layer(32);
let initial = open_glow(&mut app);
let factory = values(&app, initial);
cancel(&mut app, initial);
remember_glow(&mut app);
let id = open_glow(&mut app);
let mut h = harness(app);
h.get_by_label("Reset to Default").click();
h.run_steps(3);
assert_eq!(values(h.state(), id), factory);
let saved_default = json!({"kind": "outerGlow", "params": {"opacity": 18.0}});
h.state_mut().run("layer.layerStyle.makeDefault", saved_default).unwrap();
// Reset must replace every remembered field, even when the saved default is partial.
cancel(h.state_mut(), id);
let id = open_glow(h.state_mut());
h.run_steps(3);
h.get_by_label("Reset to Default").click();
h.run_steps(3);
let mut user = factory.clone();
user["opacity"] = json!(18.0);
assert_eq!(values(h.state(), id), user);
// A fresh app opens at factory values even with an existing Make Default entry.
let saved = h.state().session.prefs_to_json();
let mut restarted = app_with_layer(32);
restarted.session.load_prefs_json(&saved).unwrap();
let id = open_glow(&mut restarted);
assert_eq!(values(&restarted, id), factory);
let mut h = harness(restarted);
h.get_by_label("Reset to Default").click();
h.run_steps(3);
assert_eq!(values(h.state(), id), user);
}
#[test]
fn make_default_in_the_current_session_seeds_new_glows() {
let mut app = app_with_layer(32);
remember_glow(&mut app);
let id = open_glow(&mut app);
set_glow(&mut app, id, 60.0);
let user = values(&app, id);
let mut h = harness(app);
h.get_by_label("Make Default").click();
h.run_steps(3);
cancel(h.state_mut(), id);
let next = open_glow(h.state_mut());
assert_eq!(values(h.state(), next), user);
}
#[test]
fn disabled_or_refused_glows_do_not_replace_the_last_ok() {
let mut app = app_with_layer(32);
let remembered = remember_glow(&mut app);
let disabled = open_glow(&mut app);
set_glow(&mut app, disabled, 70.0);
let glow = first_of(&app, disabled, EffectKind::OuterGlow);
edit(&mut app, disabled, |draft| draft.toggle(glow));
confirm(&mut app, disabled);
other_document(&mut app);
let refused = open_glow(&mut app);
set_glow(&mut app, refused, 80.0);
let glow = first_of(&app, refused, EffectKind::OuterGlow);
edit(&mut app, refused, |draft| draft.set_param(glow, "fx", StyleValue::Other("{}".into())));
crate::dialogs::testing::confirm(&mut app, refused).unwrap();
assert!(app.ui.status_error);
let next = open_glow(&mut app);
assert_eq!(values(&app, next), remembered);
}
+3 -3
View File
@@ -82,11 +82,11 @@ fn painting_a_hidden_layer_is_refused_at_the_press() {
let n = steps(&app);
tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);
assert!(!crate::canvas::testing::in_gesture(&app) && app.live_stroke.is_none(), "{tool:?}: no stroke started");
// The Brush (#11898) and the Classic gradient (#12017) say so in an alert, the other tools
// in the status bar.
// The Brush (#11898), the Classic gradient (#12017) and the Paint Bucket (#12537) say so in
// an alert, the other tools in the status bar.
let alerts = alerts(&app);
let alert = alerts.iter().any(|m| m.contains("target layer is hidden"));
if matches!(tool, Tool::Brush | Tool::Gradient) {
if matches!(tool, Tool::Brush | Tool::Gradient | Tool::PaintBucket) {
assert!(alert, "{tool:?}: {alerts:?}");
} else {
assert!(app.ui.status.contains("target layer is hidden") && alerts.is_empty(), "{tool:?}: {}", app.ui.status);
+184 -5
View File
@@ -85,6 +85,9 @@ fn derive(id: &str, fields: &mut DialogFields) {
if id == artboard_name_options::COMMAND {
artboard_name_options::derive(fields);
}
if id == "image.applyImage" {
apply_image_mask_derive(fields);
}
}
/// Choice options from `(id, label)` pairs whose labels are `tl!` literals at the call site.
@@ -638,8 +641,6 @@ fn channel_form(app: &PhotocraftApp, id: &str) -> Option<(Vec<Param>, DialogFiel
]
}
"image.applyImage" => {
let mut masks = vec!["none".to_string()];
masks.extend(load.iter().cloned());
// Source layer: Merged, then the pixel layers top to bottom (the engine takes
// the topmost layer of a name), shown by their own names.
let mut layers = vec!["merged".to_string()];
@@ -649,7 +650,7 @@ fn channel_form(app: &PhotocraftApp, id: &str) -> Option<(Vec<Param>, DialogFiel
}
}
// Scale and Offset only affect Add and Subtract.
vec![
let mut rows = vec![
choice("sourceLayer", tl!("Layer"), channels(&layers), "merged"),
choice("sourceChannel", tl!("Source Channel"), channels(&load), &chans[0]),
Param::new("sourceInvert", tl!("Invert"), ParamKind::bool(false)),
@@ -658,8 +659,9 @@ fn channel_form(app: &PhotocraftApp, id: &str) -> Option<(Vec<Param>, DialogFiel
Param::new("scale", tl!("Scale"), ParamKind::number(Some(0.001), Some(2.0), 1.0, 0.1, 3)),
Param::new("offset", tl!("Offset"), ParamKind::int(Some(-255), Some(255), 0)),
Param::new("preserveTransparency", tl!("Preserve Transparency"), ParamKind::bool(false)),
choice("maskChannel", tl!("Mask Channel"), channels(&masks), "none"),
]
];
rows.extend(apply_image_mask_rows(app));
rows
}
"image.calculations" => {
// Image ▸ Calculations lists the channels of the source it reads (#14521), not the shared
@@ -693,6 +695,183 @@ fn channel_form(app: &PhotocraftApp, id: &str) -> Option<(Vec<Param>, DialogFiel
Some((rows, DialogFields::new()))
}
/// Apply Image's Mask... checkbox (#14489): off by default; ticked, it shows the mask group below it.
const MASK_ON: &str = "__mask";
/// The mask group's Source: the index of one of [`apply_image_documents`].
const MASK_SOURCE: &str = "__maskSource";
/// The mask group's Invert.
const MASK_INVERT: &str = "__maskInvert";
/// The mask Layer row of the source document `index`: each candidate document has its own Layer and Channel rows,
/// as their lists are that document's, and only the chosen document's pair is shown.
fn mask_layer_key(index: usize) -> String {
format!("__maskLayer/{index}")
}
/// The mask Channel row of the source document `index`.
fn mask_channel_key(index: usize) -> String {
format!("__maskChannel/{index}")
}
/// The shell key that shows the Layer and Channel rows of document `index`: the mask ticked and that document chosen
/// (a row takes one `visible_when` condition).
fn mask_shown_key(index: usize) -> String {
format!("__maskShown/{index}")
}
/// The open documents Apply Image can read from (#14480, #14489): those with the target's pixel size and bit depth,
/// whatever their colour mode, in the order they were opened, as `(index, document)`. The target is among them.
pub(crate) fn apply_image_documents(app: &PhotocraftApp) -> Vec<(usize, &photocraft_doc::Document)> {
let Some(target) = app.session.active() else { return Vec::new() };
let (size, depth) = (target.doc.size, target.doc.depth);
let mut documents: Vec<(usize, &photocraft_doc::Document)> =
app.session.documents().iter().enumerate().filter(|(_, st)| st.doc.size == size && st.doc.depth == depth).map(|(i, st)| (i, &*st.doc)).collect();
// Document ids are handed out as documents open, so they keep the opening order when tabs are dragged.
documents.sort_by_key(|(_, d)| d.id.0);
documents
}
/// The option id prefix of a layer the engine would not read by its plain name: one named "merged" (the composite) or
/// with no name, and so that no plain name is mistaken for one, any name with this prefix. The rest of the id is the
/// name, sent as `{"name": …}` ([`apply_image_layer_selector`]).
const LAYER_NAMED: &str = "layer#";
/// The option id prefix of an alpha channel the engine would not read by its plain name: one named as a built-in
/// channel ("Red", "RGB", "selection"…), a later one of a repeated name, one named as a channel value the source and
/// mask paths read as no channel ([`NO_CHANNEL`]), or one with this prefix. The rest of the id is its index, sent as
/// `{"alpha": index}` ([`apply_image_channel_selector`]).
const ALPHA_AT: &str = "alpha#";
/// Channel values the engine reads as no channel: a mask channel "none" is no mask, and an empty channel is dropped
/// from a flat source or mask (the source then reads the composite, the mask is off).
const NO_CHANNEL: [&str; 2] = ["", "none"];
/// The option id of the layer `name`: the name itself, unless the engine would read it as something else.
fn apply_image_layer_option(name: &str) -> String {
if name.is_empty() || name == "merged" || name.starts_with(LAYER_NAMED) { format!("{LAYER_NAMED}{name}") } else { name.to_owned() }
}
/// The layer selector an Apply Image Layer option sends: `{"name": …}` for a [`LAYER_NAMED`] id, else the id.
fn apply_image_layer_selector(id: &str) -> Value {
id.strip_prefix(LAYER_NAMED).map_or_else(|| json!(id), |name| json!({"name": name}))
}
/// The channel selector an Apply Image Channel option sends: `{"alpha": index}` for an [`ALPHA_AT`] id, else the id.
fn apply_image_channel_selector(id: &str) -> Value {
id.strip_prefix(ALPHA_AT).and_then(|i| i.parse::<u64>().ok()).map_or_else(|| json!(id), |i| json!({"alpha": i}))
}
/// A selector as a dialog field: a plain id as text, an explicit selector as JSON.
fn selector_field(selector: Value) -> FieldValue {
match selector {
Value::String(id) => FieldValue::Text(id),
other => FieldValue::Json(other),
}
}
/// The alpha channel options of a source document, labelled by name: an alpha whose name the engine reads as itself
/// keeps it as its id, any other is [`ALPHA_AT`] and its index, so no option shares an id with a built-in channel or
/// another alpha.
fn apply_image_alpha_options(doc: &photocraft_doc::Document) -> Vec<(String, Label)> {
use photocraft_engine::channel_cmds::{ChanRef, parse_ref};
doc.channels
.iter()
.enumerate()
.map(|(i, c)| {
let plain = !c.name.starts_with(ALPHA_AT) && !NO_CHANNEL.contains(&c.name.as_str()) && parse_ref(&json!(c.name), doc) == Some(ChanRef::Alpha(i));
(if plain { c.name.clone() } else { format!("{ALPHA_AT}{i}") }, Label::from(c.name.clone()))
})
.collect()
}
/// The Layer list of a source document and its default: Merged, then its pixel layers top to bottom (the engine takes
/// the topmost layer of a name), Merged first; a single-layer document lists only that layer. A layer keeps its own
/// option beside Merged whatever its name ([`apply_image_layer_option`]).
fn apply_image_layers(doc: &photocraft_doc::Document) -> (Vec<(String, Label)>, String) {
let all = doc.walk();
if let [(_, _, only)] = all.as_slice() {
let id = apply_image_layer_option(&only.name);
return (vec![(id.clone(), Label::from(only.name.clone()))], id);
}
let mut names: Vec<&str> = Vec::new();
let mut layers = vec![("merged".to_string(), Label::from(tl!("Merged")))];
for (_, _, l) in all.iter().rev() {
if l.surface().is_some() && !names.contains(&l.name.as_str()) {
names.push(&l.name);
layers.push((apply_image_layer_option(&l.name), Label::from(l.name.clone())));
}
}
(layers, "merged".to_string())
}
/// The mask Channel list of a source document and its default (#14489): its composite, read as luminosity and so named
/// Gray, the colour channels of a colour document, then its alpha channels (and Selection while it has one). A colour
/// document starts at its first colour channel, a one-channel document at Gray. The reference draws a rule before the
/// alpha channels; the hosted choice row takes no separators.
fn apply_image_mask_channels(doc: &photocraft_doc::Document) -> (Vec<(String, Label)>, String) {
let mode = doc.pixel_format().mode;
let composite = photocraft_engine::channel_cmds::composite_name(mode).to_string();
let mut list = vec![(composite.clone(), Label::from(tl!("Gray")))];
let mut default = composite;
if mode.color_channels() > 1 {
let colors = photocraft_engine::channel_cmds::color_names(mode);
if let Some(first) = colors.first() {
default = (*first).to_string();
}
list.extend(colors.iter().map(|n| (n.to_string(), Label::from(n.to_string()))));
}
list.extend(apply_image_alpha_options(doc));
if doc.selection.is_some() {
list.extend(channels(&["selection".to_string()]));
}
(list, default)
}
/// Apply Image's Mask... checkbox and the group it opens (#14489): Source (the documents of [`apply_image_documents`],
/// the first by default), then that document's Layer and Channel, and Invert.
fn apply_image_mask_rows(app: &PhotocraftApp) -> Vec<Param> {
let documents = apply_image_documents(app);
let shown = |row: Param| row.visible_when(MASK_ON, true);
let names: Vec<(String, Label)> = documents.iter().map(|(i, d)| (i.to_string(), Label::from(d.name.clone()))).collect();
let first = names.first().map(|(id, _)| id.clone()).unwrap_or_default();
let mut rows = vec![Param::new(MASK_ON, tl!("Mask…"), ParamKind::bool(false)), shown(choice(MASK_SOURCE, tl!("Source"), names, &first))];
for (i, doc) in documents {
let (layers, layer) = apply_image_layers(doc);
let (list, channel) = apply_image_mask_channels(doc);
rows.push(choice(&mask_layer_key(i), tl!("Layer"), layers, &layer).visible_when(mask_shown_key(i), true));
rows.push(choice(&mask_channel_key(i), tl!("Channel"), list, &channel).visible_when(mask_shown_key(i), true));
}
rows.push(shown(Param::new(MASK_INVERT, tl!("Invert"), ParamKind::bool(false))));
rows
}
/// Brings the mask group's shell keys and the `mask*` parameters of `image.applyImage` up to date: the chosen
/// document's Layer and Channel rows are shown, and OK sends `maskDocument`, `maskLayer`, `maskChannel` and, only when
/// Invert is ticked, `maskInvert`. With Mask unticked it sends no mask at all. A layer or alpha the engine would read as
/// something else by its name goes as an explicit selector.
fn apply_image_mask_derive(fields: &mut DialogFields) {
let on = fields.bool(MASK_ON) == Some(true);
let source = fields.text(MASK_SOURCE).and_then(|s| s.parse::<usize>().ok());
let documents: Vec<usize> = fields.iter().filter_map(|(k, _)| k.strip_prefix("__maskLayer/").and_then(|i| i.parse().ok())).collect();
for i in documents {
fields.set(mask_shown_key(i), on && source == Some(i));
}
for key in ["maskDocument", "maskLayer", "maskChannel", "maskInvert"] {
fields.remove(key);
}
let Some(i) = source.filter(|_| on) else { return };
let Some(channel) = fields.text(&mask_channel_key(i)).map(apply_image_channel_selector) else { return };
let layer = apply_image_layer_selector(fields.text(&mask_layer_key(i)).unwrap_or("merged"));
fields.set("maskDocument", FieldValue::Int(i64::try_from(i).unwrap_or(i64::MAX)));
fields.set("maskLayer", selector_field(layer));
fields.set("maskChannel", selector_field(channel));
if fields.bool(MASK_INVERT) == Some(true) {
fields.set("maskInvert", true);
}
}
#[cfg(test)]
#[path = "../../dialogs/apply_image_mask_group_tests.rs"]
mod apply_image_mask_group_tests;
/// The Channel options of one Image ▸ Calculations source (#14521), in the reference application's
/// order: the composite read as "Gray", the mode's colour channels, then the source layer's Layer
/// Mask and Transparency — Layer Mask only when that layer has one — and then the document's alpha
@@ -0,0 +1,234 @@
//! #12537: when the Paint Bucket can't fill (a hidden target layer, Lock All or Lock Image Pixels,
//! a group active), a click opens the reference application's alert with OK and fills nothing: no
//! History step, the target layer stays selected. Lock transparent pixels and Lock position still
//! fill; a pixel layer inside a group fills normally; a group's targeted layer mask is not refused
//! and takes today's step-without-fill. The Brush's alerts (Lock all only) and the other tools
//! stay as they are.
use egui::Modifiers;
use serde_json::json;
use super::brush_refusal_alert_tests::{active, alerts, app, steps, stroke};
use super::*;
use crate::canvas::{ToolEvent, tool_event};
use crate::control::{ControlRequest, Reply, handle};
/// A Paint Bucket click on the painted layer.
fn click(app: &mut PhotocraftApp) {
tool_event(app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE);
tool_event(app, ToolEvent::Up { x: 30.0, y: 30.0 }, Modifiers::NONE);
}
/// The active layer's pixel at the click point; a group has no surface, hence `None`.
fn pixel(app: &PhotocraftApp) -> Option<[f32; 4]> {
let st = app.session.active().unwrap();
st.doc.layer(st.active_layer.unwrap())?.surface().map(|s| s.rgba(30, 30))
}
/// A named layer's pixel at the click point - the byte check when the active layer is a group.
fn child_rgba(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> [f32; 4] {
let st = app.session.active().unwrap();
st.doc.layer(id).and_then(|l| l.surface()).map(|s| s.rgba(30, 30)).unwrap_or([0.0; 4])
}
/// The click opens one alert with `want` and changes nothing: the same pixels, no History step, the
/// same active layer. OK closes the alert.
fn refused(app: &mut PhotocraftApp, want: &str) {
let before = (steps(app), pixel(app), active(app));
click(app);
assert_eq!(alerts(app), [want], "the alert, once");
assert_eq!((steps(app), pixel(app), active(app)), before, "nothing filled, no History step, the target stays selected");
let id = app.framework.dialogs.open_dialogs().first().map(|d| d.id).unwrap();
let ctx = app.ctx().clone();
crate::dialogs::confirm(app, &ctx, id).unwrap();
assert!(alerts(app).is_empty(), "OK closes the alert");
}
#[test]
fn a_hidden_target_layer() {
let mut app = app(Tool::PaintBucket);
let id = active(&app);
app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
refused(&mut app, "Could not use the paint bucket because the target layer is hidden.");
assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status);
assert_eq!(
photocraft_engine::hidden_target::HIDDEN,
"Could not complete your request because the target layer is hidden.",
"the engine's shared text stays as it is"
);
}
#[test]
fn lock_all_and_lock_image_pixels() {
// Both are the one "the layer is locked." alert in the reference application.
for lock in ["all", "pixels"] {
let mut bucket = app(Tool::PaintBucket);
bucket.run("layer.lockLayers", json!({ lock: true })).unwrap();
refused(&mut bucket, "Could not use the paint bucket because the layer is locked.");
}
}
#[test]
fn a_group_is_active() {
// The group holds the painted child layer, so its pixels are the byte check: a group has no
// surface of its own and the group's own check would be vacuous.
let mut app = app(Tool::PaintBucket);
let child = app.session.active().unwrap().active_layer.unwrap();
let red = child_rgba(&app, child);
assert!(red[0] > 0.8 && red[3] > 0.99, "the child starts painted red: {red:?}");
app.run("layer.groupLayers", json!({})).unwrap();
// Once, with the measured wording: `press_refused` answers before `refuse_group` can add its
// own alert.
refused(&mut app, "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group.");
assert_eq!(child_rgba(&app, child), red, "the child layer's pixels inside the group stay as they were");
}
#[test]
fn a_group_inside_a_group_is_refused_once() {
// Neighbour (pattern 3): the active inner group sits inside the outer group, which holds a
// painted child; neither group has pixels of its own at the click, so the byte check is the
// child's.
let mut app = app(Tool::PaintBucket);
app.run("layer.new.group", json!({})).unwrap();
app.run("layer.new.group", json!({})).unwrap();
let inner = app.session.active().unwrap().active_layer.unwrap();
app.run("layer.new.layer", json!({})).unwrap();
let child = app.session.active().unwrap().active_layer.unwrap();
app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap();
app.run("layer.select", json!({"layer": inner.0})).unwrap();
let st = app.session.active().unwrap();
let path = st.doc.path_of(st.active_layer.unwrap()).unwrap();
assert_eq!(path.len(), 2, "the active group sits inside the outer group: {path:?}");
let red = child_rgba(&app, child);
assert!(red[0] > 0.8 && red[3] > 0.99, "the child inside the groups starts painted red: {red:?}");
refused(&mut app, "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group.");
assert_eq!(child_rgba(&app, child), red, "the child layer's pixels inside the groups stay as they were");
}
#[test]
fn the_alert_is_listed_and_confirmed_over_the_control_channel() {
let ctx = egui::Context::default();
let mut app = app(Tool::PaintBucket);
app.run("layer.lockLayers", json!({"pixels": true})).unwrap();
click(&mut app);
let mut call = |method: &str, params: serde_json::Value| {
let (req, _rx) = ControlRequest::new(method, params);
match handle(&mut app, &ctx, &req) {
Reply::Done(v) => v,
_ => panic!("{method}: expected an immediate reply"),
}
};
let inspect = call("ui.inspect", json!({}));
let dialog = &inspect["result"]["dialogs"][0];
assert_eq!(dialog["fields"]["message"], "Could not use the paint bucket because the layer is locked.", "{inspect}");
assert_eq!(call("ui.dialog.confirm", json!({"dialog": dialog["id"]}))["ok"], true);
assert!(alerts(&app).is_empty());
}
#[test]
fn a_click_on_a_visible_unlocked_layer_still_fills() {
// The guard for the whole change: the painting path is untouched.
let mut app = app(Tool::PaintBucket);
let before = steps(&app);
click(&mut app);
assert!(alerts(&app).is_empty(), "{:?}", alerts(&app));
assert_eq!(steps(&app), before + 1, "the fill was applied");
let st = app.session.active().unwrap();
let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
for (x, y) in [(30, 30), (2, 2), (61, 61)] {
let [r, g, b, a] = surface.rgba(x, y);
assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "the black foreground at ({x}, {y}): {:?}", [r, g, b, a]);
}
}
#[test]
fn lock_transparent_pixels_still_fills_the_opaque_pixels() {
let mut app = app(Tool::PaintBucket);
app.run("layer.lockLayers", json!({"transparency": true})).unwrap();
let before = steps(&app);
click(&mut app);
assert!(alerts(&app).is_empty(), "{:?}", alerts(&app));
assert_eq!(steps(&app), before + 1);
let [r, g, b, a] = pixel(&app).unwrap();
assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "the opaque region filled black: {:?}", [r, g, b, a]);
}
#[test]
fn lock_position_still_fills() {
let mut app = app(Tool::PaintBucket);
app.run("layer.lockLayers", json!({"position": true})).unwrap();
let before = steps(&app);
click(&mut app);
assert!(alerts(&app).is_empty(), "{:?}", alerts(&app));
assert_eq!(steps(&app), before + 1);
let [r, g, b, a] = pixel(&app).unwrap();
assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "filled black: {:?}", [r, g, b, a]);
}
#[test]
fn a_pixel_layer_inside_a_group_fills_normally() {
let mut app = app(Tool::PaintBucket);
app.run("layer.new.group", json!({})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
let st = app.session.active().unwrap();
let id = st.active_layer.unwrap();
let path = st.doc.path_of(id).unwrap();
assert_eq!(path.len(), 2, "the new layer is a child of the group: {path:?}");
assert!(st.doc.layer_at(&path[..1]).is_some_and(|l| l.is_group()), "its parent is a group");
let before = steps(&app);
click(&mut app);
assert!(alerts(&app).is_empty(), "{:?}", alerts(&app));
assert_eq!(steps(&app), before + 1, "the click filled the layer inside the group");
let [r, g, b, a] = pixel(&app).unwrap();
assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "filled black: {:?}", [r, g, b, a]);
}
#[test]
fn a_group_s_targeted_mask_takes_a_step_that_fills_nothing() {
// Not measured: keeps today's behaviour as a whole. Measured on `main` before and after this
// change: the click opens no alert (the alert path only speaks for pixel targets), the engine
// adds one "Paint Bucket" state, and its command answers `filled: true` while leaving the
// all-white mask's samples as they are - all pinned here, so the name says exactly what today
// is: a step, and no fill.
let mut app = app(Tool::PaintBucket);
app.run("layer.new.group", json!({})).unwrap();
app.run("layer.layerMask.revealAll", json!({})).unwrap();
app.ui.mask_target = true;
app.sync_mask_targets();
assert_eq!(crate::canvas::paint_target(&app), json!("mask"), "the group's mask is targeted");
let before = steps(&app);
click(&mut app);
assert!(alerts(&app).is_empty(), "no refusal alert on a mask target: {:?}", alerts(&app));
assert_eq!(steps(&app), before + 1, "the engine's own step lands as today");
let labels = app.run("document.inspect", json!({})).unwrap()["history"].as_array().cloned().unwrap_or_default();
assert_eq!(labels.last(), Some(&json!("Paint Bucket")), "the step the click added carries the engine's own label");
// The command's own answer, pinned once through the engine: it claims a fill and writes nothing.
let reply = app.run("paint.bucket", json!({"x": 30, "y": 30, "target": "mask"})).unwrap();
assert_eq!(reply["filled"], json!(true), "the engine reports filled: true, as on main");
assert_eq!(steps(&app), before + 2, "and that call adds its step too");
let st = app.session.active().unwrap();
let mask = st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap();
for (x, y) in [(30, 30), (2, 2), (61, 61)] {
assert_eq!(mask.surface.sample_channel(x, y, 0), 1.0, "the mask samples stay white at ({x}, {y}) as on main");
}
}
#[test]
fn the_brush_alerts_stay_as_they_are_and_the_other_tools_stay_quiet() {
// The Brush (#11898): Lock all only, never Lock Image Pixels.
let mut brush = app(Tool::Brush);
brush.run("layer.lockLayers", json!({"all": true})).unwrap();
stroke(&mut brush);
assert_eq!(alerts(&brush), ["Could not use the brush tool because the layer is locked."], "the Brush's Lock all alert is unchanged");
let mut brush = app(Tool::Brush);
brush.run("layer.lockLayers", json!({"pixels": true})).unwrap();
stroke(&mut brush);
assert!(alerts(&brush).is_empty(), "the Brush keeps no alert for Lock Image Pixels: {:?}", alerts(&brush));
// The Dodge tool has no layer alerts: a hidden target stays in the status bar.
let mut dodge = app(Tool::Dodge);
let id = active(&dodge);
dodge.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
stroke(&mut dodge);
assert!(alerts(&dodge).is_empty());
assert_eq!(dodge.ui.status, photocraft_engine::hidden_target::HIDDEN);
}
@@ -0,0 +1,159 @@
//! Smudge Pressure for Size (#12961): the bar toggle binds the same brush used by paint.smudge.
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_engine::BrushSettings;
use serde_json::json;
use crate::PhotocraftApp;
use crate::state::Tool;
const PRESSURE: &str = "Always use pressure for size";
const TOOLTIP: &str = "Always use Pressure for Size. When off, Brush Preset controls pressure";
fn bar(tool: Tool) -> Harness<'static, Box<PhotocraftApp>> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.ui.tool = tool;
let mut h =
Harness::builder().with_size(vec2(1600.0, 400.0)).with_context(app.ctx().clone()).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app);
h.run_steps(4);
h
}
fn toggle(h: &mut Harness<'static, Box<PhotocraftApp>>) {
h.get_by_label(PRESSURE).click();
h.run_steps(3);
}
fn brush_commands(h: &Harness<'static, Box<PhotocraftApp>>) -> usize {
h.state().session.journal.iter().filter(|(id, _)| id == "tools.setBrush").count()
}
#[test]
fn pressure_is_off_by_default_and_follows_finger_painting_with_the_exact_tooltip() {
let h = bar(Tool::Smudge);
let pressure = h.get_by_label(PRESSURE);
assert!(h.get_by_label("Finger Painting").rect().right() <= pressure.rect().left());
assert_eq!(pressure.accesskit_node().description().as_deref(), Some(TOOLTIP));
assert!(!h.state().session.tools.brush.pressure_size);
}
#[test]
fn the_toggle_updates_the_brush_settings_value_with_one_command_per_click() {
let mut h = bar(Tool::Smudge);
let n = brush_commands(&h);
toggle(&mut h);
assert!(h.state().session.tools.brush.pressure_size);
assert_eq!(h.state_mut().run("brush.get", json!({})).unwrap()["pressureSize"], json!(true));
assert_eq!(brush_commands(&h), n + 1);
assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": true}));
toggle(&mut h);
assert!(!h.state().session.tools.brush.pressure_size);
assert_eq!(brush_commands(&h), n + 2);
assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": false}));
}
#[test]
fn reset_tool_turns_pressure_off_and_other_tools_keep_their_own_setting() {
let mut h = bar(Tool::Brush);
h.state_mut().run("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap();
h.run_steps(2);
h.state_mut().ui.tool = Tool::Smudge;
h.run_steps(3);
assert!(!h.state().session.tools.brush.pressure_size, "Smudge starts with its own default");
toggle(&mut h);
h.state_mut().ui.tool = Tool::Brush;
h.run_steps(3);
assert!(h.state().session.tools.brush.pressure_size, "the Brush setting is retained");
h.state_mut().ui.tool = Tool::Smudge;
h.run_steps(3);
assert!(h.state().session.tools.brush.pressure_size, "Smudge remembers its value");
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap();
h.run_steps(2);
assert!(!h.state().session.tools.brush.pressure_size);
h.state_mut().ui.tool = Tool::Brush;
h.run_steps(3);
assert!(h.state().session.tools.brush.pressure_size, "resetting Smudge does not reset the Brush");
}
/// Read the actual shared generator's dabs for a pen tap, rather than duplicating its formula.
fn radii(brush: &BrushSettings, pressure: f32) -> Vec<f32> {
let mut generator = photocraft_paint::dynamics::DabGenerator::new(brush, 1.0);
let (mut dabs, mut dual) = (Vec::new(), Vec::new());
generator.push(&[photocraft_paint::StrokePoint::new(28.0, 40.0, pressure)], &mut dabs, &mut dual);
generator.finish(&mut dabs, &mut dual);
assert!(!dabs.is_empty());
dabs.into_iter().map(|dab| dab.radius).collect()
}
#[test]
fn the_ui_toggle_changes_generated_dab_size_with_pressure_and_off_restores_the_baseline() {
let mut h = bar(Tool::Smudge);
let original = h.state().session.tools.brush.clone();
let off_low = radii(&original, 0.25);
let off_full = radii(&original, 1.0);
assert_eq!(off_low, off_full);
toggle(&mut h);
let on = h.state().session.tools.brush.clone();
assert_eq!(radii(&on, 1.0), off_full);
let low = radii(&on, 0.25);
assert!(low.iter().all(|r| (*r - original.size * 0.25 * 0.5).abs() < 1e-6));
toggle(&mut h);
assert_eq!(radii(&h.state().session.tools.brush, 0.25), off_low);
assert_eq!(h.state().session.tools.brush.shape_dynamics, original.shape_dynamics, "the toggle does not rewrite preset dynamics");
}
/// A red/white edge and a real paint.smudge command, with the UI-selected brush and real point
/// pressures. All comparisons use complete resulting pixels, with no visual threshold.
fn smudged(brush: &BrushSettings, pressure: f32) -> (Vec<f32>, Vec<f32>) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80, "depth": 32, "background": "white"})).unwrap();
app.run("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 80})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
app.run("select.deselect", json!({})).unwrap();
app.ui.tool = Tool::Smudge;
crate::paint_mouse::sync_tool_brush(&mut app);
app.run("tools.setBrush", json!({"brush": brush})).unwrap();
app.ui.tool_options.strength = 100.0;
let read = |app: &PhotocraftApp| {
let state = app.session.active().unwrap();
state.doc.layer(state.active_layer.unwrap()).unwrap().surface().unwrap().read_region(state.doc.bounds())
};
let before = read(&app);
let (command, mut params) = super::dab_params(&app, Tool::Smudge).unwrap();
assert_eq!(command, "paint.smudge");
params["points"] = json!([[28.0, 40.0, pressure], [42.0, 40.0, pressure], [58.0, 40.0, pressure]]);
app.run(command, params).unwrap();
(before, read(&app))
}
#[test]
fn actual_smudge_pixels_follow_pressure_on_and_keep_the_existing_result_off() {
let mut h = bar(Tool::Smudge);
h.state_mut().run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0, "spacing": 0.25, "smoothing": {"enabled": false}}})).unwrap();
h.run_steps(2);
let off = h.state().session.tools.brush.clone();
let (before, off_low) = smudged(&off, 0.25);
let (_, off_full) = smudged(&off, 1.0);
assert_ne!(off_full, before, "the edge fixture must actually smudge");
assert_eq!(off_low, off_full, "off keeps today's pressure-independent size");
toggle(&mut h);
let on = h.state().session.tools.brush.clone();
let (_, on_low) = smudged(&on, 0.25);
let (_, on_full) = smudged(&on, 1.0);
assert_ne!(on_low, on_full, "the actual command receives pen pressure and the selected brush");
assert_ne!(on_low, off_low);
assert_eq!(on_full, off_full, "full pressure keeps the full-size result");
toggle(&mut h);
assert_eq!(smudged(&h.state().session.tools.brush, 0.25).1, off_low);
}
#[test]
fn the_smudge_change_does_not_add_pressure_controls_to_blur_or_sharpen() {
for tool in [Tool::Blur, Tool::Sharpen] {
assert!(bar(tool).query_by_label(PRESSURE).is_none(), "{tool:?}");
}
}
+13 -5
View File
@@ -39,7 +39,7 @@ fn mode_tool_name(tool: Tool) -> Option<&'static str> {
/// The tool's name in the alerts, for the tools whose wording was measured: the Brush, the
/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965), the Burn tool (#12672), the Healing Brush (#12111), the Art History Brush
/// (#12638) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017).
/// (#12638), the Paint Bucket (#12537) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017).
pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> {
match tool {
Tool::Brush => Some(tl!("brush tool")),
@@ -53,6 +53,8 @@ pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> {
Tool::Burn => Some(tl!("burn tool")),
Tool::Healing => Some(tl!("healing brush")),
Tool::ArtHistoryBrush => Some(tl!("art history brush")),
// The Paint Bucket's click (#12537).
Tool::PaintBucket => Some(tl!("paint bucket")),
Tool::Gradient if app.ui.tool_options.gradient_classic => Some(tl!("gradient tool")),
_ => None,
}
@@ -132,11 +134,13 @@ fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> {
}
}
/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge, Smudge and Burn tools and the
/// Art History Brush Lock Image Pixels as well (measured for them; the Brush keeps today's
/// behaviour there).
/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge, Smudge and Burn tools, the
/// Art History Brush, the Magic Eraser and the Paint Bucket (#12537) Lock Image Pixels as well
/// (measured for them; the Brush keeps today's behaviour there).
fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool {
locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::Burn | Tool::ArtHistoryBrush | Tool::MagicEraser) && locks.pixels)
locks.all
|| (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::Burn | Tool::ArtHistoryBrush | Tool::MagicEraser | Tool::PaintBucket)
&& locks.pixels)
}
/// A Spot Healing press on an empty pixel layer with Sample All Layers off (#12581): when that layer is hidden, the
@@ -186,3 +190,7 @@ mod burn_refusal_alert_tests;
#[cfg(test)]
#[path = "../healing_refusal_alert_tests.rs"]
mod healing_refusal_alert_tests;
#[cfg(test)]
#[path = "../paint_bucket_refusal_alerts_tests.rs"]
mod paint_bucket_refusal_alerts_tests;
+4
View File
@@ -811,3 +811,7 @@ mod remove_options_bar_labels_tests;
#[cfg(test)]
#[path = "../smudge_bar_angle_tests.rs"]
mod smudge_bar_angle_tests;
#[cfg(test)]
#[path = "../smudge_bar_pressure_size_tests.rs"]
mod smudge_bar_pressure_size_tests;
@@ -127,6 +127,23 @@ fn smudge_angle(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option<RangeAlert
alert
}
/// Smudge's pressure-for-size switch edits the active tool's own brush through
/// the same command and gesture path as the current Background Eraser controls.
fn smudge_pressure_size(ui: &mut egui::Ui, app: &mut PhotocraftApp) {
let before = (*app.session.tools.brush).clone();
let mut brush = before.clone();
let pressure = ToggleButton::new(tl!("Always use pressure for size"), Bind::given(brush.pressure_size))
.icon(IconId::new("target"))
.icon_only()
.tooltip(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure").to_owned())
.show(ui);
if let Some(on) = pressure.value().copied() {
brush.pressure_size = on;
}
let key = pressure.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e));
crate::brush_panel::commit_keyed(app, &before, &brush, key);
}
/// The options of Blur, Sharpen and Smudge.
pub(super) fn blur_sharpen_smudge(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> Option<RangeAlert> {
let o = &mut app.ui.tool_options;
@@ -149,6 +166,7 @@ pub(super) fn blur_sharpen_smudge(ui: &mut egui::Ui, app: &mut PhotocraftApp, to
}
if tool == Tool::Smudge {
check(ui, tl!("Finger Painting"), &mut o.finger_painting, true, None);
smudge_pressure_size(ui, app);
}
strength.or(angle)
}
@@ -834,3 +834,38 @@ fn an_empty_clone_source_slot_refuses_to_paint() {
assert!(app.ui.clone_source.is_some(), "the old ⌥-click point is still remembered");
assert!(crate::retouch_ui::clone_params(&app).is_none());
}
/// #13096: a Red Eye press outside the selection does nothing and says nothing, as in Photoshop:
/// no status message, no error, no History state and no pixel change.
#[test]
fn a_red_eye_press_outside_the_selection_is_silent() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600, "mode": "rgb", "depth": 8})).unwrap();
app.run("edit.fill", json!({"color": "#c08a68"})).unwrap();
for cx in [200, 500] {
for (r, color) in [(40, "#ffffff"), (30, "#d22828")] {
app.run("select.rect", json!({"x": cx - r, "y": 200 - r, "width": 2 * r, "height": 2 * r, "ellipse": true})).unwrap();
app.run("edit.fill", json!({"color": color})).unwrap();
}
}
// The left half of eye B: x 450–499. A press at x 500.0 lands on pixel 499, so press at 500.5.
app.run("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 600})).unwrap();
app.ui.tool = Tool::RedEye;
app.ui.status.clear();
app.ui.status_error = false;
let snapshot = |app: &PhotocraftApp| {
let st = app.session.active().unwrap();
(st.history.past_len(), active(app).surface().unwrap().read_region(st.doc.bounds()))
};
let (states, pixels) = snapshot(&app);
gesture(&mut app, &[[500.5, 200.5]]);
assert_eq!(app.ui.status, "", "no status message");
assert!(!app.ui.status_error);
let (after_states, after_pixels) = snapshot(&app);
assert_eq!(after_states, states, "no History state");
assert!(after_pixels == pixels, "no pixel change");
// A press inside the selection still corrects the left half.
gesture(&mut app, &[[490.5, 200.5]]);
assert!(!app.ui.status_error, "{}", app.ui.status);
assert_eq!(snapshot(&app).0, states + 1);
}