From fac90f8a83020be608f71a7e73edc8d4c0285cc4 Mon Sep 17 00:00:00 2001 From: Taeha Kim Date: Fri, 20 Nov 2026 00:50:59 +0900 Subject: [PATCH] fix(macos,linux): isolate macOS Dock/close-quit lifecycle and Linux Wayland presentation --- CHANGELOG.md | 13 + README.md | 2 +- example/README.md | 2 +- lib/src/application.dart | 32 ++ .../platform/linux/linux_gtk_bindings.dart | 53 ++- .../platform/linux/linux_window_adapter.dart | 196 ++++++++--- .../platform/macos/macos_appkit_bindings.dart | 294 +++++++++++++++++ .../platform/macos/macos_window_adapter.dart | 244 +++++++++++++- .../platform/macos/macos_window_delegate.dart | 306 +++++++++++++++++- lib/src/platform/unix_single_instance.dart | 24 ++ lib/src/testing/native_core_testing.dart | 26 +- lib/src/window.dart | 38 ++- pubspec.yaml | 2 +- test/linux_window_test.dart | 76 +++++ test/macos_window_test.dart | 96 ++++++ test/window_facade_test.dart | 48 ++- 16 files changed, 1366 insertions(+), 86 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e24fe20..c19d30b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,16 @@ +## 1.0.1 + +OS-isolated window lifecycle, macOS Dock/close-button responsiveness, and Linux Wayland presentation fixes (with zero modifications to the Windows adapter). + +### macOS (`platform/macos/`) +* **Immediate Close-to-Tray Response on Traffic-Light `[X]` Click**: Wake Flutter's macOS `CFRunLoop` / Dart microtask queue (`Timer.run` + `ensureVisualUpdate` / `scheduleFrame`) immediately inside `NativeCoreWindowDelegate.windowShouldClose:` when a close request is cancelled, so hiding the window no longer waits for the pointer to leave AppKit's red close button. +* **Automatic Dock Running Indicator Policy (`Regular` ↔ `Accessory`)**: When `MacOSWindowAdapter.hide()` hides the last visible app window while an active `NSStatusItem` (`NSStatusBarWindow` with `isVisible == true`) is present, automatically switch `NSApplication` to `Accessory (1)` so the Dock dot disappears while the menu bar icon stays alive; restore `Regular (0)` before activation on `show()`, `focus()`, or native reopen (`NSWindowDidBecomeKeyNotification`). +* **Clean Dock Quit / `Cmd+Q` Termination**: Stop forwarding `WidgetsBindingObserver.didRequestAppExit` to `WindowCloseRequestedEvent` on macOS and Linux (preserving Windows `WM_CLOSE` forwarding intact), and automatically release single-instance Unix sockets via `NSApplicationWillTerminateNotification` (`MacOSAppLifecycleObserver`) and `Application.quit()`. + +### Linux (`platform/linux/`) +* **Wayland Unmapped Presentation & Mutter `"" is ready` Fix**: Remove raw `gdk_window_show` and `gdk_window_focus` calls from `LinuxWindowAdapter._presentWindow`, and resolve X11 vs Wayland presentation via `resolveLinuxPresentAction` so unmapped Wayland startup/restore uses `gtk_window_deiconify` + `gtk_widget_show` without firing premature `gtk_window_present_with_time(0)`. +* **GTK3 Pre-Map Geometry, Native Centering, Maximized State, and Close Wakeup**: Apply `gtk_window_set_default_size` + `gdk_window_resize` before map in `setSize()` / `bounds =`, delegate `Window.center()` to `gtk_window_set_position(GTK_WIN_POS_CENTER)`, check `GDK_WINDOW_STATE_MAXIMIZED` alongside `gtk_window_is_maximized`, and wake Flutter's event loop when `delete-event` cancels close. + ## 1.0.0 Initial stable release of **`native_core`** — a unified, zero-dependency desktop window, display, and single-instance application lifecycle package for Flutter across **Linux** (`GTK3` / `GDK3` on Wayland & X11), **macOS** (`AppKit` 13.0+), and **Windows** (`Win32`). diff --git a/README.md b/README.md index 1d7cb53..31ed5b9 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Zero-dependency desktop window, display, and single-instance lifecycle primitive ```yaml dependencies: - native_core: ^1.0.0 + native_core: ^1.0.1 ``` ## Quick Start diff --git a/example/README.md b/example/README.md index aa37baf..a0f30ba 100644 --- a/example/README.md +++ b/example/README.md @@ -1,3 +1,3 @@ # native_core Example -Demonstrates frameless desktop window initialization, window geometry controls, and multi-monitor `DisplayManager` work-area inspection with `native_core` `1.0.0` using only `package:flutter/widgets.dart`. +Demonstrates frameless desktop window initialization, window geometry controls, and multi-monitor `DisplayManager` work-area inspection with `native_core` `1.0.1` using only `package:flutter/widgets.dart`. diff --git a/lib/src/application.dart b/lib/src/application.dart index 204bcdb..48880fc 100644 --- a/lib/src/application.dart +++ b/lib/src/application.dart @@ -6,6 +6,7 @@ import 'diagnostics.dart'; import 'main_window.dart'; import 'platform/linux/linux_headerbar_grab.dart'; import 'platform/linux/linux_window_adapter.dart'; +import 'platform/macos/macos_appkit_bindings.dart'; import 'platform/unix_single_instance.dart'; import 'platform/windows/windows_single_instance.dart'; import 'platform/windows/windows_win32_bindings.dart'; @@ -84,6 +85,11 @@ class Application { if (isPrimary) { _coordinatorsByToken[token] = coordinator; + if (Platform.isMacOS) { + MacOSAppLifecycleObserver.instance.registerWillTerminate( + releaseSingleInstanceSync, + ); + } return true; } @@ -102,6 +108,11 @@ class Application { if (coordinator != null) { await coordinator.release(); } + if (_coordinatorsByToken.isEmpty && Platform.isMacOS) { + MacOSAppLifecycleObserver.instance.unregisterWillTerminate( + releaseSingleInstanceSync, + ); + } return; } @@ -109,11 +120,31 @@ class Application { _coordinatorsByToken.values, ); _coordinatorsByToken.clear(); + if (Platform.isMacOS) { + MacOSAppLifecycleObserver.instance.unregisterWillTerminate( + releaseSingleInstanceSync, + ); + } for (final coordinator in active) { await coordinator.release(); } } + /// Best-effort synchronous release of all held Unix single-instance sockets + /// during OS termination (`NSApplicationWillTerminateNotification` or + /// [quit]). + void releaseSingleInstanceSync() { + final active = List.of( + _coordinatorsByToken.values, + ); + _coordinatorsByToken.clear(); + for (final coordinator in active) { + if (coordinator is UnixSingleInstanceCoordinator) { + coordinator.releaseSync(); + } + } + } + static void _activatePrimaryMainWindow() { try { final window = mainWindow; @@ -146,6 +177,7 @@ class Application { /// Terminates the native desktop application event loop and exits the process /// with [exitCode]. void quit([int exitCode = 0]) { + releaseSingleInstanceSync(); if (Platform.isLinux) { quitLinuxApplication(); } else if (Platform.isWindows) { diff --git a/lib/src/platform/linux/linux_gtk_bindings.dart b/lib/src/platform/linux/linux_gtk_bindings.dart index 23a7fa8..e04893b 100644 --- a/lib/src/platform/linux/linux_gtk_bindings.dart +++ b/lib/src/platform/linux/linux_gtk_bindings.dart @@ -21,6 +21,13 @@ const int kGtkWindowToplevel = 0; /// (`1 << 1 == 0x02`). const int kGdkWindowStateIconified = 0x02; +/// `GdkWindowState` bit flag indicating a maximized window (`1 << 2 == 0x04`). +const int kGdkWindowStateMaximized = 0x04; + +/// `GtkWindowPosition` value requesting compositor/WM centering +/// (`GTK_WIN_POS_CENTER == 1`). +const int kGtkWinPosCenter = 1; + /// Doubly-linked list node (`GList`) returned by GLib/GTK list APIs. final class GList extends ffi.Struct { /// Element payload pointer. @@ -115,8 +122,7 @@ class LinuxGtkBindings { required this.gdkSeatGetPointer, required this.gdkDeviceGetPosition, required this.gdkWindowGetState, - required this.gdkWindowShow, - required this.gdkWindowFocus, + required this.gdkWindowResize, required this.gdkEventNew, required this.gdkEventFree, required this.gdkX11WindowGetType, @@ -134,6 +140,8 @@ class LinuxGtkBindings { required this.gtkWindowFullscreen, required this.gtkWindowUnfullscreen, required this.gtkWindowPresentWithTime, + required this.gtkWindowSetDefaultSize, + required this.gtkWindowSetPosition, required this.gtkWindowResize, required this.gtkWindowMove, required this.gtkWindowGetPosition, @@ -144,6 +152,7 @@ class LinuxGtkBindings { required this.gtkGetCurrentEventTime, required this.gtkWidgetInDestruction, required this.gtkWidgetGetRealized, + required this.gtkWidgetGetMapped, required this.gtkWidgetGetVisible, required this.gtkWidgetSetVisible, required this.gtkWidgetShow, @@ -262,14 +271,10 @@ class LinuxGtkBindings { ffi.Uint32 Function(ffi.Pointer), int Function(ffi.Pointer) >('gdk_window_get_state'), - gdkWindowShow: gdk.lookupFunction< - ffi.Void Function(ffi.Pointer), - void Function(ffi.Pointer) - >('gdk_window_show'), - gdkWindowFocus: gdk.lookupFunction< - ffi.Void Function(ffi.Pointer, ffi.Uint32), - void Function(ffi.Pointer, int) - >('gdk_window_focus'), + gdkWindowResize: gdk.lookupFunction< + ffi.Void Function(ffi.Pointer, ffi.Int32, ffi.Int32), + void Function(ffi.Pointer, int, int) + >('gdk_window_resize'), gdkEventNew: gdk.lookupFunction< ffi.Pointer Function(ffi.Int32), ffi.Pointer Function(int) @@ -332,6 +337,14 @@ class LinuxGtkBindings { ffi.Void Function(ffi.Pointer, ffi.Uint32), void Function(ffi.Pointer, int) >('gtk_window_present_with_time'), + gtkWindowSetDefaultSize: gtk.lookupFunction< + ffi.Void Function(ffi.Pointer, ffi.Int32, ffi.Int32), + void Function(ffi.Pointer, int, int) + >('gtk_window_set_default_size'), + gtkWindowSetPosition: gtk.lookupFunction< + ffi.Void Function(ffi.Pointer, ffi.Int32), + void Function(ffi.Pointer, int) + >('gtk_window_set_position'), gtkWindowResize: gtk.lookupFunction< ffi.Void Function(ffi.Pointer, ffi.Int32, ffi.Int32), void Function(ffi.Pointer, int, int) @@ -394,6 +407,10 @@ class LinuxGtkBindings { ffi.Int32 Function(ffi.Pointer), int Function(ffi.Pointer) >('gtk_widget_get_realized'), + gtkWidgetGetMapped: gtk.lookupFunction< + ffi.Int32 Function(ffi.Pointer), + int Function(ffi.Pointer) + >('gtk_widget_get_mapped'), gtkWidgetGetVisible: gtk.lookupFunction< ffi.Int32 Function(ffi.Pointer), int Function(ffi.Pointer) @@ -540,11 +557,8 @@ class LinuxGtkBindings { /// `gdk_window_get_state`. final int Function(ffi.Pointer) gdkWindowGetState; - /// `gdk_window_show`. - final void Function(ffi.Pointer) gdkWindowShow; - - /// `gdk_window_focus`. - final void Function(ffi.Pointer, int) gdkWindowFocus; + /// `gdk_window_resize`. + final void Function(ffi.Pointer, int, int) gdkWindowResize; /// `gdk_event_new`. final ffi.Pointer Function(int) gdkEventNew; @@ -598,6 +612,12 @@ class LinuxGtkBindings { /// `gtk_window_present_with_time`. final void Function(ffi.Pointer, int) gtkWindowPresentWithTime; + /// `gtk_window_set_default_size`. + final void Function(ffi.Pointer, int, int) gtkWindowSetDefaultSize; + + /// `gtk_window_set_position`. + final void Function(ffi.Pointer, int) gtkWindowSetPosition; + /// `gtk_window_resize`. final void Function(ffi.Pointer, int, int) gtkWindowResize; @@ -640,6 +660,9 @@ class LinuxGtkBindings { /// `gtk_widget_get_realized`. final int Function(ffi.Pointer) gtkWidgetGetRealized; + /// `gtk_widget_get_mapped`. + final int Function(ffi.Pointer) gtkWidgetGetMapped; + /// `gtk_widget_get_visible`. final int Function(ffi.Pointer) gtkWidgetGetVisible; diff --git a/lib/src/platform/linux/linux_window_adapter.dart b/lib/src/platform/linux/linux_window_adapter.dart index 66ea8d6..fa6c512 100644 --- a/lib/src/platform/linux/linux_window_adapter.dart +++ b/lib/src/platform/linux/linux_window_adapter.dart @@ -1,11 +1,66 @@ +import 'dart:async' show Timer; import 'dart:ffi' as ffi; +import 'package:flutter/widgets.dart' show WidgetsBinding; + import '../../diagnostics.dart'; import '../../ffi/native_memory.dart'; import '../../models.dart'; import '../window_adapter.dart'; import 'linux_gtk_bindings.dart'; +/// GTK3 presentation strategy resolved by [resolveLinuxPresentAction] for +/// X11 vs Wayland sessions across unmapped, hidden, and mapped window states. +enum LinuxPresentAction { + /// Deiconify and call `gtk_widget_show` without invoking + /// `gtk_window_present_with_time(0)` (or raw GDK focus/show) on an unmapped + /// Wayland `GtkWindow`. + widgetShowOnly, + + /// Deiconify and invoke `gtk_window_present_with_time` (using a fresh X11 + /// server timestamp on X11 when no current GDK event is active). + presentWithTime, + + /// Skip redundant presentation (for example `focus()` called synchronously + /// right after `show()` on a Wayland window that has not mapped yet, which + /// would otherwise emit an unauthenticated activation request and trigger + /// GNOME Mutter's `"" is ready` banner). + noop, +} + +/// Pure, testable decision function choosing the safe GTK3 presentation call +/// sequence on Linux Wayland and X11. +LinuxPresentAction resolveLinuxPresentAction({ + required bool isShow, + required bool isX11, + required bool isVisible, + required bool isMapped, +}) { + if (isShow) { + if (!isVisible || (!isX11 && !isMapped)) { + return LinuxPresentAction.widgetShowOnly; + } + return LinuxPresentAction.presentWithTime; + } + if (!isX11 && !isMapped) { + return isVisible + ? LinuxPresentAction.noop + : LinuxPresentAction.widgetShowOnly; + } + return LinuxPresentAction.presentWithTime; +} + +void _wakeLinuxFlutterRunLoop() { + Timer.run(() {}); + try { + WidgetsBinding.instance + ..ensureVisualUpdate() + ..scheduleFrame(); + } catch (_) { + // WidgetsBinding may not be initialized in headless Dart VM tests. + } +} + /// Pure, testable selector for resolving the primary Linux `GtkWindow` from /// `gtk_window_list_toplevels()` without accidentally picking a prepended /// `GTK_WINDOW_POPUP` (`GtkTooltip`, `GtkMenu`, or IME popup). @@ -290,6 +345,9 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { final sink = adapter?._sink; if (sink == null) return 0; final allowClose = sink.dispatchCloseRequested(); + if (!allowClose) { + _wakeLinuxFlutterRunLoop(); + } return allowClose ? 0 : 1; } @@ -380,7 +438,12 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { final gtk = LinuxGtkBindings.instance; if (gtk == null) return false; try { - return gtk.gtkWindowIsMaximized(nativeHandle) != 0; + if (gtk.gtkWindowIsMaximized(nativeHandle) != 0) return true; + final gdkWin = gtk.gtkWidgetGetWindow(nativeHandle); + if (gdkWin != ffi.nullptr) { + return (gtk.gdkWindowGetState(gdkWin) & kGdkWindowStateMaximized) != 0; + } + return false; } catch (error, stackTrace) { NativeCoreDiagnostics.report( 'LinuxWindowAdapter.isMaximized', @@ -544,12 +607,10 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { final gtk = LinuxGtkBindings.instance; if (gtk == null) return; try { + final width = rect.width.round(); + final height = rect.height.round(); gtk.gtkWindowMove(nativeHandle, rect.left.round(), rect.top.round()); - gtk.gtkWindowResize( - nativeHandle, - rect.width.round(), - rect.height.round(), - ); + _applyWindowSize(gtk, width, height); } catch (error, stackTrace) { NativeCoreDiagnostics.report( 'LinuxWindowAdapter.setBounds', @@ -572,11 +633,7 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { final gtk = LinuxGtkBindings.instance; if (gtk == null) return; try { - gtk.gtkWindowResize( - nativeHandle, - size.width.round(), - size.height.round(), - ); + _applyWindowSize(gtk, size.width.round(), size.height.round()); } catch (error, stackTrace) { NativeCoreDiagnostics.report( 'LinuxWindowAdapter.setSize', @@ -586,6 +643,35 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { } } + /// Requests native GTK window centering (`GTK_WIN_POS_CENTER`), avoiding + /// Wayland `gtk_window_move(0, 0)` assumptions before the window is mapped. + void centerNative() { + if (!isNative) return; + final gtk = LinuxGtkBindings.instance; + if (gtk == null) return; + try { + gtk.gtkWindowSetPosition(nativeHandle, kGtkWinPosCenter); + } catch (error, stackTrace) { + NativeCoreDiagnostics.report( + 'LinuxWindowAdapter.centerNative', + error, + stackTrace, + ); + } + } + + void _applyWindowSize(LinuxGtkBindings gtk, int width, int height) { + if (width <= 0 || height <= 0) return; + if (gtk.gtkWidgetGetMapped(nativeHandle) == 0) { + gtk.gtkWindowSetDefaultSize(nativeHandle, width, height); + final gdkWin = gtk.gtkWidgetGetWindow(nativeHandle); + if (gdkWin != ffi.nullptr) { + gtk.gdkWindowResize(gdkWin, width, height); + } + } + gtk.gtkWindowResize(nativeHandle, width, height); + } + @override void maximize() { if (!isNative) return; @@ -641,7 +727,7 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { if (gtk == null) return; try { gtk.gtkWindowDeiconify(nativeHandle); - _presentWindow(gtk); + _presentWindow(gtk, isShow: true); } catch (error, stackTrace) { NativeCoreDiagnostics.report( 'LinuxWindowAdapter.restore', @@ -657,7 +743,7 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { final gtk = LinuxGtkBindings.instance; if (gtk == null) return; try { - _presentWindow(gtk); + _presentWindow(gtk, isShow: true); } catch (error, stackTrace) { NativeCoreDiagnostics.report( 'LinuxWindowAdapter.show', @@ -689,7 +775,7 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { final gtk = LinuxGtkBindings.instance; if (gtk == null) return; try { - _presentWindow(gtk); + _presentWindow(gtk, isShow: false); } catch (error, stackTrace) { NativeCoreDiagnostics.report( 'LinuxWindowAdapter.focus', @@ -744,38 +830,64 @@ class LinuxWindowAdapter implements WindowPlatformAdapter { @override bool showSystemMenu(NativeOffset position) => false; - void _presentWindow(LinuxGtkBindings gtk) { - gtk.gtkWidgetShow(nativeHandle); - gtk.gtkWindowDeiconify(nativeHandle); + bool _isX11GdkWindow(LinuxGtkBindings gtk, ffi.Pointer gdkWin) { + if (gdkWin == ffi.nullptr) return false; + final x11GetType = gtk.gdkX11WindowGetType; + if (x11GetType == null) return false; + try { + return gtk.gTypeCheckInstanceIsA(gdkWin, x11GetType()) != 0; + } catch (error, stackTrace) { + NativeCoreDiagnostics.report( + 'LinuxWindowAdapter.isX11', + error, + stackTrace, + ); + return false; + } + } + void _presentWindow(LinuxGtkBindings gtk, {required bool isShow}) { final gdkWin = gtk.gtkWidgetGetWindow(nativeHandle); - var timestamp = gtk.gtkGetCurrentEventTime(); - if (timestamp == 0 && gdkWin != ffi.nullptr) { - // When triggered from a D-Bus StatusNotifierItem menu click, there is no - // active GDK event (`timestamp == 0`). On X11/XWayland, fetch a fresh X - // server timestamp so Mutter/KWin focus-stealing prevention does not - // reject `_NET_ACTIVE_WINDOW` due to a stale pre-hide user timestamp. - final x11GetType = gtk.gdkX11WindowGetType; - final x11ServerTime = gtk.gdkX11GetServerTime; - if (x11GetType != null && x11ServerTime != null) { - try { - if (gtk.gTypeCheckInstanceIsA(gdkWin, x11GetType()) != 0) { - timestamp = x11ServerTime(gdkWin); + final isX11 = _isX11GdkWindow(gtk, gdkWin); + final isVisible = gtk.gtkWidgetGetVisible(nativeHandle) != 0; + final isMapped = gtk.gtkWidgetGetMapped(nativeHandle) != 0; + + final action = resolveLinuxPresentAction( + isShow: isShow, + isX11: isX11, + isVisible: isVisible, + isMapped: isMapped, + ); + + switch (action) { + case LinuxPresentAction.noop: + return; + case LinuxPresentAction.widgetShowOnly: + gtk.gtkWindowDeiconify(nativeHandle); + gtk.gtkWidgetShow(nativeHandle); + return; + case LinuxPresentAction.presentWithTime: + gtk.gtkWindowDeiconify(nativeHandle); + var timestamp = gtk.gtkGetCurrentEventTime(); + if (timestamp == 0 && isX11 && gdkWin != ffi.nullptr) { + // When triggered from a D-Bus StatusNotifierItem menu click, there is + // no active GDK event (`timestamp == 0`). On X11/XWayland, fetch a + // fresh X server timestamp so Mutter/KWin focus-stealing prevention + // does not reject `_NET_ACTIVE_WINDOW`. + final x11ServerTime = gtk.gdkX11GetServerTime; + if (x11ServerTime != null) { + try { + timestamp = x11ServerTime(gdkWin); + } catch (error, stackTrace) { + NativeCoreDiagnostics.report( + 'LinuxWindowAdapter.x11Timestamp', + error, + stackTrace, + ); + } } - } catch (error, stackTrace) { - NativeCoreDiagnostics.report( - 'LinuxWindowAdapter.x11Timestamp', - error, - stackTrace, - ); } - } - } - - gtk.gtkWindowPresentWithTime(nativeHandle, timestamp); - if (gdkWin != ffi.nullptr) { - gtk.gdkWindowShow(gdkWin); - gtk.gdkWindowFocus(gdkWin, timestamp); + gtk.gtkWindowPresentWithTime(nativeHandle, timestamp); } } diff --git a/lib/src/platform/macos/macos_appkit_bindings.dart b/lib/src/platform/macos/macos_appkit_bindings.dart index e4f63a7..29d3644 100644 --- a/lib/src/platform/macos/macos_appkit_bindings.dart +++ b/lib/src/platform/macos/macos_appkit_bindings.dart @@ -20,6 +20,17 @@ const int kNSEventTypeLeftMouseDown = 1; /// `NSEventTypeLeftMouseDragged` (`6`). const int kNSEventTypeLeftMouseDragged = 6; +/// `NSApplicationActivationPolicyRegular` (`0`) — appears in Dock and owns a +/// menu bar. +const int kNSApplicationActivationPolicyRegular = 0; + +/// `NSApplicationActivationPolicyAccessory` (`1`) — hidden from the Dock and +/// application switcher while keeping `NSStatusItem` menu bar icons alive. +const int kNSApplicationActivationPolicyAccessory = 1; + +/// `NSApplicationActivationPolicyProhibited` (`2`). +const int kNSApplicationActivationPolicyProhibited = 2; + /// Native `NSPoint` / `CGPoint` ABI layout (`double x, double y`). final class MacPoint extends ffi.Struct { /// Horizontal coordinate in points. @@ -58,6 +69,7 @@ class MacOSAppKitBindings { required this.getClassPtr, required this.registerNamePtr, required this.objectGetClass, + required this.classGetName, required this.classGetInstanceMethod, required this.allocateClassPair, required this.registerClassPair, @@ -68,10 +80,14 @@ class MacOSAppKitBindings { required this.sendIdUInt, required this.sendVoid, required this.sendVoidId, + required this.sendVoidId3, + required this.sendVoidId4, required this.sendVoidBool, required this.sendVoidInt, required this.sendVoidUInt, required this.sendBool, + required this.sendBoolInt, + required this.sendInt, required this.sendUInt, required this.sendDouble, required this.sendRect, @@ -93,6 +109,13 @@ class MacOSAppKitBindings { _attempted = true; try { + try { + ffi.DynamicLibrary.open( + '/System/Library/Frameworks/AppKit.framework/AppKit', + ); + } catch (_) { + // AppKit may already be linked into the host Flutter runner. + } final objc = ffi.DynamicLibrary.open('/usr/lib/libobjc.A.dylib'); final msgSend = objc.lookup>( 'objc_msgSend', @@ -190,6 +213,10 @@ class MacOSAppKitBindings { ffi.Pointer Function(ffi.Pointer), ffi.Pointer Function(ffi.Pointer) >('object_getClass'), + classGetName: objc.lookupFunction< + ffi.Pointer Function(ffi.Pointer), + ffi.Pointer Function(ffi.Pointer) + >('class_getName'), classGetInstanceMethod: objc.lookupFunction< ffi.Pointer Function( ffi.Pointer, @@ -302,6 +329,35 @@ class MacOSAppKitBindings { > >() .asFunction(), + sendVoidId3: + msgSend + .cast< + ffi.NativeFunction< + ffi.Void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + > + >() + .asFunction(), + sendVoidId4: + msgSend + .cast< + ffi.NativeFunction< + ffi.Void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + > + >() + .asFunction(), sendVoidBool: msgSend .cast< @@ -349,6 +405,29 @@ class MacOSAppKitBindings { > >() .asFunction(), + sendBoolInt: + msgSend + .cast< + ffi.NativeFunction< + ffi.Bool Function( + ffi.Pointer, + ffi.Pointer, + ffi.IntPtr, + ) + > + >() + .asFunction(), + sendInt: + msgSend + .cast< + ffi.NativeFunction< + ffi.IntPtr Function( + ffi.Pointer, + ffi.Pointer, + ) + > + >() + .asFunction(), sendUInt: msgSend .cast< @@ -434,6 +513,9 @@ class MacOSAppKitBindings { /// `object_getClass`. final ffi.Pointer Function(ffi.Pointer) objectGetClass; + /// `class_getName`. + final ffi.Pointer Function(ffi.Pointer) classGetName; + /// `class_getInstanceMethod`. final ffi.Pointer Function( ffi.Pointer, @@ -504,6 +586,29 @@ class MacOSAppKitBindings { ) sendVoidId; + /// `void (*objc_msgSend)(id, SEL, id, id, id)` (e.g. + /// `-[NSNotificationCenter removeObserver:name:object:]`). + final void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + sendVoidId3; + + /// `void (*objc_msgSend)(id, SEL, id, SEL, id, id)` (e.g. + /// `-[NSNotificationCenter addObserver:selector:name:object:]`). + final void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + sendVoidId4; + /// `void (*objc_msgSend)(id, SEL, BOOL)`. final void Function(ffi.Pointer, ffi.Pointer, bool) sendVoidBool; @@ -519,6 +624,13 @@ class MacOSAppKitBindings { /// `BOOL (*objc_msgSend)(id, SEL)`. final bool Function(ffi.Pointer, ffi.Pointer) sendBool; + /// `BOOL (*objc_msgSend)(id, SEL, NSInteger)`. + final bool Function(ffi.Pointer, ffi.Pointer, int) + sendBoolInt; + + /// `NSInteger (*objc_msgSend)(id, SEL)`. + final int Function(ffi.Pointer, ffi.Pointer) sendInt; + /// `NSUInteger (*objc_msgSend)(id, SEL)`. final int Function(ffi.Pointer, ffi.Pointer) sendUInt; @@ -649,4 +761,186 @@ class MacOSAppKitBindings { } return 1080.0; } + + /// Returns the Objective-C runtime class name for [obj], or `null` when + /// [obj] is `nullptr`. + String? dartClassName(ffi.Pointer obj) { + if (obj == ffi.nullptr) return null; + final cls = objectGetClass(obj); + if (cls == ffi.nullptr) return null; + final raw = classGetName(cls).cast(); + if (raw == ffi.nullptr) return null; + final bytes = []; + var i = 0; + while (raw[i] != 0) { + bytes.add(raw[i]); + i++; + } + return String.fromCharCodes(bytes); + } +} + +/// Observes `NSApplicationWillTerminateNotification` on macOS using a +/// Hot-Restart-safe Objective-C observer class (`NativeCoreAppLifecycleObserver`) +/// so `native_core` automatically releases single-instance Unix sockets when +/// terminated via Dock Quit or `Cmd+Q`. +class MacOSAppLifecycleObserver { + MacOSAppLifecycleObserver._(); + + /// Process-wide singleton observer. + static final MacOSAppLifecycleObserver instance = + MacOSAppLifecycleObserver._(); + + final Set _willTerminateCallbacks = {}; + + ffi.Pointer? _observerInstance; + bool _registeredWithCenter = false; + ffi.NativeCallable< + ffi.Void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + >? + _willTerminateCallable; + + /// Registers [callback] to run synchronously when macOS posts + /// `NSApplicationWillTerminateNotification`. + bool registerWillTerminate(void Function() callback) { + if (!Platform.isMacOS) return false; + _willTerminateCallbacks.add(callback); + return _ensureRegistered(); + } + + /// Removes a previously registered [callback]. + void unregisterWillTerminate(void Function() callback) { + _willTerminateCallbacks.remove(callback); + } + + bool _ensureRegistered() { + final mac = MacOSAppKitBindings.instance; + if (mac == null) return false; + try { + final observer = _ensureObserverInstance(mac); + if (observer == ffi.nullptr) return false; + if (_registeredWithCenter) return true; + + final centerCls = mac.getClass('NSNotificationCenter'); + if (centerCls == ffi.nullptr) return false; + final defaultCenter = mac.sendId(centerCls, mac.sel('defaultCenter')); + if (defaultCenter == ffi.nullptr) return false; + final noteName = mac.nsString('NSApplicationWillTerminateNotification'); + if (noteName == ffi.nullptr) return false; + + mac.sendVoidId4( + defaultCenter, + mac.sel('addObserver:selector:name:object:'), + observer, + mac.sel('onApplicationWillTerminate:'), + noteName, + ffi.nullptr, + ); + _registeredWithCenter = true; + return true; + } catch (error, stackTrace) { + NativeCoreDiagnostics.report( + 'MacOSAppLifecycleObserver.register', + error, + stackTrace, + ); + return false; + } + } + + ffi.Pointer _ensureObserverInstance(MacOSAppKitBindings mac) { + final existing = _observerInstance; + if (existing != null && existing != ffi.nullptr) return existing; + + _willTerminateCallable ??= ffi.NativeCallable< + ffi.Void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + >.isolateLocal(_onWillTerminate); + + final actionSel = mac.sel('onApplicationWillTerminate:'); + var cls = mac.getClass('NativeCoreAppLifecycleObserver'); + if (cls == ffi.nullptr) { + final nsObject = mac.getClass('NSObject'); + cls = NativeMemory.withUtf8CString( + 'NativeCoreAppLifecycleObserver', + (name) => mac.allocateClassPair(nsObject, name, 0), + ); + NativeMemory.withUtf8CString('v@:@', (types) { + mac.addMethod( + cls, + actionSel, + _willTerminateCallable!.nativeFunction.cast(), + types, + ); + }); + mac.registerClassPair(cls); + } else { + NativeMemory.withUtf8CString('v@:@', (types) { + mac.replaceMethod( + cls, + actionSel, + _willTerminateCallable!.nativeFunction.cast(), + types, + ); + }); + } + + return _observerInstance = mac.sendId( + mac.sendId(cls, mac.sel('alloc')), + mac.sel('init'), + ); + } + + static void _onWillTerminate( + ffi.Pointer self, + ffi.Pointer cmd, + ffi.Pointer notification, + ) { + final snapshot = List.of(instance._willTerminateCallbacks); + for (final callback in snapshot) { + try { + callback(); + } catch (error, stackTrace) { + NativeCoreDiagnostics.report( + 'MacOSAppLifecycleObserver.willTerminate', + error, + stackTrace, + ); + } + } + } +} + +/// Live macOS FFI probe verifying that `NativeCoreAppLifecycleObserver` +/// registers on `NSNotificationCenter.defaultCenter` and dispatches registered +/// termination callbacks through Objective-C `objc_msgSend`. +bool debugRunMacOSWillTerminateObserverProbe() { + if (!Platform.isMacOS) return false; + final mac = MacOSAppKitBindings.instance; + if (mac == null) return false; + + var invoked = false; + void onTerminate() { + invoked = true; + } + + final observer = MacOSAppLifecycleObserver.instance; + final registered = observer.registerWillTerminate(onTerminate); + try { + final target = observer._observerInstance; + if (!registered || target == null || target == ffi.nullptr) { + return false; + } + mac.sendVoidId(target, mac.sel('onApplicationWillTerminate:'), ffi.nullptr); + return invoked; + } finally { + observer.unregisterWillTerminate(onTerminate); + } } diff --git a/lib/src/platform/macos/macos_window_adapter.dart b/lib/src/platform/macos/macos_window_adapter.dart index 9ee5cc9..e52d202 100644 --- a/lib/src/platform/macos/macos_window_adapter.dart +++ b/lib/src/platform/macos/macos_window_adapter.dart @@ -1,4 +1,5 @@ import 'dart:ffi' as ffi; +import 'dart:io'; import 'package:flutter/widgets.dart' show WidgetsBinding; @@ -8,6 +9,185 @@ import '../window_adapter.dart'; import 'macos_appkit_bindings.dart'; import 'macos_window_delegate.dart'; +/// Resolves whether `MacOSWindowAdapter.hide()` should switch `NSApplication` +/// from `Regular (0)` to `Accessory (1)` so the Dock running indicator dot +/// disappears while a menu bar `NSStatusItem` remains active (matching macOS +/// menu-bar apps such as Docker Desktop and Rancher Desktop). +bool shouldSwitchMacOSActivationPolicyOnHide({ + required bool hasActiveStatusItem, + required bool hasOtherVisibleAppWindow, + required bool isVisibleInTaskbar, +}) { + return isVisibleInTaskbar && hasActiveStatusItem && !hasOtherVisibleAppWindow; +} + +/// Resolves whether `MacOSWindowAdapter.show()` / `focus()` / reopen should +/// switch `NSApplication` back to `Regular (0)` before activating the window so +/// the Dock running indicator dot and application menu bar reappear. +bool shouldRestoreMacOSActivationPolicyOnShow({ + required bool switchedToAccessoryOnHide, + required bool isVisibleInTaskbar, + required int currentActivationPolicy, +}) { + if (switchedToAccessoryOnHide) return true; + return isVisibleInTaskbar && + currentActivationPolicy != kNSApplicationActivationPolicyRegular; +} + +bool _isStatusBarWindow(MacOSAppKitBindings mac, ffi.Pointer win) { + if (win == ffi.nullptr) return false; + return mac.dartClassName(win) == 'NSStatusBarWindow'; +} + +bool _hasActiveStatusBarItem( + MacOSAppKitBindings mac, + ffi.Pointer sharedApp, +) { + if (sharedApp == ffi.nullptr) return false; + final windows = mac.sendId(sharedApp, mac.sel('windows')); + if (windows == ffi.nullptr) return false; + final count = mac.sendUInt(windows, mac.sel('count')); + final selAt = mac.sel('objectAtIndex:'); + final selVisible = mac.sel('isVisible'); + for (var i = 0; i < count; i++) { + final win = mac.sendIdUInt(windows, selAt, i); + if (win == ffi.nullptr) continue; + if (_isStatusBarWindow(mac, win) && mac.sendBool(win, selVisible)) { + return true; + } + } + return false; +} + +bool _hasOtherVisibleAppWindow( + MacOSAppKitBindings mac, + ffi.Pointer sharedApp, { + required ffi.Pointer excluding, +}) { + if (sharedApp == ffi.nullptr) return false; + final windows = mac.sendId(sharedApp, mac.sel('windows')); + if (windows == ffi.nullptr) return false; + final count = mac.sendUInt(windows, mac.sel('count')); + final selAt = mac.sel('objectAtIndex:'); + final selVisible = mac.sel('isVisible'); + for (var i = 0; i < count; i++) { + final win = mac.sendIdUInt(windows, selAt, i); + if (win == ffi.nullptr || win == excluding) continue; + if (_isStatusBarWindow(mac, win)) continue; + if (_isCandidateAppWindow(mac, win) && mac.sendBool(win, selVisible)) { + return true; + } + } + return false; +} + +/// Result of [debugRunMacOSStatusItemActivationPolicyProbe]. +class MacOSActivationPolicyProbeResult { + /// Creates a [MacOSActivationPolicyProbeResult]. + const MacOSActivationPolicyProbeResult({ + required this.detectedStatusBarWindowWhileActive, + required this.switchedToAccessoryPolicy, + required this.restoredRegularPolicy, + required this.clearedStatusBarWindowAfterRemove, + }); + + /// Whether a live `NSStatusItem` was detected as a visible + /// `NSStatusBarWindow` in `[NSApp windows]`. + final bool detectedStatusBarWindowWhileActive; + + /// Whether `setActivationPolicy:` switched `NSApp` to `Accessory (1)`. + final bool switchedToAccessoryPolicy; + + /// Whether `setActivationPolicy:` restored `NSApp` to `Regular (0)`. + final bool restoredRegularPolicy; + + /// Whether removing the `NSStatusItem` cleared active status-bar detection. + final bool clearedStatusBarWindowAfterRemove; +} + +/// Live macOS FFI probe verifying `NSStatusBarWindow` detection and +/// `NSApplication.setActivationPolicy:` transitions on macOS 13 through 27+. +MacOSActivationPolicyProbeResult? +debugRunMacOSStatusItemActivationPolicyProbe() { + if (!Platform.isMacOS) return null; + final mac = MacOSAppKitBindings.instance; + if (mac == null) return null; + + final nsAppCls = mac.getClass('NSApplication'); + final nsStatusBarCls = mac.getClass('NSStatusBar'); + if (nsAppCls == ffi.nullptr || nsStatusBarCls == ffi.nullptr) return null; + + final sharedApp = mac.sendId(nsAppCls, mac.sel('sharedApplication')); + final systemBar = mac.sendId(nsStatusBarCls, mac.sel('systemStatusBar')); + if (sharedApp == ffi.nullptr || systemBar == ffi.nullptr) return null; + + final sendIdDouble = + ffi.DynamicLibrary.open('/usr/lib/libobjc.A.dylib') + .lookup>('objc_msgSend') + .cast< + ffi.NativeFunction< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ffi.Double, + ) + > + >() + .asFunction< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + double, + ) + >(); + + final previousPolicy = mac.sendInt(sharedApp, mac.sel('activationPolicy')); + final statusItem = sendIdDouble( + systemBar, + mac.sel('statusItemWithLength:'), + -1.0, + ); + if (statusItem == ffi.nullptr) return null; + + try { + final activeBeforeRemove = _hasActiveStatusBarItem(mac, sharedApp); + final setAccessoryOk = mac.sendBoolInt( + sharedApp, + mac.sel('setActivationPolicy:'), + kNSApplicationActivationPolicyAccessory, + ); + final policyWhileAccessory = mac.sendInt( + sharedApp, + mac.sel('activationPolicy'), + ); + final setRegularOk = mac.sendBoolInt( + sharedApp, + mac.sel('setActivationPolicy:'), + kNSApplicationActivationPolicyRegular, + ); + final policyAfterRestore = mac.sendInt( + sharedApp, + mac.sel('activationPolicy'), + ); + + mac.sendVoidId(systemBar, mac.sel('removeStatusItem:'), statusItem); + final activeAfterRemove = _hasActiveStatusBarItem(mac, sharedApp); + + return MacOSActivationPolicyProbeResult( + detectedStatusBarWindowWhileActive: activeBeforeRemove, + switchedToAccessoryPolicy: + setAccessoryOk && + policyWhileAccessory == kNSApplicationActivationPolicyAccessory, + restoredRegularPolicy: + setRegularOk && + policyAfterRestore == kNSApplicationActivationPolicyRegular, + clearedStatusBarWindowAfterRemove: !activeAfterRemove, + ); + } finally { + mac.sendBoolInt(sharedApp, mac.sel('setActivationPolicy:'), previousPolicy); + } +} + /// Activation call plan for `NSApplication` across macOS 13 Ventura through /// macOS 27 `Golden Gate`+. class MacOSActivationPlan { @@ -43,6 +223,7 @@ MacOSActivationPlan resolveMacOSActivationPlan({ bool _isCandidateAppWindow(MacOSAppKitBindings mac, ffi.Pointer win) { if (win == ffi.nullptr) return false; + if (_isStatusBarWindow(mac, win)) return false; final vc = mac.sendId(win, mac.sel('contentViewController')); if (vc != ffi.nullptr) return true; final mask = mac.sendUInt(win, mac.sel('styleMask')); @@ -109,6 +290,7 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { bool _ownsDelegateProperty = false; bool _desiredVisible = true; + bool _switchedToAccessoryOnHide = false; TitleBarStyle _titleBarStyle = TitleBarStyle.normal; bool _isWindowControlButtonsVisible = true; NativeColor _backgroundColor = const NativeColor(0x00000000); @@ -126,9 +308,18 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { mac: mac, nsWindow: nativeHandle, sink: sink, + onBecameKey: _handleWindowBecameKey, ); } + void _handleWindowBecameKey() { + if (!isNative) return; + final mac = MacOSAppKitBindings.instance; + if (mac == null) return; + _desiredVisible = true; + _restoreRegularActivationPolicyIfNeeded(mac); + } + @override TitleBarStyle get titleBarStyle => _titleBarStyle; @@ -283,17 +474,19 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { @override set isVisibleInTaskbar(bool visible) { _isVisibleInTaskbar = visible; + _switchedToAccessoryOnHide = false; if (!isNative) return; final mac = MacOSAppKitBindings.instance; if (mac == null) return; try { final sharedApp = mac.runningNSApp(); if (sharedApp != ffi.nullptr) { - // NSApplicationActivationPolicyRegular = 0, Accessory = 1 - mac.sendVoidInt( + mac.sendBoolInt( sharedApp, mac.sel('setActivationPolicy:'), - visible ? 0 : 1, + visible + ? kNSApplicationActivationPolicyRegular + : kNSApplicationActivationPolicyAccessory, ); } } catch (error, stackTrace) { @@ -492,6 +685,7 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { final mac = MacOSAppKitBindings.instance; if (mac == null) return; try { + _restoreRegularActivationPolicyIfNeeded(mac); if (isMinimized) { mac.sendVoidId(nativeHandle, mac.sel('deminiaturize:'), ffi.nullptr); } @@ -501,6 +695,7 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { WidgetsBinding.instance.addPostFrameCallback((_) { if (!_desiredVisible || !isNative) return; if (!isFocused) { + _restoreRegularActivationPolicyIfNeeded(mac); _activateAppAndOrderFront(mac); } }); @@ -530,6 +725,7 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { try { mac.sendVoidBool(nativeHandle, mac.sel('setIsVisible:'), false); mac.sendVoidId(nativeHandle, mac.sel('orderOut:'), ffi.nullptr); + _switchToAccessoryPolicyIfTrayActive(mac); } catch (error, stackTrace) { NativeCoreDiagnostics.report( 'MacOSWindowAdapter.hide', @@ -545,6 +741,7 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { final mac = MacOSAppKitBindings.instance; if (mac == null) return; try { + _restoreRegularActivationPolicyIfNeeded(mac); if (isMinimized) { mac.sendVoidId(nativeHandle, mac.sel('deminiaturize:'), ffi.nullptr); } @@ -558,6 +755,47 @@ class MacOSWindowAdapter implements WindowPlatformAdapter { } } + void _switchToAccessoryPolicyIfTrayActive(MacOSAppKitBindings mac) { + final sharedApp = mac.runningNSApp(); + if (sharedApp == ffi.nullptr) return; + if (!shouldSwitchMacOSActivationPolicyOnHide( + hasActiveStatusItem: _hasActiveStatusBarItem(mac, sharedApp), + hasOtherVisibleAppWindow: _hasOtherVisibleAppWindow( + mac, + sharedApp, + excluding: nativeHandle, + ), + isVisibleInTaskbar: _isVisibleInTaskbar, + )) { + return; + } + _switchedToAccessoryOnHide = true; + mac.sendBoolInt( + sharedApp, + mac.sel('setActivationPolicy:'), + kNSApplicationActivationPolicyAccessory, + ); + } + + void _restoreRegularActivationPolicyIfNeeded(MacOSAppKitBindings mac) { + final sharedApp = mac.runningNSApp(); + if (sharedApp == ffi.nullptr) return; + final currentPolicy = mac.sendInt(sharedApp, mac.sel('activationPolicy')); + if (!shouldRestoreMacOSActivationPolicyOnShow( + switchedToAccessoryOnHide: _switchedToAccessoryOnHide, + isVisibleInTaskbar: _isVisibleInTaskbar, + currentActivationPolicy: currentPolicy, + )) { + return; + } + _switchedToAccessoryOnHide = false; + mac.sendBoolInt( + sharedApp, + mac.sel('setActivationPolicy:'), + kNSApplicationActivationPolicyRegular, + ); + } + @override void destroyNativeWindow() { if (!isNative) return; diff --git a/lib/src/platform/macos/macos_window_delegate.dart b/lib/src/platform/macos/macos_window_delegate.dart index 0e8a397..e601286 100644 --- a/lib/src/platform/macos/macos_window_delegate.dart +++ b/lib/src/platform/macos/macos_window_delegate.dart @@ -1,12 +1,34 @@ +import 'dart:async' show Timer; import 'dart:ffi' as ffi; import 'dart:io'; +import 'package:flutter/widgets.dart' show WidgetsBinding; + import '../../diagnostics.dart'; import '../../ffi/native_memory.dart'; import '../../models.dart'; import '../window_adapter.dart'; import 'macos_appkit_bindings.dart'; +/// Wakes Flutter's macOS `CFRunLoop` / Dart microtask queue immediately after a +/// synchronous `NativeCallable.isolateLocal` AppKit callback cancels a close +/// request and queues async Dart work (such as Close-to-Tray `window.hide()`). +/// +/// Without an explicit timer + frame wakeup, returning `NO` from +/// `windowShouldClose:` while the pointer stays over AppKit's red traffic-light +/// close button (`_NSThemeCloseWidget`) leaves microtasks stranded until the +/// cursor exits into `FlutterView`. +void _wakeFlutterRunLoop() { + Timer.run(() {}); + try { + WidgetsBinding.instance + ..ensureVisualUpdate() + ..scheduleFrame(); + } catch (_) { + // WidgetsBinding may not be initialized in headless Dart VM tests. + } +} + /// Verifies on macOS that `libobjc.A.dylib` resolved `class_replaceMethod` /// (required for Hot Restart-safe delegate trampoline rebinding). bool debugHasMacOSReplaceMethodSymbol() { @@ -16,9 +38,150 @@ bool debugHasMacOSReplaceMethodSymbol() { return mac.getClass('NSObject') != ffi.nullptr; } +/// Result of [debugRunMacOSWindowShouldCloseProbe]. +class MacOSWindowCloseProbeResult { + /// Creates a [MacOSWindowCloseProbeResult]. + const MacOSWindowCloseProbeResult({ + required this.cancelReturnedFalse, + required this.allowReturnedTrue, + required this.becameKeyDispatched, + }); + + /// Whether `windowShouldClose:` returned `NO` when the sink cancelled close. + final bool cancelReturnedFalse; + + /// Whether `windowShouldClose:` returned `YES` when the sink allowed close. + final bool allowReturnedTrue; + + /// Whether `onWindowDidBecomeKeyNotification:` invoked `onBecameKey`. + final bool becameKeyDispatched; +} + +class _ProbeEventSink implements WindowAdapterEventSink { + _ProbeEventSink({required this.allowClose}); + + bool allowClose; + + @override + bool dispatchCloseRequested() => allowClose; + + @override + void notifyNativeMoved(NativeOffset position) {} +} + +/// Live macOS FFI probe exercising Objective-C `objc_msgSend` dispatch through +/// `NativeCoreWindowDelegate` (`windowShouldClose:` cancel/allow and +/// `onWindowDidBecomeKeyNotification:`). +MacOSWindowCloseProbeResult? debugRunMacOSWindowShouldCloseProbe() { + if (!Platform.isMacOS) return null; + final mac = MacOSAppKitBindings.instance; + if (mac == null) return null; + + final nsObjectCls = mac.getClass('NSObject'); + if (nsObjectCls == ffi.nullptr) return null; + final sentinelWindow = mac.sendId( + mac.sendId(nsObjectCls, mac.sel('alloc')), + mac.sel('init'), + ); + if (sentinelWindow == ffi.nullptr) return null; + + final registry = MacOSWindowDelegateRegistry.instance; + final sink = _ProbeEventSink(allowClose: false); + var becameKey = false; + try { + final delegate = registry._ensureDelegateInstance(mac); + if (delegate == ffi.nullptr) return null; + registry._entries[sentinelWindow.address] = ( + window: sentinelWindow, + sink: sink, + onBecameKey: () => becameKey = true, + ); + + final sendBoolId = + ffi.DynamicLibrary.open('/usr/lib/libobjc.A.dylib') + .lookup>('objc_msgSend') + .cast< + ffi.NativeFunction< + ffi.Bool Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + > + >() + .asFunction< + bool Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + >(); + + final cancelRes = sendBoolId( + delegate, + mac.sel('windowShouldClose:'), + sentinelWindow, + ); + sink.allowClose = true; + final allowRes = sendBoolId( + delegate, + mac.sel('windowShouldClose:'), + sentinelWindow, + ); + + final nsNotificationCls = mac.getClass('NSNotification'); + if (nsNotificationCls != ffi.nullptr) { + final name = mac.nsString('NSWindowDidBecomeKeyNotification'); + final sendId2 = + ffi.DynamicLibrary.open('/usr/lib/libobjc.A.dylib') + .lookup>('objc_msgSend') + .cast< + ffi.NativeFunction< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + > + >() + .asFunction< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + >(); + final note = sendId2( + nsNotificationCls, + mac.sel('notificationWithName:object:'), + name, + sentinelWindow, + ); + if (note != ffi.nullptr) { + mac.sendVoidId( + delegate, + mac.sel('onWindowDidBecomeKeyNotification:'), + note, + ); + } + } + + return MacOSWindowCloseProbeResult( + cancelReturnedFalse: !cancelRes, + allowReturnedTrue: allowRes, + becameKeyDispatched: becameKey, + ); + } finally { + registry._entries.remove(sentinelWindow.address); + mac.sendVoid(sentinelWindow, mac.sel('release')); + } +} + /// Manages the Objective-C `NativeCoreWindowDelegate` class and routes -/// `windowShouldClose:` / `windowDidMove:` notifications by `NSWindow*` -/// address. +/// `windowShouldClose:`, `windowDidMove:`, and +/// `NSWindowDidBecomeKeyNotification` callbacks by `NSWindow*` address. class MacOSWindowDelegateRegistry { MacOSWindowDelegateRegistry._(); @@ -26,9 +189,23 @@ class MacOSWindowDelegateRegistry { static final MacOSWindowDelegateRegistry instance = MacOSWindowDelegateRegistry._(); - final Map window, WindowAdapterEventSink sink})> + final Map< + int, + ({ + ffi.Pointer window, + WindowAdapterEventSink sink, + void Function()? onBecameKey, + }) + > _entries = - window, WindowAdapterEventSink sink})>{}; + < + int, + ({ + ffi.Pointer window, + WindowAdapterEventSink sink, + void Function()? onBecameKey, + }) + >{}; ffi.Pointer? _delegateInstance; ffi.NativeCallable< @@ -47,22 +224,38 @@ class MacOSWindowDelegateRegistry { ) >? _windowDidMoveCallable; + ffi.NativeCallable< + ffi.Void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + >? + _windowDidBecomeKeyCallable; - /// Attaches `windowShouldClose:` and `windowDidMove:` interception to - /// [nsWindow] and returns `true` when [nsWindow]'s `delegate` property was - /// directly assigned to `NativeCoreWindowDelegate`. + /// Attaches `windowShouldClose:`, `windowDidMove:`, and + /// `NSWindowDidBecomeKeyNotification` interception to [nsWindow] and returns + /// `true` when [nsWindow]'s `delegate` property was directly assigned to + /// `NativeCoreWindowDelegate`. bool attach({ required MacOSAppKitBindings mac, required ffi.Pointer nsWindow, required WindowAdapterEventSink sink, + void Function()? onBecameKey, }) { if (nsWindow == ffi.nullptr) return false; - _entries[nsWindow.address] = (window: nsWindow, sink: sink); + _entries[nsWindow.address] = ( + window: nsWindow, + sink: sink, + onBecameKey: onBecameKey, + ); try { final delegate = _ensureDelegateInstance(mac); if (delegate == ffi.nullptr) return false; + _registerBecomeKeyObserver(mac, delegate, nsWindow); + final existing = mac.sendId(nsWindow, mac.sel('delegate')); if (existing == ffi.nullptr) { mac.sendVoidId(nsWindow, mac.sel('setDelegate:'), delegate); @@ -98,21 +291,38 @@ class MacOSWindowDelegateRegistry { return false; } - /// Unregisters [nsWindow] and clears its `delegate` property if it still - /// points to `NativeCoreWindowDelegate`. + /// Unregisters [nsWindow], removes its `NSWindowDidBecomeKeyNotification` + /// observer, and clears its `delegate` property if it still points to + /// `NativeCoreWindowDelegate`. void detach({ required MacOSAppKitBindings? mac, required ffi.Pointer nsWindow, required bool ownsDelegateProperty, }) { _entries.remove(nsWindow.address); - if (!ownsDelegateProperty || mac == null || nsWindow == ffi.nullptr) return; + if (mac == null || nsWindow == ffi.nullptr) return; final delegate = _delegateInstance; if (delegate == null || delegate == ffi.nullptr) return; try { - final current = mac.sendId(nsWindow, mac.sel('delegate')); - if (current == delegate) { - mac.sendVoidId(nsWindow, mac.sel('setDelegate:'), ffi.nullptr); + final centerCls = mac.getClass('NSNotificationCenter'); + if (centerCls != ffi.nullptr) { + final center = mac.sendId(centerCls, mac.sel('defaultCenter')); + final noteName = mac.nsString('NSWindowDidBecomeKeyNotification'); + if (center != ffi.nullptr && noteName != ffi.nullptr) { + mac.sendVoidId3( + center, + mac.sel('removeObserver:name:object:'), + delegate, + noteName, + nsWindow, + ); + } + } + if (ownsDelegateProperty) { + final current = mac.sendId(nsWindow, mac.sel('delegate')); + if (current == delegate) { + mac.sendVoidId(nsWindow, mac.sel('setDelegate:'), ffi.nullptr); + } } } catch (error, stackTrace) { NativeCoreDiagnostics.report( @@ -123,6 +333,34 @@ class MacOSWindowDelegateRegistry { } } + void _registerBecomeKeyObserver( + MacOSAppKitBindings mac, + ffi.Pointer delegate, + ffi.Pointer nsWindow, + ) { + final centerCls = mac.getClass('NSNotificationCenter'); + if (centerCls == ffi.nullptr) return; + final center = mac.sendId(centerCls, mac.sel('defaultCenter')); + final noteName = mac.nsString('NSWindowDidBecomeKeyNotification'); + if (center == ffi.nullptr || noteName == ffi.nullptr) return; + + mac.sendVoidId3( + center, + mac.sel('removeObserver:name:object:'), + delegate, + noteName, + nsWindow, + ); + mac.sendVoidId4( + center, + mac.sel('addObserver:selector:name:object:'), + delegate, + mac.sel('onWindowDidBecomeKeyNotification:'), + noteName, + nsWindow, + ); + } + ffi.Pointer _ensureDelegateInstance(MacOSAppKitBindings mac) { final existing = _delegateInstance; if (existing != null && existing != ffi.nullptr) return existing; @@ -141,6 +379,13 @@ class MacOSWindowDelegateRegistry { ffi.Pointer, ) >.isolateLocal(_onWindowDidMove); + _windowDidBecomeKeyCallable ??= ffi.NativeCallable< + ffi.Void Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ) + >.isolateLocal(_onWindowDidBecomeKeyNotification); var cls = mac.getClass('NativeCoreWindowDelegate'); if (cls == ffi.nullptr) { @@ -164,12 +409,18 @@ class MacOSWindowDelegateRegistry { _windowDidMoveCallable!.nativeFunction.cast(), types, ); + mac.addMethod( + cls, + mac.sel('onWindowDidBecomeKeyNotification:'), + _windowDidBecomeKeyCallable!.nativeFunction.cast(), + types, + ); }); mac.registerClassPair(cls); } else { // Across Flutter Hot Restart, the Objective-C runtime retains the // previously registered class whose method IMPs point at the terminated - // Dart isolate's trampolines. Rebind both selectors to this live isolate. + // Dart isolate's trampolines. Rebind all selectors to this live isolate. NativeMemory.withUtf8CString('B@:@', (types) { mac.replaceMethod( cls, @@ -185,6 +436,12 @@ class MacOSWindowDelegateRegistry { _windowDidMoveCallable!.nativeFunction.cast(), types, ); + mac.replaceMethod( + cls, + mac.sel('onWindowDidBecomeKeyNotification:'), + _windowDidBecomeKeyCallable!.nativeFunction.cast(), + types, + ); }); } @@ -201,7 +458,11 @@ class MacOSWindowDelegateRegistry { ) { final entry = instance._entries[sender.address]; if (entry == null) return true; - return entry.sink.dispatchCloseRequested(); + final allowClose = entry.sink.dispatchCloseRequested(); + if (!allowClose) { + _wakeFlutterRunLoop(); + } + return allowClose; } static void _onWindowDidMove( @@ -222,4 +483,17 @@ class MacOSWindowDelegateRegistry { final top = primaryHeight - (frame.origin.y + frame.size.height); entry.sink.notifyNativeMoved(NativeOffset(frame.origin.x, top)); } + + static void _onWindowDidBecomeKeyNotification( + ffi.Pointer self, + ffi.Pointer cmd, + ffi.Pointer notification, + ) { + final mac = MacOSAppKitBindings.instance; + if (mac == null || notification == ffi.nullptr) return; + final sender = mac.sendId(notification, mac.sel('object')); + if (sender == ffi.nullptr) return; + final entry = instance._entries[sender.address]; + entry?.onBecameKey?.call(); + } } diff --git a/lib/src/platform/unix_single_instance.dart b/lib/src/platform/unix_single_instance.dart index 4457b42..2bccc26 100644 --- a/lib/src/platform/unix_single_instance.dart +++ b/lib/src/platform/unix_single_instance.dart @@ -241,6 +241,30 @@ class UnixSingleInstanceCoordinator implements SingleInstanceCoordinator { } } + /// Synchronously unlinks the bound Unix domain socket file and initiates + /// server teardown for OS termination callbacks (such as macOS + /// `NSApplicationWillTerminateNotification`) where awaiting is impossible. + void releaseSync() { + final server = _server; + _server = null; + if (server != null) { + unawaited(server.close().then((_) {}, onError: (Object _) {})); + } + + final path = _boundSocketPath; + _boundSocketPath = null; + if (path != null) { + try { + final file = File(path); + if (file.existsSync()) { + file.deleteSync(); + } + } catch (_) { + // Best-effort cleanup of our domain socket file on shutdown. + } + } + } + @override Future release() async { final server = _server; diff --git a/lib/src/testing/native_core_testing.dart b/lib/src/testing/native_core_testing.dart index 033ef78..b0721b0 100644 --- a/lib/src/testing/native_core_testing.dart +++ b/lib/src/testing/native_core_testing.dart @@ -3,11 +3,30 @@ library; export '../platform/linux/linux_window_adapter.dart' - show LinuxSignalLifecycle, selectPrimaryLinuxToplevel; + show + LinuxPresentAction, + LinuxSignalLifecycle, + resolveLinuxPresentAction, + selectPrimaryLinuxToplevel; +export '../platform/macos/macos_appkit_bindings.dart' + show + debugRunMacOSWillTerminateObserverProbe, + kNSApplicationActivationPolicyAccessory, + kNSApplicationActivationPolicyProhibited, + kNSApplicationActivationPolicyRegular; export '../platform/macos/macos_window_adapter.dart' - show MacOSActivationPlan, resolveMacOSActivationPlan; + show + MacOSActivationPlan, + MacOSActivationPolicyProbeResult, + debugRunMacOSStatusItemActivationPolicyProbe, + resolveMacOSActivationPlan, + shouldRestoreMacOSActivationPolicyOnShow, + shouldSwitchMacOSActivationPolicyOnHide; export '../platform/macos/macos_window_delegate.dart' - show debugHasMacOSReplaceMethodSymbol; + show + MacOSWindowCloseProbeResult, + debugHasMacOSReplaceMethodSymbol, + debugRunMacOSWindowShouldCloseProbe; export '../platform/unix_single_instance.dart' show UnixSingleInstanceCoordinator, resolveUnixSingleInstanceSocketPath; export '../platform/windows/windows_frame_subclass.dart' @@ -32,3 +51,4 @@ export '../single_instance.dart' SingleInstanceCoordinator, computeSingleInstanceHash, sanitizeSingleInstanceToken; +export '../window.dart' show shouldForwardAppExitToWindowClose; diff --git a/lib/src/window.dart b/lib/src/window.dart index 1708363..6fefc07 100644 --- a/lib/src/window.dart +++ b/lib/src/window.dart @@ -14,6 +14,27 @@ import 'platform/window_adapter.dart'; import 'platform/windows/windows_window_adapter.dart'; import 'platform/windows/windows_window_finder.dart'; +/// Pure policy deciding whether Flutter's [WidgetsBindingObserver.didRequestAppExit] +/// should be forwarded to [Window.dispatchCloseRequested]. +/// +/// * **Windows**: `true` — `Alt+F4` and taskbar "Close window" deliver +/// `WM_CLOSE` through Flutter's `didRequestAppExit`. +/// * **macOS**: `false` — window close buttons (`[X]` / `Cmd+W`) are already +/// intercepted natively by `NSWindowDelegate.windowShouldClose:`, whereas +/// `didRequestAppExit` signals an explicit OS-level application quit (Dock +/// Quit / `Cmd+Q`) that must be allowed to terminate cleanly. +/// * **Linux**: `false` — window close buttons and `Alt+F4` are intercepted +/// natively by GTK's `delete-event` signal, whereas `didRequestAppExit` +/// signals application termination. +bool shouldForwardAppExitToWindowClose({ + required bool isWindows, + required bool isMacOS, + required bool isLinux, +}) { + if (isMacOS || isLinux) return false; + return isWindows; +} + /// Manages active desktop [Window] instances for the current process. class WindowManager { WindowManager._(); @@ -239,9 +260,16 @@ class Window with WidgetsBindingObserver implements WindowAdapterEventSink { @override Future didRequestAppExit() async { - return dispatchCloseRequested() - ? AppExitResponse.exit - : AppExitResponse.cancel; + if (shouldForwardAppExitToWindowClose( + isWindows: Platform.isWindows, + isMacOS: Platform.isMacOS, + isLinux: Platform.isLinux, + )) { + return dispatchCloseRequested() + ? AppExitResponse.exit + : AppExitResponse.cancel; + } + return AppExitResponse.exit; } /// Registers a callback for window events and returns its [ListenerId]. @@ -403,6 +431,10 @@ class Window with WidgetsBindingObserver implements WindowAdapterEventSink { /// Centers the window within the primary display's usable work area. void center() { + if (_adapter case final LinuxWindowAdapter linux) { + linux.centerNative(); + return; + } final current = bounds; final displays = DisplayManager.instance.getAll(); if (displays.isNotEmpty) { diff --git a/pubspec.yaml b/pubspec.yaml index a602ae3..a4c65cf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: native_core description: Zero-dependency desktop window, display, and single-instance lifecycle primitives for Flutter across Linux, macOS, and Windows. -version: 1.0.0 +version: 1.0.1 homepage: https://github.com/infradise/native_core repository: https://github.com/infradise/native_core issue_tracker: https://github.com/infradise/native_core/issues diff --git a/test/linux_window_test.dart b/test/linux_window_test.dart index 3e841c4..681f366 100644 --- a/test/linux_window_test.dart +++ b/test/linux_window_test.dart @@ -84,6 +84,82 @@ void main() { }, ); + test( + 'resolveLinuxPresentAction prevents unmapped Wayland present_with_time(0) while preserving X11 and mapped focus', + () { + // Wayland startup (before first-frame map): show() uses widgetShowOnly, + // immediate synchronous focus() becomes noop so Mutter never emits + // an unauthenticated " is ready" attention notification. + expect( + resolveLinuxPresentAction( + isShow: true, + isX11: false, + isVisible: false, + isMapped: false, + ), + LinuxPresentAction.widgetShowOnly, + ); + expect( + resolveLinuxPresentAction( + isShow: false, + isX11: false, + isVisible: true, + isMapped: false, + ), + LinuxPresentAction.noop, + ); + // Wayland focus() on a hidden unmapped window still shows it. + expect( + resolveLinuxPresentAction( + isShow: false, + isX11: false, + isVisible: false, + isMapped: false, + ), + LinuxPresentAction.widgetShowOnly, + ); + // Wayland already-mapped window uses gtk_window_present_with_time. + expect( + resolveLinuxPresentAction( + isShow: true, + isX11: false, + isVisible: true, + isMapped: true, + ), + LinuxPresentAction.presentWithTime, + ); + expect( + resolveLinuxPresentAction( + isShow: false, + isX11: false, + isVisible: true, + isMapped: true, + ), + LinuxPresentAction.presentWithTime, + ); + // X11 hidden show() maps via widgetShowOnly; focus() presents with + // fresh X11 server timestamp. + expect( + resolveLinuxPresentAction( + isShow: true, + isX11: true, + isVisible: false, + isMapped: false, + ), + LinuxPresentAction.widgetShowOnly, + ); + expect( + resolveLinuxPresentAction( + isShow: false, + isX11: true, + isVisible: true, + isMapped: false, + ), + LinuxPresentAction.presentWithTime, + ); + }, + ); + test('Linux GTK helpers are safe no-ops on non-Linux hosts', () { if (Platform.isLinux) return; final fake = Window.fakeForTesting(); diff --git a/test/macos_window_test.dart b/test/macos_window_test.dart index 12cdd21..b02758b 100644 --- a/test/macos_window_test.dart +++ b/test/macos_window_test.dart @@ -46,5 +46,101 @@ void main() { expect(displays.first.workArea.height, greaterThan(0)); }, ); + + test( + 'shouldSwitchMacOSActivationPolicyOnHide switches to Accessory only when a status item is active and no other app window is visible', + () { + expect( + shouldSwitchMacOSActivationPolicyOnHide( + hasActiveStatusItem: true, + hasOtherVisibleAppWindow: false, + isVisibleInTaskbar: true, + ), + isTrue, + ); + expect( + shouldSwitchMacOSActivationPolicyOnHide( + hasActiveStatusItem: false, + hasOtherVisibleAppWindow: false, + isVisibleInTaskbar: true, + ), + isFalse, + ); + expect( + shouldSwitchMacOSActivationPolicyOnHide( + hasActiveStatusItem: true, + hasOtherVisibleAppWindow: true, + isVisibleInTaskbar: true, + ), + isFalse, + ); + expect( + shouldSwitchMacOSActivationPolicyOnHide( + hasActiveStatusItem: true, + hasOtherVisibleAppWindow: false, + isVisibleInTaskbar: false, + ), + isFalse, + ); + + expect( + shouldRestoreMacOSActivationPolicyOnShow( + switchedToAccessoryOnHide: true, + isVisibleInTaskbar: true, + currentActivationPolicy: kNSApplicationActivationPolicyAccessory, + ), + isTrue, + ); + expect( + shouldRestoreMacOSActivationPolicyOnShow( + switchedToAccessoryOnHide: false, + isVisibleInTaskbar: false, + currentActivationPolicy: kNSApplicationActivationPolicyAccessory, + ), + isFalse, + ); + expect( + shouldRestoreMacOSActivationPolicyOnShow( + switchedToAccessoryOnHide: false, + isVisibleInTaskbar: true, + currentActivationPolicy: kNSApplicationActivationPolicyRegular, + ), + isFalse, + ); + }, + ); + + test( + 'live macOS NativeCoreWindowDelegate dispatches windowShouldClose: and NSWindowDidBecomeKeyNotification via objc_msgSend', + () { + if (!Platform.isMacOS) return; + final probe = debugRunMacOSWindowShouldCloseProbe(); + expect(probe, isNotNull); + expect(probe!.cancelReturnedFalse, isTrue); + expect(probe.allowReturnedTrue, isTrue); + expect(probe.becameKeyDispatched, isTrue); + }, + ); + + test( + 'live macOS status item detection and NSApplication activation policy transitions succeed', + () { + if (!Platform.isMacOS) return; + final probe = debugRunMacOSStatusItemActivationPolicyProbe(); + expect(probe, isNotNull); + expect(probe!.detectedStatusBarWindowWhileActive, isTrue); + expect(probe.switchedToAccessoryPolicy, isTrue); + expect(probe.restoredRegularPolicy, isTrue); + expect(probe.clearedStatusBarWindowAfterRemove, isTrue); + }, + ); + + test( + 'live macOS NSApplicationWillTerminateNotification observer dispatches cleanup callbacks', + () { + if (!Platform.isMacOS) return; + expect(debugRunMacOSWillTerminateObserverProbe(), isTrue); + }, + ); }); } diff --git a/test/window_facade_test.dart b/test/window_facade_test.dart index 58f65d4..fd85e67 100644 --- a/test/window_facade_test.dart +++ b/test/window_facade_test.dart @@ -1,10 +1,13 @@ import 'dart:ffi' as ffi; -import 'dart:ui' show Color, Offset, Rect, Size; +import 'dart:io'; +import 'dart:ui' show AppExitResponse, Color, Offset, Rect, Size; import 'package:flutter_test/flutter_test.dart'; import 'package:native_core/native_core.dart'; // ignore: implementation_imports import 'package:native_core/src/ffi/native_memory.dart'; +// ignore: implementation_imports +import 'package:native_core/src/testing/native_core_testing.dart'; void main() { group('Window facade, models, diagnostics, and NativeMemory', () { @@ -138,5 +141,48 @@ void main() { window.dispose(); }, ); + + test( + 'shouldForwardAppExitToWindowClose isolates Windows WM_CLOSE from macOS/Linux app termination', + () async { + expect( + shouldForwardAppExitToWindowClose( + isWindows: true, + isMacOS: false, + isLinux: false, + ), + isTrue, + ); + expect( + shouldForwardAppExitToWindowClose( + isWindows: false, + isMacOS: true, + isLinux: false, + ), + isFalse, + ); + expect( + shouldForwardAppExitToWindowClose( + isWindows: false, + isMacOS: false, + isLinux: true, + ), + isFalse, + ); + + final window = Window.fakeForTesting(); + window.addListener((event) { + if (event is WindowCloseRequestedEvent) { + event.request.cancel(); + } + }); + final response = await window.didRequestAppExit(); + expect( + response, + Platform.isWindows ? AppExitResponse.cancel : AppExitResponse.exit, + ); + window.dispose(); + }, + ); }); }