Merge #15990 into the merge queue batch

Fill and Stroke grey the modes the document can't use (#14647)
This commit is contained in:
David Mann committed 2026-11-25 13:28:25 +01:00
commit b8eea8463d
12 files changed
+253 -31

No files matched your search

+3
View File
@@ -169,6 +169,9 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
};
let location = p.get("location").and_then(Value::as_str).unwrap_or("center").to_string();
let id = layer_param(s, p)?;
if let Some(st) = s.active() {
crate::pixel_fill::check_mode_available("edit.stroke", &st.doc, mode)?;
}
// Stroke keeps its layer behavior for channel views; an explicit mask edits that mask.
let pixels = Value::Null;
let target = if crate::commands::is_mask_target(p) { p } else { &pixels };
+30 -1
View File
@@ -1,12 +1,41 @@
//! Filling and blending pixels into a surface: Edit › Fill's compositing, which Edit › Clear,
//! Edit › Stroke, pastes into masks and channels, a floating selection and the painting tools share.
use photocraft_color::BlendMode;
use photocraft_color::{BlendMode, ColorMode, SampleType};
use photocraft_doc::Document;
use photocraft_geom::{Rect, TILE_SIZE};
use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use crate::{EngineError, Result};
/// The blend modes the reference application greys in its Fill, Stroke and Fade Mode lists for a document of `mode`
/// at `depth` (#13806, #14647). Combinations it wasn't measured in (Grayscale 16/32, Lab 16, CMYK 16, Multichannel,
/// Duotone…) grey none.
pub fn greyed_modes(mode: ColorMode, depth: SampleType) -> &'static [BlendMode] {
use BlendMode::*;
match (mode, depth) {
(ColorMode::Grayscale, SampleType::U8) => &[DarkerColor, LighterColor, Hue, Saturation, Color, Luminosity],
(ColorMode::Lab, SampleType::U8) => &[Darken, ColorBurn, Lighten, ColorDodge, Difference, Exclusion, Subtract, Divide],
(ColorMode::Rgb, SampleType::F32) => {
&[ColorBurn, LinearBurn, Screen, ColorDodge, Overlay, SoftLight, HardLight, VividLight, LinearLight, PinLight, HardMix, Exclusion]
}
_ => &[],
}
}
/// An error for `cmd` when `blend` is one of [`greyed_modes`] for `doc`: the dialogs never offer it there.
pub fn check_mode_available(cmd: &str, doc: &Document, blend: BlendMode) -> Result<()> {
if !greyed_modes(doc.mode, doc.depth).contains(&blend) {
return Ok(());
}
let model = match doc.mode {
ColorMode::Rgb => "RGB".to_string(),
ColorMode::Cmyk => "CMYK".to_string(),
other => format!("{other:?}"),
};
Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("{} is not available in {model} {}-bit documents", blend.label(), doc.depth.bits()) })
}
/// What a pixel of the filled area gets before blending.
pub enum Source {
Color([f32; 4]),
+6 -1
View File
@@ -16,7 +16,8 @@ use serde_json::{Value, json};
use crate::commands::{cmyk_param, color_param, layer_param, parse_blend};
use crate::content_sampling::{content_aware, content_aware_options};
use crate::pixel_fill::{Blend, Source, blend_into, read_rgba};
pub use crate::pixel_fill::greyed_modes;
use crate::pixel_fill::{Blend, Source, blend_into, check_mode_available, read_rgba};
use crate::{EngineError, Result, Session};
const CMD: &str = "edit.fill";
@@ -75,6 +76,7 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
let channel = crate::channel_cmds::is_channel_target(p);
let id = if channel { None } else { Some(layer_param(s, p)?) };
let st = s.active().ok_or(EngineError::NoDocument)?;
check_mode_available(CMD, &st.doc, mode)?;
let doc_bounds = st.doc.bounds();
let sel = st.doc.selection.clone();
let area = sel.as_ref().map_or(doc_bounds, |m| m.content_bounds().intersect(&doc_bounds));
@@ -160,3 +162,6 @@ fn color_source(s: &Session, c: [f32; 4], role: usize) -> Source {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod mode_by_document_tests;
@@ -0,0 +1,111 @@
//! #14647: Edit › Fill and Edit › Stroke refuse the blend modes the reference application greys in their Mode lists
//! for the document's colour mode and depth (Grayscale 8-bit, Lab 8-bit, RGB 32-bit), and keep every mode elsewhere.
use super::*;
use serde_json::json;
/// A white 16×12 document of `mode` at `depth` bits.
fn session(mode: &str, depth: u32) -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 16, "height": 12, "mode": mode, "depth": depth, "background": "white"})).unwrap();
s
}
fn labels(modes: &[BlendMode]) -> Vec<&'static str> {
modes.iter().map(|m| m.label()).collect()
}
/// The measured cases: (colour mode, depth, the greyed modes).
const MEASURED: [(&str, u32, &[&str]); 5] = [
("grayscale", 8, &["Darker Color", "Lighter Color", "Hue", "Saturation", "Color", "Luminosity"]),
("lab", 8, &["Darken", "Color Burn", "Lighten", "Color Dodge", "Difference", "Exclusion", "Subtract", "Divide"]),
(
"rgb",
32,
&[
"Color Burn",
"Linear Burn",
"Screen",
"Color Dodge",
"Overlay",
"Soft Light",
"Hard Light",
"Vivid Light",
"Linear Light",
"Pin Light",
"Hard Mix",
"Exclusion",
],
),
("rgb", 16, &[]),
("cmyk", 8, &[]),
];
/// Cases not measured: nothing greyed, as before.
const NOT_MEASURED: [(&str, u32); 4] = [("grayscale", 16), ("lab", 16), ("cmyk", 16), ("rgb", 8)];
#[test]
fn the_greyed_modes_follow_the_measured_colour_modes_and_depths() {
for (mode, depth, want) in MEASURED {
let s = session(mode, depth);
let doc = &s.active().unwrap().doc;
assert_eq!(labels(greyed_modes(doc.mode, doc.depth)), want, "{mode} {depth}");
}
for (mode, depth) in NOT_MEASURED {
let s = session(mode, depth);
let doc = &s.active().unwrap().doc;
assert!(greyed_modes(doc.mode, doc.depth).is_empty(), "{mode} {depth}");
}
}
/// Runs `cmd` with `mode` and reports whether it ran; a refusal leaves no history step and no pixel change.
fn runs(s: &mut Session, cmd: &str, mode: BlendMode) -> bool {
let params = match cmd {
"edit.fill" => json!({"contents": "color", "color": "#336699", "mode": mode.key(), "opacity": 50}),
_ => json!({"width": 2, "color": "#336699", "location": "inside", "mode": mode.key(), "opacity": 50}),
};
let before = s.active().unwrap().history.past_len();
match s.execute(cmd, params) {
Ok(_) => true,
Err(e) => {
assert!(matches!(&e, EngineError::BadParams { cmd: c, msg } if c == cmd && msg.contains(mode.label())), "{cmd} {}: {e}", mode.label());
assert_eq!(s.active().unwrap().history.past_len(), before, "{cmd} {}: a refusal records no step", mode.label());
false
}
}
}
#[test]
fn fill_and_stroke_refuse_a_greyed_mode_and_take_every_other() {
for cmd in ["edit.fill", "edit.stroke"] {
for (mode, depth, greyed) in MEASURED {
for blend in BlendMode::LAYER_MODES {
let mut s = session(mode, depth);
s.execute("select.all", json!({})).unwrap();
assert_eq!(runs(&mut s, cmd, blend), !greyed.contains(&blend.label()), "{cmd} in {mode} {depth}: {}", blend.label());
}
}
}
}
#[test]
fn the_cases_not_measured_keep_every_mode() {
for cmd in ["edit.fill", "edit.stroke"] {
for (mode, depth) in NOT_MEASURED {
for blend in BlendMode::LAYER_MODES {
let mut s = session(mode, depth);
s.execute("select.all", json!({})).unwrap();
assert!(runs(&mut s, cmd, blend), "{cmd} in {mode} {depth}: {}", blend.label());
}
}
}
}
/// The default mode, Normal, is never greyed, so a Fill without `mode` still runs everywhere.
#[test]
fn a_fill_without_a_mode_runs_in_every_measured_document() {
for (mode, depth, _) in MEASURED {
let mut s = session(mode, depth);
s.execute("edit.fill", json!({"contents": "black"})).unwrap();
}
}
+17 -3
View File
@@ -1,11 +1,14 @@
//! The Blending rows that Fill, Stroke and the Smart Filter Blending Options dialog share: the mode list is the
//! Layers panel's, so a mode has one key and one shortcut everywhere.
//! Layers panel's, so a mode has one key and one shortcut everywhere. Fill, Stroke and Fade grey the modes the active
//! document's colour mode and depth can't use (#13806, #14647).
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind};
use craft::ui::runtime::env::Label;
use photocraft_color::BlendMode;
use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
/// A blend-mode row `key` over the Layers panel's mode list (`group` adds Pass Through), opening on `current`.
pub(crate) fn blend_param(key: &str, label: impl Into<Label>, group: bool, current: BlendMode) -> Param {
let modes = crate::panels::blend_options(group, current)
@@ -15,16 +18,24 @@ pub(crate) fn blend_param(key: &str, label: impl Into<Label>, group: bool, curre
Param::new(key, label, ParamKind::blend(modes, Some(current.key().to_string())))
}
/// A Mode row `"mode"`, labelled `label`, opening on Normal, with the modes the active document can't use greyed
/// (listed, never chosen). A remembered mode that is greyed opens as Normal: the framework drops a saved value that
/// names a disabled option.
pub(crate) fn document_mode_param(app: &PhotocraftApp, label: impl Into<Label>) -> Param {
let greyed = app.session.active().map_or(&[][..], |st| photocraft_engine::fill_cmds::greyed_modes(st.doc.mode, st.doc.depth));
blend_param("mode", label, false, BlendMode::Normal).disabled_options(greyed.iter().map(|m| m.key().to_string()))
}
/// The mode a blend row `key` holds; Normal when the field is missing or unreadable.
pub(crate) fn blend_mode(fields: &DialogFields, key: &str) -> BlendMode {
fields.text(key).and_then(photocraft_engine::commands::parse_blend).unwrap_or(BlendMode::Normal)
}
/// The Blending section, Mode, Opacity (percent) and Preserve Transparency: the rows Fill and Stroke share.
pub(crate) fn blending_rows() -> Vec<Param> {
pub(crate) fn blending_rows(app: &PhotocraftApp) -> Vec<Param> {
vec![
Param::section(tl!("Blending")),
blend_param("mode", tl!("Mode:"), false, BlendMode::Normal),
document_mode_param(app, tl!("Mode:")),
super::new_layer_ui::opacity_param(),
Param::new("preserveTransparency", tl!("Preserve Transparency"), ParamKind::bool(false)),
]
@@ -44,3 +55,6 @@ pub(crate) fn blending_params(fields: &DialogFields) -> Map<String, Value> {
}
p
}
#[cfg(test)]
mod document_modes_tests;
@@ -0,0 +1,74 @@
//! #14647: the Mode row that Edit › Fill and Edit › Stroke share greys the modes the active document's colour mode and
//! depth can't use, and a remembered mode that is greyed there opens as Normal.
use craft::ui::patterns::form_dialogs::{DialogFields, ParamDialog, ParamKind};
use photocraft_color::BlendMode;
use serde_json::json;
use super::blending_rows;
use crate::PhotocraftApp;
fn app(mode: &str, depth: u32) -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 16, "height": 12, "mode": mode, "depth": depth})).unwrap();
app
}
/// The labels of the Mode row's disabled entries in the Fill and Stroke rows of `app`.
fn greyed(app: &PhotocraftApp) -> Vec<&'static str> {
let rows = blending_rows(app);
let row = rows.iter().find(|p| p.key == "mode").unwrap();
let ParamKind::Blend { modes, .. } = &row.kind else { panic!("Mode is a blend row") };
assert_eq!(modes.len(), BlendMode::LAYER_MODES.len(), "every mode stays listed");
BlendMode::LAYER_MODES.iter().filter(|m| !row.option_enabled(m.key())).map(|m| m.label()).collect()
}
#[test]
fn the_mode_row_greys_what_the_document_cannot_use() {
let cases: [(&str, u32, &[&str]); 6] = [
("grayscale", 8, &["Darker Color", "Lighter Color", "Hue", "Saturation", "Color", "Luminosity"]),
("lab", 8, &["Darken", "Color Burn", "Lighten", "Color Dodge", "Difference", "Exclusion", "Subtract", "Divide"]),
(
"rgb",
32,
&[
"Color Burn",
"Linear Burn",
"Screen",
"Color Dodge",
"Overlay",
"Soft Light",
"Hard Light",
"Vivid Light",
"Linear Light",
"Pin Light",
"Hard Mix",
"Exclusion",
],
),
("rgb", 16, &[]),
("cmyk", 8, &[]),
("rgb", 8, &[]),
];
for (mode, depth, want) in cases {
assert_eq!(greyed(&app(mode, depth)), want, "{mode} {depth}");
}
}
#[test]
fn without_a_document_nothing_is_greyed() {
let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
assert!(greyed(&app).is_empty());
}
/// The framework restores only the remembered values a row accepts, so a greyed mode is dropped and the row opens on
/// its default, Normal; a mode the document can use is kept.
#[test]
fn a_remembered_greyed_mode_opens_as_normal() {
let mut saved = DialogFields::new();
saved.set("mode", BlendMode::Darken.key().to_string());
let lab = ParamDialog::remembered(&blending_rows(&app("lab", 8)), &saved);
assert_eq!(lab.text("mode"), None, "Darken is greyed in Lab 8-bit");
let rgb = ParamDialog::remembered(&blending_rows(&app("rgb", 16)), &saved);
assert_eq!(rgb.text("mode"), Some(BlendMode::Darken.key()), "Darken stays in RGB 16-bit");
}
@@ -4,9 +4,10 @@
use craft::ui::patterns::form_dialogs::{Param, ParamKind};
use craft::ui::runtime::env::Label;
use photocraft_color::{BlendMode, ColorMode, SampleType};
use photocraft_engine::fill_cmds::greyed_modes as greyed;
use serde_json::json;
use super::{COMMAND, greyed, param};
use super::{COMMAND, param};
use crate::PhotocraftApp;
/// The reference application's Fade Mode list, a group per row.
+1 -17
View File
@@ -4,30 +4,14 @@
use craft::ui::patterns::form_dialogs::Param;
use craft::ui::runtime::env::Label;
use photocraft_color::{BlendMode, ColorMode, SampleType};
use crate::PhotocraftApp;
pub(crate) const COMMAND: &str = "edit.fade";
/// The modes the reference application greys in its Fade dialog for a document of `mode` at `depth`. Combinations it
/// wasn't measured in (Grayscale 16/32, Lab 16, CMYK 16, Multichannel, Duotone…) grey none.
pub(crate) fn greyed(mode: ColorMode, depth: SampleType) -> &'static [BlendMode] {
use BlendMode::*;
match (mode, depth) {
(ColorMode::Grayscale, SampleType::U8) => &[DarkerColor, LighterColor, Hue, Saturation, Color, Luminosity],
(ColorMode::Lab, SampleType::U8) => &[Darken, ColorBurn, Lighten, ColorDodge, Difference, Exclusion, Subtract, Divide],
(ColorMode::Rgb, SampleType::F32) => {
&[ColorBurn, LinearBurn, Screen, ColorDodge, Overlay, SoftLight, HardLight, VividLight, LinearLight, PinLight, HardMix, Exclusion]
}
_ => &[],
}
}
/// The Mode row of the Fade dialog, labelled `label`: the blend list with the active document's greyed modes disabled.
pub(crate) fn param(app: &PhotocraftApp, label: Label) -> Param {
let greyed = app.session.active().map_or(&[][..], |st| greyed(st.doc.mode, st.doc.depth));
super::blend_options::blend_param("mode", label, false, BlendMode::Normal).disabled_options(greyed.iter().map(|m| (*m).key().to_string()))
super::blend_options::document_mode_param(app, label)
}
#[cfg(test)]
+3 -3
View File
@@ -41,7 +41,7 @@ pub(crate) fn hex(c: [f32; 3]) -> String {
}
/// The dialog's rows.
fn rows(foreground: [f32; 3], first_pattern: Option<String>) -> Vec<Param> {
fn rows(app: &PhotocraftApp, foreground: [f32; 3], first_pattern: Option<String>) -> Vec<Param> {
let contents = CONTENTS.iter().map(|(k, l)| (k.to_string(), Label::from(tl!(l)))).collect();
let mut rows = vec![
Param::new("contents", tl!("Contents:"), ParamKind::choice(contents, Some("foreground".into()))),
@@ -49,7 +49,7 @@ fn rows(foreground: [f32; 3], first_pattern: Option<String>) -> Vec<Param> {
Param::new("pattern", tl!("Custom Pattern:"), ParamKind::pattern(first_pattern)).visible_when("contents", "pattern"),
Param::new("colorAdaptation", tl!("Color Adaptation"), ParamKind::bool(true)).visible_when("contents", "contentAware"),
];
rows.extend(blending_rows());
rows.extend(blending_rows(app));
rows
}
@@ -85,7 +85,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId {
let [r, g, b, _] = app.session.tools.foreground;
let first = app.session.patterns.items.first().map(|p| p.id.clone());
let patterns = crate::panels::preset_browser::pattern_swatches(app);
let rows = rows([r, g, b], first.clone());
let rows = rows(app, [r, g, b], first.clone());
let inks = crate::color_picker_ui::ink_value(craft::theme::Srgba::rgb(r, g, b), app.session.tools.picked_role_cmyk(0));
let reset = defaults([r, g, b], first, app.session.tools.picked_role_cmyk(0));
let mut fields = DialogFields::new();
+2 -1
View File
@@ -314,10 +314,11 @@ fn reset_fill_restores_the_original_native_inks_for_the_same_rgb() {
use std::{cell::RefCell, rc::Rc};
let original = [0., 0., 0., 1.];
let reset = defaults([0.; 3], None, Some(original));
let rows = rows(&app(), [0.; 3], None);
let fields = Rc::new(RefCell::new(reset.clone()));
let shown = fields.clone();
let mut fixture = Fixture::new(move |ui| {
ParamDialog::new(COMMAND, "Fill", rows([0.; 3], None)).values(Bind::bound(&mut *shown.borrow_mut())).reset_to(reset.clone()).show(ui);
ParamDialog::new(COMMAND, "Fill", rows.clone()).values(Bind::bound(&mut *shown.borrow_mut())).reset_to(reset.clone()).show(ui);
});
fixture.settle();
fields.borrow_mut().set("contents", "color");
+3 -3
View File
@@ -21,14 +21,14 @@ const REMEMBER: &str = "photocraft.dialog.edit.stroke";
const LOCATIONS: [(&str, &str); 3] = [("inside", "Inside"), ("center", "Center"), ("outside", "Outside")];
/// The dialog's rows.
fn rows(foreground: [f32; 3]) -> Vec<Param> {
fn rows(app: &PhotocraftApp, foreground: [f32; 3]) -> Vec<Param> {
let locations = LOCATIONS.iter().map(|(k, l)| (k.to_string(), Label::from(tl!(l)))).collect();
let mut rows = vec![
Param::new("width", tl!("Width:"), ParamKind::number(Some(1.0), Some(250.0), 1.0, 1.0, 0)).unit(UnitKind::Pixels),
Param::new("color", tl!("Color:"), ParamKind::color(Some(foreground))),
Param::new("location", tl!("Location:"), ParamKind::radio(locations, Some("center".into()))),
];
rows.extend(blending_rows());
rows.extend(blending_rows(app));
rows
}
@@ -42,7 +42,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId {
held["layer"] = json!(st.active_layer);
}
let [r, g, b, _] = app.session.tools.foreground;
let rows = rows([r, g, b]);
let rows = rows(app, [r, g, b]);
let title = Label::from(tl!("Stroke"));
open_param(app, COMMAND, DialogFields::new(), held, move |fields| {
ParamDialog::new(COMMAND, title.clone(), Cow::Owned(rows.clone())).values(Bind::bound(fields)).remember(SaveKey::named(REMEMBER))
@@ -159,7 +159,7 @@ fn stroke_choices_apply_on_confirm_and_cancel_does_not_modify_document() {
/// #15539: Width shows px and Opacity % after their numbers.
#[test]
fn width_and_opacity_declare_their_units() {
let rows = rows([0.0, 0.0, 0.0]);
let rows = rows(&app(), [0.0, 0.0, 0.0]);
let unit = |key: &str| rows.iter().find(|p| p.key == key).and_then(|p| p.unit);
assert_eq!(unit("width"), Some(UnitKind::Pixels));
assert_eq!(unit("opacity"), Some(UnitKind::Percent));