fix(engine): grey out Straighten Layer where the reference does

Straighten Layer was offered wherever a ruler line existed, so its button was
live for every target and the command turned whatever it was pointed at: it
rotated and cropped the canvas on the Background, turned several selected
layers or a group, failed on a locked layer with `layer "..." is locked`, and
rotated pixels nobody could see on a hidden layer. The reference application
(#12033) keeps the button off for the Background, a multi-layer selection, a
group, Lock All and Lock Position, and answers a hidden target layer with its
alert and no change at all. The command's own `enabled` check now says the
first set, so the options bar, the CLI, the control channel and an action step
all agree about what is offered; the hidden layer stays enabled and is refused
by the command, before it reads anything for the edit, so a refused click
leaves the document, its History and the ruler line exactly as they were. The
states the ticket marks *not measured* keep today's behaviour.
This commit is contained in:
Hartmut Nörenberg committed 2026-11-07 19:36:53 +01:00
1 parent 6d408847ae
commit 5c0bec3036
7 files changed
+486 -22

No files matched your search

+14 -5
View File
@@ -334,11 +334,11 @@ fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() {
assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no Duplicate step for a copy that was taken back");
// Straighten rolls back when its crop is refused after the rotation ran.
ruled_background(&mut s, 8);
ruled_layer(&mut s, 8);
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
s.authorize = Some(|id, _| if id == "image.crop" { Err(EngineError::Other("refused".into())) } else { Ok(()) });
s.execute("actions.record", json!({"name": "Refused"})).unwrap();
assert!(s.execute("image.analysis.straightenLayer", json!({})).is_err());
assert!(s.execute("image.analysis.straightenLayer", json!({"crop": true})).is_err());
assert_eq!(s.active().unwrap().doc.size.width, 80, "the rotation was taken back");
assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no rotation step for a rotation that was taken back");
}
@@ -500,23 +500,32 @@ fn ruled_background(s: &mut Session, depth: u32) {
.unwrap();
}
/// The same, with a pixel layer on top: since #12033 the Background alone greys Straighten Layer
/// out, so the tests that run the command target a layer and pass `crop` explicitly.
fn ruled_layer(s: &mut Session, depth: u32) {
ruled_background(s, depth);
s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
}
#[test]
fn record_command_that_runs_commands_replays_it_once() {
// Straighten Layer runs Image Rotation and Crop itself: only its own call is recorded,
// so playback rotates once, not three times (rotate, crop, then straighten again).
for depth in [8, 16] {
let mut s = Session::new();
ruled_background(&mut s, depth);
ruled_layer(&mut s, depth);
s.execute("actions.record", json!({"name": "Level"})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
s.execute("image.analysis.straightenLayer", json!({})).unwrap();
// #12033: the crop is asked for, as automation does; the Background it used to default to
// now greys the command out.
s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let got = s.execute("actions.get", json!({"action": "Level"})).unwrap();
let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect();
assert_eq!(ids, ["image.analysis.rulerTool", "image.analysis.straightenLayer"], "depth {depth}");
let direct = s.active().unwrap().doc.clone();
ruled_background(&mut s, depth);
ruled_layer(&mut s, depth);
let before = s.active().unwrap().history.past_len();
let played = s.execute("actions.play", json!({"action": "Level"})).unwrap();
assert!(played.get("failed").is_none(), "depth {depth}: {played}");
+63 -2
View File
@@ -13,6 +13,11 @@
//! values the luminosity (0.30 R + 0.59 G + 0.11 B) of the composite in the document's value
//! range (0–255 at 8 bits, 0–32768 at 16 bits, 0–1 at 32 bits), integrated density area × mean.
//! Lengths and areas are scaled by the measurement scale.
//!
//! Straighten Layer is offered where the reference application offers it: the ruler line is needed,
//! and the target must be a single layer that is not the Background, not a group and not locked in
//! place ([`straighten_disabled`], #12033). A hidden target layer keeps the button and is refused
//! with [`STRAIGHTEN_HIDDEN_ERROR`] before anything changes.
use std::sync::Arc;
@@ -138,6 +143,53 @@ fn has_ruler(s: &Session) -> std::result::Result<(), String> {
s.active().and_then(|d| d.doc.measurement.ruler).map(|_| ()).ok_or_else(|| "no ruler line".into())
}
/// The reference's alert for Straighten Layer on a hidden target layer (#12033), measured: one
/// alert window with an OK button, and the document and its History stay as they were. The button
/// is *enabled* for a hidden layer, so this is the command's refusal and not a greyed state; the
/// options bar shows the same text through `tl!` (English is the catalog source).
pub const STRAIGHTEN_HIDDEN_ERROR: &str = "Could not straighten the layer because the target layer is hidden.";
/// The enabled check of `image.analysis.straightenLayer`: a ruler line, and a target the reference
/// straightens ([`straighten_disabled`], #12033).
fn has_straightenable_layer(s: &Session) -> std::result::Result<(), String> {
has_ruler(s)?;
straighten_disabled(s).map_or(Ok(()), |why| Err(why.into()))
}
/// Why Straighten Layer is greyed out for the current target, `None` when its button is live
/// (#12033). Measured with a ruler line drawn: the Background, two or more selected layers, a
/// group, a layer with Lock All and a layer with Lock Position all grey it out.
///
/// Deliberately not here: a hidden target layer keeps the button enabled and is refused by
/// [`straighten`] with [`STRAIGHTEN_HIDDEN_ERROR`], and the states the ticket marks *not measured*
/// (a layer with a mask, a shape, vector or adjustment layer, artboards, and the lock kinds other
/// than Lock All and Lock Position) keep today's behaviour. A document with no active layer keeps
/// turning the whole canvas as it does now.
fn straighten_disabled(s: &Session) -> Option<&'static str> {
let st = s.active()?;
if st.selected_layers().len() > 1 {
return Some("several layers selected");
}
// The active layer is the one the Layers panel targets; with none, the command turns the
// canvas, which the reference was not measured for.
let id = st.active_layer?;
if st.doc.is_background(id) {
return Some("the Background");
}
if st.doc.layer(id).is_some_and(|l| l.is_group()) {
return Some("a group");
}
// Locks inherited from a group count, as they do for the Move tool.
let locks = st.doc.effective_locks(id);
if locks.all {
return Some("the layer is locked");
}
if locks.position {
return Some("the layer's position is locked");
}
None
}
fn has_log(s: &Session) -> std::result::Result<(), String> {
if s.analysis.log.is_empty() { Err("the Measurement Log is empty".into()) } else { Ok(()) }
}
@@ -718,6 +770,12 @@ pub fn straighten_angle(r: &Ruler) -> f64 {
fn straighten(s: &mut Session, p: &Value) -> Result<Value> {
let d = doc(s)?;
let r = d.measurement.ruler.ok_or_else(|| EngineError::Other("no ruler line".into()))?;
// A hidden target layer keeps its button and gets this alert instead of a rotation (#12033).
// Asked before anything is read for the edit, so the document, its History and the ruler line
// stay exactly as they were; a layer inside a hidden group is hidden too (#571).
if s.active().and_then(|st| st.active_layer).is_some_and(|id| d.path_of(id).is_some_and(|path| !d.shown_at(&path))) {
return Err(EngineError::Other(STRAIGHTEN_HIDDEN_ERROR.into()));
}
let rot = straighten_angle(&r);
if rot.abs() < 1e-9 {
return Ok(json!({"angle": 0.0}));
@@ -1297,8 +1355,8 @@ pub fn specs() -> Vec<CommandSpec> {
"image.analysis.straightenLayer",
"Straighten Layer",
[],
r##"{"crop":bool=(active layer is the Background)} (rotates so the ruler line is level; crop = rotate the canvas and crop to the image)"##,
has_ruler,
r##"{"crop":bool=(active layer is the Background)} (rotates so the ruler line is level; crop = rotate the canvas and crop to the image; off for the Background, two or more selected layers, a group, Lock All and Lock Position, and a hidden target layer answers "Could not straighten the layer because the target layer is hidden." with nothing changed (#12033))"##,
has_straightenable_layer,
straighten,
true
),
@@ -1332,5 +1390,8 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
#[cfg(test)]
#[path = "analysis_straighten_enabled_tests.rs"]
mod analysis_straighten_enabled_tests;
#[cfg(test)]
mod tests;
+5 -2
View File
@@ -231,10 +231,13 @@ fn straighten_layer_and_image() {
assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one history step");
assert_eq!(d(&s).size.width, 80);
assert!(d(&s).measurement.ruler.is_none());
// The Background: rotate the canvas and crop to the image.
// The Background used to rotate the canvas and crop it to the image; #12033 greys that state
// out, so the same crop now happens on a layer and only when it is asked for.
let mut s = session(80, 60, 16);
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [40, 40]})).unwrap();
let r = s.execute("image.analysis.straightenLayer", json!({})).unwrap();
assert!(!s.is_enabled("image.analysis.straightenLayer"), "the Background is greyed out (#12033)");
s.execute("layer.new.layer", json!({})).unwrap();
let r = s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap();
assert_eq!(r["cropped"], true);
assert_eq!(r["angle"].as_f64().unwrap().abs(), 45.0);
let nd = d(&s);
@@ -0,0 +1,259 @@
//! Straighten Layer's enabled states and its hidden-layer refusal, measured against the reference
//! application (#12033).
//!
//! With a ruler line drawn the reference greys the button out for the Background, two or more
//! selected layers, a group, a layer with Lock All and a layer with Lock Position. A hidden target
//! layer keeps the button enabled: the click answers an alert ("Could not straighten the layer
//! because the target layer is hidden.") and nothing changes. Pixel, text and smart object layers
//! stay enabled and are rotated.
//!
//! A layer with a mask, a shape or vector layer, an adjustment layer, artboards and the other lock
//! kinds are *not measured* there: they keep today's behaviour, so the tests below only pin that
//! the new check does not reach them.
use photocraft_doc::LayerId;
use super::*;
const CMD: &str = "image.analysis.straightenLayer";
/// A white document with a Background, as File > New makes one.
fn session(w: u32, h: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
s
}
/// The same document in CMYK at 16 bits, which the reference also straightens.
fn cmyk_16(w: u32, h: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "mode": "cmyk", "depth": 16, "background": "white"})).unwrap();
s
}
/// A ruler line to straighten by: without one the command is off for every target.
fn rule(s: &mut Session) {
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
}
/// A block of opaque pixels on the layer: an empty layer has nothing to transform, which would
/// hide the state under test behind "nothing to transform". The colour has the layer's own channel
/// count, so it works for RGB, Grayscale and CMYK at 8 and 16 bits alike.
fn paint(s: &mut Session, l: LayerId) {
s.edit("paint", |doc, _| {
let surf = doc.layer_mut(l).unwrap().surface_mut().unwrap();
let mut px = vec![0.0; surf.channels()];
if let Some(first) = px.first_mut() {
*first = 1.0;
}
if let Some(last) = px.last_mut() {
*last = 1.0;
}
surf.fill_rect(Rect::new(10, 10, 50, 20), &px);
Ok(())
})
.unwrap();
}
/// A new pixel layer with something on it, which `layer.new.layer` makes the active one.
fn pixel_layer(s: &mut Session, name: &str) -> LayerId {
let l = LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap());
paint(s, l);
l
}
/// A type layer over the canvas.
fn text_layer(s: &mut Session) -> LayerId {
LayerId(s.execute("type.create", json!({"x": 40, "y": 50, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap())
}
/// A pixel layer turned into a smart object.
fn smart_layer(s: &mut Session) -> LayerId {
let l = pixel_layer(s, "Smart");
s.execute("layer.smartObjects.convertToSmartObject", json!({"layer": l.0})).unwrap();
l
}
fn doc_of(s: &Session) -> Arc<Document> {
s.active().unwrap().doc.clone()
}
fn steps(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
/// A state the reference greys the button out for: the engine says the command is off, so the menu
/// item and the options-bar button follow, and a call answered anyway (the CLI, the control channel,
/// an action step) is refused as a disabled command rather than run. Nothing is touched: the
/// document is the same `Arc`, no History step is added and the ruler line stays.
fn assert_greyed(s: &mut Session, what: &str) {
let (before, history) = (doc_of(s), steps(s));
assert!(!s.is_enabled(CMD), "{what}: the button is greyed out");
let e = s.execute(CMD, json!({})).unwrap_err();
let disabled = matches!(&e, EngineError::Disabled(id, _) if id == CMD);
assert!(disabled, "{what}: refused as a disabled command, got {e}");
assert!(Arc::ptr_eq(&before, &doc_of(s)), "{what}: the document was not touched");
assert_eq!(steps(s), history, "{what}: no History step");
assert!(doc_of(s).measurement.ruler.is_some(), "{what}: the ruler line is still there");
}
/// The angle the ruler line of [`rule`] straightens by.
const ROT: f64 = 4.7636;
#[test]
fn the_background_greys_straighten_layer_out() {
// Today it rotates the canvas and crops it (800 x 600 becomes 500 x 375); the reference has no
// button for it at all.
let mut s = session(100, 80);
assert!(doc_of(&s).is_background(s.active().unwrap().active_layer.unwrap()), "the Background is the target");
rule(&mut s);
assert_greyed(&mut s, "the Background");
}
#[test]
fn two_selected_layers_grey_straighten_layer_out() {
let mut s = session(100, 80);
let a = pixel_layer(&mut s, "One");
let b = pixel_layer(&mut s, "Two");
s.execute("layer.select", json!({"layer": a.0})).unwrap();
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both selected");
rule(&mut s);
assert_greyed(&mut s, "two selected layers");
// Back to one layer, the button is live again.
s.execute("layer.select", json!({"layer": b.0})).unwrap();
assert!(s.is_enabled(CMD), "one selected layer");
}
#[test]
fn a_group_greys_straighten_layer_out() {
let mut s = session(100, 80);
pixel_layer(&mut s, "Inner");
s.execute("layer.groupLayers", json!({})).unwrap();
let g = s.active().unwrap().active_layer.unwrap();
assert!(doc_of(&s).layer(g).unwrap().is_group(), "the new group is the target");
rule(&mut s);
assert_greyed(&mut s, "a group");
// A layer inside the group is a layer, so the button is on for it.
let inner = doc_of(&s).layer(g).unwrap().children().unwrap()[0].id;
s.execute("layer.select", json!({"layer": inner.0})).unwrap();
assert!(s.is_enabled(CMD), "a layer in a group");
}
#[test]
fn lock_all_and_lock_position_grey_straighten_layer_out() {
// Measured: both grey the button. Today it is enabled and the command fails with
// `layer "Colors" is locked`, which is what a greyed button cannot do any more.
for key in ["all", "position"] {
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Colors");
s.execute("layer.setProps", json!({"layer": l.0, "locks": {key: true}})).unwrap();
rule(&mut s);
assert_greyed(&mut s, &format!("Lock {}", if key == "all" { "All" } else { "Position" }));
}
}
#[test]
fn the_other_lock_kinds_are_not_reached_by_the_new_check() {
// Not measured in the reference, so they keep today's behaviour: the button stays on and the
// command answers as it does now.
for key in ["transparency", "pixels", "artboard"] {
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Colors");
s.execute("layer.setProps", json!({"layer": l.0, "locks": {key: true}})).unwrap();
rule(&mut s);
assert!(s.is_enabled(CMD), "Lock {key}: not measured, still enabled");
}
}
#[test]
fn a_hidden_layer_stays_enabled_and_is_refused_with_the_alert() {
// The one measured refusal: the button is on, the click shows the alert and nothing changes.
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Gone");
s.execute("layer.setProps", json!({"layer": l.0, "visible": false})).unwrap();
rule(&mut s);
let (before, history) = (doc_of(&s), steps(&s));
assert!(s.is_enabled(CMD), "a hidden layer keeps the button on");
let e = s.execute(CMD, json!({})).unwrap_err();
assert_eq!(e.to_string(), STRAIGHTEN_HIDDEN_ERROR, "the reference's alert text");
assert!(matches!(e, EngineError::Other(_)), "an alert, not a greyed state: {e}");
assert!(Arc::ptr_eq(&before, &doc_of(&s)), "nothing changed");
assert_eq!(steps(&s), history, "no History step");
assert!(doc_of(&s).measurement.ruler.is_some(), "a straighten that never ran leaves the ruler line");
}
#[test]
fn a_layer_hidden_with_its_group_is_refused_the_same_way() {
// A layer inside a hidden group is hidden, as for the painting tools (#571).
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Inner");
s.execute("layer.groupLayers", json!({})).unwrap();
let g = s.active().unwrap().active_layer.unwrap();
s.execute("layer.setProps", json!({"layer": g.0, "visible": false})).unwrap();
s.execute("layer.select", json!({"layer": l.0})).unwrap();
rule(&mut s);
let (before, history) = (doc_of(&s), steps(&s));
assert!(s.is_enabled(CMD), "the target is a layer, not the group");
assert_eq!(s.execute(CMD, json!({})).unwrap_err().to_string(), STRAIGHTEN_HIDDEN_ERROR);
assert!(Arc::ptr_eq(&before, &doc_of(&s)));
assert_eq!(steps(&s), history);
}
#[test]
fn without_a_ruler_line_the_button_stays_greyed_for_every_layer() {
let mut s = session(100, 80);
pixel_layer(&mut s, "Paint");
assert!(!s.is_enabled(CMD), "no ruler line");
s.execute("layer.setProps", json!({"layer": s.active().unwrap().active_layer.unwrap().0, "visible": false})).unwrap();
assert!(!s.is_enabled(CMD), "a hidden layer without a ruler line stays greyed, not enabled");
}
#[test]
fn a_single_visible_layer_still_rotates_without_cropping() {
// The pin for the state that stays: the layer turns about the canvas centre, the canvas does not.
let mut s = session(100, 80);
pixel_layer(&mut s, "Paint");
rule(&mut s);
let (history, size) = (steps(&s), (doc_of(&s).size.width, doc_of(&s).size.height));
assert!(s.is_enabled(CMD), "a layer is what the button is for");
let r = s.execute(CMD, json!({})).unwrap();
assert_eq!(r["cropped"], false, "{r}");
assert!((r["angle"].as_f64().unwrap() - ROT).abs() < 1e-3, "{r}");
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "the canvas keeps its size");
assert_eq!(steps(&s), history + 1, "one History step");
assert!(doc_of(&s).measurement.ruler.is_none(), "the ruler line is cleared");
assert!(s.undo());
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "and one Undo takes it back");
}
#[test]
fn pixel_text_and_smart_object_layers_stay_enabled_and_rotate() {
// Measured, also in a CMYK 16-bit document.
type Maker = (&'static str, fn(&mut Session) -> LayerId);
let make: [Maker; 3] = [("pixel", |s| pixel_layer(s, "Paint")), ("type", text_layer), ("smart object", smart_layer)];
for (what, make_layer) in make {
for new in [session as fn(u32, u32) -> Session, cmyk_16] {
let mut s = new(100, 80);
make_layer(&mut s);
rule(&mut s);
assert!(s.is_enabled(CMD), "{what}: enabled");
let r = s.execute(CMD, json!({}));
let r = r.unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(r["cropped"], false, "{what}: rotated, not cropped");
assert!((r["angle"].as_f64().unwrap() - ROT).abs() < 1e-3, "{what}: {r}");
}
}
}
#[test]
fn an_explicit_crop_still_crops_for_automation() {
// The `crop` param stays available to automation where the command is enabled.
let mut s = session(100, 80);
pixel_layer(&mut s, "Paint");
rule(&mut s);
let r = s.execute(CMD, json!({"crop": true})).unwrap();
assert_eq!(r["cropped"], true, "{r}");
let d = doc_of(&s);
assert!(d.size.width < 100 && d.size.height < 80, "the canvas is rotated and cropped to {:?}", [d.size.width, d.size.height]);
}
@@ -223,24 +223,24 @@ fn bad_layers_params_are_errors_not_panics() {
}
#[test]
fn straighten_layer_rotates_every_selected_layer() {
// Photoshop's Straighten Layer turns all the selected layers, not just the active one; it
// goes through `edit.transform` without a layer, so it takes the selection like Free Transform.
fn straighten_layer_wants_one_selected_layer() {
// #12033: the reference greys Straighten Layer out while two layers are selected, so it no
// longer turns the whole selection the way Free Transform does
// (`free_transform_moves_every_selected_layer_in_one_step` covers that).
let (mut s, paint, text) = two_layers();
let (p0, m0) = (bounds(&s, paint), text_matrix(&s, text));
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
let steps = s.active().unwrap().history.past_len();
let r = s.execute("image.analysis.straightenLayer", json!({})).unwrap();
assert_eq!(r["cropped"], false);
assert!(bounds(&s, paint) != p0, "the selected pixel layer turned too");
assert!(text_matrix(&s, text)[1].abs() > 0.05 && m0[1].abs() < 1e-9, "the active type layer turned");
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one history step");
assert!(s.undo());
assert_eq!((bounds(&s, paint), text_matrix(&s, text)), (p0, m0), "and one Undo takes both back");
assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both selected, the type layer active");
assert!(!s.is_enabled("image.analysis.straightenLayer"), "two selected layers");
assert!(s.execute("image.analysis.straightenLayer", json!({})).is_err());
assert_eq!((bounds(&s, paint), text_matrix(&s, text)), (p0, m0), "nothing turned");
assert_eq!(s.active().unwrap().history.past_len(), steps, "and no history step");
// With one layer selected, only that layer turns.
s.execute("layer.select", json!({"layer": paint.0})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
assert!(s.is_enabled("image.analysis.straightenLayer"), "a single layer");
s.execute("image.analysis.straightenLayer", json!({})).unwrap();
assert!(bounds(&s, paint) != p0);
assert_eq!(text_matrix(&s, text), m0, "an unselected layer stays put");
+18 -3
View File
@@ -7,6 +7,10 @@
//! part of the serialisable UI state so the control channel can read and drive it). The Color
//! Sampler points themselves live in the engine (`DocState.color_samplers`) so every front end
//! shares them; this module only maps pointer input and draws the numbered markers.
//!
//! The Ruler options bar's Straighten Layer button is on when the engine's check says so, and a
//! hidden target layer answers its click with the reference's alert rather than the status line
//! (#12033).
use egui::{Align2, Color32, CornerRadius, FontId, Pos2, RichText, Stroke, pos2, vec2};
use photocraft_doc::{Document, Ruler};
@@ -15,7 +19,7 @@ use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, ViewXform};
use crate::state::Tool;
use crate::state::{DialogKind, Tool};
use crate::theme::Tokens;
/// What a pointer drag is doing (not serialised).
@@ -526,8 +530,19 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
crate::widgets::vline(ui, 22.0);
crate::widgets::checkbox(ui, &mut app.ui.analysis.use_measurement_scale, tl!("Use Measurement Scale"));
let has = doc.measurement.ruler.is_some();
if ui.add_enabled_ui(has, |ui| crate::widgets::secondary_button(ui, tl!("Straighten Layer"), 0.0)).inner.clicked() {
let _ = app.run("image.analysis.straightenLayer", json!({}));
// The engine decides this button's state, so it goes grey for exactly the targets
// Straighten Layer is off for: the Background, several selected layers, a group and a
// layer locked in place (#12033).
let straighten = app.session.is_enabled("image.analysis.straightenLayer");
if ui.add_enabled_ui(straighten, |ui| crate::widgets::secondary_button(ui, tl!("Straighten Layer"), 0.0)).inner.clicked() {
// A hidden target layer keeps the button on and answers the click with the
// reference's alert (its message and an OK button), changing nothing (#12033).
if let Err(why) = app.run("image.analysis.straightenLayer", json!({}))
&& why == photocraft_engine::analysis_cmds::STRAIGHTEN_HIDDEN_ERROR
{
let message = photocraft_engine::analysis_cmds::STRAIGHTEN_HIDDEN_ERROR;
app.ui.open_dialog(DialogKind::Error, json!({"message": tl!(message)}).as_object().cloned().unwrap_or_default());
}
}
if ui.add_enabled_ui(has, |ui| crate::widgets::secondary_button(ui, tl!("Clear"), 0.0)).inner.clicked() {
let _ = app.run("image.analysis.rulerTool", json!({"clear": true}));
@@ -296,3 +296,120 @@ fn count_size_fields_send_whole_numbers_the_engine_applies() {
let g = &app.session.active().unwrap().doc.measurement.count_groups[0];
assert_eq!((g.marker_size, g.label_size), (8, 20));
}
// ---------------------------------------------------------------- Straighten Layer button (#12033)
/// The Ruler options bar, drawn wide enough for its buttons to show.
fn ruler_bar(mut app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> {
use egui::vec2;
app.ui.tool = Tool::Ruler;
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 60.0)).build_ui_state(
|ui: &mut egui::Ui, app: &mut PhotocraftApp| {
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
crate::panels::options_bar(app, ui);
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro);
h.run_steps(4);
h
}
/// A ruler line to straighten by, without one the button is off for every target.
fn rule(app: &mut PhotocraftApp) {
app.run("image.analysis.rulerTool", json!({"start": [10, 30], "end": [150, 25]})).unwrap();
}
/// The message of every open error dialog, in the order they were opened.
fn alerts(app: &PhotocraftApp) -> Vec<&str> {
app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(|m| m.as_str())).collect()
}
/// Each case opens one of the targets #12033 measured, on top of the plain document `app()` makes.
fn add_layer(app: &mut PhotocraftApp, name: &str) -> u64 {
app.run("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap()
}
fn on_a_layer(app: &mut PhotocraftApp) {
add_layer(app, "Paint");
}
fn on_the_background(_: &mut PhotocraftApp) {}
fn on_two_layers(app: &mut PhotocraftApp) {
let a = add_layer(app, "One");
let b = add_layer(app, "Two");
app.run("layer.select", json!({"layer": a})).unwrap();
app.run("layer.select", json!({"layer": b, "mode": "add"})).unwrap();
}
fn on_a_group(app: &mut PhotocraftApp) {
add_layer(app, "Inner");
app.run("layer.groupLayers", json!({})).unwrap();
}
fn locked(app: &mut PhotocraftApp, key: &str) {
let l = add_layer(app, "Colors");
app.run("layer.setProps", json!({"layer": l, "locks": {key: true}})).unwrap();
}
fn on_lock_all(app: &mut PhotocraftApp) {
locked(app, "all");
}
fn on_lock_position(app: &mut PhotocraftApp) {
locked(app, "position");
}
/// #12033: the options bar asks the engine, so the button is greyed out for exactly the targets
/// `image.analysis.straightenLayer` is off for - the Background, two or more selected layers, a
/// group, Lock All and Lock Position - and live for a layer.
#[test]
fn the_straighten_layer_button_greys_out_where_the_command_is_off() {
use egui_kittest::kittest::{NodeT, Queryable};
type Case = (&'static str, fn(&mut PhotocraftApp), bool);
let cases: [Case; 6] = [
("a pixel layer", on_a_layer, true),
("the Background", on_the_background, false),
("two selected layers", on_two_layers, false),
("a group", on_a_group, false),
("Lock All", on_lock_all, false),
("Lock Position", on_lock_position, false),
];
for (what, prepare, live) in cases {
let (mut app, _) = app();
prepare(&mut app);
rule(&mut app);
let h = ruler_bar(app);
assert_eq!(h.state().session.is_enabled("image.analysis.straightenLayer"), live, "{what}: the command's own check");
let button = h.get_by_label("Straighten Layer").accesskit_node();
assert_eq!(!button.is_disabled(), live, "{what}: the options-bar button follows the command");
// The other Ruler button is unaffected: a ruler line is there to clear in every state.
assert!(!h.get_by_label("Clear").accesskit_node().is_disabled(), "{what}: Clear stays on");
}
}
/// #12033: a hidden target layer is the one state that keeps its button. The click answers with the
/// reference's alert - its measured message and an OK button - instead of the status line, and the
/// document, its History and the ruler line stay as they were.
#[test]
fn a_hidden_layer_keeps_the_button_and_the_click_shows_the_alert() {
use egui_kittest::kittest::{NodeT, Queryable};
let (mut app, _) = app();
let l = app.run("layer.new.layer", json!({"name": "Gone"})).unwrap()["layer"].as_u64().unwrap();
app.run("layer.setProps", json!({"layer": l, "visible": false})).unwrap();
rule(&mut app);
let mut h = ruler_bar(app);
assert!(!h.get_by_label("Straighten Layer").accesskit_node().is_disabled(), "a hidden layer keeps the button on");
let (before, steps) = (h.state().session.active().unwrap().doc.clone(), h.state().session.active().unwrap().history.past_len());
h.get_by_label("Straighten Layer").click();
h.run_steps(2);
let st = h.state();
assert_eq!(alerts(st), [photocraft_engine::analysis_cmds::STRAIGHTEN_HIDDEN_ERROR], "one alert with the reference's text");
let now = st.session.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&before, &now.doc), "the document was not touched");
assert_eq!(now.history.past_len(), steps, "no History step");
assert!(now.doc.measurement.ruler.is_some(), "the ruler line is still there");
}