diff --git a/.github/web-build/test_bundle_demo.py b/.github/web-build/test_bundle_demo.py index c47b5f7e4..1539b1e49 100644 --- a/.github/web-build/test_bundle_demo.py +++ b/.github/web-build/test_bundle_demo.py @@ -47,7 +47,7 @@ def test_rejects_a_demo_generated_for_a_different_release(self) -> None: def test_first_run_installs_only_the_html_edition_at_the_notebook_root(self) -> None: patch = (self.root / ".github" / "web-build" / "web.diff").read_text(encoding="utf-8") - self.assertIn("with_welcome_notebook_setup(|_root, format| install_edition(format))", patch) + self.assertIn("with_welcome_notebook_setup(|_root, format, _expected| install_edition(format))", patch) self.assertIn('session.settings.set("privacy_welcome_seen", "true")', patch) self.assertIn('relative.strip_prefix(format)', patch) self.assertIn("Ok(Some(notebook.to_string_lossy().into_owned()))", patch) diff --git a/.github/web-build/web.diff b/.github/web-build/web.diff index a2ae9af0f..02af23c1c 100644 --- a/.github/web-build/web.diff +++ b/.github/web-build/web.diff @@ -594,7 +594,7 @@ index 0000000..f4394fb + let session = Session::new(Path::new(ROOT), Settings::at(SETTINGS)).map_err(|e| e.to_string())?; + // The web demo has no first-use wizard: mark it seen, so it never opens here. + session.settings.set("privacy_welcome_seen", "true").map_err(|e| e.to_string())?; -+ let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_root, format| install_edition(format)); ++ let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_root, format, _expected| install_edition(format)); + if !persist { + app = app.with_session_only_storage(); + } diff --git a/Cargo.lock b/Cargo.lock index 2832e6491..215c612c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4003,6 +4003,7 @@ dependencies = [ "notecraft-model", "notecraft-ocr", "notecraft-proofing", + "notecraft-setup", "notecraft-store", "notecraft-text", "rfd", diff --git a/android/src/activity.rs b/android/src/activity.rs index 3ad0a1973..21e65dae3 100644 --- a/android/src/activity.rs +++ b/android/src/activity.rs @@ -71,8 +71,10 @@ fn run(app: AndroidApp) -> Result<(), String> { let setup_payload: PathBuf = payload.clone(); let mut app = NoteCraftApp::new(session) .with_default_notebooks_root(layout.notebooks) - .with_welcome_notebook_setup(move |notebooks_root, format| { - notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map_err(|error| error.to_string()) + .with_welcome_notebook_setup(move |notebooks_root, format, expected_manifest| match expected_manifest { + Some(expected) => notecraft_setup::install_edition_if_unchanged(&setup_payload, notebooks_root, format, expected) + .map_err(|error| error.to_string()), + None => notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map(Some).map_err(|error| error.to_string()), }) .with_clipboard(clipboard); for (key, message) in alerts.drain(..) { diff --git a/apps/notecraft-setup/src/lib.rs b/apps/notecraft-setup/src/lib.rs index a3b9ab614..3aa1d5ea7 100644 --- a/apps/notecraft-setup/src/lib.rs +++ b/apps/notecraft-setup/src/lib.rs @@ -1,3 +1,4 @@ +use notecraft_store::{TreeSnapshot, file_hash, snapshot_tree, tree_manifest}; use std::io; use std::path::{Path, PathBuf}; @@ -15,6 +16,29 @@ pub fn macos_dmg_payload(executable: &Path) -> Option { /// notebook folder, so the notebook list finds it. Other notebooks in `notebooks_root` are never /// visited or changed. Returns the installed notebook folder. pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> io::Result { + match install_guarded(payload, notebooks_root, format, None)? { + Some(installed) => Ok(installed), + None => Err(io::Error::new(io::ErrorKind::Other, "the install reported no replacement")), + } +} + +/// Installs one generated edition, but only when the installed tree still matches +/// `expected_manifest`, the manifest recorded when it was installed. A note that landed +/// in the tree while the new edition was staged is never silently replaced: the install +/// reports no replacement and the installed tree is left as it was, so the caller can +/// ask the person instead. Returns the installed notebook folder, or `None` when the +/// tree changed. +pub fn install_edition_if_unchanged(payload: &Path, notebooks_root: &Path, format: &str, expected_manifest: &str) -> io::Result> { + install_guarded(payload, notebooks_root, format, Some(expected_manifest)) +} + +/// The shared install: stages the new edition, then swaps it in for the installed +/// tree. With an expected manifest, the installed tree must still match it when the +/// swap happens. The tree is checked once the staging copy is done, and the displaced +/// tree is checked again after the swap, before its backup is deleted: a write that +/// landed between the first check and the swap is caught by the second check, and the +/// previous tree is restored. A tree that cannot be read counts as changed. +fn install_guarded(payload: &Path, notebooks_root: &Path, format: &str, expected_manifest: Option<&str>) -> io::Result> { validate_edition(payload, format)?; let destination = notebooks_root.join(NOTEBOOK_NAME); if std::fs::symlink_metadata(&destination).is_ok_and(|metadata| metadata.file_type().is_symlink()) { @@ -29,6 +53,13 @@ pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> i return Err(error); } let had_previous = destination.exists(); + if had_previous && let Some(expected) = expected_manifest { + let unchanged = tree_manifest(&destination).is_ok_and(|current| current == expected); + if !unchanged { + remove_tree_if_present(&staging); + return Ok(None); + } + } if had_previous && let Err(error) = rename_with_retry(&destination, &backup) { // On Windows a folder cannot be moved while a file under it is open, by NoteCraft // itself, a virus scanner, a search indexer or a sync client: "Access is denied" @@ -38,9 +69,19 @@ pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> i remove_tree_if_present(&staging); return Err(error); } - let replaced = replace_in_place(&staging, &destination); + let snapshot = match expected_manifest { + Some(_) => match snapshot_tree(&destination) { + Ok(snapshot) => Some(snapshot), + Err(_) => { + remove_tree_if_present(&staging); + return Ok(None); + } + }, + None => None, + }; + let replaced = replace_in_place(&staging, &destination, snapshot.as_ref())?; remove_tree_if_present(&staging); - return replaced.map(|()| destination); + return Ok(replaced.then_some(destination)); } if let Err(error) = rename_with_retry(&staging, &destination) { if had_previous { @@ -49,8 +90,38 @@ pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> i remove_tree_if_present(&staging); return Err(error); } - remove_tree_if_present(&backup); - Ok(destination) + if had_previous { + match expected_manifest { + Some(expected) => { + let unchanged = tree_manifest(&backup).is_ok_and(|current| current == expected); + if unchanged { + remove_tree_if_present(&backup); + } else { + restore_displaced(&destination, &backup, notebooks_root)?; + return Ok(None); + } + } + None => remove_tree_if_present(&backup), + } + } + Ok(Some(destination)) +} + +/// Moves the displaced tree back over a replacement that must not stand: the new +/// tree goes aside first, the displaced tree moves back, then the new tree is +/// dropped. When a move fails the displaced tree is left in place for recovery +/// and the failure is reported instead of deleting anything. +fn restore_displaced(destination: &Path, backup: &Path, notebooks_root: &Path) -> io::Result<()> { + let discarded = notebooks_root.join(format!(".{NOTEBOOK_NAME}-discarded-{}", unique_suffix())); + if rename_with_retry(destination, &discarded).is_err() || rename_with_retry(backup, destination).is_err() { + let _ = rename_with_retry(&discarded, destination); + return Err(io::Error::new( + io::ErrorKind::Other, + "the Welcome notebook changed while the update was prepared and the previous copy could not be restored; the previous copy is kept beside the notebooks folder", + )); + } + remove_tree_if_present(&discarded); + Ok(()) } /// Renames, trying again for a few seconds while the system refuses with "Access is denied". @@ -75,25 +146,48 @@ fn rename_with_retry(from: &Path, to: &Path) -> io::Result<()> { /// Makes `destination` hold exactly what `staging` holds, without moving `destination` itself: /// every staged file is written over its counterpart, and what the new edition no longer has is /// removed. A file that cannot be removed is left; a file that cannot be written fails the install. -fn replace_in_place(staging: &Path, destination: &Path) -> io::Result<()> { +/// +/// With a snapshot, the destination is checked before each file is written over, before a +/// directory or file is removed to make way for the other kind, and before the new edition's +/// leftovers are removed: a note that landed while the new edition was staged stops the +/// replacement at once instead of being overwritten or removed. The tree is then left partly +/// replaced, so the caller can ask the person instead of silently finishing. Returns false +/// in that case. +fn replace_in_place(staging: &Path, destination: &Path, snapshot: Option<&TreeSnapshot>) -> io::Result { + replace_dir(staging, destination, Path::new(""), snapshot) +} + +fn replace_dir(staging: &Path, destination: &Path, relative: &Path, snapshot: Option<&TreeSnapshot>) -> io::Result { let mut wanted = std::collections::HashSet::new(); for entry in std::fs::read_dir(staging)? { let entry = entry?; let name = entry.file_name(); let target = destination.join(&name); + let entry_relative = relative.join(&name); wanted.insert(name); if entry.file_type()?.is_dir() { if target.is_file() { + if snapshot.is_some_and(|guard| !target_still_matches(guard, &target, &entry_relative)) { + return Ok(false); + } std::fs::remove_file(&target)?; } if !target.is_dir() { std::fs::create_dir(&target)?; } - replace_in_place(&entry.path(), &target)?; + if !replace_dir(&entry.path(), &target, &entry_relative, snapshot)? { + return Ok(false); + } } else { if target.is_dir() { + if snapshot.is_some_and(|guard| !subtree_still_matches(guard, &target, &entry_relative)) { + return Ok(false); + } std::fs::remove_dir_all(&target)?; } + if target.exists() && snapshot.is_some_and(|guard| !target_still_matches(guard, &target, &entry_relative)) { + return Ok(false); + } make_writable(&target); write_over(&entry.path(), &target)?; } @@ -103,10 +197,64 @@ fn replace_in_place(staging: &Path, destination: &Path) -> io::Result<()> { if wanted.contains(&entry.file_name()) { continue; } + let entry_relative = relative.join(entry.file_name()); + if let Some(snapshot) = snapshot { + if !snapshot.contains(&entry_relative) { + continue; + } + let path = entry.path(); + if entry.file_type().is_ok_and(|kind| kind.is_dir()) { + if !subtree_still_matches(snapshot, &path, &entry_relative) { + return Ok(false); + } + } else if entry.file_type().is_ok_and(|kind| kind.is_file()) && !target_still_matches(snapshot, &path, &entry_relative) { + return Ok(false); + } + } let path = entry.path(); let _ = if entry.file_type().is_ok_and(|kind| kind.is_dir()) { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) }; } - Ok(()) + Ok(true) +} + +/// Whether the file at `target` still holds what the snapshot recorded for +/// `relative`: it must be there, be a regular file, and hash the same. +/// Anything else, a new file, a changed file, a file that cannot be read, +/// counts as changed, never as untouched. +fn target_still_matches(snapshot: &TreeSnapshot, target: &Path, relative: &Path) -> bool { + let Some(expected) = snapshot.file_hash(relative) else { + return false; + }; + file_hash(target).is_ok_and(|current| current == expected) +} + +/// Whether everything under `dir` still holds what the snapshot recorded for +/// `relative`: every file hashes the same and nothing was added. A directory +/// that cannot be listed counts as changed. +fn subtree_still_matches(snapshot: &TreeSnapshot, dir: &Path, relative: &Path) -> bool { + let Ok(entries) = std::fs::read_dir(dir) else { + return false; + }; + for entry in entries { + let Ok(entry) = entry else { + return false; + }; + let entry_relative = relative.join(entry.file_name()); + if !snapshot.contains(&entry_relative) { + return false; + } + let Ok(kind) = entry.file_type() else { + return false; + }; + if kind.is_dir() { + if !subtree_still_matches(snapshot, &entry.path(), &entry_relative) { + return false; + } + } else if kind.is_file() && !target_still_matches(snapshot, &entry.path(), &entry_relative) { + return false; + } + } + true } /// Writes `source` over `target` through the file's own contents, never by deleting or replacing @@ -325,7 +473,7 @@ mod tests { copy_tree(&source.join("html"), &staging).expect("stage the new edition"); fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); - replace_in_place(&staging, &destination).expect("replace in place"); + assert!(replace_in_place(&staging, &destination, None).expect("replace in place"), "an unguarded replacement replaces the tree"); assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("welcome page"), b"new welcome"); assert!(destination.join("_node.toml").is_file()); @@ -347,7 +495,7 @@ mod tests { copy_tree(&source.join("html"), &staging).expect("stage the new edition"); fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); - replace_in_place(&staging, &destination).expect("replace in place"); + assert!(replace_in_place(&staging, &destination, None).expect("replace in place"), "an unguarded replacement replaces the tree"); assert_eq!(fs::read(&page).expect("welcome page"), b"new welcome"); } @@ -418,4 +566,91 @@ mod tests { assert_eq!(install_edition(&source, ¬ebooks, "docx").expect_err("reject unknown format").kind(), io::ErrorKind::InvalidInput); assert!(!notebooks.join(NOTEBOOK_NAME).exists()); } + + fn assert_no_leftovers(notebooks: &Path) { + let leftovers: Vec<_> = fs::read_dir(notebooks) + .expect("notebooks folder") + .filter_map(Result::ok) + .filter(|entry| entry.file_name().to_string_lossy().starts_with('.')) + .collect(); + assert!(leftovers.is_empty(), "no staging or backup folder is left behind: {leftovers:?}"); + } + + #[test] + fn guarded_install_replaces_a_matching_tree() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + fs::write(source.join("html/00-start/welcome/index.html"), "updated HTML").expect("update payload"); + let manifest = notecraft_store::tree_manifest(&destination).expect("manifest"); + + assert_eq!( + install_edition_if_unchanged(&source, ¬ebooks, "html", &manifest).expect("guarded install"), + Some(destination.clone()), + "a tree that still matches its manifest is replaced" + ); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("new page"), b"updated HTML"); + assert_no_leftovers(¬ebooks); + } + + #[test] + fn guarded_install_refuses_a_changed_tree_and_keeps_it() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let manifest = notecraft_store::tree_manifest(&destination).expect("manifest"); + fs::write(destination.join("00-start/welcome/index.html"), "my notes").expect("edit"); + fs::write(source.join("html/00-start/welcome/index.html"), "updated HTML").expect("update payload"); + + assert_eq!( + install_edition_if_unchanged(&source, ¬ebooks, "html", &manifest).expect("guarded install"), + None, + "a tree that changed since its manifest was recorded is not replaced" + ); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("kept page"), b"my notes"); + assert_no_leftovers(¬ebooks); + } + + #[test] + fn guarded_install_refuses_a_tree_with_an_added_file() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let manifest = notecraft_store::tree_manifest(&destination).expect("manifest"); + fs::write(destination.join("my-note.txt"), "my note").expect("added file"); + + assert_eq!( + install_edition_if_unchanged(&source, ¬ebooks, "html", &manifest).expect("guarded install"), + None, + "an added file changes the tree, so it is not replaced" + ); + assert_eq!(fs::read(destination.join("my-note.txt")).expect("kept note"), b"my note"); + assert_no_leftovers(¬ebooks); + } + + #[test] + fn guarded_in_place_replacement_stops_when_a_file_changes() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let staging = notebooks.join("staged"); + fs::create_dir_all(&staging).expect("staging folder"); + copy_tree(&source.join("html"), &staging).expect("stage the new edition"); + fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); + let snapshot = notecraft_store::snapshot_tree(&destination).expect("snapshot"); + fs::write(destination.join("00-start/welcome/index.html"), "my notes").expect("a note that lands during staging"); + + assert!(!replace_in_place(&staging, &destination, Some(&snapshot)).expect("guarded replacement"), "a changed file stops the replacement"); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("kept page"), b"my notes"); + } + + #[test] + fn guarded_in_place_replacement_replaces_an_unchanged_tree() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let staging = notebooks.join("staged"); + fs::create_dir_all(&staging).expect("staging folder"); + copy_tree(&source.join("html"), &staging).expect("stage the new edition"); + fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); + let snapshot = notecraft_store::snapshot_tree(&destination).expect("snapshot"); + + assert!(replace_in_place(&staging, &destination, Some(&snapshot)).expect("guarded replacement"), "an unchanged tree is replaced"); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("new page"), b"new welcome"); + } } diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index 8bf1c627d..3b7c6d853 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -341,10 +341,16 @@ fn main() -> eframe::Result { Box::new(move |cc| { let setup_payload = payload.clone(); let mut app = NoteCraftApp::new(session) - .with_welcome_notebook_setup(move |notebooks_root, format| { - notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map_err(|error| error.to_string()) + .with_welcome_notebook_setup(move |notebooks_root, format, expected_manifest| match expected_manifest { + Some(expected) => notecraft_setup::install_edition_if_unchanged(&setup_payload, notebooks_root, format, expected) + .map_err(|error| error.to_string()), + None => notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map(Some).map_err(|error| error.to_string()), }) .with_clipboard(clipboard); + // A newer bundled Welcome notebook replaces the installed copy when it is + // untouched, or asks once when it was changed. First-use setup is untouched: + // the wizard asks about the notebook itself. + app.check_welcome_notebook_update(env!("CARGO_PKG_VERSION")); for (key, message) in startup_alerts.drain(..) { app.alert(key, "NoteCraft", &message); } diff --git a/crates/store/src/lib.rs b/crates/store/src/lib.rs index 4c6f61bdc..ac2bd16b4 100644 --- a/crates/store/src/lib.rs +++ b/crates/store/src/lib.rs @@ -32,10 +32,12 @@ pub mod spoken; pub mod tags; pub mod testing; pub mod tree; +pub mod tree_hash; pub use error::{Result, StoreError}; pub use notecraft_model::{NodeKind, PageFormat}; pub use settings::{FormatSource, Settings}; pub use tree::{Node, NodeInfo}; +pub use tree_hash::{TreeSnapshot, file_hash, snapshot_tree, tree_manifest}; pub mod coordination; diff --git a/crates/store/src/tree_hash.rs b/crates/store/src/tree_hash.rs new file mode 100644 index 000000000..3f6f9bbb8 --- /dev/null +++ b/crates/store/src/tree_hash.rs @@ -0,0 +1,157 @@ +//! A hash of a directory tree, for telling whether the tree changed since it +//! was recorded. The Welcome notebook update uses it: the manifest recorded +//! when the notebook was installed is compared with the installed tree, so +//! an untouched notebook updates silently and an edited one asks first. +//! +//! Sorted relative paths; each file contributes its contents' hash, each +//! directory and link its path, so a file the person added, or a link they +//! made, counts as a change. Contents only: times and permissions do not +//! matter. A read failure is an error, so a tree that cannot be read is +//! treated as changed, never as untouched. + +use std::io; +use std::path::{Path, PathBuf}; + +/// What one entry of a directory tree holds: a regular file's contents hash, +/// a directory, or a link's target. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Entry { + File(String), + Dir, + Link(PathBuf), +} + +/// The state of a directory tree: every entry in traversal order (depth-first, +/// entries sorted in each directory), so the aggregate hash is stable. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TreeSnapshot { + entries: Vec<(PathBuf, Entry)>, +} + +impl TreeSnapshot { + /// The aggregate SHA-256 of the recorded tree: each file contributes a + /// line with its contents' hash, each directory and link a line with its + /// path, in traversal order. + pub fn manifest(&self) -> String { + use sha2::Digest; + let mut hasher = sha2::Sha256::new(); + for (relative, entry) in &self.entries { + let relative = relative.to_string_lossy(); + match entry { + Entry::File(hash) => hasher.update(format!("F {relative} {hash}\n")), + Entry::Dir => hasher.update(format!("D {relative}\n")), + Entry::Link(target) => hasher.update(format!("L {relative} -> {}\n", target.display())), + } + } + format!("{:x}", hasher.finalize()) + } + + /// The recorded contents hash of one regular file, if the snapshot holds it. + pub fn file_hash(&self, relative: &Path) -> Option<&str> { + self.entries.iter().find_map(|(path, entry)| match entry { + Entry::File(hash) if path == relative => Some(hash.as_str()), + _ => None, + }) + } + + /// Whether the snapshot holds any entry at this relative path. + pub fn contains(&self, relative: &Path) -> bool { + self.entries.iter().any(|(path, _)| path == relative) + } +} + +/// Reads a directory tree into a snapshot. See the module docs for what counts. +pub fn snapshot_tree(dir: &Path) -> io::Result { + let mut entries = Vec::new(); + visit(dir, dir, &mut entries)?; + Ok(TreeSnapshot { entries }) +} + +/// The aggregate SHA-256 of a directory tree, for telling whether it changed. +/// See the module docs; a read failure is an error. +pub fn tree_manifest(dir: &Path) -> io::Result { + Ok(snapshot_tree(dir)?.manifest()) +} + +/// The SHA-256 of one file's contents. +pub fn file_hash(path: &Path) -> io::Result { + use sha2::Digest; + let mut file = std::fs::File::open(path).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + let mut hasher = sha2::Sha256::new(); + std::io::copy(&mut file, &mut hasher).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + Ok(format!("{:x}", hasher.finalize())) +} + +fn visit(dir: &Path, base: &Path, entries: &mut Vec<(PathBuf, Entry)>) -> io::Result<()> { + let mut paths: Vec = std::fs::read_dir(dir) + .map_err(|error| io::Error::new(error.kind(), format!("could not list {}: {error}", dir.display())))? + .collect::>>() + .map_err(|error| io::Error::new(error.kind(), format!("could not list {}: {error}", dir.display())))? + .into_iter() + .map(|entry| entry.path()) + .collect(); + paths.sort(); + for path in paths { + let relative = path + .strip_prefix(base) + .map_err(|_| io::Error::new(io::ErrorKind::Other, format!("{} is not under {}", path.display(), base.display())))? + .to_path_buf(); + let kind = + std::fs::symlink_metadata(&path).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + if kind.file_type().is_symlink() { + let target = + std::fs::read_link(&path).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + entries.push((relative, Entry::Link(target))); + } else if kind.is_dir() { + entries.push((relative, Entry::Dir)); + visit(&path, base, entries)?; + } else { + entries.push((relative, Entry::File(file_hash(&path)?))); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::TempDir; + use std::fs; + + fn tree(dir: &Path) { + fs::create_dir_all(dir.join("00-start/welcome")).expect("tree"); + fs::write(dir.join("00-start/welcome/index.html"), "welcome").expect("page"); + fs::write(dir.join("_node.toml"), "node").expect("node"); + } + + #[test] + fn a_manifest_tells_changed_files_apart() { + let temp = TempDir::new("tree-hash-manifest"); + let first = temp.path().join("first"); + let second = temp.path().join("second"); + tree(&first); + tree(&second); + let manifest = tree_manifest(&first).expect("manifest"); + assert_eq!(tree_manifest(&second).expect("same tree"), manifest, "identical trees share a manifest"); + fs::write(second.join("00-start/welcome/index.html"), "welcome, edited").expect("edit"); + assert_ne!(tree_manifest(&second).expect("changed tree"), manifest, "an edited page changes the manifest"); + fs::write(second.join("00-start/welcome/index.html"), "welcome").expect("restore"); + fs::write(second.join("extra.txt"), "added").expect("added file"); + assert_ne!(tree_manifest(&second).expect("added file"), manifest, "an added file changes the manifest"); + } + + #[test] + fn a_snapshot_records_each_file_and_its_paths() { + let temp = TempDir::new("tree-hash-snapshot"); + let dir = temp.path().join("tree"); + tree(&dir); + let snapshot = snapshot_tree(&dir).expect("snapshot"); + let page = Path::new("00-start/welcome/index.html"); + let recorded = file_hash(&dir.join(page)).expect("file hash"); + assert_eq!(snapshot.file_hash(page), Some(recorded.as_str()), "a file's recorded hash matches its contents"); + assert_eq!(snapshot.file_hash(Path::new("missing.txt")), None, "a missing file has no recorded hash"); + assert!(snapshot.contains(Path::new("00-start/welcome")), "a directory is recorded"); + assert!(!snapshot.contains(Path::new("missing")), "a missing path is not recorded"); + assert_eq!(snapshot.manifest(), tree_manifest(&dir).expect("manifest"), "the snapshot and the tree share a manifest"); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index c8951003f..47cfa7eba 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -90,6 +90,8 @@ notecraft-ocr = { workspace = true } egui-wgpu = "0.37" # Live captions' tests script what the recogniser says (issue #300). craft-voice-core = { workspace = true } +# The Welcome notebook tests install the real bundled edition instead of stubbing the installer. +notecraft-setup = { path = "../../apps/notecraft-setup" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 45edaf359..c25ef28ea 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -286,6 +286,17 @@ const INDENT: f32 = 14.0; const WIZARD_SCREEN_MARGIN: f32 = 2.0 * (16.0 + 2.0 + 8.0); /// The height kept below the wizard's scrolling body for its Back, Next and Finish buttons. const WIZARD_BUTTON_ROW: f32 = 56.0; +/// The height kept above the wizard's scrolling body for its close button. +const WIZARD_CLOSE_ROW: f32 = 36.0; + +/// The folder name of the installed Welcome notebook, matching `notecraft_setup::NOTEBOOK_NAME`. +const WELCOME_NOTEBOOK_DIR: &str = "welcome-to-notecraft"; +/// Settings keys for the Welcome notebook update check: the installed edition's version, +/// a hash of its files at install time, and the version the update prompt was already +/// shown for. See `NoteCraftApp::check_welcome_notebook_update`. +const WELCOME_NOTEBOOK_VERSION_KEY: &str = "welcome_notebook_version"; +const WELCOME_NOTEBOOK_MANIFEST_KEY: &str = "welcome_notebook_manifest"; +const WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY: &str = "welcome_notebook_prompted_version"; /// One result of a History search (Recent Edits, Find by Author; issue #382): the page's title as /// the link that opens it, and under it where it is and when it was last changed, so two pages @@ -1822,6 +1833,12 @@ enum Dialog { add_demo: bool, error: Option, }, + /// The bundled Welcome notebook is newer than the installed copy, and the installed + /// copy was changed: update it (replacing the person's edits) or keep it. + WelcomeNotebookUpdate { + version: String, + error: Option, + }, /// A problem told to the user in a box. /// A problem told to the user in a box. Ticking "do not alert me again" stops the box for /// this `key` for the rest of the session; the status line still says what happened. Alert { @@ -2329,7 +2346,7 @@ pub struct NoteCraftApp { #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))] playback: Option, open_attachment_warning_suppressed: bool, - welcome_notebook_setup: Option Result>>, + welcome_notebook_setup: Option) -> Result, String>>>, } impl NoteCraftApp { @@ -2616,10 +2633,12 @@ impl NoteCraftApp { } /// Installs the application-owned action behind the Welcome notebook step of the first-use - /// wizard. The callback gets the notebooks folder and the chosen format id, and returns the - /// installed notebook folder. The wizard opens once: on the first launch after installation, or + /// wizard. The callback gets the notebooks folder, the chosen format id, and, for an + /// upgrade, the manifest recorded when the notebook was installed; it returns the + /// installed notebook folder, or nothing when the guarded upgrade found the tree + /// changed and replaced nothing. The wizard opens once: on the first launch after installation, or /// after the preferences are reset. It does not reopen for later versions. - pub fn with_welcome_notebook_setup(mut self, setup: impl FnMut(&Path, &str) -> Result + 'static) -> Self { + pub fn with_welcome_notebook_setup(mut self, setup: impl FnMut(&Path, &str, Option<&str>) -> Result, String> + 'static) -> Self { self.welcome_notebook_setup = Some(Box::new(setup)); self } @@ -2642,17 +2661,7 @@ impl NoteCraftApp { self.session.settings.set("telemetry_level", level).map_err(|error| error.to_string())?; self.session.settings.set_default_format(format).map_err(|error| error.to_string())?; if add_demo { - self.save_now(); - if self.is_dirty() { - return Err("the current page could not be saved before replacing the Welcome notebook".to_string()); - } - let installed = { - let setup = self.welcome_notebook_setup.as_mut().ok_or_else(|| "the bundled Welcome notebook setup is unavailable".to_string())?; - setup(self.session.root(), format.id())? - }; - self.editor = None; - self.pad = None; - self.session.refresh(); + let installed = self.install_welcome_notebook(format)?; self.status_is_error = false; self.open_path(&installed.join("00-start/welcome").to_string_lossy()); if self.status_is_error { @@ -2663,6 +2672,154 @@ impl NoteCraftApp { Ok(()) } + /// Replaces the installed Welcome notebook with the bundled edition, in the given + /// format. Saves the open page first and refuses when it cannot be saved, so the + /// replacement never strands unsaved work. Records the installed version and a hash + /// of its files, so a later release can tell whether the notebook was changed since + /// it was installed; a failed record leaves it unrecorded, and the next update asks + /// instead of silently replacing. + fn install_welcome_notebook(&mut self, format: PageFormat) -> Result { + let installed = + self.run_welcome_notebook_setup(format, None)?.ok_or_else(|| "the bundled Welcome notebook setup reported no install".to_string())?; + self.finish_welcome_notebook_install(&installed); + Ok(installed) + } + + /// Replaces the installed Welcome notebook only when it still matches the + /// manifest recorded when it was installed. Returns `None` when the tree + /// changed while the new edition was staged: nothing was replaced, so the + /// caller can ask the person instead of silently replacing their work. + fn update_welcome_notebook(&mut self, format: PageFormat, expected_manifest: &str) -> Result, String> { + let installed = self.run_welcome_notebook_setup(format, Some(expected_manifest))?; + if let Some(installed) = &installed { + self.finish_welcome_notebook_install(installed); + } + Ok(installed) + } + + /// Runs the bundled Welcome notebook setup for one format, after saving the + /// open page. The expected manifest guards an upgrade: with one, the setup + /// replaces nothing when the installed tree changed since it was recorded. + fn run_welcome_notebook_setup(&mut self, format: PageFormat, expected_manifest: Option<&str>) -> Result, String> { + self.save_now(); + if self.is_dirty() { + return Err("the current page could not be saved before replacing the Welcome notebook".to_string()); + } + let setup = self.welcome_notebook_setup.as_mut().ok_or_else(|| "the bundled Welcome notebook setup is unavailable".to_string())?; + setup(self.session.root(), format.id(), expected_manifest) + } + + /// Clears the editor after a Welcome notebook install and records the + /// installed version and manifest. + fn finish_welcome_notebook_install(&mut self, installed: &Path) { + self.editor = None; + self.pad = None; + self.session.refresh(); + Self::record_welcome_notebook(&self.session.settings, installed); + } + + /// Records the installed Welcome notebook's version and manifest. Best-effort: a + /// failed record leaves the notebook unrecorded, and the next update asks instead of + /// silently replacing. + fn record_welcome_notebook(settings: ¬ecraft_store::Settings, installed: &Path) { + if settings.set(WELCOME_NOTEBOOK_VERSION_KEY, crate::backstage::VERSION).is_err() { + log::warn!("could not record the Welcome notebook version"); + return; + } + match Self::welcome_notebook_manifest(installed) { + Ok(manifest) => { + let _ = settings.set(WELCOME_NOTEBOOK_MANIFEST_KEY, &manifest); + } + Err(error) => log::warn!("could not record the Welcome notebook manifest: {error}"), + } + } + + /// Aggregate SHA-256 of a directory tree, for telling whether the installed Welcome + /// notebook was changed since it was installed. See `notecraft_store::tree_manifest`: + /// a read failure is an error, so a tree that cannot be read is treated as changed, + /// never as untouched. + fn welcome_notebook_manifest(dir: &Path) -> Result { + notecraft_store::tree_manifest(dir).map_err(|error| error.to_string()) + } + + /// The edition the installed Welcome notebook is in: the welcome page's file says + /// which one it is. Falls back to the saved default format when the page is gone + /// (the person deleted it, so the update asks anyway). + fn installed_welcome_format(&self) -> PageFormat { + let welcome = self.session.root().join(WELCOME_NOTEBOOK_DIR).join("00-start/welcome"); + if welcome.join("index.html").is_file() { + PageFormat::Html + } else if welcome.join("index.md").is_file() { + PageFormat::Cmgfm + } else { + self.session.settings.global_format().0 + } + } + + /// Checks whether the bundled Welcome notebook is newer than the installed one, for + /// a user whose first-use setup is already done. First-use setup is untouched: the + /// wizard asks about the notebook itself. + /// + /// When the installed copy is untouched, it is replaced silently. When it was + /// changed, or its version was never recorded, a prompt asks once for this version. + /// A change that lands while the new edition is staged is caught the same way: + /// the replacement is refused and the prompt asks instead. + /// A missing notebook, or a bundled version that is not newer, does nothing. The + /// check runs at startup, whatever installed the app: it reads the installed + /// version from settings, never an installer marker. + pub fn check_welcome_notebook_update(&mut self, bundled_version: &str) { + if self.session.settings.first_use_pending() { + return; + } + let installed_dir = self.session.root().join(WELCOME_NOTEBOOK_DIR); + if !installed_dir.is_dir() { + if self.session.settings.get(WELCOME_NOTEBOOK_VERSION_KEY).is_some() { + let _ = self.session.settings.set(WELCOME_NOTEBOOK_VERSION_KEY, ""); + let _ = self.session.settings.set(WELCOME_NOTEBOOK_MANIFEST_KEY, ""); + } + return; + } + let Some(bundled) = crate::update::parse_version(bundled_version) else { + return; + }; + let bundled_version = bundled.to_string(); + let installed_version = self.session.settings.get(WELCOME_NOTEBOOK_VERSION_KEY).unwrap_or_default(); + if !crate::update::is_newer(&bundled, &installed_version) { + return; + } + let stored_manifest = self.session.settings.get(WELCOME_NOTEBOOK_MANIFEST_KEY); + let untouched = match &stored_manifest { + Some(stored) => Self::welcome_notebook_manifest(&installed_dir).is_ok_and(|current| current == *stored), + None => false, + }; + if untouched { + if let Some(expected) = stored_manifest.as_deref() { + match self.update_welcome_notebook(self.installed_welcome_format(), expected) { + Ok(Some(_)) => return, + Ok(None) => { + // The tree changed while the new edition was staged: fall + // through and ask instead of silently replacing it. + } + Err(error) => { + self.alert( + "welcome-notebook-update", + "NoteCraft", + &crate::i18n::format_message_id("ui.welcome_notebook_action_failed", &[("error", &error)]), + ); + return; + } + } + } + } + if self.session.settings.get(WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY).as_deref() == Some(bundled_version.as_str()) { + return; + } + let _ = self.session.settings.set(WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY, &bundled_version); + if self.dialog.is_none() { + self.dialog = Some(Dialog::WelcomeNotebookUpdate { version: bundled_version, error: None }); + } + } + pub fn session(&self) -> &Session { &self.session } @@ -15781,6 +15938,7 @@ impl NoteCraftApp { let mut back = false; let mut next = false; let mut finish = false; + let mut close = false; let last_step: u8 = 4; let escape = ctx.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); let backdrop = modal_backdrop(ctx, "first-use-wizard-modal-backdrop"); @@ -15805,7 +15963,7 @@ impl NoteCraftApp { let screen = ctx.content_rect(); let width = (screen.width() - WIZARD_SCREEN_MARGIN).clamp(1.0, 520.0); let banner_width = width.min(480.0); - let body_height = (screen.height() - WIZARD_SCREEN_MARGIN - WIZARD_BUTTON_ROW).max(80.0); + let body_height = (screen.height() - WIZARD_SCREEN_MARGIN - WIZARD_BUTTON_ROW - WIZARD_CLOSE_ROW).max(80.0); egui::Window::new(title.as_str()) .title_bar(false) .collapsible(false) @@ -15818,6 +15976,11 @@ impl NoteCraftApp { stay_above(ui, backdrop); ui.set_min_width(width); ui.set_max_width(width); + ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| { + if ui.button("×").clicked() { + close = true; + } + }); egui::ScrollArea::vertical().max_height(body_height).auto_shrink([false, true]).show(ui, |ui| { if *step == 0 { ui.add(egui::Image::from_bytes(banner_uri, banner_bytes).fit_to_exact_size(vec2(banner_width, banner_width / 2.0))); @@ -15898,6 +16061,68 @@ impl NoteCraftApp { Err(message) => *error = Some(message), } } + if close { + // Closing skips setup without installing the demo notebook. Marking + // setup seen keeps the wizard from opening again on the next launch. + let _ = self.session.settings.set("privacy_welcome_seen", "true"); + keep = false; + } + } + Dialog::WelcomeNotebookUpdate { version, error } => { + let mut update = false; + let mut keep_mine = false; + let escape = ctx.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); + let backdrop = modal_backdrop(ctx, "welcome-notebook-update-modal-backdrop"); + egui::Window::new(crate::tl_id!("ui.welcome_notebook_update_title")) + .title_bar(false) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .frame(modal_frame(&self.tokens)) + .show(ctx, |ui| { + stay_above(ui, backdrop); + modal_title(ui, &self.tokens, crate::tl_id!("ui.welcome_notebook_update_title")); + let width = message_width(ctx); + ui.set_min_width(width); + ui.set_max_width(width); + ui.label(crate::i18n::format_message_id("ui.welcome_notebook_update_body", &[("version", version.as_str())])); + ui.add_space(6.0); + ui.colored_label(self.tokens.warn, crate::tl_id!("ui.welcome_notebook_replace_warning")); + if let Some(message) = error { + ui.add_space(8.0); + ui.colored_label( + self.tokens.warn, + crate::i18n::format_message_id("ui.welcome_notebook_action_failed", &[("error", message.as_str())]), + ); + } + ui.add_space(14.0); + ui.horizontal(|ui| { + if modal_button(ui, &self.tokens, crate::tl_id!("ui.welcome_notebook_keep_mine"), false).clicked() { + keep_mine = true; + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if modal_button(ui, &self.tokens, crate::tl_id!("ui.welcome_notebook_update"), true).clicked() { + update = true; + } + }); + }); + }); + if escape || keep_mine { + keep = false; + } + if update { + match self.install_welcome_notebook(self.installed_welcome_format()) { + Ok(_) => keep = false, + Err(message) => { + // A failed Update is offered again after restart: clear the + // asked-for-this-version marker instead of suppressing it. + // Keep mine still records the version, so it is not asked again. + let _ = self.session.settings.set(WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY, ""); + *error = Some(message); + } + } + } } Dialog::Alert { key, title, message, suppress, suppress_forever } => { let mut ok = false; @@ -19798,19 +20023,20 @@ mod alert_tests { let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "true").expect("settings"); let upgraded = Session::new(&t.path().join("notebooks"), settings.clone()).expect("upgraded session"); - let upgraded = NoteCraftApp::new(upgraded).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let upgraded = + NoteCraftApp::new(upgraded).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(upgraded.dialog.is_none(), "an existing user is not shown the wizard again for a later version"); // A fresh install opens the wizard at the welcome page; finishing it saves every answer. let fresh = notecraft_store::Settings::at(t.path().join("fresh.toml")); let session = Session::new(&t.path().join("fresh-notebooks"), fresh.clone()).expect("fresh session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, .. })), "a fresh install starts at the welcome page"); assert!(app.finish_first_use_wizard("none", PageFormat::Html, false).is_ok()); assert_eq!(fresh.get("privacy_welcome_seen").as_deref(), Some("true")); let again = Session::new(&t.path().join("fresh-notebooks"), fresh).expect("reopened session"); - let again = NoteCraftApp::new(again).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let again = NoteCraftApp::new(again).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(again.dialog.is_none(), "a finished wizard does not open again"); } @@ -19819,7 +20045,7 @@ mod alert_tests { let t = notecraft_store::testing::TempDir::new("welcome-prompt-after-privacy"); let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); let session = Session::new(&t.path().join("notebooks"), settings).expect("session"); - let app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, .. })), "the wizard opens at the logging step"); assert!(app.queued_alerts.is_empty(), "the wizard is one window, so nothing waits behind it"); @@ -19843,7 +20069,7 @@ mod alert_tests { let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "true").expect("settings"); let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _| Err("copy failed".to_string())); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _, _| Err("copy failed".to_string())); assert!(app.finish_first_use_wizard("none", PageFormat::Cmgfm, true).is_err()); @@ -19858,11 +20084,11 @@ mod alert_tests { let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); let installed_format = std::rc::Rc::new(std::cell::RefCell::new(String::new())); let recorder = installed_format.clone(); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, format| { + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, format, _expected| { *recorder.borrow_mut() = format.to_string(); let installed = root.join("welcome-to-notecraft"); std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; - Ok(installed) + Ok(Some(installed)) }); // Opening the fake folder's page can fail; the full install and open path is covered by the UI test. @@ -19871,6 +20097,155 @@ mod alert_tests { assert_eq!(installed_format.borrow().as_str(), "cmgfm", "the chosen format reaches the install"); } + #[test] + fn welcome_notebook_manifest_tells_changed_files_apart() { + let t = notecraft_store::testing::TempDir::new("welcome-manifest"); + let first = t.path().join("first"); + let second = t.path().join("second"); + for root in [&first, &second] { + std::fs::create_dir_all(root.join("00-start/welcome")).expect("tree"); + std::fs::write(root.join("00-start/welcome/index.html"), "welcome").expect("page"); + std::fs::write(root.join("_node.toml"), "node").expect("node"); + } + let manifest = NoteCraftApp::welcome_notebook_manifest(&first).expect("manifest"); + assert_eq!(NoteCraftApp::welcome_notebook_manifest(&second).expect("same tree"), manifest, "identical trees share a manifest"); + std::fs::write(second.join("00-start/welcome/index.html"), "welcome, edited").expect("edit"); + assert_ne!(NoteCraftApp::welcome_notebook_manifest(&second).expect("changed tree"), manifest, "an edited page changes the manifest"); + std::fs::write(second.join("00-start/welcome/index.html"), "welcome").expect("restore"); + std::fs::write(second.join("extra.txt"), "added").expect("added file"); + assert_ne!(NoteCraftApp::welcome_notebook_manifest(&second).expect("added file"), manifest, "an added file changes the manifest"); + } + + #[test] + fn welcome_notebook_install_records_version_and_manifest() { + let t = notecraft_store::testing::TempDir::new("welcome-record-install"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format, _expected| { + let installed = root.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; + std::fs::write(installed.join("00-start/welcome/index.html"), "welcome").map_err(|error| error.to_string())?; + Ok(Some(installed)) + }); + // Opening the fake folder's page can fail; the install and its record happen first. + let _ = app.finish_first_use_wizard("none", PageFormat::Html, true); + assert_eq!(settings.get("welcome_notebook_version").as_deref(), Some(crate::backstage::VERSION), "the installed version is recorded"); + let installed = t.path().join("notebooks/welcome-to-notecraft"); + assert_eq!( + settings.get("welcome_notebook_manifest").as_deref(), + Some(NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest").as_str()), + "the manifest follows the installed tree" + ); + } + + #[test] + fn welcome_notebook_update_is_silent_when_untouched() { + let t = notecraft_store::testing::TempDir::new("welcome-update-silent"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + let manifest = NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", &manifest).expect("manifest"); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, _format, _expected| { + let installed = root.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; + std::fs::write(installed.join("00-start/welcome/index.html"), "new welcome").map_err(|error| error.to_string())?; + Ok(Some(installed)) + }); + app.check_welcome_notebook_update("0.0.30"); + assert!(app.dialog.is_none(), "an untouched notebook updates without asking"); + assert_eq!(settings.get("welcome_notebook_version").as_deref(), Some(crate::backstage::VERSION), "the installed version is recorded"); + assert_eq!(std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("new page"), "new welcome"); + assert_eq!( + settings.get("welcome_notebook_manifest").as_deref(), + Some(NoteCraftApp::welcome_notebook_manifest(&installed).expect("new manifest").as_str()), + "the manifest follows the new edition" + ); + } + + #[test] + fn welcome_notebook_update_prompts_when_edited() { + let t = notecraft_store::testing::TempDir::new("welcome-update-prompt"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + let manifest = NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", &manifest).expect("manifest"); + std::fs::write(installed.join("00-start/welcome/index.html"), "my notes").expect("edit"); + let called = std::rc::Rc::new(std::cell::Cell::new(false)); + let called_flag = called.clone(); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |_, _, _| { + called_flag.set(true); + Err("must not install".to_string()) + }); + app.check_welcome_notebook_update("0.0.30"); + assert!(matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { ref version, .. }) if version == "0.0.30"), "an edited notebook asks once"); + assert!(!called.get(), "asking does not install"); + assert_eq!(settings.get("welcome_notebook_prompted_version").as_deref(), Some("0.0.30"), "asking records the version"); + assert_eq!( + std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("kept page"), + "my notes", + "asking does not replace the notebook" + ); + } + + #[test] + fn welcome_notebook_update_asks_once_per_version() { + let t = notecraft_store::testing::TempDir::new("welcome-update-once"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", "stale").expect("stale manifest"); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _, _| Err("must not install".to_string())); + app.check_welcome_notebook_update("0.0.30"); + assert!(matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { .. })), "asks the first time"); + app.dialog = None; + app.check_welcome_notebook_update("0.0.30"); + assert!(app.dialog.is_none(), "does not ask again for the same version"); + app.check_welcome_notebook_update("0.0.31"); + assert!( + matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { ref version, .. }) if version == "0.0.31"), + "asks again for a newer version" + ); + } + + #[test] + fn welcome_notebook_update_asks_when_the_tree_changed_during_staging() { + let t = notecraft_store::testing::TempDir::new("welcome-update-changed"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + let manifest = NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", &manifest).expect("manifest"); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _, _| Ok(None)); + app.check_welcome_notebook_update("0.0.30"); + assert!( + matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { ref version, .. }) if version == "0.0.30"), + "a tree that changed during staging asks instead of silently replacing" + ); + assert_eq!(std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("kept page"), "old welcome"); + } + /// `--first-use` writes `privacy_welcome_seen = ""` and keeps every other setting. #[test] fn first_use_flag_value_opens_setup_with_the_saved_choices() { diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 12000c9ea..9653ba263 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -2515,7 +2515,7 @@ fn the_first_use_wizard_fits_a_phone_and_every_step_can_be_reached() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); let size = egui::vec2(360.0, 740.0); let mut h = sized_harness(app, LIGHT, size); settle(&mut h); @@ -2548,13 +2548,13 @@ fn welcome_notebook_prompt_can_replace_and_open_the_release_copy() { let destination = notebooks.join("welcome-to-notecraft"); std::fs::create_dir_all(&destination).expect("old Welcome notebook"); std::fs::write(destination.join("old-user-edit.txt"), "replace this managed copy").expect("old Welcome edit"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format| { + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format, _expected| { let destination = root.join("welcome-to-notecraft"); if destination.exists() { std::fs::remove_dir_all(&destination).map_err(|error| error.to_string())?; } copy_tree(&source.join(format), &destination); - Ok(destination) + Ok(Some(destination)) }); let mut h = harness(app, LIGHT); // Welcome, logging, format, demo, thank you. @@ -2592,10 +2592,10 @@ fn declining_the_welcome_notebook_prompt_does_not_create_it() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format| { + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format, _expected| { let destination = root.join("welcome-to-notecraft"); std::fs::create_dir_all(&destination).map_err(|error| error.to_string())?; - Ok(destination) + Ok(Some(destination)) }); let mut h = harness(app, LIGHT); h.get_by_label("Next").click(); @@ -2622,7 +2622,7 @@ fn clicking_outside_the_first_use_wizard_keeps_its_buttons_working() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); let mut h = harness(app, LIGHT); settle(&mut h); @@ -2654,7 +2654,7 @@ fn failed_welcome_notebook_generation_keeps_the_prompt_open() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|_, _| Err("permission denied".to_string())); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|_, _, _| Err("permission denied".to_string())); let mut h = harness(app, LIGHT); h.get_by_label("Next").click(); settle(&mut h); @@ -2673,6 +2673,52 @@ fn failed_welcome_notebook_generation_keeps_the_prompt_open() { assert!(!t.path().join("notebooks/welcome-to-notecraft").exists(), "a failed copy creates no partial notebook"); } +#[test] +fn first_use_wizard_close_button_skips_setup_without_installing_the_demo() { + let t = TempDir::new("ui-welcome-wizard-close"); + let s = session(&t); + s.settings.set("ui_language", "en").expect("English UI setting"); + s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); + let payload = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook"); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format, _expected| { + notecraft_setup::install_edition(&payload, root, format).map(Some).map_err(|error| error.to_string()) + }); + let mut h = harness(app, LIGHT); + h.get_by_label("×").click(); + settle(&mut h); + assert_eq!(h.query_all_by_label("Finish").count(), 0, "closing dismisses the wizard"); + assert_eq!(h.state().session().settings.get("privacy_welcome_seen").as_deref(), Some("true"), "closing marks setup seen"); + assert!(!t.path().join("notebooks/welcome-to-notecraft").exists(), "closing creates no notebook"); +} + +#[test] +fn welcome_notebook_update_prompt_keep_mine_asks_once_per_version() { + let t = TempDir::new("ui-welcome-update-prompt"); + let s = session(&t); + s.settings.set("ui_language", "en").expect("English UI setting"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "my notes").expect("edited page"); + s.settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + s.settings.set("welcome_notebook_manifest", "stale").expect("stale manifest"); + let payload = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook"); + let mut app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format, _expected| { + notecraft_setup::install_edition(&payload, root, format).map(Some).map_err(|error| error.to_string()) + }); + app.check_welcome_notebook_update("0.0.30"); + let mut h = harness(app, LIGHT); + h.get_by_label("Keep mine").click(); + settle(&mut h); + assert_eq!(h.query_all_by_label("Keep mine").count(), 0, "Keep mine closes the prompt"); + assert_eq!(h.state().session().settings.get("welcome_notebook_prompted_version").as_deref(), Some("0.0.30"), "keeping records the version"); + assert_eq!( + std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("kept page"), + "my notes", + "keeping does not replace the notebook" + ); +} + #[test] fn an_empty_notebooks_folder_stays_empty_when_the_app_opens() { let t = TempDir::new("ui-empty-notebooks"); diff --git a/i18n/en.tsv b/i18n/en.tsv index fe2b5a453..87957dbb0 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -946,6 +946,10 @@ @id ui.welcome_notebook_add_yes Yes, add it @id ui.welcome_notebook_add_no No, not now @id ui.welcome_notebook_action_failed Could not update the Welcome notebook: {error} +@id ui.welcome_notebook_update_title Update the Welcome notebook? +@id ui.welcome_notebook_update_body A new Welcome notebook is available in this release (version {version}). Your copy was changed, so updating will replace it. +@id ui.welcome_notebook_update Update +@id ui.welcome_notebook_keep_mine Keep mine @id ui.welcome_wizard_back Back @id ui.welcome_wizard_finish Finish @id ui.welcome_wizard_done_title Thank you