DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #580: feat(desktop): portable mode, portable.txt next to the executable (#574)
aiongg814153ba62b4
diff --cc README.mdindex 7bc8a29d9,09a933fc9..63aafe090--- a/README.md+++ b/README.md@@@ -147,65 -143,26 +147,72 @@@ The file stops growing at 16 MiB. `--veThe logger is `apps/designcraft/src/logging.rs`; the web build logs to the browser console instead.+ ### Portable mode++ A file named `portable.txt` next to the executable (on macOS, next to `DesignCraft.app`) makes the install portable: settings, logs and+ crash recovery are kept in a `DesignCraftData` folder beside it instead of the per-user folders+ above. The Windows portable zip ships with one; delete it to go back to `%APPDATA%\DesignCraft`.+ `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/profile.rsindex 4b9bd4921,4f3b47245..326b43813--- a/apps/designcraft/src/profile.rs+++ b/apps/designcraft/src/profile.rs@@@ -21,17 -26,34 +26,44 @@@ fn config_dir_with(os: &str, env: impl}}+ /// The folder that holds settings and recovery data instead of the user's profile:+ /// `DESIGNCRAFT_CONFIG_DIR` (empty: none at all), else a portable install's data folder.+ fn root_with(env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> Option<OsString> {+ env("DESIGNCRAFT_CONFIG_DIR").or_else(|| exe_dir.and_then(portable_dir).map(PathBuf::into_os_string))+ }++ /// `<dir>/DesignCraftData` when `dir` holds [`PORTABLE_MARKER`], where `dir` is the folder the+ /// user sees the app in: the executable's, or the one holding `DesignCraft.app` when the executable+ /// sits inside a macOS bundle (`DesignCraft.app/Contents/MacOS`, signed, never edited by hand).+ /// A folder named like the marker is no marker.+ fn portable_dir(exe_dir: &Path) -> Option<PathBuf> {+ let dir = app_bundle_parent(exe_dir).unwrap_or(exe_dir);+ dir.join(PORTABLE_MARKER).is_file().then(|| dir.join(PORTABLE_DATA_DIR))+ }++ /// The folder holding `X.app` when `exe_dir` is `X.app/Contents/MacOS`.+ fn app_bundle_parent(exe_dir: &Path) -> Option<&Path> {+ let contents = exe_dir.parent().filter(|_| exe_dir.file_name() == Some("MacOS".as_ref()))?;+ let bundle = contents.parent().filter(|_| contents.file_name() == Some("Contents".as_ref()))?;+ bundle.extension().filter(|ext| *ext == "app").and(bundle.parent())+ }++ fn executable_dir() -> Option<PathBuf> {+ std::env::current_exe().ok()?.parent().map(Path::to_path_buf)+ }+pub fn recovery_dir() -> Option<PathBuf> {- recovery_dir_with(std::env::var_os("DESIGNCRAFT_CONFIG_DIR"), designcraft_engine::recovery::default_dir).map(own_run)+ recovery_dir_with(root_with(|key| std::env::var_os(key), executable_dir().as_deref()), designcraft_engine::recovery::default_dir)++ .map(own_run)+}++/// This run's folder in the recovery folder `root`. A second running DesignCraft has its own, so+/// neither writes over the other's documents nor takes them for a crash's.+fn own_run(root: PathBuf) -> PathBuf {+ designcraft_engine::recovery::run_dir(&root).unwrap_or_else(|e| {+ log::warn!("recovery data is shared with other running apps: {e}");+ root+ })}fn recovery_dir_with(root: Option<OsString>, default: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {@@@ -69,25 -94,74 +104,87 @@@ mod testsassert_eq!(recovery_dir_with(Some(OsString::new()), || Some("/user/recovery".into())), None);}+ /// A folder standing in for the executable's; `marker` puts `portable.txt` in it, or not.+ fn install(name: &str, marker: impl FnOnce(&Path)) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("designcraft-profile-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ marker(&dir.join(PORTABLE_MARKER));+ dir+ }++ #[test]+ fn portable_marker_keeps_settings_and_recovery_next_to_the_executable() {+ let exe = install("portable", |marker| std::fs::write(marker, "").unwrap());+ for os in ["macos", "windows", "linux"] {+ assert_eq!(config_dir_with(os, environment, Some(&exe)), Some(exe.join("DesignCraftData")));+ }+ assert_eq!(+ recovery_dir_with(root_with(environment, Some(&exe)), || Some("/user/recovery".into())),+ Some(exe.join("DesignCraftData/Recovery"))+ );+ let _ = std::fs::remove_dir_all(&exe);+ }++ #[test]+ fn inside_a_macos_bundle_the_marker_sits_next_to_the_app() {+ let folder = install("bundle", |marker| std::fs::write(marker, "").unwrap());+ let exe = folder.join("DesignCraft.app/Contents/MacOS");+ std::fs::create_dir_all(&exe).unwrap();+ assert_eq!(config_dir_with("macos", environment, Some(&exe)), Some(folder.join("DesignCraftData")));+ // a marker dropped inside the bundle is not looked at+ std::fs::remove_file(folder.join(PORTABLE_MARKER)).unwrap();+ std::fs::write(exe.join(PORTABLE_MARKER), "").unwrap();+ assert_eq!(config_dir_with("macos", environment, Some(&exe)), Some("/user/Library/Application Support/DesignCraft".into()));+ let _ = std::fs::remove_dir_all(&folder);+ }++ #[test]+ fn without_a_marker_file_the_platform_paths_stay() {+ let plain = install("plain", |_| {});+ let folder = install("marker-folder", |marker| std::fs::create_dir(marker).unwrap());+ for exe in [&plain, &folder] {+ assert_eq!(config_dir_with("windows", environment, Some(exe)), Some("/roaming/DesignCraft".into()));+ assert_eq!(recovery_dir_with(root_with(environment, Some(exe)), || Some("/existing/recovery".into())), Some("/existing/recovery".into()));+ }+ let _ = std::fs::remove_dir_all(&plain);+ let _ = std::fs::remove_dir_all(&folder);+ }++ #[test]+ fn isolated_profile_wins_over_a_portable_install() {+ let exe = install("override", |marker| std::fs::write(marker, "").unwrap());+ let isolated = |key: &str| if key == "DESIGNCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) };+ assert_eq!(config_dir_with("windows", isolated, Some(&exe)), Some("/isolated".into()));+ assert_eq!(recovery_dir_with(root_with(isolated, Some(&exe)), || None), Some("/isolated/Recovery".into()));+ let empty = |key: &str| if key == "DESIGNCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { environment(key) };+ assert_eq!(config_dir_with("windows", empty, Some(&exe)), None);+ assert_eq!(recovery_dir_with(root_with(empty, Some(&exe)), || Some("/user/recovery".into())), None);+ let _ = std::fs::remove_dir_all(&exe);+ }+#[test]fn unset_override_preserves_existing_platform_paths() {- assert_eq!(config_dir_with("macos", environment), Some("/user/Library/Application Support/DesignCraft".into()));- assert_eq!(config_dir_with("windows", environment), Some("/roaming/DesignCraft".into()));- assert_eq!(config_dir_with("linux", environment), Some("/xdg-config/designcraft".into()));- assert_eq!(config_dir_with("linux", |key| if key == "HOME" { environment(key) } else { None }), Some("/user/.config/designcraft".into()));+ assert_eq!(config_dir_with("macos", environment, None), Some("/user/Library/Application Support/DesignCraft".into()));+ assert_eq!(config_dir_with("windows", environment, None), Some("/roaming/DesignCraft".into()));+ assert_eq!(config_dir_with("linux", environment, None), Some("/xdg-config/designcraft".into()));+ assert_eq!(+ config_dir_with("linux", |key| if key == "HOME" { environment(key) } else { None }, None),+ Some("/user/.config/designcraft".into())+ );assert_eq!(recovery_dir_with(None, || Some("/existing/recovery".into())), Some("/existing/recovery".into()));}++ #[test]+ fn a_run_has_its_own_recovery_folder_when_one_can_be_made() {+ let dir = std::env::temp_dir().join(format!("designcraft-profile-run-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let root = dir.join("Recovery");+ assert_eq!(own_run(root.clone()).parent(), Some(root.as_path()));+ // Nothing can be made under a file: the recovery folder itself, as before.+ let blocked = dir.join("blocked");+ std::fs::write(&blocked, "a file where the folder should be").unwrap();+ assert_eq!(own_run(blocked.join("Recovery")), blocked.join("Recovery"));+ let _ = std::fs::remove_dir_all(&dir);+ }}