14 #include "flutter/shell/platform/embedder/embedder.h"
42 FlutterLocale flutterLocale = {};
43 flutterLocale.struct_size =
sizeof(FlutterLocale);
44 flutterLocale.language_code = [[locale objectForKey:NSLocaleLanguageCode] UTF8String];
45 flutterLocale.country_code = [[locale objectForKey:NSLocaleCountryCode] UTF8String];
46 flutterLocale.script_code = [[locale objectForKey:NSLocaleScriptCode] UTF8String];
47 flutterLocale.variant_code = [[locale objectForKey:NSLocaleVariantCode] UTF8String];
53 @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification";
65 - (instancetype)initWithConnection:(NSNumber*)connection
74 - (instancetype)initWithConnection:(NSNumber*)connection
77 NSAssert(
self,
@"Super init cannot be nil");
96 @property(nonatomic, strong) NSMutableArray<NSNumber*>* isResponseValid;
101 @property(nonatomic, strong) NSPointerArray* pluginAppDelegates;
106 @property(nonatomic, readonly)
107 NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* pluginRegistrars;
132 - (void)shutDownIfNeeded;
137 - (void)sendUserLocales;
142 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message;
150 - (void)engineCallbackOnPreEngineRestart;
156 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime;
162 - (void)loadAOTData:(NSString*)assetsDir;
167 - (void)setUpPlatformViewChannel;
172 - (void)setUpAccessibilityChannel;
191 _acceptingRequests = NO;
193 _terminator = terminator ? terminator : ^(
id sender) {
196 [[NSApplication sharedApplication] terminate:sender];
198 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
199 if ([appDelegate respondsToSelector:
@selector(setTerminationHandler:)]) {
201 flutterAppDelegate.terminationHandler =
self;
208 - (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*,
id>*)arguments
210 NSString* type = arguments[@"type"];
216 FlutterAppExitType exitType =
217 [type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired;
226 - (void)requestApplicationTermination:(
id)sender
227 exitType:(FlutterAppExitType)type
229 _shouldTerminate = YES;
230 if (![
self acceptingRequests]) {
233 type = kFlutterAppExitTypeRequired;
236 case kFlutterAppExitTypeCancelable: {
240 [_engine sendOnChannel:kFlutterPlatformChannel
241 message:[codec encodeMethodCall:methodCall]
242 binaryReply:^(NSData* _Nullable reply) {
243 NSAssert(_terminator, @"terminator shouldn't be nil");
244 id decoded_reply = [codec decodeEnvelope:reply];
245 if ([decoded_reply isKindOfClass:[
FlutterError class]]) {
247 NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message],
252 if (![decoded_reply isKindOfClass:[NSDictionary class]]) {
253 NSLog(@"Call to System.requestAppExit returned an unexpected object: %@",
258 NSDictionary* replyArgs = (NSDictionary*)decoded_reply;
259 if ([replyArgs[@"response"] isEqual:@"exit"]) {
261 } else if ([replyArgs[@"response"] isEqual:@"cancel"]) {
262 _shouldTerminate = NO;
270 case kFlutterAppExitTypeRequired:
271 NSAssert(
_terminator,
@"terminator shouldn't be nil");
284 return [[NSPasteboard generalPasteboard] clearContents];
287 - (NSString*)stringForType:(NSPasteboardType)dataType {
288 return [[NSPasteboard generalPasteboard] stringForType:dataType];
291 - (BOOL)setString:(nonnull NSString*)string forType:(nonnull NSPasteboardType)dataType {
292 return [[NSPasteboard generalPasteboard] setString:string forType:dataType];
303 - (instancetype)initWithPlugin:(nonnull NSString*)pluginKey
317 NSString* _pluginKey;
323 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
326 _pluginKey = [pluginKey copy];
328 _publishedValue = [NSNull null];
333 #pragma mark - FlutterPluginRegistrar
344 return [
self viewForId:kFlutterImplicitViewId];
349 if (controller == nil) {
352 if (!controller.viewLoaded) {
353 [controller loadView];
355 return controller.flutterView;
358 - (void)addMethodCallDelegate:(nonnull
id<
FlutterPlugin>)delegate
366 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
368 id<FlutterAppLifecycleProvider> lifeCycleProvider =
369 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
370 [lifeCycleProvider addApplicationLifecycleDelegate:delegate];
371 [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
376 withId:(nonnull NSString*)factoryId {
377 [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
380 - (void)publish:(NSObject*)value {
381 _publishedValue = value;
384 - (NSString*)lookupKeyForAsset:(NSString*)asset {
388 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
395 #pragma mark - Static methods provided to engine configuration
398 [engine engineCallbackOnPlatformMessage:message];
471 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
472 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
477 static void SetThreadPriority(FlutterThreadPriority priority) {
478 if (priority == kDisplay || priority == kRaster) {
479 pthread_t thread = pthread_self();
482 if (!pthread_getschedparam(thread, &policy, ¶m)) {
484 pthread_setschedparam(thread, policy, ¶m);
486 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
490 - (instancetype)initWithName:(NSString*)labelPrefix
492 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
494 NSAssert(
self,
@"Super init cannot be nil");
501 _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
502 _pluginRegistrars = [[NSMutableDictionary alloc] init];
505 _semanticsEnabled = NO;
507 _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
508 [_isResponseValid addObject:@YES];
512 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
513 FlutterEngineGetProcAddresses(&_embedderAPI);
518 NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
519 [notificationCenter addObserver:self
520 selector:@selector(sendUserLocales)
521 name:NSCurrentLocaleDidChangeNotification
526 [
self setUpPlatformViewChannel];
527 [
self setUpAccessibilityChannel];
528 [
self setUpNotificationCenterListeners];
529 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
533 id<FlutterAppLifecycleProvider> lifecycleProvider =
534 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
535 [lifecycleProvider addApplicationLifecycleDelegate:self];
537 _terminationHandler = nil;
546 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
548 id<FlutterAppLifecycleProvider> lifecycleProvider =
549 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
550 [lifecycleProvider removeApplicationLifecycleDelegate:self];
555 for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
557 [lifecycleProvider removeApplicationLifecycleDelegate:delegate];
563 for (NSString* pluginName in _pluginRegistrars) {
564 [_pluginRegistrars[pluginName] publish:[NSNull null]];
566 @
synchronized(_isResponseValid) {
567 [_isResponseValid removeAllObjects];
568 [_isResponseValid addObject:@NO];
570 [
self shutDownEngine];
572 _embedderAPI.CollectAOTData(
_aotData);
576 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
582 NSLog(
@"Attempted to run an engine with no view controller without headless mode enabled.");
586 [
self addInternalPlugins];
589 std::vector<const char*> argv = {[
self.executableName UTF8String]};
590 std::vector<std::string> switches =
self.switches;
594 std::find(switches.begin(), switches.end(),
"--enable-impeller=true") != switches.end()) {
595 switches.push_back(
"--enable-impeller=true");
598 std::transform(switches.begin(), switches.end(), std::back_inserter(argv),
599 [](
const std::string& arg) ->
const char* { return arg.c_str(); });
601 std::vector<const char*> dartEntrypointArgs;
602 for (NSString* argument in [
_project dartEntrypointArguments]) {
603 dartEntrypointArgs.push_back([argument UTF8String]);
606 FlutterProjectArgs flutterArguments = {};
607 flutterArguments.struct_size =
sizeof(FlutterProjectArgs);
608 flutterArguments.assets_path =
_project.assetsPath.UTF8String;
609 flutterArguments.icu_data_path =
_project.ICUDataPath.UTF8String;
610 flutterArguments.command_line_argc =
static_cast<int>(argv.size());
611 flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data();
612 flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)
OnPlatformMessage;
613 flutterArguments.update_semantics_callback2 = [](
const FlutterSemanticsUpdate2* update,
619 [[engine viewControllerForId:kFlutterImplicitViewId] updateSemantics:update];
621 flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String;
622 flutterArguments.shutdown_dart_vm_when_done =
true;
623 flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size();
624 flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data();
625 flutterArguments.root_isolate_create_callback =
_project.rootIsolateCreateCallback;
626 flutterArguments.log_message_callback = [](
const char* tag,
const char* message,
629 std::cout << tag <<
": ";
631 std::cout << message << std::endl;
634 static size_t sTaskRunnerIdentifiers = 0;
635 const FlutterTaskRunnerDescription cocoa_task_runner_description = {
636 .struct_size =
sizeof(FlutterTaskRunnerDescription),
637 .
user_data = (
void*)CFBridgingRetain(
self),
638 .runs_task_on_current_thread_callback = [](
void*
user_data) ->
bool {
639 return [[NSThread currentThread] isMainThread];
641 .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
644 targetTimeInNanoseconds:target_time_nanos];
646 .identifier = ++sTaskRunnerIdentifiers,
648 const FlutterCustomTaskRunners custom_task_runners = {
649 .struct_size =
sizeof(FlutterCustomTaskRunners),
650 .platform_task_runner = &cocoa_task_runner_description,
651 .thread_priority_setter = SetThreadPriority};
652 flutterArguments.custom_task_runners = &custom_task_runners;
654 [
self loadAOTData:_project.assetsPath];
656 flutterArguments.aot_data =
_aotData;
659 flutterArguments.compositor = [
self createFlutterCompositor];
661 flutterArguments.on_pre_engine_restart_callback = [](
void*
user_data) {
663 [engine engineCallbackOnPreEngineRestart];
666 flutterArguments.vsync_callback = [](
void*
user_data, intptr_t baton) {
668 [engine onVSync:baton];
671 FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
672 FlutterEngineResult result = _embedderAPI.Initialize(
673 FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge
void*)(
self), &_engine);
674 if (result != kSuccess) {
675 NSLog(
@"Failed to initialize Flutter engine: error %d", result);
679 result = _embedderAPI.RunInitialized(_engine);
680 if (result != kSuccess) {
681 NSLog(
@"Failed to run an initialized engine: error %d", result);
685 [
self sendUserLocales];
688 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
690 while ((nextViewController = [viewControllerEnumerator nextObject])) {
691 [
self updateWindowMetricsForViewController:nextViewController];
694 [
self updateDisplayConfig];
697 [
self sendInitialSettings];
701 - (void)loadAOTData:(NSString*)assetsDir {
702 if (!_embedderAPI.RunsAOTCompiledDartCode()) {
706 BOOL isDirOut =
false;
707 NSFileManager* fileManager = [NSFileManager defaultManager];
711 NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
713 if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
717 FlutterEngineAOTDataSource source = {};
718 source.type = kFlutterEngineAOTDataSourceTypeElfPath;
719 source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
721 auto result = _embedderAPI.CreateAOTData(&source, &
_aotData);
722 if (result != kSuccess) {
723 NSLog(
@"Failed to load AOT data from: %@", elfPath);
728 NSAssert(controller != nil,
@"The controller must not be nil.");
729 NSAssert(![controller attached],
730 @"The incoming view controller is already attached to an engine.");
731 NSAssert([
_viewControllers objectForKey:@(viewId)] == nil,
@"The requested view ID is occupied.");
732 [controller setUpWithEngine:self viewId:viewId threadSynchronizer:_threadSynchronizer];
733 NSAssert(controller.viewId == viewId,
@"Failed to assign view ID.");
734 [_viewControllers setObject:controller forKey:@(viewId)];
736 if (controller.viewLoaded) {
737 [
self viewControllerViewDidLoad:controller];
746 block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
749 uint64_t targetTimeNanos =
751 FlutterEngine* engine = weakSelf;
757 [engine->_threadSynchronizer performOnPlatformThread:^{
758 engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
762 FML_DCHECK([
_vsyncWaiters objectForKey:@(viewController.viewId)] == nil);
764 [_vsyncWaiters setObject:waiter forKey:@(viewController.viewId)];
768 - (void)deregisterViewControllerForId:(
FlutterViewId)viewId {
770 if (oldController != nil) {
771 [oldController detachFromEngine];
772 [_viewControllers removeObjectForKey:@(viewId)];
775 [_vsyncWaiters removeObjectForKey:@(viewId)];
779 - (void)shutDownIfNeeded {
781 [
self shutDownEngine];
787 NSAssert(controller == nil || controller.viewId == viewId,
788 @"The stored controller has unexpected view ID.");
794 [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
795 if (currentController == controller) {
799 if (currentController == nil && controller != nil) {
801 NSAssert(controller.
engine == nil,
802 @"Failed to set view controller to the engine: "
803 @"The given FlutterViewController is already attached to an engine %@. "
804 @"If you wanted to create an FlutterViewController and set it to an existing engine, "
805 @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
807 [
self registerViewController:controller forId:kFlutterImplicitViewId];
808 }
else if (currentController != nil && controller == nil) {
810 @"The default controller has an unexpected ID %llu", currentController.viewId);
812 [
self deregisterViewControllerForId:kFlutterImplicitViewId];
813 [
self shutDownIfNeeded];
817 @"Failed to set view controller to the engine: "
818 @"The engine already has an implicit view controller %@. "
819 @"If you wanted to make the implicit view render in a different window, "
820 @"you should attach the current view controller to the window instead.",
826 return [
self viewControllerForId:kFlutterImplicitViewId];
829 - (FlutterCompositor*)createFlutterCompositor {
835 _compositor.struct_size =
sizeof(FlutterCompositor);
838 _compositor.create_backing_store_callback = [](
const FlutterBackingStoreConfig* config,
839 FlutterBackingStore* backing_store_out,
843 config, backing_store_out);
846 _compositor.collect_backing_store_callback = [](
const FlutterBackingStore* backing_store,
850 _compositor.present_layers_callback = [](
const FlutterLayer** layers,
858 layers, layers_count);
870 #pragma mark - Framework-internal methods
873 [
self registerViewController:controller forId:kFlutterImplicitViewId];
877 NSAssert([viewController attached] && viewController.
engine ==
self,
878 @"The given view controller is not associated with this engine.");
879 [
self deregisterViewControllerForId:viewController.viewId];
880 [
self shutDownIfNeeded];
884 return _engine !=
nullptr;
887 - (void)updateDisplayConfig:(NSNotification*)notification {
888 [
self updateDisplayConfig];
891 - (NSArray<NSScreen*>*)screens {
892 return [NSScreen screens];
895 - (void)updateDisplayConfig {
900 std::vector<FlutterEngineDisplay> displays;
901 for (NSScreen* screen : [
self screens]) {
902 CGDirectDisplayID displayID =
903 static_cast<CGDirectDisplayID
>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
905 double devicePixelRatio = screen.backingScaleFactor;
906 FlutterEngineDisplay display;
907 display.struct_size =
sizeof(display);
908 display.display_id = displayID;
909 display.single_display =
false;
910 display.width =
static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
911 display.height =
static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
912 display.device_pixel_ratio = devicePixelRatio;
914 CVDisplayLinkRef displayLinkRef = nil;
915 CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
918 CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
919 if (!(nominal.flags & kCVTimeIsIndefinite)) {
920 double refreshRate =
static_cast<double>(nominal.timeScale) / nominal.timeValue;
921 display.refresh_rate = round(refreshRate);
923 CVDisplayLinkRelease(displayLinkRef);
925 display.refresh_rate = 0;
928 displays.push_back(display);
930 _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
931 displays.data(), displays.size());
934 - (void)onSettingsChanged:(NSNotification*)notification {
936 NSString* brightness =
937 [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
938 [_settingsChannel sendMessage:@{
939 @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
941 @"textScaleFactor" : @1.0,
942 @"alwaysUse24HourFormat" : @false
946 - (void)sendInitialSettings {
948 [[NSDistributedNotificationCenter defaultCenter]
950 selector:@selector(onSettingsChanged:)
951 name:@"AppleInterfaceThemeChangedNotification"
953 [
self onSettingsChanged:nil];
956 - (FlutterEngineProcTable&)embedderAPI {
960 - (nonnull NSString*)executableName {
961 return [[[NSProcessInfo processInfo] arguments] firstObject] ?:
@"Flutter";
971 if (!_engine || !viewController || !viewController.viewLoaded) {
974 NSAssert([
self viewControllerForId:viewController.viewId] == viewController,
975 @"The provided view controller is not attached to this engine.");
976 NSView* view = viewController.flutterView;
977 CGRect scaledBounds = [view convertRectToBacking:view.bounds];
978 CGSize scaledSize = scaledBounds.size;
979 double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
980 auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
981 const FlutterWindowMetricsEvent windowMetricsEvent = {
982 .struct_size =
sizeof(windowMetricsEvent),
983 .width =
static_cast<size_t>(scaledSize.width),
984 .height =
static_cast<size_t>(scaledSize.height),
985 .pixel_ratio = pixelRatio,
986 .left =
static_cast<size_t>(scaledBounds.origin.x),
987 .top =
static_cast<size_t>(scaledBounds.origin.y),
988 .display_id =
static_cast<uint64_t
>(displayId),
990 _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
993 - (void)sendPointerEvent:(const FlutterPointerEvent&)event {
994 _embedderAPI.SendPointerEvent(_engine, &event, 1);
997 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
998 callback:(FlutterKeyEventCallback)callback
999 userData:(
void*)userData {
1000 _embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
1003 - (void)setSemanticsEnabled:(BOOL)enabled {
1004 if (_semanticsEnabled == enabled) {
1007 _semanticsEnabled = enabled;
1010 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1012 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1013 [nextViewController notifySemanticsEnabledChanged];
1016 _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
1019 - (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
1020 toTarget:(uint16_t)target
1021 withData:(fml::MallocMapping)data {
1022 _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
1029 #pragma mark - Private methods
1031 - (void)sendUserLocales {
1032 if (!
self.running) {
1037 NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
1038 std::vector<FlutterLocale> flutterLocales;
1039 flutterLocales.reserve(locales.count);
1040 for (NSString* localeID in [NSLocale preferredLanguages]) {
1041 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1042 [locales addObject:locale];
1046 std::vector<const FlutterLocale*> flutterLocaleList;
1047 flutterLocaleList.reserve(flutterLocales.size());
1048 std::transform(flutterLocales.begin(), flutterLocales.end(),
1049 std::back_inserter(flutterLocaleList),
1050 [](
const auto& arg) ->
const auto* { return &arg; });
1051 _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
1054 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
1055 NSData* messageData = nil;
1056 if (message->message_size > 0) {
1057 messageData = [NSData dataWithBytesNoCopy:(void*)message->message
1058 length:message->message_size
1061 NSString* channel = @(message->channel);
1062 __block
const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
1064 NSMutableArray* isResponseValid =
self.isResponseValid;
1065 FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
1066 _embedderAPI.SendPlatformMessageResponse;
1068 @
synchronized(isResponseValid) {
1069 if (![isResponseValid[0] boolValue]) {
1073 if (responseHandle) {
1074 sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
1075 static_cast<const uint8_t*
>(response.bytes), response.length);
1076 responseHandle = NULL;
1078 NSLog(
@"Error: Message responses can be sent only once. Ignoring duplicate response "
1087 handlerInfo.
handler(messageData, binaryResponseHandler);
1089 binaryResponseHandler(nil);
1093 - (void)engineCallbackOnPreEngineRestart {
1094 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1096 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1101 - (void)onVSync:(uintptr_t)baton {
1113 - (void)shutDownEngine {
1114 if (_engine ==
nullptr) {
1118 [_threadSynchronizer shutdown];
1121 FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
1122 if (result != kSuccess) {
1123 NSLog(
@"Could not de-initialize the Flutter engine: error %d", result);
1127 CFRelease((CFTypeRef)
self);
1129 result = _embedderAPI.Shutdown(_engine);
1130 if (result != kSuccess) {
1131 NSLog(
@"Failed to shut down Flutter engine: error %d", result);
1136 - (void)setUpPlatformViewChannel {
1143 [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1144 [[weakSelf platformViewController] handleMethodCall:call result:result];
1148 - (void)setUpAccessibilityChannel {
1154 [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1155 [weakSelf handleAccessibilityEvent:message];
1158 - (void)setUpNotificationCenterListeners {
1159 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1161 [center addObserver:self
1162 selector:@selector(onAccessibilityStatusChanged:)
1163 name:kEnhancedUserInterfaceNotification
1165 [center addObserver:self
1166 selector:@selector(applicationWillTerminate:)
1167 name:NSApplicationWillTerminateNotification
1169 [center addObserver:self
1170 selector:@selector(windowDidChangeScreen:)
1171 name:NSWindowDidChangeScreenNotification
1173 [center addObserver:self
1174 selector:@selector(updateDisplayConfig:)
1175 name:NSApplicationDidChangeScreenParametersNotification
1179 - (void)addInternalPlugins {
1191 [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1192 [weakSelf handleMethodCall:call result:result];
1196 - (void)applicationWillTerminate:(NSNotification*)notification {
1197 [
self shutDownEngine];
1200 - (void)windowDidChangeScreen:(NSNotification*)notification {
1203 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1205 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1206 [
self updateWindowMetricsForViewController:nextViewController];
1210 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1211 BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1212 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1214 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1218 self.semanticsEnabled = enabled;
1220 - (void)handleAccessibilityEvent:(NSDictionary<NSString*,
id>*)annotatedEvent {
1221 NSString* type = annotatedEvent[@"type"];
1222 if ([type isEqualToString:
@"announce"]) {
1223 NSString* message = annotatedEvent[@"data"][@"message"];
1224 NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1225 if (message == nil) {
1229 NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1230 ? NSAccessibilityPriorityHigh
1231 : NSAccessibilityPriorityMedium;
1233 [
self announceAccessibilityMessage:message withPriority:priority];
1237 - (void)announceAccessibilityMessage:(NSString*)message
1238 withPriority:(NSAccessibilityPriorityLevel)priority {
1239 NSAccessibilityPostNotificationWithUserInfo(
1241 NSAccessibilityAnnouncementRequestedNotification,
1242 @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
1245 if ([call.
method isEqualToString:
@"SystemNavigator.pop"]) {
1246 [[NSApplication sharedApplication] terminate:self];
1248 }
else if ([call.
method isEqualToString:
@"SystemSound.play"]) {
1249 [
self playSystemSound:call.arguments];
1251 }
else if ([call.
method isEqualToString:
@"Clipboard.getData"]) {
1252 result([
self getClipboardData:call.
arguments]);
1253 }
else if ([call.
method isEqualToString:
@"Clipboard.setData"]) {
1254 [
self setClipboardData:call.arguments];
1256 }
else if ([call.
method isEqualToString:
@"Clipboard.hasStrings"]) {
1257 result(@{
@"value" : @([
self clipboardHasStrings])});
1258 }
else if ([call.
method isEqualToString:
@"System.exitApplication"]) {
1259 if ([
self terminationHandler] == nil) {
1264 [NSApp terminate:self];
1267 [[
self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1269 }
else if ([call.
method isEqualToString:
@"System.initializationComplete"]) {
1270 if ([
self terminationHandler] != nil) {
1271 [
self terminationHandler].acceptingRequests = YES;
1279 - (void)playSystemSound:(NSString*)soundType {
1280 if ([soundType isEqualToString:
@"SystemSoundType.alert"]) {
1285 - (NSDictionary*)getClipboardData:(NSString*)format {
1287 NSString* stringInPasteboard = [
self.pasteboard stringForType:NSPasteboardTypeString];
1288 return stringInPasteboard == nil ? nil : @{
@"text" : stringInPasteboard};
1293 - (void)setClipboardData:(NSDictionary*)data {
1294 NSString* text = data[@"text"];
1295 [
self.pasteboard clearContents];
1296 if (text && ![text isEqual:[NSNull
null]]) {
1297 [
self.pasteboard setString:text forType:NSPasteboardTypeString];
1301 - (BOOL)clipboardHasStrings {
1302 return [
self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1305 - (std::vector<std::string>)switches {
1313 #pragma mark - FlutterAppLifecycleDelegate
1316 NSString* nextState =
1317 [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1318 [
self sendOnChannel:kFlutterLifecycleChannel
1319 message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1326 - (void)handleWillBecomeActive:(NSNotification*)notification {
1329 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1331 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1339 - (void)handleWillResignActive:(NSNotification*)notification {
1342 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1344 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1352 - (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1353 NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1354 if (occlusionState & NSApplicationOcclusionStateVisible) {
1357 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1359 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1363 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1367 #pragma mark - FlutterBinaryMessenger
1369 - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1370 [
self sendOnChannel:channel message:message binaryReply:nil];
1373 - (void)sendOnChannel:(NSString*)channel
1374 message:(NSData* _Nullable)message
1376 FlutterPlatformMessageResponseHandle* response_handle =
nullptr;
1381 auto captures = std::make_unique<Captures>();
1382 captures->reply = callback;
1383 auto message_reply = [](
const uint8_t* data,
size_t data_size,
void*
user_data) {
1384 auto captures =
reinterpret_cast<Captures*
>(
user_data);
1385 NSData* reply_data = nil;
1386 if (data !=
nullptr && data_size > 0) {
1387 reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1389 captures->reply(reply_data);
1393 FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
1394 _engine, message_reply, captures.get(), &response_handle);
1395 if (create_result != kSuccess) {
1396 NSLog(
@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1402 FlutterPlatformMessage platformMessage = {
1403 .struct_size =
sizeof(FlutterPlatformMessage),
1404 .channel = [channel UTF8String],
1405 .message =
static_cast<const uint8_t*
>(message.bytes),
1406 .message_size = message.length,
1407 .response_handle = response_handle,
1410 FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1411 if (message_result != kSuccess) {
1412 NSLog(
@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
1416 if (response_handle !=
nullptr) {
1417 FlutterEngineResult release_result =
1418 _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1419 if (release_result != kSuccess) {
1420 NSLog(
@"Failed to release the response handle (%d).", release_result);
1426 binaryMessageHandler:
1431 handler:[handler copy]];
1438 NSString* foundChannel = nil;
1441 if ([handlerInfo.
connection isEqual:@(connection)]) {
1447 [_messengerHandlers removeObjectForKey:foundChannel];
1451 #pragma mark - FlutterPluginRegistry
1454 id<FlutterPluginRegistrar> registrar =
self.pluginRegistrars[pluginName];
1458 self.pluginRegistrars[pluginName] = registrarImpl;
1459 registrar = registrarImpl;
1464 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1468 #pragma mark - FlutterTextureRegistrar
1471 return [_renderer registerTexture:texture];
1474 - (BOOL)registerTextureWithID:(int64_t)textureId {
1475 return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
1478 - (void)textureFrameAvailable:(int64_t)textureID {
1479 [_renderer textureFrameAvailable:textureID];
1482 - (BOOL)markTextureFrameAvailable:(int64_t)textureID {
1483 return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
1486 - (void)unregisterTexture:(int64_t)textureID {
1487 [_renderer unregisterTexture:textureID];
1490 - (BOOL)unregisterTextureWithID:(int64_t)textureID {
1491 return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
1494 #pragma mark - Task runner integration
1496 - (void)runTaskOnEmbedder:(FlutterTask)task {
1498 auto result = _embedderAPI.RunTask(_engine, &task);
1499 if (result != kSuccess) {
1500 NSLog(
@"Could not post a task to the Flutter engine.");
1505 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1508 [weakSelf runTaskOnEmbedder:task];
1511 const auto engine_time = _embedderAPI.GetCurrentTime();
1512 if (targetTime <= engine_time) {
1513 dispatch_async(dispatch_get_main_queue(), worker);
1516 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, targetTime - engine_time),
1517 dispatch_get_main_queue(), worker);
1522 - (
flutter::FlutterCompositor*)macOSCompositor {