diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 5abbe63..5e856cf 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -449,6 +449,24 @@ impl App { // Before the samples, which are named in this language. crate::i18n::set_lang(settings.language); crate::engine_download::clean_leftovers(); + // Temporary files of copies of chosen games left by a crash: in the folders of the + // databases, away from the window's thread (a network drive may be slow). + #[cfg(not(web))] + { + let mut dirs: Vec = settings + .databases + .iter() + .filter_map(|p| p.parent().map(|d| d.to_path_buf())) + .collect(); + dirs.push(own_db::default_base_dir( + settings.new_database_dir.as_deref(), + )); + dirs.sort(); + dirs.dedup(); + let _ = std::thread::Builder::new() + .name("copy-leftovers".into()) + .spawn(move || crate::batch_copy::clean_orphans(&dirs)); + } let current = env!("CARGO_PKG_VERSION"); #[cfg(not(web))] let updated_from = { diff --git a/apps/desktop/src/batch_copy.rs b/apps/desktop/src/batch_copy.rs index d98e3ed..09d02f0 100644 --- a/apps/desktop/src/batch_copy.rs +++ b/apps/desktop/src/batch_copy.rs @@ -4,7 +4,8 @@ //! background into a temporary file beside the new one and published only when whole. //! The source database is only read. -use std::collections::HashSet; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; use std::io::Write as _; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; @@ -165,15 +166,16 @@ pub struct CopyRequest { #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CopyReport { pub copied: usize, - /// The same game already copied (players, date, moves of the main line). - pub duplicates: usize, + /// Record numbers (from 0) skipped as a copy of a record already copied: the same + /// PGN text, white space aside. + pub duplicates: Vec, /// Record numbers (from 0) that could not be read. pub unreadable: Vec, } impl CopyReport { pub fn skipped(&self) -> usize { - self.duplicates + self.unreadable.len() + self.duplicates.len() + self.unreadable.len() } } @@ -219,18 +221,84 @@ impl Drop for Partial { } } +/// The temporary file of a copy into `target`: `..part--`, the +/// process that writes it in its name (`clean_orphans` knows from it whether its writer +/// is gone). fn partial_path(target: &Path) -> PathBuf { let name = target .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); - target.with_file_name(format!(".{name}.part-{}", std::process::id())) + let mut h = std::collections::hash_map::DefaultHasher::new(); + std::time::SystemTime::now().hash(&mut h); + std::thread::current().id().hash(&mut h); + target.hash(&mut h); + target.with_file_name(format!( + ".{name}{PART}{}-{:016x}", + std::process::id(), + h.finish() + )) +} + +const PART: &str = ".part-"; + +/// Temporary files of copies whose process is gone (a crash, a power cut), in `dirs`: +/// removed. Only names this program gives (`..pgn.part--`) and only when +/// no process `` runs; anything else is left alone. +pub fn clean_orphans(dirs: &[PathBuf]) { + for dir in dirs { + let Ok(entries) = std::fs::read_dir(dir) else { + continue; + }; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if let Some(pid) = orphan_pid(&name) + && pid != std::process::id() + && !Path::new(&format!("/proc/{pid}")).exists() + && entry.file_type().is_ok_and(|t| t.is_file()) + { + let _ = std::fs::remove_file(entry.path()); + } + } + } +} + +/// The writer's process of a temporary copy file named so, if the name is one. +fn orphan_pid(name: &str) -> Option { + let rest = name.strip_prefix('.')?; + let (stem, tail) = rest.rsplit_once(PART)?; + if !stem.to_lowercase().ends_with(".pgn") { + return None; + } + let (pid, hex) = tail.split_once('-')?; + (hex.len() == 16 && hex.chars().all(|c| c.is_ascii_hexdigit())) + .then(|| pid.parse().ok()) + .flatten() +} + +/// A record's PGN text with every run of white space as one space: what makes two +/// records the same for a copy (the owner's rule: tags, moves, variations, comments and +/// NAG all equal; line breaks and spaces aside). +fn normalized(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// 128 bits of a normalized record text: millions of copied records are told apart +/// without keeping their texts; equal keys are compared again in full. +fn key_of(normalized: &str) -> u128 { + let half = |salt: u64| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + salt.hash(&mut h); + normalized.hash(&mut h); + h.finish() + }; + (u128::from(half(0x9e37_79b9_7f4a_7c15)) << 64) | u128::from(half(0x6a09_e667_f3bc_c909)) } /// Copies the records of `req` from `db` into the new file `req.target`, in the table's /// order (records of equal value by number). Each record has the bytes «Add to -/// database» would append to it; a game already copied is skipped, a record that cannot -/// be read too. Written into a temporary file beside the target and published by a hard +/// database» would append to it; a record whose text was already copied is skipped, a +/// record that cannot be read too. Written into a temporary file beside the target and published by a hard /// link, which fails rather than replace a file of that name. `None`: cancelled, nothing /// is left on disk. pub fn copy_into_new( @@ -262,7 +330,10 @@ pub fn copy_into_new( .open(&partial.path)?; let mut out = std::io::BufWriter::new(file); let mut report = CopyReport::default(); - let mut seen = HashSet::new(); + // Copied records by the key of their text; equal keys of different texts (all + // but impossible) in `more`. + let mut seen: HashMap = HashMap::new(); + let mut more: Vec = Vec::new(); for (n, &record) in order.iter().enumerate() { if cancel.load(Ordering::Relaxed) { return Ok(None); @@ -276,12 +347,30 @@ pub fn copy_into_new( .and_then(|parsed| Some((parsed, record_text(db, index)?))); match text { None => report.unreadable.push(index), - Some((parsed, text)) => { - if seen.insert(store::same_game(&parsed.game)) { + Some((_, text)) => { + let flat = normalized(&text); + let key = key_of(&flat); + let same = |other: u32| { + record_text(db, other as usize).is_some_and(|t| normalized(&t) == flat) + }; + let duplicate = match seen.get(&key) { + None => { + seen.insert(key, record); + false + } + Some(&first) => { + let dup = same(first) || more.iter().any(|&o| same(o)); + if !dup { + more.push(record); + } + dup + } + }; + if duplicate { + report.duplicates.push(index); + } else { out.write_all(&store::record_for_new_file(&text))?; report.copied += 1; - } else { - report.duplicates += 1; } } } @@ -310,7 +399,23 @@ pub fn copy_into_new( } } -/// «Name: copied 3, skipped 1 — duplicates 1, unreadable 0 (No. …)». +/// « (No. 3, 4 and 2 more)» for up to `most` record numbers, nothing for none. +fn numbers(records: &[usize], most: usize) -> String { + if records.is_empty() { + return String::new(); + } + let mut list: Vec = records + .iter() + .take(most) + .map(|i| (i + 1).to_string()) + .collect(); + if records.len() > most { + list.push(trf("and {n} more", &[("n", &(records.len() - most))])); + } + format!(" ({})", trf("No. {list}", &[("list", &list.join(", "))])) +} + +/// «Name: copied 3, skipped 1 — duplicates 1 (No. 9), unreadable 0». pub fn summary(name: &str, report: &CopyReport) -> String { if report.skipped() == 0 { return trf( @@ -318,35 +423,18 @@ pub fn summary(name: &str, report: &CopyReport) -> String { &[("name", &name), ("n", &report.copied), ("m", &0)], ); } - let mut numbers: Vec = report - .unreadable - .iter() - .take(5) - .map(|i| (i + 1).to_string()) - .collect(); - if report.unreadable.len() > 5 { - numbers.push(trf( - "and {n} more", - &[("n", &(report.unreadable.len() - 5))], - )); - } - let mut text = trf( - "{name}: copied {n}, skipped {m} — duplicates {d}, unreadable {u}", + trf( + "{name}: copied {n}, skipped {m} — duplicates {d}{dl}, unreadable {u}{ul}", &[ ("name", &name), ("n", &report.copied), ("m", &report.skipped()), - ("d", &report.duplicates), + ("d", &report.duplicates.len()), + ("dl", &numbers(&report.duplicates, 10)), ("u", &report.unreadable.len()), + ("ul", &numbers(&report.unreadable, 5)), ], - ); - if !numbers.is_empty() { - text.push_str(&format!( - " ({})", - trf("No. {list}", &[("list", &numbers.join(", "))]) - )); - } - text + ) } #[cfg(test)] diff --git a/apps/desktop/src/batch_copy_tests.rs b/apps/desktop/src/batch_copy_tests.rs index fcb9351..b956075 100644 --- a/apps/desktop/src/batch_copy_tests.rs +++ b/apps/desktop/src/batch_copy_tests.rs @@ -88,6 +88,18 @@ const SOURCE: &str = r#"[Event "Club"] [Result "1-0"] 1. e4 e5 2. Nf3 Nc6 1-0 + +[Event "Club"] +[Site "?"] +[Date "2020.01.02"] +[Round "1"] +[White "Alpha"] +[Black "Beta"] +[Result "1-0"] +[MyTag "kept"] + +{A comment at the root} 1. e4 $1 {[%cal Ge2e4]} +e5 (1... c5 2. Nf3 (2. c3 d5 (2... Nf6 3. e5)) d6) 2. Nf3 $14 Nc6 1-0 "#; fn request(records: &[u32], target: &Path) -> CopyRequest { @@ -108,11 +120,13 @@ fn copy(db: &Database, req: &CopyRequest) -> Option = Vec::new(); for &i in order { let into = PgnDatabase::open(target, &mut |_| {}, &AtomicBool::new(false)).unwrap(); - let game = db.load_game(i).unwrap().game; - if store::find_same_game(&into, &game).is_none() { - store::append(&into, &record_text(db, i).unwrap()).unwrap(); + let text = record_text(db, i).unwrap(); + if !written.contains(&normalized(&text)) { + store::append(&into, &text).unwrap(); + written.push(normalized(&text)); } } } @@ -149,22 +163,23 @@ fn a_copy_has_the_bytes_of_adding_the_games_one_by_one() { let source = dir.file("source.pgn", SOURCE.as_bytes()); let before = std::fs::read(&source).unwrap(); let db = open(&source); - assert_eq!(db.len(), 4); + assert_eq!(db.len(), 5); let target = dir.0.join("copy.pgn"); - let report = copy(&db, &request(&[3, 0, 2, 1], &target)) + let report = copy(&db, &request(&[3, 0, 4, 2, 1], &target)) .unwrap() .unwrap(); - // Game 4 is game 1 again (names without case, the same date and moves). + // Record 5 is record 1 again with other line breaks: skipped; record 4 is the same + // game with other tags: copied. assert_eq!( report, CopyReport { - copied: 3, - duplicates: 1, + copied: 4, + duplicates: vec![4], unreadable: Vec::new() } ); let expected = dir.0.join("expected.pgn"); - one_by_one(&db, &[0, 1, 2, 3], &expected); + one_by_one(&db, &[0, 1, 2, 3, 4], &expected); assert_eq!( std::fs::read(&target).unwrap(), std::fs::read(&expected).unwrap() @@ -193,6 +208,75 @@ fn a_copy_has_the_bytes_of_adding_the_games_one_by_one() { } } +/// The owner's example: in Dvoretsky's endgame manual records 719 and 728 are one game +/// with other comments; both are copied (the user's file, read only, when it is there). +#[test] +fn records_with_other_comments_are_both_copied() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Дворецкий. Учебник жндшпиля.pgn"); + if !path.exists() { + return; + } + let db = open(&path); + let dir = Dir::new("dvoretsky"); + let target = dir.0.join("copy.pgn"); + let report = copy(&db, &request(&[718, 727], &target)).unwrap().unwrap(); + assert_eq!((report.copied, report.duplicates.len()), (2, 0)); + // The same record twice in a source: the second is skipped. + let one = record_text(&db, 718).unwrap(); + let source = dir.file("twice.pgn", format!("{one}\n\n{one}\n").as_bytes()); + let twice = open(&source); + let target = dir.0.join("twice-copy.pgn"); + let report = copy(&twice, &request(&[0, 1], &target)).unwrap().unwrap(); + assert_eq!((report.copied, report.duplicates), (1, vec![1])); +} + +#[test] +fn the_summary_names_the_skipped_records() { + let report = CopyReport { + copied: 5, + duplicates: (0..12).collect(), + unreadable: vec![39], + }; + assert_eq!( + summary("Pick", &report), + "Pick: copied 5, skipped 13 — duplicates 12 (No. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 2 more), unreadable 1 (No. 40)" + ); + let clean = CopyReport { + copied: 3, + ..CopyReport::default() + }; + assert_eq!(summary("Pick", &clean), "Pick: copied 3, skipped 0"); +} + +#[test] +fn only_orphans_of_this_program_are_removed() { + let dir = Dir::new("orphans"); + let mine_live = format!(".a.pgn.part-{}-0123456789abcdef", std::process::id()); + // No process has a number that high on Linux (pid_max is at most 4194304). + let dead = ".a.pgn.part-999999999-0123456789abcdef"; + let others = [ + ".a.pgn.part-999999999", + ".a.txt.part-999999999-0123456789abcdef", + "a.pgn.part-999999999-0123456789abcdef", + ".a.pgn.part-999999999-xyz", + ]; + for name in [mine_live.as_str(), dead].iter().chain(others.iter()) { + dir.file(name, b"x"); + } + clean_orphans(std::slice::from_ref(&dir.0)); + assert!(!dir.0.join(dead).exists()); + assert!(dir.0.join(&mine_live).exists()); + for name in others { + assert!(dir.0.join(name).exists(), "{name}"); + } + // Each copy has a name of its own. + let target = dir.0.join("t.pgn"); + assert_ne!(partial_path(&target), partial_path(&target)); + let name = partial_path(&target); + assert!(orphan_pid(&name.file_name().unwrap().to_string_lossy()).is_some()); +} + #[test] fn a_copy_follows_the_tables_order() { let dir = Dir::new("order"); @@ -387,3 +471,84 @@ fn timing() { let n = s.count_in(&view); println!("count chosen in 4 000 000: {:?} ({n})", t.elapsed()); } + +fn rss_anon_kb() -> u64 { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|s| { + s.lines() + .find(|l| l.starts_with("RssAnon:")) + .and_then(|l| l.split_whitespace().nth(1)?.parse().ok()) + }) + .unwrap_or(0) +} + +/// The memory a copy takes beyond the open database: the peak of `RssAnon` while it runs +/// less the value before. `CP_PROBE_DB=` and `CP_PROBE_N=` (release: +/// `cargo test --release -- --ignored --nocapture copy_memory`); without them, synthetic +/// PGN of 1 000 000 games in a temporary folder. +#[test] +#[ignore] +fn copy_memory() { + let dir = Dir::new("memory"); + let (db, n) = match std::env::var("CP_PROBE_DB") { + Ok(path) => { + let n = std::env::var("CP_PROBE_N") + .ok() + .and_then(|n| n.parse().ok()) + .unwrap_or(200_000); + (open(Path::new(&path)), n) + } + Err(_) => { + let n: usize = std::env::var("CP_PROBE_N") + .ok() + .and_then(|n| n.parse().ok()) + .unwrap_or(1_000_000); + let path = dir.0.join("big.pgn"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&path).unwrap()); + for i in 0..n { + write!( + out, + "[White \"W{i}\"]\n[Black \"B{}\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O *\n\n", + i % 977 + ) + .unwrap(); + } + drop(out); + (open(&path), n) + } + }; + let records: Vec = (0..n.min(db.len()) as u32).collect(); + // The database's own index for sorting is built once, by the table: not the copy's. + db.sort_records(&mut records.clone(), SortKey::Number, true); + let before = rss_anon_kb(); + let done = std::sync::Arc::new(AtomicBool::new(false)); + let peak = { + let done = done.clone(); + std::thread::spawn(move || { + let mut peak = 0; + while !done.load(std::sync::atomic::Ordering::Relaxed) { + peak = peak.max(rss_anon_kb()); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + peak + }) + }; + let target = dir.0.join("copy.pgn"); + let t = std::time::Instant::now(); + let report = copy(&db, &request(&records, &target)).unwrap().unwrap(); + let took = t.elapsed(); + done.store(true, std::sync::atomic::Ordering::Relaxed); + let peak = peak.join().unwrap(); + println!( + "records {}: copied {}, duplicates {}, {:?}; RssAnon before {} KB, peak {} KB, +{} KB ({:.0} B per record)", + records.len(), + report.copied, + report.duplicates.len(), + took, + before, + peak, + peak.saturating_sub(before), + peak.saturating_sub(before) as f64 * 1024.0 / records.len().max(1) as f64 + ); +} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index d73e601..bf364ee 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -19806,15 +19806,15 @@ const ROWS: &[[&str; 9]] = &[ "{name}: {n} көшірілді, {m} өткізілді", ], [ - "{name}: copied {n}, skipped {m} — duplicates {d}, unreadable {u}", - "{name}: скопировано {n}, пропущено {m} — дубли {d}, не прочитано {u}", - "{name} : {n} copiées, {m} ignorées — doublons {d}, illisibles {u}", - "{name}: {n} kopiert, {m} übersprungen — Duplikate {d}, unlesbar {u}", - "{name}: copiadas {n}, omitidas {m} — duplicadas {d}, ilegibles {u}", - "{name}: copiate {n}, saltate {m} — duplicati {d}, illeggibili {u}", - "{name}: copiadas {n}, ignoradas {m} — duplicadas {d}, ilegíveis {u}", - "{name}: {n} ta nusxalandi, {m} ta o‘tkazildi — takrorlar {d}, o‘qilmadi {u}", - "{name}: {n} көшірілді, {m} өткізілді — қайталанған {d}, оқылмады {u}", + "{name}: copied {n}, skipped {m} — duplicates {d}{dl}, unreadable {u}{ul}", + "{name}: скопировано {n}, пропущено {m} — дубли {d}{dl}, не прочитано {u}{ul}", + "{name} : {n} copiées, {m} ignorées — doublons {d}{dl}, illisibles {u}{ul}", + "{name}: {n} kopiert, {m} übersprungen — Duplikate {d}{dl}, unlesbar {u}{ul}", + "{name}: copiadas {n}, omitidas {m} — duplicadas {d}{dl}, ilegibles {u}{ul}", + "{name}: copiate {n}, saltate {m} — duplicati {d}{dl}, illeggibili {u}{ul}", + "{name}: copiadas {n}, ignoradas {m} — duplicadas {d}{dl}, ilegíveis {u}{ul}", + "{name}: {n} ta nusxalandi, {m} ta o‘tkazildi — takrorlar {d}{dl}, o‘qilmadi {u}{ul}", + "{name}: {n} көшірілді, {m} өткізілді — қайталанған {d}{dl}, оқылмады {u}{ul}", ], [ "No. {list}", @@ -19937,6 +19937,17 @@ const ROWS: &[[&str; 9]] = &[ "Boshqa nusxa yozilmoqda: tugashini kuting", "Басқа көшірме жазылуда: аяқталуын күтіңіз", ], + [ + "Selection cleared: the database changed", + "Выделение снято: база изменилась", + "Sélection annulée : la base a changé", + "Auswahl aufgehoben: die Datenbank hat sich geändert", + "Selección quitada: la base cambió", + "Selezione annullata: il database è cambiato", + "Seleção limpa: a base mudou", + "Tanlov bekor qilindi: baza o‘zgardi", + "Таңдау алынды: база өзгерді", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 08973b1..4c983b9 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -332,6 +332,12 @@ pub struct LargeView { pub cancel_batch: bool, /// Why the last copy wrote nothing: said in red where its progress was, until `×`. pub batch_error: Option, + /// The chosen records as the file had them before it was read again (a hash of + /// each one's bytes), to know they are still the same games; `None` for a choice too + /// large to check (it is let go when the file changes). + marked_before: Option>, + /// Said once (a toast), taken by the library. + pub notice: Option, scroll_to_selected: bool, scroll_to_top: bool, focus_player: bool, @@ -457,6 +463,8 @@ impl LargeView { batch: None, cancel_batch: false, batch_error: None, + marked_before: None, + notice: None, scroll_to_selected: false, scroll_to_top: false, focus_player: false, @@ -500,15 +508,37 @@ impl LargeView { self.cache.clear(); self.blocked = None; self.books = db.books(); - // Fewer records now (one deleted, the file changed): the numbers no longer mean - // the same games. - if self.marked.last().is_some_and(|r| r >= db.len()) { - self.mark_cursor_only(); - self.selected = self.selected.filter(|&c| c < db.len()); - if self.selected.is_none() { - self.mark(|m| m.clear()); + // Several chosen: kept only if each is still the same record (a game added at + // the end keeps them; one deleted or put back moves the numbers). Otherwise let + // go, and said: the choice never moves to other games unnoticed. + if self.marked.len() >= 2 { + let same = std::mem::take(&mut self.marked_before).is_some_and(|before| { + before.len() == self.marked.len() + && before + .iter() + .all(|&(r, h)| (r as usize) < db.len() && record_hash(db, r as usize) == h) + }); + if !same { + self.clear_marks(); + self.notice = Some(tr("Selection cleared: the database changed").to_owned()); } + } else if self.marked.last().is_some_and(|r| r >= db.len()) { + self.mark(|m| m.clear()); } + self.selected = self.selected.filter(|&c| c < db.len()); + } + + /// Before the file is read again: what the chosen records are now (up to + /// `CHECKED_CHOICE` of them). + pub fn before_reread(&mut self, db: &Database) { + self.marked_before = + (self.marked.len() >= 2 && self.marked.len() <= CHECKED_CHOICE).then(|| { + self.marked + .records() + .into_iter() + .map(|r| (r, record_hash(db, r as usize))) + .collect() + }); } /// Selects a record and scrolls to it (returning from a game): a choice of several @@ -2725,6 +2755,11 @@ impl LargeView { if typing && self.suggestions.is_some() { return; } + // A question or a menu over the table takes the keys (Enter there is its button, + // not «open the game»). + if crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) { + return; + } let (up, down, page_up, page_down, enter, mods) = ui.input(|i| { ( i.key_pressed(egui::Key::ArrowUp), @@ -2851,6 +2886,17 @@ impl LargeView { } } +/// Up to this many chosen records are checked when their file is read again; a larger +/// choice is let go if the file changed. +const CHECKED_CHOICE: usize = 100_000; + +/// A hash of the bytes of record `index`. +fn record_hash(db: &Database, index: usize) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + db.identity(index).hash(&mut h); + h.finish() +} + /// The width of the far right slot of the conditions line (task 27 sets it; until /// then nothing is there). const RIGHT_SLOT_W: f32 = 0.0; @@ -3218,6 +3264,44 @@ mod tests { assert_eq!(v.marked.records(), vec![3, 9]); } + fn database(name: &str, games: &[&str]) -> Database { + let path = + std::env::temp_dir().join(format!("cp-reread-{}-{name}.pgn", std::process::id())); + let text: String = games + .iter() + .map(|w| format!("[White \"{w}\"]\n[Black \"x\"]\n[Result \"*\"]\n\n1. e4 *\n\n")) + .collect(); + std::fs::write(&path, text).unwrap(); + let db = chess_import::open( + &path, + &mut |_| {}, + &std::sync::atomic::AtomicBool::new(false), + ) + .unwrap() + .db; + let _ = std::fs::remove_file(&path); + db + } + + #[test] + fn a_choice_never_moves_to_other_games_when_the_file_is_read_again() { + let before = database("before", &["a", "b", "c", "d"]); + // A game added at the end: the chosen ones are the same records. + let mut v = table(); + v.click(1, egui::Modifiers::NONE); + v.click(2, ctrl()); + v.before_reread(&before); + v.reread(&database("added", &["a", "b", "c", "d", "e"])); + assert_eq!(v.marked.records(), vec![1, 2]); + assert!(v.notice.is_none()); + // A game put back at the start (undo of a delete): the numbers moved; let go, + // and said. + v.before_reread(&before); + v.reread(&database("undo", &["z", "a", "b", "c", "d"])); + assert!(v.marked.is_empty()); + assert!(v.notice.is_some()); + } + #[test] fn the_copy_asks_for_the_chosen_records_and_the_tables_sort() { let mut v = table(); diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index c5d294f..78cfe81 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -528,7 +528,10 @@ impl Library { let selected = self.selected_db.as_deref() == Some(path); // The conditions, the position, the sort and the selection stay (§9.7): the view // finds its list anew once the file is read. - let view = self.large.remove(path); + let mut view = self.large.remove(path); + if let (Some(v), Some(db)) = (view.as_mut(), self.database(path)) { + v.before_reread(&db); + } self.forget(path); if let Some(v) = view { self.large.insert(path.to_path_buf(), v); @@ -851,6 +854,11 @@ impl Library { { ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); } + for view in self.large.values_mut() { + if let Some(text) = view.notice.take() { + actions.push(LibraryAction::Notice(text)); + } + } if let Some(path) = self.selected_db.clone() && let Some(view) = self.large.get_mut(&path) && let Some(entry) = view.prepare.take()