Merge PR #6891: Reorder Layer Comps through dragging and context actions (#6498)

This commit is contained in:
aiongg committed 2026-10-22 02:22:02 +00:00
commit b4e5eee177
23 files changed
+184 -2

No files matched your search

+22
View File
@@ -251,6 +251,27 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"deleted": id}))
}
fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "layerComp.reorder";
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let id = comp_param(doc, p, CMD)?;
let index = p
.get("index")
.and_then(Value::as_u64)
.and_then(|n| usize::try_from(n).ok())
.filter(|i| *i < doc.layer_comps.len())
.ok_or_else(|| bad(CMD, "index must name a position in the comp list"))?;
let from = index_of(doc, id);
if from != index {
s.edit("Reorder Layer Comp", |doc, _| {
let comp = doc.layer_comps.remove(from);
doc.layer_comps.insert(index, comp);
Ok(())
})?;
}
Ok(json!({"comp": id, "index": index}))
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.active().ok_or(EngineError::NoDocument)?;
let id = comp_param(&d.doc, p, "layerComp.duplicate")?;
@@ -444,6 +465,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!("layerComp.previous", "Apply Previous Layer Comp", &[], "{}", has_comps, |s, _| step(s, -1)),
spec!("layerComp.next", "Apply Next Layer Comp", &[], "{}", has_comps, |s, _| step(s, 1)),
spec!("layerComp.delete", "Delete Layer Comp", &[], r##"{"comp":id|name?}"##, has_comps, delete),
spec!("layerComp.reorder", "Reorder Layer Comp", &[], r##"{"comp":id|name?,"index":integer (zero-based final position)}"##, has_comps, reorder),
spec!("layerComp.duplicate", "Duplicate Layer Comp", &[], r##"{"comp":id|name?} → {comp}"##, has_comps, duplicate),
spec!("layerComp.rename", "Rename Layer Comp", &[], r##"{"comp":id|name?,"name":str}"##, has_comps, rename),
spec!("layerComp.setComment", "Layer Comp Comment", &[], r##"{"comp":id|name?,"comment":str}"##, has_comps, set_comment),
+40
View File
@@ -348,6 +348,46 @@ fn clearing_warnings_of_an_unknown_comp_is_an_error() {
assert_eq!(s.execute("layerComp.updateWarnings", json!({})).unwrap()["count"], 1);
}
#[test]
fn reorder_comps_preserves_capture_and_applied_state_and_undoes() {
let (mut s, _, _) = session(8);
for name in ["One", "Two", "Three"] {
s.execute("layerComp.new", json!({"name":name})).unwrap();
}
let before = doc(&s).layer_comps.clone();
let applied = doc(&s).last_applied_comp;
let steps = s.active().unwrap().history.past_len();
s.execute("layerComp.reorder", json!({"comp":"One", "index":2})).unwrap();
assert_eq!(doc(&s).layer_comps, vec![before[1].clone(), before[2].clone(), before[0].clone()]);
assert_eq!(doc(&s).last_applied_comp, applied);
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
assert!(s.undo());
assert_eq!(doc(&s).layer_comps, before);
assert!(s.redo());
s.execute("layerComp.reorder", json!({"comp":before[0].id, "index":0})).unwrap();
assert_eq!(doc(&s).layer_comps, before);
let steps = s.active().unwrap().history.past_len();
s.execute("layerComp.reorder", json!({"comp":"One", "index":0})).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), steps);
}
#[test]
fn reorder_comps_rejects_bad_indices_without_changes() {
let mut s = Session::new();
assert!(!s.is_enabled("layerComp.reorder"));
s.execute("file.new", json!({"width":8, "height":8})).unwrap();
assert!(!s.is_enabled("layerComp.reorder"));
s.execute("layerComp.new", json!({"name":"Only"})).unwrap();
let before = doc(&s).layer_comps.clone();
let steps = s.active().unwrap().history.past_len();
for index in [Value::Null, json!(-1), json!(1), json!(1.5), json!("0"), json!(u64::MAX)] {
assert!(s.execute("layerComp.reorder", json!({"index":index})).is_err());
}
assert!(s.execute("layerComp.reorder", json!({"comp":"Missing", "index":0})).is_err());
assert_eq!(doc(&s).layer_comps, before);
assert_eq!(s.active().unwrap().history.past_len(), steps);
}
/// Apply Layer Comp is recorded by the comp's name, not its document-local id: played in another
/// document it applies that document's comp of the name, or stops when there is none (#7181).
#[test]
+82 -2
View File
@@ -67,6 +67,17 @@ fn run(app: &mut PhotocraftApp, id: &str, p: Value) {
}
}
#[derive(Clone, Copy)]
struct DragComp {
document: photocraft_doc::DocId,
comp: u32,
}
fn drop_index(from: usize, target: usize, after: bool) -> usize {
let slot = target + usize::from(after);
if from < slot { slot - 1 } else { slot }
}
pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let Some(st) = app.session.active() else {
@@ -113,8 +124,35 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
.size(11.5),
);
}
for c in &doc.layer_comps {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
for (index, c) in doc.layer_comps.iter().enumerate() {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click_and_drag());
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected == Some(c.id), &c.name));
resp.dnd_set_drag_payload(DragComp { document: doc.id, comp: c.id });
if let Some(source) = resp.dnd_hover_payload::<DragComp>()
&& source.document == doc.id
&& let Some(from) = doc.layer_comps.iter().position(|c| c.id == source.comp)
{
let after = ui.input(|i| i.pointer.hover_pos().is_some_and(|p| p.y >= rect.center().y));
let to = drop_index(from, index, after);
let y = if after { rect.bottom() } else { rect.top() };
ui.painter().line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, t.accent));
if resp.dnd_release_payload::<DragComp>().is_some() && from != to {
select = Some(source.comp);
action = Some(("layerComp.reorder", json!({"comp":source.comp, "index":to})));
}
}
resp.context_menu(|ui| {
if ui.add_enabled(index > 0, egui::Button::new(tl!("Move Up"))).clicked() {
action = Some(("layerComp.reorder", json!({"comp":c.id, "index":index.saturating_sub(1)})));
select = Some(c.id);
ui.close();
}
if ui.add_enabled(index + 1 < doc.layer_comps.len(), egui::Button::new(tl!("Move Down"))).clicked() {
action = Some(("layerComp.reorder", json!({"comp":c.id, "index":index + 1})));
select = Some(c.id);
ui.close();
}
});
if selected == Some(c.id) {
ui.painter().rect_filled(rect, 0.0, t.row_selected);
} else if resp.hovered() {
@@ -251,6 +289,48 @@ mod tests {
use super::*;
use photocraft_engine::Session;
#[test]
fn dragging_a_comp_row_reorders_without_applying_it() {
use egui_kittest::{Harness, kittest::Queryable};
let mut app = PhotocraftApp::new(Session::new(), crate::Services::default());
app.run("file.new", json!({"width":16,"height":16})).unwrap();
for name in ["First", "Second", "Third"] {
app.run("layerComp.new", json!({"name":name})).unwrap();
}
let applied = app.session.active().unwrap().doc.last_applied_comp;
let first = app.session.active().unwrap().doc.layer_comps[0].id;
let mut h = Harness::builder().with_size(vec2(360.0, 300.0)).build_ui_state(|ui, app| panel(app, ui), app);
h.run_steps(3);
let from = h.get_by_label("First").rect().center();
let row = h.get_by_label("Third").rect();
let to = pos2(row.center().x, row.bottom() - 2.0);
h.event(egui::Event::PointerMoved(from));
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
h.event(egui::Event::PointerMoved(from + vec2(10.0, 0.0)));
h.run_steps(2);
h.event(egui::Event::PointerMoved(to));
h.run_steps(2);
h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(3);
let app = h.state();
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.layer_comps.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Second", "Third", "First"]);
assert_eq!(doc.last_applied_comp, applied);
assert_eq!(app.ui.layer_comp_selected, Some(first));
}
#[test]
fn comp_drop_slots_account_for_the_removed_source_row() {
assert_eq!(drop_index(0, 2, false), 1);
assert_eq!(drop_index(0, 2, true), 2);
assert_eq!(drop_index(2, 0, false), 0);
assert_eq!(drop_index(2, 0, true), 1);
assert_eq!(drop_index(1, 1, false), 1);
assert_eq!(drop_index(1, 1, true), 1);
}
#[test]
fn warning_icon_clears_only_its_own_comp() {
// Regression for #4197.
+2
View File
@@ -3900,6 +3900,8 @@ navigator Zoom Zvětšení
Increase Brush Size Zvětšit velikost štětce
Decrease Brush Hardness Snížit tvrdost štětce
Increase Brush Hardness Zvýšit tvrdost štětce
Move Up Přesunout nahoru
Move Down Přesunout dolů
Memory Usage Využití paměti
Per-document RAM limit (MB) Limit RAM na dokument (MB)
Installed RAM: {ram} MB; this limit: {percent}% Nainstalovaná RAM: {ram} MB; tento limit: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -3296,6 +3296,8 @@ curves Smooth Glätten
GPU Memory (MB, 0 = Automatic) GPU-Speicher (MB, 0 = Automatisch)
{name} was changed by another app after it was opened or saved here. {name} wurde von einer anderen App geändert, nachdem es hier geöffnet oder gespeichert wurde.
Replace it with this document, or cancel and use File › Save As to keep both. Ersetze die Datei durch dieses Dokument oder brich ab und nutze Datei › Speichern unter, um beide zu behalten.
Move Up Nach oben
Move Down Nach unten
Memory Usage Speichernutzung
Per-document RAM limit (MB) RAM-Limit pro Dokument (MB)
Installed RAM: {ram} MB; this limit: {percent}% Installierter RAM: {ram} MB; dieses Limit: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -3989,6 +3989,8 @@ curves Smooth Εξομάλυνση
Increase Brush Size Αύξηση μεγέθους πινέλου
Decrease Brush Hardness Μείωση σκληρότητας πινέλου
Increase Brush Hardness Αύξηση σκληρότητας πινέλου
Move Up Μετακίνηση επάνω
Move Down Μετακίνηση κάτω
Memory Usage Χρήση μνήμης
Per-document RAM limit (MB) Όριο RAM ανά έγγραφο (MB)
Installed RAM: {ram} MB; this limit: {percent}% Εγκατεστημένη RAM: {ram} MB· αυτό το όριο: {percent}%
Can't render this file because it contains an unexpected character in line 1034 and column 18.
+2
View File
@@ -4251,6 +4251,8 @@ navigator Zoom Zoom
Increase Brush Size Aumentar tamaño del pincel
Decrease Brush Hardness Reducir dureza del pincel
Increase Brush Hardness Aumentar dureza del pincel
Move Up Mover arriba
Move Down Mover abajo
Memory Usage Uso de memoria
Per-document RAM limit (MB) Límite de RAM por documento (MB)
Installed RAM: {ram} MB; this limit: {percent}% RAM instalada: {ram} MB; este límite: {percent}%
Can't render this file because it contains an unexpected character in line 4 and column 47.
+2
View File
@@ -3299,6 +3299,8 @@ curves Smooth Lisser
Increase Brush Size Augmenter la taille du pinceau
Decrease Brush Hardness Réduire la dureté du pinceau
Increase Brush Hardness Augmenter la dureté du pinceau
Move Up Déplacer vers le haut
Move Down Déplacer vers le bas
Memory Usage Utilisation de la mémoire
Per-document RAM limit (MB) Limite RAM par document (Mo)
Installed RAM: {ram} MB; this limit: {percent}% RAM installée : {ram} Mo ; cette limite : {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -4206,6 +4206,8 @@ cameraRaw Yellow Sárga
Increase Brush Size Ecsetméret növelése
Decrease Brush Hardness Ecsetkeménység csökkentése
Increase Brush Hardness Ecsetkeménység növelése
Move Up Mozgatás felfelé
Move Down Mozgatás lefelé
Memory Usage Memóriahasználat
Per-document RAM limit (MB) Dokumentumonkénti RAM-korlát (MB)
Installed RAM: {ram} MB; this limit: {percent}% Telepített RAM: {ram} MB; ez a korlát: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -3286,6 +3286,8 @@ curves Smooth Haluskan
Increase Brush Size Perbesar ukuran kuas
Decrease Brush Hardness Kurangi kekerasan kuas
Increase Brush Hardness Tambah kekerasan kuas
Move Up Pindah ke atas
Move Down Pindah ke bawah
Memory Usage Penggunaan memori
Per-document RAM limit (MB) Batas RAM per dokumen (MB)
Installed RAM: {ram} MB; this limit: {percent}% RAM terpasang: {ram} MB; batas ini: {percent}%
Can't render this file because it contains an unexpected character in line 4 and column 47.
+2
View File
@@ -4406,6 +4406,8 @@ shape Appearance Aspetto
GPU Memory (MB, 0 = Automatic) Memoria GPU (MB, 0 = Automatico)
{name} was changed by another app after it was opened or saved here. {name} è stato modificato da un'altra app dopo essere stato aperto o salvato qui.
Replace it with this document, or cancel and use File › Save As to keep both. Sostituiscilo con questo documento, oppure annulla e usa File › Salva con nome per tenerli entrambi.
Move Up Sposta su
Move Down Sposta giù
Memory Usage Utilizzo memoria
Per-document RAM limit (MB) Limite RAM per documento (MB)
Installed RAM: {ram} MB; this limit: {percent}% RAM installata: {ram} MB; questo limite: {percent}%
Can't render this file because it contains an unexpected character in line 2663 and column 53.
+2
View File
@@ -3966,6 +3966,8 @@ curves Smooth スムーズ
Increase Brush Size ブラシサイズを大きく
Decrease Brush Hardness ブラシの硬さを下げる
Increase Brush Hardness ブラシの硬さを上げる
Move Up 上へ移動
Move Down 下へ移動
Memory Usage メモリ使用量
Per-document RAM limit (MB) ドキュメントあたりの RAM 上限 (MB)
Installed RAM: {ram} MB; this limit: {percent}% 搭載 RAM: {ram} MB、この上限: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -3477,6 +3477,8 @@ curves Smooth 매끄럽게
Increase Brush Size 브러시 크기 늘리기
Decrease Brush Hardness 브러시 경도 줄이기
Increase Brush Hardness 브러시 경도 늘리기
Move Up 위로 이동
Move Down 아래로 이동
Memory Usage 메모리 사용량
Per-document RAM limit (MB) 문서당 RAM 한도(MB)
Installed RAM: {ram} MB; this limit: {percent}% 설치된 RAM: {ram} MB; 이 한도: {percent}%
Can't render this file because it contains an unexpected character in line 3177 and column 53.
+2
View File
@@ -4049,6 +4049,8 @@ curves Smooth Vloeiend maken
Increase Brush Size Penseelgrootte vergroten
Decrease Brush Hardness Penseelhardheid verlagen
Increase Brush Hardness Penseelhardheid verhogen
Move Up Omhoog
Move Down Omlaag
Memory Usage Geheugengebruik
Per-document RAM limit (MB) RAM-limiet per document (MB)
Installed RAM: {ram} MB; this limit: {percent}% Geïnstalleerd RAM: {ram} MB; deze limiet: {percent}%
Can't render this file because it contains an unexpected character in line 8 and column 34.
+2
View File
@@ -3888,6 +3888,8 @@ curves Smooth Wygładź
Increase Brush Size Zwiększ rozmiar pędzla
Decrease Brush Hardness Zmniejsz twardość pędzla
Increase Brush Hardness Zwiększ twardość pędzla
Move Up Przesuń w górę
Move Down Przesuń w dół
Memory Usage Użycie pamięci
Per-document RAM limit (MB) Limit RAM na dokument (MB)
Installed RAM: {ram} MB; this limit: {percent}% Zainstalowany RAM: {ram} MB; ten limit: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -4079,6 +4079,8 @@ layerLabel No Color Sem cor
Increase Brush Size Aumentar tamanho do pincel
Decrease Brush Hardness Diminuir dureza do pincel
Increase Brush Hardness Aumentar dureza do pincel
Move Up Mover para cima
Move Down Mover para baixo
Memory Usage Uso de memória
Per-document RAM limit (MB) Limite de RAM por documento (MB)
Installed RAM: {ram} MB; this limit: {percent}% RAM instalada: {ram} MB; este limite: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -3265,6 +3265,8 @@ curves Smooth Сгладить
Increase Brush Size Увеличить размер кисти
Decrease Brush Hardness Уменьшить жёсткость кисти
Increase Brush Hardness Увеличить жёсткость кисти
Move Up Переместить вверх
Move Down Переместить вниз
Memory Usage Использование памяти
Per-document RAM limit (MB) Лимит ОЗУ на документ (МБ)
Installed RAM: {ram} MB; this limit: {percent}% Установлено ОЗУ: {ram} МБ; этот лимит: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -4360,6 +4360,8 @@ shape Appearance Izgled
Increase Brush Size Povećaj veličinu četkice
Decrease Brush Hardness Smanji tvrdoću četkice
Increase Brush Hardness Povećaj tvrdoću četkice
Move Up Pomeri nagore
Move Down Pomeri nadole
Memory Usage Upotreba memorije
Per-document RAM limit (MB) RAM limit po dokumentu (MB)
Installed RAM: {ram} MB; this limit: {percent}% Instalisan RAM: {ram} MB; ovaj limit: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -4017,6 +4017,8 @@ cameraData Lens Lens
Increase Brush Size Fırça boyutunu büyüt
Decrease Brush Hardness Fırça sertliğini azalt
Increase Brush Hardness Fırça sertliğini artır
Move Up Yukarı taşı
Move Down Aşağı taşı
Memory Usage Bellek kullanımı
Per-document RAM limit (MB) Belge başına RAM sınırı (MB)
Installed RAM: {ram} MB; this limit: {percent}% Kurulu RAM: {ram} MB; bu sınır: {percent}%
Can't render this file because it contains an unexpected character in line 8 and column 34.
+2
View File
@@ -3997,6 +3997,8 @@ curves Smooth Згладити
This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Щоб продовжити, потрібно растеризувати цей шар фігури. Після цього його більше не можна буде редагувати як фігуру. Растеризувати фігуру?
This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Щоб продовжити, потрібно растеризувати цей смартоб’єкт. Після цього його вміст більше не можна буде редагувати. Растеризувати смартоб’єкт?
This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Щоб продовжити, потрібно растеризувати цей шар заливки. Після цього його заливку більше не можна буде редагувати. Растеризувати шар?
Move Up Перемістити вгору
Move Down Перемістити вниз
Memory Usage Використання пам’яті
Per-document RAM limit (MB) Ліміт RAM на документ (МБ)
Installed RAM: {ram} MB; this limit: {percent}% Встановлено RAM: {ram} МБ; цей ліміт: {percent}%
Can't render this file because it contains an unexpected character in line 1398 and column 18.
+2
View File
@@ -3779,6 +3779,8 @@ curves Smooth Làm mượt
Increase Brush Size Tăng kích thước cọ
Decrease Brush Hardness Giảm độ cứng của cọ
Increase Brush Hardness Tăng độ cứng của cọ
Move Up Di chuyển lên
Move Down Di chuyển xuống
Memory Usage Sử dụng bộ nhớ
Per-document RAM limit (MB) Giới hạn RAM mỗi tài liệu (MB)
Installed RAM: {ram} MB; this limit: {percent}% RAM đã cài: {ram} MB; giới hạn này: {percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -2922,6 +2922,8 @@ curves Smooth 平滑
Increase Brush Size 增大画笔大小
Decrease Brush Hardness 减小画笔硬度
Increase Brush Hardness 增大画笔硬度
Move Up 上移
Move Down 下移
Memory Usage 内存使用
Per-document RAM limit (MB) 每个文档的 RAM 上限 (MB)
Installed RAM: {ram} MB; this limit: {percent}% 已安装 RAM:{ram} MB;此上限:{percent}%
Can't render this file because it contains an unexpected character in line 2611 and column 53.
+2
View File
@@ -2907,6 +2907,8 @@ curves Smooth 平滑
Increase Brush Size 放大筆刷大小
Decrease Brush Hardness 降低筆刷硬度
Increase Brush Hardness 提高筆刷硬度
Move Up 上移
Move Down 下移
Memory Usage 記憶體使用量
Per-document RAM limit (MB) 每個文件的 RAM 上限 (MB)
Installed RAM: {ram} MB; this limit: {percent}% 已安裝 RAM:{ram} MB;此上限:{percent}%
Can't render this file because it contains an unexpected character in line 6 and column 47.