History panel: New Snapshot dialog and the first snapshot

Part of #2966. Every document starts with a snapshot of itself as
opened, named after it, as Photoshop does: the History panel's top row
is now that snapshot, so clicking it brings the opened document back as
one new state, even after History has dropped its oldest states.

Option-click on the camera button opens New Snapshot: Name (suggested
"Snapshot N", selected) and From (Full Document, Merged Layers, Current
Layer). "From:", "Full Document" and "Merged Layers" are translated in
all 16 catalogs, and "New Snapshot" in the 7 that lacked it.
This commit is contained in:
itsF4LCON committed 2026-10-11 19:10:02 +02:00
1 parent a564ea2c76
commit b00adf4287
24 files changed
+260 -30

No files matched your search

+31 -4
View File
@@ -99,6 +99,12 @@ fn snapshot_index(s: &Session, cmd: &str, p: &Value) -> Result<usize> {
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<Option<String>> {
match p.get("name") {
@@ -138,9 +144,9 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result<Value> {
_ => (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 }))
}
@@ -370,7 +376,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]
@@ -390,7 +397,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]
@@ -418,11 +425,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();
+11 -5
View File
@@ -213,8 +213,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<history_cmds::Snapshot>,
/// The id the next snapshot gets; ids are never reused, so deleting one keeps the others.
next_snapshot: u64,
@@ -224,9 +225,14 @@ impl DocState {
pub fn new(doc: Document, path: Option<String>) -> 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(),
@@ -244,7 +250,7 @@ impl DocState {
show_only: None,
floating: None,
color_samplers: Vec::new(),
snapshots: Vec::new(),
snapshots: vec![first],
next_snapshot: 1,
}
}
+2
View File
@@ -229,6 +229,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::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields),
DialogKind::Command if crate::delete_layer_prompt::owns(&fields) => crate::delete_layer_prompt::body(ui, &mut fields),
DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields),
@@ -464,6 +465,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
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::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields),
DialogKind::Command if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields),
DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields),
+4
View File
@@ -974,6 +974,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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -952,6 +952,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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -719,6 +719,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 Τρέχον και υποκείμενα
1 # Greek (el) PhotoCraft interface catalog.
719
720
721
722
723
724
725
726
727
+4
View File
@@ -960,6 +960,10 @@
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
New Snapshot Instantánea nueva
Create new tool preset Crear un ajuste preestablecido de herramienta nuevo
Crop Factor Factor de recorte
Ctrl Ctrl
Can't render this file because it contains an unexpected character in line 4 and column 47.
+3
View File
@@ -948,6 +948,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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -942,6 +942,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
Can't render this file because it contains an unexpected character in line 4 and column 47.
+4
View File
@@ -959,6 +959,10 @@
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
New Snapshot Nuova istantanea
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
1 # Italian (it) catalog. Columns, separated by a TAB: context <TAB> source <TAB> translation
959
960
961
962
963
964
965
966
967
968
+3
View File
@@ -961,6 +961,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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -934,6 +934,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 새 도구 사전 설정 만들기
1 # Korean (ko) catalog. UTF-8: context<TAB>English source<TAB>translation.
934
935
936
937
938
939
940
941
942
943
+3
View File
@@ -942,6 +942,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
Can't render this file because it contains an unexpected character in line 8 and column 34.
+3
View File
@@ -958,6 +958,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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -944,6 +944,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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2799,6 +2799,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 Удалить слой
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2656,6 +2656,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 Видалити поточний стан
Can't render this file because it contains an unexpected character in line 1348 and column 18.
+4
View File
@@ -962,6 +962,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
1 # Simplified Chinese (zh-hans) catalog. UTF-8, TAB-separated columns:
962
963
964
965
966
967
968
969
970
971
+4
View File
@@ -965,6 +965,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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -161,6 +161,7 @@ mod sizing;
pub mod slice_ui;
pub mod smart_ui;
pub mod snap_ui;
pub mod snapshot_dialog;
pub(crate) mod solid_fill_ui;
pub mod state;
pub mod stroke_constraint;
+86 -19
View File
@@ -2822,24 +2822,9 @@ 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<String> = st.history.redo_labels().map(str::to_string).collect();
// 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<isize> = None;
let all = entries.iter().map(|e| (e.clone(), false)).chain(redo.iter().map(|e| (e.clone(), true)));
@@ -2880,6 +2865,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
});
let mut footer_cmd: Option<&str> = None;
let mut snapshot_dialog = false;
if t.pro {
let can_delete = app.session.is_enabled("history.deleteState");
let can_new = app.session.is_enabled("history.newDocument");
@@ -2888,8 +2874,13 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
footer_cmd = Some("history.deleteState");
}
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");
if ui.input(|i| i.modifiers.alt) {
snapshot_dialog = true;
} else {
footer_cmd = Some("history.newSnapshot");
}
}
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");
@@ -2898,6 +2889,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.map(|c| (c, json!({}))).filter(|_| app.ui.transform.is_none()).or(snap_cmd)
@@ -4209,7 +4203,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());
@@ -4229,7 +4223,7 @@ mod history_transform_tests {
mod snapshot_row_tests {
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::*;
@@ -4238,8 +4232,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<String> {
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
@@ -4320,6 +4315,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<Rect> = 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]
+71
View File
@@ -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<String, Value>) -> 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<u64> {
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<String, Value>) -> Result<Value, String> {
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<String, Value>) {
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));
}
});
}
+1 -1
View File
@@ -101,7 +101,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 |
| `document.pixel` | `{"x":10,"y":10}`: composite RGBA |
| `document.presets.list` | `{}` → `{presets:[{name,settings}]}`: saved New Document configurations |
| `document.presets.save` | `{"name":"Product square","settings":{"width":1600,"height":1600,"background":"transparent"}}`: save a snapshot; names are trimmed, 1–255 characters, and ASCII case-insensitive duplicates are rejected |
+2 -1
View File
@@ -198,7 +198,7 @@ Paragraph; the rest open as in-app floating windows.
| Command palette with recents | done | UI-217-7 |
| 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, rename, delete), `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, rename, delete), `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 |
@@ -211,3 +211,4 @@ Paragraph; the rest open as in-app floating windows.
| 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions |
| 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning |
| 2026-10-11 | minor | History snapshots: the camera button takes one, snapshot rows return to it as a new state, rename and delete it (#2966) |
| 2026-10-11 | 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) |