-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
FlutterEngine.mm
1566 lines (1344 loc) · 60.8 KB
/
FlutterEngine.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/FlutterEngine_Internal.h"
#include <memory>
#include "flutter/common/constants.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/platform/darwin/platform_version.h"
#include "flutter/fml/platform/darwin/weak_nsobject.h"
#include "flutter/fml/trace_event.h"
#include "flutter/runtime/ptrace_check.h"
#include "flutter/shell/common/engine.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/common/variable_refresh_rate_display.h"
#import "flutter/shell/platform/darwin/common/command_line.h"
#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.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/darwin/ios/rendering_api_selection.h"
#include "flutter/shell/profiling/sampling_profiler.h"
/// Inheriting ThreadConfigurer and use iOS platform thread API to configure the thread priorities
/// Using iOS platform thread API to configure thread priority
static void IOSPlatformThreadConfigSetter(const fml::Thread::ThreadConfig& config) {
// set thread name
fml::Thread::SetCurrentThreadName(config);
// set thread priority
switch (config.priority) {
case fml::Thread::ThreadPriority::kBackground: {
pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0);
[[NSThread currentThread] setThreadPriority:0];
break;
}
case fml::Thread::ThreadPriority::kNormal: {
pthread_set_qos_class_self_np(QOS_CLASS_DEFAULT, 0);
[[NSThread currentThread] setThreadPriority:0.5];
break;
}
case fml::Thread::ThreadPriority::kRaster:
case fml::Thread::ThreadPriority::kDisplay: {
pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
[[NSThread currentThread] setThreadPriority:1.0];
sched_param param;
int policy;
pthread_t thread = pthread_self();
if (!pthread_getschedparam(thread, &policy, ¶m)) {
param.sched_priority = 50;
pthread_setschedparam(thread, policy, ¶m);
}
break;
}
}
}
#pragma mark - Public exported constants
NSString* const FlutterDefaultDartEntrypoint = nil;
NSString* const FlutterDefaultInitialRoute = nil;
#pragma mark - Internal constants
NSString* const kFlutterEngineWillDealloc = @"FlutterEngineWillDealloc";
NSString* const kFlutterKeyDataChannel = @"flutter/keydata";
static constexpr int kNumProfilerSamplesPerSec = 5;
@interface FlutterEngineRegistrar : NSObject <FlutterPluginRegistrar>
@property(nonatomic, assign) FlutterEngine* flutterEngine;
- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine;
@end
@interface FlutterEngine () <FlutterIndirectScribbleDelegate,
FlutterUndoManagerDelegate,
FlutterTextInputDelegate,
FlutterBinaryMessenger,
FlutterTextureRegistry>
// Maintains a dictionary of plugin names that have registered with the engine. Used by
// FlutterEngineRegistrar to implement a FlutterPluginRegistrar.
@property(nonatomic, readonly) NSMutableDictionary* pluginPublications;
@property(nonatomic, readonly) NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* registrars;
@property(nonatomic, readwrite, copy) NSString* isolateId;
@property(nonatomic, copy) NSString* initialRoute;
@property(nonatomic, retain) id<NSObject> flutterViewControllerWillDeallocObserver;
#pragma mark - Embedder API properties
@property(nonatomic, assign) BOOL enableEmbedderAPI;
// Function pointers for interacting with the embedder.h API.
@property(nonatomic) FlutterEngineProcTable& embedderAPI;
@end
@implementation FlutterEngine {
fml::scoped_nsobject<FlutterDartProject> _dartProject;
std::shared_ptr<flutter::ThreadHost> _threadHost;
std::unique_ptr<flutter::Shell> _shell;
NSString* _labelPrefix;
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory;
fml::WeakNSObject<FlutterViewController> _viewController;
fml::scoped_nsobject<FlutterDartVMServicePublisher> _publisher;
std::shared_ptr<flutter::FlutterPlatformViewsController> _platformViewsController;
flutter::IOSRenderingAPI _renderingApi;
std::shared_ptr<flutter::ProfilerMetricsIOS> _profiler_metrics;
std::shared_ptr<flutter::SamplingProfiler> _profiler;
// Channels
fml::scoped_nsobject<FlutterPlatformPlugin> _platformPlugin;
fml::scoped_nsobject<FlutterTextInputPlugin> _textInputPlugin;
fml::scoped_nsobject<FlutterUndoManagerPlugin> _undoManagerPlugin;
fml::scoped_nsobject<FlutterSpellCheckPlugin> _spellCheckPlugin;
fml::scoped_nsobject<FlutterRestorationPlugin> _restorationPlugin;
fml::scoped_nsobject<FlutterMethodChannel> _localizationChannel;
fml::scoped_nsobject<FlutterMethodChannel> _navigationChannel;
fml::scoped_nsobject<FlutterMethodChannel> _restorationChannel;
fml::scoped_nsobject<FlutterMethodChannel> _platformChannel;
fml::scoped_nsobject<FlutterMethodChannel> _platformViewsChannel;
fml::scoped_nsobject<FlutterMethodChannel> _textInputChannel;
fml::scoped_nsobject<FlutterMethodChannel> _undoManagerChannel;
fml::scoped_nsobject<FlutterMethodChannel> _scribbleChannel;
fml::scoped_nsobject<FlutterMethodChannel> _spellCheckChannel;
fml::scoped_nsobject<FlutterBasicMessageChannel> _lifecycleChannel;
fml::scoped_nsobject<FlutterBasicMessageChannel> _systemChannel;
fml::scoped_nsobject<FlutterBasicMessageChannel> _settingsChannel;
fml::scoped_nsobject<FlutterBasicMessageChannel> _keyEventChannel;
fml::scoped_nsobject<FlutterMethodChannel> _screenshotChannel;
int64_t _nextTextureId;
BOOL _allowHeadlessExecution;
BOOL _restorationEnabled;
FlutterBinaryMessengerRelay* _binaryMessenger;
FlutterTextureRegistryRelay* _textureRegistry;
std::unique_ptr<flutter::ConnectionCollection> _connections;
}
- (instancetype)init {
return [self initWithName:@"FlutterEngine" project:nil allowHeadlessExecution:YES];
}
- (instancetype)initWithName:(NSString*)labelPrefix {
return [self initWithName:labelPrefix project:nil allowHeadlessExecution:YES];
}
- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project {
return [self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
}
- (instancetype)initWithName:(NSString*)labelPrefix
project:(FlutterDartProject*)project
allowHeadlessExecution:(BOOL)allowHeadlessExecution {
return [self initWithName:labelPrefix
project:project
allowHeadlessExecution:allowHeadlessExecution
restorationEnabled:NO];
}
- (instancetype)initWithName:(NSString*)labelPrefix
project:(FlutterDartProject*)project
allowHeadlessExecution:(BOOL)allowHeadlessExecution
restorationEnabled:(BOOL)restorationEnabled {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
NSAssert(labelPrefix, @"labelPrefix is required");
_restorationEnabled = restorationEnabled;
_allowHeadlessExecution = allowHeadlessExecution;
_labelPrefix = [labelPrefix copy];
_weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(self);
if (project == nil) {
_dartProject.reset([[FlutterDartProject alloc] init]);
} else {
_dartProject.reset([project retain]);
}
_enableEmbedderAPI = _dartProject.get().settings.enable_embedder_api;
if (_enableEmbedderAPI) {
NSLog(@"============== iOS: enable_embedder_api is on ==============");
_embedderAPI.struct_size = sizeof(FlutterEngineProcTable);
FlutterEngineGetProcAddresses(&_embedderAPI);
}
if (!EnableTracingIfNecessary([_dartProject.get() settings])) {
NSLog(
@"Cannot create a FlutterEngine instance in debug mode without Flutter tooling or "
@"Xcode.\n\nTo launch in debug mode in iOS 14+, run flutter run from Flutter tools, run "
@"from an IDE with a Flutter IDE plugin or run the iOS project from Xcode.\nAlternatively "
@"profile and release mode apps can be launched from the home screen.");
[self release];
return nil;
}
_pluginPublications = [[NSMutableDictionary alloc] init];
_registrars = [[NSMutableDictionary alloc] init];
[self recreatePlatformViewController];
_binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self];
_textureRegistry = [[FlutterTextureRegistryRelay alloc] initWithParent:self];
_connections.reset(new flutter::ConnectionCollection());
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(onMemoryWarning:)
name:UIApplicationDidReceiveMemoryWarningNotification
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(onLocaleUpdated:)
name:NSCurrentLocaleDidChangeNotification
object:nil];
return self;
}
- (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) {
[center addObserver:self
selector:@selector(sceneWillEnterForeground:)
name:UISceneWillEnterForegroundNotification
object:nil];
[center addObserver:self
selector:@selector(sceneDidEnterBackground:)
name:UISceneDidEnterBackgroundNotification
object:nil];
}
- (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center {
[center addObserver:self
selector:@selector(applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[center addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
- (void)recreatePlatformViewController {
_renderingApi = flutter::GetRenderingAPIForProcess(FlutterView.forceSoftwareRendering);
_platformViewsController.reset(new flutter::FlutterPlatformViewsController());
}
- (flutter::IOSRenderingAPI)platformViewsRenderingAPI {
return _renderingApi;
}
- (void)dealloc {
/// Notify plugins of dealloc. This should happen first in dealloc since the
/// plugins may be talking to things like the binaryMessenger.
[_pluginPublications enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL* stop) {
if ([object respondsToSelector:@selector(detachFromEngineForRegistrar:)]) {
NSObject<FlutterPluginRegistrar>* registrar = self.registrars[key];
[object detachFromEngineForRegistrar:registrar];
}
}];
[[NSNotificationCenter defaultCenter] postNotificationName:kFlutterEngineWillDealloc
object:self
userInfo:nil];
// It will be destroyed and invalidate its weak pointers
// before any other members are destroyed.
_weakFactory.reset();
/// nil out weak references.
[_registrars
enumerateKeysAndObjectsUsingBlock:^(id key, FlutterEngineRegistrar* registrar, BOOL* stop) {
registrar.flutterEngine = nil;
}];
[_labelPrefix release];
[_initialRoute release];
[_pluginPublications release];
[_registrars release];
_binaryMessenger.parent = nil;
_textureRegistry.parent = nil;
[_binaryMessenger release];
[_textureRegistry release];
_textureRegistry = nil;
[_isolateId release];
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
if (_flutterViewControllerWillDeallocObserver) {
[center removeObserver:_flutterViewControllerWillDeallocObserver];
[_flutterViewControllerWillDeallocObserver release];
}
[center removeObserver:self];
[super dealloc];
}
- (flutter::Shell&)shell {
FML_DCHECK(_shell);
return *_shell;
}
- (fml::WeakNSObject<FlutterEngine>)getWeakNSObject {
return _weakFactory->GetWeakNSObject();
}
- (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics {
if (!self.platformView) {
return;
}
self.platformView->SetViewportMetrics(flutter::kFlutterImplicitViewId, viewportMetrics);
}
- (void)dispatchPointerDataPacket:(std::unique_ptr<flutter::PointerDataPacket>)packet {
if (!self.platformView) {
return;
}
self.platformView->DispatchPointerDataPacket(std::move(packet));
}
- (fml::WeakPtr<flutter::PlatformView>)platformView {
FML_DCHECK(_shell);
return _shell->GetPlatformView();
}
- (flutter::PlatformViewIOS*)iosPlatformView {
FML_DCHECK(_shell);
return static_cast<flutter::PlatformViewIOS*>(_shell->GetPlatformView().get());
}
- (fml::RefPtr<fml::TaskRunner>)platformTaskRunner {
FML_DCHECK(_shell);
return _shell->GetTaskRunners().GetPlatformTaskRunner();
}
- (fml::RefPtr<fml::TaskRunner>)uiTaskRunner {
FML_DCHECK(_shell);
return _shell->GetTaskRunners().GetUITaskRunner();
}
- (fml::RefPtr<fml::TaskRunner>)rasterTaskRunner {
FML_DCHECK(_shell);
return _shell->GetTaskRunners().GetRasterTaskRunner();
}
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(FlutterKeyEventCallback)callback
userData:(void*)userData API_AVAILABLE(ios(13.4)) {
if (@available(iOS 13.4, *)) {
} else {
return;
}
if (!self.platformView) {
return;
}
const char* character = event.character;
flutter::KeyData key_data;
key_data.Clear();
key_data.timestamp = (uint64_t)event.timestamp;
switch (event.type) {
case kFlutterKeyEventTypeUp:
key_data.type = flutter::KeyEventType::kUp;
break;
case kFlutterKeyEventTypeDown:
key_data.type = flutter::KeyEventType::kDown;
break;
case kFlutterKeyEventTypeRepeat:
key_data.type = flutter::KeyEventType::kRepeat;
break;
}
key_data.physical = event.physical;
key_data.logical = event.logical;
key_data.synthesized = event.synthesized;
auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character);
NSData* message = [NSData dataWithBytes:packet->data().data() length:packet->data().size()];
auto response = ^(NSData* reply) {
if (callback == nullptr) {
return;
}
BOOL handled = FALSE;
if (reply.length == 1 && *reinterpret_cast<const uint8_t*>(reply.bytes) == 1) {
handled = TRUE;
}
callback(handled, userData);
};
[self sendOnChannel:kFlutterKeyDataChannel message:message binaryReply:response];
}
- (void)ensureSemanticsEnabled {
self.iosPlatformView->SetSemanticsEnabled(true);
}
- (void)setViewController:(FlutterViewController*)viewController {
FML_DCHECK(self.iosPlatformView);
_viewController = viewController ? [viewController getWeakNSObject]
: fml::WeakNSObject<FlutterViewController>();
self.iosPlatformView->SetOwnerViewController(_viewController);
[self maybeSetupPlatformViewChannels];
[self updateDisplays];
_textInputPlugin.get().viewController = viewController;
if (viewController) {
__block FlutterEngine* blockSelf = self;
self.flutterViewControllerWillDeallocObserver =
[[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc
object:viewController
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification* note) {
[blockSelf notifyViewControllerDeallocated];
}];
} else {
self.flutterViewControllerWillDeallocObserver = nil;
[self notifyLowMemory];
}
}
- (void)attachView {
self.iosPlatformView->attachView();
}
- (void)setFlutterViewControllerWillDeallocObserver:(id<NSObject>)observer {
if (observer != _flutterViewControllerWillDeallocObserver) {
if (_flutterViewControllerWillDeallocObserver) {
[[NSNotificationCenter defaultCenter]
removeObserver:_flutterViewControllerWillDeallocObserver];
[_flutterViewControllerWillDeallocObserver release];
}
_flutterViewControllerWillDeallocObserver = [observer retain];
}
}
- (void)notifyViewControllerDeallocated {
[[self lifecycleChannel] sendMessage:@"AppLifecycleState.detached"];
_textInputPlugin.get().viewController = nil;
if (!_allowHeadlessExecution) {
[self destroyContext];
} else if (_shell) {
flutter::PlatformViewIOS* platform_view = [self iosPlatformView];
if (platform_view) {
platform_view->SetOwnerViewController({});
}
}
[_textInputPlugin.get() resetViewResponder];
_viewController.reset();
}
- (void)destroyContext {
[self resetChannels];
self.isolateId = nil;
_shell.reset();
_profiler.reset();
_threadHost.reset();
_platformViewsController.reset();
}
- (FlutterViewController*)viewController {
if (!_viewController) {
return nil;
}
return _viewController.get();
}
- (FlutterPlatformPlugin*)platformPlugin {
return _platformPlugin.get();
}
- (std::shared_ptr<flutter::FlutterPlatformViewsController>&)platformViewsController {
return _platformViewsController;
}
- (FlutterTextInputPlugin*)textInputPlugin {
return _textInputPlugin.get();
}
- (FlutterUndoManagerPlugin*)undoManagerPlugin {
return _undoManagerPlugin.get();
}
- (FlutterRestorationPlugin*)restorationPlugin {
return _restorationPlugin.get();
}
- (FlutterMethodChannel*)localizationChannel {
return _localizationChannel.get();
}
- (FlutterMethodChannel*)navigationChannel {
return _navigationChannel.get();
}
- (FlutterMethodChannel*)restorationChannel {
return _restorationChannel.get();
}
- (FlutterMethodChannel*)platformChannel {
return _platformChannel.get();
}
- (FlutterMethodChannel*)textInputChannel {
return _textInputChannel.get();
}
- (FlutterMethodChannel*)undoManagerChannel {
return _undoManagerChannel.get();
}
- (FlutterMethodChannel*)scribbleChannel {
return _scribbleChannel.get();
}
- (FlutterMethodChannel*)spellCheckChannel {
return _spellCheckChannel.get();
}
- (FlutterBasicMessageChannel*)lifecycleChannel {
return _lifecycleChannel.get();
}
- (FlutterBasicMessageChannel*)systemChannel {
return _systemChannel.get();
}
- (FlutterBasicMessageChannel*)settingsChannel {
return _settingsChannel.get();
}
- (FlutterBasicMessageChannel*)keyEventChannel {
return _keyEventChannel.get();
}
- (NSURL*)observatoryUrl {
return [_publisher.get() url];
}
- (NSURL*)vmServiceUrl {
return [_publisher.get() url];
}
- (void)resetChannels {
_localizationChannel.reset();
_navigationChannel.reset();
_restorationChannel.reset();
_platformChannel.reset();
_platformViewsChannel.reset();
_textInputChannel.reset();
_undoManagerChannel.reset();
_scribbleChannel.reset();
_lifecycleChannel.reset();
_systemChannel.reset();
_settingsChannel.reset();
_keyEventChannel.reset();
_spellCheckChannel.reset();
}
- (void)startProfiler {
FML_DCHECK(!_threadHost->name_prefix.empty());
_profiler_metrics = std::make_shared<flutter::ProfilerMetricsIOS>();
_profiler = std::make_shared<flutter::SamplingProfiler>(
_threadHost->name_prefix.c_str(), _threadHost->profiler_thread->GetTaskRunner(),
[self]() { return self->_profiler_metrics->GenerateSample(); }, kNumProfilerSamplesPerSec);
_profiler->Start();
}
// If you add a channel, be sure to also update `resetChannels`.
// Channels get a reference to the engine, and therefore need manual
// cleanup for proper collection.
- (void)setUpChannels {
// This will be invoked once the shell is done setting up and the isolate ID
// for the UI isolate is available.
fml::WeakNSObject<FlutterEngine> weakSelf = [self getWeakNSObject];
[_binaryMessenger setMessageHandlerOnChannel:@"flutter/isolate"
binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) {
if (weakSelf) {
weakSelf.get().isolateId =
[[FlutterStringCodec sharedInstance] decode:message];
}
}];
_localizationChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/localization"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]]);
_navigationChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/navigation"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]]);
if ([_initialRoute length] > 0) {
// Flutter isn't ready to receive this method call yet but the channel buffer will cache this.
[_navigationChannel invokeMethod:@"setInitialRoute" arguments:_initialRoute];
[_initialRoute release];
_initialRoute = nil;
}
_restorationChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/restoration"
binaryMessenger:self.binaryMessenger
codec:[FlutterStandardMethodCodec sharedInstance]]);
_platformChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/platform"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]]);
_platformViewsChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/platform_views"
binaryMessenger:self.binaryMessenger
codec:[FlutterStandardMethodCodec sharedInstance]]);
_textInputChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/textinput"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]]);
_undoManagerChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/undomanager"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]]);
_scribbleChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/scribble"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]]);
_spellCheckChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/spellcheck"
binaryMessenger:self.binaryMessenger
codec:[FlutterStandardMethodCodec sharedInstance]]);
_lifecycleChannel.reset([[FlutterBasicMessageChannel alloc]
initWithName:@"flutter/lifecycle"
binaryMessenger:self.binaryMessenger
codec:[FlutterStringCodec sharedInstance]]);
_systemChannel.reset([[FlutterBasicMessageChannel alloc]
initWithName:@"flutter/system"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMessageCodec sharedInstance]]);
_settingsChannel.reset([[FlutterBasicMessageChannel alloc]
initWithName:@"flutter/settings"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMessageCodec sharedInstance]]);
_keyEventChannel.reset([[FlutterBasicMessageChannel alloc]
initWithName:@"flutter/keyevent"
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMessageCodec sharedInstance]]);
FlutterTextInputPlugin* textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:self];
_textInputPlugin.reset(textInputPlugin);
textInputPlugin.indirectScribbleDelegate = self;
[textInputPlugin setUpIndirectScribbleInteraction:self.viewController];
FlutterUndoManagerPlugin* undoManagerPlugin =
[[FlutterUndoManagerPlugin alloc] initWithDelegate:self];
_undoManagerPlugin.reset(undoManagerPlugin);
_platformPlugin.reset([[FlutterPlatformPlugin alloc] initWithEngine:[self getWeakNSObject]]);
_restorationPlugin.reset([[FlutterRestorationPlugin alloc]
initWithChannel:_restorationChannel.get()
restorationEnabled:_restorationEnabled]);
_spellCheckPlugin.reset([[FlutterSpellCheckPlugin alloc] init]);
_screenshotChannel.reset([[FlutterMethodChannel alloc]
initWithName:@"flutter/screenshot"
binaryMessenger:self.binaryMessenger
codec:[FlutterStandardMethodCodec sharedInstance]]);
[_screenshotChannel.get()
setMethodCallHandler:^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) {
if (!(weakSelf.get() && weakSelf.get()->_shell && weakSelf.get()->_shell->IsSetup())) {
return result([FlutterError
errorWithCode:@"invalid_state"
message:@"Requesting screenshot while engine is not running."
details:nil]);
}
flutter::Rasterizer::Screenshot screenshot =
[weakSelf.get() screenshot:flutter::Rasterizer::ScreenshotType::SurfaceData
base64Encode:NO];
if (!screenshot.data) {
return result([FlutterError errorWithCode:@"failure"
message:@"Unable to get screenshot."
details:nil]);
}
// TODO(gaaclarke): Find way to eliminate this data copy.
NSData* data = [NSData dataWithBytes:screenshot.data->writable_data()
length:screenshot.data->size()];
NSString* format = [NSString stringWithUTF8String:screenshot.format.c_str()];
NSNumber* width = @(screenshot.frame_size.fWidth);
NSNumber* height = @(screenshot.frame_size.fHeight);
return result(@[ width, height, format ?: [NSNull null], data ]);
}];
}
- (void)maybeSetupPlatformViewChannels {
if (_shell && self.shell.IsSetup()) {
FlutterPlatformPlugin* platformPlugin = _platformPlugin.get();
[_platformChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[platformPlugin handleMethodCall:call result:result];
}];
fml::WeakNSObject<FlutterEngine> weakSelf = [self getWeakNSObject];
[_platformViewsChannel.get()
setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
if (weakSelf) {
weakSelf.get().platformViewsController->OnMethodCall(call, result);
}
}];
FlutterTextInputPlugin* textInputPlugin = _textInputPlugin.get();
[_textInputChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[textInputPlugin handleMethodCall:call result:result];
}];
FlutterUndoManagerPlugin* undoManagerPlugin = _undoManagerPlugin.get();
[_undoManagerChannel.get()
setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[undoManagerPlugin handleMethodCall:call result:result];
}];
FlutterSpellCheckPlugin* spellCheckPlugin = _spellCheckPlugin.get();
[_spellCheckChannel.get()
setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[spellCheckPlugin handleMethodCall:call result:result];
}];
}
}
- (flutter::Rasterizer::Screenshot)screenshot:(flutter::Rasterizer::ScreenshotType)type
base64Encode:(bool)base64Encode {
return self.shell.Screenshot(type, base64Encode);
}
- (void)launchEngine:(NSString*)entrypoint
libraryURI:(NSString*)libraryOrNil
entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
// Launch the Dart application with the inferred run configuration.
self.shell.RunEngine([_dartProject.get() runConfigurationForEntrypoint:entrypoint
libraryOrNil:libraryOrNil
entrypointArgs:entrypointArgs]);
}
- (void)setUpShell:(std::unique_ptr<flutter::Shell>)shell
withVMServicePublication:(BOOL)doesVMServicePublication {
_shell = std::move(shell);
[self setUpChannels];
[self onLocaleUpdated:nil];
[self updateDisplays];
_publisher.reset([[FlutterDartVMServicePublisher alloc]
initWithEnableVMServicePublication:doesVMServicePublication]);
[self maybeSetupPlatformViewChannels];
_shell->SetGpuAvailability(_isGpuDisabled ? flutter::GpuAvailability::kUnavailable
: flutter::GpuAvailability::kAvailable);
}
+ (BOOL)isProfilerEnabled {
bool profilerEnabled = false;
#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) || \
(FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE)
profilerEnabled = true;
#endif
return profilerEnabled;
}
+ (NSString*)generateThreadLabel:(NSString*)labelPrefix {
static size_t s_shellCount = 0;
return [NSString stringWithFormat:@"%@.%zu", labelPrefix, ++s_shellCount];
}
+ (flutter::ThreadHost)makeThreadHost:(NSString*)threadLabel {
// The current thread will be used as the platform thread. Ensure that the message loop is
// initialized.
fml::MessageLoop::EnsureInitializedForCurrentThread();
uint32_t threadHostType = flutter::ThreadHost::Type::kUi | flutter::ThreadHost::Type::kRaster |
flutter::ThreadHost::Type::kIo;
if ([FlutterEngine isProfilerEnabled]) {
threadHostType = threadHostType | flutter::ThreadHost::Type::kProfiler;
}
flutter::ThreadHost::ThreadHostConfig host_config(threadLabel.UTF8String, threadHostType,
IOSPlatformThreadConfigSetter);
host_config.ui_config =
fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
flutter::ThreadHost::Type::kUi, threadLabel.UTF8String),
fml::Thread::ThreadPriority::kDisplay);
host_config.raster_config =
fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
flutter::ThreadHost::Type::kRaster, threadLabel.UTF8String),
fml::Thread::ThreadPriority::kRaster);
host_config.io_config =
fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
flutter::ThreadHost::Type::kIo, threadLabel.UTF8String),
fml::Thread::ThreadPriority::kNormal);
return (flutter::ThreadHost){host_config};
}
static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSString* libraryURI) {
if (libraryURI) {
FML_DCHECK(entrypoint) << "Must specify entrypoint if specifying library";
settings->advisory_script_entrypoint = entrypoint.UTF8String;
settings->advisory_script_uri = libraryURI.UTF8String;
} else if (entrypoint) {
settings->advisory_script_entrypoint = entrypoint.UTF8String;
settings->advisory_script_uri = std::string("main.dart");
} else {
settings->advisory_script_entrypoint = std::string("main");
settings->advisory_script_uri = std::string("main.dart");
}
}
- (BOOL)createShell:(NSString*)entrypoint
libraryURI:(NSString*)libraryURI
initialRoute:(NSString*)initialRoute {
if (_shell != nullptr) {
FML_LOG(WARNING) << "This FlutterEngine was already invoked.";
return NO;
}
self.initialRoute = initialRoute;
auto settings = [_dartProject.get() settings];
if (initialRoute != nil) {
self.initialRoute = initialRoute;
} else if (settings.route.empty() == false) {
self.initialRoute = [NSString stringWithUTF8String:settings.route.c_str()];
}
FlutterView.forceSoftwareRendering = settings.enable_software_rendering;
auto platformData = [_dartProject.get() defaultPlatformData];
SetEntryPoint(&settings, entrypoint, libraryURI);
NSString* threadLabel = [FlutterEngine generateThreadLabel:_labelPrefix];
_threadHost = std::make_shared<flutter::ThreadHost>();
*_threadHost = [FlutterEngine makeThreadHost:threadLabel];
// Lambda captures by pointers to ObjC objects are fine here because the
// create call is synchronous.
flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
[self](flutter::Shell& shell) {
[self recreatePlatformViewController];
return std::make_unique<flutter::PlatformViewIOS>(
shell, self->_renderingApi, self->_platformViewsController, shell.GetTaskRunners(),
shell.GetConcurrentWorkerTaskRunner(), shell.GetIsGpuDisabledSyncSwitch());
};
flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
[](flutter::Shell& shell) { return std::make_unique<flutter::Rasterizer>(shell); };
flutter::TaskRunners task_runners(threadLabel.UTF8String, // label
fml::MessageLoop::GetCurrent().GetTaskRunner(), // platform
_threadHost->raster_thread->GetTaskRunner(), // raster
_threadHost->ui_thread->GetTaskRunner(), // ui
_threadHost->io_thread->GetTaskRunner() // io
);
#if APPLICATION_EXTENSION_API_ONLY
if (@available(iOS 13.0, *)) {
_isGpuDisabled = self.viewController.flutterWindowSceneIfViewLoaded.activationState ==
UISceneActivationStateBackground;
} else {
// [UIApplication sharedApplication API is not available for app extension.
// We intialize the shell assuming the GPU is required.
_isGpuDisabled = NO;
}
#else
_isGpuDisabled =
[UIApplication sharedApplication].applicationState == UIApplicationStateBackground;
#endif
// Create the shell. This is a blocking operation.
std::unique_ptr<flutter::Shell> shell = flutter::Shell::Create(
/*platform_data=*/platformData,
/*task_runners=*/task_runners,
/*settings=*/settings,
/*on_create_platform_view=*/on_create_platform_view,
/*on_create_rasterizer=*/on_create_rasterizer,
/*is_gpu_disabled=*/_isGpuDisabled);
if (shell == nullptr) {
FML_LOG(ERROR) << "Could not start a shell FlutterEngine with entrypoint: "
<< entrypoint.UTF8String;
} else {
// TODO(vashworth): Remove once done debugging https://github.com/flutter/flutter/issues/129836
FML_LOG(INFO) << "Enabled VM Service Publication: " << settings.enable_vm_service_publication;
[self setUpShell:std::move(shell)
withVMServicePublication:settings.enable_vm_service_publication];
if ([FlutterEngine isProfilerEnabled]) {
[self startProfiler];
}
}
return _shell != nullptr;
}
- (void)updateDisplays {
if (!_shell) {
// Tests may do this.
return;
}
auto vsync_waiter = _shell->GetVsyncWaiter().lock();
auto vsync_waiter_ios = std::static_pointer_cast<flutter::VsyncWaiterIOS>(vsync_waiter);
std::vector<std::unique_ptr<flutter::Display>> displays;
auto screen_size = UIScreen.mainScreen.nativeBounds.size;
auto scale = UIScreen.mainScreen.scale;
displays.push_back(std::make_unique<flutter::VariableRefreshRateDisplay>(
0, vsync_waiter_ios, screen_size.width, screen_size.height, scale));
_shell->OnDisplayUpdates(std::move(displays));
}
- (BOOL)run {
return [self runWithEntrypoint:FlutterDefaultDartEntrypoint
libraryURI:nil
initialRoute:FlutterDefaultInitialRoute];
}
- (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
return [self runWithEntrypoint:entrypoint
libraryURI:libraryURI
initialRoute:FlutterDefaultInitialRoute];
}
- (BOOL)runWithEntrypoint:(NSString*)entrypoint {
return [self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:FlutterDefaultInitialRoute];
}
- (BOOL)runWithEntrypoint:(NSString*)entrypoint initialRoute:(NSString*)initialRoute {
return [self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:initialRoute];
}
- (BOOL)runWithEntrypoint:(NSString*)entrypoint
libraryURI:(NSString*)libraryURI
initialRoute:(NSString*)initialRoute {
return [self runWithEntrypoint:entrypoint
libraryURI:libraryURI
initialRoute:initialRoute
entrypointArgs:nil];
}
- (BOOL)runWithEntrypoint:(NSString*)entrypoint
libraryURI:(NSString*)libraryURI
initialRoute:(NSString*)initialRoute
entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
if ([self createShell:entrypoint libraryURI:libraryURI initialRoute:initialRoute]) {
[self launchEngine:entrypoint libraryURI:libraryURI entrypointArgs:entrypointArgs];
}
return _shell != nullptr;
}
- (void)notifyLowMemory {
if (_shell) {
_shell->NotifyLowMemoryWarning();
}
[_systemChannel sendMessage:@{@"type" : @"memoryPressure"}];
}
#pragma mark - Text input delegate
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
updateEditingClient:(int)client
withState:(NSDictionary*)state {
[_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingState"
arguments:@[ @(client), state ]];
}
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
updateEditingClient:(int)client
withState:(NSDictionary*)state
withTag:(NSString*)tag {
[_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingStateWithTag"
arguments:@[ @(client), @{tag : state} ]];
}