LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Issue #136: merge main (upstream file split)
OneSlips8793fa83f8d1
diff --cc apps/lightcraft-cli/tests/it/cli.rsindex 4ea499cf1,8a11f5c9a..70f7143e6--- a/apps/lightcraft-cli/tests/it/cli.rs+++ b/apps/lightcraft-cli/tests/it/cli.rs@@@ -466,41 -466,6 +473,41 @@@ fn snapshot_defaults_to_cpu_without_gpuassert_eq!((decoded.width, decoded.height), (480, 320));}+/// Issue #136: `app.gpu {enabled: true, wait: false}` (what the UI sends on its first frame) answers+/// at once while the device is still being created: enabled, and nothing known yet (`null`), instead+/// of waiting for the driver. It starts creating the device (off the calling thread), so this test+/// touches the GPU driver and skips when the environment turns the GPU off.+#[test]+fn enabling_the_gpu_without_waiting_answers_before_the_device_exists() {+ if std::env::var("LIGHTCRAFT_GPU").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")) {+ lightcraft_testkit::skip!(Gpu, "LIGHTCRAFT_GPU=0: enabling the GPU starts creating a device");+ return;+ }+ let script = tmp("gpu-starting.jsonl");+ std::fs::write(+ &script,+ format!("{}\n", json!({"method": "engine.execute", "params": {"command": "app.gpu", "params": {"enabled": true, "wait": false}}})),+ )+ .unwrap();+ let image = tmp("gpu-starting.png");- let output = Command::new(BIN)++ let output = Command::new(binary())+ .env_remove("LIGHTCRAFT_GPU")+ .env_remove("LIGHTCRAFT_GPU_BACKEND")+ .env_remove("WGPU_BACKEND")+ .args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", image.to_str().unwrap(), "--size", "480x320"])+ .output()+ .unwrap();+ assert!(output.status.success(), "status {}: {}", output.status, String::from_utf8_lossy(&output.stderr));+ let replies: Vec<Value> = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();+ assert_eq!(replies.len(), 1, "{replies:?}");+ assert_eq!(replies[0]["ok"], true, "{replies:?}");+ let gpu = &replies[0]["result"];+ assert_eq!(gpu["enabled"], true, "{gpu}");+ for field in ["available", "adapter", "reason"] {+ assert_eq!(gpu[field], Value::Null, "{field} is not known while the device is created: {gpu}");+ }+}+/// Issue #136: with the GPU switched off from the environment the UI starts and renders on the CPU,/// without creating a GPU device (no driver is loaded), and says why.#[test]diff --cc crates/ui-egui/src/app/prefs.rsindex 000000000,a85a5f751..b0b100164mode 000000,100644..100644--- a/crates/ui-egui/src/app/prefs.rs+++ b/crates/ui-egui/src/app/prefs.rs@@@ -1,0 -1,114 +1,114 @@@+ use super::*;++ impl LightcraftApp {+ /// The system's appearance: the host's answer first, then egui's (none: unknown).+ pub fn system_theme(&self, ctx: &egui::Context) -> Option<egui::Theme> {+ self.services.system_theme.as_ref().and_then(|read| read(ctx)).or_else(|| ctx.system_theme())+ }++ /// Restyle `ctx` when the theme the settings select (Appearance Mode, the dark and light+ /// themes, the system's appearance in Auto) is not the one it shows. A no-op otherwise.+ pub fn sync_theme(&mut self, ctx: &egui::Context) {+ let wanted = self.ui.settings.theme(self.system_theme(ctx));+ if theme::current(ctx) != Some(wanted) {+ theme::apply_kind(ctx, wanted);+ }+ }++ /// Back from an external editor: pick up the files it saved. Reads `i.focused`, which+ /// `run_logic` does not refresh, so it belongs to the UI phase.+ pub(super) fn check_external_editor(&mut self, ctx: &egui::Context) {+ let focused = ctx.input(|i| i.focused);+ if focused && !self.ui.was_focused && !self.ui.external_edits.is_empty() {+ let ids = self.ui.external_edits.clone();+ if let Ok(r) = self.session.execute("photo.reload", &serde_json::json!({"ids": ids}))+ && r["reloaded"].as_array().is_some_and(|a| !a.is_empty())+ {+ self.toast(ctx, crate::i18n::tr("Updated the edits saved in the external editor"));+ }+ }+ self.ui.was_focused = focused;+ }++ /// Apply settings that act outside the UI state: GPU rendering and window full screen.+ pub(super) fn apply_settings(&mut self, ctx: &egui::Context) {+ if self.gpu_applied != Some(self.ui.settings.gpu) {+ self.gpu_applied = Some(self.ui.settings.gpu);- let _ = self.session.execute("app.gpu", &serde_json::json!({"enabled": self.ui.settings.gpu}));++ let _ = self.session.execute("app.gpu", &serde_json::json!({"enabled": self.ui.settings.gpu, "wait": false}));+ // GPU device + kernels off the UI thread, once the window is up and only when GPU+ // rendering is on: a broken driver must not keep the window from appearing (issue #136)+ if self.ui.settings.gpu {+ lightcraft_engine::gpu::warm_up();+ }+ }+ let mb = self.ui.settings.memory_mb;+ // automatic at startup: leave the engine's default alone+ if self.memory_applied != Some(mb) && (mb > 0 || self.memory_applied.is_some()) {+ let mb = if mb == 0 { (lightcraft_engine::memory::default_budget() >> 20) as u32 } else { mb };+ let _ = self.session.execute("app.memoryBudget", &serde_json::json!({"mb": mb}));+ }+ self.memory_applied = Some(mb);+ // the monitor profile (Settings ▸ Display): previews follow it from the next frame+ if self.display_applied.as_ref() != Some(&self.ui.settings.display_profile) {+ let path = self.ui.settings.display_profile.clone();+ match lightcraft_engine::display::Display::load_opt(&path) {+ Ok(d) => {+ self.renderer.set_display(d);+ self.display_error = None;+ }+ Err(msg) => {+ // a profile that can't be used: previews are sRGB, the setting is kept+ self.renderer.set_display(None);+ log::warn!("display profile: {msg}");+ self.toast_error(ctx, format!("{}: {msg}", crate::i18n::tr("Display profile not used")));+ self.display_error = Some(msg);+ }+ }+ self.display_applied = Some(path);+ // none chosen again: the screen's profile is read afresh+ self.screen_profile = None;+ self.screen_profile_read = None;+ }+ if self.ui.settings.display_profile.is_empty() {+ self.follow_screen_profile(ctx);+ }+ if let Some(fs) = ctx.input(|i| i.viewport().fullscreen) {+ self.window_is_fullscreen = fs;+ }+ if let Some(on) = self.ui.window_fullscreen.take() {+ ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(on));+ self.window_is_fullscreen = on;+ }+ }++ /// While no display profile is chosen, show previews through the profile of the screen the+ /// window is on (`services.screen_profile`), read about once a second so moving the window to+ /// another screen is followed. Without the service (or a profile) the display is sRGB.+ fn follow_screen_profile(&mut self, _ctx: &egui::Context) {+ let now = self.tick_now();+ if self.services.screen_profile.is_none() || self.screen_profile_read.is_some_and(|t| (0.0..1.0).contains(&(now - t))) {+ return;+ }+ self.screen_profile_read = Some(now);+ self.apply_screen_profile();+ }++ /// Read the screen's profile now and show previews through it (sRGB without one).+ pub(crate) fn apply_screen_profile(&mut self) {+ let Some(read) = self.services.screen_profile.as_mut() else { return };+ let icc = read();+ if icc == self.screen_profile {+ return;+ }+ let display = icc.as_deref().and_then(|bytes| match lightcraft_engine::display::Display::from_bytes(SCREEN_PROFILE, bytes) {+ Ok(d) => Some(std::sync::Arc::new(d)),+ Err(msg) => {+ // a profile we can't use: previews stay sRGB, as before #787+ log::warn!("screen profile: {msg}");+ None+ }+ });+ self.renderer.set_display(display);+ self.screen_profile = icc;+ }+ }diff --cc crates/ui-egui/src/dialogs/settings/performance.rsindex 000000000,daf2fa435..2310a947amode 000000,100644..100644--- a/crates/ui-egui/src/dialogs/settings/performance.rs+++ b/crates/ui-egui/src/dialogs/settings/performance.rs@@@ -1,0 -1,185 +1,193 @@@+ use super::widgets::{check, choices, heading, hint, row};+ #[cfg(not(target_arch = "wasm32"))]+ use super::widgets::{label_width, path_label};+ use super::*;++ // --------------------------------------------------------------------------------- Performance++ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {+ use lightcraft_engine::gpu;+ heading(ui, t, crate::i18n::tr("Rendering"));+ check(ui, "settings.gpu", &mut app.ui.settings.gpu, "Use the GPU for rendering");- let status = if !gpu::available() {++ // `available` would wait for a device still being created (issue #136)++ let status = if gpu::enabled() && !gpu::ready() {++ // the device is created on another thread, which doesn't wake the UI when it's done;++ // make sure that thread runs (cheap and idempotent: a start lost to an off/on switch++ // can't leave "starting" for good)++ gpu::warm_up();++ ui.ctx().request_repaint_after(std::time::Duration::from_millis(250));++ "GPU: starting…".to_string()++ } else if !gpu::available() {+ match gpu::unavailable_reason() {+ Some(why) => crate::i18n::tr_format!("Rendering on the CPU: {why}", why = why),+ None => "No usable GPU found: rendering on the CPU".to_string(),+ }+ } else {+ format!("GPU: {}", gpu::adapter_name().unwrap_or_else(|| "starting…".into()))+ };+ // One line, the whole text on hover: the reason can be a long driver message (no adapter+ // among the backends …), and the GPU state is process-wide, so it may change between frames;+ // a hint that wrapped would move every control below it under the pointer.+ ui.add(egui::Label::new(RichText::new(crate::i18n::tr(&status)).size(11.0).color(t.text_dim)).truncate()).on_hover_text(&status);+ row(ui, t, crate::i18n::tr("Preview size"), |ui| {+ let opts: Vec<(u32, String)> =+ PREVIEW_LIMITS.iter().map(|e| (*e, if *e == 0 { crate::i18n::tr("Automatic").to_string() } else { format!("{e} px") })).collect();+ let opts: Vec<(u32, &str)> = opts.iter().map(|(e, l)| (*e, l.as_str())).collect();+ choices(ui, "settingsPreview", &opts, &mut app.ui.settings.preview_limit);+ });+ hint(+ ui,+ t,+ crate::i18n::tr(+ "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.",+ ),+ );+ row(ui, t, crate::i18n::tr("Memory for caches"), |ui| {+ let auto = crate::i18n::tr_format!("Automatic ({} MB)", lightcraft_engine::memory::default_budget() >> 20);+ let opts = [(0u32, auto.as_str()), (512, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB")];+ choices(ui, "settingsMemory", &opts, &mut app.ui.settings.memory_mb);+ });+ heading(ui, t, crate::i18n::tr("Thumbnail cache"));+ let cur = (app.session.cache_bytes() >> 20) as u32;+ row(ui, t, crate::i18n::tr("Size limit"), |ui| {+ let opts = [(512u32, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB"), (8192, "8 GB")];+ let mut v = if CACHE_SIZES.contains(&cur) { cur } else { 2048 };+ if choices(ui, "settingsCache", &opts, &mut v) {+ let _ = app.run("library.preferences", json!({"cacheMb": v}));+ }+ });+ let used = app.session.media.rendered.disk().map(|d| d.size());+ row(ui, t, crate::i18n::tr("In use"), |ui| {+ ui.label(+ RichText::new(used.map(|b| format!("{:.1} MB", b as f64 / 1048576.0)).unwrap_or_else(|| crate::i18n::tr("memory only").to_string()))+ .color(t.text),+ );+ let r = ui.button(crate::i18n::tr("Clear Cache"));+ register(ui, "button:settingsClearCache", r.rect);+ if r.clicked() {+ let _ = app.run("library.clearPreviews", json!({}));+ }+ });+ heading(ui, t, crate::i18n::tr("Local folders"));+ row(ui, t, crate::i18n::tr("Forget unchanged photos"), |ui| {+ let opts = [(0u32, "Never"), (7, "After 7 days"), (30, "After 30 days"), (90, "After 90 days"), (365, "After a year")];+ let mut v = app.session.forget_local_days;+ if choices(ui, "settingsForgetLocal", &opts, &mut v) {+ let _ = app.run("library.preferences", json!({"forgetLocalDays": v}));+ }+ });+ hint(+ ui,+ t,+ crate::i18n::tr(+ "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.",+ ),+ );+ #[cfg(not(target_arch = "wasm32"))]+ smart_previews(app, ui, t);+ }++ /// Where this library keeps its smart previews (the offline-editing proxies, which can be large):+ /// the effective folder, what is in it, and choosing another one.+ #[cfg(not(target_arch = "wasm32"))]+ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {+ // listing a big folder every frame would be slow: refresh every 2 s and after a change+ let cache = egui::Id::unique("smart-location");+ let now = ui.input(|i| i.time);+ let loc: Value = match ui.data(|d| d.get_temp::<(f64, Value)>(cache)) {+ Some((at, v)) if now - at < 2.0 => v,+ _ => {+ let v = app.run("library.smartPreviewsLocation", json!({})).unwrap_or(Value::Null);+ ui.data_mut(|d| d.insert_temp(cache, (now, v.clone())));+ v+ }+ };+ if loc.is_null() {+ return;+ }+ heading(ui, t, crate::i18n::tr("Smart previews"));+ let path = loc["path"].as_str().unwrap_or_default().to_string();+ let available = loc["available"].as_bool().unwrap_or(true);+ let custom = loc["custom"].as_bool().unwrap_or(false);+ row(ui, t, crate::i18n::tr("Folder"), |ui| {+ path_label(+ ui,+ "settingsSmartFolder",+ &path,+ egui::TextStyle::Body.resolve(ui.style()),+ if available { t.text } else { t.reject },+ if custom { 0.0 } else { label_width(ui, "(library default)", egui::TextStyle::Body) },+ );+ if !custom {+ let r = ui.label(RichText::new("(library default)").color(t.text));+ register(ui, "text:settingsSmartDefault", r.rect);+ }+ });+ let (count, bytes) = (loc["count"].as_u64().unwrap_or(0), loc["bytes"].as_u64().unwrap_or(0));+ if available {+ hint(+ ui,+ t,+ &crate::i18n::tr_format!(+ "{count} smart preview{} · {:.1} MB",+ if count == 1 { "" } else { "s" },+ bytes as f64 / 1048576.0,+ count = count+ ),+ );+ } else {+ hint(+ ui,+ t,+ crate::i18n::tr(+ "This folder is not available (drive disconnected?). Smart previews are not built or used until it is back or you choose another folder.",+ ),+ );+ }+ // what happens to the previews already built when the folder changes+ let mode_id = egui::Id::unique("smart-existing");+ let mut mode: u8 = ui.data(|d| d.get_temp(mode_id)).unwrap_or(0);+ if count > 0 {+ row(ui, t, crate::i18n::tr("Existing previews"), |ui| {+ if choices(ui, "settingsSmartExisting", &[(0u8, "Move them"), (1, "Leave them"), (2, "Delete them")], &mut mode) {+ ui.data_mut(|d| d.insert_temp(mode_id, mode));+ }+ });+ }+ let existing = ["move", "leave", "discard"][mode.min(2) as usize];+ let mut result = None;+ ui.horizontal(|ui| {+ ui.add_space(LABEL_W);+ if app.services.pick_folder.is_some() {+ let r = ui.button(crate::i18n::tr("Choose Folder…"));+ register(ui, "button:settingsSmartChoose", r.rect);+ if r.clicked()+ && let Some(dir) = app.services.pick_folder.as_mut().and_then(|f| f())+ {+ result = Some(app.run("library.smartPreviewsLocation", json!({"path": dir, "existing": existing})));+ }+ }+ let r = ui.add_enabled(custom, egui::Button::new(crate::i18n::tr("Use Library Folder")));+ register(ui, "button:settingsSmartReset", r.rect);+ if r.clicked() {+ result = Some(app.run("library.smartPreviewsLocation", json!({"reset": true, "existing": existing})));+ }+ });+ if let Some(r) = result {+ ui.data_mut(|d| d.remove::<(f64, Value)>(cache));+ match r {+ Ok(v) => {+ let failed = v["failed"].as_array().map_or(0, Vec::len);+ let msg = match (existing, v["handled"].as_u64().unwrap_or(0)) {+ (_, 0) => "Smart previews folder changed".to_string(),+ ("move", n) => format!("Smart previews folder changed; moved {n}"),+ ("discard", n) => format!("Smart previews folder changed; deleted {n}"),+ _ => "Smart previews folder changed".to_string(),+ };+ app.toast(ui.ctx(), if failed > 0 { crate::i18n::tr_format!("{msg} ({failed} failed)", failed = failed, msg = msg) } else { msg });+ }+ Err(e) => app.toast(ui.ctx(), e),+ }+ }+ hint(ui, t, crate::i18n::tr("Keep it on a drive with room: smart previews are about 1 MB per photo. The thumbnail cache stays in the library."));+ }