mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge main into the batch branch bb-move-tool-mx4onk76
This commit is contained in:
commit
f40c4b5454
13 files changed
+564
-8
No files matched your search
@@ -537,6 +537,33 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
|
||||
}
|
||||
|
||||
/// HDR Toning is greyed with an active selection and in CMYK, Lab and Indexed Color documents
|
||||
/// (#14735). RGB and Grayscale keep it; Duotone and Multichannel were not measured and keep
|
||||
/// today's behaviour (`Session::precondition` refuses Bitmap for every adjustment but Invert).
|
||||
fn hdr_toning_enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document open")?;
|
||||
// The mode comes first: deselecting can't fix it.
|
||||
if let Some(reason) = hdr_toning_mode_refusal(d.doc.mode) {
|
||||
return Err(reason);
|
||||
}
|
||||
if d.doc.selection.is_some() {
|
||||
return Err("HDR Toning works on the whole image: deselect first".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A document mode that excludes HDR Toning even when the composite channel is targeted.
|
||||
pub(crate) fn hdr_toning_mode_refusal(mode: photocraft_color::ColorMode) -> Option<String> {
|
||||
use photocraft_color::ColorMode;
|
||||
let label = match mode {
|
||||
ColorMode::Cmyk => "CMYK Color",
|
||||
ColorMode::Lab => "Lab Color",
|
||||
ColorMode::Indexed => "Indexed Color",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!("HDR Toning needs an RGB or Grayscale document (this one is {label})"))
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
/// Image › Adjustments run as a smart filter (`image.adjustments.<kind>` recorded on a smart
|
||||
@@ -861,7 +888,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"HDR Toning…",
|
||||
["Image", "Adjustments"],
|
||||
r##"{"radius":1..500=30,"strength":0.1..4=0.5,"gamma":0.1..2=1,"exposure":-5..5=0,"detail":-100..300=30,"shadow":-100..100=0,"highlight":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=20,"curve":[[in,out],…] 0..255} (flattens the image)"##,
|
||||
has_doc,
|
||||
hdr_toning_enabled,
|
||||
hdr_toning
|
||||
),
|
||||
CommandSpec {
|
||||
@@ -1011,6 +1038,8 @@ fn black_white_auto(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Object(crate::adjust_params::HUE_RANGES.iter().zip(w).map(|(k, v)| ((*k).to_string(), json!(v))).collect()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hdr_toning_enabled_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Image > Adjustments > HDR Toning is greyed with an active selection and in CMYK, Lab and
|
||||
//! Indexed Color documents (#14735), stays available in RGB at 8, 16 and 32 bit and Grayscale 8
|
||||
//! bit (keeping the mode and depth), and Duotone, Multichannel and deeper Grayscale (not measured)
|
||||
//! keep today's behaviour.
|
||||
|
||||
use crate::Session;
|
||||
use serde_json::json;
|
||||
|
||||
const HDR: &str = "image.adjustments.hdrToning";
|
||||
|
||||
fn new_doc(mode: &str, depth: u32) -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "mode": mode, "depth": depth, "background": "white"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn assert_refused(mut s: Session, what: &str) {
|
||||
assert!(!s.is_enabled(HDR), "{what}: the menu entry is greyed out");
|
||||
let d = s.active().unwrap();
|
||||
let (steps, selection, mode) = (d.history.past_len(), d.doc.selection.clone(), d.doc.mode);
|
||||
assert!(s.execute(HDR, json!({})).is_err(), "{what}: running it is refused");
|
||||
let d = s.active().unwrap();
|
||||
assert_eq!(d.history.past_len(), steps, "{what}: no history state");
|
||||
assert_eq!(d.doc.selection, selection, "{what}: the selection stays");
|
||||
assert_eq!(d.doc.mode, mode, "{what}: the mode stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_active_selection_refuses_hdr_toning() {
|
||||
let mut s = new_doc("rgb", 8);
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
assert!(s.active().unwrap().doc.selection.is_some());
|
||||
assert_refused(s, "RGB with a selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_lab_and_indexed_documents_refuse_hdr_toning() {
|
||||
assert_refused(new_doc("cmyk", 8), "CMYK 8 bit");
|
||||
assert_refused(new_doc("lab", 8), "Lab 8 bit");
|
||||
let mut indexed = new_doc("rgb", 8);
|
||||
indexed.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
|
||||
assert_refused(indexed, "Indexed Color");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targeted_hdr_toning_names_the_unsupported_mode_before_the_channel() {
|
||||
let mut indexed = new_doc("rgb", 8);
|
||||
indexed.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
|
||||
let target = json!({"target": {"color": 0}});
|
||||
for (mut s, reason) in [
|
||||
(new_doc("cmyk", 8), "CMYK Color"),
|
||||
(new_doc("lab", 8), "Lab Color"),
|
||||
(indexed, "Indexed Color"),
|
||||
(new_doc("rgb", 8), "requires the composite channel"),
|
||||
] {
|
||||
let disabled = s.disabled_reason_with(HDR, &target).unwrap();
|
||||
assert!(disabled.contains(reason), "{disabled}");
|
||||
let error = s.execute(HDR, target.clone()).unwrap_err().to_string();
|
||||
assert!(error.contains(reason), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_all_depths_and_grayscale_8_bit_keep_hdr_toning_and_their_mode_and_depth() {
|
||||
for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 8)] {
|
||||
let mut s = new_doc(mode, depth);
|
||||
assert!(s.is_enabled(HDR), "{mode} {depth} bit");
|
||||
let d = s.active().unwrap();
|
||||
let (steps, before_mode, before_depth) = (d.history.past_len(), d.doc.mode, d.doc.depth);
|
||||
s.execute(HDR, json!({})).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
assert_eq!(d.history.past_len(), steps + 1, "{mode} {depth} bit: one history state");
|
||||
assert_eq!((d.doc.mode, d.doc.depth), (before_mode, before_depth), "{mode} {depth} bit keeps its mode and depth");
|
||||
}
|
||||
}
|
||||
|
||||
/// Not measured: Multichannel, Duotone and Grayscale at 16 and 32 bit keep today's behaviour.
|
||||
#[test]
|
||||
fn unmeasured_documents_keep_todays_behaviour() {
|
||||
let mut multi = new_doc("rgb", 8);
|
||||
multi.execute("image.mode.multichannel", json!({})).unwrap();
|
||||
assert!(multi.is_enabled(HDR), "Multichannel");
|
||||
|
||||
let mut duotone = new_doc("grayscale", 8);
|
||||
duotone
|
||||
.edit("duotone", |d, _| {
|
||||
d.mode = photocraft_color::ColorMode::Duotone;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(duotone.is_enabled(HDR), "Duotone");
|
||||
|
||||
for depth in [16, 32] {
|
||||
assert!(new_doc("grayscale", depth).is_enabled(HDR), "Grayscale {depth} bit");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refusals_say_why() {
|
||||
let why = super::hdr_toning_enabled(&new_doc("lab", 8)).unwrap_err();
|
||||
assert!(why.contains("Lab Color"), "{why}");
|
||||
let mut s = new_doc("rgb", 8);
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
let why = super::hdr_toning_enabled(&s).unwrap_err();
|
||||
assert!(why.contains("deselect"), "{why}");
|
||||
// A CMYK document with a selection names the mode: deselecting would not help.
|
||||
let mut s = new_doc("cmyk", 8);
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
let why = super::hdr_toning_enabled(&s).unwrap_err();
|
||||
assert!(why.contains("CMYK Color"), "{why}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_document_is_unchanged() {
|
||||
let mut s = crate::session();
|
||||
assert!(!s.is_enabled(HDR));
|
||||
assert_eq!(super::hdr_toning_enabled(&s).unwrap_err(), "no document open");
|
||||
assert!(s.execute(HDR, json!({})).is_err());
|
||||
}
|
||||
@@ -57,7 +57,14 @@ fn destructive_adjustments_all_depths_and_modes_one_undo_step() {
|
||||
for (id, params) in &cases {
|
||||
for depth in DEPTHS {
|
||||
for mode in MODES {
|
||||
// CMYK and Lab documents grey HDR Toning (#14735, hdr_toning_enabled_tests).
|
||||
let mut s = session(depth, mode);
|
||||
if id.ends_with("hdrToning") && matches!(mode, "cmyk" | "lab") {
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
assert!(s.execute(id, params.clone()).is_err(), "{id} {depth} {mode}: refused");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps, "{id} {depth} {mode}: no history step");
|
||||
continue;
|
||||
}
|
||||
let before = rgba(&s, 3, 3);
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
s.execute(id, params.clone()).unwrap_or_else(|e| panic!("{id} {depth} {mode}: {e}"));
|
||||
|
||||
@@ -63,7 +63,10 @@ pub(crate) fn refusal(s: &Session, id: &str, p: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
if id == "image.adjustments.hdrToning" {
|
||||
return Some("HDR Toning requires the composite channel".into());
|
||||
return s
|
||||
.active()
|
||||
.and_then(|state| crate::adjust_cmds::hdr_toning_mode_refusal(state.doc.mode))
|
||||
.or_else(|| Some("HDR Toning requires the composite channel".into()));
|
||||
}
|
||||
if crate::channel_cmds::routed(id) && p.get("newLayer").and_then(Value::as_bool) == Some(true) {
|
||||
return Some("Creating a new layer requires the composite channel".into());
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
use photocraft_color::BlendMode;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Session, channel_cmds};
|
||||
|
||||
const MASK_LEVEL: f32 = 128.0 / 255.0;
|
||||
|
||||
fn seeded_surface(mode: &str, depth: u8, target: &Value) -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 40, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
|
||||
match target.as_str() {
|
||||
Some("mask") => s.execute("layer.layerMask.revealAll", json!({})).unwrap(),
|
||||
Some("quickMask") => s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(),
|
||||
Some("pixels") => Value::Null,
|
||||
_ => s.execute("channel.new", json!({})).unwrap(),
|
||||
};
|
||||
let active = s.active().unwrap().active_layer;
|
||||
let params = json!({"target": target});
|
||||
s.edit("Seed the backdrop", |doc, _| {
|
||||
let (surface, _) = channel_cmds::target_surface(doc, active, ¶ms)?;
|
||||
let gray = [MASK_LEVEL];
|
||||
let rgba = [MASK_LEVEL, MASK_LEVEL, MASK_LEVEL, 1.0];
|
||||
let sample: &[f32] = if target == "pixels" { &rgba } else { &gray };
|
||||
for x in 0..40 {
|
||||
surface.write_pixel(x, 3, sample);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn gradient_row(mut s: Session, target: &Value, blend: &str) -> Vec<f32> {
|
||||
let params = json!({
|
||||
"from": [4, 3], "to": [32, 3], "stops": [[0, "#000000"], [1, "#ffffff"]],
|
||||
"target": target, "mode": blend, "method": "smooth", "dither": false
|
||||
});
|
||||
s.execute("paint.gradient", params.clone()).unwrap();
|
||||
let state = s.active().unwrap();
|
||||
let surface = channel_cmds::read_target_surface(&state.doc, state.active_layer, ¶ms).unwrap();
|
||||
(0..40).map(|x| surface.pixel(x, 3)[0]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonseparable_gradient_modes_match_normal_throughout_rgb_layer_masks() {
|
||||
let target = json!("mask");
|
||||
for depth in [8, 16] {
|
||||
let normal = gradient_row(seeded_surface("rgb", depth, &target), &target, "normal");
|
||||
assert_eq!(normal[0], 0.0);
|
||||
assert_eq!(normal[39], 1.0);
|
||||
for mode in ["darkerColor", "lighterColor", "hue", "saturation", "color", "luminosity"] {
|
||||
assert_eq!(gradient_row(seeded_surface("rgb", depth, &target), &target, mode), normal, "{depth}-bit {mode}");
|
||||
}
|
||||
let darken = gradient_row(seeded_surface("rgb", depth, &target), &target, "darken");
|
||||
assert_eq!(darken[0], 0.0);
|
||||
assert!((darken[39] - MASK_LEVEL).abs() < 1.0 / 65535.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_the_rgb_mask_depths_darker_color_still_keeps_the_darker_backdrop() {
|
||||
for (mode, depth, target) in [
|
||||
("rgb", 8, json!("pixels")),
|
||||
("rgb", 8, json!("quickMask")),
|
||||
("rgb", 8, json!({"channel": 0})),
|
||||
("rgb", 32, json!("mask")),
|
||||
("gray", 16, json!("mask")),
|
||||
] {
|
||||
let normal = gradient_row(seeded_surface(mode, depth, &target), &target, "normal");
|
||||
// Float mask luma can be one representable step below white. Integer storage rounds it.
|
||||
let white_tolerance = if depth == 32 { 4.0 * f32::EPSILON } else { 0.0 };
|
||||
assert!((normal[39] - 1.0).abs() <= white_tolerance, "{mode} {depth}-bit {target}: {}", normal[39]);
|
||||
let row = gradient_row(seeded_surface(mode, depth, &target), &target, BlendMode::DarkerColor.label());
|
||||
assert!((row[39] - MASK_LEVEL).abs() < 1.0 / 65535.0, "{mode} {depth}-bit {target}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const MASK_ROW: [f32; 21] =
|
||||
[0.0, 15.0, 34.0, 53.0, 73.0, 93.0, 113.0, 131.0, 148.0, 164.0, 178.0, 191.0, 204.0, 215.0, 226.0, 235.0, 242.0, 248.0, 253.0, 255.0, 255.0];
|
||||
|
||||
fn row(mode: &str, depth: u8, target: &str, method: &str, stops: Value, opacity: Option<Value>) -> Vec<f32> {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 800, "height": 16, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
|
||||
if target == "mask" {
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
}
|
||||
let mut params = json!({"from": [100, 10], "to": [700, 10], "stops": stops, "method": method, "dither": false, "target": target});
|
||||
if let Some(opacity) = opacity {
|
||||
params["transparency"] = opacity;
|
||||
}
|
||||
s.execute("paint.gradient", params.clone()).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let surface = crate::channel_cmds::read_target_surface(&st.doc, st.active_layer, ¶ms).unwrap();
|
||||
(0..800).map(|x| if target == "mask" { surface.pixel(x, 10)[0] } else { surface.rgba(x, 10)[3] }).map(|value| value * 255.0).collect()
|
||||
}
|
||||
|
||||
fn fade(mode: &str, depth: u8, target: &str, method: &str) -> Vec<f32> {
|
||||
row(mode, depth, target, method, json!([[0, "#000000"], [1, "#000000"]]), Some(json!([[0, 100], [1, 0]])))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_transparency_follows_the_measured_layer_mask_fade() {
|
||||
for mode in ["rgb", "gray", "cmyk", "lab"] {
|
||||
for depth in [8, 16] {
|
||||
let output = fade(mode, depth, "mask", "smooth");
|
||||
for (i, expected) in MASK_ROW.into_iter().enumerate() {
|
||||
let x = 100 + 30 * i;
|
||||
assert!((output[x] - expected).abs() <= 2.0, "{mode} {depth}-bit, x={x}: {}, expected {expected}", output[x]);
|
||||
}
|
||||
assert!(output.windows(2).all(|w| w[0] <= w[1]));
|
||||
assert_eq!(output[50], 0.0);
|
||||
assert_eq!(output[750], 255.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_mask_fade_keeps_existing_pixel_deep_mask_and_other_method_curves() {
|
||||
let pixels = fade("rgb", 8, "pixels", "smooth");
|
||||
let deep_mask = fade("rgb", 32, "mask", "smooth");
|
||||
for (x, alpha) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] {
|
||||
assert!((pixels[x] - alpha).abs() <= 2.0, "pixel alpha at {x}: {}", pixels[x]);
|
||||
assert!((deep_mask[x] - (255.0 - alpha)).abs() <= 2.0, "float mask at {x}: {}", deep_mask[x]);
|
||||
}
|
||||
|
||||
for method in ["classic", "perceptual", "linear"] {
|
||||
let pixels = fade("rgb", 8, "pixels", method);
|
||||
let mask = fade("rgb", 8, "mask", method);
|
||||
for x in [50, 250, 400, 550, 750] {
|
||||
assert!((pixels[x] + mask[x] - 255.0).abs() <= 1.0, "{method} at {x}: pixel {}, mask {}", pixels[x], mask[x]);
|
||||
}
|
||||
}
|
||||
|
||||
let colors = json!([[0, "#000000"], [1, "#ffffff"]]);
|
||||
let opaque = row("rgb", 16, "mask", "smooth", colors.clone(), None);
|
||||
assert_eq!(opaque, row("rgb", 16, "mask", "smooth", colors, Some(json!([[0, 100], [1, 100]]))));
|
||||
assert_eq!((opaque[50], opaque[750]), (0.0, 255.0));
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use photocraft_algo::paint::{FillMode, GradientShape, paint_gradient};
|
||||
use photocraft_color::BlendMode;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Surface, from_rgba};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const SOURCE: [f32; 4] = [0.25, 0.5, 0.75, 1.0];
|
||||
|
||||
fn active_surface(s: &Session) -> &Surface {
|
||||
let state = s.active().unwrap();
|
||||
state.doc.layer(state.active_layer.unwrap()).unwrap().surface().unwrap()
|
||||
}
|
||||
|
||||
fn document(mode: &str, depth: u8) -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 16, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
|
||||
s.edit("Set the three backdrop alphas", |doc, _| {
|
||||
let surface = doc.layers[0].surface_mut().unwrap();
|
||||
let format = surface.format();
|
||||
for (x, alpha) in [(3, 1.0), (4, 0.0), (5, 0.5)] {
|
||||
surface.write_pixel(x, 3, &from_rgba(&format, [0.8, 0.3, 0.2, alpha]));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_uses_the_measured_half_opacity_step_only_on_deep_rgb_and_cmyk_pixels() {
|
||||
for (mode, depth, uses_step) in [("rgb", 8, false), ("rgb", 16, true), ("rgb", 32, true), ("cmyk", 8, false), ("cmyk", 16, true), ("gray", 16, false)] {
|
||||
for blend in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen] {
|
||||
for (percent, coverage) in [(50.0, if uses_step { 128.0 / 255.0 } else { 0.5 }), (23.5, 0.235)] {
|
||||
let mut s = document(mode, depth);
|
||||
let mut wanted = active_surface(&s).clone();
|
||||
paint_gradient(
|
||||
&mut wanted,
|
||||
Rect::new(0, 0, 16, 8),
|
||||
(2.0, 3.0),
|
||||
(9.0, 3.0),
|
||||
GradientShape::Linear,
|
||||
&[(0.0, SOURCE), (1.0, SOURCE)],
|
||||
false,
|
||||
coverage,
|
||||
FillMode::Blend(blend),
|
||||
false,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
s.execute(
|
||||
"paint.gradient",
|
||||
json!({"from": [2, 3], "to": [9, 3], "colors": [SOURCE, SOURCE], "opacity": percent, "mode": blend.label(), "dither": false}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let actual = active_surface(&s);
|
||||
for x in 3..=5 {
|
||||
assert_eq!(actual.pixel(x, 3), wanted.pixel(x, 3), "{mode} {depth}-bit, {blend:?}, {percent}%, x={x}");
|
||||
}
|
||||
if uses_step && percent == 50.0 {
|
||||
assert!((actual.rgba(4, 3)[3] - 128.0 / 255.0).abs() < 0.0005);
|
||||
assert!((actual.rgba(5, 3)[3] - (0.5 + 64.0 / 255.0)).abs() < 0.0005);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_explicit_classic_uses_the_half_opacity_step() {
|
||||
for (method, coverage) in [("Classic", 128.0 / 255.0), ("linear", 0.5), ("perceptual", 0.5), ("smooth", 0.5)] {
|
||||
let mut s = document("rgb", 32);
|
||||
s.execute("paint.gradient", json!({"from": [2, 3], "to": [9, 3], "colors": [SOURCE, SOURCE], "method": method, "opacity": 50, "dither": false}))
|
||||
.unwrap();
|
||||
let alpha = active_surface(&s).rgba(4, 3)[3];
|
||||
assert!((alpha - coverage).abs() < 0.0005, "{method}: alpha {alpha}, expected {coverage}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_half_opacity_pixel_step_does_not_change_layer_masks() {
|
||||
let mut s = document("rgb", 32);
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
s.execute("paint.gradient", json!({"from": [2, 3], "to": [9, 3], "colors": ["#000000", "#ffffff"], "opacity": 50, "target": "mask", "dither": false}))
|
||||
.unwrap();
|
||||
let state = s.active().unwrap();
|
||||
let mask = &state.doc.layer(state.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface;
|
||||
assert_eq!((mask.pixel(2, 3)[0] * 255.0).round(), 128.0);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Paint helpers: Paint Bucket and Gradient tool.
|
||||
|
||||
use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient};
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::{CommandSpec, parse_blend};
|
||||
@@ -172,7 +173,9 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Photoshop's interpolation (`method`, with `smoothness` 0..=100, default 100) baked into dense
|
||||
// stops, as for Gradient Overlay: Photoshop 27.11's Classic black → white is 0.037 at t = 1/16
|
||||
// where straight stops give 0.0625.
|
||||
let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) {
|
||||
let method_param = p.get("method");
|
||||
let method = method_param.and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name);
|
||||
let stops = match method {
|
||||
Some(m) if stops.len() >= 2 => {
|
||||
let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0);
|
||||
// Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by
|
||||
@@ -181,6 +184,16 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// were not measured in the Gradient tool and keep the merged stops.
|
||||
let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None };
|
||||
match split {
|
||||
Some(split)
|
||||
if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Mask
|
||||
&& s.active().is_some_and(|st| {
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
matches!(st.doc.mode, ColorMode::Rgb | ColorMode::Grayscale | ColorMode::Cmyk | ColorMode::Lab)
|
||||
&& matches!(st.doc.depth, SampleType::U8 | SampleType::U16)
|
||||
}) =>
|
||||
{
|
||||
smooth_split_stops_with(split, photocraft_io::gradient_bake::bake_smooth_mask_opacity)
|
||||
}
|
||||
Some(split) => smooth_split_stops(split),
|
||||
None => {
|
||||
let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect();
|
||||
@@ -200,15 +213,36 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reverse = b(p, "reverse", false);
|
||||
let opacity = opacity(p, "paint.gradient")?;
|
||||
let mode = fill_mode(p, "paint.gradient", false)?;
|
||||
let target = crate::channel_cmds::target_of(p);
|
||||
// Masks and channels have no transparency to paint behind: Behind would change nothing there.
|
||||
if mode == FillMode::Behind && crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels {
|
||||
if mode == FillMode::Behind && target != crate::channel_cmds::Target::Pixels {
|
||||
return Err(EngineError::BadParams { cmd: "paint.gradient".into(), msg: "mode `behind` paints only a layer's pixels, not a mask or channel".into() });
|
||||
}
|
||||
let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding).
|
||||
let layer = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|st| st.active_layer) };
|
||||
s.edit(step_name(p), |doc, _| {
|
||||
// At the measured Classic 50% setting, deep RGB and 16-bit CMYK pixels use 8-bit source coverage.
|
||||
let opacity = if target == crate::channel_cmds::Target::Pixels
|
||||
&& (method_param.is_none() || method == Some(photocraft_io::GradientMethod::Classic))
|
||||
&& p.get("opacity").and_then(Value::as_f64) == Some(50.0)
|
||||
&& matches!((doc.mode, doc.depth), (ColorMode::Rgb, SampleType::U16 | SampleType::F32) | (ColorMode::Cmyk, SampleType::U16))
|
||||
{
|
||||
128.0 / 255.0
|
||||
} else {
|
||||
opacity
|
||||
};
|
||||
let sel = doc.selection.clone();
|
||||
let area = sel.as_ref().map(|m| m.content_bounds()).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()).intersect(&doc.bounds());
|
||||
// The RGB 8- and 16-bit layer mask uses Normal for modes that need a colour backdrop.
|
||||
let mode = if matches!(mode, FillMode::Blend(blend) if !blend.is_separable())
|
||||
&& crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Mask
|
||||
&& doc.mode == photocraft_color::ColorMode::Rgb
|
||||
&& matches!(doc.depth, photocraft_color::SampleType::U8 | photocraft_color::SampleType::U16)
|
||||
{
|
||||
FillMode::Blend(photocraft_color::BlendMode::Normal)
|
||||
} else {
|
||||
mode
|
||||
};
|
||||
let (surf, lock) = crate::channel_cmds::target_surface(doc, layer, p)?;
|
||||
paint_gradient(surf, area, from, to, shape, &stops, reverse, opacity, mode, dither, sel.as_ref(), lock);
|
||||
Ok(())
|
||||
@@ -234,7 +268,11 @@ pub(crate) const GRADIENT_MASK_STEP: &str = "Draw gradient on mask";
|
||||
/// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut
|
||||
/// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for
|
||||
/// every pixel. Positions that differ still go through `apply_opacity`.
|
||||
pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops {
|
||||
pub(crate) fn smooth_split_stops(stops: gradients::FillStops) -> gradients::Stops {
|
||||
smooth_split_stops_with(stops, photocraft_io::bake_gradient_smooth_opacity)
|
||||
}
|
||||
|
||||
fn smooth_split_stops_with((cs, os): gradients::FillStops, bake_opacity: impl FnOnce(Vec<(f32, f32)>, &[f32]) -> Vec<(f32, f32)>) -> gradients::Stops {
|
||||
let mids = vec![0.5; cs.len().saturating_sub(1)];
|
||||
let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth)
|
||||
.into_iter()
|
||||
@@ -244,7 +282,7 @@ pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::S
|
||||
})
|
||||
.collect();
|
||||
let omids = vec![0.5; os.len().saturating_sub(1)];
|
||||
let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids);
|
||||
let opacity = bake_opacity(os, &omids);
|
||||
if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) {
|
||||
return gradients::apply_opacity(colours, &opacity);
|
||||
}
|
||||
@@ -317,11 +355,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_mask_greyed_modes_tests.rs"]
|
||||
mod gradient_mask_greyed_modes_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_no_op_history_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_bitmap_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_mask_smooth_transparency_tests.rs"]
|
||||
mod gradient_mask_smooth_transparency_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bucket_behind_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_opacity_step_tests.rs"]
|
||||
mod gradient_opacity_step_tests;
|
||||
@@ -366,19 +366,35 @@ const SMOOTH_OPACITY_GAMMA: f32 = 2.2;
|
||||
/// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it.
|
||||
/// Constant opacity comes back as it is, clamped to 0..=1.
|
||||
pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> {
|
||||
bake_smooth_opacity_with(stops, midpoints, |o| o.powf(SMOOTH_OPACITY_GAMMA).cbrt(), |l| l.powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA))
|
||||
}
|
||||
|
||||
/// Smooth's opacity response for the Gradient tool on an 8- or 16-bit layer mask. The same
|
||||
/// Smooth easing with a lightness response of `L^1.75` fits the measured mask fade (#18670).
|
||||
pub fn bake_smooth_mask_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> {
|
||||
const MASK_POWER: f32 = 1.75;
|
||||
bake_smooth_opacity_with(stops, midpoints, |o| o.powf(1.0 / MASK_POWER), |l| l.powf(MASK_POWER))
|
||||
}
|
||||
|
||||
fn bake_smooth_opacity_with(
|
||||
stops: Vec<(f32, f32)>,
|
||||
midpoints: &[f32],
|
||||
to_lightness: impl Fn(f32) -> f32,
|
||||
from_lightness: impl Fn(f32) -> f32,
|
||||
) -> Vec<(f32, f32)> {
|
||||
let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 };
|
||||
if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) {
|
||||
return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect();
|
||||
}
|
||||
let mut s = stops;
|
||||
s.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect();
|
||||
let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [to_lightness(clamp(*o)); 3])).collect();
|
||||
const N: usize = 96;
|
||||
let mut baked: Vec<(f32, f32)> = (0..=N)
|
||||
.map(|k| {
|
||||
let t = k as f32 / N as f32;
|
||||
let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0];
|
||||
(t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 })
|
||||
(t, if l.is_finite() { from_lightness(l.clamp(0.0, 1.0)) } else { 1.0 })
|
||||
})
|
||||
.collect();
|
||||
baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
use egui::{Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
use super::tests::{app_harness, tap};
|
||||
use crate::{PhotocraftApp, Services};
|
||||
|
||||
type AppHarness = Harness<'static, Box<PhotocraftApp>>;
|
||||
|
||||
fn quick_mask(h: &AppHarness) -> bool {
|
||||
h.state().session.active().unwrap().doc.quick_mask.is_some()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mask_shortcut_waits_for_free_transform_to_finish() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 120, "height": 100})).unwrap();
|
||||
app.run("select.rect", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap();
|
||||
let mut h = app_harness(app);
|
||||
|
||||
for (starts_in_quick_mask, finish) in [(false, Key::Enter), (true, Key::Escape)] {
|
||||
assert_eq!(quick_mask(&h), starts_in_quick_mask);
|
||||
tap(&mut h, Key::T, Modifiers::COMMAND);
|
||||
let transform = h.state().ui.transform.as_ref().expect("Free Transform opens from its shortcut").id;
|
||||
|
||||
tap(&mut h, Key::Q, Modifiers::NONE);
|
||||
assert_eq!(quick_mask(&h), starts_in_quick_mask, "Q keeps Quick Mask unchanged while Free Transform is live");
|
||||
assert_eq!(h.state().ui.transform.as_ref().map(|t| t.id), Some(transform), "the same Free Transform stays live");
|
||||
|
||||
tap(&mut h, finish, Modifiers::NONE);
|
||||
assert!(h.state().ui.transform.is_none(), "Enter and Escape close Free Transform");
|
||||
tap(&mut h, Key::Q, Modifiers::NONE);
|
||||
assert_eq!(quick_mask(&h), !starts_in_quick_mask, "Q toggles again when the transform is closed");
|
||||
}
|
||||
}
|
||||
@@ -702,6 +702,17 @@ fn pick_tool(app: &mut PhotocraftApp, letter: char, step: PickStep, plain: bool,
|
||||
/// through [`dispatch_as`].
|
||||
fn run_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Fired) {
|
||||
let id = f.command.id.as_str();
|
||||
if f.source == FireSource::Key
|
||||
&& id == crate::panels::QUICK_MASK
|
||||
&& app.ui.transform.as_ref().is_some_and(|transform| {
|
||||
!transform.selection
|
||||
&& transform.content_aware.is_none()
|
||||
&& transform.session.warp().is_none()
|
||||
&& transform.session.current_mode() == craft::behavior::geometry::TransformMode::Free
|
||||
})
|
||||
{
|
||||
return;
|
||||
}
|
||||
// The Magnetic Lasso's bracket keys step its detection width, not the brush (#11688), until an outline is open.
|
||||
if app.ui.tool == Tool::MagneticLasso && !app.canvas_tools.selection.outline_open() {
|
||||
let step = match id {
|
||||
@@ -828,3 +839,7 @@ fn record(ctx: &egui::Context, id: &str, outcome: Outcome) {
|
||||
/// The whole-app key harness the key tests of this module share (`app_harness`, `tap`).
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "quick_mask_free_transform_tests.rs"]
|
||||
mod quick_mask_free_transform_tests;
|
||||
@@ -138,6 +138,10 @@ fn find<'a>(rows: &'a mut [Row], id: &str) -> Option<&'a mut Row> {
|
||||
/// A live row shows the chord the runtime's keymap runs its command for (`commands::chord`: overrides included, a
|
||||
/// key another command wins left out); a catalogue row shows its text.
|
||||
fn shortcut_of(app: &PhotocraftApp, id: &str, catalogue: Option<&str>) -> Option<Chord> {
|
||||
// Quick Mask has a key binding without a hint in the Select menu.
|
||||
if id == crate::panels::QUICK_MASK {
|
||||
return None;
|
||||
}
|
||||
if is_live(id) {
|
||||
return craft::ui::runtime::commands::chord(app.ctx(), &crate::shortcut_dispatch::keymap_command(id));
|
||||
}
|
||||
@@ -473,3 +477,7 @@ fn build(app: &PhotocraftApp) -> Built {
|
||||
#[cfg(test)]
|
||||
#[path = "background_entry_swap_tests.rs"]
|
||||
mod background_entry_swap_tests;
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
#[path = "quick_mask_shortcut_text_tests.rs"]
|
||||
mod quick_mask_shortcut_text_tests;
|
||||
@@ -0,0 +1,44 @@
|
||||
use egui::{Key, Modifiers};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::control::{ControlRequest, Reply};
|
||||
use crate::input::shortcut_dispatch::tests::{app_harness, tap};
|
||||
use crate::panels::QUICK_MASK;
|
||||
use crate::{PhotocraftApp, Services};
|
||||
|
||||
fn quick_mask_menu_row(app: &mut PhotocraftApp) -> Option<Value> {
|
||||
let ctx = app.ctx().clone();
|
||||
let (request, _reply) = ControlRequest::new("ui.menu.list", json!({}));
|
||||
let Reply::Done(reply) = crate::control::handle(app, &ctx, &request) else { return None };
|
||||
reply["result"].as_array()?.iter().find(|row| row["id"] == QUICK_MASK && row["path"] == json!(["Select"])).cloned()
|
||||
}
|
||||
|
||||
fn quick_mask(app: &PhotocraftApp) -> bool {
|
||||
app.session.active().is_some_and(|state| state.doc.quick_mask.is_some())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mask_menu_omits_the_hint_while_q_still_toggles_after_a_shortcut_reset() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
|
||||
let mut h = app_harness(app);
|
||||
let row = quick_mask_menu_row(h.state_mut()).expect("Quick Mask stays in the Select menu");
|
||||
assert!(row["shortcut"].is_null(), "the Select menu does not show a Quick Mask shortcut: {row}");
|
||||
|
||||
tap(&mut h, Key::Q, Modifiers::NONE);
|
||||
assert!(quick_mask(h.state()), "Q is bound by default");
|
||||
tap(&mut h, Key::Q, Modifiers::NONE);
|
||||
assert!(!quick_mask(h.state()));
|
||||
|
||||
h.state_mut().run("edit.keyboardShortcuts", json!({"set": {(QUICK_MASK): ""}})).unwrap();
|
||||
h.run_steps(2);
|
||||
tap(&mut h, Key::Q, Modifiers::NONE);
|
||||
assert!(!quick_mask(h.state()), "the user can remove Q");
|
||||
|
||||
h.state_mut().run("edit.keyboardShortcuts", json!({"reset": true})).unwrap();
|
||||
h.run_steps(2);
|
||||
tap(&mut h, Key::Q, Modifiers::NONE);
|
||||
assert!(quick_mask(h.state()), "reset restores Q");
|
||||
let row = quick_mask_menu_row(h.state_mut()).expect("Quick Mask stays in the Select menu");
|
||||
assert!(row["shortcut"].is_null(), "the Select menu does not show a Quick Mask shortcut: {row}");
|
||||
}
|
||||
Reference in new issue
Block a user