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 - (NSViewController*)viewController {
370 return [_flutterEngine viewControllerForIdentifier:kFlutterImplicitViewId];
373 - (void)addMethodCallDelegate:(nonnull
id<
FlutterPlugin>)delegate
381 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
383 id<FlutterAppLifecycleProvider> lifeCycleProvider =
384 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
385 [lifeCycleProvider addApplicationLifecycleDelegate:delegate];
386 [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
391 withId:(nonnull NSString*)factoryId {
392 [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
395 - (void)publish:(NSObject*)value {
396 _publishedValue = value;
399 - (NSString*)lookupKeyForAsset:(NSString*)asset {
403 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
410 #pragma mark - Static methods provided to engine configuration
414 [engine engineCallbackOnPlatformMessage:message];
506 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
507 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
512 static void SetThreadPriority(FlutterThreadPriority priority) {
513 if (priority == kDisplay || priority == kRaster) {
514 pthread_t thread = pthread_self();
517 if (!pthread_getschedparam(thread, &policy, ¶m)) {
519 pthread_setschedparam(thread, policy, ¶m);
521 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
525 - (instancetype)initWithName:(NSString*)labelPrefix
527 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
529 NSAssert(
self,
@"Super init cannot be nil");
531 [FlutterRunLoop ensureMainLoopInitialized];
538 _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
539 _pluginRegistrars = [[NSMutableDictionary alloc] init];
542 _semanticsEnabled = NO;
544 _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
545 [_isResponseValid addObject:@YES];
551 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
552 FlutterEngineGetProcAddresses(&_embedderAPI);
557 NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
558 [notificationCenter addObserver:self
559 selector:@selector(sendUserLocales)
560 name:NSCurrentLocaleDidChangeNotification
570 [
self setUpPlatformViewChannel];
575 [
self setUpAccessibilityChannel];
576 [
self setUpNotificationCenterListeners];
577 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
581 id<FlutterAppLifecycleProvider> lifecycleProvider =
582 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
583 [lifecycleProvider addApplicationLifecycleDelegate:self];
585 _terminationHandler = nil;
594 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
596 id<FlutterAppLifecycleProvider> lifecycleProvider =
597 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
598 [lifecycleProvider removeApplicationLifecycleDelegate:self];
603 for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
605 [lifecycleProvider removeApplicationLifecycleDelegate:delegate];
611 for (NSString* pluginName in _pluginRegistrars) {
612 [_pluginRegistrars[pluginName] publish:[NSNull null]];
614 @
synchronized(_isResponseValid) {
615 [_isResponseValid removeAllObjects];
616 [_isResponseValid addObject:@NO];
618 [
self shutDownEngine];
620 _embedderAPI.CollectAOTData(
_aotData);
624 - (FlutterTaskRunnerDescription)createPlatformThreadTaskDescription {
625 static size_t sTaskRunnerIdentifiers = 0;
626 FlutterTaskRunnerDescription cocoa_task_runner_description = {
627 .struct_size =
sizeof(FlutterTaskRunnerDescription),
629 .
user_data = (__bridge_retained
void*)
self,
630 .runs_task_on_current_thread_callback = [](
void*
user_data) ->
bool {
631 return [[NSThread currentThread] isMainThread];
633 .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
636 [engine postMainThreadTask:task targetTimeInNanoseconds:target_time_nanos];
638 .identifier = ++sTaskRunnerIdentifiers,
639 .destruction_callback =
646 return cocoa_task_runner_description;
649 - (void)onFocusChangeRequest:(const FlutterViewFocusChangeRequest*)request {
651 if (controller == nil) {
654 if (request->state == kFocused) {
655 [controller.flutterView.window makeFirstResponder:controller.flutterView];
659 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
665 NSLog(
@"Attempted to run an engine with no view controller without headless mode enabled.");
669 [
self addInternalPlugins];
672 std::vector<const char*> argv = {[
self.executableName UTF8String]};
673 std::vector<std::string> switches =
self.switches;
677 std::find(switches.begin(), switches.end(),
"--enable-impeller=true") != switches.end()) {
678 switches.push_back(
"--enable-impeller=true");
682 std::find(switches.begin(), switches.end(),
"--enable-flutter-gpu=true") != switches.end()) {
683 switches.push_back(
"--enable-flutter-gpu=true");
686 std::transform(switches.begin(), switches.end(), std::back_inserter(argv),
687 [](
const std::string& arg) ->
const char* { return arg.c_str(); });
689 std::vector<const char*> dartEntrypointArgs;
690 for (NSString* argument in [
_project dartEntrypointArguments]) {
691 dartEntrypointArgs.push_back([argument UTF8String]);
694 FlutterProjectArgs flutterArguments = {};
695 flutterArguments.struct_size =
sizeof(FlutterProjectArgs);
696 flutterArguments.assets_path =
_project.assetsPath.UTF8String;
697 flutterArguments.icu_data_path =
_project.ICUDataPath.UTF8String;
698 flutterArguments.command_line_argc =
static_cast<int>(argv.size());
699 flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data();
700 flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)
OnPlatformMessage;
701 flutterArguments.update_semantics_callback2 = [](
const FlutterSemanticsUpdate2* update,
707 [[engine viewControllerForIdentifier:kFlutterImplicitViewId] updateSemantics:update];
709 flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String;
710 flutterArguments.shutdown_dart_vm_when_done =
true;
711 flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size();
712 flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data();
713 flutterArguments.root_isolate_create_callback =
_project.rootIsolateCreateCallback;
714 flutterArguments.log_message_callback = [](
const char* tag,
const char* message,
716 std::stringstream stream;
718 stream << tag <<
": ";
721 std::string log = stream.str();
722 [FlutterLogger logDirect:[NSString stringWithUTF8String:log.c_str()]];
725 flutterArguments.engine_id =
reinterpret_cast<int64_t
>((__bridge
void*)
self);
727 BOOL mergedPlatformUIThread = YES;
728 NSNumber* enableMergedPlatformUIThread =
729 [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableMergedPlatformUIThread"];
730 if (enableMergedPlatformUIThread != nil) {
731 mergedPlatformUIThread = enableMergedPlatformUIThread.boolValue;
734 if (mergedPlatformUIThread) {
735 NSLog(
@"Running with merged UI and platform thread. Experimental.");
741 FlutterTaskRunnerDescription platformTaskRunnerDescription =
742 [
self createPlatformThreadTaskDescription];
743 std::optional<FlutterTaskRunnerDescription> uiTaskRunnerDescription;
744 if (mergedPlatformUIThread) {
745 uiTaskRunnerDescription = [
self createPlatformThreadTaskDescription];
748 const FlutterCustomTaskRunners custom_task_runners = {
749 .struct_size =
sizeof(FlutterCustomTaskRunners),
750 .platform_task_runner = &platformTaskRunnerDescription,
751 .thread_priority_setter = SetThreadPriority,
752 .ui_task_runner = uiTaskRunnerDescription ? &uiTaskRunnerDescription.value() :
nullptr,
754 flutterArguments.custom_task_runners = &custom_task_runners;
756 [
self loadAOTData:_project.assetsPath];
758 flutterArguments.aot_data =
_aotData;
761 flutterArguments.compositor = [
self createFlutterCompositor];
763 flutterArguments.on_pre_engine_restart_callback = [](
void*
user_data) {
765 [engine engineCallbackOnPreEngineRestart];
768 flutterArguments.vsync_callback = [](
void*
user_data, intptr_t baton) {
770 [engine onVSync:baton];
773 flutterArguments.view_focus_change_request_callback =
774 [](
const FlutterViewFocusChangeRequest* request,
void*
user_data) {
776 [engine onFocusChangeRequest:request];
779 FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
780 FlutterEngineResult result = _embedderAPI.Initialize(
781 FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge
void*)(
self), &_engine);
782 if (result != kSuccess) {
783 NSLog(
@"Failed to initialize Flutter engine: error %d", result);
787 result = _embedderAPI.RunInitialized(_engine);
788 if (result != kSuccess) {
789 NSLog(
@"Failed to run an initialized engine: error %d", result);
793 [
self sendUserLocales];
796 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
798 while ((nextViewController = [viewControllerEnumerator nextObject])) {
799 [
self updateWindowMetricsForViewController:nextViewController];
802 [
self updateDisplayConfig];
805 [
self sendInitialSettings];
809 - (void)loadAOTData:(NSString*)assetsDir {
810 if (!_embedderAPI.RunsAOTCompiledDartCode()) {
814 BOOL isDirOut =
false;
815 NSFileManager* fileManager = [NSFileManager defaultManager];
819 NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
821 if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
825 FlutterEngineAOTDataSource source = {};
826 source.type = kFlutterEngineAOTDataSourceTypeElfPath;
827 source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
829 auto result = _embedderAPI.CreateAOTData(&source, &
_aotData);
830 if (result != kSuccess) {
831 NSLog(
@"Failed to load AOT data from: %@", elfPath);
838 NSAssert(controller != nil,
@"The controller must not be nil.");
840 NSAssert(controller.
engine == nil,
841 @"The FlutterViewController is unexpectedly attached to "
842 @"engine %@ before initialization.",
846 @"The requested view ID is occupied.");
847 [_viewControllers setObject:controller forKey:@(viewIdentifier)];
848 [controller setUpWithEngine:self viewIdentifier:viewIdentifier];
849 NSAssert(controller.
viewIdentifier == viewIdentifier,
@"Failed to assign view ID.");
853 NSAssert(controller.
attached,
@"The FlutterViewController should switch to the attached mode "
854 @"after it is added to a FlutterEngine.");
855 NSAssert(controller.
engine ==
self,
856 @"The FlutterViewController was added to %@, but its engine unexpectedly became %@.",
859 if (controller.viewLoaded) {
860 [
self viewControllerViewDidLoad:controller];
863 if (viewIdentifier != kFlutterImplicitViewId) {
866 FlutterWindowMetricsEvent metrics{
867 .struct_size =
sizeof(FlutterWindowMetricsEvent),
873 FlutterAddViewInfo info{.struct_size =
sizeof(FlutterAddViewInfo),
874 .view_id = viewIdentifier,
875 .view_metrics = &metrics,
877 .add_view_callback = [](
const FlutterAddViewResult* r) {
878 auto added =
reinterpret_cast<bool*
>(r->user_data);
882 _embedderAPI.AddView(_engine, &info);
885 NSLog(
@"Failed to add view with ID %llu", viewIdentifier);
895 block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
898 uint64_t targetTimeNanos =
900 FlutterEngine* engine = weakSelf;
902 engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
907 [_vsyncWaiters setObject:waiter forKey:@(viewController.viewIdentifier)];
912 if (viewIdentifier != kFlutterImplicitViewId) {
913 bool removed =
false;
914 FlutterRemoveViewInfo info;
915 info.struct_size =
sizeof(FlutterRemoveViewInfo);
916 info.view_id = viewIdentifier;
917 info.user_data = &removed;
921 info.remove_view_callback = [](
const FlutterRemoveViewResult* r) {
922 auto removed =
reinterpret_cast<bool*
>(r->user_data);
923 [FlutterRunLoop.mainRunLoop performBlock:^{
927 _embedderAPI.RemoveView(_engine, &info);
929 [[FlutterRunLoop mainRunLoop] pollFlutterMessagesOnce];
938 if (controller != nil) {
939 [controller detachFromEngine];
941 @"The FlutterViewController unexpectedly stays attached after being removed. "
942 @"In unit tests, this is likely because either the FlutterViewController or "
943 @"the FlutterEngine is mocked. Please subclass these classes instead.");
945 [_viewControllers removeObjectForKey:@(viewIdentifier)];
949 waiter = [_vsyncWaiters objectForKey:@(viewIdentifier)];
950 [_vsyncWaiters removeObjectForKey:@(viewIdentifier)];
955 - (void)shutDownIfNeeded {
957 [
self shutDownEngine];
963 NSAssert(controller == nil || controller.
viewIdentifier == viewIdentifier,
964 @"The stored controller has unexpected view ID.");
970 [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
971 if (currentController == controller) {
975 if (currentController == nil && controller != nil) {
977 NSAssert(controller.
engine == nil,
978 @"Failed to set view controller to the engine: "
979 @"The given FlutterViewController is already attached to an engine %@. "
980 @"If you wanted to create an FlutterViewController and set it to an existing engine, "
981 @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
983 [
self registerViewController:controller forIdentifier:kFlutterImplicitViewId];
984 }
else if (currentController != nil && controller == nil) {
985 NSAssert(currentController.
viewIdentifier == kFlutterImplicitViewId,
986 @"The default controller has an unexpected ID %llu", currentController.
viewIdentifier);
988 [
self deregisterViewControllerForIdentifier:kFlutterImplicitViewId];
989 [
self shutDownIfNeeded];
993 @"Failed to set view controller to the engine: "
994 @"The engine already has an implicit view controller %@. "
995 @"If you wanted to make the implicit view render in a different window, "
996 @"you should attach the current view controller to the window instead.",
1002 return [
self viewControllerForIdentifier:kFlutterImplicitViewId];
1005 - (FlutterCompositor*)createFlutterCompositor {
1007 _compositor.struct_size =
sizeof(FlutterCompositor);
1010 _compositor.create_backing_store_callback = [](
const FlutterBackingStoreConfig* config,
1011 FlutterBackingStore* backing_store_out,
1015 config, backing_store_out);
1018 _compositor.collect_backing_store_callback = [](
const FlutterBackingStore* backing_store,
1022 _compositor.present_view_callback = [](
const FlutterPresentViewInfo* info) {
1024 ->Present(info->view_id, info->layers, info->layers_count);
1036 #pragma mark - Framework-internal methods
1042 NSAssert(
self.viewController == nil,
1043 @"The engine already has a view controller for the implicit view.");
1044 self.viewController = controller;
1049 [
self registerViewController:controller forIdentifier:viewIdentifier];
1053 - (void)enableMultiView {
1055 NSAssert(
self.viewController == nil,
1056 @"Multiview can only be enabled before adding any view controllers.");
1062 FlutterViewFocusEvent
event{
1063 .struct_size =
sizeof(FlutterViewFocusEvent),
1064 .view_id = viewIdentifier,
1066 .direction = kUndefined,
1068 _embedderAPI.SendViewFocusEvent(_engine, &event);
1072 FlutterViewFocusEvent
event{
1073 .struct_size =
sizeof(FlutterViewFocusEvent),
1074 .view_id = viewIdentifier,
1075 .state = kUnfocused,
1076 .direction = kUndefined,
1078 _embedderAPI.SendViewFocusEvent(_engine, &event);
1082 [
self deregisterViewControllerForIdentifier:viewController.viewIdentifier];
1083 [
self shutDownIfNeeded];
1087 return _engine !=
nullptr;
1090 - (void)updateDisplayConfig:(NSNotification*)notification {
1091 [
self updateDisplayConfig];
1094 - (NSArray<NSScreen*>*)screens {
1095 return [NSScreen screens];
1098 - (void)updateDisplayConfig {
1103 std::vector<FlutterEngineDisplay> displays;
1104 for (NSScreen* screen : [
self screens]) {
1105 CGDirectDisplayID displayID =
1106 static_cast<CGDirectDisplayID
>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
1108 double devicePixelRatio = screen.backingScaleFactor;
1109 FlutterEngineDisplay display;
1110 display.struct_size =
sizeof(display);
1111 display.display_id = displayID;
1112 display.single_display =
false;
1113 display.width =
static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
1114 display.height =
static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
1115 display.device_pixel_ratio = devicePixelRatio;
1117 CVDisplayLinkRef displayLinkRef = nil;
1118 CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
1121 CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
1122 if (!(nominal.flags & kCVTimeIsIndefinite)) {
1123 double refreshRate =
static_cast<double>(nominal.timeScale) / nominal.timeValue;
1124 display.refresh_rate = round(refreshRate);
1126 CVDisplayLinkRelease(displayLinkRef);
1128 display.refresh_rate = 0;
1131 displays.push_back(display);
1133 _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
1134 displays.data(), displays.size());
1137 - (void)onSettingsChanged:(NSNotification*)notification {
1139 NSString* brightness =
1140 [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
1141 [_settingsChannel sendMessage:@{
1142 @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
1144 @"textScaleFactor" : @1.0,
1149 - (void)sendInitialSettings {
1151 [[NSDistributedNotificationCenter defaultCenter]
1153 selector:@selector(onSettingsChanged:)
1154 name:@"AppleInterfaceThemeChangedNotification"
1156 [
self onSettingsChanged:nil];
1159 - (FlutterEngineProcTable&)embedderAPI {
1160 return _embedderAPI;
1163 - (nonnull NSString*)executableName {
1164 return [[[NSProcessInfo processInfo] arguments] firstObject] ?:
@"Flutter";
1168 if (!_engine || !viewController || !viewController.viewLoaded) {
1171 NSAssert([
self viewControllerForIdentifier:viewController.
viewIdentifier] == viewController,
1172 @"The provided view controller is not attached to this engine.");
1173 NSView* view = viewController.flutterView;
1174 CGRect scaledBounds = [view convertRectToBacking:view.bounds];
1175 CGSize scaledSize = scaledBounds.size;
1176 double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
1177 auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
1178 const FlutterWindowMetricsEvent windowMetricsEvent = {
1179 .struct_size =
sizeof(windowMetricsEvent),
1180 .width =
static_cast<size_t>(scaledSize.width),
1181 .height =
static_cast<size_t>(scaledSize.height),
1182 .pixel_ratio = pixelRatio,
1183 .left =
static_cast<size_t>(scaledBounds.origin.x),
1184 .top =
static_cast<size_t>(scaledBounds.origin.y),
1185 .display_id =
static_cast<uint64_t
>(displayId),
1188 _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
1191 - (void)sendPointerEvent:(const FlutterPointerEvent&)event {
1192 _embedderAPI.SendPointerEvent(_engine, &event, 1);
1196 - (void)setSemanticsEnabled:(BOOL)enabled {
1197 if (_semanticsEnabled == enabled) {
1200 _semanticsEnabled = enabled;
1203 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1205 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1206 [nextViewController notifySemanticsEnabledChanged];
1209 _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
1212 - (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
1213 toTarget:(uint16_t)target
1214 withData:(fml::MallocMapping)data {
1215 _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
1222 #pragma mark - Private methods
1224 - (void)sendUserLocales {
1225 if (!
self.running) {
1230 NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
1231 std::vector<FlutterLocale> flutterLocales;
1232 flutterLocales.reserve(locales.count);
1233 for (NSString* localeID in [NSLocale preferredLanguages]) {
1234 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1235 [locales addObject:locale];
1239 std::vector<const FlutterLocale*> flutterLocaleList;
1240 flutterLocaleList.reserve(flutterLocales.size());
1241 std::transform(flutterLocales.begin(), flutterLocales.end(),
1242 std::back_inserter(flutterLocaleList),
1243 [](
const auto& arg) ->
const auto* { return &arg; });
1244 _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
1247 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
1248 NSData* messageData = nil;
1249 if (message->message_size > 0) {
1250 messageData = [NSData dataWithBytesNoCopy:(void*)message->message
1251 length:message->message_size
1254 NSString* channel = @(message->channel);
1255 __block
const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
1257 NSMutableArray* isResponseValid =
self.isResponseValid;
1258 FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
1259 _embedderAPI.SendPlatformMessageResponse;
1261 @
synchronized(isResponseValid) {
1262 if (![isResponseValid[0] boolValue]) {
1266 if (responseHandle) {
1267 sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
1268 static_cast<const uint8_t*
>(response.bytes), response.length);
1269 responseHandle = NULL;
1271 NSLog(
@"Error: Message responses can be sent only once. Ignoring duplicate response "
1280 handlerInfo.
handler(messageData, binaryResponseHandler);
1282 binaryResponseHandler(nil);
1286 - (void)engineCallbackOnPreEngineRestart {
1287 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1289 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1292 [_platformViewController reset];
1298 - (void)onVSync:(uintptr_t)baton {
1303 [_vsyncWaiters objectForKey:[_vsyncWaiters.keyEnumerator nextObject]];
1304 if (waiter != nil) {
1310 self.embedderAPI.OnVsync(_engine, baton, 0, 0);
1313 if ([NSThread isMainThread]) {
1316 [FlutterRunLoop.mainRunLoop performBlock:block];
1323 - (void)shutDownEngine {
1324 if (_engine ==
nullptr) {
1328 FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
1329 if (result != kSuccess) {
1330 NSLog(
@"Could not de-initialize the Flutter engine: error %d", result);
1333 result = _embedderAPI.Shutdown(_engine);
1334 if (result != kSuccess) {
1335 NSLog(
@"Failed to shut down Flutter engine: error %d", result);
1341 NSAssert([[NSThread currentThread] isMainThread],
@"Must be called on the main thread.");
1342 return (__bridge
FlutterEngine*)
reinterpret_cast<void*
>(identifier);
1345 - (void)setUpPlatformViewChannel {
1352 [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1353 [[weakSelf platformViewController] handleMethodCall:call result:result];
1357 - (void)setUpAccessibilityChannel {
1363 [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1364 [weakSelf handleAccessibilityEvent:message];
1367 - (void)setUpNotificationCenterListeners {
1368 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1370 [center addObserver:self
1371 selector:@selector(onAccessibilityStatusChanged:)
1372 name:kEnhancedUserInterfaceNotification
1374 [center addObserver:self
1375 selector:@selector(applicationWillTerminate:)
1376 name:NSApplicationWillTerminateNotification
1378 [center addObserver:self
1379 selector:@selector(windowDidChangeScreen:)
1380 name:NSWindowDidChangeScreenNotification
1382 [center addObserver:self
1383 selector:@selector(updateDisplayConfig:)
1384 name:NSApplicationDidChangeScreenParametersNotification
1388 - (void)addInternalPlugins {
1402 [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1403 [weakSelf handleMethodCall:call result:result];
1407 - (void)didUpdateMouseCursor:(NSCursor*)cursor {
1411 [_lastViewWithPointerEvent didUpdateMouseCursor:cursor];
1414 - (void)applicationWillTerminate:(NSNotification*)notification {
1415 [
self shutDownEngine];
1418 - (void)windowDidChangeScreen:(NSNotification*)notification {
1421 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1423 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1424 [
self updateWindowMetricsForViewController:nextViewController];
1428 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1429 BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1430 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1432 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1436 self.semanticsEnabled = enabled;
1438 - (void)handleAccessibilityEvent:(NSDictionary<NSString*,
id>*)annotatedEvent {
1439 NSString* type = annotatedEvent[@"type"];
1440 if ([type isEqualToString:
@"announce"]) {
1441 NSString* message = annotatedEvent[@"data"][@"message"];
1442 NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1443 if (message == nil) {
1447 NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1448 ? NSAccessibilityPriorityHigh
1449 : NSAccessibilityPriorityMedium;
1451 [
self announceAccessibilityMessage:message withPriority:priority];
1455 - (void)announceAccessibilityMessage:(NSString*)message
1456 withPriority:(NSAccessibilityPriorityLevel)priority {
1457 NSAccessibilityPostNotificationWithUserInfo(
1458 [
self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView,
1459 NSAccessibilityAnnouncementRequestedNotification,
1460 @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
1463 if ([call.
method isEqualToString:
@"SystemNavigator.pop"]) {
1464 [[NSApplication sharedApplication] terminate:self];
1466 }
else if ([call.
method isEqualToString:
@"SystemSound.play"]) {
1467 [
self playSystemSound:call.arguments];
1469 }
else if ([call.
method isEqualToString:
@"Clipboard.getData"]) {
1470 result([
self getClipboardData:call.
arguments]);
1471 }
else if ([call.
method isEqualToString:
@"Clipboard.setData"]) {
1472 [
self setClipboardData:call.arguments];
1474 }
else if ([call.
method isEqualToString:
@"Clipboard.hasStrings"]) {
1475 result(@{
@"value" : @([
self clipboardHasStrings])});
1476 }
else if ([call.
method isEqualToString:
@"System.exitApplication"]) {
1477 if ([
self terminationHandler] == nil) {
1482 [NSApp terminate:self];
1485 [[
self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1487 }
else if ([call.
method isEqualToString:
@"System.initializationComplete"]) {
1488 if ([
self terminationHandler] != nil) {
1489 [
self terminationHandler].acceptingRequests = YES;
1497 - (void)playSystemSound:(NSString*)soundType {
1498 if ([soundType isEqualToString:
@"SystemSoundType.alert"]) {
1503 - (NSDictionary*)getClipboardData:(NSString*)format {
1505 NSString* stringInPasteboard = [
self.pasteboard stringForType:NSPasteboardTypeString];
1506 return stringInPasteboard == nil ? nil : @{
@"text" : stringInPasteboard};
1511 - (void)setClipboardData:(NSDictionary*)data {
1512 NSString* text = data[@"text"];
1513 [
self.pasteboard clearContents];
1514 if (text && ![text isEqual:[NSNull
null]]) {
1515 [
self.pasteboard setString:text forType:NSPasteboardTypeString];
1519 - (BOOL)clipboardHasStrings {
1520 return [
self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1523 - (std::vector<std::string>)switches {
1527 #pragma mark - FlutterAppLifecycleDelegate
1530 NSString* nextState =
1531 [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1532 [
self sendOnChannel:kFlutterLifecycleChannel
1533 message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1540 - (void)handleWillBecomeActive:(NSNotification*)notification {
1543 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1545 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1553 - (void)handleWillResignActive:(NSNotification*)notification {
1556 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1558 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1566 - (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1567 NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1568 if (occlusionState & NSApplicationOcclusionStateVisible) {
1571 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1573 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1577 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1581 #pragma mark - FlutterBinaryMessenger
1583 - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1584 [
self sendOnChannel:channel message:message binaryReply:nil];
1587 - (void)sendOnChannel:(NSString*)channel
1588 message:(NSData* _Nullable)message
1590 FlutterPlatformMessageResponseHandle* response_handle =
nullptr;
1595 auto captures = std::make_unique<Captures>();
1596 captures->reply = callback;
1597 auto message_reply = [](
const uint8_t* data,
size_t data_size,
void*
user_data) {
1598 auto captures =
reinterpret_cast<Captures*
>(
user_data);
1599 NSData* reply_data = nil;
1600 if (data !=
nullptr && data_size > 0) {
1601 reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1603 captures->reply(reply_data);
1607 FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
1608 _engine, message_reply, captures.get(), &response_handle);
1609 if (create_result != kSuccess) {
1610 NSLog(
@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1616 FlutterPlatformMessage platformMessage = {
1617 .struct_size =
sizeof(FlutterPlatformMessage),
1618 .channel = [channel UTF8String],
1619 .message =
static_cast<const uint8_t*
>(message.bytes),
1620 .message_size = message.length,
1621 .response_handle = response_handle,
1624 FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1625 if (message_result != kSuccess) {
1626 NSLog(
@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
1630 if (response_handle !=
nullptr) {
1631 FlutterEngineResult release_result =
1632 _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1633 if (release_result != kSuccess) {
1634 NSLog(
@"Failed to release the response handle (%d).", release_result);
1640 binaryMessageHandler:
1645 handler:[handler copy]];
1652 NSString* foundChannel = nil;
1655 if ([handlerInfo.
connection isEqual:@(connection)]) {
1661 [_messengerHandlers removeObjectForKey:foundChannel];
1665 #pragma mark - FlutterPluginRegistry
1668 id<FlutterPluginRegistrar> registrar =
self.pluginRegistrars[pluginName];
1672 self.pluginRegistrars[pluginName] = registrarImpl;
1673 registrar = registrarImpl;
1678 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1682 #pragma mark - FlutterTextureRegistrar
1685 return [_renderer registerTexture:texture];
1688 - (BOOL)registerTextureWithID:(int64_t)textureId {
1689 return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
1692 - (void)textureFrameAvailable:(int64_t)textureID {
1693 [_renderer textureFrameAvailable:textureID];
1696 - (BOOL)markTextureFrameAvailable:(int64_t)textureID {
1697 return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
1700 - (void)unregisterTexture:(int64_t)textureID {
1701 [_renderer unregisterTexture:textureID];
1704 - (BOOL)unregisterTextureWithID:(int64_t)textureID {
1705 return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
1708 #pragma mark - Task runner integration
1710 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1713 const auto engine_time = _embedderAPI.GetCurrentTime();
1714 [FlutterRunLoop.mainRunLoop
1715 performAfterDelay:(targetTime - (double)engine_time) / NSEC_PER_SEC
1718 if (self != nil && self->_engine != nil) {
1719 auto result = _embedderAPI.RunTask(self->_engine, &task);
1720 if (result != kSuccess) {
1721 NSLog(@"Could not post a task to the Flutter engine.");
1728 - (
flutter::FlutterCompositor*)macOSCompositor {
1732 #pragma mark - FlutterKeyboardManagerDelegate
1737 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
1738 callback:(FlutterKeyEventCallback)callback
1739 userData:(
void*)userData {
1740 _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)