Flutter macOS Embedder
FlutterEngineTest.mm
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
7 
8 #include <objc/objc.h>
9 
10 #include <algorithm>
11 #include <functional>
12 #include <thread>
13 #include <vector>
14 
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"
36 
37 // CREATE_FFI_LAMBDA and MOCK_ENGINE_PROC are leaky by design
38 // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
39 
41 /**
42  * The FlutterCompositor object currently in use by the FlutterEngine.
43  *
44  * May be nil if the compositor has not been initialized yet.
45  */
46 @property(nonatomic, readonly, nullable) flutter::FlutterCompositor* macOSCompositor;
47 
48 @end
49 
51 @end
52 
53 @implementation TestPlatformViewFactory
54 - (nonnull NSView*)createWithViewIdentifier:(FlutterViewIdentifier)viewIdentifier
55  arguments:(nullable id)args {
56  return viewIdentifier == 42 ? [[NSView alloc] init] : nil;
57 }
58 
59 @end
60 
61 @interface PlainAppDelegate : NSObject <NSApplicationDelegate>
62 @end
63 
64 @implementation PlainAppDelegate
65 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication* _Nonnull)sender {
66  // Always cancel, so that the test doesn't exit.
67  return NSTerminateCancel;
68 }
69 @end
70 
71 #pragma mark -
72 
73 @interface FakeLifecycleProvider : NSObject <FlutterAppLifecycleProvider, NSApplicationDelegate>
74 
75 @property(nonatomic, strong, readonly) NSPointerArray* registeredDelegates;
76 
77 // True if the given delegate is currently registered.
78 - (BOOL)hasDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate;
79 @end
80 
81 @implementation FakeLifecycleProvider {
82  /**
83  * All currently registered delegates.
84  *
85  * This does not use NSPointerArray or any other weak-pointer
86  * system, because a weak pointer will be nil'd out at the start of dealloc, which will break
87  * queries. E.g., if a delegate is dealloc'd without being unregistered, a weak pointer array
88  * would no longer contain that pointer even though removeApplicationLifecycleDelegate: was never
89  * called, causing tests to pass incorrectly.
90  */
91  std::vector<void*> _delegates;
92 }
93 
94 - (void)addApplicationLifecycleDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate {
95  _delegates.push_back((__bridge void*)delegate);
96 }
97 
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);
104 }
105 
106 - (BOOL)hasDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate {
107  return std::find(_delegates.begin(), _delegates.end(), (__bridge void*)delegate) !=
108  _delegates.end();
109 }
110 
111 @end
112 
113 #pragma mark -
114 
115 @interface FakeAppDelegatePlugin : NSObject <FlutterPlugin>
116 @end
117 
118 @implementation FakeAppDelegatePlugin
119 + (void)registerWithRegistrar:(id<FlutterPluginRegistrar>)registrar {
120 }
121 @end
122 
123 #pragma mark -
124 
126 @end
127 
128 @implementation MockableFlutterEngine
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]
134  });
135  OCMStub([mockScreen frame]).andReturn(NSMakeRect(10, 20, 30, 40));
136  return [NSArray arrayWithObject:mockScreen];
137 }
138 @end
139 
140 #pragma mark -
141 
142 namespace flutter::testing {
143 
145  FlutterEngine* engine = GetFlutterEngine();
146  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
147  ASSERT_TRUE(engine.running);
148 }
149 
150 TEST_F(FlutterEngineTest, HasNonNullExecutableName) {
151  FlutterEngine* engine = GetFlutterEngine();
152  std::string executable_name = [[engine executableName] UTF8String];
153  ASSERT_FALSE(executable_name.empty());
154 
155  // Block until notified by the Dart test of the value of Platform.executable.
156  BOOL signaled = NO;
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);
161  signaled = YES;
162  }));
163 
164  // Launch the test entrypoint.
165  EXPECT_TRUE([engine runWithEntrypoint:@"executableNameNotNull"]);
166 
167  while (!signaled) {
168  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
169  }
170 }
171 
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);
177 
178  FlutterEngine* engine = GetFlutterEngine();
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\"");
183 
184  unsetenv("FLUTTER_ENGINE_SWITCHES");
185  unsetenv("FLUTTER_ENGINE_SWITCH_1");
186  unsetenv("FLUTTER_ENGINE_SWITCH_2");
187 }
188 #endif // !FLUTTER_RELEASE
189 
190 TEST_F(FlutterEngineTest, EnableSDFsAlwaysReturnsYes) {
191  NSString* fixtures = @(flutter::testing::GetFixturesPath());
192  FlutterDartProject* project = [[FlutterDartProject alloc]
193  initWithAssetsPath:fixtures
194  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
195  EXPECT_TRUE([project enableSDFs]);
196 }
197 
198 TEST_F(FlutterEngineTest, MessengerSend) {
199  FlutterEngine* engine = GetFlutterEngine();
200  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
201 
202  NSData* test_message = [@"a message" dataUsingEncoding:NSUTF8StringEncoding];
203  bool called = false;
204 
205  engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC(
206  SendPlatformMessage, ([&called, test_message](auto engine, auto message) {
207  called = true;
208  EXPECT_STREQ(message->channel, "test");
209  EXPECT_EQ(memcmp(message->message, test_message.bytes, message->message_size), 0);
210  return kSuccess;
211  }));
212 
213  [engine.binaryMessenger sendOnChannel:@"test" message:test_message];
214  EXPECT_TRUE(called);
215 }
216 
217 TEST_F(FlutterEngineTest, CanLogToStdout) {
218  // Block until completion of print statement.
219  BOOL signaled = NO;
220  AddFfiNativeCallback("SignalNativeTest", CREATE_FFI_LAMBDA([&]() { signaled = YES; }));
221 
222  // Replace stdout stream buffer with our own.
223  FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
224  writer.expectedOutput = @"Hello logging";
225  FlutterLogger.outputWriter = writer;
226 
227  // Launch the test entrypoint.
228  FlutterEngine* engine = GetFlutterEngine();
229  EXPECT_TRUE([engine runWithEntrypoint:@"canLogToStdout"]);
230  ASSERT_TRUE(engine.running);
231 
232  while (!signaled) {
233  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
234  }
235 
236  // Verify hello world was written to stdout.
237  EXPECT_TRUE(writer.gotExpectedOutput);
238 }
239 
240 TEST_F(FlutterEngineTest, DISABLED_BackgroundIsBlack) {
241  FlutterEngine* engine = GetFlutterEngine();
242 
243  // Latch to ensure the entire layer tree has been generated and presented.
244  BOOL signaled = NO;
245  AddFfiNativeCallback("SignalNativeTest", CREATE_FFI_LAMBDA([&]() {
246  CALayer* rootLayer = engine.viewController.flutterView.layer;
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]);
252  }
253  signaled = YES;
254  }));
255 
256  // Launch the test entrypoint.
257  EXPECT_TRUE([engine runWithEntrypoint:@"backgroundTest"]);
258  ASSERT_TRUE(engine.running);
259 
260  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
261  nibName:nil
262  bundle:nil];
263  [viewController loadView];
264  viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
265 
266  while (!signaled) {
267  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
268  }
269 }
270 
271 TEST_F(FlutterEngineTest, DISABLED_CanOverrideBackgroundColor) {
272  FlutterEngine* engine = GetFlutterEngine();
273 
274  // Latch to ensure the entire layer tree has been generated and presented.
275  BOOL signaled = NO;
276  AddFfiNativeCallback("SignalNativeTest", CREATE_FFI_LAMBDA([&]() {
277  CALayer* rootLayer = engine.viewController.flutterView.layer;
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]);
283  }
284  signaled = YES;
285  }));
286 
287  // Launch the test entrypoint.
288  EXPECT_TRUE([engine runWithEntrypoint:@"backgroundTest"]);
289  ASSERT_TRUE(engine.running);
290 
291  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
292  nibName:nil
293  bundle:nil];
294  [viewController loadView];
295  viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
296  viewController.flutterView.backgroundColor = [NSColor whiteColor];
297 
298  while (!signaled) {
299  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
300  }
301 }
302 
303 TEST_F(FlutterEngineTest, CanToggleAccessibility) {
304  FlutterEngine* engine = GetFlutterEngine();
305  // Capture the update callbacks before the embedder API initializes.
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);
314  }));
315  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
316  // Set up view controller.
317  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
318  nibName:nil
319  bundle:nil];
320  [viewController loadView];
321  // Enable the semantics.
322  bool enabled_called = false;
323  engine.embedderAPI.UpdateSemanticsEnabled =
324  MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) {
325  enabled_called = enabled;
326  return kSuccess;
327  }));
328  engine.semanticsEnabled = YES;
329  EXPECT_TRUE(enabled_called);
330  // Send flutter semantics updates.
331  FlutterSemanticsNode2 root;
332  FlutterSemanticsFlags flags = FlutterSemanticsFlags{0};
333  FlutterSemanticsFlags child_flags = FlutterSemanticsFlags{0};
334  root.id = 0;
335  root.flags2 = &flags;
336  // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
337  root.actions = static_cast<FlutterSemanticsAction>(0);
338  root.text_selection_base = -1;
339  root.text_selection_extent = -1;
340  root.label = "root";
341  root.hint = "";
342  root.value = "";
343  root.increased_value = "";
344  root.decreased_value = "";
345  root.tooltip = "";
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 = "";
351 
352  FlutterSemanticsNode2 child1;
353  child1.id = 1;
354  child1.flags2 = &child_flags;
355  // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
356  child1.actions = static_cast<FlutterSemanticsAction>(0);
357  child1.text_selection_base = -1;
358  child1.text_selection_extent = -1;
359  child1.label = "child 1";
360  child1.hint = "";
361  child1.value = "";
362  child1.increased_value = "";
363  child1.decreased_value = "";
364  child1.tooltip = "";
365  child1.child_count = 0;
366  child1.custom_accessibility_actions_count = 0;
367  child1.identifier = "";
368 
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);
375 
376  // Verify the accessibility tree is attached to the flutter view.
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);
386  // Disable the semantics.
387  bool semanticsEnabled = true;
388  engine.embedderAPI.UpdateSemanticsEnabled =
389  MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](auto engine, bool enabled) {
390  semanticsEnabled = enabled;
391  return kSuccess;
392  }));
393  engine.semanticsEnabled = NO;
394  EXPECT_FALSE(semanticsEnabled);
395  // Verify the accessibility tree is removed from the view.
396  EXPECT_EQ([engine.viewController.flutterView.accessibilityChildren count], 0u);
397 
398  [engine setViewController:nil];
399 }
400 
401 TEST_F(FlutterEngineTest, CanToggleAccessibilityWhenHeadless) {
402  FlutterEngine* engine = GetFlutterEngine();
403  // Capture the update callbacks before the embedder API initializes.
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);
412  }));
413  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
414 
415  // Enable the semantics without attaching a view controller.
416  bool enabled_called = false;
417  engine.embedderAPI.UpdateSemanticsEnabled =
418  MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) {
419  enabled_called = enabled;
420  return kSuccess;
421  }));
422  engine.semanticsEnabled = YES;
423  EXPECT_TRUE(enabled_called);
424  // Send flutter semantics updates.
425  FlutterSemanticsNode2 root;
426  FlutterSemanticsFlags flags = FlutterSemanticsFlags{0};
427  FlutterSemanticsFlags child_flags = FlutterSemanticsFlags{0};
428  root.id = 0;
429  root.flags2 = &flags;
430  // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
431  root.actions = static_cast<FlutterSemanticsAction>(0);
432  root.text_selection_base = -1;
433  root.text_selection_extent = -1;
434  root.label = "root";
435  root.hint = "";
436  root.value = "";
437  root.increased_value = "";
438  root.decreased_value = "";
439  root.tooltip = "";
440  root.child_count = 1;
441  int32_t children[] = {1};
442  root.children_in_traversal_order = children;
443  root.custom_accessibility_actions_count = 0;
444 
445  FlutterSemanticsNode2 child1;
446  child1.id = 1;
447  child1.flags2 = &child_flags;
448  // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
449  child1.actions = static_cast<FlutterSemanticsAction>(0);
450  child1.text_selection_base = -1;
451  child1.text_selection_extent = -1;
452  child1.label = "child 1";
453  child1.hint = "";
454  child1.value = "";
455  child1.increased_value = "";
456  child1.decreased_value = "";
457  child1.tooltip = "";
458  child1.child_count = 0;
459  child1.custom_accessibility_actions_count = 0;
460 
461  FlutterSemanticsUpdate2 update;
462  update.node_count = 2;
463  FlutterSemanticsNode2* nodes[] = {&root, &child1};
464  update.nodes = nodes;
465  update.custom_action_count = 0;
466  // This call updates semantics for the implicit view, which does not exist,
467  // and therefore this call is invalid. But the engine should not crash.
468  update_semantics_callback(&update, (__bridge void*)engine);
469 
470  // No crashes.
471  EXPECT_EQ(engine.viewController, nil);
472 
473  // Disable the semantics.
474  bool semanticsEnabled = true;
475  engine.embedderAPI.UpdateSemanticsEnabled =
476  MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](auto engine, bool enabled) {
477  semanticsEnabled = enabled;
478  return kSuccess;
479  }));
480  engine.semanticsEnabled = NO;
481  EXPECT_FALSE(semanticsEnabled);
482  // Still no crashes
483  EXPECT_EQ(engine.viewController, nil);
484 }
485 
486 TEST_F(FlutterEngineTest, ProducesAccessibilityTreeWhenAddingViews) {
487  FlutterEngine* engine = GetFlutterEngine();
488  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
489 
490  // Enable the semantics without attaching a view controller.
491  bool enabled_called = false;
492  engine.embedderAPI.UpdateSemanticsEnabled =
493  MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) {
494  enabled_called = enabled;
495  return kSuccess;
496  }));
497  engine.semanticsEnabled = YES;
498  EXPECT_TRUE(enabled_called);
499 
500  EXPECT_EQ(engine.viewController, nil);
501 
502  // Assign the view controller after enabling semantics
503  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
504  nibName:nil
505  bundle:nil];
506  engine.viewController = viewController;
507 
508  EXPECT_NE(viewController.accessibilityBridge.lock(), nullptr);
509 }
510 
511 TEST_F(FlutterEngineTest, NativeCallbacks) {
512  BOOL latch_called = NO;
513  AddFfiNativeCallback("SignalNativeTest", CREATE_FFI_LAMBDA([&]() { latch_called = YES; }));
514 
515  FlutterEngine* engine = GetFlutterEngine();
516  EXPECT_TRUE([engine runWithEntrypoint:@"nativeCallback"]);
517  ASSERT_TRUE(engine.running);
518 
519  while (!latch_called) {
520  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
521  }
522  ASSERT_TRUE(latch_called);
523 }
524 
525 TEST_F(FlutterEngineTest, Compositor) {
526  NSString* fixtures = @(flutter::testing::GetFixturesPath());
527  FlutterDartProject* project = [[FlutterDartProject alloc]
528  initWithAssetsPath:fixtures
529  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
530  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project];
531 
532  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
533  nibName:nil
534  bundle:nil];
535  [viewController loadView];
536  [viewController viewDidLoad];
537  viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
538 
539  EXPECT_TRUE([engine runWithEntrypoint:@"canCompositePlatformViews"]);
540 
541  [engine.platformViewController registerViewFactory:[[TestPlatformViewFactory alloc] init]
542  withId:@"factory_id"];
543  [engine.platformViewController
544  handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create"
545  arguments:@{
546  @"id" : @(42),
547  @"viewType" : @"factory_id",
548  }]
549  result:^(id result){
550  }];
551 
552  // Wait up to 1 second for Flutter to emit a frame.
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) {
558  break;
559  }
560  }
561 
562  // There are two layers with Flutter contents and one view
563  EXPECT_EQ(rootLayer.sublayers.count, 2u);
564  EXPECT_EQ(viewController.flutterView.subviews.count, 1u);
565 
566  // TODO(gw280): add support for screenshot tests in this test harness
567 
568  [engine shutDownEngine];
569 }
570 
571 TEST_F(FlutterEngineTest, CompositorIgnoresUnknownView) {
572  FlutterEngine* engine = GetFlutterEngine();
573  auto original_init = engine.embedderAPI.Initialize;
574  ::FlutterCompositor compositor;
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);
581  }));
582 
583  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
584  nibName:nil
585  bundle:nil];
586  [viewController loadView];
587 
588  EXPECT_TRUE([engine runWithEntrypoint:@"empty"]);
589 
590  FlutterBackingStoreConfig config = {
591  .struct_size = sizeof(FlutterBackingStoreConfig),
592  .size = FlutterSize{10, 10},
593  };
594  FlutterBackingStore backing_store = {};
595  EXPECT_NE(compositor.create_backing_store_callback, nullptr);
596  EXPECT_TRUE(
597  compositor.create_backing_store_callback(&config, &backing_store, compositor.user_data));
598 
599  FlutterLayer layer{
600  .type = kFlutterLayerContentTypeBackingStore,
601  .backing_store = &backing_store,
602  };
603  std::vector<FlutterLayer*> layers = {&layer};
604 
605  FlutterPresentViewInfo info = {
606  .struct_size = sizeof(FlutterPresentViewInfo),
607  .view_id = 123,
608  .layers = const_cast<const FlutterLayer**>(layers.data()),
609  .layers_count = 1,
610  .user_data = compositor.user_data,
611  };
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));
615 
616  (void)viewController;
617  [engine shutDownEngine];
618 }
619 
620 TEST_F(FlutterEngineTest, DartEntrypointArguments) {
621  NSString* fixtures = @(flutter::testing::GetFixturesPath());
622  FlutterDartProject* project = [[FlutterDartProject alloc]
623  initWithAssetsPath:fixtures
624  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
625 
626  project.dartEntrypointArguments = @[ @"arg1", @"arg2" ];
627  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project];
628 
629  bool called = false;
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,
634  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
635  called = true;
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];
641 
642  EXPECT_TRUE([arg1 isEqualToString:@"arg1"]);
643  EXPECT_TRUE([arg2 isEqualToString:@"arg2"]);
644 
645  return original_init(version, config, args, user_data, engine_out);
646  }));
647 
648  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
649  EXPECT_TRUE(called);
650  [engine shutDownEngine];
651 }
652 
653 // Verify that the engine is not retained indirectly via the binary messenger held by channels and
654 // plugins. Previously, FlutterEngine.binaryMessenger returned the engine itself, and thus plugins
655 // could cause a retain cycle, preventing the engine from being deallocated.
656 // FlutterEngine.binaryMessenger now returns a FlutterBinaryMessengerRelay whose weak pointer back
657 // to the engine is cleared when the engine is deallocated.
658 // Issue: https://github.com/flutter/flutter/issues/116445
659 TEST_F(FlutterEngineTest, FlutterBinaryMessengerDoesNotRetainEngine) {
660  __weak FlutterEngine* weakEngine;
661  id<FlutterBinaryMessenger> binaryMessenger = nil;
662  @autoreleasepool {
663  // Create a test engine.
664  NSString* fixtures = @(flutter::testing::GetFixturesPath());
665  FlutterDartProject* project = [[FlutterDartProject alloc]
666  initWithAssetsPath:fixtures
667  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
668  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test"
669  project:project
670  allowHeadlessExecution:YES];
671  weakEngine = engine;
672  binaryMessenger = engine.binaryMessenger;
673  }
674 
675  // Once the engine has been deallocated, verify the weak engine pointer is nil, and thus not
676  // retained by the relay.
677  EXPECT_NE(binaryMessenger, nil);
678  EXPECT_EQ(weakEngine, nil);
679 }
680 
681 // Verify that the engine is not retained indirectly via the texture registry held by plugins.
682 // Issue: https://github.com/flutter/flutter/issues/116445
683 TEST_F(FlutterEngineTest, FlutterTextureRegistryDoesNotReturnEngine) {
684  __weak FlutterEngine* weakEngine;
685  id<FlutterTextureRegistry> textureRegistry;
686  @autoreleasepool {
687  // Create a test engine.
688  NSString* fixtures = @(flutter::testing::GetFixturesPath());
689  FlutterDartProject* project = [[FlutterDartProject alloc]
690  initWithAssetsPath:fixtures
691  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
692  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test"
693  project:project
694  allowHeadlessExecution:YES];
695  id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"MyPlugin"];
696  textureRegistry = registrar.textures;
697  }
698 
699  // Once the engine has been deallocated, verify the weak engine pointer is nil, and thus not
700  // retained via the texture registry.
701  EXPECT_NE(textureRegistry, nil);
702  EXPECT_EQ(weakEngine, nil);
703 }
704 
705 TEST_F(FlutterEngineTest, PublishedValueNilForUnknownPlugin) {
706  NSString* fixtures = @(flutter::testing::GetFixturesPath());
707  FlutterDartProject* project = [[FlutterDartProject alloc]
708  initWithAssetsPath:fixtures
709  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
710  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test"
711  project:project
712  allowHeadlessExecution:YES];
713 
714  EXPECT_EQ([engine valuePublishedByPlugin:@"NoSuchPlugin"], nil);
715 }
716 
717 TEST_F(FlutterEngineTest, PublishedValueNSNullIfNoPublishedValue) {
718  NSString* fixtures = @(flutter::testing::GetFixturesPath());
719  FlutterDartProject* project = [[FlutterDartProject alloc]
720  initWithAssetsPath:fixtures
721  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
722  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test"
723  project:project
724  allowHeadlessExecution:YES];
725  NSString* pluginName = @"MyPlugin";
726  // Request the registarar to register the plugin as existing.
727  [engine registrarForPlugin:pluginName];
728 
729  // The documented behavior is that a plugin that exists but hasn't published
730  // anything returns NSNull, rather than nil, as on iOS.
731  EXPECT_EQ([engine valuePublishedByPlugin:pluginName], [NSNull null]);
732 }
733 
734 TEST_F(FlutterEngineTest, PublishedValueReturnsLastPublished) {
735  NSString* fixtures = @(flutter::testing::GetFixturesPath());
736  FlutterDartProject* project = [[FlutterDartProject alloc]
737  initWithAssetsPath:fixtures
738  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
739  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test"
740  project:project
741  allowHeadlessExecution:YES];
742  NSString* pluginName = @"MyPlugin";
743  id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:pluginName];
744 
745  NSString* firstValue = @"A published value";
746  NSArray* secondValue = @[ @"A different published value" ];
747 
748  [registrar publish:firstValue];
749  EXPECT_EQ([engine valuePublishedByPlugin:pluginName], firstValue);
750 
751  [registrar publish:secondValue];
752  EXPECT_EQ([engine valuePublishedByPlugin:pluginName], secondValue);
753 }
754 
755 TEST_F(FlutterEngineTest, RegistrarCanReadValuePublishedByAnotherPlugin) {
756  NSString* fixtures = @(flutter::testing::GetFixturesPath());
757  FlutterDartProject* project = [[FlutterDartProject alloc]
758  initWithAssetsPath:fixtures
759  ICUDataPath:[fixtures stringByAppendingPathComponent:@"icudtl.dat"]];
760  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test"
761  project:project
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];
767 
768  NSString* publishedValue = @"A published value";
769  [publisher publish:publishedValue];
770 
771  EXPECT_EQ([reader valuePublishedByPlugin:publisherPluginName], publishedValue);
772  EXPECT_EQ([reader valuePublishedByPlugin:@"NoSuchPlugin"], nil);
773  EXPECT_EQ([reader valuePublishedByPlugin:readerPluginName], [NSNull null]);
774 }
775 
776 TEST_F(FlutterEngineTest, RegistrarForwardViewControllerLookUpToEngine) {
777  NSString* fixtures = @(flutter::testing::GetFixturesPath());
778  FlutterDartProject* project = [[FlutterDartProject alloc]
779  initWithAssetsPath:fixtures
780  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
781  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project];
782 
783  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
784  nibName:nil
785  bundle:nil];
786  id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"MyPlugin"];
787 
788  EXPECT_EQ([registrar viewController], viewController);
789 }
790 
791 // If a channel overrides a previous channel with the same name, cleaning
792 // the previous channel should not affect the new channel.
793 //
794 // This is important when recreating classes that uses a channel, because the
795 // new instance would create the channel before the first class is deallocated
796 // and clears the channel.
797 TEST_F(FlutterEngineTest, MessengerCleanupConnectionWorks) {
798  FlutterEngine* engine = GetFlutterEngine();
799  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
800 
801  NSString* channel = @"_test_";
802  NSData* channel_data = [channel dataUsingEncoding:NSUTF8StringEncoding];
803 
804  // Mock SendPlatformMessage so that if a message is sent to
805  // "test/send_message", act as if the framework has sent an empty message to
806  // the channel marked by the `sendOnChannel:message:` call's message.
807  engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC(
808  SendPlatformMessage, ([](auto engine_, auto message_) {
809  if (strcmp(message_->channel, "test/send_message") == 0) {
810  // The simplest message that is acceptable to a method channel.
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_)
815  ->GetShell()
816  .GetPlatformView()
817  ->HandlePlatformMessage(std::make_unique<PlatformMessage>(
818  channel.c_str(), fml::MallocMapping::Copy(message.c_str(), message.length()),
819  fml::RefPtr<PlatformMessageResponse>()));
820  }
821  return kSuccess;
822  }));
823 
824  __block int record = 0;
825 
826  FlutterMethodChannel* channel1 =
828  binaryMessenger:engine.binaryMessenger
829  codec:[FlutterJSONMethodCodec sharedInstance]];
830  [channel1 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
831  record += 1;
832  }];
833 
834  [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data];
835  EXPECT_EQ(record, 1);
836 
837  FlutterMethodChannel* channel2 =
839  binaryMessenger:engine.binaryMessenger
840  codec:[FlutterJSONMethodCodec sharedInstance]];
841  [channel2 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
842  record += 10;
843  }];
844 
845  [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data];
846  EXPECT_EQ(record, 11);
847 
848  [channel1 setMethodCallHandler:nil];
849 
850  [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data];
851  EXPECT_EQ(record, 21);
852 }
853 
854 TEST_F(FlutterEngineTest, HasStringsWhenPasteboardEmpty) {
855  id engineMock = CreateMockFlutterEngine(nil);
856 
857  // Call hasStrings and expect it to be false.
858  __block bool calledAfterClear = false;
859  __block bool valueAfterClear;
860  FlutterResult resultAfterClear = ^(id result) {
861  calledAfterClear = true;
862  NSNumber* valueNumber = [result valueForKey:@"value"];
863  valueAfterClear = [valueNumber boolValue];
864  };
865  FlutterMethodCall* methodCallAfterClear =
866  [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil];
867  [engineMock handleMethodCall:methodCallAfterClear result:resultAfterClear];
868  EXPECT_TRUE(calledAfterClear);
869  EXPECT_FALSE(valueAfterClear);
870 }
871 
872 TEST_F(FlutterEngineTest, HasStringsWhenPasteboardFull) {
873  id engineMock = CreateMockFlutterEngine(@"some string");
874 
875  // Call hasStrings and expect it to be true.
876  __block bool called = false;
877  __block bool value;
878  FlutterResult result = ^(id result) {
879  called = true;
880  NSNumber* valueNumber = [result valueForKey:@"value"];
881  value = [valueNumber boolValue];
882  };
883  FlutterMethodCall* methodCall =
884  [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil];
885  [engineMock handleMethodCall:methodCall result:result];
886  EXPECT_TRUE(called);
887  EXPECT_TRUE(value);
888 }
889 
890 TEST_F(FlutterEngineTest, ResponseAfterEngineDied) {
891  FlutterEngine* engine = GetFlutterEngine();
893  initWithName:@"foo"
894  binaryMessenger:engine.binaryMessenger
896  __block BOOL didCallCallback = NO;
897  [channel setMessageHandler:^(id message, FlutterReply callback) {
898  ShutDownEngine();
899  callback(nil);
900  didCallCallback = YES;
901  }];
902  EXPECT_TRUE([engine runWithEntrypoint:@"sendFooMessage"]);
903  engine = nil;
904 
905  while (!didCallCallback) {
906  [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
907  }
908 }
909 
910 TEST_F(FlutterEngineTest, ResponseFromBackgroundThread) {
911  FlutterEngine* engine = GetFlutterEngine();
913  initWithName:@"foo"
914  binaryMessenger:engine.binaryMessenger
916  __block BOOL didCallCallback = NO;
917  [channel setMessageHandler:^(id message, FlutterReply callback) {
918  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
919  callback(nil);
920  dispatch_async(dispatch_get_main_queue(), ^{
921  didCallCallback = YES;
922  });
923  });
924  }];
925  EXPECT_TRUE([engine runWithEntrypoint:@"sendFooMessage"]);
926 
927  while (!didCallCallback) {
928  [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
929  }
930 }
931 
932 TEST_F(FlutterEngineTest, CanGetEngineForId) {
933  FlutterEngine* engine = GetFlutterEngine();
934 
935  BOOL signaled = NO;
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);
940  engineId = id;
941  }
942  signaled = YES;
943  }));
944 
945  EXPECT_TRUE([engine runWithEntrypoint:@"testEngineId"]);
946  while (!signaled) {
947  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
948  }
949 
950  EXPECT_TRUE(engineId.has_value());
951  if (!engineId.has_value()) {
952  return;
953  }
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]);
958  ShutDownEngine();
959 }
960 
961 TEST_F(FlutterEngineTest, ResizeSynchronizerNotBlockingRasterThreadAfterShutdown) {
962  FlutterResizeSynchronizer* threadSynchronizer = [[FlutterResizeSynchronizer alloc] init];
963  [threadSynchronizer shutDown];
964 
965  std::thread rasterThread([&threadSynchronizer] {
966  [threadSynchronizer performCommitForSize:CGSizeMake(100, 100)
967  afterDelay:0
968  notify:^{
969  }];
970  });
971 
972  rasterThread.join();
973 }
974 
975 TEST_F(FlutterEngineTest, ManageControllersIfInitiatedByController) {
976  NSString* fixtures = @(flutter::testing::GetFixturesPath());
977  FlutterDartProject* project = [[FlutterDartProject alloc]
978  initWithAssetsPath:fixtures
979  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
980 
981  FlutterEngine* engine;
982  FlutterViewController* viewController1;
983 
984  @autoreleasepool {
985  // Create FVC1.
986  viewController1 = [[FlutterViewController alloc] initWithProject:project];
987  EXPECT_EQ(viewController1.viewIdentifier, 0ll);
988 
989  engine = viewController1.engine;
990  engine.viewController = nil;
991 
992  // Create FVC2 based on the same engine.
993  FlutterViewController* viewController2 = [[FlutterViewController alloc] initWithEngine:engine
994  nibName:nil
995  bundle:nil];
996  EXPECT_EQ(engine.viewController, viewController2);
997  }
998  // FVC2 is deallocated but FVC1 is retained.
999 
1000  EXPECT_EQ(engine.viewController, nil);
1001 
1002  engine.viewController = viewController1;
1003  EXPECT_EQ(engine.viewController, viewController1);
1004  EXPECT_EQ(viewController1.viewIdentifier, 0ll);
1005 }
1006 
1007 TEST_F(FlutterEngineTest, ManageControllersIfInitiatedByEngine) {
1008  // Don't create the engine with `CreateMockFlutterEngine`, because it adds
1009  // additional references to FlutterViewControllers, which is crucial to this
1010  // test case.
1011  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"io.flutter"
1012  project:nil
1013  allowHeadlessExecution:NO];
1014  FlutterViewController* viewController1;
1015 
1016  @autoreleasepool {
1017  viewController1 = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
1018  EXPECT_EQ(viewController1.viewIdentifier, 0ll);
1019  EXPECT_EQ(engine.viewController, viewController1);
1020 
1021  engine.viewController = nil;
1022 
1023  FlutterViewController* viewController2 = [[FlutterViewController alloc] initWithEngine:engine
1024  nibName:nil
1025  bundle:nil];
1026  EXPECT_EQ(viewController2.viewIdentifier, 0ll);
1027  EXPECT_EQ(engine.viewController, viewController2);
1028  }
1029  // FVC2 is deallocated but FVC1 is retained.
1030 
1031  EXPECT_EQ(engine.viewController, nil);
1032 
1033  engine.viewController = viewController1;
1034  EXPECT_EQ(engine.viewController, viewController1);
1035  EXPECT_EQ(viewController1.viewIdentifier, 0ll);
1036 }
1037 
1038 TEST_F(FlutterEngineTest, RemovingViewDisposesCompositorResources) {
1039  NSString* fixtures = @(flutter::testing::GetFixturesPath());
1040  FlutterDartProject* project = [[FlutterDartProject alloc]
1041  initWithAssetsPath:fixtures
1042  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
1043  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project];
1044 
1045  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
1046  nibName:nil
1047  bundle:nil];
1048  [viewController loadView];
1049  [viewController viewDidLoad];
1050  viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
1051 
1052  EXPECT_TRUE([engine runWithEntrypoint:@"drawIntoAllViews"]);
1053  // Wait up to 1 second for Flutter to emit a frame.
1054  CFTimeInterval start = CACurrentMediaTime();
1055  while (engine.macOSCompositor->DebugNumViews() == 0) {
1056  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
1057  if (CACurrentMediaTime() - start > 1) {
1058  break;
1059  }
1060  }
1061 
1062  EXPECT_EQ(engine.macOSCompositor->DebugNumViews(), 1u);
1063 
1064  engine.viewController = nil;
1065  EXPECT_EQ(engine.macOSCompositor->DebugNumViews(), 0u);
1066 
1067  [engine shutDownEngine];
1068  engine = nil;
1069 }
1070 
1071 TEST_F(FlutterEngineTest, HandlesTerminationRequest) {
1072  id engineMock = CreateMockFlutterEngine(nil);
1073  __block NSString* nextResponse = @"exit";
1074  __block BOOL triedToTerminate = NO;
1075  FlutterEngineTerminationHandler* terminationHandler =
1076  [[FlutterEngineTerminationHandler alloc] initWithEngine:engineMock
1077  terminator:^(id sender) {
1078  triedToTerminate = TRUE;
1079  // Don't actually terminate, of course.
1080  }];
1081  OCMStub([engineMock terminationHandler]).andReturn(terminationHandler);
1082  id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
1083  OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
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];
1091  FlutterBinaryReply callback;
1092  NSData* returnedMessage;
1093  [invocation getArgument:&callback atIndex:4];
1094  if ([nextResponse isEqualToString:@"error"]) {
1095  FlutterError* errorResponse = [FlutterError errorWithCode:@"Error"
1096  message:@"Failed"
1097  details:@"Details"];
1098  returnedMessage =
1099  [[FlutterJSONMethodCodec sharedInstance] encodeErrorEnvelope:errorResponse];
1100  } else {
1101  NSDictionary* responseDict = @{@"response" : nextResponse};
1102  returnedMessage =
1103  [[FlutterJSONMethodCodec sharedInstance] encodeSuccessEnvelope:responseDict];
1104  }
1105  callback(returnedMessage);
1106  }));
1107  __block NSString* calledAfterTerminate = @"";
1108  FlutterResult appExitResult = ^(id result) {
1109  NSDictionary* resultDict = result;
1110  calledAfterTerminate = resultDict[@"response"];
1111  };
1112  FlutterMethodCall* methodExitApplication =
1113  [FlutterMethodCall methodCallWithMethodName:@"System.exitApplication"
1114  arguments:@{@"type" : @"cancelable"}];
1115 
1116  // Always terminate when the binding isn't ready (which is the default).
1117  triedToTerminate = NO;
1118  calledAfterTerminate = @"";
1119  nextResponse = @"cancel";
1120  [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1121  EXPECT_STREQ([calledAfterTerminate UTF8String], "");
1122  EXPECT_TRUE(triedToTerminate);
1123 
1124  // Once the binding is ready, handle the request.
1125  terminationHandler.acceptingRequests = YES;
1126  triedToTerminate = NO;
1127  calledAfterTerminate = @"";
1128  nextResponse = @"exit";
1129  [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1130  EXPECT_STREQ([calledAfterTerminate UTF8String], "exit");
1131  EXPECT_TRUE(triedToTerminate);
1132 
1133  triedToTerminate = NO;
1134  calledAfterTerminate = @"";
1135  nextResponse = @"cancel";
1136  [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1137  EXPECT_STREQ([calledAfterTerminate UTF8String], "cancel");
1138  EXPECT_FALSE(triedToTerminate);
1139 
1140  // Check that it doesn't crash on error.
1141  triedToTerminate = NO;
1142  calledAfterTerminate = @"";
1143  nextResponse = @"error";
1144  [engineMock handleMethodCall:methodExitApplication result:appExitResult];
1145  EXPECT_STREQ([calledAfterTerminate UTF8String], "");
1146  EXPECT_TRUE(triedToTerminate);
1147 }
1148 
1149 TEST_F(FlutterEngineTest, IgnoresTerminationRequestIfNotFlutterAppDelegate) {
1150  id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate];
1151  id<NSApplicationDelegate> plainDelegate = [[PlainAppDelegate alloc] init];
1152  [NSApplication sharedApplication].delegate = plainDelegate;
1153 
1154  // Creating the engine shouldn't fail here, even though the delegate isn't a
1155  // FlutterAppDelegate.
1157 
1158  // Asking to terminate the app should cancel.
1159  EXPECT_EQ([[[NSApplication sharedApplication] delegate] applicationShouldTerminate:NSApp],
1160  NSTerminateCancel);
1161 
1162  [NSApplication sharedApplication].delegate = previousDelegate;
1163 }
1164 
1165 TEST_F(FlutterEngineTest, HandleAccessibilityEvent) {
1166  __block BOOL announced = NO;
1167  id engineMock = CreateMockFlutterEngine(nil);
1168 
1169  OCMStub([engineMock announceAccessibilityMessage:[OCMArg any]
1170  withPriority:NSAccessibilityPriorityMedium])
1171  .andDo((^(NSInvocation* invocation) {
1172  announced = TRUE;
1173  [invocation retainArguments];
1174  NSString* message;
1175  [invocation getArgument:&message atIndex:2];
1176  EXPECT_EQ(message, @"error message");
1177  }));
1178 
1179  NSDictionary<NSString*, id>* annotatedEvent =
1180  @{@"type" : @"announce",
1181  @"data" : @{@"message" : @"error message"}};
1182 
1183  [engineMock handleAccessibilityEvent:annotatedEvent];
1184 
1185  EXPECT_TRUE(announced);
1186 }
1187 
1188 TEST_F(FlutterEngineTest, HandleLifecycleStates) API_AVAILABLE(macos(10.9)) {
1189  __block flutter::AppLifecycleState sentState;
1190  id engineMock = CreateMockFlutterEngine(nil);
1191 
1192  // Have to enumerate all the values because OCMStub can't capture
1193  // non-Objective-C object arguments.
1194  OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kDetached])
1195  .andDo((^(NSInvocation* invocation) {
1197  }));
1198  OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kResumed])
1199  .andDo((^(NSInvocation* invocation) {
1201  }));
1202  OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kInactive])
1203  .andDo((^(NSInvocation* invocation) {
1205  }));
1206  OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kHidden])
1207  .andDo((^(NSInvocation* invocation) {
1209  }));
1210  OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kPaused])
1211  .andDo((^(NSInvocation* invocation) {
1213  }));
1214 
1215  __block NSApplicationOcclusionState visibility = NSApplicationOcclusionStateVisible;
1216  id mockApplication = OCMPartialMock([NSApplication sharedApplication]);
1217  OCMStub((NSApplicationOcclusionState)[mockApplication occlusionState])
1218  .andDo(^(NSInvocation* invocation) {
1219  [invocation setReturnValue:&visibility];
1220  });
1221 
1222  // handleWillBecomeActive derives visibility from the windows (not from the
1223  // occlusion state, which can latch stale), so provide a window whose visibility
1224  // we can toggle independently.
1225  __block BOOL windowVisible = YES;
1226  id mockWindow = OCMClassMock([NSWindow class]);
1227  OCMStub([mockWindow isVisible]).andDo(^(NSInvocation* invocation) {
1228  [invocation setReturnValue:&windowVisible];
1229  });
1230  OCMStub([mockApplication windows]).andReturn(@[ mockWindow ]);
1231 
1232  NSNotification* willBecomeActive =
1233  [[NSNotification alloc] initWithName:NSApplicationWillBecomeActiveNotification
1234  object:nil
1235  userInfo:nil];
1236  NSNotification* willResignActive =
1237  [[NSNotification alloc] initWithName:NSApplicationWillResignActiveNotification
1238  object:nil
1239  userInfo:nil];
1240 
1241  NSNotification* didChangeOcclusionState;
1242  didChangeOcclusionState =
1243  [[NSNotification alloc] initWithName:NSApplicationDidChangeOcclusionStateNotification
1244  object:nil
1245  userInfo:nil];
1246 
1247  [engineMock handleDidChangeOcclusionState:didChangeOcclusionState];
1248  EXPECT_EQ(sentState, flutter::AppLifecycleState::kInactive);
1249 
1250  [engineMock handleWillBecomeActive:willBecomeActive];
1251  EXPECT_EQ(sentState, flutter::AppLifecycleState::kResumed);
1252 
1253  [engineMock handleWillResignActive:willResignActive];
1254  EXPECT_EQ(sentState, flutter::AppLifecycleState::kInactive);
1255 
1256  visibility = 0;
1257  [engineMock handleDidChangeOcclusionState:didChangeOcclusionState];
1258  EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden);
1259 
1260  // Becoming active with an on-screen window resumes even though occlusionState still
1261  // reads not-visible (the stale-latch case). Regression test for #155977.
1262  [engineMock handleWillBecomeActive:willBecomeActive];
1263  EXPECT_EQ(sentState, flutter::AppLifecycleState::kResumed);
1264 
1265  // The app is now active and considered visible, so resigning active makes it
1266  // inactive (not hidden) until a real occlusion notification hides it.
1267  [engineMock handleWillResignActive:willResignActive];
1268  EXPECT_EQ(sentState, flutter::AppLifecycleState::kInactive);
1269 
1270  // Occlusion stays authoritative after a becomeActive resume: a genuine
1271  // not-visible occlusion notification still hides the app.
1272  visibility = 0;
1273  [engineMock handleDidChangeOcclusionState:didChangeOcclusionState];
1274  EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden);
1275 
1276  // Becoming active while no window is visible (e.g. activated with all windows
1277  // minimized, which does not deminiaturize) must not resume: visibility is
1278  // derived from the windows, not from the activation itself.
1279  windowVisible = NO;
1280  [engineMock handleWillBecomeActive:willBecomeActive];
1281  EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden);
1282 
1283  [mockWindow stopMocking];
1284  [mockApplication stopMocking];
1285 }
1286 
1287 TEST_F(FlutterEngineTest, ForwardsPluginDelegateRegistration) {
1288  id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate];
1289  FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init];
1290  [NSApplication sharedApplication].delegate = fakeAppDelegate;
1291 
1292  FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init];
1293  FlutterEngine* engine = CreateMockFlutterEngine(nil);
1294 
1295  [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin];
1296 
1297  EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]);
1298 
1299  [NSApplication sharedApplication].delegate = previousDelegate;
1300 }
1301 
1302 TEST_F(FlutterEngineTest, UnregistersPluginsOnEngineDestruction) {
1303  id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate];
1304  FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init];
1305  [NSApplication sharedApplication].delegate = fakeAppDelegate;
1306 
1307  FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init];
1308 
1309  @autoreleasepool {
1310  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
1311 
1312  [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin];
1313  EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]);
1314  }
1315 
1316  // When the engine is released, it should unregister any plugins it had
1317  // registered on its behalf.
1318  EXPECT_FALSE([fakeAppDelegate hasDelegate:plugin]);
1319 
1320  [NSApplication sharedApplication].delegate = previousDelegate;
1321 }
1322 
1323 TEST_F(FlutterEngineTest, RunWithEntrypointUpdatesDisplayConfig) {
1324  BOOL updated = NO;
1325  FlutterEngine* engine = GetFlutterEngine();
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) {
1330  updated = YES;
1331  return original_update_displays(engine, update_type, displays, display_count);
1332  }));
1333 
1334  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
1335  EXPECT_TRUE(updated);
1336 
1337  updated = NO;
1338  [[NSNotificationCenter defaultCenter]
1339  postNotificationName:NSApplicationDidChangeScreenParametersNotification
1340  object:nil];
1341  EXPECT_TRUE(updated);
1342 }
1343 
1344 TEST_F(FlutterEngineTest, NotificationsUpdateDisplays) {
1345  BOOL updated = NO;
1346  FlutterEngine* engine = GetFlutterEngine();
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) {
1351  updated = YES;
1352  return original_set_viewport_metrics(engine, window_metrics);
1353  }));
1354 
1355  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
1356 
1357  updated = NO;
1358  [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification
1359  object:nil];
1360  // No VC.
1361  EXPECT_FALSE(updated);
1362 
1363  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
1364  nibName:nil
1365  bundle:nil];
1366  [viewController loadView];
1367  viewController.flutterView.frame = CGRectMake(0, 0, 800, 600);
1368 
1369  [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification
1370  object:nil];
1371  EXPECT_TRUE(updated);
1372 }
1373 
1374 TEST_F(FlutterEngineTest, DisplaySizeIsInPhysicalPixel) {
1375  NSString* fixtures = @(testing::GetFixturesPath());
1376  FlutterDartProject* project = [[FlutterDartProject alloc]
1377  initWithAssetsPath:fixtures
1378  ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
1379  project.rootIsolateCreateCallback = FlutterEngineTest::IsolateCreateCallback;
1380  MockableFlutterEngine* engine = [[MockableFlutterEngine alloc] initWithName:@"foobar"
1381  project:project
1382  allowHeadlessExecution:true];
1383  BOOL updated = NO;
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);
1393  updated = YES;
1394  return original_update_displays(engine, update_type, displays, display_count);
1395  }));
1396  EXPECT_TRUE([engine runWithEntrypoint:@"main"]);
1397  EXPECT_TRUE(updated);
1398  [engine shutDownEngine];
1399  engine = nil;
1400 }
1401 
1402 TEST_F(FlutterEngineTest, ReportsHourFormat) {
1403  __block BOOL expectedValue;
1404 
1405  // Set up mocks.
1406  id channelMock = OCMClassMock([FlutterBasicMessageChannel class]);
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) {
1412  __weak id message;
1413  [invocation getArgument:&message atIndex:2];
1414  EXPECT_EQ(message[@"alwaysUse24HourFormat"], @(expectedValue));
1415  }));
1416 
1417  id mockHourFormat = OCMClassMock([FlutterHourFormat class]);
1418  OCMStub([mockHourFormat isAlwaysUse24HourFormat]).andDo((^(NSInvocation* invocation) {
1419  [invocation setReturnValue:&expectedValue];
1420  }));
1421 
1422  id engineMock = CreateMockFlutterEngine(nil);
1423 
1424  // Verify the YES case.
1425  expectedValue = YES;
1426  EXPECT_TRUE([engineMock runWithEntrypoint:@"main"]);
1427  [engineMock shutDownEngine];
1428 
1429  // Verify the NO case.
1430  expectedValue = NO;
1431  EXPECT_TRUE([engineMock runWithEntrypoint:@"main"]);
1432  [engineMock shutDownEngine];
1433 
1434  // Clean up mocks.
1435  [mockHourFormat stopMocking];
1436  [engineMock stopMocking];
1437  [channelMock stopMocking];
1438 }
1439 
1440 } // namespace flutter::testing
1441 
1442 // NOLINTEND(clang-analyzer-core.StackAddressEscape)
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
Definition: FlutterEngine.h:92
FlutterViewController * viewController
Definition: FlutterEngine.h:87
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)
FlutterViewIdentifier viewIdentifier
id CreateMockFlutterEngine(NSString *pasteboardString)
TEST_F(FlutterEngineTest, ReportsHourFormat)
instancetype sharedInstance()
void * user_data