David Mann authored and GitHub committed 2026-12-01 11:44:24 +01:00
commit ff4688155d
43 files changed
+2104 -67

No files matched your search

+20 -3
View File
@@ -931,11 +931,24 @@ fn transform_again_copy(s: &mut Session) -> Result<Value> {
}
}
fn last_transform(s: &Session) -> Result<&Value> {
s.journal
.iter()
.rev()
.find(|(id, _)| id == "edit.transform")
.map(|(_, params)| params)
.ok_or_else(|| EngineError::Other("there is no transform to repeat".into()))
}
fn can_transform_again(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
last_transform(s).map(|_| ()).map_err(|error| error.to_string())
}
/// The `edit.transform` params that repeat the last transform on the layers `ids` (their frame
/// together is the box it starts from).
fn transform_again_params(s: &Session, ids: &[LayerId]) -> Result<Value> {
let (_, last) =
s.journal.iter().rev().find(|(id, _)| id == "edit.transform").cloned().ok_or(EngineError::Other("there is no transform to repeat".into()))?;
let last = last_transform(s)?;
let (rect, quad) = (last.get("rect").cloned(), last.get("quad").cloned());
let mut p = json!({"interpolation": last.get("interpolation").cloned().unwrap_or(json!("bicubic"))});
match (rect, quad, last.get("matrix").cloned()) {
@@ -1269,7 +1282,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")),
spec!("image.autoColor", "Auto Color", &["Image"], Some("Cmd+Shift+B"), "{}", has_pixels, |s, _| auto_adjust(s, "color")),
spec!("edit.toggleLastState", "Toggle Last State", &["Edit"], Some("Cmd+Alt+Z"), "{}", has_doc, |s, _| toggle_last_state(s)),
spec!("edit.transform.again", "Again", &["Edit", "Transform"], Some("Cmd+Shift+T"), "{}", has_doc, |s, _| transform_again(s)),
spec!("edit.transform.again", "Again", &["Edit", "Transform"], Some("Cmd+Shift+T"), "{}", can_transform_again, |s, _| transform_again(s)),
spec!(
"edit.transform.againCopy",
"Transform Again on a Copy",
@@ -1329,3 +1342,7 @@ mod tests;
#[cfg(test)]
#[path = "layer_via_cut_locked_group_tests.rs"]
mod layer_via_cut_locked_group_tests;
#[cfg(test)]
#[path = "transform_again_needs_prior_tests.rs"]
mod transform_again_needs_prior_tests;
@@ -19,7 +19,7 @@ mod selection;
mod structure;
pub use crate::damage::{layer_bounds, same_pixels, selection_only_change, step_damage};
use align::{align, distribute};
use align::{align, distribute, position_locked};
use moves::link_groups;
pub use moves::shift_surface;
#[cfg(test)]
@@ -52,8 +52,9 @@ fn can_align(s: &Session) -> std::result::Result<(), String> {
match d.selected_layers().len() {
0 => Err("no layer selected".into()),
// Photoshop aligns to an active selection however many layers are selected; without one,
// a single layer aligns to the canvas and 2+ align to each other.
_ => Ok(()),
// a single layer aligns to the canvas and 2+ align to each other. A selected layer with
// Lock Position greys the entries (#18443).
_ => position_locked(&d.doc, d.selected_layers(), false).map_or(Ok(()), Err),
}
}
fn can_distribute(s: &Session) -> std::result::Result<(), String> {
@@ -1,3 +1,5 @@
use photocraft_doc::Layer;
use super::moves::{move_layers, with_links};
use super::selection::{selected, top_level};
use super::{Document, EngineError, LayerId, Rect, Result, Session, Value, bad, json};
@@ -42,9 +44,22 @@ impl Edge {
}
}
/// Selected top-level layers that have content bounds, bottom-to-top.
fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> {
top_level(doc, sel).into_iter().filter_map(|id| Some((id, align_bounds(doc.layer(id)?, doc.bounds(), doc.pixel_format().sample)?))).collect()
/// Keep layers that have content bounds, in the given order.
fn bounded_layers(doc: &Document, layers: Vec<LayerId>) -> Vec<(LayerId, Rect)> {
layers.into_iter().filter_map(|id| Some((id, align_bounds(doc.layer(id)?, doc.bounds(), doc.pixel_format().sample)?))).collect()
}
/// The refusal for a selected layer whose position is locked, naming it (#18443). `lock_all` counts Lock All as well:
/// the command refuses it, while its menu state was not measured. The Background is locked in place by construction
/// and still takes part. A locked layer together with a pixel selection was not measured either: there only
/// `move_layers` refuses, when the layer would have to move.
pub(super) fn position_locked(doc: &Document, sel: &[LayerId], lock_all: bool) -> Option<String> {
let held = sel.iter().filter_map(|id| doc.layer(*id)).find(|l| {
let locks = doc.effective_locks(l.id);
(locks.position || (lock_all && locks.all)) && !doc.is_background(l.id)
})?;
let pixel_selection = doc.selection.as_ref().is_some_and(|m| !m.content_bounds().is_empty());
(!pixel_selection).then(|| format!("layer \"{}\" is position-locked", held.name))
}
pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
@@ -53,6 +68,10 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
let sel = selected(s);
let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string();
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
// Refused before anything moves, also when the locked layer would stay where it is.
if let Some(refusal) = position_locked(&before, &sel, true) {
return Err(EngineError::Other(refusal));
}
// The History state is named after the entry (#18283).
let name = match edge {
Edge::Top => "Align Top Edges",
@@ -63,7 +82,11 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
Edge::Right => "Align Right Edges",
};
let moved = s.edit(name, |doc, _| {
let items = bounded_selection(doc, &sel);
let roots = top_level(doc, &sel);
if roots.len() != sel.len() {
return Err(EngineError::Other("a group cannot be aligned together with one of its own descendants".into()));
}
let items = bounded_layers(doc, roots);
if items.is_empty() {
return Err(EngineError::Other("the selected layers have no content to align".into()));
}
@@ -92,6 +115,10 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
if target.is_empty() {
return Err(EngineError::Other("nothing to align to".into()));
}
if matches!(edge, Edge::Left | Edge::Right) && sel.iter().filter_map(|id| doc.layer(*id)).any(has_position_locked_descendant) {
// Left and Right Edges still record their History step when a group cannot move.
return Ok(0);
}
let t2 = edge.value2(&target);
// A centre can fall on a half pixel, which rounds towards +x / +y (#18282). A selection that is not a plain
// rectangle was not measured as the reference and keeps rounding the other way.
@@ -113,6 +140,10 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
Ok(json!({"moved": moved}))
}
fn has_position_locked_descendant(layer: &Layer) -> bool {
layer.children().is_some_and(|children| children.iter().any(|child| child.locks.position || child.locks.all || has_position_locked_descendant(child)))
}
/// Whether a selection selects every pixel of its bounds fully: a rectangle with hard edges.
fn plain_rectangle(mask: &photocraft_raster::Surface, bounds: Rect) -> bool {
let mut row = vec![0.0; bounds.width() as usize];
@@ -147,7 +178,7 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result<Value> {
let kind = kind.to_string();
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let moved = s.edit("Distribute", |doc, _| {
let mut items = bounded_selection(doc, &sel);
let mut items = bounded_layers(doc, top_level(doc, &sel));
if items.len() < 3 {
return Err(EngineError::Other("distributing needs three or more layers with content".into()));
}
@@ -191,10 +222,22 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result<Value> {
Ok(json!({"moved": moved}))
}
#[cfg(test)]
#[path = "align_group_own_child_tests.rs"]
mod align_group_own_child_tests;
#[cfg(test)]
#[path = "align_history_names_tests.rs"]
mod align_history_names_tests;
#[cfg(test)]
#[path = "align_group_locked_child_tests.rs"]
mod align_group_locked_child_tests;
#[cfg(test)]
#[path = "align_half_pixel_tests.rs"]
mod align_half_pixel_tests;
#[cfg(test)]
#[path = "align_position_lock_enabled_tests.rs"]
mod align_position_lock_enabled_tests;
@@ -0,0 +1,62 @@
use photocraft_doc::{ColorMode, Document, Layer, LayerId, Locks, PixelFormat, SampleType, Size};
use photocraft_geom::Rect;
use serde_json::json;
use crate::Session;
fn paint(name: &str, bounds: Rect) -> Layer {
let mut layer = Layer::raster(name, PixelFormat::RGBA8);
layer.surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]);
layer
}
fn fixture(locks: Locks, nested: bool) -> (Session, LayerId) {
let outside = paint("Outside", Rect::new(20, 30, 60, 70));
let outside_id = outside.id;
let mut child = paint("Child", Rect::new(40, 200, 60, 220));
let child_id = child.id;
child.locks = locks;
let child = if nested { Layer::group("Nested", vec![child]) } else { child };
let group = Layer::group("Group", vec![child, paint("Sibling", Rect::new(100, 240, 130, 270))]);
let group_id = group.id;
let mut doc = Document::new("Alignment", Size::new(400, 300), ColorMode::Rgb, SampleType::U8);
doc.layers.push(outside);
doc.layers.push(group);
let mut session = crate::session();
session.add_document(doc, None);
session.execute("layer.select", json!({"layers": [outside_id.0, group_id.0]})).unwrap();
assert_eq!(session.active().unwrap().selected_layers(), &[outside_id, group_id]);
(session, child_id)
}
#[test]
fn horizontal_edges_leave_every_layer_in_place_with_a_locked_group_child() {
for (locks, nested) in [(Locks { position: true, ..Locks::default() }, false), (Locks { all: true, ..Locks::default() }, true)] {
let (mut session, _) = fixture(locks, nested);
for (edge, label) in [("leftEdges", "Align Left Edges"), ("rightEdges", "Align Right Edges")] {
let st = session.active().unwrap();
let (before, history) = (st.doc.clone(), st.history.past_len());
let result = session.execute(&format!("layer.align.{edge}"), json!({})).unwrap();
assert_eq!(result["moved"], 0);
let st = session.active().unwrap();
assert_eq!(st.doc, before);
assert_eq!(st.history.past_len(), history + 1);
assert_eq!(st.history.undo_label(), Some(label));
}
}
}
#[test]
fn unlocked_groups_align_and_vertical_alignment_keeps_its_behavior() {
let (mut session, child) = fixture(Locks::default(), false);
let result = session.execute("layer.align.leftEdges", json!({})).unwrap();
assert_eq!(result["moved"], 1);
let st = session.active().unwrap();
assert_eq!(st.doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(20, 200, 40, 220));
let (mut session, child) = fixture(Locks { position: true, ..Locks::default() }, false);
let result = session.execute("layer.align.topEdges", json!({})).unwrap();
assert_eq!(result["moved"], 1);
let st = session.active().unwrap();
assert_eq!(st.doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(40, 30, 60, 50));
}
@@ -0,0 +1,68 @@
use photocraft_doc::{ColorMode, Document, Layer, LayerId, PixelFormat, SampleType, Size};
use photocraft_geom::Rect;
use serde_json::json;
use crate::Session;
fn paint(name: &str, bounds: Rect) -> Layer {
let mut layer = Layer::raster(name, PixelFormat::RGBA8);
layer.surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]);
layer
}
fn fixture() -> (Session, LayerId, LayerId, LayerId, LayerId) {
let outside = paint("Outside", Rect::new(4, 4, 10, 12));
let child = paint("Child", Rect::new(20, 16, 27, 23));
let (outside_id, child_id) = (outside.id, child.id);
let inner = Layer::group("Inner", vec![child]);
let inner_id = inner.id;
let outer = Layer::group("Outer", vec![inner]);
let outer_id = outer.id;
let mut doc = Document::new("Alignment", Size::new(48, 32), ColorMode::Rgb, SampleType::U8);
doc.layers.push(outside);
doc.layers.push(outer);
let mut session = crate::session();
session.add_document(doc, None);
(session, outside_id, child_id, inner_id, outer_id)
}
fn select(session: &mut Session, first: LayerId, second: LayerId) {
session.execute("layer.select", json!({"layer": first.0})).unwrap();
session.execute("layer.select", json!({"layer": second.0, "mode": "toggle"})).unwrap();
let selected = session.active().unwrap().selected_layers();
assert_eq!(selected.len(), 2);
assert!(selected.contains(&first) && selected.contains(&second));
}
#[test]
fn alignment_refuses_direct_and_nested_descendants_without_an_edit() {
let (mut session, _, child, inner, outer) = fixture();
for group in [inner, outer] {
select(&mut session, group, child);
let st = session.active().unwrap();
let (before, history) = (st.doc.clone(), st.history.past_len());
for edge in ["topEdges", "verticalCenters", "bottomEdges", "leftEdges", "horizontalCenters", "rightEdges"] {
let command = format!("layer.align.{edge}");
assert!(session.is_enabled(&command), "{command} menu eligibility stays the same");
let error = session.execute(&command, json!({})).unwrap_err();
assert!(error.to_string().contains("a group cannot be aligned together with one of its own descendants"), "{error}");
let st = session.active().unwrap();
assert_eq!(st.doc, before);
assert_eq!(st.history.past_len(), history);
}
}
}
#[test]
fn alignment_moves_a_child_with_an_outside_layer_without_reparenting() {
let (mut session, outside, child, inner, _) = fixture();
select(&mut session, outside, child);
let history = session.active().unwrap().history.past_len();
let result = session.execute("layer.align.leftEdges", json!({})).unwrap();
assert_eq!(result["moved"], 1);
let st = session.active().unwrap();
assert_eq!(st.doc.layers.index().parent(child), Some(inner));
assert_eq!(st.doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(4, 16, 11, 23));
assert_eq!(st.doc.layer(outside).unwrap().surface().unwrap().content_bounds(), Rect::new(4, 4, 10, 12));
assert_eq!(st.history.past_len(), history + 1);
}
@@ -0,0 +1,180 @@
//! #18443: Layer › Align is greyed when a selected layer has Lock Position, and the command refuses a selected layer
//! with Lock Position or Lock All by name, also when that layer would not move. Lock Transparent Pixels, Lock Image
//! Pixels and the Background in the selection do not block it. Not measured, so held as they were: the menu state
//! with Lock All, and a locked layer together with a pixel selection.
use photocraft_doc::{Document, LayerId, Locks};
use photocraft_geom::Rect;
use serde_json::json;
use crate::Session;
const ENTRIES: [&str; 6] = [
"layer.align.topEdges",
"layer.align.verticalCenters",
"layer.align.bottomEdges",
"layer.align.leftEdges",
"layer.align.horizontalCenters",
"layer.align.rightEdges",
];
const POSITION: Locks = Locks { transparency: false, pixels: false, position: true, artboard: false, all: false };
const ALL: Locks = Locks { transparency: false, pixels: false, position: false, artboard: false, all: true };
const PIXELS: Locks = Locks { transparency: false, pixels: true, position: false, artboard: false, all: false };
const TRANSPARENCY: Locks = Locks { transparency: true, pixels: false, position: false, artboard: false, all: false };
/// The name of the layer the tests lock, which a refusal has to mention.
const HELD: &str = "Held in place";
fn doc(s: &Session) -> &Document {
&s.active().unwrap().doc
}
fn bounds(s: &Session, id: LayerId) -> Rect {
crate::damage::layer_bounds(doc(s).layer(id).unwrap()).unwrap()
}
fn states(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
fn pixel_layer(s: &mut Session, name: &str, r: Rect) -> LayerId {
let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap());
s.edit("paint", |doc, _| {
let layer = doc.layer_mut(id).unwrap();
layer.name = name.into();
layer.surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
id
}
/// A 100 x 80 document with a Background and two pixel layers: the one the tests lock, and a larger one down and to
/// the right of it. Left Edges and Top Edges leave the first where it is; the other four entries have to move it.
fn two_layers() -> (Session, LayerId, LayerId) {
let mut s = crate::session();
s.execute("file.new", json!({"width": 100, "height": 80})).unwrap();
let held = pixel_layer(&mut s, HELD, Rect::new(10, 10, 20, 20));
let free = pixel_layer(&mut s, "Free", Rect::new(40, 30, 70, 60));
(s, held, free)
}
/// Selects `ids`; the last one is the active layer.
fn select(s: &mut Session, ids: &[LayerId]) {
s.execute("layer.select", json!({"layer": ids[0].0})).unwrap();
for id in &ids[1..] {
s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap();
}
}
fn lock(s: &mut Session, id: LayerId, locks: Locks) {
s.edit("lock", |doc, _| {
doc.layer_mut(id).unwrap().locks = locks;
Ok(())
})
.unwrap();
}
#[test]
fn lock_position_on_a_selected_layer_greys_the_six_entries() {
for held_is_active in [false, true] {
let (mut s, held, free) = two_layers();
select(&mut s, &if held_is_active { [free, held] } else { [held, free] });
for entry in ENTRIES {
assert!(s.is_enabled(entry), "{entry}: enabled without a lock");
}
lock(&mut s, held, POSITION);
for entry in ENTRIES {
let reason = s.disabled_reason(entry).unwrap_or_else(|| panic!("{entry} stays enabled, locked layer active: {held_is_active}"));
assert!(reason.contains(HELD), "{entry}: {reason}");
}
}
}
#[test]
fn a_selected_layer_with_lock_position_or_lock_all_refuses_the_align_by_name() {
for (locks, case) in [(POSITION, "Lock Position"), (ALL, "Lock All")] {
// Left Edges and Top Edges would leave the locked layer where it is.
for entry in ENTRIES {
let (mut s, held, free) = two_layers();
select(&mut s, &[held, free]);
lock(&mut s, held, locks);
let (before, states_before) = (doc(&s).clone(), states(&s));
let error = s.execute(entry, json!({})).expect_err(&format!("{entry}, {case}: refused"));
assert!(error.to_string().contains(HELD), "{entry}, {case}: {error}");
assert!(*doc(&s) == before, "{entry}, {case}: nothing moved");
assert_eq!(states(&s), states_before, "{entry}, {case}: no History state");
}
}
}
#[test]
fn lock_transparent_pixels_and_lock_image_pixels_do_not_block() {
for (locks, case) in [(TRANSPARENCY, "Lock Transparent Pixels"), (PIXELS, "Lock Image Pixels")] {
let (mut s, lower, upper) = two_layers();
select(&mut s, &[lower, upper]);
lock(&mut s, lower, locks);
lock(&mut s, upper, locks);
for entry in ENTRIES {
assert!(s.is_enabled(entry), "{entry}, {case}");
}
let was = bounds(&s, lower);
s.execute("layer.align.rightEdges", json!({})).unwrap();
assert!(bounds(&s, lower).x0 > was.x0, "{case}: the locked layer moved");
assert_eq!(bounds(&s, lower).x1, bounds(&s, upper).x1, "{case}: the right edges agree");
}
}
#[test]
fn the_background_in_the_selection_keeps_the_entries_enabled() {
let (mut s, _, free) = two_layers();
let background = doc(&s).background().unwrap().id;
assert!(doc(&s).effective_locks(background).position, "the Background is locked in place");
select(&mut s, &[background, free]);
for entry in ENTRIES {
assert!(s.is_enabled(entry), "{entry}");
}
s.execute("layer.align.rightEdges", json!({})).unwrap();
assert_eq!(bounds(&s, free).x1, doc(&s).bounds().x1, "the layer aligns to the Background's edge");
}
/// Not measured, so as before: Lock All leaves the menu entries enabled, and with a pixel selection a locked layer is
/// refused only when it would have to move.
#[test]
fn the_unmeasured_cases_keep_todays_behaviour() {
let (mut s, held, free) = two_layers();
select(&mut s, &[held, free]);
lock(&mut s, held, ALL);
for entry in ENTRIES {
assert!(s.is_enabled(entry), "{entry}: Lock All");
}
for (locks, case) in [(POSITION, "Lock Position"), (ALL, "Lock All")] {
let (mut s, held, free) = two_layers();
select(&mut s, &[held, free]);
lock(&mut s, held, locks);
// A selection whose left edge is the locked layer's.
s.execute("select.rect", json!({"x": 10, "y": 40, "width": 50, "height": 20})).unwrap();
for entry in ENTRIES {
assert!(s.is_enabled(entry), "{entry}: {case} with a pixel selection");
}
s.execute("layer.align.leftEdges", json!({})).unwrap();
assert_eq!(bounds(&s, free).x0, bounds(&s, held).x0, "{case}: the other layer aligns to the selection");
assert!(s.execute("layer.align.rightEdges", json!({})).is_err(), "{case}: the locked layer would have to move");
}
}
/// Not in the item: a lock inherited from a group counts as the layer's, as it does when a move is refused.
#[test]
fn lock_position_inherited_from_a_group_greys_the_entries_too() {
let (mut s, held, free) = two_layers();
select(&mut s, &[held]);
let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
lock(&mut s, group, POSITION);
select(&mut s, &[held, free]);
assert!(!doc(&s).layer(held).unwrap().locks.position && doc(&s).effective_locks(held).position, "only the group holds the lock");
for entry in ENTRIES {
assert!(!s.is_enabled(entry), "{entry}");
}
}
@@ -0,0 +1,143 @@
//! #18190: Layer › New › Group from Layers… (`layer.new.groupFromLayers`) is disabled whenever an
//! artboard is among the selected layers, instead of opening the dialog and failing on OK.
use photocraft_doc::LayerId;
use serde_json::{Value, json};
use crate::{EngineError, Session};
const GROUP_FROM_LAYERS: &str = "layer.new.groupFromLayers";
fn layer_id(v: Value) -> LayerId {
LayerId(v["layer"].as_u64().unwrap())
}
/// Selects `ids` in order, leaving the last one active.
fn select(s: &mut Session, ids: &[LayerId]) {
for (i, id) in ids.iter().enumerate() {
let mode = if i == 0 { "replace" } else { "add" };
s.execute("layer.select", json!({"layer": id.0, "mode": mode})).unwrap();
}
assert_eq!(s.active().unwrap().active_layer, ids.last().copied());
}
fn snapshot(s: &Session) -> (photocraft_doc::layer_tree::LayerTree, Vec<LayerId>, Option<LayerId>, Vec<String>) {
let d = s.active().unwrap();
(d.doc.layers.clone(), d.selected_layers().to_vec(), d.active_layer, d.history.entries())
}
fn children(s: &Session, group: LayerId) -> Vec<LayerId> {
s.active().unwrap().doc.layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect()
}
/// Builds a document with `board_a` (holding `in_a`), empty `board_b`, and a top-level `loose` layer.
fn fixture() -> (Session, LayerId, LayerId, LayerId, LayerId) {
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 120, "background": "transparent"})).unwrap();
let in_a = s.active().unwrap().doc.layers[0].id;
select(&mut s, &[in_a]);
let board_a = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board A"})).unwrap());
assert_eq!(s.active().unwrap().doc.artboard_of(in_a), Some(board_a));
s.execute("select.deselectLayers", json!({})).unwrap();
let board_b = layer_id(s.execute("layer.new.artboard", json!({"name": "Board B", "rect": [110, 0, 80, 80]})).unwrap());
s.execute("select.deselectLayers", json!({})).unwrap();
let loose = layer_id(s.execute("layer.new.layer", json!({"name": "Loose"})).unwrap());
assert_eq!(s.active().unwrap().doc.artboard_of(loose), None);
(s, board_a, in_a, board_b, loose)
}
#[test]
fn disabled_and_refused_whenever_an_artboard_is_selected() {
let (mut s, board_a, in_a, board_b, loose) = fixture();
let selections: &[(&str, &[LayerId])] = &[
("artboard alone", &[board_a]),
("artboard then child", &[board_a, in_a]),
("child then artboard", &[in_a, board_a]),
("two artboards (A then B)", &[board_a, board_b]),
("two artboards (B then A)", &[board_b, board_a]),
("artboard then loose layer", &[board_a, loose]),
("loose layer then artboard", &[loose, board_a]),
];
for &(case, ids) in selections {
select(&mut s, ids);
let why = s.disabled_reason(GROUP_FROM_LAYERS);
assert!(why.as_deref().is_some_and(|w| w.contains("artboard")), "{case}: expected disabled reason naming artboards, got {why:?}");
assert!(!s.is_enabled(GROUP_FROM_LAYERS), "{case}: stays enabled");
assert!(s.precheck(GROUP_FROM_LAYERS, &json!({})).is_err(), "{case}: precheck must refuse");
for params in [json!({}), json!({"name": "Set", "color": "red"})] {
let before = snapshot(&s);
let err = s.execute(GROUP_FROM_LAYERS, params.clone()).unwrap_err();
assert!(matches!(err, EngineError::Disabled(..)), "{case} {params}: got {err:?}");
assert!(snapshot(&s) == before, "{case} {params}: changed state");
}
}
// Explicit `layer` calls: naming an artboard, or naming a layer in a selection that holds an
// artboard, is refused; naming an ordinary layer outside the selection still groups it alone.
select(&mut s, &[loose]);
let before = snapshot(&s);
assert!(matches!(s.execute(GROUP_FROM_LAYERS, json!({"layer": board_a.0})), Err(EngineError::Disabled(..))));
assert!(snapshot(&s) == before);
select(&mut s, &[board_a, in_a]);
let before = snapshot(&s);
assert!(matches!(s.execute(GROUP_FROM_LAYERS, json!({"layer": in_a.0})), Err(EngineError::Disabled(..))));
assert!(snapshot(&s) == before);
let g = layer_id(s.execute(GROUP_FROM_LAYERS, json!({"layer": loose.0})).unwrap());
assert_eq!(children(&s, g), vec![loose]);
}
#[test]
fn layers_inside_one_or_two_artboards_without_a_selected_artboard_still_group() {
// Inside one artboard.
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 120, "background": "transparent"})).unwrap();
let a1 = s.active().unwrap().doc.layers[0].id;
let a2 = layer_id(s.execute("layer.new.layer", json!({"name": "A2"})).unwrap());
select(&mut s, &[a1, a2]);
let board = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board"})).unwrap());
select(&mut s, &[a1, a2]);
assert!(s.is_enabled(GROUP_FROM_LAYERS));
let g = layer_id(s.execute(GROUP_FROM_LAYERS, json!({"name": "InBoard"})).unwrap());
assert_eq!(s.active().unwrap().doc.artboard_of(g), Some(board));
assert_eq!(children(&s, g), vec![a1, a2]);
// Across two artboards, with neither artboard itself selected.
let mut s = crate::session();
s.execute("file.new", json!({"width": 240, "height": 120, "background": "transparent"})).unwrap();
let in_a = s.active().unwrap().doc.layers[0].id;
select(&mut s, &[in_a]);
let board_a = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board A"})).unwrap());
s.execute("select.deselectLayers", json!({})).unwrap();
let in_b = layer_id(s.execute("layer.new.layer", json!({"name": "In B"})).unwrap());
select(&mut s, &[in_b]);
let board_b = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board B"})).unwrap());
select(&mut s, &[in_a, in_b]);
assert!(s.is_enabled(GROUP_FROM_LAYERS));
let g = layer_id(s.execute(GROUP_FROM_LAYERS, json!({"name": "Across"})).unwrap());
assert_eq!(s.active().unwrap().doc.artboard_of(g), Some(board_b));
assert_eq!(children(&s, g), vec![in_a, in_b]);
assert!(children(&s, board_a).is_empty());
}
#[test]
fn group_layers_keeps_todays_behaviour_with_an_artboard_selected() {
let (mut s, board_a, in_a, _, _) = fixture();
for ids in [&[board_a][..], &[board_a, in_a][..]] {
select(&mut s, ids);
assert!(s.is_enabled("layer.groupLayers"), "not measured: enabled state stays as today");
let before = snapshot(&s);
let err = s.execute("layer.groupLayers", json!({})).unwrap_err();
assert!(err.to_string().contains("artboards"), "{err}");
assert!(snapshot(&s) == before);
}
}
@@ -0,0 +1,130 @@
//! #18136: Moving a multi-layer selection moves every selected layer, hidden ones included, even
//! when the active layer is hidden. Moving a single hidden layer alone, or an explicitly named
//! hidden layer, keeps the hidden-target refusal.
use photocraft_doc::LayerId;
use photocraft_geom::Rect;
use serde_json::json;
use crate::Session;
use crate::hidden_target::{HIDDEN, refusal};
fn painted_layer(s: &mut Session, name: &str, rect: Rect) -> LayerId {
let id = LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap());
s.edit("paint", |doc, _| {
doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(rect, &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
id
}
fn select(s: &mut Session, ids: &[LayerId]) {
for (i, id) in ids.iter().enumerate() {
let mode = if i == 0 { "replace" } else { "add" };
s.execute("layer.select", json!({"layer": id.0, "mode": mode})).unwrap();
}
assert_eq!(s.active().unwrap().active_layer, ids.last().copied());
}
fn bounds(s: &Session, id: LayerId) -> Option<Rect> {
crate::damage::layer_bounds(s.active().unwrap().doc.layer(id).unwrap())
}
fn three_layer_doc() -> (Session, LayerId, LayerId, LayerId) {
let mut s = crate::session();
s.execute("file.new", json!({"width": 1000, "height": 700, "background": "white"})).unwrap();
let a = painted_layer(&mut s, "A", Rect::new(10, 20, 50, 60));
let b = painted_layer(&mut s, "B", Rect::new(80, 90, 130, 140));
let h = painted_layer(&mut s, "Hidden", Rect::new(100, 450, 200, 500));
s.execute("layer.setProps", json!({"layer": h.0, "visible": false})).unwrap();
(s, a, b, h)
}
#[test]
fn multi_layer_selection_moves_every_layer_when_the_active_layer_is_hidden() {
for hidden_active in [true, false] {
let (mut s, a, b, h) = three_layer_doc();
let order = if hidden_active { [a, b, h] } else { [h, a, b] };
select(&mut s, &order);
assert_eq!(refusal(&s, "layer.translate", &json!({})), None, "hidden_active={hidden_active}");
let (ra, rb, rh) = (bounds(&s, a).unwrap(), bounds(&s, b).unwrap(), bounds(&s, h).unwrap());
let steps = s.active().unwrap().history.past_len();
s.execute("layer.translate", json!({"dx": 100, "dy": 50})).unwrap();
assert_eq!(bounds(&s, a), Some(ra.translate(100, 50)));
assert_eq!(bounds(&s, b), Some(rb.translate(100, 50)));
assert_eq!(bounds(&s, h), Some(rh.translate(100, 50)));
let doc = &s.active().unwrap().doc;
assert!(!doc.layer(h).unwrap().visible, "the hidden layer stays hidden");
assert!(doc.layer(a).unwrap().visible && doc.layer(b).unwrap().visible);
let hist = &s.active().unwrap().history;
assert_eq!((hist.past_len(), hist.undo_label()), (steps + 1, Some("Move")));
}
// A layer hidden through a hidden parent group also moves when selected with another layer,
// and two hidden layers selected together follow the same multi-layer rule.
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap();
let vis = painted_layer(&mut s, "Visible", Rect::new(10, 10, 30, 30));
let nested = painted_layer(&mut s, "Nested", Rect::new(40, 40, 60, 60));
select(&mut s, &[nested]);
let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.execute("layer.setProps", json!({"layer": group.0, "visible": false})).unwrap();
select(&mut s, &[vis, nested]);
let (rv, rn) = (bounds(&s, vis).unwrap(), bounds(&s, nested).unwrap());
s.execute("layer.translate", json!({"dx": 15, "dy": 25})).unwrap();
assert_eq!((bounds(&s, vis), bounds(&s, nested)), (Some(rv.translate(15, 25)), Some(rn.translate(15, 25))));
s.execute("layer.setProps", json!({"layer": vis.0, "visible": false})).unwrap();
select(&mut s, &[vis, nested]);
let (rv, rn) = (bounds(&s, vis).unwrap(), bounds(&s, nested).unwrap());
s.execute("layer.translate", json!({"dx": 5, "dy": 10})).unwrap();
assert_eq!((bounds(&s, vis), bounds(&s, nested)), (Some(rv.translate(5, 10)), Some(rn.translate(5, 10))));
}
#[test]
fn a_single_hidden_layer_alone_is_still_refused() {
let (mut s, _, _, h) = three_layer_doc();
select(&mut s, &[h]);
let rh = bounds(&s, h);
let steps = s.active().unwrap().history.past_len();
assert_eq!(refusal(&s, "layer.translate", &json!({})), Some(HIDDEN));
let err = s.execute("layer.translate", json!({"dx": 100, "dy": 50})).unwrap_err().to_string();
assert!(err.contains(HIDDEN), "{err}");
assert_eq!(bounds(&s, h), rh);
assert_eq!(s.active().unwrap().history.past_len(), steps);
// A single layer hidden through its parent group is still refused too.
let child = painted_layer(&mut s, "InGroup", Rect::new(20, 20, 40, 40));
select(&mut s, &[child]);
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.execute("layer.setProps", json!({"layer": g.0, "visible": false})).unwrap();
select(&mut s, &[child]);
let rc = bounds(&s, child);
let steps = s.active().unwrap().history.past_len();
assert_eq!(refusal(&s, "layer.translate", &json!({})), Some(HIDDEN));
assert!(s.execute("layer.translate", json!({"dx": 10, "dy": 10})).unwrap_err().to_string().contains(HIDDEN));
assert_eq!(bounds(&s, child), rc);
assert_eq!(s.active().unwrap().history.past_len(), steps);
}
#[test]
fn an_explicit_hidden_layer_param_is_still_refused() {
let (mut s, a, b, h) = three_layer_doc();
for order in [[a, b, h], [h, a, b]] {
select(&mut s, &order);
let before = s.active().unwrap().doc.clone();
let steps = s.active().unwrap().history.past_len();
for layer in [json!(h.0), json!("Hidden")] {
let err = s.execute("layer.translate", json!({"layer": layer, "dx": 100, "dy": 50})).unwrap_err().to_string();
assert!(err.contains(HIDDEN), "{err}");
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(s.active().unwrap().history.past_len(), steps);
}
}
}
@@ -111,14 +111,17 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> {
Ok(())
}
/// Group from Layers is greyed while the Background is among the selected layers, as in the
/// menus (#14709).
/// Group from Layers is greyed while the Background or an artboard is among the selected layers,
/// as in the menus (#14709, #18190).
pub(super) fn can_group_from_layers(s: &Session) -> std::result::Result<(), String> {
super::has_layer(s)?;
let d = s.active().ok_or("no document open")?;
if d.selected_layers().iter().any(|id| d.doc.is_background(*id)) {
return Err("the Background layer can't go into a group".into());
}
if d.selected_layers().iter().any(|id| d.doc.layer(*id).is_some_and(|l| l.artboard().is_some())) {
return Err("artboards can't go into a group".into());
}
Ok(())
}
@@ -426,3 +429,7 @@ pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result<Value> {
#[cfg(test)]
#[path = "group_from_layers_keeps_layer_tags_tests.rs"]
mod group_from_layers_keeps_layer_tags_tests;
#[cfg(test)]
#[path = "group_from_layers_artboard_tests.rs"]
mod group_from_layers_artboard_tests;
+18 -12
View File
@@ -161,6 +161,13 @@ fn embed_all_linked(s: &mut Session, _p: &Value) -> Result<Value> {
fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
}
fn can_update_all_contents(s: &Session) -> std::result::Result<(), String> {
let doc = &s.active().ok_or("no document open")?.doc;
if matches!(doc.mode, ColorMode::Bitmap | ColorMode::Indexed) && !doc.walk().iter().any(|(_, _, layer)| matches!(&layer.content, LayerContent::Smart(_))) {
return Err("the document has no smart object".into());
}
Ok(())
}
fn has_smart_filters(s: &Session) -> std::result::Result<(), String> {
if active_smart(s)?.smart_filters.is_empty() { Err("the smart object has no smart filters".into()) } else { Ok(()) }
}
@@ -172,12 +179,16 @@ fn has_filter_mask(s: &Session) -> std::result::Result<(), String> {
active_smart(s)?.filter_mask.as_ref().map(|_| ()).ok_or_else(|| "the smart object has no filter mask".into())
}
fn convertible(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
let id = d.active_layer.ok_or("no active layer")?;
d.doc.layer(id).map(|_| ()).ok_or_else(|| "no active layer".into())
let mode = s.active().ok_or("no document open")?.doc.mode;
match mode {
ColorMode::Bitmap => return Err("Convert to Smart Object is unavailable in Bitmap mode".into()),
ColorMode::Indexed => return Err("Convert to Smart Object is unavailable in Indexed Color mode".into()),
_ => {}
}
super::enabled::has_layer(s)
}
fn not_smart(s: &Session) -> std::result::Result<(), String> {
convertible(s)?;
super::enabled::has_layer(s)?;
if active_smart(s).is_ok() { Err("the layer is already a smart object".into()) } else { Ok(()) }
}
@@ -294,14 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
crate::link_watch::update_changed
),
spec!(
"layer.smartObjects.updateAllModifiedContent",
"Update All Modified Content",
SO,
"{}",
|s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
|s, _| update_all(s)
),
spec!("layer.smartObjects.updateAllModifiedContent", "Update All Modified Content", SO, "{}", can_update_all_contents, |s, _| update_all(s)),
spec!(
"layer.smartObjects.convertToLayers",
"Convert to Layers",
@@ -434,6 +438,8 @@ pub fn specs() -> Vec<CommandSpec> {
mod stack_cache;
mod unpack;
#[cfg(test)]
mod indexed_bitmap_tests;
#[cfg(test)]
mod reset_transform_enabled_tests;
#[cfg(test)]
@@ -0,0 +1,67 @@
use super::{ColorMode, Document, Layer, LayerContent, SO, SampleType, Session, SmartObject, SmartSource, specs};
use photocraft_color::Color;
use photocraft_geom::{Affine, Size};
use serde_json::{Value, json};
use std::sync::Arc;
const CONVERT: &str = "layer.smartObjects.convertToSmartObject";
const UPDATE_ALL: &str = "layer.smartObjects.updateAllModifiedContent";
fn document(mode: ColorMode, depth: SampleType) -> Document {
Document::with_background("Mode", Size::new(8, 8), mode, depth, Color::rgb(0.5, 0.5, 0.5))
}
fn session(doc: Document) -> Session {
let mut s = crate::session();
s.add_document(doc, None);
s
}
#[test]
fn bitmap_and_indexed_disable_new_smart_objects_even_with_an_explicit_target() {
for (mode, label) in [(ColorMode::Bitmap, "Bitmap"), (ColorMode::Indexed, "Indexed Color")] {
let mut s = session(document(mode, SampleType::U8));
for spec in specs().into_iter().filter(|spec| spec.menu == SO) {
assert!(!s.is_enabled(spec.id), "{mode:?} enabled {}", spec.id);
}
let state = s.active().unwrap();
let doc = state.doc.clone();
let active = state.active_layer.unwrap();
let history = state.history.past_len();
for params in [Value::Null, json!({"layer": active.0})] {
let refusal = s.execute(CONVERT, params).unwrap_err().to_string();
assert!(refusal.contains(label), "{refusal}");
let state = s.active().unwrap();
assert!(Arc::ptr_eq(&state.doc, &doc));
assert_eq!(state.active_layer, Some(active));
assert_eq!(state.history.past_len(), history);
}
}
}
#[test]
fn supported_document_modes_keep_their_smart_object_commands_at_each_depth() {
for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale] {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
let s = session(document(mode, depth));
assert!(s.is_enabled(CONVERT), "{mode:?}/{depth:?}");
assert!(s.is_enabled(UPDATE_ALL), "{mode:?}/{depth:?}");
}
}
}
#[test]
fn an_existing_smart_object_retains_its_content_commands() {
for mode in [ColorMode::Bitmap, ColorMode::Indexed] {
let mut doc = document(mode, SampleType::U8);
let source = SmartSource::Embedded { file_name: "Existing.pcraft".into(), bytes: Arc::new(Vec::new()) };
let layer = Layer::new("Existing", LayerContent::Smart(SmartObject::new(source, Affine::translate(0.0, 0.0), None)));
let id = doc.insert_above(None, layer);
let mut s = session(doc);
s.execute("layer.select", json!({"layer": id.0})).unwrap();
assert!(s.is_enabled("layer.smartObjects.editContents"), "{mode:?}");
assert!(s.is_enabled(UPDATE_ALL), "{mode:?}");
}
}
@@ -0,0 +1,31 @@
use photocraft_geom::Rect;
use serde_json::json;
#[test]
fn transform_again_is_enabled_only_after_a_transform_in_the_session() {
let command = "edit.transform.again";
let mut session = crate::session();
assert!(!session.is_enabled(command));
session.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
session.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap();
session
.edit("Paint fixture", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 35, 30), &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
assert!(!session.is_enabled(command), "ordinary document edits do not enable Again");
let history = session.active().unwrap().history.past_len();
let error = session.execute(command, json!({})).unwrap_err().to_string();
assert!(error.contains("there is no transform to repeat"), "{error}");
assert_eq!(session.active().unwrap().history.past_len(), history);
session.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap();
assert!(session.is_enabled(command));
session.execute(command, json!({})).unwrap();
assert_eq!(session.active().unwrap().history.past_len(), history + 2);
session.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
assert!(session.is_enabled(command), "the previous transform remains session-wide when opening another document");
}
@@ -0,0 +1,61 @@
use photocraft_doc::{LayerContent, LayerId, TextLayer, text::TextShape};
use photocraft_geom::Rect;
use serde_json::json;
use crate::Session;
fn text_and_ink(s: &Session, id: LayerId) -> (&TextLayer, Rect) {
let layer = s.active().unwrap().doc.layer(id).unwrap();
let LayerContent::Text(text) = &layer.content else { panic!("expected text") };
(text, layer.surface().unwrap().content_bounds())
}
fn convert(text: &str, size: u32) -> (f32, f64) {
let mut s = crate::session();
s.execute("file.new", json!({"width": 640, "height": 480, "resolution": 72})).unwrap();
let result = s.execute("type.create", json!({"x": 100, "y": 200, "text": text, "font": "Arial", "size": size})).unwrap();
let id = LayerId(result["layer"].as_u64().unwrap());
let (point, before_ink) = text_and_ink(&s, id);
let before = super::layout_at(72.0, point);
let before_baseline = point.transform.m[5] + f64::from(before.lines[0].baseline);
let [x0, top, x1, bottom] = before.bounds().unwrap();
let expected_width = (x1 - x0).max(1.0) + (size as f32 * 0.5).max(4.0);
s.execute("type.convertToParagraphText", json!({})).unwrap();
let (paragraph, after_ink) = text_and_ink(&s, id);
let TextShape::Box { width, height, .. } = paragraph.shape else { panic!("expected paragraph text") };
let after = super::layout_at(72.0, paragraph);
assert_eq!(paragraph.text, text);
assert_eq!(after.lines.len(), before.lines.len());
assert!(!after.overflows(text), "the new box must keep every line");
assert!((width - expected_width).abs() < 1e-4);
if before.lines.len() == 1 {
let expected_height = (bottom - top).max(size as f32 * 1.2).max(after.lines[0].baseline);
assert!((height - expected_height).abs() < 1e-4, "expected {expected_height}, got {height}");
}
let after_baseline = paragraph.transform.m[5] + f64::from(after.lines[0].baseline);
assert!((after_baseline - before_baseline).abs() < 1e-4);
assert_eq!(after_ink, before_ink);
assert_eq!(s.active().unwrap().history.undo_label(), Some("Convert to Paragraph Text"));
(height, paragraph.transform.m[5])
}
#[test]
fn converting_48_point_arial_uses_its_line_height() {
let (height, y) = convert("Hello World", 48);
let arial_available = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).has_family("Arial");
if arial_available {
assert!((height - 58.0).abs() <= 1.0, "height {height}");
assert!((y - 165.63).abs() <= 1.0, "top {y}");
} else {
assert!(height >= 57.0, "the leading fits even with the fallback font: {height}");
}
}
#[test]
fn smaller_text_gets_a_shorter_box_and_multiline_text_still_fits() {
let (single, _) = convert("Hello World", 48);
let (small, _) = convert("Hello World", 24);
let (multiline, _) = convert("Hello World\nThird?\nA final line", 48);
assert!(small < single && single < multiline, "{small}, {single}, {multiline}");
}
+104 -23
View File
@@ -21,8 +21,23 @@ use crate::type_cmds::{
};
use crate::{EngineError, Result, Session};
/// Photoshop's Paste Lorem Ipsum filler.
pub const LOREM_IPSUM: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
/// One paragraph of Paste Lorem Ipsum filler.
pub const LOREM_IPSUM: &str = concat!(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ",
"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. ",
"Dum verba in pagina disponuntur, lector ordinem litterarum et spatium inter lineas considerat. ",
"Scriptor idem initium retinet et diversas sententias addit, ut forma paginae sine imagine clarius appareat. ",
"Alia verba brevia sunt, alia longiora, et finis cuiusque lineae pro latitudine spatii mutatur. ",
"Interdum pagina amplior plures litteras recipit, interdum angusta paucis verbis impletur. ",
"Utraque forma exemplum praebet, dum verba suo ordine manent.",
);
#[cfg(test)]
#[path = "type_paste_lorem_length_tests.rs"]
mod paste_lorem_length_tests;
// ---------- predicates ----------
@@ -189,17 +204,37 @@ fn to_paragraph(s: &mut Session, p: &Value) -> Result<Value> {
let [x0, y0, x1, y1] = l.bounds().unwrap_or([0.0, -t.size_pt, t.size_pt, 0.0]);
// A little slack so no line re-wraps; the box keeps the text where it was.
let width = (x1 - x0).max(1.0) + indents + (size_px * 0.5).max(4.0);
let height = (y1 - y0).max(1.0) + size_px * 0.5;
let text_height = (y1 - y0).max(1.0);
let probe_height = text_height + size_px * 0.5;
let x = match ps.align {
TextAlign::Center | TextAlign::JustifyCenter => -width / 2.0,
TextAlign::Right | TextAlign::JustifyRight => -width,
_ => 0.0,
};
let mut probe = t.clone();
probe.shape = TextShape::Box { x, y: y0, width, height };
probe.shape = TextShape::Box { x, y: y0, width, height: probe_height };
// Box text puts the first baseline at the box top plus the ascender height: measure it and
// shift the box so that baseline stays at the point-text anchor (y = 0).
let b0 = layout_at(dpi, &probe).lines.first().map_or(0.0, |ln| ln.baseline);
let boxed = layout_at(dpi, &probe);
let b0 = boxed.lines.first().map_or(0.0, |ln| ln.baseline);
let mut height = text_height;
if t.text.is_empty() || l.lines.is_empty() {
height = probe_height;
} else if l.lines.len() == 1 {
// A single line still gets its leading. Across multiple lines the bounds already
// account for the laid-out baseline spacing.
let leading = l
.glyphs
.iter()
.map(|glyph| {
let style = &l.styles[glyph.style as usize];
style.leading_pt.map_or(ps.auto_leading * l.faces[glyph.face as usize].size_px, |points| points * l.px_per_pt)
})
.fold(0.0, f32::max);
height = height.max(leading);
}
// The box uses ascender placement; keep every baseline that fit the original probe.
height = height.max(boxed.lines.last().map_or(0.0, |ln| ln.baseline - y0));
let y = y0 - b0;
t.shape = TextShape::Box { x: 0.0, y: 0.0, width, height };
t.transform = then_translate(&t.transform, f64::from(x), f64::from(y));
@@ -800,10 +835,17 @@ fn paste_lorem(s: &mut Session, p: &Value) -> Result<Value> {
// else the active layer when it is a type layer.
let new = p.get("new").and_then(Value::as_bool) == Some(true);
if !new && (explicit_layer(s, p)?.is_some() || has_text(s).is_ok()) {
let caret = with_text(s, p, "Paste Lorem Ipsum", |t, _| {
let at = p.get("at").and_then(Value::as_u64).map_or(t.text.len(), |c| byte_index(&t.text, c as usize));
replace_text(t, at, at, LOREM_IPSUM);
Ok(char_index(&t.text, at + LOREM_IPSUM.len()))
let range_end = p.get("end").and_then(Value::as_u64);
// The editor sends a range and its typing session's coalesce key. A new layer keeps its
// existing creation step; the first edit of an existing layer gets the type-edit label.
let label = if range_end.is_some() && p.get("coalesce").and_then(Value::as_str).is_some() { "Edit Type Layer" } else { "Paste Lorem Ipsum" };
let caret = with_text(s, p, label, |t, _| {
let to_byte = |c| byte_index(&t.text, usize::try_from(c).unwrap_or(usize::MAX));
let at = p.get("at").and_then(Value::as_u64).map_or(t.text.len(), to_byte);
let end = range_end.map_or(at, to_byte);
let start = at.min(end);
replace_text(t, start, at.max(end), LOREM_IPSUM);
Ok(char_index(&t.text, start + LOREM_IPSUM.len()))
})?;
return Ok(json!({"caret": caret}));
}
@@ -816,19 +858,46 @@ fn paste_lorem(s: &mut Session, p: &Value) -> Result<Value> {
}
fn update_all(s: &mut Session) -> Result<Value> {
let mut n = 0;
s.edit("Update All Text Layers", |doc, _| {
let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());
let ids: Vec<LayerId> = doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();
for id in ids {
if let Some(Layer { content: LayerContent::Text(t), .. }) = doc.layer_mut(id) {
refresh_at(dpi, format, t);
n += 1;
}
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let mut texts = doc
.walk()
.into_iter()
.filter_map(|(_, _, l)| match &l.content {
LayerContent::Text(text) => Some((l.id, text)),
_ => None,
})
.peekable();
if texts.peek().is_none() {
return Ok(json!({"updated": 0}));
}
let generation = photocraft_raster::spill::read_error_generation();
doc.scratch_health().map_err(EngineError::Other)?;
let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());
let mut count = 0;
let mut changes = Vec::new();
for (id, text) in texts {
let mut refreshed = text.clone();
refresh_at(dpi, format, &mut refreshed);
// An identical render keeps its existing PSD block, including imported metadata.
// A missing block can still be restored even if its pixels were already current.
if text.cache != refreshed.cache || (text.psd_raw.is_none() && refreshed.psd_raw.is_some()) {
changes.push((id, refreshed.cache, refreshed.psd_raw));
}
Ok(())
})?;
Ok(json!({"updated": n}))
count += 1;
}
photocraft_raster::spill::check_since(generation).and_then(|()| doc.scratch_health()).map_err(EngineError::Other)?;
if !changes.is_empty() {
s.edit("Update All Text Layers", |doc, _| {
for (id, cache, psd_raw) in changes {
if let Some(Layer { content: LayerContent::Text(text), .. }) = doc.layer_mut(id) {
text.cache = cache;
text.psd_raw = psd_raw;
}
}
Ok(())
})?;
}
Ok(json!({"updated": count}))
}
fn style_font_missing(fonts: &mut photocraft_text::FontDb, style: &photocraft_doc::text::CharStyle) -> bool {
@@ -1104,7 +1173,7 @@ pub fn specs() -> Vec<CommandSpec> {
set_path_placement
),
spec!("type.detachFromPath", "Release Type from Path", &[], LP, is_path_text, detach_from_path),
spec!("type.updateAllTextLayers", "Update All Text Layers", &["Type"], "{}", any_text, |s, _| update_all(s)),
spec!("type.updateAllTextLayers", "Update All Text Layers", &["Type"], "{}", has_doc, |s, _| update_all(s)),
spec!("type.replaceAllMissingFonts", "Replace All Missing Fonts", &["Type"], "{} (with the default family)", any_text, |s, _| replace_fonts(
s,
&serde_json::Map::new(),
@@ -1122,7 +1191,7 @@ pub fn specs() -> Vec<CommandSpec> {
"type.pasteLoremIpsum",
"Paste Lorem Ipsum",
&["Type"],
r##"{"layer":id?,"at":char? (default end),"new":bool=false (new paragraph text layer)}"##,
r##"{"layer":id?,"at":char? (default end),"end":char? (replace the range between at and end; omit to insert),"new":bool=false (new paragraph text layer)}"##,
has_doc,
paste_lorem
),
@@ -1140,10 +1209,18 @@ pub fn specs() -> Vec<CommandSpec> {
all
}
#[cfg(test)]
#[path = "type_convert_paragraph_box_tests.rs"]
mod type_convert_paragraph_box_tests;
#[cfg(test)]
#[path = "type_extra_cmds/tests.rs"]
mod tests;
#[cfg(test)]
#[path = "type_update_all_layers_tests.rs"]
mod update_all_layers_tests;
#[cfg(test)]
#[path = "type_anti_alias_history_tests.rs"]
mod anti_alias_history_tests;
@@ -1151,3 +1228,7 @@ mod anti_alias_history_tests;
#[cfg(test)]
#[path = "type_missing_fonts_history_tests.rs"]
mod missing_fonts_history_tests;
#[cfg(test)]
#[path = "type_paste_lorem_selection_tests.rs"]
mod type_paste_lorem_selection_tests;
@@ -0,0 +1,25 @@
use serde_json::json;
use super::LOREM_IPSUM;
#[test]
fn paste_lorem_adds_one_full_paragraph_without_growing_the_type_box() {
let mut session = crate::session();
session.execute("file.new", json!({"width": 240, "height": 120})).unwrap();
for params in [json!({"x": 10, "y": 20, "text": "Existing"}), json!({"box": [10, 10, 20, 18], "text": "Existing"})] {
let layer = session.execute("type.create", params).unwrap()["layer"].as_u64().unwrap();
let before = session.execute("type.info", json!({"layer": layer})).unwrap();
let reply = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 0})).unwrap();
let after = session.execute("type.info", json!({"layer": layer})).unwrap();
let filler = after["text"].as_str().unwrap().strip_suffix("Existing").unwrap();
let len = filler.chars().count();
assert_eq!(filler, LOREM_IPSUM);
assert!((950..=1100).contains(&len), "expected about one thousand characters, got {len}");
assert!(filler.starts_with("Lorem ipsum dolor sit amet"));
assert!(!filler.contains(['\r', '\n']));
assert_eq!(reply["caret"], json!(len));
assert!(!before["shape"].is_null());
assert_eq!(after["shape"], before["shape"], "the full text is kept in the original point or paragraph geometry");
}
}
@@ -0,0 +1,57 @@
use serde_json::json;
use super::LOREM_IPSUM;
#[test]
fn paste_lorem_replaces_a_character_range_and_undo_restores_text() {
let mut session = crate::session();
session.execute("file.new", json!({"width": 300, "height": 120})).unwrap();
let layer = session.execute("type.create", json!({"x": 20, "y": 70, "text": "é猫Ω"})).unwrap()["layer"].clone();
let before = session.active().unwrap().history.past_len();
// A reversed selection of one multi-byte character, as seen by the browser or desktop editor.
let result = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 2, "end": 1, "coalesce": "existing-type-edit"})).unwrap();
assert_eq!(result["caret"], 1 + LOREM_IPSUM.chars().count());
assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], format!("é{LOREM_IPSUM}Ω"));
let history = &session.active().unwrap().history;
assert_eq!(history.past_len(), before + 1);
assert_eq!(history.undo_label(), Some("Edit Type Layer"));
assert!(session.undo());
assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], "é猫Ω");
session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 1, "end": 1})).unwrap();
assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], format!("é{LOREM_IPSUM}猫Ω"));
}
#[test]
fn paste_lorem_replaces_a_new_layers_placeholder_in_its_creation_step() {
let mut session = crate::session();
session.execute("file.new", json!({"width": 300, "height": 120})).unwrap();
let before = session.active().unwrap().history.past_len();
let layer =
session.execute("type.create", json!({"x": 20, "y": 70, "text": "Lorem Ipsum", "coalesce": "new-type-layer"})).unwrap()["layer"].as_u64().unwrap();
let result = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 0, "end": 11, "coalesce": "new-type-layer"})).unwrap();
assert_eq!(result["caret"], LOREM_IPSUM.chars().count());
assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], LOREM_IPSUM);
let state = session.active().unwrap();
let id = photocraft_doc::LayerId(layer);
assert_eq!(state.doc.layer(id).unwrap().name, crate::type_cmds::layer_name(LOREM_IPSUM));
assert_eq!(state.history.past_len(), before + 1);
assert_eq!(state.history.undo_label(), Some("New Type Layer"));
assert!(session.undo());
assert!(session.active().unwrap().doc.layer(id).is_none());
}
#[test]
fn paste_lorem_clamps_both_oversized_character_offsets() {
let mut session = crate::session();
session.execute("file.new", json!({"width": 300, "height": 120})).unwrap();
let layer = session.execute("type.create", json!({"x": 20, "y": 70, "text": "é猫Ω"})).unwrap()["layer"].as_u64().unwrap();
let beyond_wasm32 = u64::from(u32::MAX) + 1;
let result = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": beyond_wasm32, "end": beyond_wasm32})).unwrap();
assert_eq!(result["caret"], 3 + LOREM_IPSUM.chars().count());
assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], format!("é猫Ω{LOREM_IPSUM}"));
}
@@ -0,0 +1,80 @@
use serde_json::json;
use super::*;
const UPDATE: &str = "type.updateAllTextLayers";
fn create_text(session: &mut Session, text: &str, y: i32) -> LayerId {
LayerId(session.execute("type.create", json!({"text": text, "x": 6, "y": y})).unwrap()["layer"].as_u64().unwrap())
}
fn text(session: &Session, id: LayerId) -> &TextLayer {
let LayerContent::Text(text) = &session.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected text") };
text
}
fn assert_clean_refresh(session: &mut Session, visited: usize) {
session.saved_to("type-update.psd".into());
let before = session.active().unwrap();
let doc = before.doc.clone();
let revision = before.revision;
let steps = before.history.past_len();
assert_eq!(session.execute(UPDATE, json!({})).unwrap()["updated"], json!(visited));
let after = session.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&doc, &after.doc));
assert_eq!(after.history.past_len(), steps);
assert_eq!(after.revision, revision);
assert!(!after.is_dirty());
}
#[test]
fn update_all_is_available_without_text_and_keeps_healthy_layers_clean() {
let mut session = crate::session();
assert!(!session.is_enabled(UPDATE));
session.execute("file.new", json!({"width": 256, "height": 128, "background": "white"})).unwrap();
assert!(session.is_enabled(UPDATE));
assert_clean_refresh(&mut session, 0);
create_text(&mut session, "First text", 24);
create_text(&mut session, "Second text", 54);
assert!(session.is_enabled(UPDATE));
assert_clean_refresh(&mut session, 2);
session.execute("select.deselectLayers", json!({})).unwrap();
assert!(session.is_enabled(UPDATE));
assert_clean_refresh(&mut session, 2);
}
#[test]
fn update_all_repairs_stale_text_in_one_undo_step() {
let mut session = crate::session();
session.execute("file.new", json!({"width": 256, "height": 128, "background": "white"})).unwrap();
let a = create_text(&mut session, "Existing text", 24);
let b = create_text(&mut session, "Text needing layout", 54);
let current = text(&session, b).cache.clone().unwrap();
let missing = text(&session, b).psd_raw.clone().unwrap();
let healthy = text(&session, a).psd_raw.clone().unwrap();
session
.edit("Stale text fixture", |doc, _| {
let LayerContent::Text(text) = &mut doc.layer_mut(b).unwrap().content else { panic!("expected text") };
text.cache = None;
text.psd_raw = None;
Ok(())
})
.unwrap();
session.saved_to("type-update.psd".into());
let prior_steps = session.active().unwrap().history.past_len();
assert_eq!(session.execute(UPDATE, json!({})).unwrap()["updated"], 2);
let updated = session.active().unwrap();
assert!(updated.is_dirty());
assert_eq!(updated.history.past_len(), prior_steps + 1);
assert_eq!(updated.history.undo_label(), Some("Update All Text Layers"));
assert_eq!(text(&session, b).cache.as_ref(), Some(&current));
assert_eq!(text(&session, b).psd_raw.as_ref(), Some(&missing));
assert!(std::sync::Arc::ptr_eq(&healthy, text(&session, a).psd_raw.as_ref().unwrap()));
session.execute("edit.undo", json!({})).unwrap();
assert!(text(&session, b).cache.is_none());
assert!(text(&session, b).psd_raw.is_none());
assert_eq!(session.active().unwrap().history.past_len(), prior_steps);
}
+19 -1
View File
@@ -139,7 +139,21 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
let q = Value::Object(o);
let st = WebSettings::from_params(&q, cmd)?;
let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?;
let buf = photocraft_compose::flatten(&wdoc);
let mut buf = photocraft_compose::flatten(&wdoc);
// A new 32-bit RGB document can be untagged. Encode its linear composite
// when exporting sRGB PNG. Tagged documents use web_document's ICC conversion.
if fmt == "png"
&& st.convert_to_srgb
&& doc.mode == photocraft_color::ColorMode::Rgb
&& doc.depth == photocraft_color::SampleType::F32
&& doc.icc_profile.is_none()
{
for [r, g, b, _] in &mut buf.px {
*r = photocraft_color::convert::linear_to_srgb(*r);
*g = photocraft_color::convert::linear_to_srgb(*g);
*b = photocraft_color::convert::linear_to_srgb(*b);
}
}
let xmp = web_xmp(&doc, st.metadata);
let exif = web_exif(&doc, st.metadata);
let opt = optimize(
@@ -157,3 +171,7 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
crate::automate_cmds::fire_event(s, "export");
Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)}))
}
#[cfg(test)]
#[path = "quick_export_32bit_tests.rs"]
mod quick_export_32bit_tests;
@@ -0,0 +1,67 @@
use photocraft_codecs::{ChannelLayout, Image, SampleType};
use photocraft_doc::Layer;
use photocraft_geom::Rect;
use serde_json::json;
use crate::Session;
fn document(depth: u32, background: &str, alpha: f32) -> Session {
let mut session = crate::session();
session.execute("file.new", json!({"width": 4, "height": 1, "depth": depth, "background": background})).unwrap();
session
.edit("Paint samples", |doc, _| {
let fmt = doc.pixel_format();
let mut layer = Layer::raster("Samples", fmt);
let surface = layer.surface_mut().unwrap();
for (x, rgb) in [(0, [200_u8, 30, 30]), (1, [30, 30, 200]), (2, [0, 0, 0])] {
let [r, g, b] = rgb.map(|v| f32::from(v) / 255.0);
surface.fill_rect(Rect::new(x, 0, x + 1, 1), &photocraft_raster::from_rgba(&fmt, [r, g, b, alpha]));
}
doc.insert_above(None, layer);
Ok(())
})
.unwrap();
assert!(session.active().unwrap().doc.icc_profile.is_none());
session
}
fn export_png(session: &mut Session, convert_to_srgb: bool) -> Image {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("quick.png");
session.execute("file.export.exportPreferences", json!({"convertToSrgb": convert_to_srgb})).unwrap();
let active = session.active().unwrap();
let (document, history, dirty) = (active.doc.clone(), active.history.past_len(), active.is_dirty());
session.execute("file.export.quickExport", json!({"path": path.to_str().unwrap()})).unwrap();
let active = session.active().unwrap();
assert_eq!(active.doc, document);
assert_eq!(active.history.past_len(), history);
assert_eq!(active.is_dirty(), dirty);
let encoded = photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap();
assert_eq!(encoded.sample_type(), SampleType::U8);
encoded
}
#[test]
fn rgb_png_encodes_linear_samples_only_at_32_bits() {
for (depth, high, low) in [(8, 200, 30), (16, 200, 30), (32, 229, 96)] {
let image = export_png(&mut document(depth, "white", 1.0), true);
assert_eq!(image.layout(), ChannelLayout::Rgb, "{depth} bits");
assert_eq!(image.data(), &[high, low, low, low, low, high, 0, 0, 0, 255, 255, 255], "{depth} bits");
}
}
#[test]
fn png_keeps_alpha_and_respects_profile_and_conversion_preferences() {
let image = export_png(&mut document(32, "transparent", 0.5), true);
assert_eq!(image.layout(), ChannelLayout::Rgba);
assert_eq!(&image.data()[..8], &[229, 96, 96, 128, 96, 96, 229, 128]);
let image = export_png(&mut document(32, "white", 1.0), false);
assert_eq!(&image.data()[..6], &[200, 30, 30, 30, 30, 200]);
let mut tagged = document(32, "white", 1.0);
tagged.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap();
assert!(tagged.active().unwrap().doc.icc_profile.is_some());
let image = export_png(&mut tagged, true);
assert_eq!(&image.data()[..6], &[200, 30, 30, 30, 30, 200]);
}
+7
View File
@@ -55,9 +55,16 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> {
return None;
}
let st = s.active()?;
if id == "layer.translate" && matches!(crate::commands::explicit_layer(s, &params), Ok(None)) && st.selected_layers().len() > 1 {
return None;
}
let layer = crate::commands::layer_param(s, &params).ok()?;
// The Art History Brush's text was measured on a layer's pixels only.
let pixels = crate::channel_cmds::target_of(&params) == crate::channel_cmds::Target::Pixels;
let why = if id == "paint.artHistoryBrush" && pixels { ART_HISTORY_HIDDEN } else { HIDDEN };
(st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(why)
}
#[cfg(test)]
#[path = "cmd/layer_multi_cmds/move_hidden_in_selection_tests.rs"]
mod move_hidden_in_selection_tests;
+6 -2
View File
@@ -114,7 +114,7 @@ choice!(CheckerColors { Light = "light", Medium = "medium", Dark = "dark", Red =
choice!(LineStyle { Lines = "lines", Dashed = "dashedLines", Dots = "dots" } default Lines);
choice!(TextEngine { Modern = "modern", EastAsian = "eastAsian", WorldReady = "worldReady" } default WorldReady);
choice!(FontPreview { Off = "off", Small = "small", Medium = "medium", Large = "large", ExtraLarge = "extraLarge", Huge = "huge" } default Medium);
choice!(RawColorSpace { Srgb = "srgb", AdobeRgb = "adobeRgb", ProPhoto = "proPhoto", DisplayP3 = "displayP3" } default AdobeRgb);
choice!(RawColorSpace { Srgb = "srgb", AdobeRgb = "adobeRgb", ProPhoto = "proPhoto", DisplayP3 = "displayP3" } default DisplayP3);
choice!(RawDepth { Eight = "8", Sixteen = "16" } default Sixteen);
choice!(RawSharpen { None = "none", Screen = "screen", Glossy = "glossy", Matte = "matte" } default None);
choice!(
@@ -1247,7 +1247,7 @@ impl RawDemosaic {
impl Default for RawDefaults {
fn default() -> Self {
Self {
color_space: RawColorSpace::AdobeRgb,
color_space: RawColorSpace::default(),
bit_depth: RawDepth::Sixteen,
resolution: 300,
sharpen_for: RawSharpen::None,
@@ -1950,6 +1950,10 @@ impl Session {
#[path = "prefs/raw_defaults_resolution_tests.rs"]
mod raw_defaults_resolution_tests;
#[cfg(test)]
#[path = "prefs/raw_defaults_space_default_tests.rs"]
mod raw_defaults_space_default_tests;
#[cfg(test)]
#[path = "prefs/reset_keeps_workspaces_tests.rs"]
mod reset_keeps_workspaces_tests;
@@ -0,0 +1,58 @@
use serde_json::json;
use super::SavedPrefsExt;
const SPACE: &str = "rawDefaults.colorSpace";
#[test]
fn raw_defaults_uses_display_p3_on_fresh_settings_and_after_reset() {
let mut s = crate::session();
let get = json!({"path": SPACE});
assert_eq!(s.execute("prefs.get", get.clone()).unwrap(), "displayP3");
for reset in ["rawDefaults", SPACE] {
s.execute("prefs.set", json!({"path": SPACE, "value": "adobeRgb"})).unwrap();
assert_eq!(s.execute("prefs.get", get.clone()).unwrap(), "adobeRgb");
s.execute("prefs.reset", json!({"path": reset})).unwrap();
assert_eq!(s.execute("prefs.get", get.clone()).unwrap(), "displayP3");
}
}
#[test]
fn saved_raw_color_spaces_load_unchanged() {
for choice in super::RawColorSpace::NAMES {
let mut s = crate::session();
let saved = json!({"rawDefaults": {"colorSpace": choice}}).to_string();
assert!(s.load_prefs_json(&saved).unwrap().is_empty(), "{choice}");
assert_eq!(s.execute("prefs.get", json!({"path": SPACE})).unwrap(), *choice);
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn batch_raw_opens_with_the_factory_display_p3_profile() {
use craft_cms::{Builtin, Profile};
use photocraft_raw::testgen::{DngSpec, mosaic, scene};
let dir = tempfile::tempdir().unwrap();
let source = dir.path().join("IMG_0001.dng");
let output = dir.path().join("out");
let (width, height) = (24, 16);
let raw = DngSpec::cfa(width, height, mosaic(&scene(width, height), width, [0, 1, 1, 2], 0, 65535)).build();
std::fs::write(&source, raw).unwrap();
let mut s = crate::session();
let result = s
.execute(
"file.automate.batch",
json!({"input":[source], "output":output, "format":"psd", "suppressOpenOptions":true, "suppressWarnings":true, "steps":[]}),
)
.unwrap();
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
let saved = std::fs::read(output.join("IMG_0001.psd")).unwrap();
let doc = photocraft_io::import("IMG_0001.psd", &saved).unwrap().document;
let profile = Profile::parse(doc.icc_profile.as_ref().unwrap()).unwrap();
assert!(profile.same_colors(Builtin::DisplayP3.profile()));
assert_eq!(doc.resolution_dpi, 300.0);
assert_eq!(doc.depth, photocraft_color::SampleType::U16);
}
+21 -1
View File
@@ -133,12 +133,30 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(damage(s, Rect::EMPTY, false));
}
}
/// The bounding rectangle of a selection whose pixels are all fully selected or not selected, on the canvas.
/// `None` for one with partly selected pixels (feathered, anti-aliased), and for an empty one.
fn hard_bounds(selection: &photocraft_raster::Surface, canvas: Rect) -> Option<Rect> {
let bounds = selection.content_bounds();
if bounds.is_empty() || selection.default_pixel().first().is_some_and(|v| *v > 0.0) {
return None;
}
let channels = selection.channels().max(1);
let hard = (bounds.y0..bounds.y1).step_by(64).all(|y| {
let rows = Rect::new(bounds.x0, y, bounds.x1, y.saturating_add(64).min(bounds.y1));
selection.read_region(rows).chunks_exact(channels).all(|px| px[0] <= 0.0 || px[0] >= 1.0)
});
hard.then(|| bounds.intersect(&canvas))
}
let (area, img) = if sample_all {
crate::selection_cmds::sample_rgba8(s, true)?
} else {
let d = s.active().ok_or(EngineError::NoDocument)?;
let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::NoLayer(id))?;
(d.doc.bounds(), sel::rgba8_image(surf, d.doc.bounds()))
// #18068: with a selection, a contiguous fill runs inside the selection's bounding rectangle, over selected
// and unselected pixels alike, and a seed outside that rectangle finds nothing. A selection with partly
// selected pixels and Sample All Layers were not measured and keep the whole canvas.
let area = d.doc.selection.as_ref().filter(|_| contiguous).and_then(|m| hard_bounds(m, d.doc.bounds())).unwrap_or_else(|| d.doc.bounds());
(area, sel::rgba8_image(surf, area))
};
// The reference's colour distance is measured for 8-bit RGB only (#11995).
let rgb8 = s.active().is_some_and(|d| d.doc.mode == ColorMode::Rgb && d.doc.depth == SampleType::U8);
@@ -337,6 +355,8 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
#[cfg(test)]
mod magic_eraser_contiguous_selection_bounds_tests;
#[cfg(test)]
mod magic_eraser_mode_refusal_tests;
#[cfg(test)]
@@ -0,0 +1,142 @@
//! #18068: with a selection and Contiguous on, the Magic Eraser's fill stays inside the selection's bounding
//! rectangle, over selected and unselected pixels alike, so it cannot reach another selected part by a path outside
//! it, and a click outside that rectangle erases nothing. The documents are the issue's, at a tenth of the size.
//! Not measured, so as before: a selection with partly selected pixels, and Sample All Layers.
use serde_json::{Value, json};
use crate::Session;
/// Red inside selection A and inside selection B, on the bar.
const IN_A: (i32, i32) = (10, 30);
const IN_B: (i32, i32) = (70, 30);
/// On the bar between A and B's side of the cut: inside the bounding rectangle, not selected.
const BESIDE_A: (i32, i32) = (25, 30);
/// The middle of the bar, between A and B: red when the bar is not cut.
const BETWEEN: (i32, i32) = (40, 30);
/// The top of the arch, above the bounding rectangle.
const ON_THE_ARCH: (i32, i32) = (40, 6);
/// White above the bounding rectangle, joined to the white of A and B above the bar.
const WHITE_ABOVE: (i32, i32) = (40, 12);
/// White inside A, above the bar.
const WHITE_IN_A: (i32, i32) = (10, 22);
fn fill(s: &mut Session, [x, y, w, h]: [i32; 4], color: &str) {
s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h, "antiAlias": false})).unwrap();
s.execute("edit.fill", json!({"color": color})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
}
/// An 80 x 45 white document with a red bar across rows 25 to 35.
fn uncut_bar() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 80, "height": 45, "mode": "rgb", "depth": 8, "background": "#ffffff"})).unwrap();
fill(&mut s, [0, 25, 80, 10], "#ff0000");
s
}
/// The bar cut between x 35 and 45, its two halves joined only by a red arch that rises to row 5, above the bounding
/// rectangle of the selections.
fn cut_bar() -> Session {
let mut s = uncut_bar();
fill(&mut s, [35, 25, 10, 10], "#ffffff");
for arch in [[30, 5, 3, 20], [47, 5, 3, 20], [30, 5, 20, 3]] {
fill(&mut s, arch, "#ff0000");
}
s
}
/// Selections A (x 0 to 20) and B (x 60 to 80), rows 20 to 40: their bounding rectangle is the full width of those
/// rows.
fn select_a_and_b(s: &mut Session) {
s.execute("select.rect", json!({"x": 0, "y": 20, "width": 20, "height": 20})).unwrap();
s.execute("select.rect", json!({"x": 60, "y": 20, "width": 20, "height": 20, "mode": "add"})).unwrap();
}
fn erase(s: &mut Session, (x, y): (i32, i32), options: Value) -> Value {
let mut p = json!({"x": x, "y": y});
p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
s.execute("paint.magicEraser", p).unwrap()
}
fn alpha(s: &Session, (x, y): (i32, i32)) -> f32 {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3]
}
/// How many History states there are, and the name of the newest.
fn history(s: &Session) -> (usize, Option<String>) {
let history = &s.active().unwrap().history;
(history.past_len(), history.undo_label().map(String::from))
}
#[test]
fn a_contiguous_fill_cannot_reach_another_selected_part_round_the_outside() {
for anti_alias in [true, false] {
let mut s = cut_bar();
select_a_and_b(&mut s);
let states = history(&s).0;
let reply = erase(&mut s, IN_A, json!({"antiAlias": anti_alias}));
assert_eq!(reply["erased"], true, "anti-alias {anti_alias}");
assert_eq!(alpha(&s, IN_A), 0.0, "anti-alias {anti_alias}: the red of A is erased");
assert_eq!(alpha(&s, IN_B), 1.0, "anti-alias {anti_alias}: B is only joined to A by the arch, outside the rectangle");
assert_eq!(alpha(&s, BESIDE_A), 1.0, "anti-alias {anti_alias}: the erase stays clipped to the selection");
assert_eq!(history(&s), (states + 1, Some("Magic Eraser".into())), "anti-alias {anti_alias}");
}
}
#[test]
fn a_seed_outside_the_bounding_rectangle_erases_nothing() {
for (mut s, seed, case) in [(cut_bar(), ON_THE_ARCH, "the arch"), (uncut_bar(), WHITE_ABOVE, "white above the rectangle")] {
select_a_and_b(&mut s);
let (before, states) = (s.active().unwrap().doc.clone(), history(&s));
let reply = erase(&mut s, seed, json!({}));
assert_eq!(reply, json!({"erased": false, "damage": [0, 0, 0, 0]}), "{case}");
assert!(s.active().unwrap().doc == before, "{case}: nothing changed");
assert_eq!(history(&s), states, "{case}: no History state");
}
}
#[test]
fn a_seed_in_the_rectangle_erases_the_selected_part_of_its_region() {
// The uncut bar joins A and B inside the rectangle, through pixels that are not selected.
for (seed, case) in [(BETWEEN, "between A and B"), (IN_A, "inside A")] {
let mut s = uncut_bar();
select_a_and_b(&mut s);
let states = history(&s).0;
erase(&mut s, seed, json!({}));
assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "{case}: the red of A and B is erased");
assert_eq!(alpha(&s, BETWEEN), 1.0, "{case}: the unselected red stays");
assert_eq!(alpha(&s, WHITE_IN_A), 1.0, "{case}: the white of A stays");
assert_eq!(history(&s), (states + 1, Some("Magic Eraser".into())), "{case}");
}
}
#[test]
fn contiguous_off_and_no_selection_keep_the_whole_canvas() {
// Contiguous off: every matching pixel, so the rectangle plays no part.
let mut s = cut_bar();
select_a_and_b(&mut s);
erase(&mut s, ON_THE_ARCH, json!({"contiguous": false}));
assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "Contiguous off erases the matching red of A and B");
// No selection: the fill follows the arch.
let mut s = cut_bar();
erase(&mut s, IN_A, json!({}));
assert_eq!((alpha(&s, ON_THE_ARCH), alpha(&s, IN_B)), (0.0, 0.0), "without a selection the whole joined red is erased");
}
/// Not measured, so as before: the region is found on the whole canvas and reaches B round the arch.
#[test]
fn a_soft_selection_and_sample_all_layers_keep_the_whole_canvas() {
let mut s = cut_bar();
select_a_and_b(&mut s);
s.execute("select.modify.feather", json!({"radius": 1})).unwrap();
erase(&mut s, IN_A, json!({}));
assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "a feathered selection");
let mut s = cut_bar();
select_a_and_b(&mut s);
erase(&mut s, IN_A, json!({"sampleAllLayers": true}));
assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "Sample All Layers");
}
@@ -96,7 +96,8 @@ fn duotone_and_multichannel_keep_todays_behaviour() {
for (case, mode) in [("Duotone", photocraft_color::ColorMode::Duotone), ("Multichannel", photocraft_color::ColorMode::Multichannel)] {
let mut s = session(mode, SampleType::U8);
let id = s.active().unwrap().active_layer.unwrap();
let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false}));
// Inside the selection: a click outside its bounding rectangle erases nothing (#18068).
let r = s.execute("paint.magicEraser", json!({"x": 12, "y": 12, "antiAlias": false}));
assert!(r.is_ok(), "{case}: keeps today's behaviour, answers {r:?}");
assert_eq!(r.unwrap()["erased"], true, "{case}");
assert_eq!(s.active().unwrap().doc.layer(id).unwrap().name, "Layer 0", "{case}");
+35 -1
View File
@@ -50,9 +50,39 @@ fn enabled(s: &Session) -> std::result::Result<(), String> {
if ids.is_empty() {
return Err("no layer selected".into());
}
// Greyed in these document modes, for more than one selected layer, for a smart object and for a
// hidden shape, as measured in the reference application (#18301). Other modes and other hidden
// layers were not measured.
use photocraft_color::ColorMode;
let mode = match st.doc.mode {
ColorMode::Cmyk => Some("CMYK"),
ColorMode::Grayscale => Some("Grayscale"),
ColorMode::Lab => Some("Lab"),
ColorMode::Indexed => Some("Indexed Color"),
_ => None,
};
if let Some(mode) = mode {
return Err(format!("not available in {mode} mode"));
}
if ids.len() > 1 {
return Err("more than one layer is selected".into());
}
let selected = st.doc.walk().into_iter().map(|(_, _, l)| l).find(|l| ids.contains(&l.id)).ok_or("no layer selected")?;
// A fill layer with a vector mask is a shape here too.
let shape = match &selected.content {
LayerContent::Shape(_) => true,
LayerContent::Fill(_) => selected.vector_mask.is_some(),
_ => false,
};
if matches!(selected.content, LayerContent::Smart(_)) {
return Err("the layer is a smart object".into());
}
if shape && !selected.visible {
return Err("the shape layer is hidden".into());
}
// Photoshop greys Copy CSS out for a fill layer without a shape (measured), and for an
// adjustment layer, which has nothing to place either.
if st.doc.walk().iter().any(|(_, _, l)| ids.contains(&l.id) && has_css(l)) { Ok(()) } else { Err("no selected layer has CSS".into()) }
if has_css(selected) { Ok(()) } else { Err("no selected layer has CSS".into()) }
}
/// Whether a layer can have a rule (one with nothing to place still gets none).
@@ -374,3 +404,7 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "layer_css_enabled_states_tests.rs"]
mod enabled_states_tests;
@@ -0,0 +1,120 @@
//! #18301: Layer › Copy CSS is greyed, with a reason, for a smart object, a hidden shape layer, two or more selected
//! layers and CMYK, Grayscale, Lab and Indexed documents, as in the reference application. One visible shape, type,
//! pixel, Background or group layer in an RGB document keeps it enabled. Hidden layers of other kinds and Bitmap
//! documents were not measured and keep it enabled too.
use photocraft_doc::LayerId;
use photocraft_geom::Rect;
use serde_json::json;
use super::ID;
use crate::Session;
fn document(mode: &str, depth: u32) -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 64, "height": 48, "mode": mode, "depth": depth})).unwrap();
s
}
fn shape(s: &mut Session) -> u64 {
s.execute("shape.create", json!({"rect": [8, 8, 20, 16], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap()
}
fn pixels(s: &mut Session) -> u64 {
let id = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
s.edit("setup", |doc, _| {
doc.layer_mut(LayerId(id)).unwrap().surface_mut().unwrap().fill_rect(Rect::new(4, 4, 20, 20), &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
id
}
fn smart_object(s: &mut Session) -> u64 {
pixels(s);
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap()
}
fn point_type(s: &mut Session) -> u64 {
s.execute("type.create", json!({"x": 10, "y": 30, "text": "Hi", "size": 14})).unwrap()["layer"].as_u64().unwrap()
}
fn group(s: &mut Session) -> u64 {
s.execute("layer.new.group", json!({})).unwrap()["layer"].as_u64().unwrap()
}
fn hide(s: &mut Session, id: u64) {
s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
s.execute("layer.select", json!({"layer": id})).unwrap();
}
/// Greyed with a reason, and running it is refused.
fn assert_greyed(s: &mut Session, case: &str) {
assert!(!s.is_enabled(ID), "{case}: greyed");
assert!(s.disabled_reason(ID).is_some_and(|reason| !reason.is_empty()), "{case}: with a reason");
assert!(s.execute(ID, json!({})).is_err(), "{case}: refused");
}
#[test]
fn a_smart_object_a_hidden_shape_and_several_layers_grey_copy_css() {
let mut s = document("rgb", 8);
smart_object(&mut s);
assert_greyed(&mut s, "a smart object");
let mut s = document("rgb", 8);
let id = shape(&mut s);
assert!(s.is_enabled(ID), "the shape while it is visible");
hide(&mut s, id);
assert_greyed(&mut s, "a hidden shape layer");
for with_smart_object in [false, true] {
let mut s = document("rgb", 8);
let a = shape(&mut s);
let b = if with_smart_object { smart_object(&mut s) } else { shape(&mut s) };
s.execute("layer.select", json!({"layer": a})).unwrap();
s.execute("layer.select", json!({"layer": b, "mode": "add"})).unwrap();
assert_greyed(&mut s, if with_smart_object { "a shape and a smart object" } else { "two shapes" });
}
}
#[test]
fn cmyk_grayscale_lab_and_indexed_documents_grey_copy_css() {
for mode in ["cmyk", "grayscale", "lab"] {
let mut s = document(mode, 8);
shape(&mut s);
assert_greyed(&mut s, mode);
}
let mut s = document("rgb", 8);
assert!(s.is_enabled(ID), "the Background before the mode change");
s.execute("image.mode.indexedColor", json!({})).unwrap();
assert_greyed(&mut s, "indexed");
}
#[test]
fn one_visible_layer_in_an_rgb_document_keeps_copy_css_enabled() {
for depth in [8, 16, 32] {
let mut s = document("rgb", depth);
assert!(s.is_enabled(ID), "{depth}-bit: the Background");
for (kind, make) in [("a shape", shape as fn(&mut Session) -> u64), ("point type", point_type), ("a pixel layer", pixels), ("a group", group)] {
make(&mut s);
assert!(s.is_enabled(ID), "{depth}-bit: {kind}");
}
shape(&mut s);
s.execute("layer.lockLayers", json!({"all": true})).unwrap();
assert!(s.is_enabled(ID), "{depth}-bit: a shape with Lock All");
}
}
/// Not measured, so these stay enabled as they were.
#[test]
fn the_unmeasured_cases_keep_copy_css_enabled() {
for (kind, make) in [("type", point_type as fn(&mut Session) -> u64), ("pixel", pixels), ("group", group)] {
let mut s = document("rgb", 8);
let id = make(&mut s);
hide(&mut s, id);
assert!(s.is_enabled(ID), "a hidden {kind} layer");
}
let mut s = crate::session();
s.execute("file.new", json!({"width": 16, "height": 16, "mode": "bitmap", "depth": 1})).unwrap();
assert!(s.is_enabled(ID), "a Bitmap document");
}
+17
View File
@@ -121,9 +121,22 @@ pub fn background_eraser_stroke(stroke: &Stroke) -> Stroke {
let mut stroke = stroke.clone();
stroke.brush.opacity = 1.0;
stroke.brush.erase = false;
// The reference leaves the layer untouched at the lightest pen pressure (#18060): when every
// point's tip is narrower than half a pixel the stroke paints nothing. The floor that keeps a
// painted dab half a pixel wide would otherwise erase a 1 px line. A stroke whose pressure
// rises above the threshold keeps today's behaviour throughout, as the item leaves it.
if stroke.points.iter().all(|p| tip_narrower_than_half_a_pixel(&stroke.brush, p)) {
stroke.points.clear();
}
stroke
}
/// Whether `p`'s tip diameter is below the half pixel a dab's radius is floored at.
fn tip_narrower_than_half_a_pixel(brush: &crate::BrushSettings, p: &crate::StrokePoint) -> bool {
let step = crate::dynamics::StepInput { point: *p, direction: 0.0, initial_direction: 0.0, step: 0 };
crate::dynamics::base_diameter(brush, &step) < 0.5
}
/// One Background Eraser dab's edit of a working copy of `pre` (the target before the stroke):
/// shared by [`apply_background_eraser`] and live previews that run the dabs as they come, so both
/// erase the same pixels. `None` when `pre` has no alpha channel (nothing can be erased).
@@ -306,6 +319,10 @@ mod find_edges_tests;
#[path = "bg_erase_decontamination_tests.rs"]
mod decontamination_tests;
#[cfg(test)]
#[path = "bg_erase_lowest_pressure_tests.rs"]
mod lowest_pressure_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,59 @@
//! #18060: a Background Eraser stroke at the very lightest pen pressure erases nothing. With Size:
//! Pen Pressure and a 41 px hard tip, the reference application leaves the layer untouched at
//! pressure 0.01, while 0.02 and up paint a thin line; the lightest measurement below is 0.05,
//! which keeps the widths the item records.
use photocraft_color::PixelFormat;
use photocraft_geom::Rect;
use photocraft_raster::{Surface, from_rgba};
use crate::bg_erase::{BgEraseSettings, apply_background_eraser};
use crate::replace::{Limits, Sampling};
use crate::{BrushSettings, Stroke, StrokePoint};
const GREEN: [f32; 4] = [0.2, 0.6, 0.2, 1.0];
const Y: f64 = 20.0;
/// A 60 × 40 flat green field: any erased pixel shows.
fn field() -> Surface {
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(Rect::new(0, 0, 60, 40), &from_rgba(&PixelFormat::RGBA8, GREEN));
s
}
/// A constant-pressure horizontal stroke with the measured 41 px hard tip and Size: Pen Pressure.
fn stroke(pressure: f32) -> Stroke {
Stroke {
brush: BrushSettings { size: 41.0, hardness: 1.0, spacing: 0.25, pressure_size: true, ..Default::default() },
points: (5..=35).map(|x| StrokePoint::new(f64::from(x), Y, pressure)).collect(),
}
}
fn settings() -> BgEraseSettings {
BgEraseSettings { sampling: Sampling::BackgroundSwatch, limits: Limits::Contiguous, tolerance: 0.5, background: GREEN, ..Default::default() }
}
/// Done when 1: at pressure 0.01 every pixel's alpha is unchanged.
#[test]
fn the_lightest_pressure_leaves_the_layer_untouched() {
let pre = field();
let mut s = pre.clone();
let d = apply_background_eraser(&mut s, &stroke(0.01), &settings(), None).unwrap();
assert!(d.is_empty(), "nothing was erased: {d:?}");
assert_eq!(s, pre, "pressure 0.01 leaves the layer untouched");
}
/// Done when 2 and 3: 0.05 and above still erase, and a mouse stroke (pressure 1.0) is unchanged.
#[test]
fn pressure_005_and_above_still_erase() {
for (pressure, erased) in [(0.05, false), (0.25, false), (0.5, false), (1.0, true)] {
let mut s = field();
let d = apply_background_eraser(&mut s, &stroke(pressure), &settings(), None).unwrap();
assert!(!d.is_empty(), "pressure {pressure} erases");
let centre = s.rgba(20, Y as i32)[3];
match erased {
true => assert_eq!(centre, 0.0, "the mouse (pressure 1.0) erases fully: {centre}"),
false => assert!(centre < 1.0, "pressure {pressure} paints a thin line: {centre}"),
}
}
}
@@ -0,0 +1,116 @@
//! #18097: with the Background Eraser active the canvas cursor is the not-allowed one over a layer
//! mask and over the composite of a 32-bit document, as the reference application shows, and the
//! tip cursor everywhere the issue left unmeasured.
use craft::behavior::{Cursor, CursorIcon};
use egui::{Modifiers, vec2};
use egui_kittest::Harness;
use serde_json::json;
use crate::PhotocraftApp;
use crate::guide_cursor_tests::hover;
use crate::state::Tool;
const IN_IMAGE: f32 = 100.0;
const ON_LAYER: f32 = 150.0;
const BLOCKED: Option<Cursor> = Some(Cursor::System(CursorIcon::NotAllowed));
/// The canvas at 100 % on a 400 × 300 `depth`-bit document with the Background Eraser active.
fn harness(depth: u32) -> Harness<'static, Box<PhotocraftApp>> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 300, "depth": depth})).unwrap();
app.sync_views();
app.ui.extras.rulers = false;
app.ui.tool = Tool::BackgroundEraser;
let ctx = app.ctx().clone();
let mut h = Harness::builder().with_context(ctx).with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |_cc| app);
h.run_steps(4);
let v = &mut h.state_mut().ui.views[0];
v.zoom = 1.0;
v.center = [200.0, 150.0];
v.clear_pending();
h.run_steps(2);
h
}
/// A pixel layer filled red, so the tool has pixels to erase.
fn pixel_layer(h: &mut Harness<'static, Box<PhotocraftApp>>) {
h.state_mut().run("layer.new.layer", json!({})).unwrap();
h.state_mut().run("edit.fill", json!({"color": "#ff0000"})).unwrap();
}
/// A layer mask revealing everything, on the active layer.
fn layer_mask(h: &mut Harness<'static, Box<PhotocraftApp>>) {
h.state_mut().run("select.all", json!({})).unwrap();
// The selection becomes the mask.
h.state_mut().run("layer.layerMask.revealSelection", json!({})).unwrap();
}
fn cursor(h: &mut Harness<'static, Box<PhotocraftApp>>) -> Option<Cursor> {
hover(h, IN_IMAGE, ON_LAYER, Modifiers::NONE);
h.state().canvas_tools.last_response.as_ref().and_then(|response| response.cursor.clone())
}
/// Done when 1 and 2: a layer mask (enabled or disabled, of a pixel layer or a group) blocks the
/// cursor, the layer's own pixels do not.
#[test]
fn a_layer_mask_blocks_the_background_eraser_cursor() {
let mut h = harness(8);
pixel_layer(&mut h);
let normal = cursor(&mut h);
assert!(normal.is_some() && normal != BLOCKED, "the pixel layer has the tip cursor");
layer_mask(&mut h);
h.state_mut().ui.mask_target = true;
assert_eq!(cursor(&mut h), BLOCKED, "the targeted mask");
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::NotAllowed);
h.state_mut().run("layer.layerMask.enabled", json!({"enabled": false})).unwrap();
assert_eq!(cursor(&mut h), BLOCKED, "a disabled mask is targeted too");
h.state_mut().run("layer.layerMask.enabled", json!({"enabled": true})).unwrap();
h.state_mut().ui.mask_target = false;
assert_eq!(cursor(&mut h), normal, "the layer's own pixels keep the tip cursor");
// A group's mask, targeted from the Layers panel.
h.state_mut().run("layer.new.group", json!({})).unwrap();
layer_mask(&mut h);
h.state_mut().ui.mask_target = true;
assert_eq!(cursor(&mut h), BLOCKED, "a group mask");
}
/// Done when 1 and 2: the composite of a 32-bit document blocks the cursor, an 8- or 16-bit one
/// does not.
#[test]
fn a_thirty_two_bit_composite_blocks_the_background_eraser_cursor() {
for (depth, blocked) in [(8, false), (16, false), (32, true)] {
let mut h = harness(depth);
pixel_layer(&mut h);
let got = cursor(&mut h);
assert_eq!(got == BLOCKED, blocked, "{depth}-bit: {got:?}");
}
}
/// Done when 3: the targets the issue left unmeasured keep today's cursor: the Quick Mask, an
/// adjustment layer's mask, and a vector mask.
#[test]
fn the_unmeasured_targets_keep_the_tip_cursor() {
let mut h = harness(8);
pixel_layer(&mut h);
let normal = cursor(&mut h);
h.state_mut().run("select.editInQuickMaskMode", json!({"on": true})).unwrap();
assert_eq!(cursor(&mut h), normal, "Quick Mask");
h.state_mut().run("select.editInQuickMaskMode", json!({"on": false})).unwrap();
h.state_mut().run("layer.newAdjustmentLayer.curves", json!({})).unwrap();
layer_mask(&mut h);
h.state_mut().ui.mask_target = true;
assert_eq!(cursor(&mut h), normal, "an adjustment layer's mask");
let mut h = harness(8);
pixel_layer(&mut h);
let normal = cursor(&mut h);
h.state_mut().run("layer.vectorMask.add", json!({})).unwrap();
assert_eq!(cursor(&mut h), normal, "a vector mask");
}
@@ -167,6 +167,16 @@ pub(super) fn paint_cursor_blocked(app: &PhotocraftApp) -> bool {
if tool == Tool::ArtHistoryBrush {
return app.session.active().is_some_and(|state| matches!(state.doc.mode, photocraft_color::ColorMode::Indexed | photocraft_color::ColorMode::Bitmap));
}
// The Background Eraser refuses a layer mask and the composite of a 32-bit document, and shows
// the not-allowed cursor over both (#18097). The targets the issue left unmeasured (an alpha
// channel, Quick Mask, an adjustment layer, colour channels) keep the tip cursor.
if tool == Tool::BackgroundEraser {
let Some(state) = app.session.active() else { return false };
let target = super::paint_target(app);
let mask = target.as_str() == Some("mask") && !crate::adjustment_layer_active(state);
let wide = target.as_str() == Some("pixels") && state.doc.depth == photocraft_color::SampleType::F32;
return mask || wide;
}
if !matches!(tool, Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::MixerBrush) {
return false;
}
@@ -264,3 +274,7 @@ mod locked_layer_cursor_tests;
#[cfg(test)]
#[path = "art_history_mode_cursor_tests.rs"]
mod art_history_mode_cursor_tests;
#[cfg(test)]
#[path = "background_eraser_target_cursor_tests.rs"]
mod background_eraser_target_cursor_tests;
+7 -2
View File
@@ -24,11 +24,12 @@ use craft::ui::contract::Entry;
use craft::ui::contract::Tracked;
use craft::ui::dialog::{DialogId, DialogResult};
use craft::ui::list::ThumbAspect;
use craft::ui::patterns::blend_keys::blend_entries;
use craft::ui::patterns::presets::{PresetFns, PresetRow, PresetSource, ThumbInfo};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::primitives::FacePaint;
use craft::ui::primitives::textures::TextureCache;
use craft::ui::runtime::env::Env;
use craft::ui::runtime::env::{Env, Label};
use craft::ui::runtime::memory::{SaveKey, run_value, set_run_value};
use egui::{ColorImage, Pos2, Rect, pos2};
use photocraft_doc::effects::{FxPaint, GlowSource, GlowTechnique, StrokePosition};
@@ -47,6 +48,8 @@ pub(crate) mod color_picker;
mod contour;
#[cfg(test)]
mod drop_shadow_last_values_tests;
#[cfg(test)]
mod effect_blend_separators_tests;
mod gradient_field;
#[cfg(test)]
mod gradient_method_tests;
@@ -649,7 +652,9 @@ fn specs(keys: &HashMap<String, String>, user: &Map<String, Value>, light: f32)
/// it has one (an imported .pdn).
fn blend_modes(layer: &Layer) -> Vec<Entry<String>> {
let own = photocraft_color::BlendMode::PAINT_NET_MODES.into_iter().find(|m| m.label() == layer.blend.label());
photocraft_color::BlendMode::LAYER_MODES.into_iter().chain(own).map(|m| Entry::new(m.label().to_string(), m.label().to_string())).collect()
let modes: Vec<_> =
photocraft_color::BlendMode::LAYER_MODES.into_iter().chain(own).map(|mode| crate::panels::blend_entry(mode.label().to_string(), mode)).collect();
blend_entries(&modes, |mode| Label::from(tl!(mode.key.as_str()).to_string()))
}
/// English blend-mode name to the app's key: PhotoCraft keys modes by their label.
@@ -0,0 +1,20 @@
//! The shared Layer Style selector receives grouped entries and stable blend-mode keys.
use super::{blend_modes, tests::app_with_layer};
use photocraft_color::BlendMode;
#[test]
fn separates_the_five_blend_groups_and_keeps_the_layers_paint_net_mode() {
let mut app = app_with_layer(32);
let state = app.session.active_mut().unwrap();
let id = state.active_layer.unwrap();
let mut layer = state.doc.layer(id).unwrap().clone();
let own = BlendMode::PAINT_NET_MODES[0];
layer.blend = own;
let entries = blend_modes(&layer);
let groups: Vec<_> = entries.windows(2).filter(|pair| pair[0].is_separator()).filter_map(|pair| pair[1].value().map(String::as_str)).collect();
assert_eq!(groups, ["Darken", "Lighten", "Overlay", "Difference", "Hue"]);
assert_eq!(entries.iter().filter(|entry| entry.is_separator()).count(), groups.len());
let keys: Vec<_> = entries.iter().filter_map(|entry| entry.value().map(String::as_str)).collect();
let expected: Vec<_> = BlendMode::LAYER_MODES.into_iter().chain([own]).map(BlendMode::label).collect();
assert_eq!(keys, expected);
}
@@ -0,0 +1,93 @@
//! #16802: with a document open, the Home screen has a way back to it: the rail's Home row, and the document's entry
//! at the bottom of the Window menu. With no document open, Home has nothing behind it and both leave it up.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use crate::PhotocraftApp;
use crate::app::framework::BuildApp as _;
type H = Harness<'static, Box<PhotocraftApp>>;
/// The app showing its document area (the Home screen while Home is up), with `documents` documents open. The app's
/// own frame runs around it, so a command the Home screen fires is run as in the app.
fn harness(documents: usize) -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
for _ in 0..documents {
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
}
let mut h = Harness::builder()
.with_size(egui::vec2(1100.0, 700.0))
.with_max_steps(64)
.build_app(|ui, app: &mut PhotocraftApp| crate::canvas::document_area(app, ui), app);
h.run_steps(4);
h
}
/// Whether the Home screen is up.
fn home(h: &mut H) -> bool {
h.state_mut().home_screen_up()
}
/// The options bar's Home button: shows Home over the open documents.
fn show_home(h: &mut H) {
crate::canvas::start_screen::toggle_home(h.state_mut());
h.run_steps(4);
}
/// A click on the Home row of the Home screen's rail.
fn click_home_row(h: &mut H) {
h.get_by_label("Home").click();
h.run_steps(4);
}
#[test]
fn the_rails_home_row_returns_to_the_open_document() {
let mut h = harness(1);
show_home(&mut h);
assert!(home(&mut h), "Home is up over the document");
let (doc, open) = (h.state().session.active().map(|d| d.doc.id), h.state().session.documents().len());
click_home_row(&mut h);
assert!(!home(&mut h), "the Home row leaves Home: {}", h.state().ui.status);
assert_eq!(h.state().session.active().map(|d| d.doc.id), doc, "back on the same document");
assert_eq!(h.state().session.documents().len(), open, "nothing opened or closed");
}
/// Chooses Window menu item `id`, through the gate a menu click passes (its enabled state included).
fn choose(h: &mut H, id: &str) {
let ctx = h.ctx.clone();
crate::shortcut_dispatch::dispatch(h.state_mut(), &ctx, id);
h.run_steps(4);
}
#[test]
fn choosing_an_open_document_in_the_window_menu_leaves_home() {
let mut h = harness(2);
let first = h.state().session.documents()[0].doc.id;
show_home(&mut h);
assert!(home(&mut h));
choose(&mut h, "window.document.0");
assert!(!home(&mut h), "choosing the document leaves Home: {}", h.state().ui.status);
assert_eq!(h.state().session.active().map(|d| d.doc.id), Some(first), "and shows that document");
}
#[test]
fn next_and_previous_document_leave_home() {
for id in ["window.nextDocument", "window.previousDocument"] {
let mut h = harness(2);
let before = h.state().session.active().map(|d| d.doc.id);
show_home(&mut h);
choose(&mut h, id);
assert!(!home(&mut h), "{id} leaves Home: {}", h.state().ui.status);
assert_ne!(h.state().session.active().map(|d| d.doc.id), before, "{id} shows the other document");
}
}
#[test]
fn with_no_document_open_home_stays_up() {
let mut h = harness(0);
assert!(home(&mut h), "Home is all there is with no document");
click_home_row(&mut h);
assert!(home(&mut h), "the Home row has nothing to return to");
}
+2
View File
@@ -1140,6 +1140,8 @@ mod vertical_type_icon_tests;
#[cfg(test)]
mod view_guides_submenu_tests;
#[cfg(test)]
mod home_screen_way_back_tests;
#[cfg(test)]
mod lasso_click_tests;
#[cfg(test)]
+6
View File
@@ -468,6 +468,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Type", "Anti-Alias"], "---", None, "---"),
(&["Type", "Anti-Alias"], "Windows LCD", None, "type.antiAlias.windowsLcd"),
(&["Type", "Anti-Alias"], "Windows", None, "type.antiAlias.windows"),
(&["Type"], "---", None, "---"),
(&["Type", "Orientation"], "Horizontal", None, "type.orientation.horizontal"),
(&["Type", "Orientation"], "Vertical", None, "type.orientation.vertical"),
(&["Type", "OpenType"], "Standard Ligatures", None, "type.openType.standardLigatures"),
@@ -524,6 +525,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Type", "Font Preview Size"], "Large", None, "type.fontPreviewSize.large"),
(&["Type", "Font Preview Size"], "Extra Large", None, "type.fontPreviewSize.extraLarge"),
(&["Type", "Font Preview Size"], "Huge", None, "type.fontPreviewSize.huge"),
(&["Type"], "---", None, "---"),
(&["Type", "Language Options"], "Default Features", None, "type.languageOptions.defaultFeatures"),
(&["Type", "Language Options"], "East Asian Features", None, "type.languageOptions.eastAsianFeatures"),
(&["Type", "Language Options"], "Middle Eastern Features", None, "type.languageOptions.middleEasternFeatures"),
@@ -828,3 +830,7 @@ pub const ARRANGE_ICONS: &[(&str, &str)] = &[
("window.arrange.sixUp", "arrange-six-up"),
("window.arrange.consolidateAllToTabs", "arrange-consolidate-all-to-tabs"),
];
#[cfg(test)]
#[path = "menus/type_menu_groups_tests.rs"]
mod type_menu_groups_tests;
+5
View File
@@ -657,6 +657,7 @@ fn invoke_export_command(app: &mut PhotocraftApp, id: &str, params: &Value) -> R
fn invoke_type_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
match id {
"type.pasteLoremIpsum" if app.ui.text_edit.is_none() && params.as_object().is_none_or(|object| object.is_empty()) => Some(Ok(Value::Null)),
"type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore"
if params.as_object().is_none_or(|object| object.is_empty()) =>
{
@@ -860,6 +861,8 @@ fn invoke_window_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str,
app.run("document.activate", json!({"document": next}))?;
}
app.jobs.focus = None;
// Next and Previous Document show the document they choose, so they leave Home too (#16802).
app.ui.chrome.home = None;
Ok(json!({"document": next}))
})()),
_ if id.starts_with(DOCUMENT_ITEM) => Some((|| {
@@ -868,6 +871,8 @@ fn invoke_window_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str,
id.strip_prefix(DOCUMENT_ITEM).ok_or("no such document")?.parse::<usize>().ok().filter(|index| *index < count).ok_or("no such document")?;
app.session.set_active(next);
app.jobs.focus = None;
// Choosing a document shows it, so it leaves the Home screen opened over the documents (#16802).
app.ui.chrome.home = None;
Ok(json!({"document": next}))
})()),
_ => None,
+11
View File
@@ -5,6 +5,10 @@ use photocraft_engine::color_cmds::ColorExt;
use super::invoke::{panel_alias, proof_preset, workspace_id};
use super::{DOCUMENT_ITEM, PhotocraftApp, Value};
#[cfg(test)]
#[path = "type_paste_lorem_greyed_tests.rs"]
mod type_paste_lorem_greyed_tests;
/// Whether View › Zoom Out has stopped at a document-specific minimum.
pub(crate) fn zoom_out_at_minimum(app: &PhotocraftApp) -> bool {
let Some(document) = app.session.active() else { return false };
@@ -61,6 +65,10 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
if crate::analysis::handles(id) {
return true;
}
// The view command wrapper otherwise uses the engine's document-level availability.
if id == "type.pasteLoremIpsum" {
return app.ui.text_edit.is_some() && app.session.is_enabled(id);
}
if let Some(e) = crate::view_cmds::is_enabled(app, id) {
return e;
}
@@ -100,6 +108,9 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
"window.togglePanels" => true,
// With one document open the key stays quiet, as in Photoshop, rather than reporting why.
"window.nextDocument" | "window.previousDocument" => app.session.active().is_some(),
// Home over the open documents, or back to them (the Home rail's Home row fires it, #16802). With no document
// open there is nothing behind Home.
"window.home" => !app.session.documents().is_empty(),
i if panel_alias(i).is_some() || workspace_id(i).is_some() => true,
i if proof_preset(i).is_some() => app.session.active().is_some(),
// "Custom…" is the full Proof Setup dialog.
@@ -0,0 +1,23 @@
use crate::PhotocraftApp;
use craft::menu::{Node, from_items};
#[test]
fn type_submenus_keep_their_reference_groups() {
let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let bar = from_items(&["Type"], &crate::menus::menu_rows(&app));
let entries: Vec<_> = bar.menus[0]
.children
.iter()
.map(|node| match node {
Node::Separator => "---",
Node::Submenu { label, .. } | Node::Heading(label) => label.as_str(),
Node::Item(row) => row.command.id.as_str(),
_ => "<unknown menu node>",
})
.collect();
assert!(entries.windows(6).any(|rows| rows == ["---", "Anti-Alias", "---", "Orientation", "OpenType", "---"]), "{entries:?}");
assert!(entries.windows(6).any(|rows| rows == ["---", "Font Preview Size", "---", "Language Options", "---", "type.updateAllTextLayers"]), "{entries:?}");
let warp = entries.iter().position(|entry| *entry == "type.warpText").unwrap();
let preview = entries.iter().position(|entry| *entry == "Font Preview Size").unwrap();
assert!(warp < preview, "{entries:?}");
}
@@ -0,0 +1,71 @@
use serde_json::{Value, json};
use crate::PhotocraftApp;
const PASTE: &str = "type.pasteLoremIpsum";
fn enabled(app: &PhotocraftApp) -> bool {
let rows = crate::menus::menu_rows(app);
let row = crate::menus::row(&rows, PASTE).expect("Paste Lorem Ipsum is in the menu");
assert_eq!(row.path, ["Type"]);
row.enabled
}
fn assert_no_menu_paste(app: &mut PhotocraftApp, ctx: &egui::Context) {
let state = |app: &PhotocraftApp| app.session.active().map(|d| (d.revision, d.history.past_len()));
let before = state(app);
assert_eq!(crate::menus::invoke(app, ctx, PASTE, json!({})).unwrap(), Value::Null);
assert_eq!(state(app), before, "the disabled menu action leaves the document and history alone");
}
#[test]
fn paste_lorem_menu_requires_an_active_text_edit() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = app.ctx().clone();
assert!(!enabled(&app), "no document");
assert_no_menu_paste(&mut app, &ctx);
app.run("file.new", json!({"width": 120, "height": 80, "background": "white"})).unwrap();
app.sync_views();
app.run("layer.new.layer", json!({"name": "Paint"})).unwrap();
assert!(!enabled(&app), "pixel layer selected");
assert_no_menu_paste(&mut app, &ctx);
app.run("select.deselectLayers", json!({})).unwrap();
assert!(!enabled(&app), "no layer selected");
assert_no_menu_paste(&mut app, &ctx);
for params in [json!({"x": 4, "y": 24, "text": "Sample"}), json!({"box": [4, 8, 112, 64], "text": "Sample"})] {
let layer = app.run("type.create", params).unwrap()["layer"].as_u64().unwrap();
assert!(!enabled(&app), "selecting a type layer does not start editing");
assert_no_menu_paste(&mut app, &ctx);
assert_eq!(app.run("type.info", json!({"layer": layer})).unwrap()["text"], "Sample");
crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap();
let edit = app.ui.text_edit.as_mut().unwrap();
edit.anchor = edit.caret;
assert!(enabled(&app), "enabled while editing");
let result = crate::menus::invoke(&mut app, &ctx, PASTE, json!({})).unwrap();
let info = app.run("type.info", json!({"layer": layer})).unwrap();
let text = info["text"].as_str().unwrap();
assert!(text.starts_with("Sample") && text.len() > "Sample".len());
assert_eq!(result["caret"].as_u64().unwrap(), text.chars().count() as u64);
crate::type_tool::commit(&mut app);
assert!(!enabled(&app), "disabled after committing the edit");
}
}
#[test]
fn paste_lorem_engine_command_still_works_outside_the_editor() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = app.ctx().clone();
app.run("file.new", json!({"width": 120, "height": 80, "background": "white"})).unwrap();
let created = app.run(PASTE, json!({"new": true})).unwrap()["layer"].as_u64().unwrap();
let info = app.run("type.info", json!({"layer": created})).unwrap();
let original = info["text"].as_str().unwrap();
let inserted = crate::menus::invoke(&mut app, &ctx, PASTE, json!({"layer": created, "at": 0})).unwrap();
let updated = app.run("type.info", json!({"layer": created})).unwrap();
assert_eq!(inserted["caret"].as_u64().unwrap(), original.chars().count() as u64);
assert_eq!(updated["text"].as_str().unwrap(), original.repeat(2));
app.run(PASTE, json!({})).unwrap();
assert_eq!(app.run("type.info", json!({"layer": created})).unwrap()["text"].as_str().unwrap(), original.repeat(3));
assert!(!enabled(&app));
}
@@ -1055,9 +1055,10 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para
return Some(r);
}
if id == "type.pasteLoremIpsum" && no_params(params) {
// While typing, paste at the caret.
// While typing, replace the selected characters, or insert at the caret.
if let Some(te) = app.ui.text_edit.clone() {
let r = app.run(id, json!({"layer": te.layer, "at": te.caret, "coalesce": te.session}));
let [start, end] = crate::type_tool::selected_range(app).unwrap_or([te.caret; 2]);
let r = app.run(id, json!({"layer": te.layer, "at": start, "end": end, "coalesce": te.session}));
if let (Ok(v), Some(te)) = (&r, app.ui.text_edit.as_mut())
&& let Some(c) = v.get("caret").and_then(Value::as_u64)
{
@@ -0,0 +1,59 @@
use egui::{Event, Modifiers, PointerButton};
use photocraft_doc::LayerId;
use photocraft_geom::Rect;
use serde_json::json;
use crate::PhotocraftApp;
use crate::guide_cursor_tests::{harness, hover, screen};
use crate::state::Tool;
fn paint(app: &mut PhotocraftApp, bounds: Rect) -> LayerId {
let layer = LayerId(app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap());
app.session
.edit("Paint fixture", |doc, _| {
doc.layer_mut(layer).unwrap().surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
layer
}
#[test]
fn hover_with_transform_controls_and_auto_select_off_does_not_select_on_click() {
let mut h = harness(Tool::Move);
let app = h.state_mut();
let bounds = Rect::new(90, 110, 130, 145);
let painted = paint(app, bounds);
paint(app, Rect::new(290, 90, 335, 140));
app.ui.tool_options.move_auto_select = false;
app.ui.tool_options.move_show_transform = true;
h.run_steps(2);
hover(&mut h, 110.0, 125.0, Modifiers::NONE);
assert_eq!(h.state().canvas_hover_layer, Some(painted));
assert_eq!(super::target(h.state_mut(), Some([110.0, 125.0]), false, false), Some(bounds));
let st = h.state().session.active().unwrap();
let (before, active, history) = (st.doc.clone(), st.active_layer, st.history.past_len());
assert_ne!(active, Some(painted));
let pos = screen(&h, 110.0, 125.0);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
let st = h.state().session.active().unwrap();
assert_eq!(st.doc, before);
assert_eq!(st.active_layer, active);
assert_eq!(st.history.past_len(), history);
h.state_mut().ui.tool_options.move_show_transform = false;
hover(&mut h, 110.0, 125.0, Modifiers::NONE);
assert_eq!(h.state().canvas_hover_layer, None);
hover(&mut h, 110.0, 125.0, Modifiers::COMMAND);
assert_eq!(h.state().canvas_hover_layer, Some(painted));
h.state_mut().ui.tool_options.move_auto_select = true;
hover(&mut h, 110.0, 125.0, Modifiers::NONE);
assert_eq!(h.state().canvas_hover_layer, Some(painted));
hover(&mut h, 110.0, 125.0, Modifiers::COMMAND);
assert_eq!(h.state().canvas_hover_layer, None);
}
+14 -9
View File
@@ -1,6 +1,6 @@
//! Move tool › Show Highlight on Rollover (Preferences › Tools, on by default): with Auto-Select
//! on, or ⌘ held while it is off, hovering the canvas outlines the layer (or group, per the
//! Auto-Select target) that a click there would pick. The hit test is the click's own
//! Move tool › Show Highlight on Rollover (Preferences › Tools, on by default): hovering the canvas
//! outlines the layer or group the Auto-Select hit test finds. Show Transform Controls also allows
//! the outline while Auto-Select is off and no modifier is held. The hit test is the click's own
//! (`pick_cmds::move_auto_select_target`), so a type layer is outlined anywhere inside its text, as it
//! is picked there (#2591). The answer is cached per document revision and pointer pixel: a
//! pointer resting on the canvas costs nothing per frame.
@@ -14,7 +14,7 @@ use photocraft_geom::Rect;
use crate::PhotocraftApp;
use crate::state::Tool;
/// The last answer: what a click at `at` on that revision of the document would outline.
/// The cached rollover target at `at` on this document revision.
pub(crate) struct Hover {
doc: DocId,
revision: u64,
@@ -25,16 +25,17 @@ pub(crate) struct Hover {
}
/// The document-space bounds to outline with the pointer at `at` (document px), or `None` when
/// nothing is highlighted: the preference is off, another tool is current, a click wouldn't
/// Auto-Select (it's off without ⌘, or the selected pixels move instead), a button is down (which
/// covers every drag), or a transform is under way.
/// nothing is highlighted: the preference is off, another tool is current, the hover mode is
/// inactive, the selected pixels move instead, a button is down, or a transform is under way.
pub(crate) fn target(app: &mut PhotocraftApp, at: Option<[f64; 2]>, command: bool, pressed: bool) -> Option<Rect> {
let options = &app.ui.tool_options;
let hover_enabled = if options.move_auto_select { !command } else { command || options.move_show_transform };
if !app.session.prefs().tools.show_highlight_on_rollover
|| app.ui.tool != Tool::Move
|| !app.ui.tool_options.move_show_hover_bounds
|| !options.move_show_hover_bounds
|| pressed
|| app.ui.transform.is_some()
|| app.ui.tool_options.move_auto_select == command
|| !hover_enabled
|| crate::move_ui::moves_selected_pixels_with(app, Tool::Move)
{
app.canvas_hover_layer = None;
@@ -122,6 +123,10 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rec
HoverOutline::new(tl!("Layer rollover"), shape).show_at(ui, canvas);
}
#[cfg(test)]
#[path = "../move_hover_auto_select_off_tests.rs"]
mod move_hover_auto_select_off_tests;
#[cfg(test)]
mod tests {
use serde_json::json;