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
16 changes: 15 additions & 1 deletion Cargo.lock

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

8 changes: 6 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,12 @@ 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", "NSBundle", "NSData", "NSError", "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"] }
# macOS: system notifications when a job ends in the background (the same objc2 generation as objc2-app-kit)
objc2-user-notifications = { version = "0.3", default-features = false, features = ["std", "block2", "UNNotificationContent", "UNNotificationRequest", "UNNotificationTrigger", "UNUserNotificationCenter"] }
# 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
3 changes: 3 additions & 0 deletions apps/lightcraft-web/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,9 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
pick_folder: None,
// the browser reports prefers-color-scheme to egui
system_theme: None,
keep_awake: None,
dock_badge: None,
notify: None,
}
}

Expand Down
2 changes: 2 additions & 0 deletions apps/lightcraft/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ muda = { workspace = true }
objc2 = { workspace = true }
objc2-app-kit = { workspace = true }
objc2-foundation = { workspace = true }
block2 = { workspace = true }
objc2-user-notifications = { 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));
}
}
6 changes: 6 additions & 0 deletions apps/lightcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ 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;
#[cfg(target_os = "macos")]
mod notify;
#[cfg(target_os = "macos")]
mod screen_profile;
mod window_gpu;

Expand Down
90 changes: 90 additions & 0 deletions apps/lightcraft/src/notify.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//! System notifications for jobs that end while LightCraft is in the background (macOS).
//!
//! The UI decides when (`Services::notify`: a job the person started has ended while the window is not in front, and
//! Settings ▸ General ▸ Notifications is on). This shows it through `UNUserNotificationCenter`. The system asks the
//! person for permission the first time a notification is requested and remembers the answer; asking again later
//! returns that answer without a prompt, so every notification asks first and shows itself only when allowed.
//!
//! `UNUserNotificationCenter` needs an app bundle: in a process without a bundle identifier (a binary started from
//! a build folder, a test) it raises an Objective-C exception. Such a process shows nothing and says so once in the
//! log. All calls are safe API: the completion blocks get the system's error as a raw pointer, which is never read.

use std::sync::atomic::{AtomicU64, Ordering};

use block2::RcBlock;
use objc2::runtime::Bool;
use objc2_foundation::{NSBundle, NSError, NSString};
use objc2_user_notifications::{UNAuthorizationOptions, UNMutableNotificationContent, UNNotificationRequest, UNUserNotificationCenter};

use lightcraft_ui_egui::Notice;

/// Whether notifications can be shown from a process with this bundle identifier: only an app bundle has one.
fn can_notify(bundle_identifier: Option<&str>) -> bool {
bundle_identifier.is_some_and(|id| !id.is_empty())
}

/// Ask the system to show `notice`, once the person has allowed notifications from LightCraft.
fn post(notice: &Notice) {
let (title, body) = (notice.title.clone(), notice.body.clone());
// the system calls this on a queue of its own, with the person's answer
let answered = RcBlock::new(move |allowed: Bool, _error: *mut NSError| {
if allowed.as_bool() {
add(&title, &body);
} else {
log::info!("notifications from LightCraft are not allowed (System Settings ▸ Notifications)");
}
});
UNUserNotificationCenter::currentNotificationCenter().requestAuthorizationWithOptions_completionHandler(UNAuthorizationOptions::Alert, &answered);
}

/// Put the notification in the system's list: it is shown at once because it has no trigger.
fn add(title: &str, body: &str) {
static NEXT: AtomicU64 = AtomicU64::new(1);
let content = UNMutableNotificationContent::new();
content.setTitle(&NSString::from_str(title));
content.setBody(&NSString::from_str(body));
let id = NSString::from_str(&format!("ai.storyteller.lightcraft.job-{}", NEXT.fetch_add(1, Ordering::Relaxed)));
let request = UNNotificationRequest::requestWithIdentifier_content_trigger(&id, &content, None);
UNUserNotificationCenter::currentNotificationCenter().addNotificationRequest_withCompletionHandler(&request, None);
}

/// The host service for `Services::notify`.
pub fn service() -> lightcraft_ui_egui::NotifyFn {
// asked of the bundle once; None until the first notification
let mut available: Option<bool> = None;
Box::new(move |notice| {
let available = *available.get_or_insert_with(|| {
let id = NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string());
let ok = can_notify(id.as_deref());
if !ok {
log::info!("no notifications: this process is not an app bundle");
}
ok
});
if available {
post(notice);
}
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn only_a_process_with_a_bundle_identifier_can_notify() {
assert!(can_notify(Some("ai.storyteller.lightcraft")));
assert!(!can_notify(Some("")));
assert!(!can_notify(None));
}

#[test]
fn a_process_that_is_not_an_app_bundle_shows_nothing_and_does_not_crash() {
// the test binary has no bundle identifier: asking the notification center would raise an exception
assert_eq!(NSBundle::mainBundle().bundleIdentifier(), None);
let mut notify = service();
for _ in 0..2 {
notify(&Notice { title: "LightCraft".into(), body: "Exporting finished".into() });
}
}
}
15 changes: 15 additions & 0 deletions apps/lightcraft/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
screen_profile: Some(colord::service()),
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
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,
// macOS: a notification when a job ends while the window is in the background
#[cfg(target_os = "macos")]
notify: Some(notify::service()),
#[cfg(not(target_os = "macos"))]
notify: None,
pick_display_profile: Some(Box::new(|| {
let mut d = file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Choose Monitor Profile"))
Expand Down
Loading
Loading