Windows: graphics fallbacks, a visible start error, the C runtime inside the exe
A Windows 10 user saw the program quit silently after SmartScreen: a Windows program has no console, so a failed graphics start left no trace. A start that fails or dies before its first frame now tries again without Vulkan, with OpenGL, then with software drawing (WARP), and keeps the mode that worked; what no mode overcomes, and any panic, goes to a message box and chesspenguin.log. The C runtime is linked statically (no VCRUNTIME140.dll needed); CI checks that and starts the window on the GPU-less Windows runner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5f7e0f5178
commit
16b7572d57
8 changed files with 294 additions and 4 deletions
|
|
@ -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 {
|
||||
|
|
|
|||
218
apps/desktop/src/graphics.rs
Normal file
218
apps/desktop/src/graphics.rs
Normal file
|
|
@ -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<Mode> = OnceLock::new();
|
||||
static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
fn state_file() -> Option<PathBuf> {
|
||||
crate::settings::Settings::config_dir().map(|d| d.join("graphics"))
|
||||
}
|
||||
|
||||
pub fn log_file() -> Option<PathBuf> {
|
||||
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<usize> = 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<String> = 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());
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue