From 0f08a911aa85121e5959233d7d9ca6295d52ad43 Mon Sep 17 00:00:00 2001 From: stuartmorgan Date: Fri, 11 Aug 2023 12:57:06 -0700 Subject: [PATCH] Allow macOS plugins to register as app delegates (flutter/engine#44587) Adds `addApplicationDelegate:` to the macOS plugin registrar, following the corresponding iOS method, and wires it up to the existing app delegation forwarding that was recently added for use at the application level. (The actual delegate is non-trivially different between iOS and macOS, but that's not resolveable without a complex migration on the iOS side, so the APIs currently diverge after the level of the `addApplicationDelegate:` method itself.) This doesn't add any new methods to the delegation; those will be added in a follow-up PR. Also fixes a retain cycle in the termination handler that prevented the new test from working. Most of https://github.com/flutter/flutter/issues/41471 [C++, Objective-C, Java style guides]: https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style --- .../Source/FlutterBinaryMessengerRelay.mm | 2 +- .../framework/Headers/FlutterAppDelegate.h | 39 +++++--- .../Headers/FlutterAppLifecycleDelegate.h | 2 +- .../framework/Headers/FlutterPluginMacOS.h | 3 +- .../Headers/FlutterPluginRegistrarMacOS.h | 7 ++ .../macos/framework/Source/FlutterEngine.mm | 45 +++++++-- .../framework/Source/FlutterEngineTest.mm | 98 ++++++++++++++++++- 7 files changed, 169 insertions(+), 27 deletions(-) diff --git a/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm b/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm index 2b75609c02..4b13093666 100644 --- a/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm +++ b/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm @@ -14,7 +14,7 @@ FLUTTER_ASSERT_ARC - (instancetype)initWithParent:(NSObject*)parent { self = [super init]; if (self != nil) { - self.parent = parent; + _parent = parent; } return self; } diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h index c7aaeca37e..5130b487e2 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h @@ -10,6 +10,30 @@ #import "FlutterAppLifecycleDelegate.h" #import "FlutterMacros.h" +/** + * A protocol to be implemented by the `NSApplicationDelegate` of an application to enable the + * Flutter framework and any Flutter plugins to register to receive application life cycle events. + * + * Implementers should forward all of the `NSApplicationDelegate` methods corresponding to the + * handlers in FlutterAppLifecycleDelegate to any registered delegates. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterAppLifecycleProvider + +/** + * Adds an object implementing |FlutterAppLifecycleDelegate| to the list of + * delegates to be informed of application lifecycle events. + */ +- (void)addApplicationLifecycleDelegate:(nonnull NSObject*)delegate; + +/** + * Removes an object implementing |FlutterAppLifecycleDelegate| to the list of + * delegates to be informed of application lifecycle events. + */ +- (void)removeApplicationLifecycleDelegate:(nonnull NSObject*)delegate; + +@end + /** * |NSApplicationDelegate| subclass for simple apps that want default behavior. * @@ -20,13 +44,14 @@ * * Updates the main Flutter window's title to match the name in the app's Info.plist. * |mainFlutterWindow| must be set before the application finishes launching for this to take * effect. + * * Forwards `NSApplicationDelegate` callbacks to plugins that register for them. * * App delegates for Flutter applications are *not* required to inherit from * this class. Developers of custom app delegate classes should copy and paste * code as necessary from FlutterAppDelegate.mm. */ FLUTTER_DARWIN_EXPORT -@interface FlutterAppDelegate : NSObject +@interface FlutterAppDelegate : NSObject /** * The application menu in the menu bar. @@ -39,18 +64,6 @@ FLUTTER_DARWIN_EXPORT */ @property(weak, nonatomic) IBOutlet NSWindow* mainFlutterWindow; -/** - * Adds an object implementing |FlutterAppLifecycleDelegate| to the list of - * delegates to be informed of application lifecycle events. - */ -- (void)addApplicationLifecycleDelegate:(NSObject*)delegate; - -/** - * Removes an object implementing |FlutterAppLifecycleDelegate| to the list of - * delegates to be informed of application lifecycle events. - */ -- (void)removeApplicationLifecycleDelegate:(NSObject*)delegate; - @end #endif // FLUTTER_FLUTTERAPPDELEGATE_H_ diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h index fd8d52de20..50ad8d3c5f 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h @@ -9,7 +9,6 @@ #include #import "FlutterMacros.h" -#import "FlutterPluginMacOS.h" NS_ASSUME_NONNULL_BEGIN @@ -18,6 +17,7 @@ NS_ASSUME_NONNULL_BEGIN * Protocol for listener of lifecycle events from the NSApplication, typically a * FlutterPlugin. */ +FLUTTER_DARWIN_EXPORT @protocol FlutterAppLifecycleDelegate @optional diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h index af8e0dd686..653f7052bb 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h @@ -4,6 +4,7 @@ #import +#import "FlutterAppLifecycleDelegate.h" #import "FlutterChannels.h" #import "FlutterCodecs.h" #import "FlutterMacros.h" @@ -22,7 +23,7 @@ NS_ASSUME_NONNULL_BEGIN * expand over time to more closely match the functionality of the iOS FlutterPlugin. */ FLUTTER_DARWIN_EXPORT -@protocol FlutterPlugin +@protocol FlutterPlugin /** * Creates an instance of the plugin to register with |registrar| using the desired diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h index 86746c8bb3..5affc8d0fe 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h @@ -52,6 +52,13 @@ FLUTTER_DARWIN_EXPORT - (void)addMethodCallDelegate:(nonnull id)delegate channel:(nonnull FlutterMethodChannel*)channel; +/** + * Registers the plugin as a receiver of `NSApplicationDelegate` calls. + * + * @param delegate The receiving object, such as the plugin's main class. + */ +- (void)addApplicationDelegate:(nonnull NSObject*)delegate; + /** * Registers a `FlutterPlatformViewFactory` for creation of platform views. * diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm index 648c5d213b..a48ed892d4 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm @@ -90,6 +90,11 @@ constexpr char kTextPlainFormat[] = "text/plain"; */ @property(nonatomic, strong) NSMutableArray* isResponseValid; +/** + * All delegates added via plugin calls to addApplicationDelegate. + */ +@property(nonatomic, strong) NSPointerArray* pluginAppDelegates; + - (nullable FlutterViewController*)viewControllerForId:(FlutterViewId)viewId; /** @@ -165,7 +170,7 @@ constexpr char kTextPlainFormat[] = "text/plain"; #pragma mark - @implementation FlutterEngineTerminationHandler { - FlutterEngine* _engine; + __weak FlutterEngine* _engine; FlutterTerminationCallback _terminator; } @@ -320,6 +325,16 @@ constexpr char kTextPlainFormat[] = "text/plain"; }]; } +- (void)addApplicationDelegate:(NSObject*)delegate { + id appDelegate = [[NSApplication sharedApplication] delegate]; + if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) { + id lifeCycleProvider = + static_cast>(appDelegate); + [lifeCycleProvider addApplicationLifecycleDelegate:delegate]; + [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate]; + } +} + - (void)registerViewFactory:(nonnull NSObject*)factory withId:(nonnull NSString*)factoryId { [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId]; @@ -421,6 +436,8 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi _visible = NO; _project = project ?: [[FlutterDartProject alloc] init]; _messengerHandlers = [[NSMutableDictionary alloc] init]; + _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self]; + _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray]; _currentMessengerConnection = 1; _allowHeadlessExecution = allowHeadlessExecution; _semanticsEnabled = NO; @@ -448,12 +465,12 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi [self setUpAccessibilityChannel]; [self setUpNotificationCenterListeners]; id appDelegate = [[NSApplication sharedApplication] delegate]; - const SEL selector = @selector(addApplicationLifecycleDelegate:); - if ([appDelegate respondsToSelector:selector]) { + if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) { _terminationHandler = [[FlutterEngineTerminationHandler alloc] initWithEngine:self terminator:nil]; - FlutterAppDelegate* flutterAppDelegate = reinterpret_cast(appDelegate); - [flutterAppDelegate addApplicationLifecycleDelegate:self]; + id lifecycleProvider = + static_cast>(appDelegate); + [lifecycleProvider addApplicationLifecycleDelegate:self]; } else { _terminationHandler = nil; } @@ -462,10 +479,20 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi } - (void)dealloc { - FlutterAppDelegate* appDelegate = - reinterpret_cast([[NSApplication sharedApplication] delegate]); - if (appDelegate != nil) { - [appDelegate removeApplicationLifecycleDelegate:self]; + id appDelegate = [[NSApplication sharedApplication] delegate]; + if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) { + id lifecycleProvider = + static_cast>(appDelegate); + [lifecycleProvider removeApplicationLifecycleDelegate:self]; + + // Unregister any plugins that registered as app delegates, since they are not guaranteed to + // live after the engine is destroyed, and their delegation registration is intended to be bound + // to the engine and its lifetime. + for (id delegate in _pluginAppDelegates) { + if (delegate) { + [lifecycleProvider removeApplicationLifecycleDelegate:delegate]; + } + } } @synchronized(_isResponseValid) { [_isResponseValid removeAllObjects]; diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm index cf384cfd1b..fee6cdefad 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm @@ -7,8 +7,10 @@ #include +#include #include #include +#include #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/lib/ui/window/platform_message.h" @@ -16,6 +18,8 @@ #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" #include "flutter/shell/platform/embedder/embedder.h" @@ -59,6 +63,60 @@ constexpr int64_t kImplicitViewId = 0ll; } @end +#pragma mark - + +@interface FakeLifecycleProvider : NSObject + +@property(nonatomic, strong, readonly) NSPointerArray* registeredDelegates; + +// True if the given delegate is currently registered. +- (BOOL)hasDelegate:(nonnull NSObject*)delegate; +@end + +@implementation FakeLifecycleProvider { + /** + * All currently registered delegates. + * + * This does not use NSPointerArray or any other weak-pointer + * system, because a weak pointer will be nil'd out at the start of dealloc, which will break + * queries. E.g., if a delegate is dealloc'd without being unregistered, a weak pointer array + * would no longer contain that pointer even though removeApplicationLifecycleDelegate: was never + * called, causing tests to pass incorrectly. + */ + std::vector _delegates; +} + +- (void)addApplicationLifecycleDelegate:(nonnull NSObject*)delegate { + _delegates.push_back((__bridge void*)delegate); +} + +- (void)removeApplicationLifecycleDelegate: + (nonnull NSObject*)delegate { + auto delegateIndex = std::find(_delegates.begin(), _delegates.end(), (__bridge void*)delegate); + NSAssert(delegateIndex != _delegates.end(), + @"Attempting to unregister a delegate that was not registered."); + _delegates.erase(delegateIndex); +} + +- (BOOL)hasDelegate:(nonnull NSObject*)delegate { + return std::find(_delegates.begin(), _delegates.end(), (__bridge void*)delegate) != + _delegates.end(); +} + +@end + +#pragma mark - + +@interface FakeAppDelegatePlugin : NSObject +@end + +@implementation FakeAppDelegatePlugin ++ (void)registerWithRegistrar:(id)registrar { +} +@end + +#pragma mark - + namespace flutter::testing { TEST_F(FlutterEngineTest, CanLaunch) { @@ -515,7 +573,7 @@ TEST_F(FlutterEngineTest, FlutterBinaryMessengerDoesNotRetainEngine) { ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project - allowHeadlessExecution:true]; + allowHeadlessExecution:YES]; weakEngine = engine; binaryMessenger = engine.binaryMessenger; } @@ -539,7 +597,7 @@ TEST_F(FlutterEngineTest, FlutterTextureRegistryDoesNotReturnEngine) { ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project - allowHeadlessExecution:true]; + allowHeadlessExecution:YES]; id registrar = [engine registrarForPlugin:@"MyPlugin"]; textureRegistry = registrar.textures; } @@ -956,6 +1014,42 @@ TEST_F(FlutterEngineTest, HandleLifecycleStates) API_AVAILABLE(macos(10.9)) { [mockApplication stopMocking]; } +TEST_F(FlutterEngineTest, ForwardsPluginDelegateRegistration) { + id previousDelegate = [[NSApplication sharedApplication] delegate]; + FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init]; + [NSApplication sharedApplication].delegate = fakeAppDelegate; + + FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init]; + FlutterEngine* engine = CreateMockFlutterEngine(nil); + + [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin]; + + EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]); + + [NSApplication sharedApplication].delegate = previousDelegate; +} + +TEST_F(FlutterEngineTest, UnregistersPluginsOnEngineDestruction) { + id previousDelegate = [[NSApplication sharedApplication] delegate]; + FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init]; + [NSApplication sharedApplication].delegate = fakeAppDelegate; + + FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init]; + + @autoreleasepool { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + + [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin]; + EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]); + } + + // When the engine is released, it should unregister any plugins it had + // registered on its behalf. + EXPECT_FALSE([fakeAppDelegate hasDelegate:plugin]); + + [NSApplication sharedApplication].delegate = previousDelegate; +} + } // namespace flutter::testing // NOLINTEND(clang-analyzer-core.StackAddressEscape)