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.

6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 2 additions & 0 deletions apps/lightcraft-web/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

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
42 changes: 42 additions & 0 deletions apps/lightcraft/src/dock_badge.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
(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"));
}
}
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));
}
}
4 changes: 4 additions & 0 deletions apps/lightcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 10 additions & 0 deletions apps/lightcraft/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
132 changes: 132 additions & 0 deletions crates/engine/src/activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,34 @@ 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 ([`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<String> {
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")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// A task's place in the list, held by whoever owns the job; dropping it removes the row.
Expand Down Expand Up @@ -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::*;
Expand Down
4 changes: 4 additions & 0 deletions crates/ui-egui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading