Flutter iOS 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 
5 #import <Foundation/Foundation.h>
6 #import <OCMock/OCMock.h>
7 #import <XCTest/XCTest.h>
8 
9 #import <objc/runtime.h>
10 
11 #import "flutter/common/settings.h"
12 #include "flutter/fml/synchronization/sync_switch.h"
13 #include "flutter/lib/ui/window/platform_message.h"
14 #include "flutter/lib/ui/window/platform_message_response.h"
15 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
18 #import "flutter/shell/platform/darwin/common/test_utils_swift/test_utils_swift.h"
19 #import "flutter/shell/platform/darwin/ios/InternalFlutterSwift/InternalFlutterSwift.h"
29 
30 namespace {
31 // A `PlatformMessageResponse` that records completion.
32 //
33 // This allows tests to inject an inbound platform message the way the engine's platform view would
34 // and observe that it was answered.
35 class TestPlatformMessageResponse : public flutter::PlatformMessageResponse {
36  public:
37  static fml::RefPtr<TestPlatformMessageResponse> Create() {
38  return fml::AdoptRef(new TestPlatformMessageResponse());
39  }
40  void Complete(std::unique_ptr<fml::Mapping> data) override { is_complete_ = true; }
41  void CompleteEmpty() override { is_complete_ = true; }
42 
43  private:
44  TestPlatformMessageResponse() = default;
45 };
46 
47 // Returns a mock view controller whose view is in a window on a screen with the given native size
48 // and scale.
49 id CreateMockViewControllerOnScreen(CGSize screenNativeSize, CGFloat screenScale) {
50  UIScreen* screen = OCMClassMock([UIScreen class]);
51  OCMStub([screen nativeBounds]).andDo(^(NSInvocation* invocation) {
52  CGRect nativeBounds = CGRectMake(0, 0, screenNativeSize.width, screenNativeSize.height);
53  [invocation setReturnValue:&nativeBounds];
54  });
55  OCMStub([screen scale]).andDo(^(NSInvocation* invocation) {
56  CGFloat scale = screenScale;
57  [invocation setReturnValue:&scale];
58  });
59  UIWindowScene* windowScene = OCMClassMock([UIWindowScene class]);
60  OCMStub([windowScene screen]).andReturn(screen);
61  UIWindow* window = OCMClassMock([UIWindow class]);
62  OCMStub([window windowScene]).andReturn(windowScene);
63  UIView* view = OCMClassMock([UIView class]);
64  OCMStub([view window]).andReturn(window);
66  OCMStub([viewController viewIfLoaded]).andReturn(view);
67  return viewController;
68 }
69 } // namespace
70 
71 /// A `FlutterTexture` that vends no frames. Used to obtain a registered texture id.
72 @interface TestFlutterTexture : NSObject <FlutterTexture>
73 @end
74 
75 @implementation TestFlutterTexture
76 - (CVPixelBufferRef _Nullable)copyPixelBuffer {
77  return nullptr;
78 }
79 @end
80 
82 @end
83 
84 /// A minimal FlutterPlugin that does not implement any lifecycle methods.
85 /// Used to verify that plugins not using lifecycle events do not trigger a warning.
86 @interface TestMinimalFlutterPlugin : NSObject <FlutterPlugin>
87 @end
88 
89 @implementation TestMinimalFlutterPlugin
90 + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
91 }
92 @end
93 
95 @property(nonatomic) BOOL ensureSemanticsEnabledCalled;
96 @end
97 
98 @implementation FlutterEngineSpy
99 
100 - (void)ensureSemanticsEnabled {
101  _ensureSemanticsEnabledCalled = YES;
102 }
103 
104 @end
105 
107 
108 @end
109 
110 /// FlutterBinaryMessengerRelay used for testing that setting FlutterEngine.binaryMessenger to
111 /// the current instance doesn't trigger a use-after-free bug.
112 ///
113 /// See: testSetBinaryMessengerToSameBinaryMessenger
115 @property(nonatomic, assign) BOOL failOnDealloc;
116 @end
117 
118 @implementation FakeBinaryMessengerRelay
119 - (void)dealloc {
120  if (_failOnDealloc) {
121  XCTFail("FakeBinaryMessageRelay should not be deallocated");
122  }
123 }
124 @end
125 
126 @interface FlutterEngineTest : XCTestCase
127 @end
128 
129 @implementation FlutterEngineTest
130 
131 - (void)setUp {
132 }
133 
134 - (void)tearDown {
135 }
136 
137 - (void)testCreate {
138  FlutterDartProject* project = [[FlutterDartProject alloc] init];
139  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
140  XCTAssertNotNil(engine);
141 }
142 
143 - (void)testShellGetters {
144  FlutterDartProject* project = [[FlutterDartProject alloc] init];
145  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
146  XCTAssertNotNil(engine);
147 
148  // Ensure getters don't deref _shell when it's null, and instead return nullptr.
149  XCTAssertNil(engine.platformTaskRunner);
150  XCTAssertNil(engine.uiTaskRunner);
151  XCTAssertNil(engine.rasterTaskRunner);
152 }
153 
154 - (void)testTaskRunnerPropertyStability {
155  FlutterDartProject* project = [[FlutterDartProject alloc] init];
156  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
157  [engine run];
158 
159  // Since the taskRunners are wrappers, ensure that we generate them once and they keep the same
160  // identity over time. This makes identity checks on the runners safe/possible.
161  XCTAssertNotNil(engine.platformTaskRunner);
162  XCTAssertEqual(engine.platformTaskRunner, engine.platformTaskRunner);
163  XCTAssertNotNil(engine.uiTaskRunner);
164  XCTAssertEqual(engine.uiTaskRunner, engine.uiTaskRunner);
165  XCTAssertNotNil(engine.rasterTaskRunner);
166  XCTAssertEqual(engine.rasterTaskRunner, engine.rasterTaskRunner);
167 }
168 
169 - (void)testRunOnRunningEngineIsRefused {
170  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:nil];
171  XCTAssertTrue([engine run]);
172  FlutterFMLTaskRunner* platformTaskRunner = engine.platformTaskRunner;
173 
174  // Verify a second call reports that it did not restart the engine.
175  XCTAssertFalse([engine run]);
176  XCTAssertEqual(engine.platformTaskRunner, platformTaskRunner);
177 }
178 
179 - (void)testRunWithDifferentEntrypointOnRunningEngineIsRefused {
180  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:nil];
181  XCTAssertTrue([engine run]);
182 
183  // Verify a second call reports that it did not restart the engine with a new entrypoint.
184  XCTAssertFalse([engine runWithEntrypoint:@"someOtherEntrypoint"]);
185 }
186 
187 - (void)testRunAfterDestroyContextIsRefused {
188  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:nil];
189  XCTAssertTrue([engine run]);
190  [engine destroyContext];
191 
192  // A destroyed engine releases the shell, so the `_shell != nullptr` guard against double
193  // invocation no longer catches a second run. Verify the destroyed state is refused on its own.
194  XCTAssertFalse([engine run]);
195  XCTAssertNil(engine.platformTaskRunner);
196  XCTAssertNil(engine.uiTaskRunner);
197  XCTAssertNil(engine.rasterTaskRunner);
198 }
199 
200 - (void)testDestroyContextIsIdempotent {
201  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:nil];
202  XCTAssertTrue([engine run]);
203 
204  // Both `appOrSceneWillTerminate` and view controller deallocation can destroy the same engine.
205  // Verify a second call is a no-op and not a double teardown.
206  [engine destroyContext];
207  [engine destroyContext];
208  XCTAssertNil(engine.platformTaskRunner);
209 }
210 
211 - (void)testTextureCallbacksAfterDestroyContextAreIgnored {
212  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:nil];
213  XCTAssertTrue([engine run]);
214  NSObject<FlutterTextureRegistry>* textures = [[engine registrarForPlugin:@"test"] textures];
215  int64_t textureId = [textures registerTexture:[[TestFlutterTexture alloc] init]];
216  [engine destroyContext];
217 
218  // Texture producers outlive the shell. Verify a frame callback arriving after teardown or during
219  // app termination don't crash.
220  [textures textureFrameAvailable:textureId];
221  [textures unregisterTexture:textureId];
222 }
223 
224 - (void)testInfoPlist {
225  // Check the embedded Flutter.framework Info.plist, not the linked dylib.
226  NSURL* flutterFrameworkURL =
227  [NSBundle.mainBundle.privateFrameworksURL URLByAppendingPathComponent:@"Flutter.framework"];
228  NSBundle* flutterBundle = [NSBundle bundleWithURL:flutterFrameworkURL];
229  XCTAssertEqualObjects(flutterBundle.bundleIdentifier, @"io.flutter.flutter");
230 
231  NSDictionary<NSString*, id>* infoDictionary = flutterBundle.infoDictionary;
232 
233  // OS version can have one, two, or three digits: "8", "8.0", "8.0.0"
234  NSError* regexError = NULL;
235  NSRegularExpression* osVersionRegex =
236  [NSRegularExpression regularExpressionWithPattern:@"((0|[1-9]\\d*)\\.)*(0|[1-9]\\d*)"
237  options:NSRegularExpressionCaseInsensitive
238  error:&regexError];
239  XCTAssertNil(regexError);
240 
241  // Smoke test the test regex.
242  NSString* testString = @"9";
243  NSUInteger versionMatches =
244  [osVersionRegex numberOfMatchesInString:testString
245  options:NSMatchingAnchored
246  range:NSMakeRange(0, testString.length)];
247  XCTAssertEqual(versionMatches, 1UL);
248  testString = @"9.1";
249  versionMatches = [osVersionRegex numberOfMatchesInString:testString
250  options:NSMatchingAnchored
251  range:NSMakeRange(0, testString.length)];
252  XCTAssertEqual(versionMatches, 1UL);
253  testString = @"9.0.1";
254  versionMatches = [osVersionRegex numberOfMatchesInString:testString
255  options:NSMatchingAnchored
256  range:NSMakeRange(0, testString.length)];
257  XCTAssertEqual(versionMatches, 1UL);
258  testString = @".0.1";
259  versionMatches = [osVersionRegex numberOfMatchesInString:testString
260  options:NSMatchingAnchored
261  range:NSMakeRange(0, testString.length)];
262  XCTAssertEqual(versionMatches, 0UL);
263 
264  // Test Info.plist values.
265  NSString* minimumOSVersion = infoDictionary[@"MinimumOSVersion"];
266  versionMatches = [osVersionRegex numberOfMatchesInString:minimumOSVersion
267  options:NSMatchingAnchored
268  range:NSMakeRange(0, minimumOSVersion.length)];
269  XCTAssertEqual(versionMatches, 1UL);
270 
271  // SHA length is 40.
272  XCTAssertEqual(((NSString*)infoDictionary[@"FlutterEngine"]).length, 40UL);
273 
274  // {clang_version} placeholder is 15 characters. The clang string version
275  // is longer than that, so check if the placeholder has been replaced, without
276  // actually checking a literal string, which could be different on various machines.
277  XCTAssertTrue(((NSString*)infoDictionary[@"ClangVersion"]).length > 15UL);
278 }
279 
280 - (void)testDeallocated {
281  __weak FlutterEngine* weakEngine = nil;
282  @autoreleasepool {
283  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"];
284  weakEngine = engine;
285  [engine run];
286  XCTAssertNotNil(weakEngine);
287  }
288  XCTAssertNil(weakEngine);
289 }
290 
291 - (void)testSendMessageBeforeRun {
292  FlutterDartProject* project = [[FlutterDartProject alloc] init];
293  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
294  XCTAssertNotNil(engine);
295  XCTAssertThrows([engine.binaryMessenger
296  sendOnChannel:@"foo"
297  message:[@"bar" dataUsingEncoding:NSUTF8StringEncoding]
298  binaryReply:nil]);
299 }
300 
301 - (void)testSetMessageHandlerBeforeRun {
302  FlutterDartProject* project = [[FlutterDartProject alloc] init];
303  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
304  XCTAssertNotNil(engine);
305  XCTAssertThrows([engine.binaryMessenger
306  setMessageHandlerOnChannel:@"foo"
307  binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply _Nonnull reply){
308 
309  }]);
310 }
311 
312 - (void)testNilSetMessageHandlerBeforeRun {
313  FlutterDartProject* project = [[FlutterDartProject alloc] init];
314  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
315  XCTAssertNotNil(engine);
316  XCTAssertNoThrow([engine.binaryMessenger setMessageHandlerOnChannel:@"foo"
317  binaryMessageHandler:nil]);
318 }
319 
320 - (void)testNotifyPluginOfDealloc {
321  id plugin = OCMProtocolMock(@protocol(FlutterPlugin));
322  OCMStub([plugin detachFromEngineForRegistrar:[OCMArg any]]);
323  @autoreleasepool {
324  FlutterDartProject* project = [[FlutterDartProject alloc] init];
325  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
326  NSObject<FlutterPluginRegistrar>* registrar = [engine registrarForPlugin:@"plugin"];
327  [registrar publish:plugin];
328  }
329  OCMVerify([plugin detachFromEngineForRegistrar:[OCMArg any]]);
330 }
331 
332 - (void)testGetViewControllerFromRegistrar {
333  FlutterDartProject* project = [[FlutterDartProject alloc] init];
334  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
335  id mockEngine = OCMPartialMock(engine);
336  NSObject<FlutterPluginRegistrar>* registrar = [mockEngine registrarForPlugin:@"plugin"];
337 
338  // Verify accessing the viewController getter calls FlutterEngine.viewController.
339  (void)[registrar viewController];
340  OCMVerify(times(1), [mockEngine viewController]);
341 }
342 
343 - (void)testSetBinaryMessengerToSameBinaryMessenger {
344  FakeBinaryMessengerRelay* fakeBinaryMessenger = [[FakeBinaryMessengerRelay alloc] init];
345 
346  FlutterEngine* engine = [[FlutterEngine alloc] init];
347  [engine setBinaryMessenger:fakeBinaryMessenger];
348 
349  // Verify that the setter doesn't free the old messenger before setting the new messenger.
350  fakeBinaryMessenger.failOnDealloc = YES;
351  [engine setBinaryMessenger:fakeBinaryMessenger];
352 
353  // Don't fail when ARC releases the binary messenger.
354  fakeBinaryMessenger.failOnDealloc = NO;
355 }
356 
357 - (void)testRunningInitialRouteSendsNavigationMessage {
358  id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]);
359 
360  FlutterEngine* engine = [[FlutterEngine alloc] init];
361  [engine setBinaryMessenger:mockBinaryMessenger];
362 
363  // Run with an initial route.
364  [engine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"];
365 
366  // Now check that an encoded method call has been made on the binary messenger to set the
367  // initial route to "test".
368  FlutterMethodCall* setInitialRouteMethodCall =
369  [FlutterMethodCall methodCallWithMethodName:@"setInitialRoute" arguments:@"test"];
370  NSData* encodedSetInitialRouteMethod =
371  [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:setInitialRouteMethodCall];
372  OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/navigation"
373  message:encodedSetInitialRouteMethod]);
374 }
375 
376 - (void)testInitialRouteSettingsSendsNavigationMessage {
377  id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]);
378 
379  auto settings = FLTDefaultSettingsForBundle();
380  settings.route = "test";
381  FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings];
382  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
383  [engine setBinaryMessenger:mockBinaryMessenger];
384  [engine run];
385 
386  // Now check that an encoded method call has been made on the binary messenger to set the
387  // initial route to "test".
388  FlutterMethodCall* setInitialRouteMethodCall =
389  [FlutterMethodCall methodCallWithMethodName:@"setInitialRoute" arguments:@"test"];
390  NSData* encodedSetInitialRouteMethod =
391  [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:setInitialRouteMethodCall];
392  OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/navigation"
393  message:encodedSetInitialRouteMethod]);
394 }
395 
396 - (void)testWaitForFirstFrameTimeout {
397  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"];
398  [engine run];
399  XCTestExpectation* timeoutFirstFrame = [self expectationWithDescription:@"timeoutFirstFrame"];
400  [engine waitForFirstFrame:0.1
401  callback:^(BOOL didTimeout) {
402  if (timeoutFirstFrame) {
403  [timeoutFirstFrame fulfill];
404  }
405  }];
406  [self waitForExpectations:@[ timeoutFirstFrame ]];
407 }
408 
409 - (void)testSpawn {
410  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"];
411  [engine run];
412  FlutterEngine* spawn = [engine spawnWithEntrypoint:nil
413  libraryURI:nil
414  initialRoute:nil
415  entrypointArgs:nil];
416  XCTAssertNotNil(spawn);
417 }
418 
419 - (void)testEngineId {
420  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"];
421  [engine run];
422  int64_t id1 = engine.engineIdentifier;
423  XCTAssertTrue(id1 != 0);
424  NSObject<FlutterPluginRegistrar>* registrar1 = [engine registrarForPlugin:@"foo"];
425  XCTAssertEqual(registrar1.engineIdentifier, id1);
426  FlutterEngine* spawn = [engine spawnWithEntrypoint:nil
427  libraryURI:nil
428  initialRoute:nil
429  entrypointArgs:nil];
430  int64_t id2 = spawn.engineIdentifier;
431  NSObject<FlutterPluginRegistrar>* registrar2 = [spawn registrarForPlugin:@"foo"];
432  XCTAssertEqual(registrar2.engineIdentifier, id2);
433  XCTAssertEqual([FlutterEngine engineForIdentifier:id1], engine);
434  XCTAssertEqual([FlutterEngine engineForIdentifier:id2], spawn);
435 }
436 
437 - (void)testSetHandlerAfterRun {
438  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"];
439  XCTestExpectation* gotMessage = [self expectationWithDescription:@"gotMessage"];
440  dispatch_async(dispatch_get_main_queue(), ^{
441  NSObject<FlutterPluginRegistrar>* registrar = [engine registrarForPlugin:@"foo"];
442  fml::AutoResetWaitableEvent latch;
443  [engine run];
444  flutter::Shell& shell = engine.shell;
445  fml::TaskRunner::RunNowOrPostTask(
446  engine.shell.GetTaskRunners().GetUITaskRunner(), [&latch, &shell] {
447  flutter::Engine::Delegate& delegate = shell;
448  auto message = std::make_unique<flutter::PlatformMessage>("foo", nullptr);
449  delegate.OnEngineHandlePlatformMessage(std::move(message));
450  latch.Signal();
451  });
452  latch.Wait();
453  [registrar.messenger setMessageHandlerOnChannel:@"foo"
454  binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) {
455  [gotMessage fulfill];
456  }];
457  });
458  [self waitForExpectations:@[ gotMessage ]];
459 }
460 
461 - (void)testThreadPrioritySetCorrectly {
462  XCTestExpectation* prioritiesSet = [self expectationWithDescription:@"prioritiesSet"];
463  prioritiesSet.expectedFulfillmentCount = 2;
464 
465  IMP mockSetThreadPriority =
466  imp_implementationWithBlock(^(NSThread* thread, double threadPriority) {
467  if ([thread.name hasSuffix:@".raster"]) {
468  XCTAssertEqual(threadPriority, 1.0);
469  [prioritiesSet fulfill];
470  } else if ([thread.name hasSuffix:@".io"]) {
471  XCTAssertEqual(threadPriority, 0.5);
472  [prioritiesSet fulfill];
473  }
474  });
475  Method method = class_getInstanceMethod([NSThread class], @selector(setThreadPriority:));
476  IMP originalSetThreadPriority = method_getImplementation(method);
477  method_setImplementation(method, mockSetThreadPriority);
478 
479  FlutterEngine* engine = [[FlutterEngine alloc] init];
480  [engine run];
481  [self waitForExpectations:@[ prioritiesSet ]];
482 
483  method_setImplementation(method, originalSetThreadPriority);
484 }
485 
486 - (void)testCanEnableDisableEmbedderAPIThroughInfoPlist {
487  {
488  // Not enable embedder API by default
489  auto settings = FLTDefaultSettingsForBundle();
490  FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings];
491  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
492  XCTAssertFalse(engine.enableEmbedderAPI);
493  }
494  {
495  // Enable embedder api
496  id mockMainBundle = OCMPartialMock([NSBundle mainBundle]);
497  OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTEnableIOSEmbedderAPI"])
498  .andReturn(@"YES");
499  auto settings = FLTDefaultSettingsForBundle();
500  FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings];
501  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
502  XCTAssertTrue(engine.enableEmbedderAPI);
503  }
504 }
505 
506 - (void)testFlutterTextInputViewDidResignFirstResponderWillCallTextInputClientConnectionClosed {
507  id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]);
508  FlutterEngine* engine = [[FlutterEngine alloc] init];
509  [engine setBinaryMessenger:mockBinaryMessenger];
510  [engine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"];
511  [engine flutterTextInputView:nil didResignFirstResponderWithTextInputClient:1];
512  FlutterMethodCall* methodCall =
513  [FlutterMethodCall methodCallWithMethodName:@"TextInputClient.onConnectionClosed"
514  arguments:@[ @(1) ]];
515  NSData* encodedMethodCall = [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:methodCall];
516  OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/textinput" message:encodedMethodCall]);
517 }
518 
519 - (void)testFlutterTextInputViewDidRestoreFirstResponderWillCallTextInputClientOnFocusReceived {
520  id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]);
521  FlutterEngine* engine = [[FlutterEngine alloc] init];
522  [engine setBinaryMessenger:mockBinaryMessenger];
523  [engine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"];
524  FlutterMethodCall* methodCall =
525  [FlutterMethodCall methodCallWithMethodName:@"TextInputClient.onFocusReceived"
526  arguments:@[ @(123) ]];
527  NSData* encodedMethodCall = [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:methodCall];
528  NSData* encodedReply = [[FlutterJSONMethodCodec sharedInstance] encodeSuccessEnvelope:@NO];
529  id mockBinaryReply = [OCMArg invokeBlockWithArgs:encodedReply, nil];
530  OCMStub([mockBinaryMessenger sendOnChannel:@"flutter/textinput"
531  message:encodedMethodCall
532  binaryReply:mockBinaryReply]);
533 
534  __block id focusReceivedResult;
535  [engine flutterTextInputView:nil
536  didRestoreFirstResponderWithTextInputClient:123
537  result:^(id result) {
538  focusReceivedResult = result;
539  }];
540  XCTAssertEqualObjects(focusReceivedResult, @NO);
541 }
542 
543 - (void)testFlutterEngineUpdatesDisplays {
544  FlutterEngine* engine = [[FlutterEngine alloc] init];
545  id mockEngine = OCMPartialMock(engine);
546 
547  [engine run];
548  OCMVerify(times(1), [mockEngine updateDisplays]);
549  engine.viewController = nil;
550  OCMVerify(times(2), [mockEngine updateDisplays]);
551 }
552 
553 - (void)testUpdateDisplaysFallsBackToMainScreenBeforeViewIsInWindow {
554  FlutterEngine* engine = [[FlutterEngine alloc] init];
555  id mockEngine = OCMPartialMock(engine);
556 
557  // The framework can read the display as soon as the isolate launches, before any view controller
558  // is attached, so `run` must send a display even though there is no screen to ask yet.
559  [engine run];
560 
561  CGSize mainScreenNativeSize = UIScreen.mainScreen.nativeBounds.size;
562  CGFloat mainScreenScale = UIScreen.mainScreen.scale;
563  OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:mainScreenNativeSize
564  scale:mainScreenScale]);
565 }
566 
567 - (void)testUpdateDisplaysUsesScreenOfViewWindow {
568  FlutterEngine* engine = [[FlutterEngine alloc] init];
569  id mockEngine = OCMPartialMock(engine);
570  __block id viewController = nil;
571  OCMStub([mockEngine viewController]).andDo(^(NSInvocation* invocation) {
572  __unsafe_unretained id value = viewController;
573  [invocation setReturnValue:&value];
574  });
575  [engine run];
576 
577  viewController = CreateMockViewControllerOnScreen(CGSizeMake(1001, 2002), 3);
578  [engine updateDisplays];
579 
580  OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
581 }
582 
583 - (void)testUpdateDisplaysDoesNotResendUnchangedDisplay {
584  FlutterEngine* engine = [[FlutterEngine alloc] init];
585  id mockEngine = OCMPartialMock(engine);
586  __block id viewController = nil;
587  OCMStub([mockEngine viewController]).andDo(^(NSInvocation* invocation) {
588  __unsafe_unretained id value = viewController;
589  [invocation setReturnValue:&value];
590  });
591  [engine run];
592 
593  viewController = CreateMockViewControllerOnScreen(CGSizeMake(1001, 2002), 3);
594  [engine updateDisplays];
595  [engine updateDisplays];
596  // A different view controller on a screen with the same size and scale.
597  viewController = CreateMockViewControllerOnScreen(CGSizeMake(1001, 2002), 3);
598  [engine updateDisplays];
599 
600  OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
601 }
602 
603 - (void)testUpdateDisplaysResendsWhenScreenChanges {
604  FlutterEngine* engine = [[FlutterEngine alloc] init];
605  id mockEngine = OCMPartialMock(engine);
606  __block id viewController = nil;
607  OCMStub([mockEngine viewController]).andDo(^(NSInvocation* invocation) {
608  __unsafe_unretained id value = viewController;
609  [invocation setReturnValue:&value];
610  });
611  [engine run];
612 
613  // E.g. moving between the outer and inner displays of a device with multiple built-in displays.
614  viewController = CreateMockViewControllerOnScreen(CGSizeMake(1001, 2002), 3);
615  [engine updateDisplays];
616  viewController = CreateMockViewControllerOnScreen(CGSizeMake(3003, 4004), 3);
617  [engine updateDisplays];
618  viewController = CreateMockViewControllerOnScreen(CGSizeMake(1001, 2002), 3);
619  [engine updateDisplays];
620  // Same size, different scale.
621  viewController = CreateMockViewControllerOnScreen(CGSizeMake(1001, 2002), 2);
622  [engine updateDisplays];
623 
624  OCMVerify(times(2), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
625  OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(3003, 4004) scale:3]);
626  OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:2]);
627 }
628 
629 - (void)testUpdateDisplaysKeepsLastDisplayWhenViewIsNotInWindow {
630  FlutterEngine* engine = [[FlutterEngine alloc] init];
631  id mockEngine = OCMPartialMock(engine);
632  __block id viewController = nil;
633  OCMStub([mockEngine viewController]).andDo(^(NSInvocation* invocation) {
634  __unsafe_unretained id value = viewController;
635  [invocation setReturnValue:&value];
636  });
637  [engine run];
638 
639  viewController = CreateMockViewControllerOnScreen(CGSizeMake(1001, 2002), 3);
640  [engine updateDisplays];
641  // A view controller whose view is not loaded (e.g. a newly attached view controller).
642  viewController = OCMClassMock([FlutterViewController class]);
643  [engine updateDisplays];
644  // No view controller.
645  viewController = nil;
646  [engine updateDisplays];
647 
648  // Only the initial display (from `run`) used the `UIScreen.mainScreen` fallback.
649  CGSize mainScreenNativeSize = UIScreen.mainScreen.nativeBounds.size;
650  CGFloat mainScreenScale = UIScreen.mainScreen.scale;
651  OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:mainScreenNativeSize
652  scale:mainScreenScale]);
653  OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
654 }
655 
656 - (void)testLifeCycleNotificationDidEnterBackgroundForApplication {
657  FlutterDartProject* project = [[FlutterDartProject alloc] init];
658  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
659  [engine run];
660  NSNotification* sceneNotification =
661  [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
662  object:nil
663  userInfo:nil];
664  NSNotification* applicationNotification =
665  [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification
666  object:nil
667  userInfo:nil];
668  id mockEngine = OCMPartialMock(engine);
669  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
670  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
671  OCMVerify(times(1), [mockEngine applicationDidEnterBackground:[OCMArg any]]);
672  XCTAssertTrue(engine.isGpuDisabled);
673  BOOL gpuDisabled = NO;
674  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
675  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
676  gpuDisabled = NO;
677  }));
678  XCTAssertTrue(gpuDisabled);
679 }
680 
681 - (void)testLifeCycleNotificationDidEnterBackgroundForScene {
682  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
683  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
684  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
685  });
686  FlutterDartProject* project = [[FlutterDartProject alloc] init];
687  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
688  [engine run];
689  NSNotification* sceneNotification =
690  [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
691  object:nil
692  userInfo:nil];
693  NSNotification* applicationNotification =
694  [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification
695  object:nil
696  userInfo:nil];
697  id mockEngine = OCMPartialMock(engine);
698  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
699  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
700  OCMVerify(times(1), [mockEngine sceneDidEnterBackground:[OCMArg any]]);
701  XCTAssertTrue(engine.isGpuDisabled);
702  BOOL gpuDisabled = NO;
703  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
704  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
705  gpuDisabled = NO;
706  }));
707  XCTAssertTrue(gpuDisabled);
708  [mockBundle stopMocking];
709 }
710 
711 - (void)testLifeCycleNotificationWillEnterForegroundForApplication {
712  FlutterDartProject* project = [[FlutterDartProject alloc] init];
713  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
714  [engine run];
715  NSNotification* sceneNotification =
716  [NSNotification notificationWithName:UISceneWillEnterForegroundNotification
717  object:nil
718  userInfo:nil];
719  NSNotification* applicationNotification =
720  [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification
721  object:nil
722  userInfo:nil];
723  id mockEngine = OCMPartialMock(engine);
724  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
725  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
726  OCMVerify(times(1), [mockEngine applicationWillEnterForeground:[OCMArg any]]);
727  XCTAssertFalse(engine.isGpuDisabled);
728  BOOL gpuDisabled = YES;
729  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
730  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
731  gpuDisabled = NO;
732  }));
733  XCTAssertFalse(gpuDisabled);
734 }
735 
736 - (void)testLifeCycleNotificationWillEnterForegroundForScene {
737  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
738  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
739  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
740  });
741  FlutterDartProject* project = [[FlutterDartProject alloc] init];
742  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
743  [engine run];
744  NSNotification* sceneNotification =
745  [NSNotification notificationWithName:UISceneWillEnterForegroundNotification
746  object:nil
747  userInfo:nil];
748  NSNotification* applicationNotification =
749  [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification
750  object:nil
751  userInfo:nil];
752  id mockEngine = OCMPartialMock(engine);
753  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
754  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
755  OCMVerify(times(1), [mockEngine sceneWillEnterForeground:[OCMArg any]]);
756  XCTAssertFalse(engine.isGpuDisabled);
757  BOOL gpuDisabled = YES;
758  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
759  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
760  gpuDisabled = NO;
761  }));
762  XCTAssertFalse(gpuDisabled);
763  [mockBundle stopMocking];
764 }
765 
766 // Verifies a value assigned to `isGpuDisabled` before the engine runs is set on the shell.
767 //
768 // The property is public and readwrite, so an embedder that knows it is starting an engine into the
769 // background can set it before `run`. Reading the lifecycle state anywhere on the creation path
770 // would overwrite that assignment, and the caller has no way to observe it happening.
771 //
772 // See: https://github.com/flutter/flutter/issues/190835
773 - (void)testGpuStateSetBeforeRunIsAppliedToShell {
774  FlutterDartProject* project = [[FlutterDartProject alloc] init];
775  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
776 
777  engine.isGpuDisabled = YES;
778  XCTAssertTrue(engine.isGpuDisabled);
779 
780  [engine run];
781 
782  XCTAssertTrue(engine.isGpuDisabled);
783 
784  BOOL gpuDisabled = NO;
785  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
786  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
787  gpuDisabled = NO;
788  }));
789  XCTAssertTrue(gpuDisabled);
790 }
791 
792 // Verifies an engine created while the application is backgrounded starts with the GPU disabled.
793 //
794 // Lifecycle notifications only report transitions. Verify that we explicitly check GPU state on
795 // creation.
796 //
797 // See: https://github.com/flutter/flutter/issues/190835
798 - (void)testGpuIsDisabledWhenCreatedWhileBackgrounded {
799  id mockApplication = OCMClassMock([UIApplication class]);
800  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
801  OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateBackground);
802  [self addTeardownBlock:^{
803  [mockApplication stopMocking];
804  }];
805 
806  FlutterDartProject* project = [[FlutterDartProject alloc] init];
807  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
808 
809  // Read at init. No notification could have arrived yet.
810  XCTAssertTrue(engine.isGpuDisabled);
811 
812  [engine run];
813 
814  BOOL gpuDisabled = NO;
815  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
816  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
817  gpuDisabled = NO;
818  }));
819  XCTAssertTrue(gpuDisabled);
820 }
821 
822 // Verifies an engine created while the app is foregrounded starts with the GPU available, and that
823 // detaching a view controller re-enables the GPU on an engine that currently has it disabled.
824 //
825 // Attaching or detaching a view controller must re-read the lifecycle state and update the current
826 // engine GPU state. An engine disabled by an earlier background transition must come back up with
827 // the GPU available once the application reads as foregrounded.
828 //
829 // This is specifically testing *app* scenarios, where `UIApplication.sharedApplication` is
830 // available.
831 //
832 // See: https://github.com/flutter/flutter/issues/190835
833 - (void)testGpuIsEnabledWhenCreatedWhileForegrounded {
834  id mockApplication = OCMClassMock([UIApplication class]);
835  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
836  OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateActive);
837  [self addTeardownBlock:^{
838  [mockApplication stopMocking];
839  }];
840 
841  FlutterDartProject* project = [[FlutterDartProject alloc] init];
842  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
843  [engine run];
844 
845  XCTAssertFalse(engine.isGpuDisabled);
846 
847  BOOL gpuDisabled = YES;
848  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
849  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
850  gpuDisabled = NO;
851  }));
852  XCTAssertFalse(gpuDisabled);
853 
854  // Detaching re-reads the lifecycle state. The application is readable, so the read must overwrite
855  // this rather than preserve it.
856  engine.isGpuDisabled = YES;
857  engine.viewController = nil;
858 
859  XCTAssertFalse(engine.isGpuDisabled);
860 
861  gpuDisabled = YES;
862  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
863  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
864  gpuDisabled = NO;
865  }));
866  XCTAssertFalse(gpuDisabled);
867 }
868 
869 // Verifies that detaching a view controller leaves the GPU disabled when the lifecycle state cannot
870 // be read.
871 //
872 // Attaching or detaching a view controller re-reads the lifecycle state. In an app extension, there
873 // is no `UIApplication`, and no scene without a view controller whose view is attached to a
874 // window's view hierarchy, so we have no source to check. The value determined by the last scene
875 // notification is the only information available, so we preserve that.
876 //
877 // In particular, an engine disabled while its scene is backgrounded must stay disabled, since
878 // rendering in the background will result in app termination.
879 //
880 // See: https://github.com/flutter/flutter/issues/190835
881 - (void)testGpuStateIsPreservedWhenLifecycleStateIsUnknown {
882  // Declaring `NSExtension` puts `FlutterSharedApplication` into its app extension configuration
883  // rather than stubbing its result.
884  //
885  // `isAvailable` is NO, `application` returns nil without touching `UIApplication`, and the engine
886  // registers the scene observers rather than the application ones.
887  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
888  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
889  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
890  });
891  [self addTeardownBlock:^{
892  [mockBundle stopMocking];
893  }];
895 
896  FlutterDartProject* project = [[FlutterDartProject alloc] init];
897  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
898  [engine run];
899 
900  // The scene notification is the only signal available in this configuration, and the engine is
901  // observing for it because the bundle declares an extension.
902  [[NSNotificationCenter defaultCenter]
903  postNotification:[NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
904  object:nil
905  userInfo:nil]];
906  XCTAssertTrue(engine.isGpuDisabled);
907 
908  // Detaching re-reads the lifecycle state, and must find no source to overwrite the above with.
909  engine.viewController = nil;
910 
911  XCTAssertTrue(engine.isGpuDisabled);
912 
913  BOOL gpuDisabled = NO;
914  [engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
915  fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
916  gpuDisabled = NO;
917  }));
918  XCTAssertTrue(gpuDisabled);
919 }
920 
921 // Verifies a handler registered against a background FlutterTaskQueue runs off the platform thread.
922 //
923 // Using the `FlutterTaskQueue` public API, a plugin may register a channel handler against a
924 // background queue and expect to be called off the platform thread. `PlatformMessageHandlerIosTest`
925 // tests the handler in isolation, but doesn't cover the full path an actual plugin takes:
926 //
927 // `-[FlutterEngine makeBackgroundTaskQueue]` and
928 // `-[FlutterEngine setMessageHandlerOnChannel:binaryMessageHandler:taskQueue:]`.
929 //
930 // The embedder API has no equivalent concept: `EmbedderPlatformMessageHandler` always trampolines
931 // to the platform thread, so this contract has to be reproduced explicitly during embedder API
932 // migration.
933 //
934 // `testNilTaskQueueDeliversOnThePlatformThread`, tests the other direction.
935 - (void)testBackgroundTaskQueueDeliversOffThePlatformThread {
936  FlutterDartProject* project = [[FlutterDartProject alloc] init];
937  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
938  [engine run];
939 
940  NSObject<FlutterTaskQueue>* taskQueue = [engine makeBackgroundTaskQueue];
941  XCTAssertNotNil(taskQueue);
942 
943  NSString* channel = @"com.example.background";
944  XCTestExpectation* didCallHandler = [self expectationWithDescription:@"didCallHandler"];
946  [engine setMessageHandlerOnChannel:channel
947  binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply reply) {
948  XCTAssertFalse([NSThread isMainThread]);
949  reply(nil);
950  [didCallHandler fulfill];
951  }
952  taskQueue:taskQueue];
953  XCTAssertTrue(connection > 0);
954 
955  // Deliver a message the way the platform view would on receiving one from the engine.
956  auto response = TestPlatformMessageResponse::Create();
957  engine.platformView->GetPlatformMessageHandlerIos()->HandlePlatformMessage(
958  std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response));
959 
960  [self waitForExpectationsWithTimeout:5.0 handler:nil];
961  XCTAssertTrue(response->is_complete());
962 
963  [engine cleanUpConnection:connection];
964 }
965 
966 // Verifies a handler registered without a task queue runs on the platform thread.
967 //
968 // Together with `testBackgroundTaskQueueDeliversOffThePlatformThread` locks in the invariant that
969 // the task queue argument, and nothing else, decides the thread. The default is the platform
970 // thread, which needs to be preserved throughout embedder API migration: this is what allows
971 // plugins interact with UIKit directly from their channel handlers.
972 //
973 // This is the half the embedder API migration is most likely to cause to pass by accident.
974 // `EmbedderPlatformMessageHandler` trampolines everything to the platform thread, so an
975 // implementation that never leaves it goes green here and fails only in
976 // `testBackgroundTaskQueueDeliversOffThePlatformThread`.
977 - (void)testNilTaskQueueDeliversOnThePlatformThread {
978  FlutterDartProject* project = [[FlutterDartProject alloc] init];
979  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
980  [engine run];
981 
982  NSString* channel = @"com.example.platform";
983  XCTestExpectation* didCallHandler = [self expectationWithDescription:@"didCallHandler"];
985  [engine setMessageHandlerOnChannel:channel
986  binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply reply) {
987  XCTAssertTrue([NSThread isMainThread]);
988  reply(nil);
989  [didCallHandler fulfill];
990  }
991  taskQueue:nil];
992  XCTAssertTrue(connection > 0);
993 
994  auto response = TestPlatformMessageResponse::Create();
995  engine.platformView->GetPlatformMessageHandlerIos()->HandlePlatformMessage(
996  std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response));
997 
998  [self waitForExpectationsWithTimeout:5.0 handler:nil];
999  XCTAssertTrue(response->is_complete());
1000 
1001  [engine cleanUpConnection:connection];
1002 }
1003 
1004 - (void)testLifeCycleNotificationSceneWillConnect {
1005  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1006  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
1007  [engine run];
1008  id mockScene = OCMClassMock([UIWindowScene class]);
1009  id mockLifecycleProvider = OCMProtocolMock(@protocol(FlutterSceneLifeCycleProvider));
1010  id mockLifecycleDelegate = OCMClassMock([FlutterPluginSceneLifeCycleDelegate class]);
1011  OCMStub([mockScene delegate]).andReturn(mockLifecycleProvider);
1012  OCMStub([mockLifecycleProvider sceneLifeCycleDelegate]).andReturn(mockLifecycleDelegate);
1013 
1014  NSNotification* sceneNotification =
1015  [NSNotification notificationWithName:UISceneWillConnectNotification
1016  object:mockScene
1017  userInfo:nil];
1018 
1019  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
1020  OCMVerify(times(1), [mockLifecycleDelegate engine:engine
1021  receivedConnectNotificationFor:mockScene]);
1022 }
1023 
1024 - (void)testSpawnsShareGpuContext {
1025  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"];
1026  [engine run];
1027  FlutterEngine* spawn = [engine spawnWithEntrypoint:nil
1028  libraryURI:nil
1029  initialRoute:nil
1030  entrypointArgs:nil];
1031  XCTAssertNotNil(spawn);
1032  XCTAssertTrue(engine.platformView != nullptr);
1033  XCTAssertTrue(spawn.platformView != nullptr);
1034  std::shared_ptr<flutter::IOSContext> engine_context = engine.platformView->GetIosContext();
1035  std::shared_ptr<flutter::IOSContext> spawn_context = spawn.platformView->GetIosContext();
1036  XCTAssertEqual(engine_context, spawn_context);
1037 }
1038 
1039 - (void)testEnableSemanticsWhenFlutterViewAccessibilityDidCall {
1040  FlutterEngineSpy* engine = [[FlutterEngineSpy alloc] initWithName:@"foobar"];
1041  engine.ensureSemanticsEnabledCalled = NO;
1042  [engine flutterViewAccessibilityDidCall];
1043  XCTAssertTrue(engine.ensureSemanticsEnabledCalled);
1044 }
1045 
1046 - (void)testCanMergePlatformAndUIThread {
1047 #if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
1048  auto settings = FLTDefaultSettingsForBundle();
1049  FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings];
1050  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
1051  [engine run];
1052 
1053  XCTAssertEqual(engine.shell.GetTaskRunners().GetUITaskRunner(),
1054  engine.shell.GetTaskRunners().GetPlatformTaskRunner());
1055 #endif // defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
1056 }
1057 
1058 - (void)testAddSceneDelegateToRegistrar {
1059  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1060  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
1061  id mockEngine = OCMPartialMock(engine);
1062  NSObject<FlutterPluginRegistrar>* registrar = [mockEngine registrarForPlugin:@"plugin"];
1063  id mockPlugin = OCMProtocolMock(@protocol(TestFlutterPluginWithSceneEvents));
1064  [registrar addSceneDelegate:mockPlugin];
1065 
1066  OCMVerify(times(1), [mockEngine addSceneLifeCycleDelegate:[OCMArg any]]);
1067 }
1068 
1069 - (void)testNotifyAppDelegateOfEngineInitialization {
1070  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1071  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
1072 
1073  id mockApplication = OCMClassMock([UIApplication class]);
1074  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1075  id mockAppDelegate = OCMProtocolMock(@protocol(FlutterImplicitEngineDelegate));
1076  OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1077 
1078  [engine performImplicitEngineCallback];
1079  OCMVerify(times(1), [mockAppDelegate didInitializeImplicitFlutterEngine:[OCMArg any]]);
1080 }
1081 
1082 - (void)testRegistrarForPlugin {
1083  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1084  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
1085  FlutterEngine* mockEngine = OCMPartialMock(engine);
1086  id mockViewController = OCMClassMock([FlutterViewController class]);
1087  id mockBinaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
1088  id mockTextureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry));
1089  id mockPlatformViewController = OCMClassMock([FlutterPlatformViewsController class]);
1090  OCMStub([mockEngine viewController]).andReturn(mockViewController);
1091  OCMStub([mockEngine binaryMessenger]).andReturn(mockBinaryMessenger);
1092  OCMStub([mockEngine textureRegistry]).andReturn(mockTextureRegistry);
1093  OCMStub([mockEngine platformViewsController]).andReturn(mockPlatformViewController);
1094 
1095  NSString* pluginKey = @"plugin";
1096  NSString* assetKey = @"asset";
1097  NSString* factoryKey = @"platform_view_factory";
1098 
1099  NSObject<FlutterPluginRegistrar>* registrar = [mockEngine registrarForPlugin:pluginKey];
1100 
1101  XCTAssertTrue([registrar respondsToSelector:@selector(messenger)]);
1102  XCTAssertTrue([registrar respondsToSelector:@selector(textures)]);
1103  XCTAssertTrue([registrar respondsToSelector:@selector(registerViewFactory:withId:)]);
1104  XCTAssertTrue([registrar
1105  respondsToSelector:@selector(registerViewFactory:withId:gestureRecognizersBlockingPolicy:)]);
1106  XCTAssertTrue([registrar respondsToSelector:@selector(viewController)]);
1107  XCTAssertTrue([registrar respondsToSelector:@selector(publish:)]);
1108  XCTAssertTrue([registrar respondsToSelector:@selector(valuePublishedByPlugin:)]);
1109  XCTAssertTrue([registrar respondsToSelector:@selector(addMethodCallDelegate:channel:)]);
1110  XCTAssertTrue([registrar respondsToSelector:@selector(addApplicationDelegate:)]);
1111  XCTAssertTrue([registrar respondsToSelector:@selector(lookupKeyForAsset:)]);
1112  XCTAssertTrue([registrar respondsToSelector:@selector(lookupKeyForAsset:fromPackage:)]);
1113 
1114  // Verify messenger, textures, and viewController forwards to FlutterEngine
1115  XCTAssertEqual(registrar.messenger, mockBinaryMessenger);
1116  XCTAssertEqual(registrar.textures, mockTextureRegistry);
1117  XCTAssertEqual(registrar.viewController, mockViewController);
1118 
1119  // Verify registerViewFactory:withId:, registerViewFactory:withId:gestureRecognizersBlockingPolicy
1120  // forwards to FlutterEngine
1121  id mockPlatformViewFactory = OCMProtocolMock(@protocol(FlutterPlatformViewFactory));
1122  [registrar registerViewFactory:mockPlatformViewFactory withId:factoryKey];
1123  [registrar registerViewFactory:mockPlatformViewFactory
1124  withId:factoryKey
1125  gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager];
1126  OCMVerify(times(2), [mockPlatformViewController registerViewFactory:mockPlatformViewFactory
1127  withId:factoryKey
1128  gestureRecognizersBlockingPolicy:
1130 
1131  // Verify publish forwards to FlutterEngine
1132  id plugin = OCMProtocolMock(@protocol(FlutterPlugin));
1133  [registrar publish:plugin];
1134  XCTAssertEqual(mockEngine.pluginPublications[pluginKey], plugin);
1135 
1136  // Verify lookup forwards to FlutterEngine by fetching the published plugin
1137  id published = [registrar valuePublishedByPlugin:pluginKey];
1138  XCTAssertEqual(plugin, published);
1139 
1140  // Verify lookupKeyForAsset:, lookupKeyForAsset:fromPackage forward to engine
1141  [registrar lookupKeyForAsset:assetKey];
1142  OCMVerify(times(1), [mockEngine lookupKeyForAsset:assetKey]);
1143  [registrar lookupKeyForAsset:assetKey fromPackage:pluginKey];
1144  OCMVerify(times(1), [mockEngine lookupKeyForAsset:assetKey fromPackage:pluginKey]);
1145 }
1146 
1147 - (void)testRegistrarForApplication {
1148  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1149  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
1150  FlutterEngine* mockEngine = OCMPartialMock(engine);
1151  id mockViewController = OCMClassMock([FlutterViewController class]);
1152  id mockBinaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
1153  id mockTextureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry));
1154  id mockPlatformViewController = OCMClassMock([FlutterPlatformViewsController class]);
1155  OCMStub([mockEngine viewController]).andReturn(mockViewController);
1156  OCMStub([mockEngine binaryMessenger]).andReturn(mockBinaryMessenger);
1157  OCMStub([mockEngine textureRegistry]).andReturn(mockTextureRegistry);
1158  OCMStub([mockEngine platformViewsController]).andReturn(mockPlatformViewController);
1159 
1160  NSString* pluginKey = @"plugin";
1161  NSString* factoryKey = @"platform_view_factory";
1162 
1163  NSObject<FlutterApplicationRegistrar>* registrar = [mockEngine registrarForApplication:pluginKey];
1164 
1165  XCTAssertTrue([registrar respondsToSelector:@selector(engineIdentifier)]);
1166  XCTAssertEqual(registrar.engineIdentifier, engine.engineIdentifier);
1167  XCTAssertTrue([registrar respondsToSelector:@selector(messenger)]);
1168  XCTAssertTrue([registrar respondsToSelector:@selector(textures)]);
1169  XCTAssertTrue([registrar respondsToSelector:@selector(registerViewFactory:withId:)]);
1170  XCTAssertTrue([registrar
1171  respondsToSelector:@selector(registerViewFactory:withId:gestureRecognizersBlockingPolicy:)]);
1172  XCTAssertFalse([registrar respondsToSelector:@selector(viewController)]);
1173  XCTAssertFalse([registrar respondsToSelector:@selector(publish:)]);
1174  XCTAssertFalse([registrar respondsToSelector:@selector(valuePublishedByPlugin:)]);
1175  XCTAssertFalse([registrar respondsToSelector:@selector(addMethodCallDelegate:channel:)]);
1176  XCTAssertFalse([registrar respondsToSelector:@selector(addApplicationDelegate:)]);
1177  XCTAssertFalse([registrar respondsToSelector:@selector(lookupKeyForAsset:)]);
1178  XCTAssertFalse([registrar respondsToSelector:@selector(lookupKeyForAsset:fromPackage:)]);
1179 
1180  // Verify messenger and textures forwards to FlutterEngine
1181  XCTAssertEqual(registrar.messenger, mockBinaryMessenger);
1182  XCTAssertEqual(registrar.textures, mockTextureRegistry);
1183 
1184  // Verify registerViewFactory:withId:, registerViewFactory:withId:gestureRecognizersBlockingPolicy
1185  // forwards to FlutterEngine
1186  id mockPlatformViewFactory = OCMProtocolMock(@protocol(FlutterPlatformViewFactory));
1187  [registrar registerViewFactory:mockPlatformViewFactory withId:factoryKey];
1188  [registrar registerViewFactory:mockPlatformViewFactory
1189  withId:factoryKey
1190  gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager];
1191  OCMVerify(times(2), [mockPlatformViewController registerViewFactory:mockPlatformViewFactory
1192  withId:factoryKey
1193  gestureRecognizersBlockingPolicy:
1195 }
1196 
1197 - (void)testSendDeepLinkToFrameworkTimesOut {
1198  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1199  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
1200  id mockEngine = OCMPartialMock(engine);
1201  id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@YES, nil];
1202  OCMStub([mockEngine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]);
1203 
1204  NSURL* url = [NSURL URLWithString:@"example.com"];
1205 
1206  [mockEngine sendDeepLinkToFramework:url
1207  completionHandler:^(BOOL success) {
1208  XCTAssertFalse(success);
1209  }];
1210 }
1211 
1212 - (void)testSendDeepLinkToFrameworkUsingNavigationChannel {
1213  NSString* urlString = @"example.com";
1214  NSURL* url = [NSURL URLWithString:urlString];
1215  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1216  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
1217  id mockEngine = OCMPartialMock(engine);
1218  id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@NO, nil];
1219  OCMStub([mockEngine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]);
1220  id mockNavigationChannel = OCMClassMock([FlutterMethodChannel class]);
1221  OCMStub([mockEngine navigationChannel]).andReturn(mockNavigationChannel);
1222  id mockNavigationChannelCallback = [OCMArg invokeBlockWithArgs:@1, nil];
1223  OCMStub([mockNavigationChannel invokeMethod:@"pushRouteInformation"
1224  arguments:@{@"location" : urlString}
1225  result:mockNavigationChannelCallback]);
1226 
1227  [mockEngine sendDeepLinkToFramework:url
1228  completionHandler:^(BOOL success) {
1229  XCTAssertTrue(success);
1230  }];
1231 }
1232 
1233 - (void)testSendDeepLinkToFrameworkUsingNavigationChannelFails {
1234  NSString* urlString = @"example.com";
1235  NSURL* url = [NSURL URLWithString:urlString];
1236  FlutterDartProject* project = [[FlutterDartProject alloc] init];
1237  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project];
1238  id mockEngine = OCMPartialMock(engine);
1239  id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@NO, nil];
1240  OCMStub([mockEngine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]);
1241  id mockNavigationChannel = OCMClassMock([FlutterMethodChannel class]);
1242  OCMStub([mockEngine navigationChannel]).andReturn(mockNavigationChannel);
1243  id mockNavigationChannelCallback = [OCMArg invokeBlockWithArgs:@0, nil];
1244  OCMStub([mockNavigationChannel invokeMethod:@"pushRouteInformation"
1245  arguments:@{@"location" : urlString}
1246  result:mockNavigationChannelCallback]);
1247 
1248  [mockEngine sendDeepLinkToFramework:url
1249  completionHandler:^(BOOL success) {
1250  XCTAssertFalse(success);
1251  }];
1252 }
1253 
1254 #pragma mark - Scene Lifecycle Warning Tests
1255 
1256 - (void)testAddApplicationDelegateLogsWarningWhenPluginDoesNotConformToSceneDelegate {
1257  FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
1258  writer.expectedOutput = @"uses deprecated application lifecycle events";
1259  FlutterLogger.outputWriter = writer;
1260 
1261  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:nil];
1262  id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"TestPlugin"];
1263 
1264  // Create a mock plugin that does NOT conform to FlutterSceneLifeCycleDelegate.
1265  id mockPlugin = OCMProtocolMock(@protocol(FlutterPlugin));
1266 
1267  id mockAppDelegate = OCMProtocolMock(@protocol(FlutterAppLifeCycleProvider));
1268  id mockApplication = OCMClassMock([UIApplication class]);
1269  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1270  OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1271 
1272  [registrar addApplicationDelegate:mockPlugin];
1273 
1274  XCTAssertTrue(writer.gotExpectedOutput,
1275  @"Expected warning about plugin not adopting scenes was not logged");
1276 }
1277 
1278 - (void)testAddApplicationDelegateDoesNotLogWarningWhenPluginConformsToSceneDelegate {
1279  FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
1280  FlutterLogger.outputWriter = writer;
1281 
1282  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:nil];
1283  id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"TestPluginWithSceneEvents"];
1284 
1285  id mockPlugin = OCMProtocolMock(@protocol(TestFlutterPluginWithSceneEvents));
1286 
1287  id mockAppDelegate = OCMProtocolMock(@protocol(FlutterAppLifeCycleProvider));
1288  id mockApplication = OCMClassMock([UIApplication class]);
1289  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1290  OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1291 
1292  [registrar addApplicationDelegate:mockPlugin];
1293 
1294  XCTAssertFalse(writer.didLog, @"No warning should be logged for scene-conforming plugin");
1295 }
1296 
1297 - (void)testAddApplicationDelegateDoesNotLogWarningWhenPluginDoesNotUseLifecycleEvents {
1298  FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
1299  FlutterLogger.outputWriter = writer;
1300 
1301  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:nil];
1302  id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"MinimalPlugin"];
1303 
1304  // Use a concrete FlutterPlugin that does NOT implement any lifecycle methods.
1305  // Even though it does not conform to FlutterSceneLifeCycleDelegate,
1306  // no warning should be logged because it doesn't use any lifecycle events.
1307  TestMinimalFlutterPlugin* plugin = [[TestMinimalFlutterPlugin alloc] init];
1308 
1309  id mockAppDelegate = OCMProtocolMock(@protocol(FlutterAppLifeCycleProvider));
1310  id mockApplication = OCMClassMock([UIApplication class]);
1311  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1312  OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1313 
1314  [registrar addApplicationDelegate:plugin];
1315 
1316  XCTAssertFalse(writer.didLog,
1317  @"No warning should be logged for a plugin that doesn't use lifecycle events");
1318 }
1319 
1320 @end
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterBinaryReply)(NSData *_Nullable reply)
int64_t FlutterBinaryMessengerConnection
flutter::Settings FLTDefaultSettingsForBundle(NSBundle *bundle, NSProcessInfo *processInfoOrNil)
@ FlutterPlatformViewGestureRecognizersBlockingPolicyEager
FlutterViewController * viewController
void Complete(std::unique_ptr< fml::Mapping > data) override
static fml::RefPtr< TestPlatformMessageResponse > Create()
const std::shared_ptr< IOSContext > & GetIosContext()
BOOL runWithEntrypoint:initialRoute:(nullable NSString *entrypoint,[initialRoute] nullable NSString *NS_SWIFT_UI_ACTOR)
flutter::PlatformViewIOS * platformView()
flutter::Shell & shell()
void setBinaryMessenger:(FlutterBinaryMessengerRelay *binaryMessenger)
void updateDisplays()
FlutterEngine * spawnWithEntrypoint:libraryURI:initialRoute:entrypointArgs:(/*nullable */NSString *entrypoint,[libraryURI]/*nullable */NSString *libraryURI,[initialRoute]/*nullable */NSString *initialRoute,[entrypointArgs]/*nullable */NSArray< NSString * > *NS_SWIFT_UI_ACTOR)
NSMutableDictionary * pluginPublications
void ensureSemanticsEnabled()
void waitForFirstFrame:callback:(NSTimeInterval timeout,[callback] void(^ callback)(BOOL didTimeout))
instancetype methodCallWithMethodName:arguments:(NSString *method,[arguments] id _Nullable arguments)
A FlutterTexture that vends no frames. Used to obtain a registered texture id.
id CreateMockViewControllerOnScreen(CGSize screenNativeSize, CGFloat screenScale)
nullable NSObject< FlutterPluginRegistrar > * registrarForPlugin:(NSString *pluginKey)
CVPixelBufferRef _Nullable copyPixelBuffer()