PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Free Transform: refuse a locked layer up front (#2585) (#2609)
Valentin Kleinf521e231c389
diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rsindex 1199c6032..d11cf3cc1 100644--- a/crates/engine/src/transform_cmds.rs+++ b/crates/engine/src/transform_cmds.rs@@ -181,16 +181,46 @@ pub(crate) fn group_locks(doc: &Document, id: LayerId) -> Locks {doc.path_of(id).and_then(|p| Some(doc.locks_at(p.split_last()?.1))).unwrap_or_default()}+/// The locks a transform of `l` meets: its own and `group`'s (those it inherits). The Background's+/// position lock doesn't count: Photoshop turns it into a normal layer first ([`transform_layer`]).+fn transform_locks(l: &Layer, group: Locks) -> Locks {+ let mut own = l.locks;+ if own.position && l.name == "Background" {+ own.position = false;+ own.transparency = false;+ }+ own.union(group)+}++/// Would a transform of the layer `id` be refused because it, a group around it, or (for a group)+/// a layer inside it is locked in place? The same rule [`transform_layer`] applies at commit, so+/// Free Transform can refuse before its box opens, as Photoshop does.+pub fn locked_for_transform(doc: &Document, id: LayerId) -> bool {+ let Some(l) = doc.layer(id) else { return false };+ // An explicit stack rather than recursion: documents can nest deeply.+ let mut stack = vec![(l, group_locks(doc, id))];+ while let Some((l, group)) = stack.pop() {+ let locks = transform_locks(l, group);+ if locks.position || locks.all {+ return true;+ }+ if let LayerContent::Group(g) = &l.content {+ stack.extend(g.children.iter().map(|c| (c, locks)));+ }+ }+ false+}+/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]).pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option<Affine>, interp: Interp) -> Result<()> {crate::allocation::checkpoint("transforming pixels")?;+ let locks = transform_locks(l, group);// Photoshop turns the Background into a normal layer before transforming it.if l.locks.position && l.name == "Background" {l.locks.position = false;l.locks.transparency = false;l.name = "Layer 0".into();}- let locks = l.locks.union(group);if locks.position || locks.all {return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));}@@ -505,6 +535,34 @@ mod tests {assert_eq!(l.surface().unwrap().pixel(30, 30)[3], 0.0, "revealed area is transparent");}+ /// `locked_for_transform` (what Free Transform asks before its box opens, #2585) agrees with+ /// what `edit.transform` refuses at commit: a position lock, its own or a group's; never the+ /// Background's (it becomes Layer 0).+ #[test]+ fn locked_for_transform_matches_the_commit() {+ let quad = json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]});+ let lock = |s: &mut Session, id: LayerId, on: bool| {+ s.edit("lock", |doc, _| {+ doc.layer_mut(id).unwrap().locks.position = on;+ Ok(())+ })+ .unwrap();+ };+ let mut s = session();+ let layer = s.active().unwrap().active_layer.unwrap();+ lock(&mut s, layer, true);+ assert!(locked_for_transform(&s.active().unwrap().doc, layer));+ assert!(s.execute("edit.transform", quad.clone()).is_err());+ lock(&mut s, layer, false);+ let group = LayerId(s.execute("layer.groupLayers", json!({"layer": layer.0})).unwrap()["layer"].as_u64().unwrap());+ lock(&mut s, group, true);+ s.execute("layer.select", json!({"layer": layer.0})).unwrap();+ assert!(locked_for_transform(&s.active().unwrap().doc, layer), "the group's lock reaches the layer");+ assert!(s.execute("edit.transform", quad.clone()).is_err());+ let bg = s.active().unwrap().doc.layers[0].id;+ assert!(!locked_for_transform(&s.active().unwrap().doc, bg), "the Background transforms");+ }+#[test]fn with_selection_only_selected_pixels_move() {let mut s = session();diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 2a2a068bb..a18d84717 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -5762,6 +5762,46 @@ mod transform_controls_tests {assert_eq!(t.rect, [20.0, 30.0, 100.0, 70.0]);}+ /// #2585: Free Transform on a position-locked layer is refused before the box opens, with+ /// Photoshop's alert, from ⌘T and from the Move tool's transform controls alike. It used to+ /// open, preview every drag and fail only at commit.+ #[test]+ fn free_transform_on_a_locked_layer_is_refused_up_front() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();+ app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap();+ app.session+ .edit("lock", |doc, active| {+ doc.layer_mut(active.unwrap()).unwrap().locks.position = true;+ Ok(())+ })+ .unwrap();+ app.sync_views();+ let errors = |app: &PhotocraftApp| -> Vec<String> {+ app.ui+ .dialogs+ .iter()+ .filter(|d| d.kind == crate::state::DialogKind::Error)+ .filter_map(|d| d.fields.get("message")?.as_str().map(String::from))+ .collect()+ };+ let ctx = egui::Context::default();+ // ⌘T.+ let r = crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({}));+ assert_eq!(r, Err(crate::transform_tool::LOCKED.to_string()));+ assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "no box opened");+ assert_eq!(errors(&app), [crate::transform_tool::LOCKED]);+ app.ui.dialogs.clear();+ // The Move tool's transform controls.+ app.ui.tool = Tool::Move;+ app.ui.tool_options.move_show_transform = true;+ let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0 };+ let r = transform_controls_rect(&app, &xf).unwrap();+ assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom()));+ assert!(app.ui.transform.is_none());+ assert_eq!(errors(&app), [crate::transform_tool::LOCKED]);+ }+#[test]fn transform_control_hit_keeps_move_interior_free_and_has_rotation_band() {let r = Rect::from_min_max(pos2(20.0, 30.0), pos2(100.0, 70.0));diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 5e0510dcd..695c14327 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -1647,6 +1647,7 @@Mobile Mobilní zařízeníMove Tool Nástroj přesunCould not use the move tool because the layer is locked. Nástroj Přesun nelze použít, protože vrstva je zamčená.+ Could not complete the Free Transform command because the layer is locked. Příkaz Volná transformace nelze dokončit, protože vrstva je zamčená.Multiply NásobitMy Brushes Moje štětceNeutrals Neutrálnídiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 62d01bd14..1079eefef 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -1627,6 +1627,7 @@Mobile MobilMove Tool Verschieben-WerkzeugCould not use the move tool because the layer is locked. Das Verschieben-Werkzeug konnte nicht verwendet werden, weil die Ebene gesperrt ist.+ Could not complete the Free Transform command because the layer is locked. Der Befehl „Frei transformieren“ konnte nicht ausgeführt werden, weil die Ebene gesperrt ist.Multiply MultiplizierenMy Brushes Meine PinselNeutrals Neutralediff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 41af7e933..1ee4957f7 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3227,6 +3227,7 @@ cameraRaw Yellow ΚίτρινοMagic Wand Tool Μαγικό ραβδί (Magic Wand Tool)Move Tool Μετακίνηση (Move Tool)Could not use the move tool because the layer is locked. Δεν ήταν δυνατή η χρήση του εργαλείου Μετακίνηση, επειδή το επίπεδο είναι κλειδωμένο.+ Could not complete the Free Transform command because the layer is locked. Δεν ήταν δυνατή η ολοκλήρωση της εντολής Ελεύθερος μετασχηματισμός, επειδή το επίπεδο είναι κλειδωμένο.Note Tool Σημείωση (Note Tool)Object Selection Tool Επιλογή αντικειμένου (Object Selection Tool)Paint Bucket Tool Κουβάς γεμίσματος (Paint Bucket Tool)diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 9290db49c..b85a2c5ca 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -1631,6 +1631,7 @@Mobile MóvilMove Tool Herramienta MoverCould not use the move tool because the layer is locked. No se pudo usar la herramienta Mover porque la capa está bloqueada.+ Could not complete the Free Transform command because the layer is locked. No se pudo completar el comando Transformación libre porque la capa está bloqueada.Multiply MultiplicarMy Brushes Mis pincelesNeutrals Neutrosdiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 36d945371..88088270a 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -1610,6 +1610,7 @@Mobile MobileMove Tool Outil DéplacementCould not use the move tool because the layer is locked. Impossible d'utiliser l'outil Déplacement, car le calque est verrouillé.+ Could not complete the Free Transform command because the layer is locked. Impossible d'exécuter la commande Transformation libre, car le calque est verrouillé.Multiply ProduitMy Brushes Mes pinceauxNeutrals Neutresdiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 828d65531..421c68c16 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -1604,6 +1604,7 @@Mobile SelulerMove Tool Alat PindahCould not use the move tool because the layer is locked. Tidak dapat menggunakan alat Pindahkan karena layer terkunci.+ Could not complete the Free Transform command because the layer is locked. Tidak dapat menyelesaikan perintah Transformasi Bebas karena layer terkunci.Multiply MultiplyMy Brushes Kuas SayaNeutrals Netraldiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex b6c359208..1fd70c9fc 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -1629,6 +1629,7 @@Mobile MobileMove Tool Strumento SpostaCould not use the move tool because the layer is locked. Impossibile usare lo strumento Sposta perché il livello è bloccato.+ Could not complete the Free Transform command because the layer is locked. Impossibile completare il comando Trasformazione libera perché il livello è bloccato.Multiply MoltiplicaMy Brushes I miei pennelliNeutrals Neutridiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex d0b0674f6..08ddf0992 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -1635,6 +1635,7 @@Mobile モバイルMove Tool 移動ツールCould not use the move tool because the layer is locked. レイヤーがロックされているため、移動ツールを使用できません。+ Could not complete the Free Transform command because the layer is locked. レイヤーがロックされているため、自由変形コマンドを完了できません。Multiply 乗算My Brushes マイブラシNeutrals 中間色系diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex a93f1a543..2b32c878d 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -1605,6 +1605,7 @@Mobile 모바일Move Tool 이동 도구Could not use the move tool because the layer is locked. 레이어가 잠겨 있어 이동 도구를 사용할 수 없습니다.+ Could not complete the Free Transform command because the layer is locked. 레이어가 잠겨 있어 자유 변형 명령을 완료할 수 없습니다.Multiply 곱하기My Brushes 내 브러시Neutrals 중립색diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex e1f786227..0c6db6b9f 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -1618,6 +1618,7 @@Mobile MobielMove Tool VerplaatsgereedschapCould not use the move tool because the layer is locked. Kan het verplaatsgereedschap niet gebruiken omdat de laag is vergrendeld.+ Could not complete the Free Transform command because the layer is locked. Kan de opdracht Vrije transformatie niet voltooien omdat de laag is vergrendeld.Multiply VermenigvuldigenMy Brushes Mijn penselenNeutrals Neutrale tintendiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 9cf709947..f00cfc5b5 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -1628,6 +1628,7 @@Mobile Urządzenia mobilneMove Tool Narzędzie PrzesunięcieCould not use the move tool because the layer is locked. Nie można użyć narzędzia Przesunięcie, ponieważ warstwa jest zablokowana.+ Could not complete the Free Transform command because the layer is locked. Nie można ukończyć polecenia Dowolne przekształcanie, ponieważ warstwa jest zablokowana.Multiply MnożenieMy Brushes Moje pędzleNeutrals Neutralnediff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex eb5d4a8ba..2559bb158 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -1609,6 +1609,7 @@Mobile Dispositivos móveisMove Tool Ferramenta MoverCould not use the move tool because the layer is locked. Não foi possível usar a ferramenta Mover porque a camada está bloqueada.+ Could not complete the Free Transform command because the layer is locked. Não foi possível concluir o comando Transformação livre porque a camada está bloqueada.Multiply MultiplicaçãoMy Brushes Meus pincéisNeutrals Neutrosdiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 118effef7..97865b52c 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -1511,6 +1511,7 @@{name} Properties Свойства: {name}Move Tool ПеремещениеCould not use the move tool because the layer is locked. Не удалось использовать инструмент «Перемещение», потому что слой заблокирован.+ Could not complete the Free Transform command because the layer is locked. Не удалось выполнить команду «Свободное трансформирование», потому что слой заблокирован.Rectangular Marquee Tool Прямоугольная областьElliptical Marquee Tool Овальная областьBrush Tool Кистьdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex b822050d5..8642ca2f0 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -1494,6 +1494,7 @@{name} Properties Властивості: {name}Move Tool Інструмент «Переміщення»Could not use the move tool because the layer is locked. Не вдалося використати інструмент «Переміщення», бо шар заблоковано.+ Could not complete the Free Transform command because the layer is locked. Не вдалося виконати команду «Вільна трансформація», бо шар заблоковано.Rectangular Marquee Tool Інструмент «Прямокутне виділення»Elliptical Marquee Tool Інструмент «Еліптичне виділення»Brush Tool Інструмент «Пензель»diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex f89dc8a25..120656243 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -1644,6 +1644,7 @@Mobile 移动设备Move Tool 移动工具Could not use the move tool because the layer is locked. 无法使用移动工具,因为图层已锁定。+ Could not complete the Free Transform command because the layer is locked. 无法完成“自由变换”命令,因为图层已锁定。Multiply 正片叠底My Brushes 我的画笔Neutrals 中性色diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex d82d854de..18b7da882 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -1637,6 +1637,7 @@Mobile 行動裝置Move Tool 移動工具Could not use the move tool because the layer is locked. 無法使用移動工具,因為圖層已鎖定。+ Could not complete the Free Transform command because the layer is locked. 無法完成「任意變形」指令,因為圖層已鎖定。Multiply 色彩增值My Brushes 我的筆刷Neutrals 中間色diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsindex 786369216..0bcae39aa 100644--- a/crates/ui-egui/src/transform_tool.rs+++ b/crates/ui-egui/src/transform_tool.rs@@ -83,6 +83,10 @@ struct Follow {hidden: bool,}+/// Photoshop's alert when Free Transform (⌘T, Edit › Transform, the Move tool's transform controls)+/// starts on a layer locked in place, by its own lock or a group's.+pub const LOCKED: &str = "Could not complete the Free Transform command because the layer is locked.";+/// Grab radius of the box's handles, in screen points. Generous, so a corner is easy to catch;/// just beyond it, outside the box, a drag rotates.pub const HANDLE_PX: f64 = 12.0;@@ -158,6 +162,11 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>}let id = st.active_layer.ok_or("no active layer")?;let layer = doc.layer(id).ok_or("no layer")?;+ if photocraft_engine::transform_cmds::locked_for_transform(&doc, id) {+ // Photoshop refuses before the box opens rather than when it is committed (#2585).+ app.ui.open_dialog(crate::state::DialogKind::Error, json!({"message": tl!(LOCKED)}).as_object().cloned().unwrap_or_default());+ return Err(LOCKED.into());+ }if matches!(layer.content, LayerContent::Adjustment(_)) && layer.mask.is_none() {return Err("Adjustment layers have nothing to transform".into());}