library: choose several games and copy them into a new database (task 42)
This commit is contained in:
parent
57a63fa455
commit
8522f30c28
13 changed files with 2050 additions and 59 deletions
|
|
@ -37,6 +37,7 @@ trainer.workspace = true
|
|||
play.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
online-games.workspace = true
|
||||
web-time.workspace = true
|
||||
sha2 = "0.11"
|
||||
|
|
|
|||
|
|
@ -299,6 +299,8 @@ pub struct App {
|
|||
repertoire: Option<crate::repertoire_ui::RepertoireUi>,
|
||||
#[cfg(not(web))]
|
||||
toast_repertoire: Option<(trainer::repertoire::RepertoireId, String)>,
|
||||
/// The database a copy of chosen games made: the toast's «Open».
|
||||
toast_open_db: Option<PathBuf>,
|
||||
applied_dark: Option<bool>,
|
||||
debug: DebugStartup,
|
||||
}
|
||||
|
|
@ -547,6 +549,7 @@ impl App {
|
|||
repertoire: None,
|
||||
#[cfg(not(web))]
|
||||
toast_repertoire: None,
|
||||
toast_open_db: None,
|
||||
applied_dark: None,
|
||||
debug: DebugStartup::from_env(),
|
||||
}
|
||||
|
|
@ -1240,6 +1243,7 @@ impl App {
|
|||
{
|
||||
self.toast_repertoire = None;
|
||||
}
|
||||
self.toast_open_db = None;
|
||||
self.toast = Some(Toast {
|
||||
text: msg.into(),
|
||||
until: ctx.input(|i| i.time) + secs,
|
||||
|
|
@ -1448,10 +1452,7 @@ impl App {
|
|||
/// The PGN text of record `index` of a database, as `current_pgn` would give it.
|
||||
fn record_pgn(&self, from: &std::path::Path, index: usize) -> Option<String> {
|
||||
let db = self.library.database(from)?;
|
||||
match db.as_pgn() {
|
||||
Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index),
|
||||
_ => db.load_game(index).map(|p| p.game.to_pgn()),
|
||||
}
|
||||
crate::batch_copy::record_text(&db, index)
|
||||
}
|
||||
|
||||
fn append_current(&mut self, ctx: &egui::Context, target: PathBuf) {
|
||||
|
|
@ -1914,6 +1915,80 @@ impl App {
|
|||
self.own.new_base = Some(own_db::NewBaseDialog::new(dir, after));
|
||||
}
|
||||
|
||||
/// Starts the copy of the chosen records of the new-database dialog into `path`
|
||||
/// (task 42): the file appears only when the copy is whole; the user stays in the
|
||||
/// source database.
|
||||
fn start_copy(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> {
|
||||
let Some(own_db::AfterCreate::CopySelection {
|
||||
path: from,
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
..
|
||||
}) = self.own.new_base.as_ref().map(|d| d.after.clone())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if path.exists() {
|
||||
return Err(tr("A file with this name is already there.").to_owned());
|
||||
}
|
||||
if self
|
||||
.library
|
||||
.start_batch(ctx, &from, records, sort, ascending, path)
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(tr("Another copy is being written: wait until it finishes").to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a copy of chosen records: a toast, and the new database on the shelf.
|
||||
fn batch_ended(&mut self, ctx: &egui::Context, end: crate::library::BatchEnd) {
|
||||
use crate::library::BatchEnd;
|
||||
match end {
|
||||
BatchEnd::Done { target, report } => {
|
||||
let name = own_db::base_name(&target);
|
||||
self.settings.touch_database(&target);
|
||||
self.settings_dirty = true;
|
||||
self.toast_for(ctx, crate::batch_copy::summary(&name, &report), 8.0);
|
||||
self.toast_open_db = Some(target);
|
||||
}
|
||||
BatchEnd::Cancelled { target } => {
|
||||
let name = own_db::base_name(&target);
|
||||
self.toast(
|
||||
ctx,
|
||||
trf(
|
||||
"Copying cancelled: «{name}» was not created",
|
||||
&[("name", &name)],
|
||||
),
|
||||
);
|
||||
}
|
||||
BatchEnd::Failed {
|
||||
source,
|
||||
target,
|
||||
error,
|
||||
} => {
|
||||
let text = match error {
|
||||
crate::batch_copy::CopyError::SourceChanged => {
|
||||
self.library.clear_selection(&source);
|
||||
trf(
|
||||
"«{src}» changed while copying. Nothing was written",
|
||||
&[("src", &own_db::base_name(&source))],
|
||||
)
|
||||
}
|
||||
e => trf(
|
||||
"Could not write «{name}»: {reason}. Nothing was written",
|
||||
&[
|
||||
("name", &own_db::base_name(&target)),
|
||||
("reason", &e.reason()),
|
||||
],
|
||||
),
|
||||
};
|
||||
self.toast_for(ctx, text, 8.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the empty file and puts it on the shelf, selected and as the database the
|
||||
/// next game goes to.
|
||||
fn create_base(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> {
|
||||
|
|
@ -2660,7 +2735,13 @@ impl App {
|
|||
NewBaseOutcome::AddExisting(p) => (false, p),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let made = if create {
|
||||
let copy = matches!(
|
||||
self.own.new_base.as_ref().map(|d| &d.after),
|
||||
Some(own_db::AfterCreate::CopySelection { .. })
|
||||
);
|
||||
let made = if copy {
|
||||
self.start_copy(ctx, path.clone())
|
||||
} else if create {
|
||||
self.create_base(ctx, path.clone())
|
||||
} else {
|
||||
self.settings.touch_database(&path);
|
||||
|
|
@ -2692,6 +2773,8 @@ impl App {
|
|||
};
|
||||
self.wait_for(ctx, &path, step)
|
||||
}
|
||||
// Started by `start_copy`; its end is a toast.
|
||||
own_db::AfterCreate::CopySelection { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -4277,6 +4360,40 @@ impl eframe::App for App {
|
|||
self.own.then_close = None;
|
||||
self.open_chooser(&ctx, ChooserFor::Record { path, index });
|
||||
}
|
||||
LibraryAction::CopySelection {
|
||||
path,
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
hidden,
|
||||
} => {
|
||||
self.own.then_close = None;
|
||||
self.new_base_dialog(own_db::AfterCreate::CopySelection {
|
||||
path,
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
hidden,
|
||||
});
|
||||
// `CP_BATCH=new:<name>`: the dialog answered at once.
|
||||
if let Some(name) = std::env::var("CP_BATCH")
|
||||
.ok()
|
||||
.and_then(|b| b.strip_prefix("new:").map(str::to_owned))
|
||||
&& let Some(d) = self.own.new_base.as_mut()
|
||||
{
|
||||
d.name = name;
|
||||
let target = d.path();
|
||||
match self.start_copy(&ctx, target) {
|
||||
Ok(()) => self.own.new_base = None,
|
||||
Err(e) => {
|
||||
if let Some(d) = self.own.new_base.as_mut() {
|
||||
d.error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
LibraryAction::Notice(text) => self.toast(&ctx, text),
|
||||
LibraryAction::EditGameData { path, index } => {
|
||||
self.open_game(&ctx, path, index, None);
|
||||
self.edit_game_data();
|
||||
|
|
@ -4404,6 +4521,10 @@ impl eframe::App for App {
|
|||
self.start_play(&ctx, start);
|
||||
}
|
||||
}
|
||||
// A copy of chosen games ends whatever is on the screen.
|
||||
if let Some(end) = self.library.poll_batch(&ctx) {
|
||||
self.batch_ended(&ctx, end);
|
||||
}
|
||||
// Ctrl+Z on the library while the deleted game can still come back.
|
||||
if self.game.is_none()
|
||||
&& self.own.undo.is_some()
|
||||
|
|
@ -4416,6 +4537,7 @@ impl eframe::App for App {
|
|||
}
|
||||
|
||||
let mut undo_clicked = false;
|
||||
let mut open_copy: Option<PathBuf> = None;
|
||||
#[cfg(not(web))]
|
||||
let mut open_repertoire = None;
|
||||
if let Some(t) = &self.toast {
|
||||
|
|
@ -4431,10 +4553,11 @@ impl eframe::App for App {
|
|||
let (msg, undo) = (t.text.clone(), t.undo && self.own.undo.is_some());
|
||||
#[cfg(not(web))]
|
||||
let repertoire_link = self.toast_repertoire.clone();
|
||||
let open_db = self.toast_open_db.clone();
|
||||
#[cfg(not(web))]
|
||||
let has_action = undo || repertoire_link.is_some();
|
||||
let has_action = undo || repertoire_link.is_some() || open_db.is_some();
|
||||
#[cfg(web)]
|
||||
let has_action = undo;
|
||||
let has_action = undo || open_db.is_some();
|
||||
let area = egui::Area::new(egui::Id::new(TOAST))
|
||||
.anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0))
|
||||
.order(egui::Order::Foreground)
|
||||
|
|
@ -4453,6 +4576,9 @@ impl eframe::App for App {
|
|||
if repertoire_link.is_some() && ui.button(tr("Open")).clicked() {
|
||||
open_repertoire = repertoire_link.clone();
|
||||
}
|
||||
if open_db.is_some() && ui.button(tr("Open")).clicked() {
|
||||
open_copy = open_db.clone();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -4470,6 +4596,11 @@ impl eframe::App for App {
|
|||
self.toast = None;
|
||||
self.undo_delete(&ctx);
|
||||
}
|
||||
if let Some(path) = open_copy {
|
||||
self.toast = None;
|
||||
self.toast_open_db = None;
|
||||
self.library.select_db(&path, &ctx);
|
||||
}
|
||||
#[cfg(not(web))]
|
||||
if let Some((id, title)) = open_repertoire {
|
||||
self.toast = None;
|
||||
|
|
@ -4490,6 +4621,7 @@ impl eframe::App for App {
|
|||
}
|
||||
|
||||
fn on_exit(&mut self) {
|
||||
self.library.stop_batch();
|
||||
self.analysis.stop();
|
||||
crate::review_engine::shutdown();
|
||||
if let Some(p) = self.prep.as_mut() {
|
||||
|
|
|
|||
354
apps/desktop/src/batch_copy.rs
Normal file
354
apps/desktop/src/batch_copy.rs
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
//! Several records of a database copied into a new database (task 42,
|
||||
//! docs/design/tasks-42-43-2026-11-27.md): the records chosen in the table, a set of
|
||||
//! record numbers that keeps a bit per record, and the copy itself, written in the
|
||||
//! 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::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
use chess_core::pgn::store;
|
||||
use chess_import::Database;
|
||||
use chess_import::chessbase::base::SortKey;
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// Records chosen in a table: one bit per record number. Membership is one lookup, and
|
||||
/// choosing all the records of a list of millions is one pass over it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Selection {
|
||||
words: Vec<u64>,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
pub fn contains(&self, index: usize) -> bool {
|
||||
self.words
|
||||
.get(index / 64)
|
||||
.is_some_and(|w| w & (1 << (index % 64)) != 0)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.count
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.count == 0
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, index: usize) {
|
||||
let word = index / 64;
|
||||
if word >= self.words.len() {
|
||||
self.words.resize(word + 1, 0);
|
||||
}
|
||||
let bit = 1 << (index % 64);
|
||||
if self.words[word] & bit == 0 {
|
||||
self.words[word] |= bit;
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, index: usize) {
|
||||
if let Some(w) = self.words.get_mut(index / 64) {
|
||||
let bit = 1 << (index % 64);
|
||||
if *w & bit != 0 {
|
||||
*w &= !bit;
|
||||
self.count -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toggle(&mut self, index: usize) {
|
||||
if self.contains(index) {
|
||||
self.remove(index);
|
||||
} else {
|
||||
self.insert(index);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.words.clear();
|
||||
self.count = 0;
|
||||
}
|
||||
|
||||
/// Only `index` chosen.
|
||||
pub fn only(&mut self, index: usize) {
|
||||
self.clear();
|
||||
self.insert(index);
|
||||
}
|
||||
|
||||
/// Adds every record of `records` (a list of the table).
|
||||
pub fn extend(&mut self, records: &[u32]) {
|
||||
if let Some(&most) = records.iter().max() {
|
||||
let words = most as usize / 64 + 1;
|
||||
if words > self.words.len() {
|
||||
self.words.resize(words, 0);
|
||||
}
|
||||
}
|
||||
for &r in records {
|
||||
let (word, bit) = (r as usize / 64, 1u64 << (r % 64));
|
||||
if self.words[word] & bit == 0 {
|
||||
self.words[word] |= bit;
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The chosen records, in the order of their numbers.
|
||||
pub fn records(&self) -> Vec<u32> {
|
||||
let mut out = Vec::with_capacity(self.count);
|
||||
for (n, &w) in self.words.iter().enumerate() {
|
||||
let mut w = w;
|
||||
while w != 0 {
|
||||
let bit = w.trailing_zeros();
|
||||
out.push((n * 64) as u32 + bit);
|
||||
w &= w - 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The highest chosen record.
|
||||
pub fn last(&self) -> Option<usize> {
|
||||
let (n, w) = self
|
||||
.words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|(_, w)| **w != 0)?;
|
||||
Some(n * 64 + 63 - w.leading_zeros() as usize)
|
||||
}
|
||||
|
||||
/// Records from `len` on let go (a database with fewer records now).
|
||||
pub fn retain_below(&mut self, len: usize) {
|
||||
while let Some(last) = self.last().filter(|&l| l >= len) {
|
||||
self.remove(last);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of `records` are chosen.
|
||||
pub fn count_in(&self, records: &[u32]) -> usize {
|
||||
if self.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
records
|
||||
.iter()
|
||||
.filter(|&&r| self.contains(r as usize))
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
/// The PGN text of record `index` as «Add to database» copies it: the record's own
|
||||
/// text when the file is PGN read without restoring letters, otherwise the game written
|
||||
/// anew (a ChessBase database has no PGN; restored letters are in the copy).
|
||||
pub fn record_text(db: &Database, index: usize) -> Option<String> {
|
||||
match db.as_pgn() {
|
||||
Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index),
|
||||
_ => db.load_game(index).map(|p| p.game.to_pgn()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What to copy: the chosen records (by number), the table's order and the new file.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CopyRequest {
|
||||
pub records: Vec<u32>,
|
||||
pub sort: SortKey,
|
||||
pub ascending: bool,
|
||||
pub target: PathBuf,
|
||||
/// A pause per record (`CP_BATCH_SLOW`): the progress can be seen and photographed.
|
||||
pub slow: bool,
|
||||
}
|
||||
|
||||
/// How a copy went.
|
||||
#[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) that could not be read.
|
||||
pub unreadable: Vec<usize>,
|
||||
}
|
||||
|
||||
impl CopyReport {
|
||||
pub fn skipped(&self) -> usize {
|
||||
self.duplicates + self.unreadable.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why nothing was written.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CopyError {
|
||||
/// A file of that name appeared meanwhile: it is not touched.
|
||||
#[error("a file with this name is already there")]
|
||||
Exists,
|
||||
/// The source file changed on disk: the record numbers no longer mean the same games.
|
||||
#[error("the source changed")]
|
||||
SourceChanged,
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
impl CopyError {
|
||||
/// The reason in the user's words.
|
||||
pub fn reason(&self) -> String {
|
||||
match self {
|
||||
CopyError::Exists => tr("a file with this name is already there").to_owned(),
|
||||
CopyError::SourceChanged => tr("the source changed").to_owned(),
|
||||
CopyError::Io(e) => match e.kind() {
|
||||
std::io::ErrorKind::StorageFull => tr("no space left on the disk").to_owned(),
|
||||
std::io::ErrorKind::PermissionDenied => tr("no permission to write").to_owned(),
|
||||
_ => e.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The temporary file of a copy; removed unless published.
|
||||
struct Partial {
|
||||
path: PathBuf,
|
||||
published: bool,
|
||||
}
|
||||
|
||||
impl Drop for Partial {
|
||||
fn drop(&mut self) {
|
||||
if !self.published {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()))
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// link, which fails rather than replace a file of that name. `None`: cancelled, nothing
|
||||
/// is left on disk.
|
||||
pub fn copy_into_new(
|
||||
db: &Database,
|
||||
req: &CopyRequest,
|
||||
progress: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<Result<CopyReport, CopyError>> {
|
||||
let mut order = req.records.clone();
|
||||
order.sort_unstable();
|
||||
db.sort_records(&mut order, req.sort, req.ascending);
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let partial = Partial {
|
||||
path: partial_path(&req.target),
|
||||
published: false,
|
||||
};
|
||||
let run = || -> Result<Option<CopyReport>, CopyError> {
|
||||
if let Some(dir) = req.target.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
if req.target.exists() {
|
||||
return Err(CopyError::Exists);
|
||||
}
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&partial.path)?;
|
||||
let mut out = std::io::BufWriter::new(file);
|
||||
let mut report = CopyReport::default();
|
||||
let mut seen = HashSet::new();
|
||||
for (n, &record) in order.iter().enumerate() {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Ok(None);
|
||||
}
|
||||
if req.slow {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
let index = record as usize;
|
||||
let text = db
|
||||
.load_game(index)
|
||||
.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)) {
|
||||
out.write_all(&store::record_for_new_file(&text))?;
|
||||
report.copied += 1;
|
||||
} else {
|
||||
report.duplicates += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
progress.store(n + 1, Ordering::Relaxed);
|
||||
}
|
||||
let file = out.into_inner().map_err(|e| e.into_error())?;
|
||||
file.sync_all()?;
|
||||
if let Some(pgn) = db.as_pgn()
|
||||
&& pgn.source_changed().unwrap_or(true)
|
||||
{
|
||||
return Err(CopyError::SourceChanged);
|
||||
}
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Ok(None);
|
||||
}
|
||||
match std::fs::hard_link(&partial.path, &req.target) {
|
||||
Ok(()) => Ok(Some(report)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(CopyError::Exists),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
};
|
||||
match run() {
|
||||
Ok(None) => None,
|
||||
Ok(Some(report)) => Some(Ok(report)),
|
||||
Err(e) => Some(Err(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// «Name: copied 3, skipped 1 — duplicates 1, unreadable 0 (No. …)».
|
||||
pub fn summary(name: &str, report: &CopyReport) -> String {
|
||||
if report.skipped() == 0 {
|
||||
return trf(
|
||||
"{name}: copied {n}, skipped {m}",
|
||||
&[("name", &name), ("n", &report.copied), ("m", &0)],
|
||||
);
|
||||
}
|
||||
let mut numbers: Vec<String> = 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}",
|
||||
&[
|
||||
("name", &name),
|
||||
("n", &report.copied),
|
||||
("m", &report.skipped()),
|
||||
("d", &report.duplicates),
|
||||
("u", &report.unreadable.len()),
|
||||
],
|
||||
);
|
||||
if !numbers.is_empty() {
|
||||
text.push_str(&format!(
|
||||
" ({})",
|
||||
trf("No. {list}", &[("list", &numbers.join(", "))])
|
||||
));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "batch_copy_tests.rs"]
|
||||
mod tests;
|
||||
389
apps/desktop/src/batch_copy_tests.rs
Normal file
389
apps/desktop/src/batch_copy_tests.rs
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
|
||||
use chess_core::PgnDatabase;
|
||||
use chess_core::pgn::store;
|
||||
|
||||
use super::*;
|
||||
|
||||
struct Dir(PathBuf);
|
||||
|
||||
impl Dir {
|
||||
fn new(name: &str) -> Dir {
|
||||
let path = std::env::temp_dir().join(format!("cp-batch-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Dir(path)
|
||||
}
|
||||
|
||||
fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
|
||||
let path = self.0.join(name);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
/// Files of the folder besides `keep` (a temporary file left behind shows here).
|
||||
fn others(&self, keep: &[&Path]) -> Vec<PathBuf> {
|
||||
std::fs::read_dir(&self.0)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().path())
|
||||
.filter(|p| !keep.contains(&p.as_path()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> Database {
|
||||
chess_import::open(path, &mut |_| {}, &AtomicBool::new(false))
|
||||
.unwrap()
|
||||
.db
|
||||
}
|
||||
|
||||
/// Games with what a copy must keep: a start position with fullmove 0, variations three
|
||||
/// deep, comments at the root and after moves, NAG, arrows, a tag of its own, and the
|
||||
/// first game once more (a duplicate).
|
||||
const SOURCE: &str = r#"[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
|
||||
|
||||
[Event "Study"]
|
||||
[Site "?"]
|
||||
[Date "2021.??.??"]
|
||||
[Round "?"]
|
||||
[White "Gamma"]
|
||||
[Black "Delta"]
|
||||
[Result "*"]
|
||||
[SetUp "1"]
|
||||
[FEN "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0"]
|
||||
|
||||
1. e4 Kd7 {the king} 2. Kf2 *
|
||||
|
||||
[Event "Club"]
|
||||
[Site "?"]
|
||||
[Date "2019.05.05"]
|
||||
[Round "2"]
|
||||
[White "Beta"]
|
||||
[Black "Alpha"]
|
||||
[Result "0-1"]
|
||||
|
||||
1. d4 d5 2. c4 $2 dxc4 0-1
|
||||
|
||||
[Event "Club again"]
|
||||
[Site "?"]
|
||||
[Date "2020.01.02"]
|
||||
[Round "1"]
|
||||
[White "alpha"]
|
||||
[Black "BETA"]
|
||||
[Result "1-0"]
|
||||
|
||||
1. e4 e5 2. Nf3 Nc6 1-0
|
||||
"#;
|
||||
|
||||
fn request(records: &[u32], target: &Path) -> CopyRequest {
|
||||
CopyRequest {
|
||||
records: records.to_vec(),
|
||||
sort: SortKey::Number,
|
||||
ascending: true,
|
||||
target: target.to_path_buf(),
|
||||
slow: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(db: &Database, req: &CopyRequest) -> Option<Result<CopyReport, CopyError>> {
|
||||
copy_into_new(db, req, &AtomicUsize::new(0), &AtomicBool::new(false))
|
||||
}
|
||||
|
||||
/// The new database as «Add to database» would make it: an empty file, then each record
|
||||
/// appended in turn, a game already there skipped.
|
||||
fn one_by_one(db: &Database, order: &[usize], target: &Path) {
|
||||
std::fs::write(target, b"").unwrap();
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_keeps_a_bit_per_record() {
|
||||
let mut s = Selection::default();
|
||||
assert!(s.is_empty() && !s.contains(5));
|
||||
s.insert(5);
|
||||
s.insert(5);
|
||||
s.insert(200);
|
||||
assert_eq!((s.len(), s.records()), (2, vec![5, 200]));
|
||||
s.toggle(5);
|
||||
s.toggle(7);
|
||||
assert_eq!(s.records(), vec![7, 200]);
|
||||
s.extend(&[1, 7, 300]);
|
||||
assert_eq!((s.len(), s.records()), (4, vec![1, 7, 200, 300]));
|
||||
assert_eq!(s.count_in(&[0, 1, 2, 300]), 2);
|
||||
s.remove(1000);
|
||||
s.remove(7);
|
||||
assert_eq!(s.len(), 3);
|
||||
assert_eq!(s.last(), Some(300));
|
||||
s.retain_below(201);
|
||||
assert_eq!(s.records(), vec![1, 200]);
|
||||
s.only(42);
|
||||
assert_eq!(s.records(), vec![42]);
|
||||
s.clear();
|
||||
assert!(s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_has_the_bytes_of_adding_the_games_one_by_one() {
|
||||
let dir = Dir::new("same");
|
||||
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);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let report = copy(&db, &request(&[3, 0, 2, 1], &target))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
// Game 4 is game 1 again (names without case, the same date and moves).
|
||||
assert_eq!(
|
||||
report,
|
||||
CopyReport {
|
||||
copied: 3,
|
||||
duplicates: 1,
|
||||
unreadable: Vec::new()
|
||||
}
|
||||
);
|
||||
let expected = dir.0.join("expected.pgn");
|
||||
one_by_one(&db, &[0, 1, 2, 3], &expected);
|
||||
assert_eq!(
|
||||
std::fs::read(&target).unwrap(),
|
||||
std::fs::read(&expected).unwrap()
|
||||
);
|
||||
// The source is only read; no temporary file is left.
|
||||
assert_eq!(std::fs::read(&source).unwrap(), before);
|
||||
assert!(dir.others(&[&source, &target, &expected]).is_empty());
|
||||
// Every game whole: tags, start position, variations, comments, NAG, arrows.
|
||||
let copied = open(&target);
|
||||
for (i, j) in [(0, 0), (1, 1), (2, 2)] {
|
||||
assert_eq!(
|
||||
copied.load_game(j).unwrap().game.to_pgn(),
|
||||
db.load_game(i).unwrap().game.to_pgn()
|
||||
);
|
||||
}
|
||||
let text = std::fs::read_to_string(&target).unwrap();
|
||||
for kept in [
|
||||
"[MyTag \"kept\"]",
|
||||
"{A comment at the root}",
|
||||
"$1",
|
||||
"[%cal Ge2e4]",
|
||||
"(2... Nf6 3. e5)",
|
||||
"4k3/8/8/8/8/8/4P3/4K3 w - - 0 0",
|
||||
] {
|
||||
assert!(text.contains(kept), "{kept}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_follows_the_tables_order() {
|
||||
let dir = Dir::new("order");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let req = CopyRequest {
|
||||
sort: SortKey::White,
|
||||
ascending: false,
|
||||
..request(&[0, 1, 2], &target)
|
||||
};
|
||||
copy(&db, &req).unwrap().unwrap();
|
||||
let mut table = vec![0, 1, 2];
|
||||
db.sort_records(&mut table, SortKey::White, false);
|
||||
let whites: Vec<String> = (0..3)
|
||||
.map(|i| {
|
||||
open(&target)
|
||||
.load_game(i)
|
||||
.unwrap()
|
||||
.game
|
||||
.tag("White")
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
})
|
||||
.collect();
|
||||
let wanted: Vec<String> = table
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
db.load_game(i as usize)
|
||||
.unwrap()
|
||||
.game
|
||||
.tag("White")
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(whites, wanted);
|
||||
assert_eq!(whites, ["Gamma", "Beta", "Alpha"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_copy_leaves_nothing() {
|
||||
let dir = Dir::new("cancel");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let cancel = AtomicBool::new(true);
|
||||
let got = copy_into_new(
|
||||
&db,
|
||||
&request(&[0, 1], &target),
|
||||
&AtomicUsize::new(0),
|
||||
&cancel,
|
||||
);
|
||||
assert!(got.is_none());
|
||||
assert!(!target.exists());
|
||||
assert!(dir.others(&[&source]).is_empty());
|
||||
|
||||
// Cancelled while writing (another thread, a slow copy).
|
||||
let cancel = std::sync::Arc::new(AtomicBool::new(false));
|
||||
let progress = std::sync::Arc::new(AtomicUsize::new(0));
|
||||
let (c, p) = (cancel.clone(), progress.clone());
|
||||
let req = CopyRequest {
|
||||
slow: true,
|
||||
..request(&[0, 1, 2, 3], &target)
|
||||
};
|
||||
let worker = std::thread::spawn(move || copy_into_new(&db, &req, &p, &c));
|
||||
while progress.load(std::sync::atomic::Ordering::Relaxed) == 0 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
cancel.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
assert!(worker.join().unwrap().is_none());
|
||||
assert!(!target.exists());
|
||||
assert!(dir.others(&[&source]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_never_replaces_a_file() {
|
||||
let dir = Dir::new("exists");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.file("copy.pgn", b"mine");
|
||||
let got = copy(&db, &request(&[0], &target)).unwrap();
|
||||
assert!(matches!(got, Err(CopyError::Exists)));
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"mine");
|
||||
assert!(dir.others(&[&source, &target]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_changed_while_copying_writes_nothing() {
|
||||
let dir = Dir::new("changed");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
std::fs::write(&source, format!("{SOURCE}\n[White \"x\"]\n\n1. e4 *\n")).unwrap();
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let got = copy(&db, &request(&[0], &target)).unwrap();
|
||||
assert!(matches!(got, Err(CopyError::SourceChanged)));
|
||||
assert!(!target.exists());
|
||||
assert!(dir.others(&[&source]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_source_is_copied_as_its_text_reads() {
|
||||
let dir = Dir::new("legacy");
|
||||
// windows-1252: «é», «ü» and «—» are one byte each.
|
||||
let mut bytes = b"[Event \"Caf\xe9\"]\n[White \"M\xfcller\"]\n[Black \"Ren\xe9\"]\n[Result \"1-0\"]\n\n{Le d\xe9but \x97 bien} 1. e4 e5 1-0\n".to_vec();
|
||||
bytes.extend_from_slice(b"\n[White \"B\"]\n[Black \"C\"]\n[Result \"*\"]\n\n1. d4 *\n");
|
||||
let source = dir.file("legacy.pgn", &bytes);
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
copy(&db, &request(&[0, 1], &target)).unwrap().unwrap();
|
||||
let expected = dir.0.join("expected.pgn");
|
||||
one_by_one(&db, &[0, 1], &expected);
|
||||
assert_eq!(
|
||||
std::fs::read(&target).unwrap(),
|
||||
std::fs::read(&expected).unwrap()
|
||||
);
|
||||
let copied = open(&target);
|
||||
let (a, b) = (
|
||||
db.load_game(0).unwrap().game,
|
||||
copied.load_game(0).unwrap().game,
|
||||
);
|
||||
assert_eq!(a.tag("White"), b.tag("White"));
|
||||
assert_eq!(a.to_pgn(), b.to_pgn());
|
||||
assert!(String::from_utf8(std::fs::read(&target).unwrap()).is_ok());
|
||||
assert_eq!(std::fs::read(&source).unwrap(), bytes);
|
||||
}
|
||||
|
||||
/// windows-1251 bytes of `text` (ASCII and the Russian letters without «ё»).
|
||||
fn cp1251(text: &str) -> Vec<u8> {
|
||||
text.chars()
|
||||
.map(|c| match c {
|
||||
'А'..='я' => (c as u32 - 'А' as u32 + 0xC0) as u8,
|
||||
c => c as u8,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_with_restored_letters_is_copied_as_adding_one_game() {
|
||||
let dir = Dir::new("repair");
|
||||
// `~~`, `o^` and `><` stand for ч, ю and Ч in old Russian files; restored on reading
|
||||
// (a copy has the restored text, as a game added alone; tasks.md, task 42, Д1).
|
||||
let comment = "{Клo^~~евые поля, ><ерные играo^т, ~~ерные} ".repeat(12);
|
||||
let text = format!(
|
||||
"[White \"Петров\"]\n[Black \"Иванов\"]\n[Result \"*\"]\n\n{comment}1. e4 *\n\n[White \"Б\"]\n[Black \"В\"]\n[Result \"*\"]\n\n{{~~ерные}} 1. d4 *\n"
|
||||
);
|
||||
let bytes = cp1251(&text);
|
||||
let source = dir.file("repair.pgn", &bytes);
|
||||
let db = open(&source);
|
||||
assert!(db.as_pgn().is_some_and(|p| p.repair_letters_enabled()));
|
||||
let target = dir.0.join("copy.pgn");
|
||||
copy(&db, &request(&[0, 1], &target)).unwrap().unwrap();
|
||||
let expected = dir.0.join("expected.pgn");
|
||||
one_by_one(&db, &[0, 1], &expected);
|
||||
assert_eq!(
|
||||
std::fs::read(&target).unwrap(),
|
||||
std::fs::read(&expected).unwrap()
|
||||
);
|
||||
assert!(std::fs::read_to_string(&target).unwrap().contains("ерные"));
|
||||
assert_eq!(std::fs::read(&source).unwrap(), bytes);
|
||||
}
|
||||
|
||||
/// Copying 1000 games and choosing 4 million rows: timed (`cargo test -- --ignored
|
||||
/// --nocapture`, release for figures).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn timing() {
|
||||
let dir = Dir::new("timing");
|
||||
let mut text = String::new();
|
||||
for i in 0..1000 {
|
||||
text.push_str(&format!(
|
||||
"[Event \"E\"]\n[White \"W{i}\"]\n[Black \"B{i}\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 (2. f4 exf4 {{gambit}}) Nc6 3. Bb5 $1 a6 4. Ba4 Nf6 5. O-O Be7 *\n\n"
|
||||
));
|
||||
}
|
||||
let source = dir.file("source.pgn", text.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let records: Vec<u32> = (0..1000).collect();
|
||||
let t = std::time::Instant::now();
|
||||
let report = copy(&db, &request(&records, &target)).unwrap().unwrap();
|
||||
println!(
|
||||
"copy 1000 games: {:?} ({} copied)",
|
||||
t.elapsed(),
|
||||
report.copied
|
||||
);
|
||||
let view: Vec<u32> = (0..4_000_000).collect();
|
||||
let t = std::time::Instant::now();
|
||||
let mut s = Selection::default();
|
||||
s.extend(&view);
|
||||
println!("select all of 4 000 000: {:?}", t.elapsed());
|
||||
let t = std::time::Instant::now();
|
||||
let n = s.count_in(&view);
|
||||
println!("count chosen in 4 000 000: {:?} ({n})", t.elapsed());
|
||||
}
|
||||
|
|
@ -930,6 +930,11 @@ impl<T: Send + 'static> Background<T> {
|
|||
pub fn cancel(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Waits up to `timeout` for the result (the work cleans up after itself).
|
||||
pub fn wait(&self, timeout: std::time::Duration) -> Option<Option<T>> {
|
||||
self.rx.recv_timeout(timeout).ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Background<T> {
|
||||
|
|
|
|||
|
|
@ -19618,6 +19618,325 @@ const ROWS: &[[&str; 9]] = &[
|
|||
"Oxirgi mashg‘ulot",
|
||||
"Соңғы жаттығу",
|
||||
],
|
||||
[
|
||||
"Selected: {n}",
|
||||
"Выбрано: {n}",
|
||||
"Sélection : {n}",
|
||||
"Ausgewählt: {n}",
|
||||
"Seleccionadas: {n}",
|
||||
"Selezionate: {n}",
|
||||
"Selecionadas: {n}",
|
||||
"Tanlangan: {n}",
|
||||
"Таңдалды: {n}",
|
||||
],
|
||||
[
|
||||
"Selected: {n} ({k} hidden by the filter)",
|
||||
"Выбрано: {n} ({k} скрыто фильтром)",
|
||||
"Sélection : {n} ({k} masquées par le filtre)",
|
||||
"Ausgewählt: {n} ({k} vom Filter verborgen)",
|
||||
"Seleccionadas: {n} ({k} ocultas por el filtro)",
|
||||
"Selezionate: {n} ({k} nascoste dal filtro)",
|
||||
"Selecionadas: {n} ({k} ocultas pelo filtro)",
|
||||
"Tanlangan: {n} ({k} tasi filtr bilan yashirilgan)",
|
||||
"Таңдалды: {n} ({k} сүзгімен жасырылған)",
|
||||
],
|
||||
[
|
||||
"Deselect",
|
||||
"Снять",
|
||||
"Désélectionner",
|
||||
"Abwählen",
|
||||
"Deseleccionar",
|
||||
"Deseleziona",
|
||||
"Desmarcar",
|
||||
"Bekor qilish",
|
||||
"Алып тастау",
|
||||
],
|
||||
[
|
||||
"Clear the selection (Esc)",
|
||||
"Снять выделение (Esc)",
|
||||
"Annuler la sélection (Échap)",
|
||||
"Auswahl aufheben (Esc)",
|
||||
"Quitar la selección (Esc)",
|
||||
"Annulla la selezione (Esc)",
|
||||
"Limpar a seleção (Esc)",
|
||||
"Tanlovni bekor qilish (Esc)",
|
||||
"Таңдауды алып тастау (Esc)",
|
||||
],
|
||||
[
|
||||
"Games hidden by the filter will be copied too. Esc clears the selection",
|
||||
"Скрытые фильтром партии тоже будут скопированы. Снять выделение — Esc",
|
||||
"Les parties masquées par le filtre seront aussi copiées. Échap annule la sélection",
|
||||
"Vom Filter verborgene Partien werden mitkopiert. Esc hebt die Auswahl auf",
|
||||
"Las partidas ocultas por el filtro también se copiarán. Esc quita la selección",
|
||||
"Anche le partite nascoste dal filtro saranno copiate. Esc annulla la selezione",
|
||||
"As partidas ocultas pelo filtro também serão copiadas. Esc limpa a seleção",
|
||||
"Filtr yashirgan partiyalar ham nusxalanadi. Esc — tanlovni bekor qilish",
|
||||
"Сүзгі жасырған партиялар да көшіріледі. Esc — таңдауды алып тастау",
|
||||
],
|
||||
[
|
||||
"Games selected: {n}",
|
||||
"Выбрано партий: {n}",
|
||||
"Parties sélectionnées : {n}",
|
||||
"Ausgewählte Partien: {n}",
|
||||
"Partidas seleccionadas: {n}",
|
||||
"Partite selezionate: {n}",
|
||||
"Partidas selecionadas: {n}",
|
||||
"Tanlangan partiyalar: {n}",
|
||||
"Таңдалған партиялар: {n}",
|
||||
],
|
||||
[
|
||||
"New database from selected…",
|
||||
"Новая база из выбранных…",
|
||||
"Nouvelle base à partir de la sélection…",
|
||||
"Neue Datenbank aus Auswahl…",
|
||||
"Nueva base con las seleccionadas…",
|
||||
"Nuovo database dalle selezionate…",
|
||||
"Nova base a partir das selecionadas…",
|
||||
"Tanlanganlardan yangi baza…",
|
||||
"Таңдалғандардан жаңа база…",
|
||||
],
|
||||
[
|
||||
"Select all (Ctrl+A)",
|
||||
"Выделить все (Ctrl+A)",
|
||||
"Tout sélectionner (Ctrl+A)",
|
||||
"Alle auswählen (Strg+A)",
|
||||
"Seleccionar todo (Ctrl+A)",
|
||||
"Seleziona tutto (Ctrl+A)",
|
||||
"Selecionar tudo (Ctrl+A)",
|
||||
"Hammasini tanlash (Ctrl+A)",
|
||||
"Барлығын таңдау (Ctrl+A)",
|
||||
],
|
||||
[
|
||||
"Clear selection (Esc)",
|
||||
"Снять выделение (Esc)",
|
||||
"Annuler la sélection (Échap)",
|
||||
"Auswahl aufheben (Esc)",
|
||||
"Quitar selección (Esc)",
|
||||
"Annulla selezione (Esc)",
|
||||
"Limpar seleção (Esc)",
|
||||
"Tanlovni bekor qilish (Esc)",
|
||||
"Таңдауды алып тастау (Esc)",
|
||||
],
|
||||
[
|
||||
"Writing to «{name}» — wait until it finishes",
|
||||
"Идёт запись в «{name}» — дождитесь окончания",
|
||||
"Écriture dans « {name} » — attendez la fin",
|
||||
"Schreibe in «{name}» — warten Sie, bis es fertig ist",
|
||||
"Escribiendo en «{name}»: espere a que termine",
|
||||
"Scrittura in «{name}» — attendi la fine",
|
||||
"Gravando em «{name}» — aguarde o fim",
|
||||
"«{name}» ga yozilmoqda — tugashini kuting",
|
||||
"«{name}» ішіне жазылуда — аяқталуын күтіңіз",
|
||||
],
|
||||
[
|
||||
"From the selection: {games} from «{src}»",
|
||||
"Из выбранных: {games} из «{src}»",
|
||||
"De la sélection : {games} de « {src} »",
|
||||
"Aus der Auswahl: {games} aus «{src}»",
|
||||
"De la selección: {games} de «{src}»",
|
||||
"Dalla selezione: {games} da «{src}»",
|
||||
"Da seleção: {games} de «{src}»",
|
||||
"Tanlovdan: «{src}» dan {games}",
|
||||
"Таңдаудан: «{src}» ішінен {games}",
|
||||
],
|
||||
[
|
||||
"{k} of them are hidden by the filter now",
|
||||
"из них {k} сейчас скрыты фильтром",
|
||||
"dont {k} masquées par le filtre",
|
||||
"davon {k} gerade vom Filter verborgen",
|
||||
"{k} de ellas ocultas ahora por el filtro",
|
||||
"di cui {k} ora nascoste dal filtro",
|
||||
"{k} delas ocultas agora pelo filtro",
|
||||
"ulardan {k} tasi hozir filtr bilan yashirilgan",
|
||||
"олардың {k} қазір сүзгімен жасырылған",
|
||||
],
|
||||
[
|
||||
"Many games: writing may take a few minutes; you can cancel it",
|
||||
"Много партий: запись может занять несколько минут, её можно отменить",
|
||||
"Beaucoup de parties : l’écriture peut prendre quelques minutes ; vous pouvez l’annuler",
|
||||
"Viele Partien: das Schreiben kann einige Minuten dauern; Sie können es abbrechen",
|
||||
"Muchas partidas: la escritura puede tardar unos minutos; se puede cancelar",
|
||||
"Molte partite: la scrittura può richiedere alcuni minuti; puoi annullarla",
|
||||
"Muitas partidas: a gravação pode levar alguns minutos; pode cancelá-la",
|
||||
"Partiyalar ko‘p: yozish bir necha daqiqa olishi mumkin, uni bekor qilish mumkin",
|
||||
"Партиялар көп: жазу бірнеше минутқа созылуы мүмкін, оны тоқтатуға болады",
|
||||
],
|
||||
[
|
||||
"Create and copy",
|
||||
"Создать и скопировать",
|
||||
"Créer et copier",
|
||||
"Erstellen und kopieren",
|
||||
"Crear y copiar",
|
||||
"Crea e copia",
|
||||
"Criar e copiar",
|
||||
"Yaratish va nusxalash",
|
||||
"Жасау және көшіру",
|
||||
],
|
||||
[
|
||||
"Writing to «{name}»: {i} of {n}",
|
||||
"Запись в «{name}»: {i} из {n}",
|
||||
"Écriture dans « {name} » : {i} sur {n}",
|
||||
"Schreibe in «{name}»: {i} von {n}",
|
||||
"Escribiendo en «{name}»: {i} de {n}",
|
||||
"Scrittura in «{name}»: {i} di {n}",
|
||||
"Gravando em «{name}»: {i} de {n}",
|
||||
"«{name}» ga yozilmoqda: {n} dan {i}",
|
||||
"«{name}» ішіне жазу: {n} ішінен {i}",
|
||||
],
|
||||
[
|
||||
"Cancelling…",
|
||||
"Отмена…",
|
||||
"Annulation…",
|
||||
"Wird abgebrochen…",
|
||||
"Cancelando…",
|
||||
"Annullamento…",
|
||||
"Cancelando…",
|
||||
"Bekor qilinmoqda…",
|
||||
"Тоқтатылуда…",
|
||||
],
|
||||
[
|
||||
"{name}: copied {n}, skipped {m}",
|
||||
"{name}: скопировано {n}, пропущено {m}",
|
||||
"{name} : {n} copiées, {m} ignorées",
|
||||
"{name}: {n} kopiert, {m} übersprungen",
|
||||
"{name}: copiadas {n}, omitidas {m}",
|
||||
"{name}: copiate {n}, saltate {m}",
|
||||
"{name}: copiadas {n}, ignoradas {m}",
|
||||
"{name}: {n} ta nusxalandi, {m} ta o‘tkazildi",
|
||||
"{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}",
|
||||
],
|
||||
[
|
||||
"No. {list}",
|
||||
"№ {list}",
|
||||
"n° {list}",
|
||||
"Nr. {list}",
|
||||
"n.º {list}",
|
||||
"n. {list}",
|
||||
"n.º {list}",
|
||||
"№ {list}",
|
||||
"№ {list}",
|
||||
],
|
||||
[
|
||||
"and {n} more",
|
||||
"и ещё {n}",
|
||||
"et {n} de plus",
|
||||
"und {n} weitere",
|
||||
"y {n} más",
|
||||
"e altre {n}",
|
||||
"e mais {n}",
|
||||
"va yana {n} ta",
|
||||
"және тағы {n}",
|
||||
],
|
||||
[
|
||||
"Copying cancelled: «{name}» was not created",
|
||||
"Копирование отменено: база «{name}» не создана",
|
||||
"Copie annulée : « {name} » n’a pas été créée",
|
||||
"Kopieren abgebrochen: «{name}» wurde nicht erstellt",
|
||||
"Copia cancelada: «{name}» no se ha creado",
|
||||
"Copia annullata: «{name}» non è stato creato",
|
||||
"Cópia cancelada: «{name}» não foi criada",
|
||||
"Nusxalash bekor qilindi: «{name}» yaratilmadi",
|
||||
"Көшіру тоқтатылды: «{name}» жасалмады",
|
||||
],
|
||||
[
|
||||
"Could not write «{name}»: {reason}. Nothing was written",
|
||||
"Не удалось записать «{name}»: {reason}. Ничего не записано",
|
||||
"Impossible d’écrire « {name} » : {reason}. Rien n’a été écrit",
|
||||
"«{name}» konnte nicht geschrieben werden: {reason}. Nichts wurde geschrieben",
|
||||
"No se pudo escribir «{name}»: {reason}. No se escribió nada",
|
||||
"Impossibile scrivere «{name}»: {reason}. Non è stato scritto nulla",
|
||||
"Não foi possível gravar «{name}»: {reason}. Nada foi gravado",
|
||||
"«{name}» ni yozib bo‘lmadi: {reason}. Hech narsa yozilmadi",
|
||||
"«{name}» жазылмады: {reason}. Ештеңе жазылған жоқ",
|
||||
],
|
||||
[
|
||||
"«{src}» changed while copying. Nothing was written",
|
||||
"База «{src}» изменилась во время копирования. Ничего не записано",
|
||||
"« {src} » a changé pendant la copie. Rien n’a été écrit",
|
||||
"«{src}» hat sich beim Kopieren geändert. Nichts wurde geschrieben",
|
||||
"«{src}» cambió durante la copia. No se escribió nada",
|
||||
"«{src}» è cambiato durante la copia. Non è stato scritto nulla",
|
||||
"«{src}» mudou durante a cópia. Nada foi gravado",
|
||||
"«{src}» nusxalash paytida o‘zgardi. Hech narsa yozilmadi",
|
||||
"«{src}» көшіру кезінде өзгерді. Ештеңе жазылған жоқ",
|
||||
],
|
||||
[
|
||||
"Games are deleted one at a time: clear the selection (Esc)",
|
||||
"Удалять можно по одной партии: снимите выделение (Esc)",
|
||||
"Les parties se suppriment une par une : annulez la sélection (Échap)",
|
||||
"Partien werden einzeln gelöscht: heben Sie die Auswahl auf (Esc)",
|
||||
"Las partidas se borran de una en una: quite la selección (Esc)",
|
||||
"Le partite si eliminano una alla volta: annulla la selezione (Esc)",
|
||||
"As partidas são apagadas uma de cada vez: limpe a seleção (Esc)",
|
||||
"Partiyalar bittadan o‘chiriladi: tanlovni bekor qiling (Esc)",
|
||||
"Партиялар бір-бірден жойылады: таңдауды алып тастаңыз (Esc)",
|
||||
],
|
||||
[
|
||||
"a file with this name is already there",
|
||||
"файл с таким именем уже есть",
|
||||
"un fichier de ce nom existe déjà",
|
||||
"eine Datei mit diesem Namen gibt es schon",
|
||||
"ya existe un archivo con ese nombre",
|
||||
"esiste già un file con questo nome",
|
||||
"já existe um ficheiro com este nome",
|
||||
"bu nomli fayl allaqachon bor",
|
||||
"мұндай атаулы файл бар",
|
||||
],
|
||||
[
|
||||
"the source changed",
|
||||
"источник изменился",
|
||||
"la source a changé",
|
||||
"die Quelle hat sich geändert",
|
||||
"el origen cambió",
|
||||
"la sorgente è cambiata",
|
||||
"a origem mudou",
|
||||
"manba o‘zgardi",
|
||||
"көз өзгерді",
|
||||
],
|
||||
[
|
||||
"no space left on the disk",
|
||||
"на диске нет места",
|
||||
"plus d’espace sur le disque",
|
||||
"kein Platz mehr auf dem Datenträger",
|
||||
"no queda espacio en el disco",
|
||||
"spazio su disco esaurito",
|
||||
"sem espaço no disco",
|
||||
"diskda joy qolmadi",
|
||||
"дискіде орын жоқ",
|
||||
],
|
||||
[
|
||||
"no permission to write",
|
||||
"нет прав на запись",
|
||||
"pas de droit d’écriture",
|
||||
"keine Schreibrechte",
|
||||
"sin permiso de escritura",
|
||||
"nessun permesso di scrittura",
|
||||
"sem permissão de escrita",
|
||||
"yozishga ruxsat yo‘q",
|
||||
"жазуға рұқсат жоқ",
|
||||
],
|
||||
[
|
||||
"Another copy is being written: wait until it finishes",
|
||||
"Идёт другая запись: дождитесь окончания",
|
||||
"Une autre copie est en cours d’écriture : attendez la fin",
|
||||
"Eine andere Kopie wird geschrieben: warten Sie, bis sie fertig ist",
|
||||
"Se está escribiendo otra copia: espere a que termine",
|
||||
"È in corso un’altra copia: attendi la fine",
|
||||
"Outra cópia está a ser gravada: aguarde o fim",
|
||||
"Boshqa nusxa yozilmoqda: tugashini kuting",
|
||||
"Басқа көшірме жазылуда: аяқталуын күтіңіз",
|
||||
],
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -19681,6 +20000,7 @@ mod tests {
|
|||
include_str!("opening_lines.rs"),
|
||||
include_str!("opening_session.rs"),
|
||||
include_str!("repertoire_ui.rs"),
|
||||
include_str!("batch_copy.rs"),
|
||||
];
|
||||
let mut chars = std::collections::BTreeSet::new();
|
||||
for row in ROWS.iter() {
|
||||
|
|
|
|||
|
|
@ -278,6 +278,15 @@ struct Suggestions {
|
|||
highlighted: Option<usize>,
|
||||
}
|
||||
|
||||
/// A copy of chosen records being written, as the conditions line shows it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BatchStatus {
|
||||
pub name: String,
|
||||
pub done: usize,
|
||||
pub total: usize,
|
||||
pub cancelling: bool,
|
||||
}
|
||||
|
||||
/// State of one large database in the library (kept for the session).
|
||||
pub struct LargeView {
|
||||
form: Form,
|
||||
|
|
@ -307,8 +316,20 @@ pub struct LargeView {
|
|||
suggestions: Option<Suggestions>,
|
||||
/// The pointer is on the open suggestion list.
|
||||
pointer_on_list: bool,
|
||||
/// Record index of the selected row.
|
||||
/// Record index of the row under the keyboard cursor: Enter, F2 and «Board» take it.
|
||||
pub selected: Option<usize>,
|
||||
/// The records chosen (task 42): one or many, kept across filters and sorting.
|
||||
marked: crate::batch_copy::Selection,
|
||||
/// Where a Shift range starts.
|
||||
anchor: Option<usize>,
|
||||
/// Changes of `marked` and of `view`, and the chosen records the list hides then.
|
||||
marked_gen: u64,
|
||||
view_gen: u64,
|
||||
hidden: Option<(u64, u64, usize)>,
|
||||
/// The copy of chosen records being written (set by the library each frame).
|
||||
pub batch: Option<BatchStatus>,
|
||||
/// «Cancel» of that copy was clicked.
|
||||
pub cancel_batch: bool,
|
||||
scroll_to_selected: bool,
|
||||
scroll_to_top: bool,
|
||||
focus_player: bool,
|
||||
|
|
@ -386,6 +407,21 @@ impl LargeView {
|
|||
}
|
||||
let drawer = pane_env.as_deref() == Some("drawer");
|
||||
// `CP_SORT=date`: newest games first (screenshots).
|
||||
// `CP_SELECT=3,7,15`: these records (their numbers in the table) chosen, the
|
||||
// cursor on the last (screenshots of task 42).
|
||||
let mut marked = crate::batch_copy::Selection::default();
|
||||
let mut cursor = None;
|
||||
if let Ok(list) = std::env::var("CP_SELECT") {
|
||||
for n in list
|
||||
.split(',')
|
||||
.filter_map(|n| n.trim().parse::<usize>().ok())
|
||||
{
|
||||
if n > 0 {
|
||||
marked.insert(n - 1);
|
||||
cursor = Some(n - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
let sort = if std::env::var("CP_SORT").as_deref() == Ok("date") {
|
||||
(SortKey::Date, false)
|
||||
} else {
|
||||
|
|
@ -410,7 +446,14 @@ impl LargeView {
|
|||
suggest_job: None,
|
||||
suggestions: None,
|
||||
pointer_on_list: false,
|
||||
selected: None,
|
||||
selected: cursor,
|
||||
marked,
|
||||
anchor: cursor,
|
||||
marked_gen: 0,
|
||||
view_gen: 0,
|
||||
hidden: None,
|
||||
batch: None,
|
||||
cancel_batch: false,
|
||||
scroll_to_selected: false,
|
||||
scroll_to_top: false,
|
||||
focus_player: false,
|
||||
|
|
@ -454,14 +497,143 @@ 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects a record and scrolls to it (returning from a game).
|
||||
/// Selects a record and scrolls to it (returning from a game): a choice of several
|
||||
/// records stays.
|
||||
pub fn reveal(&mut self, index: usize) {
|
||||
self.selected = Some(index);
|
||||
if self.marked.len() <= 1 {
|
||||
self.mark(|m| m.only(index));
|
||||
}
|
||||
self.scroll_to_selected = true;
|
||||
}
|
||||
|
||||
/// Changes the chosen records.
|
||||
fn mark(&mut self, change: impl FnOnce(&mut crate::batch_copy::Selection)) {
|
||||
change(&mut self.marked);
|
||||
self.marked_gen += 1;
|
||||
}
|
||||
|
||||
/// No record chosen any more.
|
||||
pub fn clear_marks(&mut self) {
|
||||
self.mark(|m| m.clear());
|
||||
self.anchor = None;
|
||||
}
|
||||
|
||||
/// The chosen records hidden by the list's filter, counted once per change.
|
||||
fn hidden_marked(&mut self) -> usize {
|
||||
let key = (self.marked_gen, self.view_gen);
|
||||
match self.hidden {
|
||||
Some((m, v, n)) if (m, v) == key => n,
|
||||
_ => {
|
||||
let n = self.marked.len() - self.marked.count_in(&self.view);
|
||||
self.hidden = Some((key.0, key.1, n));
|
||||
n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The choice comes down to the cursor's row (Esc, «Clear», a row deleted).
|
||||
fn mark_cursor_only(&mut self) {
|
||||
let cursor = self.selected;
|
||||
self.mark(|m| match cursor {
|
||||
Some(i) => m.only(i),
|
||||
None => m.clear(),
|
||||
});
|
||||
self.anchor = cursor;
|
||||
}
|
||||
|
||||
/// The records of the view from position `a` to position `b` (either order).
|
||||
fn range(&self, a: usize, b: usize) -> &[u32] {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
&self.view[lo..=hi.min(self.view.len().saturating_sub(1))]
|
||||
}
|
||||
|
||||
fn position_of(&self, record: usize) -> Option<usize> {
|
||||
self.view.iter().position(|&i| i as usize == record)
|
||||
}
|
||||
|
||||
/// A click on the row of `index` with `mods` (§42.5).
|
||||
fn click(&mut self, index: usize, mods: egui::Modifiers) {
|
||||
// An anchor hidden by the filter: the cursor, when it is seen, starts the range.
|
||||
let anchor = self
|
||||
.anchor
|
||||
.filter(|a| self.position_of(*a).is_some())
|
||||
.or(self.selected.filter(|c| self.position_of(*c).is_some()));
|
||||
let at = self.position_of(index);
|
||||
match (
|
||||
mods.command,
|
||||
mods.shift,
|
||||
anchor.and_then(|a| self.position_of(a)),
|
||||
at,
|
||||
) {
|
||||
(add, true, Some(a), Some(b)) => {
|
||||
let range = self.range(a, b).to_vec();
|
||||
self.mark(|m| {
|
||||
if !add {
|
||||
m.clear();
|
||||
}
|
||||
m.extend(&range);
|
||||
});
|
||||
}
|
||||
(true, false, _, _) => {
|
||||
self.mark(|m| m.toggle(index));
|
||||
self.anchor = Some(index);
|
||||
}
|
||||
_ => {
|
||||
self.mark(|m| m.only(index));
|
||||
self.anchor = Some(index);
|
||||
}
|
||||
}
|
||||
self.selected = Some(index);
|
||||
}
|
||||
|
||||
/// Every row of the list chosen (Ctrl+A): the list's records only.
|
||||
fn select_all(&mut self) {
|
||||
let view = std::mem::take(&mut self.view);
|
||||
self.mark(|m| m.extend(&view));
|
||||
self.view = view;
|
||||
if self.selected.is_none() {
|
||||
self.selected = self.view.first().map(|&i| i as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// «New database from selected…»: the library opens the dialog (none while another
|
||||
/// copy is written).
|
||||
fn ask_copy(&mut self, path: &Path, actions: &mut Vec<LibraryAction>) {
|
||||
if self.batch.is_some() || !crate::platform::CAPS.batch_copy {
|
||||
return;
|
||||
}
|
||||
let (records, sort, ascending) = self.copy_request();
|
||||
actions.push(LibraryAction::CopySelection {
|
||||
path: path.to_path_buf(),
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
hidden: self.hidden_marked(),
|
||||
});
|
||||
}
|
||||
|
||||
/// The chosen records for a copy, in the table's order once sorted by the copy.
|
||||
fn copy_request(&self) -> (Vec<u32>, SortKey, bool) {
|
||||
let (sort, ascending) = if self.blocked.is_some() {
|
||||
self.sort
|
||||
} else {
|
||||
self.effective_sort()
|
||||
};
|
||||
(self.marked.records(), sort, ascending)
|
||||
}
|
||||
|
||||
pub fn pane(&self) -> Pane {
|
||||
self.pane
|
||||
}
|
||||
|
|
@ -525,6 +697,9 @@ impl LargeView {
|
|||
} else if self.drawer().is_some() {
|
||||
self.drawer_open = false;
|
||||
true
|
||||
} else if self.marked.len() >= 2 {
|
||||
self.mark_cursor_only();
|
||||
true
|
||||
} else if self.board_alone() {
|
||||
self.pane = Pane::Hidden;
|
||||
true
|
||||
|
|
@ -623,17 +798,23 @@ impl LargeView {
|
|||
);
|
||||
}
|
||||
self.view = answer.view;
|
||||
self.view_gen += 1;
|
||||
self.outcome = answer.outcome;
|
||||
self.in_order = answer.in_order;
|
||||
self.blocked = answer.blocked;
|
||||
self.shown = Some(job.request);
|
||||
// A selected game that left the list is no longer selected, so Enter
|
||||
// cannot open a game the user does not see.
|
||||
// A choice of several records stays: it is built from several searches,
|
||||
// and its hidden part is counted.
|
||||
if let Some(sel) = self.selected
|
||||
&& new_filter
|
||||
&& !self.view.contains(&(sel as u32))
|
||||
{
|
||||
self.selected = None;
|
||||
if self.marked.len() <= 1 {
|
||||
self.mark(|m| m.clear());
|
||||
}
|
||||
}
|
||||
if new_filter {
|
||||
// The user looks at the result of the new filter from its top.
|
||||
|
|
@ -1161,9 +1342,19 @@ impl LargeView {
|
|||
let mut clear = None;
|
||||
let mut goto = None;
|
||||
let mut toggle_order = false;
|
||||
let chosen = self.marked.len();
|
||||
let hidden = if chosen >= 2 { self.hidden_marked() } else { 0 };
|
||||
let batch = self.batch.clone();
|
||||
let mut clear_marked = false;
|
||||
let mut cancel_batch = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_min_height(22.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
// Right to left (docs/design/task-27-brilliant-search-2026-11-27.md §4.1):
|
||||
// the slot of the far right, the move order, the choice or its copy, the
|
||||
// conditions. The far right slot keeps one width whatever it shows, so what
|
||||
// stands left of it does not move when it changes.
|
||||
Self::right_slot(ui, RIGHT_SLOT_W);
|
||||
if let Some((same, all)) = self.in_order
|
||||
&& self.board.is_set()
|
||||
&& (same < all || self.only_order)
|
||||
|
|
@ -1191,6 +1382,66 @@ impl LargeView {
|
|||
);
|
||||
}
|
||||
}
|
||||
// The choice, or the copy being written, in the same place (§42.3).
|
||||
if batch.is_some() || chosen >= 2 {
|
||||
ui.add_space(SLOT_GAP);
|
||||
}
|
||||
if let Some(b) = &batch {
|
||||
if b.cancelling {
|
||||
ui.spinner();
|
||||
ui.label(RichText::new(tr("Cancelling…")).weak());
|
||||
} else {
|
||||
if ui.link(tr("Cancel")).clicked() {
|
||||
cancel_batch = true;
|
||||
}
|
||||
let fraction = b.done as f32 / b.total.max(1) as f32;
|
||||
ui.add(egui::ProgressBar::new(fraction).desired_width(80.0).desired_height(8.0));
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"Writing to «{name}»: {i} of {n}",
|
||||
&[("name", &b.name), ("i", &grouped(b.done)), ("n", &grouped(b.total))],
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
} else if chosen >= 2 {
|
||||
if ui
|
||||
.link(tr("Deselect"))
|
||||
.on_hover_text(tr("Clear the selection (Esc)"))
|
||||
.clicked()
|
||||
{
|
||||
clear_marked = true;
|
||||
}
|
||||
let full = if hidden > 0 {
|
||||
trf(
|
||||
"Selected: {n} ({k} hidden by the filter)",
|
||||
&[("n", &grouped(chosen)), ("k", &grouped(hidden))],
|
||||
)
|
||||
} else {
|
||||
trf("Selected: {n}", &[("n", &grouped(chosen))])
|
||||
};
|
||||
// Short in a narrow line: the conditions keep their 140 px.
|
||||
let short = ui.available_width()
|
||||
< 140.0 + ui.fonts_mut(|f| {
|
||||
f.layout_no_wrap(
|
||||
full.clone(),
|
||||
egui::TextStyle::Body.resolve(ui.style()),
|
||||
Color32::WHITE,
|
||||
)
|
||||
.size()
|
||||
.x
|
||||
}) + 16.0;
|
||||
let text = if short { format!("{} ·", grouped(chosen)) } else { format!("{full} ·") };
|
||||
let label = ui.label(text);
|
||||
if hidden > 0 {
|
||||
label.on_hover_text(format!(
|
||||
"{full}\n{}",
|
||||
tr("Games hidden by the filter will be copied too. Esc clears the selection")
|
||||
));
|
||||
} else if short {
|
||||
label.on_hover_text(full);
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
if conditions.is_empty() {
|
||||
ui.label(RichText::new(tr("No conditions: all games are shown")).weak());
|
||||
|
|
@ -1225,6 +1476,12 @@ impl LargeView {
|
|||
if toggle_order {
|
||||
self.only_order = !self.only_order;
|
||||
}
|
||||
if clear_marked {
|
||||
self.mark_cursor_only();
|
||||
}
|
||||
if cancel_batch {
|
||||
self.cancel_batch = true;
|
||||
}
|
||||
if let Some(c) = clear {
|
||||
self.clear(c);
|
||||
}
|
||||
|
|
@ -1235,6 +1492,15 @@ impl LargeView {
|
|||
}
|
||||
}
|
||||
|
||||
/// The far right slot of the conditions line, `width` wide (none yet: task 27 puts
|
||||
/// its search there).
|
||||
fn right_slot(ui: &mut Ui, width: f32) {
|
||||
if width > 0.0 {
|
||||
ui.allocate_exact_size(vec2(width, 22.0), Sense::hover());
|
||||
ui.add_space(SLOT_GAP);
|
||||
}
|
||||
}
|
||||
|
||||
/// The filter panel (an `egui::Panel` on the right of the library).
|
||||
pub fn panel(&mut self, ui: &mut Ui, db: &Arc<Database>) {
|
||||
self.update(db, ui.ctx());
|
||||
|
|
@ -2022,7 +2288,26 @@ impl LargeView {
|
|||
return open_notes;
|
||||
}
|
||||
|
||||
// Records the database does not have (`CP_SELECT` on a short one) are not chosen.
|
||||
if self.marked.last().is_some_and(|r| r >= db.len()) {
|
||||
let len = db.len();
|
||||
self.mark(|m| m.retain_below(len));
|
||||
self.selected = self.selected.filter(|&c| c < len);
|
||||
}
|
||||
self.keyboard(ui, path, actions);
|
||||
// `CP_BATCH=new:<name>`: the chosen records copied into a new database once the
|
||||
// list is there (screenshots, checks).
|
||||
if std::env::var("CP_BATCH").is_ok_and(|b| b.starts_with("new:"))
|
||||
&& !self.marked.is_empty()
|
||||
&& !self.view.is_empty()
|
||||
{
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
let mut first = false;
|
||||
ONCE.call_once(|| first = true);
|
||||
if first {
|
||||
self.ask_copy(path, actions);
|
||||
}
|
||||
}
|
||||
|
||||
let scroll_row = if std::mem::take(&mut self.scroll_to_selected) {
|
||||
self.selected
|
||||
|
|
@ -2103,6 +2388,8 @@ impl LargeView {
|
|||
year_only,
|
||||
use_position,
|
||||
);
|
||||
let frame_color = ui.visuals().selection.stroke.color;
|
||||
let table_clip = ui.clip_rect().intersect(ui.max_rect());
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt(("game table", layout))
|
||||
.striped(true)
|
||||
|
|
@ -2122,6 +2409,11 @@ impl LargeView {
|
|||
let mut hovered = None;
|
||||
let view = &self.view;
|
||||
let selected = self.selected;
|
||||
let marked = &self.marked;
|
||||
let many = marked.len() >= 2;
|
||||
let batch_running = self.batch.as_ref().map(|b| b.name.clone());
|
||||
let mut batch_menu = None;
|
||||
let mut secondary = None;
|
||||
// A position not applied (no memory) does not sort: the arrow shows the view's own order.
|
||||
let sort = if self.blocked.is_some() {
|
||||
self.sort
|
||||
|
|
@ -2163,7 +2455,8 @@ impl LargeView {
|
|||
};
|
||||
let index = index as usize;
|
||||
let r = db.row(index);
|
||||
row.set_selected(selected == Some(index));
|
||||
let is_marked = marked.contains(index);
|
||||
row.set_selected(is_marked);
|
||||
let key = viewed::key(db.identity(index));
|
||||
let seen = viewed.contains(key);
|
||||
let elo = |e: u16| if e > 0 { e.to_string() } else { String::new() };
|
||||
|
|
@ -2254,7 +2547,24 @@ impl LargeView {
|
|||
.filter(|t| !t.trim().is_empty() && *t != "?" && !t.contains("://"))
|
||||
.collect();
|
||||
let resp = row.response();
|
||||
// The cursor among several chosen rows, or on a row not chosen: a frame
|
||||
// (a shape, not a colour; §42.4).
|
||||
if selected == Some(index) && (many || !is_marked) {
|
||||
ui_painter_frame(&resp, frame_color, table_clip);
|
||||
}
|
||||
let resp = if about.is_empty() { resp } else { resp.on_hover_text(about.join(" · ")) };
|
||||
if resp.secondary_clicked() {
|
||||
secondary = Some(index);
|
||||
}
|
||||
// Several chosen and this one among them: the menu of the choice.
|
||||
if many && is_marked {
|
||||
resp.context_menu(|ui| {
|
||||
if let Some(item) = batch_items(ui, marked.len(), batch_running.as_deref()) {
|
||||
batch_menu = Some(item);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button(tr("Open")).clicked() {
|
||||
opened = Some(index);
|
||||
|
|
@ -2300,6 +2610,10 @@ impl LargeView {
|
|||
actions.push(LibraryAction::AddGameToDatabase { path: path.to_path_buf(), index });
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Select all (Ctrl+A)")).clicked() {
|
||||
batch_menu = Some(BatchItem::SelectAll);
|
||||
ui.close();
|
||||
}
|
||||
let label = if seen {
|
||||
tr("Mark as not viewed")
|
||||
} else {
|
||||
|
|
@ -2317,6 +2631,7 @@ impl LargeView {
|
|||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if resp.hovered() {
|
||||
hovered = Some(index);
|
||||
}
|
||||
|
|
@ -2348,7 +2663,20 @@ impl LargeView {
|
|||
self.typed_at = f64::NEG_INFINITY;
|
||||
}
|
||||
if let Some(i) = clicked {
|
||||
self.selected = Some(i);
|
||||
let mods = ui.input(|i| i.modifiers);
|
||||
self.click(i, mods);
|
||||
}
|
||||
// A right click on a row not chosen chooses it alone.
|
||||
if let Some(i) = secondary
|
||||
&& !(self.marked.len() >= 2 && self.marked.contains(i))
|
||||
{
|
||||
self.click(i, egui::Modifiers::NONE);
|
||||
}
|
||||
match batch_menu {
|
||||
Some(BatchItem::NewBase) => self.ask_copy(path, actions),
|
||||
Some(BatchItem::SelectAll) => self.select_all(),
|
||||
Some(BatchItem::Clear) => self.mark_cursor_only(),
|
||||
None => {}
|
||||
}
|
||||
if let Some(index) = opened {
|
||||
self.selected = Some(index);
|
||||
|
|
@ -2361,7 +2689,10 @@ impl LargeView {
|
|||
open_notes
|
||||
}
|
||||
|
||||
/// Up/Down move the selection, Page Up/Down by a page, Enter opens.
|
||||
/// Up/Down move the cursor, Page Up/Down by a page, Home/End to the ends, Enter
|
||||
/// opens. Without a modifier the choice follows the cursor, Shift chooses the range
|
||||
/// from the anchor, Ctrl moves the cursor alone; Ctrl+Space toggles its row, Ctrl+A
|
||||
/// chooses the whole list (§42.6).
|
||||
fn keyboard(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec<LibraryAction>) {
|
||||
// In a filter field the arrows still move through the table (unless the
|
||||
// suggestions are open), but Enter belongs to the field.
|
||||
|
|
@ -2369,17 +2700,44 @@ impl LargeView {
|
|||
if typing && self.suggestions.is_some() {
|
||||
return;
|
||||
}
|
||||
let (up, down, page_up, page_down, enter) = ui.input(|i| {
|
||||
let (up, down, page_up, page_down, enter, mods) = ui.input(|i| {
|
||||
(
|
||||
i.key_pressed(egui::Key::ArrowUp),
|
||||
i.key_pressed(egui::Key::ArrowDown),
|
||||
i.key_pressed(egui::Key::PageUp),
|
||||
i.key_pressed(egui::Key::PageDown),
|
||||
i.key_pressed(egui::Key::Enter),
|
||||
i.modifiers,
|
||||
)
|
||||
});
|
||||
// The selected record: F2 opens it with its data, Ctrl+Shift+S adds a copy of it
|
||||
// to another database, Delete removes it (a question first).
|
||||
let (home, end) = if typing {
|
||||
(false, false)
|
||||
} else {
|
||||
ui.input(|i| {
|
||||
(
|
||||
i.key_pressed(egui::Key::Home),
|
||||
i.key_pressed(egui::Key::End),
|
||||
)
|
||||
})
|
||||
};
|
||||
if !typing {
|
||||
let (all, toggle) = ui.input_mut(|i| {
|
||||
(
|
||||
i.consume_key(egui::Modifiers::COMMAND, egui::Key::A),
|
||||
i.consume_key(egui::Modifiers::COMMAND, egui::Key::Space),
|
||||
)
|
||||
});
|
||||
if all {
|
||||
self.select_all();
|
||||
}
|
||||
if toggle && let Some(c) = self.selected {
|
||||
self.mark(|m| m.toggle(c));
|
||||
self.anchor = Some(c);
|
||||
}
|
||||
}
|
||||
// The cursor's record: F2 opens it with its data, Ctrl+Shift+S adds a copy of it
|
||||
// to another database (several chosen: a new database of them), Delete removes
|
||||
// it (a question first; never while several are chosen).
|
||||
if !typing && let Some(index) = self.selected {
|
||||
let (data, add, delete) = ui.input_mut(|i| {
|
||||
(
|
||||
|
|
@ -2391,6 +2749,7 @@ impl LargeView {
|
|||
i.consume_key(egui::Modifiers::NONE, egui::Key::Delete),
|
||||
)
|
||||
});
|
||||
let many = self.marked.len() >= 2;
|
||||
let p = path.to_path_buf();
|
||||
if data {
|
||||
actions.push(LibraryAction::EditGameData {
|
||||
|
|
@ -2398,32 +2757,57 @@ impl LargeView {
|
|||
index,
|
||||
});
|
||||
}
|
||||
if add {
|
||||
if add && many {
|
||||
self.ask_copy(path, actions);
|
||||
} else if add {
|
||||
actions.push(LibraryAction::AddGameToDatabase {
|
||||
path: p.clone(),
|
||||
index,
|
||||
});
|
||||
}
|
||||
// Also for a database that takes no games: the app says why.
|
||||
if delete {
|
||||
if delete && many {
|
||||
actions.push(LibraryAction::Notice(
|
||||
tr("Games are deleted one at a time: clear the selection (Esc)").to_owned(),
|
||||
));
|
||||
} else if delete {
|
||||
// Also for a database that takes no games: the app says why.
|
||||
actions.push(LibraryAction::DeleteGame { path: p, index });
|
||||
}
|
||||
}
|
||||
// Enter belongs to a filter field, but in the quick search it opens the game.
|
||||
let enter = enter && (!typing || self.search_focused);
|
||||
let step = if page_up || page_down { 20 } else { 1 };
|
||||
if up || down || page_up || page_down {
|
||||
let pos = self
|
||||
.selected
|
||||
.and_then(|r| self.view.iter().position(|&i| i as usize == r));
|
||||
if up || down || page_up || page_down || home || end {
|
||||
let pos = self.selected.and_then(|r| self.position_of(r));
|
||||
let last = self.view.len().saturating_sub(1);
|
||||
let next = match (pos, down || page_down) {
|
||||
_ if home => 0,
|
||||
_ if end => last,
|
||||
(None, _) => 0,
|
||||
(Some(p), true) => (p + step).min(last),
|
||||
(Some(p), false) => p.saturating_sub(step),
|
||||
};
|
||||
if let Some(&i) = self.view.get(next) {
|
||||
self.selected = Some(i as usize);
|
||||
let i = i as usize;
|
||||
if mods.shift {
|
||||
let from = self
|
||||
.anchor
|
||||
.and_then(|a| self.position_of(a))
|
||||
.or(pos)
|
||||
.unwrap_or(next);
|
||||
if self.anchor.and_then(|a| self.position_of(a)).is_none() {
|
||||
self.anchor = self.view.get(from).map(|&r| r as usize);
|
||||
}
|
||||
let range = self.range(from, next).to_vec();
|
||||
self.mark(|m| {
|
||||
m.clear();
|
||||
m.extend(&range);
|
||||
});
|
||||
} else if !mods.command {
|
||||
self.mark(|m| m.only(i));
|
||||
self.anchor = Some(i);
|
||||
}
|
||||
self.selected = Some(i);
|
||||
self.scroll_to_selected = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -2442,6 +2826,64 @@ impl LargeView {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// Space between the slots of the conditions line (`item_spacing.x` + 4).
|
||||
const SLOT_GAP: f32 = 4.0;
|
||||
|
||||
/// An item of the menus about the chosen records.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum BatchItem {
|
||||
NewBase,
|
||||
SelectAll,
|
||||
Clear,
|
||||
}
|
||||
|
||||
/// The menu of several chosen rows (§42.7): how many, the copy, select all, clear. The
|
||||
/// copy waits while another one is written.
|
||||
fn batch_items(ui: &mut Ui, n: usize, writing: Option<&str>) -> Option<BatchItem> {
|
||||
let mut out = None;
|
||||
ui.label(RichText::new(trf("Games selected: {n}", &[("n", &grouped(n))])).weak());
|
||||
ui.separator();
|
||||
let copy = ui.add_enabled(
|
||||
writing.is_none() && crate::platform::CAPS.batch_copy,
|
||||
egui::Button::new(tr("New database from selected…")),
|
||||
);
|
||||
let copy = match writing {
|
||||
Some(name) => copy.on_disabled_hover_text(trf(
|
||||
"Writing to «{name}» — wait until it finishes",
|
||||
&[("name", &name)],
|
||||
)),
|
||||
None => copy,
|
||||
};
|
||||
if copy.clicked() {
|
||||
out = Some(BatchItem::NewBase);
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Select all (Ctrl+A)")).clicked() {
|
||||
out = Some(BatchItem::SelectAll);
|
||||
}
|
||||
if ui.button(tr("Clear selection (Esc)")).clicked() {
|
||||
out = Some(BatchItem::Clear);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The keyboard cursor's frame: 1 px inside the row.
|
||||
fn ui_painter_frame(row: &egui::Response, color: Color32, clip: egui::Rect) {
|
||||
let stroke = Stroke::new(1.0, color);
|
||||
row.ctx
|
||||
.layer_painter(row.layer_id)
|
||||
.with_clip_rect(clip)
|
||||
.rect_stroke(
|
||||
row.rect.intersect(clip),
|
||||
0.0,
|
||||
stroke,
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
|
||||
/// A condition of the list, shown as a chip.
|
||||
struct Condition {
|
||||
text: String,
|
||||
|
|
@ -2681,6 +3123,116 @@ fn new_game_hint(name: &str) -> String {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ctrl() -> egui::Modifiers {
|
||||
egui::Modifiers::COMMAND
|
||||
}
|
||||
|
||||
fn shift() -> egui::Modifiers {
|
||||
egui::Modifiers::SHIFT
|
||||
}
|
||||
|
||||
/// A view showing records 0..20 in the order 19, 18, … 0 (a sort).
|
||||
fn table() -> LargeView {
|
||||
let mut v = LargeView::new();
|
||||
v.view = (0..20).rev().collect();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_choose_one_toggle_and_ranges_in_the_tables_order() {
|
||||
let mut v = table();
|
||||
v.click(3, egui::Modifiers::NONE);
|
||||
assert_eq!((v.marked.records(), v.selected), (vec![3], Some(3)));
|
||||
v.click(7, ctrl());
|
||||
v.click(15, ctrl());
|
||||
assert_eq!(v.marked.records(), vec![3, 7, 15]);
|
||||
v.click(7, ctrl());
|
||||
assert_eq!(v.marked.records(), vec![3, 15]);
|
||||
// Shift: the range from the anchor (7, the last Ctrl click) in the table's order
|
||||
// replaces the choice; Ctrl+Shift adds it.
|
||||
v.click(10, shift());
|
||||
assert_eq!(v.marked.records(), vec![7, 8, 9, 10]);
|
||||
v.click(1, ctrl());
|
||||
v.click(3, ctrl() | shift());
|
||||
assert_eq!(v.marked.records(), vec![1, 2, 3, 7, 8, 9, 10]);
|
||||
v.click(5, egui::Modifiers::NONE);
|
||||
assert_eq!(v.marked.records(), vec![5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_anchor_hidden_by_the_filter_gives_way_to_the_cursor() {
|
||||
let mut v = table();
|
||||
v.click(30, egui::Modifiers::NONE);
|
||||
v.click(4, ctrl());
|
||||
v.anchor = Some(30);
|
||||
v.click(6, shift());
|
||||
assert_eq!(v.marked.records(), vec![4, 5, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_all_takes_the_list_and_escape_comes_back_to_the_cursor() {
|
||||
let mut v = table();
|
||||
v.marked.insert(40);
|
||||
v.click(40, ctrl());
|
||||
v.click(2, ctrl());
|
||||
v.select_all();
|
||||
assert_eq!(v.marked.len(), 20);
|
||||
assert_eq!(v.hidden_marked(), 0);
|
||||
v.marked.insert(40);
|
||||
v.marked_gen += 1;
|
||||
assert_eq!(v.hidden_marked(), 1);
|
||||
assert!(v.escape());
|
||||
assert_eq!(v.marked.records(), vec![2]);
|
||||
// One chosen: Escape is the next one's (here nobody's).
|
||||
assert!(!v.escape());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returning_from_a_game_keeps_a_choice_of_several() {
|
||||
let mut v = table();
|
||||
v.click(1, egui::Modifiers::NONE);
|
||||
v.reveal(9);
|
||||
assert_eq!(v.marked.records(), vec![9]);
|
||||
v.click(3, ctrl());
|
||||
v.reveal(3);
|
||||
assert_eq!(v.marked.records(), vec![3, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_copy_asks_for_the_chosen_records_and_the_tables_sort() {
|
||||
let mut v = table();
|
||||
v.sort = (SortKey::White, false);
|
||||
v.click(5, egui::Modifiers::NONE);
|
||||
v.click(2, ctrl());
|
||||
let mut actions = Vec::new();
|
||||
v.ask_copy(Path::new("/x.pgn"), &mut actions);
|
||||
match actions.as_slice() {
|
||||
[
|
||||
LibraryAction::CopySelection {
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
hidden,
|
||||
..
|
||||
},
|
||||
] => {
|
||||
assert_eq!(records, &vec![2, 5]);
|
||||
assert_eq!((*sort, *ascending, *hidden), (SortKey::White, false, 0));
|
||||
}
|
||||
_ => panic!("one copy"),
|
||||
}
|
||||
// None while another copy is written.
|
||||
v.batch = Some(BatchStatus {
|
||||
name: "x".into(),
|
||||
done: 0,
|
||||
total: 1,
|
||||
cancelling: false,
|
||||
});
|
||||
actions.clear();
|
||||
v.ask_copy(Path::new("/x.pgn"), &mut actions);
|
||||
assert!(actions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_group_and_shorten() {
|
||||
assert_eq!(grouped(11_741_260), "11\u{202f}741\u{202f}260");
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ mod adjourned;
|
|||
mod analysis;
|
||||
mod app;
|
||||
mod assets;
|
||||
mod batch_copy;
|
||||
mod board;
|
||||
mod board_search;
|
||||
mod chatgpt;
|
||||
|
|
|
|||
|
|
@ -83,6 +83,17 @@ pub enum LibraryAction {
|
|||
path: PathBuf,
|
||||
index: usize,
|
||||
},
|
||||
/// «New database from selected…»: the chosen records (by number) of `path`, the
|
||||
/// table's order, how many of them the filter hides (task 42).
|
||||
CopySelection {
|
||||
path: PathBuf,
|
||||
records: Vec<u32>,
|
||||
sort: chess_import::chessbase::base::SortKey,
|
||||
ascending: bool,
|
||||
hidden: usize,
|
||||
},
|
||||
/// A short message (a toast).
|
||||
Notice(String),
|
||||
EditGameData {
|
||||
path: PathBuf,
|
||||
index: usize,
|
||||
|
|
@ -266,6 +277,35 @@ pub struct Library {
|
|||
pub aside: Option<crate::adjourned::Card>,
|
||||
/// The games of the databases not opened, for their cards.
|
||||
counts: crate::db_counts::Counts,
|
||||
/// Chosen records being copied into a new database (one copy at a time).
|
||||
batch: Option<BatchJob>,
|
||||
}
|
||||
|
||||
/// A copy of chosen records into a new database, written in the background.
|
||||
struct BatchJob {
|
||||
source: PathBuf,
|
||||
target: PathBuf,
|
||||
total: usize,
|
||||
work: crate::board_search::Background<
|
||||
Result<crate::batch_copy::CopyReport, crate::batch_copy::CopyError>,
|
||||
>,
|
||||
cancelling: bool,
|
||||
}
|
||||
|
||||
/// How a copy of chosen records ended.
|
||||
pub enum BatchEnd {
|
||||
Done {
|
||||
target: PathBuf,
|
||||
report: crate::batch_copy::CopyReport,
|
||||
},
|
||||
Cancelled {
|
||||
target: PathBuf,
|
||||
},
|
||||
Failed {
|
||||
source: PathBuf,
|
||||
target: PathBuf,
|
||||
error: crate::batch_copy::CopyError,
|
||||
},
|
||||
}
|
||||
|
||||
impl Library {
|
||||
|
|
@ -286,9 +326,118 @@ impl Library {
|
|||
update: None,
|
||||
aside: None,
|
||||
counts: crate::db_counts::Counts::new(ctx),
|
||||
batch: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts copying `records` of `source` into the new file `target` (none while
|
||||
/// another copy is written). `false`: the source is not read or the thread did not
|
||||
/// start.
|
||||
pub fn start_batch(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
source: &Path,
|
||||
records: Vec<u32>,
|
||||
sort: chess_import::chessbase::base::SortKey,
|
||||
ascending: bool,
|
||||
target: PathBuf,
|
||||
) -> bool {
|
||||
if self.batch.is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(db) = self.database(source) else {
|
||||
return false;
|
||||
};
|
||||
let total = records.len();
|
||||
let req = crate::batch_copy::CopyRequest {
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
target: target.clone(),
|
||||
slow: std::env::var_os("CP_BATCH_SLOW").is_some(),
|
||||
};
|
||||
let now = ctx.input(|i| i.time);
|
||||
let Some(work) = crate::board_search::Background::spawn(ctx, now, move |p, c| {
|
||||
crate::batch_copy::copy_into_new(&db, &req, p, c)
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
self.batch = Some(BatchJob {
|
||||
source: source.to_path_buf(),
|
||||
target,
|
||||
total,
|
||||
work,
|
||||
cancelling: false,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// The chosen records of `path` let go (their numbers no longer mean the same games).
|
||||
pub fn clear_selection(&mut self, path: &Path) {
|
||||
if let Some(view) = self.large.get_mut(path) {
|
||||
view.clear_marks();
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the copy being written to stop.
|
||||
pub fn cancel_batch(&mut self) {
|
||||
if let Some(job) = &mut self.batch {
|
||||
job.work.cancel();
|
||||
job.cancelling = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the copy being written and waits a little for it to clean up (closing the
|
||||
/// program): its temporary file goes, no new database appears.
|
||||
pub fn stop_batch(&mut self) {
|
||||
if let Some(job) = self.batch.take() {
|
||||
job.work.cancel();
|
||||
job.work.wait(std::time::Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of the copy being written, once it came (called every frame, whatever is
|
||||
/// on the screen); while it runs the source's conditions line shows it.
|
||||
pub fn poll_batch(&mut self, ctx: &egui::Context) -> Option<BatchEnd> {
|
||||
let job = self.batch.as_ref()?;
|
||||
let Some(result) = job.work.poll() else {
|
||||
let status = large_db::BatchStatus {
|
||||
name: crate::own_db::base_name(&job.target),
|
||||
done: job.work.progress(),
|
||||
total: job.total,
|
||||
cancelling: job.cancelling,
|
||||
};
|
||||
let source = job.source.clone();
|
||||
let mut cancel = false;
|
||||
if let Some(view) = self.large.get_mut(&source) {
|
||||
cancel = std::mem::take(&mut view.cancel_batch);
|
||||
view.batch = Some(status);
|
||||
}
|
||||
if cancel {
|
||||
self.cancel_batch();
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
return None;
|
||||
};
|
||||
let job = self.batch.take()?;
|
||||
if let Some(view) = self.large.get_mut(&job.source) {
|
||||
view.batch = None;
|
||||
view.cancel_batch = false;
|
||||
}
|
||||
Some(match result {
|
||||
None => BatchEnd::Cancelled { target: job.target },
|
||||
Some(Ok(report)) => BatchEnd::Done {
|
||||
target: job.target,
|
||||
report,
|
||||
},
|
||||
Some(Err(error)) => BatchEnd::Failed {
|
||||
source: job.source,
|
||||
target: job.target,
|
||||
error,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts loading `path` in the background (no-op if already loaded/loading).
|
||||
pub fn load(&mut self, path: &Path, ctx: &egui::Context) {
|
||||
if matches!(
|
||||
|
|
|
|||
|
|
@ -82,8 +82,20 @@ pub enum AfterCreate {
|
|||
AddGame,
|
||||
/// Add a copy of a record of a table to it.
|
||||
AddRecord { path: PathBuf, index: usize },
|
||||
/// Copy the chosen records of a table into it, in the table's order (task 42): the
|
||||
/// file is made by the copy, only when whole.
|
||||
CopySelection {
|
||||
path: PathBuf,
|
||||
records: Vec<u32>,
|
||||
sort: chess_import::chessbase::base::SortKey,
|
||||
ascending: bool,
|
||||
hidden: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// From this many chosen games on, the dialog says the copy may take a while.
|
||||
const MANY_GAMES: usize = 50_000;
|
||||
|
||||
pub struct NewBaseDialog {
|
||||
pub name: String,
|
||||
pub dir: PathBuf,
|
||||
|
|
@ -121,7 +133,7 @@ impl NewBaseDialog {
|
|||
}
|
||||
}
|
||||
|
||||
fn path(&self) -> PathBuf {
|
||||
pub fn path(&self) -> PathBuf {
|
||||
self.dir.join(format!("{}.pgn", self.stem()))
|
||||
}
|
||||
|
||||
|
|
@ -143,6 +155,41 @@ impl NewBaseDialog {
|
|||
egui::Modal::new(egui::Id::new("new_base")).show(ctx, |ui| {
|
||||
ui.set_width(440.0);
|
||||
ui.heading(tr("New database"));
|
||||
let copy = matches!(self.after, AfterCreate::CopySelection { .. });
|
||||
if let AfterCreate::CopySelection {
|
||||
path,
|
||||
records,
|
||||
hidden,
|
||||
..
|
||||
} = &self.after
|
||||
{
|
||||
let weak = |ui: &mut egui::Ui, text: String| {
|
||||
ui.add(egui::Label::new(RichText::new(text).weak()).truncate());
|
||||
};
|
||||
weak(
|
||||
ui,
|
||||
trf(
|
||||
"From the selection: {games} from «{src}»",
|
||||
&[
|
||||
("games", &crate::i18n::games(records.len())),
|
||||
("src", &base_name(path)),
|
||||
],
|
||||
),
|
||||
);
|
||||
if *hidden > 0 {
|
||||
weak(
|
||||
ui,
|
||||
trf("{k} of them are hidden by the filter now", &[("k", hidden)]),
|
||||
);
|
||||
}
|
||||
if records.len() >= MANY_GAMES {
|
||||
weak(
|
||||
ui,
|
||||
tr("Many games: writing may take a few minutes; you can cancel it")
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.label(tr("Title"));
|
||||
let check = self.check();
|
||||
|
|
@ -195,10 +242,21 @@ impl NewBaseDialog {
|
|||
let enter = ui.input(|i| i.key_pressed(Key::Enter));
|
||||
match &check {
|
||||
Ok(false) => {
|
||||
if crate::widgets::primary(ui, tr("Create")).clicked() || enter {
|
||||
let label = if copy {
|
||||
tr("Create and copy")
|
||||
} else {
|
||||
tr("Create")
|
||||
};
|
||||
if crate::widgets::primary(ui, label).clicked() || enter {
|
||||
out = Some(NewBaseOutcome::Create(self.path()));
|
||||
}
|
||||
}
|
||||
// The copy goes into a new file only: the one there is not touched.
|
||||
Ok(true) if copy => {
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
crate::widgets::primary(ui, tr("Create and copy"))
|
||||
});
|
||||
}
|
||||
Ok(true) => {
|
||||
if crate::widgets::primary(ui, tr("Put it on the shelf")).clicked()
|
||||
|| enter
|
||||
|
|
@ -209,9 +267,12 @@ impl NewBaseDialog {
|
|||
// The same main button, only disabled: the row does not jump
|
||||
// when the first letter is typed.
|
||||
Err(_) => {
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
crate::widgets::primary(ui, tr("Create"))
|
||||
});
|
||||
let label = if copy {
|
||||
tr("Create and copy")
|
||||
} else {
|
||||
tr("Create")
|
||||
};
|
||||
ui.add_enabled_ui(false, |ui| crate::widgets::primary(ui, label));
|
||||
}
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
|
|
|
|||
|
|
@ -51,6 +51,8 @@ pub struct Caps {
|
|||
/// The reference tab (what was played here in the databases) and the search of a
|
||||
/// position in a database (not in the light web version).
|
||||
pub reference: bool,
|
||||
/// Several chosen games copied into a new database in the background (task 42).
|
||||
pub batch_copy: bool,
|
||||
}
|
||||
|
||||
/// The features of this platform.
|
||||
|
|
@ -66,6 +68,7 @@ pub const CAPS: Caps = Caps {
|
|||
training: true,
|
||||
download_pgn: false,
|
||||
reference: true,
|
||||
batch_copy: true,
|
||||
};
|
||||
|
||||
/// The features of this platform: the light web version (`docs/decisions.md`, «Веб-версия»).
|
||||
|
|
@ -81,6 +84,7 @@ pub const CAPS: Caps = Caps {
|
|||
training: false,
|
||||
download_pgn: true,
|
||||
reference: false,
|
||||
batch_copy: false,
|
||||
};
|
||||
|
||||
/// The program's settings (`~/.config/chesspenguin`; in a browser, its storage).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue