Own databases: the chooser lists only bases that take games; UTF-8 copy from the card menu; Create does not jump
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-25 01:03:57 +03:00
parent 0f66486a22
commit 05026ec45a
4 changed files with 105 additions and 179 deletions

View file

@ -77,10 +77,10 @@ enum QuestionThen {
path: PathBuf,
index: usize,
},
/// Make the copy (asked from the card's menu); its card is then selected.
Utf8Copy {
path: PathBuf,
dest: PathBuf,
purpose: ChooserFor,
},
/// The write failed: the same write again.
Retry(Retry),
@ -1121,6 +1121,35 @@ impl App {
}
}
/// A UTF-8 copy of a PGN in a legacy encoding (the card's menu): asked first.
fn utf8_copy(&mut self, path: PathBuf) {
let encoding = match self.library.write_block(&path) {
Some(own_db::Block::Encoding(e)) => e,
_ => return,
};
// "X (UTF-8).pgn", or "X (UTF-8 2).pgn" when that is taken.
let stem = own_db::base_name(&path);
let dest = (1..)
.map(|k| {
let n = if k == 1 {
String::new()
} else {
format!(" {k}")
};
path.with_file_name(format!("{stem} (UTF-8{n}).pgn"))
})
.find(|p| !p.exists())
.expect("a free name");
self.ask(
QuestionKind::Utf8Copy {
path: path.clone(),
dest: dest.clone(),
encoding,
},
QuestionThen::Utf8Copy { path, dest },
);
}
fn new_base_dialog(&mut self, after: own_db::AfterCreate) {
let dir = own_db::default_base_dir(self.settings.new_database_dir.as_deref());
self.own.new_base = Some(own_db::NewBaseDialog::new(dir, after));
@ -1209,14 +1238,7 @@ impl App {
(QuestionThen::Delete { path, index }, Answer::Primary) => {
self.delete_now(ctx, path, index)
}
(
QuestionThen::Utf8Copy {
path,
dest,
purpose,
},
Answer::Primary,
) => {
(QuestionThen::Utf8Copy { path, dest }, Answer::Primary) => {
let Some(db) = self.library.database(&path) else {
return;
};
@ -1234,14 +1256,11 @@ impl App {
self.settings
.databases
.insert(at.min(self.settings.databases.len()), dest.clone());
// The copy is the one to add to: chosen in the list, which
// comes back for the same game or record.
// The copy is the one to add to from now on.
self.settings.last_target = Some(dest.clone());
self.settings_dirty = true;
self.library.load(&dest, ctx);
self.library.select_db(&dest, ctx);
self.toast(ctx, trf("Copy made: {path}", &[("path", &dest.display())]));
self.own.chooser = None;
self.open_chooser(ctx, purpose);
}
Err(e) => {
self.toast(ctx, trf("Could not make the copy: {e}", &[("e", &e)]))
@ -1341,39 +1360,6 @@ impl App {
self.close_after_save = self.own.then_close.take();
self.pick_save(ctx);
}
ChooserOutcome::Utf8Copy(path) => {
let encoding = match self.library.write_block(&path) {
Some(own_db::Block::Encoding(e)) => e,
_ => "?",
};
// "X (UTF-8).pgn", or "X (UTF-8 2).pgn" when that is taken.
let stem = own_db::base_name(&path);
let dest = (1..)
.map(|k| {
let n = if k == 1 {
String::new()
} else {
format!(" {k}")
};
path.with_file_name(format!("{stem} (UTF-8{n}).pgn"))
})
.find(|p| !p.exists())
.expect("a free name");
let purpose = chooser.purpose.clone();
self.own.chooser = Some(chooser);
self.ask(
QuestionKind::Utf8Copy {
path: path.clone(),
dest: dest.clone(),
encoding,
},
QuestionThen::Utf8Copy {
path,
dest,
purpose,
},
);
}
ChooserOutcome::Cancel => {
if let Some(intent) = self.own.then_close.take() {
self.confirm_close = Some(intent);
@ -2171,6 +2157,7 @@ impl eframe::App for App {
self.own.then_close = None;
self.new_base_dialog(own_db::AfterCreate::Shelf);
}
LibraryAction::Utf8Copy(path) => self.utf8_copy(path),
LibraryAction::DeleteGame { path, index } => {
self.delete_game(&ctx, path, index)
}

View file

@ -9075,50 +9075,6 @@ const ROWS: &[[&str; 9]] = &[
"Jildda ko‘rsatish",
"Қалтада көрсету",
],
[
"updates itself from Lichess and Chess.com",
"обновляется сама с Lichess и Chess.com",
"mise à jour automatique depuis Lichess et Chess.com",
"wird automatisch von Lichess und Chess.com aktualisiert",
"se actualiza sola desde Lichess y Chess.com",
"si aggiorna da solo da Lichess e Chess.com",
"é atualizada sozinha pelo Lichess e pelo Chess.com",
"Lichess va Chess.com orqali o‘zi yangilanadi",
"Lichess пен Chess.com арқылы өзі жаңарады",
],
[
"read only",
"только чтение",
"lecture seule",
"schreibgeschützt",
"solo lectura",
"sola lettura",
"somente leitura",
"faqat o‘qish uchun",
"тек оқуға арналған",
],
[
"encoding {enc} — a UTF-8 copy can take games",
"кодировка {enc} — партии можно добавлять в копию в UTF-8",
"encodage {enc} — une copie en UTF-8 peut recevoir des parties",
"Kodierung {enc} — Partien können in eine UTF-8-Kopie aufgenommen werden",
"codificación {enc} — las partidas se pueden añadir a una copia en UTF-8",
"codifica {enc} — le partite si possono aggiungere a una copia in UTF-8",
"codificação {enc} — as partidas podem ser adicionadas a uma cópia em UTF-8",
"kodlash {enc} — partiyalarni UTF-8 dagi nusxaga qo‘shish mumkin",
"кодтау {enc} — партияларды UTF-8 көшірмесіне қосуға болады",
],
[
"no permission to write the file",
"нет прав на запись файла",
"pas de droit d’écriture sur le fichier",
"keine Schreibrechte für die Datei",
"sin permiso para escribir el archivo",
"nessun permesso di scrittura sul file",
"sem permissão para gravar o arquivo",
"faylga yozishga ruxsat yo‘q",
"файлға жазуға рұқсат жоқ",
],
[
"This database is downloaded from Lichess and Chess.com and updates itself: a game added by hand would be lost at the next update. Add the game to a database of your own.",
"Эта база скачана с Lichess и Chess.com и обновляется сама: партия, добавленная вручную, пропадёт при следующем обновлении. Добавьте партию в свою базу.",
@ -9284,17 +9240,6 @@ const ROWS: &[[&str; 9]] = &[
"Javonda hali PGN bazalar yo‘q — quyida yarating.",
"Сөреде әзірге PGN базалары жоқ — төменде жасаңыз.",
],
[
"Make a copy in UTF-8 and add the game to it",
"Создать копию в UTF-8 и добавить партию в неё",
"Créer une copie en UTF-8 et y ajouter la partie",
"Eine UTF-8-Kopie erstellen und die Partie dort hinzufügen",
"Crear una copia en UTF-8 y añadirle la partida",
"Crea una copia in UTF-8 e aggiungici la partita",
"Criar uma cópia em UTF-8 e adicionar a partida a ela",
"UTF-8 da nusxa yaratib, partiyani unga qo‘shish",
"UTF-8 көшірмесін жасап, партияны соған қосу",
],
[
"✚ New database…",
"✚ Новая база…",
@ -9780,6 +9725,17 @@ const ROWS: &[[&str; 9]] = &[
"Bazani o‘qib bo‘lmadi: {e}",
"Базаны оқу мүмкін болмады: {e}",
],
[
"A copy of the file in UTF-8, next to it: games can be added to the copy",
"Копия файла в UTF-8 рядом с ним: в копию можно добавлять партии",
"Une copie du fichier en UTF-8, à côté de lui : on peut ajouter des parties à la copie",
"Eine Kopie der Datei in UTF-8 daneben: In die Kopie lassen sich Partien aufnehmen",
"Una copia del archivo en UTF-8, junto a él: a la copia se pueden añadir partidas",
"Una copia del file in UTF-8, accanto a esso: alla copia si possono aggiungere partite",
"Uma cópia do arquivo em UTF-8, ao lado dele: à cópia é possível adicionar partidas",
"Faylning UTF-8 dagi nusxasi yonida: nusxaga o‘yinlar qo‘shish mumkin",
"Файлдың UTF-8 көшірмесі қасында: көшірмеге партия қосуға болады",
],
];
#[cfg(test)]

View file

@ -50,6 +50,8 @@ pub enum LibraryAction {
OpenSettings,
/// A new, empty PGN database (own-databases.md §2).
NewDatabase,
/// A UTF-8 copy of a PGN in a legacy encoding, which can take games.
Utf8Copy(PathBuf),
/// A record of a table: delete it, add a copy of it to another database, open it
/// with its data for editing.
DeleteGame {
@ -868,11 +870,27 @@ impl Library {
if resp.clicked() {
self.select_db(path, ui.ctx());
}
let legacy = matches!(
self.write_block(path),
Some(crate::own_db::Block::Encoding(_))
);
resp.context_menu(|ui| {
if ui.button(tr("Show in folder")).clicked() {
crate::own_db::show_in_folder(path);
ui.close();
}
// Games are written in UTF-8: a legacy file takes them through a copy.
if legacy
&& ui
.button(tr("Make a copy in UTF-8…"))
.on_hover_text(tr(
"A copy of the file in UTF-8, next to it: games can be added to the copy",
))
.clicked()
{
actions.push(LibraryAction::Utf8Copy(path.to_path_buf()));
ui.close();
}
if ui.button(tr("Remove from list")).clicked() {
actions.push(LibraryAction::RemoveDatabase(path.to_path_buf()));
ui.close();

View file

@ -30,20 +30,6 @@ pub enum Block {
}
impl Block {
/// One line, for a list row or a tooltip.
pub fn short(&self) -> String {
match self {
Block::Online => tr("updates itself from Lichess and Chess.com").to_owned(),
Block::ReadOnly => tr("read only").to_owned(),
Block::Encoding(enc) => trf(
"encoding {enc} — a UTF-8 copy can take games",
&[("enc", enc)],
),
Block::NoPermission => tr("no permission to write the file").to_owned(),
Block::Missing => tr("file not found").to_owned(),
}
}
/// The explanation when the user tries anyway.
pub fn long(&self) -> String {
match self {
@ -216,8 +202,12 @@ impl NewBaseDialog {
out = Some(NewBaseOutcome::AddExisting(self.path()));
}
}
// The same main button, only disabled: the row does not jump
// when the first letter is typed.
Err(_) => {
ui.add_enabled(false, egui::Button::new(tr("Create")));
ui.add_enabled_ui(false, |ui| {
crate::widgets::primary(ui, tr("Create"))
});
}
}
if ui.button(tr("Cancel")).clicked() {
@ -272,8 +262,6 @@ pub enum ChooserOutcome {
Pick(PathBuf),
NewBase,
SaveAsFile,
/// A PGN in another encoding: make the copy and add to it.
Utf8Copy(PathBuf),
Cancel,
}
@ -340,17 +328,17 @@ impl Chooser {
needle.is_empty() || self.rows[i].name.to_lowercase().contains(&needle)
})
.collect();
// Writable ones first, in shelf order; the others, greyed, after them.
// Only the databases that take games, in shelf order; those still being read
// after them (they may turn out to take games). Online, ChessBase, legacy
// encodings, read-only files are not offered at all.
let order: Vec<usize> = shown
.iter()
.copied()
.filter(|&i| self.rows[i].takes_games())
.chain(
shown
.iter()
.copied()
.filter(|&i| !self.rows[i].takes_games()),
)
.chain(shown.iter().copied().filter(|&i| {
let r = &self.rows[i];
r.block.is_none() && r.games.is_none()
}))
.collect();
let (up, down, enter) = ui.input(|i| {
(
@ -386,62 +374,39 @@ impl Chooser {
.weak(),
);
}
let width = ui.available_width();
for i in order {
let row = &self.rows[i];
let selected = self.selected == Some(i);
let text = match row.games {
Some(n) => format!("{} · {}", row.name, crate::i18n::games(n)),
None => format!("{} · {}", row.name, tr("reading…")),
};
let folder = row
.path
.parent()
.map(|p| p.display().to_string())
.unwrap_or_default();
match (&row.block, row.games) {
(None, Some(_)) => {
let resp = ui
.add_sized(
[width, 0.0],
egui::Button::selectable(selected, text),
)
.on_hover_text(&folder);
if resp.clicked() {
self.selected = Some(i);
}
if resp.double_clicked() {
out = Some(ChooserOutcome::Pick(row.path.clone()));
}
}
(None, None) => {
ui.label(RichText::new(text).weak());
}
(Some(Block::Encoding(enc)), _) => {
// The copy is the way in: a link at the end of the row.
ui.horizontal(|ui| {
ui.label(RichText::new(format!("{text} · {enc} ·")).weak());
if ui
.link(tr("Make a copy in UTF-8…"))
.on_hover_text(tr(
"Make a copy in UTF-8 and add the game to it",
))
.clicked()
{
out = Some(ChooserOutcome::Utf8Copy(row.path.clone()));
// Rows the whole width, their text from the left.
ui.with_layout(egui::Layout::top_down_justified(egui::Align::Min), |ui| {
for i in order {
let row = &self.rows[i];
let selected = self.selected == Some(i);
let text = match row.games {
Some(n) => format!("{} · {}", row.name, crate::i18n::games(n)),
None => format!("{} · {}", row.name, tr("reading…")),
};
let folder = row
.path
.parent()
.map(|p| p.display().to_string())
.unwrap_or_default();
match (&row.block, row.games) {
(None, Some(_)) => {
let resp = ui
.add(egui::Button::selectable(selected, text))
.on_hover_text(&folder);
if resp.clicked() {
self.selected = Some(i);
}
});
}
(Some(b), _) => {
ui.add_enabled(
false,
egui::Button::new(format!("{text} — {}", b.short()))
.frame(false),
)
.on_disabled_hover_text(b.long());
if resp.double_clicked() {
out = Some(ChooserOutcome::Pick(row.path.clone()));
}
}
(None, None) => {
ui.label(RichText::new(text).weak());
}
(Some(_), _) => {}
}
}
}
});
});
ui.separator();
if ui.button(tr("✚ New database…")).clicked() {