13 #include "flutter/common/constants.h"
16 #include "flutter/shell/platform/embedder/embedder.h"
18 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
20 #import "flutter/shell/platform/darwin/macos/InternalFlutterSwift/InternalFlutterSwift.h"
41 using flutter::kFlutterImplicitViewId;
48 FlutterLocale flutterLocale = {};
49 flutterLocale.struct_size =
sizeof(FlutterLocale);
50 flutterLocale.language_code = [[locale objectForKey:NSLocaleLanguageCode] UTF8String];
51 flutterLocale.country_code = [[locale objectForKey:NSLocaleCountryCode] UTF8String];
52 flutterLocale.script_code = [[locale objectForKey:NSLocaleScriptCode] UTF8String];
53 flutterLocale.variant_code = [[locale objectForKey:NSLocaleVariantCode] UTF8String];
59 @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification";
71 - (instancetype)initWithConnection:(NSNumber*)connection
80 - (instancetype)initWithConnection:(NSNumber*)connection
83 NSAssert(
self,
@"Super init cannot be nil");
105 @property(nonatomic, strong) NSMutableArray<NSNumber*>* isResponseValid;
110 @property(nonatomic, strong) NSPointerArray* pluginAppDelegates;
115 @property(nonatomic, readonly)
116 NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* pluginRegistrars;
143 - (void)shutDownIfNeeded;
148 - (void)sendUserLocales;
153 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message;
161 - (void)engineCallbackOnPreEngineRestart;
167 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime;
173 - (void)loadAOTData:(NSString*)assetsDir;
178 - (void)setUpPlatformViewChannel;
183 - (void)setUpAccessibilityChannel;
202 _acceptingRequests = NO;
204 _terminator = terminator ? terminator : ^(
id sender) {
207 [[NSApplication sharedApplication] terminate:sender];
209 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
210 if ([appDelegate respondsToSelector:
@selector(setTerminationHandler:)]) {
212 flutterAppDelegate.terminationHandler =
self;
219 - (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*,
id>*)arguments
221 NSString* type = arguments[@"type"];
227 FlutterAppExitType exitType =
228 [type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired;
230 [
self requestApplicationTermination:[NSApplication sharedApplication]
237 - (void)requestApplicationTermination:(
id)sender
238 exitType:(FlutterAppExitType)type
240 _shouldTerminate = YES;
241 if (![
self acceptingRequests]) {
244 type = kFlutterAppExitTypeRequired;
247 case kFlutterAppExitTypeCancelable: {
251 [_engine sendOnChannel:kFlutterPlatformChannel
252 message:[codec encodeMethodCall:methodCall]
253 binaryReply:^(NSData* _Nullable reply) {
254 NSAssert(_terminator, @"terminator shouldn't be nil");
255 id decoded_reply = [codec decodeEnvelope:reply];
256 if ([decoded_reply isKindOfClass:[
FlutterError class]]) {
258 NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message],
263 if (![decoded_reply isKindOfClass:[NSDictionary class]]) {
264 NSLog(@"Call to System.requestAppExit returned an unexpected object: %@",
269 NSDictionary* replyArgs = (NSDictionary*)decoded_reply;
270 if ([replyArgs[@"response"] isEqual:@"exit"]) {
272 } else if ([replyArgs[@"response"] isEqual:@"cancel"]) {
273 _shouldTerminate = NO;
281 case kFlutterAppExitTypeRequired:
282 NSAssert(
_terminator,
@"terminator shouldn't be nil");
295 return [[NSPasteboard generalPasteboard] clearContents];
298 - (NSString*)stringForType:(NSPasteboardType)dataType {
299 return [[NSPasteboard generalPasteboard] stringForType:dataType];
302 - (BOOL)setString:(nonnull NSString*)string forType:(nonnull NSPasteboardType)dataType {
303 return [[NSPasteboard generalPasteboard] setString:string forType:dataType];
314 - (instancetype)initWithPlugin:(nonnull NSString*)pluginKey
328 NSString* _pluginKey;
334 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
337 _pluginKey = [pluginKey copy];
339 _publishedValue = [NSNull null];
344 #pragma mark - FlutterPluginRegistrar
355 return [
self viewForIdentifier:kFlutterImplicitViewId];
360 if (controller == nil) {
363 if (!controller.viewLoaded) {
364 [controller loadView];
366 return controller.flutterView;
369 - (void)addMethodCallDelegate:(nonnull
id<
FlutterPlugin>)delegate
377 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
379 id<FlutterAppLifecycleProvider> lifeCycleProvider =
380 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
381 [lifeCycleProvider addApplicationLifecycleDelegate:delegate];
382 [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
387 withId:(nonnull NSString*)factoryId {
388 [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
391 - (void)publish:(NSObject*)value {
392 _publishedValue = value;
395 - (NSString*)lookupKeyForAsset:(NSString*)asset {
399 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
406 #pragma mark - Static methods provided to engine configuration
410 [engine engineCallbackOnPlatformMessage:message];
502 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
503 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
508 static void SetThreadPriority(FlutterThreadPriority priority) {
509 if (priority == kDisplay || priority == kRaster) {
510 pthread_t thread = pthread_self();
513 if (!pthread_getschedparam(thread, &policy, ¶m)) {
515 pthread_setschedparam(thread, policy, ¶m);
517 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
521 - (instancetype)initWithName:(NSString*)labelPrefix
523 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
525 NSAssert(
self,
@"Super init cannot be nil");
527 [FlutterRunLoop ensureMainLoopInitialized];
535 _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
536 _pluginRegistrars = [[NSMutableDictionary alloc] init];
539 _semanticsEnabled = NO;
541 _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
542 [_isResponseValid addObject:@YES];
548 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
549 FlutterEngineGetProcAddresses(&_embedderAPI);
554 NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
555 [notificationCenter addObserver:self
556 selector:@selector(sendUserLocales)
557 name:NSCurrentLocaleDidChangeNotification
567 [
self setUpPlatformViewChannel];
572 [
self setUpAccessibilityChannel];
573 [
self setUpNotificationCenterListeners];
574 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
578 id<FlutterAppLifecycleProvider> lifecycleProvider =
579 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
580 [lifecycleProvider addApplicationLifecycleDelegate:self];
582 _terminationHandler = nil;
591 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
593 id<FlutterAppLifecycleProvider> lifecycleProvider =
594 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
595 [lifecycleProvider removeApplicationLifecycleDelegate:self];
600 for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
602 [lifecycleProvider removeApplicationLifecycleDelegate:delegate];
608 for (NSString* pluginName in _pluginRegistrars) {
609 [_pluginRegistrars[pluginName] publish:[NSNull null]];
611 @
synchronized(_isResponseValid) {
612 [_isResponseValid removeAllObjects];
613 [_isResponseValid addObject:@NO];
615 [
self shutDownEngine];
617 _embedderAPI.CollectAOTData(
_aotData);
621 - (FlutterTaskRunnerDescription)createPlatformThreadTaskDescription {
622 static size_t sTaskRunnerIdentifiers = 0;
623 FlutterTaskRunnerDescription cocoa_task_runner_description = {
624 .struct_size =
sizeof(FlutterTaskRunnerDescription),
626 .
user_data = (__bridge_retained
void*)
self,
627 .runs_task_on_current_thread_callback = [](
void*
user_data) ->
bool {
628 return [[NSThread currentThread] isMainThread];
630 .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
633 [engine postMainThreadTask:task targetTimeInNanoseconds:target_time_nanos];
635 .identifier = ++sTaskRunnerIdentifiers,
636 .destruction_callback =
643 return cocoa_task_runner_description;
646 - (void)onFocusChangeRequest:(const FlutterViewFocusChangeRequest*)request {
648 if (controller == nil) {
651 if (request->state == kFocused) {
652 [controller.flutterView.window makeFirstResponder:controller.flutterView];
656 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
662 NSLog(
@"Attempted to run an engine with no view controller without headless mode enabled.");
666 [
self addInternalPlugins];
669 std::vector<const char*> argv = {[
self.executableName UTF8String]};
670 std::vector<std::string> switches =
self.switches;
674 std::find(switches.begin(), switches.end(),
"--enable-impeller=true") != switches.end()) {
675 switches.push_back(
"--enable-impeller=true");
679 std::find(switches.begin(), switches.end(),
"--enable-flutter-gpu=true") != switches.end()) {
680 switches.push_back(
"--enable-flutter-gpu=true");
683 std::transform(switches.begin(), switches.end(), std::back_inserter(argv),
684 [](
const std::string& arg) ->
const char* { return arg.c_str(); });
686 std::vector<const char*> dartEntrypointArgs;
687 for (NSString* argument in [
_project dartEntrypointArguments]) {
688 dartEntrypointArgs.push_back([argument UTF8String]);
691 FlutterProjectArgs flutterArguments = {};
692 flutterArguments.struct_size =
sizeof(FlutterProjectArgs);
693 flutterArguments.assets_path =
_project.assetsPath.UTF8String;
694 flutterArguments.icu_data_path =
_project.ICUDataPath.UTF8String;
695 flutterArguments.command_line_argc =
static_cast<int>(argv.size());
696 flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data();
697 flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)
OnPlatformMessage;
698 flutterArguments.update_semantics_callback2 = [](
const FlutterSemanticsUpdate2* update,
704 [[engine viewControllerForIdentifier:kFlutterImplicitViewId] updateSemantics:update];
706 flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String;
707 flutterArguments.shutdown_dart_vm_when_done =
true;
708 flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size();
709 flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data();
710 flutterArguments.root_isolate_create_callback =
_project.rootIsolateCreateCallback;
711 flutterArguments.log_message_callback = [](
const char* tag,
const char* message,
713 std::stringstream stream;
715 stream << tag <<
": ";
718 std::string log = stream.str();
719 [FlutterLogger logDirect:[NSString stringWithUTF8String:log.c_str()]];
722 flutterArguments.engine_id =
reinterpret_cast<int64_t
>((__bridge
void*)
self);
724 BOOL mergedPlatformUIThread = YES;
725 NSNumber* enableMergedPlatformUIThread =
726 [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableMergedPlatformUIThread"];
727 if (enableMergedPlatformUIThread != nil) {
728 mergedPlatformUIThread = enableMergedPlatformUIThread.boolValue;
731 if (mergedPlatformUIThread) {
732 NSLog(
@"Running with merged UI and platform thread. Experimental.");
738 FlutterTaskRunnerDescription platformTaskRunnerDescription =
739 [
self createPlatformThreadTaskDescription];
740 std::optional<FlutterTaskRunnerDescription> uiTaskRunnerDescription;
741 if (mergedPlatformUIThread) {
742 uiTaskRunnerDescription = [
self createPlatformThreadTaskDescription];
745 const FlutterCustomTaskRunners custom_task_runners = {
746 .struct_size =
sizeof(FlutterCustomTaskRunners),
747 .platform_task_runner = &platformTaskRunnerDescription,
748 .thread_priority_setter = SetThreadPriority,
749 .ui_task_runner = uiTaskRunnerDescription ? &uiTaskRunnerDescription.value() :
nullptr,
751 flutterArguments.custom_task_runners = &custom_task_runners;
753 [
self loadAOTData:_project.assetsPath];
755 flutterArguments.aot_data =
_aotData;
758 flutterArguments.compositor = [
self createFlutterCompositor];
760 flutterArguments.on_pre_engine_restart_callback = [](
void*
user_data) {
762 [engine engineCallbackOnPreEngineRestart];
765 flutterArguments.vsync_callback = [](
void*
user_data, intptr_t baton) {
767 [engine onVSync:baton];
770 flutterArguments.view_focus_change_request_callback =
771 [](
const FlutterViewFocusChangeRequest* request,
void*
user_data) {
773 [engine onFocusChangeRequest:request];
776 FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
777 FlutterEngineResult result = _embedderAPI.Initialize(
778 FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge
void*)(
self), &_engine);
779 if (result != kSuccess) {
780 NSLog(
@"Failed to initialize Flutter engine: error %d", result);
784 result = _embedderAPI.RunInitialized(_engine);
785 if (result != kSuccess) {
786 NSLog(
@"Failed to run an initialized engine: error %d", result);
790 [
self sendUserLocales];
793 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
795 while ((nextViewController = [viewControllerEnumerator nextObject])) {
796 [
self updateWindowMetricsForViewController:nextViewController];
799 [
self updateDisplayConfig];
802 [
self sendInitialSettings];
806 - (void)loadAOTData:(NSString*)assetsDir {
807 if (!_embedderAPI.RunsAOTCompiledDartCode()) {
811 BOOL isDirOut =
false;
812 NSFileManager* fileManager = [NSFileManager defaultManager];
816 NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
818 if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
822 FlutterEngineAOTDataSource source = {};
823 source.type = kFlutterEngineAOTDataSourceTypeElfPath;
824 source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
826 auto result = _embedderAPI.CreateAOTData(&source, &
_aotData);
827 if (result != kSuccess) {
828 NSLog(
@"Failed to load AOT data from: %@", elfPath);
835 NSAssert(controller != nil,
@"The controller must not be nil.");
837 NSAssert(controller.
engine == nil,
838 @"The FlutterViewController is unexpectedly attached to "
839 @"engine %@ before initialization.",
843 @"The requested view ID is occupied.");
844 [_viewControllers setObject:controller forKey:@(viewIdentifier)];
845 [controller setUpWithEngine:self viewIdentifier:viewIdentifier];
846 NSAssert(controller.
viewIdentifier == viewIdentifier,
@"Failed to assign view ID.");
850 NSAssert(controller.
attached,
@"The FlutterViewController should switch to the attached mode "
851 @"after it is added to a FlutterEngine.");
852 NSAssert(controller.
engine ==
self,
853 @"The FlutterViewController was added to %@, but its engine unexpectedly became %@.",
856 if (controller.viewLoaded) {
857 [
self viewControllerViewDidLoad:controller];
860 if (viewIdentifier != kFlutterImplicitViewId) {
863 FlutterWindowMetricsEvent metrics{
864 .struct_size =
sizeof(FlutterWindowMetricsEvent),
870 FlutterAddViewInfo info{.struct_size =
sizeof(FlutterAddViewInfo),
871 .view_id = viewIdentifier,
872 .view_metrics = &metrics,
874 .add_view_callback = [](
const FlutterAddViewResult* r) {
875 auto added =
reinterpret_cast<bool*
>(r->user_data);
879 _embedderAPI.AddView(_engine, &info);
882 NSLog(
@"Failed to add view with ID %llu", viewIdentifier);
892 block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
895 uint64_t targetTimeNanos =
897 FlutterEngine* engine = weakSelf;
899 engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
904 [_vsyncWaiters setObject:waiter forKey:@(viewController.viewIdentifier)];
909 if (viewIdentifier != kFlutterImplicitViewId) {
910 bool removed =
false;
911 FlutterRemoveViewInfo info;
912 info.struct_size =
sizeof(FlutterRemoveViewInfo);
913 info.view_id = viewIdentifier;
914 info.user_data = &removed;
918 info.remove_view_callback = [](
const FlutterRemoveViewResult* r) {
919 auto removed =
reinterpret_cast<bool*
>(r->user_data);
920 [FlutterRunLoop.mainRunLoop performBlock:^{
924 _embedderAPI.RemoveView(_engine, &info);
926 [[FlutterRunLoop mainRunLoop] pollFlutterMessagesOnce];
935 if (controller != nil) {
936 [controller detachFromEngine];
938 @"The FlutterViewController unexpectedly stays attached after being removed. "
939 @"In unit tests, this is likely because either the FlutterViewController or "
940 @"the FlutterEngine is mocked. Please subclass these classes instead.");
942 [_viewControllers removeObjectForKey:@(viewIdentifier)];
946 waiter = [_vsyncWaiters objectForKey:@(viewIdentifier)];
947 [_vsyncWaiters removeObjectForKey:@(viewIdentifier)];
952 - (void)shutDownIfNeeded {
954 [
self shutDownEngine];
960 NSAssert(controller == nil || controller.
viewIdentifier == viewIdentifier,
961 @"The stored controller has unexpected view ID.");
967 [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
968 if (currentController == controller) {
972 if (currentController == nil && controller != nil) {
974 NSAssert(controller.
engine == nil,
975 @"Failed to set view controller to the engine: "
976 @"The given FlutterViewController is already attached to an engine %@. "
977 @"If you wanted to create an FlutterViewController and set it to an existing engine, "
978 @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
980 [
self registerViewController:controller forIdentifier:kFlutterImplicitViewId];
981 }
else if (currentController != nil && controller == nil) {
982 NSAssert(currentController.
viewIdentifier == kFlutterImplicitViewId,
983 @"The default controller has an unexpected ID %llu", currentController.
viewIdentifier);
985 [
self deregisterViewControllerForIdentifier:kFlutterImplicitViewId];
986 [
self shutDownIfNeeded];
990 @"Failed to set view controller to the engine: "
991 @"The engine already has an implicit view controller %@. "
992 @"If you wanted to make the implicit view render in a different window, "
993 @"you should attach the current view controller to the window instead.",
999 return [
self viewControllerForIdentifier:kFlutterImplicitViewId];
1002 - (FlutterCompositor*)createFlutterCompositor {
1004 _compositor.struct_size =
sizeof(FlutterCompositor);
1007 _compositor.create_backing_store_callback = [](
const FlutterBackingStoreConfig* config,
1008 FlutterBackingStore* backing_store_out,
1012 config, backing_store_out);
1015 _compositor.collect_backing_store_callback = [](
const FlutterBackingStore* backing_store,
1019 _compositor.present_view_callback = [](
const FlutterPresentViewInfo* info) {
1021 ->Present(info->view_id, info->layers, info->layers_count);
1033 #pragma mark - Framework-internal methods
1039 NSAssert(
self.viewController == nil,
1040 @"The engine already has a view controller for the implicit view.");
1041 self.viewController = controller;
1046 [
self registerViewController:controller forIdentifier:viewIdentifier];
1050 - (void)enableMultiView {
1052 NSAssert(
self.viewController == nil,
1053 @"Multiview can only be enabled before adding any view controllers.");
1059 FlutterViewFocusEvent
event{
1060 .struct_size =
sizeof(FlutterViewFocusEvent),
1061 .view_id = viewIdentifier,
1063 .direction = kUndefined,
1065 _embedderAPI.SendViewFocusEvent(_engine, &event);
1069 FlutterViewFocusEvent
event{
1070 .struct_size =
sizeof(FlutterViewFocusEvent),
1071 .view_id = viewIdentifier,
1072 .state = kUnfocused,
1073 .direction = kUndefined,
1075 _embedderAPI.SendViewFocusEvent(_engine, &event);
1079 [
self deregisterViewControllerForIdentifier:viewController.viewIdentifier];
1080 [
self shutDownIfNeeded];
1084 return _engine !=
nullptr;
1087 - (void)updateDisplayConfig:(NSNotification*)notification {
1088 [
self updateDisplayConfig];
1091 - (NSArray<NSScreen*>*)screens {
1092 return [NSScreen screens];
1095 - (void)updateDisplayConfig {
1100 std::vector<FlutterEngineDisplay> displays;
1101 for (NSScreen* screen : [
self screens]) {
1102 CGDirectDisplayID displayID =
1103 static_cast<CGDirectDisplayID
>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
1105 double devicePixelRatio = screen.backingScaleFactor;
1106 FlutterEngineDisplay display;
1107 display.struct_size =
sizeof(display);
1108 display.display_id = displayID;
1109 display.single_display =
false;
1110 display.width =
static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
1111 display.height =
static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
1112 display.device_pixel_ratio = devicePixelRatio;
1114 CVDisplayLinkRef displayLinkRef = nil;
1115 CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
1118 CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
1119 if (!(nominal.flags & kCVTimeIsIndefinite)) {
1120 double refreshRate =
static_cast<double>(nominal.timeScale) / nominal.timeValue;
1121 display.refresh_rate = round(refreshRate);
1123 CVDisplayLinkRelease(displayLinkRef);
1125 display.refresh_rate = 0;
1128 displays.push_back(display);
1130 _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
1131 displays.data(), displays.size());
1134 - (void)onSettingsChanged:(NSNotification*)notification {
1136 NSString* brightness =
1137 [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
1138 [_settingsChannel sendMessage:@{
1139 @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
1141 @"textScaleFactor" : @1.0,
1146 - (void)sendInitialSettings {
1148 [[NSDistributedNotificationCenter defaultCenter]
1150 selector:@selector(onSettingsChanged:)
1151 name:@"AppleInterfaceThemeChangedNotification"
1153 [
self onSettingsChanged:nil];
1156 - (FlutterEngineProcTable&)embedderAPI {
1157 return _embedderAPI;
1160 - (nonnull NSString*)executableName {
1161 return [[[NSProcessInfo processInfo] arguments] firstObject] ?:
@"Flutter";
1165 if (!_engine || !viewController || !viewController.viewLoaded) {
1168 NSAssert([
self viewControllerForIdentifier:viewController.
viewIdentifier] == viewController,
1169 @"The provided view controller is not attached to this engine.");
1170 NSView* view = viewController.flutterView;
1171 CGRect scaledBounds = [view convertRectToBacking:view.bounds];
1172 CGSize scaledSize = scaledBounds.size;
1173 double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
1174 auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
1175 const FlutterWindowMetricsEvent windowMetricsEvent = {
1176 .struct_size =
sizeof(windowMetricsEvent),
1177 .width =
static_cast<size_t>(scaledSize.width),
1178 .height =
static_cast<size_t>(scaledSize.height),
1179 .pixel_ratio = pixelRatio,
1180 .left =
static_cast<size_t>(scaledBounds.origin.x),
1181 .top =
static_cast<size_t>(scaledBounds.origin.y),
1182 .display_id =
static_cast<uint64_t
>(displayId),
1185 _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
1188 - (void)sendPointerEvent:(const FlutterPointerEvent&)event {
1189 _embedderAPI.SendPointerEvent(_engine, &event, 1);
1193 - (void)setSemanticsEnabled:(BOOL)enabled {
1194 if (_semanticsEnabled == enabled) {
1197 _semanticsEnabled = enabled;
1200 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1202 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1203 [nextViewController notifySemanticsEnabledChanged];
1206 _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
1209 - (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
1210 toTarget:(uint16_t)target
1211 withData:(fml::MallocMapping)data {
1212 _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
1219 #pragma mark - Private methods
1221 - (void)sendUserLocales {
1222 if (!
self.running) {
1227 NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
1228 std::vector<FlutterLocale> flutterLocales;
1229 flutterLocales.reserve(locales.count);
1230 for (NSString* localeID in [NSLocale preferredLanguages]) {
1231 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1232 [locales addObject:locale];
1236 std::vector<const FlutterLocale*> flutterLocaleList;
1237 flutterLocaleList.reserve(flutterLocales.size());
1238 std::transform(flutterLocales.begin(), flutterLocales.end(),
1239 std::back_inserter(flutterLocaleList),
1240 [](
const auto& arg) ->
const auto* { return &arg; });
1241 _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
1244 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
1245 NSData* messageData = nil;
1246 if (message->message_size > 0) {
1247 messageData = [NSData dataWithBytesNoCopy:(void*)message->message
1248 length:message->message_size
1251 NSString* channel = @(message->channel);
1252 __block
const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
1254 NSMutableArray* isResponseValid =
self.isResponseValid;
1255 FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
1256 _embedderAPI.SendPlatformMessageResponse;
1258 @
synchronized(isResponseValid) {
1259 if (![isResponseValid[0] boolValue]) {
1263 if (responseHandle) {
1264 sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
1265 static_cast<const uint8_t*
>(response.bytes), response.length);
1266 responseHandle = NULL;
1268 NSLog(
@"Error: Message responses can be sent only once. Ignoring duplicate response "
1277 handlerInfo.
handler(messageData, binaryResponseHandler);
1279 binaryResponseHandler(nil);
1283 - (void)engineCallbackOnPreEngineRestart {
1284 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1286 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1289 [_platformViewController reset];
1295 - (void)onVSync:(uintptr_t)baton {
1300 [_vsyncWaiters objectForKey:[_vsyncWaiters.keyEnumerator nextObject]];
1301 if (waiter != nil) {
1307 self.embedderAPI.OnVsync(_engine, baton, 0, 0);
1310 if ([NSThread isMainThread]) {
1313 [FlutterRunLoop.mainRunLoop performBlock:block];
1320 - (void)shutDownEngine {
1321 if (_engine ==
nullptr) {
1325 FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
1326 if (result != kSuccess) {
1327 NSLog(
@"Could not de-initialize the Flutter engine: error %d", result);
1330 result = _embedderAPI.Shutdown(_engine);
1331 if (result != kSuccess) {
1332 NSLog(
@"Failed to shut down Flutter engine: error %d", result);
1338 NSAssert([[NSThread currentThread] isMainThread],
@"Must be called on the main thread.");
1339 return (__bridge
FlutterEngine*)
reinterpret_cast<void*
>(identifier);
1342 - (void)setUpPlatformViewChannel {
1349 [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1350 [[weakSelf platformViewController] handleMethodCall:call result:result];
1354 - (void)setUpAccessibilityChannel {
1360 [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1361 [weakSelf handleAccessibilityEvent:message];
1364 - (void)setUpNotificationCenterListeners {
1365 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1367 [center addObserver:self
1368 selector:@selector(onAccessibilityStatusChanged:)
1369 name:kEnhancedUserInterfaceNotification
1371 [center addObserver:self
1372 selector:@selector(applicationWillTerminate:)
1373 name:NSApplicationWillTerminateNotification
1375 [center addObserver:self
1376 selector:@selector(windowDidChangeScreen:)
1377 name:NSWindowDidChangeScreenNotification
1379 [center addObserver:self
1380 selector:@selector(updateDisplayConfig:)
1381 name:NSApplicationDidChangeScreenParametersNotification
1385 - (void)addInternalPlugins {
1399 [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1400 [weakSelf handleMethodCall:call result:result];
1404 - (void)didUpdateMouseCursor:(NSCursor*)cursor {
1408 [_lastViewWithPointerEvent didUpdateMouseCursor:cursor];
1411 - (void)applicationWillTerminate:(NSNotification*)notification {
1412 [
self shutDownEngine];
1415 - (void)windowDidChangeScreen:(NSNotification*)notification {
1418 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1420 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1421 [
self updateWindowMetricsForViewController:nextViewController];
1425 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1426 BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1427 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1429 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1433 self.semanticsEnabled = enabled;
1435 - (void)handleAccessibilityEvent:(NSDictionary<NSString*,
id>*)annotatedEvent {
1436 NSString* type = annotatedEvent[@"type"];
1437 if ([type isEqualToString:
@"announce"]) {
1438 NSString* message = annotatedEvent[@"data"][@"message"];
1439 NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1440 if (message == nil) {
1444 NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1445 ? NSAccessibilityPriorityHigh
1446 : NSAccessibilityPriorityMedium;
1448 [
self announceAccessibilityMessage:message withPriority:priority];
1452 - (void)announceAccessibilityMessage:(NSString*)message
1453 withPriority:(NSAccessibilityPriorityLevel)priority {
1454 NSAccessibilityPostNotificationWithUserInfo(
1455 [
self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView,
1456 NSAccessibilityAnnouncementRequestedNotification,
1457 @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
1460 if ([call.
method isEqualToString:
@"SystemNavigator.pop"]) {
1461 [[NSApplication sharedApplication] terminate:self];
1463 }
else if ([call.
method isEqualToString:
@"SystemSound.play"]) {
1464 [
self playSystemSound:call.arguments];
1466 }
else if ([call.
method isEqualToString:
@"Clipboard.getData"]) {
1467 result([
self getClipboardData:call.
arguments]);
1468 }
else if ([call.
method isEqualToString:
@"Clipboard.setData"]) {
1469 [
self setClipboardData:call.arguments];
1471 }
else if ([call.
method isEqualToString:
@"Clipboard.hasStrings"]) {
1472 result(@{
@"value" : @([
self clipboardHasStrings])});
1473 }
else if ([call.
method isEqualToString:
@"System.exitApplication"]) {
1474 if ([
self terminationHandler] == nil) {
1479 [NSApp terminate:self];
1482 [[
self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1484 }
else if ([call.
method isEqualToString:
@"System.initializationComplete"]) {
1485 if ([
self terminationHandler] != nil) {
1486 [
self terminationHandler].acceptingRequests = YES;
1494 - (void)playSystemSound:(NSString*)soundType {
1495 if ([soundType isEqualToString:
@"SystemSoundType.alert"]) {
1500 - (NSDictionary*)getClipboardData:(NSString*)format {
1502 NSString* stringInPasteboard = [
self.pasteboard stringForType:NSPasteboardTypeString];
1503 return stringInPasteboard == nil ? nil : @{
@"text" : stringInPasteboard};
1508 - (void)setClipboardData:(NSDictionary*)data {
1509 NSString* text = data[@"text"];
1510 [
self.pasteboard clearContents];
1511 if (text && ![text isEqual:[NSNull
null]]) {
1512 [
self.pasteboard setString:text forType:NSPasteboardTypeString];
1516 - (BOOL)clipboardHasStrings {
1517 return [
self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1520 - (std::vector<std::string>)switches {
1524 #pragma mark - FlutterAppLifecycleDelegate
1527 NSString* nextState =
1528 [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1529 [
self sendOnChannel:kFlutterLifecycleChannel
1530 message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1537 - (void)handleWillBecomeActive:(NSNotification*)notification {
1540 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1542 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1550 - (void)handleWillResignActive:(NSNotification*)notification {
1553 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1555 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1563 - (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1564 NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1565 if (occlusionState & NSApplicationOcclusionStateVisible) {
1568 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1570 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1574 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1578 #pragma mark - FlutterBinaryMessenger
1580 - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1581 [
self sendOnChannel:channel message:message binaryReply:nil];
1584 - (void)sendOnChannel:(NSString*)channel
1585 message:(NSData* _Nullable)message
1587 FlutterPlatformMessageResponseHandle* response_handle =
nullptr;
1592 auto captures = std::make_unique<Captures>();
1593 captures->reply = callback;
1594 auto message_reply = [](
const uint8_t* data,
size_t data_size,
void*
user_data) {
1595 auto captures =
reinterpret_cast<Captures*
>(
user_data);
1596 NSData* reply_data = nil;
1597 if (data !=
nullptr && data_size > 0) {
1598 reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1600 captures->reply(reply_data);
1604 FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
1605 _engine, message_reply, captures.get(), &response_handle);
1606 if (create_result != kSuccess) {
1607 NSLog(
@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1613 FlutterPlatformMessage platformMessage = {
1614 .struct_size =
sizeof(FlutterPlatformMessage),
1615 .channel = [channel UTF8String],
1616 .message =
static_cast<const uint8_t*
>(message.bytes),
1617 .message_size = message.length,
1618 .response_handle = response_handle,
1621 FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1622 if (message_result != kSuccess) {
1623 NSLog(
@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
1627 if (response_handle !=
nullptr) {
1628 FlutterEngineResult release_result =
1629 _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1630 if (release_result != kSuccess) {
1631 NSLog(
@"Failed to release the response handle (%d).", release_result);
1637 binaryMessageHandler:
1642 handler:[handler copy]];
1649 NSString* foundChannel = nil;
1652 if ([handlerInfo.
connection isEqual:@(connection)]) {
1658 [_messengerHandlers removeObjectForKey:foundChannel];
1662 #pragma mark - FlutterPluginRegistry
1665 id<FlutterPluginRegistrar> registrar =
self.pluginRegistrars[pluginName];
1669 self.pluginRegistrars[pluginName] = registrarImpl;
1670 registrar = registrarImpl;
1675 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1679 #pragma mark - FlutterTextureRegistrar
1682 return [_renderer registerTexture:texture];
1685 - (BOOL)registerTextureWithID:(int64_t)textureId {
1686 return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
1689 - (void)textureFrameAvailable:(int64_t)textureID {
1690 [_renderer textureFrameAvailable:textureID];
1693 - (BOOL)markTextureFrameAvailable:(int64_t)textureID {
1694 return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
1697 - (void)unregisterTexture:(int64_t)textureID {
1698 [_renderer unregisterTexture:textureID];
1701 - (BOOL)unregisterTextureWithID:(int64_t)textureID {
1702 return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
1705 #pragma mark - Task runner integration
1707 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1710 const auto engine_time = _embedderAPI.GetCurrentTime();
1711 [FlutterRunLoop.mainRunLoop
1712 performAfterDelay:(targetTime - (double)engine_time) / NSEC_PER_SEC
1715 if (self != nil && self->_engine != nil) {
1716 auto result = _embedderAPI.RunTask(self->_engine, &task);
1717 if (result != kSuccess) {
1718 NSLog(@"Could not post a task to the Flutter engine.");
1725 - (
flutter::FlutterCompositor*)macOSCompositor {
1729 #pragma mark - FlutterKeyboardManagerDelegate
1734 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
1735 callback:(FlutterKeyEventCallback)callback
1736 userData:(
void*)userData {
1737 _embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
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)
FLUTTER_DARWIN_EXPORT NSObject const * FlutterMethodNotImplemented
FlutterBinaryMessengerConnection _connection
FlutterMethodChannel * _platformViewsChannel
_FlutterEngineAOTData * _aotData
std::unique_ptr< flutter::FlutterCompositor > _macOSCompositor
static const int kMainThreadPriority
static void OnPlatformMessage(const FlutterPlatformMessage *message, void *user_data)
FlutterPlatformViewController * _platformViewController
FlutterBasicMessageChannel * _accessibilityChannel
FlutterBasicMessageChannel * _settingsChannel
static FlutterLocale FlutterLocaleFromNSLocale(NSLocale *locale)
BOOL _allowHeadlessExecution
NSMutableDictionary< NSString *, FlutterEngineHandlerInfo * > * _messengerHandlers
FlutterBinaryMessengerConnection _currentMessengerConnection
FlutterMethodChannel * _platformChannel
NSString *const kFlutterLifecycleChannel
static NSString *const kEnhancedUserInterfaceNotification
The private notification for voice over.
NSMapTable< NSNumber *, FlutterVSyncWaiter * > * _vsyncWaiters
FlutterViewIdentifier _nextViewIdentifier
NSString *const kFlutterPlatformChannel
FlutterTextInputPlugin * _textInputPlugin
FlutterDartProject * _project
NSMapTable * _viewControllers
FlutterCompositor _compositor
__weak FlutterView * _lastViewWithPointerEvent
FlutterKeyboardManager * _keyboardManager
FlutterWindowController * _windowController
FlutterTerminationCallback _terminator
constexpr char kTextPlainFormat[]
Clipboard plain text format.
__weak FlutterEngine * _flutterEngine
FlutterBinaryMessengerRelay * _binaryMessenger
static NSString *const kEnhancedUserInterfaceKey
NSString *const kFlutterSettingsChannel
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterTerminationCallback)(id _Nullable sender)
int64_t FlutterViewIdentifier
NSString * lookupKeyForAsset:fromPackage:(NSString *asset,[fromPackage] NSString *package)
NSString * lookupKeyForAsset:(NSString *asset)
NSInteger clearContents()
instancetype messageChannelWithName:binaryMessenger:codec:(NSString *name,[binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger,[codec] NSObject< FlutterMessageCodec > *codec)
instancetype displayLinkWithView:(NSView *view)
FlutterBinaryMessageHandler handler
id< FlutterBinaryMessenger > binaryMessenger
NSObject * publishedValue
instancetype methodCallWithMethodName:arguments:(NSString *method,[arguments] id _Nullable arguments)
void setMethodCallHandler:(FlutterMethodCallHandler _Nullable handler)
instancetype methodChannelWithName:binaryMessenger:codec:(NSString *name,[binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger,[codec] NSObject< FlutterMethodCodec > *codec)
void registerWithRegistrar:delegate:(nonnull id< FlutterPluginRegistrar > registrar,[delegate] nullable id< FlutterMouseCursorPluginDelegate > delegate)
Converts between the time representation used by Flutter Engine and CAMediaTime.
uint64_t CAMediaTimeToEngineTime:(CFTimeInterval time)
void waitForVSync:(uintptr_t baton)
void onPreEngineRestart()
FlutterViewIdentifier viewIdentifier
void onAccessibilityStatusChanged:(BOOL enabled)
std::vector< std::string > GetSwitchesFromEnvironment()
instancetype sharedInstance()
void handleMethodCall:result:(FlutterMethodCall *call,[result] FlutterResult result)