diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c67be2..3871cf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,14 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https check that the file did not change on the disk meanwhile. The game's header names its database and number (🔒 read-only, 🌐 online); the card menu has «Show in folder»; «Remove from list» says where the file stays. A new game gets today's date. +- Library: «+ Add database», «✚ New database» and «🌐 Online games» moved from the row of + database cards to the title row, beside «Databases» (folded into «+ ▾» and «🌐» in a + narrow window); the cards row holds only databases. An empty shelf shows the three + actions as large cards in the middle. The table header of a database that takes games + has «+ Game»: a new game meant for that database — its header says so and Ctrl+S adds + it there straight away. «Add to database» lists only databases that take games; a PGN + in a legacy encoding gets its UTF-8 copy from its card's menu. The built-in sample + databases are read-only. An empty database shows no filter panel. ## [1.0.3] — 2026-10-24 diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 9a4ceca..61f0620 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -441,6 +441,13 @@ impl App { self.open_chooser(ctx, ChooserFor::Record { path, index }) } ("data", _) => self.edit_game_data(), + // The table's «+ Game» for the first database. + ("newin", Some(path)) => { + self.new_game(); + if let Some(g) = self.game.as_mut() { + g.target = Some(path); + } + } ("save", _) => self.save_current(ctx, None), ("delete", Some(path)) => self.delete_game(ctx, path, index), _ => {} @@ -534,6 +541,7 @@ impl App { /// Ctrl+S: a game from a PGN that takes games is saved back into it; any other game /// is added to a database of the user's choice. fn save_current(&mut self, ctx: &egui::Context, then_close: Option) { + let target = self.current_target(); let Some(g) = &self.game else { return }; self.own.then_close = then_close; match &g.source { @@ -552,10 +560,27 @@ impl App { } self.replace_current(ctx); } + // A new game meant for a database (the table's «+ Game»): straight there. + None if let Some(t) = target => self.add_current_to(ctx, t), _ => self.open_chooser(ctx, ChooserFor::CurrentGame), } } + /// The database the new game on the screen is meant for, while it still takes games + /// and is on the shelf; else the target is dropped. + fn current_target(&mut self) -> Option { + let g = self.game.as_mut()?; + let t = g.target.clone()?; + if g.source.is_some() + || !self.settings.databases.contains(&t) + || self.library.write_block(&t).is_some() + { + g.target = None; + return None; + } + Some(t) + } + /// Writes the game over its record in its own PGN. fn replace_current(&mut self, ctx: &egui::Context) { let Some(g) = &self.game else { return }; @@ -614,7 +639,8 @@ impl App { .as_ref() .and_then(|g| g.source.as_ref()) .map(|s| s.path.clone()); - let preselect = self.settings.last_target.clone().or(source); + let target = self.current_target(); + let preselect = target.or(self.settings.last_target.clone()).or(source); // Databases not read yet are read now, for their counts and encodings. for p in self.settings.databases.clone() { if self.library.database(&p).is_none() && p.exists() { @@ -716,6 +742,7 @@ impl App { index, block: None, }); + g.target = None; g.game.mark_saved(); } self.settings.last_target = Some(target.clone()); @@ -1844,6 +1871,8 @@ impl App { .as_ref() .filter(|s| s.block.is_none()) .map(|s| own_db::base_name(&s.path)); + // A new game meant for a database goes there. + let target = self.current_target().map(|t| own_db::base_name(&t)); egui::Modal::new(egui::Id::new("confirm_close")).show(ctx, |ui| { ui.set_width(380.0); ui.heading(tr("Game modified")); @@ -1854,6 +1883,9 @@ impl App { (Some(name), _) => { ui.label(trf("Save the changes to «{name}»?", &[("name", name)])); } + (None, None) if let Some(name) = &target => { + ui.label(trf("Add the game to «{name}»?", &[("name", name)])); + } (None, Some(s)) => { if let Some(b) = &s.block { ui.label(b.long()); @@ -1868,9 +1900,10 @@ impl App { } ui.add_space(8.0); ui.horizontal(|ui| { - let primary = match &own { - Some(name) => trf("Save to «{name}»", &[("name", name)]), - None => tr("Add to database…").to_owned(), + let primary = match (&own, &target) { + (Some(name), _) => trf("Save to «{name}»", &[("name", name)]), + (None, Some(name)) => trf("Add to «{name}»", &[("name", name)]), + (None, None) => tr("Add to database…").to_owned(), }; if crate::widgets::primary(ui, &primary).clicked() { choice = Some(0); @@ -1903,7 +1936,7 @@ impl App { match choice { Some(0) => { self.confirm_close = None; - if own.is_some() { + if own.is_some() || target.is_some() { self.save_current(ctx, Some(intent)); } else { self.own.then_close = Some(intent); @@ -1998,6 +2031,9 @@ impl eframe::App for App { self.settings_ui.open = !self.settings_ui.open; } + // A new game's target base that left the shelf or stopped taking games is + // dropped before the game is drawn (its header names the target). + let _ = self.current_target(); if let Some(game) = &mut self.game { let input_enabled = self.confirm_close.is_none(); // A database opened for the reference tab arrives here (the library is @@ -2133,6 +2169,12 @@ impl eframe::App for App { } LibraryAction::OpenPgn(text) => self.open_pgn_text(&ctx, text, true), LibraryAction::NewGame => self.new_game(), + LibraryAction::NewGameIn(path) => { + self.new_game(); + if let Some(g) = self.game.as_mut() { + g.target = Some(path); + } + } LibraryAction::PastePgn => self.paste_pgn(&ctx), LibraryAction::AddDatabases => self.pick_databases(&ctx), LibraryAction::OnlineGames => self.online.open(), diff --git a/apps/desktop/src/examples.rs b/apps/desktop/src/examples.rs index 9d2aa42..2aaacd3 100644 --- a/apps/desktop/src/examples.rs +++ b/apps/desktop/src/examples.rs @@ -26,6 +26,12 @@ fn dir() -> Option { .map(|d| d.data_local_dir().join("examples")) } +/// A sample database of the program: only read (games added there would end up in a +/// hidden data folder). +pub fn is_example(path: &std::path::Path) -> bool { + dir().is_some_and(|d| path.starts_with(d)) +} + /// Adds the samples once; `true` when the settings changed. A new library starts with /// them (the classics open); an existing one gets them after its own databases. pub fn first_run_setup(settings: &mut Settings) -> bool { diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 8935ab2..a11e90a 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -49,6 +49,9 @@ impl Preview { pub struct GameView { pub game: Game, pub source: Option, + /// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there. + /// Cleared once the game is in a database. + pub target: Option, pub diagnostics: Vec, cursor: NodeId, board: BoardState, @@ -141,6 +144,7 @@ impl GameView { }, previous: None, data_asked: false, + target: None, update: None, translation: Default::default(), translate_now: false, @@ -176,6 +180,17 @@ impl GameView { /// Where the game lives: «🗄 Petrov · No. 13» (🌐 an online database, 🔒 a read-only /// one); nothing for a game that is in no database yet. pub fn source_line(&self) -> Option { + if self.source.is_none() + && let Some(t) = &self.target + { + return Some(format!( + "🗄 {}", + trf( + "{name} · new game", + &[("name", &crate::own_db::base_name(t))] + ) + )); + } let s = self.source.as_ref()?; let icon = match &s.block { None => "🗄", @@ -191,11 +206,15 @@ impl GameView { /// What Ctrl+S does to this game, for the button's tooltip. pub fn save_hint(&self) -> String { - match &self.source { - Some(s) if s.block.is_none() => trf( + match (&self.source, &self.target) { + (Some(s), _) if s.block.is_none() => trf( "Save to «{name}» (Ctrl+S)", &[("name", &crate::own_db::base_name(&s.path))], ), + (None, Some(t)) => trf( + "Add to «{name}» (Ctrl+S)", + &[("name", &crate::own_db::base_name(t))], + ), _ => tr("Add to database… (Ctrl+S)").to_owned(), } } @@ -1380,13 +1399,9 @@ impl GameView { actions.push(GameAction::EditGameData); ui.close(); } - if let Some(s) = self.source.as_ref().filter(|s| s.block.is_none()) - && ui - .button(trf( - "Save to «{name}» (Ctrl+S)", - &[("name", &crate::own_db::base_name(&s.path))], - )) - .clicked() + let writable_source = self.source.as_ref().is_some_and(|s| s.block.is_none()); + if (writable_source || (self.source.is_none() && self.target.is_some())) + && ui.button(self.save_hint()).clicked() { actions.push(GameAction::Save); ui.close(); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 502ab85..b6f3773 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -9229,17 +9229,6 @@ const ROWS: &[[&str; 9]] = &[ "🔍 Baza qidirish", "🔍 База іздеу", ], - [ - "No PGN databases on the shelf yet — create one below.", - "На полке пока нет PGN-баз — создайте ниже.", - "Pas encore de base PGN sur l’étagère — créez-en une ci-dessous.", - "Noch keine PGN-Datenbanken im Regal — legen Sie unten eine an.", - "Aún no hay bases PGN en el estante; cree una abajo.", - "Ancora nessun database PGN sullo scaffale: creane uno qui sotto.", - "Ainda não há bases PGN na estante — crie uma abaixo.", - "Javonda hali PGN bazalar yo‘q — quyida yarating.", - "Сөреде әзірге PGN базалары жоқ — төменде жасаңыз.", - ], [ "✚ New database…", "✚ Новая база…", @@ -9736,6 +9725,138 @@ const ROWS: &[[&str; 9]] = &[ "Faylning UTF-8 dagi nusxasi yonida: nusxaga o‘yinlar qo‘shish mumkin", "Файлдың UTF-8 көшірмесі қасында: көшірмеге партия қосуға болады", ], + [ + "Add the game to «{name}»?", + "Добавить партию в «{name}»?", + "Ajouter la partie à « {name} » ?", + "Die Partie in „{name}“ aufnehmen?", + "¿Añadir la partida a «{name}»?", + "Aggiungere la partita a «{name}»?", + "Adicionar a partida a “{name}”?", + "O‘yinni “{name}” bazasiga qo‘shasizmi?", + "Партияны «{name}» базасына қосу керек пе?", + ], + [ + "{name} · new game", + "{name} · новая партия", + "{name} · nouvelle partie", + "{name} · neue Partie", + "{name} · partida nueva", + "{name} · nuova partita", + "{name} · nova partida", + "{name} · yangi o‘yin", + "{name} · жаңа партия", + ], + [ + "Add to «{name}» (Ctrl+S)", + "Добавить в «{name}» (Ctrl+S)", + "Ajouter à « {name} » (Ctrl+S)", + "In „{name}“ aufnehmen (Ctrl+S)", + "Añadir a «{name}» (Ctrl+S)", + "Aggiungi a «{name}» (Ctrl+S)", + "Adicionar a “{name}” (Ctrl+S)", + "“{name}” bazasiga qo‘shish (Ctrl+S)", + "«{name}» базасына қосу (Ctrl+S)", + ], + [ + "🔍 Search", + "🔍 Поиск", + "🔍 Rechercher", + "🔍 Suche", + "🔍 Buscar", + "🔍 Cerca", + "🔍 Buscar", + "🔍 Qidirish", + "🔍 Іздеу", + ], + [ + "+ Game", + "+ Партия", + "+ Partie", + "+ Partie", + "+ Partida", + "+ Partita", + "+ Partida", + "+ O‘yin", + "+ Партия", + ], + [ + "A new game for «{name}»: Ctrl+S adds it to this database", + "Новая партия для «{name}»: Ctrl+S добавит её в эту базу", + "Une nouvelle partie pour « {name} » : Ctrl+S l’ajoute à cette base", + "Eine neue Partie für „{name}“: Strg+S nimmt sie in diese Datenbank auf", + "Una partida nueva para «{name}»: Ctrl+S la añade a esta base", + "Una nuova partita per «{name}»: Ctrl+S la aggiunge a questo database", + "Uma nova partida para “{name}”: Ctrl+S a adiciona a esta base", + "“{name}” uchun yangi o‘yin: Ctrl+S uni shu bazaga qo‘shadi", + "«{name}» үшін жаңа партия: Ctrl+S оны осы базаға қосады", + ], + [ + "This is a sample database of the program; it is only read. Make a database of your own for your games.", + "Это пример из комплекта программы, он только читается. Для своих партий создайте свою базу.", + "C’est une base d’exemple du programme ; elle est en lecture seule. Créez votre propre base pour vos parties.", + "Dies ist eine Beispieldatenbank des Programms; sie wird nur gelesen. Legen Sie für Ihre Partien eine eigene Datenbank an.", + "Es una base de ejemplo del programa; solo se lee. Cree su propia base para sus partidas.", + "È un database di esempio del programma; è in sola lettura. Crea un tuo database per le tue partite.", + "É uma base de exemplo do programa; ela é somente leitura. Crie sua própria base para suas partidas.", + "Bu dasturning namuna bazasi, u faqat o‘qiladi. O‘yinlaringiz uchun o‘z bazangizni yarating.", + "Бұл бағдарламаның үлгі базасы, ол тек оқылады. Өз партияларыңыз үшін жеке база жасаңыз.", + ], + [ + "No databases yet", + "Баз пока нет", + "Aucune base pour l’instant", + "Noch keine Datenbanken", + "Aún no hay bases", + "Nessun database per ora", + "Ainda não há bases", + "Hozircha bazalar yo‘q", + "Әзірге база жоқ", + ], + [ + "or", + "или", + "ou", + "oder", + "o", + "oppure", + "ou", + "yoki", + "немесе", + ], + [ + "Choose a database above", + "Выберите базу выше", + "Choisissez une base ci-dessus", + "Wählen Sie oben eine Datenbank", + "Elija una base arriba", + "Scegli un database qui sopra", + "Escolha uma base acima", + "Yuqoridan bazani tanlang", + "Жоғарыдан базаны таңдаңыз", + ], + [ + "No databases of your own yet: create one below.", + "Своих баз пока нет: создайте её ниже.", + "Pas encore de base à vous : créez-en une ci-dessous.", + "Noch keine eigene Datenbank: Legen Sie unten eine an.", + "Aún no tiene bases propias: cree una abajo.", + "Non hai ancora database tuoi: creane uno qui sotto.", + "Você ainda não tem bases próprias: crie uma abaixo.", + "Hozircha o‘z bazangiz yo‘q: quyida yarating.", + "Әзірге өз базаңыз жоқ: төменде жасаңыз.", + ], + [ + "«+ Game» opens an empty board; Ctrl+S adds the game here. Or open any game and choose «Add to database…» (Ctrl+Shift+S)", + "«+ Партия» откроет пустую доску; Ctrl+S добавит партию сюда. Или откройте любую партию и выберите «Добавить в базу…» (Ctrl+Shift+S)", + "« + Partie » ouvre un échiquier vide ; Ctrl+S ajoute la partie ici. Ou ouvrez n’importe quelle partie et choisissez « Ajouter à une base… » (Ctrl+Shift+S)", + "„+ Partie“ öffnet ein leeres Brett; Strg+S nimmt die Partie hier auf. Oder öffnen Sie eine beliebige Partie und wählen Sie „Zur Datenbank hinzufügen…“ (Strg+Umschalt+S)", + "«+ Partida» abre un tablero vacío; Ctrl+S añade la partida aquí. O abra cualquier partida y elija «Añadir a una base…» (Ctrl+Shift+S)", + "«+ Partita» apre una scacchiera vuota; Ctrl+S aggiunge qui la partita. Oppure apri una partita qualsiasi e scegli «Aggiungi a un database…» (Ctrl+Shift+S)", + "“+ Partida” abre um tabuleiro vazio; Ctrl+S adiciona a partida aqui. Ou abra qualquer partida e escolha “Adicionar a uma base…” (Ctrl+Shift+S)", + "“+ O‘yin” bo‘sh taxtani ochadi; Ctrl+S o‘yinni shu yerga qo‘shadi. Yoki istalgan o‘yinni oching va “Bazaga qo‘shish…” ni tanlang (Ctrl+Shift+S)", + "«+ Партия» бос тақтаны ашады; Ctrl+S партияны осында қосады. Немесе кез келген партияны ашып, «Базаға қосу…» таңдаңыз (Ctrl+Shift+S)", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 94dd1dc..c87fef1 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -886,10 +886,22 @@ impl LargeView { let resp = ui .add( egui::TextEdit::singleline(&mut self.form.search) - .hint_text(tr("🔍 Search: player, event, ECO, year")) + .hint_text(if width < 200.0 { + tr("🔍 Search") + } else { + tr("🔍 Search: player, event, ECO, year") + }) .desired_width(width), ) - .on_hover_text(tr("Ctrl+F; again — the filters")); + .on_hover_text(if width < 200.0 { + format!( + "{}\n{}", + tr("🔍 Search: player, event, ECO, year"), + tr("Ctrl+F; again — the filters") + ) + } else { + tr("Ctrl+F; again — the filters").to_owned() + }); if resp.changed() { self.typed_at = now; } @@ -1621,24 +1633,42 @@ impl LargeView { // A database with no games yet (own-databases.md §2.3): how to put one in. if total == 0 && writable { let name = crate::own_db::base_name(path); + // The header as for any database; nothing to search, so no field and no switch. + ui.horizontal(|ui| { + ui.label(RichText::new(&name).strong()); + ui.label(RichText::new(format!("· {}", header.format)).weak()); + ui.label(format!("· {}", crate::i18n::games(0))); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .button(tr("+ Game")) + .on_hover_text(new_game_hint(&name)) + .clicked() + { + actions.push(LibraryAction::NewGameIn(path.to_path_buf())); + } + }); + }); ui.vertical_centered(|ui| { ui.add_space(60.0); ui.label( RichText::new(trf("No games in «{name}» yet", &[("name", &name)])).size(16.0), ); + ui.add_space(10.0); + if crate::widgets::primary(ui, tr("+ Game")) + .on_hover_text(new_game_hint(&name)) + .clicked() + { + actions.push(LibraryAction::NewGameIn(path.to_path_buf())); + } ui.add_space(6.0); ui.label( RichText::new(tr( - "Add one: ♟ New game, or «Add to database…» (Ctrl+Shift+S) from any game.", + "«+ Game» opens an empty board; Ctrl+S adds the game here. Or open any game and choose «Add to database…» (Ctrl+Shift+S)", )) .weak(), ); ui.add_space(6.0); ui.label(RichText::new(trf("File: {path}", &[("path", &path.display())])).weak()); - ui.add_space(10.0); - if ui.button(tr("♟ New game")).clicked() { - actions.push(LibraryAction::NewGame); - } }); return open_notes; } @@ -1705,31 +1735,52 @@ impl LargeView { let name_w = text_w(ui, &name, egui::TextStyle::Body) + gap; let format_w = body(&format) + gap; let avail = ui.available_width(); - let right = |field: f32| switch_w + 8.0 + search_w(field); + // «+ Game» (a database that takes games only), shortened to «+» after the field. + let plus_w = |full: bool| { + if !writable { + 0.0 + } else if full { + body(tr("+ Game")) + pad + 8.0 + gap + } else { + body("+") + pad + 8.0 + gap + } + }; + let right = |field: f32, full: bool| switch_w + 8.0 + search_w(field) + plus_w(full); // One line: the widest field that leaves the counter and at least 80 of the name. - // (field, format, the name's least room: 0 leaves the name out) + // (field, format, the name's least room: 0 leaves the name out, «+ Game» in full) let one_line = [ - (220.0, true, name_w), - (220.0, false, 80.0 + gap), - (140.0, false, 80.0 + gap), - (140.0, false, 0.0), + (220.0, true, name_w, true), + (220.0, false, 80.0 + gap, true), + (140.0, false, 80.0 + gap, true), + (140.0, false, 80.0 + gap, false), + (140.0, false, 0.0, false), ] .into_iter() - .find(|(field, with_format, name_least)| { + .find(|(field, with_format, name_least, full)| { let format = if *with_format { format_w } else { 0.0 }; - avail - right(*field) - info_w - format >= *name_least + avail - right(*field, *full) - info_w - format >= *name_least }) - .map(|(field, with_format, _)| (field, with_format)); - let field = match one_line { - Some((field, _)) => field, - None if avail - right(220.0) >= 80.0 + gap => 220.0, - None => 140.0, + .map(|(field, with_format, _, full)| (field, with_format, full)); + let (field, plus_full) = match one_line { + Some((field, _, full)) => (field, full), + None if avail - right(220.0, true) >= 80.0 + gap => (220.0, true), + None => (140.0, false), }; - let with_format = one_line.is_some_and(|(_, f)| f); + let with_format = one_line.is_some_and(|(_, f, _)| f); let mut back_to_list = false; + let mut new_game = false; let alone = self.board_alone(); // On a line of its own the counter loses its leading "· ". - let counter_text = if one_line.is_some() { + // The name is drawn when it has its own width or at least 80 (shortened). + let name_shown = |room: f32| room >= name_w.min(80.0 + gap); + let name_room = if one_line.is_some() { + avail - right(field, plus_full) - info_w - if with_format { format_w } else { 0.0 } + } else { + avail - right(field, plus_full) + }; + let shown = name_shown(name_room); + // What starts the line loses its leading "· ". + let counter_text = if one_line.is_some() && (shown || with_format) { counter.as_str() } else { counter.trim_start_matches("· ") @@ -1772,13 +1823,8 @@ impl LargeView { } } }; - let name_room = if one_line.is_some() { - avail - right(field) - info_w - if with_format { format_w } else { 0.0 } - } else { - avail - right(field) - }; ui.horizontal(|ui| { - if name_room >= 80.0 + gap { + if shown { ui.allocate_ui( vec2((name_room - gap).floor(), ui.spacing().interact_size.y), |ui| { @@ -1788,7 +1834,12 @@ impl LargeView { ); } if with_format { - ui.label(RichText::new(&format).weak()) + let format = if shown { + format.as_str() + } else { + format.trim_start_matches("· ") + }; + ui.label(RichText::new(format).weak()) .on_hover_text(&header.format_hint); } if one_line.is_some() { @@ -1799,6 +1850,17 @@ impl LargeView { ui.scope(|ui| self.pane_switch(ui)); ui.add_space(8.0); self.search_field(ui, now, field); + if writable { + ui.add_space(8.0 - ui.spacing().item_spacing.x); + let label = if plus_full { tr("+ Game") } else { "+" }; + if ui + .button(label) + .on_hover_text(new_game_hint(&name)) + .clicked() + { + new_game = true; + } + } }); }); if one_line.is_none() { @@ -1807,6 +1869,9 @@ impl LargeView { if back_to_list { self.pane = Pane::Hidden; } + if new_game { + actions.push(LibraryAction::NewGameIn(path.to_path_buf())); + } self.chips(ui, settings); ui.add_space(2.0); self.drawer_top = ui.cursor().top(); @@ -2532,6 +2597,14 @@ pub fn short_count(n: usize) -> String { } } +/// The tooltip of «+ Game»: where its game goes. +fn new_game_hint(name: &str) -> String { + trf( + "A new game for «{name}»: Ctrl+S adds it to this database", + &[("name", &name)], + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 7382346..6b3d3f0 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -38,6 +38,8 @@ pub enum LibraryAction { /// Open PGN text as a new game. OpenPgn(String), NewGame, + /// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there. + NewGameIn(PathBuf), PastePgn, AddDatabases, /// The window for downloading games from Lichess and Chess.com. @@ -91,6 +93,25 @@ fn button_w(ui: &Ui, text: &str) -> f32 { + ui.spacing().item_spacing.x } +/// A PGN file whose beginning is in a legacy (single-byte) encoding: it takes games only +/// through a UTF-8 copy. For a file not read yet (its card's menu). +fn legacy_pgn(path: &Path) -> bool { + use std::io::Read; + let pgn = path + .extension() + .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("pgn")); + if !pgn || crate::online::is_online(path) || crate::examples::is_example(path) { + return false; + } + let mut head = Vec::with_capacity(64 << 10); + let read = std::fs::File::open(path).and_then(|f| f.take(64 << 10).read_to_end(&mut head)); + if read.is_err() { + return false; + } + let guess = chess_core::detect_encoding(&head); + guess.encoding != chess_core::TextEncoding::Utf8 && !guess.ascii_only +} + /// The width of the shelf's buttons on the right (`Library::shelf_buttons`). fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 { let texts: [&str; 3] = if icons { @@ -261,6 +282,9 @@ impl Library { if crate::online::is_online(path) { return Some(Block::Online); } + if crate::examples::is_example(path) { + return Some(Block::Example); + } if !path.exists() { return Some(Block::Missing); } @@ -431,18 +455,13 @@ impl Library { .selected_db .as_ref() .is_some_and(|p| self.large.get(p).is_some_and(|v| v.pane() == Pane::Board)); - let (add_w, new_w, online_w) = side_card_widths(ui); - let cards = databases.len() + 2 + usize::from(self.online); + // The shelf's rows hold the databases only (their actions are in the title row). + let cards = databases.len(); let card_rows = { let mut rows = 1; let mut x = 0.0; - for k in 0..cards { - let w = match k.checked_sub(databases.len()) { - None => 190.0, - Some(0) => add_w, - Some(1) => new_w, - Some(_) => online_w, - }; + for _ in 0..cards { + let w = 190.0; if x > 0.0 && x + w > width - 16.0 { rows += 1; x = 0.0; @@ -472,7 +491,10 @@ impl Library { width < table_min + FILTERS_MIN, width < table_min_pos + SEARCH_BOARD_MIN, ); + // An empty database has nothing to filter: no panel beside it. + let empty = db.games() + db.texts() == 0; match view.pane() { + _ if empty => {} Pane::Filters if view.drawer().is_none() && width >= table_min + FILTERS_MIN => { let r = egui::Panel::right("filters") .resizable(true) @@ -597,13 +619,7 @@ impl Library { // The list of databases gives way first (to 180), then the buttons on the right // show their icons, then the list goes down to 140 (narrow-windows.md §2.5). let gap = ui.spacing().item_spacing.x; - let others = button_w(ui, "+") - + if self.online { - button_w(ui, "🌐") - } else { - 0.0 - } - + 16.0; + let others = self.shelf_actions_w(ui, true) + 16.0; let free = ui.available_width() - others; let icons = free - shelf_buttons_w(ui, self.update.as_deref(), false) < 180.0 + gap; let list = (free - shelf_buttons_w(ui, self.update.as_deref(), icons) - gap) @@ -629,26 +645,7 @@ impl Library { if let Some(p) = pick { self.select_db(&p, ui.ctx()); } - ui.menu_button("+", |ui| { - if ui.button(tr("Add database…")).on_hover_text(tr( - "Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)", - )).clicked() { - actions.push(LibraryAction::AddDatabases); - ui.close(); - } - if ui.button(tr("New database…")).on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")).clicked() { - actions.push(LibraryAction::NewDatabase); - ui.close(); - } - }); - if self.online - && ui - .button("🌐") - .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) - .clicked() - { - actions.push(LibraryAction::OnlineGames); - } + self.shelf_actions(ui, true, actions); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { self.shelf_buttons(ui, icons, actions); }); @@ -705,74 +702,153 @@ impl Library { fn shelf(&mut self, ui: &mut Ui, databases: &[PathBuf], actions: &mut Vec) { ui.add_space(8.0); + // The title row (library-layout.md §1.4): «Databases», the actions with databases + // on the left, the game and program ones on the right. Narrowing: the left group + // folds to «+ ▾ 🌐» first (databases are added seldom), then the right one shows + // icons, then the title goes. + let avail = ui.available_width(); let heading = text_w(ui, tr("Databases"), egui::TextStyle::Heading) + 16.0; - let icons = - ui.available_width() - heading < shelf_buttons_w(ui, self.update.as_deref(), false); + let between = 24.0; + let update = self.update.as_deref(); + let full = self.shelf_actions_w(ui, false); + let short = self.shelf_actions_w(ui, true); + let right = |icons| shelf_buttons_w(ui, update, icons); + let (title, folded, icons) = if heading + full + between + right(false) <= avail { + (true, false, false) + } else if heading + short + between + right(false) <= avail { + (true, true, false) + } else if heading + short + between + right(true) <= avail { + (true, true, true) + } else { + (false, true, true) + }; ui.horizontal(|ui| { - ui.heading(tr("Databases")); + if title { + ui.heading(tr("Databases")); + ui.add_space(16.0 - ui.spacing().item_spacing.x); + } + self.shelf_actions(ui, folded, actions); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { self.shelf_buttons(ui, icons, actions); }); }); - ui.add_space(4.0); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(8.0, 8.0); - for path in databases { - self.db_card(ui, path, actions); - } - let (add_w, new_w, online_w) = side_card_widths(ui); - let (rect, resp) = ui.allocate_exact_size(vec2(add_w, 64.0), Sense::click()); - let visuals = ui.style().interact(&resp); - ui.painter() - .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); - ui.painter().text( - rect.center(), - egui::Align2::CENTER_CENTER, - tr("+ Add database"), - egui::FontId::proportional(15.0), - visuals.text_color(), - ); - if resp - .on_hover_text(tr( - "Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)", - )) + if !databases.is_empty() { + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 8.0); + for path in databases { + self.db_card(ui, path, actions); + } + }); + } + ui.add_space(8.0); + } + + /// The width of `shelf_actions`. + fn shelf_actions_w(&self, ui: &Ui, folded: bool) -> f32 { + let online = self.online_running.map_or(0.0, |n| { + 14.0 + ui.spacing().item_spacing.x + button_w(ui, &crate::large_db::grouped(n)) + }); + let buttons = if folded { + button_w(ui, "+ ▾") + + if self.online { + button_w(ui, "🌐") + } else { + 0.0 + } + } else { + button_w(ui, tr("+ Add database")) + + button_w(ui, tr("✚ New database")) + + if self.online { + button_w(ui, &format!("🌐 {}", tr("Online games"))) + } else { + 0.0 + } + }; + buttons + if self.online { online } else { 0.0 } + } + + /// «+ Add database · ✚ New database · 🌐 Online games», or folded: «+ ▾» (a menu of + /// the first two) and «🌐»; a download under way shows its count beside the globe. + fn shelf_actions(&self, ui: &mut Ui, folded: bool, actions: &mut Vec) { + let add_hint = tr("Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)"); + let new_hint = tr("An empty PGN file for your own games (Ctrl+Shift+N)"); + let online_hint = tr( + "Download any player's games by nickname into a database: yours, a pupil's, an opponent's", + ); + if folded { + ui.menu_button("+ ▾", |ui| { + if ui + .button(tr("Add database…")) + .on_hover_text(add_hint) + .clicked() + { + actions.push(LibraryAction::AddDatabases); + ui.close(); + } + if ui + .button(tr("New database…")) + .on_hover_text(new_hint) + .clicked() + { + actions.push(LibraryAction::NewDatabase); + ui.close(); + } + }); + } else { + if ui + .button(tr("+ Add database")) + .on_hover_text(add_hint) .clicked() { actions.push(LibraryAction::AddDatabases); } - let (rect, resp) = ui.allocate_exact_size(vec2(new_w, 64.0), Sense::click()); - let visuals = ui.style().interact(&resp); - ui.painter() - .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); - ui.painter().text( - rect.center(), - egui::Align2::CENTER_CENTER, - tr("✚ New database"), - egui::FontId::proportional(15.0), - visuals.text_color(), - ); - if resp - .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) + if ui + .button(tr("✚ New database")) + .on_hover_text(new_hint) .clicked() { actions.push(LibraryAction::NewDatabase); } - if self.online { - let (rect, resp) = ui.allocate_exact_size(vec2(online_w, 64.0), Sense::click()); - let visuals = ui.style().interact(&resp); - ui.painter() - .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); - let below = match self.online_running { - Some(n) => trf("downloading… {n}", &[("n", &crate::i18n::games(n))]), - None => "Lichess · Chess.com".to_owned(), - }; - ui.painter().text( - rect.center() + vec2(0.0, -9.0), - egui::Align2::CENTER_CENTER, - format!("🌐 {}", tr("Online games")), - egui::FontId::proportional(15.0), - visuals.text_color(), - ); + } + if self.online { + let label = if folded { + "🌐".to_owned() + } else { + format!("🌐 {}", tr("Online games")) + }; + let hint = match self.online_running { + Some(n) => trf("downloading… {n}", &[("n", &crate::i18n::games(n))]), + None => online_hint.to_owned(), + }; + if ui.button(label).on_hover_text(hint).clicked() { + actions.push(LibraryAction::OnlineGames); + } + if let Some(n) = self.online_running { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(crate::large_db::grouped(n)).weak()); + } + } + } + + /// The empty shelf's invitation: the three actions as large cards, centred. + fn action_cards(&self, ui: &mut Ui, actions: &mut Vec) { + let (add_w, new_w, online_w) = side_card_widths(ui); + let total = add_w + new_w + if self.online { online_w + 8.0 } else { 0.0 } + 8.0; + let card = |ui: &mut Ui, w: f32, title: &str, below: Option<&str>| { + let (rect, resp) = ui.allocate_exact_size(vec2(w, 64.0), Sense::click()); + let visuals = ui.style().interact(&resp); + ui.painter() + .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); + let up = if below.is_some() { -9.0 } else { 0.0 }; + ui.painter().text( + rect.center() + vec2(0.0, up), + egui::Align2::CENTER_CENTER, + title, + egui::FontId::proportional(15.0), + visuals.text_color(), + ); + if let Some(below) = below { ui.painter().text( rect.center() + vec2(0.0, 11.0), egui::Align2::CENTER_CENTER, @@ -780,15 +856,48 @@ impl Library { egui::FontId::proportional(13.0), ui.visuals().weak_text_color(), ); - if resp - .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) - .clicked() - { - actions.push(LibraryAction::OnlineGames); - } + } + resp + }; + // One row, centred; a column of them, centred, when the row does not fit. + let row = ui.available_width() >= total; + let layout = if row { + egui::Layout::left_to_right(egui::Align::Min) + } else { + egui::Layout::top_down(egui::Align::Center) + }; + ui.with_layout(layout, |ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 8.0); + if row { + ui.add_space(((ui.available_width() - total) / 2.0).max(0.0)); + } + if card(ui, add_w, tr("+ Add database"), None) + .on_hover_text(tr( + "Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)", + )) + .clicked() + { + actions.push(LibraryAction::AddDatabases); + } + if card(ui, new_w, tr("✚ New database"), None) + .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) + .clicked() + { + actions.push(LibraryAction::NewDatabase); + } + if self.online + && card( + ui, + online_w, + &format!("🌐 {}", tr("Online games")), + Some("Lichess · Chess.com"), + ) + .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) + .clicked() + { + actions.push(LibraryAction::OnlineGames); } }); - ui.add_space(8.0); } fn db_card(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec) { @@ -870,16 +979,20 @@ impl Library { if resp.clicked() { self.select_db(path, ui.ctx()); } - let legacy = matches!( - self.write_block(path), - Some(crate::own_db::Block::Encoding(_)) - ); + let block = self.write_block(path); + let not_read = self.database(path).is_none() && block.is_none(); 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. + // Games are written in UTF-8: a legacy file takes them through a copy. A file + // not read yet is looked at now (its beginning), while the menu is open. + let legacy = match &block { + Some(crate::own_db::Block::Encoding(_)) => true, + None if not_read => legacy_pgn(path), + _ => false, + }; if legacy && ui .button(tr("Make a copy in UTF-8…")) @@ -905,15 +1018,36 @@ impl Library { fn table_area(&mut self, ui: &mut Ui, settings: &Settings, actions: &mut Vec) { let Some(path) = self.selected_db.clone() else { - ui.centered_and_justified(|ui| { - ui.label( - RichText::new(tr( - "Choose a database above, add a PGN file or start a new game", - )) - .weak() - .size(16.0), - ); - }); + if settings.databases.is_empty() { + // The empty shelf (library-layout.md §1.5): its actions where a newcomer + // looks, large. + ui.vertical_centered(|ui| { + ui.add_space(60.0); + ui.label(RichText::new(tr("No databases yet")).size(16.0)); + ui.add_space(12.0); + }); + self.action_cards(ui, actions); + ui.vertical_centered(|ui| { + ui.add_space(12.0); + ui.horizontal(|ui| { + let w = text_w(ui, tr("or"), egui::TextStyle::Body) + + button_w(ui, tr("♟ New game")); + ui.add_space(((ui.available_width() - w) / 2.0).max(0.0)); + ui.label(RichText::new(tr("or")).weak()); + if ui.button(tr("♟ New game")).clicked() { + actions.push(LibraryAction::NewGame); + } + }); + }); + } else { + ui.centered_and_justified(|ui| { + ui.label( + RichText::new(tr("Choose a database above")) + .weak() + .size(16.0), + ); + }); + } return; }; let db = match self.slots.get(&path) { diff --git a/apps/desktop/src/own_db.rs b/apps/desktop/src/own_db.rs index d839c4d..aa3924a 100644 --- a/apps/desktop/src/own_db.rs +++ b/apps/desktop/src/own_db.rs @@ -21,6 +21,8 @@ pub enum Block { Online, /// A ChessBase database or an archive: read only. ReadOnly, + /// A sample database of the program: read only. + Example, /// A PGN in another encoding: a UTF-8 copy can take games. Encoding(&'static str), /// The file cannot be written (permissions). @@ -36,6 +38,7 @@ impl Block { Block::Online => tr("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.").to_owned(), Block::ReadOnly => tr("ChessBase databases and archives are only read. Add the game to a PGN database of your own.").to_owned(), Block::Encoding(enc) => trf("This file is in the {enc} encoding; games are written in UTF-8. Make a copy of it in UTF-8 and add games to the copy — the original stays as it is.", &[("enc", enc)]), + Block::Example => tr("This is a sample database of the program; it is only read. Make a database of your own for your games.").to_owned(), Block::NoPermission => tr("The file cannot be written: no permission.").to_owned(), Block::Missing => tr("The file is not on the disk any more.").to_owned(), } @@ -368,10 +371,8 @@ impl Chooser { .show(ui, |ui| { if order.is_empty() { ui.label( - RichText::new(tr( - "No PGN databases on the shelf yet — create one below.", - )) - .weak(), + RichText::new(tr("No databases of your own yet: create one below.")) + .weak(), ); } // Rows the whole width, their text from the left. @@ -409,7 +410,14 @@ impl Chooser { }); }); ui.separator(); - if ui.button(tr("✚ New database…")).clicked() { + // Nothing to choose: the new database is the main way, not «Add». + let none = !self.rows.iter().any(|r| r.block.is_none()); + let new_base = if none { + crate::widgets::primary(ui, tr("✚ New database…")) + } else { + ui.button(tr("✚ New database…")) + }; + if new_base.clicked() || (none && ui.input(|i| i.key_pressed(Key::Enter))) { out = Some(ChooserOutcome::NewBase); } if self.purpose == ChooserFor::CurrentGame @@ -425,13 +433,15 @@ impl Chooser { ui.add_space(8.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let pick = self.selected.map(|i| self.rows[i].path.clone()); - let add = ui - .add_enabled_ui(pick.is_some(), |ui| crate::widgets::primary(ui, tr("Add"))) - .inner; - if (add.clicked() || enter) - && let Some(p) = pick - { - out = Some(ChooserOutcome::Pick(p)); + if !none { + let add = ui + .add_enabled_ui(pick.is_some(), |ui| crate::widgets::primary(ui, tr("Add"))) + .inner; + if (add.clicked() || enter) + && let Some(p) = pick + { + out = Some(ChooserOutcome::Pick(p)); + } } if ui.button(tr("Cancel")).clicked() { out = Some(ChooserOutcome::Cancel); diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 43b14eb..a08a793 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -51,7 +51,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete` — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete|newin` (`newin` — «+ Партия» первой базы) — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index 56f95b8..f176982 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -77,7 +77,7 @@ - **Мысли:** ядро на Rust уже общее (UniFFI умеет Swift); нужен интерфейс на SwiftUI, аккаунт Apple Developer (99 $/год) и проверка App Store; Stockfish на iOS разрешён (есть в App Store у других). Большая отдельная работа. ### 8. Нужна ли строка быстрого поиска, когда есть панель фильтров? -- **Статус:** новая (вопрос владельца). +- **Статус:** решено (2026-10-25): оставить оба. Аналитик и дизайнер (`docs/research/library-layout.md`, `docs/design/library-layout.md`): поиск ищет слово по всем полям сразу («вафин 2025») и виден, когда фильтры скрыты (узкое окно, доска поиска); в узком поле подсказка короткая «🔍 Поиск». - **Добавлено:** 2026-10-24. - **Вопрос:** в шапке таблицы есть поле «Поиск: игрок, турнир, ECO, год», а справа — панель фильтров с теми же полями. Не дублируют ли они друг друга? - **Чем поиск сейчас отличается** (`docs/design/large-databases.md` §9.2): одно поле ищет сразу по всему — игрокам, турниру, комментатору, ECO, году, дате — без выбора поля и без открытия панели; слова можно смешивать («вафин 2025»). Фильтры точнее: цвет, диапазон лет, Эло, результат, длина, аннотации. Поиск и фильтры складываются.