diff --git a/apps/photocraft-cli/tests/it/orientation.rs b/apps/photocraft-cli/tests/it/orientation.rs index 101195581f..3895df367a 100644 --- a/apps/photocraft-cli/tests/it/orientation.rs +++ b/apps/photocraft-cli/tests/it/orientation.rs @@ -125,7 +125,8 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() { let (a, b) = (d.join("a.pcraft"), d.join("b.pcraft")); ok(bin().arg("convert").arg(&jpg).arg(&a)); ok(bin().arg("convert").arg(&a).arg(&b)); - // Everything but the file's own path and saved document name must match. + // Everything but the file's own path and saved document name (which the first snapshot is + // named after) must match. let info = |p: &Path| { let mut v = serde_json::from_str::(&ok(bin().arg("info").arg(p))).unwrap(); v.as_object_mut().unwrap().remove("file"); @@ -136,8 +137,12 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() { assert_eq!((ia["width"].as_u64(), ia["height"].as_u64()), (Some(16), Some(32))); assert_eq!(ia["name"], "a.pcraft"); assert_eq!(ib["name"], "b.pcraft"); - ia.as_object_mut().unwrap().remove("name"); - ib.as_object_mut().unwrap().remove("name"); + assert_eq!(ia["snapshots"][0]["name"], "a.pcraft"); + assert_eq!(ib["snapshots"][0]["name"], "b.pcraft"); + for v in [&mut ia, &mut ib] { + v.as_object_mut().unwrap().remove("name"); + v["snapshots"][0].as_object_mut().unwrap().remove("name"); + } assert_eq!(ia, ib); let (pa, pb) = (d.join("a.png"), d.join("b.png")); ok(bin().arg("convert").arg(&a).arg(&pa)); diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index 14bfbffd54..0596bbb12d 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -101,6 +101,12 @@ fn snapshot_index(s: &Session, cmd: &str, p: &Value) -> Result { st.snapshots.iter().position(|snap| snap.id == id).ok_or_else(|| bad(cmd, format!("no snapshot {id}"))) } +/// The name `history.newSnapshot` gives a snapshot without one: "Snapshot N" (the New Snapshot +/// dialog suggests it too). +pub fn next_snapshot_name(st: &crate::DocState) -> String { + format!("Snapshot {}", st.next_snapshot) +} + /// A non-blank `name` param, trimmed; `None` when absent. fn name_param(cmd: &str, p: &Value) -> Result> { match p.get("name") { @@ -140,9 +146,9 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result { _ => (st.doc.clone(), st.layer_target()), }; let st = s.active_mut().ok_or(EngineError::NoDocument)?; + let name = name.unwrap_or_else(|| next_snapshot_name(st)); let id = st.next_snapshot; st.next_snapshot = id.saturating_add(1); - let name = name.unwrap_or_else(|| format!("Snapshot {id}")); st.snapshots.push(Snapshot { id, name: name.clone(), doc, layers }); Ok(json!({ "snapshot": id, "name": name })) } @@ -413,7 +419,8 @@ mod tests { assert_eq!(entries(&s), before, "taking a snapshot is not a step"); let r = s.execute("history.newSnapshot", json!({"name": "Before green"})).unwrap(); assert_eq!(r, json!({"snapshot": 2, "name": "Before green"})); - assert_eq!(snapshots(&s), json!([{"id": 1, "name": "Snapshot 1"}, {"id": 2, "name": "Before green"}])); + let first = json!({"id": 0, "name": s.active().unwrap().doc.name}); + assert_eq!(snapshots(&s), json!([first, {"id": 1, "name": "Snapshot 1"}, {"id": 2, "name": "Before green"}])); } #[test] @@ -433,7 +440,7 @@ mod tests { assert!(s.active().unwrap().active_layer.is_some()); s.execute("edit.undo", json!({})).unwrap(); assert_eq!(top_pixel(&s), blue, "undo leaves the snapshot"); - assert_eq!(snapshots(&s).as_array().unwrap().len(), 1, "snapshots are not history"); + assert_eq!(snapshots(&s).as_array().unwrap().len(), 2, "snapshots are not history"); } #[test] @@ -465,7 +472,7 @@ mod tests { let base = with.active().unwrap().memory_bytes(); with.execute("history.newSnapshot", json!({"from": "mergedLayers"})).unwrap(); let st = with.active().unwrap(); - let flat = tile_bytes(&st.snapshots[0].doc); + let flat = tile_bytes(&st.snapshots.last().unwrap().doc); assert!(flat > 0); assert_eq!(st.memory_bytes(), base + flat); // Room for the document's tiles and four fill tiles. @@ -494,11 +501,11 @@ mod tests { s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); let st = s.active().unwrap(); // The snapshot's green layer tile, now only in it and the last state. - let shared = tile_bytes(&Document { layers: st.snapshots[0].doc.layers[1..].to_vec(), ..(*st.doc).clone() }); + let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec(), ..(*st.doc).clone() }); let all = st.history.unique_bytes(&st.doc); let r = s.execute("edit.purge.histories", json!({})).unwrap(); assert_eq!(r["bytes"], json!(all - shared), "the green tile stays with the snapshot"); - assert_eq!(s.active().unwrap().snapshots.len(), 1); + assert_eq!(s.active().unwrap().snapshots.len(), 2, "the first snapshot and the new one"); } #[test] @@ -509,11 +516,31 @@ mod tests { } s.execute("history.renameSnapshot", json!({"snapshot": 2, "name": "Lesson start"})).unwrap(); s.execute("history.deleteSnapshot", json!({"snapshot": 1})).unwrap(); - assert_eq!(snapshots(&s), json!([{"id": 2, "name": "Lesson start"}, {"id": 3, "name": "Snapshot 3"}])); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(snapshots(&s), json!([{"id": 2, "name": "Lesson start"}, {"id": 3, "name": "Snapshot 3"}]), "the first snapshot can go too"); let r = s.execute("history.newSnapshot", json!({})).unwrap(); assert_eq!(r["snapshot"], json!(4), "ids are never reused"); } + /// Photoshop's first snapshot (#2966): every document starts with a snapshot of itself as + /// opened, named after it, so the opening state can always be brought back, even after + /// History has dropped its oldest states. + #[test] + fn a_document_starts_with_a_first_snapshot_of_itself() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(snapshots(&s), json!([{"id": 0, "name": name}])); + let opened = top_pixel(&s); + for _ in 0..3 { + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + } + s.active_mut().unwrap().history.purge_last(); + s.execute("history.selectSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(top_pixel(&s), opened, "back to the document as opened"); + assert_eq!(entries(&s).last(), Some(&name), "a state named after the document"); + } + #[test] fn snapshot_commands_refuse_bad_params() { let mut s = Session::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 44cbe903ad..914604f219 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -244,8 +244,9 @@ pub struct DocState { /// pixel coordinates. Per-document view state: discarded when the document closes, never saved /// to `.pcraft` or PSD, and not a history step. pub color_samplers: Vec<[f64; 2]>, - /// History panel snapshots, oldest first (`history.newSnapshot`, #2966). Kept for the - /// session only, as in Photoshop: not history states, and not saved with the document. + /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is + /// the document as opened. Kept for the session only, as in Photoshop: not history states, + /// and not saved with the document. pub snapshots: Vec, /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. next_snapshot: u64, @@ -272,9 +273,14 @@ impl DocState { pub fn new(doc: Document, path: Option) -> Self { let active_layer = doc.top_layer(); let mut history = History::default(); - history.set_current_layers(LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }); + let target = LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }; + history.set_current_layers(target.clone()); + let doc = Arc::new(doc); + // Photoshop's first snapshot: the document as opened, named after it, so the History + // panel's top row can always bring it back (#2966). + let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; Self { - doc: Arc::new(doc), + doc, history, active_layer, selected_layers: active_layer.into_iter().collect(), @@ -294,7 +300,7 @@ impl DocState { show_only: None, floating: None, color_samplers: Vec::new(), - snapshots: Vec::new(), + snapshots: vec![first], next_snapshot: 1, source_snapshot: None, } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index bc658783cd..4fa22fe947 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -434,6 +434,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::pattern_fill_ui::owns(&fields) => crate::pattern_fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields), + DialogKind::Command if crate::snapshot_dialog::owns(&fields) => crate::snapshot_dialog::body(ui, &mut fields), DialogKind::Command if crate::channel_options_ui::owns(&fields) => crate::channel_options_ui::body(ui, &mut fields), DialogKind::Command if crate::channel_options_ui::owns_new_spot(&fields) => crate::channel_options_ui::new_spot_body(ui, &mut fields), DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields), @@ -836,6 +837,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields), + DialogKind::Command if crate::snapshot_dialog::owns(&d.fields) => crate::snapshot_dialog::confirm(app, &d.fields), DialogKind::Command if crate::channel_options_ui::owns(&d.fields) => crate::channel_options_ui::confirm(app, &d.fields), DialogKind::Command if crate::channel_options_ui::owns_new_spot(&d.fields) => crate::channel_options_ui::confirm_new_spot(app, &d.fields), DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields), diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 94cf3af78c..45995bc934 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1033,6 +1033,10 @@ Create new pattern from the selection Vytvořit nový vzorek z výběru Create new shape from the current path Vytvořit nový tvar z aktuální cesty Create new snapshot Vytvořit nový snímek + From: Z: + Full Document Celý dokument + Merged Layers Sloučené vrstvy + New Snapshot Nový snímek Create new tool preset Vytvořit nové přednastavení nástroje Crop Factor Crop faktor Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 31d9234175..0237b17f67 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1014,6 +1014,10 @@ Create new pattern from the selection Neues Muster aus der Auswahl erstellen Create new shape from the current path Neue Form aus dem aktuellen Pfad erstellen Create new snapshot Neuen Snapshot erstellen + From: Von: + Full Document Gesamtes Dokument + Merged Layers Zusammengefügte Ebenen + New Snapshot Neuer Snapshot Create new style (from the selected type) Neuen Stil erstellen (aus dem ausgewählten Text) Create new style from the selected layer Neuen Stil aus der ausgewählten Ebene erstellen Create new tool preset Neue Werkzeugvorgabe erstellen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f9d30d2e17..1b4df4c2dc 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -761,6 +761,9 @@ Create new pattern from the selection Δημιουργία μοτίβου από την επιλογή Create new shape from the current path Δημιουργία σχήματος από την τρέχουσα διαδρομή Create new snapshot Δημιουργία νέου στιγμιότυπου + From: Από: + Full Document Ολόκληρο έγγραφο + Merged Layers Συγχωνευμένα επίπεδα Create new style (from the selected type) Δημιουργία στυλ από τον επιλεγμένο τύπο Create new style from the selected layer Δημιουργία στυλ από το επιλεγμένο επίπεδο Current & Below Τρέχον και υποκείμενα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 46fb5e26d8..7c90e26cb7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1023,6 +1023,9 @@ Create new pattern from the selection Crear un motivo nuevo a partir de la selección Create new shape from the current path Crear una forma nueva a partir del trazado actual Create new snapshot Crear una instantánea nueva + From: De: + Full Document Documento completo + Merged Layers Capas combinadas Create new tool preset Crear un ajuste preestablecido de herramienta nuevo Crop Factor Factor de recorte Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9465fc2f47..11265f5919 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1008,6 +1008,9 @@ Create new pattern from the selection Créer un nouveau motif à partir de la sélection Create new shape from the current path Créer une nouvelle forme à partir du tracé actif Create new snapshot Créer un nouvel instantané + From: À partir de : + Full Document Document entier + Merged Layers Calques fusionnés Create new tool preset Créer un nouveau préréglage d'outil Crop Factor Facteur de recadrage Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e4e76aa163..2d0701365f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3898,6 +3898,9 @@ cameraRaw Yellow Sárga New document… ⌘N Új dokumentum… ⌘N New Layer from Brush Új réteg ecsetből New Path Új útvonal + From: Forrás: + Full Document Teljes dokumentum + Merged Layers Egyesített rétegek New Snapshot Új pillanatkép New Snapshot… Új pillanatkép… History Options… Előzménybeállítások… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b36d200a2f..4731d99ea9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1018,6 +1018,9 @@ Create new pattern from the selection Buat pola baru dari seleksi Create new shape from the current path Buat bentuk baru dari path saat ini Create new snapshot Buat snapshot baru + From: Dari: + Full Document Seluruh Dokumen + Merged Layers Layer Gabungan Create new tool preset Buat preset alat baru Crop Factor Faktor Crop Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index be74550523..910d53f755 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1018,6 +1018,9 @@ Create new pattern from the selection Crea nuovo pattern dalla selezione Create new shape from the current path Crea nuova forma dal tracciato corrente Create new snapshot Crea nuova istantanea + From: Da: + Full Document Documento intero + Merged Layers Livelli uniti Create new style (from the selected type) Crea nuovo stile (dal testo selezionato) Create new style from the selected layer Crea nuovo stile dal livello selezionato Create new tool preset Crea nuovo predefinito strumento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9229bea1d5..e97a838178 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1021,6 +1021,9 @@ Create new pattern from the selection 選択範囲から新規パターンを作成 Create new shape from the current path 現在のパスから新規シェイプを作成 Create new snapshot 新規スナップショットを作成 + From: 作成元: + Full Document ドキュメント全体 + Merged Layers 結合されたレイヤー Create new tool preset 新規ツールプリセットを作成 Crop Factor 切り抜き係数 Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 051338b9e9..ad79fa27a5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1016,6 +1016,10 @@ Create new pattern from the selection 선택 영역으로 새 패턴 만들기 Create new shape from the current path 현재 패스로 새 모양 만들기 Create new snapshot 새 스냅샷 만들기 + From: 원본: + Full Document 전체 문서 + Merged Layers 병합된 레이어 + New Snapshot 새 스냅샷 Create new style (from the selected type) 새 스타일 만들기(선택한 문자에서) Create new style from the selected layer 선택한 레이어로 새 스타일 만들기 Create new tool preset 새 도구 사전 설정 만들기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5328de32e3..f7ea472983 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1000,6 +1000,9 @@ Create new pattern from the selection Nieuw patroon maken van de selectie Create new shape from the current path Nieuwe vorm maken van het huidige pad Create new snapshot Nieuwe momentopname maken + From: Van: + Full Document Volledig document + Merged Layers Samengevoegde lagen Create new style (from the selected type) Nieuwe stijl maken (van de geselecteerde tekst) Create new style from the selected layer Nieuwe stijl maken van de geselecteerde laag Create new tool preset Nieuwe gereedschapsvoorinstelling maken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 097361e3da..ee968bc268 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1035,6 +1035,9 @@ Create new pattern from the selection Utwórz nowy wzór z zaznaczenia Create new shape from the current path Utwórz nowy kształt z bieżącej ścieżki Create new snapshot Utwórz nową migawkę + From: Z: + Full Document Cały dokument + Merged Layers Scalone warstwy Create new style (from the selected type) Utwórz nowy styl (z zaznaczonego tekstu) Create new style from the selected layer Utwórz nowy styl z zaznaczonej warstwy Create new tool preset Utwórz nowe ustawienie wstępne narzędzia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2452b14b2e..de3a0e4041 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1001,6 +1001,9 @@ Create new pattern from the selection Criar novo padrão a partir da seleção Create new shape from the current path Criar nova forma a partir do demarcador atual Create new snapshot Criar novo instantâneo + From: De: + Full Document Documento inteiro + Merged Layers Camadas mescladas Create new style (from the selected type) Criar novo estilo (a partir do texto selecionado) Create new style from the selected layer Criar novo estilo a partir da camada selecionada Create new tool preset Criar nova predefinição de ferramenta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e2eab9f4d2..7d319c2f1f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2911,6 +2911,9 @@ fontWeight Italic Курсив Create new document from current state Создать новый документ из текущего состояния Create new fill or adjustment layer Создать новый слой-заливку или корректирующий слой Create new snapshot Создать новый снимок + From: Из: + Full Document Весь документ + Merged Layers Объединённые слои Delete Cropped Pixels Удалить отсечённые пикселы Delete current state Удалить текущее состояние Delete layer Удалить слой diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index da7ed3937c..7977b74dd3 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -2287,6 +2287,9 @@ Create Snapshot Napravi snimak stanja Delete Snapshot Obriši snimak stanja New Snapshot Novi snimak stanja + From: Od: + Full Document Ceo dokument + Merged Layers Spojeni slojevi New Snapshot… Novi snimak stanja… History Options… Opcije istorije… Snapshot 1 Snimak stanja 1 diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 40f4270a51..b326be49c2 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2709,6 +2709,9 @@ cameraRaw Color Renk Color indicates Renk şunu gösterir: Create Snapshot Anlık Görüntü Oluştur Delete Snapshot Anlık Görüntüyü Sil + From: Kaynak: + Full Document Tam Belge + Merged Layers Birleştirilmiş Katmanlar New Snapshot Yeni Anlık Görüntü New Snapshot… Yeni Anlık Görüntü… History Options… Geçmiş Seçenekleri… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b54865285e..3ffdc6a692 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2762,6 +2762,9 @@ fontWeight Italic Курсивний Create new document from current state Створити новий документ із поточного стану Create new fill or adjustment layer Створити новий шар заливки або корекції Create new snapshot Створити новий знімок стану + From: З: + Full Document Увесь документ + Merged Layers Об'єднані шари Delete Cropped Pixels Видаляти обрізані пікселі Delete current state Видалити поточний стан diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0d5eec0d88..c57b787a58 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -981,6 +981,10 @@ Frame from Layers… Frame từ các lớp… Create new document from current state Tạo tài liệu mới từ trạng thái hiện tại Create new snapshot Tạo ảnh chụp trạng thái mới + From: Từ: + Full Document Toàn bộ tài liệu + Merged Layers Các lớp đã gộp + New Snapshot Ảnh chụp trạng thái mới Delete current state Xóa trạng thái hiện tại No properties Không có thuộc tính Hide Properties Ẩn Thuộc tính diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a459127233..12a51bd7b1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1045,6 +1045,10 @@ Create new pattern from the selection 从选区创建图案 Create new shape from the current path 从当前路径创建形状 Create new snapshot 创建快照 + From: 自: + Full Document 完整文档 + Merged Layers 合并的图层 + New Snapshot 新建快照 Create new tool preset 创建工具预设 Crop Factor 裁切系数 Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 83e1af1f46..1c87e95820 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1033,6 +1033,10 @@ Create new pattern from the selection 從選取範圍建立新圖樣 Create new shape from the current path 從目前路徑建立新形狀 Create new snapshot 建立新快照 + From: 自: + Full Document 完整文件 + Merged Layers 合併的圖層 + New Snapshot 新增快照 Create new tool preset 建立新工具預設集 Crop Factor 裁切係數 Ctrl Ctrl diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f416bc45f9..2d2b637268 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -212,6 +212,7 @@ pub mod slice_ui; pub mod smart_filter_dialog; pub mod smart_ui; pub mod snap_ui; +pub mod snapshot_dialog; pub(crate) mod solid_fill_ui; pub mod spring_tools; pub mod stack_dialog; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 808a7a8969..321692b9a4 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -3540,10 +3540,10 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { empty(ui, tl!("No document")); return; }; - let doc = st.doc.clone(); let entries = st.history.entries(); let current = entries.len() - 1; let redo: Vec = st.history.redo_labels().map(str::to_string).collect(); + let doc_id = st.doc.id; let source = photocraft_engine::history_source_cmds::source(st); let selected_snap = selected_snapshot(ui.ctx(), st); let spot = (doc.id, history_spot(st)); @@ -3553,20 +3553,6 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ctx.data_mut(|d| d.remove::(history_drag_key())); } let drag = ctx.data(|d| d.get_temp::(history_drag_key())); - // Snapshot row (Photoshop shows the document's opening state with a thumbnail). - { - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::hover()); - let thumb = Rect::from_min_size(pos2(rect.left() + 28.0, rect.center().y - 14.0), vec2(28.0, 28.0)); - let ctx = ui.ctx().clone(); - if let Some(layer) = doc.layers.first() { - widgets::checker(ui.painter(), thumb, 4.0); - let (tex, _) = app.layer_thumb(&ctx, &doc, layer); - ui.painter().image(tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); - } - ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside); - ui.painter().text(pos2(thumb.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &doc.name, egui::FontId::proportional(12.0), t.text); - ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); - } let mut snap_cmd = None; let mut target: Option = None; let mut set_source: Option = None; @@ -3633,7 +3619,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { target = Some(i); } else if resp.clicked() && selected_snap.is_some() { // The current state is already the document: clicking it only selects it. - ctx.data_mut(|d| d.remove::(selected_snapshot_key(doc.id))); + ctx.data_mut(|d| d.remove::(selected_snapshot_key(doc_id))); } } if follow && let Some(rect) = current_rect { @@ -3657,6 +3643,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::layer_transfer::ghost(&ctx, p, &label.unwrap_or_default()); } let mut footer_cmd: Option<(&str, Value)> = None; + let mut snapshot_dialog = false; if t.pro { // With a snapshot selected the trash deletes it, as in Photoshop (#5324). let can_delete = selected_snap.is_some() || app.session.is_enabled("history.deleteState"); @@ -3679,8 +3666,13 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } let can_snap = app.session.is_enabled("history.newSnapshot"); + // ⌥-click opens New Snapshot (name, From) instead, as in Photoshop. if ui.add_enabled_ui(can_snap, |ui| icons::button(ui, "scan", 26.0, false, tl!("Create new snapshot"))).inner.clicked() { - footer_cmd = Some(("history.newSnapshot", json!({}))); + if ui.input(|i| i.modifiers.alt) { + snapshot_dialog = true; + } else { + footer_cmd = Some(("history.newSnapshot", json!({}))); + } } if ui.add_enabled_ui(can_new, |ui| icons::button(ui, "file-plus", 26.0, false, tl!("Create new document from current state"))).inner.clicked() { footer_cmd = Some(("history.newDocument", json!({}))); @@ -3692,6 +3684,9 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // An open Free Transform owns Undo (transform_tool::intercept): stepping the document's history under // its box would leave it transforming pixels that changed. + if snapshot_dialog { + crate::snapshot_dialog::open(app); + } // Selecting a snapshot changes the document, so it waits for an open transform like the rows. let snap_cmd = snap_cmd.filter(|(cmd, _)| *cmd != "history.selectSnapshot" || app.ui.transform.is_none()); if let Some((cmd, p)) = footer_cmd.filter(|_| app.ui.transform.is_none()).or(snap_cmd) { @@ -5579,7 +5574,7 @@ mod history_transform_tests { let steps = h.state().session.active().unwrap().history.entries().len(); click(&mut h, b[1].0.center()); let st = h.state().session.active().unwrap(); - assert_eq!(st.snapshots.len(), 1, "the camera takes a snapshot"); + assert_eq!(st.snapshots.len(), 2, "the camera takes a snapshot, after the first one"); assert_eq!(st.history.entries().len(), steps, "which is not a history state"); let docs = h.state().session.documents().len(); click(&mut h, b[2].0.center()); @@ -5653,8 +5648,9 @@ mod snapshot_row_tests { h.state().session.active().unwrap().doc.layers.last().unwrap().surface().unwrap().rgba(1, 1) } + /// The names of the snapshots taken after the first one (the document as opened). fn snapshot_names(h: &Harness<'static, PhotocraftApp>) -> Vec { - h.state().session.active().unwrap().snapshots.iter().map(|s| s.name.clone()).collect() + h.state().session.active().unwrap().snapshots.iter().skip(1).map(|s| s.name.clone()).collect() } /// Snapshot rows (#2966) sit under the opening row: clicking one returns to it as a new @@ -5776,7 +5772,7 @@ mod snapshot_row_tests { let p = trash(&h); click(&mut h, p); let st = h.state().session.active().unwrap(); - assert!(st.snapshots.is_empty(), "the trash deleted the snapshot"); + assert_eq!(st.snapshots.len(), 1, "the trash deleted the snapshot (the first snapshot stays)"); assert_eq!(st.history.entries().len(), steps, "and left the states alone"); // An edit after the click deselects the snapshot: the trash deletes the state. @@ -5790,7 +5786,7 @@ mod snapshot_row_tests { let p = trash(&h); click(&mut h, p); let st = h.state().session.active().unwrap(); - assert_eq!(st.snapshots.len(), 1, "the snapshot is kept"); + assert_eq!(st.snapshots.len(), 2, "the snapshot is kept"); assert_eq!(st.history.entries().len(), steps - 1, "the current state is deleted"); } @@ -5803,7 +5799,7 @@ mod snapshot_row_tests { let to = trash(&h); drag(&mut h, egui::pos2(row.x, row.y), to); let st = h.state().session.active().unwrap(); - assert!(st.snapshots.is_empty(), "the dragged snapshot is deleted"); + assert_eq!(st.snapshots.len(), 1, "the dragged snapshot is deleted (the first snapshot stays)"); assert_eq!(st.history.entries().len(), steps, "no state is"); // The second-to-last state: it and the state after it go, as with Delete. @@ -5816,7 +5812,7 @@ mod snapshot_row_tests { drag(&mut h, egui::pos2(row.x, row.y), to); let st = h.state().session.active().unwrap(); assert_eq!(st.history.entries().len(), 1, "the dragged state and the ones after it are deleted"); - assert_eq!(st.snapshots.len(), 1, "the snapshot is kept"); + assert_eq!(st.snapshots.len(), 2, "the snapshot is kept"); } /// Snapshot rows scroll with the states: many snapshots in a short dock leave the footer and @@ -5840,6 +5836,78 @@ mod snapshot_row_tests { assert!(buttons.iter().all(|b| view.contains_rect(*b)), "footer in view: {buttons:?} in {view:?}"); } + /// The top row is the first snapshot, the document as opened: clicking it brings that back + /// (the Discord report on #2966: "History original file click does not work"). + #[test] + fn the_top_row_returns_to_the_document_as_opened() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + let opened = app.session.active().unwrap().doc.layers[0].surface().unwrap().rgba(1, 1); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let name = app.session.active().unwrap().doc.name.clone(); + let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app); + h.run_steps(3); + h.get_by_label(&name).click(); + h.run_steps(2); + let st = h.state().session.active().unwrap(); + assert_eq!(st.doc.layers[0].surface().unwrap().rgba(1, 1), opened); + assert_eq!(st.history.entries().last(), Some(&name)); + } + + /// ⌥-click on the camera opens New Snapshot (#2966): the name, selected so typing replaces + /// it, and From (Full Document, Merged Layers, Current Layer); OK takes the snapshot. + #[test] + fn alt_click_on_the_camera_opens_new_snapshot() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + history(app, ui); + crate::dialogs::show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.state_mut().ui.theme = crate::theme::ThemeKind::ProMedium; + h.run_steps(4); + let mut buttons: Vec = h + .ctx + .viewport(|v| v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(26.0, 26.0)).map(|w| w.rect).collect()); + buttons.sort_by(|a, b| b.center().x.total_cmp(&a.center().x)); + let camera = buttons[1].center(); + let alt = egui::Modifiers::ALT; + h.event(egui::Event::ModifiersChanged(alt)); + h.event(egui::Event::PointerMoved(camera)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: camera, button: egui::PointerButton::Primary, pressed, modifiers: alt }); + h.run_steps(1); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().snapshots.len(), 1, "⌥-click opens the dialog instead"); + assert!(h.state().ui.dialogs.last().is_some_and(|d| crate::snapshot_dialog::owns(&d.fields))); + h.get_by_role(egui::accesskit::Role::TextInput).type_text("Red layer only"); + h.run_steps(1); + h.get_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.accesskit_node().value().as_deref() == Some("Full Document")).unwrap().click(); + h.run_steps(3); + h.get_by_label("Current Layer").click(); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + let st = h.state().session.active().unwrap(); + let snap = st.snapshots.last().unwrap(); + assert_eq!(snap.name, "Red layer only"); + assert_eq!(snap.doc.layers.len(), 1, "only the current layer"); + assert!(h.state().ui.dialogs.is_empty()); + } + /// Renaming belongs to one document: snapshot ids restart in each, so switching tabs must not /// carry the edit over to the other document's snapshot with the same id. #[test] diff --git a/crates/ui-egui/src/snapshot_dialog.rs b/crates/ui-egui/src/snapshot_dialog.rs new file mode 100644 index 0000000000..3ee7553b84 --- /dev/null +++ b/crates/ui-egui/src/snapshot_dialog.rs @@ -0,0 +1,71 @@ +//! History › New Snapshot (⌥-click the History panel's camera button, #2966): Photoshop's dialog +//! for `history.newSnapshot`, with the snapshot's Name and what it is taken From (the full +//! document, its layers merged, or only the current layer). The command stays directly callable +//! with the same params by agents and Actions. + +use egui::{Align2, Sense, pos2, vec2}; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::theme::Tokens; + +pub const COMMAND: &str = "history.newSnapshot"; +const MARK: &str = "__newSnapshot"; + +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// Open the dialog on the active document, suggesting the name the camera button would give. +pub fn open(app: &mut PhotocraftApp) -> Option { + let name = photocraft_engine::history_cmds::next_snapshot_name(app.session.active()?); + let mut f = Map::new(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!(COMMAND)); + f.insert("__label".into(), json!("New Snapshot")); + f.insert("name".into(), json!(name)); + f.insert("from".into(), json!("fullDocument")); + Some(app.ui.open_dialog(crate::state::DialogKind::Command, f)) +} + +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + app.run(COMMAND, json!({"name": f.get("name"), "from": f.get("from")})) +} + +fn label(ui: &mut egui::Ui, text: &str) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(64.0, 22.0), Sense::hover()); + ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim); +} + +pub fn body(ui: &mut egui::Ui, f: &mut Map) { + ui.spacing_mut().item_spacing.y = 6.0; + ui.horizontal(|ui| { + label(ui, tl!("Name:")); + let mut name = f.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(260.0)); + // Opens on the name, selected, so typing replaces it (Photoshop). + if !ui.is_sizing_pass() && !f.contains_key("__named") { + r.request_focus(); + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { + let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(name.chars().count())); + state.cursor.set_char_range(Some(all)); + state.store(ui.ctx(), r.id); + } + f.insert("__named".into(), json!(true)); + } + f.insert("name".into(), json!(name)); + }); + ui.horizontal(|ui| { + label(ui, tl!("From:")); + let mut from = f.get("from").and_then(Value::as_str).unwrap_or("fullDocument").to_string(); + let opts = [ + ("fullDocument".to_string(), tl!("Full Document")), + ("mergedLayers".to_string(), tl!("Merged Layers")), + ("currentLayer".to_string(), tl!("Current Layer")), + ]; + if crate::widgets::dropdown(ui, "new-snapshot-from", &mut from, &opts, 170.0) { + f.insert("from".into(), json!(from)); + } + }); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0eea2d5c07..990def2fd6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -118,7 +118,7 @@ store expose and persist the same setting; scripts keep using canonical command | `layer.newAdjustmentLayer.hueSaturation` | `{"hue":30,"saturation":10}` | | `paint.stroke` | `{"points":[[x,y,pressure],…],"size":20,"color":"#ff0000"}` | | `select.rect` | `{"x":0,"y":0,"width":100,"height":50,"mode":"add","ellipse":false}` | -| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`), selection bounds | +| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened), selection bounds | | `layer.list` | `{"document":index?,"flat":bool?}`: just the layers, top-down: `id`, `name`, `kind`, `visible`, `bounds` (`[x,y,w,h]` or null), `selected`, `active`; groups list their `children`, or with `flat` every layer is one row with its `depth` and `parent` group id | | `document.pixel` | `{"x":10,"y":10}`: composite RGBA, four floats 0..1 (not 0..255) | | `document.presets.list` | `{}` → `{presets:[{name,settings}]}`: saved New Document configurations | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9ade01ddd9..f14a0f4252 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -231,7 +231,7 @@ Paragraph; the rest open as in-app floating windows. | Menu bar from the keyboard: Alt / F10 focus the bar, ← → ↓ ↩ drive it, Alt+letter opens a menu, underlined mnemonics run items | done | `menu_keys.rs`, #4988; macOS uses the native bar | | Every preference takes effect | partial | 46 of 149 do nothing (scorecard) | | UI scale presets | missing | UI-217-9, #2492 | -| History snapshots: camera button, snapshot rows (click returns and selects, rename, delete; the trash deletes the selected snapshot, and a snapshot or state dragged onto it, #5324), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`; New Snapshot dialog, first snapshot and History Options to come (#2966) | +| History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns and selects, rename, delete; the trash deletes the selected snapshot, and a snapshot or state dragged onto it, #5324), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; the snapshot History Options and History Brush sources to come (#2966) | | Themes: Photoshop's four greys | partial | five themes; #2661 | | Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 | | Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 | @@ -286,6 +286,7 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-12 | minor | Layers panel: Clip Thumbnails to Layer Bounds frames each layer's pixels instead of the canvas (#4281) | | 2026-10-12 | minor | Guides: ⌥-click turns a guide through the click; double-click opens Preferences › Guides, Grid & Slices | | 2026-10-13 | minor | Smart filter rows can be dragged up or down their stack to reorder the filters | +| 2026-10-12 | minor | History snapshots: the New Snapshot dialog (⌥-click the camera), and the first snapshot of the document as opened as the panel's top row (#2966) | | 2026-10-13 | minor | On-canvas corner radius widgets on live rectangles (TOOL-214-12) | | 2026-10-13 | minor | Curvature Pen edits the active path: drag anchors, click a segment to add, double-click smooth/corner, cursor badges | | 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) |