DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #580 (update): portable mode needs a writable DesignCraftData
aiongg6d2163d497a2
diff --cc README.mdindex 63aafe090,43b20ff1f..33b917652--- a/README.md+++ b/README.md@@@ -152,67 -148,23 +152,69 @@@ The logger is `apps/designcraft/src/logA file named `portable.txt` next to the executable (on macOS, next to `DesignCraft.app`) makes the install portable: settings, logs andcrash recovery are kept in a `DesignCraftData` folder beside it instead of the per-user foldersabove. The Windows portable zip ships with one; delete it to go back to `%APPDATA%\DesignCraft`.+ If `DesignCraftData` cannot be written (a copy unzipped into Program Files), the per-user folders+ are used instead and the log and the status bar say so.`DESIGNCRAFT_CONFIG_DIR` still takes precedence. The code is `apps/designcraft/src/profile.rs`.-### Graphics backend--The canvas is rendered on the CPU; the GPU only composites the interface, through wgpu. A-graphics driver that faults takes the process down before any Rust code can catch it, so the-backend is chosen before the window exists, and a start that never showed a frame is remembered:-`gpu.json` in the settings directory records the backend being tried until the first frame has-been presented. A record left behind means that backend crashed (or the app was killed) at-start-up, so the next start tries the next one (DirectX 12, Vulkan, then OpenGL on Windows;-Vulkan, then OpenGL on Linux) and says so in the status bar. The list starts over once every-backend has failed, or with a new DesignCraft version; delete the file or set `WGPU_BACKEND` to-start afresh. Seen in the wild: on an AMD hybrid-graphics laptop (a Radeon RX 6800M beside an-integrated Radeon) the AMD Vulkan driver faulted at the first present, which is why DirectX 12 is-the Windows default. The code is `apps/designcraft/src/gpu.rs`.+### Graphics backend and processor++The canvas is rendered on the CPU; the GPU only composites the interface, through wgpu, so any+adapter that can show the window will do. The code is `apps/designcraft/src/gpu.rs` (the adapter)+and `apps/designcraft/src/gpu/backend.rs` (the backend).++- **Backend.** A graphics driver that faults takes the process down before any Rust code can+ catch it, so each start creates its wgpu instance with one backend, chosen before the window+ exists: on Windows DirectX 12, then OpenGL, then Vulkan, each on its own (creating an OpenGL+ instance crashed inside AMD's `atio6axx.dll`, #167, and creating a Vulkan instance loads every+ installed Vulkan driver, of which a faulty one can crash the app); on Linux Vulkan with OpenGL+ beside it, then OpenGL alone; on macOS Metal. Seen in the wild: on an AMD hybrid-graphics laptop+ (a Radeon RX 6800M beside an integrated Radeon) the AMD Vulkan driver faulted at the first+ present, which is why DirectX 12 is the Windows default.+- **A start that never showed a frame is remembered:** `gpu.json` in the settings directory+ records the backend being tried until the first frame has been presented. A record left behind+ means that backend crashed (or the app was killed) at start-up, so the next start tries the next+ backend and says so in the status bar. The list starts over once every backend has failed, or+ with a new DesignCraft version; delete the file or set `WGPU_BACKEND` to start afresh.+- **Adapter.** Among the adapters of those backends, the app picks the one that draws the window+ (eframe's `native_adapter_selector`): adapters that report they can't present to the window are+ never tried; then the one `WGPU_ADAPTER_NAME` names; hardware before software (llvmpipe, WARP);+ the native backends before OpenGL; the GPU that drives a display, and among those the one that+ drives the primary display; then the power preference; then a GPU's DirectX 12 adapter before its+ Vulkan one. A GPU without a monitor is the wrong one even when it can present: Windows has to+ copy every frame to the GPU that shows it, and an integrated GPU's driver reset under that,+ losing the graphics device or blanking every monitor for minutes. Windows says which GPU drives+ which display (`EnumDisplayDevices`), Linux through `/sys/class/drm` (a built-in `eDP`, `LVDS` or+ `DSI` panel counts as the primary display); on macOS, or when nothing matches, the power+ preference decides: power saving on Windows and macOS, the system's order elsewhere (Mesa puts+ the GPU the desktop runs on first, and a Wayland compositor may refuse frames from another GPU).+ `WGPU_POWER_PREF` replaces this with the user's choice of kind.+- **If the window fails on its adapter while starting up** (an error from wgpu, such as a lost+ device, or a panic inside wgpu, egui-wgpu or naga during the first frames), the app starts+ again without that adapter and tries the next one, telling which in the status bar; the run that+ failed keeps its log as `designcraft.1.log`. When no adapter of the start's backends is left, it+ starts again with the next backend. Software renderers (WARP, llvmpipe) come last: they are+ passed over while another backend is left to try, and allowed once no graphics processor could+ show the window. On Unix the new app replaces the process (an AppImage stays mounted); on+ Windows it starts beside it. Adapters are told apart by backend and PCI ids, or by name where the+ backend reports no ids (Metal lists every GPU of a dual-GPU Mac as `0000:0000`). What was left+ out travels in the restarted app's `--gpu-skip=` argument (`Vulkan:1002:164e`, `Metal:Intel+ Iris Pro Graphics`, or a whole backend such as `Dx12`), one more on each restart, so the+ restarts end. When nothing is left, the app logs why and exits with an error. Documents+ recovered after a crash stay in the recovery folder until they are saved or closed, so a restart+ never loses them.+- **If the window's first frame is late** (20 seconds after the app was created and the files+ named at the start opened), the log and the status bar say so. The adapter counts as hanging,+ and the app starts again without it, only when the UI thread has been stuck in the graphics+ stack, outside DesignCraft's own code, for 60 seconds while the window wasn't known to be+ minimized, covered or in the background. A large document composing on a slow machine never+ counts.+- **The log** lists the GPUs that drive a display (`display GPUs (PCI vendor:device): 10de:2204+ (primary)`), every adapter with whether it drives a display, the one drawn on and why (`drawing+ on NVIDIA GeForce RTX 3090 (Dx12, DiscreteGpu): it drives the primary display`), and the driver+ version. That is the first thing to look for in a report of a window that stays black or never+ opens.+- On Linux with Mesa, `MESA_VK_DEVICE_SELECT=10de:2f04!` (vendor:device as `vulkaninfo --summary`+ or `lspci -nn` show it) leaves only that GPU to Vulkan, and `DRI_PRIME=1` picks the other GPU.### Webdiff --cc apps/designcraft/src/main.rsindex 1c2163554,233ec74fa..def63f9b6--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@@ -321,14 -229,17 +321,20 @@@ fn main() -> std::process::ExitCode"--sample" => sample = true,"--version" => {println!("designcraft {}", env!("CARGO_PKG_VERSION"));- return Ok(());+ return std::process::ExitCode::SUCCESS;}- _ => files.push(a),+ _ => match gpu::skip_arg(&a) {+ Some(list) => skip = list,+ None => files.push(a),+ },}}+ // A portable.txt whose DesignCraftData folder cannot be written: the platform folders are used+ // instead (see `profile`), and the user is told, in the log and in the status bar.+ let portable_note = profile::unwritable_portable_dir().map(|dir| {+ log::warn!("portable mode is off: {} cannot be written; settings and recovery use the usual folders", dir.display());+ format!("Portable mode is off: {} cannot be written, so settings are kept in the usual place.", dir.display())+ });// The log file lives under the settings directory; opened after the arguments, so `--version`// leaves no file behind. Records logged until now are written to it first.if let (Some(logger), Some(dir)) = (logger, profile::config_dir()) {@@@ -395,99 -282,58 +401,103 @@@b.with_x11();}));}- eframe::run_native(- "DesignCraft",- options,- Box::new(move |cc| {- let mut gpu = gpu;- if let Some(rs) = &cc.wgpu_render_state {- // What a bug report needs to know about the graphics driver.- let info = rs.adapter.get_info();- log::info!("graphics: {} on {:?} ({:?}; driver {} {})", info.name, info.backend, info.device_type, info.driver, info.driver_info);- if let (Some(s), Some(backend)) = (gpu.as_mut(), gpu::Backend::of(info.backend)) {- s.started_with(backend);+ // Registered before the event loop starts, so it catches the Finder event that launched the app+ // as well as later ones. Lives until the event loop returns; the app creator only borrows it.+ #[cfg(target_os = "macos")]+ let apple_events = apple_events::AppleEvents::install();+ #[cfg(target_os = "macos")]+ let events = &apple_events;+ let created = startup.clone();+ // A panic that ends the window (egui-wgpu's own) is caught here: never a crash.+ let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ eframe::run_native(+ "DesignCraft",+ options,+ Box::new(move |cc| {+ let mut restarted = None;+ if let Some(rs) = &cc.wgpu_render_state {+ // What a bug report needs to know about the graphics driver.+ let info = rs.adapter.get_info();+ log::info!(+ "graphics: {} on {:?} ({:?}; driver {} {}; power preference {power:?})",+ info.name,+ info.backend,+ info.device_type,+ info.driver,+ info.driver_info+ );+ created.started_with(info.backend);+ created.created(&cc.egui_ctx);+ if !skip.is_empty() {+ // A processor chosen by `WGPU_POWER_PREF` can be the one that can't show the window.+ let hint = if chosen_gpu { " (without WGPU_POWER_PREF it uses the one that drives your display)" } else { "" };+ restarted = Some(format!(+ "The graphics processor tried first couldn't show the window, so DesignCraft started again on {} ({:?}, {:?}){hint}.",+ info.name.trim(),+ info.backend,+ info.device_type+ ));+ }}- }- let mut session = Session::new();- // Crash recovery: reopen what a previous run left unsaved, then keep it current.- session.recovery_dir = profile::recovery_dir();- let recovered = session.execute("file.recovery.open", &serde_json::json!({})).ok();- let mut app = DesignApp::new(session, services());- if let Some(line) = gpu.as_ref().and_then(gpu::Startup::status_line) {- app.status(line);- }- // Recovered documents matter more than the graphics note; both are in the log.- if let Some(n) = recovered.as_ref().and_then(|r| r["opened"].as_array()).map(Vec::len).filter(|n| *n > 0) {- app.status(format!("Recovered {n} unsaved document{} from the last session.", if n == 1 { "" } else { "s" }));- }- load_prefs(&mut app);- // After `load_prefs`, which replaces the UI state and with it the status line.- if let Some(note) = portable_note {- app.status(note);- }- app.integrated_titlebar = cfg!(target_os = "macos");- if let Some(port) = control_port {- let rx = control_server::start(port, cc.egui_ctx.clone());- app = app.with_control(rx);- }- if sample {- let _ = app.run("file.newSample", serde_json::json!({}));- }- for f in files {- if let Err(e) = app.open_file("file.open", serde_json::json!({"path": f})) {- eprintln!("designcraft: {f}: {e}");+ let mut session = Session::new();+ // Crash recovery: reopen what a previous run left unsaved, then keep it current.+ session.recovery_dir = profile::recovery_dir();+ let recovered = session.execute("file.recovery.open", &serde_json::json!({})).ok();+ let mut app = DesignApp::new(session, services());+ if let Some(line) = restarted.or_else(|| created.status_line()) {+ app.status(line);}- }- Ok(Box::new(App {- app,- #[cfg(target_os = "macos")]- menu: None,- startup: gpu,- frames: 0,- }))- }),- )+ // Recovered documents matter more than the graphics note; both are in the log.+ if let Some(n) = recovered.as_ref().and_then(|r| r["opened"].as_array()).map(Vec::len).filter(|n| *n > 0) {+ app.status(format!("Recovered {n} unsaved document{} from the last session.", if n == 1 { "" } else { "s" }));+ }+ load_prefs(&mut app);++ // After `load_prefs`, which replaces the UI state and with it the status line.++ if let Some(note) = portable_note {++ app.status(note);++ }+ app.integrated_titlebar = cfg!(target_os = "macos");+ if let Some(port) = control_port {+ let rx = control_server::start(port, cc.egui_ctx.clone());+ app = app.with_control(rx);+ }+ if sample {+ let _ = app.run("file.newSample", serde_json::json!({}));+ }+ for f in files {+ if let Err(e) = app.open_file("file.open", serde_json::json!({"path": f})) {+ log::warn!("{f}: {e}");+ }+ }+ // The first frame is due from now (`gpu::watch_first_frame`).+ created.ready();+ Ok(Box::new(App {+ app,+ #[cfg(target_os = "macos")]+ menu: None,+ startup: created,+ #[cfg(target_os = "macos")]+ apple_events: events.connect(&cc.egui_ctx),+ #[cfg(target_os = "macos")]+ movable: None,+ frames: 0,+ }))+ }),+ )+ }))+ .map_err(|payload| designcraft_engine::guard::panic_message(payload.as_ref()));+ // The window's end, or a graphics failure that starts the app again. A failure is logged:+ // standard error and the log file, since a Windows start has no console to show it.+ // Documents that arrived after the last frame, for a start again to open too.+ #[cfg(target_os = "macos")]+ startup.opening(apple_events.queued());+ match gpu::finish(run, &startup) {+ Ok(()) => std::process::ExitCode::SUCCESS,+ Err(e) => {+ log::error!("DesignCraft stopped: {e}");+ std::process::ExitCode::FAILURE+ }+ }}#[cfg(test)]