PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Smart Objects: Copy/Paste with no selection keeps the smart object (#2428) (#2653)
Valentin Klein93599a1837a9
diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rsindex cd226cb1c..faee9aa47 100644--- a/crates/engine/src/channel_clip.rs+++ b/crates/engine/src/channel_clip.rs@@ -73,7 +73,7 @@ pub(crate) fn copy(s: &mut Session) -> Result<Option<Value>> {if bounds.is_empty() {return Err(EngineError::Other("Could not copy: the selected area is empty".into()));}- s.clipboard = Some(Clip { surface, bounds });+ s.clipboard = Some(Clip { surface, bounds, layers: None });Ok(Some(json!({"bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()], "channel": k})))}diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rsindex 84db0b15e..a638ea63a 100644--- a/crates/engine/src/edit_cmds.rs+++ b/crates/engine/src/edit_cmds.rs@@ -24,6 +24,26 @@ pub(crate) use paste_target;pub struct Clip {pub surface: Surface,pub bounds: Rect,+ /// The copied layer itself, when Copy took a whole layer that Paste should recreate rather+ /// than rasterize (see [`whole_layer`]): a scratch document in the source's colour holding it.+ /// `surface` still holds its pixels, for Paste Into, masks, channels and other apps.+ pub layers: Option<Box<Document>>,+}++/// Photoshop's layer-based copy (CC 2018 on): with no selection, Copy takes the active layer+/// whole. Here that applies to smart objects, so Paste makes a smart object again instead of its+/// pixels (#2428); other layers paste as pixels.+fn whole_layer(doc: &Document, id: LayerId) -> Option<Box<Document>> {+ let l = doc.layer(id)?;+ if doc.selection.is_some() || !matches!(l.content, LayerContent::Smart(_)) || !crate::layer_copy_cmds::layered(doc.mode) {+ return None;+ }+ let mut copies = Document::new("", doc.size, doc.mode, doc.depth);+ copies.icc_profile = doc.icc_profile.clone();+ copies.resolution_dpi = doc.resolution_dpi;+ copies.patterns = doc.patterns.clone();+ copies.layers.push(l.clone());+ Some(Box::new(copies))}fn has_doc(s: &Session) -> std::result::Result<(), String> {@@ -79,7 +99,7 @@ fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Result<Clip> {};let mut out = Surface::new(with_alpha);if area.is_empty() {- return Ok(Clip { surface: out, bounds: Rect::EMPTY });+ return Ok(Clip { surface: out, bounds: Rect::EMPTY, layers: None });}// Only the selected area is read: converting the whole layer (a 24 MP Background gaining// alpha) cost about a second per Layer via Copy (#668).@@ -117,7 +137,7 @@ fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Result<Clip> {out.try_write_region(area, &px).map_err(|e| EngineError::Other(format!("not enough memory while copying pixels ({e}); the document was not changed")))?;out.prune();let bounds = out.content_bounds();- Ok(Clip { surface: out, bounds })+ Ok(Clip { surface: out, bounds, layers: None })}/// Merged composite of the visible document as a surface in the document's format.@@ -134,7 +154,7 @@ fn copy(s: &mut Session, merged: bool) -> Result<Value> {} else {let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?;let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?;- lift(surf, d.doc.selection.as_ref(), canvas)?+ Clip { layers: whole_layer(&d.doc, id), ..lift(surf, d.doc.selection.as_ref(), canvas)? }};if clip.bounds.is_empty() {return Err(EngineError::Other("Could not copy: the selected area is empty".into()));@@ -184,6 +204,9 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result<Value> {let canvas = d.doc.bounds();let fmt = d.doc.pixel_format();let (dx, dy) = paste_offset(&clip, canvas, p, in_place);+ if let Some(layers) = clip.layers.as_deref().filter(|_| crate::layer_copy_cmds::layered(d.doc.mode)) {+ return paste_layers(s, layers, dx, dy);+ }let moved = shifted(&clip.surface, dx, dy);let target = PixelFormat::new(fmt.mode, fmt.sample, true);let surf = if moved.format() == target { moved } else { moved.convert(target) };@@ -198,6 +221,29 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result<Value> {Ok(json!({"layer": id.0, "offset": [dx, dy]}))}+/// Paste of a whole copied layer ([`whole_layer`]): fresh copies, converted to the document's+/// colour, moved as the pixels would be, above the active layer. A pasted smart object gets its+/// own contents, independent of the copied one (as across documents).+fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let mut copies = layers.clone();+ for l in &mut copies.layers {+ *l = l.duplicate();+ }+ crate::layer_copy_cmds::adapt_copies(s, &mut copies, &d.doc)?;+ crate::layer_copy_cmds::translate_copies(&mut copies, dx, dy);+ let patterns: Vec<_> = copies.patterns.iter().filter(|pat| !d.doc.patterns.iter().any(|q| q.id == pat.id)).cloned().collect();+ let id = s.edit("Paste", |doc, active| {+ doc.patterns.extend(patterns);+ for l in copies.layers {+ *active = Some(doc.insert_above(*active, l));+ }+ doc.selection = None;+ active.ok_or(EngineError::Other("nothing to paste".into()))+ })?;+ Ok(json!({"layer": id.0, "offset": [dx, dy]}))+}+/// How far a paste moves the clipboard pixels: not at all in place (or when they lie on the/// canvas and no `center` is given), else onto `center` (the view centre from the UI) or the/// canvas centre.@@ -1099,25 +1145,33 @@ mod tests {st.doc.layer(st.active_layer.unwrap()).unwrap().content.clone()}- /// #541: a smart object copies what it shows, with or without a selection, and pastes as+ /// #541, #2428: with no selection, Copy takes a smart object whole and Paste makes a smart+ /// object again, with contents of its own; with a selection, the selected pixels paste as/// pixels. Cut edits pixels, so it's refused; Layer via Copy and Duplicate Layer copy the layer.#[test]fn copy_a_smart_object_layer() {let mut s = session();s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let LayerContent::Smart(original) = active_content(&s) else { panic!("smart object") };assert!(s.is_enabled("edit.copy"));assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 40, 20]), "no selection: the whole layer");s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap();- assert!(matches!(active_content(&s), LayerContent::Raster(_)));+ let LayerContent::Smart(pasted) = active_content(&s) else { panic!("the paste is a smart object (#2428)") };+ assert_eq!(pasted.source, original.source, "the same contents");+ assert_ne!(pasted.contents_id, original.contents_id, "but not linked to the copied one");assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30));- assert_eq!(- s.active().unwrap().doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().pixel(20, 20),- vec![1.0, 0.0, 0.0, 1.0]- );+ s.execute("edit.paste", json!({"center": [70, 70]})).unwrap();+ assert!(matches!(active_content(&s), LayerContent::Smart(_)));+ assert_eq!(active_bounds(&s), Rect::new(50, 60, 90, 80), "placed as pasted pixels are");+ s.undo();s.undo();assert!(matches!(active_content(&s), LayerContent::Smart(_)));s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 10, 10]), "only the selected part");+ s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap();+ assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels");+ assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 20));+ s.undo();let cut = s.execute("edit.cut", json!({})).unwrap_err().to_string();assert!(cut.contains("not directly editable"), "{cut}");assert!(matches!(active_content(&s), LayerContent::Smart(_)));@@ -1129,6 +1183,20 @@ mod tests {assert_eq!(s.active().unwrap().doc.layers.len(), 4);}+ /// #2428: a smart object copied in one document pastes into another as a smart object, in+ /// that document's bit depth.+ #[test]+ fn paste_a_smart_object_into_another_document() {+ let mut s = session();+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ s.execute("edit.copy", json!({})).unwrap();+ s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap();+ s.execute("edit.paste", json!({})).unwrap();+ let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") };+ assert_eq!(sm.cache.map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits");+ assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30), "on the canvas: in place");+ }+/// Type and shape layers copy their rendered pixels too; groups and adjustments have none.#[test]fn copy_reads_any_layer_that_shows_pixels() {diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/layer_copy_cmds.rsindex 59f18ad76..fd87cb838 100644--- a/crates/engine/src/layer_copy_cmds.rs+++ b/crates/engine/src/layer_copy_cmds.rs@@ -51,7 +51,7 @@ fn point(p: &Value, key: &str) -> Result<Option<[f64; 2]>> {}/// Modes whose layers convert through the colour engine.-fn layered(mode: ColorMode) -> bool {+pub(crate) fn layered(mode: ColorMode) -> bool {matches!(mode, ColorMode::Rgb | ColorMode::Grayscale | ColorMode::Cmyk | ColorMode::Lab)}@@ -59,6 +59,45 @@ fn center(r: Rect) -> [f64; 2] {[(f64::from(r.x0) + f64::from(r.x1)) / 2.0, (f64::from(r.y0) + f64::from(r.y1)) / 2.0]}+/// Readies `copies` (a scratch document of the source's colour holding duplicated layers) for+/// landing in `dest`: smart objects get fresh contents ids, keeping only the sharing within the+/// batch (contents ids belong to a document, so the copies never join objects already in `dest`,+/// including another opening of the same file), and the pixels convert to `dest`'s profile and+/// bit depth.+pub(crate) fn adapt_copies(s: &Session, copies: &mut Document, dest: &Document) -> Result<()> {+ let mut contents = HashMap::new();+ let smart_ids: Vec<_> = copies.walk().into_iter().filter_map(|(_, _, l)| matches!(l.content, LayerContent::Smart(_)).then_some(l.id)).collect();+ for id in smart_ids {+ if let Some(l) = copies.layer_mut(id)+ && let LayerContent::Smart(sm) = &mut l.content+ {+ sm.contents_id = *contents.entry(sm.contents_id).or_insert_with(SmartContentsId::fresh);+ }+ }+ if (copies.mode, &copies.icc_profile) != (dest.mode, &dest.icc_profile) {+ let profile = crate::color_cmds::document_profile(dest);+ crate::color_cmds::convert_document(copies, &profile, s.color.settings.intent(), s.color.settings.bpc)?;+ }+ if copies.depth != dest.depth {+ crate::image_cmds::for_each_surface(&mut copies.layers, true, &mut |surf, _| {+ let f = surf.format().with_sample(dest.depth);+ *surf = surf.convert(f);+ });+ }+ Ok(())+}++/// Moves every layer of `copies` by whole pixels (content, masks, vectors and smart placement).+pub(crate) fn translate_copies(copies: &mut Document, dx: i32, dy: i32) {+ if dx != 0 || dy != 0 {+ let snapshot = copies.clone();+ for l in &mut copies.layers {+ crate::commands::translate_layer(&snapshot, l, dx, dy);+ crate::vector_cmds::translate_vectors(&snapshot, l, f64::from(dx), f64::from(dy));+ }+ }+}+/// `layer.copyToDocument`.fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {let dest = doc_index(s, p, "document")?.ok_or_else(|| bad("missing `document` (the destination's index)"))?;@@ -107,27 +146,7 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {}copies.layers.push(l);}- // Contents IDs belong to a document. Preserve sharing within this batch, without joining- // pre-existing objects in the destination (including another opening of the same file).- let mut contents = HashMap::new();- let smart_ids: Vec<_> = copies.walk().into_iter().filter_map(|(_, _, l)| matches!(l.content, LayerContent::Smart(_)).then_some(l.id)).collect();- for id in smart_ids {- if let Some(l) = copies.layer_mut(id)- && let LayerContent::Smart(sm) = &mut l.content- {- sm.contents_id = *contents.entry(sm.contents_id).or_insert_with(SmartContentsId::fresh);- }- }- if (copies.mode, &copies.icc_profile) != (ddoc.mode, &ddoc.icc_profile) {- let profile = crate::color_cmds::document_profile(&ddoc);- crate::color_cmds::convert_document(&mut copies, &profile, s.color.settings.intent(), s.color.settings.bpc)?;- }- if copies.depth != ddoc.depth {- crate::image_cmds::for_each_surface(&mut copies.layers, true, &mut |surf, _| {- let f = surf.format().with_sample(ddoc.depth);- *surf = surf.convert(f);- });- }+ adapt_copies(s, &mut copies, &ddoc)?;// Placement: centred on the destination's canvas, centred on a point, or offset from where// the layers are in the source (default: the same canvas position).let bounds = copies.layers.iter().filter_map(crate::layer_multi_cmds::layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b));@@ -142,13 +161,7 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {point(p, "offset")?.map_or((0.0, 0.0), |o| (o[0], o[1]))};let (dx, dy) = (dx.round() as i32, dy.round() as i32);- if dx != 0 || dy != 0 {- let snapshot = copies.clone();- for l in &mut copies.layers {- crate::commands::translate_layer(&snapshot, l, dx, dy);- crate::vector_cmds::translate_vectors(&snapshot, l, f64::from(dx), f64::from(dy));- }- }+ translate_copies(&mut copies, dx, dy);let patterns: Vec<_> = sdoc.patterns.iter().filter(|pat| !ddoc.patterns.iter().any(|d| d.id == pat.id)).cloned().collect();s.set_active(dest);let label = if ids.len() == 1 { "Duplicate Layer" } else { "Duplicate Layers" };diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex f8fe21baa..012b4ac83 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1973,7 +1973,7 @@ impl PhotocraftApp {let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes);surface.prune();- self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r });+ self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r, layers: None });self.os_clip_sig = Some(sig);self.clip_external = true;true