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

Since the native menu bar (#894), Quit runs file.exit, which closes the window through eframe
while AppKit's run loop is still going. AppKit's Touch Bar finder then removes a KVO observer from
the already-deallocated view in the next display cycle (`-[_NSTouchBarFinderObservation
invalidate]`): an uncaught exception that aborts on macOS 27 (#1458) and leaves a windowless app
on macOS 26 (#1575). The window's close button took the same path before #894; ⌘Q used winit's
default menu, which calls terminate:.

Every way of leaving (Quit, ⌘Q, the close button, the OS quit event, app.quit) arrives at
guard_window_close as a close request. Once leaving is settled (nothing unsaved, or the prompt
answered) it now runs Services::quit when the platform has one, keeping the window open for it.
On macOS that is -[NSApplication terminate:], scheduled on the main queue so winit is out of its
event handler and eframe's exiting hook still saves the window layout.

Reproduced in a macOS 26.6.2 VM with XCUITest: on main, Quit, Quit with a document, ⌘Q and the
close button abort with the #1458 stack; with this change all of them exit, write no crash report
and save ui.ron.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Brennan StehlingandClaude Opus 5.5 authored and GitHub committed 2026-10-09 16:05:58 +07:00
1 parent a273d3b27d
commit 22ba13b47b
6 files changed
+88 -11

No files matched your search

Generated
+1
View File
@@ -3975,6 +3975,7 @@ dependencies = [
"arboard",
"async-io",
"core-graphics2",
"dispatch2",
"eframe",
"egui",
"fmv-macos-events",
+3
View File
@@ -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]
+26 -5
View File
@@ -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"),
});
}
+2
View File
@@ -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);
+49 -6
View File
@@ -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);
}
}
+7
View File
@@ -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