diff --git a/crates/engine-core/src/cmd/layer_menu_cmds.rs b/crates/engine-core/src/cmd/layer_menu_cmds.rs index 6fcc6abd4b..8f9cd5f067 100644 --- a/crates/engine-core/src/cmd/layer_menu_cmds.rs +++ b/crates/engine-core/src/cmd/layer_menu_cmds.rs @@ -522,49 +522,52 @@ fn native(_: &Session) -> Enabled { // ---------- layer style ---------- fn blending_options(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.layerStyle.blendingOptions"; let id = layer_param(s, p)?; + s.edit("Blending Options", |doc, _| apply_blending_options(doc, id, p))?; + Ok(Value::Null) +} + +/// Apply parsed blending settings inside the caller's document edit. +pub(crate) fn apply_blending_options(doc: &mut Document, id: LayerId, p: &Value) -> Result<()> { + const CMD: &str = "layer.layerStyle.blendingOptions"; let blend = match p.get("blend").and_then(Value::as_str) { 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)); let fill = p.get("fillOpacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); - let mode = s.active().ok_or(EngineError::NoDocument)?.doc.mode; + let mode = doc.mode; let blend_if = match p.get("blendIf") { None => None, Some(v) => Some(blend_if_entries(v, mode)?), }; let adv = advanced_params(p, mode)?; - s.edit("Blending Options", |doc, _| { - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if let Some(b) = blend { - if b == BlendMode::PassThrough && !l.is_group() { - return Err(bad(CMD, "Pass Through is for groups")); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if let Some(b) = blend { + if b == BlendMode::PassThrough && !l.is_group() { + return Err(bad(CMD, "Pass Through is for groups")); + } + l.blend = b; + } + if let Some(o) = opacity { + l.opacity = o; + } + if let Some(f) = fill { + l.fill_opacity = f; + } + match &blend_if { + // `null`: Blend If back to the defaults. + Some(None) => l.blend_if = BlendIf::default(), + Some(Some(entries)) => { + for (i, this, under) in entries { + let [cur_this, cur_under] = l.blend_if.get(*i); + l.blend_if.set(*i, [this.unwrap_or(cur_this), under.unwrap_or(cur_under)]); } - l.blend = b; } - if let Some(o) = opacity { - l.opacity = o; - } - if let Some(f) = fill { - l.fill_opacity = f; - } - match &blend_if { - // `null`: Blend If back to the defaults. - Some(None) => l.blend_if = BlendIf::default(), - Some(Some(entries)) => { - for (i, this, under) in entries { - let [cur_this, cur_under] = l.blend_if.get(*i); - l.blend_if.set(*i, [this.unwrap_or(cur_this), under.unwrap_or(cur_under)]); - } - } - None => {} - } - adv.apply(l); - Ok(()) - })?; - Ok(Value::Null) + None => {} + } + adv.apply(l); + Ok(()) } /// The Advanced Blending parameters of `layer.layerStyle.blendingOptions`; `None` = keep. @@ -716,7 +719,16 @@ fn blend_range(v: &Value) -> Option { } fn global_light(s: &mut Session, p: &Value) -> Result { - let cur = s.active().ok_or(EngineError::NoDocument)?.doc.global_light; + let current = s.active().ok_or(EngineError::NoDocument)?.doc.global_light; + let light = global_light_params(current, p)?; + s.edit("Global Light", |doc, _| { + doc.global_light = light; + Ok(()) + })?; + Ok(json!({"angle": light.angle, "altitude": light.altitude})) +} + +pub(crate) fn global_light_params(cur: photocraft_doc::effects::GlobalLight, p: &Value) -> Result { // Read as f64 and reject what f32 can't hold: 1e39 would become inf, and rem_euclid NaN. let f32_param = |key: &str, default: f32| match p.get(key).and_then(Value::as_f64) { None => Ok(default), @@ -729,12 +741,7 @@ fn global_light(s: &mut Session, p: &Value) -> Result { if angle == -180.0 && raw_angle > 0.0 { angle = 180.0; } - s.edit("Global Light", |doc, _| { - doc.global_light.angle = angle; - doc.global_light.altitude = altitude; - Ok(()) - })?; - Ok(json!({"angle": angle, "altitude": altitude})) + Ok(photocraft_doc::effects::GlobalLight { angle, altitude }) } fn scale_effects(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine-core/src/layer_style.rs b/crates/engine-core/src/layer_style.rs index a40b6ef00e..9159a5a9fe 100644 --- a/crates/engine-core/src/layer_style.rs +++ b/crates/engine-core/src/layer_style.rs @@ -1005,8 +1005,8 @@ const MAX_EFFECTS: usize = 256; /// The most strokes `add` puts on one layer: the Layer Style dialog's limit (#15140). pub(crate) const MAX_STROKES: usize = 10; -/// Replaces a layer's whole effect list in one history step: the Layer Style dialog's -/// apply. Each entry builds an effect from `params`, or edits the snapshot it carried +/// Applies blending options, effects, and shared light changes in one history step. +/// Each entry builds an effect from `params`, or edits the snapshot it carried /// (`fx`: the effect JSON as the dialog loaded it, kept verbatim for everything the /// dialog doesn't model) with the params present. Unknown kinds, kind/snapshot /// mismatches and malformed snapshots are errors, never panics. @@ -1061,9 +1061,33 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result { } list.push(fx); } + let options = |key: &str| match p.get(key) { + None => Ok(None), + Some(value) if value.is_object() => Ok(Some(value)), + Some(_) => Err(bad(CMD, format!("`{key}` must be an object"))), + }; + let blending = options("blendingOptions")?; + let light = options("globalLight")? + .map(|params| { + let current = s.active().ok_or(EngineError::NoDocument)?.doc.global_light; + crate::layer_menu_cmds::global_light_params(current, params) + }) + .transpose()?; let count = list.len(); - let label = if list.is_empty() { "Clear Layer Style" } else { "Edit Layer Style" }; + let label = if blending.is_some() || light.is_some() { + "Layer Style" + } else if list.is_empty() { + "Clear Layer Style" + } else { + "Edit Layer Style" + }; s.edit(label, |doc, _| { + if let Some(params) = blending { + crate::layer_menu_cmds::apply_blending_options(doc, id, params)?; + } + if let Some(light) = light { + doc.global_light = light; + } for pat in &pats { crate::pattern_cmds::ensure_in_doc(doc, pat); } @@ -1221,7 +1245,7 @@ pub fn specs() -> Vec { label: "Edit Layer Style", menu: &[], shortcut: None, - params: r##"{"layer":id,"effects":[{"kind":"dropShadow|innerShadow|outerGlow|innerGlow|stroke|colorOverlay|gradientOverlay|patternOverlay|satin|bevelEmboss","params":{…layer.layerStyle. params…},"fx":}]} (replaces the layer's whole effect list; an entry with `fx` edits that effect with the params present, one without builds from params)"##, + params: r##"{"layer":id,"blendingOptions":{…layer.layerStyle.blendingOptions params…}?,"globalLight":{"angle":deg?,"altitude":deg?}?,"effects":[{"kind":"dropShadow|innerShadow|outerGlow|innerGlow|stroke|colorOverlay|gradientOverlay|patternOverlay|satin|bevelEmboss","params":{…layer.layerStyle. params…},"fx":}]} (replaces the layer's whole effect list and applies optional blending and light settings in one history state; an entry with `fx` edits that effect with the params present, one without builds from params)"##, enabled: has_layer, run: replace_effects, journal: true, diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index e51c2b1e80..8939ad973d 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -780,17 +780,8 @@ fn light_to_apply(style: &LayerStyle, initial: Option) -> Option { light_angle } -/// Runs the style's commands through `run`: blending options, then the whole effect list in one -/// `layer.layerStyle.replace` (instances keep their order; their snapshots carry what the dialog -/// doesn't model). `light` is the document's global light angle when the dialog opened. -// The typed draft cannot hold a malformed parameter group, so there is nothing to validate. -pub(crate) fn apply( - style: &LayerStyle, - layer: LayerId, - light: Option, - mut run: impl FnMut(&str, Value) -> Result, -) -> Result { - run("layer.layerStyle.blendingOptions", blending_json(&style.blending, layer))?; +/// Applies blending, the ordered effect snapshots, and any shared light change in one edit. +pub(crate) fn apply(style: &LayerStyle, layer: LayerId, light: Option, run: impl FnOnce(&str, Value) -> Result) -> Result { let entries: Vec = style .effects .iter() @@ -800,12 +791,11 @@ pub(crate) fn apply( effect_entry(fx_of(&e.params).as_ref(), e.kind.key(), params, light) }) .collect(); - run("layer.layerStyle.replace", json!({"layer": layer.0, "effects": entries}))?; - // An effect lit by the global light follows the document's light angle, so the Angle slider - // drives that shared angle rather than the per-effect angle the compositor ignores. + let mut params = json!({"layer": layer.0, "blendingOptions": blending_json(&style.blending, layer), "effects": entries}); if let Some(angle) = light_to_apply(style, light) { - run("layer.layerStyle.globalLight", json!({"angle": angle}))?; + params["globalLight"] = json!({"angle": angle}); } + run("layer.layerStyle.replace", params)?; Ok(Value::Null) } @@ -1070,5 +1060,7 @@ pub(crate) fn gradient_layer_bounds(session: &Session, layer: LayerId) -> Option (w > 0.0 && h > 0.0).then_some([w, h]) } +#[cfg(test)] +mod ok_history_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/dialogs/layer_style/ok_history_tests.rs b/crates/ui-egui/src/dialogs/layer_style/ok_history_tests.rs new file mode 100644 index 0000000000..55d7c5aae7 --- /dev/null +++ b/crates/ui-egui/src/dialogs/layer_style/ok_history_tests.rs @@ -0,0 +1,130 @@ +//! #14850: a Layer Style confirmation is one undoable edit. + +use super::{ + tests::{edit, first_of}, + *, +}; +use egui_kittest::Harness; +use photocraft_doc::Layer; + +fn pixel_layer_app() -> Result, String> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16}))?; + app.run("layer.new.layer", json!({}))?; + Ok(app) +} + +fn layer(app: &PhotocraftApp) -> Option<&Layer> { + let state = app.session.active()?; + state.doc.layer(state.active_layer?) +} + +#[test] +fn opacity_only_ok_is_one_undoable_layer_style_edit() { + let mut app = pixel_layer_app().unwrap(); + let before = app.session.active().unwrap().history.entries().to_vec(); + let id = open(&mut app, Some(BLENDING)).unwrap(); + edit(&mut app, id, |draft| draft.style.blending.opacity = 70.0); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + + let entries = app.session.active().unwrap().history.entries(); + assert_eq!(&entries[..before.len()], before.as_slice()); + assert_eq!(&entries[before.len()..], ["Layer Style"]); + assert_eq!(layer(&app).unwrap().opacity, 0.7); + assert!(layer(&app).unwrap().effects.items.is_empty()); + + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(layer(&app).unwrap().opacity, 1.0); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(layer(&app).unwrap().opacity, 0.7); +} + +#[test] +fn fill_stroke_and_global_light_undo_and_redo_together() { + let mut app = pixel_layer_app().unwrap(); + app.run("layer.layerStyle.stroke", json!({"size": 3})).unwrap(); + let initial_effects = layer(&app).unwrap().effects.clone(); + let initial_light = app.session.active().unwrap().doc.global_light; + let before = app.session.active().unwrap().history.entries().len(); + let id = open(&mut app, Some(BLENDING)).unwrap(); + let stroke = first_of(&app, id, EffectKind::Stroke); + edit(&mut app, id, |draft| { + draft.style.blending.fill_opacity = 40.0; + draft.style.global_light = 45.0; + draft.set_param(stroke, "size", StyleValue::Number(7.0)); + }); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + + assert_eq!(&app.session.active().unwrap().history.entries()[before..], ["Layer Style"]); + assert_eq!(layer(&app).unwrap().fill_opacity, 0.4); + let edited_effects = layer(&app).unwrap().effects.clone(); + assert!(matches!(&edited_effects.items[0], photocraft_doc::Effect::Stroke(stroke) if stroke.size == 7.0)); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, 45.0); + + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(layer(&app).unwrap().fill_opacity, 1.0); + assert_eq!(layer(&app).unwrap().effects, initial_effects); + assert_eq!(app.session.active().unwrap().doc.global_light, initial_light); + + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(layer(&app).unwrap().fill_opacity, 0.4); + assert_eq!(layer(&app).unwrap().effects, edited_effects); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, 45.0); +} + +#[test] +fn cancel_and_escape_leave_history_and_opacity_unchanged() { + let app = pixel_layer_app().unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + let before = h.state().session.active().unwrap().history.entries().to_vec(); + for escape in [false, true] { + let app = h.state_mut(); + let id = open(app, Some(BLENDING)).unwrap(); + edit(app, id, |draft| draft.style.blending.opacity = 70.0); + h.run_steps(3); + if escape { + h.key_press(egui::Key::Escape); + h.run_steps(3); + } else { + crate::dialogs::testing::cancel(h.state_mut(), id).unwrap(); + } + assert!(h.state().framework.dialogs.get_by_id::(id).is_none()); + assert_eq!(h.state().session.active().unwrap().history.entries(), before.as_slice()); + assert_eq!(layer(h.state()).unwrap().opacity, 1.0); + } +} + +#[test] +fn unchanged_ok_adds_at_most_one_step() { + let mut app = pixel_layer_app().unwrap(); + let before = app.session.active().unwrap().history.entries().len(); + let id = open(&mut app, None).unwrap(); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + let entries = app.session.active().unwrap().history.entries(); + assert!(entries.len() <= before + 1); + if let Some(label) = entries.get(before) { + assert_eq!(label, "Layer Style"); + } +} + +#[test] +fn rejected_effect_keeps_opacity_and_history_unchanged() { + let mut app = pixel_layer_app().unwrap(); + app.run("layer.layerStyle.stroke", json!({"size": 3})).unwrap(); + let initial_effects = layer(&app).unwrap().effects.clone(); + let before = app.session.active().unwrap().history.entries().to_vec(); + let id = open(&mut app, Some(BLENDING)).unwrap(); + edit(&mut app, id, |draft| { + draft.style.blending.opacity = 70.0; + draft.style.effects[0].params.0.insert("fx".into(), StyleValue::Other("{}".into())); + }); + crate::dialogs::testing::confirm(&mut app, id).unwrap(); + assert!(app.ui.status_error); + + assert_eq!(app.session.active().unwrap().history.entries(), before.as_slice()); + assert_eq!(layer(&app).unwrap().opacity, 1.0); + assert_eq!(layer(&app).unwrap().effects, initial_effects); +} diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index dc12ab152a..22c649cd31 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -480,21 +480,15 @@ fn unchanged_global_light_angle_is_not_applied() { let mut d = LayerStyleDraft::new(drafted(&s)); let bevel = d.add_instance(EffectKind::BevelEmboss, &defaults(EffectKind::BevelEmboss)); assert!(d.style.effect(bevel).is_some()); - let mut commands = Vec::new(); // The dialog opened with the angle the draft still holds. - apply(&d.style, id, Some(f64::from(d.style.global_light)), |cmd, _| { - commands.push(cmd.to_string()); - Ok(Value::Null) - }) - .unwrap(); - assert!(!commands.iter().any(|cmd| cmd == "layer.layerStyle.globalLight"), "{commands:?}"); - commands.clear(); - apply(&d.style, id, Some(47.5), |cmd, _| { - commands.push(cmd.to_string()); - Ok(Value::Null) - }) - .unwrap(); - assert!(commands.iter().any(|cmd| cmd == "layer.layerStyle.globalLight"), "a changed angle is applied: {commands:?}"); + for (opening, expected) in [(f64::from(d.style.global_light), false), (47.5, true)] { + apply(&d.style, id, Some(opening), |cmd, params| { + assert_eq!(cmd, "layer.layerStyle.replace"); + assert_eq!(params.get("globalLight").is_some(), expected); + Ok(Value::Null) + }) + .unwrap(); + } let mut app = app_with_layer(32); let light = app.session.active().unwrap().doc.global_light.angle;