12 #include "flutter/common/constants.h"
15 #include "flutter/shell/platform/embedder/embedder.h"
38 using flutter::kFlutterImplicitViewId;
45 FlutterLocale flutterLocale = {};
46 flutterLocale.struct_size =
sizeof(FlutterLocale);
47 flutterLocale.language_code = [[locale objectForKey:NSLocaleLanguageCode] UTF8String];
48 flutterLocale.country_code = [[locale objectForKey:NSLocaleCountryCode] UTF8String];
49 flutterLocale.script_code = [[locale objectForKey:NSLocaleScriptCode] UTF8String];
50 flutterLocale.variant_code = [[locale objectForKey:NSLocaleVariantCode] UTF8String];
56 @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification";
68 - (instancetype)initWithConnection:(NSNumber*)connection
77 - (instancetype)initWithConnection:(NSNumber*)connection
80 NSAssert(
self,
@"Super init cannot be nil");
99 @property(nonatomic, strong) NSMutableArray<NSNumber*>* isResponseValid;
104 @property(nonatomic, strong) NSPointerArray* pluginAppDelegates;
109 @property(nonatomic, readonly)
110 NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* pluginRegistrars;
137 - (void)shutDownIfNeeded;
142 - (void)sendUserLocales;
147 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message;
155 - (void)engineCallbackOnPreEngineRestart;
161 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime;
167 - (void)loadAOTData:(NSString*)assetsDir;
172 - (void)setUpPlatformViewChannel;
177 - (void)setUpAccessibilityChannel;
196 _acceptingRequests = NO;
198 _terminator = terminator ? terminator : ^(
id sender) {
201 [[NSApplication sharedApplication] terminate:sender];
203 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
204 if ([appDelegate respondsToSelector:
@selector(setTerminationHandler:)]) {
206 flutterAppDelegate.terminationHandler =
self;
213 - (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*,
id>*)arguments
215 NSString* type = arguments[@"type"];
221 FlutterAppExitType exitType =
222 [type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired;
231 - (void)requestApplicationTermination:(
id)sender
232 exitType:(FlutterAppExitType)type
234 _shouldTerminate = YES;
235 if (![
self acceptingRequests]) {
238 type = kFlutterAppExitTypeRequired;
241 case kFlutterAppExitTypeCancelable: {
245 [_engine sendOnChannel:kFlutterPlatformChannel
246 message:[codec encodeMethodCall:methodCall]
247 binaryReply:^(NSData* _Nullable reply) {
248 NSAssert(_terminator, @"terminator shouldn't be nil");
249 id decoded_reply = [codec decodeEnvelope:reply];
250 if ([decoded_reply isKindOfClass:[
FlutterError class]]) {
252 NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message],
257 if (![decoded_reply isKindOfClass:[NSDictionary class]]) {
258 NSLog(@"Call to System.requestAppExit returned an unexpected object: %@",
263 NSDictionary* replyArgs = (NSDictionary*)decoded_reply;
264 if ([replyArgs[@"response"] isEqual:@"exit"]) {
266 } else if ([replyArgs[@"response"] isEqual:@"cancel"]) {
267 _shouldTerminate = NO;
275 case kFlutterAppExitTypeRequired:
276 NSAssert(
_terminator,
@"terminator shouldn't be nil");
289 return [[NSPasteboard generalPasteboard] clearContents];
292 - (NSString*)stringForType:(NSPasteboardType)dataType {
293 return [[NSPasteboard generalPasteboard] stringForType:dataType];
296 - (BOOL)setString:(nonnull NSString*)string forType:(nonnull NSPasteboardType)dataType {
297 return [[NSPasteboard generalPasteboard] setString:string forType:dataType];
308 - (instancetype)initWithPlugin:(nonnull NSString*)pluginKey
322 NSString* _pluginKey;
328 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
331 _pluginKey = [pluginKey copy];
333 _publishedValue = [NSNull null];
338 #pragma mark - FlutterPluginRegistrar
349 return [
self viewForIdentifier:kFlutterImplicitViewId];
354 if (controller == nil) {
357 if (!controller.viewLoaded) {
358 [controller loadView];
360 return controller.flutterView;
363 - (void)addMethodCallDelegate:(nonnull
id<
FlutterPlugin>)delegate
371 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
373 id<FlutterAppLifecycleProvider> lifeCycleProvider =
374 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
375 [lifeCycleProvider addApplicationLifecycleDelegate:delegate];
376 [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
381 withId:(nonnull NSString*)factoryId {
382 [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
385 - (void)publish:(NSObject*)value {
386 _publishedValue = value;
389 - (NSString*)lookupKeyForAsset:(NSString*)asset {
393 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
400 #pragma mark - Static methods provided to engine configuration
404 [engine engineCallbackOnPlatformMessage:message];
478 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
479 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
484 static void SetThreadPriority(FlutterThreadPriority priority) {
485 if (priority == kDisplay || priority == kRaster) {
486 pthread_t thread = pthread_self();
489 if (!pthread_getschedparam(thread, &policy, ¶m)) {
491 pthread_setschedparam(thread, policy, ¶m);
493 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
497 - (instancetype)initWithName:(NSString*)labelPrefix
499 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
501 NSAssert(
self,
@"Super init cannot be nil");
508 _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
509 _pluginRegistrars = [[NSMutableDictionary alloc] init];
512 _semanticsEnabled = NO;
514 _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
515 [_isResponseValid addObject:@YES];
517 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
518 FlutterEngineGetProcAddresses(&_embedderAPI);
523 NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
524 [notificationCenter addObserver:self
525 selector:@selector(sendUserLocales)
526 name:NSCurrentLocaleDidChangeNotification
537 [
self setUpPlatformViewChannel];
538 [
self setUpAccessibilityChannel];
539 [
self setUpNotificationCenterListeners];
540 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
544 id<FlutterAppLifecycleProvider> lifecycleProvider =
545 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
546 [lifecycleProvider addApplicationLifecycleDelegate:self];
548 _terminationHandler = nil;
557 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
559 id<FlutterAppLifecycleProvider> lifecycleProvider =
560 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
561 [lifecycleProvider removeApplicationLifecycleDelegate:self];
566 for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
568 [lifecycleProvider removeApplicationLifecycleDelegate:delegate];
574 for (NSString* pluginName in _pluginRegistrars) {
575 [_pluginRegistrars[pluginName] publish:[NSNull null]];
577 @
synchronized(_isResponseValid) {
578 [_isResponseValid removeAllObjects];
579 [_isResponseValid addObject:@NO];
581 [
self shutDownEngine];
583 _embedderAPI.CollectAOTData(
_aotData);
587 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
593 NSLog(
@"Attempted to run an engine with no view controller without headless mode enabled.");
597 [
self addInternalPlugins];
600 std::vector<const char*> argv = {[
self.executableName UTF8String]};
601 std::vector<std::string> switches =
self.switches;
605 std::find(switches.begin(), switches.end(),
"--enable-impeller=true") != switches.end()) {
606 switches.push_back(
"--enable-impeller=true");
609 std::transform(switches.begin(), switches.end(), std::back_inserter(argv),
610 [](
const std::string& arg) ->
const char* { return arg.c_str(); });
612 std::vector<const char*> dartEntrypointArgs;
613 for (NSString* argument in [
_project dartEntrypointArguments]) {
614 dartEntrypointArgs.push_back([argument UTF8String]);
617 FlutterProjectArgs flutterArguments = {};
618 flutterArguments.struct_size =
sizeof(FlutterProjectArgs);
619 flutterArguments.assets_path =
_project.assetsPath.UTF8String;
620 flutterArguments.icu_data_path =
_project.ICUDataPath.UTF8String;
621 flutterArguments.command_line_argc =
static_cast<int>(argv.size());
622 flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data();
623 flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)
OnPlatformMessage;
624 flutterArguments.update_semantics_callback2 = [](
const FlutterSemanticsUpdate2* update,
630 [[engine viewControllerForIdentifier:kFlutterImplicitViewId] updateSemantics:update];
632 flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String;
633 flutterArguments.shutdown_dart_vm_when_done =
true;
634 flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size();
635 flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data();
636 flutterArguments.root_isolate_create_callback =
_project.rootIsolateCreateCallback;
637 flutterArguments.log_message_callback = [](
const char* tag,
const char* message,
640 std::cout << tag <<
": ";
642 std::cout << message << std::endl;
645 static size_t sTaskRunnerIdentifiers = 0;
646 const FlutterTaskRunnerDescription cocoa_task_runner_description = {
647 .struct_size =
sizeof(FlutterTaskRunnerDescription),
648 .
user_data = (
void*)CFBridgingRetain(
self),
649 .runs_task_on_current_thread_callback = [](
void*
user_data) ->
bool {
650 return [[NSThread currentThread] isMainThread];
652 .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
655 targetTimeInNanoseconds:target_time_nanos];
657 .identifier = ++sTaskRunnerIdentifiers,
659 const FlutterCustomTaskRunners custom_task_runners = {
660 .struct_size =
sizeof(FlutterCustomTaskRunners),
661 .platform_task_runner = &cocoa_task_runner_description,
662 .thread_priority_setter = SetThreadPriority};
663 flutterArguments.custom_task_runners = &custom_task_runners;
665 [
self loadAOTData:_project.assetsPath];
667 flutterArguments.aot_data =
_aotData;
670 flutterArguments.compositor = [
self createFlutterCompositor];
672 flutterArguments.on_pre_engine_restart_callback = [](
void*
user_data) {
674 [engine engineCallbackOnPreEngineRestart];
677 flutterArguments.vsync_callback = [](
void*
user_data, intptr_t baton) {
679 [engine onVSync:baton];
682 FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
683 FlutterEngineResult result = _embedderAPI.Initialize(
684 FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge
void*)(
self), &_engine);
685 if (result != kSuccess) {
686 NSLog(
@"Failed to initialize Flutter engine: error %d", result);
690 result = _embedderAPI.RunInitialized(_engine);
691 if (result != kSuccess) {
692 NSLog(
@"Failed to run an initialized engine: error %d", result);
696 [
self sendUserLocales];
699 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
701 while ((nextViewController = [viewControllerEnumerator nextObject])) {
702 [
self updateWindowMetricsForViewController:nextViewController];
705 [
self updateDisplayConfig];
708 [
self sendInitialSettings];
712 - (void)loadAOTData:(NSString*)assetsDir {
713 if (!_embedderAPI.RunsAOTCompiledDartCode()) {
717 BOOL isDirOut =
false;
718 NSFileManager* fileManager = [NSFileManager defaultManager];
722 NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
724 if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
728 FlutterEngineAOTDataSource source = {};
729 source.type = kFlutterEngineAOTDataSourceTypeElfPath;
730 source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
732 auto result = _embedderAPI.CreateAOTData(&source, &
_aotData);
733 if (result != kSuccess) {
734 NSLog(
@"Failed to load AOT data from: %@", elfPath);
741 NSAssert(controller != nil,
@"The controller must not be nil.");
742 NSAssert(controller.
engine == nil,
743 @"The FlutterViewController is unexpectedly attached to "
744 @"engine %@ before initialization.",
747 @"The requested view ID is occupied.");
748 [_viewControllers setObject:controller forKey:@(viewIdentifier)];
749 [controller setUpWithEngine:self
750 viewIdentifier:viewIdentifier
751 threadSynchronizer:_threadSynchronizer];
752 NSAssert(controller.
viewIdentifier == viewIdentifier,
@"Failed to assign view ID.");
756 NSAssert(controller.
attached,
@"The FlutterViewController should switch to the attached mode "
757 @"after it is added to a FlutterEngine.");
758 NSAssert(controller.
engine ==
self,
759 @"The FlutterViewController was added to %@, but its engine unexpectedly became %@.",
762 if (controller.viewLoaded) {
763 [
self viewControllerViewDidLoad:controller];
772 block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
775 uint64_t targetTimeNanos =
777 FlutterEngine* engine = weakSelf;
783 [engine->_threadSynchronizer performOnPlatformThread:^{
784 engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
790 [_vsyncWaiters setObject:waiter forKey:@(viewController.viewIdentifier)];
799 if (controller != nil) {
800 [controller detachFromEngine];
802 @"The FlutterViewController unexpectedly stays attached after being removed. "
803 @"In unit tests, this is likely because either the FlutterViewController or "
804 @"the FlutterEngine is mocked. Please subclass these classes instead.");
806 [_viewControllers removeObjectForKey:@(viewIdentifier)];
808 [_vsyncWaiters removeObjectForKey:@(viewIdentifier)];
812 - (void)shutDownIfNeeded {
814 [
self shutDownEngine];
820 NSAssert(controller == nil || controller.
viewIdentifier == viewIdentifier,
821 @"The stored controller has unexpected view ID.");
827 [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
828 if (currentController == controller) {
832 if (currentController == nil && controller != nil) {
834 NSAssert(controller.
engine == nil,
835 @"Failed to set view controller to the engine: "
836 @"The given FlutterViewController is already attached to an engine %@. "
837 @"If you wanted to create an FlutterViewController and set it to an existing engine, "
838 @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
840 [
self registerViewController:controller forIdentifier:kFlutterImplicitViewId];
841 }
else if (currentController != nil && controller == nil) {
842 NSAssert(currentController.
viewIdentifier == kFlutterImplicitViewId,
843 @"The default controller has an unexpected ID %llu", currentController.
viewIdentifier);
845 [
self deregisterViewControllerForIdentifier:kFlutterImplicitViewId];
846 [
self shutDownIfNeeded];
850 @"Failed to set view controller to the engine: "
851 @"The engine already has an implicit view controller %@. "
852 @"If you wanted to make the implicit view render in a different window, "
853 @"you should attach the current view controller to the window instead.",
859 return [
self viewControllerForIdentifier:kFlutterImplicitViewId];
862 - (FlutterCompositor*)createFlutterCompositor {
864 _compositor.struct_size =
sizeof(FlutterCompositor);
867 _compositor.create_backing_store_callback = [](
const FlutterBackingStoreConfig* config,
868 FlutterBackingStore* backing_store_out,
872 config, backing_store_out);
875 _compositor.collect_backing_store_callback = [](
const FlutterBackingStore* backing_store,
879 _compositor.present_view_callback = [](
const FlutterPresentViewInfo* info) {
881 ->Present(info->view_id, info->layers, info->layers_count);
893 #pragma mark - Framework-internal methods
898 NSAssert(
self.viewController == nil,
899 @"The engine already has a view controller for the implicit view.");
900 self.viewController = controller;
904 [
self deregisterViewControllerForIdentifier:viewController.viewIdentifier];
905 [
self shutDownIfNeeded];
909 return _engine !=
nullptr;
912 - (void)updateDisplayConfig:(NSNotification*)notification {
913 [
self updateDisplayConfig];
916 - (NSArray<NSScreen*>*)screens {
917 return [NSScreen screens];
920 - (void)updateDisplayConfig {
925 std::vector<FlutterEngineDisplay> displays;
926 for (NSScreen* screen : [
self screens]) {
927 CGDirectDisplayID displayID =
928 static_cast<CGDirectDisplayID
>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
930 double devicePixelRatio = screen.backingScaleFactor;
931 FlutterEngineDisplay display;
932 display.struct_size =
sizeof(display);
933 display.display_id = displayID;
934 display.single_display =
false;
935 display.width =
static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
936 display.height =
static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
937 display.device_pixel_ratio = devicePixelRatio;
939 CVDisplayLinkRef displayLinkRef = nil;
940 CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
943 CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
944 if (!(nominal.flags & kCVTimeIsIndefinite)) {
945 double refreshRate =
static_cast<double>(nominal.timeScale) / nominal.timeValue;
946 display.refresh_rate = round(refreshRate);
948 CVDisplayLinkRelease(displayLinkRef);
950 display.refresh_rate = 0;
953 displays.push_back(display);
955 _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
956 displays.data(), displays.size());
959 - (void)onSettingsChanged:(NSNotification*)notification {
961 NSString* brightness =
962 [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
963 [_settingsChannel sendMessage:@{
964 @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
966 @"textScaleFactor" : @1.0,
971 - (void)sendInitialSettings {
973 [[NSDistributedNotificationCenter defaultCenter]
975 selector:@selector(onSettingsChanged:)
976 name:@"AppleInterfaceThemeChangedNotification"
978 [
self onSettingsChanged:nil];
981 - (FlutterEngineProcTable&)embedderAPI {
985 - (nonnull NSString*)executableName {
986 return [[[NSProcessInfo processInfo] arguments] firstObject] ?:
@"Flutter";
990 if (!_engine || !viewController || !viewController.viewLoaded) {
993 NSAssert([
self viewControllerForIdentifier:viewController.
viewIdentifier] == viewController,
994 @"The provided view controller is not attached to this engine.");
995 NSView* view = viewController.flutterView;
996 CGRect scaledBounds = [view convertRectToBacking:view.bounds];
997 CGSize scaledSize = scaledBounds.size;
998 double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
999 auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
1000 const FlutterWindowMetricsEvent windowMetricsEvent = {
1001 .struct_size =
sizeof(windowMetricsEvent),
1002 .width =
static_cast<size_t>(scaledSize.width),
1003 .height =
static_cast<size_t>(scaledSize.height),
1004 .pixel_ratio = pixelRatio,
1005 .left =
static_cast<size_t>(scaledBounds.origin.x),
1006 .top =
static_cast<size_t>(scaledBounds.origin.y),
1007 .display_id =
static_cast<uint64_t
>(displayId),
1010 _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
1013 - (void)sendPointerEvent:(const FlutterPointerEvent&)event {
1014 _embedderAPI.SendPointerEvent(_engine, &event, 1);
1018 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
1019 callback:(FlutterKeyEventCallback)callback
1020 userData:(
void*)userData {
1021 _embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
1024 - (void)setSemanticsEnabled:(BOOL)enabled {
1025 if (_semanticsEnabled == enabled) {
1028 _semanticsEnabled = enabled;
1031 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1033 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1034 [nextViewController notifySemanticsEnabledChanged];
1037 _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
1040 - (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
1041 toTarget:(uint16_t)target
1042 withData:(fml::MallocMapping)data {
1043 _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
1050 #pragma mark - Private methods
1052 - (void)sendUserLocales {
1053 if (!
self.running) {
1058 NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
1059 std::vector<FlutterLocale> flutterLocales;
1060 flutterLocales.reserve(locales.count);
1061 for (NSString* localeID in [NSLocale preferredLanguages]) {
1062 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1063 [locales addObject:locale];
1067 std::vector<const FlutterLocale*> flutterLocaleList;
1068 flutterLocaleList.reserve(flutterLocales.size());
1069 std::transform(flutterLocales.begin(), flutterLocales.end(),
1070 std::back_inserter(flutterLocaleList),
1071 [](
const auto& arg) ->
const auto* { return &arg; });
1072 _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
1075 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
1076 NSData* messageData = nil;
1077 if (message->message_size > 0) {
1078 messageData = [NSData dataWithBytesNoCopy:(void*)message->message
1079 length:message->message_size
1082 NSString* channel = @(message->channel);
1083 __block
const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
1085 NSMutableArray* isResponseValid =
self.isResponseValid;
1086 FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
1087 _embedderAPI.SendPlatformMessageResponse;
1089 @
synchronized(isResponseValid) {
1090 if (![isResponseValid[0] boolValue]) {
1094 if (responseHandle) {
1095 sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
1096 static_cast<const uint8_t*
>(response.bytes), response.length);
1097 responseHandle = NULL;
1099 NSLog(
@"Error: Message responses can be sent only once. Ignoring duplicate response "
1108 handlerInfo.
handler(messageData, binaryResponseHandler);
1110 binaryResponseHandler(nil);
1114 - (void)engineCallbackOnPreEngineRestart {
1115 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1117 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1122 - (void)onVSync:(uintptr_t)baton {
1134 - (void)shutDownEngine {
1135 if (_engine ==
nullptr) {
1139 [_threadSynchronizer shutdown];
1142 FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
1143 if (result != kSuccess) {
1144 NSLog(
@"Could not de-initialize the Flutter engine: error %d", result);
1148 CFRelease((CFTypeRef)
self);
1150 result = _embedderAPI.Shutdown(_engine);
1151 if (result != kSuccess) {
1152 NSLog(
@"Failed to shut down Flutter engine: error %d", result);
1157 - (void)setUpPlatformViewChannel {
1164 [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1165 [[weakSelf platformViewController] handleMethodCall:call result:result];
1169 - (void)setUpAccessibilityChannel {
1175 [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1176 [weakSelf handleAccessibilityEvent:message];
1179 - (void)setUpNotificationCenterListeners {
1180 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1182 [center addObserver:self
1183 selector:@selector(onAccessibilityStatusChanged:)
1184 name:kEnhancedUserInterfaceNotification
1186 [center addObserver:self
1187 selector:@selector(applicationWillTerminate:)
1188 name:NSApplicationWillTerminateNotification
1190 [center addObserver:self
1191 selector:@selector(windowDidChangeScreen:)
1192 name:NSWindowDidChangeScreenNotification
1194 [center addObserver:self
1195 selector:@selector(updateDisplayConfig:)
1196 name:NSApplicationDidChangeScreenParametersNotification
1200 - (void)addInternalPlugins {
1213 [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1214 [weakSelf handleMethodCall:call result:result];
1218 - (void)didUpdateMouseCursor:(NSCursor*)cursor {
1222 [_lastViewWithPointerEvent didUpdateMouseCursor:cursor];
1225 - (void)applicationWillTerminate:(NSNotification*)notification {
1226 [
self shutDownEngine];
1229 - (void)windowDidChangeScreen:(NSNotification*)notification {
1232 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1234 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1235 [
self updateWindowMetricsForViewController:nextViewController];
1239 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1240 BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1241 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1243 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1247 self.semanticsEnabled = enabled;
1249 - (void)handleAccessibilityEvent:(NSDictionary<NSString*,
id>*)annotatedEvent {
1250 NSString* type = annotatedEvent[@"type"];
1251 if ([type isEqualToString:
@"announce"]) {
1252 NSString* message = annotatedEvent[@"data"][@"message"];
1253 NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1254 if (message == nil) {
1258 NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1259 ? NSAccessibilityPriorityHigh
1260 : NSAccessibilityPriorityMedium;
1262 [
self announceAccessibilityMessage:message withPriority:priority];
1266 - (void)announceAccessibilityMessage:(NSString*)message
1267 withPriority:(NSAccessibilityPriorityLevel)priority {
1268 NSAccessibilityPostNotificationWithUserInfo(
1269 [
self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView,
1270 NSAccessibilityAnnouncementRequestedNotification,
1271 @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
1274 if ([call.
method isEqualToString:
@"SystemNavigator.pop"]) {
1275 [[NSApplication sharedApplication] terminate:self];
1277 }
else if ([call.
method isEqualToString:
@"SystemSound.play"]) {
1278 [
self playSystemSound:call.arguments];
1280 }
else if ([call.
method isEqualToString:
@"Clipboard.getData"]) {
1281 result([
self getClipboardData:call.
arguments]);
1282 }
else if ([call.
method isEqualToString:
@"Clipboard.setData"]) {
1283 [
self setClipboardData:call.arguments];
1285 }
else if ([call.
method isEqualToString:
@"Clipboard.hasStrings"]) {
1286 result(@{
@"value" : @([
self clipboardHasStrings])});
1287 }
else if ([call.
method isEqualToString:
@"System.exitApplication"]) {
1288 if ([
self terminationHandler] == nil) {
1293 [NSApp terminate:self];
1296 [[
self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1298 }
else if ([call.
method isEqualToString:
@"System.initializationComplete"]) {
1299 if ([
self terminationHandler] != nil) {
1300 [
self terminationHandler].acceptingRequests = YES;
1308 - (void)playSystemSound:(NSString*)soundType {
1309 if ([soundType isEqualToString:
@"SystemSoundType.alert"]) {
1314 - (NSDictionary*)getClipboardData:(NSString*)format {
1316 NSString* stringInPasteboard = [
self.pasteboard stringForType:NSPasteboardTypeString];
1317 return stringInPasteboard == nil ? nil : @{
@"text" : stringInPasteboard};
1322 - (void)setClipboardData:(NSDictionary*)data {
1323 NSString* text = data[@"text"];
1324 [
self.pasteboard clearContents];
1325 if (text && ![text isEqual:[NSNull
null]]) {
1326 [
self.pasteboard setString:text forType:NSPasteboardTypeString];
1330 - (BOOL)clipboardHasStrings {
1331 return [
self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1334 - (std::vector<std::string>)switches {
1342 #pragma mark - FlutterAppLifecycleDelegate
1345 NSString* nextState =
1346 [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1347 [
self sendOnChannel:kFlutterLifecycleChannel
1348 message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1355 - (void)handleWillBecomeActive:(NSNotification*)notification {
1358 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1360 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1368 - (void)handleWillResignActive:(NSNotification*)notification {
1371 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1373 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1381 - (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1382 NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1383 if (occlusionState & NSApplicationOcclusionStateVisible) {
1386 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1388 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1392 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1396 #pragma mark - FlutterBinaryMessenger
1398 - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1399 [
self sendOnChannel:channel message:message binaryReply:nil];
1402 - (void)sendOnChannel:(NSString*)channel
1403 message:(NSData* _Nullable)message
1405 FlutterPlatformMessageResponseHandle* response_handle =
nullptr;
1410 auto captures = std::make_unique<Captures>();
1411 captures->reply = callback;
1412 auto message_reply = [](
const uint8_t* data,
size_t data_size,
void*
user_data) {
1413 auto captures =
reinterpret_cast<Captures*
>(
user_data);
1414 NSData* reply_data = nil;
1415 if (data !=
nullptr && data_size > 0) {
1416 reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1418 captures->reply(reply_data);
1422 FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
1423 _engine, message_reply, captures.get(), &response_handle);
1424 if (create_result != kSuccess) {
1425 NSLog(
@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1431 FlutterPlatformMessage platformMessage = {
1432 .struct_size =
sizeof(FlutterPlatformMessage),
1433 .channel = [channel UTF8String],
1434 .message =
static_cast<const uint8_t*
>(message.bytes),
1435 .message_size = message.length,
1436 .response_handle = response_handle,
1439 FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1440 if (message_result != kSuccess) {
1441 NSLog(
@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
1445 if (response_handle !=
nullptr) {
1446 FlutterEngineResult release_result =
1447 _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1448 if (release_result != kSuccess) {
1449 NSLog(
@"Failed to release the response handle (%d).", release_result);
1455 binaryMessageHandler:
1460 handler:[handler copy]];
1467 NSString* foundChannel = nil;
1470 if ([handlerInfo.
connection isEqual:@(connection)]) {
1476 [_messengerHandlers removeObjectForKey:foundChannel];
1480 #pragma mark - FlutterPluginRegistry
1483 id<FlutterPluginRegistrar> registrar =
self.pluginRegistrars[pluginName];
1487 self.pluginRegistrars[pluginName] = registrarImpl;
1488 registrar = registrarImpl;
1493 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1497 #pragma mark - FlutterTextureRegistrar
1500 return [_renderer registerTexture:texture];
1503 - (BOOL)registerTextureWithID:(int64_t)textureId {
1504 return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
1507 - (void)textureFrameAvailable:(int64_t)textureID {
1508 [_renderer textureFrameAvailable:textureID];
1511 - (BOOL)markTextureFrameAvailable:(int64_t)textureID {
1512 return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
1515 - (void)unregisterTexture:(int64_t)textureID {
1516 [_renderer unregisterTexture:textureID];
1519 - (BOOL)unregisterTextureWithID:(int64_t)textureID {
1520 return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
1523 #pragma mark - Task runner integration
1525 - (void)runTaskOnEmbedder:(FlutterTask)task {
1527 auto result = _embedderAPI.RunTask(_engine, &task);
1528 if (result != kSuccess) {
1529 NSLog(
@"Could not post a task to the Flutter engine.");
1534 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1537 [weakSelf runTaskOnEmbedder:task];
1540 const auto engine_time = _embedderAPI.GetCurrentTime();
1541 if (targetTime <= engine_time) {
1542 dispatch_async(dispatch_get_main_queue(), worker);
1545 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, targetTime - engine_time),
1546 dispatch_get_main_queue(), worker);
1551 - (
flutter::FlutterCompositor*)macOSCompositor {