Recover the last session automatically and add New project

This commit is contained in:
Dandaedre 2026-11-14 13:06:28 +01:00
parent 1156edff33
commit 2c4d8f1ed4
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
9 changed files with 575 additions and 10 deletions

View File

@ -13,6 +13,8 @@ mod preferences_ui;
mod project_ui;
#[path = "ratio_ui.rs"]
mod ratio_ui;
#[path = "recovery_ui.rs"]
mod recovery_ui;
#[path = "viewport_guides.rs"]
mod viewport_guides;
use format_ui::{FormatDraft, OutputDraft, PropertyTab};
@ -35,6 +37,7 @@ pub struct Editor {
device: device_ui::DeviceUi,
layer_ui: layers_ui::LayerUi,
settings: settings::Store,
recovery: recovery_ui::Recovery,
themes_open: bool,
preferences_open: bool,
snapping: midra_layout::snapping::Snapping,
@ -246,6 +249,7 @@ impl Default for Editor {
device: Default::default(),
layer_ui: Default::default(),
settings: settings::Store::default(),
recovery: recovery_ui::Recovery::default(),
themes_open: false,
preferences_open: false,
snapping: Default::default(),
@ -312,6 +316,15 @@ impl Editor {
pub(super) fn with_saved_settings(ctx: &egui::Context) -> Self {
let (store, saved) = settings::Store::open();
let mut editor = Self::with_settings(ctx, store, saved);
if let Some(path) = editor
.settings
.path
.as_ref()
.and_then(|p| p.parent())
.map(|p| p.join("last_project.json"))
{
editor.restore_recovery(ctx, path);
}
editor.device.try_startup_connection(ctx);
editor
}
@ -3105,7 +3118,10 @@ impl Editor {
self.apply_fields();
self.fields_closing = self.fields_pending();
}
let blocked = self.fields_closing
let blocked = self.files.new_requested
|| self.files.new_after_save
|| self.files.new_ready
|| self.fields_closing
|| self
.format_draft
.as_ref()
@ -3255,6 +3271,7 @@ impl Editor {
self.output_window(ctx);
self.formats_window(ctx);
self.project_windows(ctx);
self.new_project_window(ctx);
self.preferences_window(ctx);
self.device_window(ctx);
self.layers_window(ctx);
@ -3278,6 +3295,20 @@ impl Editor {
impl eframe::App for Editor {
fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
self.ui(ctx);
if !ctx.input(|i| i.pointer.any_down())
&& !self.layout.dragging()
&& self.pivot_drag.is_none()
{
self.autosave_recovery(false);
}
ctx.request_repaint_after(std::time::Duration::from_secs(2));
}
fn on_exit(&mut self, _: Option<&eframe::glow::Context>) {
self.layout.cancel_drag();
if let Some((_, before)) = self.pivot_drag.take() {
self.layout = before;
}
self.autosave_recovery(true);
}
}

View File

@ -5,13 +5,17 @@ use std::path::PathBuf;
#[derive(Default)]
pub(super) struct FileUi {
project_path: Option<PathBuf>,
pub(super) project_path: Option<PathBuf>,
pub(super) manual_saved_at: Option<u64>,
pub(super) new_requested: bool,
pub(super) new_after_save: bool,
pub(super) new_ready: bool,
opening: Option<(PathBuf, Project)>,
writing: Option<(PathBuf, String)>,
message: Option<String>,
pub(super) message: Option<String>,
}
impl Editor {
fn project(&self) -> Project {
pub(super) fn project(&self) -> Project {
let mut p = Project::from_layout(&self.layout);
p.editor.position_point = self.corner;
p.editor.position_layer_point = self.position_layer_point;
@ -33,7 +37,11 @@ impl Editor {
});
p
}
fn install_project(&mut self, ctx: &egui::Context, project: Project) -> Result<(), String> {
pub(super) fn install_project(
&mut self,
ctx: &egui::Context,
project: Project,
) -> Result<(), String> {
if self.device.sending {
return Err(
"Wait for the device send and readback before opening another project.".into(),
@ -64,6 +72,7 @@ impl Editor {
*self = Self {
device: std::mem::take(&mut self.device),
settings: std::mem::take(&mut self.settings),
recovery: std::mem::take(&mut self.recovery),
snapping: self.snapping,
resize_mode: self.resize_mode,
grid_tool: self.grid_tool,
@ -85,7 +94,7 @@ impl Editor {
self.sync();
Ok(())
}
fn save_project_as(&mut self) {
pub(super) fn save_project_as(&mut self) {
self.layout.finish_drag();
match self.project().to_json() {
Ok(contents) => {
@ -95,9 +104,14 @@ impl Editor {
.save_file()
{
self.queue_write(path, contents);
} else {
self.files.new_after_save = false;
}
}
Err(e) => self.files.message = Some(e),
Err(e) => {
self.files.new_after_save = false;
self.files.message = Some(e);
}
}
}
fn queue_write(&mut self, path: PathBuf, contents: String) {
@ -112,10 +126,18 @@ impl Editor {
Ok(()) => {
if contents.trim_start().starts_with('{') && Project::from_json(&contents).is_ok() {
self.files.project_path = Some(path.clone());
self.files.manual_saved_at = Some(recovery_ui::now_seconds());
if self.files.new_after_save {
self.files.new_ready = true;
self.files.new_after_save = false;
}
}
format!("Saved {}", path.display())
}
Err(e) => format!("Could not save {}: {e}", path.display()),
Err(e) => {
self.files.new_after_save = false;
format!("Could not save {}: {e}", path.display())
}
});
}
/// Persist only measurement choices; other unsaved edits remain in memory.
@ -137,6 +159,35 @@ impl Editor {
}
}
pub(super) fn project_menu(&mut self, ui: &mut egui::Ui) {
if ui
.add_enabled(!self.device.sending, egui::Button::new("New project…"))
.clicked()
{
self.files.new_requested = true;
ui.close_menu();
}
if let Some(error) = &self.recovery.error {
ui.colored_label(ui.visuals().error_fg_color, error);
}
if self.recovery.error.is_some() && ui.button("Retry recovery").clicked() {
if self.recovery.restore_failed {
if let Some(path) = self.recovery.path.clone() {
self.restore_recovery(ui.ctx(), path);
}
} else {
self.recovery.error = None;
self.autosave_recovery(true);
}
}
if let Some(path) = &self.recovery.path {
ui.small(if self.recovery.error.is_some() {
"Recovery autosave paused"
} else {
"Recovery autosave on · resumes on launch"
})
.on_hover_text(path.display().to_string());
}
ui.small(self.manual_save_age());
if ui.button("Open project…").clicked() {
ui.close_menu();
if let Some(path) = rfd::FileDialog::new()
@ -269,7 +320,8 @@ impl Editor {
let mut cancel = false;
egui::Window::new("Open project?").collapsible(false).open(&mut open).show(ctx,|ui| {
ui.label(path.display().to_string());
ui.label("Opening replaces the current work and undo history. Cancel and save the current project first if needed.");
ui.label("Opening replaces the current work, undo history and recovery autosave. Cancel and save a separate project first if needed.");
ui.label(self.manual_save_age());
ui.horizontal(|ui| {load=ui.button("Open project").clicked();cancel=ui.button("Cancel").clicked();});
});
if load {
@ -302,6 +354,8 @@ impl Editor {
self.write_project_file(path, contents, true);
} else if open && !cancel {
self.files.writing = Some((path, contents));
} else {
self.files.new_after_save = false;
}
}
if let Some(message) = self.files.message.take() {
@ -324,6 +378,32 @@ impl Editor {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_after_save_requires_success_and_does_not_count_autosave() {
let dir = tempfile::tempdir().unwrap();
let mut app = Editor::default();
app.files.new_after_save = true;
app.write_project_file(
dir.path().join("missing/layout.json"),
app.project().to_json().unwrap(),
false,
);
assert!(!app.files.new_ready);
assert!(!app.files.new_after_save);
assert!(app.files.manual_saved_at.is_none());
app.files.new_after_save = true;
app.write_project_file(
dir.path().join("layout.json"),
app.project().to_json().unwrap(),
false,
);
assert!(app.files.new_ready);
assert!(app.files.manual_saved_at.is_some());
let time = app.files.manual_saved_at;
app.autosave_position_points();
assert_eq!(app.files.manual_saved_at, time);
}
#[test]
fn measurement_clicks_autosave_only_points_and_exports_keep_project_target() {
use super::super::tests::{click_text, frame, mouse};

View File

@ -0,0 +1,272 @@
use super::*;
use midra_layout::project::{Project, write_file};
use serde::{Deserialize, Serialize};
use std::{
io::Read,
path::PathBuf,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Snapshot {
version: u32,
project: Project,
project_path: Option<PathBuf>,
manual_saved_at: Option<u64>,
}
#[derive(Default)]
pub(super) struct Recovery {
pub path: Option<PathBuf>,
last: Option<String>,
checked: Option<Instant>,
pub error: Option<String>,
pub restore_failed: bool,
}
pub(super) fn now_seconds() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
impl Editor {
pub(super) fn restore_recovery(&mut self, ctx: &egui::Context, path: PathBuf) {
self.recovery.path = Some(path.clone());
self.recovery.error = None;
self.recovery.restore_failed = false;
let result: Result<(), String> = (|| {
let file = match std::fs::File::open(&path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e.to_string()),
};
let mut bytes = Vec::new();
file.take(100 * 1024 * 1024 + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() > 100 * 1024 * 1024 {
return Err("Recovery file exceeds 100 MiB".into());
}
let snapshot: Snapshot = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
if snapshot.version != 1 {
return Err("Unsupported recovery version".into());
}
// Use the project loader to preserve its validation/migration contract.
let project = Project::from_json(
&serde_json::to_string(&snapshot.project).map_err(|e| e.to_string())?,
)?;
self.install_project(ctx, project)?;
self.files.project_path = snapshot.project_path;
self.files.manual_saved_at = snapshot.manual_saved_at;
Ok(())
})();
if let Err(error) = result {
self.recovery.restore_failed = true;
self.recovery.error = Some(format!(
"Recovery could not be restored: {error}. The file is preserved; save any work separately before retrying."
));
self.files.message = self.recovery.error.clone();
}
}
pub(super) fn autosave_recovery(&mut self, force: bool) {
if self.recovery.path.is_none() || self.recovery.error.is_some() {
return;
}
if !force
&& self
.recovery
.checked
.is_some_and(|t| t.elapsed() < Duration::from_secs(2))
{
return;
}
self.recovery.checked = Some(Instant::now());
let result: Result<(), String> = (|| {
let project = self.project();
project.layout()?;
let text = serde_json::to_string(&Snapshot {
version: 1,
project,
project_path: self.files.project_path.clone(),
manual_saved_at: self.files.manual_saved_at,
})
.map_err(|e| e.to_string())?;
if text.len() > 100 * 1024 * 1024 {
return Err("Recovery snapshot exceeds 100 MiB".into());
}
if self.recovery.last.as_ref() == Some(&text) {
return Ok(());
}
let path = self.recovery.path.as_ref().unwrap();
std::fs::create_dir_all(path.parent().ok_or("Recovery path has no parent")?)
.map_err(|e| e.to_string())?;
write_file(path, text.as_bytes(), true)?;
self.recovery.last = Some(text);
Ok(())
})();
if let Err(error) = result {
self.recovery.error = Some(format!(
"Recovery autosave failed: {error}. Use Save project to keep a separate copy."
));
self.files.message = self.recovery.error.clone();
}
}
pub(super) fn manual_save_age(&self) -> String {
match self.files.manual_saved_at {
Some(time) => {
let seconds = now_seconds().saturating_sub(time);
if seconds < 60 {
"Last manual save: less than a minute ago".into()
} else {
format!("Last manual save: {} minutes ago", seconds / 60)
}
}
None => "No recorded manual save for this project".into(),
}
}
pub(super) fn new_project_window(&mut self, ctx: &egui::Context) {
if self.files.new_ready {
self.files.new_ready = false;
match self.install_project(ctx, Project::from_layout(&Layout::default())) {
Ok(()) => {
self.recovery.error = None;
self.recovery.restore_failed = false;
self.autosave_recovery(true);
}
Err(error) => self.files.message = Some(error),
}
}
if !self.files.new_requested {
return;
}
let mut open = true;
let mut save = false;
let mut discard = false;
let mut cancel = false;
egui::Window::new("New project?").collapsible(false).open(&mut open).show(ctx, |ui| {
ui.label("Starting a new project replaces the recovery autosave. Current edits will be lost unless saved to a separate project file.");
ui.label(self.manual_save_age());
ui.small("Autosave does not count as a manual save. Only applied edits are saved; pending drafts will be discarded.");
ui.horizontal(|ui| {
save = ui.button("Save and create new…").clicked();
discard = ui.button("Discard and create new").clicked();
cancel = ui.button("Cancel").clicked();
});
});
if !open || cancel {
self.files.new_requested = false;
}
if discard {
self.files.new_requested = false;
self.files.new_ready = true;
ctx.request_repaint();
}
if save {
self.files.new_requested = false;
self.files.new_after_save = true;
self.save_project_as();
}
}
}
#[cfg(test)]
mod tests {
use super::super::tests::{click_text, frame};
use super::*;
#[test]
fn documented_recovery_example_loads() {
let ctx = egui::Context::default();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("last_project.json");
std::fs::write(
&path,
include_str!("../../../docs/interfaces/midra-layout-recovery-v1.example.json"),
)
.unwrap();
let mut app = Editor::default();
app.restore_recovery(&ctx, path);
assert!(app.recovery.error.is_none());
assert_eq!(app.project(), Project::from_layout(&Layout::default()));
}
#[test]
fn recovery_restores_applied_edits_metadata_and_leaves_named_file_alone() {
let ctx = egui::Context::default();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config/last_project.json");
let named = dir.path().join("named.json");
std::fs::write(&named, "leave untouched").unwrap();
let mut app = Editor::default();
app.restore_recovery(&ctx, path.clone());
app.files.project_path = Some(named.clone());
app.files.manual_saved_at = Some(now_seconds() - 180);
app.layout.nudge(40.0, -20.0).unwrap();
app.layout.set_layer_pivots(&[(1, [0.2, 0.7])]).unwrap();
app.corner = PositionPoint::BottomRight;
app.position_layer_point = Some(PositionPoint::Center);
app.backdrop_title = "Recovered conference".into();
app.autosave_recovery(true);
assert!(app.recovery.error.is_none());
assert_eq!(std::fs::read_to_string(&named).unwrap(), "leave untouched");
let first = std::fs::read(&path).unwrap();
app.autosave_recovery(true);
assert_eq!(std::fs::read(&path).unwrap(), first);
let mut restored = Editor::default();
restored.restore_recovery(&ctx, path);
assert!(restored.recovery.error.is_none());
assert_eq!(restored.project(), app.project());
assert_eq!(restored.files.project_path, Some(named));
assert_eq!(restored.files.manual_saved_at, app.files.manual_saved_at);
assert!(restored.manual_save_age().contains("3 minutes"));
restored.layout.undo();
assert_eq!(restored.project(), app.project());
}
#[test]
fn invalid_recovery_is_preserved_and_write_failure_keeps_last_snapshot() {
let ctx = egui::Context::default();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("last_project.json");
for text in ["broken", "{\"version\":999}"] {
std::fs::write(&path, text).unwrap();
let mut app = Editor::default();
let before = app.project();
app.restore_recovery(&ctx, path.clone());
assert!(app.recovery.error.is_some());
assert!(app.recovery.restore_failed);
assert_eq!(app.project(), before);
app.autosave_recovery(true);
assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
}
let mut app = Editor::default();
app.recovery.path = Some(path.join("impossible.json"));
app.autosave_recovery(true);
assert!(app.recovery.error.is_some());
assert_eq!(std::fs::read_to_string(path).unwrap(), "{\"version\":999}");
}
#[test]
fn new_project_cancel_preserves_work_and_discard_replaces_recovery() {
let ctx = egui::Context::default();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("last_project.json");
let mut app = Editor::default();
app.restore_recovery(&ctx, path.clone());
app.layout.nudge(123.0, 0.0).unwrap();
app.sync();
app.autosave_recovery(true);
let before = app.project();
app.files.new_requested = true;
click_text(&mut app, &ctx, "Cancel");
assert_eq!(app.project(), before);
app.files.new_requested = true;
click_text(&mut app, &ctx, "Discard and create new");
frame(&mut app, &ctx, vec![]);
assert_eq!(app.project(), Project::from_layout(&Layout::default()));
assert!(app.files.manual_saved_at.is_none());
let mut restored = Editor::default();
restored.restore_recovery(&ctx, path);
assert_eq!(restored.project(), app.project());
}
}

View File

@ -0,0 +1,114 @@
{
"version": 1,
"project": {
"format": "beffroi.midra-layout",
"version": 9,
"output_resolution": {
"width": 1920,
"height": 1080
},
"inputs": [
{
"id": 1,
"source_format": "sixteen_nine",
"native_resolution": {
"width": 1920,
"height": 1080
},
"input_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
}
},
{
"id": 2,
"source_format": "sixteen_nine",
"native_resolution": {
"width": 1920,
"height": 1080
},
"input_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
}
}
],
"layers": [
{
"id": 1,
"source_id": 1,
"bounds": {
"x": 120.0,
"y": 180.0,
"width": 640.0,
"height": 360.0
},
"advanced_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
},
"visible": true,
"locked": false,
"name": "Presenter",
"folder": "",
"midra_link": null,
"pivot": [
0.5,
0.5
]
},
{
"id": 2,
"source_id": 2,
"bounds": {
"x": 1160.0,
"y": 180.0,
"width": 640.0,
"height": 360.0
},
"advanced_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
},
"visible": true,
"locked": false,
"name": "Slides",
"folder": "",
"midra_link": null,
"pivot": [
0.5,
0.5
]
}
],
"reference": null,
"editor": {
"backdrop_title": "Example Conference Name",
"selected_layer_ids": [
2
],
"position_point": "top_left",
"keep_aspect_ratio": true,
"viewport_zoom": 1.0,
"viewport_pan": [
0.0,
0.0
],
"show_source_pattern": false,
"show_toolbar_icon_names": false,
"outline_layers": false,
"position_layer_point": null
},
"next_layer_id": 3
},
"project_path": null,
"manual_saved_at": null
}

View File

@ -0,0 +1,38 @@
# Midra Layout recovery, version 1
`last_project.json` lives beside the per-user `settings.json` (see
[settings paths](midra-layout-settings.md)). It is an internal UTF-8 JSON envelope,
not a named project export. Headless/default editors never access this path.
| Field | Meaning |
| --- | --- |
| `version` | Integer `1`; other versions rejected |
| `project` | Complete [project v9](midra-layout.md), including embedded reference bytes; its units, precision and validation apply without display rounding |
| `project_path` | Last opened/successfully saved named JSON path, or null; SVG exports do not change it |
| `manual_saved_at` | Unix UTC seconds of the last successful explicit project save, or null when unknown; recovery and measurement-point autosaves do not update it |
Unknown envelope fields and files over 100 MiB are rejected. Project validation
and reference decoding must succeed before replacing the editor. No file at
`project_path` is opened during recovery; it identifies the target for subsequent
measurement-point autosaves. The startup device connection remains governed by
application settings, not recovery.
Checkpoints run at most every two seconds, outside active pointer/resize gestures,
and on normal exit. Identical snapshots are skipped. Writes use the existing
same-directory temporary-file, file-sync and atomic replacement helper. A failed
write leaves the previous file intact and pauses retries until requested. Invalid
startup recovery is preserved; Retry reloads it, while explicitly starting New
project permits replacement. Multiple app instances share this single slot;
last successful writer wins.
Recovery retains applied values only: no undo history, pending text/format/import
drafts, transient tools, or credentials. A normal exit cancels unfinished canvas
gestures before the final checkpoint. The schema does not replace named project
JSON: Save continues to emit a bare project v9 document. Opening/New replaces the
single recovery slot; New warns with the manual-save age and Save/Discard/Cancel.
A failed or cancelled manual save never completes Save-and-create-new.
[Complete recovery example](midra-layout-recovery-v1.example.json) is exercised by the startup regression test.
Future breaking envelope changes require a version bump and explicit migration
or rejection. Recovery is not an interchange format; use Save for portable files.

View File

@ -122,3 +122,5 @@ center), active independently of `snapping.enabled` within the same six-logical-
radius. Anchors take priority over active grids and configured edge/pixel snapping.
Alt bypasses these anchors and grids while inverting configured snapping as usual.
This adds no settings fields; pivot positions are saved per layer in projects.
Recovery autosave is a separate `last_project.json` beside settings, not a settings field. See [recovery format](midra-layout-recovery.md).

View File

@ -204,3 +204,5 @@ screen. Destination choices display both IDs. Browsing another screen does not
retarget existing links; choosing a destination there explicitly replaces that
layer's saved link. Direct send/load actions use each layer's saved screen,
independently of the screen currently displayed in the configuration window.
Automatic session recovery wraps this project representation in a separate [recovery file](midra-layout-recovery.md); named project JSON remains version 9.

View File

@ -519,7 +519,7 @@ Reference display, camera, theme and preference controls already apply immediate
Device destination links also save to the local document immediately. Device
sends remain explicit: closing export configuration never sends, and local
Apply/Discard prompts never write to Midra. This does not change project save or
application-exit behavior; save the project to retain applied edits across launches.
application-exit behavior. Applied edits recover automatically on launch; use Save project for a separate named copy.
While adjusting a layer crop, click empty canvas or another layer to leave crop
mode and select normally. Clicking or dragging the visible image or its faded
@ -832,3 +832,27 @@ screen. Destination choices display both IDs. Browsing another screen does not
retarget existing links; choosing a destination there explicitly replaces that
layer's saved link. Direct send/load actions use each layer's saved screen,
independently of the screen currently displayed in the configuration window.
### Recovery autosave and New project
Applied edits and the reference image are checkpointed to `last_project.json`
beside the application settings, at most every two seconds between gestures and
again on normal exit. The last session resumes automatically on launch without
an Open dialog. Unchanged snapshots are not rewritten. Named project files remain
explicit saves (measurement-point autosave still updates its two fields).
**Project → New project…** starts the default layout after confirmation. The warning
shows the last recorded manual-save age; autosave does not count. Choose **Save and
create new…**, **Discard and create new**, or **Cancel**. Cancelling a save or a
failed save keeps the current project. Opening another project also replaces the
recovery copy, so save a named copy when you want to keep multiple projects.
Recovery contains applied project values, not undo history or unfinished text,
Source/import drafts. A crash can lose edits since the last checkpoint; normal
exit cancels unfinished canvas gestures. Project-menu status shows the recovery
path and failures. A corrupt/unsupported recovery file is preserved with autosave
paused; Retry recovery attempts to load it again. For a write failure, Retry
attempts to save again. New project explicitly replaces the recovery copy.
See the [recovery file contract](interfaces/midra-layout-recovery.md).

View File

@ -4,6 +4,8 @@
## Unreleased
- Recover the last session automatically from a separate two-second autosave; named saves stay explicit. New project offers Save/Discard/Cancel and shows the last manual-save age. Failed/corrupt recovery is reported and preserved.
- Measurement-point choices and the independent-point toggle autosave to the current project file; other unsaved edits remain untouched. New projects need a first Save.
- Separate Select (V, previous behavior) from Move (M), which drags the existing selection without selecting, deselecting or resizing.