From eb2fb2634ff46cad24f084a6b41394eddcd1d4ef Mon Sep 17 00:00:00 2001 From: Sean Lavery Date: Wed, 7 Oct 2026 03:11:06 -0700 Subject: [PATCH] Add rendering modes and CPU fallback recovery (#434) * Add rendering policy with legacy preference migration and safe adapter selection * Add rendering mode preferences and GPU fallback recovery warning * Complete CPU fallback recovery and validate rendering mode UI * Simplify GPU recovery and reuse preference persistence * Rendering modes: rebase onto the preferences merge/retry save path; drop docs screenshots save_preferences now writes through write_prefs (merging other instances' changes) and only marks the revision saved when the write succeeds, so a failed recovery choice is still retried. Removes a leftover diff3 marker in es.tsv, the docs/images/rendering-*.png screenshots and their ATTRIBUTION row (no binary assets in the repo), and regenerates docs/scorecard.md for the new performance.renderingMode preference. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- apps/photocraft/src/gpu_startup.rs | 69 +++++++++-- apps/photocraft/src/main.rs | 64 +++++++++- crates/engine/src/prefs.rs | 17 +++ crates/engine/src/prefs/tests.rs | 6 +- crates/engine/tests/rendering_preferences.rs | 37 ++++++ crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/gpu_canvas.rs | 12 +- crates/ui-egui/src/gpu_status.rs | 124 +++++++++++++++++-- crates/ui-egui/src/i18n/cs.tsv | 17 +++ crates/ui-egui/src/i18n/es.tsv | 16 +++ crates/ui-egui/src/i18n/ja.tsv | 17 +++ crates/ui-egui/src/i18n/ru.tsv | 17 +++ crates/ui-egui/src/i18n/zh-hant.tsv | 17 +++ crates/ui-egui/src/lib.rs | 19 ++- crates/ui-egui/src/prefs_ui.rs | 82 ++++++++++-- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/gpu_device_loss.rs | 9 +- docs/control-protocol.md | 12 +- docs/scorecard.md | 4 +- 19 files changed, 497 insertions(+), 47 deletions(-) create mode 100644 crates/engine/tests/rendering_preferences.rs diff --git a/apps/photocraft/src/gpu_startup.rs b/apps/photocraft/src/gpu_startup.rs index d84744deaa..0f55ad7d0e 100644 --- a/apps/photocraft/src/gpu_startup.rs +++ b/apps/photocraft/src/gpu_startup.rs @@ -24,7 +24,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, PoisonError}; use eframe::{egui_wgpu, wgpu}; -use photocraft_engine::prefs::GpuBackend; +use photocraft_engine::prefs::{GpuBackend, RenderingMode}; use serde_json::{Value, json}; /// The marker's file name in the config directory. @@ -154,6 +154,19 @@ pub fn plan(pref: GpuBackend, crashed: Option<&Marker>, env: Option<&str>, safe_ Plan { backend: pref, env: None, reason: None, remember: false } } +/// Resolve the rendering policy before the window exists. Explicit GPU/Automatic selections +/// reset a legacy CPU backend to automatic; CPU keeps software-preferred window presentation. +pub fn plan_with_mode(pref: GpuBackend, mode: RenderingMode, crashed: Option<&Marker>, env: Option<&str>, safe_gpu: bool, os: Os) -> Plan { + let backend = match mode { + RenderingMode::Cpu => GpuBackend::Cpu, + RenderingMode::Auto | RenderingMode::Gpu if pref == GpuBackend::Cpu => GpuBackend::Auto, + _ => pref, + }; + let env = if safe_gpu || mode == RenderingMode::Cpu { None } else { env }; + let crashed = if mode == RenderingMode::Cpu { None } else { crashed }; + plan(backend, crashed, env, safe_gpu, os) +} + /// Instance backends for `plan` (`None`: egui's default, which honours `WGPU_BACKEND`). pub fn backends(plan: &Plan, os: Os) -> Option { if plan.env.is_some() { @@ -211,8 +224,7 @@ fn rank(a: &Candidate, backend: GpuBackend, os: Os) -> (u8, u8) { /// The adapter to use among `adapters` (`None` when there is none). pub fn pick(adapters: &[Candidate], backend: GpuBackend, os: Os) -> Option { - let any_ok = adapters.iter().any(|a| a.surface_ok); - adapters.iter().enumerate().filter(|(_, a)| a.surface_ok || !any_ok).min_by_key(|(i, a)| (rank(a, backend, os), *i)).map(|(i, _)| i) + adapters.iter().enumerate().filter(|(_, a)| a.surface_ok).min_by_key(|(i, a)| (rank(a, backend, os), *i)).map(|(i, _)| i) } /// Whether picking `chosen` applied the Intel-on-Windows DX12 default (a Vulkan adapter of the @@ -250,6 +262,10 @@ pub fn configure(setup: &mut egui_wgpu::WgpuSetup, plan: &Plan, os: Os, sentinel }) .collect(); let i = pick(&cands, backend, os).ok_or_else(|| "no graphics adapter found".to_string())?; + if backend == GpuBackend::Cpu && cands.get(i).is_some_and(|c| c.device_type != wgpu::DeviceType::Cpu) { + *note.lock().unwrap_or_else(PoisonError::into_inner) = + Some("CPU image rendering; no software graphics adapter is available, so the window uses hardware graphics".into()); + } if backend == GpuBackend::Auto && intel_dx12_applied(&cands, i, os) { *note.lock().unwrap_or_else(PoisonError::into_inner) = Some("Intel graphics on Windows: using DirectX 12 (the Intel Vulkan driver is known to crash)".into()); @@ -357,14 +373,15 @@ impl Sentinel { } } -/// `performance.gpuBackend` and `performance.useGpu` from the preferences file, read before the -/// app (and its full preference load) exists. Unreadable values are the defaults. -pub fn read_prefs(path: Option<&Path>) -> (GpuBackend, bool) { +/// Read the policy leniently at startup, including old settings without renderingMode. +pub fn read_rendering_prefs(path: Option<&Path>) -> (GpuBackend, RenderingMode) { let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null); let perf = v.get("performance"); let backend = perf.and_then(|p| p.get("gpuBackend")).and_then(Value::as_str).and_then(GpuBackend::parse).unwrap_or_default(); let use_gpu = perf.and_then(|p| p.get("useGpu")).and_then(Value::as_bool).unwrap_or(true); - (backend, use_gpu) + let explicit = perf.and_then(|p| p.get("renderingMode")).and_then(Value::as_str).and_then(RenderingMode::parse); + let mode = explicit.unwrap_or(if !use_gpu || backend == GpuBackend::Cpu { RenderingMode::Cpu } else { RenderingMode::Auto }); + (backend, mode) } #[cfg(test)] @@ -376,6 +393,17 @@ mod tests { Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() } } + #[test] + fn cpu_policy_ignores_hardware_backend_override() { + let p = plan_with_mode(Vulkan, RenderingMode::Cpu, None, Some("vulkan"), false, Os::Windows); + assert_eq!(p.backend, Cpu); + assert!(p.env.is_none()); + assert_eq!(plan_with_mode(Vulkan, RenderingMode::Cpu, Some(&crashed("vulkan", "vulkan")), None, false, Os::Windows).backend, Cpu); + let p = plan_with_mode(Auto, RenderingMode::Gpu, None, Some("vulkan"), true, Os::Windows); + assert_eq!(p.backend, Cpu); + assert!(p.env.is_none()); + } + #[test] fn no_marker_uses_the_preference() { for os in [Os::Windows, Os::Mac, Os::Other] { @@ -474,6 +502,21 @@ mod tests { assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0)); } + #[test] + fn adapters_must_present_even_when_none_support_the_surface() { + let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12); + a.surface_ok = false; + assert_eq!(pick(&[a], Auto, Os::Windows), None); + assert_eq!(pick(&[a], Cpu, Os::Windows), None); + } + + #[test] + fn explicit_policy_overrides_legacy_cpu_backend() { + assert_eq!(plan_with_mode(Cpu, RenderingMode::Gpu, None, None, false, Os::Mac).backend, Auto); + assert_eq!(plan_with_mode(Metal, RenderingMode::Cpu, None, None, false, Os::Mac).backend, Cpu); + assert_eq!(plan_with_mode(Auto, RenderingMode::Gpu, None, None, true, Os::Mac).backend, Cpu); + } + #[test] fn marker_round_trip_and_lenient_parse() { let m = Marker { @@ -551,14 +594,16 @@ mod tests { let dir = temp_dir("prefs"); std::fs::create_dir_all(&dir).unwrap(); let p = dir.join("preferences.json"); - assert_eq!(read_prefs(None), (Auto, true)); - assert_eq!(read_prefs(Some(&p)), (Auto, true)); + assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto)); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap(); - assert_eq!(read_prefs(Some(&p)), (Dx12, false)); + assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu)); std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap(); - assert_eq!(read_prefs(Some(&p)), (Auto, true)); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); + std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu)); std::fs::write(&p, "{not json").unwrap(); - assert_eq!(read_prefs(Some(&p)), (Auto, true)); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 45a2d84f6d..fee8a6517b 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -146,13 +146,13 @@ fn main() -> eframe::Result { // driver moves to a safer one), and lock this start's marker until the first frames render. let t_sentinel = std::time::Instant::now(); let os = gpu_startup::Os::current(); - let (pref, _) = gpu_startup::read_prefs(services::prefs_file().as_deref()); + let (pref, mode) = gpu_startup::read_rendering_prefs(services::prefs_file().as_deref()); let (previous, sentinel) = match services::config_dir() { Some(dir) => gpu_startup::Sentinel::begin(&dir), None => (gpu_startup::Previous::Clean, None), }; let env_backend = std::env::var("WGPU_BACKEND").ok(); - let plan = gpu_startup::plan(pref, previous.crashed(), env_backend.as_deref(), safe_gpu, os); + let plan = gpu_startup::plan_with_mode(pref, mode, previous.crashed(), env_backend.as_deref(), safe_gpu, os); if let Some(m) = previous.crashed() { log::warn!("the previous start didn't finish (GPU backend {}, adapter {:?}); {}", m.backend, m.adapter, plan.reason.as_deref().unwrap_or("")); } @@ -172,11 +172,15 @@ fn main() -> eframe::Result { gpu_startup::configure(&mut options.wgpu_options.wgpu_setup, &plan, os, sentinel.clone(), gpu_note.clone()); let sentinel_ms = t_sentinel.elapsed().as_secs_f64() * 1000.0; log::info!("GPU startup: {:?} ({sentinel_ms:.2} ms)", plan); + let retry_cpu = !safe_gpu && plan.backend != photocraft_engine::prefs::GpuBackend::Cpu; + let app_created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let created_in_callback = app_created.clone(); let started_sentinel = sentinel.clone(); let result = eframe::run_native( - "Photocraft", + "PhotoCraft", options, Box::new(move |cc| { + created_in_callback.store(true, std::sync::atomic::Ordering::Relaxed); let automation = control.as_ref().map(|(_, _, workspace)| workspace.clone()); let mut services = services::native(automation); services.preset_store = presets; @@ -192,13 +196,21 @@ fn main() -> eframe::Result { let info = &mut app.perf.gpu_info; info.preference = pref.name().to_string(); info.selected = if plan.env.is_some() { "env".into() } else { plan.backend.name().to_string() }; - info.fallback = plan.reason.clone().or_else(|| gpu_note.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()); + info.fallback = match (plan.reason.clone(), gpu_note.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()) { + (Some(reason), Some(note)) => Some(format!("{reason}. {note}")), + (reason, note) => reason.or(note), + }; info.canvas = "cpu".into(); if let Some(rs) = cc.wgpu_render_state.clone() { app.perf.gpu_info.set_adapter(&rs.adapter.get_info()); - if plan.backend != photocraft_engine::prefs::GpuBackend::Cpu + let software_window = rs.adapter.get_info().device_type == eframe::wgpu::DeviceType::Cpu; + if software_window && mode != photocraft_engine::prefs::RenderingMode::Cpu { + app.perf.gpu_info.fallback = Some("No compatible hardware graphics adapter; using software graphics.".into()); + } + if !software_window + && plan.backend != photocraft_engine::prefs::GpuBackend::Cpu && std::env::var_os("PHOTOCRAFT_CPU_CANVAS").is_none() - && app.session.prefs().performance.use_gpu + && app.session.prefs().performance.effective_rendering_mode() != photocraft_engine::prefs::RenderingMode::Cpu { app.set_wgpu(rs); } else { @@ -206,13 +218,33 @@ fn main() -> eframe::Result { let _ = photocraft_ui_egui::gpu_canvas::DeviceHealth::watch(&rs.device); } } + let fallback_reason = std::env::var("PHOTOCRAFT_GPU_STARTUP_FAILURE").ok().or_else(|| { + (app.perf.gpu_info.canvas == "cpu" && mode != photocraft_engine::prefs::RenderingMode::Cpu) + .then(|| app.perf.gpu_info.fallback.clone()) + .flatten() + }); + if let Some(reason) = fallback_reason { + photocraft_ui_egui::gpu_status::queue_fallback_notice(&mut app, &reason); + } app.perf.span("gpuSentinel", sentinel_ms); // Once the first frames rendered: clear the marker, and keep a crash fallback. + let remember_cpu = + std::env::var_os("PHOTOCRAFT_GPU_STARTUP_FAILURE").is_some() || (plan.remember && plan.backend == photocraft_engine::prefs::GpuBackend::Cpu); let remember = plan.remember.then_some(plan.backend); app.on_started(move |app| { if let Some(s) = started_sentinel.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() { s.finish(); } + if remember_cpu + && let Err(error) = app.run( + "prefs.set", + serde_json::json!({"values": { + "performance.renderingMode": "cpu", "performance.useGpu": false + }}), + ) + { + log::warn!("couldn't remember CPU recovery: {error}"); + } if let Some(b) = remember && app.session.prefs().performance.gpu_backend != b && let Err(e) = app.run("prefs.set", serde_json::json!({"path": "performance.gpuBackend", "value": b.name()})) @@ -249,6 +281,26 @@ fn main() -> eframe::Result { { s.finish(); } + // Retry in a fresh process: winit event loops cannot be recreated reliably in-process. + // Only renderer initialization failures qualify; never restart after editing has begun. + if retry_cpu && !app_created.load(std::sync::atomic::Ordering::Relaxed) && matches!(&result, Err(eframe::Error::Wgpu(_))) { + let reason = result.as_ref().err().map(ToString::to_string).unwrap_or_default(); + if let Some(s) = sentinel.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() { + s.finish(); + } + if let Ok(exe) = std::env::current_exe() { + let launched = std::process::Command::new(exe) + .args(std::env::args_os().skip(1)) + .arg("--safe-gpu") + .env_remove("WGPU_BACKEND") + .env("PHOTOCRAFT_GPU_STARTUP_FAILURE", &reason) + .spawn(); + match launched { + Ok(_) => return Ok(()), + Err(error) => log::error!("could not start CPU compatibility mode: {error}"), + } + } + } result } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 852676c405..6b2530dc7b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -66,6 +66,11 @@ choice!( /// crashes inside the graphics driver moves this to the next safer choice. GpuBackend { Auto = "auto", Vulkan = "vulkan", Dx12 = "dx12", Metal = "metal", Gl = "gl", Cpu = "cpu" } default Auto ); +choice!( + /// Rendering policy, independent of the advanced graphics backend selection. + /// CPU disables image acceleration; the native window may still need hardware graphics. + RenderingMode { Auto = "auto", Gpu = "gpu", Cpu = "cpu" } default Auto +); choice!(UiFontSize { Tiny = "tiny", Small = "small", Medium = "medium", Large = "large" } default Small); choice!(LogDestination { Metadata = "metadata", TextFile = "textFile", Both = "both" } default Metadata); choice!(LogDetail { SessionsOnly = "sessionsOnly", Concise = "concise", Detailed = "detailed" } default Concise); @@ -385,6 +390,8 @@ pub struct Performance { pub cache_tile_size: u32, /// Draw the canvas with the GPU (applies at next launch). pub use_gpu: bool, + /// Explicit rendering policy. None preserves older useGpu/gpuBackend preferences. + pub rendering_mode: Option, /// Graphics backend (applies at next launch; see [`GpuBackend`]). pub gpu_backend: GpuBackend, /// Memory budget of the layer-effect cache, in MB. @@ -393,6 +400,11 @@ pub struct Performance { } impl Performance { + /// Resolve old preferences without allowing legacy flags to override an explicit mode. + pub fn effective_rendering_mode(&self) -> RenderingMode { + self.rendering_mode.unwrap_or_else(|| if !self.use_gpu || self.gpu_backend == GpuBackend::Cpu { RenderingMode::Cpu } else { RenderingMode::Auto }) + } + /// Pixel memory a document and its History may hold (Memory Usage), in bytes: beyond it /// the oldest history states are dropped. pub fn history_budget_bytes(&self) -> usize { @@ -408,6 +420,7 @@ impl Default for Performance { cache_levels: 4, cache_tile_size: 8192, use_gpu: true, + rendering_mode: None, gpu_backend: GpuBackend::Auto, effect_cache_mb: 768, legacy_compositing: false, @@ -881,6 +894,7 @@ pub fn choices(path: &str) -> Option<&'static [&'static str]> { "rawDefaults.bitDepth" => RawDepth::NAMES, "rawDefaults.sharpenFor" => RawSharpen::NAMES, "performance.gpuBackend" => GpuBackend::NAMES, + "performance.renderingMode" => RenderingMode::NAMES, _ => return None, }) } @@ -985,6 +999,9 @@ fn set_path(root: &mut Value, path: &str, value: Value) -> std::result::Result<( /// Validate one value for `path` before it is stored (choices, ranges, colours). fn check_value(path: &str, v: &Value) -> std::result::Result<(), String> { + if path == "performance.renderingMode" && v.is_null() { + return Ok(()); // Legacy policy, resolved from useGpu and gpuBackend. + } if let Some(c) = choices(path) { let s = v.as_str().ok_or_else(|| format!("`{path}` must be one of {}", c.join("|")))?; if !c.contains(&s) { diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index 78bd564a43..24363b2916 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -213,7 +213,11 @@ fn choice_and_range_tables_cover_enum_fields() { for (k, v) in p[id].as_object().unwrap() { let path = format!("{id}.{k}"); if let Some(c) = choices(&path) { - assert!(c.contains(&v.as_str().unwrap()), "{path}"); + if path == "performance.renderingMode" && v.is_null() { + assert_eq!(p["performance"]["renderingMode"], json!(null), "legacy mode is inferred until explicitly selected"); + } else { + assert!(c.contains(&v.as_str().unwrap()), "{path}"); + } } if let Some((lo, hi)) = range(&path) { let x = v.as_f64().unwrap(); diff --git a/crates/engine/tests/rendering_preferences.rs b/crates/engine/tests/rendering_preferences.rs new file mode 100644 index 0000000000..2e50f2cae4 --- /dev/null +++ b/crates/engine/tests/rendering_preferences.rs @@ -0,0 +1,37 @@ +//! Rendering policy migration and command validation, without a graphics device. +use photocraft_engine::prefs::{GpuBackend, Preferences, RenderingMode}; +use serde_json::json; + +#[test] +fn old_preferences_preserve_cpu_choices() { + for old in [json!({"useGpu": false}), json!({"gpuBackend": "cpu"})] { + let p: Preferences = serde_json::from_value(json!({"performance": old})).unwrap(); + assert_eq!(p.performance.effective_rendering_mode(), RenderingMode::Cpu); + } + assert_eq!(Preferences::default().performance.effective_rendering_mode(), RenderingMode::Auto); +} + +#[test] +fn explicit_choices_override_legacy_flags_and_round_trip() { + let mut p = Preferences::default(); + p.performance.use_gpu = false; + p.performance.gpu_backend = GpuBackend::Cpu; + for mode in [RenderingMode::Auto, RenderingMode::Gpu, RenderingMode::Cpu] { + p.set("performance.renderingMode", json!(mode.name())).unwrap(); + assert_eq!(p.performance.effective_rendering_mode(), mode); + let restored: Preferences = serde_json::from_value(p.to_json()).unwrap(); + assert_eq!(restored.performance.effective_rendering_mode(), mode); + } +} + +#[test] +fn malformed_policy_is_rejected_without_changing_preferences() { + let mut p = Preferences::default(); + let before = p.to_json(); + for invalid in [json!("quantum"), json!(7), json!({}), json!(true)] { + assert!(p.set("performance.renderingMode", invalid).is_err()); + assert_eq!(p.to_json(), before); + } + p.reset(Some("performance.renderingMode")).unwrap(); + assert_eq!(p.performance.rendering_mode, None); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b3fc3c0242..abf11d70bc 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -538,6 +538,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { "status": app.ui.status, "statusError": app.ui.status_error, "notices": app.ui.notices, + "gpuFallbackNotice": app.ui.gpu_fallback_notice, "frame": app.frame, "session": photocraft_engine::inspect::session(&app.session), "document": app.session.active().map(photocraft_engine::inspect::document), diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index 28032eda9c..3be11919f1 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -840,7 +840,17 @@ impl GpuInfo { format!("Driver: {}", or(&self.driver, "unknown")), format!("GPU backend preference: {}", or(&self.preference, "auto")), format!("Selected at launch: {}", or(&self.selected, "auto")), - format!("Canvas renderer: {}", if self.canvas == "gpu" { "GPU" } else { "CPU" }), + format!("Image compositor: {}", if self.canvas == "gpu" { "GPU" } else { "CPU" }), + format!( + "Window renderer: {}", + if self.device_type == "cpu" { + "Software adapter" + } else if self.adapter.is_empty() { + "Unknown" + } else { + "Graphics adapter" + } + ), ]; if let Some(f) = &self.fallback { v.push(format!("Fallback: {f}")); diff --git a/crates/ui-egui/src/gpu_status.rs b/crates/ui-egui/src/gpu_status.rs index cfd261b531..9ce1e06f38 100644 --- a/crates/ui-egui/src/gpu_status.rs +++ b/crates/ui-egui/src/gpu_status.rs @@ -1,6 +1,6 @@ //! GPU health in the shell (#243, #4): when the wgpu device is lost or reports an error, the //! GPU canvas is dropped and every document keeps drawing through the CPU compositor and egui -//! textures for the rest of the session, with a non-modal notice. Also runs the desktop app's +//! textures for the rest of the session, with a recovery warning. Also runs the desktop app's //! "started" hook once the first frames have rendered (the crash-safe startup marker), and //! provides the Help › System Info text. @@ -53,13 +53,7 @@ pub fn fall_back(app: &mut PhotocraftApp, fault: &photocraft_gpu::Fault) { app.perf.gpu_info.canvas = "cpu".into(); app.perf.gpu_info.lost = Some(fault.to_string()); let title = if fault.is_lost() { LOST_MESSAGE } else { ERROR_MESSAGE }; - let detail = fault.detail().trim(); - let mut lines = Vec::new(); - if !detail.is_empty() { - lines.push(detail.to_string()); - } - lines.push("Your documents are unchanged. Save your work; the GPU is used again after a restart.".into()); - crate::notices::post(app, title, lines, true); + queue_fallback_notice(app, fault.to_string()); app.ui.status = title.to_string(); app.ui.status_error = true; } @@ -82,3 +76,117 @@ pub fn system_info_json(app: &PhotocraftApp) -> serde_json::Value { "lines": system_info(app), }) } + +/// Queue the same recovery warning for startup and runtime failures. +pub fn queue_fallback_notice(app: &mut PhotocraftApp, reason: impl Into) { + app.ui.gpu_fallback_notice = Some(reason.into()); +} + +/// Store the next-launch choice without restarting or risking unsaved documents. +fn choose_recovery(app: &mut PhotocraftApp, retry: bool) -> Result<(), String> { + app.run( + "prefs.set", + json!({"values": { + "performance.renderingMode": if retry { "gpu" } else { "cpu" }, + "performance.useGpu": retry, + "performance.gpuBackend": "auto" + }}), + )?; + crate::prefs_ui::save_preferences(app)?; + app.ui.gpu_fallback_notice = None; + if retry { + crate::notices::post( + app, + "GPU retry scheduled", + vec!["Save your work and restart PhotoCraft to retry GPU acceleration. CPU rendering remains active for this session.".into()], + false, + ); + } + Ok(()) +} + +/// Recovery is an explicit choice; the CPU document renderer stays active while the user works. +pub fn show_fallback(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(reason) = app.ui.gpu_fallback_notice.clone() else { return }; + let t = crate::theme::Tokens::get(ctx); + let mut choice = None; + egui::Window::new(tl!("Switched to CPU rendering")) + .id(egui::Id::new("gpu-fallback-warning")) + .collapsible(false) + .resizable(false) + .default_width(440.0) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ctx, |ui| { + ui.label(egui::RichText::new(tl!("GPU acceleration could not continue. Your documents are unchanged.")).color(t.warning)); + ui.label(tl!("PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter.")); + ui.collapsing(tl!("Details"), |ui| { + ui.label(&reason); + }); + ui.label(tl!("Retry GPU requires a restart. Save your work first.")); + ui.add_space(8.0); + ui.horizontal(|ui| { + if crate::widgets::primary_button(ui, tl!("Keep Using CPU"), 150.0).clicked() { + choice = Some(false); + } + if crate::widgets::secondary_button(ui, tl!("Retry GPU"), 120.0).clicked() { + choice = Some(true); + } + }); + }); + if let Some(retry) = choice + && let Err(error) = choose_recovery(app, retry) + { + crate::notices::error(app, error); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fallback_warning_keeps_reason_in_inspectable_state() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + queue_fallback_notice(&mut app, "device unavailable"); + let state = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(state["gpu_fallback_notice"], "device unavailable"); + assert_eq!(crate::control::inspect(&app, &egui::Context::default())["gpuFallbackNotice"], "device unavailable"); + } + + #[test] + fn failed_preference_save_keeps_recovery_warning_open() { + let services = crate::Services { save_prefs: Some(Box::new(|_| Err("disk full".into()))), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + queue_fallback_notice(&mut app, "GPU fault"); + assert!(choose_recovery(&mut app, true).is_err()); + assert_eq!(app.ui.gpu_fallback_notice.as_deref(), Some("GPU fault")); + assert!(app.ui.notices.is_empty()); + } + + #[test] + fn recovery_choices_save_next_launch_mode_without_restarting() { + let saves = std::rc::Rc::new(std::cell::Cell::new(0)); + let count = saves.clone(); + let services = crate::Services { + save_prefs: Some(Box::new(move |_| { + count.set(count.get() + 1); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + queue_fallback_notice(&mut app, "device unavailable"); + choose_recovery(&mut app, false).unwrap(); + assert!(!app.session.prefs().performance.use_gpu); + assert_eq!(app.session.prefs().get("performance.renderingMode"), Some(json!("cpu"))); + assert!(app.ui.gpu_fallback_notice.is_none()); + crate::prefs_ui::tick(&mut app, &egui::Context::default()); + assert_eq!(saves.get(), 1, "recovery choice writes once"); + choose_recovery(&mut app, true).unwrap(); + assert!(app.session.prefs().performance.use_gpu); + assert_eq!(app.session.prefs().get("performance.renderingMode"), Some(json!("gpu"))); + assert!(app.gpu.is_none()); + crate::prefs_ui::tick(&mut app, &egui::Context::default()); + assert_eq!(saves.get(), 2, "retry choice writes once"); + } +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3a36e857a6..19305c6ad2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1996,3 +1996,20 @@ Opening… Otevírání… Reading… Načítání… Working… Zpracování… + +# Rendering mode and recovery + Rendering Mode Režim vykreslování + Automatic (recommended) Automaticky (doporučeno) + CPU / Compatibility CPU / Kompatibilita + Automatic uses GPU acceleration when available and falls back to CPU rendering on errors. Automatický režim používá dostupnou GPU a při chybě přejde na CPU. + Switched to CPU rendering Přepnuto na vykreslování CPU + GPU acceleration could not continue. Your documents are unchanged. Akcelerace GPU nemohla pokračovat. Dokumenty zůstaly nezměněny. + PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter. PhotoCraft skládá obraz pomocí CPU. Okno může nadále používat grafický adaptér. + Retry GPU requires a restart. Save your work first. Opakování GPU vyžaduje restart. Nejprve uložte práci. + Keep Using CPU Pokračovat s CPU + Retry GPU Zkusit GPU znovu + Advanced Pokročilé + GPU Backend Backend GPU + Details Podrobnosti + + Rendering mode Režim vykreslování diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index df7aef3a01..d57feccfcf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2071,3 +2071,19 @@ # Command-id override: under Edit > Purge a bare "Deshacer" reads as an action, not the history. @id edit.purge.undo Historial de deshacer +# Rendering mode and recovery + Rendering Mode Modo de renderizado + Automatic (recommended) Automático (recomendado) + CPU / Compatibility CPU / Compatibilidad + Automatic uses GPU acceleration when available and falls back to CPU rendering on errors. Automático utiliza la GPU cuando está disponible y cambia a la CPU si hay errores. + Switched to CPU rendering Se cambió al renderizado por CPU + GPU acceleration could not continue. Your documents are unchanged. La aceleración GPU no pudo continuar. Los documentos no han cambiado. + PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter. PhotoCraft compone las imágenes en la CPU. La ventana aún puede usar el adaptador gráfico. + Retry GPU requires a restart. Save your work first. Reintentar la GPU requiere reiniciar. Guarda primero tu trabajo. + Keep Using CPU Seguir usando CPU + Retry GPU Reintentar GPU + Advanced Avanzado + GPU Backend Motor GPU + Details Detalles + + Rendering mode Modo de renderizado diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 242e558769..8f6be3f604 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1986,3 +1986,20 @@ Opening… 開いています… Reading… 読み込み中… Working… 処理中… + +# Rendering mode and recovery + Rendering Mode レンダリングモード + Automatic (recommended) 自動(推奨) + CPU / Compatibility CPU / 互換性 + Automatic uses GPU acceleration when available and falls back to CPU rendering on errors. 自動モードは利用可能な場合にGPUを使用し、エラー時はCPU描画に切り替えます。 + Switched to CPU rendering CPU描画に切り替えました + GPU acceleration could not continue. Your documents are unchanged. GPUアクセラレーションを継続できませんでした。ドキュメントは変更されていません。 + PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter. PhotoCraftはCPUで画像を合成しています。ウィンドウは引き続きグラフィックスアダプターを使用する場合があります。 + Retry GPU requires a restart. Save your work first. GPUの再試行には再起動が必要です。先に作業を保存してください。 + Keep Using CPU CPUを使い続ける + Retry GPU GPUを再試行 + Advanced 詳細設定 + GPU Backend GPUバックエンド + Details 詳細 + + Rendering mode レンダリングモード diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 10551d1611..74a1235d1a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2264,3 +2264,20 @@ Opening… Открытие… Reading… Чтение… Working… Обработка… + +# Rendering mode and recovery + Rendering Mode Режим отрисовки + Automatic (recommended) Автоматически (рекомендуется) + CPU / Compatibility CPU / Совместимость + Automatic uses GPU acceleration when available and falls back to CPU rendering on errors. Автоматический режим использует GPU, когда он доступен, и переходит на CPU при ошибках. + Switched to CPU rendering Включена отрисовка на CPU + GPU acceleration could not continue. Your documents are unchanged. Ускорение GPU остановлено. Документы не изменены. + PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter. PhotoCraft обрабатывает изображения на CPU. Окно может продолжать использовать графический адаптер. + Retry GPU requires a restart. Save your work first. Для повтора GPU нужен перезапуск. Сначала сохраните работу. + Keep Using CPU Продолжить с CPU + Retry GPU Повторить GPU + GPU Backend Бэкенд GPU + Details Подробности + GPU GPU + + Rendering mode Режим отрисовки diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f8b01436ed..6f6c23d1e2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1978,3 +1978,20 @@ Opening… 正在開啟… Reading… 正在讀取… Working… 處理中… + +# Rendering mode and recovery + Rendering Mode 渲染模式 + Automatic (recommended) 自動(建議) + CPU / Compatibility CPU / 相容模式 + Automatic uses GPU acceleration when available and falls back to CPU rendering on errors. 自動模式會在可用時使用 GPU 加速,發生錯誤時改用 CPU 渲染。 + Switched to CPU rendering 已改用 CPU 渲染 + GPU acceleration could not continue. Your documents are unchanged. GPU 加速無法繼續。您的文件未變更。 + PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter. PhotoCraft 正使用 CPU 合成影像。視窗仍可能使用您的顯示卡。 + Retry GPU requires a restart. Save your work first. 重試 GPU 需要重新啟動。請先儲存您的工作。 + Keep Using CPU 繼續使用 CPU + Retry GPU 重試 GPU + Advanced 進階 + GPU Backend GPU 後端 + Details 詳細資訊 + + Rendering mode 渲染模式 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4fe6bf7a66..88600f8934 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -461,8 +461,22 @@ impl PhotocraftApp { pub fn set_wgpu(&mut self, rs: eframe::egui_wgpu::RenderState) { // Preferences › Performance › cache tile size (PHOTOCRAFT_GPU_TILE still overrides). let tile = self.session.prefs().performance.cache_tile_size; - let gpu = gpu_canvas::GpuCanvas::with_tile(&rs, Some(tile)); - self.perf.gpu_info.set_adapter(&gpu.adapter_info()); + // Escaped driver/setup panics must leave the session and CPU canvas alive. + self.perf.gpu_info.set_adapter(&rs.adapter.get_info()); + let gpu = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu_canvas::GpuCanvas::with_tile(&rs, Some(tile)))) { + Ok(gpu) => gpu, + Err(payload) => { + let detail = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) + .unwrap_or_else(|| "GPU canvas initialization failed".into()); + self.perf.gpu_info.canvas = "cpu".into(); + self.perf.gpu_info.fallback = Some(detail.clone()); + gpu_status::queue_fallback_notice(self, detail); + return; + } + }; self.perf.gpu_info.canvas = "gpu".into(); self.gpu = Some(gpu); self.prefs_rt.gpu_style = None; @@ -917,6 +931,7 @@ impl eframe::App for PhotocraftApp { wide_angle_ui::show(self, &ctx); canvas::extra_windows(self, &ctx); notices::show(self, &ctx); + gpu_status::show_fallback(self, &ctx); // A device lost while drawing this frame: switch to the CPU canvas before the next one. gpu_status::check(self, &ctx); self.automation_input = false; diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 38796105a5..a67114952b 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -343,6 +343,20 @@ fn merge_changes(base: &Value, ours: &Value, theirs: &mut Value) { } } +/// Write the preferences now, through the same merge as [`persist`], for recovery choices that +/// need the result immediately. The pending revision stays unsaved when the write fails. +pub(crate) fn save_preferences(app: &mut PhotocraftApp) -> Result<(), String> { + let rev = app.session.prefs.rev(); + let ours = app.session.prefs_value(); + write_prefs(app, &ours)?; + app.prefs_rt.saved_rev = rev; + app.prefs_rt.saved_value = Some(ours); + if let Some(id) = std::mem::take(&mut app.prefs_rt.save_retry).notice { + app.ui.notices.retain(|n| n.id != id); + } + Ok(()) +} + /// Background autosave of documents with unsaved changes every N minutes (File Handling). fn autosave(app: &mut PhotocraftApp) { let fh = &app.session.prefs().file_handling; @@ -657,8 +671,7 @@ pub fn open_preferences(app: &mut PhotocraftApp, section: &str) -> u64 { let section = if SECTIONS.iter().any(|(id, _)| *id == section) { section } else { "general" }; let working = preference_values(app.session.prefs()); let order = field_order(app.session.prefs(), &working); - let gpu = app.perf.gpu_info.lines(); - open_kind(app, "prefs", "Preferences", json!({"section": section, "values": working, "__order": order, "__gpuInfo": gpu})) + open_kind(app, "prefs", "Preferences", json!({"section": section, "values": working, "__order": order})) } /// Each section's keys in declaration order (JSON objects sort their keys; the serialised text @@ -725,7 +738,10 @@ pub fn open_mismatch(app: &mut PhotocraftApp, report: &Value) -> u64 { /// Render one of our dialogs' bodies. pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") { - "prefs" => prefs_body(ui, f), + "prefs" => { + f.insert("__gpuInfo".into(), json!(app.perf.gpu_info.lines())); + prefs_body(ui, f); + } "shortcuts" => shortcuts_body(app, ui, f), "presets" => presets_body(app, ui, f), "presetsIO" => presets_io_body(ui, f), @@ -853,16 +869,49 @@ fn gpu_status_rows(ui: &mut egui::Ui, info: Option<&Value>, obj: &mut Map = options.iter().map(|o| choice_label(o)).collect(); + let pairs: Vec<(String, &str)> = options.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); + crate::widgets::dropdown(ui, "graphics-backend", &mut current, &pairs, 220.0); + obj.insert("gpuBackend".into(), json!(current)); + }); }); } +/// One user-facing choice; legacy flags remain compatible with older settings. +fn rendering_mode_row(ui: &mut egui::Ui, obj: &mut Map) { + let mut current = rendering_mode_value(obj); + ui.horizontal(|ui| { + ui.label(tl!("Rendering Mode")); + let pairs = + vec![("auto".to_string(), tl!("Automatic (recommended)")), ("gpu".to_string(), tl!("GPU")), ("cpu".to_string(), tl!("CPU / Compatibility"))]; + let previous = current.clone(); + crate::widgets::dropdown(ui, "rendering-mode", &mut current, &pairs, 240.0); + if current != previous { + obj.insert("renderingMode".into(), json!(current)); + obj.insert("useGpu".into(), json!(current != "cpu")); + } + }); + ui.label(tl!("Automatic uses GPU acceleration when available and falls back to CPU rendering on errors.")); + ui.add_space(8.0); +} + +fn rendering_mode_value(obj: &Map) -> String { + obj.get("renderingMode").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| { + if obj.get("useGpu").and_then(Value::as_bool) == Some(false) || obj.get("gpuBackend").and_then(Value::as_str) == Some("cpu") { + "cpu".into() + } else { + "auto".into() + } + }) +} + /// Does `section` have any setting the dialog shows (see [`prefs::HIDDEN_UNTIL_IMPLEMENTED`])? fn has_visible_fields(values: &Value, section: &str) -> bool { values.get(section).and_then(Value::as_object).is_some_and(|o| o.keys().any(|k| !prefs::is_hidden(&format!("{section}.{k}")))) @@ -872,6 +921,9 @@ fn has_visible_fields(values: &Value, section: &str) -> bool { /// number fields with the preference's range, text fields. fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map, order: &[String], lang: crate::i18n::Lang) { let t = Tokens::get(ui.ctx()); + if section == "performance" { + rendering_mode_row(ui, obj); + } let mut keys: Vec = order.iter().filter(|k| obj.contains_key(*k)).cloned().collect(); keys.extend(obj.keys().filter(|k| !order.contains(k)).cloned()); egui::Grid::new(("prefs-grid", section)).num_columns(2).spacing([14.0, 7.0]).show(ui, |ui| { @@ -879,7 +931,7 @@ fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map let path = format!("{section}.{k}"); // Settings nothing reads yet stay out of the dialog (issue #204); their stored values // pass through untouched. - if prefs::is_hidden(&path) { + if prefs::is_hidden(&path) || (section == "performance" && matches!(k.as_str(), "useGpu" | "gpuBackend" | "renderingMode")) { continue; } let v = obj.get(&k).cloned().unwrap_or(Value::Null); @@ -1317,6 +1369,16 @@ mod shortcut_capture_tests; #[cfg(test)] mod tests { + + #[test] + fn rendering_mode_display_respects_explicit_mode_and_legacy_disable() { + let legacy = serde_json::json!({"useGpu": false, "gpuBackend": "auto"}); + assert_eq!(super::rendering_mode_value(legacy.as_object().unwrap()), "cpu"); + let explicit = serde_json::json!({"renderingMode": "gpu", "useGpu": false, "gpuBackend": "cpu"}); + assert_eq!(super::rendering_mode_value(explicit.as_object().unwrap()), "gpu"); + let automatic = serde_json::json!({"renderingMode": null, "useGpu": true, "gpuBackend": "auto"}); + assert_eq!(super::rendering_mode_value(automatic.as_object().unwrap()), "auto"); + } use super::*; use std::sync::{Arc, Mutex}; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6f5f8cebd1..4433eb55cd 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -660,6 +660,9 @@ pub struct UiState { /// Non-blocking notices (import/export warnings, files that couldn't open), newest last. #[serde(default)] pub notices: Vec, + /// Pending GPU fallback warning, visible to automation. + #[serde(default)] + pub gpu_fallback_notice: Option, /// Status bar info field, Home screen (see `chrome_ui`). #[serde(default)] pub chrome: crate::chrome_ui::ChromeState, @@ -713,6 +716,7 @@ impl Default for UiState { status: String::new(), status_error: false, notices: Vec::new(), + gpu_fallback_notice: None, chrome: Default::default(), } } diff --git a/crates/ui-egui/tests/gpu_device_loss.rs b/crates/ui-egui/tests/gpu_device_loss.rs index 0f27098544..f8da5cdb05 100644 --- a/crates/ui-egui/tests/gpu_device_loss.rs +++ b/crates/ui-egui/tests/gpu_device_loss.rs @@ -112,9 +112,10 @@ fn app_switches_to_the_cpu_canvas_and_keeps_the_documents() { let app = h.state(); assert!(!app.gpu_active(), "still on the GPU canvas"); assert_eq!(app.session.documents().len(), 1, "document kept"); - let n = app.ui.notices.last().expect("notice"); - assert_eq!(n.title, gpu_status::LOST_MESSAGE); - assert!(n.error); + assert_eq!(app.ui.status, gpu_status::LOST_MESSAGE); + assert!(app.ui.status_error); + assert!(app.ui.gpu_fallback_notice.as_deref().unwrap_or("").contains("killed by the OS")); + assert!(app.ui.notices.is_empty(), "one recovery warning, no duplicate notice"); assert!(app.perf.gpu_info.lost.as_deref().unwrap_or("").contains("killed by the OS")); assert_eq!(app.perf.gpu_info.canvas, "cpu"); // The CPU path draws the document: a refresh after the loss is a CPU one. @@ -158,7 +159,7 @@ fn system_info_lists_the_graphics_state() { app.perf.gpu_info.fallback = Some("the previous start didn't finish on vulkan; using dx12".into()); let lines = gpu_status::system_info(&app); let text = lines.join("\n"); - for want in ["Graphics adapter: Test GPU", "Backend: dx12", "Selected at launch: dx12", "Fallback: the previous start", "Canvas renderer: CPU"] { + for want in ["Graphics adapter: Test GPU", "Backend: dx12", "Selected at launch: dx12", "Fallback: the previous start", "Image compositor: CPU"] { assert!(text.contains(want), "{want} missing from\n{text}"); } let v = gpu_status::system_info_json(&app); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 71380b7f5b..67395aaacb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -46,7 +46,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}` - `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing) - `ui.resize {width, height}`: resize the main window -- `ui.gpu.simulateLoss {error?}`: act as if the wgpu device was lost (or reported an error with `error: true`). The app switches to the CPU renderer for the rest of the session and shows the same notice as on a real loss. Returns `wasActive` and `gpuInfo`. For testing the fallback +- `ui.gpu.simulateLoss {error?}`: act as if the wgpu device was lost (or reported an error with `error: true`). The app switches to the CPU image compositor for the rest of the session and shows the same recovery warning as on a real loss. `gpuFallbackNotice` in `ui.inspect` contains the reason while the warning is open. Keep Using CPU saves CPU compatibility for the next launch; Retry GPU saves GPU mode and asks the user to save and restart. The window renderer still requires a working graphics or software adapter. Returns `wasActive` and `gpuInfo`. For testing the fallback - `ui.screenshot {path?, focus?}`: capture the main window (PNG). With no path the reply contains base64 PNG data; a path is relative to the automation write root. Raises the window first (default) because occluded macOS windows stop rendering @@ -265,3 +265,13 @@ accounting, compositor scratch-space accounting, command cancellation/duration l general per-method capabilities. Desktop screenshot capture/encoding and document import/export still need their own operation budgets; the desktop reply ceiling applies after the UI creates its response. A bounded output does not imply bounded command cost. + +### Rendering modes + +`performance.renderingMode` accepts `auto`, `gpu`, or `cpu`. Automatic is the default for new +settings; older `useGpu: false` or `gpuBackend: cpu` preferences continue to select CPU mode +until an explicit mode is saved. Changes apply at the next launch. Automatic and GPU both +fall back on graphics errors rather than risk documents. CPU compatibility composites images +on the CPU and prefers software window adapters, when available. macOS still uses Metal for +the window. A failed window renderer initialization retries once in CPU compatibility mode; +a driver process crash is detected by the startup marker on the next launch. diff --git a/docs/scorecard.md b/docs/scorecard.md index 5cbb89e01f..bbc2969663 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 12 | 46 scenarios: 3 within budget, 22 over budget or failing, 13 tracked only, 4 not run, 8 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 1 | 8 | 18 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 130/256, round trip ≥ 258/256 | | [Tools](#tools) | 3 | 14 | 13 | | -| [Workspace and UI](#workspace-and-ui) | 0 | 4 | 19 | settings that do nothing: 60 of 133 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 0 | 4 | 19 | settings that do nothing: 60 of 134 (target 0) | | [Type](#type) | 0 | 3 | 6 | | | [Automation](#automation) | 1 | 3 | 7 | 626 of 626 menu items live (100.0%) | | [Reliability](#reliability) | 3 | 1 | 3 | never-crash lints on 26 of 26 crates; panic_hunt present | @@ -153,7 +153,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 60 of 133** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 60 of 134** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.beep_when_done`, `general.export_clipboard`, `general.resize_image_during_place`, `general.always_create_smart_objects_when_placing`, `general.animated_zoom`, `general.zoom_resizes_windows`, `general.use_legacy_free_transform`, `interface.ui_font_size`, `interface.show_channels_in_color`, `interface.dynamic_color_sliders`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.open_documents_as_tabs`, `workspace.enable_floating_document_window_docking`, `workspace.large_tabs`, `workspace.enable_narrow_options_bar`, `tools.zoom_clicked_point_to_center`, `tools.enable_flick_panning`, `tools.vary_round_brush_hardness_on_hud`, `tools.show_transformation_values`, `tools.double_click_layer_mask_launches_select_and_mask`, `file_handling.image_previews`, `file_handling.lowercase_extension`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.ask_before_saving_layered_tiff`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `cursors.brush_preview_color`, `units_and_rulers.type_units`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `units_and_rulers.print_resolution`, `units_and_rulers.screen_resolution`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.smart_quotes`, `type_.missing_glyph_protection`, `type_.show_font_names_in_english`, `type_.use_esc_to_commit`, `type_.text_engine`, `type_.font_preview`, `type_.fill_new_type_layers_with_placeholder`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `enhanced_controls.zoom_with_trackpad_pinch`, `enhanced_controls.rotate_view_with_trackpad`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.