diff --git a/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h b/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h index 9c32ed9986..6b39687162 100644 --- a/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h +++ b/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h @@ -87,7 +87,7 @@ FLUTTER_DARWIN_EXPORT * * @param connection The result from `setMessageHandlerOnChannel:binaryMessageHandler:`. */ -- (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection; +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_FLUTTERBINARYMESSENGER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannels.mm b/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannels.mm index f5527a438e..eb03ce6913 100644 --- a/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannels.mm +++ b/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannels.mm @@ -70,7 +70,7 @@ static void ResizeChannelBuffer(NSObject* binaryMessenge - (void)setMessageHandler:(FlutterMessageHandler)handler { if (!handler) { if (_connection > 0) { - [_messenger cleanupConnection:_connection]; + [_messenger cleanUpConnection:_connection]; _connection = 0; } else { [_messenger setMessageHandlerOnChannel:_name binaryMessageHandler:nil]; @@ -230,7 +230,7 @@ NSObject const* FlutterMethodNotImplemented = [NSObject new]; - (void)setMethodCallHandler:(FlutterMethodCallHandler)handler { if (!handler) { if (_connection > 0) { - [_messenger cleanupConnection:_connection]; + [_messenger cleanUpConnection:_connection]; _connection = 0; } else { [_messenger setMessageHandlerOnChannel:_name binaryMessageHandler:nil]; diff --git a/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m b/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m index 3c52bddf89..fbefe90a8d 100644 --- a/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m +++ b/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m @@ -43,7 +43,7 @@ return 0; } -- (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection { +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { } @end @@ -184,7 +184,7 @@ OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil]]); [channel setMessageHandler:nil]; - OCMVerify([binaryMessenger cleanupConnection:connection]); + OCMVerify([binaryMessenger cleanUpConnection:connection]); } - (void)testMethodChannelCleanup { @@ -208,7 +208,7 @@ OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil]]); [channel setMethodCallHandler:nil]; - OCMVerify([binaryMessenger cleanupConnection:connection]); + OCMVerify([binaryMessenger cleanUpConnection:connection]); } @end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterBinaryMessengerRelay.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterBinaryMessengerRelay.mm index d0f59a5df9..24f9beb2d2 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterBinaryMessengerRelay.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterBinaryMessengerRelay.mm @@ -46,9 +46,9 @@ } } -- (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection { +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { if (self.parent) { - return [self.parent cleanupConnection:connection]; + return [self.parent cleanUpConnection:connection]; } else { FML_LOG(WARNING) << "Communicating on a dead channel."; } diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm index ac201da0e5..de4f4c20ec 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm @@ -881,7 +881,7 @@ static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSS } } -- (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection { +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { if (_shell && _shell->IsSetup()) { std::string channel = _connections->CleanupConnection(connection); if (!channel.empty()) { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm index cc5ac62d38..59dbefc9e9 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm @@ -1498,8 +1498,8 @@ static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) binaryMessageHandler:handler]; } -- (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection { - [_engine.get().binaryMessenger cleanupConnection:connection]; +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { + [_engine.get().binaryMessenger cleanUpConnection:connection]; } #pragma mark - FlutterTextureRegistry diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm index 44035fd238..df2425c12e 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm @@ -1570,7 +1570,7 @@ fml::RefPtr CreateNewThread(std::string name) { latch.Signal(); }); latch.Wait(); - OCMVerify([messenger cleanupConnection:connection]); + OCMVerify([messenger cleanUpConnection:connection]); [engine stopMocking]; } @end diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h index c5dbb4ab35..12ead38f10 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h @@ -24,7 +24,7 @@ FLUTTER_DARWIN_EXPORT @interface FlutterEngine : NSObject /** - * Initializes an engine with the given viewController. + * Initializes an engine with the given project. * * @param labelPrefix Currently unused; in the future, may be used for labelling threads * as with the iOS FlutterEngine. @@ -34,7 +34,7 @@ FLUTTER_DARWIN_EXPORT project:(nullable FlutterDartProject*)project; /** - * Initializes an engine with the given viewController. + * Initializes an engine that can run headlessly with the given project. * * @param labelPrefix Currently unused; in the future, may be used for labelling threads * as with the iOS FlutterEngine. 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 ab196fa2f7..1206a1ce05 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 @@ -33,6 +33,33 @@ static FlutterLocale FlutterLocaleFromNSLocale(NSLocale* locale) { return flutterLocale; } +#pragma mark - + +// Records an active handler of the messenger (FlutterEngine) that listens to +// platform messages on a given channel. +@interface FlutterEngineHandlerInfo : NSObject + +- (instancetype)initWithConnection:(NSNumber*)connection + handler:(FlutterBinaryMessageHandler)handler; + +@property(nonatomic, readonly) FlutterBinaryMessageHandler handler; +@property(nonatomic, readonly) NSNumber* connection; + +@end + +@implementation FlutterEngineHandlerInfo +- (instancetype)initWithConnection:(NSNumber*)connection + handler:(FlutterBinaryMessageHandler)handler { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _connection = connection; + _handler = handler; + return self; +} +@end + +#pragma mark - + /** * Private interface declaration for FlutterEngine. */ @@ -131,8 +158,12 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi // The project being run by this engine. FlutterDartProject* _project; - // A mapping of channel names to the registered handlers for those channels. - NSMutableDictionary* _messageHandlers; + // A mapping of channel names to the registered information for those channels. + NSMutableDictionary* _messengerHandlers; + + // A self-incremental integer to assign to newly assigned channels as + // identification. + FlutterBinaryMessengerConnection _currentMessengerConnection; // Whether the engine can continue running after the view controller is removed. BOOL _allowHeadlessExecution; @@ -160,7 +191,8 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi NSAssert(self, @"Super init cannot be nil"); _project = project ?: [[FlutterDartProject alloc] init]; - _messageHandlers = [[NSMutableDictionary alloc] init]; + _messengerHandlers = [[NSMutableDictionary alloc] init]; + _currentMessengerConnection = 1; _allowHeadlessExecution = allowHeadlessExecution; _semanticsEnabled = NO; @@ -544,9 +576,9 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi } }; - FlutterBinaryMessageHandler channelHandler = _messageHandlers[channel]; - if (channelHandler) { - channelHandler(messageData, binaryResponseHandler); + FlutterEngineHandlerInfo* handlerInfo = _messengerHandlers[channel]; + if (handlerInfo) { + handlerInfo.handler(messageData, binaryResponseHandler); } else { binaryResponseHandler(nil); } @@ -640,12 +672,27 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(nonnull NSString*)channel binaryMessageHandler: (nullable FlutterBinaryMessageHandler)handler { - _messageHandlers[channel] = [handler copy]; - return 0; + _currentMessengerConnection += 1; + _messengerHandlers[channel] = + [[FlutterEngineHandlerInfo alloc] initWithConnection:@(_currentMessengerConnection) + handler:[handler copy]]; + return _currentMessengerConnection; } -- (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection { - // There hasn't been a need to implement this yet for macOS. +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { + // Find the _messengerHandlers that has the required connection, and record its + // channel. + NSString* foundChannel = nil; + for (NSString* key in [_messengerHandlers allKeys]) { + FlutterEngineHandlerInfo* handlerInfo = [_messengerHandlers objectForKey:key]; + if ([handlerInfo.connection isEqual:@(connection)]) { + foundChannel = key; + break; + } + } + if (foundChannel) { + [_messengerHandlers removeObjectForKey:foundChannel]; + } } #pragma mark - FlutterPluginRegistry 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 56d6a62072..7710c8b459 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 @@ -2,14 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" + +#include + #include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/lib/ui/window/platform_message.h" #include "flutter/shell/platform/common/accessibility_bridge.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" -#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" -#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" #include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/embedder_engine.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/testing/test_dart_native_resolver.h" @@ -405,4 +410,67 @@ TEST(FlutterEngine, DartEntrypointArguments) { EXPECT_TRUE(called); } +// If a channel overrides a previous channel with the same name, cleaning +// the previous channel should not affect the new channel. +// +// This is important when recreating classes that uses a channel, because the +// new instance would create the channel before the first class is deallocated +// and clears the channel. +TEST_F(FlutterEngineTest, MessengerCleanupConnectionWorks) { + FlutterEngine* engine = GetFlutterEngine(); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + + NSString* channel = @"_test_"; + NSData* channel_data = [channel dataUsingEncoding:NSUTF8StringEncoding]; + + // Mock SendPlatformMessage so that if a message is sent to + // "test/send_message", act as if the framework has sent an empty message to + // the channel marked by the `sendOnChannel:message:` call's message. + engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC( + SendPlatformMessage, ([](auto engine_, auto message_) { + if (strcmp(message_->channel, "test/send_message") == 0) { + // The simplest message that is acceptable to a method channel. + std::string message = R"|({"method": "a"})|"; + std::string channel(reinterpret_cast(message_->message), + message_->message_size); + reinterpret_cast(engine_) + ->GetShell() + .GetPlatformView() + ->HandlePlatformMessage(std::make_unique( + channel.c_str(), fml::MallocMapping::Copy(message.c_str(), message.length()), + fml::RefPtr())); + } + return kSuccess; + })); + + __block int record = 0; + + FlutterMethodChannel* channel1 = + [FlutterMethodChannel methodChannelWithName:channel + binaryMessenger:engine.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + [channel1 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + record += 1; + }]; + + [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; + EXPECT_EQ(record, 1); + + FlutterMethodChannel* channel2 = + [FlutterMethodChannel methodChannelWithName:channel + binaryMessenger:engine.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + [channel2 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + record += 10; + }]; + + [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; + EXPECT_EQ(record, 11); + + [channel1 setMethodCallHandler:nil]; + + [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; + EXPECT_EQ(record, 21); +} + } // namespace flutter::testing diff --git a/engine/src/flutter/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerInitialRouteTest.m b/engine/src/flutter/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerInitialRouteTest.m index 49677ee38f..50f70f2a46 100644 --- a/engine/src/flutter/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerInitialRouteTest.m +++ b/engine/src/flutter/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerInitialRouteTest.m @@ -78,8 +78,8 @@ FLUTTER_ASSERT_ARC [self waitForExpectationsWithTimeout:30.0 handler:nil]; - [binaryMessenger cleanupConnection:waitingForStatusConnection]; - [binaryMessenger cleanupConnection:initialRoutTestChannelConnection]; + [binaryMessenger cleanUpConnection:waitingForStatusConnection]; + [binaryMessenger cleanUpConnection:initialRoutTestChannelConnection]; } @end