Flutter iOS Embedder
FlutterViewControllerTest.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 <OCMock/OCMock.h>
6 #import <XCTest/XCTest.h>
7 
8 #include "flutter/fml/platform/darwin/message_loop_darwin.h"
9 #import "flutter/lib/ui/window/platform_configuration.h"
10 #include "flutter/lib/ui/window/pointer_data.h"
11 #include "flutter/lib/ui/window/pointer_data_packet.h"
12 #import "flutter/lib/ui/window/viewport_metrics.h"
30 #import "flutter/shell/platform/embedder/embedder.h"
31 #import "flutter/testing/ios/IosUnitTests/App/AppDelegate.h"
32 #import "flutter/third_party/spring_animation/spring_animation.h"
33 
35 
36 using namespace flutter::testing;
37 
38 typedef void (^FlutterKeyboardAnimationCallback)(NSTimeInterval targetTime);
39 
41 - (void)setUpKeyboardAnimationVsyncClient:
42  (FlutterKeyboardAnimationCallback)keyboardAnimationCallback;
43 @property(nonatomic, assign, readwrite) CGFloat targetViewInsetBottom;
44 @property(nonatomic, assign) BOOL keyboardAnimationIsShowing;
45 @property(nonatomic, weak) id<FlutterKeyboardInsetManagerDelegate> delegate;
46 @property(nonatomic, strong) FlutterVSyncClient* keyboardAnimationVSyncClient;
47 @property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground;
48 - (void)handleKeyboardNotification:(NSNotification*)notification;
49 - (BOOL)isKeyboardNotificationForDifferentView:(NSNotification*)notification;
50 - (CGFloat)calculateKeyboardInset:(CGRect)keyboardFrame
51  keyboardMode:(FlutterKeyboardMode)keyboardMode;
52 - (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification;
53 - (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification;
54 - (CGFloat)calculateMultitaskingAdjustment:(CGRect)screenRect keyboardFrame:(CGRect)keyboardFrame;
55 - (void)startKeyBoardAnimation:(NSTimeInterval)duration;
57 - (UIView*)keyboardAnimationView;
58 - (SpringAnimation*)keyboardSpringAnimation;
59 - (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation;
62 @end
63 
64 // A fake keyboard inset manager.
65 //
66 // Used to verify that FlutterViewController drives the manager through the
67 // FlutterKeyboardInsetManagerProtocol (e.g. on viewDidDisappear), while
68 // avoiding the need to set up and perform real animations.
69 @interface FakeFlutterKeyboardInsetManager : NSObject <FlutterKeyboardInsetManagerProtocol>
70 @property(nonatomic, assign) CGFloat targetViewInsetBottom;
71 @property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground;
72 @property(nonatomic, strong) FlutterVSyncClient* keyboardAnimationVSyncClient;
73 @property(nonatomic, assign) BOOL didCallEnsureViewportMetricsIsCorrect;
74 @property(nonatomic, assign) BOOL didCallInvalidateKeyboardAnimationVSyncClient;
75 
76 - (instancetype)initWithDelegate:(id<FlutterKeyboardInsetManagerDelegate>)delegate;
77 @end
78 
79 @implementation FakeFlutterKeyboardInsetManager {
80  __weak id<FlutterKeyboardInsetManagerDelegate> _delegate;
81 }
82 
83 - (instancetype)initWithDelegate:(id<FlutterKeyboardInsetManagerDelegate>)delegate {
84  self = [super init];
85  if (self) {
86  _delegate = delegate;
87  }
88  return self;
89 }
90 
91 - (void)setDelegate:(id<FlutterKeyboardInsetManagerDelegate>)delegate {
92  _delegate = delegate;
93 }
94 
95 - (id<FlutterKeyboardInsetManagerDelegate>)delegate {
96  return _delegate;
97 }
98 
99 - (void)startKeyBoardAnimation:(NSTimeInterval)duration {
100 }
101 
102 - (void)handleKeyboardNotification:(NSNotification*)notification {
103 }
104 
105 - (void)setUpKeyboardAnimationVsyncClient:(FlutterKeyboardAnimationCallback)animationCallback {
106  self.keyboardAnimationVSyncClient = nil;
107 }
108 
109 - (void)invalidate {
110 }
111 
112 - (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation {
113 }
114 
115 - (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification {
116  return NO;
117 }
118 
119 - (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification {
120  return FlutterKeyboardModeHidden;
121 }
122 
123 - (void)ensureViewportMetricsIsCorrect {
124  self.didCallEnsureViewportMetricsIsCorrect = YES;
125 }
126 
127 - (void)invalidateKeyboardAnimationVSyncClient {
128  self.didCallInvalidateKeyboardAnimationVSyncClient = YES;
129 }
130 
131 - (void)hideKeyboardImmediately {
132  [self ensureViewportMetricsIsCorrect];
133  [self invalidateKeyboardAnimationVSyncClient];
134 }
135 
136 - (SpringAnimation*)keyboardSpringAnimation {
137  return nullptr;
138 }
139 
140 - (UIView*)keyboardAnimationView {
141  return nullptr;
142 }
143 
144 @end
145 
146 @interface TestKeyboardInsetDelegate : NSObject <FlutterKeyboardInsetManagerDelegate>
147 @property(nonatomic, strong) UIScreen* mockScreen;
148 @property(nonatomic, strong) UIView* mockView;
149 @property(nonatomic, strong) FlutterEngine* mockEngine;
150 @property(nonatomic, assign) CGFloat currentInset;
151 @property(nonatomic, copy) void (^updateViewportMetricsBlock)(CGFloat inset);
152 @property(nonatomic, assign) BOOL isViewLoaded;
153 @property(nonatomic, assign) BOOL mockIsPadInSlideOverOrStageManagerMode;
154 @property(nonatomic, assign) CGRect mockConvertedViewRect;
155 @property(nonatomic, strong) FlutterFMLTaskRunner* mockTaskRunner;
156 @end
157 
158 @implementation TestKeyboardInsetDelegate
159 
160 - (instancetype)init {
161  if (self = [super init]) {
162  fml::MessageLoop::EnsureInitializedForCurrentThread();
163  _mockTaskRunner = [[FlutterFMLTaskRunner alloc]
164  initWithTaskRunner:fml::MessageLoop::GetCurrent().GetTaskRunner()];
165  }
166  return self;
167 }
168 
169 - (FlutterFMLTaskRunner*)uiTaskRunner {
170  return self.mockTaskRunner;
171 }
172 
173 - (void)updateViewportMetricsWithInset:(CGFloat)inset {
174  self.currentInset = inset;
175  if (self.updateViewportMetricsBlock) {
176  self.updateViewportMetricsBlock(inset);
177  }
178 }
179 
180 - (CGFloat)physicalViewInsetBottom {
181  return self.currentInset;
182 }
183 
184 - (UIView*)view {
185  return self.mockView;
186 }
187 
188 - (FlutterEngine*)engine {
189  return self.mockEngine;
190 }
191 
192 - (UIScreen*)flutterScreenIfViewLoaded {
193  return self.mockScreen;
194 }
195 
196 - (BOOL)isPadInSlideOverOrStageManagerMode {
197  return self.mockIsPadInSlideOverOrStageManagerMode;
198 }
199 
200 - (CGRect)convertViewRectToScreen:(CGRect)rect {
201  return self.mockConvertedViewRect;
202 }
203 
204 @end
205 
206 /// A view controller that allows headless execution in the engine it creates.
208 @end
209 
212  return YES;
213 }
214 @end
215 
216 /// Sometimes we have to use a custom mock to avoid retain cycles in OCMock.
217 /// Used for testing low memory notification.
219 
220 @property(nonatomic, strong) FlutterBasicMessageChannel* lifecycleChannel;
221 @property(nonatomic, strong) FlutterBasicMessageChannel* keyEventChannel;
222 @property(nonatomic, weak) FlutterViewController* viewController;
223 @property(nonatomic, strong) FlutterTextInputPlugin* textInputPlugin;
224 @property(nonatomic, assign) BOOL didCallNotifyLowMemory;
225 @property(nonatomic, strong) FlutterFMLTaskRunner* uiTaskRunner;
226 
228 
229 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
230  callback:(nullable FlutterKeyEventCallback)callback
231  userData:(nullable void*)userData;
232 
233 - (nullable FlutterFMLTaskRunner*)uiTaskRunner;
234 - (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint;
235 - (void)attachView;
236 @end
237 
238 @implementation FlutterEnginePartialMock
239 
240 // Synthesize properties declared readonly in FlutterEngine.
241 @synthesize lifecycleChannel;
242 @synthesize keyEventChannel;
243 @synthesize viewController;
244 @synthesize textInputPlugin;
245 
246 - (void)notifyLowMemory {
247  _didCallNotifyLowMemory = YES;
248 }
249 
250 - (instancetype)init {
251  if (self = [super init]) {
252  fml::MessageLoop::EnsureInitializedForCurrentThread();
253  _uiTaskRunner = [[FlutterFMLTaskRunner alloc]
254  initWithTaskRunner:fml::MessageLoop::GetCurrent().GetTaskRunner()];
255  }
256  return self;
257 }
258 
259 - (nullable FlutterFMLTaskRunner*)uiTaskRunner {
260  return _uiTaskRunner;
261 }
262 
263 - (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint {
264  return YES;
265 }
266 
267 - (void)attachView {
268  // Do nothing to avoid crash when platformView is nil on bots.
269 }
270 
271 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
272  callback:(FlutterKeyEventCallback)callback
273  userData:(void*)userData API_AVAILABLE(ios(9.0)) {
274  if (callback == nil) {
275  return;
276  }
277  // NSAssert(callback != nullptr, @"Invalid callback");
278  // Response is async, so we have to post it to the run loop instead of calling
279  // it directly.
280  CFRunLoopPerformBlock(CFRunLoopGetCurrent(), fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode,
281  ^() {
282  callback(true, userData);
283  });
284 }
285 @end
286 
287 @interface FlutterEngine ()
288 - (BOOL)createShell:(NSString*)entrypoint
289  libraryURI:(NSString*)libraryURI
290  initialRoute:(NSString*)initialRoute;
291 - (void)dispatchPointerDataPacket:(std::unique_ptr<flutter::PointerDataPacket>)packet;
292 - (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics;
293 - (void)attachView;
294 @end
295 
297 - (void)notifyLowMemory;
298 @end
299 
300 extern NSNotificationName const FlutterViewControllerWillDealloc;
301 
302 /// A simple mock class for FlutterEngine.
303 ///
304 /// OCMClassMock can't be used for FlutterEngine sometimes because OCMock retains arguments to
305 /// invocations and since the init for FlutterViewController calls a method on the
306 /// FlutterEngine it creates a retain cycle that stops us from testing behaviors related to
307 /// deleting FlutterViewControllers.
308 ///
309 /// Used for testing deallocation.
310 @interface MockEngine : NSObject
311 @property(nonatomic, strong) FlutterDartProject* project;
312 @end
313 
314 @implementation MockEngine
316  return nil;
317 }
318 - (void)setViewController:(FlutterViewController*)viewController {
319  // noop
320 }
321 @end
322 
324 @property(nonatomic, retain, readonly)
325  NSMutableArray<id<FlutterKeyPrimaryResponder>>* primaryResponders;
326 @end
327 
329 @property(nonatomic, copy, readonly) FlutterSendKeyEvent sendEvent;
330 @end
331 
333 @property(nonatomic, strong) FlutterEngine* mockLaunchEngine;
334 @end
335 
336 @interface FlutterViewController (Tests) <FlutterKeyboardInsetManagerDelegate>
337 
338 @property(nonatomic, assign) double targetViewInsetBottom;
339 @property(nonatomic, assign) BOOL keyboardAnimationIsShowing;
340 @property(nonatomic, strong) FlutterVSyncClient* keyboardAnimationVSyncClient;
341 @property(nonatomic, strong) FlutterVSyncClient* touchRateCorrectionVSyncClient;
342 @property(nonatomic, assign) BOOL awokenFromNib;
343 
344 - (void)surfaceUpdated:(BOOL)appeared;
345 - (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences;
346 - (void)handlePressEvent:(FlutterUIPressProxy*)press
347  nextAction:(void (^)())next API_AVAILABLE(ios(13.4));
348 - (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer;
352 - (void)onUserSettingsChanged:(NSNotification*)notification;
353 - (void)applicationWillTerminate:(NSNotification*)notification;
354 - (void)goToApplicationLifecycle:(nonnull NSString*)state;
355 
356 - (void)addInternalPlugins;
357 - (flutter::PointerData)generatePointerDataForFake;
358 - (void)dispatchTouches:(NSSet*)touches
359  pointerDataChangeOverride:(flutter::PointerData::Change*)changeOverride
360  event:(UIEvent*)event;
361 - (void)sharedSetupWithProject:(nullable FlutterDartProject*)project
362  initialRoute:(nullable NSString*)initialRoute;
363 - (void)applicationBecameActive:(NSNotification*)notification;
364 - (void)applicationWillResignActive:(NSNotification*)notification;
365 - (void)applicationWillTerminate:(NSNotification*)notification;
366 - (void)applicationDidEnterBackground:(NSNotification*)notification;
367 - (void)applicationWillEnterForeground:(NSNotification*)notification;
368 - (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0));
369 - (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0));
370 - (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0));
371 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0));
372 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0));
373 - (void)onAccessibilityStatusChanged:(NSNotification*)notification;
374 @end
375 
376 @interface FlutterViewControllerTest : XCTestCase
377 @property(nonatomic, strong) id mockEngine;
378 @property(nonatomic, strong) id mockTextInputPlugin;
379 @property(nonatomic, strong) id messageSent;
380 - (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback;
381 @end
382 
383 @interface UITouch ()
384 
385 @property(nonatomic, readwrite) UITouchPhase phase;
386 
387 @end
388 
389 /// A `FlutterEngine` that saves received `PointerData`s instead of forwarding to the shell.
391 - (const std::vector<flutter::PointerData>&)capturedPointerData;
392 @end
393 
394 @implementation PointerDataCapturingEngine {
395  std::vector<flutter::PointerData> _capturedPointerData;
396 }
397 
398 - (void)dispatchPointerDataPacket:(std::unique_ptr<flutter::PointerDataPacket>)packet {
399  for (size_t i = 0; i < packet->GetLength(); i++) {
400  _capturedPointerData.push_back(packet->GetPointerData(i));
401  }
402 }
403 
404 - (const std::vector<flutter::PointerData>&)capturedPointerData {
405  return _capturedPointerData;
406 }
407 
408 @end
409 
410 @implementation FlutterViewControllerTest
411 
412 - (void)setUp {
413  self.mockEngine = OCMClassMock([FlutterEngine class]);
414  self.mockTextInputPlugin = OCMClassMock([FlutterTextInputPlugin class]);
415  OCMStub([self.mockEngine textInputPlugin]).andReturn(self.mockTextInputPlugin);
416  self.messageSent = nil;
417 }
418 
419 - (void)tearDown {
420  // We stop mocking here to avoid retain cycles that stop
421  // FlutterViewControllers from deallocing.
422  [self.mockEngine stopMocking];
423  self.mockEngine = nil;
424  self.mockTextInputPlugin = nil;
425  self.messageSent = nil;
426 }
427 
428 - (id)setUpMockScreen {
429  UIScreen* mockScreen = OCMClassMock([UIScreen class]);
430  // iPhone 14 pixels
431  CGRect screenBounds = CGRectMake(0, 0, 1170, 2532);
432  OCMStub([mockScreen bounds]).andReturn(screenBounds);
433  CGFloat screenScale = 1;
434  OCMStub([mockScreen scale]).andReturn(screenScale);
435 
436  return mockScreen;
437 }
438 
439 - (id)setUpMockView:(FlutterViewController*)viewControllerMock
440  screen:(UIScreen*)screen
441  viewFrame:(CGRect)viewFrame
442  convertedFrame:(CGRect)convertedFrame {
443  OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen);
444  UIView* view = [[UIView alloc] initWithFrame:viewFrame];
445  UIWindow* window = [[UIWindow alloc] initWithFrame:viewFrame];
446  [window addSubview:view];
447 
448  OCMStub([viewControllerMock viewIfLoaded]).andReturn(view);
449  OCMStub([viewControllerMock view]).andReturn(view);
450 
451  return view;
452 }
453 
454 // Verifies that `engineAllowHeadlessExecution` can be set through key-value coding.
455 // The property is readonly and has no setter, so Interface Builder's User Defined Runtime
456 // Attributes set the synthesized instance variable directly via KVC. If we ever declared a getter
457 // or marked the poperty @dynamic, it would break.
458 //
459 // Interface Builder applies runtime attributes during nib loading, before `awakeFromNib` creates
460 // the engine. Only the value in place at that point reaches the engine.
461 - (void)testEngineAllowHeadlessExecutionIsSettableViaKeyValueCoding {
462  FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:nil
463  nibName:nil
464  bundle:nil];
466 
467  // Verify set via key-value coding.
468  [viewController setValue:@YES forKey:@"engineAllowHeadlessExecution"];
470 }
471 
472 // Verifies that an implicitly created engine sets `allowHeadlessExecution` based on the view
473 // controller's `engineAllowHeadlessExecution`.
474 - (void)testImplicitEngineTakesAllowHeadlessExecutionFromViewController {
475  // Verify allowHeadlessExecution is NO by default.
476  FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:nil
477  nibName:nil
478  bundle:nil];
480 
481  // Verify allowHeadlessExecution is YES when the VC allows it.
482  FlutterViewController* headlessViewController =
483  [[FlutterHeadlessAllowedViewController alloc] initWithProject:nil nibName:nil bundle:nil];
484  XCTAssertTrue(headlessViewController.engine.allowHeadlessExecution);
485 }
486 
487 - (void)testStartKeyboardAnimationWillInvokeSetupKeyboardSpringAnimationIfNeeded {
489  [engine runWithEntrypoint:nil];
490  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
491  nibName:nil
492  bundle:nil];
493  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
494  OCMStub([viewControllerMock isViewLoaded]).andReturn(YES);
495  __unused UIView* dummyView = [viewControllerMock view];
496  viewController.keyboardInsetManager.delegate =
497  (id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock;
498 
499  engine.viewController = viewControllerMock;
500 
501  FlutterKeyboardInsetManager* manager =
502  (FlutterKeyboardInsetManager*)viewController.keyboardInsetManager;
503 
504  id viewClassMock = OCMClassMock([UIView class]);
505  OCMStub([viewClassMock animateWithDuration:0.25 animations:[OCMArg any] completion:[OCMArg any]])
506  .andDo(^(NSInvocation* invocation) {
507  // -getArgument:atIndex: does a raw memcpy without retaining; declare the block locals
508  // __unsafe_unretained so ARC doesn't over-release the invocation-owned blocks.
509  __unsafe_unretained void (^animations)(void);
510  [invocation getArgument:&animations atIndex:3];
511  if (animations) {
512  animations();
513  }
514  __unsafe_unretained void (^completion)(BOOL finished);
515  [invocation getArgument:&completion atIndex:4];
516  if (completion) {
517  completion(YES);
518  }
519  });
520 
521  // Pre-seed a spring animation. startKeyBoardAnimation: must call
522  // setUpKeyboardSpringAnimationIfNeeded:, which clears it back to nil since the UIView animation
523  // is mocked out and therefore produces no real "position" CASpringAnimation to derive one from.
524  manager.targetViewInsetBottom = 320;
525  manager.keyboardSpringAnimation = [[SpringAnimation alloc] initWithStiffness:100
526  damping:10
527  mass:1
528  initialVelocity:0
529  fromValue:0
530  toValue:320];
531  XCTAssertNotNil(manager.keyboardSpringAnimation);
532 
533  [manager startKeyBoardAnimation:0.25];
534 
535  XCTAssertNil(manager.keyboardSpringAnimation);
536  [viewClassMock stopMocking];
537 }
538 
539 - (void)testSetupKeyboardSpringAnimationIfNeeded {
541  [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
542  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
543  viewController.keyboardInsetManager.delegate =
544  (id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock;
545  UIScreen* screen = [self setUpMockScreen];
546  CGRect viewFrame = screen.bounds;
547  [self setUpMockView:viewControllerMock
548  screen:screen
549  viewFrame:viewFrame
550  convertedFrame:viewFrame];
551 
552  // Null check.
553  [viewController.keyboardInsetManager setUpKeyboardSpringAnimationIfNeeded:nil];
554  SpringAnimation* keyboardSpringAnimation =
555  viewController.keyboardInsetManager.keyboardSpringAnimation;
556  XCTAssertTrue(keyboardSpringAnimation == nil);
557 
558  // CAAnimation that is not a CASpringAnimation.
559  CABasicAnimation* nonSpringAnimation = [CABasicAnimation animation];
560  nonSpringAnimation.duration = 1.0;
561  nonSpringAnimation.fromValue = [NSNumber numberWithFloat:0.0];
562  nonSpringAnimation.toValue = [NSNumber numberWithFloat:1.0];
563  nonSpringAnimation.keyPath = @"position";
564  [viewController.keyboardInsetManager setUpKeyboardSpringAnimationIfNeeded:nonSpringAnimation];
565  keyboardSpringAnimation = viewController.keyboardInsetManager.keyboardSpringAnimation;
566 
567  XCTAssertTrue(keyboardSpringAnimation == nil);
568 
569  // CASpringAnimation.
570  CASpringAnimation* springAnimation = [CASpringAnimation animation];
571  springAnimation.mass = 1.0;
572  springAnimation.stiffness = 100.0;
573  springAnimation.damping = 10.0;
574  springAnimation.keyPath = @"position";
575  springAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
576  springAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)];
577  [viewController.keyboardInsetManager setUpKeyboardSpringAnimationIfNeeded:springAnimation];
578  keyboardSpringAnimation = viewController.keyboardInsetManager.keyboardSpringAnimation;
579  XCTAssertTrue(keyboardSpringAnimation != nil);
580 }
581 
582 /**
583  * @brief Verifies that simultaneous compounding animation calls are handled correctly.
584  *
585  * This captures animation calls made while the keyboard animation is currently animating.
586  * If the new animation is in the same direction as the current animation, the current
587  * animation should continue with an updated targetViewInsetBottom instead of starting a new one.
588  */
589 - (void)testKeyboardAnimationIsShowingAndCompounding {
590  UIScreen* screen = [self setUpMockScreen];
591  CGFloat screenWidth = screen.bounds.size.width;
592  CGFloat screenHeight = screen.bounds.size.height;
593  CGRect viewFrame = screen.bounds;
594 
595  TestKeyboardInsetDelegate* delegate = [[TestKeyboardInsetDelegate alloc] init];
596  delegate.isViewLoaded = YES;
597  delegate.mockScreen = screen;
598  delegate.mockView = [[UIView alloc] init];
599  delegate.mockConvertedViewRect = viewFrame;
600 
602  delegate.mockEngine = engine;
603 
604  // Set the delegate as the engine's current view controller so the notifications are not
605  // treated as coming from a different view (i.e. shouldIgnoreKeyboardNotification: returns NO).
606  engine.viewController = (FlutterViewController*)delegate;
607 
608  FlutterKeyboardInsetManager* manager =
609  [[FlutterKeyboardInsetManager alloc] initWithDelegate:delegate
610  displayLinkManager:FlutterDisplayLinkManager.shared];
611 
612  BOOL isLocal = YES;
613 
614  // Start show keyboard animation.
615  CGRect initialShowKeyboardBeginFrame = CGRectMake(0, screenHeight, screenWidth, 250);
616  CGRect initialShowKeyboardEndFrame = CGRectMake(0, screenHeight - 250, screenWidth, 500);
617  NSNotification* fakeNotification = [NSNotification
618  notificationWithName:UIKeyboardWillChangeFrameNotification
619  object:nil
620  userInfo:@{
621  @"UIKeyboardFrameBeginUserInfoKey" : @(initialShowKeyboardBeginFrame),
622  @"UIKeyboardFrameEndUserInfoKey" : @(initialShowKeyboardEndFrame),
623  @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25),
624  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
625  }];
626  manager.targetViewInsetBottom = 0;
627  [manager handleKeyboardNotification:fakeNotification];
628  BOOL isShowingAnimation1 = manager.keyboardAnimationIsShowing;
629  XCTAssertTrue(isShowingAnimation1);
630 
631  // Start compounding show keyboard animation.
632  CGRect compoundingShowKeyboardBeginFrame = CGRectMake(0, screenHeight - 250, screenWidth, 250);
633  CGRect compoundingShowKeyboardEndFrame = CGRectMake(0, screenHeight - 500, screenWidth, 500);
634  fakeNotification = [NSNotification
635  notificationWithName:UIKeyboardWillChangeFrameNotification
636  object:nil
637  userInfo:@{
638  @"UIKeyboardFrameBeginUserInfoKey" : @(compoundingShowKeyboardBeginFrame),
639  @"UIKeyboardFrameEndUserInfoKey" : @(compoundingShowKeyboardEndFrame),
640  @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25),
641  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
642  }];
643 
644  [manager handleKeyboardNotification:fakeNotification];
645  BOOL isShowingAnimation2 = manager.keyboardAnimationIsShowing;
646  XCTAssertTrue(isShowingAnimation2);
647  XCTAssertTrue(isShowingAnimation1 == isShowingAnimation2);
648 
649  // Start hide keyboard animation.
650  CGRect initialHideKeyboardBeginFrame = CGRectMake(0, screenHeight - 500, screenWidth, 250);
651  CGRect initialHideKeyboardEndFrame = CGRectMake(0, screenHeight - 250, screenWidth, 500);
652  fakeNotification = [NSNotification
653  notificationWithName:UIKeyboardWillChangeFrameNotification
654  object:nil
655  userInfo:@{
656  @"UIKeyboardFrameBeginUserInfoKey" : @(initialHideKeyboardBeginFrame),
657  @"UIKeyboardFrameEndUserInfoKey" : @(initialHideKeyboardEndFrame),
658  @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25),
659  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
660  }];
661 
662  [manager handleKeyboardNotification:fakeNotification];
663  BOOL isShowingAnimation3 = manager.keyboardAnimationIsShowing;
664  XCTAssertFalse(isShowingAnimation3);
665  XCTAssertTrue(isShowingAnimation2 != isShowingAnimation3);
666 
667  // Start compounding hide keyboard animation.
668  CGRect compoundingHideKeyboardBeginFrame = CGRectMake(0, screenHeight - 250, screenWidth, 250);
669  CGRect compoundingHideKeyboardEndFrame = CGRectMake(0, screenHeight, screenWidth, 500);
670  fakeNotification = [NSNotification
671  notificationWithName:UIKeyboardWillChangeFrameNotification
672  object:nil
673  userInfo:@{
674  @"UIKeyboardFrameBeginUserInfoKey" : @(compoundingHideKeyboardBeginFrame),
675  @"UIKeyboardFrameEndUserInfoKey" : @(compoundingHideKeyboardEndFrame),
676  @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25),
677  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
678  }];
679 
680  [manager handleKeyboardNotification:fakeNotification];
681  BOOL isShowingAnimation4 = manager.keyboardAnimationIsShowing;
682  XCTAssertFalse(isShowingAnimation4);
683  XCTAssertTrue(isShowingAnimation3 == isShowingAnimation4);
684 
685  [manager invalidate];
686 }
687 
688 - (void)testShouldIgnoreKeyboardNotification {
690  [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
691  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
692  // Stub the mock engine to return the mock view controller to pass
693  // isKeyboardNotificationForDifferentView
694  OCMStub([self.mockEngine viewController]).andReturn(viewControllerMock);
695 
696  // Exercise the real shouldIgnoreKeyboardNotification: implementation.
697  FlutterKeyboardInsetManager* managerMock = [[FlutterKeyboardInsetManager alloc]
698  initWithDelegate:(id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock
699  displayLinkManager:FlutterDisplayLinkManager.shared];
700  viewController.keyboardInsetManager = managerMock;
701 
702  UIScreen* screen = [self setUpMockScreen];
703  CGRect viewFrame = screen.bounds;
704  [self setUpMockView:viewControllerMock
705  screen:screen
706  viewFrame:viewFrame
707  convertedFrame:viewFrame];
708 
709  CGFloat screenWidth = screen.bounds.size.width;
710  CGFloat screenHeight = screen.bounds.size.height;
711  CGRect emptyKeyboard = CGRectZero;
712  CGRect zeroHeightKeyboard = CGRectMake(0, 0, screenWidth, 0);
713  CGRect validKeyboardEndFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320);
714  BOOL isLocal = NO;
715 
716  // Hide notification, valid keyboard
717  NSNotification* notification =
718  [NSNotification notificationWithName:UIKeyboardWillHideNotification
719  object:nil
720  userInfo:@{
721  @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame),
722  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
723  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
724  }];
725 
726  BOOL shouldIgnore = [managerMock shouldIgnoreKeyboardNotification:notification];
727  XCTAssertTrue(shouldIgnore == NO);
728 
729  // All zero keyboard
730  isLocal = YES;
731  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
732  object:nil
733  userInfo:@{
734  @"UIKeyboardFrameEndUserInfoKey" : @(emptyKeyboard),
735  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
736  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
737  }];
738  shouldIgnore = [managerMock shouldIgnoreKeyboardNotification:notification];
739  XCTAssertTrue(shouldIgnore == YES);
740 
741  // Zero height keyboard
742  isLocal = NO;
743  notification =
744  [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
745  object:nil
746  userInfo:@{
747  @"UIKeyboardFrameEndUserInfoKey" : @(zeroHeightKeyboard),
748  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
749  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
750  }];
751  shouldIgnore = [managerMock shouldIgnoreKeyboardNotification:notification];
752  XCTAssertTrue(shouldIgnore == NO);
753 
754  // Valid keyboard, triggered from another app
755  isLocal = NO;
756  notification =
757  [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
758  object:nil
759  userInfo:@{
760  @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame),
761  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
762  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
763  }];
764  shouldIgnore = [managerMock shouldIgnoreKeyboardNotification:notification];
765  XCTAssertTrue(shouldIgnore == YES);
766 
767  // Valid keyboard
768  isLocal = YES;
769  notification =
770  [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
771  object:nil
772  userInfo:@{
773  @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame),
774  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
775  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
776  }];
777  shouldIgnore = [managerMock shouldIgnoreKeyboardNotification:notification];
778  XCTAssertTrue(shouldIgnore == NO);
779 
780  [(id)viewControllerMock stopMocking];
781 }
782 
783 - (void)testKeyboardAnimationWillNotCrashWhenEngineDestroyed {
784  FlutterEngine* engine = [[FlutterEngine alloc] init];
785  [engine runWithEntrypoint:nil];
786  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
787  nibName:nil
788  bundle:nil];
789  [viewController.keyboardInsetManager
790  setUpKeyboardAnimationVsyncClient:^(NSTimeInterval targetTime){
791  }];
792  [engine destroyContext];
793 }
794 
795 - (void)testKeyboardAnimationFirstVsyncCallbackCalculatesSafeInset {
797  [engine runWithEntrypoint:nil];
798  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
799  nibName:nil
800  bundle:nil];
801  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
802  OCMStub([viewControllerMock isViewLoaded]).andReturn(YES);
803  __unused UIView* dummyView = [viewControllerMock view];
804  viewController.keyboardInsetManager.delegate =
805  (id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock;
806 
807  engine.viewController = viewControllerMock;
808 
809  XCTestExpectation* expectation = [self expectationWithDescription:@"metrics updated"];
810  // Stub updateViewportMetricsWithInset: to capture the inset value passed.
811  __block CGFloat capturedInset = -1.0;
812  __block BOOL fulfilled = NO;
813  OCMStub([viewControllerMock updateViewportMetricsWithInset:0])
814  .ignoringNonObjectArgs()
815  .andDo(^(NSInvocation* invocation) {
816  [invocation getArgument:&capturedInset atIndex:2];
817  if (!fulfilled) {
818  fulfilled = YES;
819  // Prevent the instant UIView animation completion block from overriding the captured
820  // vsync inset.
821  [viewController.keyboardInsetManager invalidateKeyboardAnimationVSyncClient];
822  [expectation fulfill];
823  }
824  });
825 
826  // Configure keyboard spring animation.
827  CASpringAnimation* springAnimation = [CASpringAnimation animation];
828  springAnimation.mass = 1.0;
829  springAnimation.stiffness = 100.0;
830  springAnimation.damping = 10.0;
831  springAnimation.keyPath = @"position";
832 
833  viewController.keyboardInsetManager.targetViewInsetBottom = 300.0;
834 
835  // Start the keyboard animation.
836  [viewController.keyboardInsetManager startKeyBoardAnimation:0.25];
837  [viewController.keyboardInsetManager setUpKeyboardSpringAnimationIfNeeded:springAnimation];
838 
839  // Simulate the first vsync callback passing the initial CADisplayLink directly.
840  FlutterVSyncClient* client = viewController.keyboardInsetManager.keyboardAnimationVSyncClient;
841  [client onDisplayLink:client.displayLink];
842 
843  // Wait for task runner to execute callback on main queue.
844  [self waitForExpectationsWithTimeout:5.0 handler:nil];
845 
846  // The captured inset must be a finite, non-NaN, non-negative value (close to start of animation).
847  XCTAssertFalse(isnan(capturedInset));
848  XCTAssertFalse(isinf(capturedInset));
849  XCTAssertGreaterThanOrEqual(capturedInset, 0.0);
850  XCTAssertLessThan(capturedInset, 300.0);
851 }
852 
853 - (void)testKeyboardAnimationCallbackIsDeliveredAsynchronously {
854  // FlutterEnginePartialMock.uiTaskRunner runs on the current (test) message loop, so the vsync
855  // client's display-link registration and invalidation happen deterministically on this thread.
857  [engine runWithEntrypoint:nil];
858  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
859  nibName:nil
860  bundle:nil];
861 
862  id mockCADisplayLink = OCMClassMock([CADisplayLink class]);
863  OCMStub(
864  ClassMethod([mockCADisplayLink displayLinkWithTarget:[OCMArg any]
865  selector:sel_registerName("onDisplayLink:")]));
866 
867  XCTestExpectation* expectation = [self expectationWithDescription:@"keyboard animation callback"];
868  __block BOOL callbackExecuted = NO;
869  [viewController.keyboardInsetManager
870  setUpKeyboardAnimationVsyncClient:^(NSTimeInterval targetTime) {
871  callbackExecuted = YES;
872  [expectation fulfill];
873  }];
874 
875  FlutterVSyncClient* client = viewController.keyboardInsetManager.keyboardAnimationVSyncClient;
876  [client onDisplayLink:client.displayLink];
877 
878  // The callback is dispatched to the main queue, so it must not have run synchronously within
879  // -onDisplayLink:.
880  XCTAssertFalse(callbackExecuted);
881 
882  // Spinning the run loop drains the main queue, at which point the callback runs.
883  [self waitForExpectationsWithTimeout:5.0 handler:nil];
884  XCTAssertTrue(callbackExecuted);
885  [mockCADisplayLink stopMocking];
886 }
887 
888 - (void)testCalculateKeyboardAttachMode {
890  [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
891 
892  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
893  viewController.keyboardInsetManager.delegate =
894  (id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock;
895  UIScreen* screen = [self setUpMockScreen];
896  CGRect viewFrame = screen.bounds;
897  [self setUpMockView:viewControllerMock
898  screen:screen
899  viewFrame:viewFrame
900  convertedFrame:viewFrame];
901 
902  CGFloat screenWidth = screen.bounds.size.width;
903  CGFloat screenHeight = screen.bounds.size.height;
904 
905  // hide notification
906  CGRect keyboardFrame = CGRectZero;
907  NSNotification* notification =
908  [NSNotification notificationWithName:UIKeyboardWillHideNotification
909  object:nil
910  userInfo:@{
911  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
912  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
913  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
914  }];
915  FlutterKeyboardMode keyboardMode =
916  [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
917  XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden);
918 
919  // all zeros
920  keyboardFrame = CGRectZero;
921  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
922  object:nil
923  userInfo:@{
924  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
925  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
926  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
927  }];
928  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
929  XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating);
930 
931  // 0 height
932  keyboardFrame = CGRectMake(0, 0, screenWidth, 0);
933  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
934  object:nil
935  userInfo:@{
936  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
937  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
938  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
939  }];
940  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
941  XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden);
942 
943  // floating
944  keyboardFrame = CGRectMake(0, 0, 320, 320);
945  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
946  object:nil
947  userInfo:@{
948  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
949  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
950  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
951  }];
952  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
953  XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating);
954 
955  // undocked
956  keyboardFrame = CGRectMake(0, 0, screenWidth, 320);
957  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
958  object:nil
959  userInfo:@{
960  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
961  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
962  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
963  }];
964  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
965  XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating);
966 
967  // docked
968  keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320);
969  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
970  object:nil
971  userInfo:@{
972  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
973  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
974  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
975  }];
976  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
977  XCTAssertTrue(keyboardMode == FlutterKeyboardModeDocked);
978 
979  // docked - rounded values
980  CGFloat longDecimalHeight = 320.666666666666666;
981  keyboardFrame = CGRectMake(0, screenHeight - longDecimalHeight, screenWidth, longDecimalHeight);
982  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
983  object:nil
984  userInfo:@{
985  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
986  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
987  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
988  }];
989  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
990  XCTAssertTrue(keyboardMode == FlutterKeyboardModeDocked);
991 
992  // hidden - rounded values
993  keyboardFrame = CGRectMake(0, screenHeight - .0000001, screenWidth, longDecimalHeight);
994  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
995  object:nil
996  userInfo:@{
997  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
998  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
999  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
1000  }];
1001  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
1002  XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden);
1003 
1004  // hidden
1005  keyboardFrame = CGRectMake(0, screenHeight, screenWidth, 320);
1006  notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification
1007  object:nil
1008  userInfo:@{
1009  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
1010  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
1011  @"UIKeyboardIsLocalUserInfoKey" : @(YES)
1012  }];
1013  keyboardMode = [viewController.keyboardInsetManager calculateKeyboardAttachMode:notification];
1014  XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden);
1015 }
1016 
1017 - (void)testCalculateMultitaskingAdjustment {
1018  UIScreen* screen = [UIScreen mainScreen];
1019  CGFloat screenWidth = screen.bounds.size.width;
1020  CGFloat screenHeight = screen.bounds.size.height;
1021  CGRect screenRect = screen.bounds;
1022  CGRect convertedViewFrame = CGRectMake(0, 0, 320, screenHeight - 20);
1023  CGRect keyboardFrame = CGRectMake(20, screenHeight - 320, screenWidth, 300);
1024 
1025  TestKeyboardInsetDelegate* delegate = [[TestKeyboardInsetDelegate alloc] init];
1026  delegate.mockScreen = screen;
1027  delegate.isViewLoaded = YES;
1028 
1030  delegate.mockConvertedViewRect = convertedViewFrame;
1031 
1032  FlutterKeyboardInsetManager* manager =
1033  [[FlutterKeyboardInsetManager alloc] initWithDelegate:delegate
1034  displayLinkManager:FlutterDisplayLinkManager.shared];
1035 
1036  CGFloat adjustment = [manager calculateMultitaskingAdjustment:screenRect
1037  keyboardFrame:keyboardFrame];
1038  XCTAssertTrue(adjustment == 20);
1039 }
1040 
1041 - (void)testCalculateKeyboardInset {
1042  UIScreen* screen = [UIScreen mainScreen];
1043  CGFloat screenWidth = screen.bounds.size.width;
1044  CGFloat screenHeight = screen.bounds.size.height;
1045  CGRect convertedViewFrame = CGRectMake(0, 0, 320, screenHeight - 20);
1046  CGRect keyboardFrame = CGRectMake(20, screenHeight - 320, screenWidth, 300);
1047 
1048  TestKeyboardInsetDelegate* delegate = [[TestKeyboardInsetDelegate alloc] init];
1049  delegate.isViewLoaded = YES;
1050  delegate.mockScreen = screen;
1051 
1052  delegate.mockConvertedViewRect = convertedViewFrame;
1053 
1054  FlutterKeyboardInsetManager* manager =
1055  [[FlutterKeyboardInsetManager alloc] initWithDelegate:delegate
1056  displayLinkManager:FlutterDisplayLinkManager.shared];
1057 
1058  CGFloat inset = [manager calculateKeyboardInset:keyboardFrame
1059  keyboardMode:FlutterKeyboardModeDocked];
1060  XCTAssertTrue(inset == 300 * screen.scale);
1061 }
1062 
1063 - (void)testHandleKeyboardNotification {
1064  UIScreen* screen = [self setUpMockScreen];
1065  CGFloat screenWidth = screen.bounds.size.width;
1066  CGFloat screenHeight = screen.bounds.size.height;
1067  CGRect keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320);
1068  CGRect viewFrame = screen.bounds;
1069  BOOL isLocal = YES;
1070  NSNotification* notification = [NSNotification
1071  notificationWithName:UIKeyboardWillShowNotification
1072  object:nil
1073  userInfo:@{
1074  @"UIKeyboardFrameEndUserInfoKey" : [NSValue valueWithCGRect:keyboardFrame],
1075  @"UIKeyboardAnimationDurationUserInfoKey" : @0.25,
1076  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
1077  }];
1078 
1079  TestKeyboardInsetDelegate* delegate = [[TestKeyboardInsetDelegate alloc] init];
1080  delegate.isViewLoaded = YES;
1081  delegate.mockScreen = screen;
1082 
1083  // view() is non-optional in the delegate protocol; provide a real view so the real
1084  // startKeyBoardAnimation: can add its animation view to the hierarchy.
1085  delegate.mockView = [[UIView alloc] init];
1086  delegate.mockConvertedViewRect = viewFrame;
1087 
1089  delegate.mockEngine = engine;
1090  engine.viewController = (FlutterViewController*)delegate;
1091 
1092  FlutterKeyboardInsetManager* manager =
1093  [[FlutterKeyboardInsetManager alloc] initWithDelegate:delegate
1094  displayLinkManager:FlutterDisplayLinkManager.shared];
1095  manager.targetViewInsetBottom = 0;
1096 
1097  [manager handleKeyboardNotification:notification];
1098 
1099  // Verify the docked keyboard produces an inset.
1100  XCTAssertTrue(manager.targetViewInsetBottom == 320 * screen.scale);
1101 
1102  // Verify handleKeyboardNotification: kicks off the animation, which sets up the vsync client.
1103  XCTAssertNotNil(manager.keyboardAnimationVSyncClient);
1104 
1105  [manager invalidate];
1106 }
1107 
1108 - (void)testEnsureBottomInsetIsZeroWhenKeyboardDismissed {
1110  [engine runWithEntrypoint:nil];
1111  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
1112  nibName:nil
1113  bundle:nil];
1114 
1115  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
1116  viewController.keyboardInsetManager.delegate =
1117  (id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock;
1118 
1119  engine.viewController = viewControllerMock;
1120 
1121  CGRect keyboardFrame = CGRectZero;
1122  BOOL isLocal = YES;
1123  NSNotification* fakeNotification =
1124  [NSNotification notificationWithName:UIKeyboardWillHideNotification
1125  object:nil
1126  userInfo:@{
1127  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
1128  @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25),
1129  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
1130  }];
1131 
1132  viewController.keyboardInsetManager.targetViewInsetBottom = 10;
1133  [viewController.keyboardInsetManager handleKeyboardNotification:fakeNotification];
1134  XCTAssertTrue(viewController.keyboardInsetManager.targetViewInsetBottom == 0);
1135 }
1136 
1137 - (void)testStopKeyBoardAnimationWhenReceivedWillHideNotificationAfterWillShowNotification {
1138  // see: https://github.com/flutter/flutter/issues/112281
1139 
1141  [engine runWithEntrypoint:nil];
1142  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
1143  nibName:nil
1144  bundle:nil];
1145  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
1146  viewController.keyboardInsetManager.delegate =
1147  (id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock;
1148 
1149  engine.viewController = viewControllerMock;
1150  OCMStub([viewControllerMock isViewLoaded]).andReturn(YES);
1151  __unused UIView* dummyView2 = [viewControllerMock view];
1152 
1153  UIScreen* screen = [self setUpMockScreen];
1154  OCMStub([screen scale]).andReturn(1.0);
1155  OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen);
1156  CGRect viewFrame = screen.bounds;
1157  [self setUpMockView:viewControllerMock
1158  screen:screen
1159  viewFrame:viewFrame
1160  convertedFrame:viewFrame];
1161  viewController.keyboardInsetManager.targetViewInsetBottom = 0;
1162 
1163  CGFloat screenWidth = screen.bounds.size.width;
1164  CGFloat screenHeight = screen.bounds.size.height;
1165  CGRect keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320);
1166  BOOL isLocal = YES;
1167 
1168  // Receive will show notification
1169  NSNotification* fakeShowNotification =
1170  [NSNotification notificationWithName:UIKeyboardWillShowNotification
1171  object:nil
1172  userInfo:@{
1173  UIKeyboardFrameEndUserInfoKey : @(keyboardFrame),
1174  UIKeyboardAnimationDurationUserInfoKey : @0.25,
1175  UIKeyboardIsLocalUserInfoKey : @(isLocal)
1176  }];
1177  [viewController.keyboardInsetManager handleKeyboardNotification:fakeShowNotification];
1178  XCTAssertEqual(viewController.keyboardInsetManager.targetViewInsetBottom, 320 * screen.scale);
1179 
1180  // Receive will hide notification
1181  NSNotification* fakeHideNotification =
1182  [NSNotification notificationWithName:UIKeyboardWillHideNotification
1183  object:nil
1184  userInfo:@{
1185  @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame),
1186  @"UIKeyboardAnimationDurationUserInfoKey" : @(0.0),
1187  @"UIKeyboardIsLocalUserInfoKey" : @(isLocal)
1188  }];
1189  [viewController.keyboardInsetManager handleKeyboardNotification:fakeHideNotification];
1190  XCTAssertEqual(viewController.keyboardInsetManager.targetViewInsetBottom, 0);
1191 
1192  // Check if the keyboard animation is stopped.
1193  XCTAssertNil([viewController.keyboardInsetManager keyboardAnimationView]);
1194  XCTAssertNil([viewController.keyboardInsetManager keyboardSpringAnimation]);
1195 }
1196 
1197 - (void)testEnsureViewportMetricsWillInvokeAndDisplayLinkWillInvalidateInViewDidDisappear {
1199  [engine runWithEntrypoint:nil];
1200  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
1201  nibName:nil
1202  bundle:nil];
1203  id viewControllerMock = OCMPartialMock(viewController);
1204  viewController.keyboardInsetManager.delegate =
1205  (id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock;
1206 
1208  initWithDelegate:(id<FlutterKeyboardInsetManagerDelegate>)viewControllerMock];
1209  viewController.keyboardInsetManager = managerMock;
1210 
1211  [viewControllerMock viewDidDisappear:YES];
1212 
1213  XCTAssertTrue(managerMock.didCallEnsureViewportMetricsIsCorrect);
1214  XCTAssertTrue(managerMock.didCallInvalidateKeyboardAnimationVSyncClient);
1215 }
1216 
1217 - (void)testViewDidDisappearDoesntPauseEngineWhenNotTheViewController {
1218  id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1220  mockEngine.lifecycleChannel = lifecycleChannel;
1221  FlutterViewController* viewControllerA =
1222  [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
1223  FlutterViewController* viewControllerB =
1224  [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
1225  id viewControllerMock = OCMPartialMock(viewControllerA);
1226  OCMStub([viewControllerMock surfaceUpdated:NO]);
1227  mockEngine.viewController = viewControllerB;
1228  [viewControllerA viewDidDisappear:NO];
1229  OCMReject([lifecycleChannel sendMessage:@"AppLifecycleState.paused"]);
1230  OCMReject([viewControllerMock surfaceUpdated:[OCMArg any]]);
1231 }
1232 
1233 - (void)testAppWillTerminateViewDidDestroyTheEngine {
1234  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1235  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1236  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1237  nibName:nil
1238  bundle:nil];
1239  id viewControllerMock = OCMPartialMock(viewController);
1240  OCMStub([viewControllerMock goToApplicationLifecycle:@"AppLifecycleState.detached"]);
1241  OCMStub([mockEngine destroyContext]);
1242  [viewController applicationWillTerminate:nil];
1243  OCMVerify([viewControllerMock goToApplicationLifecycle:@"AppLifecycleState.detached"]);
1244  OCMVerify([mockEngine destroyContext]);
1245 }
1246 
1247 - (void)testViewDidDisappearDoesPauseEngineWhenIsTheViewController {
1248  id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1250  mockEngine.lifecycleChannel = lifecycleChannel;
1251  __weak FlutterViewController* weakViewController;
1252  @autoreleasepool {
1253  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1254  nibName:nil
1255  bundle:nil];
1256  weakViewController = viewController;
1257  id viewControllerMock = OCMPartialMock(viewController);
1258  OCMStub([viewControllerMock surfaceUpdated:NO]);
1259  [viewController viewDidDisappear:NO];
1260  OCMVerify([lifecycleChannel sendMessage:@"AppLifecycleState.paused"]);
1261  OCMVerify([viewControllerMock surfaceUpdated:NO]);
1262  }
1263  XCTAssertNil(weakViewController);
1264 }
1265 
1266 - (void)
1267  testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewWillAppear {
1268  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1269  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1270  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1271  nibName:nil
1272  bundle:nil];
1273  [viewController viewWillAppear:YES];
1274  OCMVerify([viewController onUserSettingsChanged:nil]);
1275 }
1276 
1277 - (void)
1278  testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewWillAppear {
1279  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1280  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1281  FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine
1282  nibName:nil
1283  bundle:nil];
1284  mockEngine.viewController = nil;
1285  FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine
1286  nibName:nil
1287  bundle:nil];
1288  mockEngine.viewController = nil;
1289  mockEngine.viewController = viewControllerB;
1290  [viewControllerA viewWillAppear:YES];
1291  OCMVerify(never(), [viewControllerA onUserSettingsChanged:nil]);
1292 }
1293 
1294 - (void)
1295  testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewDidAppear {
1296  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1297  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1298  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1299  nibName:nil
1300  bundle:nil];
1301  [viewController viewDidAppear:YES];
1302  OCMVerify([viewController onUserSettingsChanged:nil]);
1303 }
1304 
1305 - (void)
1306  testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewDidAppear {
1307  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1308  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1309  FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine
1310  nibName:nil
1311  bundle:nil];
1312  mockEngine.viewController = nil;
1313  FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine
1314  nibName:nil
1315  bundle:nil];
1316  mockEngine.viewController = nil;
1317  mockEngine.viewController = viewControllerB;
1318  [viewControllerA viewDidAppear:YES];
1319  OCMVerify(never(), [viewControllerA onUserSettingsChanged:nil]);
1320 }
1321 
1322 - (void)
1323  testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewWillDisappear {
1324  id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1326  mockEngine.lifecycleChannel = lifecycleChannel;
1327  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1328  nibName:nil
1329  bundle:nil];
1331  [viewController viewWillDisappear:NO];
1332  OCMVerify([lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]);
1333 }
1334 
1335 - (void)
1336  testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewWillDisappear {
1337  id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1339  mockEngine.lifecycleChannel = lifecycleChannel;
1340  FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine
1341  nibName:nil
1342  bundle:nil];
1343  FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine
1344  nibName:nil
1345  bundle:nil];
1346  mockEngine.viewController = viewControllerB;
1347  [viewControllerA viewDidDisappear:NO];
1348  OCMReject([lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]);
1349 }
1350 
1351 - (void)testUpdateViewportMetricsIfNeeded_DoesntInvokeEngineWhenNotTheViewController {
1352  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1353  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1354  FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine
1355  nibName:nil
1356  bundle:nil];
1357  mockEngine.viewController = nil;
1358  FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine
1359  nibName:nil
1360  bundle:nil];
1361  mockEngine.viewController = viewControllerB;
1362  [viewControllerA updateViewportMetricsIfNeeded];
1363  flutter::ViewportMetrics viewportMetrics;
1364  OCMVerify(never(), [mockEngine updateViewportMetrics:viewportMetrics]);
1365 }
1366 
1367 - (void)testUpdateViewportMetricsIfNeeded_DoesInvokeEngineWhenIsTheViewController {
1368  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1369  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1370  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1371  nibName:nil
1372  bundle:nil];
1374  flutter::ViewportMetrics viewportMetrics;
1375  OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs();
1376  [viewController updateViewportMetricsIfNeeded];
1377  OCMVerifyAll(mockEngine);
1378 }
1379 
1380 - (void)testUpdatedViewportMetricsDoesResizeFlutterViewWhenAutoResizable {
1381  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1382  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1383 
1384  FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:mockEngine
1385  nibName:nil
1386  bundle:nil];
1387  id mockVC = OCMPartialMock(realVC);
1388  mockEngine.viewController = mockVC;
1389 
1390  OCMExpect([mockVC updateAutoResizeConstraints]);
1391 
1392  [mockVC setAutoResizable:YES];
1393 
1394  [mockVC viewDidLayoutSubviews];
1395 
1396  OCMVerifyAll(mockVC);
1397 }
1398 
1399 - (void)testUpdatedViewportMetricsDoesNotResizeFlutterViewWhenNotAutoResizable {
1400  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1401  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1402 
1403  FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:mockEngine
1404  nibName:nil
1405  bundle:nil];
1406  id mockVC = OCMPartialMock(realVC);
1407  mockEngine.viewController = mockVC;
1408 
1409  OCMReject([mockVC updateAutoResizeConstraints]);
1410 
1411  [mockVC setAutoResizable:NO];
1412 
1413  [mockVC viewDidLayoutSubviews];
1414 
1415  OCMVerifyAll(mockVC);
1416 }
1417 
1418 - (void)testViewDidLayoutSubviewsUpdatesEngineDisplays {
1419  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1420  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1421  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1422  nibName:nil
1423  bundle:nil];
1424 
1425  // Layout is when the view may have moved to a different screen (e.g. between the inner and outer
1426  // displays of a device with multiple built-in displays).
1427  OCMExpect([mockEngine updateDisplays]);
1428  [viewController viewDidLayoutSubviews];
1429  OCMVerifyAll((id)mockEngine);
1430 }
1431 
1432 - (void)testViewDidLayoutSubviewsDoesNotUpdateEngineDisplaysWhenNotEngineViewController {
1433  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1434  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1435  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1436  nibName:nil
1437  bundle:nil];
1438  mockEngine.viewController = nil;
1439 
1440  OCMReject([mockEngine updateDisplays]);
1441  [viewController viewDidLayoutSubviews];
1442  OCMVerifyAll((id)mockEngine);
1443 }
1444 
1445 - (void)testUpdateViewportMetricsIfNeeded_DoesNotInvokeEngineWhenShouldBeIgnoredDuringRotation {
1446  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1447  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1448  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1449  nibName:nil
1450  bundle:nil];
1451  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
1452  UIScreen* screen = [self setUpMockScreen];
1453  OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen);
1455 
1456  id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator));
1457  OCMStub([mockCoordinator transitionDuration]).andReturn(0.5);
1458 
1459  // Mimic the device rotation.
1460  [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator];
1461  // Should not trigger the engine call when during rotation.
1462  [viewController updateViewportMetricsIfNeeded];
1463 
1464  OCMVerify(never(), [mockEngine updateViewportMetrics:flutter::ViewportMetrics()]);
1465 }
1466 
1467 - (void)testViewWillTransitionToSize_DoesDelayEngineCallIfNonZeroDuration {
1468  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1469  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1470  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1471  nibName:nil
1472  bundle:nil];
1473  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
1474  UIScreen* screen = [self setUpMockScreen];
1475  OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen);
1477 
1478  // Mimic the device rotation with non-zero transition duration.
1479  NSTimeInterval transitionDuration = 0.5;
1480  id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator));
1481  OCMStub([mockCoordinator transitionDuration]).andReturn(transitionDuration);
1482 
1483  flutter::ViewportMetrics viewportMetrics;
1484  OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs();
1485 
1486  [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator];
1487  // Should not immediately call the engine (this request should be ignored).
1488  [viewController updateViewportMetricsIfNeeded];
1489  OCMVerify(never(), [mockEngine updateViewportMetrics:flutter::ViewportMetrics()]);
1490 
1491  // Should delay the engine call for half of the transition duration.
1492  // Wait for additional transitionDuration to allow updateViewportMetrics calls if any.
1493  XCTWaiterResult result = [XCTWaiter
1494  waitForExpectations:@[ [self expectationWithDescription:@"Waiting for rotation duration"] ]
1495  timeout:transitionDuration];
1496  XCTAssertEqual(result, XCTWaiterResultTimedOut);
1497 
1498  OCMVerifyAll(mockEngine);
1499 }
1500 
1501 - (void)testViewWillTransitionToSize_DoesNotDelayEngineCallIfZeroDuration {
1502  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1503  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1504  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1505  nibName:nil
1506  bundle:nil];
1507  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
1508  UIScreen* screen = [self setUpMockScreen];
1509  OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen);
1511 
1512  // Mimic the device rotation with zero transition duration.
1513  id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator));
1514  OCMStub([mockCoordinator transitionDuration]).andReturn(0);
1515 
1516  flutter::ViewportMetrics viewportMetrics;
1517  OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs();
1518 
1519  // Should immediately trigger the engine call, without delay.
1520  [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator];
1521  [viewController updateViewportMetricsIfNeeded];
1522 
1523  OCMVerifyAll(mockEngine);
1524 }
1525 
1526 - (void)testViewDidLoadDoesntInvokeEngineWhenNotTheViewController {
1527  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1528  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1529  FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine
1530  nibName:nil
1531  bundle:nil];
1532  mockEngine.viewController = nil;
1533  FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine
1534  nibName:nil
1535  bundle:nil];
1536  mockEngine.viewController = viewControllerB;
1537  UIView* view = viewControllerA.view;
1538  XCTAssertNotNil(view);
1539  OCMVerify(never(), [mockEngine attachView]);
1540 }
1541 
1542 - (void)testViewDidLoadDoesInvokeEngineWhenIsTheViewController {
1543  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1544  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1545  mockEngine.viewController = nil;
1546  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1547  nibName:nil
1548  bundle:nil];
1550  UIView* view = viewController.view;
1551  XCTAssertNotNil(view);
1552  OCMVerify(times(1), [mockEngine attachView]);
1553 }
1554 
1555 - (void)testViewDidLoadDoesntInvokeEngineAttachViewWhenEngineNeedsLaunch {
1556  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1557  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1558  mockEngine.viewController = nil;
1559  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1560  nibName:nil
1561  bundle:nil];
1562  // sharedSetupWithProject sets the engine needs to be launched.
1563  [viewController sharedSetupWithProject:nil initialRoute:nil];
1565  UIView* view = viewController.view;
1566  XCTAssertNotNil(view);
1567  OCMVerify(never(), [mockEngine attachView]);
1568 }
1569 
1570 - (void)testSplashScreenViewRemoveNotCrash {
1571  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:nil];
1572  [engine runWithEntrypoint:nil];
1573  FlutterViewController* flutterViewController =
1574  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
1575  [flutterViewController setSplashScreenView:[[UIView alloc] init]];
1576  [flutterViewController setSplashScreenView:nil];
1577 }
1578 
1579 - (void)testInternalPluginsWeakPtrNotCrash {
1580  FlutterSendKeyEvent sendEvent;
1581  @autoreleasepool {
1582  FlutterViewController* vc = [[FlutterViewController alloc] initWithProject:nil
1583  nibName:nil
1584  bundle:nil];
1585  [vc addInternalPlugins];
1586  FlutterKeyboardManager* keyboardManager = vc.keyboardManager;
1588  [(NSArray<id<FlutterKeyPrimaryResponder>>*)keyboardManager.primaryResponders firstObject];
1589  sendEvent = [keyPrimaryResponder sendEvent];
1590  }
1591 
1592  if (sendEvent) {
1593  sendEvent({}, nil, nil);
1594  }
1595 }
1596 
1597 // Regression test for https://github.com/flutter/engine/pull/32098.
1598 - (void)testInternalPluginsInvokeInViewDidLoad {
1599  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1600  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1601  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1602  nibName:nil
1603  bundle:nil];
1604  UIView* view = viewController.view;
1605  // The implementation in viewDidLoad requires the viewControllers.viewLoaded is true.
1606  // Accessing the view to make sure the view loads in the memory,
1607  // which makes viewControllers.viewLoaded true.
1608  XCTAssertNotNil(view);
1609  [viewController viewDidLoad];
1610  OCMVerify([viewController addInternalPlugins]);
1611 }
1612 
1613 - (void)testBinaryMessenger {
1614  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
1615  nibName:nil
1616  bundle:nil];
1617  XCTAssertNotNil(vc);
1618  id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
1619  OCMStub([self.mockEngine binaryMessenger]).andReturn(messenger);
1620  XCTAssertEqual(vc.binaryMessenger, messenger);
1621  OCMVerify([self.mockEngine binaryMessenger]);
1622 }
1623 
1624 - (void)testViewControllerIsReleased {
1625  __weak FlutterViewController* weakViewController;
1626  __weak UIView* weakView;
1627  @autoreleasepool {
1628  FlutterEngine* engine = [[FlutterEngine alloc] init];
1629 
1630  [engine runWithEntrypoint:nil];
1631  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
1632  nibName:nil
1633  bundle:nil];
1634  weakViewController = viewController;
1635  [viewController loadView];
1636  [viewController viewDidLoad];
1637  weakView = viewController.view;
1638  XCTAssertTrue([viewController.view isKindOfClass:[FlutterView class]]);
1639  }
1640  XCTAssertNil(weakViewController);
1641  XCTAssertNil(weakView);
1642 }
1643 
1644 #pragma mark - Platform Brightness
1645 
1646 - (void)testItReportsLightPlatformBrightnessByDefault {
1647  // Setup test.
1648  id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1649  OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel);
1650 
1651  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
1652  nibName:nil
1653  bundle:nil];
1654 
1655  // Exercise behavior under test.
1656  [vc traitCollectionDidChange:nil];
1657 
1658  // Verify behavior.
1659  OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1660  return [message[@"platformBrightness"] isEqualToString:@"light"];
1661  }]]);
1662 
1663  // Clean up mocks
1664  [settingsChannel stopMocking];
1665 }
1666 
1667 - (void)testItReportsPlatformBrightnessWhenViewWillAppear {
1668  // Setup test.
1669  id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1670  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1671  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1672  OCMStub([mockEngine settingsChannel]).andReturn(settingsChannel);
1673  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine
1674  nibName:nil
1675  bundle:nil];
1676 
1677  // Exercise behavior under test.
1678  [vc viewWillAppear:false];
1679 
1680  // Verify behavior.
1681  OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1682  return [message[@"platformBrightness"] isEqualToString:@"light"];
1683  }]]);
1684 
1685  // Clean up mocks
1686  [settingsChannel stopMocking];
1687 }
1688 
1689 - (void)testItReportsDarkPlatformBrightnessWhenTraitCollectionRequestsIt {
1690  // Setup test.
1691  id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1692  OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel);
1693  id mockTraitCollection =
1694  [self fakeTraitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];
1695 
1696  // We partially mock the real FlutterViewController to act as the OS and report
1697  // the UITraitCollection of our choice. Mocking the object under test is not
1698  // desirable, but given that the OS does not offer a DI approach to providing
1699  // our own UITraitCollection, this seems to be the least bad option.
1700  id partialMockVC = OCMPartialMock([[FlutterViewController alloc] initWithEngine:self.mockEngine
1701  nibName:nil
1702  bundle:nil]);
1703  OCMStub([partialMockVC traitCollection]).andReturn(mockTraitCollection);
1704 
1705  // Exercise behavior under test.
1706  [partialMockVC traitCollectionDidChange:nil];
1707 
1708  // Verify behavior.
1709  OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1710  return [message[@"platformBrightness"] isEqualToString:@"dark"];
1711  }]]);
1712 
1713  // Clean up mocks
1714  [partialMockVC stopMocking];
1715  [settingsChannel stopMocking];
1716  [mockTraitCollection stopMocking];
1717 }
1718 
1719 // Creates a mocked UITraitCollection with nil values for everything except userInterfaceStyle,
1720 // which is set to the given "style".
1721 - (UITraitCollection*)fakeTraitCollectionWithUserInterfaceStyle:(UIUserInterfaceStyle)style {
1722  id mockTraitCollection = OCMClassMock([UITraitCollection class]);
1723  OCMStub([mockTraitCollection userInterfaceStyle]).andReturn(style);
1724  return mockTraitCollection;
1725 }
1726 
1727 - (void)testTraitCollectionDidChangeCallsResetIntrinsicContentSizeWhenAutoResizable {
1728  // Setup test.
1729  id mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1730  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1731 
1732  FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:mockEngine
1733  nibName:nil
1734  bundle:nil];
1735  id partialMockVC = OCMPartialMock(realVC);
1736 
1737  id mockFlutterView = OCMClassMock([FlutterView class]);
1738  OCMStub([partialMockVC flutterView]).andReturn(mockFlutterView);
1739 
1740  // Ensure isAutoResizable is YES
1741  OCMStub([partialMockVC isAutoResizable]).andReturn(YES);
1742 
1743  // Expect resetIntrinsicContentSize to be called on mockFlutterView
1744  OCMExpect([mockFlutterView resetIntrinsicContentSize]);
1745 
1746  // Exercise behavior under test.
1747  [partialMockVC traitCollectionDidChange:nil];
1748 
1749  // Verify behavior.
1750  OCMVerifyAll(mockFlutterView);
1751 
1752  // Clean up mocks
1753  [partialMockVC stopMocking];
1754  [mockFlutterView stopMocking];
1755 }
1756 
1757 #pragma mark - Platform Contrast
1758 
1759 - (void)testItReportsNormalPlatformContrastByDefault {
1760  // Setup test.
1761  id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1762  OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel);
1763 
1764  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
1765  nibName:nil
1766  bundle:nil];
1767 
1768  // Exercise behavior under test.
1769  [vc traitCollectionDidChange:nil];
1770 
1771  // Verify behavior.
1772  OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1773  return [message[@"platformContrast"] isEqualToString:@"normal"];
1774  }]]);
1775 
1776  // Clean up mocks
1777  [settingsChannel stopMocking];
1778 }
1779 
1780 - (void)testItReportsPlatformContrastWhenViewWillAppear {
1781  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1782  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1783 
1784  // Setup test.
1785  id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1786  OCMStub([mockEngine settingsChannel]).andReturn(settingsChannel);
1787  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine
1788  nibName:nil
1789  bundle:nil];
1790 
1791  // Exercise behavior under test.
1792  [vc viewWillAppear:false];
1793 
1794  // Verify behavior.
1795  OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1796  return [message[@"platformContrast"] isEqualToString:@"normal"];
1797  }]]);
1798 
1799  // Clean up mocks
1800  [settingsChannel stopMocking];
1801 }
1802 
1803 - (void)testItReportsHighContrastWhenTraitCollectionRequestsIt {
1804  // Setup test.
1805  id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]);
1806  OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel);
1807 
1808  id mockTraitCollection = [self fakeTraitCollectionWithContrast:UIAccessibilityContrastHigh];
1809 
1810  // We partially mock the real FlutterViewController to act as the OS and report
1811  // the UITraitCollection of our choice. Mocking the object under test is not
1812  // desirable, but given that the OS does not offer a DI approach to providing
1813  // our own UITraitCollection, this seems to be the least bad option.
1814  id partialMockVC = OCMPartialMock([[FlutterViewController alloc] initWithEngine:self.mockEngine
1815  nibName:nil
1816  bundle:nil]);
1817  OCMStub([partialMockVC traitCollection]).andReturn(mockTraitCollection);
1818 
1819  // Exercise behavior under test.
1820  [partialMockVC traitCollectionDidChange:mockTraitCollection];
1821 
1822  // Verify behavior.
1823  OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1824  return [message[@"platformContrast"] isEqualToString:@"high"];
1825  }]]);
1826 
1827  // Clean up mocks
1828  [partialMockVC stopMocking];
1829  [settingsChannel stopMocking];
1830  [mockTraitCollection stopMocking];
1831 }
1832 
1833 - (void)testItReportsAlwaysUsed24HourFormat {
1834  // Setup test.
1835  id settingsChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]);
1836  OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel);
1837  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
1838  nibName:nil
1839  bundle:nil];
1840  // Test the YES case.
1841  id mockHourFormat = OCMClassMock([FlutterHourFormat class]);
1842  OCMStub([mockHourFormat isAlwaysUse24HourFormat]).andReturn(YES);
1843  OCMExpect([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1844  return [message[@"alwaysUse24HourFormat"] isEqual:@(YES)];
1845  }]]);
1846  [vc onUserSettingsChanged:nil];
1847  [mockHourFormat stopMocking];
1848 
1849  // Test the NO case.
1850  mockHourFormat = OCMClassMock([FlutterHourFormat class]);
1851  OCMStub([mockHourFormat isAlwaysUse24HourFormat]).andReturn(NO);
1852  OCMExpect([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) {
1853  return [message[@"alwaysUse24HourFormat"] isEqual:@(NO)];
1854  }]]);
1855  [vc onUserSettingsChanged:nil];
1856  [mockHourFormat stopMocking];
1857 
1858  // Clean up mocks.
1859  [settingsChannel stopMocking];
1860 }
1861 
1862 - (void)testOnAccessibilityStatusChangedCallsEnableSemanticsWithFlags {
1864  [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
1865  id mockAccessibilityFeatures = OCMClassMock([FlutterAccessibilityFeatures class]);
1866  OCMStub([mockAccessibilityFeatures flags]).andReturn(333);
1867  id mockViewController = OCMPartialMock(viewController);
1868  OCMStub([mockViewController accessibilityFeatures]).andReturn(mockAccessibilityFeatures);
1869 
1870  [mockViewController onAccessibilityStatusChanged:nil];
1871  OCMVerify([self.mockEngine enableSemantics:[OCMArg any] withFlags:333]);
1872 }
1873 
1874 - (void)testHandleAccessibilityNotifications {
1876  [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
1877  id mockViewController = OCMPartialMock(viewController);
1878  __block NSUInteger callsCount = 0;
1879  OCMStub([mockViewController onAccessibilityStatusChanged:[OCMArg isNotNil]])
1880  .andDo(^(NSInvocation* invocation) {
1881  callsCount++;
1882  });
1883 
1884  FlutterAccessibilityFeatures* accessibilityFeatures = [[FlutterAccessibilityFeatures alloc] init];
1885  NSArray<NSString*>* accessibilityNotification = [accessibilityFeatures observedNotificationNames];
1886 
1887  for (NSUInteger i = 0; i < [accessibilityNotification count]; i++) {
1888  NSString* notificationName = [accessibilityNotification objectAtIndex:i];
1889  [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil];
1890  XCTAssertEqual(callsCount, i + 1);
1891  }
1892 }
1893 
1894 - (void)testAccessibilityPerformEscapePopsRoute {
1895  FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]);
1896  [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil];
1897  id mockNavigationChannel = OCMClassMock([FlutterMethodChannel class]);
1898  OCMStub([mockEngine navigationChannel]).andReturn(mockNavigationChannel);
1899 
1900  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
1901  nibName:nil
1902  bundle:nil];
1903  XCTAssertTrue([viewController accessibilityPerformEscape]);
1904 
1905  OCMVerify([mockNavigationChannel invokeMethod:@"popRoute" arguments:nil]);
1906 
1907  [mockNavigationChannel stopMocking];
1908 }
1909 
1910 - (void)testPerformOrientationUpdateForcesOrientationChange {
1911  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait
1912  currentOrientation:UIInterfaceOrientationLandscapeLeft
1913  didChangeOrientation:YES
1914  resultingOrientation:UIInterfaceOrientationPortrait];
1915 
1916  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait
1917  currentOrientation:UIInterfaceOrientationLandscapeRight
1918  didChangeOrientation:YES
1919  resultingOrientation:UIInterfaceOrientationPortrait];
1920 
1921  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait
1922  currentOrientation:UIInterfaceOrientationPortraitUpsideDown
1923  didChangeOrientation:YES
1924  resultingOrientation:UIInterfaceOrientationPortrait];
1925 
1926  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown
1927  currentOrientation:UIInterfaceOrientationLandscapeLeft
1928  didChangeOrientation:YES
1929  resultingOrientation:UIInterfaceOrientationPortraitUpsideDown];
1930 
1931  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown
1932  currentOrientation:UIInterfaceOrientationLandscapeRight
1933  didChangeOrientation:YES
1934  resultingOrientation:UIInterfaceOrientationPortraitUpsideDown];
1935 
1936  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown
1937  currentOrientation:UIInterfaceOrientationPortrait
1938  didChangeOrientation:YES
1939  resultingOrientation:UIInterfaceOrientationPortraitUpsideDown];
1940 
1941  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape
1942  currentOrientation:UIInterfaceOrientationPortrait
1943  didChangeOrientation:YES
1944  resultingOrientation:UIInterfaceOrientationLandscapeLeft];
1945 
1946  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape
1947  currentOrientation:UIInterfaceOrientationPortraitUpsideDown
1948  didChangeOrientation:YES
1949  resultingOrientation:UIInterfaceOrientationLandscapeLeft];
1950 
1951  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft
1952  currentOrientation:UIInterfaceOrientationPortrait
1953  didChangeOrientation:YES
1954  resultingOrientation:UIInterfaceOrientationLandscapeLeft];
1955 
1956  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft
1957  currentOrientation:UIInterfaceOrientationLandscapeRight
1958  didChangeOrientation:YES
1959  resultingOrientation:UIInterfaceOrientationLandscapeLeft];
1960 
1961  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft
1962  currentOrientation:UIInterfaceOrientationPortraitUpsideDown
1963  didChangeOrientation:YES
1964  resultingOrientation:UIInterfaceOrientationLandscapeLeft];
1965 
1966  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight
1967  currentOrientation:UIInterfaceOrientationPortrait
1968  didChangeOrientation:YES
1969  resultingOrientation:UIInterfaceOrientationLandscapeRight];
1970 
1971  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight
1972  currentOrientation:UIInterfaceOrientationLandscapeLeft
1973  didChangeOrientation:YES
1974  resultingOrientation:UIInterfaceOrientationLandscapeRight];
1975 
1976  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight
1977  currentOrientation:UIInterfaceOrientationPortraitUpsideDown
1978  didChangeOrientation:YES
1979  resultingOrientation:UIInterfaceOrientationLandscapeRight];
1980 
1981  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown
1982  currentOrientation:UIInterfaceOrientationPortraitUpsideDown
1983  didChangeOrientation:YES
1984  resultingOrientation:UIInterfaceOrientationPortrait];
1985 }
1986 
1987 - (void)testPerformOrientationUpdateDoesNotForceOrientationChange {
1988  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll
1989  currentOrientation:UIInterfaceOrientationPortrait
1990  didChangeOrientation:NO
1991  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
1992 
1993  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll
1994  currentOrientation:UIInterfaceOrientationPortraitUpsideDown
1995  didChangeOrientation:NO
1996  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
1997 
1998  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll
1999  currentOrientation:UIInterfaceOrientationLandscapeLeft
2000  didChangeOrientation:NO
2001  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2002 
2003  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll
2004  currentOrientation:UIInterfaceOrientationLandscapeRight
2005  didChangeOrientation:NO
2006  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2007 
2008  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown
2009  currentOrientation:UIInterfaceOrientationPortrait
2010  didChangeOrientation:NO
2011  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2012 
2013  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown
2014  currentOrientation:UIInterfaceOrientationLandscapeLeft
2015  didChangeOrientation:NO
2016  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2017 
2018  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown
2019  currentOrientation:UIInterfaceOrientationLandscapeRight
2020  didChangeOrientation:NO
2021  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2022 
2023  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait
2024  currentOrientation:UIInterfaceOrientationPortrait
2025  didChangeOrientation:NO
2026  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2027 
2028  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown
2029  currentOrientation:UIInterfaceOrientationPortraitUpsideDown
2030  didChangeOrientation:NO
2031  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2032 
2033  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape
2034  currentOrientation:UIInterfaceOrientationLandscapeLeft
2035  didChangeOrientation:NO
2036  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2037 
2038  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape
2039  currentOrientation:UIInterfaceOrientationLandscapeRight
2040  didChangeOrientation:NO
2041  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2042 
2043  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft
2044  currentOrientation:UIInterfaceOrientationLandscapeLeft
2045  didChangeOrientation:NO
2046  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2047 
2048  [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight
2049  currentOrientation:UIInterfaceOrientationLandscapeRight
2050  didChangeOrientation:NO
2051  resultingOrientation:static_cast<UIInterfaceOrientation>(0)];
2052 }
2053 
2054 // Perform an orientation update test that fails when the expected outcome
2055 // for an orientation update is not met
2056 - (void)orientationTestWithOrientationUpdate:(UIInterfaceOrientationMask)mask
2057  currentOrientation:(UIInterfaceOrientation)currentOrientation
2058  didChangeOrientation:(BOOL)didChange
2059  resultingOrientation:(UIInterfaceOrientation)resultingOrientation {
2060  id mockApplication = OCMClassMock([UIApplication class]);
2061  id mockWindowScene;
2062  id deviceMock;
2063  id mockVC;
2064  __block __weak id weakPreferences;
2065  @autoreleasepool {
2066  FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:self.mockEngine
2067  nibName:nil
2068  bundle:nil];
2069 
2070  if (@available(iOS 16.0, *)) {
2071  mockWindowScene = OCMClassMock([UIWindowScene class]);
2072  mockVC = OCMPartialMock(realVC);
2073  OCMStub([mockVC flutterWindowSceneIfViewLoaded]).andReturn(mockWindowScene);
2074  if (realVC.supportedInterfaceOrientations == mask) {
2075  OCMReject([mockWindowScene requestGeometryUpdateWithPreferences:[OCMArg any]
2076  errorHandler:[OCMArg any]]);
2077  } else {
2078  // iOS 16 will decide whether to rotate based on the new preference, so always set it
2079  // when it changes.
2080  OCMExpect([mockWindowScene
2081  requestGeometryUpdateWithPreferences:[OCMArg checkWithBlock:^BOOL(
2082  UIWindowSceneGeometryPreferencesIOS*
2083  preferences) {
2084  weakPreferences = preferences;
2085  return preferences.interfaceOrientations == mask;
2086  }]
2087  errorHandler:[OCMArg any]]);
2088  }
2089  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
2090  OCMStub([mockApplication connectedScenes]).andReturn([NSSet setWithObject:mockWindowScene]);
2091  } else {
2092  deviceMock = OCMPartialMock([UIDevice currentDevice]);
2093  if (!didChange) {
2094  OCMReject([deviceMock setValue:[OCMArg any] forKey:@"orientation"]);
2095  } else {
2096  OCMExpect([deviceMock setValue:@(resultingOrientation) forKey:@"orientation"]);
2097  }
2098  mockWindowScene = OCMClassMock([UIWindowScene class]);
2099  mockVC = OCMPartialMock(realVC);
2100  OCMStub([mockVC flutterWindowSceneIfViewLoaded]).andReturn(mockWindowScene);
2101  OCMStub(((UIWindowScene*)mockWindowScene).interfaceOrientation).andReturn(currentOrientation);
2102  }
2103 
2104  [realVC performOrientationUpdate:mask];
2105  if (@available(iOS 16.0, *)) {
2106  OCMVerifyAll(mockWindowScene);
2107  } else {
2108  OCMVerifyAll(deviceMock);
2109  }
2110  }
2111  [mockWindowScene stopMocking];
2112  [deviceMock stopMocking];
2113  [mockApplication stopMocking];
2114  XCTAssertNil(weakPreferences);
2115 }
2116 
2117 // Creates a mocked UITraitCollection with nil values for everything except accessibilityContrast,
2118 // which is set to the given "contrast".
2119 - (UITraitCollection*)fakeTraitCollectionWithContrast:(UIAccessibilityContrast)contrast {
2120  id mockTraitCollection = OCMClassMock([UITraitCollection class]);
2121  OCMStub([mockTraitCollection accessibilityContrast]).andReturn(contrast);
2122  return mockTraitCollection;
2123 }
2124 
2125 - (void)testWillDeallocNotification {
2126  XCTestExpectation* expectation =
2127  [[XCTestExpectation alloc] initWithDescription:@"notification called"];
2128  id engine = [[MockEngine alloc] init];
2129  @autoreleasepool {
2130  // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
2131  FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine
2132  nibName:nil
2133  bundle:nil];
2134  [NSNotificationCenter.defaultCenter addObserverForName:FlutterViewControllerWillDealloc
2135  object:nil
2136  queue:[NSOperationQueue mainQueue]
2137  usingBlock:^(NSNotification* _Nonnull note) {
2138  [expectation fulfill];
2139  }];
2140  XCTAssertNotNil(realVC);
2141  realVC = nil;
2142  }
2143  [self waitForExpectations:@[ expectation ] timeout:1.0];
2144 }
2145 
2146 - (void)testReleasesKeyboardManagerOnDealloc {
2147  __weak FlutterKeyboardManager* weakKeyboardManager = nil;
2148  @autoreleasepool {
2150 
2151  [viewController addInternalPlugins];
2152  weakKeyboardManager = viewController.keyboardManager;
2153  XCTAssertNotNil(weakKeyboardManager);
2154  [viewController deregisterNotifications];
2155  viewController = nil;
2156  }
2157  // View controller has released the keyboard manager.
2158  XCTAssertNil(weakKeyboardManager);
2159 }
2160 
2161 - (void)testDoesntLoadViewInInit {
2162  FlutterDartProject* project = [[FlutterDartProject alloc] init];
2163  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
2164  [engine createShell:@"" libraryURI:@"" initialRoute:nil];
2165  FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine
2166  nibName:nil
2167  bundle:nil];
2168  XCTAssertFalse([realVC isViewLoaded], @"shouldn't have loaded since it hasn't been shown");
2169  engine.viewController = nil;
2170 }
2171 
2172 - (void)testHideOverlay {
2173  FlutterDartProject* project = [[FlutterDartProject alloc] init];
2174  FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
2175  [engine createShell:@"" libraryURI:@"" initialRoute:nil];
2176  FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine
2177  nibName:nil
2178  bundle:nil];
2179  XCTAssertFalse(realVC.prefersHomeIndicatorAutoHidden, @"");
2180  [NSNotificationCenter.defaultCenter postNotificationName:FlutterViewControllerHideHomeIndicator
2181  object:nil];
2182  XCTAssertTrue(realVC.prefersHomeIndicatorAutoHidden, @"");
2183  engine.viewController = nil;
2184 }
2185 
2186 - (void)testNotifyLowMemory {
2188  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
2189  nibName:nil
2190  bundle:nil];
2191  id viewControllerMock = OCMPartialMock(viewController);
2192  OCMStub([viewControllerMock surfaceUpdated:NO]);
2193  [viewController beginAppearanceTransition:NO animated:NO];
2194  [viewController endAppearanceTransition];
2195  XCTAssertTrue(mockEngine.didCallNotifyLowMemory);
2196 }
2197 
2198 - (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback {
2199  NSMutableDictionary* replyMessage = [@{
2200  @"handled" : @YES,
2201  } mutableCopy];
2202  // Response is async, so we have to post it to the run loop instead of calling
2203  // it directly.
2204  self.messageSent = message;
2205  CFRunLoopPerformBlock(CFRunLoopGetCurrent(), fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode,
2206  ^() {
2207  callback(replyMessage);
2208  });
2209 }
2210 
2211 - (void)testValidKeyUpEvent API_AVAILABLE(ios(13.4)) {
2212  if (@available(iOS 13.4, *)) {
2213  // noop
2214  } else {
2215  return;
2216  }
2218  mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]);
2219  OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]])
2220  .andCall(self, @selector(sendMessage:reply:));
2221  OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES);
2222  mockEngine.textInputPlugin = self.mockTextInputPlugin;
2223 
2224  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine
2225  nibName:nil
2226  bundle:nil];
2227 
2228  // Allocate the keyboard manager in the view controller by adding the internal
2229  // plugins.
2230  [vc addInternalPlugins];
2231 
2232  [vc handlePressEvent:keyUpEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0)
2233  nextAction:^(){
2234  }];
2235 
2236  XCTAssert(self.messageSent != nil);
2237  XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]);
2238  XCTAssert([self.messageSent[@"type"] isEqualToString:@"keyup"]);
2239  XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]);
2240  XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]);
2241  XCTAssert([self.messageSent[@"characters"] isEqualToString:@""]);
2242  XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@""]);
2243  [vc deregisterNotifications];
2244 }
2245 
2246 - (void)testValidKeyDownEvent API_AVAILABLE(ios(13.4)) {
2247  if (@available(iOS 13.4, *)) {
2248  // noop
2249  } else {
2250  return;
2251  }
2252 
2254  mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]);
2255  OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]])
2256  .andCall(self, @selector(sendMessage:reply:));
2257  OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES);
2258  mockEngine.textInputPlugin = self.mockTextInputPlugin;
2259 
2260  __strong FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine
2261  nibName:nil
2262  bundle:nil];
2263  // Allocate the keyboard manager in the view controller by adding the internal
2264  // plugins.
2265  [vc addInternalPlugins];
2266 
2267  [vc handlePressEvent:keyDownEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0f, "A",
2268  "a")
2269  nextAction:^(){
2270  }];
2271 
2272  XCTAssert(self.messageSent != nil);
2273  XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]);
2274  XCTAssert([self.messageSent[@"type"] isEqualToString:@"keydown"]);
2275  XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]);
2276  XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]);
2277  XCTAssert([self.messageSent[@"characters"] isEqualToString:@"A"]);
2278  XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@"a"]);
2279  [vc deregisterNotifications];
2280  vc = nil;
2281 }
2282 
2283 - (void)testIgnoredKeyEvents API_AVAILABLE(ios(13.4)) {
2284  if (@available(iOS 13.4, *)) {
2285  // noop
2286  } else {
2287  return;
2288  }
2289  id keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]);
2290  OCMStub([keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]])
2291  .andCall(self, @selector(sendMessage:reply:));
2292  OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES);
2293  OCMStub([self.mockEngine keyEventChannel]).andReturn(keyEventChannel);
2294 
2295  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
2296  nibName:nil
2297  bundle:nil];
2298 
2299  // Allocate the keyboard manager in the view controller by adding the internal
2300  // plugins.
2301  [vc addInternalPlugins];
2302 
2303  [vc handlePressEvent:keyEventWithPhase(UIPressPhaseStationary, UIKeyboardHIDUsageKeyboardA,
2304  UIKeyModifierShift, 123.0)
2305  nextAction:^(){
2306  }];
2307  [vc handlePressEvent:keyEventWithPhase(UIPressPhaseCancelled, UIKeyboardHIDUsageKeyboardA,
2308  UIKeyModifierShift, 123.0)
2309  nextAction:^(){
2310  }];
2311  [vc handlePressEvent:keyEventWithPhase(UIPressPhaseChanged, UIKeyboardHIDUsageKeyboardA,
2312  UIKeyModifierShift, 123.0)
2313  nextAction:^(){
2314  }];
2315 
2316  XCTAssert(self.messageSent == nil);
2317  OCMVerify(never(), [keyEventChannel sendMessage:[OCMArg any]]);
2318  [vc deregisterNotifications];
2319 }
2320 
2321 - (void)testPanGestureRecognizer API_AVAILABLE(ios(13.4)) {
2322  if (@available(iOS 13.4, *)) {
2323  // noop
2324  } else {
2325  return;
2326  }
2327 
2328  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
2329  nibName:nil
2330  bundle:nil];
2331  XCTAssertNotNil(vc);
2332  UIView* view = vc.view;
2333  XCTAssertNotNil(view);
2334  NSArray* gestureRecognizers = view.gestureRecognizers;
2335  XCTAssertNotNil(gestureRecognizers);
2336 
2337  BOOL found = NO;
2338  for (id gesture in gestureRecognizers) {
2339  if ([gesture isKindOfClass:[UIPanGestureRecognizer class]]) {
2340  found = YES;
2341  break;
2342  }
2343  }
2344  XCTAssertTrue(found);
2345 }
2346 
2347 - (void)testMouseSupport API_AVAILABLE(ios(13.4)) {
2348  if (@available(iOS 13.4, *)) {
2349  // noop
2350  } else {
2351  return;
2352  }
2353 
2354  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
2355  nibName:nil
2356  bundle:nil];
2357  XCTAssertNotNil(vc);
2358 
2359  id mockPanGestureRecognizer = OCMClassMock([UIPanGestureRecognizer class]);
2360  XCTAssertNotNil(mockPanGestureRecognizer);
2361 
2362  [vc discreteScrollEvent:mockPanGestureRecognizer];
2363 
2364  // The mouse position within panGestureRecognizer should be checked
2365  [[mockPanGestureRecognizer verify] locationInView:[OCMArg any]];
2366  [[[self.mockEngine verify] ignoringNonObjectArgs]
2367  dispatchPointerDataPacket:std::make_unique<flutter::PointerDataPacket>(0)];
2368 }
2369 
2370 // Verify stylus and touch-geometry fields.
2371 //
2372 // Ensure `tilt` and `orientation` are correctly renormalized. iOS reports angles relative to the
2373 // surface plane with 0 representing horizontal. The engine expects them relative to the surface
2374 // normal with zero representing vertical.
2375 - (void)testStylusTouchFieldsSurviveConversion {
2376  PointerDataCapturingEngine* engine = [[PointerDataCapturingEngine alloc] initWithName:@"foobar"
2377  project:nil];
2378  // `-[FlutterEngine setViewController:]` requires PlatformViewIOS, which only exists after
2379  // the shell has been created.
2380  [engine run];
2381  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:engine
2382  nibName:nil
2383  bundle:nil];
2384  XCTAssertNotNil(vc);
2385 
2386  // A stylus held at 30 degrees off the surface, swung 45 degrees clockwise from the +x axis.
2387  const CGFloat altitudeAngle = M_PI / 6; // 30 degrees from the surface plane.
2388  const CGFloat azimuthAngle = M_PI / 4; // 45 degrees clockwise from +x.
2389  const CGFloat force = 0.75;
2390  const CGFloat maximumPossibleForce = 4.0;
2391  const CGFloat majorRadius = 20.0;
2392  const CGFloat majorRadiusTolerance = 3.0;
2393 
2394  id fakeTouch = OCMPartialMock([[UITouch alloc] init]);
2395  [fakeTouch setPhase:UITouchPhaseBegan];
2396  OCMStub([fakeTouch force]).andReturn(force);
2397  OCMStub([fakeTouch maximumPossibleForce]).andReturn(maximumPossibleForce);
2398  OCMStub([fakeTouch majorRadius]).andReturn(majorRadius);
2399  OCMStub([fakeTouch majorRadiusTolerance]).andReturn(majorRadiusTolerance);
2400  OCMStub([fakeTouch altitudeAngle]).andReturn(altitudeAngle);
2401  OCMStub([fakeTouch azimuthAngleInView:[OCMArg any]]).andReturn(azimuthAngle);
2402 
2403  [vc dispatchTouches:[NSSet setWithObject:fakeTouch] pointerDataChangeOverride:nullptr event:nil];
2404 
2405  const std::vector<flutter::PointerData>& captured = [engine capturedPointerData];
2406  XCTAssertEqual(captured.size(), 1u);
2407  const flutter::PointerData& data = captured[0];
2408 
2409  const double tolerance = 1e-6;
2410 
2411  // Pressure is a straight copy; `pressure_min` is always 0.
2412  XCTAssertEqualWithAccuracy(data.pressure, force, tolerance);
2413  XCTAssertEqualWithAccuracy(data.pressure_max, maximumPossibleForce, tolerance);
2414  XCTAssertEqualWithAccuracy(data.pressure_min, 0.0, tolerance);
2415 
2416  // Radius is a copy, with the tolerance applied symmetrically to produce min/max.
2417  XCTAssertEqualWithAccuracy(data.radius_major, majorRadius, tolerance);
2418  XCTAssertEqualWithAccuracy(data.radius_min, majorRadius - majorRadiusTolerance, tolerance);
2419  XCTAssertEqualWithAccuracy(data.radius_max, majorRadius + majorRadiusTolerance, tolerance);
2420 
2421  // iOS measures altitude from the surface plane; `PointerData.tilt` measures from the surface
2422  // normal. Same range, swapped origin, so the two are complements about pi/2.
2423  XCTAssertEqualWithAccuracy(data.tilt, M_PI_2 - altitudeAngle, tolerance);
2424 
2425  // iOS measures azimuth from the +x axis; `PointerData.orientation` measures from the +y axis.
2426  // Same sweep direction, phase-shifted by pi/2.
2427  XCTAssertEqualWithAccuracy(data.orientation, azimuthAngle - M_PI_2, tolerance);
2428 }
2429 
2430 // Verify max stylus tilt angle.
2431 //
2432 // A stylus lying flat on the glass is altitude 0 to iOS, which must map to the maximum tilt of pi/2
2433 // in the engine. A stylus held perpendicular is altitude pi/2, mapping to engine tilt 0.
2434 - (void)testStylusTiltEndpoints {
2435  PointerDataCapturingEngine* engine = [[PointerDataCapturingEngine alloc] initWithName:@"foobar"
2436  project:nil];
2437  [engine run];
2438  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:engine
2439  nibName:nil
2440  bundle:nil];
2441 
2442  id flatTouch = OCMPartialMock([[UITouch alloc] init]);
2443  [flatTouch setPhase:UITouchPhaseBegan];
2444  OCMStub([flatTouch altitudeAngle]).andReturn(0.0);
2445  OCMStub([flatTouch azimuthAngleInView:[OCMArg any]]).andReturn(M_PI_2);
2446 
2447  [vc dispatchTouches:[NSSet setWithObject:flatTouch] pointerDataChangeOverride:nullptr event:nil];
2448 
2449  id perpendicularTouch = OCMPartialMock([[UITouch alloc] init]);
2450  [perpendicularTouch setPhase:UITouchPhaseBegan];
2451  OCMStub([perpendicularTouch altitudeAngle]).andReturn(M_PI_2);
2452  OCMStub([perpendicularTouch azimuthAngleInView:[OCMArg any]]).andReturn(0.0);
2453 
2454  [vc dispatchTouches:[NSSet setWithObject:perpendicularTouch]
2455  pointerDataChangeOverride:nullptr
2456  event:nil];
2457 
2458  const double tolerance = 1e-6;
2459  const std::vector<flutter::PointerData>& captured = [engine capturedPointerData];
2460  XCTAssertEqual(captured.size(), 2u);
2461 
2462  // Flat on the surface: maximum tilt.
2463  XCTAssertEqualWithAccuracy(captured[0].tilt, M_PI_2, tolerance);
2464  // Azimuth of pi/2 points along +y, which is orientation 0.
2465  XCTAssertEqualWithAccuracy(captured[0].orientation, 0.0, tolerance);
2466 
2467  // Perpendicular to the surface: zero tilt.
2468  XCTAssertEqualWithAccuracy(captured[1].tilt, 0.0, tolerance);
2469  // Azimuth of 0 points along +x, a quarter turn back from +y.
2470  XCTAssertEqualWithAccuracy(captured[1].orientation, -M_PI_2, tolerance);
2471 }
2472 
2473 - (void)testFakeEventTimeStamp {
2474  FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine
2475  nibName:nil
2476  bundle:nil];
2477  XCTAssertNotNil(vc);
2478 
2479  flutter::PointerData pointer_data = [vc generatePointerDataForFake];
2480  int64_t current_micros = [[NSProcessInfo processInfo] systemUptime] * 1000 * 1000;
2481  int64_t interval_micros = current_micros - pointer_data.time_stamp;
2482  const int64_t tolerance_millis = 2;
2483  XCTAssertTrue(interval_micros / 1000 < tolerance_millis,
2484  @"PointerData.time_stamp should be equal to NSProcessInfo.systemUptime");
2485 }
2486 
2487 - (void)testSplashScreenViewCanSetNil {
2488  FlutterViewController* flutterViewController =
2489  [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
2490  [flutterViewController setSplashScreenView:nil];
2491 }
2492 
2493 - (void)testLifeCycleNotificationApplicationBecameActive {
2494  FlutterEngine* engine = [[FlutterEngine alloc] init];
2495  [engine runWithEntrypoint:nil];
2496  FlutterViewController* flutterViewController =
2497  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2498  NSNotification* sceneNotification =
2499  [NSNotification notificationWithName:UISceneDidActivateNotification object:nil userInfo:nil];
2500  NSNotification* applicationNotification =
2501  [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification
2502  object:nil
2503  userInfo:nil];
2504  id mockVC = OCMPartialMock(flutterViewController);
2505  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2506  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2507  OCMReject([mockVC sceneBecameActive:[OCMArg any]]);
2508  OCMVerify([mockVC applicationBecameActive:[OCMArg any]]);
2509  XCTAssertFalse(
2510  flutterViewController.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground);
2511  XCTestExpectation* timeoutApplicationLifeCycle =
2512  [self expectationWithDescription:@"timeoutApplicationLifeCycle"];
2513  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
2514  dispatch_get_main_queue(), ^{
2515  [timeoutApplicationLifeCycle fulfill];
2516  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]);
2517  [flutterViewController deregisterNotifications];
2518  });
2519  [self waitForExpectationsWithTimeout:5.0 handler:nil];
2520 }
2521 
2522 - (void)testLifeCycleNotificationSceneBecameActive {
2523  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
2524  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
2525  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
2526  });
2527  FlutterEngine* engine = [[FlutterEngine alloc] init];
2528  [engine runWithEntrypoint:nil];
2529  FlutterViewController* flutterViewController =
2530  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2531  NSNotification* sceneNotification =
2532  [NSNotification notificationWithName:UISceneDidActivateNotification object:nil userInfo:nil];
2533  NSNotification* applicationNotification =
2534  [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification
2535  object:nil
2536  userInfo:nil];
2537  id mockVC = OCMPartialMock(flutterViewController);
2538  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2539  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2540  OCMVerify([mockVC sceneBecameActive:[OCMArg any]]);
2541  OCMReject([mockVC applicationBecameActive:[OCMArg any]]);
2542  XCTAssertFalse(
2543  flutterViewController.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground);
2544  XCTestExpectation* timeoutApplicationLifeCycle =
2545  [self expectationWithDescription:@"timeoutApplicationLifeCycle"];
2546  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
2547  dispatch_get_main_queue(), ^{
2548  [timeoutApplicationLifeCycle fulfill];
2549  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]);
2550  [flutterViewController deregisterNotifications];
2551  });
2552  [self waitForExpectationsWithTimeout:5.0 handler:nil];
2553  [mockBundle stopMocking];
2554 }
2555 
2556 // Verifies the surface is created when the application becomes active after the first layout
2557 // pass has already run. UIKit lays out the view while the application is still inactive during a
2558 // cold start, we create the surface during activation.
2559 - (void)testSurfaceCreatedWhenApplicationBecomesActiveAfterLayoutWhileInactive {
2560  FlutterEngine* engine = [[FlutterEngine alloc] init];
2561  [engine runWithEntrypoint:nil];
2562  FlutterViewController* flutterViewController =
2563  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2564 
2565  // The window must be attached to the connected scene to have a screen, without which the
2566  // viewport metrics stay empty and the surface is never updated.
2567  UIWindowScene* windowScene =
2568  (UIWindowScene*)UIApplication.sharedApplication.connectedScenes.anyObject;
2569  XCTAssertNotNil(windowScene, @"The host app must have a connected scene for test");
2570  UIWindow* window = [[UIWindow alloc] initWithWindowScene:windowScene];
2571  [window addSubview:flutterViewController.view];
2572  flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100);
2573 
2574  __block UIApplicationState applicationState = UIApplicationStateInactive;
2575  id mockApplication = OCMClassMock([UIApplication class]);
2576  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
2577  OCMStub([mockApplication applicationState]).andDo(^(NSInvocation* invocation) {
2578  [invocation setReturnValue:&applicationState];
2579  });
2580  id mockVC = OCMPartialMock(flutterViewController);
2581 
2582  // Verify the surface exists once the application is active, whichever callback creates it.
2583  [flutterViewController viewDidLayoutSubviews];
2584  applicationState = UIApplicationStateActive;
2585  [NSNotificationCenter.defaultCenter postNotificationName:UIApplicationDidBecomeActiveNotification
2586  object:nil];
2587  OCMVerify([mockVC surfaceUpdated:YES]);
2588 
2589  [NSObject cancelPreviousPerformRequestsWithTarget:flutterViewController];
2590  [flutterViewController deregisterNotifications];
2591  [mockApplication stopMocking];
2592 }
2593 
2594 // Verifies a layout pass while the application is backgrounded does not create the surface.
2595 // Surface creation accesses the GPU, which can terminate backgrounded processes.
2596 - (void)testSurfaceNotCreatedWhenLayoutRunsWhileApplicationStateIsBackground {
2597  FlutterEngine* engine = [[FlutterEngine alloc] init];
2598  [engine runWithEntrypoint:nil];
2599  FlutterViewController* flutterViewController =
2600  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2601 
2602  // The window must be attached to the connected scene to have a screen, without which the
2603  // viewport metrics stay empty and the surface is never updated.
2604  UIWindowScene* windowScene =
2605  (UIWindowScene*)UIApplication.sharedApplication.connectedScenes.anyObject;
2606  XCTAssertNotNil(windowScene, @"The host app must have a connected scene for test");
2607  UIWindow* window = [[UIWindow alloc] initWithWindowScene:windowScene];
2608  [window addSubview:flutterViewController.view];
2609  flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100);
2610 
2611  id mockApplication = OCMClassMock([UIApplication class]);
2612  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
2613  OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateBackground);
2614  id mockVC = OCMPartialMock(flutterViewController);
2615 
2616  [flutterViewController viewDidLayoutSubviews];
2617  OCMVerify(never(), [mockVC surfaceUpdated:YES]);
2618 
2619  [flutterViewController deregisterNotifications];
2620  [mockApplication stopMocking];
2621 }
2622 
2623 // Verifies rendering resumes when the application returns to the foreground. UIApplication
2624 // has state UIApplicationStateBackground while UIApplicationWillEnterForegroundNotification is
2625 // being delivered.
2626 - (void)testSurfaceCreatedOnWillEnterForegroundWhileApplicationStateIsBackground {
2627  FlutterEngine* engine = [[FlutterEngine alloc] init];
2628  [engine runWithEntrypoint:nil];
2629  FlutterViewController* flutterViewController =
2630  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2631 
2632  // The window must be attached to the connected scene to have a screen, without which the
2633  // viewport metrics stay empty and the surface is never updated.
2634  UIWindowScene* windowScene =
2635  (UIWindowScene*)UIApplication.sharedApplication.connectedScenes.anyObject;
2636  XCTAssertNotNil(windowScene, @"The host app must have a connected scene for test");
2637  UIWindow* window = [[UIWindow alloc] initWithWindowScene:windowScene];
2638  [window addSubview:flutterViewController.view];
2639  flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100);
2640 
2641  __block UIApplicationState applicationState = UIApplicationStateActive;
2642  id mockApplication = OCMClassMock([UIApplication class]);
2643  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
2644  OCMStub([mockApplication applicationState]).andDo(^(NSInvocation* invocation) {
2645  [invocation setReturnValue:&applicationState];
2646  });
2647  id mockVC = OCMPartialMock(flutterViewController);
2648 
2649  // Lay out while active so the viewport metrics are known and the surface is created.
2650  [flutterViewController viewDidLayoutSubviews];
2651  OCMVerify(times(1), [mockVC surfaceUpdated:YES]);
2652 
2653  // Verify backgrounding tears down the surface.
2654  applicationState = UIApplicationStateBackground;
2655  [NSNotificationCenter.defaultCenter
2656  postNotificationName:UIApplicationDidEnterBackgroundNotification
2657  object:nil];
2658  OCMVerify([mockVC surfaceUpdated:NO]);
2659 
2660  // Verify foregrounding recreates it while the application is still reporting backgrounded state.
2661  [NSNotificationCenter.defaultCenter
2662  postNotificationName:UIApplicationWillEnterForegroundNotification
2663  object:nil];
2664  OCMVerify(times(2), [mockVC surfaceUpdated:YES]);
2665 
2666  [NSObject cancelPreviousPerformRequestsWithTarget:flutterViewController];
2667  [flutterViewController deregisterNotifications];
2668  [mockApplication stopMocking];
2669 }
2670 
2671 - (void)testLifeCycleNotificationApplicationWillResignActive {
2672  FlutterEngine* engine = [[FlutterEngine alloc] init];
2673  [engine runWithEntrypoint:nil];
2674  FlutterViewController* flutterViewController =
2675  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2676  NSNotification* sceneNotification =
2677  [NSNotification notificationWithName:UISceneWillDeactivateNotification
2678  object:nil
2679  userInfo:nil];
2680  NSNotification* applicationNotification =
2681  [NSNotification notificationWithName:UIApplicationWillResignActiveNotification
2682  object:nil
2683  userInfo:nil];
2684  id mockVC = OCMPartialMock(flutterViewController);
2685  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2686  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2687  OCMReject([mockVC sceneWillResignActive:[OCMArg any]]);
2688  OCMVerify([mockVC applicationWillResignActive:[OCMArg any]]);
2689  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]);
2690  [flutterViewController deregisterNotifications];
2691 }
2692 
2693 - (void)testLifeCycleNotificationSceneWillResignActive {
2694  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
2695  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
2696  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
2697  });
2698  FlutterEngine* engine = [[FlutterEngine alloc] init];
2699  [engine runWithEntrypoint:nil];
2700  FlutterViewController* flutterViewController =
2701  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2702  NSNotification* sceneNotification =
2703  [NSNotification notificationWithName:UISceneWillDeactivateNotification
2704  object:nil
2705  userInfo:nil];
2706  NSNotification* applicationNotification =
2707  [NSNotification notificationWithName:UIApplicationWillResignActiveNotification
2708  object:nil
2709  userInfo:nil];
2710  id mockVC = OCMPartialMock(flutterViewController);
2711  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2712  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2713  OCMVerify([mockVC sceneWillResignActive:[OCMArg any]]);
2714  OCMReject([mockVC applicationWillResignActive:[OCMArg any]]);
2715  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]);
2716  [flutterViewController deregisterNotifications];
2717  [mockBundle stopMocking];
2718 }
2719 
2720 - (void)testLifeCycleNotificationApplicationWillTerminate {
2721  FlutterEngine* engine = [[FlutterEngine alloc] init];
2722  [engine runWithEntrypoint:nil];
2723  FlutterViewController* flutterViewController =
2724  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2725  NSNotification* sceneNotification =
2726  [NSNotification notificationWithName:UISceneDidDisconnectNotification
2727  object:nil
2728  userInfo:nil];
2729  NSNotification* applicationNotification =
2730  [NSNotification notificationWithName:UIApplicationWillTerminateNotification
2731  object:nil
2732  userInfo:nil];
2733  id mockVC = OCMPartialMock(flutterViewController);
2734  id mockEngine = OCMPartialMock(engine);
2735  OCMStub([mockVC engine]).andReturn(mockEngine);
2736  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2737  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2738  OCMReject([mockVC sceneWillDisconnect:[OCMArg any]]);
2739  OCMVerify([mockVC applicationWillTerminate:[OCMArg any]]);
2740  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.detached"]);
2741  OCMVerify([mockEngine destroyContext]);
2742  [flutterViewController deregisterNotifications];
2743 }
2744 
2745 - (void)testLifeCycleNotificationSceneWillTerminate {
2746  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
2747  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
2748  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
2749  });
2750  FlutterEngine* engine = [[FlutterEngine alloc] init];
2751  [engine runWithEntrypoint:nil];
2752  FlutterViewController* flutterViewController =
2753  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2754  NSNotification* sceneNotification =
2755  [NSNotification notificationWithName:UISceneDidDisconnectNotification
2756  object:nil
2757  userInfo:nil];
2758  NSNotification* applicationNotification =
2759  [NSNotification notificationWithName:UIApplicationWillTerminateNotification
2760  object:nil
2761  userInfo:nil];
2762  id mockVC = OCMPartialMock(flutterViewController);
2763  id mockEngine = OCMPartialMock(engine);
2764  OCMStub([mockVC engine]).andReturn(mockEngine);
2765  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2766  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2767  OCMVerify([mockVC sceneWillDisconnect:[OCMArg any]]);
2768  OCMReject([mockVC applicationWillTerminate:[OCMArg any]]);
2769  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.detached"]);
2770  OCMVerify([mockEngine destroyContext]);
2771  [flutterViewController deregisterNotifications];
2772  [mockBundle stopMocking];
2773 }
2774 
2775 - (void)testLifeCycleNotificationApplicationDidEnterBackground {
2776  FlutterEngine* engine = [[FlutterEngine alloc] init];
2777  [engine runWithEntrypoint:nil];
2778  FlutterViewController* flutterViewController =
2779  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2780  NSNotification* sceneNotification =
2781  [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
2782  object:nil
2783  userInfo:nil];
2784  NSNotification* applicationNotification =
2785  [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification
2786  object:nil
2787  userInfo:nil];
2788  id mockVC = OCMPartialMock(flutterViewController);
2789  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2790  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2791  OCMReject([mockVC sceneDidEnterBackground:[OCMArg any]]);
2792  OCMVerify([mockVC applicationDidEnterBackground:[OCMArg any]]);
2793  XCTAssertTrue(
2794  flutterViewController.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground);
2795  OCMVerify([mockVC surfaceUpdated:NO]);
2796  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.paused"]);
2797  [flutterViewController deregisterNotifications];
2798 }
2799 
2800 - (void)testLifeCycleNotificationSceneDidEnterBackground {
2801  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
2802  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
2803  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
2804  });
2805  FlutterEngine* engine = [[FlutterEngine alloc] init];
2806  [engine runWithEntrypoint:nil];
2807  FlutterViewController* flutterViewController =
2808  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2809  NSNotification* sceneNotification =
2810  [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
2811  object:nil
2812  userInfo:nil];
2813  NSNotification* applicationNotification =
2814  [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification
2815  object:nil
2816  userInfo:nil];
2817  id mockVC = OCMPartialMock(flutterViewController);
2818  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2819  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2820  OCMVerify([mockVC sceneDidEnterBackground:[OCMArg any]]);
2821  OCMReject([mockVC applicationDidEnterBackground:[OCMArg any]]);
2822  XCTAssertTrue(
2823  flutterViewController.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground);
2824  OCMVerify([mockVC surfaceUpdated:NO]);
2825  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.paused"]);
2826  [flutterViewController deregisterNotifications];
2827  [mockBundle stopMocking];
2828 }
2829 
2830 /**
2831  * Verifies that scene lifecycle notifications (specifically UISceneDidEnterBackgroundNotification)
2832  * originating from a different scene (e.g. out-of-process system keyboard scene on iOS 27 Beta)
2833  * are ignored, while notifications for the matching scene hosting the view controller are
2834  * processed.
2835  *
2836  * Prevents regressions where global scene notifications trigger pausing the app's rendering.
2837  * See: https://github.com/flutter/flutter/issues/187844
2838  */
2839 - (void)
2840  testLifeCycleNotificationSceneDidEnterBackgroundIgnoresOtherScenes API_AVAILABLE(ios(13.0)) {
2841  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
2842  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
2843  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
2844  });
2845  FlutterEngine* engine = [[FlutterEngine alloc] init];
2846  [engine runWithEntrypoint:nil];
2847  FlutterViewController* flutterViewController =
2848  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2849  id mockVC = OCMPartialMock(flutterViewController);
2850 
2851  // Mock the active window scene that hosts the FlutterViewController.
2852  id flutterWindowScene = OCMClassMock([UIWindowScene class]);
2853  OCMStub([mockVC flutterWindowSceneIfViewLoaded]).andReturn(flutterWindowScene);
2854 
2855  // Create an auxiliary scene (e.g. the system keyboard) unrelated to the Flutter window.
2856  id auxiliaryScene = OCMClassMock([UIWindowScene class]);
2857 
2858  // Post a notification from the auxiliary (non-Flutter) scene and ensure it is ignored.
2859  // It should not trigger surface update removal or affect keyboard transitioning state.
2860  NSNotification* auxiliarySceneNotification =
2861  [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
2862  object:auxiliaryScene
2863  userInfo:nil];
2864  [NSNotificationCenter.defaultCenter postNotification:auxiliarySceneNotification];
2865  OCMVerify(never(), [mockVC surfaceUpdated:[OCMArg any]]);
2866  OCMVerify(never(), [mockVC goToApplicationLifecycle:@"AppLifecycleState.paused"]);
2867  XCTAssertFalse(
2868  flutterViewController.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground);
2869 
2870  // Post a notification from the Flutter scene and assert it is processed.
2871  // It should trigger surface update removal and transition lifecycle state to paused.
2872  NSNotification* flutterSceneNotification =
2873  [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
2874  object:flutterWindowScene
2875  userInfo:nil];
2876  [NSNotificationCenter.defaultCenter postNotification:flutterSceneNotification];
2877  OCMVerify([mockVC surfaceUpdated:NO]);
2878  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.paused"]);
2879  XCTAssertTrue(
2880  flutterViewController.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground);
2881 
2882  [flutterViewController deregisterNotifications];
2883  [mockBundle stopMocking];
2884 }
2885 
2886 - (void)testLifeCycleNotificationApplicationWillEnterForeground {
2887  FlutterEngine* engine = [[FlutterEngine alloc] init];
2888  [engine runWithEntrypoint:nil];
2889  FlutterViewController* flutterViewController =
2890  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2891  // The window must be attached to the connected scene to have a screen, without which the
2892  // viewport metrics stay empty and the surface is never updated.
2893  UIWindowScene* windowScene =
2894  (UIWindowScene*)UIApplication.sharedApplication.connectedScenes.anyObject;
2895  XCTAssertNotNil(windowScene, @"The host app must have a connected scene for test");
2896  UIWindow* window = [[UIWindow alloc] initWithWindowScene:windowScene];
2897  [window addSubview:flutterViewController.view];
2898  flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100);
2899  [flutterViewController viewDidLayoutSubviews];
2900  NSNotification* sceneNotification =
2901  [NSNotification notificationWithName:UISceneWillEnterForegroundNotification
2902  object:nil
2903  userInfo:nil];
2904  NSNotification* applicationNotification =
2905  [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification
2906  object:nil
2907  userInfo:nil];
2908  id mockVC = OCMPartialMock(flutterViewController);
2909  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2910  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2911  OCMReject([mockVC sceneWillEnterForeground:[OCMArg any]]);
2912  OCMVerify([mockVC applicationWillEnterForeground:[OCMArg any]]);
2913  OCMVerify([mockVC surfaceUpdated:YES]);
2914  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]);
2915  [flutterViewController deregisterNotifications];
2916 }
2917 
2918 - (void)testLifeCycleNotificationSceneWillEnterForeground {
2919  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
2920  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
2921  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
2922  });
2923  FlutterEngine* engine = [[FlutterEngine alloc] init];
2924  [engine runWithEntrypoint:nil];
2925  FlutterViewController* flutterViewController =
2926  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2927  // The window must be attached to the connected scene to have a screen, without which the
2928  // viewport metrics stay empty and the surface is never updated.
2929  UIWindowScene* windowScene =
2930  (UIWindowScene*)UIApplication.sharedApplication.connectedScenes.anyObject;
2931  XCTAssertNotNil(windowScene, @"The host app must have a connected scene for test");
2932  UIWindow* window = [[UIWindow alloc] initWithWindowScene:windowScene];
2933  [window addSubview:flutterViewController.view];
2934  flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100);
2935  [flutterViewController viewDidLayoutSubviews];
2936  NSNotification* sceneNotification =
2937  [NSNotification notificationWithName:UISceneWillEnterForegroundNotification
2938  object:nil
2939  userInfo:nil];
2940  NSNotification* applicationNotification =
2941  [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification
2942  object:nil
2943  userInfo:nil];
2944  id mockVC = OCMPartialMock(flutterViewController);
2945  [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
2946  [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
2947  OCMVerify([mockVC sceneWillEnterForeground:[OCMArg any]]);
2948  OCMReject([mockVC applicationWillEnterForeground:[OCMArg any]]);
2949  OCMVerify([mockVC surfaceUpdated:YES]);
2950  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]);
2951  [flutterViewController deregisterNotifications];
2952  [mockBundle stopMocking];
2953 }
2954 
2955 - (void)testLifeCycleNotificationCancelledInvalidResumed {
2956  FlutterEngine* engine = [[FlutterEngine alloc] init];
2957  [engine runWithEntrypoint:nil];
2958  FlutterViewController* flutterViewController =
2959  [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
2960  NSNotification* applicationDidBecomeActiveNotification =
2961  [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification
2962  object:nil
2963  userInfo:nil];
2964  NSNotification* applicationWillResignActiveNotification =
2965  [NSNotification notificationWithName:UIApplicationWillResignActiveNotification
2966  object:nil
2967  userInfo:nil];
2968  id mockVC = OCMPartialMock(flutterViewController);
2969  [NSNotificationCenter.defaultCenter postNotification:applicationDidBecomeActiveNotification];
2970  [NSNotificationCenter.defaultCenter postNotification:applicationWillResignActiveNotification];
2971  OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]);
2972 
2973  XCTestExpectation* timeoutApplicationLifeCycle =
2974  [self expectationWithDescription:@"timeoutApplicationLifeCycle"];
2975  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
2976  dispatch_get_main_queue(), ^{
2977  OCMReject([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]);
2978  [timeoutApplicationLifeCycle fulfill];
2979  [flutterViewController deregisterNotifications];
2980  });
2981  [self waitForExpectationsWithTimeout:5.0 handler:nil];
2982 }
2983 
2984 - (void)testSetupKeyboardAnimationVsyncClientWillCreateNewVsyncClientForFlutterViewController {
2985  id bundleMock = OCMPartialMock([NSBundle mainBundle]);
2986  OCMStub([bundleMock objectForInfoDictionaryKey:@"CADisableMinimumFrameDurationOnPhone"])
2987  .andReturn(@YES);
2988  id mockDisplayLinkManager = OCMPartialMock([FlutterDisplayLinkManager shared]);
2989  [self addTeardownBlock:^{
2990  [mockDisplayLinkManager stopMocking];
2991  }];
2992  double maxFrameRate = 120;
2993  (void)[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
2994  FlutterEngine* engine = [[FlutterEngine alloc] init];
2995  [engine runWithEntrypoint:nil];
2996  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
2997  nibName:nil
2998  bundle:nil];
2999  FlutterKeyboardAnimationCallback callback = ^(NSTimeInterval targetTime) {
3000  };
3001  [viewController.keyboardInsetManager setUpKeyboardAnimationVsyncClient:callback];
3002  XCTAssertNotNil(viewController.keyboardInsetManager.keyboardAnimationVSyncClient);
3003  CADisplayLink* link =
3004  viewController.keyboardInsetManager.keyboardAnimationVSyncClient.displayLink;
3005  XCTAssertNotNil(link);
3006  CADisplayLink* linkMock = OCMPartialMock(link);
3007  if (@available(iOS 15.0, *)) {
3008  CAFrameRateRange range = CAFrameRateRangeMake(maxFrameRate / 2, maxFrameRate, maxFrameRate);
3009  NSValue* rangeValue = [NSValue valueWithBytes:&range objCType:@encode(CAFrameRateRange)];
3010  [[[(id)linkMock stub] andReturnValue:rangeValue] preferredFrameRateRange];
3011 
3012  XCTAssertEqual(linkMock.preferredFrameRateRange.maximum, maxFrameRate);
3013  XCTAssertEqual(linkMock.preferredFrameRateRange.preferred, maxFrameRate);
3014  XCTAssertEqual(linkMock.preferredFrameRateRange.minimum, maxFrameRate / 2);
3015  } else {
3016  [[[(id)linkMock stub] andReturnValue:@(maxFrameRate)] preferredFramesPerSecond];
3017  XCTAssertEqual(linkMock.preferredFramesPerSecond, maxFrameRate);
3018  }
3019 }
3020 
3021 - (void)testFlutterViewControllerStartKeyboardAnimationWillCreateVsyncClientCorrectly {
3022  id mockDisplayLink = OCMClassMock([CADisplayLink class]);
3023  OCMStub(ClassMethod([mockDisplayLink displayLinkWithTarget:[OCMArg any]
3024  selector:sel_registerName("onDisplayLink:")]))
3025  .andReturn(mockDisplayLink);
3026 
3027  TestKeyboardInsetDelegate* delegate = [[TestKeyboardInsetDelegate alloc] init];
3028  delegate.isViewLoaded = YES;
3030  delegate.mockEngine = engine;
3031 
3032  FlutterKeyboardInsetManager* manager =
3033  [[FlutterKeyboardInsetManager alloc] initWithDelegate:delegate
3034  displayLinkManager:FlutterDisplayLinkManager.shared];
3035  manager.targetViewInsetBottom = 100;
3036  [manager startKeyBoardAnimation:0.25];
3037 
3038  XCTAssertNotNil(manager.keyboardAnimationVSyncClient);
3039  fml::MessageLoop::GetCurrent().RunExpiredTasksNow();
3040  [manager invalidate];
3041  [mockDisplayLink stopMocking];
3042 }
3043 
3044 - (void)
3045  testSetupKeyboardAnimationVsyncClientWillNotCreateNewVsyncClientWhenKeyboardAnimationCallbackIsNil {
3046  FlutterEngine* engine = [[FlutterEngine alloc] init];
3047  [engine runWithEntrypoint:nil];
3048  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3049  nibName:nil
3050  bundle:nil];
3051  [viewController.keyboardInsetManager setUpKeyboardAnimationVsyncClient:nil];
3052  XCTAssertNil(viewController.keyboardInsetManager.keyboardAnimationVSyncClient);
3053 }
3054 
3055 - (void)testSupportsShowingSystemContextMenuForIOS16AndAbove {
3056  FlutterEngine* engine = [[FlutterEngine alloc] init];
3057  [engine runWithEntrypoint:nil];
3058  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3059  nibName:nil
3060  bundle:nil];
3061  BOOL supportsShowingSystemContextMenu = [viewController supportsShowingSystemContextMenu];
3062  if (@available(iOS 16.0, *)) {
3063  XCTAssertTrue(supportsShowingSystemContextMenu);
3064  } else {
3065  XCTAssertFalse(supportsShowingSystemContextMenu);
3066  }
3067 }
3068 
3069 - (void)testStatePropertiesWhenApplicationStateIsActive {
3070  FlutterEngine* engine = [[FlutterEngine alloc] init];
3071  [engine runWithEntrypoint:nil];
3072  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3073  nibName:nil
3074  bundle:nil];
3075  id mockApplication = OCMClassMock([UIApplication class]);
3076  OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateActive);
3077  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
3078  XCTAssertTrue(viewController.stateIsActive);
3079  XCTAssertTrue(viewController.stateIsForeground);
3080  XCTAssertFalse(viewController.stateIsBackground);
3081 }
3082 
3083 - (void)testStatePropertiesWhenApplicationStateIsBackground {
3084  FlutterEngine* engine = [[FlutterEngine alloc] init];
3085  [engine runWithEntrypoint:nil];
3086  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3087  nibName:nil
3088  bundle:nil];
3089  id mockApplication = OCMClassMock([UIApplication class]);
3090  OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateBackground);
3091  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
3092  XCTAssertFalse(viewController.stateIsActive);
3093  XCTAssertFalse(viewController.stateIsForeground);
3094  XCTAssertTrue(viewController.stateIsBackground);
3095 }
3096 
3097 - (void)testStatePropertiesWhenApplicationStateIsInactive {
3098  FlutterEngine* engine = [[FlutterEngine alloc] init];
3099  [engine runWithEntrypoint:nil];
3100  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3101  nibName:nil
3102  bundle:nil];
3103  id mockApplication = OCMClassMock([UIApplication class]);
3104  OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateInactive);
3105  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
3106  XCTAssertFalse(viewController.stateIsActive);
3107  XCTAssertTrue(viewController.stateIsForeground);
3108  XCTAssertFalse(viewController.stateIsBackground);
3109 }
3110 
3111 - (void)testStatePropertiesWhenSceneStateIsActive {
3112  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
3113  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
3114  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
3115  });
3116  FlutterEngine* engine = [[FlutterEngine alloc] init];
3117  [engine runWithEntrypoint:nil];
3118  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3119  nibName:nil
3120  bundle:nil];
3121  id mockVC = OCMPartialMock(viewController);
3122  OCMStub([mockVC activationState]).andReturn(UISceneActivationStateForegroundActive);
3123  XCTAssertTrue(viewController.stateIsActive);
3124  XCTAssertTrue(viewController.stateIsForeground);
3125  XCTAssertFalse(viewController.stateIsBackground);
3126 
3127  [mockBundle stopMocking];
3128  [mockVC stopMocking];
3129 }
3130 
3131 - (void)testStatePropertiesWhenSceneStateIsBackground {
3132  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
3133  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
3134  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
3135  });
3136  FlutterEngine* engine = [[FlutterEngine alloc] init];
3137  [engine runWithEntrypoint:nil];
3138  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3139  nibName:nil
3140  bundle:nil];
3141  id mockVC = OCMPartialMock(viewController);
3142  OCMStub([mockVC activationState]).andReturn(UISceneActivationStateBackground);
3143  XCTAssertFalse(viewController.stateIsActive);
3144  XCTAssertFalse(viewController.stateIsForeground);
3145  XCTAssertTrue(viewController.stateIsBackground);
3146 
3147  [mockBundle stopMocking];
3148  [mockVC stopMocking];
3149 }
3150 
3151 - (void)testStatePropertiesWhenSceneStateIsInactive {
3152  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
3153  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
3154  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
3155  });
3156  FlutterEngine* engine = [[FlutterEngine alloc] init];
3157  [engine runWithEntrypoint:nil];
3158  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3159  nibName:nil
3160  bundle:nil];
3161  id mockVC = OCMPartialMock(viewController);
3162  OCMStub([mockVC activationState]).andReturn(UISceneActivationStateForegroundInactive);
3163  XCTAssertFalse(viewController.stateIsActive);
3164  XCTAssertTrue(viewController.stateIsForeground);
3165  XCTAssertFalse(viewController.stateIsBackground);
3166 
3167  [mockBundle stopMocking];
3168  [mockVC stopMocking];
3169 }
3170 
3171 - (void)testStatePropertiesWhenSceneStateIsUnattached {
3172  id mockBundle = OCMPartialMock([NSBundle mainBundle]);
3173  OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
3174  @"NSExtensionPointIdentifier" : @"com.apple.share-services"
3175  });
3176  FlutterEngine* engine = [[FlutterEngine alloc] init];
3177  [engine runWithEntrypoint:nil];
3178  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
3179  nibName:nil
3180  bundle:nil];
3181  id mockVC = OCMPartialMock(viewController);
3182  OCMStub([mockVC activationState]).andReturn(UISceneActivationStateUnattached);
3183  XCTAssertFalse(viewController.stateIsActive);
3184  XCTAssertFalse(viewController.stateIsForeground);
3185  XCTAssertFalse(viewController.stateIsBackground);
3186 
3187  [mockBundle stopMocking];
3188  [mockVC stopMocking];
3189 }
3190 
3191 - (void)testPerformImplicitEngineCallbacks {
3192  id mockRegistrant = OCMProtocolMock(@protocol(FlutterPluginRegistrant));
3193  id appDelegate = [[UIApplication sharedApplication] delegate];
3194  [appDelegate setMockLaunchEngine:self.mockEngine];
3195  UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Flutter" bundle:nil];
3196  XCTAssertTrue([appDelegate respondsToSelector:@selector(setPluginRegistrant:)]);
3197  [appDelegate setPluginRegistrant:mockRegistrant];
3199  (FlutterViewController*)[storyboard instantiateInitialViewController];
3200  [appDelegate setPluginRegistrant:nil];
3201  OCMVerify([mockRegistrant registerWithRegistry:viewController]);
3202  OCMVerify([self.mockEngine performImplicitEngineCallback]);
3203  [appDelegate setMockLaunchEngine:nil];
3204 }
3205 
3206 - (void)testPerformImplicitEngineCallbacksUsesAppLaunchEventFallbacks {
3207  id mockEngine = OCMClassMock([FlutterEngine class]);
3208  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
3209  nibName:nil
3210  bundle:nil];
3211  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
3212  OCMStub([mockEngine performImplicitEngineCallback]).andReturn(YES);
3213  OCMStub([viewControllerMock awokenFromNib]).andReturn(YES);
3214 
3215  id mockApplication = OCMClassMock([UIApplication class]);
3216  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
3217  FlutterAppDelegate* mockApplicationDelegate = OCMClassMock([FlutterAppDelegate class]);
3218  OCMStub([mockApplication delegate]).andReturn(mockApplicationDelegate);
3219  OCMStub([mockApplicationDelegate takeLaunchEngine]).andReturn(mockEngine);
3220 
3221  id mockScene = OCMClassMock([UIScene class]);
3222  id mockSceneDelegate = OCMProtocolMock(@protocol(UISceneDelegate));
3223  OCMStub([mockScene delegate]).andReturn(mockSceneDelegate);
3224  OCMStub([mockApplication connectedScenes]).andReturn([NSSet setWithObject:mockScene]);
3225 
3226  FlutterPluginAppLifeCycleDelegate* mockLifecycleDelegate =
3227  OCMClassMock([FlutterPluginAppLifeCycleDelegate class]);
3228  OCMStub([mockApplicationDelegate lifeCycleDelegate]).andReturn(mockLifecycleDelegate);
3229 
3230  [viewControllerMock sharedSetupWithProject:nil initialRoute:nil];
3231  OCMVerify([mockLifecycleDelegate sceneFallbackWillFinishLaunchingApplication:mockApplication]);
3232  OCMVerify([mockLifecycleDelegate sceneFallbackDidFinishLaunchingApplication:mockApplication]);
3233 }
3234 
3235 - (void)testPerformImplicitEngineCallbacksNoAppLaunchEventFallbacksWhenNoStoryboard {
3236  id mockEngine = OCMClassMock([FlutterEngine class]);
3237  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
3238  nibName:nil
3239  bundle:nil];
3240  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
3241  OCMStub([mockEngine performImplicitEngineCallback]).andReturn(YES);
3242  OCMStub([viewControllerMock awokenFromNib]).andReturn(NO);
3243 
3244  id mockApplication = OCMClassMock([UIApplication class]);
3245  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
3246  FlutterAppDelegate* mockApplicationDelegate = OCMClassMock([FlutterAppDelegate class]);
3247  OCMStub([mockApplication delegate]).andReturn(mockApplicationDelegate);
3248  OCMStub([mockApplicationDelegate takeLaunchEngine]).andReturn(mockEngine);
3249 
3250  id mockScene = OCMClassMock([UIScene class]);
3251  id mockSceneDelegate = OCMProtocolMock(@protocol(UISceneDelegate));
3252  OCMStub([mockScene delegate]).andReturn(mockSceneDelegate);
3253  OCMStub([mockApplication connectedScenes]).andReturn([NSSet setWithObject:mockScene]);
3254 
3255  FlutterPluginAppLifeCycleDelegate* mockLifecycleDelegate =
3256  OCMClassMock([FlutterPluginAppLifeCycleDelegate class]);
3257  OCMStub([mockApplicationDelegate lifeCycleDelegate]).andReturn(mockLifecycleDelegate);
3258 
3259  [viewControllerMock sharedSetupWithProject:nil initialRoute:nil];
3260  OCMReject([mockLifecycleDelegate sceneFallbackWillFinishLaunchingApplication:mockApplication]);
3261  OCMReject([mockLifecycleDelegate sceneFallbackDidFinishLaunchingApplication:mockApplication]);
3262 }
3263 
3264 - (void)testPerformImplicitEngineCallbacksNoAppLaunchEventFallbacksWhenNoScenes {
3265  id mockEngine = OCMClassMock([FlutterEngine class]);
3266  FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine
3267  nibName:nil
3268  bundle:nil];
3269  FlutterViewController* viewControllerMock = OCMPartialMock(viewController);
3270  OCMStub([mockEngine performImplicitEngineCallback]).andReturn(YES);
3271  OCMStub([viewControllerMock awokenFromNib]).andReturn(YES);
3272 
3273  id mockApplication = OCMClassMock([UIApplication class]);
3274  OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
3275  FlutterAppDelegate* mockApplicationDelegate = OCMClassMock([FlutterAppDelegate class]);
3276  OCMStub([mockApplication delegate]).andReturn(mockApplicationDelegate);
3277  OCMStub([mockApplicationDelegate takeLaunchEngine]).andReturn(mockEngine);
3278 
3279  FlutterPluginAppLifeCycleDelegate* mockLifecycleDelegate =
3280  OCMClassMock([FlutterPluginAppLifeCycleDelegate class]);
3281  OCMStub([mockApplicationDelegate lifeCycleDelegate]).andReturn(mockLifecycleDelegate);
3282 
3283  [viewControllerMock sharedSetupWithProject:nil initialRoute:nil];
3284  OCMReject([mockLifecycleDelegate sceneFallbackWillFinishLaunchingApplication:mockApplication]);
3285  OCMReject([mockLifecycleDelegate sceneFallbackDidFinishLaunchingApplication:mockApplication]);
3286 }
3287 
3288 - (void)testGrabLaunchEngine {
3289  id appDelegate = [[UIApplication sharedApplication] delegate];
3290  XCTAssertTrue([appDelegate respondsToSelector:@selector(setMockLaunchEngine:)]);
3291  [appDelegate setMockLaunchEngine:self.mockEngine];
3292  UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Flutter" bundle:nil];
3293  XCTAssertTrue(storyboard);
3295  (FlutterViewController*)[storyboard instantiateInitialViewController];
3296  XCTAssertTrue(viewController);
3297  XCTAssertTrue([viewController isKindOfClass:[FlutterViewController class]]);
3298  XCTAssertEqual(viewController.engine, self.mockEngine);
3299  [appDelegate setMockLaunchEngine:nil];
3300 }
3301 
3302 - (void)testDoesntGrabLaunchEngine {
3303  id appDelegate = [[UIApplication sharedApplication] delegate];
3304  XCTAssertTrue([appDelegate respondsToSelector:@selector(setMockLaunchEngine:)]);
3305  [appDelegate setMockLaunchEngine:self.mockEngine];
3306  FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
3307  XCTAssertNotNil(flutterViewController.engine);
3308  XCTAssertNotEqual(flutterViewController.engine, self.mockEngine);
3309  [appDelegate setMockLaunchEngine:nil];
3310 }
3311 
3312 @end
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterReply)(id _Nullable reply)
void(^ FlutterSendKeyEvent)(const FlutterKeyEvent &, _Nullable FlutterKeyEventCallback, void *_Nullable)
UITextSmartQuotesType smartQuotesType API_AVAILABLE(ios(11.0))
FlutterViewController * viewController
FlutterTextInputPlugin * textInputPlugin
void(^ FlutterKeyboardAnimationCallback)(NSTimeInterval targetTime)
NSNotificationName const FlutterViewControllerWillDealloc
SpringAnimation * keyboardSpringAnimation()
id< FlutterKeyboardInsetManagerDelegate > delegate
NSMutableArray< id< FlutterKeyPrimaryResponder > > * primaryResponders
FlutterVSyncClient * touchRateCorrectionVSyncClient
FlutterVSyncClient * keyboardAnimationVSyncClient
FlutterEngine * mockLaunchEngine
FlutterBasicMessageChannel * keyEventChannel
FlutterBasicMessageChannel * lifecycleChannel
FlutterViewController * viewController
BOOL runWithEntrypoint:(nullable NSString *NS_SWIFT_UI_ACTOR)
BOOL runWithEntrypoint:(nullable NSString *entrypoint)
FlutterBasicMessageChannel * lifecycleChannel
FlutterBasicMessageChannel * keyEventChannel
FlutterFMLTaskRunner * uiTaskRunner
A view controller that allows headless execution in the engine it creates.
NSObject< FlutterBinaryMessenger > * binaryMessenger
A FlutterEngine that saves received PointerDatas instead of forwarding to the shell.
const std::vector< flutter::PointerData > & capturedPointerData()
FlutterFMLTaskRunner * mockTaskRunner
void(^ updateViewportMetricsBlock)(CGFloat inset)