Autosave measurement points to the current project

This commit is contained in:
Dandaedre 2026-11-14 13:00:46 +01:00
parent 54832b3715
commit 1156edff33
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
5 changed files with 151 additions and 5 deletions

View File

@ -1235,6 +1235,7 @@ impl Editor {
) {
self.corner = c;
self.sync();
self.autosave_position_points();
}
}
let (name, horizontal, vertical) = match self.corner {
@ -1266,6 +1267,7 @@ impl Editor {
{
self.position_layer_point = independent.then_some(self.corner);
self.sync();
self.autosave_position_points();
}
if let Some(mut point) = self.position_layer_point {
ink.text(0.0, 396.0, "TO LAYER POINT", 11.0, palette.muted);
@ -1297,6 +1299,7 @@ impl Editor {
point = candidate;
self.position_layer_point = Some(point);
self.sync();
self.autosave_position_points();
}
}
let name = match point {

View File

@ -5,6 +5,7 @@ use std::path::PathBuf;
#[derive(Default)]
pub(super) struct FileUi {
project_path: Option<PathBuf>,
opening: Option<(PathBuf, Project)>,
writing: Option<(PathBuf, String)>,
message: Option<String>,
@ -108,10 +109,33 @@ impl Editor {
}
fn write_project_file(&mut self, path: PathBuf, contents: String, overwrite: bool) {
self.files.message = Some(match write_file(&path, contents.as_bytes(), overwrite) {
Ok(()) => format!("Saved {}", path.display()),
Ok(()) => {
if contents.trim_start().starts_with('{') && Project::from_json(&contents).is_ok() {
self.files.project_path = Some(path.clone());
}
format!("Saved {}", path.display())
}
Err(e) => format!("Could not save {}: {e}", path.display()),
});
}
/// Persist only measurement choices; other unsaved edits remain in memory.
pub(super) fn autosave_position_points(&mut self) {
let Some(path) = self.files.project_path.as_ref() else {
return;
};
let result = (|| {
let mut saved = Project::read(path)?;
saved.editor.position_point = self.corner;
saved.editor.position_layer_point = self.position_layer_point;
write_file(path, saved.to_json()?.as_bytes(), true)
})();
if let Err(error) = result {
self.files.message = Some(format!(
"Could not autosave measurement points to {}: {error}. Selections remain active; use Save project to save them.",
path.display()
));
}
}
pub(super) fn project_menu(&mut self, ui: &mut egui::Ui) {
if ui.button("Open project…").clicked() {
ui.close_menu();
@ -250,7 +274,10 @@ impl Editor {
});
if load {
self.files.message = Some(match self.install_project(ctx, project) {
Ok(()) => format!("Opened {}", path.display()),
Ok(()) => {
self.files.project_path = Some(path.clone());
format!("Opened {}", path.display())
}
Err(e) => format!("Cannot open project; current work kept: {e}"),
});
} else if open && !cancel {
@ -297,6 +324,111 @@ impl Editor {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn measurement_clicks_autosave_only_points_and_exports_keep_project_target() {
use super::super::tests::{click_text, frame, mouse};
let ctx = egui::Context::default();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("layout.json");
let mut app = Editor::default();
let saved = app.project();
app.write_project_file(path.clone(), saved.to_json().unwrap(), false);
assert_eq!(app.files.project_path.as_ref(), Some(&path));
app.files.message = None;
// Other local edits must not be silently saved with the point selection.
app.layout.nudge(15.0, 30.0).unwrap();
app.backdrop_title = "Unsaved title".into();
// Preserve unrelated changes already written by another editor as well.
let mut external = saved.clone();
external.editor.backdrop_title = "External title".into();
write_file(&path, external.to_json().unwrap().as_bytes(), true).unwrap();
app.sync();
frame(&mut app, &ctx, vec![]);
let output = frame(&mut app, &ctx, vec![]);
let pos = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == "MEASURE POSITION FROM" => {
Some(t.pos + Vec2::new(84.0, 75.0))
}
_ => None,
})
.unwrap();
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(&mut app, &ctx, vec![mouse(pos, false)]);
external.editor.position_point = PositionPoint::BottomRight;
assert_eq!(Project::read(&path).unwrap(), external);
click_text(&mut app, &ctx, "Use a different layer point");
external.editor.position_layer_point = Some(PositionPoint::BottomRight);
assert_eq!(Project::read(&path).unwrap(), external);
let output = frame(&mut app, &ctx, vec![]);
let pos = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == "TO LAYER POINT" => {
Some(t.pos + Vec2::new(46.0, 49.0))
}
_ => None,
})
.unwrap();
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(&mut app, &ctx, vec![mouse(pos, false)]);
external.editor.position_layer_point = Some(PositionPoint::Center);
assert_eq!(Project::read(&path).unwrap(), external);
click_text(&mut app, &ctx, "Use a different layer point");
external.editor.position_layer_point = None;
assert_eq!(Project::read(&path).unwrap(), external);
app.write_project_file(
dir.path().join("layout.svg"),
saved.to_svg(false).unwrap(),
false,
);
assert_eq!(app.files.project_path.as_ref(), Some(&path));
let mut reopened = Editor::default();
reopened
.install_project(&ctx, Project::read(&path).unwrap())
.unwrap();
assert_eq!(reopened.corner, PositionPoint::BottomRight);
assert_eq!(reopened.position_layer_point, None);
}
#[test]
fn point_autosave_requires_a_valid_existing_project_and_reports_failure() {
let mut app = Editor {
corner: PositionPoint::Center,
..Default::default()
};
app.autosave_position_points();
assert!(app.files.message.is_none());
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("broken.json");
std::fs::write(&path, "invalid project").unwrap();
app.files.project_path = Some(path.clone());
app.autosave_position_points();
assert!(
app.files
.message
.as_ref()
.unwrap()
.contains("Could not autosave")
);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "invalid project");
assert_eq!(app.corner, PositionPoint::Center);
std::fs::remove_file(&path).unwrap();
app.autosave_position_points();
assert!(!path.exists());
}
#[test]
fn opening_project_preserves_session_resize_choice() {
let ctx = egui::Context::default();

View File

@ -122,7 +122,14 @@ IDs; adding a layer consumes `next_layer_id`. Unused input slots are retained
to preserve shared-source references. Loading starts a fresh history. Loading requires a
replacement confirmation; failed loading leaves current work intact. Writes use
a same-directory temporary file and atomic publication. Existing destination
files require explicit replacement confirmation. A failed no-overwrite write
files require explicit replacement confirmation for Save/exports. Measurement-point
clicks and the independent-point toggle are an exception: they reread the current
project and atomically update only `editor.position_point` and
`editor.position_layer_point`, preserving its other stored values (including external edits).
Older schemas migrate to v9 on this write. No project path is stored in settings;
new documents require a first Save. SVG exports never change the active project path.
Missing/invalid/unwritable projects are left untouched and an error is shown;
active in-memory choices remain available for a manual Save. A failed no-overwrite write
leaves the existing file intact.
## Layer history and export scopes

View File

@ -301,8 +301,10 @@ For absolute center coordinates, choose screen **Top left** and layer **Center**
Changing points or turning the toggle off only updates the displayed offsets.
Numeric size and ratio edits keep the selected layer endpoint fixed. Screen-right
and screen-bottom origins keep their existing inward-positive signs; screen
center uses positive right/down. Both points and the toggle save with the project;
older projects open with matched points. Canvas guides show the chosen endpoints.
center uses positive right/down. Both points and the toggle autosave immediately to the opened or last-saved project.
Only these choices are written; other edits still need Save. For a new project,
save it once to establish its file. Write failures keep the selection active and show an error.
Older projects open with matched points. Canvas guides show the chosen endpoints.
### Displaying and entering aspect ratios

View File

@ -4,6 +4,8 @@
## Unreleased
- 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.
- Layer properties’ Layer tab applies size/locked-ratio changes immediately; remove its Apply button. Drag edits undo together; Source edits remain explicit.