Cache legacy blend mode parsing

This commit is contained in:
FredApps committed 2026-11-19 13:06:09 +01:00
1 parent 5e6b4c0945
commit 19641af171
42 files changed
+108 -99

No files matched your search

+36
View File
@@ -46,6 +46,23 @@ pub enum BlendMode {
PaintNetColorDodge,
}
/// Parse legacy command names and labels, retaining their case and punctuation tolerance.
pub fn parse_blend(s: &str) -> Option<BlendMode> {
fn normalize(value: &str) -> String {
value.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "")
}
static ALIASES: std::sync::OnceLock<std::collections::HashMap<String, BlendMode>> = std::sync::OnceLock::new();
let aliases = ALIASES.get_or_init(|| {
let mut aliases = std::collections::HashMap::new();
for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) {
aliases.entry(normalize(mode.label())).or_insert(mode);
aliases.entry(normalize(&format!("{mode:?}"))).or_insert(mode);
}
aliases
});
aliases.get(&normalize(s)).copied()
}
impl BlendMode {
/// Stable key used by the Layers panel.
pub fn key(self) -> &'static str {
@@ -674,6 +691,25 @@ mod tests;
mod key_tests {
use super::BlendMode;
#[test]
fn parser_preserves_legacy_names_and_normalization() {
let normalize = |s: &str| s.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "");
let legacy = |s: &str| {
let wanted = normalize(s);
std::iter::once(BlendMode::PassThrough)
.chain(BlendMode::layer_modes())
.find(|mode| normalize(mode.label()) == wanted || normalize(&format!("{mode:?}")) == wanted)
};
for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) {
for name in [mode.label().to_owned(), format!("{mode:?}"), mode.label().to_ascii_uppercase().replace(' ', "_-")] {
assert_eq!(super::parse_blend(&name), legacy(&name), "{name}");
}
}
for name in ["", "not a mode", "color.burn", "é"] {
assert_eq!(super::parse_blend(name), legacy(name), "{name}");
}
}
#[test]
fn canonical_keys_match_legacy_panel_names_and_round_trip() {
for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) {
+4 -4
View File
@@ -1,6 +1,6 @@
//! The command registry. Ids follow Photoshop's menu structure (see the parity checklist).
use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
use photocraft_color::{Color, ColorMode, SampleType};
use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId, LayerMask, Size};
use photocraft_geom::{Rect, TILE_SIZE};
use photocraft_raster::Surface;
@@ -189,13 +189,13 @@ use adjust_params::{adjust_mode, destructive_adjust, doc_mode, new_adjustment};
pub use adjust_params::{adjustment_from_params, adjustment_kind};
pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface};
use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_or_channel, has_selection};
pub use layer_params::blend_from_str;
pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask};
pub(crate) use layer_references::{recorded_drop, recorded_layer};
use ops::{arrange, merge_group, move_mask, set_mask, set_mask_and_deselect};
pub(crate) use ops::{layer_copy, translate_layer, translate_layer_wrapped};
use params::{bad, set_clipped};
pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param};
pub use photocraft_color::blend::parse_blend;
pub fn command_specs() -> &'static [CommandSpec] {
&registry().specs
@@ -726,7 +726,7 @@ fn build() -> Vec<CommandSpec> {
// The Background has no opacity, fill or blend mode: like Photoshop, setting
// one that changes its look turns it into a normal layer ("Layer 0") first.
let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0);
let blends = p.get("blend").and_then(Value::as_str).and_then(blend_from_str).is_some_and(|b| b != photocraft_color::BlendMode::Normal);
let blends = p.get("blend").and_then(Value::as_str).and_then(parse_blend).is_some_and(|b| b != photocraft_color::BlendMode::Normal);
for &id in &ids {
if num("opacity") || num("fill") || blends {
crate::extra_cmds::background_to_layer(doc, id);
@@ -745,7 +745,7 @@ fn build() -> Vec<CommandSpec> {
l.fill_opacity = v;
}
if let Some(v) = p.get("blend").and_then(Value::as_str) {
let b = blend_from_str(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?;
let b = parse_blend(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?;
// Pass Through is a group's mode only, as in Photoshop.
if b == photocraft_color::BlendMode::PassThrough && !l.is_group() {
return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0)));
+1 -1
View File
@@ -24,7 +24,7 @@ pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &
None | Some(Value::Null) => BlendMode::Normal,
Some(v) => {
let m = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name".into()))?;
crate::commands::blend_from_str(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))?
crate::commands::parse_blend(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))?
}
};
let clip = match p.get("clipToPrevious") {
+1 -1
View File
@@ -892,7 +892,7 @@ fn adjustment_layer_to(id: &str, p: &Value) -> Option<Descriptor> {
None | Some(Value::Null) => None,
Some(v) => {
let label = v.as_str()?;
if crate::commands::blend_from_str(label)? == photocraft_doc::BlendMode::PassThrough {
if crate::commands::parse_blend(label)? == photocraft_doc::BlendMode::PassThrough {
return None;
}
Some(blend_ps(label)?)
+1 -1
View File
@@ -56,7 +56,7 @@ pub(super) fn blend_label(ps: &str) -> Option<&'static str> {
}
pub(super) fn blend_ps(label: &str) -> Option<&'static str> {
crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k)
crate::commands::parse_blend(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::parse_blend(v) == Some(m))).map(|(k, _)| *k)
}
/// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding.
+1 -1
View File
@@ -448,7 +448,7 @@ fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings {
} else if p.get("mode").and_then(Value::as_str).is_some_and(|m| m.eq_ignore_ascii_case("behind")) {
b.mode = photocraft_color::BlendMode::Normal;
b.behind = true;
} else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::blend_from_str) {
} else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::parse_blend) {
b.mode = m;
b.behind = false;
}
+1 -1
View File
@@ -314,7 +314,7 @@ impl Blending {
match name.to_ascii_lowercase().as_str() {
"add" => Ok(Blending::Add { scale, offset }),
"subtract" => Ok(Blending::Subtract { scale, offset }),
other => match crate::commands::blend_from_str(other) {
other => match crate::commands::parse_blend(other) {
Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)),
_ => Err(format!("unsupported blending `{other}`")),
},
+1 -1
View File
@@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::channel_cmds::Target;
use crate::commands::{CommandSpec, blend_from_str, int, layer_param};
use crate::commands::{CommandSpec, int, layer_param, parse_blend};
use crate::{EngineError, Result, Session};
// ------------------------------------------------------------------ state
+2 -2
View File
@@ -1,5 +1,5 @@
use super::{
BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or,
BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, f32_or, from_rgba_into, json, parse_blend, str_or,
surface_of, surface_of_mut, to_rgba,
};
@@ -103,7 +103,7 @@ fn fade_job(s: &Session, p: &Value) -> Result<FadeJob> {
let cmd = "edit.fade";
let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?;
let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0;
let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?;
let mode = parse_blend(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let prev = before_state(st, &src).ok_or_else(|| bad(cmd, "no previous state"))?;
let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?;
+1 -1
View File
@@ -147,7 +147,7 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
let picked = s.tools.picked_cmyk([color[0], color[1], color[2]]);
let mode = match p.get("mode") {
None | Some(Value::Null) => photocraft_color::BlendMode::Normal,
Some(Value::String(m)) => crate::commands::blend_from_str(m)
Some(Value::String(m)) => crate::commands::parse_blend(m)
.filter(|m| *m != photocraft_color::BlendMode::PassThrough)
.ok_or_else(|| EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("unknown blend mode `{m}`") })?,
Some(v) => return Err(EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("mode must be a blend mode name, not {v}") }),
+2 -2
View File
@@ -11,7 +11,7 @@ use photocraft_geom::{Rect, TILE_SIZE};
use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde_json::{Value, json};
use crate::commands::{blend_from_str, color_param, layer_param};
use crate::commands::{color_param, layer_param, parse_blend};
use crate::{EngineError, Result, Session};
const CMD: &str = "edit.fill";
@@ -66,7 +66,7 @@ fn contents(p: &Value) -> Result<&str> {
fn mode(p: &Value) -> Result<BlendMode> {
match p.get("mode") {
None | Some(Value::Null) => Ok(BlendMode::Normal),
Some(Value::String(m)) => blend_from_str(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))),
Some(Value::String(m)) => parse_blend(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))),
Some(v) => Err(bad(format!("`mode` must be a blend mode name, not {v}"))),
}
}
+2 -2
View File
@@ -17,7 +17,7 @@ use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId
use photocraft_geom::Rect;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str, check_pixels_unlocked, layer_param};
use crate::commands::{CommandSpec, check_pixels_unlocked, layer_param, parse_blend};
use crate::presets::gradients::{GradientPreset, transparency_param};
use crate::{EngineError, Result, Session};
@@ -300,7 +300,7 @@ pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result<Layer> {
let opacity = num(p, "opacity").unwrap_or(100.0).clamp(0.0, 100.0) / 100.0;
let blend = match p.get("mode").and_then(Value::as_str) {
None | Some("") => photocraft_color::BlendMode::Normal,
Some(m) => blend_from_str(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?,
Some(m) => parse_blend(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?,
};
let canvas = doc.bounds();
if canvas.is_empty() {
+1 -1
View File
@@ -525,7 +525,7 @@ fn blending_options(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "layer.layerStyle.blendingOptions";
let id = layer_param(s, p)?;
let blend = match p.get("blend").and_then(Value::as_str) {
Some(b) => Some(crate::commands::blend_from_str(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
Some(b) => Some(crate::commands::parse_blend(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
None => None,
};
let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
+1 -7
View File
@@ -1,5 +1,5 @@
use super::params::bad;
use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value};
use super::{Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value};
/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that
/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays
@@ -72,12 +72,6 @@ pub(crate) fn layer_param(s: &Session, p: &Value) -> Result<LayerId> {
}
}
pub fn blend_from_str(s: &str) -> Option<BlendMode> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "");
let want = norm(s);
std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want)
}
/// The active selection as the mask of a layer being created, or None without a selection.
/// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on
/// the selected area only (#1250). [`mask_new_layer`] then drops the selection (#8801).
+3 -3
View File
@@ -3,7 +3,7 @@
use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::presets::gradients;
use crate::{EngineError, Result, Session};
@@ -47,7 +47,7 @@ fn fill_mode(p: &Value) -> Result<FillMode> {
match p.get("mode") {
None | Some(Value::Null) => Ok(FillMode::Blend(photocraft_color::BlendMode::Normal)),
Some(Value::String(m)) if m.eq_ignore_ascii_case("clear") => Ok(FillMode::Clear),
Some(Value::String(m)) => blend_from_str(m)
Some(Value::String(m)) => parse_blend(m)
.filter(|m| *m != photocraft_color::BlendMode::PassThrough)
.map(FillMode::Blend)
.ok_or_else(|| bad(format!("unknown blend mode `{m}`"))),
@@ -186,7 +186,7 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
};
let reverse = b(p, "reverse", false);
let opacity = opacity(p, "paint.gradient")?;
let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal);
let blend = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(photocraft_color::BlendMode::Normal);
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("Gradient", |doc, _| {
+1 -1
View File
@@ -22,7 +22,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use rayon::prelude::*;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::{EngineError, Result, Session};
mod art_history;
+2 -2
View File
@@ -3,7 +3,7 @@ use super::heal::history_source;
use super::sampling::{SampleLayers, sample_layers};
use super::{
BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value,
alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point,
alpha_index, apply_coverage, bad, coverage, damage_json, flag, has_pixel_layer, json, parse_blend, parse_brush, pattern_stamp, periodic, point,
reject_huge_stroke, run_stroke, to_rgba,
};
@@ -212,7 +212,7 @@ pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value,
pub(super) fn blend_param(p: &Value, cmd: &str) -> Result<BlendMode> {
match p.get("mode").and_then(Value::as_str) {
None => Ok(BlendMode::Normal),
Some(m) => blend_from_str(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))),
Some(m) => parse_blend(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))),
}
}
+3 -3
View File
@@ -1,8 +1,8 @@
use super::sampling::{AllLayers, sample_all_layers};
use super::{
BlendMode, BrushSettings, Document, EngineError, Footprint, IndexedParallelIterator, LayerId, ParallelIterator, ParallelSliceMut, PixelFormat, Rect,
Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, blend_from_str, damage_json,
dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba,
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,
};
// ---------------------------------------------------------------------------------------------
@@ -206,7 +206,7 @@ pub(super) enum DabTool {
fn smudge_mode(p: &Value, cmd: &str) -> Result<BlendMode> {
use BlendMode::{Color, Darken, Hue, Lighten, Luminosity, Normal, Saturation};
let Some(v) = p.get("mode") else { return Ok(Normal) };
let named = v.as_str().and_then(blend_from_str).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity));
let named = v.as_str().and_then(parse_blend).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity));
named.ok_or_else(|| {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_owned);
bad(cmd, format!("unknown mode `{given}` (normal|darken|lighten|hue|saturation|color|luminosity)"))
+1 -1
View File
@@ -34,7 +34,7 @@ use photocraft_raster::Surface;
use serde_json::{Value, json};
use stack_cache::{Stage, StageKey};
use crate::commands::{CommandSpec, blend_from_str, layer_param};
use crate::commands::{CommandSpec, layer_param, parse_blend};
use crate::jobs::JobCtx;
use crate::{EngineError, Result, Session};
+3 -3
View File
@@ -1,8 +1,8 @@
use super::rendering::{refresh_or_fail, refresh_or_fail_in};
use super::source::source_bytes;
use super::{
BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, blend_from_str, json,
layer_param, other,
BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, json, layer_param, other,
parse_blend,
};
pub(super) fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> {
@@ -241,7 +241,7 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn blending_options(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "layer.smartFilter.blendingOptions";
let blend = match p.get("blend").and_then(Value::as_str) {
Some(b) => Some(blend_from_str(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
Some(b) => Some(parse_blend(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
None => None,
};
let opacity = p.get("opacity").and_then(Value::as_f64).map(|o| if o > 1.0 { o / 100.0 } else { o } as f32);
+1 -1
View File
@@ -26,7 +26,7 @@ use photocraft_geom::{Affine, Point, Rect};
use photocraft_vector as vector;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::{EngineError, Result, Session};
/// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized.
+2 -2
View File
@@ -2,7 +2,7 @@ use super::params::{color, f64p, layer_id, op_from, parse_path, path_json};
use super::shape::{map_path, map_shape, transform_shape, with_shape};
use super::{
Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Rect, Result, SelectionMode, Session, Value, bad,
blend_from_str, json, sel, vector,
json, parse_blend, sel, vector,
};
// ---------------------------------------------------------------------------
@@ -444,7 +444,7 @@ pub(super) fn path_fill(s: &mut Session, p: &Value) -> Result<Value> {
let rgb = c.to_rgb();
let src = [rgb[0], rgb[1], rgb[2], c.alpha];
let opacity = (f64p(p, "opacity").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32;
let mode = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(BlendMode::Normal);
let mode = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(BlendMode::Normal);
let feather = f64p(p, "feather").unwrap_or(0.0) as f32;
let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);
let id = layer_id(s, p)?;
+1 -3
View File
@@ -37,9 +37,7 @@ impl GroupOptions {
let blend = match get("mode") {
None => None,
Some(v) => Some(
v.as_str()
.and_then(crate::commands::blend_from_str)
.ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?,
v.as_str().and_then(crate::commands::parse_blend).ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?,
),
};
let opacity = match get("opacity") {
+4 -4
View File
@@ -9,7 +9,7 @@ use photocraft_doc::{
};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, blend_from_str};
use crate::commands::{CommandSpec, parse_blend};
use crate::presets::{always, bad};
use crate::{EngineError, Result, Session};
@@ -714,7 +714,7 @@ fn overlay_common(c: &mut FxCommon, p: &Value) {
if let Some(x) = b_of(p, "enabled") {
c.enabled = x;
}
if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) {
if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(parse_blend) {
c.blend = x;
}
if let Some(x) = f_of(p, "opacity") {
@@ -883,10 +883,10 @@ fn overlay_bevel(bv: &mut Bevel, p: &Value) {
}
overlay_contour(p, "glossContour", &mut bv.gloss_contour);
overlay_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias);
if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) {
if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(parse_blend) {
bv.highlight.blend = blend;
}
if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) {
if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(parse_blend) {
bv.shadow.blend = blend;
}
overlay_color(p, "highlightColor", &mut bv.highlight_color);
+1 -1
View File
@@ -74,7 +74,7 @@ pub(crate) fn parse(p: &Value) -> Result<NewLayer> {
None | Some(Value::Null) => BlendMode::Normal,
Some(v) => {
let name = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name"))?;
crate::commands::blend_from_str(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))?
crate::commands::parse_blend(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))?
}
};
let opacity = match p.get("opacity") {
+1 -1
View File
@@ -280,7 +280,7 @@ fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
}
},
blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::blend_from_str).or_else(|| with_blend.then_some(l.blend)),
blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::parse_blend).or_else(|| with_blend.then_some(l.blend)),
fill_opacity: p.get("fillOpacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.fill_opacity)),
opacity: p.get("opacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.opacity)),
};
+2 -6
View File
@@ -199,14 +199,10 @@ fn dont_save_all(_: &Value, _: &Value) -> Vec<(String, Value)> {
vec![pair("applyToAll", json!(true)), pair("choice", json!("dontSave"))]
}
/// A blend label such as "Multiply" to the Blend row's id; a string `blend_from_str` refuses passes through so the
/// A blend label such as "Multiply" to the Blend row's id; a string `parse_blend` refuses passes through so the
/// row refuses it.
fn blend_id(value: &Value) -> Value {
value
.as_str()
.and_then(photocraft_engine::commands::blend_from_str)
.map(|mode| json!(crate::panels::layers_tree::blend_key(mode).to_string()))
.unwrap_or_else(|| value.clone())
value.as_str().and_then(photocraft_engine::commands::parse_blend).map(|mode| json!(mode.key().to_string())).unwrap_or_else(|| value.clone())
}
// PLAN: the framework field ids `mode` (Fill, Stroke) and `blend` (Smart Filter) are assumed (dialogs-w22 by request).
+1 -1
View File
@@ -615,7 +615,7 @@ fn marquee_params(app: &PhotocraftApp, p: &Value) -> std::result::Result<(Option
fn gradient_blend_param(p: &Value) -> std::result::Result<Option<photocraft_color::BlendMode>, String> {
let Some(value) = p.get("gradientBlendMode") else { return Ok(None) };
let Some(name) = value.as_str() else { return Err("gradientBlendMode must be a blend mode name".into()) };
photocraft_engine::commands::blend_from_str(name)
photocraft_engine::commands::parse_blend(name)
.filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m))
.map(Some)
.ok_or_else(|| format!("unknown gradient blend mode `{name}`"))
+1 -1
View File
@@ -660,7 +660,7 @@ fn convert_blend_mode(key: &str, value: &mut Value) {
}
let Some(mode) = value.get_mut("mode") else { return };
if let Some(blend) = mode.as_str().and_then(crate::panels::layers_tree::blend_of) {
*mode = Value::String(crate::panels::layers_tree::blend_key(blend));
*mode = Value::String(blend.key().to_string());
}
}
+6 -6
View File
@@ -6,18 +6,18 @@ use craft::ui::runtime::env::Label;
use photocraft_color::BlendMode;
use serde_json::{Map, Value, json};
use crate::panels::layers_tree::blend_key;
/// 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).into_iter().map(|(m, name)| (crate::panels::blend_entry(blend_key(m), m), Label::from(name))).collect();
Param::new(key, label, ParamKind::blend(modes, Some(blend_key(current))))
let modes = crate::panels::blend_options(group, current)
.into_iter()
.map(|(m, name)| (crate::panels::blend_entry(m.key().to_string(), m), Label::from(name)))
.collect();
Param::new(key, label, ParamKind::blend(modes, Some(current.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::blend_from_str).unwrap_or(BlendMode::Normal)
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.
@@ -8,7 +8,6 @@ use serde_json::json;
use super::{COMMAND, greyed, param};
use crate::PhotocraftApp;
use crate::panels::layers_tree::blend_key;
/// The reference application's Fade Mode list, a group per row.
const GROUPS: [&[&str]; 6] = [
@@ -46,7 +45,7 @@ fn the_list_is_the_27_modes_in_the_reference_order() {
#[test]
fn the_params_doc_lists_all_27_modes_and_the_old_names_still_work() {
let options = spec_modes();
let modes: Vec<Option<BlendMode>> = options.iter().map(|o| photocraft_engine::commands::blend_from_str(o)).collect();
let modes: Vec<Option<BlendMode>> = options.iter().map(|o| photocraft_engine::commands::parse_blend(o)).collect();
assert_eq!(modes, BlendMode::LAYER_MODES.map(Some).to_vec());
for old in ["normal", "multiply", "screen", "overlay", "softLight", "hardLight", "darken", "lighten", "difference", "color", "luminosity"] {
assert!(options.iter().any(|o| o == old), "{old} is still listed");
@@ -61,7 +60,7 @@ fn every_listed_mode_fades() {
s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
s.execute("edit.fill", json!({"color": "#336699"})).unwrap();
let out = s.execute(COMMAND, json!({"opacity": 50, "mode": key})).unwrap();
assert_eq!(out["mode"], json!(photocraft_engine::commands::blend_from_str(&key).unwrap().label()), "{key}");
assert_eq!(out["mode"], json!(photocraft_engine::commands::parse_blend(&key).unwrap().label()), "{key}");
}
}
@@ -104,7 +103,7 @@ fn the_row_disables_the_documents_greyed_modes() {
let ParamKind::Blend { modes, .. } = &row.kind else { panic!("Mode is a blend row") };
assert_eq!(modes.len(), BlendMode::LAYER_MODES.len(), "{mode} {depth}");
for m in BlendMode::LAYER_MODES {
assert_eq!(row.option_enabled(&blend_key(m)), !want.contains(&m), "{mode} {depth}: {}", m.label());
assert_eq!(row.option_enabled(&m.key().to_string()), !want.contains(&m), "{mode} {depth}: {}", m.label());
}
}
}
+1 -2
View File
@@ -7,7 +7,6 @@ use craft::ui::runtime::env::Label;
use photocraft_color::{BlendMode, ColorMode, SampleType};
use crate::PhotocraftApp;
use crate::panels::layers_tree::blend_key;
pub(crate) const COMMAND: &str = "edit.fade";
@@ -28,7 +27,7 @@ pub(crate) fn greyed(mode: ColorMode, depth: SampleType) -> &'static [BlendMode]
/// 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| blend_key(*m)))
super::blend_options::blend_param("mode", label, false, BlendMode::Normal).disabled_options(greyed.iter().map(|m| (*m).key().to_string()))
}
#[cfg(test)]
+1 -2
View File
@@ -17,7 +17,6 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::dialogs::blend_options::{blending_params, blending_rows};
use crate::dialogs::params::{captured, open_param};
use crate::panels::layers_tree::blend_key;
/// The command of the dialog, which is also its dialog key.
pub const COMMAND: &str = "edit.fill";
@@ -64,7 +63,7 @@ fn defaults(foreground: [f32; 3], first_pattern: Option<String>) -> DialogFields
f.set("pattern", id);
}
f.set("colorAdaptation", true);
f.set("mode", blend_key(BlendMode::Normal));
f.set("mode", BlendMode::Normal.key().to_string());
f.set("opacity", 100.0);
f.set("preserveTransparency", false);
f
@@ -36,7 +36,7 @@ fn ok_creates_the_group_with_the_options_in_one_step_and_cancel_changes_nothing(
let id = open(&mut app, NEW_GROUP);
set(&mut app, id, "name", json!("Sky")).unwrap();
set(&mut app, id, "color", json!("blue")).unwrap();
set(&mut app, id, "mode", json!(crate::panels::layers_tree::blend_key(BlendMode::Multiply))).unwrap();
set(&mut app, id, "mode", json!(BlendMode::Multiply.key().to_string())).unwrap();
set(&mut app, id, "opacity", json!(60.0)).unwrap();
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
assert_eq!(steps(&app), initial + 1, "one history step");
+2 -3
View File
@@ -13,7 +13,6 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::dialogs::params;
use crate::panels::layers_tree::blend_key;
/// The command the dialog stands for; it is also the dialog's key.
pub const COMMAND: &str = "layer.new.layer";
@@ -59,7 +58,7 @@ pub(crate) fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamRe
}
fn mode(f: &DialogFields) -> BlendMode {
f.text("mode").and_then(photocraft_engine::commands::blend_from_str).filter(|m| *m != BlendMode::PassThrough).unwrap_or(BlendMode::Normal)
f.text("mode").and_then(photocraft_engine::commands::parse_blend).filter(|m| *m != BlendMode::PassThrough).unwrap_or(BlendMode::Normal)
}
fn flag(f: &DialogFields, k: &str) -> bool {
@@ -150,7 +149,7 @@ mod tests {
let id = top(&app);
assert!(set(&mut app, id, "fillNeutral", json!(true)).is_err(), "Normal has no neutral color");
set(&mut app, id, "name", json!("Dodge & Burn")).unwrap();
set(&mut app, id, "mode", json!(blend_key(BlendMode::Overlay))).unwrap();
set(&mut app, id, "mode", json!(BlendMode::Overlay.key().to_string())).unwrap();
set(&mut app, id, "opacity", json!(60.0)).unwrap();
set(&mut app, id, "color", json!("violet")).unwrap();
set(&mut app, id, "fillNeutral", json!(true)).unwrap();
@@ -13,7 +13,6 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::dialogs::blend_options::{blend_mode, blend_param};
use crate::dialogs::params::{captured, open_param};
use crate::panels::layers_tree::blend_key;
/// The command of the Blending Options dialog, which is also its dialog key.
pub const COMMAND: &str = "layer.smartFilter.blendingOptions";
@@ -72,11 +71,11 @@ pub fn open(app: &mut PhotocraftApp, layer: LayerId, index: usize) -> Result<Dia
let params = vec![
blend_param("blend", tl!("Mode"), false, filter.blend),
Param::read_only_text("blendNote", "", tl!("Dissolve is approximated: it blends without Photoshop's dither."))
.visible_when("blend", blend_key(BlendMode::Dissolve)),
.visible_when("blend", BlendMode::Dissolve.key().to_string()),
Param::new("opacity", tl!("Opacity"), ParamKind::range(0.0, 100.0, 100.0, SliderScale::Linear)),
];
let mut fields = DialogFields::new();
fields.set("blend", blend_key(filter.blend));
fields.set("blend", filter.blend.key().to_string());
fields.set("opacity", f64::from(filter.opacity) * 100.0);
app.filter_preview = None;
Ok(open_param(app, COMMAND, fields, target, move |f| ParamDialog::new(COMMAND, title.clone(), params.clone()).values(Bind::bound(f)).previews(true)))
@@ -113,7 +113,7 @@ fn blending_edits_one_filter_with_percent_opacity_and_undo_redo() {
confirm(&mut app, id);
let changed = filters(&app, layer);
assert!((changed[0].opacity - 0.01).abs() < 1e-6);
assert_eq!(blend_key(changed[0].blend), blend);
assert_eq!((changed[0].blend).key().to_string(), blend);
assert_eq!(serde_json::to_value(&changed[1]).unwrap(), serde_json::to_value(&original[1]).unwrap());
assert_eq!(photocraft_engine::smart_cmds::contents_of(&app.session.active().unwrap().doc, layer).unwrap(), source);
assert_eq!(app.session.active().unwrap().doc.layer(layer).unwrap().blend, BlendMode::Normal);
+1 -4
View File
@@ -144,10 +144,7 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys
assert!(!table("photocraft.filter.gaussianBlur").unwrap().contains_key("preview"), "a null drops");
assert!(table("craft_draw.shape.create.ellipse").is_some(), "a routed key lands under its library scope");
assert!(table("photocraft.shape.create.ellipse").is_none());
assert_eq!(
table("photocraft.edit.fill").unwrap().get("mode"),
Some(&toml::Value::String(crate::panels::layers_tree::blend_key(photocraft_color::BlendMode::ColorBurn)))
);
assert_eq!(table("photocraft.edit.fill").unwrap().get("mode"), Some(&toml::Value::String(photocraft_color::BlendMode::ColorBurn.key().to_string())));
let mut left: Vec<&str> = prefs.dialogs.keys().map(String::as_str).collect();
left.sort_unstable();
let mut kept = vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF];
@@ -15,7 +15,6 @@ use photocraft_color::BlendMode;
use photocraft_doc::{Layer, LayerId};
use serde_json::json;
use super::layers_tree::blend_key;
use crate::PhotocraftApp;
use crate::state::Tool;
@@ -28,7 +27,7 @@ fn opacity(e: EditEvent<f64>) -> LayersEvent<LayerId> {
}
fn key(m: BlendMode) -> String {
blend_key(m)
m.key().to_string()
}
fn label() -> Arc<str> {
+2 -2
View File
@@ -68,11 +68,11 @@ pub fn patched(current: &LayerFilter, v: &Value) -> Result<LayerFilter, String>
}
if let Some(mode) = o.get("mode") {
let name = mode.as_str().ok_or("layerFilter.mode must be a blend mode name")?;
let m = photocraft_engine::commands::blend_from_str(name).filter(|m| BlendMode::LAYER_MODES.contains(m)).ok_or_else(|| {
let m = photocraft_engine::commands::parse_blend(name).filter(|m| BlendMode::LAYER_MODES.contains(m)).ok_or_else(|| {
let modes: Vec<&str> = BlendMode::LAYER_MODES.iter().map(|m| m.label()).collect();
format!("layerFilter.mode: `{name}` is not a layer blend mode the filter lists (modes: {})", modes.join(", "))
})?;
f.mode = super::layers_tree::blend_key(m);
f.mode = m.key().to_string();
}
if let Some(e) = o.get("effect") {
f.effect = choose::<EffectKind>("effect", "effect", &EffectKind::ALL, e)?;
@@ -8,7 +8,7 @@ use photocraft_engine::Session;
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::panels::layers_tree::{blend_key, ui_label};
use crate::panels::layers_tree::ui_label;
/// `doc`'s layers, top to bottom, groups before their contents.
fn top_down(doc: &Document) -> Vec<&Layer> {
@@ -71,7 +71,7 @@ fn patched_reads_the_protocol_and_refuses_bad_values() {
json!({"by": "mode", "mode": "Multiply", "kinds": ["type", "pixel", "type"]}),
filter(FilterBy::Mode, |f| {
f.name = "ink".into();
f.mode = blend_key(BlendMode::Multiply);
f.mode = BlendMode::Multiply.key().to_string();
f.kinds = vec![FilterKind::Type, FilterKind::Pixel];
}),
),
+3 -9
View File
@@ -25,15 +25,9 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
/// The key the panel and the filter use for a blend mode: its label folded as the engine's
/// `blend_from_str` reads it ("normal", "lineardodgeadd").
pub(crate) fn blend_key(m: BlendMode) -> String {
m.key().to_string()
}
/// The blend mode a panel key names.
pub(crate) fn blend_of(key: &str) -> Option<BlendMode> {
photocraft_engine::commands::blend_from_str(key)
photocraft_engine::commands::parse_blend(key)
}
/// A document label colour as the framework's (`None` for none), matched by name.
@@ -241,7 +235,7 @@ impl LayerTree for PhotoLayers<'_> {
info.renamable = !info.background;
info.clipped = l.clipped;
info.linked = l.link_group.is_some();
info.blend_key = blend_key(l.blend);
info.blend_key = l.blend.key().to_string();
info.blend_label = (!matches!(l.blend, BlendMode::Normal | BlendMode::PassThrough)).then(|| tl!(l.blend.label()).to_string());
info.effect_kinds = l.effects.items.iter().filter(|e| e.enabled()).filter_map(effect_kind).collect();
info.advanced_blending = l.excluded_channels != 0 || l.advanced != Default::default() || !l.blend_if.is_default();
@@ -371,7 +365,7 @@ impl LayerTree for PhotoLayers<'_> {
fn properties(&self) -> Option<LayerProperties> {
let l = self.st.active_layer.and_then(|id| self.layer(&id))?;
let mut p = LayerProperties::new(blend_key(l.blend));
let mut p = LayerProperties::new(l.blend.key().to_string());
// Pass Through is a group's mode: offered only when every target is a group.
p.group = self.targets().iter().all(|id| self.layer(id).is_some_and(Layer::is_group));
p.opacity = f64::from(l.opacity) * 100.0;