From 4ebb1bb6835601a485cde511707db58c1d7519f7 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 24 Oct 2026 10:19:59 +0300 Subject: [PATCH] =?UTF-8?q?Desktop:=20the=20library=20in=20a=20narrow=20wi?= =?UTF-8?q?ndow=20=E2=80=94=20filters=20over=20the=20list,=20the=20board?= =?UTF-8?q?=20in=20its=20place?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit By the window's width alone (docs/design/narrow-windows.md §2): when the list would get less than its least width beside them, the filters open over it (Esc, a click elsewhere or the segment closes them) and the search board takes the list's place (Esc, the segment or the counter go back). The header of the list is measured from its texts and takes a second line when needed; the shelf folds into one line when its cards need more than two rows or the window is low, its buttons showing icons when narrow. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + apps/desktop/src/i18n.rs | 8 + apps/desktop/src/large_db.rs | 397 ++++++++++++++++++++++++++--------- apps/desktop/src/library.rs | 233 +++++++++++++++----- docs/dev/desktop.md | 2 +- 5 files changed, 499 insertions(+), 152 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 804ae3f..c6a2fb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Desktop: narrow windows (half a screen, a tiling window manager) no longer overlap: + - the reference tab, the engine settings and the game's title fit their place (the + reference tab slid under the board from a 1200-point window down); + - in a narrow window the filters open over the list of games, and the search board + takes the place of the list (Esc goes back); + - a narrow tall window shows the notation under the board; + - the header of the list and the shelf shorten what does not fit, or take a second + line; the window can be made as small as 640×480. + ## [0.16.1] — 2026-10-24 - Desktop: the filter panel no longer widens while a name is typed; the rows of «Game» diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 2fcc0a9..01560c7 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -2207,6 +2207,14 @@ const ROWS: &[[&str; 6]] = &[ "Filtros: jugadores, torneo, años, Elo… (Ctrl+F)", "Filtri: giocatori, torneo, anni, Elo… (Ctrl+F)", ], + [ + "Show the list of games (Esc)", + "Показать список партий (Esc)", + "Afficher la liste des parties (Échap)", + "Partienliste anzeigen (Esc)", + "Mostrar la lista de partidas (Esc)", + "Mostra l'elenco delle partite (Esc)", + ], [ "Hide the panel", "Скрыть панель", diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 21a618b..0d2c892 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -210,6 +210,29 @@ pub enum Pane { Board, } +/// Widths of the narrow set of table columns (docs/design/narrow-windows.md §1): the +/// least table is built of them, so the table and its least width do not part. +const MOVE_COL: f32 = 52.0; +const ELO_COL: f32 = 44.0; +const RESULT_COL: f32 = 56.0; +const YEAR_COL: f32 = 48.0; +/// A name still recognised ("Конюшенко С…"). +const NAME_MIN: f32 = 110.0; + +/// The width of the "№" column: as wide as the largest number (a check mark before it). +fn number_col(db: &Database) -> f32 { + let digits = grouped(db.len()).chars().count() as f32; + (digits * 8.0 + 24.0).clamp(52.0, 84.0) +} + +/// The width of `text` in `style` on one line. +fn text_w(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { + ui.painter() + .layout_no_wrap(text.to_owned(), style.resolve(ui.style()), Color32::WHITE) + .size() + .x +} + /// Search outcomes of the session, by filter and position with the board's move order /// (it decides "in this move order"). type OutcomeCache = HashMap<(u64, u64), Arc>; @@ -296,6 +319,13 @@ pub struct LargeView { blocked: Option, /// Ctrl+F asked for the quick search. focus_search: bool, + /// The window is too narrow for the filters beside the table: they open over it + /// (`drawer_open`), and too narrow for the board beside it: one at a time (§2). + narrow_filters: bool, + narrow_board: bool, + drawer_open: bool, + /// Where the filters open over the table: under its header and conditions. + drawer_top: f32, /// The quick search has the keyboard (arrows and Enter go to the table). search_focused: bool, } @@ -333,9 +363,13 @@ impl LargeView { Some(b) => (b, Pane::Board), None => (SearchBoard::new(), Pane::Filters), }; - if std::env::var("CP_PANE").as_deref() == Ok("hidden") { + // `CP_PANE=hidden`: no panel; `=drawer`: the filters open over the table in a + // narrow window (beside it in a wide one). + let pane_env = std::env::var("CP_PANE").ok(); + if pane_env.as_deref() == Some("hidden") { pane = Pane::Hidden; } + let drawer = pane_env.as_deref() == Some("drawer"); // `CP_SORT=date`: newest games first (screenshots). let sort = if std::env::var("CP_SORT").as_deref() == Ok("date") { (SortKey::Date, false) @@ -371,6 +405,10 @@ impl LargeView { blocked: None, focus_search: false, search_focused: false, + narrow_filters: drawer, + narrow_board: false, + drawer_open: drawer, + drawer_top: 0.0, } } @@ -407,6 +445,74 @@ impl LargeView { self.pane } + /// The least width of the table with the narrow set of columns (§1): the "Move" + /// column instead of "№" when the list is a position's games. + pub fn table_min_width(&self, db: &Database, use_position: bool) -> f32 { + let first = if use_position { + MOVE_COL + } else { + number_col(db) + }; + first + 2.0 * ELO_COL + RESULT_COL + YEAR_COL + 2.0 * NAME_MIN + 6.0 * 8.0 + 10.0 + 16.0 + } + + /// The layout the window allows (§2.1). Narrowing closes the filters rather than + /// laying them over the table; widening docks the filters opened over it. + pub fn set_layout(&mut self, narrow_filters: bool, narrow_board: bool) { + if narrow_filters && !self.narrow_filters { + self.drawer_open = false; + } + if !narrow_filters && self.narrow_filters && self.drawer_open { + self.drawer_open = false; + if self.pane != Pane::Board || !narrow_board { + self.pane = Pane::Filters; + } + } + self.narrow_filters = narrow_filters; + self.narrow_board = narrow_board; + } + + /// The filters open over the table: from where (under the header). + pub fn drawer(&self) -> Option { + (self.narrow_filters && self.drawer_open).then_some(self.drawer_top) + } + + pub fn close_drawer(&mut self) { + self.drawer_open = false; + } + + /// The board takes the place of the table (a narrow window). + pub fn board_alone(&self) -> bool { + self.narrow_board && self.pane == Pane::Board + } + + /// Escape in the library with no field typing: the filters over the table close, + /// then the board alone gives the place back to the table. + pub fn escape(&mut self) -> bool { + if self.drawer().is_some() { + self.drawer_open = false; + true + } else if self.board_alone() { + self.pane = Pane::Hidden; + true + } else { + false + } + } + + /// Opens the filters: beside the table, or over it in a narrow window (over the + /// board alone too, which stays). + fn open_filters(&mut self) { + if self.narrow_filters { + self.drawer_open = true; + if !self.board_alone() { + self.pane = Pane::Filters; + } + } else { + self.pane = Pane::Filters; + } + } + /// Shows the board with `line` played from `start` (a position from a game). pub fn show_position( &mut self, @@ -740,7 +846,7 @@ impl LargeView { /// The quick search of the header (§9.2): words found in a player, the tournament, /// the annotator, the ECO code or the date; with the panel and the position. - fn search_field(&mut self, ui: &mut Ui, now: f64) { + fn search_field(&mut self, ui: &mut Ui, now: f64, width: f32) { // The × has its place also when there is nothing to clear: the field stays put. if self.form.search.is_empty() { ui.add_space(20.0); @@ -751,11 +857,6 @@ impl LargeView { self.form.search.clear(); self.typed_at = f64::NEG_INFINITY; } - let width = if ui.available_width() > 700.0 { - 220.0 - } else { - 140.0 - }; let resp = ui .add( egui::TextEdit::singleline(&mut self.form.search) @@ -794,7 +895,12 @@ impl LargeView { /// The pane switch `[Filters | Board]`; a click on the shown pane hides it. fn pane_switch(&mut self, ui: &mut Ui) { let active = self.form.active(); - let filters = if active > 0 && self.pane != Pane::Filters { + let filters_shown = if self.narrow_filters { + self.drawer_open + } else { + self.pane == Pane::Filters + }; + let filters = if active > 0 && !filters_shown { trf("Filters ({n})", &[("n", &active)]) } else { tr("Filters").to_string() @@ -806,22 +912,31 @@ impl LargeView { }; // Right to left: the board segment first. ui.spacing_mut().item_spacing.x = 0.0; - for (pane, label, hint) in [ + for (pane, label, hint, on) in [ ( Pane::Board, board, tr("Find games by position: play moves on the board (Ctrl+B)"), + self.pane == Pane::Board, ), ( Pane::Filters, filters, tr("Filters: players, tournament, years, rating… (Ctrl+F twice)"), + filters_shown, ), ] { - let on = self.pane == pane; let hint = if on { tr("Hide the panel") } else { hint }; if ui.selectable_label(on, label).on_hover_text(hint).clicked() { - self.pane = if on { Pane::Hidden } else { pane }; + match (pane, on) { + (Pane::Filters, false) => self.open_filters(), + (Pane::Filters, true) if self.narrow_filters => self.drawer_open = false, + (_, true) => self.pane = Pane::Hidden, + (_, false) => { + self.pane = pane; + self.drawer_open = false; + } + } } } } @@ -1062,8 +1177,10 @@ impl LargeView { if let Some(c) = clear { self.clear(c); } - if let Some(p) = goto { - self.pane = p; + match goto { + Some(Pane::Filters) => self.open_filters(), + Some(p) => self.pane = p, + None => {} } } @@ -1474,94 +1591,170 @@ impl LargeView { let progress = self.slow_progress(now, db.len()); let total = db.games() + db.texts(); - // The pane switch comes first (right): it stays visible in a narrow window, - // then the quick search; the rest of the line is shortened. + // The header (docs/design/narrow-windows.md §2.4), by importance: the pane switch, + // the quick search (220, down to 140), the counter, "⟳ New games", the import + // notes, the database's name (shortened, at least 80, else left out: it is on + // the shelf too), its format. Measured from the texts; what does not fit on one + // line goes to a second. + let name = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let format = format!("· {}", header.format); + let counter = match &self.shown { + Some(s) + if (s.use_position && self.blocked.is_none()) + || s.filter != Filter::default() + || self.form.active() > 0 => + { + trf( + "· found {n} of {total}", + &[("n", &grouped(self.view.len())), ("total", &grouped(total))], + ) + } + _ if db.texts() > 0 => format!( + "· {} · {}", + crate::i18n::games(db.games()), + crate::i18n::texts(db.texts()) + ), + _ => format!("· {}", crate::i18n::games(db.games())), + }; + // The board alone in a narrow window: the counter leads back to the list. + let counter = if self.board_alone() { + format!("{} ›", counter.trim_start_matches("· ")) + } else { + counter + }; + let gap = ui.spacing().item_spacing.x; + let pad = 2.0 * ui.spacing().button_padding.x; + let body = |t: &str| text_w(ui, t, egui::TextStyle::Body); + let switch_w = { + let active = self.form.active(); + body(&trf("Filters ({n})", &[("n", &active)])) + + body(&format!("{} •", tr("Board"))) + + 2.0 * pad + }; + let search_w = |field: f32| 20.0 + gap + field + 8.0 + 8.0 + gap; + let info_w = body(&counter) + + gap + + progress.map_or(0.0, |_| 14.0 + gap + body("100 %") + gap) + + if notes > 0 { + body(&format!("ℹ {notes}")) + pad + gap + } else { + 0.0 + } + + header.online.as_ref().map_or(0.0, |o| { + if o.busy { + 14.0 + gap + body(tr("updating…")) + gap + } else { + text_w(ui, tr("⟳ New games"), egui::TextStyle::Small) + pad + gap + } + }); + 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); + // One line: the widest field that leaves the counter and at least 80 of the name. + let one_line = [(220.0, true), (220.0, false), (140.0, false)] + .into_iter() + .find(|(field, with_format)| { + let rest = + avail - right(*field) - info_w - if *with_format { format_w } else { 0.0 }; + if *with_format { + rest >= name_w + } else { + rest >= 80.0 + gap + } + }); + let field = match one_line { + Some((field, _)) => field, + None if avail - right(220.0) >= 80.0 + gap => 220.0, + None => 140.0, + }; + let with_format = one_line.is_some_and(|(_, f)| f); + let mut back_to_list = false; + let alone = self.board_alone(); + let mut info = |ui: &mut Ui| { + let mut text = RichText::new(&counter); + if progress.is_some() { + text = text.weak(); + } + if alone { + if ui + .link(text) + .on_hover_text(tr("Show the list of games (Esc)")) + .clicked() + { + back_to_list = true; + } + } else { + ui.label(text); + } + if let Some(p) = progress { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak()); + } + if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { + open_notes = true; + } + // A database from Lichess and Chess.com: its new games. + if let Some(online) = &header.online { + if online.busy { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(tr("updating…")).weak()); + } else if ui + .add_enabled(online.enabled, egui::Button::new(tr("⟳ New games")).small()) + .on_hover_text(&online.hint) + .on_disabled_hover_text(&online.hint) + .clicked() + { + actions.push(LibraryAction::UpdateOnline(path.to_path_buf())); + } + } + }; + 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 { + ui.allocate_ui( + vec2((name_room - gap).floor(), ui.spacing().interact_size.y), + |ui| { + ui.add(egui::Label::new(RichText::new(&name).strong()).truncate()) + .on_hover_text(&name); + }, + ); + } + if with_format { + ui.label(RichText::new(&format).weak()) + .on_hover_text(&header.format_hint); + } + if one_line.is_some() { + info(ui); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // The switch packs its segments; the rest keeps the usual spacing. ui.scope(|ui| self.pane_switch(ui)); ui.add_space(8.0); - self.search_field(ui, now); - ui.add_space(8.0); - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - // The name gives way first: the counter is the result, and the name - // is on the shelf card too (§9.2). - let room = (ui.available_width() - 300.0).max(80.0); - ui.scope(|ui| { - ui.set_max_width(room); - ui.add( - egui::Label::new( - RichText::new( - path.file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(), - ) - .strong(), - ) - .truncate(), - ); - }); - if ui.available_width() > 520.0 { - ui.label(RichText::new(format!("· {}", header.format)).weak()) - .on_hover_text(&header.format_hint); - } - let counter = match &self.shown { - Some(s) - if (s.use_position && self.blocked.is_none()) - || s.filter != Filter::default() - || self.form.active() > 0 => - { - trf( - "· found {n} of {total}", - &[("n", &grouped(self.view.len())), ("total", &grouped(total))], - ) - } - _ if db.texts() > 0 => format!( - "· {} · {}", - crate::i18n::games(db.games()), - crate::i18n::texts(db.texts()) - ), - _ => format!("· {}", crate::i18n::games(db.games())), - }; - let mut counter = RichText::new(counter); - if progress.is_some() { - counter = counter.weak(); - } - ui.add(egui::Label::new(counter).truncate()); - if let Some(p) = progress { - ui.add(egui::Spinner::new().size(14.0)); - ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak()); - } - if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { - open_notes = true; - } - // A database from Lichess and Chess.com: its new games. - if let Some(online) = &header.online { - if online.busy { - ui.add(egui::Spinner::new().size(14.0)); - ui.label(RichText::new(tr("updating…")).weak()); - } else if ui - .add_enabled( - online.enabled, - egui::Button::new(tr("⟳ New games")).small(), - ) - .on_hover_text(&online.hint) - .on_disabled_hover_text(&online.hint) - .clicked() - { - actions.push(LibraryAction::UpdateOnline(path.to_path_buf())); - } - } - }); + self.search_field(ui, now, field); }); }); + if one_line.is_none() { + ui.horizontal_wrapped(|ui| info(ui)); + } + if back_to_list { + self.pane = Pane::Hidden; + } self.chips(ui, settings); ui.add_space(2.0); + self.drawer_top = ui.cursor().top(); // Ctrl+F: the quick search; once more, the filters' first field (§9.10). if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)) { if self.search_focused { - self.pane = Pane::Filters; + self.open_filters(); self.focus_player = true; } else { self.focus_search = true; @@ -1583,6 +1776,12 @@ impl LargeView { self.only_order = false; } + // A narrow window: the board takes the place of the table (§2.3). + if self.board_alone() { + self.board_panel(ui, db, settings, actions); + return open_notes; + } + // A position that could not be searched (no memory) does not filter the list. let use_position = self.shown.as_ref().is_some_and(|s| s.use_position) && self.blocked.is_none(); @@ -1677,29 +1876,23 @@ impl LargeView { let year_only = width < 1000.0; let mut columns: Vec<(&str, Option, Column)> = Vec::new(); if use_position { - columns.push((tr("Move"), None, Column::exact(52.0))); + columns.push((tr("Move"), None, Column::exact(MOVE_COL))); } if show_number { - // As wide as the largest number (a check mark before it). - let digits = grouped(db.len()).chars().count() as f32; - columns.push(( - "№", - Some(SortKey::Number), - Column::exact((digits * 8.0 + 24.0).clamp(52.0, 84.0)), - )); + columns.push(("№", Some(SortKey::Number), Column::exact(number_col(db)))); } // Without the event the names share the rest of the width. let name = if show_event { - Column::initial(170.0).at_least(60.0).clip(true) + Column::initial(170.0).at_least(NAME_MIN).clip(true) } else { - Column::remainder().at_least(60.0).clip(true) + Column::remainder().at_least(NAME_MIN).clip(true) }; columns.extend([ (tr("White"), Some(SortKey::White), name), - ("Elo", Some(SortKey::WhiteElo), Column::exact(44.0)), + ("Elo", Some(SortKey::WhiteElo), Column::exact(ELO_COL)), (tr("Black"), Some(SortKey::Black), name), - ("Elo", Some(SortKey::BlackElo), Column::exact(44.0)), - (tr("Res."), Some(SortKey::Result), Column::exact(56.0)), + ("Elo", Some(SortKey::BlackElo), Column::exact(ELO_COL)), + (tr("Res."), Some(SortKey::Result), Column::exact(RESULT_COL)), ]); if show_moves { columns.push((tr("Length"), Some(SortKey::Moves), Column::exact(56.0))); @@ -1721,7 +1914,7 @@ impl LargeView { columns.push((tr("Round"), None, Column::exact(48.0))); } if year_only { - columns.push((tr("Year"), Some(SortKey::Date), Column::exact(48.0))); + columns.push((tr("Year"), Some(SortKey::Date), Column::exact(YEAR_COL))); } else { columns.push((tr("Date"), Some(SortKey::Date), Column::exact(88.0))); } diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 3559c1d..f690a65 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -56,6 +56,37 @@ struct ImportInfo { notes: Vec, } +fn text_w(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { + ui.painter() + .layout_no_wrap( + text.to_owned(), + style.resolve(ui.style()), + egui::Color32::WHITE, + ) + .size() + .x +} + +fn button_w(ui: &Ui, text: &str) -> f32 { + text_w(ui, text, egui::TextStyle::Button) + + 2.0 * ui.spacing().button_padding.x + + ui.spacing().item_spacing.x +} + +/// 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 { + ["⚙", "📋", "♟"] + } else { + [tr("⚙ Settings"), tr("📋 Paste PGN"), tr("♟ New game")] + }; + texts.iter().map(|t| button_w(ui, t)).sum::() + update.map_or(0.0, |v| button_w(ui, v)) +} + +/// The least widths of the panels beside the table (narrow-windows.md §1). +const FILTERS_MIN: f32 = 260.0; +const SEARCH_BOARD_MIN: f32 = 340.0; + pub struct Library { slots: HashMap, /// Games the user has opened (by content). @@ -307,47 +338,118 @@ impl Library { ) -> Vec { self.poll(); let mut actions = Vec::new(); - // With the search board open in a low window the shelf folds into one line, - // leaving the height to the board. + // A field had the keyboard when this frame began: its Escape is its own. + let typing = ui.ctx().egui_wants_keyboard_input(); + let width = ui.available_width(); + let height = ui.ctx().content_rect().height(); + // The shelf folds into one line when its cards would take more than two rows, in + // a low window, and with the search board open in a window under 760. let board_open = self .selected_db .as_ref() .is_some_and(|p| self.large.get(p).is_some_and(|v| v.pane() == Pane::Board)); - let low = ui.ctx().content_rect().height() < 760.0; - if board_open && low { + let cards = databases.len() + 1 + usize::from(self.online); + let card_rows = { + let mut rows = 1; + let mut x = 0.0; + for k in 0..cards { + let w = if k < databases.len() { 190.0 } else { 150.0 }; + if x > 0.0 && x + w > width - 16.0 { + rows += 1; + x = 0.0; + } + x += w + 8.0; + } + rows + }; + if card_rows > 2 || height < 600.0 || (board_open && height < 760.0) { egui::Panel::top("shelf_compact") .show(ui, |ui| self.compact_shelf(ui, databases, &mut actions)); } else { egui::Panel::top("shelf").show(ui, |ui| self.shelf(ui, databases, &mut actions)); } - // A database has its filter panel or its search board on the right. + // A database has its filter panel or its search board on the right, when the + // window leaves the table its least width beside them (narrow-windows.md §2.1); + // otherwise the filters open over the table and the board takes its place. + let mut drawer = None; if let Some(path) = self.selected_db.clone() && let Some(Slot::Ready(db)) = self.slots.get(&path) && let Some(view) = self.large.get_mut(&path) { let db = db.clone(); + let table_min = view.table_min_width(&db, false); + let table_min_pos = view.table_min_width(&db, true); + view.set_layout( + width < table_min + FILTERS_MIN, + width < table_min_pos + SEARCH_BOARD_MIN, + ); match view.pane() { - Pane::Filters => { + Pane::Filters if view.drawer().is_none() && width >= table_min + FILTERS_MIN => { let r = egui::Panel::right("filters") .resizable(true) .default_size(280.0) - .size_range(260.0..=380.0) + .size_range(FILTERS_MIN..=(width - table_min).floor().min(380.0)) .show(ui, |ui| view.panel(ui, &db)); crate::widgets::check_panel("filters", &r.response); } - Pane::Board => { - let width = ui.available_width(); + Pane::Board if !view.board_alone() => { + let most = (width - table_min_pos).floor().max(SEARCH_BOARD_MIN); let r = egui::Panel::right("search_board") .resizable(true) - .default_size((width * 0.5).max(340.0)) - .size_range(340.0..=(width - 420.0).max(340.0)) + .default_size((width * 0.5).clamp(SEARCH_BOARD_MIN, most)) + .size_range(SEARCH_BOARD_MIN..=most) .show(ui, |ui| view.board_panel(ui, &db, settings, &mut actions)); crate::widgets::check_panel("search_board", &r.response); } - Pane::Hidden => {} + _ => {} } + drawer = view.drawer().map(|top| (path, db, top)); } egui::CentralPanel::default().show(ui, |ui| self.table_area(ui, settings, &mut actions)); + // The filters over the table: on its right edge under its header, with a shadow; + // the table stays live. A click elsewhere closes them (and does what it does). + if let Some((path, db, top)) = drawer + && let Some(view) = self.large.get_mut(&path) + { + let screen = ui.ctx().content_rect(); + // As wide as the filters beside the table were left (a strip of the + // table stays visible to click). + let stored = + egui::containers::panel::PanelState::load(ui.ctx(), egui::Id::new("filters")) + .map_or(280.0, |p| p.size().x); + let size = vec2( + stored.clamp(FILTERS_MIN, 380.0).min(width - 48.0), + screen.bottom() - top, + ); + let rect = egui::Rect::from_min_size(egui::pos2(screen.right() - size.x, top), size); + let area = egui::Area::new(egui::Id::new("filters_drawer")) + .order(egui::Order::Middle) + .fixed_pos(rect.min) + .show(ui.ctx(), |ui| { + let frame = egui::Frame::side_top_panel(ui.style()) + .stroke(ui.visuals().window_stroke) + .shadow(ui.visuals().window_shadow); + frame.show(ui, |ui| { + let inner = rect.shrink2(frame.total_margin().sum() / 2.0); + ui.set_min_size(inner.size()); + ui.set_max_size(inner.size()); + view.panel(ui, &db); + }); + }); + if area.response.clicked_elsewhere() && !ui.ctx().is_being_dragged(area.response.id) { + view.close_drawer(); + } + } + // Escape: the filters over the table close, then the board alone gives the place + // back to the table (a field takes its own Escape first). + if !typing + && let Some(path) = self.selected_db.clone() + && let Some(view) = self.large.get_mut(&path) + && ui.input(|i| i.key_pressed(egui::Key::Escape)) + && view.escape() + { + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); + } self.notes_window(ui.ctx()); actions } @@ -395,12 +497,28 @@ impl Library { .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_default() }; + // 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 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) + .clamp(140.0, 260.0) + .floor(); ui.horizontal(|ui| { let current = self.selected_db.as_deref().map(name).unwrap_or_default(); let mut pick = None; egui::ComboBox::from_id_salt("shelf_db") .selected_text(format!("🗄 {current}")) - .width(260.0) + .width(list) + .truncate() .show_ui(ui, |ui| { for p in databases { if ui @@ -432,51 +550,68 @@ impl Library { actions.push(LibraryAction::OnlineGames); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("⚙ Settings")).clicked() { - actions.push(LibraryAction::OpenSettings); - } - if let Some(v) = &self.update - && crate::widgets::update_button(ui, v).clicked() - { - actions.push(LibraryAction::OpenUpdate); - } - if ui.button(tr("📋 Paste PGN")).clicked() { - actions.push(LibraryAction::PastePgn); - } - if ui.button(tr("♟ New game")).clicked() { - actions.push(LibraryAction::NewGame); - } + self.shelf_buttons(ui, icons, actions); }); }); } + /// "♟ New game · 📋 Paste PGN · ⚙ Settings" (right to left), or their icons with + /// the names in the tooltips. + fn shelf_buttons(&self, ui: &mut Ui, icons: bool, actions: &mut Vec) { + let label = |full: &'static str, icon: &'static str| if icons { icon } else { full }; + let hint = |full: &str, hint: &str| { + if icons { + format!( + "{}\n{hint}", + full.trim_start_matches(|c: char| !c.is_alphabetic()) + ) + } else { + hint.to_owned() + } + }; + if ui + .button(label(tr("⚙ Settings"), "⚙")) + .on_hover_text(hint(tr("⚙ Settings"), "Ctrl+,")) + .clicked() + { + actions.push(LibraryAction::OpenSettings); + } + if let Some(v) = &self.update + && crate::widgets::update_button(ui, v).clicked() + { + actions.push(LibraryAction::OpenUpdate); + } + if ui + .button(label(tr("📋 Paste PGN"), "📋")) + .on_hover_text(hint( + tr("📋 Paste PGN"), + tr("Open a game from the clipboard"), + )) + .clicked() + { + actions.push(LibraryAction::PastePgn); + } + if ui + .button(label(tr("♟ New game"), "♟")) + .on_hover_text(hint( + tr("♟ New game"), + tr("Empty board in the starting position (Ctrl+N)"), + )) + .clicked() + { + actions.push(LibraryAction::NewGame); + } + } + fn shelf(&mut self, ui: &mut Ui, databases: &[PathBuf], actions: &mut Vec) { ui.add_space(8.0); + 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); ui.horizontal(|ui| { ui.heading(tr("Databases")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("⚙ Settings")).clicked() { - actions.push(LibraryAction::OpenSettings); - } - if let Some(v) = &self.update - && crate::widgets::update_button(ui, v).clicked() - { - actions.push(LibraryAction::OpenUpdate); - } - if ui - .button(tr("📋 Paste PGN")) - .on_hover_text(tr("Open a game from the clipboard")) - .clicked() - { - actions.push(LibraryAction::PastePgn); - } - if ui - .button(tr("♟ New game")) - .on_hover_text(tr("Empty board in the starting position (Ctrl+N)")) - .clicked() - { - actions.push(LibraryAction::NewGame); - } + self.shelf_buttons(ui, icons, actions); }); }); ui.add_space(4.0); diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 45a13fd..af33404 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -50,7 +50,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_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` — база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды), `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_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 Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды), `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). ## Языки