Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Keyboard layer navigation: Alt+[ / Alt+] / Alt+, / Alt+. and Shift to add (part of #352) (#470)

BFlatf49b5a48536f
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 79fff5b2d..854e3b481 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -987,6 +987,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::automate_cmds::specs());
v.extend(crate::print_cmds::specs());
v.extend(crate::pick_cmds::specs());
+ v.extend(crate::layer_nav_cmds::specs());
v.extend(crate::frame_cmds::specs());
v.extend(crate::migrate_cmds::specs());
v.extend(crate::trap_cmds::specs());
diff --git a/crates/engine/src/layer_nav_cmds.rs b/crates/engine/src/layer_nav_cmds.rs
new file mode 100644
index 000000000..bd1ecb661
--- /dev/null
+++ b/crates/engine/src/layer_nav_cmds.rs
@@ -0,0 +1,199 @@
+//! Keyboard layer navigation, the shortcuts that have no menu item (#352): ⌥] / ⌥[ select the
+//! layer above / below, ⌥. / ⌥, the top / bottom layer, and ⇧⌥] / ⇧⌥[ add the layer above /
+//! below to the selection. They follow the Layers panel's rows, top to bottom: a group's row comes
+//! before its children, and the children of a collapsed group are skipped.
+
+use photocraft_doc::{Document, Layer, LayerContent, LayerId};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::layer_multi_cmds::set_selection;
+use crate::{EngineError, Result, Session};
+
+fn has_layers(s: &Session) -> std::result::Result<(), String> {
+ let st = s.active().ok_or("no document open")?;
+ if st.doc.layers.is_empty() { Err("the document has no layers".into()) } else { Ok(()) }
+}
+
+/// The Layers panel's rows, top to bottom: each group before its children, collapsed groups
+/// without them.
+pub fn panel_rows(doc: &Document) -> Vec<LayerId> {
+ fn rec(layers: &[Layer], out: &mut Vec<LayerId>) {
+ for l in layers.iter().rev() {
+ out.push(l.id);
+ if let LayerContent::Group(g) = &l.content
+ && g.expanded
+ {
+ rec(&g.children, out);
+ }
+ }
+ }
+ let mut out = Vec::new();
+ rec(&doc.layers, &mut out);
+ out
+}
+
+/// Where `id` is in `rows`; a layer inside a collapsed group counts as that group's row (the
+/// nearest enclosing one that has a row).
+fn row_of(doc: &Document, rows: &[LayerId], id: LayerId) -> Option<usize> {
+ let path = doc.path_of(id)?;
+ (1..=path.len()).rev().find_map(|n| doc.layer_at(&path[..n]).and_then(|l| rows.iter().position(|r| *r == l.id)))
+}
+
+#[derive(Clone, Copy)]
+enum Step {
+ Above,
+ Below,
+ Top,
+ Bottom,
+}
+
+/// Selects (or with `add`, adds to the selection) the row `step` away from the active layer.
+/// At the top or bottom row the selection stays as it is.
+fn navigate(s: &mut Session, step: Step, add: bool) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let rows = panel_rows(&st.doc);
+ let last = rows.len().checked_sub(1).ok_or_else(|| EngineError::Other("the document has no layers".into()))?;
+ let current = st.active_layer.and_then(|a| row_of(&st.doc, &rows, a));
+ let target = match (step, current) {
+ (Step::Top, _) | (Step::Above, None) => 0,
+ (Step::Bottom, _) | (Step::Below, None) => last,
+ (Step::Above, Some(i)) => i.saturating_sub(1),
+ (Step::Below, Some(i)) => (i + 1).min(last),
+ };
+ let id = rows.get(target).copied().ok_or_else(|| EngineError::Other("no layer there".into()))?;
+ if add {
+ let mut sel = st.selected_layers();
+ if !sel.contains(&id) {
+ sel.push(id);
+ }
+ let anchor = st.layer_anchor;
+ set_selection(s, sel, Some(id), anchor)?;
+ } else {
+ s.select_layer(id)?;
+ }
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ Ok(json!({"layer": id.0, "selected": st.selected_layers().iter().map(|l| l.0).collect::<Vec<_>>()}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $sc:expr, $step:expr, $add:expr) => {
+ CommandSpec {
+ id: $id,
+ label: $label,
+ menu: &[],
+ shortcut: Some($sc),
+ params: "{} (follows the Layers panel's rows; collapsed groups are one row)",
+ enabled: has_layers,
+ journal: true,
+ run: |s, _| navigate(s, $step, $add),
+ }
+ };
+ }
+ vec![
+ spec!("layer.selectAbove", "Select Layer Above", "Alt+]", Step::Above, false),
+ spec!("layer.selectBelow", "Select Layer Below", "Alt+[", Step::Below, false),
+ spec!("layer.selectTop", "Select Top Layer", "Alt+.", Step::Top, false),
+ spec!("layer.selectBottom", "Select Bottom Layer", "Alt+,", Step::Bottom, false),
+ spec!("layer.addAboveToSelection", "Add Layer Above to Selection", "Alt+Shift+]", Step::Above, true),
+ spec!("layer.addBelowToSelection", "Add Layer Below to Selection", "Alt+Shift+[", Step::Below, true),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Bottom to top: Background, A, Group { B, C }, D. Panel rows: D, Group, C, B, A, Background.
+ fn session() -> (Session, [LayerId; 6]) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
+ let bg = s.active().unwrap().doc.layers[0].id;
+ let id = |s: &mut Session, cmd: &str, p: Value| LayerId(s.execute(cmd, p).unwrap()["layer"].as_u64().unwrap());
+ let a = id(&mut s, "layer.new.layer", json!({"name": "A"}));
+ let b = id(&mut s, "layer.new.layer", json!({"name": "B"}));
+ let c = id(&mut s, "layer.new.layer", json!({"name": "C"}));
+ s.execute("layer.select", json!({"layer": b.0})).unwrap();
+ s.execute("layer.select", json!({"layer": c.0, "mode": "add"})).unwrap();
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ let group = s.active().unwrap().doc.layers.iter().find(|l| l.is_group()).unwrap().id;
+ let d = id(&mut s, "layer.new.layer", json!({"name": "D"}));
+ (s, [bg, a, group, b, c, d])
+ }
+
+ fn active(s: &Session) -> LayerId {
+ s.active().unwrap().active_layer.unwrap()
+ }
+
+ #[test]
+ fn steps_follow_the_panel_rows_and_stop_at_the_ends() {
+ let (mut s, [bg, a, group, b, c, d]) = session();
+ assert_eq!(panel_rows(&s.active().unwrap().doc), vec![d, group, c, b, a, bg]);
+ s.execute("layer.select", json!({"layer": d.0})).unwrap();
+ for want in [group, c, b, a, bg, bg] {
+ s.execute("layer.selectBelow", json!({})).unwrap();
+ assert_eq!(active(&s), want);
+ }
+ for want in [a, b, c, group, d, d] {
+ s.execute("layer.selectAbove", json!({})).unwrap();
+ assert_eq!(active(&s), want);
+ }
+ s.execute("layer.selectBottom", json!({})).unwrap();
+ assert_eq!((active(&s), s.active().unwrap().selected_layers()), (bg, vec![bg]));
+ s.execute("layer.selectTop", json!({})).unwrap();
+ assert_eq!(active(&s), d);
+ }
+
+ #[test]
+ fn collapsed_groups_are_one_row_and_adding_extends_the_selection() {
+ let (mut s, [bg, a, group, _b, c, d]) = session();
+ s.edit("collapse", |doc, _| {
+ if let Some(LayerContent::Group(g)) = doc.layer_mut(group).map(|l| &mut l.content) {
+ g.expanded = false;
+ }
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(panel_rows(&s.active().unwrap().doc), vec![d, group, a, bg]);
+ // A layer inside the collapsed group steps from the group's row.
+ s.execute("layer.select", json!({"layer": c.0})).unwrap();
+ s.execute("layer.selectBelow", json!({})).unwrap();
+ assert_eq!(active(&s), a);
+ s.execute("layer.addAboveToSelection", json!({})).unwrap();
+ s.execute("layer.addAboveToSelection", json!({})).unwrap();
+ let mut sel = s.active().unwrap().selected_layers();
+ sel.sort();
+ let mut want = vec![a, group, d];
+ want.sort();
+ assert_eq!((active(&s), sel), (d, want));
+ s.execute("layer.addBelowToSelection", json!({})).unwrap();
+ assert_eq!(active(&s), group, "the active layer moves; the selection keeps every layer");
+ assert_eq!(s.active().unwrap().selected_layers().len(), 3);
+ }
+
+ #[test]
+ fn selecting_never_dirties_and_bad_states_are_errors() {
+ let (mut s, _) = session();
+ let st = s.active_mut().unwrap();
+ st.saved_revision = st.revision;
+ s.execute("layer.selectTop", json!({"junk": [1, 2]})).unwrap();
+ assert!(!s.active().unwrap().is_dirty(), "selecting a layer is not an edit");
+ let mut empty = Session::new();
+ for c in specs() {
+ assert!(!empty.is_enabled(c.id));
+ assert!(empty.execute(c.id, json!({})).is_err());
+ }
+ empty.execute("file.new", json!({"width": 4, "height": 4})).unwrap();
+ empty
+ .edit("clear", |doc, active| {
+ doc.layers.clear();
+ *active = None;
+ Ok(())
+ })
+ .unwrap();
+ for c in specs() {
+ assert!(empty.execute(c.id, json!({})).is_err(), "{}: no layers", c.id);
+ }
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 6143ad366..e02611b93 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -42,6 +42,7 @@ pub mod inspect;
pub mod jobs;
pub mod layer_menu_cmds;
pub mod layer_multi_cmds;
+pub mod layer_nav_cmds;
pub mod layer_style;
pub mod lens_cmds;
pub mod mask_view_cmds;
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 99669e256..30b870afb 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -351,6 +351,12 @@
Merge Down Sloučit dolů
Merge Visible Sloučit viditelné
Stamp Visible Otisknout viditelné
+ Select Layer Above Vybrat vrstvu nad
+ Select Layer Below Vybrat vrstvu pod
+ Select Top Layer Vybrat horní vrstvu
+ Select Bottom Layer Vybrat spodní vrstvu
+ Add Layer Above to Selection Přidat vrstvu nad do výběru
+ Add Layer Below to Selection Přidat vrstvu pod do výběru
Stamp Down Otisknout dolů
Flatten Image Sloučit do jedné vrstvy
Matting Začištění okrajů
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index e09f5dbea..96c545fb8 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -343,6 +343,12 @@
Merge Down Combinar hacia abajo
Merge Visible Combinar visibles
Stamp Visible Estampar visibles
+ Select Layer Above Seleccionar la capa de arriba
+ Select Layer Below Seleccionar la capa de abajo
+ Select Top Layer Seleccionar la capa superior
+ Select Bottom Layer Seleccionar la capa inferior
+ Add Layer Above to Selection Añadir la capa de arriba a la selección
+ Add Layer Below to Selection Añadir la capa de abajo a la selección
Stamp Down Estampar hacia abajo
Flatten Image Acoplar imagen
Matting Matizado
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index f3856950b..a908e0a8c 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -347,6 +347,12 @@
Merge Down 下のレイヤーと結合
Merge Visible 表示レイヤーを結合
Stamp Visible 表示レイヤーをスタンプ
+ Select Layer Above 上のレイヤーを選択
+ Select Layer Below 下のレイヤーを選択
+ Select Top Layer 最上位のレイヤーを選択
+ Select Bottom Layer 最下位のレイヤーを選択
+ Add Layer Above to Selection 上のレイヤーを選択に追加
+ Add Layer Below to Selection 下のレイヤーを選択に追加
Stamp Down 下のレイヤーにスタンプ
Flatten Image 画像を統合
Matting マット処理
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index eccdad2e8..3cbecb14a 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1760,6 +1760,12 @@
Merge Shape Components Объединить компоненты фигуры
Merge Visible Свести видимые
Stamp Visible Штамп видимых
+ Select Layer Above Выбрать слой выше
+ Select Layer Below Выбрать слой ниже
+ Select Top Layer Выбрать верхний слой
+ Select Bottom Layer Выбрать нижний слой
+ Add Layer Above to Selection Добавить слой выше к выбору
+ Add Layer Below to Selection Добавить слой ниже к выбору
Stamp Down Штамп вниз
Mesh Сетка
Middle Eastern & South Asian Composer Компоновка для Ближнего Востока и Южной Азии
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 08d782ce1..5262400bb 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -346,6 +346,12 @@
Merge Down 向下合并
Merge Visible 合并可见图层
Stamp Visible 盖印可见图层
+ Select Layer Above 选择上方图层
+ Select Layer Below 选择下方图层
+ Select Top Layer 选择顶部图层
+ Select Bottom Layer 选择底部图层
+ Add Layer Above to Selection 将上方图层添加到选择
+ Add Layer Below to Selection 将下方图层添加到选择
Stamp Down 向下盖印
Flatten Image 拼合图像
Matting 修边
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 8729dc1e0..ce91a0692 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -351,6 +351,12 @@
Merge Down 向下合併圖層
Merge Visible 合併可見圖層
Stamp Visible 蓋印可見圖層
+ Select Layer Above 選取上方圖層
+ Select Layer Below 選取下方圖層
+ Select Top Layer 選取最上層圖層
+ Select Bottom Layer 選取最下層圖層
+ Add Layer Above to Selection 將上方圖層加入選取
+ Add Layer Below to Selection 將下方圖層加入選取
Stamp Down 向下蓋印
Flatten Image 影像平面化
Matting 修邊
diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rs
index 58cf39092..5805a633b 100644
--- a/crates/ui-egui/src/shortcut_dispatch/tests.rs
+++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs
@@ -297,3 +297,18 @@ fn a_disabled_shortcut_says_why() {
assert!(matches!(log.as_slice(), [(id, Outcome::Disabled(_) | Outcome::Failed(_))] if id == "layer.mergeLayers"), "{log:?}");
assert!(!h.state().ui.status.is_empty() && h.state().ui.status_error, "the status bar says why");
}
+
+/// #352: ⌥[ ⌥] ⌥, ⌥. and ⇧⌥[ walk the Layers panel's rows from the keyboard.
+#[test]
+fn alt_brackets_walk_the_layers_panel() {
+ let mut h = harness();
+ // Rows, top to bottom: paint, Hello (type), group, in-group, Background.
+ assert_eq!(active_name(&h), "paint");
+ for (key, want) in [("Alt+[", "Hello"), ("Alt+[", "group"), ("Alt+[", "in-group"), ("Alt+]", "group"), ("Alt+,", "Background"), ("Alt+.", "paint")] {
+ press(&mut h, key);
+ assert_eq!(active_name(&h), want, "after {key}");
+ }
+ press(&mut h, "Alt+Shift+[");
+ assert_eq!(active_name(&h), "Hello");
+ assert_eq!(h.state().session.active().unwrap().selected_layers().len(), 2, "⇧⌥[ adds to the selection");
+}