[macOS] Clearing overridden channel should not affect the latest channel (flutter/engine#29242)

If a class contains a channel, recreating an instance of this class will lead to the following scenario:

- The new channel is created with the same name and assigned with a callback (which overrides the earlier channel's)
- The earlier class is deallocated, deallocating the earlier channel

This PR fixes the problem where the second channel's callback will be cleared by the first channel's deallocation.
This commit is contained in:
Tong Mu
2021-10-26 01:45:50 -07:00
committed by GitHub
parent 641bca6a4c
commit 056234966b
11 changed files with 143 additions and 28 deletions

View File

@@ -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_

View File

@@ -70,7 +70,7 @@ static void ResizeChannelBuffer(NSObject<FlutterBinaryMessenger>* 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];

View File

@@ -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

View File

@@ -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.";
}

View File

@@ -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()) {

View File

@@ -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

View File

@@ -1570,7 +1570,7 @@ fml::RefPtr<fml::TaskRunner> CreateNewThread(std::string name) {
latch.Signal();
});
latch.Wait();
OCMVerify([messenger cleanupConnection:connection]);
OCMVerify([messenger cleanUpConnection:connection]);
[engine stopMocking];
}
@end

View File

@@ -24,7 +24,7 @@ FLUTTER_DARWIN_EXPORT
@interface FlutterEngine : NSObject <FlutterTextureRegistry, FlutterPluginRegistry>
/**
* 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.

View File

@@ -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<NSString*, FlutterBinaryMessageHandler>* _messageHandlers;
// A mapping of channel names to the registered information for those channels.
NSMutableDictionary<NSString*, FlutterEngineHandlerInfo*>* _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

View File

@@ -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 <functional>
#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<const char*>(message_->message),
message_->message_size);
reinterpret_cast<EmbedderEngine*>(engine_)
->GetShell()
.GetPlatformView()
->HandlePlatformMessage(std::make_unique<PlatformMessage>(
channel.c_str(), fml::MallocMapping::Copy(message.c_str(), message.length()),
fml::RefPtr<PlatformMessageResponse>()));
}
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

View File

@@ -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