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"
43 #include "flutter/shell/profiling/sampling_profiler.h"
51 fml::Thread::SetCurrentThreadName(config);
54 switch (config.priority) {
55 case fml::Thread::ThreadPriority::kBackground: {
56 pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0);
57 [[NSThread currentThread] setThreadPriority:0];
60 case fml::Thread::ThreadPriority::kNormal: {
61 pthread_set_qos_class_self_np(QOS_CLASS_DEFAULT, 0);
62 [[NSThread currentThread] setThreadPriority:0.5];
65 case fml::Thread::ThreadPriority::kRaster:
66 case fml::Thread::ThreadPriority::kDisplay: {
67 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
68 [[NSThread currentThread] setThreadPriority:1.0];
71 pthread_t thread = pthread_self();
72 if (!pthread_getschedparam(thread, &policy, ¶m)) {
73 param.sched_priority = 50;
74 pthread_setschedparam(thread, policy, ¶m);
81 #pragma mark - Public exported constants
86 #pragma mark - Internal constants
102 #pragma mark - Properties
105 @property(nonatomic, readonly, copy) NSString* labelPrefix;
106 @property(nonatomic, readonly, assign) BOOL allowHeadlessExecution;
107 @property(nonatomic, readonly, assign) BOOL restorationEnabled;
113 @property(nonatomic, readonly) NSMutableDictionary* pluginPublications;
114 @property(nonatomic, readonly) NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* registrars;
116 @property(nonatomic, readwrite, copy) NSString*
isolateId;
117 @property(nonatomic, copy) NSString* initialRoute;
118 @property(nonatomic, strong) id<NSObject> flutterViewControllerWillDeallocObserver;
120 @property(nonatomic, assign) int64_t nextTextureId;
122 #pragma mark - Channel properties
144 #pragma mark - Embedder API properties
153 std::shared_ptr<flutter::ThreadHost> _threadHost;
164 - (int64_t)engineIdentifier {
165 return reinterpret_cast<int64_t
>((__bridge
void*)
self);
168 - (instancetype)init {
169 return [
self initWithName:@"FlutterEngine" project:nil allowHeadlessExecution:YES];
172 - (instancetype)initWithName:(NSString*)labelPrefix {
173 return [
self initWithName:labelPrefix project:nil allowHeadlessExecution:YES];
176 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
177 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
180 - (instancetype)initWithName:(NSString*)labelPrefix
182 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
183 return [
self initWithName:labelPrefix
185 allowHeadlessExecution:allowHeadlessExecution
186 restorationEnabled:NO];
189 - (instancetype)initWithName:(NSString*)labelPrefix
191 allowHeadlessExecution:(BOOL)allowHeadlessExecution
192 restorationEnabled:(BOOL)restorationEnabled {
194 NSAssert(
self,
@"Super init cannot be nil");
195 NSAssert(labelPrefix,
@"labelPrefix is required");
198 _allowHeadlessExecution = allowHeadlessExecution;
199 _labelPrefix = [labelPrefix copy];
202 _enableEmbedderAPI = _dartProject.
settings.enable_embedder_api;
203 if (_enableEmbedderAPI) {
204 NSLog(
@"============== iOS: enable_embedder_api is on ==============");
205 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
206 FlutterEngineGetProcAddresses(&_embedderAPI);
209 if (!EnableTracingIfNecessary(_dartProject.settings)) {
211 @"Cannot create a FlutterEngine instance in debug mode without Flutter tooling or "
212 @"Xcode.\n\nTo launch in debug mode in iOS 14+, run flutter run from Flutter tools, run "
213 @"from an IDE with a Flutter IDE plugin or run the iOS project from Xcode.\nAlternatively "
214 @"profile and release mode apps can be launched from the home screen.");
218 _pluginPublications = [[NSMutableDictionary alloc] init];
219 _registrars = [[NSMutableDictionary alloc] init];
220 [
self recreatePlatformViewsController];
225 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
226 [center addObserver:self
227 selector:@selector(onMemoryWarning:)
228 name:UIApplicationDidReceiveMemoryWarningNotification
231 [
self setUpLifecycleNotifications:center];
233 [center addObserver:self
234 selector:@selector(onLocaleUpdated:)
235 name:NSCurrentLocaleDidChangeNotification
242 NSAssert([[NSThread currentThread] isMainThread],
@"Must be called on the main thread.");
243 return (__bridge
FlutterEngine*)
reinterpret_cast<void*
>(identifier);
246 - (void)setUpLifecycleNotifications:(NSNotificationCenter*)center {
249 if (@available(iOS 13.0, *)) {
250 [center addObserver:self
251 selector:@selector(sceneWillEnterForeground:)
252 name:UISceneWillEnterForegroundNotification
254 [center addObserver:self
255 selector:@selector(sceneDidEnterBackground:)
256 name:UISceneDidEnterBackgroundNotification
261 [center addObserver:self
262 selector:@selector(applicationWillEnterForeground:)
263 name:UIApplicationWillEnterForegroundNotification
265 [center addObserver:self
266 selector:@selector(applicationDidEnterBackground:)
267 name:UIApplicationDidEnterBackgroundNotification
271 - (void)recreatePlatformViewsController {
276 - (
flutter::IOSRenderingAPI)platformViewsRenderingAPI {
283 [_pluginPublications enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL* stop) {
284 if ([object respondsToSelector:@selector(detachFromEngineForRegistrar:)]) {
285 NSObject<FlutterPluginRegistrar>* registrar = self.registrars[key];
286 [object detachFromEngineForRegistrar:registrar];
294 enumerateKeysAndObjectsUsingBlock:^(id key, FlutterEngineRegistrar* registrar, BOOL* stop) {
295 registrar.flutterEngine = nil;
301 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
302 if (_flutterViewControllerWillDeallocObserver) {
303 [center removeObserver:_flutterViewControllerWillDeallocObserver];
305 [center removeObserver:self];
313 - (void)updateViewportMetrics:(
flutter::ViewportMetrics)viewportMetrics {
314 if (!
self.platformView) {
317 self.platformView->SetViewportMetrics(flutter::kFlutterImplicitViewId, viewportMetrics);
320 - (void)dispatchPointerDataPacket:(std::unique_ptr<
flutter::PointerDataPacket>)packet {
321 if (!
self.platformView) {
324 self.platformView->DispatchPointerDataPacket(std::move(packet));
327 - (void)installFirstFrameCallback:(
void (^)(
void))block {
328 if (!
self.platformView) {
333 self.
platformView->SetNextFrameCallback([weakSelf, block] {
338 FML_DCHECK(strongSelf.platformTaskRunner);
339 FML_DCHECK(strongSelf.rasterTaskRunner);
340 FML_DCHECK(strongSelf.rasterTaskRunner->RunsTasksOnCurrentThread());
342 strongSelf.platformTaskRunner->PostTask([block]() { block(); });
346 - (void)enableSemantics:(BOOL)enabled withFlags:(int64_t)flags {
347 if (!
self.platformView) {
351 self.platformView->SetAccessibilityFeatures(flags);
354 - (void)notifyViewCreated {
355 if (!
self.platformView) {
358 self.platformView->NotifyCreated();
361 - (void)notifyViewDestroyed {
362 if (!
self.platformView) {
365 self.platformView->NotifyDestroyed();
368 - (
flutter::PlatformViewIOS*)platformView {
375 - (
fml::RefPtr<fml::TaskRunner>)platformTaskRunner {
379 return _shell->GetTaskRunners().GetPlatformTaskRunner();
382 - (
fml::RefPtr<fml::TaskRunner>)uiTaskRunner {
386 return _shell->GetTaskRunners().GetUITaskRunner();
389 - (
fml::RefPtr<fml::TaskRunner>)rasterTaskRunner {
393 return _shell->GetTaskRunners().GetRasterTaskRunner();
396 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
397 callback:(FlutterKeyEventCallback)callback
398 userData:(
void*)userData API_AVAILABLE(ios(13.4)) {
399 if (@available(iOS 13.4, *)) {
403 if (!
self.platformView) {
406 const char* character =
event.character;
408 flutter::KeyData key_data;
410 key_data.timestamp = (uint64_t)event.timestamp;
411 switch (event.type) {
412 case kFlutterKeyEventTypeUp:
413 key_data.type = flutter::KeyEventType::kUp;
415 case kFlutterKeyEventTypeDown:
416 key_data.type = flutter::KeyEventType::kDown;
418 case kFlutterKeyEventTypeRepeat:
419 key_data.type = flutter::KeyEventType::kRepeat;
422 key_data.physical =
event.physical;
423 key_data.logical =
event.logical;
424 key_data.synthesized =
event.synthesized;
426 auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character);
427 NSData* message = [NSData dataWithBytes:packet->data().data() length:packet->data().size()];
429 auto response = ^(NSData* reply) {
430 if (callback ==
nullptr) {
433 BOOL handled = FALSE;
434 if (reply.length == 1 && *
reinterpret_cast<const uint8_t*
>(reply.bytes) == 1) {
437 callback(handled, userData);
440 [
self sendOnChannel:kFlutterKeyDataChannel message:message binaryReply:response];
443 - (void)ensureSemanticsEnabled {
444 if (!
self.platformView) {
447 self.platformView->SetSemanticsEnabled(
true);
451 FML_DCHECK(
self.platformView);
453 self.platformView->SetOwnerViewController(_viewController);
454 [
self maybeSetupPlatformViewChannels];
455 [
self updateDisplays];
460 self.flutterViewControllerWillDeallocObserver =
461 [[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc
462 object:viewController
463 queue:[NSOperationQueue mainQueue]
464 usingBlock:^(NSNotification* note) {
465 [weakSelf notifyViewControllerDeallocated];
468 self.flutterViewControllerWillDeallocObserver = nil;
469 [
self notifyLowMemory];
474 FML_DCHECK(
self.platformView);
475 self.platformView->attachView();
478 - (void)setFlutterViewControllerWillDeallocObserver:(
id<NSObject>)observer {
479 if (observer != _flutterViewControllerWillDeallocObserver) {
480 if (_flutterViewControllerWillDeallocObserver) {
481 [[NSNotificationCenter defaultCenter]
482 removeObserver:_flutterViewControllerWillDeallocObserver];
484 _flutterViewControllerWillDeallocObserver = observer;
488 - (void)notifyViewControllerDeallocated {
489 [
self.lifecycleChannel sendMessage:@"AppLifecycleState.detached"];
490 self.textInputPlugin.viewController = nil;
491 if (!
self.allowHeadlessExecution) {
492 [
self destroyContext];
493 }
else if (
self.platformView) {
494 self.platformView->SetOwnerViewController({});
496 [
self.textInputPlugin resetViewResponder];
497 _viewController = nil;
500 - (void)destroyContext {
501 [
self resetChannels];
502 self.isolateId = nil;
506 _platformViewsController = nil;
509 - (NSURL*)observatoryUrl {
510 return self.publisher.url;
513 - (NSURL*)vmServiceUrl {
514 return self.publisher.url;
517 - (void)resetChannels {
518 self.localizationChannel = nil;
519 self.navigationChannel = nil;
520 self.restorationChannel = nil;
521 self.platformChannel = nil;
522 self.platformViewsChannel = nil;
523 self.textInputChannel = nil;
524 self.undoManagerChannel = nil;
525 self.scribbleChannel = nil;
526 self.lifecycleChannel = nil;
527 self.systemChannel = nil;
528 self.settingsChannel = nil;
529 self.keyEventChannel = nil;
530 self.spellCheckChannel = nil;
533 - (void)startProfiler {
534 FML_DCHECK(!_threadHost->name_prefix.empty());
535 _profiler = std::make_shared<flutter::SamplingProfiler>(
536 _threadHost->name_prefix.c_str(), _threadHost->profiler_thread->GetTaskRunner(),
538 flutter::ProfilerMetricsIOS profiler_metrics;
539 return profiler_metrics.GenerateSample();
548 - (void)setUpChannels {
552 [_binaryMessenger setMessageHandlerOnChannel:@"flutter/isolate"
553 binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) {
562 binaryMessenger:self.binaryMessenger
565 self.navigationChannel =
567 binaryMessenger:self.binaryMessenger
570 if ([_initialRoute length] > 0) {
572 [
self.navigationChannel invokeMethod:@"setInitialRoute" arguments:_initialRoute];
576 self.restorationChannel =
578 binaryMessenger:self.binaryMessenger
581 self.platformChannel =
583 binaryMessenger:self.binaryMessenger
586 self.platformViewsChannel =
588 binaryMessenger:self.binaryMessenger
591 self.textInputChannel =
593 binaryMessenger:self.binaryMessenger
596 self.undoManagerChannel =
598 binaryMessenger:self.binaryMessenger
601 self.scribbleChannel =
603 binaryMessenger:self.binaryMessenger
606 self.spellCheckChannel =
608 binaryMessenger:self.binaryMessenger
611 self.lifecycleChannel =
613 binaryMessenger:self.binaryMessenger
618 binaryMessenger:self.binaryMessenger
621 self.settingsChannel =
623 binaryMessenger:self.binaryMessenger
626 self.keyEventChannel =
628 binaryMessenger:self.binaryMessenger
632 self.textInputPlugin.indirectScribbleDelegate =
self;
633 [
self.textInputPlugin setUpIndirectScribbleInteraction:self.viewController];
638 self.restorationPlugin =
640 restorationEnabled:self.restorationEnabled];
643 self.screenshotChannel =
645 binaryMessenger:self.binaryMessenger
648 [
self.screenshotChannel setMethodCallHandler:^(FlutterMethodCall* _Nonnull call,
649 FlutterResult _Nonnull result) {
651 if (!(strongSelf && strongSelf->_shell && strongSelf->_shell->IsSetup())) {
654 message:@"Requesting screenshot while engine is not running."
657 flutter::Rasterizer::Screenshot screenshot =
658 [strongSelf screenshot:flutter::Rasterizer::ScreenshotType::SurfaceData base64Encode:NO];
659 if (!screenshot.data) {
661 message:@"Unable to get screenshot."
665 NSData* data = [NSData dataWithBytes:screenshot.data->writable_data()
666 length:screenshot.data->size()];
667 NSString* format = [NSString stringWithUTF8String:screenshot.format.c_str()];
668 NSNumber* width = @(screenshot.frame_size.fWidth);
669 NSNumber* height = @(screenshot.frame_size.fHeight);
670 return result(@[ width, height, format ?: [NSNull null], data ]);
674 - (void)maybeSetupPlatformViewChannels {
675 if (
_shell &&
self.shell.IsSetup()) {
678 [
self.platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
679 [weakSelf.platformPlugin handleMethodCall:call result:result];
682 [
self.platformViewsChannel
683 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
685 [weakSelf.platformViewsController onMethodCall:call result:result];
689 [
self.textInputChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
690 [weakSelf.textInputPlugin handleMethodCall:call result:result];
693 [
self.undoManagerChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
694 [weakSelf.undoManagerPlugin handleMethodCall:call result:result];
697 [
self.spellCheckChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
698 [weakSelf.spellCheckPlugin handleMethodCall:call result:result];
703 - (
flutter::Rasterizer::Screenshot)screenshot:(
flutter::Rasterizer::ScreenshotType)type
704 base64Encode:(
bool)base64Encode {
705 return self.shell.Screenshot(type, base64Encode);
708 - (void)launchEngine:(NSString*)entrypoint
709 libraryURI:(NSString*)libraryOrNil
710 entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
712 flutter::RunConfiguration configuration =
713 [
self.dartProject runConfigurationForEntrypoint:entrypoint
714 libraryOrNil:libraryOrNil
715 entrypointArgs:entrypointArgs];
717 configuration.SetEngineId(
self.engineIdentifier);
718 self.shell.RunEngine(std::move(configuration));
721 - (void)setUpShell:(std::unique_ptr<
flutter::Shell>)shell
722 withVMServicePublication:(BOOL)doesVMServicePublication {
723 _shell = std::move(shell);
724 [
self setUpChannels];
725 [
self onLocaleUpdated:nil];
726 [
self updateDisplays];
728 initWithEnableVMServicePublication:doesVMServicePublication];
729 [
self maybeSetupPlatformViewChannels];
730 _shell->SetGpuAvailability(_isGpuDisabled ? flutter::GpuAvailability::kUnavailable
731 : flutter::GpuAvailability::kAvailable);
734 + (BOOL)isProfilerEnabled {
735 bool profilerEnabled =
false;
736 #if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) || \
737 (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE)
738 profilerEnabled =
true;
740 return profilerEnabled;
743 + (NSString*)generateThreadLabel:(NSString*)labelPrefix {
744 static size_t s_shellCount = 0;
745 return [NSString stringWithFormat:@"%@.%zu", labelPrefix, ++s_shellCount];
748 static flutter::ThreadHost MakeThreadHost(NSString* thread_label,
749 const flutter::Settings& settings) {
752 fml::MessageLoop::EnsureInitializedForCurrentThread();
754 uint32_t threadHostType = flutter::ThreadHost::Type::kRaster | flutter::ThreadHost::Type::kIo;
755 if (!settings.merged_platform_ui_thread) {
756 threadHostType |= flutter::ThreadHost::Type::kUi;
760 threadHostType = threadHostType | flutter::ThreadHost::Type::kProfiler;
763 flutter::ThreadHost::ThreadHostConfig host_config(thread_label.UTF8String, threadHostType,
766 host_config.ui_config =
767 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
768 flutter::ThreadHost::Type::kUi, thread_label.UTF8String),
769 fml::Thread::ThreadPriority::kDisplay);
770 host_config.raster_config =
771 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
772 flutter::ThreadHost::Type::kRaster, thread_label.UTF8String),
773 fml::Thread::ThreadPriority::kRaster);
775 host_config.io_config =
776 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
777 flutter::ThreadHost::Type::kIo, thread_label.UTF8String),
778 fml::Thread::ThreadPriority::kNormal);
780 return (flutter::ThreadHost){host_config};
783 static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSString* libraryURI) {
785 FML_DCHECK(entrypoint) <<
"Must specify entrypoint if specifying library";
786 settings->advisory_script_entrypoint = entrypoint.UTF8String;
787 settings->advisory_script_uri = libraryURI.UTF8String;
788 }
else if (entrypoint) {
789 settings->advisory_script_entrypoint = entrypoint.UTF8String;
790 settings->advisory_script_uri = std::string(
"main.dart");
792 settings->advisory_script_entrypoint = std::string(
"main");
793 settings->advisory_script_uri = std::string(
"main.dart");
797 - (BOOL)createShell:(NSString*)entrypoint
798 libraryURI:(NSString*)libraryURI
799 initialRoute:(NSString*)initialRoute {
801 FML_LOG(WARNING) <<
"This FlutterEngine was already invoked.";
805 self.initialRoute = initialRoute;
807 auto settings = [
self.dartProject settings];
808 if (initialRoute != nil) {
809 self.initialRoute = initialRoute;
810 }
else if (settings.route.empty() ==
false) {
811 self.initialRoute = [NSString stringWithUTF8String:settings.route.c_str()];
814 auto platformData = [
self.dartProject defaultPlatformData];
816 SetEntryPoint(&settings, entrypoint, libraryURI);
818 NSString* threadLabel = [
FlutterEngine generateThreadLabel:self.labelPrefix];
819 _threadHost = std::make_shared<flutter::ThreadHost>();
820 *_threadHost = MakeThreadHost(threadLabel, settings);
823 flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
824 [weakSelf](flutter::Shell& shell) {
827 return std::unique_ptr<flutter::PlatformViewIOS>();
829 [strongSelf recreatePlatformViewsController];
830 strongSelf.platformViewsController.taskRunner =
831 shell.GetTaskRunners().GetPlatformTaskRunner();
832 return std::make_unique<flutter::PlatformViewIOS>(
833 shell, strongSelf->_renderingApi, strongSelf.platformViewsController,
834 shell.GetTaskRunners(), shell.GetConcurrentWorkerTaskRunner(),
835 shell.GetIsGpuDisabledSyncSwitch());
838 flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
839 [](flutter::Shell& shell) {
return std::make_unique<flutter::Rasterizer>(shell); };
841 fml::RefPtr<fml::TaskRunner> ui_runner;
842 if (settings.enable_impeller && settings.merged_platform_ui_thread) {
843 ui_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
845 ui_runner = _threadHost->ui_thread->GetTaskRunner();
847 flutter::TaskRunners task_runners(threadLabel.UTF8String,
848 fml::MessageLoop::GetCurrent().GetTaskRunner(),
849 _threadHost->raster_thread->GetTaskRunner(),
851 _threadHost->io_thread->GetTaskRunner()
855 self.isGpuDisabled =
self.viewController.stateIsBackground;
858 std::unique_ptr<flutter::Shell> shell = flutter::Shell::Create(
862 on_create_platform_view,
863 on_create_rasterizer,
866 if (shell ==
nullptr) {
867 FML_LOG(ERROR) <<
"Could not start a shell FlutterEngine with entrypoint: "
868 << entrypoint.UTF8String;
871 FML_LOG(INFO) <<
"Enabled VM Service Publication: " << settings.enable_vm_service_publication;
872 [
self setUpShell:std::move(shell)
873 withVMServicePublication:settings.enable_vm_service_publication];
875 [
self startProfiler];
882 - (void)updateDisplays {
887 auto vsync_waiter =
_shell->GetVsyncWaiter().lock();
888 auto vsync_waiter_ios = std::static_pointer_cast<flutter::VsyncWaiterIOS>(vsync_waiter);
889 std::vector<std::unique_ptr<flutter::Display>> displays;
890 auto screen_size = UIScreen.mainScreen.nativeBounds.size;
891 auto scale = UIScreen.mainScreen.scale;
892 displays.push_back(std::make_unique<flutter::VariableRefreshRateDisplay>(
893 0, vsync_waiter_ios, screen_size.width, screen_size.height, scale));
894 _shell->OnDisplayUpdates(std::move(displays));
898 return [
self runWithEntrypoint:FlutterDefaultDartEntrypoint
900 initialRoute:FlutterDefaultInitialRoute];
903 - (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
904 return [
self runWithEntrypoint:entrypoint
905 libraryURI:libraryURI
906 initialRoute:FlutterDefaultInitialRoute];
909 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
910 return [
self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:FlutterDefaultInitialRoute];
913 - (BOOL)runWithEntrypoint:(NSString*)entrypoint initialRoute:(NSString*)initialRoute {
914 return [
self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:initialRoute];
917 - (BOOL)runWithEntrypoint:(NSString*)entrypoint
918 libraryURI:(NSString*)libraryURI
919 initialRoute:(NSString*)initialRoute {
920 return [
self runWithEntrypoint:entrypoint
921 libraryURI:libraryURI
922 initialRoute:initialRoute
926 - (BOOL)runWithEntrypoint:(NSString*)entrypoint
927 libraryURI:(NSString*)libraryURI
928 initialRoute:(NSString*)initialRoute
929 entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
930 if ([
self createShell:entrypoint libraryURI:libraryURI initialRoute:initialRoute]) {
931 [
self launchEngine:entrypoint libraryURI:libraryURI entrypointArgs:entrypointArgs];
937 - (void)notifyLowMemory {
939 _shell->NotifyLowMemoryWarning();
941 [
self.systemChannel sendMessage:@{@"type" : @"memoryPressure"}];
944 #pragma mark - Text input delegate
947 updateEditingClient:(
int)client
948 withState:(NSDictionary*)state {
949 [
self.textInputChannel invokeMethod:@"TextInputClient.updateEditingState"
950 arguments:@[ @(client), state ]];
954 updateEditingClient:(
int)client
955 withState:(NSDictionary*)state
956 withTag:(NSString*)tag {
957 [
self.textInputChannel invokeMethod:@"TextInputClient.updateEditingStateWithTag"
958 arguments:@[ @(client), @{tag : state} ]];
962 updateEditingClient:(
int)client
963 withDelta:(NSDictionary*)delta {
964 [
self.textInputChannel invokeMethod:@"TextInputClient.updateEditingStateWithDeltas"
965 arguments:@[ @(client), delta ]];
969 updateFloatingCursor:(FlutterFloatingCursorDragState)state
970 withClient:(
int)client
971 withPosition:(NSDictionary*)position {
972 NSString* stateString;
974 case FlutterFloatingCursorDragStateStart:
975 stateString =
@"FloatingCursorDragState.start";
977 case FlutterFloatingCursorDragStateUpdate:
978 stateString =
@"FloatingCursorDragState.update";
980 case FlutterFloatingCursorDragStateEnd:
981 stateString =
@"FloatingCursorDragState.end";
984 [
self.textInputChannel invokeMethod:@"TextInputClient.updateFloatingCursor"
985 arguments:@[ @(client), stateString, position ]];
989 performAction:(FlutterTextInputAction)action
990 withClient:(
int)client {
991 NSString* actionString;
993 case FlutterTextInputActionUnspecified:
998 actionString =
@"TextInputAction.unspecified";
1000 case FlutterTextInputActionDone:
1001 actionString =
@"TextInputAction.done";
1003 case FlutterTextInputActionGo:
1004 actionString =
@"TextInputAction.go";
1006 case FlutterTextInputActionSend:
1007 actionString =
@"TextInputAction.send";
1009 case FlutterTextInputActionSearch:
1010 actionString =
@"TextInputAction.search";
1012 case FlutterTextInputActionNext:
1013 actionString =
@"TextInputAction.next";
1015 case FlutterTextInputActionContinue:
1016 actionString =
@"TextInputAction.continueAction";
1018 case FlutterTextInputActionJoin:
1019 actionString =
@"TextInputAction.join";
1021 case FlutterTextInputActionRoute:
1022 actionString =
@"TextInputAction.route";
1024 case FlutterTextInputActionEmergencyCall:
1025 actionString =
@"TextInputAction.emergencyCall";
1027 case FlutterTextInputActionNewline:
1028 actionString =
@"TextInputAction.newline";
1031 [
self.textInputChannel invokeMethod:@"TextInputClient.performAction"
1032 arguments:@[ @(client), actionString ]];
1036 showAutocorrectionPromptRectForStart:(NSUInteger)start
1038 withClient:(
int)client {
1039 [
self.textInputChannel invokeMethod:@"TextInputClient.showAutocorrectionPromptRect"
1040 arguments:@[ @(client), @(start), @(end) ]];
1044 willDismissEditMenuWithTextInputClient:(
int)client {
1045 [
self.platformChannel invokeMethod:@"ContextMenu.onDismissSystemContextMenu"
1046 arguments:@[ @(client) ]];
1050 shareSelectedText:(NSString*)selectedText {
1051 [
self.platformPlugin showShareViewController:selectedText];
1055 searchWebWithSelectedText:(NSString*)selectedText {
1056 [
self.platformPlugin searchWeb:selectedText];
1060 lookUpSelectedText:(NSString*)selectedText {
1061 [
self.platformPlugin showLookUpViewController:selectedText];
1064 #pragma mark - FlutterViewEngineDelegate
1070 [
self.textInputChannel invokeMethod:@"TextInputClient.showToolbar" arguments:@[ @(client) ]];
1074 focusElement:(UIScribbleElementIdentifier)elementIdentifier
1075 atPoint:(CGPoint)referencePoint
1080 [
self.textInputChannel
1081 invokeMethod:@"TextInputClient.focusElement"
1082 arguments:@[ elementIdentifier, @(referencePoint.x), @(referencePoint.y) ]
1087 requestElementsInRect:(CGRect)rect
1092 [
self.textInputChannel
1093 invokeMethod:@"TextInputClient.requestElementsInRect"
1094 arguments:@[ @(rect.origin.x), @(rect.origin.y), @(rect.size.width), @(rect.size.height) ]
1102 [
self.textInputChannel invokeMethod:@"TextInputClient.scribbleInteractionBegan" arguments:nil];
1109 [
self.textInputChannel invokeMethod:@"TextInputClient.scribbleInteractionFinished" arguments:nil];
1113 insertTextPlaceholderWithSize:(CGSize)size
1114 withClient:(
int)client {
1118 [
self.textInputChannel invokeMethod:@"TextInputClient.insertTextPlaceholder"
1119 arguments:@[ @(client), @(size.width), @(size.height) ]];
1123 removeTextPlaceholder:(
int)client {
1127 [
self.textInputChannel invokeMethod:@"TextInputClient.removeTextPlaceholder"
1128 arguments:@[ @(client) ]];
1132 didResignFirstResponderWithTextInputClient:(
int)client {
1136 [
self.textInputChannel invokeMethod:@"TextInputClient.onConnectionClosed"
1137 arguments:@[ @(client) ]];
1158 dispatch_async(dispatch_get_main_queue(), ^(
void) {
1159 long platform_view_id = [
self.platformViewsController firstResponderPlatformViewId];
1160 if (platform_view_id == -1) {
1164 [
self.platformViewsChannel invokeMethod:@"viewFocused" arguments:@(platform_view_id)];
1168 #pragma mark - Undo Manager Delegate
1170 - (void)handleUndoWithDirection:(FlutterUndoRedoDirection)direction {
1171 NSString* action = (direction == FlutterUndoRedoDirectionUndo) ?
@"undo" :
@"redo";
1172 [
self.undoManagerChannel invokeMethod:@"UndoManagerClient.handleUndo" arguments:@[ action ]];
1175 - (UIView<UITextInput>*)activeTextInputView {
1176 return [[
self textInputPlugin] textInputView];
1179 - (NSUndoManager*)undoManager {
1180 return self.viewController.undoManager;
1183 #pragma mark - Screenshot Delegate
1185 - (
flutter::Rasterizer::Screenshot)takeScreenshot:(
flutter::Rasterizer::ScreenshotType)type
1186 asBase64Encoded:(BOOL)base64Encode {
1187 FML_DCHECK(
_shell) <<
"Cannot takeScreenshot without a shell";
1188 return _shell->Screenshot(type, base64Encode);
1191 - (void)flutterViewAccessibilityDidCall {
1193 [
self ensureSemanticsEnabled];
1215 #pragma mark - FlutterBinaryMessenger
1217 - (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
1218 [
self sendOnChannel:channel message:message binaryReply:nil];
1221 - (void)sendOnChannel:(NSString*)channel
1222 message:(NSData*)message
1224 NSParameterAssert(channel);
1226 @"Sending a message before the FlutterEngine has been run.");
1227 fml::RefPtr<flutter::PlatformMessageResponseDarwin> response =
1228 (callback == nil) ?
nullptr
1229 : fml::MakeRefCounted<flutter::PlatformMessageResponseDarwin>(
1233 _shell->GetTaskRunners().GetPlatformTaskRunner());
1234 std::unique_ptr<flutter::PlatformMessage> platformMessage =
1235 (message == nil) ? std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response)
1236 : std::make_unique<flutter::PlatformMessage>(
1239 _shell->GetPlatformView()->DispatchPlatformMessage(std::move(platformMessage));
1249 binaryMessageHandler:
1251 return [
self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
1255 setMessageHandlerOnChannel:(NSString*)channel
1258 NSParameterAssert(channel);
1260 self.platformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.UTF8String,
1261 handler, taskQueue);
1262 return _connections->AquireConnection(channel.UTF8String);
1264 NSAssert(!handler,
@"Setting a message handler before the FlutterEngine has been run.");
1272 std::string channel =
_connections->CleanupConnection(connection);
1273 if (!channel.empty()) {
1274 self.platformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.c_str(), nil,
1280 #pragma mark - FlutterTextureRegistry
1283 FML_DCHECK(
self.platformView);
1284 int64_t textureId =
self.nextTextureId++;
1285 self.platformView->RegisterExternalTexture(textureId, texture);
1289 - (void)unregisterTexture:(int64_t)textureId {
1290 _shell->GetPlatformView()->UnregisterTexture(textureId);
1293 - (void)textureFrameAvailable:(int64_t)textureId {
1294 _shell->GetPlatformView()->MarkTextureFrameAvailable(textureId);
1297 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1301 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1305 - (id<FlutterPluginRegistry>)pluginRegistry {
1309 #pragma mark - FlutterPluginRegistry
1312 NSAssert(
self.pluginPublications[pluginKey] == nil,
@"Duplicate plugin key: %@", pluginKey);
1313 self.pluginPublications[pluginKey] = [NSNull null];
1315 flutterEngine:self];
1316 self.registrars[pluginKey] = result;
1320 - (BOOL)hasPlugin:(NSString*)pluginKey {
1321 return _pluginPublications[pluginKey] != nil;
1324 - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
1325 return _pluginPublications[pluginKey];
1328 #pragma mark - Notifications
1330 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1331 [
self flutterWillEnterForeground:notification];
1334 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1335 [
self flutterDidEnterBackground:notification];
1338 - (void)applicationWillEnterForeground:(NSNotification*)notification {
1339 [
self flutterWillEnterForeground:notification];
1342 - (void)applicationDidEnterBackground:(NSNotification*)notification {
1343 [
self flutterDidEnterBackground:notification];
1346 - (void)flutterWillEnterForeground:(NSNotification*)notification {
1347 [
self setIsGpuDisabled:NO];
1350 - (void)flutterDidEnterBackground:(NSNotification*)notification {
1351 [
self setIsGpuDisabled:YES];
1352 [
self notifyLowMemory];
1355 - (void)onMemoryWarning:(NSNotification*)notification {
1356 [
self notifyLowMemory];
1359 - (void)setIsGpuDisabled:(BOOL)value {
1361 _shell->SetGpuAvailability(value ? flutter::GpuAvailability::kUnavailable
1362 : flutter::GpuAvailability::kAvailable);
1364 _isGpuDisabled = value;
1367 #pragma mark - Locale updates
1369 - (void)onLocaleUpdated:(NSNotification*)notification {
1371 NSMutableArray<NSString*>* localeData = [[NSMutableArray alloc] init];
1372 NSArray<NSString*>* preferredLocales = [NSLocale preferredLanguages];
1373 for (NSString* localeID in preferredLocales) {
1374 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1375 NSString* languageCode = [locale objectForKey:NSLocaleLanguageCode];
1376 NSString* countryCode = [locale objectForKey:NSLocaleCountryCode];
1377 NSString* scriptCode = [locale objectForKey:NSLocaleScriptCode];
1378 NSString* variantCode = [locale objectForKey:NSLocaleVariantCode];
1379 if (!languageCode) {
1382 [localeData addObject:languageCode];
1383 [localeData addObject:(countryCode ? countryCode : @"")];
1384 [localeData addObject:(scriptCode ? scriptCode : @"")];
1385 [localeData addObject:(variantCode ? variantCode : @"")];
1387 if (localeData.count == 0) {
1390 [
self.localizationChannel invokeMethod:@"setLocale" arguments:localeData];
1393 - (void)waitForFirstFrameSync:(NSTimeInterval)timeout
1394 callback:(NS_NOESCAPE
void (^_Nonnull)(BOOL didTimeout))callback {
1395 fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000);
1396 fml::Status status =
self.shell.WaitForFirstFrame(waitTime);
1397 callback(status.code() == fml::StatusCode::kDeadlineExceeded);
1400 - (void)waitForFirstFrame:(NSTimeInterval)timeout
1401 callback:(
void (^_Nonnull)(BOOL didTimeout))callback {
1402 dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0);
1403 dispatch_group_t group = dispatch_group_create();
1406 __block BOOL didTimeout = NO;
1407 dispatch_group_async(group, queue, ^{
1413 fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000);
1414 fml::Status status = strongSelf.
shell.WaitForFirstFrame(waitTime);
1415 didTimeout = status.code() == fml::StatusCode::kDeadlineExceeded;
1419 dispatch_group_notify(group, dispatch_get_main_queue(), ^{
1433 callback(didTimeout);
1437 - (
FlutterEngine*)spawnWithEntrypoint:( NSString*)entrypoint
1438 libraryURI:( NSString*)libraryURI
1439 initialRoute:( NSString*)initialRoute
1440 entrypointArgs:( NSArray<NSString*>*)entrypointArgs {
1441 NSAssert(
_shell,
@"Spawning from an engine without a shell (possibly not run).");
1443 project:self.dartProject
1444 allowHeadlessExecution:self.allowHeadlessExecution];
1445 flutter::RunConfiguration configuration =
1446 [
self.dartProject runConfigurationForEntrypoint:entrypoint
1447 libraryOrNil:libraryURI
1448 entrypointArgs:entrypointArgs];
1450 configuration.SetEngineId(result.engineIdentifier);
1457 std::shared_ptr<flutter::IOSContext> context = ios_platform_view->
GetIosContext();
1458 FML_DCHECK(context);
1462 flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
1463 [result, context](flutter::Shell& shell) {
1464 [result recreatePlatformViewsController];
1465 result.platformViewsController.taskRunner = shell.GetTaskRunners().GetPlatformTaskRunner();
1466 return std::make_unique<flutter::PlatformViewIOS>(
1467 shell, context, result.platformViewsController, shell.GetTaskRunners());
1470 flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
1471 [](flutter::Shell& shell) {
return std::make_unique<flutter::Rasterizer>(shell); };
1473 std::string cppInitialRoute;
1475 cppInitialRoute = [initialRoute UTF8String];
1478 std::unique_ptr<flutter::Shell> shell =
_shell->Spawn(
1479 std::move(configuration), cppInitialRoute, on_create_platform_view, on_create_rasterizer);
1481 result->_threadHost = _threadHost;
1483 result->_isGpuDisabled = _isGpuDisabled;
1484 [result setUpShell:std::move(shell) withVMServicePublication:NO];
1488 - (const
flutter::ThreadHost&)threadHost {
1489 return *_threadHost;
1493 return self.dartProject;
1499 NSString* _pluginKey;
1502 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
1503 self = [
super init];
1504 NSAssert(
self,
@"Super init cannot be nil");
1505 _pluginKey = [pluginKey copy];
1506 _flutterEngine = flutterEngine;
1511 return _flutterEngine.binaryMessenger;
1515 return _flutterEngine.textureRegistry;
1518 - (void)publish:(NSObject*)value {
1519 _flutterEngine.pluginPublications[_pluginKey] = value;
1522 - (void)addMethodCallDelegate:(NSObject<
FlutterPlugin>*)delegate
1529 - (void)addApplicationDelegate:(NSObject<
FlutterPlugin>*)delegate
1530 NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in plugins used in app extensions") {
1531 id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
1533 id<FlutterAppLifeCycleProvider> lifeCycleProvider =
1534 (id<FlutterAppLifeCycleProvider>)appDelegate;
1535 [lifeCycleProvider addApplicationLifeCycleDelegate:delegate];
1539 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1540 return [_flutterEngine lookupKeyForAsset:asset];
1543 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1544 return [_flutterEngine lookupKeyForAsset:asset fromPackage:package];
1548 withId:(NSString*)factoryId {
1549 [
self registerViewFactory:factory
1551 gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager];
1555 withId:(NSString*)factoryId
1556 gestureRecognizersBlockingPolicy:
1558 [_flutterEngine.platformViewsController registerViewFactory:factory
1560 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
std::unique_ptr< flutter::ConnectionCollection > _connections
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)
Maintains a current integer assigned to a name (connections).
static Connection MakeErrorConnection(int errCode)
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)
NSObject< FlutterTextureRegistry > * parent
fml::MallocMapping CopyNSDataToMapping(NSData *data)
IOSRenderingAPI GetRenderingAPIForProcess(bool force_software)
instancetype sharedInstance()
void handleMethodCall:result:(FlutterMethodCall *call,[result] FlutterResult result)