diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..52be801 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,4 @@ +# Windows: the C runtime is linked into the executable, so it starts on a Windows +# without the Visual C++ Redistributable (VCRUNTIME140.dll). +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c8370cb..8eb4e08 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,9 +29,37 @@ jobs: - uses: actions/checkout@v7 - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - - run: cargo build --locked -p chesspenguin + - run: cargo build --release --locked -p chesspenguin # Self-update: replacing the running executable (the Windows rename scheme). - - run: "cargo test --locked -p chesspenguin update::" + - run: "cargo test --release --locked -p chesspenguin update::" + # The C runtime is inside the executable (.cargo/config.toml): no VCRUNTIME140.dll. + - name: No Visual C++ runtime needed + shell: pwsh + run: | + $bytes = [IO.File]::ReadAllBytes("target/release/chesspenguin.exe") + $text = [Text.Encoding]::ASCII.GetString($bytes) + if ($text -match "(?i)vcruntime140\.dll") { throw "chesspenguin.exe imports VCRUNTIME140.dll" } + # The window starts on a machine without a graphics card (the runner): the log says + # which graphics mode it took. Informational for now. + - name: Start the window + shell: pwsh + continue-on-error: true + run: | + $env:CP_SCREENSHOT = "$PWD/start.png" + $env:CP_SCREENSHOT_DELAY = "5" + $p = Start-Process target/release/chesspenguin.exe -PassThru + $p | Wait-Process -Timeout 90 -ErrorAction SilentlyContinue + Get-Process chesspenguin -ErrorAction SilentlyContinue | Stop-Process -Force + $log = "$env:APPDATA/vrubelroman/ChessPenguin/config/chesspenguin.log" + if (Test-Path $log) { Get-Content $log } + Get-Content "$env:APPDATA/vrubelroman/ChessPenguin/config/graphics" -ErrorAction SilentlyContinue + if (-not (Test-Path start.png)) { throw "no screenshot: the window did not start" } + - uses: actions/upload-artifact@v7 + if: always() + with: + name: windows-start + path: start.png + if-no-files-found: ignore # Apple Silicon: the build and the app bundle (decision 15). macos-build: diff --git a/CHANGELOG.md b/CHANGELOG.md index 03579e1..b081dcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Windows: ChessPenguin no longer quits silently on a machine whose graphics do not + cooperate (an old driver, a broken Vulkan, a virtual machine). A start that fails or dies + before its first frame tries again without Vulkan, then with OpenGL, then with software + drawing, and keeps the mode that worked. What still prevents the start is shown in a + message and written to chesspenguin.log beside the settings. The C runtime is now inside + the executable, so the Visual C++ Redistributable is not needed. - The window "Games from Lichess and Chess.com" opens with an empty nickname, the cursor in it: the next search is usually for another player (a database already downloaded fetches its new games with "⟳ New games"). diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 0ce4882..c94626c 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -726,6 +726,10 @@ impl App { impl eframe::App for App { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + // The window has shown its first frame: this graphics mode works. + if ui.ctx().cumulative_frame_nr() >= 1 { + crate::graphics::started(); + } let ctx = ui.ctx().clone(); if self.applied_dark != Some(self.settings.dark_mode) { ctx.set_visuals(if self.settings.dark_mode { diff --git a/apps/desktop/src/graphics.rs b/apps/desktop/src/graphics.rs new file mode 100644 index 0000000..a3b277d --- /dev/null +++ b/apps/desktop/src/graphics.rs @@ -0,0 +1,218 @@ +//! Starting the window on machines whose graphics do not cooperate (an old driver, a +//! broken Vulkan, a virtual machine, remote desktop). A start that fails or dies before +//! the first frames tries the next, more modest mode; the mode that worked is kept. +//! A failure no mode overcomes, and any panic, is shown in a message box and written to +//! `chesspenguin.log` beside the settings: a Windows program has no console to print to. + +use std::io::Write as _; +use std::path::PathBuf; +use std::sync::OnceLock; + +use eframe::egui_wgpu::{WgpuConfiguration, WgpuSetup, WgpuSetupCreateNew}; +use eframe::wgpu; + +/// The ways to draw, from the usual one to software rendering. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// wgpu's own choice: Vulkan, DirectX 12 or Metal, then OpenGL. + Default, + /// Without Vulkan (a broken Vulkan driver can kill the process on Windows). + NoVulkan, + /// OpenGL only. + OpenGl, + /// The processor draws (WARP on Windows, llvmpipe on Linux): slow but works. + Software, +} + +const MODES: [Mode; 4] = [Mode::Default, Mode::NoVulkan, Mode::OpenGl, Mode::Software]; + +static CURRENT: OnceLock = OnceLock::new(); +static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn state_file() -> Option { + crate::settings::Settings::config_dir().map(|d| d.join("graphics")) +} + +pub fn log_file() -> Option { + crate::settings::Settings::config_dir().map(|d| d.join("chesspenguin.log")) +} + +/// The state file: "trying N" while a start in mode N is not yet known to work, +/// "ok N" once it drew its first frames. +fn read_state() -> Option<(bool, usize)> { + let text = std::fs::read_to_string(state_file()?).ok()?; + let (word, n) = text.trim().split_once(' ')?; + let n: usize = n.parse().ok()?; + (n < MODES.len()).then_some((word == "ok", n)) +} + +fn write_state(ok: bool, n: usize) { + if let Some(f) = state_file() { + if let Some(d) = f.parent() { + let _ = std::fs::create_dir_all(d); + } + let _ = std::fs::write(f, format!("{} {n}", if ok { "ok" } else { "trying" })); + } +} + +/// Set for a process started again after a failed start: the modes tried so far. +const TRIED: &str = "CP_GRAPHICS_TRIED"; + +/// The mode for this start: the one that worked last time, the next one after a start +/// that died before its first frame, or the one a failed start chose for this process. +/// `WGPU_BACKEND` set by hand wins. +pub fn choose() -> Mode { + if std::env::var_os("WGPU_BACKEND").is_some() { + return *CURRENT.get_or_init(|| Mode::Default); + } + let retrying = std::env::var_os(TRIED).is_some(); + let n = match read_state() { + Some((ok, n)) if ok || retrying => n, + Some((_, n)) => { + let next = (n + 1) % MODES.len(); + log(&format!( + "the last start in mode {:?} did not finish, trying {:?}", + MODES[n], MODES[next] + )); + next + } + None => 0, + }; + write_state(false, n); + *CURRENT.get_or_init(|| MODES[n]) +} + +/// The first frame is shown: keep this mode for the next starts. +pub fn started() { + if STARTED.swap(true, std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Some(&mode) = CURRENT.get() + && std::env::var_os("WGPU_BACKEND").is_none() + && let Some(n) = MODES.iter().position(|m| *m == mode) + && read_state() != Some((true, n)) + { + write_state(true, n); + if mode != Mode::Default { + log(&format!("started in mode {mode:?}")); + } + } +} + +/// The start in this mode failed with an error: start again in a mode not tried yet +/// (a new process: the window system allows one event loop per process). False when +/// every mode has failed. +pub fn retry(error: &str) -> bool { + let mode = CURRENT.get().copied().unwrap_or(Mode::Default); + log(&format!("the start in mode {mode:?} failed: {error}")); + let n = MODES.iter().position(|m| *m == mode).unwrap_or(0); + let mut tried: Vec = std::env::var(TRIED) + .unwrap_or_default() + .split(',') + .filter_map(|t| t.parse().ok()) + .collect(); + tried.push(n); + let next = (1..MODES.len()) + .map(|k| (n + k) % MODES.len()) + .find(|m| !tried.contains(m)); + let exe = std::env::current_exe(); + let (Some(next), Ok(exe), None) = (next, exe, std::env::var_os("WGPU_BACKEND")) else { + if let Some(f) = state_file() { + let _ = std::fs::remove_file(f); + } + return false; + }; + write_state(false, next); + let tried: Vec = tried.iter().map(|t| t.to_string()).collect(); + std::process::Command::new(exe) + .args(std::env::args_os().skip(1)) + .env(TRIED, tried.join(",")) + .spawn() + .is_ok() +} + +pub fn options(mode: Mode) -> WgpuConfiguration { + let mut setup = WgpuSetupCreateNew::without_display_handle(); + let backends = &mut setup.instance_descriptor.backends; + match mode { + Mode::Default => return WgpuConfiguration::default(), + Mode::NoVulkan => { + *backends = (wgpu::Backends::PRIMARY | wgpu::Backends::GL) - wgpu::Backends::VULKAN + } + Mode::OpenGl => *backends = wgpu::Backends::GL, + Mode::Software => { + *backends = wgpu::Backends::all(); + setup.native_adapter_selector = Some(std::sync::Arc::new(|adapters, surface| { + adapters + .iter() + .filter(|a| a.get_info().device_type == wgpu::DeviceType::Cpu) + .find(|a| surface.is_none_or(|s| a.is_surface_supported(s))) + .cloned() + .ok_or_else(|| "no software renderer".to_owned()) + })); + } + } + WgpuConfiguration { + wgpu_setup: WgpuSetup::CreateNew(setup), + ..Default::default() + } +} + +/// Appends a line to the log (kept under a megabyte). +pub fn log(line: &str) { + let Some(f) = log_file() else { + return; + }; + if let Some(d) = f.parent() { + let _ = std::fs::create_dir_all(d); + } + if std::fs::metadata(&f).is_ok_and(|m| m.len() > 1 << 20) { + let _ = std::fs::remove_file(&f); + } + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&f) + { + let _ = writeln!( + file, + "[{now}] ChessPenguin {}: {line}", + env!("CARGO_PKG_VERSION") + ); + } +} + +/// A message box for what ended the program (there may be no window to show it in). +pub fn fatal(text: &str) { + let path = log_file() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Error) + .set_title("ChessPenguin") + .set_description(format!( + "{}\n\n{text}\n\n{}", + crate::i18n::tr("ChessPenguin could not start."), + crate::i18n::trf("Details are in {path}", &[("path", &path)]), + )) + .set_buttons(rfd::MessageButtons::Ok) + .show(); +} + +/// Panics go to the log; one on the main thread also to a message box. +pub fn install_panic_hook() { + let default = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let thread = std::thread::current(); + let name = thread.name().unwrap_or("?").to_owned(); + let backtrace = std::backtrace::Backtrace::force_capture(); + log(&format!("panic in thread {name}: {info}\n{backtrace}")); + default(info); + if name == "main" { + fatal(&info.to_string()); + } + })); +} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 5c9e218..003f2e3 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -341,6 +341,22 @@ const ROWS: &[[&str; 6]] = &[ "Detalles", "Dettagli", ], + [ + "ChessPenguin could not start.", + "ChessPenguin не удалось запустить.", + "ChessPenguin n’a pas pu démarrer.", + "ChessPenguin konnte nicht starten.", + "ChessPenguin no pudo iniciarse.", + "ChessPenguin non è riuscito ad avviarsi.", + ], + [ + "Details are in {path}", + "Подробности в файле {path}", + "Les détails sont dans {path}", + "Details stehen in {path}", + "Los detalles están en {path}", + "I dettagli sono in {path}", + ], [ "A stockfish package of your distribution is found by ChessPenguin too.", "Пакет stockfish вашего дистрибутива ChessPenguin тоже находит сам.", @@ -4344,6 +4360,7 @@ mod tests { include_str!("board.rs"), include_str!("engine_download.rs"), include_str!("main.rs"), + include_str!("graphics.rs"), ]; let mut missing = Vec::new(); let mut found = 0; diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 6c4169e..781776b 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -11,6 +11,7 @@ mod engine_offer; mod engines; mod examples; mod game_view; +mod graphics; mod i18n; mod large_db; mod library; @@ -49,6 +50,9 @@ fn main() -> eframe::Result { } return Ok(()); } + crate::i18n::set_lang(settings::Settings::load().language); + graphics::install_panic_hook(); + let mode = graphics::choose(); let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() .with_app_id("io.github.vrubelroman.chessPenguin") @@ -60,14 +64,22 @@ fn main() -> eframe::Result { eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png")) .unwrap_or_default(), ), + wgpu_options: graphics::options(mode), ..Default::default() }; - eframe::run_native( + let result = eframe::run_native( "ChessPenguin", options, Box::new(|cc| { assets::install(&cc.egui_ctx); Ok(Box::new(app::App::new(&cc.egui_ctx))) }), - ) + ); + if let Err(e) = &result { + if graphics::retry(&e.to_string()) { + return Ok(()); + } + graphics::fatal(&e.to_string()); + } + result } diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 8e64a7c..eb4d10d 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -13,6 +13,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `update_ui.rs` | Окно «Обновление ChessPenguin»: «Вышла версия X · У вас Y · Что нового», один сценарий на вид установки с главной кнопкой, «Не сейчас», «Пропустить эту версию» (`skipped_version`); скачивание с прогрессом (окно можно закрыть, кнопка у «Настроек» показывает проценты); итог: «Перезапустить сейчас / Позже», шаги для macOS с «Закрыть ChessPenguin», команда с «Копировать», «Открыть папку» и шагами для пакетов; ошибки понятными словами, исходный текст — в «Подробностях». Перезапуск: `request_close(QuitApp)`, в `finish_close` настройки сохраняются, новый процесс запускается без переменных `CP_*`; отмена вопроса о партиях отменяет и перезапуск | | `online.rs` | Онлайн-партии: проба обоих API при старте (повтор через 5 минут), поиск ника, загрузка в PGN-базу в `/online/` с файлом состояния `.online.json` (аккаунты базы, отметки Lichess `since`/незаконченные партии и Chess.com месяц/время, число партий, длина файла и его последние байты — хвост после аварии обрезается), одна загрузка на файл (`Claim`), имена `Ник (Lichess + Chess.com).pgn` или `A (Lichess) + B (Chess.com).pgn`. Живой тест `online_live` (ник — только через `CP_ONLINE_NICK`). | | `online_ui.rs` | Окно «Партии с Lichess и Chess.com»: ник игрока (любого: свой, ученика, соперника; другой ник для Chess.com), площадки, ответившие на пробу, «Найти» (Enter), найденное, «Объединить партии с обоих сайтов в одну базу» (по умолчанию), строка «В базу …» (`targets`: база, где эти аккаунты уже есть, иначе новая), «Скачать», прогресс по сайту (Lichess: из N, оставшееся время; Chess.com: месяц i из n), «Остановить», итоги с «Открыть базу» / «Попробовать снова» и «Подробностями»; при закрытом окне итог — тостом; `stop_all` при выходе. | +| `graphics.rs` | Запуск окна на «трудной» графике. Режимы: обычный (выбор wgpu), без Vulkan, только OpenGL, программная отрисовка (WARP / llvmpipe). Файл `graphics` в папке настроек: `trying N` до первого кадра, `ok N` после; запуск, умерший до первого кадра, берёт следующий режим, ошибка запуска перезапускает процесс в ещё не испробованном режиме (`CP_GRAPHICS_TRIED`), режим, который сработал, сохраняется. `WGPU_BACKEND` отключает перебор. Паника и ошибка, которую не обошёл ни один режим, — в окно сообщения и в `chesspenguin.log` рядом с настройками (у Windows-программы нет консоли) | | `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой | | `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура | | `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках |