diff --git a/Cargo.lock b/Cargo.lock index acd433bc27b..775307b0aff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3589,6 +3589,7 @@ dependencies = [ name = "lightcraft" version = "0.18.0" dependencies = [ + "block2 0.6.2", "chrono", "craft-update", "eframe", diff --git a/Cargo.toml b/Cargo.toml index 8549d6167e4..69f36c54a1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -113,8 +113,10 @@ rfd = "0.17" muda = { version = "0.21", default-features = false } # native menu bar (macOS: objc2/AppKit, pure Rust; no GTK) # macOS: the profile of the screen showing the window (safe AppKit bindings; muda and wgpu use the same) objc2 = { version = "0.6", default-features = false, features = ["std"] } -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSColorSpace", "NSResponder", "NSScreen", "NSWindow"] } -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSColorSpace", "NSDockTile", "NSResponder", "NSScreen", "NSWindow"] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSProcessInfo", "NSString"] } +# macOS: the block `NSProcessInfo` runs while a job holds the Mac awake (the version objc2-foundation already uses) +block2 = { version = "0.6", default-features = false, features = ["std"] } # Linux: the desktop's dark/light setting from the XDG settings portal (Settings ▸ Interface ▸ # Appearance Mode ▸ Auto). Pure Rust; the version accesskit already brings in, pinned to it. zbus = "=5.19.0" diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 79773918b47..56d21b18ba3 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -334,6 +334,8 @@ fn services( pick_folder: None, // the browser reports prefers-color-scheme to egui system_theme: None, + keep_awake: None, + dock_badge: None, } } diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index cf8aaf2e067..afd108711a2 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -51,6 +51,7 @@ muda = { workspace = true } objc2 = { workspace = true } objc2-app-kit = { workspace = true } objc2-foundation = { workspace = true } +block2 = { workspace = true } [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) diff --git a/apps/lightcraft/src/dock_badge.rs b/apps/lightcraft/src/dock_badge.rs new file mode 100644 index 00000000000..61891877b7e --- /dev/null +++ b/apps/lightcraft/src/dock_badge.rs @@ -0,0 +1,42 @@ +//! The number of running jobs on the Dock icon (macOS). +//! +//! The UI says how many jobs the person started are running (`Services::dock_badge`, from +//! `Activity::running_jobs`); this shows it as the badge of the app's Dock tile, and clears it at zero, so an +//! export in a minimized window can be seen from the Dock. A badge is text on the icon: `NSDockTile` has no safe +//! drawing path for a progress bar without a custom view, and the badge needs no `unsafe`. + +use objc2::MainThreadMarker; +use objc2_app_kit::NSApplication; +use objc2_foundation::NSString; + +/// The text of the badge for `running` jobs: nothing at zero. +pub fn label(running: usize) -> Option { + (running > 0).then(|| running.to_string()) +} + +/// Show `running` on the Dock icon. AppKit is main-thread only: from another thread nothing is shown. +pub fn show(running: usize) { + let Some(mtm) = MainThreadMarker::new() else { return }; + let tile = NSApplication::sharedApplication(mtm).dockTile(); + match label(running) { + Some(text) => tile.setBadgeLabel(Some(&NSString::from_str(&text))), + None => tile.setBadgeLabel(None), + } +} + +/// The host service for `Services::dock_badge`. +pub fn service() -> lightcraft_ui_egui::DockBadgeFn { + Box::new(show) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_badge_is_the_count_and_empty_when_idle() { + assert_eq!(label(0), None); + assert_eq!(label(1).as_deref(), Some("1")); + assert_eq!(label(12).as_deref(), Some("12")); + } +} diff --git a/apps/lightcraft/src/keep_awake.rs b/apps/lightcraft/src/keep_awake.rs new file mode 100644 index 00000000000..a67033fab24 --- /dev/null +++ b/apps/lightcraft/src/keep_awake.rs @@ -0,0 +1,111 @@ +//! Keep running while a long job does (macOS). +//! +//! While an export, import or other job the person started is in flight, macOS must neither put the Mac to idle +//! sleep nor App-Nap the window: a minimized or hidden app is throttled, and a long export of a library on a share +//! stalls. The UI says when that changes (`Services::keep_awake`, from `Activity::wake_reason`); this holds the +//! matching `NSProcessInfo` activity (user initiated, idle system sleep disabled) whose reason names the job, which +//! `pmset -g assertions` then shows. +//! +//! The activity is held with `performActivityWithOptions:reason:usingBlock:`, which is safe to call: a helper thread +//! sits inside the block until its [`Hold`] is dropped, and AppKit ends the activity when the block returns. +//! `beginActivityWithOptions:reason:` would need `endActivity:`, an `unsafe` method, and this crate forbids `unsafe`. +//! Activities belong to the process, not to the thread that began them. + +use std::sync::{Arc, Mutex, PoisonError, mpsc}; + +use block2::RcBlock; +use objc2_foundation::{NSActivityOptions, NSProcessInfo, NSString}; + +/// A running activity: dropping it ends it. +pub struct Hold { + /// The helper thread waits for this to disconnect. + _release: mpsc::Sender<()>, +} + +/// Begin an activity named `reason`. `previous` ends only once this one has begun, so the Mac is never left +/// unprotected when the job named in the reason changes. If the helper thread can't start, `previous` is returned +/// still held (the Mac stays protected, under the old reason), or `None` when there was none. +pub fn begin(reason: &str, previous: Option) -> Option { + let (release, wait) = mpsc::channel::<()>(); + let reason = reason.to_owned(); + // shared with the thread so that a thread that never starts leaves it here + let previous = Arc::new(Mutex::new(previous)); + let handed = previous.clone(); + let spawned = std::thread::Builder::new().name("keep-awake".into()).spawn(move || { + // (an `NSString` is not `Send`: made here) + let reason = NSString::from_str(&reason); + let held = RcBlock::new(move || { + // begun: the one before it can go + drop(handed.lock().unwrap_or_else(PoisonError::into_inner).take()); + // (Err: the hold was dropped, which is the end) + let _ = wait.recv(); + }); + NSProcessInfo::processInfo().performActivityWithOptions_reason_usingBlock( + NSActivityOptions::UserInitiated | NSActivityOptions::IdleSystemSleepDisabled, + &reason, + &held, + ); + }); + match spawned { + Ok(_) => Some(Hold { _release: release }), + Err(e) => { + log::warn!("could not keep the Mac awake for a running job: {e}"); + previous.lock().unwrap_or_else(PoisonError::into_inner).take() + } + } +} + +/// The host service: holds one activity while the UI says a job needs it. +pub fn service() -> lightcraft_ui_egui::KeepAwakeFn { + let mut hold: Option = None; + Box::new(move |reason| { + hold = match reason { + Some(reason) => begin(reason, hold.take()), + None => None, + }; + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + fn assertions() -> String { + let out = std::process::Command::new("pmset").args(["-g", "assertions"]).output().expect("pmset runs"); + String::from_utf8_lossy(&out.stdout).into_owned() + } + + fn wait_for(reason: &str, present: bool) -> bool { + let t0 = Instant::now(); + while t0.elapsed() < Duration::from_secs(10) { + if assertions().contains(reason) == present { + return true; + } + std::thread::sleep(Duration::from_millis(100)); + } + false + } + + #[test] + fn a_hold_shows_in_the_power_assertions_until_it_is_dropped() { + let reason = format!("LightCraft test hold {}", std::process::id()); + let hold = begin(&reason, None).expect("the helper thread starts"); + assert!(wait_for(&reason, true), "pmset lists the activity while the hold lives"); + drop(hold); + assert!(wait_for(&reason, false), "pmset stops listing it once the hold is dropped"); + } + + #[test] + fn a_new_reason_replaces_the_old_one() { + let first = format!("LightCraft first hold {}", std::process::id()); + let second = format!("LightCraft second hold {}", std::process::id()); + let a = begin(&first, None); + assert!(wait_for(&first, true)); + let b = begin(&second, a); + assert!(wait_for(&second, true)); + assert!(wait_for(&first, false), "the earlier one ends once the later one has begun"); + drop(b); + assert!(wait_for(&second, false)); + } +} diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 3a7bda66960..e645544b800 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -30,8 +30,12 @@ mod appearance; mod colord; mod control_server; mod dialog_filter; +#[cfg(target_os = "macos")] +mod dock_badge; mod editors; mod hdr_display; +#[cfg(target_os = "macos")] +mod keep_awake; mod logging; #[cfg(target_os = "macos")] mod native_menu; diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index c02ce47a1e0..9ab25914f8c 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -150,6 +150,16 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std:: screen_profile: win_screen_profile::service(cc), #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] screen_profile: None, + // macOS: a running job keeps the Mac awake and the window out of App Nap + #[cfg(target_os = "macos")] + keep_awake: Some(keep_awake::service()), + #[cfg(not(target_os = "macos"))] + keep_awake: None, + // macOS: the number of running jobs on the Dock icon + #[cfg(target_os = "macos")] + dock_badge: Some(dock_badge::service()), + #[cfg(not(target_os = "macos"))] + dock_badge: None, pick_display_profile: Some(Box::new(|| { let mut d = file_dialog() .set_title(lightcraft_ui_egui::i18n::tr("Choose Monitor Profile")) diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 147d20f3a58..6f1ac5cc0e3 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -217,6 +217,34 @@ impl Activity { pub fn running_cancellable(&self) -> Vec { lock(&self.inner.tasks).iter().filter(|e| e.is_cancellable() && !e.is_cancelled()).map(|e| e.info()).collect() } + + /// Why the machine should stay awake for the work in flight, or `None` when nothing needs it: the label of the + /// oldest job the person started, with `+ N more` when others run too. A job asked to stop no longer counts, and + /// neither does housekeeping the person did not ask for ([`started_by_person`]). The label is English: it is for + /// the system's logs and tools (`pmset -g assertions`), not for the window. + pub fn wake_reason(&self) -> Option { + let tasks = lock(&self.inner.tasks); + let mut holding = tasks.iter().filter(|e| started_by_person(e.kind) && !e.is_cancelled()); + let first = holding.next()?; + Some(match holding.count() { + 0 => first.label.clone(), + more => format!("{} + {more} more", first.label), + }) + } + + /// How many jobs the person started are running, for the Dock badge. A job asked to stop still counts until it + /// has stopped (it is still running); housekeeping the person did not ask for does not ([`started_by_person`]). + pub fn running_jobs(&self) -> usize { + lock(&self.inner.tasks).iter().filter(|e| started_by_person(e.kind)).count() + } +} + +/// Whether a task of `kind` is work the person started, one they would not want cut short by the machine sleeping +/// and would want counted in the Dock. The thumbnail cache tidy, the GPU check, the focus-point reading, the face +/// scan and the checks of recent libraries and of raw files start by themselves (and the first can hang on an +/// offline share). +fn started_by_person(kind: &str) -> bool { + !matches!(kind, "cache" | "facesGpu" | "focus" | "faces" | "library" | "recheck") } /// A task's place in the list, held by whoever owns the job; dropping it removes the row. @@ -303,6 +331,110 @@ impl TaskHandle { } } +#[cfg(test)] +mod wake_tests { + use super::*; + + #[test] + fn nothing_running_needs_no_wake() { + assert_eq!(Activity::default().wake_reason(), None); + } + + #[test] + fn a_running_export_names_itself() { + let a = Activity::default(); + let _g = a.start("export", "Exporting", Cancel::Yes); + assert_eq!(a.wake_reason().as_deref(), Some("Exporting")); + } + + #[test] + fn housekeeping_the_person_did_not_ask_for_does_not_count() { + let a = Activity::default(); + let _c = a.start("cache", "Tidying the thumbnail cache", Cancel::Yes); + let _f = a.start("facesGpu", "Checking the GPU for faces", Cancel::No); + let _s = a.start("faces", "Finding faces", Cancel::No); + let _p = a.start("focus", "Reading focus points", Cancel::Yes); + let _l = a.start("library", "Checking recent libraries", Cancel::No); + let _r = a.start("recheck", "Checking raw files", Cancel::Yes); + assert_eq!(a.wake_reason(), None); + let _e = a.start("import", "Importing", Cancel::Yes); + assert_eq!(a.wake_reason().as_deref(), Some("Importing")); + } + + #[test] + fn several_jobs_name_the_oldest_and_count_the_rest() { + let a = Activity::default(); + let _x = a.start("export", "Exporting", Cancel::Yes); + let _c = a.start("cache", "Tidying the thumbnail cache", Cancel::Yes); + let _i = a.start("import", "Importing", Cancel::Yes); + let _p = a.start("previews", "Building previews", Cancel::Yes); + assert_eq!(a.wake_reason().as_deref(), Some("Exporting + 2 more")); + } + + #[test] + fn the_hold_ends_when_the_last_job_ends() { + let a = Activity::default(); + let x = a.start("export", "Exporting", Cancel::Yes); + let i = a.start("import", "Importing", Cancel::Yes); + drop(x); + assert_eq!(a.wake_reason().as_deref(), Some("Importing")); + drop(i); + assert_eq!(a.wake_reason(), None); + } + + #[test] + fn a_job_that_was_asked_to_stop_no_longer_holds() { + let a = Activity::default(); + let x = a.start("export", "Exporting", Cancel::Yes); + a.cancel(x.id()).unwrap(); + assert_eq!(a.wake_reason(), None); + } +} + +#[cfg(test)] +mod running_jobs_tests { + use super::*; + + #[test] + fn nothing_running_counts_zero() { + assert_eq!(Activity::default().running_jobs(), 0); + } + + #[test] + fn each_job_the_person_started_counts_once() { + let a = Activity::default(); + let _x = a.start("export", "Exporting", Cancel::Yes); + assert_eq!(a.running_jobs(), 1); + let _i = a.start("import", "Importing", Cancel::Yes); + let _p = a.start("previews", "Building previews", Cancel::Yes); + assert_eq!(a.running_jobs(), 3); + } + + #[test] + fn housekeeping_the_person_did_not_ask_for_does_not_count() { + let a = Activity::default(); + let _c = a.start("cache", "Tidying the thumbnail cache", Cancel::Yes); + let _g = a.start("facesGpu", "Checking the GPU for faces", Cancel::No); + let _f = a.start("faces", "Finding faces", Cancel::No); + let _p = a.start("focus", "Reading focus points", Cancel::Yes); + let _l = a.start("library", "Checking recent libraries", Cancel::No); + let _r = a.start("recheck", "Checking raw files", Cancel::Yes); + assert_eq!(a.running_jobs(), 0); + let _e = a.start("import", "Importing", Cancel::Yes); + assert_eq!(a.running_jobs(), 1, "a job the person started still counts beside the housekeeping"); + } + + #[test] + fn a_job_still_stopping_counts_until_it_ends() { + let a = Activity::default(); + let x = a.start("export", "Exporting", Cancel::Yes); + a.cancel(x.id()).unwrap(); + assert_eq!(a.running_jobs(), 1); + drop(x); + assert_eq!(a.running_jobs(), 0); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 74425972d80..80a5d0e1843 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -137,6 +137,8 @@ impl LightcraftApp { display_error: None, screen_profile: None, screen_profile_read: None, + awake_told: None, + badge_told: 0, library_problem: None, library_window_input: Default::default(), alt_asks_for_library: false, @@ -610,6 +612,8 @@ impl LightcraftApp { /// on other threads (export, denoise, the device warm-up). `false`: the deadline passed first /// (the host exits anyway). The app renders nothing afterwards. pub fn shutdown(&mut self, timeout: std::time::Duration) -> bool { + self.release_keep_awake(); + self.release_dock_badge(); lightcraft_engine::gpu::begin_shutdown(); #[cfg(not(target_arch = "wasm32"))] let t0 = std::time::Instant::now(); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 66e377a9138..4cac80f4e74 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -59,11 +59,67 @@ impl LightcraftApp { } } + /// Tell the host what should keep the machine awake (`services.keep_awake`), when that changes. While a job + /// holds, a repaint is asked for every second so its end is noticed (and the hold released) even when nothing + /// else is drawn. Once the app is shutting down the hold is gone for good ([`LightcraftApp::release_keep_awake`]). + pub(super) fn sync_keep_awake(&mut self, ctx: &egui::Context) { + if lightcraft_engine::gpu::shutting_down() { + return; + } + let Some(keep_awake) = self.services.keep_awake.as_mut() else { return }; + let reason = self.session.activity.wake_reason(); + if reason.is_some() { + ctx.request_repaint_after(std::time::Duration::from_secs(1)); + } + if reason != self.awake_told { + keep_awake(reason.as_deref()); + self.awake_told = reason; + } + } + + /// Let go of the hold the host was told about, if any (quitting). + pub(super) fn release_keep_awake(&mut self) { + if let Some(keep_awake) = self.services.keep_awake.as_mut() + && self.awake_told.take().is_some() + { + keep_awake(None); + } + } + + /// Tell the host how many jobs are running (`services.dock_badge`), when that changes. A job still stopping counts + /// until it has stopped, so the count is also looked at every second while it is above zero. Once the app is + /// shutting down the badge is gone for good ([`LightcraftApp::release_dock_badge`]). + pub(super) fn sync_dock_badge(&mut self, ctx: &egui::Context) { + if lightcraft_engine::gpu::shutting_down() { + return; + } + let Some(dock_badge) = self.services.dock_badge.as_mut() else { return }; + let running = self.session.activity.running_jobs(); + if running > 0 { + ctx.request_repaint_after(std::time::Duration::from_secs(1)); + } + if running != self.badge_told { + dock_badge(running); + self.badge_told = running; + } + } + + /// Clear the badge the host was told about, if any (quitting). + pub(super) fn release_dock_badge(&mut self) { + if let Some(dock_badge) = self.services.dock_badge.as_mut() + && std::mem::take(&mut self.badge_told) != 0 + { + dock_badge(0); + } + } + /// Queues and timers. Each consumed queue is drained once per call; time-gated work uses the /// monotonic app clock, so a hidden `run_logic` keeps it advancing and a second layout pass is /// a no-op rather than a duplicate. pub(super) fn logic_background(&mut self, ctx: &egui::Context) { self.background_prep(ctx); + self.sync_dock_badge(ctx); + self.sync_keep_awake(ctx); panels::notices::logic(self, ctx); // closing the window (or Quit) with changes only in memory: retry, else ask first if ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) { @@ -520,3 +576,77 @@ impl LightcraftApp { pub(crate) fn import_tick_allowed(ctx: &egui::Context) -> bool { ctx.current_pass_index() == 0 } + +#[cfg(test)] +mod keep_awake_tests { + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use crate::Services; + use lightcraft_engine::activity::Cancel; + + use super::*; + + /// A context that records every delay it is asked to repaint after. + fn recording_context() -> (egui::Context, Arc>>) { + let ctx = egui::Context::default(); + let asked = Arc::new(Mutex::new(Vec::new())); + let sink = asked.clone(); + ctx.set_request_repaint_callback(move |info| sink.lock().unwrap().push(info.delay)); + (ctx, asked) + } + + fn app_with_keep_awake() -> LightcraftApp { + let keep_awake: crate::KeepAwakeFn = Box::new(|_| {}); + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, keep_awake: Some(keep_awake), ..Default::default() }) + } + + #[test] + fn a_holding_job_asks_for_a_repaint_within_a_second_and_an_idle_app_asks_for_none() { + let (ctx, asked) = recording_context(); + let mut app = app_with_keep_awake(); + app.sync_keep_awake(&ctx); + assert!(asked.lock().unwrap().is_empty(), "nothing runs: no repaint is asked for"); + + let _job = app.session.activity.start("export", "Exporting", Cancel::Yes); + app.sync_keep_awake(&ctx); + assert_eq!(*asked.lock().unwrap(), [Duration::from_secs(1)], "the end of the job is looked for every second"); + } + + fn app_with_dock_badge() -> (LightcraftApp, Arc>>) { + let told = Arc::new(Mutex::new(Vec::new())); + let sink = told.clone(); + let dock_badge: crate::DockBadgeFn = Box::new(move |n| sink.lock().unwrap().push(n)); + let app = + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, dock_badge: Some(dock_badge), ..Default::default() }); + (app, told) + } + + #[test] + fn a_running_job_asks_for_a_repaint_within_a_second_until_it_has_stopped() { + let (ctx, asked) = recording_context(); + let (mut app, told) = app_with_dock_badge(); + app.sync_dock_badge(&ctx); + assert!(asked.lock().unwrap().is_empty(), "nothing runs: no repaint is asked for"); + assert!(told.lock().unwrap().is_empty(), "nothing runs: the host is told nothing"); + + let job = app.session.activity.start("export", "Exporting", Cancel::Yes); + app.sync_dock_badge(&ctx); + assert_eq!(*asked.lock().unwrap(), [Duration::from_secs(1)], "the end of the job is looked for every second"); + assert_eq!(*told.lock().unwrap(), [1]); + + // asked to stop, a job still counts, so the count is still looked at (a fresh context: egui asks its host + // again only for a delay shorter than the one still pending) + let (ctx, asked) = recording_context(); + app.session.activity.cancel(job.id()).unwrap(); + app.sync_dock_badge(&ctx); + assert_eq!(*asked.lock().unwrap(), [Duration::from_secs(1)], "a job still stopping is still looked for every second"); + assert_eq!(*told.lock().unwrap(), [1], "the count did not change: the host is not told again"); + + let (ctx, asked) = recording_context(); + drop(job); + app.sync_dock_badge(&ctx); + assert!(asked.lock().unwrap().is_empty(), "nothing runs any more: no repaint is asked for"); + assert_eq!(*told.lock().unwrap(), [1, 0]); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1b34105562..d6ca913ba2b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -102,8 +102,8 @@ pub use clock::{monotonic_ms, now_ms}; #[cfg(target_os = "linux")] pub use services::OpenModelFolderFn; pub use services::{ - CheckEditorFn, HostAction, OpenAllWithFn, OpenUrlFn, OpenWithFn, PickFiles, PickFolder, PngEncode, RevealFn, SaveFile, ScreenProfileFn, Services, - SharedWrite, SystemThemeFn, WriteFn, + CheckEditorFn, DockBadgeFn, HostAction, KeepAwakeFn, OpenAllWithFn, OpenUrlFn, OpenWithFn, PickFiles, PickFolder, PngEncode, RevealFn, SaveFile, + ScreenProfileFn, Services, SharedWrite, SystemThemeFn, WriteFn, }; use state::{GestureFrame, InjectedPress}; @@ -385,6 +385,10 @@ pub struct LightcraftApp { /// and when it was last read (egui time, s). pub(crate) screen_profile: Option>, pub(crate) screen_profile_read: Option, + /// What the host was last told keeps the machine awake (`services.keep_awake`): the reason, or `None` for idle. + pub(crate) awake_told: Option, + /// The job count the host was last told for the Dock badge (`services.dock_badge`). + pub(crate) badge_told: usize, /// The library failed to open at launch: the blocking window, then the temporary-session /// banner (issue #100). Cleared once a library opens. pub library_problem: Option, diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 695a9d7d6de..9f004eac453 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -35,6 +35,14 @@ pub type OpenModelFolderFn = std::sync::Arc Result<(), String> + /// not known). pub type ScreenProfileFn = Box Option>>; +/// Told when the work that should keep the machine awake changes: `Some(reason)` while a job the person started runs +/// (the reason names it), `None` once nothing needs it. Called only on a change, always from the UI thread. +pub type KeepAwakeFn = Box)>; + +/// Told how many jobs the person started are running, for the Dock badge: the count, `0` once none is. Called only on +/// a change, always from the UI thread. +pub type DockBadgeFn = Box; + /// Whether an external editor can be started (its name as in [`Services::open_with`]); the /// error says why not and what to do (e.g. PhotoCraft isn't installed). pub type CheckEditorFn = Box Result<(), String>>; @@ -130,4 +138,8 @@ pub struct Services { pub restore_library: Option, /// The system appearance for Appearance Mode ▸ Auto, ahead of egui's own report. pub system_theme: Option, + /// Keep the system from sleeping or throttling the app while a long job runs (macOS App Nap and idle sleep). + pub keep_awake: Option, + /// Show how many jobs are running on the app's Dock icon (macOS). + pub dock_badge: Option, } diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index b353405ffca..9d398adb49b 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -591,3 +591,105 @@ fn immediate_library_commands_and_auto_sync_show_completion() { assert!(h.app.run("library.compact", json!({})).is_err()); assert!(h.app.ui.toast.is_none()); } + +/// What `services.keep_awake` was told, in order. +type Told = std::rc::Rc>>>; + +fn demo_keeping_awake() -> (Headless, Told) { + let told = Told::default(); + let sink = told.clone(); + let keep_awake: crate::KeepAwakeFn = Box::new(move |reason| sink.borrow_mut().push(reason.map(str::to_owned))); + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, keep_awake: Some(keep_awake), ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + h.settle(T); + told.borrow_mut().clear(); + (h, told) +} + +#[test] +fn a_running_job_is_told_to_the_host_once_and_its_end_too() { + let (mut h, told) = demo_keeping_awake(); + for _ in 0..3 { + h.step(); + } + assert!(told.borrow().is_empty(), "nothing runs: the host hears nothing"); + + let g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + for _ in 0..4 { + h.step(); + } + assert_eq!(*told.borrow(), [Some("Exporting".to_string())], "told once, not on every frame"); + + drop(g); + for _ in 0..4 { + h.step(); + } + assert_eq!(*told.borrow(), [Some("Exporting".to_string()), None]); +} + +#[test] +fn a_cancelled_job_is_released_before_it_stops() { + let (mut h, told) = demo_keeping_awake(); + let g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + h.step(); + h.app.session.activity.cancel(g.id()).unwrap(); + h.step(); + assert_eq!(*told.borrow(), [Some("Exporting".to_string()), None]); +} + +#[test] +fn a_window_with_no_host_service_ignores_jobs() { + let mut h = demo(); + let _g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + h.step(); + assert_eq!(h.app.awake_told, None); +} + +/// What `services.dock_badge` was told, in order. +type Badges = std::rc::Rc>>; + +fn demo_with_dock_badge() -> (Headless, Badges) { + let badges = Badges::default(); + let sink = badges.clone(); + let dock_badge: crate::DockBadgeFn = Box::new(move |count| sink.borrow_mut().push(count)); + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, dock_badge: Some(dock_badge), ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + h.settle(T); + badges.borrow_mut().clear(); + (h, badges) +} + +#[test] +fn the_dock_badge_follows_the_number_of_running_jobs_and_clears_when_idle() { + let (mut h, badges) = demo_with_dock_badge(); + for _ in 0..3 { + h.step(); + } + assert!(badges.borrow().is_empty(), "nothing runs: the host hears nothing"); + + let export = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + h.step(); + let import = h.app.session.activity.start("import", "Importing", Cancel::Yes); + h.step(); + h.step(); + assert_eq!(*badges.borrow(), [1, 2], "told on each change, not on every frame"); + + drop(export); + h.step(); + drop(import); + h.step(); + assert_eq!(*badges.borrow(), [1, 2, 1, 0]); +} + +#[test] +fn a_job_asked_to_stop_stays_in_the_dock_count_until_it_has_stopped() { + let (mut h, badges) = demo_with_dock_badge(); + let g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + h.step(); + h.app.session.activity.cancel(g.id()).unwrap(); + h.step(); + assert_eq!(*badges.borrow(), [1]); + drop(g); + h.step(); + assert_eq!(*badges.borrow(), [1, 0]); +} diff --git a/crates/ui-egui/tests/shutdown.rs b/crates/ui-egui/tests/shutdown.rs index 1a601bc78f3..6c077b0eddb 100644 --- a/crates/ui-egui/tests/shutdown.rs +++ b/crates/ui-egui/tests/shutdown.rs @@ -10,7 +10,14 @@ use lightcraft_ui_egui::{LightcraftApp, Services}; #[test] fn shutdown_leaves_no_render_worker_running() { - let services = Services { png: None, ..Default::default() }; + // what the host was told about jobs holding the machine awake + let told = std::rc::Rc::new(std::cell::RefCell::new(Vec::>::new())); + let sink = told.clone(); + let keep_awake: lightcraft_ui_egui::KeepAwakeFn = Box::new(move |reason| sink.borrow_mut().push(reason.map(str::to_owned))); + let badges = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); + let badge_sink = badges.clone(); + let dock_badge: lightcraft_ui_egui::DockBadgeFn = Box::new(move |count| badge_sink.borrow_mut().push(count)); + let services = Services { png: None, keep_awake: Some(keep_awake), dock_badge: Some(dock_badge), ..Default::default() }; let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1200.0, 760.0], 1.0); // frames until the grid's thumbnails are being rendered on the workers let t0 = Instant::now(); @@ -19,8 +26,15 @@ fn shutdown_leaves_no_render_worker_running() { h.step(); } assert!(!lightcraft_engine::gpu::shutting_down()); + // a job is running when the app quits: the hold on the machine ends with it + let _job = h.app.session.activity.start("export", "Exporting", lightcraft_engine::activity::Cancel::Yes); + h.step(); + assert_eq!(told.borrow().last(), Some(&Some("Exporting".to_string()))); + assert_eq!(badges.borrow().last(), Some(&1)); assert!(h.app.shutdown(Duration::from_secs(120)), "the jobs that were running ended in time"); + assert_eq!(told.borrow().last(), Some(&None), "quitting lets go of the hold"); + assert_eq!(badges.borrow().last(), Some(&0), "quitting clears the Dock badge"); assert_eq!(h.app.renderer.live_workers(), 0); assert_eq!(h.app.renderer.queued(), 0, "jobs that had not started are dropped"); assert!(lightcraft_engine::gpu::shutting_down()); @@ -30,6 +44,8 @@ fn shutdown_leaves_no_render_worker_running() { for _ in 0..3 { h.step(); } + assert_eq!(told.borrow().last(), Some(&None), "the job still runs, but the window does not take the hold again"); + assert_eq!(badges.borrow().last(), Some(&0), "nor the badge"); assert_eq!(h.app.renderer.live_workers(), 0); assert_eq!(h.app.renderer.queued(), 0); diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 6f2b0034772..dd7dbcbd9f1 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -6,6 +6,17 @@ the amount of work isn't known), the count and what it's working on, and ✕ if a task that can stop is running. Agents see the same list through `activity.list` / `activity.cancel`, and `ui.inspect` reports it as `activity`. +On macOS a running job the person started also keeps the Mac awake: `Activity::wake_reason` names the oldest such job +(housekeeping that starts by itself doesn't count: the thumbnail-cache tidy, the GPU check, the focus-point reading, +the face scan and the checks of recent libraries and of raw files; neither does a job that was asked to stop), the UI tells +the host when that changes (`Services::keep_awake`), and the app holds an `NSProcessInfo` activity (user initiated, +idle system sleep disabled) with that reason until the last job ends, is cancelled or the app quits. +`pmset -g assertions` lists it. A new `kind` that is background housekeeping rather than something the person asked for +goes in `started_by_person` in `activity.rs`, which also decides what the Dock badge counts. + +On macOS the Dock icon carries a badge with the number of running jobs the person started (`Activity::running_jobs`, +`Services::dock_badge`), cleared when none is left. A job that was asked to stop counts until it has stopped. + The registry is `lightcraft_engine::activity` (`crates/engine/src/activity.rs`, `Session::activity`). The stack is `crates/ui-egui/src/panels/activity.rs`. Every job that can last more than a moment uses it; **don't add a progress window, panel or progress toast of your own**. A dialog may still show progress inline (the Synchronize Folder diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index cf6ab0de745..3d6bdee3852 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -463,7 +463,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | -| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | +| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`), `apps/lightcraft/src/keep_awake.rs`, `apps/lightcraft/src/dock_badge.rs` | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list; on macOS a running job the person started holds an `NSProcessInfo` activity (no idle sleep, no App Nap) until the last one ends or is cancelled, and the Dock icon's badge counts the running jobs until none is left. No pause (Lightroom can pause some tasks) | | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | @@ -802,6 +802,8 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | LR-BEHAV-BG-TASKS: on macOS a running job the person started (export, import, preview build, merge, Synchronize Folder…) keeps the Mac from idle sleep and the app out of App Nap until the last one ends or is cancelled; status unchanged (✅) | +| 2026-10-27 | minor | LR-BEHAV-BG-TASKS: on macOS the Dock icon carries a badge with the number of running jobs the person started, cleared when none is left; status unchanged (✅) | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | diff --git a/docs/whats-new.md b/docs/whats-new.md index ab0f90c0338..3e46dc21984 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -38,6 +38,15 @@ process 5: new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update to Current Process. See [process versions](process-versions.md). +### On macOS, a long job keeps the Mac awake +- While an export, import, preview build, merge or other job you started is running, the Mac no longer goes to sleep + on its own and macOS no longer slows the app down when its window is hidden or minimized. Both end as soon as the + last job finishes or is canceled. + +### On macOS, the Dock icon shows how many jobs are running +- The Dock icon of LightCraft carries a badge with the number of jobs you started that are running (an export, an + import, a preview build…). It goes away when the last one ends, so a job in a minimized window can still be seen. + ## 2026-11-02 ### The Windows title bar is readable from the moment the window opens @@ -343,7 +352,6 @@ a second. On a Mac the window also holds one drawable less: its width × height × 4 bytes, 15–22 MB for a 1200–1500-point-wide window on a Retina display. - ## 2026-10-24 ### AI Denoise follows the photo's real noise