5 #include "common/settings.h"
6 #define FML_USED_ON_EMBEDDER
12 #include "flutter/common/constants.h"
13 #include "flutter/fml/message_loop.h"
14 #include "flutter/fml/platform/darwin/platform_version.h"
15 #include "flutter/fml/trace_event.h"
16 #include "flutter/runtime/ptrace_check.h"
17 #include "flutter/shell/common/engine.h"
18 #include "flutter/shell/common/platform_view.h"
19 #include "flutter/shell/common/shell.h"
20 #include "flutter/shell/common/switches.h"
21 #include "flutter/shell/common/thread_host.h"
22 #include "flutter/shell/common/variable_refresh_rate_display.h"
23 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
26 #import "flutter/shell/platform/darwin/ios/InternalFlutterSwift/InternalFlutterSwift.h"
44 #include "flutter/shell/profiling/sampling_profiler.h"
52 fml::Thread::SetCurrentThreadName(config);
55 switch (config.priority) {
56 case fml::Thread::ThreadPriority::kBackground: {
57 pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0);
58 [[NSThread currentThread] setThreadPriority:0];
61 case fml::Thread::ThreadPriority::kNormal: {
62 pthread_set_qos_class_self_np(QOS_CLASS_DEFAULT, 0);
63 [[NSThread currentThread] setThreadPriority:0.5];
66 case fml::Thread::ThreadPriority::kRaster:
67 case fml::Thread::ThreadPriority::kDisplay: {
68 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
69 [[NSThread currentThread] setThreadPriority:1.0];
72 pthread_t thread = pthread_self();
73 if (!pthread_getschedparam(thread, &policy, ¶m)) {
74 param.sched_priority = 50;
75 pthread_setschedparam(thread, policy, ¶m);
82 #pragma mark - Public exported constants
87 #pragma mark - Internal constants
103 #pragma mark - Properties
106 @property(nonatomic, readonly, copy) NSString* labelPrefix;
107 @property(nonatomic, readonly, assign) BOOL allowHeadlessExecution;
108 @property(nonatomic, readonly, assign) BOOL restorationEnabled;
114 @property(nonatomic, readonly) NSMutableDictionary* pluginPublications;
115 @property(nonatomic, readonly) NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* registrars;
117 @property(nonatomic, readwrite, copy) NSString*
isolateId;
118 @property(nonatomic, copy) NSString* initialRoute;
119 @property(nonatomic, strong) id<NSObject> flutterViewControllerWillDeallocObserver;
121 @property(nonatomic, strong) FlutterConnectionCollection* connections;
122 @property(nonatomic, assign) int64_t nextTextureId;
124 #pragma mark - Channel properties
146 #pragma mark - Embedder API properties
155 std::shared_ptr<flutter::ThreadHost> _threadHost;
165 - (int64_t)engineIdentifier {
166 return reinterpret_cast<int64_t
>((__bridge
void*)
self);
169 - (instancetype)init {
170 return [
self initWithName:@"FlutterEngine" project:nil allowHeadlessExecution:YES];
173 - (instancetype)initWithName:(NSString*)labelPrefix {
174 return [
self initWithName:labelPrefix project:nil allowHeadlessExecution:YES];
177 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
178 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
181 - (instancetype)initWithName:(NSString*)labelPrefix
183 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
184 return [
self initWithName:labelPrefix
186 allowHeadlessExecution:allowHeadlessExecution
187 restorationEnabled:NO];
190 - (instancetype)initWithName:(NSString*)labelPrefix
192 allowHeadlessExecution:(BOOL)allowHeadlessExecution
193 restorationEnabled:(BOOL)restorationEnabled {
195 NSAssert(
self,
@"Super init cannot be nil");
196 NSAssert(labelPrefix,
@"labelPrefix is required");
199 _allowHeadlessExecution = allowHeadlessExecution;
200 _labelPrefix = [labelPrefix copy];
203 _enableEmbedderAPI = _dartProject.
settings.enable_embedder_api;
204 if (_enableEmbedderAPI) {
205 NSLog(
@"============== iOS: enable_embedder_api is on ==============");
206 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
207 FlutterEngineGetProcAddresses(&_embedderAPI);
210 if (!EnableTracingIfNecessary(_dartProject.settings)) {
212 @"Cannot create a FlutterEngine instance in debug mode without Flutter tooling or "
213 @"Xcode.\n\nTo launch in debug mode in iOS 14+, run flutter run from Flutter tools, run "
214 @"from an IDE with a Flutter IDE plugin or run the iOS project from Xcode.\nAlternatively "
215 @"profile and release mode apps can be launched from the home screen.");
219 _pluginPublications = [[NSMutableDictionary alloc] init];
220 _registrars = [[NSMutableDictionary alloc] init];
221 [
self recreatePlatformViewsController];
224 _connections = [[FlutterConnectionCollection alloc] init];
226 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
227 [center addObserver:self
228 selector:@selector(onMemoryWarning:)
229 name:UIApplicationDidReceiveMemoryWarningNotification
232 [
self setUpLifecycleNotifications:center];
234 [center addObserver:self
235 selector:@selector(onLocaleUpdated:)
236 name:NSCurrentLocaleDidChangeNotification
243 NSAssert([[NSThread currentThread] isMainThread],
@"Must be called on the main thread.");
244 return (__bridge
FlutterEngine*)
reinterpret_cast<void*
>(identifier);
247 - (void)setUpLifecycleNotifications:(NSNotificationCenter*)center {
250 [center addObserver:self
251 selector:@selector(sceneWillEnterForeground:)
252 name:UISceneWillEnterForegroundNotification
254 [center addObserver:self
255 selector:@selector(sceneDidEnterBackground:)
256 name:UISceneDidEnterBackgroundNotification
260 [center addObserver:self
261 selector:@selector(applicationWillEnterForeground:)
262 name:UIApplicationWillEnterForegroundNotification
264 [center addObserver:self
265 selector:@selector(applicationDidEnterBackground:)
266 name:UIApplicationDidEnterBackgroundNotification
270 - (void)recreatePlatformViewsController {
275 - (
flutter::IOSRenderingAPI)platformViewsRenderingAPI {
282 [_pluginPublications enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL* stop) {
283 if ([object respondsToSelector:@selector(detachFromEngineForRegistrar:)]) {
284 NSObject<FlutterPluginRegistrar>* registrar = self.registrars[key];
285 [object detachFromEngineForRegistrar:registrar];
293 enumerateKeysAndObjectsUsingBlock:^(id key, FlutterEngineRegistrar* registrar, BOOL* stop) {
294 registrar.flutterEngine = nil;
300 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
301 if (_flutterViewControllerWillDeallocObserver) {
302 [center removeObserver:_flutterViewControllerWillDeallocObserver];
304 [center removeObserver:self];
312 - (void)updateViewportMetrics:(
flutter::ViewportMetrics)viewportMetrics {
313 if (!
self.platformView) {
316 self.platformView->SetViewportMetrics(flutter::kFlutterImplicitViewId, viewportMetrics);
319 - (void)dispatchPointerDataPacket:(std::unique_ptr<
flutter::PointerDataPacket>)packet {
320 if (!
self.platformView) {
323 self.platformView->DispatchPointerDataPacket(std::move(packet));
326 - (void)installFirstFrameCallback:(
void (^)(
void))block {
327 if (!
self.platformView) {
332 self.
platformView->SetNextFrameCallback([weakSelf, block] {
337 FML_DCHECK(strongSelf.platformTaskRunner);
338 FML_DCHECK(strongSelf.rasterTaskRunner);
339 FML_DCHECK(strongSelf.rasterTaskRunner->RunsTasksOnCurrentThread());
341 strongSelf.platformTaskRunner->PostTask([block]() { block(); });
345 - (void)enableSemantics:(BOOL)enabled withFlags:(int64_t)flags {
346 if (!
self.platformView) {
350 self.platformView->SetAccessibilityFeatures(flags);
353 - (void)notifyViewCreated {
354 if (!
self.platformView) {
357 self.platformView->NotifyCreated();
360 - (void)notifyViewDestroyed {
361 if (!
self.platformView) {
364 self.platformView->NotifyDestroyed();
367 - (
flutter::PlatformViewIOS*)platformView {
374 - (
fml::RefPtr<fml::TaskRunner>)platformTaskRunner {
378 return _shell->GetTaskRunners().GetPlatformTaskRunner();
381 - (
fml::RefPtr<fml::TaskRunner>)uiTaskRunner {
385 return _shell->GetTaskRunners().GetUITaskRunner();
388 - (
fml::RefPtr<fml::TaskRunner>)rasterTaskRunner {
392 return _shell->GetTaskRunners().GetRasterTaskRunner();
395 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
396 callback:(FlutterKeyEventCallback)callback
397 userData:(
void*)userData API_AVAILABLE(ios(13.4)) {
398 if (@available(iOS 13.4, *)) {
402 if (!
self.platformView) {
405 const char* character =
event.character;
407 flutter::KeyData key_data;
409 key_data.timestamp = (uint64_t)event.timestamp;
410 switch (event.type) {
411 case kFlutterKeyEventTypeUp:
412 key_data.type = flutter::KeyEventType::kUp;
414 case kFlutterKeyEventTypeDown:
415 key_data.type = flutter::KeyEventType::kDown;
417 case kFlutterKeyEventTypeRepeat:
418 key_data.type = flutter::KeyEventType::kRepeat;
421 key_data.physical =
event.physical;
422 key_data.logical =
event.logical;
423 key_data.synthesized =
event.synthesized;
425 auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character);
426 NSData* message = [NSData dataWithBytes:packet->data().data() length:packet->data().size()];
428 auto response = ^(NSData* reply) {
429 if (callback ==
nullptr) {
432 BOOL handled = FALSE;
433 if (reply.length == 1 && *
reinterpret_cast<const uint8_t*
>(reply.bytes) == 1) {
436 callback(handled, userData);
439 [
self sendOnChannel:kFlutterKeyDataChannel message:message binaryReply:response];
442 - (void)ensureSemanticsEnabled {
443 if (!
self.platformView) {
446 self.platformView->SetSemanticsEnabled(
true);
450 FML_DCHECK(
self.platformView);
452 self.platformView->SetOwnerViewController(_viewController);
453 [
self maybeSetupPlatformViewChannels];
454 [
self updateDisplays];
459 self.flutterViewControllerWillDeallocObserver =
460 [[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc
461 object:viewController
462 queue:[NSOperationQueue mainQueue]
463 usingBlock:^(NSNotification* note) {
464 [weakSelf notifyViewControllerDeallocated];
467 self.flutterViewControllerWillDeallocObserver = nil;
468 [
self notifyLowMemory];
473 FML_DCHECK(
self.platformView);
474 self.platformView->attachView();
477 - (void)setFlutterViewControllerWillDeallocObserver:(
id<NSObject>)observer {
478 if (observer != _flutterViewControllerWillDeallocObserver) {
479 if (_flutterViewControllerWillDeallocObserver) {
480 [[NSNotificationCenter defaultCenter]
481 removeObserver:_flutterViewControllerWillDeallocObserver];
483 _flutterViewControllerWillDeallocObserver = observer;
487 - (void)notifyViewControllerDeallocated {
488 [
self.lifecycleChannel sendMessage:@"AppLifecycleState.detached"];
489 self.textInputPlugin.viewController = nil;
490 if (!
self.allowHeadlessExecution) {
491 [
self destroyContext];
492 }
else if (
self.platformView) {
493 self.platformView->SetOwnerViewController({});
495 [
self.textInputPlugin resetViewResponder];
496 _viewController = nil;
499 - (void)destroyContext {
500 [
self resetChannels];
501 self.isolateId = nil;
505 _platformViewsController = nil;
508 - (NSURL*)vmServiceUrl {
509 return self.publisher.url;
512 - (void)resetChannels {
513 self.localizationChannel = nil;
514 self.navigationChannel = nil;
515 self.restorationChannel = nil;
516 self.platformChannel = nil;
517 self.platformViewsChannel = nil;
518 self.textInputChannel = nil;
519 self.undoManagerChannel = nil;
520 self.scribbleChannel = nil;
521 self.lifecycleChannel = nil;
522 self.systemChannel = nil;
523 self.settingsChannel = nil;
524 self.keyEventChannel = nil;
525 self.spellCheckChannel = nil;
528 - (void)startProfiler {
529 FML_DCHECK(!_threadHost->name_prefix.empty());
530 _profiler = std::make_shared<flutter::SamplingProfiler>(
531 _threadHost->name_prefix.c_str(), _threadHost->profiler_thread->GetTaskRunner(),
533 flutter::ProfilerMetricsIOS profiler_metrics;
534 return profiler_metrics.GenerateSample();
543 - (void)setUpChannels {
547 [_binaryMessenger setMessageHandlerOnChannel:@"flutter/isolate"
548 binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) {
557 binaryMessenger:self.binaryMessenger
560 self.navigationChannel =
562 binaryMessenger:self.binaryMessenger
565 if ([_initialRoute length] > 0) {
567 [
self.navigationChannel invokeMethod:@"setInitialRoute" arguments:_initialRoute];
571 self.restorationChannel =
573 binaryMessenger:self.binaryMessenger
576 self.platformChannel =
578 binaryMessenger:self.binaryMessenger
581 self.platformViewsChannel =
583 binaryMessenger:self.binaryMessenger
586 self.textInputChannel =
588 binaryMessenger:self.binaryMessenger
591 self.undoManagerChannel =
593 binaryMessenger:self.binaryMessenger
596 self.scribbleChannel =
598 binaryMessenger:self.binaryMessenger
601 self.spellCheckChannel =
603 binaryMessenger:self.binaryMessenger
606 self.lifecycleChannel =
608 binaryMessenger:self.binaryMessenger
613 binaryMessenger:self.binaryMessenger
616 self.settingsChannel =
618 binaryMessenger:self.binaryMessenger
621 self.keyEventChannel =
623 binaryMessenger:self.binaryMessenger
627 self.textInputPlugin.indirectScribbleDelegate =
self;
628 [
self.textInputPlugin setUpIndirectScribbleInteraction:self.viewController];
633 self.restorationPlugin =
635 restorationEnabled:self.restorationEnabled];
638 self.screenshotChannel =
640 binaryMessenger:self.binaryMessenger
643 [
self.screenshotChannel setMethodCallHandler:^(FlutterMethodCall* _Nonnull call,
644 FlutterResult _Nonnull result) {
646 if (!(strongSelf && strongSelf->_shell && strongSelf->_shell->IsSetup())) {
649 message:@"Requesting screenshot while engine is not running."
652 flutter::Rasterizer::Screenshot screenshot =
653 [strongSelf screenshot:flutter::Rasterizer::ScreenshotType::SurfaceData base64Encode:NO];
654 if (!screenshot.data) {
656 message:@"Unable to get screenshot."
660 NSData* data = [NSData dataWithBytes:screenshot.data->writable_data()
661 length:screenshot.data->size()];
662 NSString* format = [NSString stringWithUTF8String:screenshot.format.c_str()];
663 NSNumber* width = @(screenshot.frame_size.fWidth);
664 NSNumber* height = @(screenshot.frame_size.fHeight);
665 return result(@[ width, height, format ?: [NSNull null], data ]);
669 - (void)maybeSetupPlatformViewChannels {
670 if (
_shell &&
self.shell.IsSetup()) {
673 [
self.platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
674 [weakSelf.platformPlugin handleMethodCall:call result:result];
677 [
self.platformViewsChannel
678 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
680 [weakSelf.platformViewsController onMethodCall:call result:result];
684 [
self.textInputChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
685 [weakSelf.textInputPlugin handleMethodCall:call result:result];
688 [
self.undoManagerChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
689 [weakSelf.undoManagerPlugin handleMethodCall:call result:result];
692 [
self.spellCheckChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
693 [weakSelf.spellCheckPlugin handleMethodCall:call result:result];
698 - (
flutter::Rasterizer::Screenshot)screenshot:(
flutter::Rasterizer::ScreenshotType)type
699 base64Encode:(
bool)base64Encode {
700 return self.shell.Screenshot(type, base64Encode);
703 - (void)launchEngine:(NSString*)entrypoint
704 libraryURI:(NSString*)libraryOrNil
705 entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
707 flutter::RunConfiguration configuration =
708 [
self.dartProject runConfigurationForEntrypoint:entrypoint
709 libraryOrNil:libraryOrNil
710 entrypointArgs:entrypointArgs];
712 configuration.SetEngineId(
self.engineIdentifier);
713 self.shell.RunEngine(std::move(configuration));
716 - (void)setUpShell:(std::unique_ptr<
flutter::Shell>)shell
717 withVMServicePublication:(BOOL)doesVMServicePublication {
718 _shell = std::move(shell);
719 [
self setUpChannels];
720 [
self onLocaleUpdated:nil];
721 [
self updateDisplays];
723 initWithEnableVMServicePublication:doesVMServicePublication];
724 [
self maybeSetupPlatformViewChannels];
725 _shell->SetGpuAvailability(_isGpuDisabled ? flutter::GpuAvailability::kUnavailable
726 : flutter::GpuAvailability::kAvailable);
729 + (BOOL)isProfilerEnabled {
730 bool profilerEnabled =
false;
731 #if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) || \
732 (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE)
733 profilerEnabled =
true;
735 return profilerEnabled;
738 + (NSString*)generateThreadLabel:(NSString*)labelPrefix {
739 static size_t s_shellCount = 0;
740 return [NSString stringWithFormat:@"%@.%zu", labelPrefix, ++s_shellCount];
743 static flutter::ThreadHost MakeThreadHost(NSString* thread_label,
744 const flutter::Settings& settings) {
747 fml::MessageLoop::EnsureInitializedForCurrentThread();
749 uint32_t threadHostType = flutter::ThreadHost::Type::kRaster | flutter::ThreadHost::Type::kIo;
750 if (settings.merged_platform_ui_thread != flutter::Settings::MergedPlatformUIThread::kEnabled) {
751 threadHostType |= flutter::ThreadHost::Type::kUi;
755 threadHostType = threadHostType | flutter::ThreadHost::Type::kProfiler;
758 flutter::ThreadHost::ThreadHostConfig host_config(thread_label.UTF8String, threadHostType,
761 host_config.ui_config =
762 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
763 flutter::ThreadHost::Type::kUi, thread_label.UTF8String),
764 fml::Thread::ThreadPriority::kDisplay);
765 host_config.raster_config =
766 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
767 flutter::ThreadHost::Type::kRaster, thread_label.UTF8String),
768 fml::Thread::ThreadPriority::kRaster);
770 host_config.io_config =
771 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
772 flutter::ThreadHost::Type::kIo, thread_label.UTF8String),
773 fml::Thread::ThreadPriority::kNormal);
775 return (flutter::ThreadHost){host_config};
778 static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSString* libraryURI) {
780 FML_DCHECK(entrypoint) <<
"Must specify entrypoint if specifying library";
781 settings->advisory_script_entrypoint = entrypoint.UTF8String;
782 settings->advisory_script_uri = libraryURI.UTF8String;
783 }
else if (entrypoint) {
784 settings->advisory_script_entrypoint = entrypoint.UTF8String;
785 settings->advisory_script_uri = std::string(
"main.dart");
787 settings->advisory_script_entrypoint = std::string(
"main");
788 settings->advisory_script_uri = std::string(
"main.dart");
792 - (BOOL)createShell:(NSString*)entrypoint
793 libraryURI:(NSString*)libraryURI
794 initialRoute:(NSString*)initialRoute {
796 [FlutterLogger logWarning:@"This FlutterEngine was already invoked."];
800 self.initialRoute = initialRoute;
802 auto settings = [
self.dartProject settings];
803 if (initialRoute != nil) {
804 self.initialRoute = initialRoute;
805 }
else if (settings.route.empty() ==
false) {
806 self.initialRoute = [NSString stringWithUTF8String:settings.route.c_str()];
809 auto platformData = [
self.dartProject defaultPlatformData];
811 SetEntryPoint(&settings, entrypoint, libraryURI);
813 NSString* threadLabel = [
FlutterEngine generateThreadLabel:self.labelPrefix];
814 _threadHost = std::make_shared<flutter::ThreadHost>();
815 *_threadHost = MakeThreadHost(threadLabel, settings);
818 flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
819 [weakSelf](flutter::Shell& shell) {
822 return std::unique_ptr<flutter::PlatformViewIOS>();
824 [strongSelf recreatePlatformViewsController];
825 strongSelf.platformViewsController.taskRunner =
826 shell.GetTaskRunners().GetPlatformTaskRunner();
827 return std::make_unique<flutter::PlatformViewIOS>(
828 shell, strongSelf->_renderingApi, strongSelf.platformViewsController,
829 shell.GetTaskRunners(), shell.GetConcurrentWorkerTaskRunner(),
830 shell.GetIsGpuDisabledSyncSwitch());
833 flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
834 [](flutter::Shell& shell) {
return std::make_unique<flutter::Rasterizer>(shell); };
836 fml::RefPtr<fml::TaskRunner> ui_runner;
837 if (settings.enable_impeller &&
838 settings.merged_platform_ui_thread == flutter::Settings::MergedPlatformUIThread::kEnabled) {
839 ui_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
841 ui_runner = _threadHost->ui_thread->GetTaskRunner();
843 flutter::TaskRunners task_runners(threadLabel.UTF8String,
844 fml::MessageLoop::GetCurrent().GetTaskRunner(),
845 _threadHost->raster_thread->GetTaskRunner(),
847 _threadHost->io_thread->GetTaskRunner()
851 self.isGpuDisabled =
self.viewController
852 ?
self.viewController.stateIsBackground
855 UIApplicationStateBackground;
858 std::unique_ptr<flutter::Shell> shell = flutter::Shell::Create(
862 on_create_platform_view,
863 on_create_rasterizer,
866 if (shell ==
nullptr) {
867 NSString* errorMessage = [NSString
868 stringWithFormat:@"Could not start a shell FlutterEngine with entrypoint: %@", entrypoint];
869 [FlutterLogger logError:errorMessage];
871 [
self setUpShell:std::move(shell)
872 withVMServicePublication:settings.enable_vm_service_publication];
874 [
self startProfiler];
881 - (void)updateDisplays {
886 auto vsync_waiter =
_shell->GetVsyncWaiter().lock();
887 auto vsync_waiter_ios = std::static_pointer_cast<flutter::VsyncWaiterIOS>(vsync_waiter);
888 std::vector<std::unique_ptr<flutter::Display>> displays;
889 auto screen_size = UIScreen.mainScreen.nativeBounds.size;
890 auto scale = UIScreen.mainScreen.scale;
891 displays.push_back(std::make_unique<flutter::VariableRefreshRateDisplay>(
892 0, vsync_waiter_ios, screen_size.width, screen_size.height, scale));
893 _shell->OnDisplayUpdates(std::move(displays));
897 return [
self runWithEntrypoint:FlutterDefaultDartEntrypoint
899 initialRoute:FlutterDefaultInitialRoute];
902 - (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
903 return [
self runWithEntrypoint:entrypoint
904 libraryURI:libraryURI
905 initialRoute:FlutterDefaultInitialRoute];
908 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
909 return [
self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:FlutterDefaultInitialRoute];
912 - (BOOL)runWithEntrypoint:(NSString*)entrypoint initialRoute:(NSString*)initialRoute {
913 return [
self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:initialRoute];
916 - (BOOL)runWithEntrypoint:(NSString*)entrypoint
917 libraryURI:(NSString*)libraryURI
918 initialRoute:(NSString*)initialRoute {
919 return [
self runWithEntrypoint:entrypoint
920 libraryURI:libraryURI
921 initialRoute:initialRoute
925 - (BOOL)runWithEntrypoint:(NSString*)entrypoint
926 libraryURI:(NSString*)libraryURI
927 initialRoute:(NSString*)initialRoute
928 entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
929 if ([
self createShell:entrypoint libraryURI:libraryURI initialRoute:initialRoute]) {
930 [
self launchEngine:entrypoint libraryURI:libraryURI entrypointArgs:entrypointArgs];
936 - (void)notifyLowMemory {
938 _shell->NotifyLowMemoryWarning();
940 [
self.systemChannel sendMessage:@{@"type" : @"memoryPressure"}];
943 #pragma mark - Text input delegate
946 updateEditingClient:(
int)client
947 withState:(NSDictionary*)state {
948 [
self.textInputChannel invokeMethod:@"TextInputClient.updateEditingState"
949 arguments:@[ @(client), state ]];
953 updateEditingClient:(
int)client
954 withState:(NSDictionary*)state
955 withTag:(NSString*)tag {
956 [
self.textInputChannel invokeMethod:@"TextInputClient.updateEditingStateWithTag"
957 arguments:@[ @(client), @{tag : state} ]];
961 updateEditingClient:(
int)client
962 withDelta:(NSDictionary*)delta {
963 [
self.textInputChannel invokeMethod:@"TextInputClient.updateEditingStateWithDeltas"
964 arguments:@[ @(client), delta ]];
968 updateFloatingCursor:(FlutterFloatingCursorDragState)state
969 withClient:(
int)client
970 withPosition:(NSDictionary*)position {
971 NSString* stateString;
973 case FlutterFloatingCursorDragStateStart:
974 stateString =
@"FloatingCursorDragState.start";
976 case FlutterFloatingCursorDragStateUpdate:
977 stateString =
@"FloatingCursorDragState.update";
979 case FlutterFloatingCursorDragStateEnd:
980 stateString =
@"FloatingCursorDragState.end";
983 [
self.textInputChannel invokeMethod:@"TextInputClient.updateFloatingCursor"
984 arguments:@[ @(client), stateString, position ]];
988 performAction:(FlutterTextInputAction)action
989 withClient:(
int)client {
990 NSString* actionString;
992 case FlutterTextInputActionUnspecified:
997 actionString =
@"TextInputAction.unspecified";
999 case FlutterTextInputActionDone:
1000 actionString =
@"TextInputAction.done";
1002 case FlutterTextInputActionGo:
1003 actionString =
@"TextInputAction.go";
1005 case FlutterTextInputActionSend:
1006 actionString =
@"TextInputAction.send";
1008 case FlutterTextInputActionSearch:
1009 actionString =
@"TextInputAction.search";
1011 case FlutterTextInputActionNext:
1012 actionString =
@"TextInputAction.next";
1014 case FlutterTextInputActionContinue:
1015 actionString =
@"TextInputAction.continueAction";
1017 case FlutterTextInputActionJoin:
1018 actionString =
@"TextInputAction.join";
1020 case FlutterTextInputActionRoute:
1021 actionString =
@"TextInputAction.route";
1023 case FlutterTextInputActionEmergencyCall:
1024 actionString =
@"TextInputAction.emergencyCall";
1026 case FlutterTextInputActionNewline:
1027 actionString =
@"TextInputAction.newline";
1030 [
self.textInputChannel invokeMethod:@"TextInputClient.performAction"
1031 arguments:@[ @(client), actionString ]];
1035 showAutocorrectionPromptRectForStart:(NSUInteger)start
1037 withClient:(
int)client {
1038 [
self.textInputChannel invokeMethod:@"TextInputClient.showAutocorrectionPromptRect"
1039 arguments:@[ @(client), @(start), @(end) ]];
1043 willDismissEditMenuWithTextInputClient:(
int)client {
1044 [
self.platformChannel invokeMethod:@"ContextMenu.onDismissSystemContextMenu"
1045 arguments:@[ @(client) ]];
1049 shareSelectedText:(NSString*)selectedText {
1050 [
self.platformPlugin showShareViewController:selectedText];
1054 searchWebWithSelectedText:(NSString*)selectedText {
1055 [
self.platformPlugin searchWeb:selectedText];
1059 lookUpSelectedText:(NSString*)selectedText {
1060 [
self.platformPlugin showLookUpViewController:selectedText];
1063 #pragma mark - FlutterViewEngineDelegate
1069 [
self.textInputChannel invokeMethod:@"TextInputClient.showToolbar" arguments:@[ @(client) ]];
1073 focusElement:(UIScribbleElementIdentifier)elementIdentifier
1074 atPoint:(CGPoint)referencePoint
1079 [
self.textInputChannel
1080 invokeMethod:@"TextInputClient.focusElement"
1081 arguments:@[ elementIdentifier, @(referencePoint.x), @(referencePoint.y) ]
1086 requestElementsInRect:(CGRect)rect
1091 [
self.textInputChannel
1092 invokeMethod:@"TextInputClient.requestElementsInRect"
1093 arguments:@[ @(rect.origin.x), @(rect.origin.y), @(rect.size.width), @(rect.size.height) ]
1101 [
self.textInputChannel invokeMethod:@"TextInputClient.scribbleInteractionBegan" arguments:nil];
1108 [
self.textInputChannel invokeMethod:@"TextInputClient.scribbleInteractionFinished" arguments:nil];
1112 insertTextPlaceholderWithSize:(CGSize)size
1113 withClient:(
int)client {
1117 [
self.textInputChannel invokeMethod:@"TextInputClient.insertTextPlaceholder"
1118 arguments:@[ @(client), @(size.width), @(size.height) ]];
1122 removeTextPlaceholder:(
int)client {
1126 [
self.textInputChannel invokeMethod:@"TextInputClient.removeTextPlaceholder"
1127 arguments:@[ @(client) ]];
1131 didResignFirstResponderWithTextInputClient:(
int)client {
1135 [
self.textInputChannel invokeMethod:@"TextInputClient.onConnectionClosed"
1136 arguments:@[ @(client) ]];
1157 dispatch_async(dispatch_get_main_queue(), ^(
void) {
1158 long platform_view_id = [
self.platformViewsController firstResponderPlatformViewId];
1159 if (platform_view_id == -1) {
1163 [
self.platformViewsChannel invokeMethod:@"viewFocused" arguments:@(platform_view_id)];
1167 #pragma mark - Undo Manager Delegate
1169 - (void)handleUndoWithDirection:(FlutterUndoRedoDirection)direction {
1170 NSString* action = (direction == FlutterUndoRedoDirectionUndo) ?
@"undo" :
@"redo";
1171 [
self.undoManagerChannel invokeMethod:@"UndoManagerClient.handleUndo" arguments:@[ action ]];
1174 - (UIView<UITextInput>*)activeTextInputView {
1175 return [[
self textInputPlugin] textInputView];
1178 - (NSUndoManager*)undoManager {
1179 return self.viewController.undoManager;
1182 #pragma mark - Screenshot Delegate
1184 - (
flutter::Rasterizer::Screenshot)takeScreenshot:(
flutter::Rasterizer::ScreenshotType)type
1185 asBase64Encoded:(BOOL)base64Encode {
1186 FML_DCHECK(
_shell) <<
"Cannot takeScreenshot without a shell";
1187 return _shell->Screenshot(type, base64Encode);
1190 - (void)flutterViewAccessibilityDidCall {
1192 [
self ensureSemanticsEnabled];
1214 #pragma mark - FlutterBinaryMessenger
1216 - (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
1217 [
self sendOnChannel:channel message:message binaryReply:nil];
1220 - (void)sendOnChannel:(NSString*)channel
1221 message:(NSData*)message
1223 NSParameterAssert(channel);
1225 @"Sending a message before the FlutterEngine has been run.");
1226 fml::RefPtr<flutter::PlatformMessageResponseDarwin> response =
1227 (callback == nil) ?
nullptr
1228 : fml::MakeRefCounted<flutter::PlatformMessageResponseDarwin>(
1232 _shell->GetTaskRunners().GetPlatformTaskRunner());
1233 std::unique_ptr<flutter::PlatformMessage> platformMessage =
1234 (message == nil) ? std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response)
1235 : std::make_unique<flutter::PlatformMessage>(
1238 _shell->GetPlatformView()->DispatchPlatformMessage(std::move(platformMessage));
1248 binaryMessageHandler:
1250 return [
self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
1254 setMessageHandlerOnChannel:(NSString*)channel
1257 NSParameterAssert(channel);
1259 self.platformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.UTF8String,
1260 handler, taskQueue);
1261 return [
self.connections acquireConnectionForChannel:channel];
1263 NSAssert(!handler,
@"Setting a message handler before the FlutterEngine has been run.");
1265 return [FlutterConnectionCollection makeErrorConnectionWithErrorCode:-1L];
1271 NSString* channel = [
self.connections cleanupConnectionWithID:connection];
1272 if (channel.length > 0) {
1273 self.platformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.UTF8String, nil,
1279 #pragma mark - FlutterTextureRegistry
1282 FML_DCHECK(
self.platformView);
1283 int64_t textureId =
self.nextTextureId++;
1284 self.platformView->RegisterExternalTexture(textureId, texture);
1288 - (void)unregisterTexture:(int64_t)textureId {
1289 _shell->GetPlatformView()->UnregisterTexture(textureId);
1292 - (void)textureFrameAvailable:(int64_t)textureId {
1293 _shell->GetPlatformView()->MarkTextureFrameAvailable(textureId);
1296 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1300 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1304 - (id<FlutterPluginRegistry>)pluginRegistry {
1308 #pragma mark - FlutterPluginRegistry
1311 NSAssert(
self.pluginPublications[pluginKey] == nil,
@"Duplicate plugin key: %@", pluginKey);
1312 self.pluginPublications[pluginKey] = [NSNull null];
1314 flutterEngine:self];
1315 self.registrars[pluginKey] = result;
1319 - (BOOL)hasPlugin:(NSString*)pluginKey {
1320 return _pluginPublications[pluginKey] != nil;
1323 - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
1324 return _pluginPublications[pluginKey];
1327 #pragma mark - Notifications
1329 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1330 [
self flutterWillEnterForeground:notification];
1333 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1334 [
self flutterDidEnterBackground:notification];
1337 - (void)applicationWillEnterForeground:(NSNotification*)notification {
1338 [
self flutterWillEnterForeground:notification];
1341 - (void)applicationDidEnterBackground:(NSNotification*)notification {
1342 [
self flutterDidEnterBackground:notification];
1345 - (void)flutterWillEnterForeground:(NSNotification*)notification {
1346 [
self setIsGpuDisabled:NO];
1349 - (void)flutterDidEnterBackground:(NSNotification*)notification {
1350 [
self setIsGpuDisabled:YES];
1351 [
self notifyLowMemory];
1354 - (void)onMemoryWarning:(NSNotification*)notification {
1355 [
self notifyLowMemory];
1358 - (void)setIsGpuDisabled:(BOOL)value {
1360 _shell->SetGpuAvailability(value ? flutter::GpuAvailability::kUnavailable
1361 : flutter::GpuAvailability::kAvailable);
1363 _isGpuDisabled = value;
1366 #pragma mark - Locale updates
1368 - (void)onLocaleUpdated:(NSNotification*)notification {
1370 NSMutableArray<NSString*>* localeData = [[NSMutableArray alloc] init];
1371 NSArray<NSString*>* preferredLocales = [NSLocale preferredLanguages];
1372 for (NSString* localeID in preferredLocales) {
1373 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1374 NSString* languageCode = [locale objectForKey:NSLocaleLanguageCode];
1375 NSString* countryCode = [locale objectForKey:NSLocaleCountryCode];
1376 NSString* scriptCode = [locale objectForKey:NSLocaleScriptCode];
1377 NSString* variantCode = [locale objectForKey:NSLocaleVariantCode];
1378 if (!languageCode) {
1381 [localeData addObject:languageCode];
1382 [localeData addObject:(countryCode ? countryCode : @"")];
1383 [localeData addObject:(scriptCode ? scriptCode : @"")];
1384 [localeData addObject:(variantCode ? variantCode : @"")];
1386 if (localeData.count == 0) {
1389 [
self.localizationChannel invokeMethod:@"setLocale" arguments:localeData];
1392 - (void)waitForFirstFrameSync:(NSTimeInterval)timeout
1393 callback:(NS_NOESCAPE
void (^_Nonnull)(BOOL didTimeout))callback {
1394 fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000);
1395 fml::Status status =
self.shell.WaitForFirstFrame(waitTime);
1396 callback(status.code() == fml::StatusCode::kDeadlineExceeded);
1399 - (void)waitForFirstFrame:(NSTimeInterval)timeout
1400 callback:(
void (^_Nonnull)(BOOL didTimeout))callback {
1401 dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0);
1402 dispatch_group_t group = dispatch_group_create();
1405 __block BOOL didTimeout = NO;
1406 dispatch_group_async(group, queue, ^{
1412 fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000);
1413 fml::Status status = strongSelf.
shell.WaitForFirstFrame(waitTime);
1414 didTimeout = status.code() == fml::StatusCode::kDeadlineExceeded;
1418 dispatch_group_notify(group, dispatch_get_main_queue(), ^{
1432 callback(didTimeout);
1436 - (
FlutterEngine*)spawnWithEntrypoint:( NSString*)entrypoint
1437 libraryURI:( NSString*)libraryURI
1438 initialRoute:( NSString*)initialRoute
1439 entrypointArgs:( NSArray<NSString*>*)entrypointArgs {
1440 NSAssert(
_shell,
@"Spawning from an engine without a shell (possibly not run).");
1442 project:self.dartProject
1443 allowHeadlessExecution:self.allowHeadlessExecution];
1444 flutter::RunConfiguration configuration =
1445 [
self.dartProject runConfigurationForEntrypoint:entrypoint
1446 libraryOrNil:libraryURI
1447 entrypointArgs:entrypointArgs];
1449 configuration.SetEngineId(result.engineIdentifier);
1456 std::shared_ptr<flutter::IOSContext> context = ios_platform_view->
GetIosContext();
1457 FML_DCHECK(context);
1461 flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
1462 [result, context](flutter::Shell& shell) {
1463 [result recreatePlatformViewsController];
1464 result.platformViewsController.taskRunner = shell.GetTaskRunners().GetPlatformTaskRunner();
1465 return std::make_unique<flutter::PlatformViewIOS>(
1466 shell, context, result.platformViewsController, shell.GetTaskRunners());
1469 flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
1470 [](flutter::Shell& shell) {
return std::make_unique<flutter::Rasterizer>(shell); };
1472 std::string cppInitialRoute;
1474 cppInitialRoute = [initialRoute UTF8String];
1477 std::unique_ptr<flutter::Shell> shell =
_shell->Spawn(
1478 std::move(configuration), cppInitialRoute, on_create_platform_view, on_create_rasterizer);
1480 result->_threadHost = _threadHost;
1482 result->_isGpuDisabled = _isGpuDisabled;
1483 [result setUpShell:std::move(shell) withVMServicePublication:NO];
1487 - (const
flutter::ThreadHost&)threadHost {
1488 return *_threadHost;
1492 return self.dartProject;
1498 NSString* _pluginKey;
1501 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
1502 self = [
super init];
1503 NSAssert(
self,
@"Super init cannot be nil");
1504 _pluginKey = [pluginKey copy];
1505 _flutterEngine = flutterEngine;
1510 return _flutterEngine.binaryMessenger;
1514 return _flutterEngine.textureRegistry;
1517 - (void)publish:(NSObject*)value {
1518 _flutterEngine.pluginPublications[_pluginKey] = value;
1521 - (void)addMethodCallDelegate:(NSObject<
FlutterPlugin>*)delegate
1528 - (void)addApplicationDelegate:(NSObject<
FlutterPlugin>*)delegate
1529 NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in plugins used in app extensions") {
1530 id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
1532 id<FlutterAppLifeCycleProvider> lifeCycleProvider =
1533 (id<FlutterAppLifeCycleProvider>)appDelegate;
1534 [lifeCycleProvider addApplicationLifeCycleDelegate:delegate];
1538 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1539 return [_flutterEngine lookupKeyForAsset:asset];
1542 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1543 return [_flutterEngine lookupKeyForAsset:asset fromPackage:package];
1547 withId:(NSString*)factoryId {
1548 [
self registerViewFactory:factory
1550 gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager];
1554 withId:(NSString*)factoryId
1555 gestureRecognizersBlockingPolicy:
1557 [_flutterEngine.platformViewsController registerViewFactory:factory
1559 gestureRecognizersBlockingPolicy:gestureRecognizersBlockingPolicy];
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterBinaryReply)(NSData *_Nullable reply)
void(^ FlutterBinaryMessageHandler)(NSData *_Nullable message, FlutterBinaryReply reply)
int64_t FlutterBinaryMessengerConnection
void(^ FlutterResult)(id _Nullable result)
NSString *const FlutterDefaultDartEntrypoint
std::shared_ptr< flutter::SamplingProfiler > _profiler
std::unique_ptr< flutter::Shell > _shell
NSString *const kFlutterKeyDataChannel
NSString *const FlutterDefaultInitialRoute
flutter::IOSRenderingAPI _renderingApi
FlutterTextureRegistryRelay * _textureRegistry
static FLUTTER_ASSERT_ARC void IOSPlatformThreadConfigSetter(const fml::Thread::ThreadConfig &config)
static constexpr int kNumProfilerSamplesPerSec
FlutterBinaryMessengerRelay * _binaryMessenger
FlutterPlatformViewGestureRecognizersBlockingPolicy
FlutterViewController * viewController
FlutterTextInputPlugin * textInputPlugin
FlutterEngineProcTable & embedderAPI
NSString * lookupKeyForAsset:fromPackage:(NSString *asset,[fromPackage] NSString *package)
const flutter::Settings & settings()
NSString * lookupKeyForAsset:(NSString *asset)
NSObject< FlutterBinaryMessenger > * parent
FlutterMethodChannel * textInputChannel
flutter::PlatformViewIOS * platformView()
FlutterMethodChannel * navigationChannel
FlutterBasicMessageChannel * keyEventChannel
FlutterBasicMessageChannel * lifecycleChannel
FlutterMethodChannel * platformChannel
FlutterMethodChannel * localizationChannel
FlutterBasicMessageChannel * systemChannel
FlutterBasicMessageChannel * settingsChannel
FlutterMethodChannel * restorationChannel
FlutterEngine * flutterEngine
instancetype errorWithCode:message:details:(NSString *code,[message] NSString *_Nullable message,[details] id _Nullable details)
void setMethodCallHandler:(FlutterMethodCallHandler _Nullable handler)
UIApplication * application
NSObject< FlutterTextureRegistry > * parent
fml::MallocMapping CopyNSDataToMapping(NSData *data)
IOSRenderingAPI GetRenderingAPIForProcess(bool force_software)
instancetype sharedInstance()
void handleMethodCall:result:(FlutterMethodCall *call,[result] FlutterResult result)