Merge origin/main into craft-i18n-cutover

Keeps the deletion of the in-repo catalogs; #12357's Layer Via Copy/Cut
rows are in craft-i18n.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Martin BallandClaude Opus 5.5 committed 2026-11-08 22:28:32 +00:00
commit dd39514ef0
117 files changed
+7874 -331

No files matched your search

@@ -0,0 +1,71 @@
//! #11897: the Brush's chosen Clear on the Background paints as Normal. The options bar turns
//! Clear off at the press there (`clear_off_on_background` in ui-egui), so the engine never sees
//! it; a `"mode": "clear"` stroke that does reach the Background is a held `~`, which keeps
//! erasing to the background colour. On a pixel layer Clear still erases, and the Eraser on the
//! Background still paints the background colour.
use crate::Session;
use serde_json::{Value, json};
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap();
s.tools.foreground = BLACK;
s.tools.background = GREEN;
s
}
fn pixel(s: &mut Session, x: i32, y: i32) -> [f32; 4] {
let v = s.execute("document.pixel", json!({"x": x, "y": y})).unwrap();
let a: Vec<f32> = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap() as f32).collect();
[a[0], a[1], a[2], a[3]]
}
fn close(a: [f32; 4], b: [f32; 4]) -> bool {
a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= 0.02)
}
/// A hard stroke across (10..30, 10), as the canvas sends it in Clear mode.
fn clear_stroke() -> Value {
json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0, "erase": true, "mode": "clear"})
}
/// A held `~` on the Background erases to the background colour, as before #11897.
#[test]
fn a_clear_stroke_on_the_background_still_paints_the_background_colour() {
let mut s = session();
s.execute("paint.stroke", clear_stroke()).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, GREEN), "painted {p:?}, not the foreground");
assert_eq!(s.active().unwrap().history.undo_label(), Some("Brush Tool"));
}
#[test]
fn a_normal_stroke_on_the_background_paints_the_foreground() {
let mut s = session();
s.execute("paint.stroke", json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0})).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, BLACK), "{p:?}");
}
#[test]
fn clear_on_a_pixel_layer_still_erases() {
let mut s = session();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": [1.0, 0.0, 0.0, 1.0]})).unwrap();
s.execute("paint.stroke", clear_stroke()).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, WHITE), "erased down to the white Background: {p:?}");
}
#[test]
fn the_eraser_on_the_background_still_paints_the_background_colour() {
let mut s = session();
s.execute("paint.stroke", json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0, "erase": true})).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, GREEN), "{p:?}");
}
+19 -1
View File
@@ -242,9 +242,27 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) {
if let Some(wp) = &mut doc.work_path {
*wp = wp.transform(a);
}
// A note's icon point maps with the pixels; its popup keeps its size (#11795). Under Image Size
// and Canvas Size it also keeps its offset from the icon, as Photoshop's does. Where it sits
// after a turn or flip wasn't measured, so it keeps today's origin there: the top-left of the
// mapped rectangle.
for n in &mut doc.notes {
// An all-zero popup means none is stored (PSD export writes its default one): keep it.
if n.popup == [0.0; 4] {
n.position = map_pt(a, n.position);
continue;
}
let [px, py] = n.position;
let (dx, dy, w, h) = (n.popup[0] - px, n.popup[1] - py, n.popup[2] - n.popup[0], n.popup[3] - n.popup[1]);
n.position = map_pt(a, n.position);
n.popup = map_box(a, n.popup);
let [m0, m1, m2, m3, ..] = a.m;
let [x, y] = if m1.abs() < EPS && m2.abs() < EPS && m0 > 0.0 && m3 > 0.0 {
[n.position[0] + dx, n.position[1] + dy]
} else {
let [l, t, ..] = map_box(a, n.popup);
[l, t]
};
n.popup = [x, y, x + w, y + h];
}
for g in &mut doc.measurement.count_groups {
for p in &mut g.points {
+6
View File
@@ -69,6 +69,8 @@ pub mod comps_cmds;
pub mod contour_lib_cmds;
#[cfg(test)]
mod count_delete_group_tests;
#[cfg(test)]
mod count_history_names_tests;
pub mod cutout_cmds;
pub mod distort_cmds;
pub mod document_preset_cmds;
@@ -114,6 +116,8 @@ pub(super) mod migrate_cmds;
pub mod mode_cmds;
pub mod multichannel_cmds;
pub mod notes_cmds;
#[cfg(test)]
mod notes_stored_values_tests;
mod ops;
pub mod paint_cmds;
mod params;
@@ -150,6 +154,8 @@ pub mod type_area_cmds;
pub mod type_caret_cmds;
pub mod type_cmds;
pub mod type_extra_cmds;
#[cfg(test)]
mod type_indexed_mode_tests;
pub mod type_mask_cmds;
pub mod type_spell_cmds;
pub mod type_styles_cmds;
+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}");
+92 -8
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,60 @@ 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; an active id the document no longer holds is refused.
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?;
// An id the document no longer holds: `Session::edit` keeps the *selected* layers valid but
// not the active one, so an edit that drops the active layer can leave a stale id behind.
// Turning and cropping the whole canvas for a layer that is not there is the worse answer, and
// `select_layer` and `restore_layer_selection` both refuse such an id.
let Some(layer) = st.doc.layer(id) else {
return Some("no active layer");
};
if st.doc.is_background(id) {
return Some("the Background");
}
if layer.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 +777,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}));
@@ -796,7 +861,7 @@ fn count_add(s: &mut Session, p: &Value) -> Result<Value> {
if gi.is_some_and(|i| i >= group_count) {
return Err(bad("count.add", "no such group"));
}
let n = s.edit("Count", |d, _| {
let n = s.edit("Add Count Object", |d, _| {
if d.measurement.count_groups.is_empty() {
let g = new_group(d, None, None);
d.measurement.count_groups.push(g);
@@ -846,7 +911,7 @@ fn locate(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
fn count_remove(s: &mut Session, p: &Value) -> Result<Value> {
let (g, i) = locate(s, p, "count.remove")?;
s.edit("Count", |d, _| {
s.edit("Delete Count Object", |d, _| {
d.measurement.count_groups[g].points.remove(i);
Ok(())
})?;
@@ -856,7 +921,7 @@ fn count_remove(s: &mut Session, p: &Value) -> Result<Value> {
fn count_move(s: &mut Session, p: &Value) -> Result<Value> {
let to = point(p.get("to")).ok_or_else(|| bad("count.move", "pass `to`: [x, y]"))?;
let (g, i) = locate(s, p, "count.move")?;
s.edit("Count", |d, _| {
s.edit("Drag Count Object", |d, _| {
d.measurement.count_groups[g].points[i] = to;
Ok(())
})?;
@@ -881,7 +946,7 @@ fn count_clear(s: &mut Session, p: &Value) -> Result<Value> {
fn count_new_group(s: &mut Session, p: &Value) -> Result<Value> {
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
let color = color_of("count.newGroup", p, "color")?;
s.edit("New Count Group", |d, _| {
s.edit("Add Count Group", |d, _| {
let g = new_group(d, name, color);
d.measurement.count_groups.push(g);
d.measurement.active_count_group = d.measurement.count_groups.len() - 1;
@@ -949,8 +1014,24 @@ fn count_set_group(s: &mut Session, p: &Value) -> Result<Value> {
}
let activate = p.get("active").and_then(Value::as_bool) == Some(true) || p.as_object().is_some_and(|o| o.len() == 1 && o.contains_key("group"));
let changed = grp != d.measurement.count_groups[g];
if changed || (activate && d.measurement.active_count_group != g) {
s.edit("Count Group Options", |d, _| {
let switches = activate && d.measurement.active_count_group != g;
if changed || switches {
// One field changed: Photoshop's name for it (#11763). Several fields, or a switch of the
// current group (not measured), keep "Count Group Options".
let old = &d.measurement.count_groups[g];
let fields = [
(grp.name != old.name, "Set Count Group Name"),
(grp.visible != old.visible, "Set Count Group Visibility"),
(grp.color != old.color, "Set Count Draw Color"),
(grp.marker_size != old.marker_size, "Set Count Marker Size"),
(grp.label_size != old.label_size, "Set Count Font Size"),
];
let mut one = fields.iter().filter(|(c, _)| *c).map(|(_, l)| *l);
let label = match (one.next(), one.next()) {
(Some(l), None) if !switches => l,
_ => "Count Group Options",
};
s.edit(label, |d, _| {
d.measurement.count_groups[g] = grp;
if activate {
d.measurement.active_count_group = g;
@@ -1297,8 +1378,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 +1413,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,283 @@
//! 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 an_active_layer_the_document_no_longer_holds_is_refused() {
// `Session::edit` prunes the selected layers but not the active id, so an edit that drops the
// active layer can leave one behind (`select_layer` and `restore_layer_selection` both refuse
// such an id). The command must then say it is off, not rotate and crop the whole canvas for a
// layer that is not there.
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Gone");
s.edit("drop", |doc, _| {
doc.layers.retain(|layer| layer.id != l);
Ok(())
})
.unwrap();
assert_eq!(s.active().unwrap().active_layer, Some(l), "the target still points at the dropped layer");
assert!(doc_of(&s).layer(l).is_none(), "and the document does not hold it");
rule(&mut s);
assert_greyed(&mut s, "an active layer that is gone");
// The destructive case this closes: `crop` asks for the canvas, which would turn and shrink for
// a target that no longer exists.
let size = (doc_of(&s).size.width, doc_of(&s).size.height);
assert!(s.execute(CMD, json!({"crop": true})).is_err());
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "the canvas kept its size");
}
#[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]);
}
@@ -0,0 +1,100 @@
//! #11763: each Count tool edit gets the reference application's History name. A `count.setGroup`
//! that changes exactly one field takes that field's name; several fields at once, or a switch of
//! the current group, keep "Count Group Options".
use serde_json::{Value, json};
use crate::Session;
/// A 100 × 100 document with one count group holding one marker at 10,10 (its first state is
/// "Add Count Object").
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
s.execute("count.add", json!({"x": 10, "y": 10})).unwrap();
s
}
fn steps(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
/// Run `id` and return the History name of the one step it added.
fn named(s: &mut Session, id: &str, p: Value) -> String {
let before = steps(s);
s.execute(id, p.clone()).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
assert_eq!(steps(s), before + 1, "{id} {p} adds exactly one step");
s.active().unwrap().history.undo_label().unwrap_or_default().to_string()
}
#[test]
fn marker_edits_are_add_drag_and_delete_count_object() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
// The first click makes "Count Group 1" too, still one "Add Count Object" step.
assert_eq!(named(&mut s, "count.add", json!({"x": 10, "y": 10})), "Add Count Object");
assert_eq!(named(&mut s, "count.add", json!({"x": 40, "y": 40})), "Add Count Object");
assert_eq!(named(&mut s, "count.move", json!({"x": 10, "y": 10, "to": [20, 20]})), "Drag Count Object");
assert_eq!(named(&mut s, "count.remove", json!({"x": 40, "y": 40})), "Delete Count Object");
}
#[test]
fn group_edits_keep_or_take_their_names() {
let mut s = session();
assert_eq!(named(&mut s, "count.newGroup", json!({"name": "Leaves"})), "Add Count Group");
assert_eq!(named(&mut s, "count.clear", json!({})), "Clear Count");
assert_eq!(named(&mut s, "count.deleteGroup", json!({})), "Delete Count Group");
}
#[test]
fn a_single_field_change_uses_that_fields_name() {
for (p, want) in [
(json!({"name": "Seeds"}), "Set Count Group Name"),
(json!({"visible": false}), "Set Count Group Visibility"),
(json!({"color": "#204080"}), "Set Count Draw Color"),
(json!({"markerSize": 5}), "Set Count Marker Size"),
(json!({"labelSize": 20}), "Set Count Font Size"),
] {
let mut s = session();
assert_eq!(named(&mut s, "count.setGroup", p.clone()), want, "{p}");
}
}
#[test]
fn several_fields_at_once_keep_count_group_options() {
let mut s = session();
assert_eq!(named(&mut s, "count.setGroup", json!({"markerSize": 5, "labelSize": 20})), "Count Group Options");
// A field sent with its current value doesn't count as a change.
let mut s = session();
let name = s.execute("image.analysis.countTool", json!({})).unwrap()["groups"][0]["name"].clone();
assert_eq!(named(&mut s, "count.setGroup", json!({"name": name, "markerSize": 6})), "Set Count Marker Size");
}
#[test]
fn switching_the_current_group_keeps_todays_name() {
let mut s = session();
s.execute("count.newGroup", json!({"name": "Two"})).unwrap();
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 0})), "Count Group Options", "only `group`");
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 1, "active": true})), "Count Group Options", "`active: true`, no field change");
// A field change together with a switch is two changes: today's name too.
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 0, "active": true, "visible": false})), "Count Group Options");
}
#[test]
fn no_change_adds_no_step_and_bad_params_stay_errors() {
let mut s = session();
let before = steps(&s);
// The current group's own values: nothing changes, no step.
s.execute("count.setGroup", json!({"group": 0})).unwrap();
assert_eq!(steps(&s), before);
for (id, p) in [
("count.setGroup", json!({"group": 9, "name": "x"})),
("count.setGroup", json!({"markerSize": 2.5})),
("count.move", json!({"x": 90, "y": 90, "to": [1, 1]})),
("count.remove", json!({"x": 90, "y": 90})),
("count.add", json!({"x": 1, "y": 1, "group": 7})),
] {
assert!(s.execute(id, p.clone()).is_err(), "{id} {p}");
assert_eq!(steps(&s), before, "{id} {p} adds no step");
}
}
+2 -2
View File
@@ -1267,8 +1267,8 @@ pub fn specs() -> Vec<CommandSpec> {
has_clip,
|s, p| paste(s, p, true)
),
spec!("layer.new.layerViaCopy", "Layer via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)),
spec!("layer.new.layerViaCut", "Layer via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)),
spec!("layer.new.layerViaCopy", "Layer Via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)),
spec!("layer.new.layerViaCut", "Layer Via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)),
spec!("layer.mergeVisible", "Merge Visible", &["Layer"], Some("Cmd+Shift+E"), "{}", has_doc, |s, _| merge_visible(s)),
spec!("image.autoTone", "Auto Tone", &["Image"], Some("Cmd+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "tone")),
spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")),
+16
View File
@@ -24,6 +24,7 @@ mod batch_run;
mod export;
mod info;
mod open;
mod open_as_smart_object;
mod paths;
mod place_steps;
mod processing;
@@ -50,6 +51,8 @@ pub(crate) use open::{BatchOpen, batch_open_notice, batch_open_params, remember_
pub use open::{PLACE_EMBEDDED, open_bytes_as, open_bytes_as_with_options, place_bytes, raw_defaults};
pub(crate) use open::{PlaceInput, apply_place, import, import_with_options, tag_exr_colorspace};
use open::{approve_memory, close_all, close_others, open_as, place, revert};
pub use open_as_smart_object::admit_as_smart_object;
use open_as_smart_object::open_as_smart_object;
use paths::is_file;
#[cfg(test)]
use paths::openable_name;
@@ -285,6 +288,15 @@ pub fn specs() -> Vec<CommandSpec> {
native,
open_as
),
spec!(
"file.openAsSmartObject",
"Open as Smart Object…",
&["File"],
None,
r##"{"path":str,"confirmDamage":bool=false (a damaged PSD waits for an answer, as File > Open's does)} (opens the file as a new untitled document named "<file name without its last extension>-N" with the file's size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer named after the file) → {document, docId, name, layer, warnings, color, smartObject} (or {held, name, warnings, color, damaged, smartObject} while a prompt waits)"##,
native,
open_as_smart_object
),
// One-shot permission for one file, not something to replay later: never journaled or
// recorded in an action, since replaying it in another session/on another file would
// grant memory use nobody approved (#10897). It also releases the queued source on both
@@ -421,6 +433,10 @@ mod tests;
#[path = "file_cmds/place_job_tests.rs"]
mod place_job_tests;
#[cfg(test)]
#[path = "file_cmds/open_as_smart_object_tests.rs"]
mod open_as_smart_object_tests;
#[cfg(test)]
mod aces_exr_tests {
use super::*;
+9 -3
View File
@@ -74,9 +74,15 @@ fn import_result(name: &str, bytes: &[u8]) -> Result<photocraft_io::ImportResult
/// The one import path every caller shares: allocation checkpoint, native `.pcraft` and format
/// dispatch through `photocraft_io::import_with_options`, typed memory refusals, and the
/// preview-only refusal wherever the import came from.
fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
pub(super) fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
import_result_for_open(name, bytes, opts).map(|(r, _)| r)
}
/// [`import_result_with`], also telling whether a PSD/PSB had damaged data it recovered from, as
/// File › Open's job learns it (`photocraft_io::import_for_open`), so an interactive caller can ask.
pub(super) fn import_result_for_open(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<(photocraft_io::ImportResult, bool)> {
crate::allocation::checkpoint("importing document")?;
let r = photocraft_io::import_with_options(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
let (r, damaged) = photocraft_io::import_for_open(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
// Auxiliary imports return only a document and cannot surface the preview's fidelity warning.
// Open has its own warning-preserving path; never silently place or process a thumbnail.
if r.preview_only {
@@ -84,7 +90,7 @@ fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOpti
"{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here"
)));
}
Ok(r)
Ok((r, damaged))
}
// ---------- close / revert / save a copy / open as ----------
@@ -0,0 +1,115 @@
//! File › Open as Smart Object… (#11678): a file opens as a new untitled document with the file's
//! size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer.
//!
//! The layer is built as File › Place Embedded builds one (an embedded smart object at the file's own
//! size and position `0, 0`) and put into the document before it is admitted, so the opening
//! snapshot already shows it.
use super::open::import_result_for_open;
use super::paths::{file_name, read_file, stem, untitled_name};
use super::{Affine, Arc, Document, Layer, LayerContent, Result, Session, SmartObject, SmartSource, Value, flattened_checked, json, str_param};
use crate::layer_place::Place;
const CMD: &str = "file.openAsSmartObject";
/// The history step's name.
const LABEL: &str = "Open As Smart Object";
/// Opens the file as a document holding one embedded smart object. The read, decode and flatten
/// run on the job's worker (inline under `execute`); the document is built, given File › Open's
/// colour policy and admitted, or held for its profile prompt, when the job is applied. The reply
/// has the shape of File › Open's job: `{document, docId, name, layer, warnings, color}`, or
/// `{held, name, warnings, color, smartObject}` while the profile prompt waits.
pub(super) fn open_as_smart_object(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path", CMD)?.to_string();
let name = file_name(&path);
let opts = crate::jobs::import_options(s.prefs());
// An interactive caller (the app) asks before opening a PSD that had damaged data, as File > Open does.
let confirm_damage = p.get("confirmDamage").and_then(Value::as_bool).unwrap_or(false);
crate::jobs::run(
s,
&format!("Opening {name}"),
false,
move |ctx| {
ctx.progress(0.0, "Reading");
let bytes = read_file(&path)?;
ctx.check()?;
ctx.progress(0.05, "Decoding");
let (r, damaged) = import_result_for_open(&name, &bytes, &opts)?;
ctx.check()?;
ctx.progress(0.9, "Flattening");
// The file as one image: the smart object's rendered contents.
let pixels = flattened_checked(&r.document, r.document.pixel_format(), CMD)?;
Ok((path, name, Arc::new(bytes), r, pixels, confirm_damage && damaged))
},
|s, (path, name, bytes, r, pixels, damaged)| apply(s, &path, &name, bytes, r, pixels, damaged),
)
}
fn apply(
s: &mut Session,
path: &str,
file: &str,
bytes: Arc<Vec<u8>>,
r: photocraft_io::ImportResult,
pixels: photocraft_raster::Surface,
damaged: bool,
) -> Result<Value> {
let warnings = r.warnings;
let mut src = r.document;
super::tag_exr_colorspace(s, file, &mut src);
super::raw_defaults(s, &warnings, &mut src);
let layer_name = stem(path);
// "<name>-1", the next free number while a document with that name is open.
let name = untitled_name(&layer_name, |n| s.documents().iter().any(|d| d.doc.name == n) || s.held_open_named(n));
let mut doc = Document::new(name.clone(), src.size, src.mode, src.depth);
doc.resolution_dpi = src.resolution_dpi;
doc.icc_profile = src.icc_profile.clone();
doc.color_table = src.color_table.clone();
doc.duotone = src.duotone.clone();
// Embedded (not linked): the original file name keeps its extension, so Edit Contents opens it.
let source = SmartSource::Embedded { file_name: file.to_string(), bytes };
let so = SmartObject::new(source, Affine { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] }, Some(pixels));
let layer = Layer::new(layer_name, LayerContent::Smart(so));
let layer_id = layer.id;
crate::layer_place::insert_new(&mut doc, None, layer, Place::AutoEditable);
// File › Open's completion: a raw has no embedded profile to ask about; otherwise the profile
// prompt holds the document, and without a question the Color Settings policy is applied.
let raw = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE));
let question = s.color.open_question(&doc).filter(|_| !raw);
if damaged || question.is_some() {
let held = s.hold_open(doc, false);
return Ok(json!({"held": held, "name": name, "warnings": warnings, "color": question, "damaged": damaged, "smartObject": true}));
}
let color = s.color.open_policy(&mut doc, s.prefs().file_handling.ignore_exif_profile_tag);
let index = admit_as_smart_object(s, doc);
let id = s.documents().get(index).map(|st| st.doc.id.0);
// Admission numbers the document again, so the reply reads the name it was admitted under.
let name = s.documents().get(index).map_or(name, |st| st.doc.name.clone());
Ok(json!({"document": index, "docId": id, "name": name, "layer": layer_id.0, "warnings": warnings, "color": color, "smartObject": true}))
}
/// Admits a document built by Open as Smart Object (one smart object layer) as an untitled
/// document: the opening snapshot already shows the placed layer, is named after it, and the
/// history is the single state "Open As Smart Object", as File › Open's is one state.
pub fn admit_as_smart_object(s: &mut Session, mut doc: Document) -> usize {
let layer_name = doc.layers.first().map(|l| l.name.clone());
// The number was free when the file was read, but documents held for their prompts did not count
// then, and one of them may have been cancelled since: take the first free one now, as each
// document is admitted.
if let Some(base) = &layer_name {
doc.name = untitled_name(base, |n| s.documents().iter().any(|d| d.doc.name == n));
}
// Untitled: no path, so Save asks where to save.
let index = s.add_document(doc, None);
if let Some(st) = s.active_mut() {
if let (Some(first), Some(name)) = (st.snapshots.iter_mut().find(|snap| snap.id == 0), layer_name) {
first.name = name;
}
st.history.set_current_label(LABEL);
}
index
}
@@ -0,0 +1,367 @@
//! File › Open as Smart Object… (#11678): a file opens as a new untitled document holding one
//! embedded smart object layer.
use super::*;
fn tmp(name: &str) -> String {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let d = std::env::temp_dir().join(format!("photocraft-open-as-so-{}-{name}-{id}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d.to_string_lossy().into_owned()
}
/// A small PNG with a gradient, so the pixels differ from place to place.
fn write_png(dir: &str, name: &str, w: u32, h: u32) -> String {
let px: Vec<u8> = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 255 / w) as u8, (y * 255 / h) as u8, ((x + y) % 256) as u8])).collect();
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let path = join(dir, name);
std::fs::write(&path, bytes).unwrap();
path
}
/// A two-layer 16-bit PSD at 300 ppi tagged with Display P3, made with the engine's own save.
fn write_psd16(dir: &str, name: &str, w: u32, h: u32) -> String {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "depth": 16})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap();
let path = join(dir, name);
save_doc(&s.active().unwrap().doc, &path, None).unwrap();
path
}
fn imported(path: &str) -> Document {
photocraft_io::import(&file_name(path), &std::fs::read(path).unwrap()).unwrap().document
}
fn active(s: &Session) -> &Document {
&s.active().unwrap().doc
}
fn names(s: &Session) -> Vec<String> {
s.documents().iter().map(|d| d.doc.name.clone()).collect()
}
/// The one layer of the active document, which must be an embedded smart object.
fn embedded(s: &Session) -> (String, String, Arc<Vec<u8>>) {
let d = active(s);
assert_eq!(d.layers.len(), 1, "one layer, not a Background plus a layer");
let layer = &d.layers[0];
match &layer.content {
LayerContent::Smart(so) => match &so.source {
SmartSource::Embedded { file_name, bytes } => (layer.name.clone(), file_name.clone(), Arc::clone(bytes)),
other => panic!("expected an embedded smart object, got {other:?}"),
},
_ => panic!("the layer is not a smart object"),
}
}
#[test]
fn a_png_opens_as_an_untitled_document_with_one_embedded_smart_object() {
let dir = tmp("png");
let path = write_png(&dir, "a_test.png", 64, 48);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(r["name"], "a_test-1", "{r}");
assert_eq!(s.documents().len(), 1);
let st = s.active().unwrap();
assert_eq!(st.doc.name, "a_test-1");
assert_eq!(st.path, None, "untitled: Save asks where to save");
let file = imported(&path);
let d = &st.doc;
assert_eq!((d.size.width, d.size.height), (64, 48));
assert_eq!(d.resolution_dpi, file.resolution_dpi);
assert_eq!((d.mode, d.depth), (file.mode, file.depth));
assert_eq!(d.icc_profile, file.icc_profile);
let (layer, original, bytes) = embedded(&s);
assert_eq!(layer, "a_test", "named after the file without its extension");
assert_eq!(original, "a_test.png", "Edit Contents opens the original file name");
assert_eq!(*bytes, std::fs::read(&path).unwrap(), "the file itself is embedded");
}
#[test]
fn the_smart_object_shows_the_file() {
let dir = tmp("pixels");
let path = write_png(&dir, "grad.png", 32, 16);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let want = photocraft_compose::render(&imported(&path), Rect::new(0, 0, 32, 16)).px.clone();
let got = photocraft_compose::render(active(&s), Rect::new(0, 0, 32, 16)).px.clone();
assert_eq!(got, want);
}
#[test]
fn a_16_bit_psd_keeps_size_resolution_mode_depth_and_profile() {
let dir = tmp("psd");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let mut s = Session::new();
// The files were measured in the working spaces, where nothing asks; Preserve keeps Display P3.
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let file = imported(&path);
assert_eq!(file.resolution_dpi, 300.0);
assert!(file.icc_profile.is_some());
let d = active(&s);
assert_eq!(d.name, "c.layered-1", "only the last extension is dropped");
assert_eq!((d.size.width, d.size.height), (40, 30));
assert_eq!(d.resolution_dpi, 300.0);
assert_eq!((d.mode, d.depth), (file.mode, file.depth));
assert_eq!(d.depth, photocraft_doc::SampleType::U16);
assert_eq!(d.icc_profile, file.icc_profile);
let (layer, original, _) = embedded(&s);
assert_eq!((layer.as_str(), original.as_str()), ("c.layered", "c.layered.psd"));
}
#[test]
fn history_is_the_single_state_open_as_smart_object() {
let dir = tmp("history");
let path = write_png(&dir, "a_test.png", 16, 16);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let st = s.active().unwrap();
assert_eq!(st.history.entries(), ["Open As Smart Object"], "one state, as File > Open has");
assert_eq!(st.snapshots.first().map(|snap| snap.name.as_str()), Some("a_test"), "the opening snapshot is named after the layer");
}
#[test]
fn the_opening_snapshot_shows_the_placed_smart_object() {
let dir = tmp("snapshot");
let path = write_png(&dir, "a_test.png", 16, 16);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let st = s.active().unwrap();
let first = st.snapshots.first().unwrap();
assert_eq!(first.doc.layers.len(), 1, "snapshot 0 already holds the smart object");
assert!(matches!(first.doc.layers[0].content, LayerContent::Smart(_)));
assert_eq!(first.layers.active, Some(first.doc.layers[0].id));
assert_eq!(st.active_layer, Some(first.doc.layers[0].id));
assert_eq!(st.history.entries(), ["Open As Smart Object"]);
}
#[test]
fn the_number_is_the_next_free_one_and_starts_again_after_they_close() {
let dir = tmp("numbers");
let path = write_png(&dir, "a_test.png", 8, 8);
let mut s = Session::new();
for _ in 0..3 {
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
}
assert_eq!(names(&s), ["a_test-1", "a_test-2", "a_test-3"]);
while !s.documents().is_empty() {
s.close(0);
}
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(names(&s), ["a_test-1"]);
}
#[test]
fn a_plain_open_of_the_same_file_is_unchanged() {
let dir = tmp("plain");
let path = write_png(&dir, "a_test.png", 8, 8);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
open_bytes_as(&mut s, &path, &std::fs::read(&path).unwrap(), None, Some(path.clone())).unwrap();
assert_eq!(names(&s), ["a_test-1", "a_test.png"]);
assert!(matches!(active(&s).layers[0].content, LayerContent::Raster(_)));
}
#[test]
fn several_files_open_one_document_each() {
let dir = tmp("several");
let a = write_png(&dir, "a_test.png", 8, 8);
let b = write_psd16(&dir, "d_other.psd", 12, 10);
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": a})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": b})).unwrap();
assert_eq!(names(&s), ["a_test-1", "d_other-1"]);
for st in s.documents() {
assert_eq!(st.doc.layers.len(), 1);
assert!(matches!(st.doc.layers[0].content, LayerContent::Smart(_)));
}
}
#[test]
fn a_missing_or_unreadable_file_is_an_error_not_a_crash() {
let dir = tmp("bad");
let junk = join(&dir, "notes.png");
std::fs::write(&junk, b"this is not an image").unwrap();
let text = join(&dir, "readme.txt");
std::fs::write(&text, b"hello").unwrap();
let mut s = Session::new();
for path in [join(&dir, "missing.png"), junk, text] {
let r = s.execute("file.openAsSmartObject", json!({"path": path}));
assert!(r.is_err(), "{path}: {r:?}");
}
assert!(s.documents().is_empty(), "a failed open leaves no document behind");
}
#[test]
fn bad_params_are_errors() {
let mut s = Session::new();
for params in [json!({}), json!({"path": 7}), json!({"path": null})] {
let r = s.execute("file.openAsSmartObject", params.clone());
assert!(r.is_err(), "{params}: {r:?}");
}
assert!(s.documents().is_empty());
}
fn job(r: crate::jobs::Started) -> crate::jobs::JobId {
match r {
crate::jobs::Started::Job(id) => id,
crate::jobs::Started::Done(v) => panic!("expected a background job, ran inline: {v}"),
}
}
/// Poll until job `id` ends (or 60 s pass); returns its event.
fn wait_event(s: &mut Session, id: crate::jobs::JobId) -> crate::jobs::JobEvent {
let t = std::time::Instant::now();
loop {
if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) {
return e;
}
assert!(t.elapsed() < std::time::Duration::from_secs(60), "job {id:?} did not finish");
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
#[test]
fn the_import_runs_as_a_job_when_started() {
let dir = tmp("job");
let path = write_png(&dir, "a_test.png", 32, 24);
let mut s = Session::new();
let id = job(s.start("file.openAsSmartObject", json!({"path": path})).unwrap());
assert!(s.documents().is_empty(), "nothing is admitted before the job is applied");
let e = wait_event(&mut s, id);
let crate::jobs::JobOutcome::Done(v) = &e.outcome else { panic!("{e:?}") };
assert!(v["docId"].is_u64(), "{v}");
assert_eq!(v["name"], "a_test-1", "{v}");
assert_eq!(s.documents().len(), 1);
embedded(&s);
}
#[test]
fn the_colour_policy_matches_file_open() {
let dir = tmp("policy");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let settings = json!({"askOnMismatch": false, "policyRgb": "convert"});
let mut open = Session::new();
open.execute("edit.colorSettings", settings.clone()).unwrap();
open.execute("file.openAs", json!({"path": path})).unwrap();
let mut so = Session::new();
so.execute("edit.colorSettings", settings).unwrap();
so.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let (a, b) = (active(&open), active(&so));
assert_eq!(a.icc_profile, b.icc_profile, "Convert is applied as File > Open applies it");
assert_eq!((a.mode, a.depth, a.size), (b.mode, b.depth, b.size));
assert_eq!(a.resolution_dpi, b.resolution_dpi);
}
#[test]
fn ask_when_opening_holds_the_document_like_file_open() {
let dir = tmp("ask");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(r["color"]["ask"], true, "{r}");
assert_eq!(r["smartObject"], true, "{r}");
assert!(r["held"].is_u64(), "{r}");
assert!(s.documents().is_empty(), "held for the profile prompt, not admitted");
let (doc, _) = s.take_held_open(r["held"].as_u64().unwrap()).unwrap();
assert_eq!(doc.name, "c.layered-1");
assert_eq!(doc.layers.len(), 1);
assert!(matches!(doc.layers[0].content, LayerContent::Smart(_)));
}
#[test]
fn the_reply_flags_a_smart_object_so_a_queued_document_keeps_its_history_label() {
let dir = tmp("flag");
let path = write_png(&dir, "a_test.png", 16, 12);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(r["smartObject"], true, "{r}");
}
#[test]
fn a_damaged_psd_is_held_for_confirmation_when_asked_and_opens_otherwise() {
let dir = tmp("damaged");
let path = join(&dir, "d.psd");
std::fs::write(&path, crate::jobs::psd_open_fixture::make_psd(true)).unwrap();
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
let r = s.execute("file.openAsSmartObject", json!({"path": path, "confirmDamage": true})).unwrap();
assert_eq!(r["damaged"], true, "{r}");
assert_eq!(r["smartObject"], true, "{r}");
assert!(r["held"].is_u64(), "{r}");
assert!(s.documents().is_empty(), "held for the damage prompt, not admitted");
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert!(r["docId"].is_u64(), "a headless caller opens the recovered content: {r}");
}
#[test]
fn a_document_held_for_its_prompt_does_not_share_its_name_with_the_next() {
let dir = tmp("held-name");
let path = write_psd16(&dir, "a_test.psd", 20, 20);
let mut s = Session::new();
let first = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let second = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(first["name"], "a_test-1");
assert_eq!(second["name"], "a_test-2", "the held document's name is taken: {second}");
// Both held docs leave the session for the app's queue; admitting them one by one numbers each.
let (a, _) = s.take_held_open(first["held"].as_u64().unwrap()).unwrap();
let (b, _) = s.take_held_open(second["held"].as_u64().unwrap()).unwrap();
admit_as_smart_object(&mut s, a);
admit_as_smart_object(&mut s, b);
assert_eq!(names(&s), ["a_test-1", "a_test-2"]);
let mut t = Session::new();
let (c, _) = {
let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
t.take_held_open(r["held"].as_u64().unwrap()).unwrap()
};
let (d, _) = {
t.execute("edit.colorSettings", json!({"askOnMismatch": true})).unwrap();
let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
t.take_held_open(r["held"].as_u64().unwrap()).unwrap()
};
assert_eq!(c.name, d.name, "taken out of the session, both are named a_test-1 when read");
admit_as_smart_object(&mut t, c);
admit_as_smart_object(&mut t, d);
assert_eq!(names(&t), ["a_test-1", "a_test-2"], "the second takes the next free number when admitted");
}
#[test]
fn a_cancelled_hold_frees_its_number_for_the_one_admitted_after_it() {
let dir = tmp("cancelled-hold");
let path = write_psd16(&dir, "photo.psd", 20, 20);
let mut s = Session::new();
let first = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let second = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!((first["name"].as_str(), second["name"].as_str()), (Some("photo-1"), Some("photo-2")));
// photo-1 is cancelled while photo-2 waits; photo-2 is admitted with nothing open.
s.take_held_open(first["held"].as_u64().unwrap()).unwrap();
let (b, _) = s.take_held_open(second["held"].as_u64().unwrap()).unwrap();
admit_as_smart_object(&mut s, b);
assert_eq!(names(&s), ["photo-1"], "the first free number is taken at admission, with no collision");
}
#[test]
fn the_reply_names_the_document_as_admitted() {
let dir = tmp("reply-name");
let path = write_psd16(&dir, "photo.psd", 20, 20);
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"askOnMismatch": true})).unwrap();
let held = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(held["name"], "photo-1", "{held}");
assert!(held["held"].is_u64(), "{held}");
// The next open skips the prompt: photo-1 is held, so the number read was 2, but admission takes the first free one.
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(names(&s), ["photo-1"], "{r}");
assert_eq!(r["name"], "photo-1", "the reply carries the name the document was admitted under: {r}");
}
+10 -3
View File
@@ -5,9 +5,12 @@ use photocraft_io::{ImportResult, raw::RawTuning};
use super::{EngineError, Result, Session, Value, json};
/// The prior settings of a sidecar, and its crop (in the raw's stored orientation).
type Prior = (CameraRaw, Option<photocraft_io::camera_raw_xmp::Crop>);
/// Read only a bounded regular XMP file. No ambient sidecar reads are granted to gated sessions.
#[cfg(not(target_arch = "wasm32"))]
fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
fn prior_settings(path: Option<&str>) -> Result<Option<Prior>> {
use std::io::Read;
let Some(path) = path else { return Ok(None) };
let sidecar = match path.rsplit_once('.') {
@@ -31,11 +34,11 @@ fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
if !report.ignored.is_empty() {
return Err(EngineError::Other(format!("{sidecar}: unsupported prior RAW settings: {}", report.ignored.join(", "))));
}
Ok(Some(settings))
Ok(Some((settings, report.crop)))
}
#[cfg(target_arch = "wasm32")]
fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
fn prior_settings(path: Option<&str>) -> Result<Option<Prior>> {
if path.is_some() { Err(EngineError::Other("cannot read RAW sidecars on the web".into())) } else { Ok(None) }
}
@@ -67,6 +70,8 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8])
return Err(EngineError::Other("RAW sidecar opening requires a trusted session; no implicit read capability is available".into()));
}
let prior = prior_settings(path)?;
let crop = prior.as_ref().and_then(|(_, crop)| *crop);
let prior = prior.map(|(settings, _)| settings);
let mut settings = prior.clone().unwrap_or_default();
let opts = crate::jobs::import_options(s.prefs());
let mut imported = photocraft_io::import_with_options(name, bytes, &opts).map_err(|error| EngineError::Other(format!("{name}: {error}")))?;
@@ -87,6 +92,8 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8])
clarity: settings.clarity,
texture: settings.texture,
dehaze: settings.dehaze,
// The sidecar's crop, as the interactive open applies it: before the Camera Raw step.
crop,
};
if tuning != (RawTuning { demosaic: opts.demosaic, ..Default::default() }) {
super::open::raw_defaults(s, &imported.warnings, &mut imported.document);
+21
View File
@@ -734,6 +734,27 @@ fn batch_quiet_raw_applies_prior_settings_and_workflow_without_touching_inputs()
assert!(s.batch_open_notices.is_none());
}
/// #9985: quiet RAW opening crops to the sidecar's crop, as the interactive open does.
#[test]
fn batch_quiet_raw_applies_the_sidecar_crop() {
use photocraft_raw::testgen::{DngSpec, mosaic, scene};
let dir = tmp("batch-quiet-raw-crop");
let path = join(&dir, "raw.dng");
let (w, h) = (24, 16);
let bytes = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 65535)).build();
std::fs::write(&path, &bytes).unwrap();
let crop = photocraft_io::camera_raw_xmp::Crop { top: 0.25, left: 0.125, bottom: 0.75, right: 0.625 };
let xmp = photocraft_io::camera_raw_xmp::save_with_crop(&photocraft_algo::camera_raw::CameraRaw::default(), Some(crop));
std::fs::write(join(&dir, "raw.xmp"), &xmp).unwrap();
let mut s = Session::new();
let output = join(&dir, "out");
let p = json!({"input":[path],"output":output,"format":"psd","suppressOpenOptions":true,"suppressWarnings":true,"steps":[]});
let result = s.execute("file.automate.batch", p).unwrap();
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
let actual = photocraft_io::import("raw.psd", &std::fs::read(join(&output, "raw.psd")).unwrap()).unwrap().document;
assert_eq!((actual.size.width, actual.size.height), (12, 8), "the 24x16 frame cropped to x 3..15, y 4..12");
}
fn tmp(name: &str) -> String {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+32 -10
View File
@@ -22,14 +22,33 @@ fn has_notes(s: &Session) -> std::result::Result<(), String> {
if s.active().is_some_and(|d| !d.doc.notes.is_empty()) { Ok(()) } else { Err("the document has no notes".into()) }
}
/// PDF-style date (`D:YYYYMMDDhhmmssZ`) as Photoshop stores in notes; empty without a clock.
/// Photoshop's default note colour (#11795): RGB 255, 255, 131 (stored as 16-bit 0x8383 blue).
pub const DEFAULT_NOTE_COLOR: [f32; 3] = [1.0, 1.0, 131.0 / 255.0];
/// The PDF date (`D:YYYYMMDDHHMMSS+HH'mm'`) Photoshop stores in a note: local time with its
/// offset from UTC (#11795), through chrono. Empty without a clock (the web build).
fn pdf_date() -> String {
let iso = crate::analysis_cmds::now_iso();
if iso.len() < 19 {
return String::new();
#[cfg(not(target_arch = "wasm32"))]
{
let now = chrono::Local::now();
pdf_date_at(&now.with_timezone(now.offset()))
}
let digits: String = iso[..19].chars().filter(char::is_ascii_digit).collect();
format!("D:{digits}Z")
#[cfg(target_arch = "wasm32")]
{
String::new()
}
}
/// [`pdf_date`] for the moment `at`: its own wall-clock time and UTC offset.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn pdf_date_at<Tz: chrono::TimeZone>(at: &chrono::DateTime<Tz>) -> String
where
Tz::Offset: std::fmt::Display,
{
use chrono::Offset;
let off = at.offset().fix().local_minus_utc();
let (sign, off) = if off < 0 { ('-', -off) } else { ('+', off) };
format!("D:{}{sign}{:02}'{:02}'", at.format("%Y%m%d%H%M%S"), off / 3600, off % 3600 / 60)
}
pub fn note_json(i: usize, n: &Note) -> Value {
@@ -44,7 +63,8 @@ fn color_of(cmd: &str, p: &Value) -> Result<Option<Color>> {
if p.get("color").is_none() {
return Ok(None);
}
let c = crate::commands::color_param(cmd, p, "color", [1.0, 1.0, 0.51, 1.0])?;
let [r, g, b] = DEFAULT_NOTE_COLOR;
let c = crate::commands::color_param(cmd, p, "color", [r, g, b, 1.0])?;
Ok(Some(Color::rgb(c[0], c[1], c[2])))
}
@@ -65,10 +85,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
author: p.get("author").and_then(Value::as_str).unwrap_or("").to_string(),
text: p.get("text").and_then(Value::as_str).unwrap_or("").to_string(),
position: [x, y],
popup: [x + 20.0, y + 20.0, x + 260.0, y + 160.0],
// Photoshop's popup: 240 × 140, at the icon's top-left + (8, 10) (#11795).
popup: [x + 8.0, y + 10.0, x + 248.0, y + 150.0],
color: Color::rgb(DEFAULT_NOTE_COLOR[0], DEFAULT_NOTE_COLOR[1], DEFAULT_NOTE_COLOR[2]),
open: p.get("open").and_then(Value::as_bool).unwrap_or(true),
modified: pdf_date(),
..Default::default()
};
if let Some(c) = color_of(CMD, p)? {
n.color = c;
@@ -270,7 +291,8 @@ mod tests {
let d = s.active().unwrap().doc.clone();
assert_eq!(d.notes[0].text, "fixed");
assert_eq!(d.notes[0].position, [20.0, 12.0]);
assert_eq!(d.notes[0].popup[0], 40.0);
// The popup travels with its icon: 20 + 8 (#11795).
assert_eq!(d.notes[0].popup[0], 28.0);
// Unchanged edits don't add history.
let before = s.active().unwrap().history.past_len();
assert_eq!(s.execute("notes.set", json!({"index": 0, "text": "fixed"})).unwrap()["changed"], false);
@@ -0,0 +1,116 @@
//! #11795: what a new note stores, as in Photoshop: colour 255, 255, 131, a 240 × 140 popup at the
//! icon's top-left + (8, 10), and a local-time PDF date with its offset. Document operations move
//! the popup with its icon and keep its size.
use chrono::{FixedOffset, TimeZone};
use serde_json::json;
use super::notes_cmds::{DEFAULT_NOTE_COLOR, pdf_date_at};
use crate::Session;
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
}
fn note(s: &Session, i: usize) -> photocraft_doc::Note {
s.active().unwrap().doc.notes[i].clone()
}
#[test]
fn a_new_note_has_the_default_colour_and_popup() {
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
let n = note(&s, 0);
let rgb = n.color.to_rgb();
assert_eq!(rgb.map(|v| (v * 255.0).round() as i32), [255, 255, 131], "{rgb:?}");
assert_eq!(DEFAULT_NOTE_COLOR.map(|v| (v * 65535.0).round() as u32), [0xffff, 0xffff, 0x8383], "the 16-bit components Photoshop saves");
assert_eq!(n.popup, [108.0, 110.0, 348.0, 250.0], "icon + (8, 10), 240 × 140");
// A note on the pasteboard keeps its popup there too.
s.execute("notes.add", json!({"x": -178, "y": 300})).unwrap();
assert_eq!(note(&s, 1).popup, [-170.0, 310.0, 70.0, 450.0]);
// An explicit colour still wins.
s.execute("notes.add", json!({"x": 10, "y": 10, "color": [0.25, 0.5, 1.0]})).unwrap();
assert_eq!(note(&s, 2).color.to_rgb(), [0.25, 0.5, 1.0]);
}
#[test]
fn the_date_is_local_time_with_its_offset() {
let at = |offset: i32| FixedOffset::east_opt(offset).unwrap().with_ymd_and_hms(2026, 11, 6, 20, 14, 55).unwrap();
assert_eq!(pdf_date_at(&at(3600)), "D:20261106201455+01'00'");
assert_eq!(pdf_date_at(&at(0)), "D:20261106201455+00'00'");
assert_eq!(pdf_date_at(&at(-(5 * 3600 + 30 * 60))), "D:20261106201455-05'30'");
// A new note's own date has that shape.
let mut s = session(100, 100);
s.execute("notes.add", json!({"x": 10, "y": 10})).unwrap();
let d = note(&s, 0).modified;
let b = d.as_bytes();
assert!(d.len() == 23 && d.starts_with("D:") && matches!(b[16], b'+' | b'-') && b[19] == b'\'' && b[22] == b'\'', "{d}");
assert!(d[2..16].chars().all(|c| c.is_ascii_digit()), "{d}");
}
#[test]
fn image_size_moves_the_icon_and_keeps_the_popup_size() {
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 99})).unwrap();
let before = note(&s, 0);
s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap();
let n = note(&s, 0);
assert_eq!(n.position, [50.0, 49.5], "the icon point scales as today");
let size = |p: [f64; 4]| [p[2] - p[0], p[3] - p[1]];
assert_eq!(size(n.popup), size(before.popup), "240 × 140 still");
assert_eq!([n.popup[0] - n.position[0], n.popup[1] - n.position[1]], [8.0, 10.0], "still at icon + (8, 10)");
}
#[test]
fn canvas_size_and_a_quarter_turn_keep_the_popup_size() {
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap();
let n = note(&s, 0);
assert_eq!(n.position, [0.0, 50.0], "moved by the canvas offset");
assert_eq!(n.popup, [8.0, 60.0, 248.0, 200.0]);
s.execute("image.imageRotation.90cw", json!({})).unwrap();
let r = note(&s, 0);
assert_eq!([r.popup[2] - r.popup[0], r.popup[3] - r.popup[1]], [240.0, 140.0], "a turn doesn't swap the popup's sides");
}
#[test]
fn a_mode_change_leaves_notes_alone() {
let mut s = session(100, 100);
s.execute("notes.add", json!({"x": 10, "y": 20})).unwrap();
let before = note(&s, 0);
s.execute("image.mode.cmyk", json!({})).unwrap();
assert_eq!(note(&s, 0), before);
}
#[test]
fn a_turn_keeps_todays_popup_origin_and_the_popup_size() {
// Where the popup sits after a turn wasn't measured (#11795), so it keeps today's origin (the
// top-left of the turned rectangle) and only the size rule applies.
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
// The popup [108, 110, 348, 250] turned 90° clockwise on a 400 px tall canvas spans x 150..290,
// y 108..348; it starts there and stays 240 × 140.
s.execute("image.imageRotation.90cw", json!({})).unwrap();
assert_eq!(note(&s, 0).popup, [150.0, 108.0, 390.0, 248.0]);
// A flip keeps today's mirrored popup, which already has its size.
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
s.execute("image.imageRotation.flipCanvasHorizontal", json!({})).unwrap();
assert_eq!(note(&s, 0).popup, [252.0, 110.0, 492.0, 250.0]);
}
#[test]
fn an_unset_popup_stays_unset_under_image_size() {
// An all-zero popup means "none stored": PSD export writes its default popup for it, so Image
// Size must not turn it into a 0 × 0 rectangle somewhere else.
let mut s = session(600, 400);
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
doc.notes.push(photocraft_doc::Note { position: [100.0, 100.0], ..Default::default() });
s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap();
let n = note(&s, 0);
assert_eq!(n.position, [50.0, 50.0]);
assert_eq!(n.popup, [0.0; 4]);
}
+1 -1
View File
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &[],
shortcut: None,
params: brush_params!(
r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal" → {"damage","offset","aligned","nextSource"}"#
r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal","wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges) → {"damage","offset","aligned","nextSource"}"#
),
enabled: has_pixel_layer,
run: healing_brush,
+26 -27
View File
@@ -130,26 +130,19 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
let from_live = live.is_some();
let map = clone_mapping(s, p, &stroke, CMD)?;
let off = map.offset();
let dmg =
run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| {
if let Some(l) = live {
*surf = l.surface;
return Ok(l.bounds);
}
if flag(p, "wrap", false) {
let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0);
renderer.push(&stroke.points);
renderer.finish();
let before = surf.clone();
let bounds = renderer.bounds();
return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode }
.draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD));
}
let (bounds, cov) = coverage(CMD, &stroke)?;
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?;
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
})?;
let dmg = run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| {
if let Some(l) = live {
*surf = l.surface;
return Ok(l.bounds);
}
if flag(p, "wrap", false) {
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |before, r| clone_sample(pre, id, before, which, r, &map, true, CMD));
}
let (bounds, cov) = coverage(CMD, &stroke)?;
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?;
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
})?;
let mut r = clone_result(dmg, off, aligned, p, &stroke);
if from_live {
r["fromLive"] = json!(true);
@@ -272,11 +265,14 @@ impl LiveRetouch {
/// Everything the stroke has touched so far.
pub fn bounds(&self) -> Rect {
let bounds = self.renderer.bounds().union(&self.tail);
if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) {
periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b))
} else {
bounds
}
if self.wraps() { periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) } else { bounds }
}
/// Whether the stroke repeats across the canvas edges (View › Pattern Preview). Only the Clone
/// Stamp and the Healing Brush do: the reference application's other retouching tools stop
/// at the edge.
fn wraps(&self) -> bool {
matches!(self.cmd.as_str(), "paint.cloneStamp" | "paint.healingBrush") && flag(&self.params, "wrap", false)
}
/// Every point rendered so far, in order.
@@ -328,7 +324,7 @@ impl LiveRetouch {
let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect();
self.points.extend_from_slice(&pts);
self.renderer.push(&pts);
if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) {
if self.wraps() {
return self.push_periodic();
}
let old = std::mem::replace(&mut self.tail, Rect::EMPTY);
@@ -360,6 +356,8 @@ impl LiveRetouch {
let LivePaint::Clone { which, map, cmd } = &self.paint else {
return Err(bad(&self.cmd, "periodic painting requires a clone source"));
};
let (pre, id, pre_surf, live_cmd) = (&self.pre, self.id, &self.pre_surf, self.cmd.as_str());
let paint = |r| clone_sample(pre, id, pre_surf, *which, r, map, true, cmd);
let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?;
periodic::Composite {
target: surf,
@@ -369,8 +367,9 @@ impl LiveRetouch {
selection: self.sel.as_ref(),
lock: self.lock,
mode: self.mode,
cmd: live_cmd,
}
.draw(dirty, &self.brush, &self.points, |r| clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, true, cmd))
.draw(dirty, &self.brush, &self.points, paint)
}
/// Redraw `r` from the pre-stroke pixels with the clone source through coverage `cov`.
+18 -2
View File
@@ -1,4 +1,5 @@
use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample};
use super::periodic;
use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers};
use super::{
BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad,
@@ -53,15 +54,30 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
let map = clone_mapping(s, p, &stroke, CMD)?;
let off = map.offset();
let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| {
// Pattern Preview: source and destination repeat across the canvas edges, so a stroke over
// a seam heals as one patch and goes on wherever it repeats.
let wrap = flag(p, "wrap", false);
let (bounds, cov) = coverage(CMD, &stroke)?;
let (g, cov) = pad_coverage(bounds, &cov, 2);
let fmt = surf.format();
let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?;
let src = clone_sample(pre, id, surf, which, g, &map, wrap, CMD)?;
// The destination the texture is fitted to: the layer itself, or what the user sees when
// sampling several layers (so healing onto an empty layer matches the composite).
let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) };
let dst = if wrap {
periodic::sample(pre, id, surf, which, g, CMD)?
} else if which == SampleLayers::Current {
Region::read(surf, g)
} else {
composite_region(pre, id, which, g, fmt)
};
let mask: Vec<bool> = cov.iter().map(|c| *c > 0.0).collect();
let healed = heal_region(&fmt, &src, &dst, &mask);
if wrap {
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| {
let part = healed.crop(r);
if part.rect == r { Ok(part) } else { Err(bad(CMD, "the healed patch does not cover the stroke")) }
});
}
Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode))
})?;
Ok(clone_result(dmg, off, aligned, p, &stroke))
+58 -5
View File
@@ -153,6 +153,8 @@ struct Plan {
/// Shift of the repaired area from the selection, and of the texture from the repaired area.
dst_shift: (i32, i32),
src_shift: (i32, i32),
/// Destination mode: a hard rectangular selection moves with the patch.
destination: bool,
offset: (i32, i32),
}
@@ -186,7 +188,7 @@ fn plan(s: &Session, p: &Value) -> Result<Plan> {
PatchMode::Source => ((0, 0), (dx, dy)),
PatchMode::Destination => ((dx, dy), (-dx, -dy)),
};
Ok(Plan { id, canvas, area, dst_shift, src_shift, offset: (dx, dy) })
Ok(Plan { id, canvas, area, dst_shift, src_shift, destination: mode == PatchMode::Destination, offset: (dx, dy) })
}
/// Heal `surf` at the selection (shifted by `dst_shift`) with texture read `src_shift` away, the
@@ -212,16 +214,63 @@ fn patch_surface(surf: &mut Surface, sel: &Surface, plan: &Plan, lock: bool, ste
apply_coverage(surf, g, &cov, 1.0, None, lock, &healed, BlendMode::Normal)
}
/// Rows scanned per band by [`is_hard_rect_within`], so the coverage buffer stays small.
const RECT_BAND_ROWS: i32 = 64;
/// Whether `sel` is a hard-edged rectangle: nothing selected outside its own `bounds` and every pixel
/// inside fully selected (the only Destination selection measured to move with the patch). The
/// bounds may reach past the canvas; the patched area is then only the part on the canvas. Bounds
/// of more than [`MAX_PIXELS`] pixels (the patch's own cap) are never classified as a hard
/// rectangle, so a huge selection moved mostly off the canvas is not scanned and stays in place.
fn is_hard_rect(sel: &Surface, bounds: Rect) -> bool {
is_hard_rect_within(sel, bounds, MAX_PIXELS)
}
/// [`is_hard_rect`] with the pixel `limit` given. Scans `bounds` in bands of [`RECT_BAND_ROWS`] rows
/// and stops at the first pixel that is not fully selected.
fn is_hard_rect_within(sel: &Surface, bounds: Rect, limit: u64) -> bool {
let (w, h) = ((i64::from(bounds.x1) - i64::from(bounds.x0)).max(0) as u64, (i64::from(bounds.y1) - i64::from(bounds.y0)).max(0) as u64);
if w.saturating_mul(h) > limit || sel.default_pixel().first().copied().unwrap_or(0.0) > 0.0 {
return false;
}
let mut y = bounds.y0;
while y < bounds.y1 {
let y1 = y.saturating_add(RECT_BAND_ROWS).min(bounds.y1);
if !coverage(sel, Rect::new(bounds.x0, y, bounds.x1, y1)).iter().all(|c| *c >= 1.0) {
return false;
}
y = y1;
}
true
}
pub(super) fn patch(s: &mut Session, p: &Value) -> Result<Value> {
if flag(p, "contentAware", false) {
return patch_content_aware(s, p);
}
let plan = plan(s, p)?;
let label = HISTORY_NAME;
let dmg = run_stroke(s, label, plan.id, p, |pre, surf, _, lock| {
let sel = pre.selection.as_ref().ok_or_else(|| bad(CMD, "select the area to patch first"))?;
Ok(patch_surface(surf, sel, &plan, lock, 1))
})?;
let dmg = if plan.destination {
// Destination: a plain rectangular selection moves with the patch, in the same history state.
let dmg = s.edit(label, |doc, _| {
let sel = doc.selection.clone().ok_or_else(|| bad(CMD, "select the area to patch first"))?;
let (surf, lock) = crate::channel_cmds::target_surface(doc, plan.id, p)?;
let dmg = patch_surface(surf, &sel, &plan, lock, 1);
let bounds = sel.content_bounds();
if is_hard_rect(&sel, bounds) {
let (dx, dy) = plan.offset;
doc.selection = Some(sel.translated(dx, dy, bounds));
}
Ok(dmg)
})?;
s.hint_damage(dmg);
dmg
} else {
run_stroke(s, label, plan.id, p, |pre, surf, _, lock| {
let sel = pre.selection.as_ref().ok_or_else(|| bad(CMD, "select the area to patch first"))?;
Ok(patch_surface(surf, sel, &plan, lock, 1))
})?
};
Ok(json!({ "damage": damage_json(dmg), "offset": [plan.offset.0, plan.offset.1] }))
}
@@ -305,3 +354,7 @@ fn patch_content_aware(s: &mut Session, p: &Value) -> Result<Value> {
},
)
}
#[cfg(test)]
#[path = "patch_destination_selection_tests.rs"]
mod patch_destination_selection_tests;
@@ -0,0 +1,203 @@
//! Patch in Destination mode moves a plain rectangular selection with the patch (#12119).
use super::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "depth": 8, "mode": "rgb"})).unwrap();
s.edit("setup", |doc, active| {
let b = doc.bounds();
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let fmt = surf.format();
let mut data = Vec::new();
for y in b.y0..b.y1 {
for x in b.x0..b.x1 {
let v = if (x / 8 + y / 8) % 2 == 0 { 0.2 } else { 0.8 };
let px = if x >= 400 { [0.1, 0.6, 0.2, 1.0] } else { [v, v, v, 1.0] };
data.extend(photocraft_raster::from_rgba(&fmt, px));
}
}
surf.write_region(b, &data);
Ok(())
})
.unwrap();
s
}
fn bounds(s: &mut Session) -> Value {
s.execute("document.inspect", json!({})).unwrap()["selectionBounds"].clone()
}
fn px(s: &Session, x: i32, y: i32) -> [f32; 4] {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
}
fn history_len(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
fn select_rect(s: &mut Session) {
s.execute("select.rect", json!({"x": 120, "y": 120, "width": 40, "height": 40})).unwrap();
}
const DESTINATION: fn() -> Value = || json!({"mode": "destination", "offset": [460, 280]});
#[test]
fn destination_moves_the_selection_with_the_patch_and_undo_restores_both() {
let mut s = session();
select_rect(&mut s);
let before = px(&s, 600, 420);
let source_before: Vec<[f32; 4]> = [(130, 130), (140, 140), (148, 140)].iter().map(|&(x, y)| px(&s, x, y)).collect();
let r = s.execute("paint.patch", DESTINATION()).unwrap();
assert_eq!(r["offset"], json!([460, 280]));
// The damage covers the patched area (the 40 px square at the destination, plus the solve's ring).
assert_eq!(r["damage"], json!([578, 398, 44, 44]));
assert_eq!(bounds(&mut s), json!([580, 400, 40, 40]));
assert_ne!(px(&s, 600, 420), before, "pixels changed too");
// Source pixels untouched.
let source_after: Vec<[f32; 4]> = [(130, 130), (140, 140), (148, 140)].iter().map(|&(x, y)| px(&s, x, y)).collect();
assert_eq!(source_after, source_before);
// The destination carries the source texture: the step between two neighbouring checker cells is kept
// in the same direction and at a similar strength (the seamless clone adds a smooth colour correction, and the
// red channel clamps at 0 on the dark green, so the step shrinks).
let step_src = px(&s, 140, 140)[0] - px(&s, 148, 140)[0];
let step_dst = px(&s, 600, 420)[0] - px(&s, 608, 420)[0];
assert!(step_src * step_dst > 0.0 && step_dst.abs() > 0.2, "texture kept: source step {step_src}, destination step {step_dst}");
// The moved selection is still a hard-edged rectangle exactly filling its bounds.
let d = s.active().unwrap();
let sel = d.doc.selection.as_ref().unwrap();
assert!(is_hard_rect(sel, sel.content_bounds()));
// One history state: a single undo brings back the pixels and the old selection.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
assert_eq!(px(&s, 600, 420), before);
}
#[test]
fn destination_selection_stays_when_it_is_not_a_plain_rectangle() {
let cases: [(&str, Value, Value); 4] = [
("feathered", json!({"x": 120, "y": 120, "width": 40, "height": 40, "feather": 6.0}), json!(null)),
("ellipse", json!({"x": 120, "y": 120, "width": 40, "height": 40, "ellipse": true}), json!(null)),
("lasso", json!({"points": [[120, 120], [160, 130], [140, 165]]}), json!("lasso")),
("rectangle with a hole", json!({"x": 120, "y": 120, "width": 40, "height": 40}), json!("hole")),
];
for (name, params, kind) in cases {
let mut s = session();
let cmd = if kind == json!("lasso") { "select.lasso" } else { "select.rect" };
s.execute(cmd, params).unwrap();
if kind == json!("hole") {
// Same bounds as the rectangle, but not every pixel inside is fully selected.
s.execute("select.rect", json!({"x": 135, "y": 135, "width": 10, "height": 10, "mode": "subtract"})).unwrap();
}
let sel_before = bounds(&mut s);
let area = |s: &Session| -> Vec<[f32; 4]> { (400..440).flat_map(|y| (580..620).map(move |x| (x, y))).map(|(x, y)| px(s, x, y)).collect() };
let before = area(&s);
s.execute("paint.patch", DESTINATION()).unwrap();
assert_eq!(bounds(&mut s), sel_before, "{name}: the selection stays in place");
assert_ne!(area(&s), before, "{name}: the patch still lands");
}
}
#[test]
fn partial_coverage_and_oversized_rectangles_are_not_constructible_apart_from_the_hole_case() {
// `plan.area` is the selection's own content bounds, so a rectangle larger than the area cannot
// exist, and the area is never wider than the selection. The only way the bounds equal the area
// yet coverage falls short is a hole (covered above). An inverted selection makes the area the
// whole canvas, which no non-zero drag can keep on the canvas, so Patch refuses it.
let mut s = session();
select_rect(&mut s);
s.execute("select.inverse", json!({})).unwrap();
assert!(s.execute("paint.patch", DESTINATION()).is_err());
}
#[test]
fn destination_without_a_selection_fails_and_leaves_history_alone() {
let mut s = session();
// A marker step after the setup, so a stray undo would be visible.
s.edit("marker", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
let h = history_len(&s);
assert!(s.execute("paint.patch", DESTINATION()).is_err());
assert_eq!(history_len(&s), h, "no history entry");
// Undo reverts the marker (the last real step), not the setup.
s.execute("edit.undo", json!({})).unwrap();
assert_ne!(px(&s, 15, 15), [1.0, 0.0, 0.0, 1.0], "the marker step was undone");
assert!((px(&s, 450, 300)[0] - 0.1).abs() < 0.01 && (px(&s, 450, 300)[1] - 0.6).abs() < 0.01, "the setup step is still there");
}
#[test]
fn redo_restores_the_patched_pixels_and_the_moved_selection() {
let mut s = session();
select_rect(&mut s);
let before = px(&s, 600, 420);
s.execute("paint.patch", DESTINATION()).unwrap();
let patched = px(&s, 600, 420);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
assert_eq!(px(&s, 600, 420), before);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(bounds(&mut s), json!([580, 400, 40, 40]));
assert_eq!(px(&s, 600, 420), patched);
}
#[test]
fn source_mode_keeps_the_selection() {
let mut s = session();
select_rect(&mut s);
s.execute("paint.patch", json!({"offset": [260, 0]})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
}
#[test]
fn content_aware_keeps_the_selection_and_changes_the_pixels() {
let mut s = session();
select_rect(&mut s);
// Content-Aware ignores the mode and fills the selection itself from the dragged-to place (the
// green half), so the pixels under the selection change.
let before = px(&s, 140, 140);
s.execute("paint.patch", json!({"offset": [400, 0], "contentAware": true})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
assert_ne!(px(&s, 140, 140), before, "the selected area was filled");
}
#[test]
fn destination_moves_a_hard_rectangle_that_extends_past_the_canvas() {
let mut s = session();
// 60x40 rectangle with 20 columns off the left edge; the part on the canvas is x 0..40.
s.execute("select.rect", json!({"x": 0, "y": 100, "width": 60, "height": 40})).unwrap();
s.execute("select.transformSelection", json!({"dx": -20, "dy": 0})).unwrap();
let sel_before = bounds(&mut s);
let before = px(&s, 480, 400);
s.execute("paint.patch", DESTINATION()).unwrap();
assert_ne!(px(&s, 480, 400), before, "the patch lands on the canvas part");
let d = s.active().unwrap();
let sel = d.doc.selection.as_ref().unwrap();
assert_eq!(sel.content_bounds(), Rect::new(440, 380, 500, 420), "the whole rectangle moved, off-canvas part included");
assert!(sel.read_region(Rect::new(440, 380, 500, 420)).chunks_exact(sel.channels().max(1)).all(|p| p[0] >= 1.0));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(bounds(&mut s), sel_before);
assert_eq!(px(&s, 480, 400), before);
}
#[test]
fn hard_rect_check_is_capped_and_scans_every_band() {
let mut s = session();
// 40x150 rectangle: three bands of 64 rows (64 + 64 + 22).
s.execute("select.rect", json!({"x": 100, "y": 100, "width": 40, "height": 150})).unwrap();
let d = s.active().unwrap();
let sel = d.doc.selection.as_ref().unwrap();
let b = sel.content_bounds();
assert_eq!(b, Rect::new(100, 100, 140, 250));
assert!(!is_hard_rect_within(sel, b, 5999), "over the limit is never a hard rectangle");
assert!(is_hard_rect_within(sel, b, 6000), "at the limit it is checked as usual");
assert!(is_hard_rect_within(sel, b, u64::MAX));
// A hole in the third band must still be found.
let mut holed = sel.clone();
let fmt = holed.format();
holed.write_region(Rect::new(120, 240, 121, 241), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 0.0, 0.0]));
assert!(!is_hard_rect_within(&holed, b, u64::MAX), "a hole past the first band fails the check");
}
+31 -2
View File
@@ -1,6 +1,6 @@
//! Bounded reads from the repeating document tile used by Pattern Preview.
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, StrokePoint, Surface, alpha_index, apply_coverage, bad};
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, Stroke, StrokePoint, Surface, alpha_index, apply_coverage, bad};
/// At most four disjoint rectangles in the document tile. Projecting the dirty area separately
/// from the stroke bounds avoids scanning the whole document when a small dab crosses a seam.
@@ -23,6 +23,33 @@ pub(super) fn project(rect: Rect, tile: Rect) -> Vec<Rect> {
ys.into_iter().flat_map(|(y0, y1)| xs.iter().map(move |&(x0, x1)| Rect::new(x0, y0, x1, y1))).collect()
}
/// A composite tool's stroke wrapped around the document: `paint` gives the pixels for a
/// rectangle in the stroke's own coordinates, from the target as it was before the stroke, and
/// they go on through the stroke's coverage wherever it repeats on the document.
#[allow(clippy::too_many_arguments)]
pub(super) fn stroke(
pre: &Document,
target: &mut Surface,
stroke: &Stroke,
selection: Option<&Surface>,
lock: bool,
mode: BlendMode,
cmd: &str,
mut paint: impl FnMut(&Surface, Rect) -> Result<Region>,
) -> Result<Rect> {
let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0);
renderer.push(&stroke.points);
renderer.finish();
let before = target.clone();
let bounds = renderer.bounds();
Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd }.draw(
bounds,
&stroke.brush,
&stroke.points,
|r| paint(&before, r),
)
}
/// Composite periodic copies of one stroke, restoring each dirty patch from pre-stroke pixels.
/// Each dab wraps once, then builds flow towards its opacity ceiling. Stroke opacity and
/// selection are applied once after all dabs, including repeated visits through other tiles.
@@ -34,6 +61,8 @@ pub(super) struct Composite<'a> {
pub selection: Option<&'a Surface>,
pub lock: bool,
pub mode: BlendMode,
/// The command an over-budget stroke's error names.
pub cmd: &'a str,
}
impl Composite<'_> {
@@ -138,7 +167,7 @@ impl Composite<'_> {
);
*work = work.saturating_add(r.width() as u64 * r.height() as u64);
if *work > 64 * 1024 * 1024 {
return Err(bad("paint.cloneStamp", "wrapped stroke exceeds its coverage budget"));
return Err(bad(self.cmd, "wrapped stroke exceeds its coverage budget"));
}
ctx.rasterize_into(dab, dual, r, &mut values, wet.then_some(&mut depths));
let mut sampled = None;
+189
View File
@@ -2532,3 +2532,192 @@ fn periodic_clone_interior_matches_ordinary_brush_masks_and_transparency() {
}
}
}
// ---------------------------------------------------------------------------------------------
// View › Pattern Preview: Clone Stamp and Healing Brush wrap across the canvas edges (#8883)
// ---------------------------------------------------------------------------------------------
/// The canvas the Pattern Preview tests wrap around.
const WRAP: (u32, u32) = (48, 36);
/// `texture` repeated every canvas, so each copy of a pixel holds the same colour.
fn tiled_texture(x: i32, y: i32) -> [f32; 4] {
texture(x.rem_euclid(WRAP.0 as i32), y.rem_euclid(WRAP.1 as i32))
}
/// A stroke from just inside the corner where the middle copy of a three-by-three tiling meets
/// the next copies, out across both of its edges.
fn corner_stroke(extra: &Value) -> Value {
let mut p = json!({"points": [[84, 64], [106, 79]], "size": 12, "hardness": 100});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
p
}
/// The stroke tools that wrap, with their options. Both composite a paint image through the
/// stroke's coverage (`periodic::Composite`), which matches the ordinary composite only within
/// rounding.
fn wrap_cases() -> [(&'static str, Value); 2] {
[("paint.healingBrush", json!({"offset": [-20, -14]})), ("paint.cloneStamp", json!({"offset": [-20, -14]}))]
}
/// The native-channel difference `periodic::Composite` may leave against the ordinary composite.
fn composite_tolerance(depth: u64) -> f32 {
match depth {
8 => 1.1 / 255.0,
16 => 1.1 / 65535.0,
_ => 0.00001,
}
}
#[test]
fn every_wrapping_stroke_paints_the_canvas_as_on_the_canvas_tiled_three_by_three() {
// A stroke with `"wrap": true` gives each pixel of the canvas what the same stroke gives the
// copy of that pixel it goes over, on a document holding the canvas tiled three by three.
let (w, h) = (WRAP.0 as usize, WRAP.1 as usize);
for depth in DEPTHS {
for (cmd, extra) in wrap_cases() {
let mut canvas = session(WRAP.0, WRAP.1, depth, "rgb");
paint_layer(&mut canvas, tiled_texture);
let mut tiled = session(3 * WRAP.0, 3 * WRAP.1, depth, "rgb");
paint_layer(&mut tiled, tiled_texture);
let (mut wrapped, plain) = (corner_stroke(&extra), corner_stroke(&extra));
wrapped["wrap"] = json!(true);
canvas.execute(cmd, wrapped).unwrap_or_else(|e| panic!("{cmd} at {depth}: {e}"));
let before = layer_pixels(&tiled);
tiled.execute(cmd, plain).unwrap();
let (got, want) = (layer_pixels(&canvas), layer_pixels(&tiled));
let n = got.len() / (w * h);
let at = |x: usize, y: usize| (y * 3 * w + x) * n..(y * 3 * w + x + 1) * n;
let tolerance = composite_tolerance(depth);
let (mut moved, mut edges) = (0, [false; 4]);
for y in 0..h {
for x in 0..w {
let copies = (0..3).flat_map(|j| (0..3).map(move |i| (x + i * w, y + j * h)));
let changed: Vec<_> = copies.filter(|&(u, v)| want[at(u, v)] != before[at(u, v)]).collect();
let (pixel, expected) = match changed.as_slice() {
[] => (&got[(y * w + x) * n..][..n], &before[at(x, y)]),
[(u, v)] => (&got[(y * w + x) * n..][..n], &want[at(*u, *v)]),
_ => panic!("{cmd}: ({x}, {y}) has two copies under the stroke"),
};
let error = pixel.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(error <= tolerance, "{cmd} {extra} at {depth}-bit: ({x}, {y}) is off by {error}");
if !changed.is_empty() {
moved += 1;
edges[0] |= x < 8;
edges[1] |= x >= w - 8;
edges[2] |= y < 8;
edges[3] |= y >= h - 8;
}
}
}
assert!(moved > 150 && edges.iter().all(|&e| e), "{cmd} {extra} at {depth}-bit: the stroke crossed both edges ({moved} px, {edges:?})");
}
}
}
#[test]
fn a_wrapped_stroke_inside_the_canvas_paints_as_an_ordinary_one() {
let p = json!({"points": [[130, 110], [150, 118], [168, 112]], "size": 14, "hardness": 60});
for depth in [8, 32] {
for (cmd, extra) in wrap_cases() {
let run = |wrap: bool| {
let mut s = session(300, 230, depth, "rgb");
paint_layer(&mut s, tiled_texture);
let mut q = p.clone();
for (k, v) in extra.as_object().unwrap() {
q[k] = v.clone();
}
q["wrap"] = json!(wrap);
s.execute(cmd, q).unwrap();
layer_pixels(&s)
};
let (plain, wrapped) = (run(false), run(true));
let error = plain.iter().zip(&wrapped).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(error <= composite_tolerance(depth), "{cmd} {extra} at {depth}-bit: off by {error}");
}
}
}
#[test]
fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() {
for (cmd, extra) in wrap_cases() {
let mut s = session(16, 12, 8, "rgb");
paint_layer(&mut s, tiled_texture);
let before = layer_pixels(&s);
let mut p = json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 0, "wrap": true});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
let d = r["damage"].as_array().map(|d| d.iter().filter_map(Value::as_i64).collect::<Vec<_>>()).unwrap_or_default();
assert!(matches!(d.as_slice(), [x, y, w, h] if *x >= 0 && *y >= 0 && x + w <= 16 && y + h <= 12), "{cmd}: damage {d:?} is on the canvas");
let st = s.active().unwrap();
let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
assert!([(-1, 5), (16, 5), (5, -1), (5, 12), (40, 30)].iter().all(|&(x, y)| surf.rgba(x, y)[3] == 0.0), "{cmd}: nothing lands off the canvas");
assert!(layer_pixels(&s) != before, "{cmd} {extra}: the stroke changed the canvas");
}
}
#[test]
fn the_tools_the_reference_application_does_not_wrap_stop_at_the_canvas_edge() {
// Measured in the reference application: in Pattern Preview the Clone Stamp and Healing
// Brush carry a stroke on across the canvas edges, but Blur … Sponge, Color Replacement,
// Background Eraser, Pattern Stamp and History Brush warn that they don't wrap, and Spot
// Healing stops at the edge too. Their `wrap` stroke over the corner paints as the same
// stroke without it.
let points = [[36.0, 24.0], [58.0, 39.0]];
let cases = [
("paint.blur", json!({"strength": 80})),
("paint.sharpen", json!({"strength": 60})),
("paint.smudge", json!({"strength": 70})),
("paint.dodge", json!({"exposure": 60})),
("paint.burn", json!({"exposure": 40})),
("paint.sponge", json!({"mode": "saturate"})),
("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60})),
("paint.backgroundEraser", json!({"tolerance": 40})),
("paint.patternStamp", json!({"pattern": "Checkerboard"})),
("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true, "seed": 7})),
("paint.historyBrush", json!({"state": 1})),
("paint.spotHealing", json!({"type": "contentAware"})),
];
for (cmd, extra) in cases {
let run = |wrap: bool| {
let mut s = session(WRAP.0, WRAP.1, 8, "rgb");
paint_layer(&mut s, tiled_texture);
// Painted over since history state 1, so the History Brush has something to bring back.
paint_layer(&mut s, |x, y| tiled_texture(x + 7, y + 5));
let mut p = dab_opts(&points, 100, &extra);
p["size"] = json!(12);
p["wrap"] = json!(wrap);
let before = layer_pixels(&s);
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
(before, layer_pixels(&s))
};
let ((before, plain), (_, wrapped)) = (run(false), run(true));
assert!(plain != before, "{cmd} {extra}: the stroke paints inside the canvas");
assert!(wrapped == plain, "{cmd} {extra}: nothing comes back at the opposite edges");
}
}
#[test]
fn live_history_and_pattern_strokes_stop_at_the_canvas_edge() {
// The History Brush and aligned Pattern Stamp previews stop at the edge as their commits do.
let points = [[36.0, 24.0], [58.0, 39.0]];
let pts: Vec<_> = points.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect();
for (cmd, extra) in [("paint.historyBrush", json!({"state": 1})), ("paint.patternStamp", json!({"pattern": "Checkerboard"}))] {
let bounds = |wrap: bool| {
let mut s = session(WRAP.0, WRAP.1, 8, "rgb");
paint_layer(&mut s, tiled_texture);
paint_layer(&mut s, |_, _| [0.15, 0.2, 0.7, 1.0]);
let mut p = dab_opts(&points[..1], 100, &extra);
p["size"] = json!(12);
p["wrap"] = json!(wrap);
let mut live = LiveRetouch::begin(&s, cmd, &p).unwrap();
live.push(&pts[1..]).unwrap();
live.bounds()
};
assert_eq!(bounds(true), bounds(false), "{cmd}: the live stroke stays where it was drawn");
}
}
+10 -2
View File
@@ -17,6 +17,8 @@ mod modify_window;
mod color_range_performance;
#[cfg(test)]
mod color_range_window_tests;
#[cfg(test)]
mod wand_seed_outside_tests;
fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
@@ -139,9 +141,15 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
Some(plane) => plane,
None => sample_rgba8(s, b(p, "sampleAllLayers", false))?,
};
let region = sel::wand_region(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true));
drop(img);
let m = mode(p);
// Subtract and Intersect grow the region from the seed through the selection only (#11779).
// A global match (Contiguous off) ignores the limit, so it skips the full-area mask.
let contiguous = b(p, "contiguous", true);
let within = (contiguous && matches!(m, SelectionMode::Subtract | SelectionMode::Intersect))
.then(|| s.active().and_then(|st| st.doc.selection.as_ref()).map(|sel| sel::mask_from_surface(Some(sel), area)))
.flatten();
let region = sel::wand_region_within(&img, area, (x, y), f(p, "tolerance", 32.0), contiguous, b(p, "antiAlias", true), within.as_deref());
drop(img);
let selected = s.edit("Magic Wand", |doc, _| {
doc.selection = sel::combine_region(doc.selection.as_ref(), region.as_ref(), m);
Ok(doc.selection.is_some())
@@ -0,0 +1,113 @@
//! #11779: with Contiguous on, the Magic Wand's Subtract and Intersect grow the region from the
//! seed through the current selection only. A seed outside the selection subtracts nothing and
//! intersects to nothing.
use serde_json::json;
use crate::Session;
/// 800 × 600, white, with a grey ramp of ten 40 px blocks from x 100 (100, 105, …, 145).
fn ramp() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
for k in 0..10 {
let v = 100 + 5 * k;
s.execute("select.rect", json!({"x": 100 + 40 * k, "y": 350, "width": 40, "height": 100})).unwrap();
s.execute("edit.fill", json!({"color": format!("#{v:02x}{v:02x}{v:02x}")})).unwrap();
}
s.execute("select.deselect", json!({})).unwrap();
s
}
fn wand(s: &mut Session, x: i32, tolerance: f64, mode: &str) {
s.execute("select.magicWand", json!({"x": x, "y": 400, "tolerance": tolerance, "mode": mode})).unwrap();
}
fn wand_global(s: &mut Session, x: i32, tolerance: f64, mode: &str) {
s.execute("select.magicWand", json!({"x": x, "y": 400, "tolerance": tolerance, "mode": mode, "contiguous": false})).unwrap();
}
/// The columns of row 400 that are at least half selected: (first, end), or `None`. Every
/// column in between must be selected too, so a hole in the run fails the test.
fn selected(s: &Session) -> Option<(i32, i32)> {
let doc = &s.active().unwrap().doc;
let row = photocraft_geom::Rect::new(0, 400, 800, 401);
let m = photocraft_algo::selection::mask_from_surface(doc.selection.as_ref(), row);
let first = m.iter().position(|v| *v >= 0.5)?;
let last = m.iter().rposition(|v| *v >= 0.5)?;
assert!(m[first..=last].iter().all(|v| *v >= 0.5), "a hole in the selected run {first}..={last}");
Some((first as i32, last as i32 + 1))
}
/// Greys 100 to 130 (x 100–380) selected, as tolerance 32 on the first block selects them, plus
/// the Anti-alias fringe: column 380 of grey 135 at about 251/255, as measured in #11776.
fn ramp_selected() -> Session {
let mut s = ramp();
wand(&mut s, 110, 32.0, "replace");
assert_eq!(selected(&s), Some((100, 381)));
s
}
#[test]
fn a_seed_outside_the_selection_subtracts_nothing() {
let mut s = ramp_selected();
// Grey 145 (x 460–500) is outside the selection, though its own region reaches into it.
wand(&mut s, 480, 32.0, "subtract");
assert_eq!(selected(&s), Some((100, 381)), "unchanged");
}
#[test]
fn a_seed_outside_the_selection_intersects_to_nothing() {
let mut s = ramp_selected();
wand(&mut s, 480, 32.0, "intersect");
assert_eq!(selected(&s), None);
}
#[test]
fn a_seed_inside_the_selection_works_as_before() {
// Grey 125 with tolerance 10 reaches greys 115–135; inside the selection that is x 220–380.
// With the default Anti-alias fringe, as measured in #11779: Subtract leaves 100–219 (x 219
// keeps about 6/255, under the 0.5 cut) and Intersect 219–381.
let mut s = ramp_selected();
wand(&mut s, 320, 10.0, "subtract");
assert_eq!(selected(&s), Some((100, 219)));
let mut s = ramp_selected();
wand(&mut s, 320, 10.0, "intersect");
assert_eq!(selected(&s), Some((219, 381)));
}
#[test]
fn contiguous_off_keeps_the_global_match() {
// Without Contiguous the seed's colour matches everywhere, as before: greys 115–145 are
// x 220–500, wherever the seed lies.
let mut s = ramp_selected();
wand_global(&mut s, 480, 32.0, "subtract");
assert_eq!(selected(&s), Some((100, 219)));
let mut s = ramp_selected();
wand_global(&mut s, 480, 32.0, "intersect");
assert_eq!(selected(&s), Some((219, 381)));
}
#[test]
fn without_a_selection_subtract_and_intersect_select_nothing() {
for mode in ["subtract", "intersect"] {
let mut s = ramp();
wand(&mut s, 320, 10.0, mode);
assert_eq!(selected(&s), None, "{mode}");
}
}
#[test]
fn the_fill_passes_only_pixels_at_least_half_selected() {
use photocraft_algo::selection::wand_region_within;
use photocraft_geom::Rect;
// One flat grey row of four pixels; only the coverage limit decides the region.
let img = [[128u8, 128, 128, 255]; 4];
let area = Rect::new(0, 0, 4, 1);
let fill = |within: [f32; 4], seed: i32| wand_region_within(&img, area, (seed, 0), 0.0, true, false, Some(&within));
assert!(fill([0.49, 1.0, 1.0, 1.0], 0).is_none(), "a seed just under half selected finds nothing");
let r = fill([0.5, 1.0, 1.0, 1.0], 0).unwrap();
assert_eq!((0..4).map(|x| r.at(x, 0) >= 0.5).collect::<Vec<_>>(), [true; 4], "half selected counts");
let r = fill([1.0, 1.0, 0.49, 1.0], 0).unwrap();
assert_eq!((0..4).map(|x| r.at(x, 0) >= 0.5).collect::<Vec<_>>(), [true, true, false, false], "the fill stops at 0.49");
}
@@ -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");
+52 -2
View File
@@ -8,7 +8,7 @@
use std::sync::Arc;
use photocraft_color::{Color, PixelFormat};
use photocraft_color::{Color, ColorMode, PixelFormat};
use photocraft_doc::text::{
AntiAlias, Caps, CharStyle, FontBaseline, FontFeature, FontVariation, Kerning, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection,
TextRun, TextShape,
@@ -937,6 +937,56 @@ pub(crate) fn new_text_layer(s: &Session, p: &Value, cmd: &str) -> Result<TextLa
Ok(t)
}
/// The name of the history state a new type layer makes: what `type.create` records, and what the
/// Type tool's commit keeps in the modes [`commits_as_selection`] names (#12041).
pub const NEW_TYPE_LAYER_LABEL: &str = "New Type Layer";
/// Whether committing Type-tool text `t` in colour mode `mode` leaves no type layer, but a
/// selection in the shape of its glyphs, as Photoshop does in its Indexed Color and Bitmap
/// documents (#12041).
///
/// Both halves of the answer come from the issue:
/// - the modes: Indexed Color and Bitmap are the two documents that keep no type layer;
/// - the text: only the horizontal point text the measurement describes - the tool "still lets you
/// click and type" and the commit leaves "a selection in the shape of the typed glyphs". Paragraph
/// (box) text and vertical type are on its *Not measured* list, whose rule is that an unmeasured
/// case keeps today's behaviour - and today's behaviour is the outcome that makes sense here
/// anyway: a coverage mask cannot give back a box that reflows or a column of stacked lines, so
/// the selection would end the editability the layer exists for. The Type Mask tools keep turning
/// both into the selection, as they do today: there the user asked for one.
///
/// The check belongs to the Type tool's commit (the Type Mask tools' `type.createSelection` with
/// `removeLayer`, which it already runs for `ed.mask`) and *not* to the `type.create` command, even
/// though a colour-mode check there is what looks simplest:
/// - `type.create` is the primitive the tools build the layer they edit and show on canvas with
/// (`pointer_up` in `ui-egui`), and Preferences > Type > "Fill new type layers with placeholder
/// text" (on by default) already gives that first call non-empty text. Branching there would make
/// the click produce a selection and no layer, so there would be nothing to type into - while the
/// reference application still lets you click and type in these modes and shows the text while
/// editing. Only its commit differs.
/// - `type.create` is also what automation, actions and a script's new text layer go through, and
/// the measured difference is the tool's.
pub fn commits_as_selection(mode: ColorMode, t: &TextLayer) -> bool {
let measured = matches!(t.shape, TextShape::Point) && t.orientation == Orientation::Horizontal;
measured && matches!(mode, ColorMode::Indexed | ColorMode::Bitmap)
}
/// Name the step the Type tool's commit made in such a document (#12041). The commit runs the Type
/// Mask tools' `type.createSelection` with `removeLayer` - the same conversion, coalesced into the
/// one step of the typing session - and that command names the step "Type Mask", while Photoshop's
/// history state here is the type layer's own name.
///
/// An edit that does not carry the session's `coalesce` key (the Alt+arrow kerning step, which is
/// deliberately one state per press) ends the session's step, exactly as it does for the Type Mask
/// tools and for the plain type layer's rename on commit; the conversion is then a state of its own
/// and takes this name too. Photoshop repeats a state name whenever the same thing happens again,
/// so the two states read as the two type-layer steps they are.
pub fn name_selection_commit(s: &mut Session) {
if let Some(st) = s.active_mut() {
st.history.set_current_label(NEW_TYPE_LAYER_LABEL);
}
}
const CHAR_PARAMS: &str = r##""font":str,"fontStyle":str,"weight":100..900,"italic":bool,"size":0.1..=1296 pt,"color":"#rrggbb"|[r,g,b,a],"tracking":-1000..=10000 (1/1000 em),"leading":pt|"auto","baselineShift":pt,"horizontalScale":%,"verticalScale":%,"underline":bool,"strikethrough":bool,"fauxBold":bool,"fauxItalic":bool,"kerning":1/1000em (manual, after each character)|"metrics"|"optical"|"off","caps":"normal|small|all","baseline":"normal|superscript|subscript","ligatures":bool,"discretionaryLigatures":bool,"features":{"ss01":1},"variations":{"wght":650},"language":str"##;
pub fn specs() -> Vec<CommandSpec> {
@@ -953,7 +1003,7 @@ pub fn specs() -> Vec<CommandSpec> {
let mut t = new_text_layer(s, p, "type.create")?;
let given = p.get("name").and_then(Value::as_str).map(str::to_string);
let name = given.clone().unwrap_or_else(|| layer_name(&t.text));
let id = s.edit("New Type Layer", |doc, active| {
let id = s.edit(NEW_TYPE_LAYER_LABEL, |doc, active| {
refresh(doc, &mut t);
let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::AutoEditable);
*active = Some(id);
@@ -0,0 +1,287 @@
//! #12041: committing Type-tool text in an Indexed Color or a Bitmap document.
//!
//! The reference application still lets you click and type there and shows the text while editing;
//! the commit leaves **no type layer** and a selection in the shape of the glyphs, as one history
//! state named "New Type Layer", and paints nothing. [`super::type_cmds::commits_as_selection`] is
//! that mode check and [`super::type_cmds::name_selection_commit`] the step's name; the conversion
//! is the Type Mask tools' `type.createSelection` with `removeLayer`, coalesced into the typing
//! session, which is what [`commit`] below runs and what `ui-egui`'s `commit_here` now does for the
//! Type tool in these modes.
//!
//! `type.create` itself stays mode-agnostic on purpose, and
//! [`the_type_layer_command_keeps_making_the_tools_working_layer`] pins that: the tools make the
//! layer they edit and show on canvas with that command, on the first click already with text in it
//! when Preferences > Type > "Fill new type layers with placeholder text" is on (the default), so a
//! mode branch there would take away the layer the session types into.
//!
//! The issue measures the horizontal point text you click and type, and lists paragraph text and
//! vertical type under *Not measured*, where its rule is that today's behaviour stays:
//! [`only_the_measured_horizontal_point_text_converts_in_these_modes`] pins that half of the check,
//! and [`an_uncoalesced_edit_between_typing_and_the_commit_splits_the_states`] what happens to the
//! states when an edit outside the session's coalesce group comes between the typing and the commit.
use super::type_cmds::{commits_as_selection, name_selection_commit, new_text_layer};
use super::*;
use photocraft_doc::text::{Orientation, TextShape};
/// The typing session's coalesce key, as `ui-egui`'s `session_key` gives one.
const SESSION: &str = "type-session-12041";
/// The text the tool commits, at a baseline inside every document used here. `coalesce` for the
/// tool's own calls (one step for the session), without it for a script's or the pin's.
fn typed(coalesce: bool) -> Value {
let mut p = json!({ "text": "Hi", "x": 20, "y": 80, "size": 48 });
if coalesce {
p["coalesce"] = json!(SESSION);
}
p
}
/// A blank RGB document, to be converted to the mode under test.
fn blank() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 240, "height": 120, "background": "transparent"})).unwrap();
s
}
fn indexed() -> Session {
let mut s = blank();
s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
assert_eq!(mode(&s), ColorMode::Indexed, "the setup made an Indexed Color document");
s
}
fn bitmap() -> Session {
let mut s = blank();
s.execute("image.mode.grayscale", json!({})).unwrap();
s.execute("image.mode.bitmap", json!({"method": "threshold", "frequency": 12, "shape": "diamond"})).unwrap();
assert_eq!(mode(&s), ColorMode::Bitmap, "the setup made a Bitmap document");
s
}
fn mode(s: &Session) -> ColorMode {
s.active().unwrap().doc.mode
}
/// The Type tool's commit of the session's working layer in a document [`commits_as_selection`]
/// names: the Type Mask tools' conversion, in the session's one step, which keeps the name the step
/// was opened with.
fn commit(s: &mut Session, layer: u64) {
s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "operation": "new", "coalesce": SESSION})).unwrap();
name_selection_commit(s);
}
fn text_layers(s: &Session) -> usize {
s.active().unwrap().doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).count()
}
fn layers(s: &Session) -> usize {
s.active().unwrap().doc.walk().len()
}
/// The selection's coverage over the whole canvas, in document pixels.
fn coverage(s: &Session) -> Vec<f32> {
let d = s.active().unwrap().doc.clone();
let b = d.bounds();
let mut out = Vec::new();
for y in b.y0..b.y1 {
for x in b.x0..b.x1 {
out.push(d.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)));
}
}
out
}
/// The selection's bounds, as its corners.
fn selection_corners(s: &Session) -> Option<[i32; 4]> {
s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()).map(|r| [r.x0, r.y0, r.x1, r.y1])
}
/// Every layer's pixels, quantised: what the commit must leave exactly as it was.
fn pixels(s: &Session) -> Vec<u8> {
let d = s.active().unwrap().doc.clone();
let b = d.bounds();
let mut out = Vec::new();
for (_, _, l) in d.walk() {
let Some(surface) = l.surface() else { continue };
for y in b.y0..b.y1 {
for x in b.x0..b.x1 {
out.extend(surface.rgba(x, y).map(|v| (v * 255.0).round() as u8));
}
}
}
out
}
fn history(s: &Session) -> Vec<String> {
s.active().unwrap().history.entries()
}
#[test]
fn committing_in_indexed_color_or_bitmap_leaves_the_glyphs_selected_and_no_layer() {
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let (steps, layers_before, pixels_before) = (history(&s).len(), layers(&s), pixels(&s));
// The tool's session: a type layer to edit and show while typing, as measured.
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
assert_eq!(text_layers(&s), 1, "{name}: typing happens on a layer the tool can show");
commit(&mut s, layer);
assert_eq!(text_layers(&s), 0, "{name}: committing leaves no type layer");
assert_eq!(layers(&s), layers_before, "{name}: the working layer went with it");
assert!(s.active().unwrap().doc.selection.is_some(), "{name}: the glyphs are selected");
let selected = s.active().unwrap().doc.selection.as_ref().unwrap();
assert!(!selected.content_bounds().is_empty(), "{name}: the selection has a shape");
assert!(coverage(&s).iter().any(|v| *v > 0.0), "{name}: the selected pixels are the glyphs'");
assert_eq!(pixels(&s), pixels_before, "{name}: the commit paints nothing");
// One step for the whole session, named as Photoshop names it.
let h = history(&s);
assert_eq!(h.len(), steps + 1, "{name}: the session is one history state: {h:?}");
assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: its name");
// And undoing that one state gives the document back as it was.
s.execute("edit.undo", json!({})).unwrap();
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: undo takes the selection");
assert_eq!(layers(&s), layers_before, "{name}: undo takes the whole session");
assert_eq!(pixels(&s), pixels_before, "{name}: nothing else was changed");
}
}
#[test]
fn the_selection_is_the_glyph_shape_the_type_mask_of_the_same_text_makes() {
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
commit(&mut s, layer);
let (got, got_bounds) = (coverage(&s), selection_corners(&s));
// The pin: the same text straight through the Type Mask command.
let mut pin = make();
pin.execute("type.createSelection", typed(false)).unwrap();
assert_eq!(got_bounds, selection_corners(&pin), "{name}: same selection bounds");
assert_eq!(got, coverage(&pin), "{name}: same selection coverage");
}
}
#[test]
fn rgb_grayscale_cmyk_and_lab_keep_making_type_layers_at_every_depth() {
for (id, want) in [("rgb", ColorMode::Rgb), ("gray", ColorMode::Grayscale), ("cmyk", ColorMode::Cmyk), ("lab", ColorMode::Lab)] {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 240, "height": 120, "mode": id, "depth": depth, "background": "transparent"})).unwrap();
assert_eq!(mode(&s), want, "{id} at {depth} bit: the document really is that mode");
let point = new_text_layer(&s, &typed(false), "type.create").unwrap();
assert!(!commits_as_selection(want, &point), "{id} keeps type layers");
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
// Today's commit: rename the session's layer in the same step, select nothing.
let name = super::type_cmds::layer_name("Hi");
s.execute("type.edit", json!({"layer": layer, "name": name, "coalesce": SESSION})).unwrap();
assert_eq!(text_layers(&s), 1, "{id} at {depth} bit keeps its type layer");
assert!(s.active().unwrap().doc.selection.is_none(), "{id} at {depth} bit selects nothing");
let h = history(&s);
assert_eq!(h.len(), 2, "{id} at {depth} bit: open plus one step for the session: {h:?}");
assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{id} at {depth} bit keeps the step's name");
}
}
}
#[test]
fn the_type_layer_command_keeps_making_the_tools_working_layer_in_these_modes() {
// `type.create` is the primitive the Type tools create the layer they edit with (and scripts and
// actions their text layers with), so the colour-mode branch is the commit's, not its own.
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let id = s.execute("type.create", typed(false)).unwrap()["layer"].as_u64().unwrap();
assert!(matches!(s.active().unwrap().doc.layer(LayerId(id)).unwrap().content, LayerContent::Text(_)), "{name}: the command still makes the layer");
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: and selects nothing itself");
assert_eq!(history(&s).last().map(String::as_str), Some("New Type Layer"), "{name}: its own step name");
}
}
#[test]
fn a_refused_conversion_leaves_the_typed_text_and_the_document_alone() {
// The commit's fallback in `ui-egui` keeps today's type layer when the conversion is refused,
// so the typed text is not lost with a selection that was never made. Here the document would
// have to keep no layer at all, which is what `type.createSelection` with `removeLayer` refuses.
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let only = s.active().unwrap().doc.layers[0].id.0;
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.delete", json!({"layer": only})).unwrap();
let (pixels_before, steps, label) = (pixels(&s), history(&s).len(), history(&s).last().cloned());
assert!(
s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "operation": "new", "coalesce": SESSION})).is_err(),
"{name}: the conversion is refused"
);
// `commit_here` stops there and keeps the layer, so the step is never renamed either.
assert_eq!(text_layers(&s), 1, "{name}: the typed text stays as a type layer");
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: nothing was selected");
assert_eq!(pixels(&s), pixels_before, "{name}: the refused step painted nothing");
assert_eq!(history(&s).len(), steps, "{name}: the refused step is no new state");
assert_eq!(history(&s).last().cloned(), label, "{name}: the refused conversion renames nothing");
}
}
/// The measurement covers horizontal point text. Paragraph (box) text and vertical type are on the
/// issue's *Not measured* list, where its rule is that today's behaviour stays - and a coverage mask
/// could not give a reflowing box or a stacked column back anyway, so their editable layer stays.
#[test]
fn only_the_measured_horizontal_point_text_converts_in_these_modes() {
let s = indexed();
let point = new_text_layer(&s, &typed(false), "type.create").unwrap();
assert!(matches!(point.shape, TextShape::Point) && point.orientation == Orientation::Horizontal, "the fixture is horizontal point text");
let mut box_params = typed(false);
box_params["box"] = json!([20.0, 20.0, 180.0, 80.0]);
let paragraph = new_text_layer(&s, &box_params, "type.create").unwrap();
assert!(matches!(paragraph.shape, TextShape::Box { .. }), "the fixture is paragraph text");
let mut vertical_params = typed(false);
vertical_params["orientation"] = json!("vertical");
let vertical = new_text_layer(&s, &vertical_params, "type.create").unwrap();
assert_eq!(vertical.orientation, Orientation::Vertical, "the fixture is vertical text");
for mode in [ColorMode::Indexed, ColorMode::Bitmap] {
assert!(commits_as_selection(mode, &point), "{mode:?}: the measured text becomes the selection");
assert!(!commits_as_selection(mode, &paragraph), "{mode:?}: paragraph text keeps its type layer");
assert!(!commits_as_selection(mode, &vertical), "{mode:?}: vertical text keeps its type layer");
}
}
/// An edit that does not carry the session's `coalesce` key ends its coalesce group - in the tool
/// that is the deliberately per-press Alt+arrow kerning step. The commit then makes a state of its
/// own, which is what the Type Mask tools' commit and the plain layer's rename do in the same
/// situation today; nothing is mis-named and nothing else moves.
#[test]
fn an_uncoalesced_edit_between_typing_and_the_commit_splits_the_states() {
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
// The stand-in for that kerning press: a real edit under no coalesce key.
s.execute("type.edit", json!({"layer": layer, "antialias": "sharp"})).unwrap();
let before = history(&s);
assert_eq!(before.last().map(String::as_str), Some("Edit Type"), "{name}: the unkeyed edit is a state of its own");
commit(&mut s, layer);
let h = history(&s);
assert_eq!(h.len(), before.len() + 1, "{name}: the commit is a further state once the group ended: {h:?}");
assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: named for the type layer either way");
assert_eq!(h[h.len() - 2].as_str(), "Edit Type", "{name}: the edit between them keeps its own name");
assert_eq!(text_layers(&s), 0, "{name}: still no type layer is left");
assert!(s.active().unwrap().doc.selection.is_some(), "{name}: still the glyphs are selected");
s.execute("edit.undo", json!({})).unwrap();
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: one undo takes the conversion");
assert_eq!(text_layers(&s), 1, "{name}: which brings the working layer back, as the mask tools' undo does");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(text_layers(&s), 1, "{name}: the next undo takes the unkeyed edit, not the session");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(text_layers(&s), 0, "{name}: and the third one takes the typing session");
}
}
+1 -1
View File
@@ -2156,7 +2156,7 @@ mod tests;
#[cfg(test)]
#[path = "../../io/tests/support/recovery_psd.rs"]
mod psd_open_fixture;
pub(crate) mod psd_open_fixture;
#[cfg(test)]
mod psd_open_confirmation_tests {
+2
View File
@@ -357,4 +357,6 @@ mod tests;
#[cfg(test)]
mod fx_mode_tests;
#[cfg(test)]
mod brush_clear_background_tests;
pub mod command_hints;
+5
View File
@@ -193,6 +193,11 @@ impl Session {
self.next_held_open
}
/// Whether a document held back for its prompt already has `name`.
pub(crate) fn held_open_named(&self, name: &str) -> bool {
self.held_opens.iter().any(|(_, d, _)| d.name == name)
}
/// Takes a document a background open held back for the profile prompt: the document and
/// whether its source is read-only. `None` when there is no such document (already taken).
pub fn take_held_open(&mut self, id: u64) -> Option<(Document, bool)> {