14 #include "flutter/shell/platform/embedder/embedder.h"
39 FlutterLocale flutterLocale = {};
40 flutterLocale.struct_size =
sizeof(FlutterLocale);
41 flutterLocale.language_code = [[locale objectForKey:NSLocaleLanguageCode] UTF8String];
42 flutterLocale.country_code = [[locale objectForKey:NSLocaleCountryCode] UTF8String];
43 flutterLocale.script_code = [[locale objectForKey:NSLocaleScriptCode] UTF8String];
44 flutterLocale.variant_code = [[locale objectForKey:NSLocaleVariantCode] UTF8String];
50 @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification";
62 - (instancetype)initWithConnection:(NSNumber*)connection
71 - (instancetype)initWithConnection:(NSNumber*)connection
74 NSAssert(
self,
@"Super init cannot be nil");
93 @property(nonatomic, strong) NSMutableArray<NSNumber*>* isResponseValid;
98 @property(nonatomic, strong) NSPointerArray* pluginAppDelegates;
103 @property(nonatomic, readonly)
104 NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* pluginRegistrars;
129 - (void)shutDownIfNeeded;
134 - (void)sendUserLocales;
139 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message;
147 - (void)engineCallbackOnPreEngineRestart;
153 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime;
159 - (void)loadAOTData:(NSString*)assetsDir;
164 - (void)setUpPlatformViewChannel;
169 - (void)setUpAccessibilityChannel;
188 _acceptingRequests = NO;
190 _terminator = terminator ? terminator : ^(
id sender) {
193 [[NSApplication sharedApplication] terminate:sender];
195 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
196 if ([appDelegate respondsToSelector:
@selector(setTerminationHandler:)]) {
198 flutterAppDelegate.terminationHandler =
self;
205 - (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*,
id>*)arguments
207 NSString* type = arguments[@"type"];
213 FlutterAppExitType exitType =
214 [type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired;
223 - (void)requestApplicationTermination:(
id)sender
224 exitType:(FlutterAppExitType)type
226 _shouldTerminate = YES;
227 if (![
self acceptingRequests]) {
230 type = kFlutterAppExitTypeRequired;
233 case kFlutterAppExitTypeCancelable: {
237 [_engine sendOnChannel:kFlutterPlatformChannel
238 message:[codec encodeMethodCall:methodCall]
239 binaryReply:^(NSData* _Nullable reply) {
240 NSAssert(_terminator, @"terminator shouldn't be nil");
241 id decoded_reply = [codec decodeEnvelope:reply];
242 if ([decoded_reply isKindOfClass:[
FlutterError class]]) {
244 NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message],
249 if (![decoded_reply isKindOfClass:[NSDictionary class]]) {
250 NSLog(@"Call to System.requestAppExit returned an unexpected object: %@",
255 NSDictionary* replyArgs = (NSDictionary*)decoded_reply;
256 if ([replyArgs[@"response"] isEqual:@"exit"]) {
258 } else if ([replyArgs[@"response"] isEqual:@"cancel"]) {
259 _shouldTerminate = NO;
267 case kFlutterAppExitTypeRequired:
268 NSAssert(
_terminator,
@"terminator shouldn't be nil");
282 - (instancetype)initWithPlugin:(nonnull NSString*)pluginKey
296 NSString* _pluginKey;
302 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
305 _pluginKey = [pluginKey copy];
307 _publishedValue = [NSNull null];
312 #pragma mark - FlutterPluginRegistrar
323 return [
self viewForId:kFlutterImplicitViewId];
328 if (controller == nil) {
331 if (!controller.viewLoaded) {
332 [controller loadView];
334 return controller.flutterView;
337 - (void)addMethodCallDelegate:(nonnull
id<
FlutterPlugin>)delegate
345 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
347 id<FlutterAppLifecycleProvider> lifeCycleProvider =
348 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
349 [lifeCycleProvider addApplicationLifecycleDelegate:delegate];
350 [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
355 withId:(nonnull NSString*)factoryId {
356 [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
359 - (void)publish:(NSObject*)value {
360 _publishedValue = value;
363 - (NSString*)lookupKeyForAsset:(NSString*)asset {
367 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
374 #pragma mark - Static methods provided to engine configuration
377 [engine engineCallbackOnPlatformMessage:message];
446 - (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
447 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
450 - (instancetype)initWithName:(NSString*)labelPrefix
452 allowHeadlessExecution:(BOOL)allowHeadlessExecution {
454 NSAssert(
self,
@"Super init cannot be nil");
460 _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
461 _pluginRegistrars = [[NSMutableDictionary alloc] init];
464 _semanticsEnabled = NO;
466 _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
467 [_isResponseValid addObject:@YES];
471 _embedderAPI.struct_size =
sizeof(FlutterEngineProcTable);
472 FlutterEngineGetProcAddresses(&_embedderAPI);
477 NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
478 [notificationCenter addObserver:self
479 selector:@selector(sendUserLocales)
480 name:NSCurrentLocaleDidChangeNotification
485 [
self setUpPlatformViewChannel];
486 [
self setUpAccessibilityChannel];
487 [
self setUpNotificationCenterListeners];
488 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
492 id<FlutterAppLifecycleProvider> lifecycleProvider =
493 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
494 [lifecycleProvider addApplicationLifecycleDelegate:self];
496 _terminationHandler = nil;
503 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
505 id<FlutterAppLifecycleProvider> lifecycleProvider =
506 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
507 [lifecycleProvider removeApplicationLifecycleDelegate:self];
512 for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
514 [lifecycleProvider removeApplicationLifecycleDelegate:delegate];
520 for (NSString* pluginName in _pluginRegistrars) {
521 [_pluginRegistrars[pluginName] publish:[NSNull null]];
523 @
synchronized(_isResponseValid) {
524 [_isResponseValid removeAllObjects];
525 [_isResponseValid addObject:@NO];
527 [
self shutDownEngine];
529 _embedderAPI.CollectAOTData(
_aotData);
533 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
539 NSLog(
@"Attempted to run an engine with no view controller without headless mode enabled.");
543 [
self addInternalPlugins];
546 std::vector<const char*> argv = {[
self.executableName UTF8String]};
547 std::vector<std::string> switches =
self.switches;
551 std::find(switches.begin(), switches.end(),
"--enable-impeller=true") != switches.end()) {
552 switches.push_back(
"--enable-impeller=true");
555 std::transform(switches.begin(), switches.end(), std::back_inserter(argv),
556 [](
const std::string& arg) ->
const char* { return arg.c_str(); });
558 std::vector<const char*> dartEntrypointArgs;
559 for (NSString* argument in [
_project dartEntrypointArguments]) {
560 dartEntrypointArgs.push_back([argument UTF8String]);
563 FlutterProjectArgs flutterArguments = {};
564 flutterArguments.struct_size =
sizeof(FlutterProjectArgs);
565 flutterArguments.assets_path =
_project.assetsPath.UTF8String;
566 flutterArguments.icu_data_path =
_project.ICUDataPath.UTF8String;
567 flutterArguments.command_line_argc =
static_cast<int>(argv.size());
568 flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data();
569 flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)
OnPlatformMessage;
570 flutterArguments.update_semantics_callback2 = [](
const FlutterSemanticsUpdate2* update,
576 [[engine viewControllerForId:kFlutterImplicitViewId] updateSemantics:update];
578 flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String;
579 flutterArguments.shutdown_dart_vm_when_done =
true;
580 flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size();
581 flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data();
582 flutterArguments.root_isolate_create_callback =
_project.rootIsolateCreateCallback;
583 flutterArguments.log_message_callback = [](
const char* tag,
const char* message,
586 std::cout << tag <<
": ";
588 std::cout << message << std::endl;
591 static size_t sTaskRunnerIdentifiers = 0;
592 const FlutterTaskRunnerDescription cocoa_task_runner_description = {
593 .struct_size =
sizeof(FlutterTaskRunnerDescription),
594 .
user_data = (
void*)CFBridgingRetain(
self),
595 .runs_task_on_current_thread_callback = [](
void*
user_data) ->
bool {
596 return [[NSThread currentThread] isMainThread];
598 .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
601 targetTimeInNanoseconds:target_time_nanos];
603 .identifier = ++sTaskRunnerIdentifiers,
605 const FlutterCustomTaskRunners custom_task_runners = {
606 .struct_size =
sizeof(FlutterCustomTaskRunners),
607 .platform_task_runner = &cocoa_task_runner_description,
609 flutterArguments.custom_task_runners = &custom_task_runners;
611 [
self loadAOTData:_project.assetsPath];
613 flutterArguments.aot_data =
_aotData;
616 flutterArguments.compositor = [
self createFlutterCompositor];
618 flutterArguments.on_pre_engine_restart_callback = [](
void*
user_data) {
620 [engine engineCallbackOnPreEngineRestart];
623 FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
624 FlutterEngineResult result = _embedderAPI.Initialize(
625 FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge
void*)(
self), &_engine);
626 if (result != kSuccess) {
627 NSLog(
@"Failed to initialize Flutter engine: error %d", result);
631 result = _embedderAPI.RunInitialized(_engine);
632 if (result != kSuccess) {
633 NSLog(
@"Failed to run an initialized engine: error %d", result);
637 [
self sendUserLocales];
640 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
642 while ((nextViewController = [viewControllerEnumerator nextObject])) {
643 [
self updateWindowMetricsForViewController:nextViewController];
646 [
self updateDisplayConfig];
649 [
self sendInitialSettings];
653 - (void)loadAOTData:(NSString*)assetsDir {
654 if (!_embedderAPI.RunsAOTCompiledDartCode()) {
658 BOOL isDirOut =
false;
659 NSFileManager* fileManager = [NSFileManager defaultManager];
663 NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
665 if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
669 FlutterEngineAOTDataSource source = {};
670 source.type = kFlutterEngineAOTDataSourceTypeElfPath;
671 source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
673 auto result = _embedderAPI.CreateAOTData(&source, &
_aotData);
674 if (result != kSuccess) {
675 NSLog(
@"Failed to load AOT data from: %@", elfPath);
680 NSAssert(controller != nil,
@"The controller must not be nil.");
681 NSAssert(![controller attached],
682 @"The incoming view controller is already attached to an engine.");
683 NSAssert([
_viewControllers objectForKey:@(viewId)] == nil,
@"The requested view ID is occupied.");
684 [controller setUpWithEngine:self viewId:viewId threadSynchronizer:_threadSynchronizer];
685 NSAssert(controller.viewId == viewId,
@"Failed to assign view ID.");
686 [_viewControllers setObject:controller forKey:@(viewId)];
689 - (void)deregisterViewControllerForId:(
FlutterViewId)viewId {
691 if (oldController != nil) {
692 [oldController detachFromEngine];
693 [_viewControllers removeObjectForKey:@(viewId)];
697 - (void)shutDownIfNeeded {
699 [
self shutDownEngine];
705 NSAssert(controller == nil || controller.viewId == viewId,
706 @"The stored controller has unexpected view ID.");
712 [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
713 if (currentController == controller) {
717 if (currentController == nil && controller != nil) {
719 NSAssert(controller.
engine == nil,
720 @"Failed to set view controller to the engine: "
721 @"The given FlutterViewController is already attached to an engine %@. "
722 @"If you wanted to create an FlutterViewController and set it to an existing engine, "
723 @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
725 [
self registerViewController:controller forId:kFlutterImplicitViewId];
726 }
else if (currentController != nil && controller == nil) {
728 @"The default controller has an unexpected ID %llu", currentController.viewId);
730 [
self deregisterViewControllerForId:kFlutterImplicitViewId];
731 [
self shutDownIfNeeded];
735 @"Failed to set view controller to the engine: "
736 @"The engine already has an implicit view controller %@. "
737 @"If you wanted to make the implicit view render in a different window, "
738 @"you should attach the current view controller to the window instead.",
744 return [
self viewControllerForId:kFlutterImplicitViewId];
747 - (FlutterCompositor*)createFlutterCompositor {
752 _compositor.struct_size =
sizeof(FlutterCompositor);
755 _compositor.create_backing_store_callback = [](
const FlutterBackingStoreConfig* config,
756 FlutterBackingStore* backing_store_out,
760 config, backing_store_out);
763 _compositor.collect_backing_store_callback = [](
const FlutterBackingStore* backing_store,
767 _compositor.present_layers_callback = [](
const FlutterLayer** layers,
775 layers, layers_count);
787 #pragma mark - Framework-internal methods
790 [
self registerViewController:controller forId:kFlutterImplicitViewId];
794 NSAssert([viewController attached] && viewController.
engine ==
self,
795 @"The given view controller is not associated with this engine.");
796 [
self deregisterViewControllerForId:viewController.viewId];
797 [
self shutDownIfNeeded];
801 return _engine !=
nullptr;
804 - (void)updateDisplayConfig:(NSNotification*)notification {
805 [
self updateDisplayConfig];
808 - (void)updateDisplayConfig {
813 std::vector<FlutterEngineDisplay> displays;
814 for (NSScreen* screen : [NSScreen screens]) {
815 CGDirectDisplayID displayID =
816 static_cast<CGDirectDisplayID
>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
818 FlutterEngineDisplay display;
819 display.struct_size =
sizeof(display);
820 display.display_id = displayID;
821 display.single_display =
false;
822 display.width =
static_cast<size_t>(screen.frame.size.width);
823 display.height =
static_cast<size_t>(screen.frame.size.height);
824 display.device_pixel_ratio = screen.backingScaleFactor;
826 CVDisplayLinkRef displayLinkRef = nil;
827 CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
830 CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
831 if (!(nominal.flags & kCVTimeIsIndefinite)) {
832 double refreshRate =
static_cast<double>(nominal.timeScale) / nominal.timeValue;
833 display.refresh_rate = round(refreshRate);
835 CVDisplayLinkRelease(displayLinkRef);
837 display.refresh_rate = 0;
840 displays.push_back(display);
842 _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
843 displays.data(), displays.size());
846 - (void)onSettingsChanged:(NSNotification*)notification {
848 NSString* brightness =
849 [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
850 [_settingsChannel sendMessage:@{
851 @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
853 @"textScaleFactor" : @1.0,
854 @"alwaysUse24HourFormat" : @false
858 - (void)sendInitialSettings {
860 [[NSDistributedNotificationCenter defaultCenter]
862 selector:@selector(onSettingsChanged:)
863 name:@"AppleInterfaceThemeChangedNotification"
865 [
self onSettingsChanged:nil];
868 - (FlutterEngineProcTable&)embedderAPI {
872 - (nonnull NSString*)executableName {
873 return [[[NSProcessInfo processInfo] arguments] firstObject] ?:
@"Flutter";
883 if (!_engine || !viewController || !viewController.viewLoaded) {
886 NSAssert([
self viewControllerForId:viewController.viewId] == viewController,
887 @"The provided view controller is not attached to this engine.");
888 NSView* view = viewController.flutterView;
889 CGRect scaledBounds = [view convertRectToBacking:view.bounds];
890 CGSize scaledSize = scaledBounds.size;
891 double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
892 auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
893 const FlutterWindowMetricsEvent windowMetricsEvent = {
894 .struct_size =
sizeof(windowMetricsEvent),
895 .width =
static_cast<size_t>(scaledSize.width),
896 .height =
static_cast<size_t>(scaledSize.height),
897 .pixel_ratio = pixelRatio,
898 .left =
static_cast<size_t>(scaledBounds.origin.x),
899 .top =
static_cast<size_t>(scaledBounds.origin.y),
900 .display_id =
static_cast<uint64_t
>(displayId),
902 _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
905 - (void)sendPointerEvent:(const FlutterPointerEvent&)event {
906 _embedderAPI.SendPointerEvent(_engine, &event, 1);
909 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
910 callback:(FlutterKeyEventCallback)callback
911 userData:(
void*)userData {
912 _embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
915 - (void)setSemanticsEnabled:(BOOL)enabled {
916 if (_semanticsEnabled == enabled) {
919 _semanticsEnabled = enabled;
922 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
924 while ((nextViewController = [viewControllerEnumerator nextObject])) {
925 [nextViewController notifySemanticsEnabledChanged];
928 _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
931 - (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
932 toTarget:(uint16_t)target
933 withData:(fml::MallocMapping)data {
934 _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
941 #pragma mark - Private methods
943 - (void)sendUserLocales {
949 NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
950 std::vector<FlutterLocale> flutterLocales;
951 flutterLocales.reserve(locales.count);
952 for (NSString* localeID in [NSLocale preferredLanguages]) {
953 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
954 [locales addObject:locale];
958 std::vector<const FlutterLocale*> flutterLocaleList;
959 flutterLocaleList.reserve(flutterLocales.size());
960 std::transform(flutterLocales.begin(), flutterLocales.end(),
961 std::back_inserter(flutterLocaleList),
962 [](
const auto& arg) ->
const auto* { return &arg; });
963 _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
966 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
967 NSData* messageData = nil;
968 if (message->message_size > 0) {
969 messageData = [NSData dataWithBytesNoCopy:(void*)message->message
970 length:message->message_size
973 NSString* channel = @(message->channel);
974 __block
const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
976 NSMutableArray* isResponseValid =
self.isResponseValid;
977 FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
978 _embedderAPI.SendPlatformMessageResponse;
980 @
synchronized(isResponseValid) {
981 if (![isResponseValid[0] boolValue]) {
985 if (responseHandle) {
986 sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
987 static_cast<const uint8_t*
>(response.bytes), response.length);
988 responseHandle = NULL;
990 NSLog(
@"Error: Message responses can be sent only once. Ignoring duplicate response "
999 handlerInfo.
handler(messageData, binaryResponseHandler);
1001 binaryResponseHandler(nil);
1005 - (void)engineCallbackOnPreEngineRestart {
1006 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1008 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1016 - (void)shutDownEngine {
1017 if (_engine ==
nullptr) {
1021 [_threadSynchronizer shutdown];
1024 FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
1025 if (result != kSuccess) {
1026 NSLog(
@"Could not de-initialize the Flutter engine: error %d", result);
1030 CFRelease((CFTypeRef)
self);
1032 result = _embedderAPI.Shutdown(_engine);
1033 if (result != kSuccess) {
1034 NSLog(
@"Failed to shut down Flutter engine: error %d", result);
1039 - (void)setUpPlatformViewChannel {
1046 [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1047 [[weakSelf platformViewController] handleMethodCall:call result:result];
1051 - (void)setUpAccessibilityChannel {
1057 [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1058 [weakSelf handleAccessibilityEvent:message];
1061 - (void)setUpNotificationCenterListeners {
1062 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1064 [center addObserver:self
1065 selector:@selector(onAccessibilityStatusChanged:)
1066 name:kEnhancedUserInterfaceNotification
1068 [center addObserver:self
1069 selector:@selector(applicationWillTerminate:)
1070 name:NSApplicationWillTerminateNotification
1072 [center addObserver:self
1073 selector:@selector(windowDidChangeScreen:)
1074 name:NSWindowDidChangeScreenNotification
1076 [center addObserver:self
1077 selector:@selector(updateDisplayConfig:)
1078 name:NSApplicationDidChangeScreenParametersNotification
1082 - (void)addInternalPlugins {
1094 [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1095 [weakSelf handleMethodCall:call result:result];
1099 - (void)applicationWillTerminate:(NSNotification*)notification {
1100 [
self shutDownEngine];
1103 - (void)windowDidChangeScreen:(NSNotification*)notification {
1106 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1108 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1109 [
self updateWindowMetricsForViewController:nextViewController];
1113 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1114 BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1115 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1117 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1121 self.semanticsEnabled = enabled;
1123 - (void)handleAccessibilityEvent:(NSDictionary<NSString*,
id>*)annotatedEvent {
1124 NSString* type = annotatedEvent[@"type"];
1125 if ([type isEqualToString:
@"announce"]) {
1126 NSString* message = annotatedEvent[@"data"][@"message"];
1127 NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1128 if (message == nil) {
1132 NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1133 ? NSAccessibilityPriorityHigh
1134 : NSAccessibilityPriorityMedium;
1136 [
self announceAccessibilityMessage:message withPriority:priority];
1140 - (void)announceAccessibilityMessage:(NSString*)message
1141 withPriority:(NSAccessibilityPriorityLevel)priority {
1142 NSAccessibilityPostNotificationWithUserInfo(
1144 NSAccessibilityAnnouncementRequestedNotification,
1145 @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
1148 if ([call.
method isEqualToString:
@"SystemNavigator.pop"]) {
1149 [[NSApplication sharedApplication] terminate:self];
1151 }
else if ([call.
method isEqualToString:
@"SystemSound.play"]) {
1152 [
self playSystemSound:call.arguments];
1154 }
else if ([call.
method isEqualToString:
@"Clipboard.getData"]) {
1155 result([
self getClipboardData:call.
arguments]);
1156 }
else if ([call.
method isEqualToString:
@"Clipboard.setData"]) {
1157 [
self setClipboardData:call.arguments];
1159 }
else if ([call.
method isEqualToString:
@"Clipboard.hasStrings"]) {
1160 result(@{
@"value" : @([
self clipboardHasStrings])});
1161 }
else if ([call.
method isEqualToString:
@"System.exitApplication"]) {
1162 if ([
self terminationHandler] == nil) {
1167 [NSApp terminate:self];
1170 [[
self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1172 }
else if ([call.
method isEqualToString:
@"System.initializationComplete"]) {
1173 if ([
self terminationHandler] != nil) {
1174 [
self terminationHandler].acceptingRequests = YES;
1182 - (void)playSystemSound:(NSString*)soundType {
1183 if ([soundType isEqualToString:
@"SystemSoundType.alert"]) {
1188 - (NSDictionary*)getClipboardData:(NSString*)format {
1189 NSPasteboard* pasteboard =
self.pasteboard;
1191 NSString* stringInPasteboard = [pasteboard stringForType:NSPasteboardTypeString];
1192 return stringInPasteboard == nil ? nil : @{
@"text" : stringInPasteboard};
1197 - (void)setClipboardData:(NSDictionary*)data {
1198 NSPasteboard* pasteboard =
self.pasteboard;
1199 NSString* text = data[@"text"];
1200 [pasteboard clearContents];
1201 if (text && ![text isEqual:[NSNull
null]]) {
1202 [pasteboard setString:text forType:NSPasteboardTypeString];
1206 - (BOOL)clipboardHasStrings {
1207 return [
self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1210 - (NSPasteboard*)pasteboard {
1211 return [NSPasteboard generalPasteboard];
1214 - (std::vector<std::string>)switches {
1222 #pragma mark - FlutterAppLifecycleDelegate
1225 NSString* nextState =
1226 [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1227 [
self sendOnChannel:kFlutterLifecycleChannel
1228 message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1235 - (void)handleWillBecomeActive:(NSNotification*)notification {
1238 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1240 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1248 - (void)handleWillResignActive:(NSNotification*)notification {
1251 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1253 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1261 - (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1262 NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1263 if (occlusionState & NSApplicationOcclusionStateVisible) {
1266 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1268 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1272 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1276 #pragma mark - FlutterBinaryMessenger
1278 - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1279 [
self sendOnChannel:channel message:message binaryReply:nil];
1282 - (void)sendOnChannel:(NSString*)channel
1283 message:(NSData* _Nullable)message
1285 FlutterPlatformMessageResponseHandle* response_handle =
nullptr;
1290 auto captures = std::make_unique<Captures>();
1291 captures->reply = callback;
1292 auto message_reply = [](
const uint8_t* data,
size_t data_size,
void*
user_data) {
1293 auto captures =
reinterpret_cast<Captures*
>(
user_data);
1294 NSData* reply_data = nil;
1295 if (data !=
nullptr && data_size > 0) {
1296 reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1298 captures->reply(reply_data);
1302 FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
1303 _engine, message_reply, captures.get(), &response_handle);
1304 if (create_result != kSuccess) {
1305 NSLog(
@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1311 FlutterPlatformMessage platformMessage = {
1312 .struct_size =
sizeof(FlutterPlatformMessage),
1313 .channel = [channel UTF8String],
1314 .message =
static_cast<const uint8_t*
>(message.bytes),
1315 .message_size = message.length,
1316 .response_handle = response_handle,
1319 FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1320 if (message_result != kSuccess) {
1321 NSLog(
@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
1325 if (response_handle !=
nullptr) {
1326 FlutterEngineResult release_result =
1327 _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1328 if (release_result != kSuccess) {
1329 NSLog(
@"Failed to release the response handle (%d).", release_result);
1335 binaryMessageHandler:
1340 handler:[handler copy]];
1347 NSString* foundChannel = nil;
1350 if ([handlerInfo.
connection isEqual:@(connection)]) {
1356 [_messengerHandlers removeObjectForKey:foundChannel];
1360 #pragma mark - FlutterPluginRegistry
1363 id<FlutterPluginRegistrar> registrar =
self.pluginRegistrars[pluginName];
1367 self.pluginRegistrars[pluginName] = registrarImpl;
1368 registrar = registrarImpl;
1373 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1377 #pragma mark - FlutterTextureRegistrar
1380 return [_renderer registerTexture:texture];
1383 - (BOOL)registerTextureWithID:(int64_t)textureId {
1384 return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
1387 - (void)textureFrameAvailable:(int64_t)textureID {
1388 [_renderer textureFrameAvailable:textureID];
1391 - (BOOL)markTextureFrameAvailable:(int64_t)textureID {
1392 return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
1395 - (void)unregisterTexture:(int64_t)textureID {
1396 [_renderer unregisterTexture:textureID];
1399 - (BOOL)unregisterTextureWithID:(int64_t)textureID {
1400 return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
1403 #pragma mark - Task runner integration
1405 - (void)runTaskOnEmbedder:(FlutterTask)task {
1407 auto result = _embedderAPI.RunTask(_engine, &task);
1408 if (result != kSuccess) {
1409 NSLog(
@"Could not post a task to the Flutter engine.");
1414 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1417 [weakSelf runTaskOnEmbedder:task];
1420 const auto engine_time = _embedderAPI.GetCurrentTime();
1421 if (targetTime <= engine_time) {
1422 dispatch_async(dispatch_get_main_queue(), worker);
1425 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, targetTime - engine_time),
1426 dispatch_get_main_queue(), worker);
1431 - (
flutter::FlutterCompositor*)macOSCompositor {