Skip to content
Merged
153 changes: 144 additions & 9 deletions apps/rustgis/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,13 @@ struct Menus {
#[derive(Default)]
struct Menus {}

/// Preferences in `prefs.json` beside the platform's other app settings.
/// Preferences in `prefs.json` beside the platform's other app settings. Settings that can't be
/// read or saved are said in the window, not only logged: a setting that looks saved but isn't
/// would be lost silently when RustGIS closes.
mod prefs {
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};

use rustgis_ui_egui::Services;
use serde_json::{Map, Value};
Expand All @@ -45,28 +49,100 @@ mod prefs {
rustgis_engine::data::dirs::config_dir()
}

/// A problem with the preferences file, waiting for the window to say it.
#[derive(Debug, PartialEq)]
pub enum Notice {
/// The file couldn't be read: the defaults are in use.
Unreadable(String),
/// A malformed file was moved here, and new settings started in its place.
SetAside(PathBuf),
/// A setting couldn't be saved.
NotSaved(String),
}

static NOTICES: Mutex<Vec<Notice>> = Mutex::new(Vec::new());
/// Repeated equivalent failures stay quiet; changed recovery details must reach the window.
static LAST_FAILURE: Mutex<Option<String>> = Mutex::new(None);

/// The waiting notices; a panic while one was added doesn't lose the others.
fn notices() -> std::sync::MutexGuard<'static, Vec<Notice>> {
NOTICES.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// The saved preferences, or none when the file can't be read: said once a run.
fn read() -> Map<String, Value> {
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static WARNED: AtomicBool = AtomicBool::new(false);
rustgis_engine::prefs::read().unwrap_or_else(|error| {
if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
if !WARNED.swap(true, Ordering::Relaxed) {
log::warn!("{error}");
notices().push(Notice::Unreadable(error));
}
Map::new()
})
}

/// Keeps what a save came to for the window: a malformed file set aside (which also explains
/// an earlier read failure still waiting), or a failure whose outcome changed since last time.
pub fn saved(result: Result<Option<PathBuf>, String>) {
match result {
Ok(set_aside) => {
*LAST_FAILURE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
if let Some(path) = set_aside {
log::warn!("unreadable preferences set aside as {}", path.display());
let mut notices = notices();
notices.retain(|n| !matches!(n, Notice::Unreadable(_)));
notices.push(Notice::SetAside(path));
}
}
Err(error) => {
log::warn!("{error}");
let mut last = LAST_FAILURE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if last.as_deref() != Some(error.as_str()) {
*last = Some(error.clone());
notices().push(Notice::NotSaved(error));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AGENTS.md (medium confidence): the failed-save notice has no count.

AGENTS.md asks for "one notice per kind with a count" and for saying "what, how much and where". This notice is deduplicated to one per run of failures, but it does not say how many settings weren't saved, or which ones. The count could be kept in FAILING (for example an AtomicU32 of skipped saves) and reported when a save finally works, or included in the notice text. The test on lines 146–166 should then assert the count.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The warning covers the whole settings store: changes last only until the app closes, while the existing file is preserved. Repeated failed attempts can update the same key, so their count would not tell the user how many distinct settings are unsaved. Keeping one error per failure episode avoids repeated warnings without presenting a misleading loss count.

}
}
}
}

/// The problems since the last call, oldest first.
pub fn take_notices() -> Vec<Notice> {
std::mem::take(&mut *notices())
}

/// A save during logic or UI may queue a notice after this frame's drain. Ensure another
/// frame delivers it even when the user stops interacting with the window.
pub fn repaint_if_pending(ctx: &egui::Context) {
if !notices().is_empty() {
ctx.request_repaint();
}
}

/// A notice's text in the current language.
pub fn text(notice: &Notice) -> String {
use rustgis_ui_egui::i18n::fmt;
match notice {
Notice::Unreadable(error) => {
fmt("Your settings couldn't be read ({error}), so RustGIS is using its defaults.", &[("error", error)])
}
Notice::SetAside(path) => fmt(
"Your settings couldn't be read, so RustGIS started new ones. The old settings file was kept as {path}.",
&[("path", &path.display().to_string())],
),
Notice::NotSaved(error) => fmt("Settings could not be saved reliably ({error}).", &[("error", error)]),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quality (medium-low confidence): the not-saved notice drops the consequence that the module doc above it promises to convey.

The doc comment on this module says a setting that looks saved but isn't "would be lost silently when RustGIS closes". For a hard failure (write_at returned before replacing the file: read-only, disk full, permissions), the setting is not on disk at all and will be gone when the app closes. The text here says only "Settings could not be saved reliably (…)". "Reliably" suggests partial durability, not a change that is absent from disk, and the user is not told what happens next.

The durability case (the file was replaced but the directory sync failed) is a different outcome, and the wording here fits it. The two outcomes share one NotSaved(String) variant, so they can't get different text yet. A small fix: split the variant, e.g. NotSaved(String) for a failed write and NotDurable(String) for an unconfirmed flush, and let the failed-write text say the change "will be lost when RustGIS closes".

I'm not treating this as blocking. Raising it because the notice is the only signal the user gets.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The notice includes the operation's error, which distinguishes a failed replacement from an already-visible replacement whose durability is unconfirmed. Splitting the presentation into separate failed-write and unconfirmed-durability notices is left for the release quality pass, as a wording improvement. A blanket “lost when RustGIS closes” consequence would be inaccurate for the latter case.

}
}

/// The desktop's keychain and the preference hooks over `prefs.json`; saves report through
/// [`saved`].
pub fn services() -> Services {
let secrets: std::sync::Arc<dyn rustgis_engine::data::secrets::SecretStore> =
std::sync::Arc::new(rustgis_keychain::Keychain::default());
// The ChatGPT sign-in's tokens go to the same keychain (its accounts stay in the file).
rustgis_assistant::chatgpt::set_secret_store(Some(secrets.clone()));
Services {
load_pref: Some(Box::new(|key: &str| read().get(key).and_then(Value::as_str).map(str::to_string))),
save_pref: Some(Box::new(|key: &str, value: &str| {
if let Err(error) = rustgis_engine::prefs::write(key, value) {
log::warn!("{error}");
}
})),
save_pref: Some(Box::new(|key: &str, value: &str| saved(rustgis_engine::prefs::write(key, value)))),
secrets: Some(secrets),
..Services::default()
}
Expand Down Expand Up @@ -276,15 +352,22 @@ impl eframe::App for App {
}
self.0.ui.titlebar = titlebar;
}
// Settings that couldn't be read or saved, since the last frame.
for notice in prefs::take_notices() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug (medium confidence): a notice queued during a frame can stay hidden until another frame happens.

Saves run inside ui and logic, and this loop drains the queue at the top of the next logic call. The comment at line 339 says egui "repaints on events only", so after a click that triggers a failed save, nothing may request the frame that shows the notice. It can wait until the next pointer movement, or never appear.

Suggested fix: request a repaint when notices are waiting. Add a pending() helper next to take_notices (!notices().is_empty()), then in fn ui after self.0.ui(ui); add if prefs::pending() { ui.ctx().request_repaint(); }.

Worth checking in the headless ui_shot harness with a failing save, since that is the path the screenshots in this PR show.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c3e217b. Both desktop logic and UI request another frame when preference notices remain queued after their work. A failed save is therefore delivered without another input event. The regression settles an idle context, checks that a pending failure requests a frame, then checks that draining it lets the context settle again. Focused regression, full native CI, WebAssembly and hooks passed.

let text = prefs::text(&notice);
self.0.session.notify(text, true);
}
self.0.logic(ctx);
#[cfg(target_os = "macos")]
self.menus(ctx);
if self.0.quit_requested {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
prefs::repaint_if_pending(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.ui(ui);
prefs::repaint_if_pending(ui.ctx());
}
#[cfg(not(target_os = "macos"))]
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
Expand Down Expand Up @@ -620,7 +703,7 @@ fn main() -> eframe::Result {
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod tests {
use super::{backends, crash, flag, running};
use super::{backends, crash, flag, prefs, running};
use eframe::wgpu::Backends;

#[test]
Expand Down Expand Up @@ -711,6 +794,58 @@ mod tests {
assert!(super::recovery_store(Some(dir.join("fresh"))).is_ok());
}

#[test]
fn settings_that_cannot_be_saved_are_said_once_until_saving_works() {
use prefs::Notice;
// Clean saves say nothing.
prefs::saved(Ok(None));
assert_eq!(prefs::take_notices(), []);
// An idle window must get another frame when a save queues a notice late in a frame.
let ctx = egui::Context::default();
let frame = || {
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| prefs::repaint_if_pending(ui.ctx()));
output.textures_delta.clear();
};
for _ in 0..4 {
frame();
}
assert!(!ctx.has_requested_repaint(), "clean preferences keep the window idle");
// A full disk: said once, not for every setting that follows.
prefs::saved(Err("could not save preferences: no space left".into()));
prefs::saved(Err("could not save preferences: no space left".into()));
frame();
assert!(ctx.has_requested_repaint(), "the pending failure requests its delivery frame");
assert_eq!(prefs::take_notices(), [Notice::NotSaved("could not save preferences: no space left".into())]);
for _ in 0..4 {
frame();
}
assert!(!ctx.has_requested_repaint(), "draining the notice lets the window settle");
// Recovery can advance during a failure episode: do not retain obsolete instructions.
let changed =
"preferences were replaced, but their durability could not be confirmed; malformed preferences were kept at prefs.json.bad";
prefs::saved(Err(changed.into()));
assert_eq!(prefs::take_notices(), [Notice::NotSaved(changed.into())]);
prefs::saved(Err(changed.into()));
assert!(prefs::take_notices().is_empty(), "equivalent recovery outcomes stay quiet");
// Once a save works, the next failure is news again.
prefs::saved(Ok(None));
prefs::saved(Err("could not save preferences: read-only".into()));
assert_eq!(prefs::take_notices(), [Notice::NotSaved("could not save preferences: read-only".into())]);
prefs::saved(Ok(None));
// A malformed file set aside says where it went.
let bad = std::path::PathBuf::from("prefs.json.bad");
prefs::saved(Ok(Some(bad.clone())));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quality / test coverage (AGENTS.md "test both ways", medium-low confidence): the new startup notice is not covered. Nothing exercises read() pushing Notice::Unreadable, and nothing checks that saved(Ok(Some(..))) removes a waiting Unreadable (the retain on line 93). This test pushes SetAside directly, so the retain never runs against a waiting Unreadable.

A short addition would close it: push an Unreadable the way read() does, call saved(Ok(Some(path))), and assert that only SetAside remains.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is additional coverage for working notice behavior: startup queues Unreadable, and saved(Ok(Some(path))) removes it before queuing SetAside. Existing tests cover clean saves, failed-save suppression and recovery-path delivery. The additional queued-startup-notice assertion is left for the release quality pass.

assert_eq!(prefs::take_notices(), [Notice::SetAside(bad.clone())]);
let text = prefs::text(&Notice::SetAside(bad));
assert!(text.contains("prefs.json.bad"), "{text}");
// Both a failed replacement and an unconfirmed final flush give an accurate notice.
for error in ["could not save preferences: read-only", "preferences were replaced, but their durability could not be confirmed"] {
let text = prefs::text(&Notice::NotSaved(error.into()));
assert!(text.contains("Settings could not be saved reliably") && text.contains(error), "{text}");
assert!(!text.contains("changes last only until"), "{text}");
}
}

#[test]
fn crash_times_are_utc_dates() {
assert_eq!(crash::utc(0), "1970-01-01 00:00:00");
Expand Down
Loading
Loading