Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

macOS: quit with terminate:, not by closing the window (#1575, #1458) (#1624)

Brennan Stehling22ba13b47bdf
diff --git a/Cargo.lock b/Cargo.lock
index 86dae6035..c9f9b0a87 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3975,6 +3975,7 @@ dependencies = [
"arboard",
"async-io",
"core-graphics2",
+ "dispatch2",
"eframe",
"egui",
"fmv-macos-events",
diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml
index a79bfe968..eb0907077 100644
--- a/apps/photocraft/Cargo.toml
+++ b/apps/photocraft/Cargo.toml
@@ -57,6 +57,9 @@ objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std
# The macOS menu bar (mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK
# with default features off). Pinned exactly: review the diff before bumping.
muda = { version = "=0.21.1", default-features = false }
+# Quit with `terminate:` from the main queue, outside winit's event handler (mac_window.rs).
+# Already in Cargo.lock (winit, objc2-app-kit); pinned exactly to the same version.
+dispatch2 = { version = "=0.3.1", default-features = false, features = ["std"] }
# Drop position on X11 (`cursor.rs`): pure-Rust X client, already in Cargo.lock; pinned exactly.
[target.'cfg(target_os = "linux")'.dependencies]
diff --git a/apps/photocraft/src/mac_window.rs b/apps/photocraft/src/mac_window.rs
index 073ec1593..491c7b283 100644
--- a/apps/photocraft/src/mac_window.rs
+++ b/apps/photocraft/src/mac_window.rs
@@ -1,9 +1,13 @@
-//! macOS title bar dragging. The window draws under a transparent title bar (`main.rs`), so AppKit
-//! would otherwise drag the window from anywhere in that strip, menus included: pressing a menu
-//! title and dragging down to an item moved the window instead. Turning AppKit's own dragging off
-//! leaves only the app's drag region (the free gap between the menus and the controls,
+//! macOS window lifecycle: title bar dragging and quitting.
+//!
+//! Dragging: the window draws under a transparent title bar (`main.rs`), so AppKit would
+//! otherwise drag the window from anywhere in that strip, menus included: pressing a menu title
+//! and dragging down to an item moved the window instead. Turning AppKit's own dragging off leaves
+//! only the app's drag region (the free gap between the menus and the controls,
//! `panels::title_bar`), which starts a drag explicitly (`ViewportCommand::StartDrag`, AppKit's
-//! `performWindowDragWithEvent:`, which works on an unmovable window). All safe objc2 calls.
+//! `performWindowDragWithEvent:`, which works on an unmovable window).
+//!
+//! Quitting: see [`terminate_later`]. All safe objc2 calls.
use objc2::MainThreadMarker;
use objc2_app_kit::NSApplication;
@@ -18,3 +22,20 @@ pub fn disable_native_title_drag() {
window.setMovable(false);
}
}
+
+/// Quit the way a Mac app does, with `-[NSApplication terminate:]` (`Services::quit`), instead of
+/// letting eframe close the window. eframe drops the window while AppKit's run loop is still
+/// running, and on Macs with a Touch Bar AppKit's next display cycle then tries to stop observing
+/// a view that is gone: an uncaught exception that crashes (macOS 27) or leaves a windowless app
+/// that only Force Quit ends (macOS 26) (#1458, #1575). `terminate:` ends the process before
+/// another display cycle runs; winit's `applicationWillTerminate:` closes the windows and has
+/// eframe save the window layout first, as the old ⌘Q (winit's default menu) did.
+///
+/// Scheduled on the main queue: winit has to be out of its event handler, or eframe's exit
+/// handling (and the save) is dropped.
+pub fn terminate_later() {
+ dispatch2::DispatchQueue::main().exec_async(|| match MainThreadMarker::new() {
+ Some(mtm) => NSApplication::sharedApplication(mtm).terminate(None),
+ None => log::warn!("quit: the main queue ran off the main thread; not terminating"),
+ });
+}
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index 1f98f6011..934983a8f 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -419,6 +419,8 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
{
app.services.os_events = Some(apple_events.connect(&cc.egui_ctx));
+ // Quit through AppKit, not by closing the window (Touch Bar Macs, #1575, #1458).
+ app.services.quit = Some(Box::new(mac_window::terminate_later));
// The macOS menu bar, installed now so winit's default menu doesn't stay up.
if !in_window_menus {
app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app);
diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs
index 708fa1b81..d20bae748 100644
--- a/crates/ui-egui/src/discard_ui.rs
+++ b/crates/ui-egui/src/discard_ui.rs
@@ -88,14 +88,23 @@ impl PhotocraftApp {
}
}
-/// Called once per frame: holds back a window close request while there is unsaved work.
+/// Called once per frame: holds back a window close request while there is unsaved work. Every
+/// way of leaving (File › Exit / Quit, the close button, the OS's quit event, `app.quit`) ends up
+/// here as a close request.
pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) {
- if app.allow_close || !ctx.input(|i| i.viewport().close_requested()) {
+ if !ctx.input(|i| i.viewport().close_requested()) {
return;
}
- if intercept(app, EXIT, &Value::Null) {
+ if !app.allow_close && intercept(app, EXIT, &Value::Null) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
+ return;
+ }
+ // Leaving: through the platform's own quit where there is one (see `Services::quit`), with
+ // the window left open for it to close.
+ if let Some(quit) = app.services.quit.as_mut() {
+ ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
+ quit();
}
}
@@ -516,15 +525,20 @@ mod tests {
assert!(h.state().session.documents().is_empty());
}
- /// One frame with the window's close button pressed; whether the guard cancelled the close.
- fn press_window_close(app: &mut PhotocraftApp) -> bool {
+ /// One frame with the window's close button pressed; the commands the guard sent.
+ fn window_close_commands(app: &mut PhotocraftApp) -> Vec<egui::ViewportCommand> {
let mut info = egui::ViewportInfo::default();
info.events.push(egui::ViewportEvent::Close);
let mut input = egui::RawInput::default();
input.viewports.insert(egui::ViewportId::ROOT, info);
let mut out = egui::Context::default().run_ui(input, |ui| guard_window_close(app, ui.ctx()));
out.textures_delta.clear();
- let commands = &out.viewport_output[&egui::ViewportId::ROOT].commands;
+ out.viewport_output.remove(&egui::ViewportId::ROOT).map(|o| o.commands).unwrap_or_default()
+ }
+
+ /// One frame with the window's close button pressed; whether the guard cancelled the close.
+ fn press_window_close(app: &mut PhotocraftApp) -> bool {
+ let commands = &window_close_commands(app);
let cancelled = commands.iter().any(|c| matches!(c, egui::ViewportCommand::CancelClose));
assert_eq!(commands.iter().any(|c| matches!(c, egui::ViewportCommand::Focus)), cancelled);
cancelled
@@ -557,4 +571,33 @@ mod tests {
assert!(!press_window_close(&mut app));
assert!(app.discard.is_none());
}
+
+ /// With a platform quit (macOS), leaving runs it and keeps the window open for it to close;
+ /// unsaved work still asks first.
+ #[test]
+ fn leaving_runs_the_platform_quit_instead_of_closing_the_window() {
+ use std::{cell::Cell, rc::Rc};
+ let quits = Rc::new(Cell::new(0));
+ let mut app = app_with_docs(1);
+ let counted = quits.clone();
+ app.services.quit = Some(Box::new(move || counted.set(counted.get() + 1)));
+ // The close is cancelled for the quit to do it, with no prompt brought forward.
+ let cancels_only = |c: &[egui::ViewportCommand]| {
+ c.iter().any(|c| matches!(c, egui::ViewportCommand::CancelClose)) && !c.iter().any(|c| matches!(c, egui::ViewportCommand::Focus))
+ };
+
+ assert!(cancels_only(&window_close_commands(&mut app)), "the window stays for the quit to close");
+ assert_eq!(quits.get(), 1);
+
+ make_dirty(&mut app, 0);
+ assert!(press_window_close(&mut app), "unsaved work asks first");
+ assert_eq!(quits.get(), 1, "no quit while the prompt is up");
+ assert!(app.discard.is_some());
+
+ // Don't Save: the prompt confirms, and the close it sends quits.
+ app.discard = None;
+ app.allow_close = true;
+ assert!(cancels_only(&window_close_commands(&mut app)));
+ assert_eq!(quits.get(), 2);
+ }
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 19c54c305..e157518e9 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -233,6 +233,8 @@ pub struct Recovered {
pub type AppendTextFn = Box<dyn FnMut(&str, &str) -> Result<(), String>>;
/// Requests from the operating system since the last call (see [`OsEvent`]).
pub type OsEventsFn = Box<dyn FnMut() -> Vec<OsEvent>>;
+/// Ends the app the platform's own way (see [`Services::quit`]).
+pub type QuitFn = Box<dyn FnMut()>;
/// Where the OS pointer is now, in egui points within the window; `None` when unknown.
pub type CursorPosFn = Box<dyn FnMut(&egui::Context) -> Option<egui::Pos2>>;
@@ -300,6 +302,11 @@ pub struct Services {
pub read_displays: Option<monitor_status::ReadDisplaysFn>,
/// The macOS menu bar, when the desktop app installed one; the in-window menus are hidden then.
pub native_menu: Option<native_menu::NativeMenu>,
+ /// Ends the app once leaving is settled (nothing unsaved, or the prompt answered), instead of
+ /// letting eframe close the window. macOS: `-[NSApplication terminate:]`. Closing the window
+ /// while AppKit's run loop is still going crashes or hangs Touch Bar Macs (#1575, #1458).
+ /// Without one, eframe closes the window and the app ends with it.
+ pub quit: Option<QuitFn>,
}
/// A document histogram being computed off the UI thread: (document, revision, receiver of