5 #define FML_USED_ON_EMBEDDER
11 #include "flutter/common/constants.h"
12 #include "flutter/fml/message_loop.h"
13 #include "flutter/fml/platform/darwin/platform_version.h"
14 #include "flutter/fml/platform/darwin/weak_nsobject.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"
42 #include "flutter/shell/profiling/sampling_profiler.h"
48 fml::Thread::SetCurrentThreadName(config);
51 switch (config.priority) {
52 case fml::Thread::ThreadPriority::kBackground: {
53 pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0);
54 [[NSThread currentThread] setThreadPriority:0];
57 case fml::Thread::ThreadPriority::kNormal: {
58 pthread_set_qos_class_self_np(QOS_CLASS_DEFAULT, 0);
59 [[NSThread currentThread] setThreadPriority:0.5];
62 case fml::Thread::ThreadPriority::kRaster:
63 case fml::Thread::ThreadPriority::kDisplay: {
64 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
65 [[NSThread currentThread] setThreadPriority:1.0];
68 pthread_t thread = pthread_self();
69 if (!pthread_getschedparam(thread, &policy, ¶m)) {
70 param.sched_priority = 50;
71 pthread_setschedparam(thread, policy, ¶m);
78 #pragma mark - Public exported constants
83 #pragma mark - Internal constants
101 @property(nonatomic, readonly) NSMutableDictionary* pluginPublications;
102 @property(nonatomic, readonly) NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* registrars;
104 @property(nonatomic, readwrite, copy) NSString*
isolateId;
105 @property(nonatomic, copy) NSString* initialRoute;
106 @property(nonatomic, retain) id<NSObject> flutterViewControllerWillDeallocObserver;
108 #pragma mark - Embedder API properties
116 fml::scoped_nsobject<FlutterDartProject> _dartProject;
123 fml::scoped_nsobject<FlutterDartVMServicePublisher>
_publisher;
160 - (instancetype)init {
164 - (instancetype)initWithName:(NSString*)labelPrefix {
168 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
169 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
172 - (instancetype)initWithName:(NSString*)labelPrefix
174 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
175 return [
self initWithName:labelPrefix
177 allowHeadlessExecution:allowHeadlessExecution
178 restorationEnabled:NO];
181 - (instancetype)initWithName:(NSString*)labelPrefix
183 allowHeadlessExecution:(BOOL)allowHeadlessExecution
184 restorationEnabled:(BOOL)restorationEnabled {
186 NSAssert(
self,
@"Super init cannot be nil");
187 NSAssert(labelPrefix,
@"labelPrefix is required");
193 _weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(
self);
195 if (project == nil) {
198 _dartProject.reset([project retain]);
201 _enableEmbedderAPI = _dartProject.get().settings.enable_embedder_api;
202 if (_enableEmbedderAPI) {
203 NSLog(
@"============== iOS: enable_embedder_api is on ==============");
204 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
205 FlutterEngineGetProcAddresses(&_embedderAPI);
208 if (!EnableTracingIfNecessary([_dartProject.get() settings])) {
210 @"Cannot create a FlutterEngine instance in debug mode without Flutter tooling or "
211 @"Xcode.\n\nTo launch in debug mode in iOS 14+, run flutter run from Flutter tools, run "
212 @"from an IDE with a Flutter IDE plugin or run the iOS project from Xcode.\nAlternatively "
213 @"profile and release mode apps can be launched from the home screen.");
218 _pluginPublications = [[NSMutableDictionary alloc] init];
219 _registrars = [[NSMutableDictionary alloc] init];
220 [
self recreatePlatformViewController];
226 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
227 [center addObserver:self
228 selector:@selector(onMemoryWarning:)
229 name:UIApplicationDidReceiveMemoryWarningNotification
232 #if APPLICATION_EXTENSION_API_ONLY
233 if (@available(iOS 13.0, *)) {
234 [
self setUpSceneLifecycleNotifications:center];
236 [
self setUpApplicationLifecycleNotifications:center];
239 [
self setUpApplicationLifecycleNotifications:center];
242 [center addObserver:self
243 selector:@selector(onLocaleUpdated:)
244 name:NSCurrentLocaleDidChangeNotification
250 - (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) {
251 [center addObserver:self
252 selector:@selector(sceneWillEnterForeground:)
253 name:UISceneWillEnterForegroundNotification
255 [center addObserver:self
256 selector:@selector(sceneDidEnterBackground:)
257 name:UISceneDidEnterBackgroundNotification
261 - (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center {
262 [center addObserver:self
263 selector:@selector(applicationWillEnterForeground:)
264 name:UIApplicationWillEnterForegroundNotification
266 [center addObserver:self
267 selector:@selector(applicationDidEnterBackground:)
268 name:UIApplicationDidEnterBackgroundNotification
272 - (void)recreatePlatformViewController {
277 - (
flutter::IOSRenderingAPI)platformViewsRenderingAPI {
284 [_pluginPublications enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL* stop) {
285 if ([object respondsToSelector:@selector(detachFromEngineForRegistrar:)]) {
286 NSObject<FlutterPluginRegistrar>* registrar = self.registrars[key];
287 [object detachFromEngineForRegistrar:registrar];
291 [[NSNotificationCenter defaultCenter] postNotificationName:kFlutterEngineWillDealloc
301 enumerateKeysAndObjectsUsingBlock:^(id key, FlutterEngineRegistrar* registrar, BOOL* stop) {
302 registrar.flutterEngine = nil;
305 [_labelPrefix release];
306 [_initialRoute release];
307 [_pluginPublications release];
308 [_registrars release];
311 [_binaryMessenger release];
312 [_textureRegistry release];
314 [_isolateId release];
316 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
317 if (_flutterViewControllerWillDeallocObserver) {
318 [center removeObserver:_flutterViewControllerWillDeallocObserver];
319 [_flutterViewControllerWillDeallocObserver release];
321 [center removeObserver:self];
331 - (fml::WeakNSObject<FlutterEngine>)getWeakNSObject {
335 - (void)updateViewportMetrics:(
flutter::ViewportMetrics)viewportMetrics {
336 if (!
self.platformView) {
339 self.platformView->SetViewportMetrics(flutter::kFlutterImplicitViewId, viewportMetrics);
342 - (void)dispatchPointerDataPacket:(std::unique_ptr<
flutter::PointerDataPacket>)packet {
343 if (!
self.platformView) {
346 self.platformView->DispatchPointerDataPacket(std::move(packet));
349 - (fml::WeakPtr<flutter::PlatformView>)platformView {
351 return _shell->GetPlatformView();
354 - (
flutter::PlatformViewIOS*)iosPlatformView {
359 - (fml::RefPtr<fml::TaskRunner>)platformTaskRunner {
361 return _shell->GetTaskRunners().GetPlatformTaskRunner();
364 - (fml::RefPtr<fml::TaskRunner>)uiTaskRunner {
366 return _shell->GetTaskRunners().GetUITaskRunner();
369 - (fml::RefPtr<fml::TaskRunner>)rasterTaskRunner {
371 return _shell->GetTaskRunners().GetRasterTaskRunner();
374 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
375 callback:(FlutterKeyEventCallback)callback
376 userData:(
void*)userData API_AVAILABLE(ios(13.4)) {
377 if (@available(iOS 13.4, *)) {
381 if (!
self.platformView) {
384 const char* character =
event.character;
386 flutter::KeyData key_data;
388 key_data.timestamp = (uint64_t)event.timestamp;
389 switch (event.type) {
390 case kFlutterKeyEventTypeUp:
391 key_data.type = flutter::KeyEventType::kUp;
393 case kFlutterKeyEventTypeDown:
394 key_data.type = flutter::KeyEventType::kDown;
396 case kFlutterKeyEventTypeRepeat:
397 key_data.type = flutter::KeyEventType::kRepeat;
400 key_data.physical =
event.physical;
401 key_data.logical =
event.logical;
402 key_data.synthesized =
event.synthesized;
404 auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character);
405 NSData* message = [NSData dataWithBytes:packet->data().data() length:packet->data().size()];
407 auto response = ^(NSData* reply) {
408 if (callback ==
nullptr) {
411 BOOL handled = FALSE;
412 if (reply.length == 1 && *
reinterpret_cast<const uint8_t*
>(reply.bytes) == 1) {
415 callback(handled, userData);
418 [
self sendOnChannel:kFlutterKeyDataChannel message:message binaryReply:response];
421 - (void)ensureSemanticsEnabled {
422 self.iosPlatformView->SetSemanticsEnabled(
true);
426 FML_DCHECK(
self.iosPlatformView);
428 : fml::WeakNSObject<FlutterViewController>();
430 [
self maybeSetupPlatformViewChannels];
431 [
self updateDisplays];
437 self.flutterViewControllerWillDeallocObserver =
438 [[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc
439 object:viewController
440 queue:[NSOperationQueue mainQueue]
441 usingBlock:^(NSNotification* note) {
442 [blockSelf notifyViewControllerDeallocated];
445 self.flutterViewControllerWillDeallocObserver = nil;
446 [
self notifyLowMemory];
451 self.iosPlatformView->attachView();
454 - (void)setFlutterViewControllerWillDeallocObserver:(
id<NSObject>)observer {
455 if (observer != _flutterViewControllerWillDeallocObserver) {
456 if (_flutterViewControllerWillDeallocObserver) {
457 [[NSNotificationCenter defaultCenter]
458 removeObserver:_flutterViewControllerWillDeallocObserver];
459 [_flutterViewControllerWillDeallocObserver release];
461 _flutterViewControllerWillDeallocObserver = [observer retain];
465 - (void)notifyViewControllerDeallocated {
466 [[
self lifecycleChannel] sendMessage:@"AppLifecycleState.detached"];
470 [
self destroyContext];
477 [_textInputPlugin.get() resetViewResponder];
481 - (void)destroyContext {
482 [
self resetChannels];
483 self.isolateId = nil;
500 - (std::shared_ptr<flutter::FlutterPlatformViewsController>&)platformViewsController {
549 - (NSURL*)observatoryUrl {
550 return [_publisher.get() url];
553 - (NSURL*)vmServiceUrl {
554 return [_publisher.get() url];
557 - (void)resetChannels {
573 - (void)startProfiler {
576 _profiler = std::make_shared<flutter::SamplingProfiler>(
585 - (void)setUpChannels {
588 fml::WeakNSObject<FlutterEngine> weakSelf = [
self getWeakNSObject];
589 [_binaryMessenger setMessageHandlerOnChannel:@"flutter/isolate"
590 binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) {
592 weakSelf.get().isolateId =
598 initWithName:
@"flutter/localization"
599 binaryMessenger:
self.binaryMessenger
603 initWithName:
@"flutter/navigation"
604 binaryMessenger:
self.binaryMessenger
607 if ([_initialRoute length] > 0) {
609 [_navigationChannel invokeMethod:@"setInitialRoute" arguments:_initialRoute];
610 [_initialRoute release];
615 initWithName:
@"flutter/restoration"
616 binaryMessenger:
self.binaryMessenger
620 initWithName:
@"flutter/platform"
621 binaryMessenger:
self.binaryMessenger
625 initWithName:
@"flutter/platform_views"
626 binaryMessenger:
self.binaryMessenger
630 initWithName:
@"flutter/textinput"
631 binaryMessenger:
self.binaryMessenger
635 initWithName:
@"flutter/undomanager"
636 binaryMessenger:
self.binaryMessenger
640 initWithName:
@"flutter/scribble"
641 binaryMessenger:
self.binaryMessenger
645 initWithName:
@"flutter/spellcheck"
646 binaryMessenger:
self.binaryMessenger
650 initWithName:
@"flutter/lifecycle"
651 binaryMessenger:
self.binaryMessenger
655 initWithName:
@"flutter/system"
656 binaryMessenger:
self.binaryMessenger
660 initWithName:
@"flutter/settings"
661 binaryMessenger:
self.binaryMessenger
665 initWithName:
@"flutter/keyevent"
666 binaryMessenger:
self.binaryMessenger
686 initWithName:
@"flutter/screenshot"
687 binaryMessenger:
self.binaryMessenger
690 [_screenshotChannel.get()
691 setMethodCallHandler:^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) {
692 if (!(weakSelf.get() && weakSelf.get()->_shell && weakSelf.get()->_shell->IsSetup())) {
695 message:@"Requesting screenshot while engine is not running."
698 flutter::Rasterizer::Screenshot screenshot =
699 [weakSelf.get() screenshot:flutter::Rasterizer::ScreenshotType::SurfaceData
701 if (!screenshot.data) {
703 message:@"Unable to get screenshot."
707 NSData* data = [NSData dataWithBytes:screenshot.data->writable_data()
708 length:screenshot.data->size()];
709 NSString* format = [NSString stringWithUTF8String:screenshot.format.c_str()];
710 NSNumber* width = @(screenshot.frame_size.fWidth);
711 NSNumber* height = @(screenshot.frame_size.fHeight);
712 return result(@[ width, height, format ?: [NSNull null], data ]);
716 - (void)maybeSetupPlatformViewChannels {
717 if (
_shell &&
self.shell.IsSetup()) {
719 [_platformChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
723 fml::WeakNSObject<FlutterEngine> weakSelf = [
self getWeakNSObject];
724 [_platformViewsChannel.get()
725 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
727 weakSelf.get().platformViewsController->OnMethodCall(call, result);
732 [_textInputChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
737 [_undoManagerChannel.get()
738 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
743 [_spellCheckChannel.get()
744 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
750 - (
flutter::Rasterizer::Screenshot)screenshot:(
flutter::Rasterizer::ScreenshotType)type
751 base64Encode:(
bool)base64Encode {
752 return self.shell.Screenshot(type, base64Encode);
755 - (void)launchEngine:(NSString*)entrypoint
756 libraryURI:(NSString*)libraryOrNil
757 entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
759 self.shell.RunEngine([_dartProject.get() runConfigurationForEntrypoint:entrypoint
760 libraryOrNil:libraryOrNil
761 entrypointArgs:entrypointArgs]);
764 - (void)setUpShell:(std::unique_ptr<
flutter::Shell>)shell
765 withVMServicePublication:(BOOL)doesVMServicePublication {
766 _shell = std::move(shell);
767 [
self setUpChannels];
768 [
self onLocaleUpdated:nil];
769 [
self updateDisplays];
771 initWithEnableVMServicePublication:doesVMServicePublication]);
772 [
self maybeSetupPlatformViewChannels];
773 _shell->SetGpuAvailability(_isGpuDisabled ? flutter::GpuAvailability::kUnavailable
774 : flutter::GpuAvailability::kAvailable);
777 + (BOOL)isProfilerEnabled {
778 bool profilerEnabled =
false;
779 #if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) || \
780 (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE)
781 profilerEnabled =
true;
783 return profilerEnabled;
786 + (NSString*)generateThreadLabel:(NSString*)labelPrefix {
787 static size_t s_shellCount = 0;
788 return [NSString stringWithFormat:@"%@.%zu", labelPrefix, ++s_shellCount];
791 + (
flutter::ThreadHost)makeThreadHost:(NSString*)threadLabel {
794 fml::MessageLoop::EnsureInitializedForCurrentThread();
796 uint32_t threadHostType = flutter::ThreadHost::Type::kUi | flutter::ThreadHost::Type::kRaster |
797 flutter::ThreadHost::Type::kIo;
800 threadHostType = threadHostType | flutter::ThreadHost::Type::kProfiler;
803 flutter::ThreadHost::ThreadHostConfig host_config(threadLabel.UTF8String, threadHostType,
806 host_config.ui_config =
807 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
808 flutter::ThreadHost::Type::kUi, threadLabel.UTF8String),
809 fml::Thread::ThreadPriority::kDisplay);
811 host_config.raster_config =
812 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
813 flutter::ThreadHost::Type::kRaster, threadLabel.UTF8String),
814 fml::Thread::ThreadPriority::kRaster);
816 host_config.io_config =
817 fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName(
818 flutter::ThreadHost::Type::kIo, threadLabel.UTF8String),
819 fml::Thread::ThreadPriority::kNormal);
821 return (flutter::ThreadHost){host_config};
824 static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSString* libraryURI) {
826 FML_DCHECK(entrypoint) <<
"Must specify entrypoint if specifying library";
827 settings->advisory_script_entrypoint = entrypoint.UTF8String;
828 settings->advisory_script_uri = libraryURI.UTF8String;
829 }
else if (entrypoint) {
830 settings->advisory_script_entrypoint = entrypoint.UTF8String;
831 settings->advisory_script_uri = std::string(
"main.dart");
833 settings->advisory_script_entrypoint = std::string(
"main");
834 settings->advisory_script_uri = std::string(
"main.dart");
838 - (BOOL)createShell:(NSString*)entrypoint
839 libraryURI:(NSString*)libraryURI
840 initialRoute:(NSString*)initialRoute {
842 FML_LOG(WARNING) <<
"This FlutterEngine was already invoked.";
846 self.initialRoute = initialRoute;
848 auto settings = [_dartProject.get() settings];
849 if (initialRoute != nil) {
850 self.initialRoute = initialRoute;
851 }
else if (settings.route.empty() ==
false) {
852 self.initialRoute = [NSString stringWithUTF8String:settings.route.c_str()];
857 auto platformData = [_dartProject.get() defaultPlatformData];
859 SetEntryPoint(&settings, entrypoint, libraryURI);
861 NSString* threadLabel = [
FlutterEngine generateThreadLabel:_labelPrefix];
862 _threadHost = std::make_shared<flutter::ThreadHost>();
867 flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
868 [
self](flutter::Shell& shell) {
869 [
self recreatePlatformViewController];
870 return std::make_unique<flutter::PlatformViewIOS>(
871 shell,
self->_renderingApi,
self->_platformViewsController, shell.GetTaskRunners(),
872 shell.GetConcurrentWorkerTaskRunner(), shell.GetIsGpuDisabledSyncSwitch());
875 flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
876 [](flutter::Shell& shell) {
return std::make_unique<flutter::Rasterizer>(shell); };
878 flutter::TaskRunners task_runners(threadLabel.UTF8String,
879 fml::MessageLoop::GetCurrent().GetTaskRunner(),
885 #if APPLICATION_EXTENSION_API_ONLY
886 if (@available(iOS 13.0, *)) {
887 _isGpuDisabled =
self.viewController.flutterWindowSceneIfViewLoaded.activationState ==
888 UISceneActivationStateBackground;
896 [UIApplication sharedApplication].applicationState == UIApplicationStateBackground;
900 std::unique_ptr<flutter::Shell> shell = flutter::Shell::Create(
904 on_create_platform_view,
905 on_create_rasterizer,
908 if (shell ==
nullptr) {
909 FML_LOG(ERROR) <<
"Could not start a shell FlutterEngine with entrypoint: "
910 << entrypoint.UTF8String;
913 FML_LOG(INFO) <<
"Enabled VM Service Publication: " << settings.enable_vm_service_publication;
914 [
self setUpShell:std::move(shell)
915 withVMServicePublication:settings.enable_vm_service_publication];
917 [
self startProfiler];
924 - (void)updateDisplays {
929 auto vsync_waiter =
_shell->GetVsyncWaiter().lock();
930 auto vsync_waiter_ios = std::static_pointer_cast<flutter::VsyncWaiterIOS>(vsync_waiter);
931 std::vector<std::unique_ptr<flutter::Display>> displays;
932 auto screen_size = UIScreen.mainScreen.nativeBounds.size;
933 auto scale = UIScreen.mainScreen.scale;
934 displays.push_back(std::make_unique<flutter::VariableRefreshRateDisplay>(
935 0, vsync_waiter_ios, screen_size.width, screen_size.height, scale));
936 _shell->OnDisplayUpdates(std::move(displays));
945 - (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
946 return [
self runWithEntrypoint:entrypoint
947 libraryURI:libraryURI
948 initialRoute:FlutterDefaultInitialRoute];
951 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
952 return [
self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:FlutterDefaultInitialRoute];
955 - (BOOL)runWithEntrypoint:(NSString*)entrypoint initialRoute:(NSString*)initialRoute {
956 return [
self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:initialRoute];
959 - (BOOL)runWithEntrypoint:(NSString*)entrypoint
960 libraryURI:(NSString*)libraryURI
961 initialRoute:(NSString*)initialRoute {
962 return [
self runWithEntrypoint:entrypoint
963 libraryURI:libraryURI
964 initialRoute:initialRoute
968 - (BOOL)runWithEntrypoint:(NSString*)entrypoint
969 libraryURI:(NSString*)libraryURI
970 initialRoute:(NSString*)initialRoute
971 entrypointArgs:(NSArray<NSString*>*)entrypointArgs {
972 if ([
self createShell:entrypoint libraryURI:libraryURI initialRoute:initialRoute]) {
973 [
self launchEngine:entrypoint libraryURI:libraryURI entrypointArgs:entrypointArgs];
979 - (void)notifyLowMemory {
981 _shell->NotifyLowMemoryWarning();
983 [_systemChannel sendMessage:@{@"type" : @"memoryPressure"}];
986 #pragma mark - Text input delegate
989 updateEditingClient:(
int)client
990 withState:(NSDictionary*)state {
991 [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingState"
992 arguments:@[ @(client), state ]];
996 updateEditingClient:(
int)client
997 withState:(NSDictionary*)state
998 withTag:(NSString*)tag {
999 [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingStateWithTag"
1000 arguments:@[ @(client), @{tag : state} ]];
1004 updateEditingClient:(
int)client
1005 withDelta:(NSDictionary*)delta {
1006 [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingStateWithDeltas"
1007 arguments:@[ @(client), delta ]];
1011 updateFloatingCursor:(FlutterFloatingCursorDragState)state
1012 withClient:(
int)client
1013 withPosition:(NSDictionary*)position {
1014 NSString* stateString;
1016 case FlutterFloatingCursorDragStateStart:
1017 stateString =
@"FloatingCursorDragState.start";
1019 case FlutterFloatingCursorDragStateUpdate:
1020 stateString =
@"FloatingCursorDragState.update";
1022 case FlutterFloatingCursorDragStateEnd:
1023 stateString =
@"FloatingCursorDragState.end";
1026 [_textInputChannel.get() invokeMethod:@"TextInputClient.updateFloatingCursor"
1027 arguments:@[ @(client), stateString, position ]];
1031 performAction:(FlutterTextInputAction)action
1032 withClient:(
int)client {
1033 NSString* actionString;
1035 case FlutterTextInputActionUnspecified:
1040 actionString =
@"TextInputAction.unspecified";
1042 case FlutterTextInputActionDone:
1043 actionString =
@"TextInputAction.done";
1045 case FlutterTextInputActionGo:
1046 actionString =
@"TextInputAction.go";
1048 case FlutterTextInputActionSend:
1049 actionString =
@"TextInputAction.send";
1051 case FlutterTextInputActionSearch:
1052 actionString =
@"TextInputAction.search";
1054 case FlutterTextInputActionNext:
1055 actionString =
@"TextInputAction.next";
1057 case FlutterTextInputActionContinue:
1058 actionString =
@"TextInputAction.continueAction";
1060 case FlutterTextInputActionJoin:
1061 actionString =
@"TextInputAction.join";
1063 case FlutterTextInputActionRoute:
1064 actionString =
@"TextInputAction.route";
1066 case FlutterTextInputActionEmergencyCall:
1067 actionString =
@"TextInputAction.emergencyCall";
1069 case FlutterTextInputActionNewline:
1070 actionString =
@"TextInputAction.newline";
1073 [_textInputChannel.get() invokeMethod:@"TextInputClient.performAction"
1074 arguments:@[ @(client), actionString ]];
1078 showAutocorrectionPromptRectForStart:(NSUInteger)start
1080 withClient:(
int)client {
1081 [_textInputChannel.get() invokeMethod:@"TextInputClient.showAutocorrectionPromptRect"
1082 arguments:@[ @(client), @(start), @(end) ]];
1085 #pragma mark - FlutterViewEngineDelegate
1091 [_textInputChannel.get() invokeMethod:@"TextInputClient.showToolbar" arguments:@[ @(client) ]];
1095 focusElement:(UIScribbleElementIdentifier)elementIdentifier
1096 atPoint:(CGPoint)referencePoint
1101 [_textInputChannel.get()
1102 invokeMethod:@"TextInputClient.focusElement"
1103 arguments:@[ elementIdentifier, @(referencePoint.x), @(referencePoint.y) ]
1108 requestElementsInRect:(CGRect)rect
1113 [_textInputChannel.get()
1114 invokeMethod:@"TextInputClient.requestElementsInRect"
1115 arguments:@[ @(rect.origin.x), @(rect.origin.y), @(rect.size.width), @(rect.size.height) ]
1123 [_textInputChannel.get() invokeMethod:@"TextInputClient.scribbleInteractionBegan" arguments:nil];
1130 [_textInputChannel.get() invokeMethod:@"TextInputClient.scribbleInteractionFinished"
1135 insertTextPlaceholderWithSize:(CGSize)size
1136 withClient:(
int)client {
1140 [_textInputChannel.get() invokeMethod:@"TextInputClient.insertTextPlaceholder"
1141 arguments:@[ @(client), @(size.width), @(size.height) ]];
1145 removeTextPlaceholder:(
int)client {
1149 [_textInputChannel.get() invokeMethod:@"TextInputClient.removeTextPlaceholder"
1150 arguments:@[ @(client) ]];
1154 didResignFirstResponderWithTextInputClient:(
int)client {
1158 [_textInputChannel.get() invokeMethod:@"TextInputClient.onConnectionClosed"
1159 arguments:@[ @(client) ]];
1180 dispatch_async(dispatch_get_main_queue(), ^(
void) {
1181 long platform_view_id =
self.platformViewsController->FindFirstResponderPlatformViewId();
1182 if (platform_view_id == -1) {
1186 [_platformViewsChannel.get() invokeMethod:@"viewFocused" arguments:@(platform_view_id)];
1190 #pragma mark - Undo Manager Delegate
1193 handleUndoWithDirection:(FlutterUndoRedoDirection)direction {
1194 NSString* action = (direction == FlutterUndoRedoDirectionUndo) ?
@"undo" :
@"redo";
1195 [_undoManagerChannel.get() invokeMethod:@"UndoManagerClient.handleUndo" arguments:@[ action ]];
1198 #pragma mark - Screenshot Delegate
1200 - (
flutter::Rasterizer::Screenshot)takeScreenshot:(
flutter::Rasterizer::ScreenshotType)type
1201 asBase64Encoded:(BOOL)base64Encode {
1202 FML_DCHECK(
_shell) <<
"Cannot takeScreenshot without a shell";
1203 return _shell->Screenshot(type, base64Encode);
1206 - (void)flutterViewAccessibilityDidCall {
1208 [
self ensureSemanticsEnabled];
1226 [_binaryMessenger release];
1231 #pragma mark - FlutterBinaryMessenger
1233 - (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
1234 [
self sendOnChannel:channel message:message binaryReply:nil];
1237 - (void)sendOnChannel:(NSString*)channel
1238 message:(NSData*)message
1240 NSParameterAssert(channel);
1242 @"Sending a message before the FlutterEngine has been run.");
1243 fml::RefPtr<flutter::PlatformMessageResponseDarwin> response =
1244 (callback == nil) ?
nullptr
1245 : fml::MakeRefCounted<flutter::PlatformMessageResponseDarwin>(
1249 _shell->GetTaskRunners().GetPlatformTaskRunner());
1250 std::unique_ptr<flutter::PlatformMessage> platformMessage =
1251 (message == nil) ? std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response)
1252 : std::make_unique<flutter::PlatformMessage>(
1255 _shell->GetPlatformView()->DispatchPlatformMessage(std::move(platformMessage));
1265 binaryMessageHandler:
1267 return [
self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
1271 setMessageHandlerOnChannel:(NSString*)channel
1274 NSParameterAssert(channel);
1276 self.iosPlatformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.UTF8String,
1277 handler, taskQueue);
1278 return _connections->AquireConnection(channel.UTF8String);
1280 NSAssert(!handler,
@"Setting a message handler before the FlutterEngine has been run.");
1288 std::string channel =
_connections->CleanupConnection(connection);
1289 if (!channel.empty()) {
1290 self.iosPlatformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.c_str(), nil,
1296 #pragma mark - FlutterTextureRegistry
1300 self.iosPlatformView->RegisterExternalTexture(textureId, texture);
1304 - (void)unregisterTexture:(int64_t)textureId {
1305 _shell->GetPlatformView()->UnregisterTexture(textureId);
1308 - (void)textureFrameAvailable:(int64_t)textureId {
1309 _shell->GetPlatformView()->MarkTextureFrameAvailable(textureId);
1312 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1316 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1320 - (id<FlutterPluginRegistry>)pluginRegistry {
1324 #pragma mark - FlutterPluginRegistry
1327 NSAssert(
self.pluginPublications[pluginKey] == nil,
@"Duplicate plugin key: %@", pluginKey);
1328 self.pluginPublications[pluginKey] = [NSNull null];
1330 flutterEngine:self];
1331 self.registrars[pluginKey] = result;
1332 return [result autorelease];
1335 - (BOOL)hasPlugin:(NSString*)pluginKey {
1336 return _pluginPublications[pluginKey] != nil;
1339 - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
1340 return _pluginPublications[pluginKey];
1343 #pragma mark - Notifications
1345 #if APPLICATION_EXTENSION_API_ONLY
1346 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1347 [
self flutterWillEnterForeground:notification];
1350 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1351 [
self flutterDidEnterBackground:notification];
1354 - (void)applicationWillEnterForeground:(NSNotification*)notification {
1355 [
self flutterWillEnterForeground:notification];
1358 - (void)applicationDidEnterBackground:(NSNotification*)notification {
1359 [
self flutterDidEnterBackground:notification];
1363 - (void)flutterWillEnterForeground:(NSNotification*)notification {
1364 [
self setIsGpuDisabled:NO];
1367 - (void)flutterDidEnterBackground:(NSNotification*)notification {
1368 [
self setIsGpuDisabled:YES];
1369 [
self notifyLowMemory];
1372 - (void)onMemoryWarning:(NSNotification*)notification {
1373 [
self notifyLowMemory];
1376 - (void)setIsGpuDisabled:(BOOL)value {
1378 _shell->SetGpuAvailability(value ? flutter::GpuAvailability::kUnavailable
1379 : flutter::GpuAvailability::kAvailable);
1381 _isGpuDisabled = value;
1384 #pragma mark - Locale updates
1386 - (void)onLocaleUpdated:(NSNotification*)notification {
1388 NSMutableArray<NSString*>* localeData = [[[NSMutableArray alloc] init] autorelease];
1389 NSArray<NSString*>* preferredLocales = [NSLocale preferredLanguages];
1390 for (NSString* localeID in preferredLocales) {
1391 NSLocale* locale = [[[NSLocale alloc] initWithLocaleIdentifier:localeID] autorelease];
1392 NSString* languageCode = [locale objectForKey:NSLocaleLanguageCode];
1393 NSString* countryCode = [locale objectForKey:NSLocaleCountryCode];
1394 NSString* scriptCode = [locale objectForKey:NSLocaleScriptCode];
1395 NSString* variantCode = [locale objectForKey:NSLocaleVariantCode];
1396 if (!languageCode) {
1399 [localeData addObject:languageCode];
1400 [localeData addObject:(countryCode ? countryCode : @"")];
1401 [localeData addObject:(scriptCode ? scriptCode : @"")];
1402 [localeData addObject:(variantCode ? variantCode : @"")];
1404 if (localeData.count == 0) {
1407 [
self.localizationChannel invokeMethod:@"setLocale" arguments:localeData];
1410 - (void)waitForFirstFrame:(NSTimeInterval)timeout
1411 callback:(
void (^_Nonnull)(BOOL didTimeout))callback {
1412 dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0);
1413 dispatch_async(queue, ^{
1414 fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000);
1416 self.shell.WaitForFirstFrame(waitTime).code() == fml::StatusCode::kDeadlineExceeded;
1417 dispatch_async(dispatch_get_main_queue(), ^{
1418 callback(didTimeout);
1423 - (
FlutterEngine*)spawnWithEntrypoint:( NSString*)entrypoint
1424 libraryURI:( NSString*)libraryURI
1425 initialRoute:( NSString*)initialRoute
1426 entrypointArgs:( NSArray<NSString*>*)entrypointArgs {
1427 NSAssert(
_shell,
@"Spawning from an engine without a shell (possibly not run).");
1429 project:_dartProject.get()
1430 allowHeadlessExecution:_allowHeadlessExecution];
1431 flutter::RunConfiguration configuration =
1432 [_dartProject.get() runConfigurationForEntrypoint:entrypoint
1433 libraryOrNil:libraryURI
1434 entrypointArgs:entrypointArgs];
1441 std::shared_ptr<flutter::IOSContext> context = ios_platform_view->
GetIosContext();
1442 FML_DCHECK(context);
1446 flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
1447 [result, context](flutter::Shell& shell) {
1448 [result recreatePlatformViewController];
1449 return std::make_unique<flutter::PlatformViewIOS>(
1450 shell, context, result->_platformViewsController, shell.GetTaskRunners());
1453 flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
1454 [](flutter::Shell& shell) {
return std::make_unique<flutter::Rasterizer>(shell); };
1456 std::string cppInitialRoute;
1458 cppInitialRoute = [initialRoute UTF8String];
1461 std::unique_ptr<flutter::Shell> shell =
_shell->Spawn(
1462 std::move(configuration), cppInitialRoute, on_create_platform_view, on_create_rasterizer);
1467 result->_isGpuDisabled = _isGpuDisabled;
1468 [result setUpShell:std::move(shell) withVMServicePublication:NO];
1469 return [result autorelease];
1472 - (const
flutter::ThreadHost&)threadHost {
1477 return _dartProject.get();
1480 - (BOOL)isUsingImpeller {
1487 NSString* _pluginKey;
1490 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
1491 self = [
super init];
1492 NSAssert(
self,
@"Super init cannot be nil");
1493 _pluginKey = [pluginKey copy];
1494 _flutterEngine = flutterEngine;
1499 [_pluginKey release];
1504 return _flutterEngine.binaryMessenger;
1508 return _flutterEngine.textureRegistry;
1511 - (void)publish:(NSObject*)value {
1512 _flutterEngine.pluginPublications[_pluginKey] = value;
1515 - (void)addMethodCallDelegate:(NSObject<
FlutterPlugin>*)delegate
1522 - (void)addApplicationDelegate:(NSObject<
FlutterPlugin>*)delegate
1523 NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in plugins used in app extensions") {
1524 id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
1526 id<FlutterAppLifeCycleProvider> lifeCycleProvider =
1527 (id<FlutterAppLifeCycleProvider>)appDelegate;
1528 [lifeCycleProvider addApplicationLifeCycleDelegate:delegate];
1532 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1533 return [_flutterEngine lookupKeyForAsset:asset];
1536 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1537 return [_flutterEngine lookupKeyForAsset:asset fromPackage:package];
1541 withId:(NSString*)factoryId {
1542 [
self registerViewFactory:factory
1544 gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager];
1548 withId:(NSString*)factoryId
1549 gestureRecognizersBlockingPolicy:
1551 [_flutterEngine platformViewsController]->RegisterViewFactory(factory, factoryId,
1552 gestureRecognizersBlockingPolicy);