-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathFlutterViewController.mm
2629 lines (2277 loc) · 104 KB
/
FlutterViewController.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import <os/log.h>
#include <memory>
#include "flutter/common/constants.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/platform/darwin/platform_version.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "flutter/runtime/ptrace_check.h"
#include "flutter/shell/common/thread_host.h"
#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h"
#import "flutter/shell/platform/darwin/ios/platform_view_ios.h"
#import "flutter/shell/platform/embedder/embedder.h"
#import "flutter/third_party/spring_animation/spring_animation.h"
static constexpr int kMicrosecondsPerSecond = 1000 * 1000;
static constexpr CGFloat kScrollViewContentSize = 2.0;
static NSString* const kFlutterRestorationStateAppData = @"FlutterRestorationStateAppData";
NSNotificationName const FlutterSemanticsUpdateNotification = @"FlutterSemanticsUpdate";
NSNotificationName const FlutterViewControllerWillDealloc = @"FlutterViewControllerWillDealloc";
NSNotificationName const FlutterViewControllerHideHomeIndicator =
@"FlutterViewControllerHideHomeIndicator";
NSNotificationName const FlutterViewControllerShowHomeIndicator =
@"FlutterViewControllerShowHomeIndicator";
// Struct holding data to help adapt system mouse/trackpad events to embedder events.
typedef struct MouseState {
// Current coordinate of the mouse cursor in physical device pixels.
CGPoint location = CGPointZero;
// Last reported translation for an in-flight pan gesture in physical device pixels.
CGPoint last_translation = CGPointZero;
} MouseState;
// This is left a FlutterBinaryMessenger privately for now to give people a chance to notice the
// change. Unfortunately unless you have Werror turned on, incompatible pointers as arguments are
// just a warning.
@interface FlutterViewController () <FlutterBinaryMessenger, UIScrollViewDelegate>
// TODO(dkwingsmt): Make the view ID property public once the iOS shell
// supports multiple views.
// https://github.com/flutter/flutter/issues/138168
@property(nonatomic, readonly) int64_t viewIdentifier;
@property(nonatomic, readwrite, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI;
@property(nonatomic, assign) BOOL isHomeIndicatorHidden;
@property(nonatomic, assign) BOOL isPresentingViewControllerAnimating;
/**
* Whether we should ignore viewport metrics updates during rotation transition.
*/
@property(nonatomic, assign) BOOL shouldIgnoreViewportMetricsUpdatesDuringRotation;
/**
* Keyboard animation properties
*/
@property(nonatomic, assign) CGFloat targetViewInsetBottom;
@property(nonatomic, assign) CGFloat originalViewInsetBottom;
@property(nonatomic, retain) VSyncClient* keyboardAnimationVSyncClient;
@property(nonatomic, assign) BOOL keyboardAnimationIsShowing;
@property(nonatomic, assign) fml::TimePoint keyboardAnimationStartTime;
@property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground;
/// VSyncClient for touch events delivery frame rate correction.
///
/// On promotion devices(eg: iPhone13 Pro), the delivery frame rate of touch events is 60HZ
/// but the frame rate of rendering is 120HZ, which is different and will leads jitter and laggy.
/// With this VSyncClient, it can correct the delivery frame rate of touch events to let it keep
/// the same with frame rate of rendering.
@property(nonatomic, retain) VSyncClient* touchRateCorrectionVSyncClient;
/*
* Mouse and trackpad gesture recognizers
*/
// Mouse and trackpad hover
@property(nonatomic, retain)
UIHoverGestureRecognizer* hoverGestureRecognizer API_AVAILABLE(ios(13.4));
// Mouse wheel scrolling
@property(nonatomic, retain)
UIPanGestureRecognizer* discreteScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4));
// Trackpad and Magic Mouse scrolling
@property(nonatomic, retain)
UIPanGestureRecognizer* continuousScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4));
// Trackpad pinching
@property(nonatomic, retain)
UIPinchGestureRecognizer* pinchGestureRecognizer API_AVAILABLE(ios(13.4));
// Trackpad rotating
@property(nonatomic, retain)
UIRotationGestureRecognizer* rotationGestureRecognizer API_AVAILABLE(ios(13.4));
/**
* Creates and registers plugins used by this view controller.
*/
- (void)addInternalPlugins;
- (void)deregisterNotifications;
@end
@implementation FlutterViewController {
std::unique_ptr<fml::WeakNSObjectFactory<FlutterViewController>> _weakFactory;
fml::scoped_nsobject<FlutterEngine> _engine;
// We keep a separate reference to this and create it ahead of time because we want to be able to
// set up a shell along with its platform view before the view has to appear.
fml::scoped_nsobject<FlutterView> _flutterView;
fml::scoped_nsobject<UIView> _splashScreenView;
fml::ScopedBlock<void (^)(void)> _flutterViewRenderedCallback;
UIInterfaceOrientationMask _orientationPreferences;
UIStatusBarStyle _statusBarStyle;
flutter::ViewportMetrics _viewportMetrics;
BOOL _initialized;
BOOL _viewOpaque;
BOOL _engineNeedsLaunch;
fml::scoped_nsobject<NSMutableSet<NSNumber*>> _ongoingTouches;
// This scroll view is a workaround to accommodate iOS 13 and higher. There isn't a way to get
// touches on the status bar to trigger scrolling to the top of a scroll view. We place a
// UIScrollView with height zero and a content offset so we can get those events. See also:
// https://github.com/flutter/flutter/issues/35050
fml::scoped_nsobject<UIScrollView> _scrollView;
fml::scoped_nsobject<UIView> _keyboardAnimationView;
fml::scoped_nsobject<SpringAnimation> _keyboardSpringAnimation;
MouseState _mouseState;
// Timestamp after which a scroll inertia cancel event should be inferred.
NSTimeInterval _scrollInertiaEventStartline;
// When an iOS app is running in emulation on an Apple Silicon Mac, trackpad input goes through
// a translation layer, and events are not received with precise deltas. Due to this, we can't
// rely on checking for a stationary trackpad event. Fortunately, AppKit will send an event of
// type UIEventTypeScroll following a scroll when inertia should stop. This field is needed to
// estimate if such an event represents the natural end of scrolling inertia or a user-initiated
// cancellation.
NSTimeInterval _scrollInertiaEventAppKitDeadline;
}
@synthesize displayingFlutterUI = _displayingFlutterUI;
@synthesize prefersStatusBarHidden = _flutterPrefersStatusBarHidden;
@dynamic viewIdentifier;
#pragma mark - Manage and override all designated initializers
- (instancetype)initWithEngine:(FlutterEngine*)engine
nibName:(nullable NSString*)nibName
bundle:(nullable NSBundle*)nibBundle {
NSAssert(engine != nil, @"Engine is required");
self = [super initWithNibName:nibName bundle:nibBundle];
if (self) {
_viewOpaque = YES;
if (engine.viewController) {
FML_LOG(ERROR) << "The supplied FlutterEngine " << [[engine description] UTF8String]
<< " is already used with FlutterViewController instance "
<< [[engine.viewController description] UTF8String]
<< ". One instance of the FlutterEngine can only be attached to one "
"FlutterViewController at a time. Set FlutterEngine.viewController "
"to nil before attaching it to another FlutterViewController.";
}
_engine.reset([engine retain]);
_engineNeedsLaunch = NO;
_flutterView.reset([[FlutterView alloc] initWithDelegate:_engine
opaque:self.isViewOpaque
enableWideGamut:engine.project.isWideGamutEnabled]);
_weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterViewController>>(self);
_ongoingTouches.reset([[NSMutableSet alloc] init]);
[self performCommonViewControllerInitialization];
[engine setViewController:self];
}
return self;
}
- (instancetype)initWithProject:(FlutterDartProject*)project
nibName:(NSString*)nibName
bundle:(NSBundle*)nibBundle {
self = [super initWithNibName:nibName bundle:nibBundle];
if (self) {
[self sharedSetupWithProject:project initialRoute:nil];
}
return self;
}
- (instancetype)initWithProject:(FlutterDartProject*)project
initialRoute:(NSString*)initialRoute
nibName:(NSString*)nibName
bundle:(NSBundle*)nibBundle {
self = [super initWithNibName:nibName bundle:nibBundle];
if (self) {
[self sharedSetupWithProject:project initialRoute:initialRoute];
}
return self;
}
- (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
return [self initWithProject:nil nibName:nil bundle:nil];
}
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
self = [super initWithCoder:aDecoder];
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
if (!_engine) {
[self sharedSetupWithProject:nil initialRoute:nil];
}
}
- (instancetype)init {
return [self initWithProject:nil nibName:nil bundle:nil];
}
- (void)sharedSetupWithProject:(nullable FlutterDartProject*)project
initialRoute:(nullable NSString*)initialRoute {
// Need the project to get settings for the view. Initializing it here means
// the Engine class won't initialize it later.
if (!project) {
project = [[[FlutterDartProject alloc] init] autorelease];
}
FlutterView.forceSoftwareRendering = project.settings.enable_software_rendering;
_weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterViewController>>(self);
auto engine = fml::scoped_nsobject<FlutterEngine>{[[FlutterEngine alloc]
initWithName:@"io.flutter"
project:project
allowHeadlessExecution:self.engineAllowHeadlessExecution
restorationEnabled:[self restorationIdentifier] != nil]};
if (!engine) {
return;
}
_viewOpaque = YES;
_engine = engine;
_flutterView.reset([[FlutterView alloc] initWithDelegate:_engine
opaque:self.isViewOpaque
enableWideGamut:project.isWideGamutEnabled]);
[_engine.get() createShell:nil libraryURI:nil initialRoute:initialRoute];
_engineNeedsLaunch = YES;
_ongoingTouches.reset([[NSMutableSet alloc] init]);
[self loadDefaultSplashScreenView];
[self performCommonViewControllerInitialization];
}
- (BOOL)isViewOpaque {
return _viewOpaque;
}
- (void)setViewOpaque:(BOOL)value {
_viewOpaque = value;
if (_flutterView.get().layer.opaque != value) {
_flutterView.get().layer.opaque = value;
[_flutterView.get().layer setNeedsLayout];
}
}
#pragma mark - Common view controller initialization tasks
- (void)performCommonViewControllerInitialization {
if (_initialized) {
return;
}
_initialized = YES;
_orientationPreferences = UIInterfaceOrientationMaskAll;
_statusBarStyle = UIStatusBarStyleDefault;
[self setUpNotificationCenterObservers];
}
- (FlutterEngine*)engine {
return _engine.get();
}
- (fml::WeakNSObject<FlutterViewController>)getWeakNSObject {
return _weakFactory->GetWeakNSObject();
}
- (void)setUpNotificationCenterObservers {
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(onOrientationPreferencesUpdated:)
name:@(flutter::kOrientationUpdateNotificationName)
object:nil];
[center addObserver:self
selector:@selector(onPreferredStatusBarStyleUpdated:)
name:@(flutter::kOverlayStyleUpdateNotificationName)
object:nil];
#if APPLICATION_EXTENSION_API_ONLY
if (@available(iOS 13.0, *)) {
[self setUpSceneLifecycleNotifications:center];
} else {
[self setUpApplicationLifecycleNotifications:center];
}
#else
[self setUpApplicationLifecycleNotifications:center];
#endif
[center addObserver:self
selector:@selector(keyboardWillChangeFrame:)
name:UIKeyboardWillChangeFrameNotification
object:nil];
[center addObserver:self
selector:@selector(keyboardWillShowNotification:)
name:UIKeyboardWillShowNotification
object:nil];
[center addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityVoiceOverStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilitySwitchControlStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilitySpeakScreenStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityInvertColorsStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityReduceMotionStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityBoldTextStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityDarkerSystemColorsStatusDidChangeNotification
object:nil];
if (@available(iOS 13.0, *)) {
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityOnOffSwitchLabelsDidChangeNotification
object:nil];
}
[center addObserver:self
selector:@selector(onUserSettingsChanged:)
name:UIContentSizeCategoryDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onHideHomeIndicatorNotification:)
name:FlutterViewControllerHideHomeIndicator
object:nil];
[center addObserver:self
selector:@selector(onShowHomeIndicatorNotification:)
name:FlutterViewControllerShowHomeIndicator
object:nil];
}
- (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) {
[center addObserver:self
selector:@selector(sceneBecameActive:)
name:UISceneDidActivateNotification
object:nil];
[center addObserver:self
selector:@selector(sceneWillResignActive:)
name:UISceneWillDeactivateNotification
object:nil];
[center addObserver:self
selector:@selector(sceneWillDisconnect:)
name:UISceneDidDisconnectNotification
object:nil];
[center addObserver:self
selector:@selector(sceneDidEnterBackground:)
name:UISceneDidEnterBackgroundNotification
object:nil];
[center addObserver:self
selector:@selector(sceneWillEnterForeground:)
name:UISceneWillEnterForegroundNotification
object:nil];
}
- (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center {
[center addObserver:self
selector:@selector(applicationBecameActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:nil];
[center addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
- (void)setInitialRoute:(NSString*)route {
[[_engine.get() navigationChannel] invokeMethod:@"setInitialRoute" arguments:route];
}
- (void)popRoute {
[[_engine.get() navigationChannel] invokeMethod:@"popRoute" arguments:nil];
}
- (void)pushRoute:(NSString*)route {
[[_engine.get() navigationChannel] invokeMethod:@"pushRoute" arguments:route];
}
#pragma mark - Loading the view
static UIView* GetViewOrPlaceholder(UIView* existing_view) {
if (existing_view) {
return existing_view;
}
auto placeholder = [[[UIView alloc] init] autorelease];
placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
if (@available(iOS 13.0, *)) {
placeholder.backgroundColor = UIColor.systemBackgroundColor;
} else {
placeholder.backgroundColor = UIColor.whiteColor;
}
placeholder.autoresizesSubviews = YES;
// Only add the label when we know we have failed to enable tracing (and it was necessary).
// Otherwise, a spurious warning will be shown in cases where an engine cannot be initialized for
// other reasons.
if (flutter::GetTracingResult() == flutter::TracingResult::kDisabled) {
auto messageLabel = [[[UILabel alloc] init] autorelease];
messageLabel.numberOfLines = 0u;
messageLabel.textAlignment = NSTextAlignmentCenter;
messageLabel.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
messageLabel.text =
@"In iOS 14+, debug mode Flutter apps can only be launched from Flutter tooling, "
@"IDEs with Flutter plugins or from Xcode.\n\nAlternatively, build in profile or release "
@"modes to enable launching from the home screen.";
[placeholder addSubview:messageLabel];
}
return placeholder;
}
- (void)loadView {
self.view = GetViewOrPlaceholder(_flutterView.get());
self.view.multipleTouchEnabled = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self installSplashScreenViewIfNecessary];
UIScrollView* scrollView = [[UIScrollView alloc] init];
scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// The color shouldn't matter since it is offscreen.
scrollView.backgroundColor = UIColor.whiteColor;
scrollView.delegate = self;
// This is an arbitrary small size.
scrollView.contentSize = CGSizeMake(kScrollViewContentSize, kScrollViewContentSize);
// This is an arbitrary offset that is not CGPointZero.
scrollView.contentOffset = CGPointMake(kScrollViewContentSize, kScrollViewContentSize);
[self.view addSubview:scrollView];
_scrollView.reset(scrollView);
}
- (flutter::PointerData)generatePointerDataForFake {
flutter::PointerData pointer_data;
pointer_data.Clear();
pointer_data.kind = flutter::PointerData::DeviceKind::kTouch;
// `UITouch.timestamp` is defined as seconds since system startup. Synthesized events can get this
// time with `NSProcessInfo.systemUptime`. See
// https://developer.apple.com/documentation/uikit/uitouch/1618144-timestamp?language=objc
pointer_data.time_stamp = [[NSProcessInfo processInfo] systemUptime] * kMicrosecondsPerSecond;
return pointer_data;
}
static void SendFakeTouchEvent(UIScreen* screen,
FlutterEngine* engine,
CGPoint location,
flutter::PointerData::Change change) {
const CGFloat scale = screen.scale;
flutter::PointerData pointer_data = [[engine viewController] generatePointerDataForFake];
pointer_data.physical_x = location.x * scale;
pointer_data.physical_y = location.y * scale;
auto packet = std::make_unique<flutter::PointerDataPacket>(/*count=*/1);
pointer_data.change = change;
packet->SetPointerData(0, pointer_data);
[engine dispatchPointerDataPacket:std::move(packet)];
}
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView*)scrollView {
if (!_engine) {
return NO;
}
CGPoint statusBarPoint = CGPointZero;
UIScreen* screen = [self flutterScreenIfViewLoaded];
if (screen) {
SendFakeTouchEvent(screen, _engine.get(), statusBarPoint, flutter::PointerData::Change::kDown);
SendFakeTouchEvent(screen, _engine.get(), statusBarPoint, flutter::PointerData::Change::kUp);
}
return NO;
}
#pragma mark - Managing launch views
- (void)installSplashScreenViewIfNecessary {
// Show the launch screen view again on top of the FlutterView if available.
// This launch screen view will be removed once the first Flutter frame is rendered.
if (_splashScreenView && (self.isBeingPresented || self.isMovingToParentViewController)) {
[_splashScreenView.get() removeFromSuperview];
_splashScreenView.reset();
return;
}
// Use the property getter to initialize the default value.
UIView* splashScreenView = self.splashScreenView;
if (splashScreenView == nil) {
return;
}
splashScreenView.frame = self.view.bounds;
[self.view addSubview:splashScreenView];
}
+ (BOOL)automaticallyNotifiesObserversOfDisplayingFlutterUI {
return NO;
}
- (void)setDisplayingFlutterUI:(BOOL)displayingFlutterUI {
if (_displayingFlutterUI != displayingFlutterUI) {
if (displayingFlutterUI == YES) {
if (!self.viewIfLoaded.window) {
return;
}
}
[self willChangeValueForKey:@"displayingFlutterUI"];
_displayingFlutterUI = displayingFlutterUI;
[self didChangeValueForKey:@"displayingFlutterUI"];
}
}
- (void)callViewRenderedCallback {
self.displayingFlutterUI = YES;
if (_flutterViewRenderedCallback != nil) {
_flutterViewRenderedCallback.get()();
_flutterViewRenderedCallback.reset();
}
}
- (void)removeSplashScreenView:(dispatch_block_t _Nullable)onComplete {
NSAssert(_splashScreenView, @"The splash screen view must not be null");
UIView* splashScreen = [_splashScreenView.get() retain];
_splashScreenView.reset();
[UIView animateWithDuration:0.2
animations:^{
splashScreen.alpha = 0;
}
completion:^(BOOL finished) {
[splashScreen removeFromSuperview];
[splashScreen release];
if (onComplete) {
onComplete();
}
}];
}
- (void)installFirstFrameCallback {
if (!_engine) {
return;
}
fml::WeakPtr<flutter::PlatformViewIOS> weakPlatformView = [_engine.get() platformView];
if (!weakPlatformView) {
return;
}
// Start on the platform thread.
weakPlatformView->SetNextFrameCallback([weakSelf = [self getWeakNSObject],
platformTaskRunner = [_engine.get() platformTaskRunner],
rasterTaskRunner = [_engine.get() rasterTaskRunner]]() {
FML_DCHECK(rasterTaskRunner->RunsTasksOnCurrentThread());
// Get callback on raster thread and jump back to platform thread.
platformTaskRunner->PostTask([weakSelf]() {
if (weakSelf) {
fml::scoped_nsobject<FlutterViewController> flutterViewController(
[(FlutterViewController*)weakSelf.get() retain]);
if (flutterViewController) {
if (flutterViewController.get()->_splashScreenView) {
[flutterViewController removeSplashScreenView:^{
[flutterViewController callViewRenderedCallback];
}];
} else {
[flutterViewController callViewRenderedCallback];
}
}
}
});
});
}
#pragma mark - Properties
- (int64_t)viewIdentifier {
// TODO(dkwingsmt): Fill the view ID property with the correct value once the
// iOS shell supports multiple views.
return flutter::kFlutterImplicitViewId;
}
- (UIView*)splashScreenView {
if (!_splashScreenView) {
return nil;
}
return _splashScreenView.get();
}
- (UIView*)keyboardAnimationView {
return _keyboardAnimationView.get();
}
- (SpringAnimation*)keyboardSpringAnimation {
return _keyboardSpringAnimation.get();
}
- (BOOL)loadDefaultSplashScreenView {
NSString* launchscreenName =
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"UILaunchStoryboardName"];
if (launchscreenName == nil) {
return NO;
}
UIView* splashView = [self splashScreenFromStoryboard:launchscreenName];
if (!splashView) {
splashView = [self splashScreenFromXib:launchscreenName];
}
if (!splashView) {
return NO;
}
self.splashScreenView = splashView;
return YES;
}
- (UIView*)splashScreenFromStoryboard:(NSString*)name {
UIStoryboard* storyboard = nil;
@try {
storyboard = [UIStoryboard storyboardWithName:name bundle:nil];
} @catch (NSException* exception) {
return nil;
}
if (storyboard) {
UIViewController* splashScreenViewController = [storyboard instantiateInitialViewController];
return splashScreenViewController.view;
}
return nil;
}
- (UIView*)splashScreenFromXib:(NSString*)name {
NSArray* objects = nil;
@try {
objects = [[NSBundle mainBundle] loadNibNamed:name owner:self options:nil];
} @catch (NSException* exception) {
return nil;
}
if ([objects count] != 0) {
UIView* view = [objects objectAtIndex:0];
return view;
}
return nil;
}
- (void)setSplashScreenView:(UIView*)view {
if (!view) {
// Special case: user wants to remove the splash screen view.
if (_splashScreenView) {
[self removeSplashScreenView:nil];
}
return;
}
_splashScreenView.reset([view retain]);
_splashScreenView.get().autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
- (void)setFlutterViewDidRenderCallback:(void (^)(void))callback {
_flutterViewRenderedCallback.reset(callback, fml::scoped_policy::OwnershipPolicy::kRetain);
}
#pragma mark - Surface creation and teardown updates
- (void)surfaceUpdated:(BOOL)appeared {
if (!_engine) {
return;
}
// NotifyCreated/NotifyDestroyed are synchronous and require hops between the UI and raster
// thread.
if (appeared) {
[self installFirstFrameCallback];
[_engine.get() platformViewsController]->SetFlutterView(_flutterView.get());
[_engine.get() platformViewsController]->SetFlutterViewController(self);
[_engine.get() iosPlatformView]->NotifyCreated();
} else {
self.displayingFlutterUI = NO;
[_engine.get() iosPlatformView]->NotifyDestroyed();
[_engine.get() platformViewsController]->SetFlutterView(nullptr);
[_engine.get() platformViewsController]->SetFlutterViewController(nullptr);
}
}
#pragma mark - UIViewController lifecycle notifications
- (void)viewDidLoad {
TRACE_EVENT0("flutter", "viewDidLoad");
if (_engine && _engineNeedsLaunch) {
[_engine.get() launchEngine:nil libraryURI:nil entrypointArgs:nil];
[_engine.get() setViewController:self];
_engineNeedsLaunch = NO;
} else if ([_engine.get() viewController] == self) {
[_engine.get() attachView];
}
// Register internal plugins.
[self addInternalPlugins];
// Create a vsync client to correct delivery frame rate of touch events if needed.
[self createTouchRateCorrectionVSyncClientIfNeeded];
if (@available(iOS 13.4, *)) {
_hoverGestureRecognizer =
[[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(hoverEvent:)];
_hoverGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_hoverGestureRecognizer];
_discreteScrollingPanGestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(discreteScrollEvent:)];
_discreteScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete;
// Disallowing all touch types. If touch events are allowed here, touches to the screen will be
// consumed by the UIGestureRecognizer instead of being passed through to flutter via
// touchesBegan. Trackpad and mouse scrolls are sent by the platform as scroll events rather
// than touch events, so they will still be received.
_discreteScrollingPanGestureRecognizer.allowedTouchTypes = @[];
_discreteScrollingPanGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_discreteScrollingPanGestureRecognizer];
_continuousScrollingPanGestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self
action:@selector(continuousScrollEvent:)];
_continuousScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskContinuous;
_continuousScrollingPanGestureRecognizer.allowedTouchTypes = @[];
_continuousScrollingPanGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_continuousScrollingPanGestureRecognizer];
_pinchGestureRecognizer =
[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchEvent:)];
_pinchGestureRecognizer.allowedTouchTypes = @[];
_pinchGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_pinchGestureRecognizer];
_rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] init];
_rotationGestureRecognizer.allowedTouchTypes = @[];
_rotationGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_rotationGestureRecognizer];
}
[super viewDidLoad];
}
- (void)addInternalPlugins {
self.keyboardManager = [[[FlutterKeyboardManager alloc] init] autorelease];
fml::WeakNSObject<FlutterViewController> weakSelf = [self getWeakNSObject];
FlutterSendKeyEvent sendEvent =
^(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* userData) {
if (weakSelf) {
[weakSelf.get()->_engine.get() sendKeyEvent:event callback:callback userData:userData];
}
};
[self.keyboardManager addPrimaryResponder:[[[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:sendEvent] autorelease]];
FlutterChannelKeyResponder* responder = [[[FlutterChannelKeyResponder alloc]
initWithChannel:self.engine.keyEventChannel] autorelease];
[self.keyboardManager addPrimaryResponder:responder];
FlutterTextInputPlugin* textInputPlugin = self.engine.textInputPlugin;
if (textInputPlugin != nil) {
[self.keyboardManager addSecondaryResponder:textInputPlugin];
}
if ([_engine.get() viewController] == self) {
[textInputPlugin setUpIndirectScribbleInteraction:self];
}
}
- (void)removeInternalPlugins {
self.keyboardManager = nil;
}
- (void)viewWillAppear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewWillAppear");
if ([_engine.get() viewController] == self) {
// Send platform settings to Flutter, e.g., platform brightness.
[self onUserSettingsChanged:nil];
// Only recreate surface on subsequent appearances when viewport metrics are known.
// First time surface creation is done on viewDidLayoutSubviews.
if (_viewportMetrics.physical_width) {
[self surfaceUpdated:YES];
}
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.inactive"];
[[_engine.get() restorationPlugin] markRestorationComplete];
}
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewDidAppear");
if ([_engine.get() viewController] == self) {
[self onUserSettingsChanged:nil];
[self onAccessibilityStatusChanged:nil];
BOOL stateIsActive = YES;
#if APPLICATION_EXTENSION_API_ONLY
if (@available(iOS 13.0, *)) {
stateIsActive = self.flutterWindowSceneIfViewLoaded.activationState ==
UISceneActivationStateForegroundActive;
}
#else
stateIsActive = UIApplication.sharedApplication.applicationState == UIApplicationStateActive;
#endif
if (stateIsActive) {
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.resumed"];
}
}
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewWillDisappear");
if ([_engine.get() viewController] == self) {
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.inactive"];
}
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewDidDisappear");
if ([_engine.get() viewController] == self) {
[self invalidateKeyboardAnimationVSyncClient];
[self ensureViewportMetricsIsCorrect];
[self surfaceUpdated:NO];
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.paused"];
[self flushOngoingTouches];
[_engine.get() notifyLowMemory];
}
[super viewDidDisappear:animated];
}
- (void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
// We delay the viewport metrics update for half of rotation transition duration, to address
// a bug with distorted aspect ratio.
// See: https://github.com/flutter/flutter/issues/16322
//
// This approach does not fully resolve all distortion problem. But instead, it reduces the
// rotation distortion roughly from 4x to 2x. The most distorted frames occur in the middle
// of the transition when it is rotating the fastest, making it hard to notice.
NSTimeInterval transitionDuration = coordinator.transitionDuration;
// Do not delay viewport metrics update if zero transition duration.
if (transitionDuration == 0) {
return;
}
_shouldIgnoreViewportMetricsUpdatesDuringRotation = YES;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
static_cast<int64_t>(transitionDuration / 2.0 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
// `viewWillTransitionToSize` is only called after the previous rotation is
// complete. So there won't be race condition for this flag.
_shouldIgnoreViewportMetricsUpdatesDuringRotation = NO;
[self updateViewportMetricsIfNeeded];
});
}
- (void)flushOngoingTouches {
if (_engine && _ongoingTouches.get().count > 0) {
auto packet = std::make_unique<flutter::PointerDataPacket>(_ongoingTouches.get().count);
size_t pointer_index = 0;
// If the view controller is going away, we want to flush cancel all the ongoing
// touches to the framework so nothing gets orphaned.
for (NSNumber* device in _ongoingTouches.get()) {
// Create fake PointerData to balance out each previously started one for the framework.
flutter::PointerData pointer_data = [self generatePointerDataForFake];
pointer_data.change = flutter::PointerData::Change::kCancel;
pointer_data.device = device.longLongValue;
pointer_data.pointer_identifier = 0;
pointer_data.view_id = self.viewIdentifier;
// Anything we put here will be arbitrary since there are no touches.
pointer_data.physical_x = 0;
pointer_data.physical_y = 0;
pointer_data.physical_delta_x = 0.0;
pointer_data.physical_delta_y = 0.0;
pointer_data.pressure = 1.0;
pointer_data.pressure_max = 1.0;
packet->SetPointerData(pointer_index++, pointer_data);
}
[_ongoingTouches removeAllObjects];
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
}
}
- (void)deregisterNotifications {
[[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc
object:self
userInfo:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dealloc {
// It will be destroyed and invalidate its weak pointers
// before any other members are destroyed.
_weakFactory.reset();
[self removeInternalPlugins];
[self deregisterNotifications];
[self invalidateKeyboardAnimationVSyncClient];
[self invalidateTouchRateCorrectionVSyncClient];
_scrollView.get().delegate = nil;
_hoverGestureRecognizer.delegate = nil;
[_hoverGestureRecognizer release];
_discreteScrollingPanGestureRecognizer.delegate = nil;
[_discreteScrollingPanGestureRecognizer release];
_continuousScrollingPanGestureRecognizer.delegate = nil;
[_continuousScrollingPanGestureRecognizer release];
_pinchGestureRecognizer.delegate = nil;
[_pinchGestureRecognizer release];
_rotationGestureRecognizer.delegate = nil;
[_rotationGestureRecognizer release];
[super dealloc];
}
#pragma mark - Application lifecycle notifications
- (void)applicationBecameActive:(NSNotification*)notification {
TRACE_EVENT0("flutter", "applicationBecameActive");
[self appOrSceneBecameActive];
}
- (void)applicationWillResignActive:(NSNotification*)notification {