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),
649 .
user_data = (__bridge_retained
void*)
self,
650 .runs_task_on_current_thread_callback = [](
void*
user_data) ->
bool {
651 return [[NSThread currentThread] isMainThread];
653 .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
656 [engine postMainThreadTask:task targetTimeInNanoseconds:target_time_nanos];
658 .identifier = ++sTaskRunnerIdentifiers,
659 .destruction_callback =
666 const FlutterCustomTaskRunners custom_task_runners = {
667 .struct_size =
sizeof(FlutterCustomTaskRunners),
668 .platform_task_runner = &cocoa_task_runner_description,
669 .thread_priority_setter = SetThreadPriority};
670 flutterArguments.custom_task_runners = &custom_task_runners;
672 [
self loadAOTData:_project.assetsPath];
674 flutterArguments.aot_data =
_aotData;
677 flutterArguments.compositor = [
self createFlutterCompositor];
679 flutterArguments.on_pre_engine_restart_callback = [](
void*
user_data) {
681 [engine engineCallbackOnPreEngineRestart];
684 flutterArguments.vsync_callback = [](
void*
user_data, intptr_t baton) {
686 [engine onVSync:baton];
689 FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
690 FlutterEngineResult result = _embedderAPI.Initialize(
691 FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge
void*)(
self), &_engine);
692 if (result != kSuccess) {
693 NSLog(
@"Failed to initialize Flutter engine: error %d", result);
697 result = _embedderAPI.RunInitialized(_engine);
698 if (result != kSuccess) {
699 NSLog(
@"Failed to run an initialized engine: error %d", result);
703 [
self sendUserLocales];
706 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
708 while ((nextViewController = [viewControllerEnumerator nextObject])) {
709 [
self updateWindowMetricsForViewController:nextViewController];
712 [
self updateDisplayConfig];
715 [
self sendInitialSettings];
719 - (void)loadAOTData:(NSString*)assetsDir {
720 if (!_embedderAPI.RunsAOTCompiledDartCode()) {
724 BOOL isDirOut =
false;
725 NSFileManager* fileManager = [NSFileManager defaultManager];
729 NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
731 if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
735 FlutterEngineAOTDataSource source = {};
736 source.type = kFlutterEngineAOTDataSourceTypeElfPath;
737 source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
739 auto result = _embedderAPI.CreateAOTData(&source, &
_aotData);
740 if (result != kSuccess) {
741 NSLog(
@"Failed to load AOT data from: %@", elfPath);
748 NSAssert(controller != nil,
@"The controller must not be nil.");
749 NSAssert(controller.
engine == nil,
750 @"The FlutterViewController is unexpectedly attached to "
751 @"engine %@ before initialization.",
754 @"The requested view ID is occupied.");
755 [_viewControllers setObject:controller forKey:@(viewIdentifier)];
756 [controller setUpWithEngine:self
757 viewIdentifier:viewIdentifier
758 threadSynchronizer:_threadSynchronizer];
759 NSAssert(controller.
viewIdentifier == viewIdentifier,
@"Failed to assign view ID.");
763 NSAssert(controller.
attached,
@"The FlutterViewController should switch to the attached mode "
764 @"after it is added to a FlutterEngine.");
765 NSAssert(controller.
engine ==
self,
766 @"The FlutterViewController was added to %@, but its engine unexpectedly became %@.",
769 if (controller.viewLoaded) {
770 [
self viewControllerViewDidLoad:controller];
779 block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
782 uint64_t targetTimeNanos =
784 FlutterEngine* engine = weakSelf;
790 [engine->_threadSynchronizer performOnPlatformThread:^{
791 engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
797 [_vsyncWaiters setObject:waiter forKey:@(viewController.viewIdentifier)];
806 if (controller != nil) {
807 [controller detachFromEngine];
809 @"The FlutterViewController unexpectedly stays attached after being removed. "
810 @"In unit tests, this is likely because either the FlutterViewController or "
811 @"the FlutterEngine is mocked. Please subclass these classes instead.");
813 [_viewControllers removeObjectForKey:@(viewIdentifier)];
815 [_vsyncWaiters removeObjectForKey:@(viewIdentifier)];
819 - (void)shutDownIfNeeded {
821 [
self shutDownEngine];
827 NSAssert(controller == nil || controller.
viewIdentifier == viewIdentifier,
828 @"The stored controller has unexpected view ID.");
834 [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
835 if (currentController == controller) {
839 if (currentController == nil && controller != nil) {
841 NSAssert(controller.
engine == nil,
842 @"Failed to set view controller to the engine: "
843 @"The given FlutterViewController is already attached to an engine %@. "
844 @"If you wanted to create an FlutterViewController and set it to an existing engine, "
845 @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
847 [
self registerViewController:controller forIdentifier:kFlutterImplicitViewId];
848 }
else if (currentController != nil && controller == nil) {
849 NSAssert(currentController.
viewIdentifier == kFlutterImplicitViewId,
850 @"The default controller has an unexpected ID %llu", currentController.
viewIdentifier);
852 [
self deregisterViewControllerForIdentifier:kFlutterImplicitViewId];
853 [
self shutDownIfNeeded];
857 @"Failed to set view controller to the engine: "
858 @"The engine already has an implicit view controller %@. "
859 @"If you wanted to make the implicit view render in a different window, "
860 @"you should attach the current view controller to the window instead.",
866 return [
self viewControllerForIdentifier:kFlutterImplicitViewId];
869 - (FlutterCompositor*)createFlutterCompositor {
871 _compositor.struct_size =
sizeof(FlutterCompositor);
874 _compositor.create_backing_store_callback = [](
const FlutterBackingStoreConfig* config,
875 FlutterBackingStore* backing_store_out,
879 config, backing_store_out);
882 _compositor.collect_backing_store_callback = [](
const FlutterBackingStore* backing_store,
886 _compositor.present_view_callback = [](
const FlutterPresentViewInfo* info) {
888 ->Present(info->view_id, info->layers, info->layers_count);
900 #pragma mark - Framework-internal methods
905 NSAssert(
self.viewController == nil,
906 @"The engine already has a view controller for the implicit view.");
907 self.viewController = controller;
911 [
self deregisterViewControllerForIdentifier:viewController.viewIdentifier];
912 [
self shutDownIfNeeded];
916 return _engine !=
nullptr;
919 - (void)updateDisplayConfig:(NSNotification*)notification {
920 [
self updateDisplayConfig];
923 - (NSArray<NSScreen*>*)screens {
924 return [NSScreen screens];
927 - (void)updateDisplayConfig {
932 std::vector<FlutterEngineDisplay> displays;
933 for (NSScreen* screen : [
self screens]) {
934 CGDirectDisplayID displayID =
935 static_cast<CGDirectDisplayID
>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
937 double devicePixelRatio = screen.backingScaleFactor;
938 FlutterEngineDisplay display;
939 display.struct_size =
sizeof(display);
940 display.display_id = displayID;
941 display.single_display =
false;
942 display.width =
static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
943 display.height =
static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
944 display.device_pixel_ratio = devicePixelRatio;
946 CVDisplayLinkRef displayLinkRef = nil;
947 CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
950 CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
951 if (!(nominal.flags & kCVTimeIsIndefinite)) {
952 double refreshRate =
static_cast<double>(nominal.timeScale) / nominal.timeValue;
953 display.refresh_rate = round(refreshRate);
955 CVDisplayLinkRelease(displayLinkRef);
957 display.refresh_rate = 0;
960 displays.push_back(display);
962 _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
963 displays.data(), displays.size());
966 - (void)onSettingsChanged:(NSNotification*)notification {
968 NSString* brightness =
969 [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
970 [_settingsChannel sendMessage:@{
971 @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
973 @"textScaleFactor" : @1.0,
978 - (void)sendInitialSettings {
980 [[NSDistributedNotificationCenter defaultCenter]
982 selector:@selector(onSettingsChanged:)
983 name:@"AppleInterfaceThemeChangedNotification"
985 [
self onSettingsChanged:nil];
988 - (FlutterEngineProcTable&)embedderAPI {
992 - (nonnull NSString*)executableName {
993 return [[[NSProcessInfo processInfo] arguments] firstObject] ?:
@"Flutter";
997 if (!_engine || !viewController || !viewController.viewLoaded) {
1000 NSAssert([
self viewControllerForIdentifier:viewController.
viewIdentifier] == viewController,
1001 @"The provided view controller is not attached to this engine.");
1002 NSView* view = viewController.flutterView;
1003 CGRect scaledBounds = [view convertRectToBacking:view.bounds];
1004 CGSize scaledSize = scaledBounds.size;
1005 double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
1006 auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
1007 const FlutterWindowMetricsEvent windowMetricsEvent = {
1008 .struct_size =
sizeof(windowMetricsEvent),
1009 .width =
static_cast<size_t>(scaledSize.width),
1010 .height =
static_cast<size_t>(scaledSize.height),
1011 .pixel_ratio = pixelRatio,
1012 .left =
static_cast<size_t>(scaledBounds.origin.x),
1013 .top =
static_cast<size_t>(scaledBounds.origin.y),
1014 .display_id =
static_cast<uint64_t
>(displayId),
1017 _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
1020 - (void)sendPointerEvent:(const FlutterPointerEvent&)event {
1021 _embedderAPI.SendPointerEvent(_engine, &event, 1);
1025 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
1026 callback:(FlutterKeyEventCallback)callback
1027 userData:(
void*)userData {
1028 _embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
1031 - (void)setSemanticsEnabled:(BOOL)enabled {
1032 if (_semanticsEnabled == enabled) {
1035 _semanticsEnabled = enabled;
1038 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1040 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1041 [nextViewController notifySemanticsEnabledChanged];
1044 _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
1047 - (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
1048 toTarget:(uint16_t)target
1049 withData:(fml::MallocMapping)data {
1050 _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
1057 #pragma mark - Private methods
1059 - (void)sendUserLocales {
1060 if (!
self.running) {
1065 NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
1066 std::vector<FlutterLocale> flutterLocales;
1067 flutterLocales.reserve(locales.count);
1068 for (NSString* localeID in [NSLocale preferredLanguages]) {
1069 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1070 [locales addObject:locale];
1074 std::vector<const FlutterLocale*> flutterLocaleList;
1075 flutterLocaleList.reserve(flutterLocales.size());
1076 std::transform(flutterLocales.begin(), flutterLocales.end(),
1077 std::back_inserter(flutterLocaleList),
1078 [](
const auto& arg) ->
const auto* { return &arg; });
1079 _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
1082 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
1083 NSData* messageData = nil;
1084 if (message->message_size > 0) {
1085 messageData = [NSData dataWithBytesNoCopy:(void*)message->message
1086 length:message->message_size
1089 NSString* channel = @(message->channel);
1090 __block
const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
1092 NSMutableArray* isResponseValid =
self.isResponseValid;
1093 FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
1094 _embedderAPI.SendPlatformMessageResponse;
1096 @
synchronized(isResponseValid) {
1097 if (![isResponseValid[0] boolValue]) {
1101 if (responseHandle) {
1102 sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
1103 static_cast<const uint8_t*
>(response.bytes), response.length);
1104 responseHandle = NULL;
1106 NSLog(
@"Error: Message responses can be sent only once. Ignoring duplicate response "
1115 handlerInfo.
handler(messageData, binaryResponseHandler);
1117 binaryResponseHandler(nil);
1121 - (void)engineCallbackOnPreEngineRestart {
1122 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1124 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1129 - (void)onVSync:(uintptr_t)baton {
1141 - (void)shutDownEngine {
1142 if (_engine ==
nullptr) {
1146 [_threadSynchronizer shutdown];
1149 FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
1150 if (result != kSuccess) {
1151 NSLog(
@"Could not de-initialize the Flutter engine: error %d", result);
1154 result = _embedderAPI.Shutdown(_engine);
1155 if (result != kSuccess) {
1156 NSLog(
@"Failed to shut down Flutter engine: error %d", result);
1161 - (void)setUpPlatformViewChannel {
1168 [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1169 [[weakSelf platformViewController] handleMethodCall:call result:result];
1173 - (void)setUpAccessibilityChannel {
1179 [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1180 [weakSelf handleAccessibilityEvent:message];
1183 - (void)setUpNotificationCenterListeners {
1184 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1186 [center addObserver:self
1187 selector:@selector(onAccessibilityStatusChanged:)
1188 name:kEnhancedUserInterfaceNotification
1190 [center addObserver:self
1191 selector:@selector(applicationWillTerminate:)
1192 name:NSApplicationWillTerminateNotification
1194 [center addObserver:self
1195 selector:@selector(windowDidChangeScreen:)
1196 name:NSWindowDidChangeScreenNotification
1198 [center addObserver:self
1199 selector:@selector(updateDisplayConfig:)
1200 name:NSApplicationDidChangeScreenParametersNotification
1204 - (void)addInternalPlugins {
1217 [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1218 [weakSelf handleMethodCall:call result:result];
1222 - (void)didUpdateMouseCursor:(NSCursor*)cursor {
1226 [_lastViewWithPointerEvent didUpdateMouseCursor:cursor];
1229 - (void)applicationWillTerminate:(NSNotification*)notification {
1230 [
self shutDownEngine];
1233 - (void)windowDidChangeScreen:(NSNotification*)notification {
1236 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1238 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1239 [
self updateWindowMetricsForViewController:nextViewController];
1243 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1244 BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1245 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1247 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1251 self.semanticsEnabled = enabled;
1253 - (void)handleAccessibilityEvent:(NSDictionary<NSString*,
id>*)annotatedEvent {
1254 NSString* type = annotatedEvent[@"type"];
1255 if ([type isEqualToString:
@"announce"]) {
1256 NSString* message = annotatedEvent[@"data"][@"message"];
1257 NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1258 if (message == nil) {
1262 NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1263 ? NSAccessibilityPriorityHigh
1264 : NSAccessibilityPriorityMedium;
1266 [
self announceAccessibilityMessage:message withPriority:priority];
1270 - (void)announceAccessibilityMessage:(NSString*)message
1271 withPriority:(NSAccessibilityPriorityLevel)priority {
1272 NSAccessibilityPostNotificationWithUserInfo(
1273 [
self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView,
1274 NSAccessibilityAnnouncementRequestedNotification,
1275 @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
1278 if ([call.
method isEqualToString:
@"SystemNavigator.pop"]) {
1279 [[NSApplication sharedApplication] terminate:self];
1281 }
else if ([call.
method isEqualToString:
@"SystemSound.play"]) {
1282 [
self playSystemSound:call.arguments];
1284 }
else if ([call.
method isEqualToString:
@"Clipboard.getData"]) {
1285 result([
self getClipboardData:call.
arguments]);
1286 }
else if ([call.
method isEqualToString:
@"Clipboard.setData"]) {
1287 [
self setClipboardData:call.arguments];
1289 }
else if ([call.
method isEqualToString:
@"Clipboard.hasStrings"]) {
1290 result(@{
@"value" : @([
self clipboardHasStrings])});
1291 }
else if ([call.
method isEqualToString:
@"System.exitApplication"]) {
1292 if ([
self terminationHandler] == nil) {
1297 [NSApp terminate:self];
1300 [[
self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1302 }
else if ([call.
method isEqualToString:
@"System.initializationComplete"]) {
1303 if ([
self terminationHandler] != nil) {
1304 [
self terminationHandler].acceptingRequests = YES;
1312 - (void)playSystemSound:(NSString*)soundType {
1313 if ([soundType isEqualToString:
@"SystemSoundType.alert"]) {
1318 - (NSDictionary*)getClipboardData:(NSString*)format {
1320 NSString* stringInPasteboard = [
self.pasteboard stringForType:NSPasteboardTypeString];
1321 return stringInPasteboard == nil ? nil : @{
@"text" : stringInPasteboard};
1326 - (void)setClipboardData:(NSDictionary*)data {
1327 NSString* text = data[@"text"];
1328 [
self.pasteboard clearContents];
1329 if (text && ![text isEqual:[NSNull
null]]) {
1330 [
self.pasteboard setString:text forType:NSPasteboardTypeString];
1334 - (BOOL)clipboardHasStrings {
1335 return [
self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1338 - (std::vector<std::string>)switches {
1346 #pragma mark - FlutterAppLifecycleDelegate
1349 NSString* nextState =
1350 [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1351 [
self sendOnChannel:kFlutterLifecycleChannel
1352 message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1359 - (void)handleWillBecomeActive:(NSNotification*)notification {
1362 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1364 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1372 - (void)handleWillResignActive:(NSNotification*)notification {
1375 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1377 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1385 - (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1386 NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1387 if (occlusionState & NSApplicationOcclusionStateVisible) {
1390 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1392 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1396 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1400 #pragma mark - FlutterBinaryMessenger
1402 - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1403 [
self sendOnChannel:channel message:message binaryReply:nil];
1406 - (void)sendOnChannel:(NSString*)channel
1407 message:(NSData* _Nullable)message
1409 FlutterPlatformMessageResponseHandle* response_handle =
nullptr;
1414 auto captures = std::make_unique<Captures>();
1415 captures->reply = callback;
1416 auto message_reply = [](
const uint8_t* data,
size_t data_size,
void*
user_data) {
1417 auto captures =
reinterpret_cast<Captures*
>(
user_data);
1418 NSData* reply_data = nil;
1419 if (data !=
nullptr && data_size > 0) {
1420 reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1422 captures->reply(reply_data);
1426 FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
1427 _engine, message_reply, captures.get(), &response_handle);
1428 if (create_result != kSuccess) {
1429 NSLog(
@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1435 FlutterPlatformMessage platformMessage = {
1436 .struct_size =
sizeof(FlutterPlatformMessage),
1437 .channel = [channel UTF8String],
1438 .message =
static_cast<const uint8_t*
>(message.bytes),
1439 .message_size = message.length,
1440 .response_handle = response_handle,
1443 FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1444 if (message_result != kSuccess) {
1445 NSLog(
@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
1449 if (response_handle !=
nullptr) {
1450 FlutterEngineResult release_result =
1451 _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1452 if (release_result != kSuccess) {
1453 NSLog(
@"Failed to release the response handle (%d).", release_result);
1459 binaryMessageHandler:
1464 handler:[handler copy]];
1471 NSString* foundChannel = nil;
1474 if ([handlerInfo.
connection isEqual:@(connection)]) {
1480 [_messengerHandlers removeObjectForKey:foundChannel];
1484 #pragma mark - FlutterPluginRegistry
1487 id<FlutterPluginRegistrar> registrar =
self.pluginRegistrars[pluginName];
1491 self.pluginRegistrars[pluginName] = registrarImpl;
1492 registrar = registrarImpl;
1497 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1501 #pragma mark - FlutterTextureRegistrar
1504 return [_renderer registerTexture:texture];
1507 - (BOOL)registerTextureWithID:(int64_t)textureId {
1508 return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
1511 - (void)textureFrameAvailable:(int64_t)textureID {
1512 [_renderer textureFrameAvailable:textureID];
1515 - (BOOL)markTextureFrameAvailable:(int64_t)textureID {
1516 return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
1519 - (void)unregisterTexture:(int64_t)textureID {
1520 [_renderer unregisterTexture:textureID];
1523 - (BOOL)unregisterTextureWithID:(int64_t)textureID {
1524 return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
1527 #pragma mark - Task runner integration
1529 - (void)runTaskOnEmbedder:(FlutterTask)task {
1531 auto result = _embedderAPI.RunTask(_engine, &task);
1532 if (result != kSuccess) {
1533 NSLog(
@"Could not post a task to the Flutter engine.");
1538 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1541 [weakSelf runTaskOnEmbedder:task];
1544 const auto engine_time = _embedderAPI.GetCurrentTime();
1545 if (targetTime <= engine_time) {
1546 dispatch_async(dispatch_get_main_queue(), worker);
1549 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, targetTime - engine_time),
1550 dispatch_get_main_queue(), worker);
1555 - (
flutter::FlutterCompositor*)macOSCompositor {