Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ muda = { version = "0.21", default-features = false } # native menu bar (macOS:
# 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-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"
Expand Down
1 change: 1 addition & 0 deletions apps/lightcraft-web/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ fn services(
pick_folder: None,
// the browser reports prefers-color-scheme to egui
system_theme: None,
keep_awake: None,
}
}

Expand Down
1 change: 1 addition & 0 deletions apps/lightcraft/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
111 changes: 111 additions & 0 deletions apps/lightcraft/src/keep_awake.rs
Original file line number Diff line number Diff line change
@@ -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<Hold>) -> Option<Hold> {
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<Hold> = 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));
}
}
2 changes: 2 additions & 0 deletions apps/lightcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ mod control_server;
mod dialog_filter;
mod editors;
mod hdr_display;
#[cfg(target_os = "macos")]
mod keep_awake;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
Expand Down
5 changes: 5 additions & 0 deletions apps/lightcraft/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ 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,
pick_display_profile: Some(Box::new(|| {
let mut d = file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Choose Monitor Profile"))
Expand Down
81 changes: 81 additions & 0 deletions crates/engine/src/activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,27 @@ impl Activity {
pub fn running_cancellable(&self) -> Vec<TaskInfo> {
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 ([`holds_awake`]). 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<String> {
let tasks = lock(&self.inner.tasks);
let mut holding = tasks.iter().filter(|e| holds_awake(e.kind) && !e.is_cancelled());
let first = holding.next()?;
Some(match holding.count() {
0 => first.label.clone(),
more => format!("{} + {more} more", first.label),
})
}
}

/// Whether a task of `kind` is work the person started and would not want cut short by the machine sleeping. 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 holds_awake(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.
Expand Down Expand Up @@ -303,6 +324,66 @@ 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 tests {
use super::*;
Expand Down
2 changes: 2 additions & 0 deletions crates/ui-egui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ impl LightcraftApp {
display_error: None,
screen_profile: None,
screen_profile_read: None,
awake_told: None,
library_problem: None,
library_window_input: Default::default(),
alt_asks_for_library: false,
Expand Down Expand Up @@ -610,6 +611,7 @@ 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();
lightcraft_engine::gpu::begin_shutdown();
#[cfg(not(target_arch = "wasm32"))]
let t0 = std::time::Instant::now();
Expand Down
65 changes: 65 additions & 0 deletions crates/ui-egui/src/app/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,39 @@ 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);
}
}

/// 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_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) {
Expand Down Expand Up @@ -520,3 +548,40 @@ 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<Mutex<Vec<Duration>>>) {
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");
}
}
6 changes: 4 additions & 2 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, HostAction, KeepAwakeFn, OpenAllWithFn, OpenUrlFn, OpenWithFn, PickFiles, PickFolder, PngEncode, RevealFn, SaveFile,
ScreenProfileFn, Services, SharedWrite, SystemThemeFn, WriteFn,
};
use state::{GestureFrame, InjectedPress};

Expand Down Expand Up @@ -385,6 +385,8 @@ pub struct LightcraftApp {
/// and when it was last read (egui time, s).
pub(crate) screen_profile: Option<Vec<u8>>,
pub(crate) screen_profile_read: Option<f64>,
/// What the host was last told keeps the machine awake (`services.keep_awake`): the reason, or `None` for idle.
pub(crate) awake_told: Option<String>,
/// 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<panels::library_problem::LibraryProblem>,
Expand Down
6 changes: 6 additions & 0 deletions crates/ui-egui/src/services.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ pub type OpenModelFolderFn = std::sync::Arc<dyn Fn(&str) -> Result<(), String> +
/// not known).
pub type ScreenProfileFn = Box<dyn FnMut() -> Option<Vec<u8>>>;

/// 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<dyn FnMut(Option<&str>)>;

/// 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<dyn Fn(&str) -> Result<(), String>>;
Expand Down Expand Up @@ -130,4 +134,6 @@ pub struct Services {
pub restore_library: Option<HostAction>,
/// The system appearance for Appearance Mode ▸ Auto, ahead of egui's own report.
pub system_theme: Option<SystemThemeFn>,
/// Keep the system from sleeping or throttling the app while a long job runs (macOS App Nap and idle sleep).
pub keep_awake: Option<KeepAwakeFn>,
}
Loading
Loading