15 #include "flutter/fml/synchronization/waitable_event.h"
16 #include "flutter/lib/ui/window/platform_message.h"
18 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
21 #import "flutter/shell/platform/darwin/common/test_utils_swift/test_utils_swift.h"
22 #import "flutter/shell/platform/darwin/macos/InternalFlutterSwift/InternalFlutterSwift.h"
30 #include "flutter/shell/platform/embedder/embedder.h"
31 #include "flutter/shell/platform/embedder/embedder_engine.h"
32 #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
33 #include "flutter/testing/stream_capture.h"
34 #include "flutter/testing/test_dart_native_resolver.h"
35 #include "gtest/gtest.h"
55 arguments:(nullable id)args {
56 return viewIdentifier == 42 ? [[NSView alloc] init] : nil;
65 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication* _Nonnull)sender {
67 return NSTerminateCancel;
75 @property(nonatomic, strong, readonly) NSPointerArray* registeredDelegates;
78 - (BOOL)hasDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate;
91 std::vector<void*> _delegates;
94 - (void)addApplicationLifecycleDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate {
95 _delegates.push_back((__bridge
void*)delegate);
98 - (void)removeApplicationLifecycleDelegate:
99 (nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate {
100 auto delegateIndex = std::find(_delegates.begin(), _delegates.end(), (__bridge
void*)delegate);
101 NSAssert(delegateIndex != _delegates.end(),
102 @"Attempting to unregister a delegate that was not registered.");
103 _delegates.erase(delegateIndex);
106 - (BOOL)hasDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate {
107 return std::find(_delegates.begin(), _delegates.end(), (__bridge
void*)delegate) !=
119 + (void)registerWithRegistrar:(id<FlutterPluginRegistrar>)registrar {
129 - (NSArray<NSScreen*>*)screens {
130 id mockScreen = OCMClassMock([NSScreen
class]);
131 OCMStub([mockScreen backingScaleFactor]).andReturn(2.0);
132 OCMStub([mockScreen deviceDescription]).andReturn(@{
133 @"NSScreenNumber" : [NSNumber numberWithInt:10]
135 OCMStub([mockScreen frame]).andReturn(NSMakeRect(10, 20, 30, 40));
136 return [NSArray arrayWithObject:mockScreen];
146 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
147 ASSERT_TRUE(engine.running);
152 std::string executable_name = [[engine executableName] UTF8String];
153 ASSERT_FALSE(executable_name.empty());
157 AddFfiNativeCallback(
"NotifyStringValue", CREATE_FFI_LAMBDA([&](Dart_Handle value) {
158 const auto dart_string =
159 tonic::DartConverter<std::string>::FromDart(value);
160 EXPECT_EQ(executable_name, dart_string);
165 EXPECT_TRUE([engine runWithEntrypoint:
@"executableNameNotNull"]);
168 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
172 #ifndef FLUTTER_RELEASE
174 setenv(
"FLUTTER_ENGINE_SWITCHES",
"2", 1);
175 setenv(
"FLUTTER_ENGINE_SWITCH_1",
"abc", 1);
176 setenv(
"FLUTTER_ENGINE_SWITCH_2",
"foo=\"bar, baz\"", 1);
179 std::vector<std::string> switches = engine.switches;
180 ASSERT_EQ(switches.size(), 2UL);
181 EXPECT_EQ(switches[0],
"--abc");
182 EXPECT_EQ(switches[1],
"--foo=\"bar, baz\"");
184 unsetenv(
"FLUTTER_ENGINE_SWITCHES");
185 unsetenv(
"FLUTTER_ENGINE_SWITCH_1");
186 unsetenv(
"FLUTTER_ENGINE_SWITCH_2");
191 NSString* fixtures = @(flutter::testing::GetFixturesPath());
193 initWithAssetsPath:fixtures
194 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
195 EXPECT_TRUE([project enableSDFs]);
200 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
202 NSData* test_message = [@"a message" dataUsingEncoding:NSUTF8StringEncoding];
205 engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC(
206 SendPlatformMessage, ([&called, test_message](
auto engine,
auto message) {
208 EXPECT_STREQ(message->channel,
"test");
209 EXPECT_EQ(memcmp(message->message, test_message.bytes, message->message_size), 0);
213 [engine.binaryMessenger sendOnChannel:@"test" message:test_message];
220 AddFfiNativeCallback(
"SignalNativeTest", CREATE_FFI_LAMBDA([&]() { signaled = YES; }));
223 FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
224 writer.expectedOutput =
@"Hello logging";
225 FlutterLogger.outputWriter = writer;
229 EXPECT_TRUE([engine runWithEntrypoint:
@"canLogToStdout"]);
230 ASSERT_TRUE(engine.running);
233 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
237 EXPECT_TRUE(writer.gotExpectedOutput);
245 AddFfiNativeCallback(
"SignalNativeTest", CREATE_FFI_LAMBDA([&]() {
247 EXPECT_TRUE(rootLayer.backgroundColor != nil);
248 if (rootLayer.backgroundColor != nil) {
249 NSColor* actualBackgroundColor =
250 [NSColor colorWithCGColor:rootLayer.backgroundColor];
251 EXPECT_EQ(actualBackgroundColor, [NSColor blackColor]);
257 EXPECT_TRUE([engine runWithEntrypoint:
@"backgroundTest"]);
258 ASSERT_TRUE(engine.running);
263 [viewController loadView];
264 viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
267 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
276 AddFfiNativeCallback(
"SignalNativeTest", CREATE_FFI_LAMBDA([&]() {
278 EXPECT_TRUE(rootLayer.backgroundColor != nil);
279 if (rootLayer.backgroundColor != nil) {
280 NSColor* actualBackgroundColor =
281 [NSColor colorWithCGColor:rootLayer.backgroundColor];
282 EXPECT_EQ(actualBackgroundColor, [NSColor whiteColor]);
288 EXPECT_TRUE([engine runWithEntrypoint:
@"backgroundTest"]);
289 ASSERT_TRUE(engine.running);
294 [viewController loadView];
295 viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
299 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
306 auto original_init = engine.embedderAPI.Initialize;
307 std::function<void(
const FlutterSemanticsUpdate2*,
void*)> update_semantics_callback;
308 engine.embedderAPI.Initialize = MOCK_ENGINE_PROC(
309 Initialize, ([&update_semantics_callback, &original_init](
310 size_t version,
const FlutterRendererConfig* config,
311 const FlutterProjectArgs* args,
void*
user_data,
auto engine_out) {
312 update_semantics_callback = args->update_semantics_callback2;
313 return original_init(version, config, args,
user_data, engine_out);
315 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
320 [viewController loadView];
322 bool enabled_called =
false;
323 engine.embedderAPI.UpdateSemanticsEnabled =
324 MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](
auto engine,
bool enabled) {
325 enabled_called = enabled;
328 engine.semanticsEnabled = YES;
329 EXPECT_TRUE(enabled_called);
331 FlutterSemanticsNode2 root;
332 FlutterSemanticsFlags flags = FlutterSemanticsFlags{0};
333 FlutterSemanticsFlags child_flags = FlutterSemanticsFlags{0};
335 root.flags2 = &flags;
337 root.actions =
static_cast<FlutterSemanticsAction
>(0);
338 root.text_selection_base = -1;
339 root.text_selection_extent = -1;
343 root.increased_value =
"";
344 root.decreased_value =
"";
346 root.child_count = 1;
347 int32_t children[] = {1};
348 root.children_in_traversal_order = children;
349 root.custom_accessibility_actions_count = 0;
350 root.identifier =
"";
352 FlutterSemanticsNode2 child1;
354 child1.flags2 = &child_flags;
356 child1.actions =
static_cast<FlutterSemanticsAction
>(0);
357 child1.text_selection_base = -1;
358 child1.text_selection_extent = -1;
359 child1.label =
"child 1";
362 child1.increased_value =
"";
363 child1.decreased_value =
"";
365 child1.child_count = 0;
366 child1.custom_accessibility_actions_count = 0;
367 child1.identifier =
"";
369 FlutterSemanticsUpdate2 update;
370 update.node_count = 2;
371 FlutterSemanticsNode2* nodes[] = {&root, &child1};
372 update.nodes = nodes;
373 update.custom_action_count = 0;
374 update_semantics_callback(&update, (__bridge
void*)engine);
377 EXPECT_EQ([engine.
viewController.flutterView.accessibilityChildren count], 1u);
378 NSAccessibilityElement* native_root = engine.
viewController.flutterView.accessibilityChildren[0];
379 EXPECT_TRUE([native_root.accessibilityLabel isEqualToString:
@"root"]);
380 EXPECT_EQ(native_root.accessibilityRole, NSAccessibilityGroupRole);
381 EXPECT_EQ([native_root.accessibilityChildren count], 1u);
382 NSAccessibilityElement* native_child1 = native_root.accessibilityChildren[0];
383 EXPECT_TRUE([native_child1.accessibilityValue isEqualToString:
@"child 1"]);
384 EXPECT_EQ(native_child1.accessibilityRole, NSAccessibilityStaticTextRole);
385 EXPECT_EQ([native_child1.accessibilityChildren count], 0u);
387 bool semanticsEnabled =
true;
388 engine.embedderAPI.UpdateSemanticsEnabled =
389 MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](
auto engine,
bool enabled) {
390 semanticsEnabled = enabled;
393 engine.semanticsEnabled = NO;
394 EXPECT_FALSE(semanticsEnabled);
396 EXPECT_EQ([engine.
viewController.flutterView.accessibilityChildren count], 0u);
398 [engine setViewController:nil];
404 auto original_init = engine.embedderAPI.Initialize;
405 std::function<void(
const FlutterSemanticsUpdate2*,
void*)> update_semantics_callback;
406 engine.embedderAPI.Initialize = MOCK_ENGINE_PROC(
407 Initialize, ([&update_semantics_callback, &original_init](
408 size_t version,
const FlutterRendererConfig* config,
409 const FlutterProjectArgs* args,
void*
user_data,
auto engine_out) {
410 update_semantics_callback = args->update_semantics_callback2;
411 return original_init(version, config, args,
user_data, engine_out);
413 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
416 bool enabled_called =
false;
417 engine.embedderAPI.UpdateSemanticsEnabled =
418 MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](
auto engine,
bool enabled) {
419 enabled_called = enabled;
422 engine.semanticsEnabled = YES;
423 EXPECT_TRUE(enabled_called);
425 FlutterSemanticsNode2 root;
426 FlutterSemanticsFlags flags = FlutterSemanticsFlags{0};
427 FlutterSemanticsFlags child_flags = FlutterSemanticsFlags{0};
429 root.flags2 = &flags;
431 root.actions =
static_cast<FlutterSemanticsAction
>(0);
432 root.text_selection_base = -1;
433 root.text_selection_extent = -1;
437 root.increased_value =
"";
438 root.decreased_value =
"";
440 root.child_count = 1;
441 int32_t children[] = {1};
442 root.children_in_traversal_order = children;
443 root.custom_accessibility_actions_count = 0;
445 FlutterSemanticsNode2 child1;
447 child1.flags2 = &child_flags;
449 child1.actions =
static_cast<FlutterSemanticsAction
>(0);
450 child1.text_selection_base = -1;
451 child1.text_selection_extent = -1;
452 child1.label =
"child 1";
455 child1.increased_value =
"";
456 child1.decreased_value =
"";
458 child1.child_count = 0;
459 child1.custom_accessibility_actions_count = 0;
461 FlutterSemanticsUpdate2 update;
462 update.node_count = 2;
463 FlutterSemanticsNode2* nodes[] = {&root, &child1};
464 update.nodes = nodes;
465 update.custom_action_count = 0;
468 update_semantics_callback(&update, (__bridge
void*)engine);
474 bool semanticsEnabled =
true;
475 engine.embedderAPI.UpdateSemanticsEnabled =
476 MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](
auto engine,
bool enabled) {
477 semanticsEnabled = enabled;
480 engine.semanticsEnabled = NO;
481 EXPECT_FALSE(semanticsEnabled);
488 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
491 bool enabled_called =
false;
492 engine.embedderAPI.UpdateSemanticsEnabled =
493 MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](
auto engine,
bool enabled) {
494 enabled_called = enabled;
497 engine.semanticsEnabled = YES;
498 EXPECT_TRUE(enabled_called);
508 EXPECT_NE(viewController.accessibilityBridge.lock(),
nullptr);
512 BOOL latch_called = NO;
513 AddFfiNativeCallback(
"SignalNativeTest", CREATE_FFI_LAMBDA([&]() { latch_called = YES; }));
516 EXPECT_TRUE([engine runWithEntrypoint:
@"nativeCallback"]);
517 ASSERT_TRUE(engine.running);
519 while (!latch_called) {
520 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
522 ASSERT_TRUE(latch_called);
526 NSString* fixtures = @(flutter::testing::GetFixturesPath());
528 initWithAssetsPath:fixtures
529 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
535 [viewController loadView];
536 [viewController viewDidLoad];
537 viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
539 EXPECT_TRUE([engine runWithEntrypoint:
@"canCompositePlatformViews"]);
542 withId:@"factory_id"];
543 [engine.platformViewController
547 @"viewType" : @"factory_id",
553 CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
554 CALayer* rootLayer = viewController.flutterView.layer;
555 while (rootLayer.sublayers.count == 0) {
556 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
557 if (CFAbsoluteTimeGetCurrent() - start > 1) {
563 EXPECT_EQ(rootLayer.sublayers.count, 2u);
564 EXPECT_EQ(viewController.flutterView.subviews.count, 1u);
573 auto original_init = engine.embedderAPI.Initialize;
575 engine.embedderAPI.Initialize = MOCK_ENGINE_PROC(
576 Initialize, ([&compositor, &original_init](
577 size_t version,
const FlutterRendererConfig* config,
578 const FlutterProjectArgs* args,
void*
user_data,
auto engine_out) {
579 compositor = *args->compositor;
580 return original_init(version, config, args,
user_data, engine_out);
586 [viewController loadView];
588 EXPECT_TRUE([engine runWithEntrypoint:
@"empty"]);
590 FlutterBackingStoreConfig config = {
591 .struct_size =
sizeof(FlutterBackingStoreConfig),
592 .size = FlutterSize{10, 10},
594 FlutterBackingStore backing_store = {};
595 EXPECT_NE(compositor.create_backing_store_callback,
nullptr);
597 compositor.create_backing_store_callback(&config, &backing_store, compositor.user_data));
600 .type = kFlutterLayerContentTypeBackingStore,
601 .backing_store = &backing_store,
603 std::vector<FlutterLayer*> layers = {&layer};
605 FlutterPresentViewInfo info = {
606 .struct_size =
sizeof(FlutterPresentViewInfo),
608 .layers =
const_cast<const FlutterLayer**
>(layers.data()),
612 EXPECT_NE(compositor.present_view_callback,
nullptr);
613 EXPECT_FALSE(compositor.present_view_callback(&info));
614 EXPECT_TRUE(compositor.collect_backing_store_callback(&backing_store, compositor.user_data));
616 (void)viewController;
621 NSString* fixtures = @(flutter::testing::GetFixturesPath());
623 initWithAssetsPath:fixtures
624 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
626 project.dartEntrypointArguments = @[ @"arg1", @"arg2" ];
630 auto original_init = engine.embedderAPI.Initialize;
631 engine.embedderAPI.Initialize = MOCK_ENGINE_PROC(
632 Initialize, ([&called, &original_init](
size_t version,
const FlutterRendererConfig* config,
633 const FlutterProjectArgs* args,
void*
user_data,
636 EXPECT_EQ(args->dart_entrypoint_argc, 2);
637 NSString* arg1 = [[NSString alloc] initWithCString:args->dart_entrypoint_argv[0]
638 encoding:NSUTF8StringEncoding];
639 NSString* arg2 = [[NSString alloc] initWithCString:args->dart_entrypoint_argv[1]
640 encoding:NSUTF8StringEncoding];
642 EXPECT_TRUE([arg1 isEqualToString:
@"arg1"]);
643 EXPECT_TRUE([arg2 isEqualToString:
@"arg2"]);
645 return original_init(version, config, args,
user_data, engine_out);
648 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
661 id<FlutterBinaryMessenger> binaryMessenger = nil;
664 NSString* fixtures = @(flutter::testing::GetFixturesPath());
666 initWithAssetsPath:fixtures
667 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
670 allowHeadlessExecution:YES];
677 EXPECT_NE(binaryMessenger, nil);
678 EXPECT_EQ(weakEngine, nil);
685 id<FlutterTextureRegistry> textureRegistry;
688 NSString* fixtures = @(flutter::testing::GetFixturesPath());
690 initWithAssetsPath:fixtures
691 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
694 allowHeadlessExecution:YES];
695 id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"MyPlugin"];
696 textureRegistry = registrar.textures;
701 EXPECT_NE(textureRegistry, nil);
702 EXPECT_EQ(weakEngine, nil);
706 NSString* fixtures = @(flutter::testing::GetFixturesPath());
708 initWithAssetsPath:fixtures
709 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
712 allowHeadlessExecution:YES];
714 EXPECT_EQ([engine valuePublishedByPlugin:
@"NoSuchPlugin"], nil);
718 NSString* fixtures = @(flutter::testing::GetFixturesPath());
720 initWithAssetsPath:fixtures
721 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
724 allowHeadlessExecution:YES];
725 NSString* pluginName =
@"MyPlugin";
727 [engine registrarForPlugin:pluginName];
731 EXPECT_EQ([engine valuePublishedByPlugin:pluginName], [NSNull
null]);
735 NSString* fixtures = @(flutter::testing::GetFixturesPath());
737 initWithAssetsPath:fixtures
738 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
741 allowHeadlessExecution:YES];
742 NSString* pluginName =
@"MyPlugin";
743 id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:pluginName];
745 NSString* firstValue =
@"A published value";
746 NSArray* secondValue = @[ @"A different published value" ];
748 [registrar publish:firstValue];
749 EXPECT_EQ([engine valuePublishedByPlugin:pluginName], firstValue);
751 [registrar publish:secondValue];
752 EXPECT_EQ([engine valuePublishedByPlugin:pluginName], secondValue);
756 NSString* fixtures = @(flutter::testing::GetFixturesPath());
758 initWithAssetsPath:fixtures
759 ICUDataPath:[fixtures stringByAppendingPathComponent:@"icudtl.dat"]];
762 allowHeadlessExecution:YES];
763 NSString* publisherPluginName =
@"PublisherPlugin";
764 NSString* readerPluginName =
@"ReaderPlugin";
765 id<FlutterPluginRegistrar> publisher = [engine registrarForPlugin:publisherPluginName];
766 id<FlutterPluginRegistrar> reader = [engine registrarForPlugin:readerPluginName];
768 NSString* publishedValue =
@"A published value";
769 [publisher publish:publishedValue];
771 EXPECT_EQ([reader valuePublishedByPlugin:publisherPluginName], publishedValue);
772 EXPECT_EQ([reader valuePublishedByPlugin:
@"NoSuchPlugin"], nil);
773 EXPECT_EQ([reader valuePublishedByPlugin:readerPluginName], [NSNull
null]);
777 NSString* fixtures = @(flutter::testing::GetFixturesPath());
779 initWithAssetsPath:fixtures
780 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
786 id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"MyPlugin"];
788 EXPECT_EQ([registrar viewController], viewController);
799 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
801 NSString* channel =
@"_test_";
802 NSData* channel_data = [channel dataUsingEncoding:NSUTF8StringEncoding];
807 engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC(
808 SendPlatformMessage, ([](
auto engine_,
auto message_) {
809 if (strcmp(message_->channel,
"test/send_message") == 0) {
811 std::string message = R
"|({"method": "a"})|";
812 std::string channel(reinterpret_cast<const char*>(message_->message),
813 message_->message_size);
814 reinterpret_cast<EmbedderEngine*>(engine_)
817 ->HandlePlatformMessage(std::make_unique<PlatformMessage>(
818 channel.c_str(), fml::MallocMapping::Copy(message.c_str(), message.length()),
819 fml::RefPtr<PlatformMessageResponse>()));
824 __block
int record = 0;
834 [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data];
835 EXPECT_EQ(record, 1);
845 [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data];
846 EXPECT_EQ(record, 11);
850 [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data];
851 EXPECT_EQ(record, 21);
858 __block
bool calledAfterClear =
false;
859 __block
bool valueAfterClear;
861 calledAfterClear =
true;
862 NSNumber* valueNumber = [result valueForKey:@"value"];
863 valueAfterClear = [valueNumber boolValue];
867 [engineMock handleMethodCall:methodCallAfterClear result:resultAfterClear];
868 EXPECT_TRUE(calledAfterClear);
869 EXPECT_FALSE(valueAfterClear);
876 __block
bool called =
false;
880 NSNumber* valueNumber = [result valueForKey:@"value"];
881 value = [valueNumber boolValue];
885 [engineMock handleMethodCall:methodCall result:result];
894 binaryMessenger:engine.binaryMessenger
896 __block BOOL didCallCallback = NO;
900 didCallCallback = YES;
902 EXPECT_TRUE([engine runWithEntrypoint:
@"sendFooMessage"]);
905 while (!didCallCallback) {
906 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
914 binaryMessenger:engine.binaryMessenger
916 __block BOOL didCallCallback = NO;
918 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
920 dispatch_async(dispatch_get_main_queue(), ^{
921 didCallCallback = YES;
925 EXPECT_TRUE([engine runWithEntrypoint:
@"sendFooMessage"]);
927 while (!didCallCallback) {
928 [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
936 std::optional<int64_t> engineId;
937 AddFfiNativeCallback(
"NotifyEngineId", CREATE_FFI_LAMBDA([&](Dart_Handle argument) {
938 if (!Dart_IsNull(argument)) {
939 const auto id = tonic::DartConverter<int64_t>::FromDart(argument);
945 EXPECT_TRUE([engine runWithEntrypoint:
@"testEngineId"]);
947 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
950 EXPECT_TRUE(engineId.has_value());
951 if (!engineId.has_value()) {
954 id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"MyPlugin"];
955 EXPECT_EQ(engine.engineIdentifier, *engineId);
956 EXPECT_EQ(registrar.engineIdentifier, *engineId);
957 EXPECT_EQ(engine, [
FlutterEngine engineForIdentifier:*engineId]);
962 FlutterResizeSynchronizer* threadSynchronizer = [[FlutterResizeSynchronizer alloc] init];
963 [threadSynchronizer shutDown];
965 std::thread rasterThread([&threadSynchronizer] {
966 [threadSynchronizer performCommitForSize:CGSizeMake(100, 100)
976 NSString* fixtures = @(flutter::testing::GetFixturesPath());
978 initWithAssetsPath:fixtures
979 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
989 engine = viewController1.
engine;
1013 allowHeadlessExecution:NO];
1039 NSString* fixtures = @(flutter::testing::GetFixturesPath());
1041 initWithAssetsPath:fixtures
1042 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
1048 [viewController loadView];
1049 [viewController viewDidLoad];
1050 viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
1052 EXPECT_TRUE([engine runWithEntrypoint:
@"drawIntoAllViews"]);
1054 CFTimeInterval start = CACurrentMediaTime();
1055 while (engine.macOSCompositor->DebugNumViews() == 0) {
1056 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
1057 if (CACurrentMediaTime() - start > 1) {
1062 EXPECT_EQ(engine.macOSCompositor->DebugNumViews(), 1u);
1065 EXPECT_EQ(engine.macOSCompositor->DebugNumViews(), 0u);
1073 __block NSString* nextResponse =
@"exit";
1074 __block BOOL triedToTerminate = NO;
1077 terminator:^(id sender) {
1078 triedToTerminate = TRUE;
1081 OCMStub([engineMock terminationHandler]).andReturn(terminationHandler);
1084 [engineMock binaryMessenger])
1085 .andReturn(binaryMessengerMock);
1086 OCMStub([engineMock sendOnChannel:
@"flutter/platform"
1087 message:[OCMArg any]
1088 binaryReply:[OCMArg any]])
1089 .andDo((^(NSInvocation* invocation) {
1090 [invocation retainArguments];
1092 NSData* returnedMessage;
1093 [invocation getArgument:&callback atIndex:4];
1094 if ([nextResponse isEqualToString:
@"error"]) {
1101 NSDictionary* responseDict = @{
@"response" : nextResponse};
1105 callback(returnedMessage);
1107 __block NSString* calledAfterTerminate =
@"";
1109 NSDictionary* resultDict = result;
1110 calledAfterTerminate = resultDict[@"response"];
1117 triedToTerminate = NO;
1118 calledAfterTerminate =
@"";
1119 nextResponse =
@"cancel";
1120 [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1121 EXPECT_STREQ([calledAfterTerminate UTF8String],
"");
1122 EXPECT_TRUE(triedToTerminate);
1126 triedToTerminate = NO;
1127 calledAfterTerminate =
@"";
1128 nextResponse =
@"exit";
1129 [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1130 EXPECT_STREQ([calledAfterTerminate UTF8String],
"exit");
1131 EXPECT_TRUE(triedToTerminate);
1133 triedToTerminate = NO;
1134 calledAfterTerminate =
@"";
1135 nextResponse =
@"cancel";
1136 [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1137 EXPECT_STREQ([calledAfterTerminate UTF8String],
"cancel");
1138 EXPECT_FALSE(triedToTerminate);
1141 triedToTerminate = NO;
1142 calledAfterTerminate =
@"";
1143 nextResponse =
@"error";
1144 [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1145 EXPECT_STREQ([calledAfterTerminate UTF8String],
"");
1146 EXPECT_TRUE(triedToTerminate);
1150 id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate];
1152 [NSApplication sharedApplication].delegate = plainDelegate;
1159 EXPECT_EQ([[[NSApplication sharedApplication] delegate] applicationShouldTerminate:NSApp],
1162 [NSApplication sharedApplication].delegate = previousDelegate;
1166 __block BOOL announced = NO;
1169 OCMStub([engineMock announceAccessibilityMessage:[OCMArg any]
1170 withPriority:NSAccessibilityPriorityMedium])
1171 .andDo((^(NSInvocation* invocation) {
1173 [invocation retainArguments];
1175 [invocation getArgument:&message atIndex:2];
1176 EXPECT_EQ(message,
@"error message");
1179 NSDictionary<NSString*, id>* annotatedEvent =
1180 @{
@"type" :
@"announce",
1181 @"data" : @{
@"message" :
@"error message"}};
1183 [engineMock handleAccessibilityEvent:annotatedEvent];
1185 EXPECT_TRUE(announced);
1195 .andDo((^(NSInvocation* invocation) {
1199 .andDo((^(NSInvocation* invocation) {
1203 .andDo((^(NSInvocation* invocation) {
1207 .andDo((^(NSInvocation* invocation) {
1211 .andDo((^(NSInvocation* invocation) {
1215 __block NSApplicationOcclusionState visibility = NSApplicationOcclusionStateVisible;
1216 id mockApplication = OCMPartialMock([NSApplication sharedApplication]);
1217 OCMStub((NSApplicationOcclusionState)[mockApplication occlusionState])
1218 .andDo(^(NSInvocation* invocation) {
1219 [invocation setReturnValue:&visibility];
1225 __block BOOL windowVisible = YES;
1226 id mockWindow = OCMClassMock([NSWindow
class]);
1227 OCMStub([mockWindow isVisible]).andDo(^(NSInvocation* invocation) {
1228 [invocation setReturnValue:&windowVisible];
1230 OCMStub([mockApplication windows]).andReturn(@[ mockWindow ]);
1232 NSNotification* willBecomeActive =
1233 [[NSNotification alloc] initWithName:NSApplicationWillBecomeActiveNotification
1236 NSNotification* willResignActive =
1237 [[NSNotification alloc] initWithName:NSApplicationWillResignActiveNotification
1241 NSNotification* didChangeOcclusionState;
1242 didChangeOcclusionState =
1243 [[NSNotification alloc] initWithName:NSApplicationDidChangeOcclusionStateNotification
1247 [engineMock handleDidChangeOcclusionState:didChangeOcclusionState];
1250 [engineMock handleWillBecomeActive:willBecomeActive];
1253 [engineMock handleWillResignActive:willResignActive];
1257 [engineMock handleDidChangeOcclusionState:didChangeOcclusionState];
1262 [engineMock handleWillBecomeActive:willBecomeActive];
1267 [engineMock handleWillResignActive:willResignActive];
1273 [engineMock handleDidChangeOcclusionState:didChangeOcclusionState];
1280 [engineMock handleWillBecomeActive:willBecomeActive];
1283 [mockWindow stopMocking];
1284 [mockApplication stopMocking];
1288 id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate];
1290 [NSApplication sharedApplication].delegate = fakeAppDelegate;
1295 [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin];
1297 EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]);
1299 [NSApplication sharedApplication].delegate = previousDelegate;
1303 id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate];
1305 [NSApplication sharedApplication].delegate = fakeAppDelegate;
1312 [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin];
1313 EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]);
1318 EXPECT_FALSE([fakeAppDelegate hasDelegate:plugin]);
1320 [NSApplication sharedApplication].delegate = previousDelegate;
1326 auto original_update_displays = engine.embedderAPI.NotifyDisplayUpdate;
1327 engine.embedderAPI.NotifyDisplayUpdate = MOCK_ENGINE_PROC(
1328 NotifyDisplayUpdate, ([&updated, &original_update_displays](
1329 auto engine,
auto update_type,
auto* displays,
auto display_count) {
1331 return original_update_displays(engine, update_type, displays, display_count);
1334 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
1335 EXPECT_TRUE(updated);
1338 [[NSNotificationCenter defaultCenter]
1339 postNotificationName:NSApplicationDidChangeScreenParametersNotification
1341 EXPECT_TRUE(updated);
1347 auto original_set_viewport_metrics = engine.embedderAPI.SendWindowMetricsEvent;
1348 engine.embedderAPI.SendWindowMetricsEvent = MOCK_ENGINE_PROC(
1349 SendWindowMetricsEvent,
1350 ([&updated, &original_set_viewport_metrics](
auto engine,
auto* window_metrics) {
1352 return original_set_viewport_metrics(engine, window_metrics);
1355 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
1358 [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification
1361 EXPECT_FALSE(updated);
1366 [viewController loadView];
1367 viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
1369 [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification
1371 EXPECT_TRUE(updated);
1375 NSString* fixtures = @(testing::GetFixturesPath());
1377 initWithAssetsPath:fixtures
1378 ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
1379 project.rootIsolateCreateCallback = FlutterEngineTest::IsolateCreateCallback;
1382 allowHeadlessExecution:true];
1384 auto original_update_displays = engine.embedderAPI.NotifyDisplayUpdate;
1385 engine.embedderAPI.NotifyDisplayUpdate = MOCK_ENGINE_PROC(
1386 NotifyDisplayUpdate, ([&updated, &original_update_displays](
1387 auto engine,
auto update_type,
auto* displays,
auto display_count) {
1388 EXPECT_EQ(display_count, 1UL);
1389 EXPECT_EQ(displays->display_id, 10UL);
1390 EXPECT_EQ(displays->width, 60UL);
1391 EXPECT_EQ(displays->height, 80UL);
1392 EXPECT_EQ(displays->device_pixel_ratio, 2UL);
1394 return original_update_displays(engine, update_type, displays, display_count);
1396 EXPECT_TRUE([engine runWithEntrypoint:
@"main"]);
1397 EXPECT_TRUE(updated);
1403 __block BOOL expectedValue;
1407 OCMStub([channelMock messageChannelWithName:
@"flutter/settings"
1408 binaryMessenger:[OCMArg any]
1409 codec:[OCMArg any]])
1410 .andReturn(channelMock);
1411 OCMStub([channelMock sendMessage:[OCMArg any]]).andDo((^(NSInvocation* invocation) {
1413 [invocation getArgument:&message atIndex:2];
1414 EXPECT_EQ(message[
@"alwaysUse24HourFormat"], @(expectedValue));
1418 OCMStub([mockHourFormat isAlwaysUse24HourFormat]).andDo((^(NSInvocation* invocation) {
1419 [invocation setReturnValue:&expectedValue];
1425 expectedValue = YES;
1426 EXPECT_TRUE([engineMock runWithEntrypoint:
@"main"]);
1427 [engineMock shutDownEngine];
1431 EXPECT_TRUE([engineMock runWithEntrypoint:
@"main"]);
1432 [engineMock shutDownEngine];
1435 [mockHourFormat stopMocking];
1436 [engineMock stopMocking];
1437 [channelMock stopMocking];
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterBinaryReply)(NSData *_Nullable reply)
void(^ FlutterResult)(id _Nullable result)
int64_t FlutterViewIdentifier
flutter::FlutterCompositor * macOSCompositor
void setMessageHandler:(FlutterMessageHandler _Nullable handler)
id< FlutterBinaryMessenger > binaryMessenger
FlutterViewController * viewController
instancetype errorWithCode:message:details:(NSString *code,[message] NSString *_Nullable message,[details] id _Nullable details)
instancetype methodCallWithMethodName:arguments:(NSString *method,[arguments] id _Nullable arguments)
void setMethodCallHandler:(FlutterMethodCallHandler _Nullable handler)
instancetype methodChannelWithName:binaryMessenger:codec:(NSString *name,[binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger,[codec] NSObject< FlutterMethodCodec > *codec)
NSColor * backgroundColor
FlutterViewIdentifier viewIdentifier
id CreateMockFlutterEngine(NSString *pasteboardString)
TEST_F(FlutterEngineTest, ReportsHourFormat)
instancetype sharedInstance()