19#import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
21#import "flutter/shell/platform/darwin/macos/InternalFlutterSwift/InternalFlutterSwift.h"
37#import <CoreVideo/CoreVideo.h>
38#import <IOSurface/IOSurface.h>
55 flutterLocale.
language_code = [[locale objectForKey:NSLocaleLanguageCode] UTF8String];
56 flutterLocale.
country_code = [[locale objectForKey:NSLocaleCountryCode] UTF8String];
57 flutterLocale.
script_code = [[locale objectForKey:NSLocaleScriptCode] UTF8String];
58 flutterLocale.
variant_code = [[locale objectForKey:NSLocaleVariantCode] UTF8String];
64 @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification";
76- (instancetype)initWithConnection:(NSNumber*)connection
85- (instancetype)initWithConnection:(NSNumber*)connection
88 NSAssert(
self,
@"Super init cannot be nil");
101 FlutterMouseCursorPluginDelegate,
102 FlutterKeyboardManagerDelegate,
103 FlutterTextInputPluginDelegate>
110@property(nonatomic, strong) NSMutableArray<NSNumber*>* isResponseValid;
115@property(nonatomic, strong) NSPointerArray* pluginAppDelegates;
120@property(nonatomic, readonly)
121 NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* pluginRegistrars;
148- (void)shutDownIfNeeded;
153- (void)sendUserLocales;
164- (void)postMainThreadTask:(
FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime;
170- (void)loadAOTData:(NSString*)assetsDir;
175- (void)setUpPlatformViewChannel;
180- (void)setUpAccessibilityChannel;
199 _acceptingRequests = NO;
201 _terminator = terminator ? terminator : ^(
id sender) {
204 [[NSApplication sharedApplication] terminate:sender];
206 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
207 if ([appDelegate respondsToSelector:@selector(setTerminationHandler:)]) {
209 flutterAppDelegate.terminationHandler =
self;
216- (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*,
id>*)arguments
218 NSString*
type = arguments[@"type"];
224 FlutterAppExitType exitType =
225 [type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired;
227 [
self requestApplicationTermination:[NSApplication sharedApplication]
234- (void)requestApplicationTermination:(
id)sender
235 exitType:(FlutterAppExitType)type
237 _shouldTerminate = YES;
238 if (![
self acceptingRequests]) {
241 type = kFlutterAppExitTypeRequired;
244 case kFlutterAppExitTypeCancelable: {
248 [_engine sendOnChannel:kFlutterPlatformChannel
249 message:[codec encodeMethodCall:methodCall]
250 binaryReply:^(NSData* _Nullable reply) {
251 NSAssert(_terminator, @"terminator shouldn't be nil");
252 id decoded_reply = [codec decodeEnvelope:reply];
253 if ([decoded_reply isKindOfClass:[
FlutterError class]]) {
255 NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message],
260 if (![decoded_reply isKindOfClass:[NSDictionary class]]) {
261 NSLog(@"Call to System.requestAppExit returned an unexpected object: %@",
266 NSDictionary* replyArgs = (NSDictionary*)decoded_reply;
267 if ([replyArgs[@"response"] isEqual:@"exit"]) {
269 } else if ([replyArgs[@"response"] isEqual:@"cancel"]) {
270 _shouldTerminate = NO;
278 case kFlutterAppExitTypeRequired:
279 NSAssert(
_terminator,
@"terminator shouldn't be nil");
292 return [[NSPasteboard generalPasteboard] clearContents];
295- (NSString*)stringForType:(NSPasteboardType)dataType {
296 return [[NSPasteboard generalPasteboard] stringForType:dataType];
299- (
BOOL)setString:(nonnull NSString*)string forType:(nonnull NSPasteboardType)dataType {
300 return [[NSPasteboard generalPasteboard] setString:string forType:dataType];
311- (instancetype)initWithPlugin:(nonnull NSString*)pluginKey
325 NSString* _pluginKey;
331- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(
FlutterEngine*)flutterEngine {
334 _pluginKey = [pluginKey copy];
336 _publishedValue = [NSNull null];
341#pragma mark - FlutterPluginRegistrar
343- (
id<FlutterBinaryMessenger>)messenger {
347- (
id<FlutterTextureRegistry>)textures {
352 return [
self viewForIdentifier:kFlutterImplicitViewId];
357 if (controller == nil) {
360 if (!controller.viewLoaded) {
361 [controller loadView];
363 return controller.flutterView;
367 return [_flutterEngine viewControllerForIdentifier:kFlutterImplicitViewId];
370- (void)addMethodCallDelegate:(nonnull
id<FlutterPlugin>)delegate
373 [delegate handleMethodCall:call result:result];
377- (void)addApplicationDelegate:(NSObject<FlutterAppLifecycleDelegate>*)delegate {
378 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
379 if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
380 id<FlutterAppLifecycleProvider> lifeCycleProvider =
381 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
382 [lifeCycleProvider addApplicationLifecycleDelegate:delegate];
383 [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
388 withId:(nonnull NSString*)factoryId {
389 [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
392- (void)publish:(NSObject*)value {
393 _publishedValue =
value;
396- (NSString*)lookupKeyForAsset:(NSString*)asset {
400- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
407#pragma mark - Static methods provided to engine configuration
411 [engine engineCallbackOnPlatformMessage:message];
507- (instancetype)initWithName:(NSString*)labelPrefix project:(
FlutterDartProject*)project {
508 return [
self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
515 pthread_t thread = pthread_self();
518 if (!pthread_getschedparam(thread, &policy, ¶m)) {
520 pthread_setschedparam(thread, policy, ¶m);
522 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
526- (instancetype)initWithName:(NSString*)labelPrefix
528 allowHeadlessExecution:(
BOOL)allowHeadlessExecution {
530 NSAssert(
self,
@"Super init cannot be nil");
532 [FlutterRunLoop ensureMainLoopInitialized];
539 _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
540 _pluginRegistrars = [[NSMutableDictionary alloc] init];
543 _semanticsEnabled = NO;
545 _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
546 [_isResponseValid addObject:@YES];
558 NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
559 [notificationCenter addObserver:self
560 selector:@selector(sendUserLocales)
561 name:NSCurrentLocaleDidChangeNotification
571 [
self setUpPlatformViewChannel];
576 [
self setUpAccessibilityChannel];
577 [
self setUpNotificationCenterListeners];
578 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
579 if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
582 id<FlutterAppLifecycleProvider> lifecycleProvider =
583 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
584 [lifecycleProvider addApplicationLifecycleDelegate:self];
586 _terminationHandler = nil;
595 id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
596 if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
597 id<FlutterAppLifecycleProvider> lifecycleProvider =
598 static_cast<id<FlutterAppLifecycleProvider>
>(appDelegate);
599 [lifecycleProvider removeApplicationLifecycleDelegate:self];
604 for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
606 [lifecycleProvider removeApplicationLifecycleDelegate:delegate];
612 for (NSString* pluginName in _pluginRegistrars) {
613 [_pluginRegistrars[pluginName] publish:[NSNull null]];
615 @
synchronized(_isResponseValid) {
616 [_isResponseValid removeAllObjects];
617 [_isResponseValid addObject:@NO];
619 [
self shutDownEngine];
621 _embedderAPI.CollectAOTData(
_aotData);
626 static size_t sTaskRunnerIdentifiers = 0;
631 .runs_task_on_current_thread_callback = [](
void*
user_data) ->
bool {
632 return [[NSThread currentThread] isMainThread];
634 .post_task_callback = [](
FlutterTask task, uint64_t target_time_nanos,
637 [engine postMainThreadTask:task targetTimeInNanoseconds:target_time_nanos];
639 .identifier = ++sTaskRunnerIdentifiers,
640 .destruction_callback =
647 return cocoa_task_runner_description;
652 if (controller == nil) {
656 [controller.flutterView.window makeFirstResponder:controller.flutterView];
660- (
BOOL)runWithEntrypoint:(NSString*)entrypoint {
666 NSLog(
@"Attempted to run an engine with no view controller without headless mode enabled.");
670 [
self addInternalPlugins];
673 std::vector<const char*>
argv = {[
self.executableName UTF8String]};
674 std::vector<std::string> switches =
self.switches;
677 if (std::find(switches.begin(), switches.end(),
"--enable-impeller=false") != switches.end()) {
680 "--enable-impeller=true") != switches.end()) {
681 switches.push_back(
"--enable-impeller=true");
684 if (std::find(switches.begin(), switches.end(),
"--enable-impeller=true") == switches.end()) {
685 FML_LOG(IMPORTANT) <<
"Using the Skia rendering backend (Metal).";
689 std::find(switches.begin(), switches.end(),
"--impeller-use-sdfs=true") != switches.end()) {
690 switches.push_back(
"--impeller-use-sdfs=true");
694 std::find(switches.begin(), switches.end(),
"--enable-flutter-gpu=true") != switches.end()) {
695 switches.push_back(
"--enable-flutter-gpu=true");
698 std::transform(switches.begin(), switches.end(), std::back_inserter(
argv),
699 [](
const std::string& arg) ->
const char* { return arg.c_str(); });
701 std::vector<const char*> dartEntrypointArgs;
702 for (NSString* argument in [
_project dartEntrypointArguments]) {
703 dartEntrypointArgs.push_back([argument UTF8String]);
719 [[engine viewControllerForIdentifier:kFlutterImplicitViewId] updateSemantics:update];
728 std::stringstream stream;
730 stream << tag <<
": ";
733 std::string log = stream.str();
734 [FlutterLogger logDirect:[NSString stringWithUTF8String:log.c_str()]];
737 flutterArguments.
engine_id =
reinterpret_cast<int64_t
>((__bridge
void*)
self);
739 if (std::find(switches.begin(), switches.end(),
"--enable-impeller=false") != switches.end()) {
740 enableWideGamut = NO;
744 BOOL mergedPlatformUIThread = YES;
745 NSNumber* enableMergedPlatformUIThread =
746 [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableMergedPlatformUIThread"];
747 if (enableMergedPlatformUIThread != nil) {
748 mergedPlatformUIThread = enableMergedPlatformUIThread.boolValue;
751 if (!mergedPlatformUIThread) {
752 NSLog(
@"Warning: Merged threads is disabled. Running Flutter without merged threads is "
753 "deprecated and will be unsupported in a future release.\n"
755 "To turn on merged threads, update your macos/Runner/Info.plist file:\n"
757 " <key>FLTEnableMergedPlatformUIThread</key>\n"
760 "If you disabled merged threads to work around an issue, please report it here: "
761 "https://github.com/flutter/flutter/issues/150525.");
768 [
self createPlatformThreadTaskDescription];
769 std::optional<FlutterTaskRunnerDescription> uiTaskRunnerDescription;
770 if (mergedPlatformUIThread) {
771 uiTaskRunnerDescription = [
self createPlatformThreadTaskDescription];
776 .platform_task_runner = &platformTaskRunnerDescription,
777 .thread_priority_setter = SetThreadPriority,
778 .ui_task_runner = uiTaskRunnerDescription ? &uiTaskRunnerDescription.value() :
nullptr,
782 [
self loadAOTData:_project.assetsPath];
787 flutterArguments.
compositor = [
self createFlutterCompositor];
791 [engine engineCallbackOnPreEngineRestart];
796 [engine onVSync:baton];
802 [engine onFocusChangeRequest:request];
809 NSLog(
@"Failed to initialize Flutter engine: error %d", result);
813 result = _embedderAPI.RunInitialized(_engine);
815 NSLog(
@"Failed to run an initialized engine: error %d", result);
819 [
self sendUserLocales];
822 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
824 while ((nextViewController = [viewControllerEnumerator nextObject])) {
825 [
self updateWindowMetricsForViewController:nextViewController];
828 [
self updateDisplayConfig];
831 [
self sendInitialSettings];
835- (void)loadAOTData:(NSString*)assetsDir {
836 if (!_embedderAPI.RunsAOTCompiledDartCode()) {
840 BOOL isDirOut =
false;
841 NSFileManager* fileManager = [NSFileManager defaultManager];
845 NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
847 if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
853 source.
elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
855 auto result = _embedderAPI.CreateAOTData(&source, &
_aotData);
857 NSLog(
@"Failed to load AOT data from: %@", elfPath);
864 NSAssert(controller != nil,
@"The controller must not be nil.");
866 NSAssert(controller.
engine == nil,
867 @"The FlutterViewController is unexpectedly attached to "
868 @"engine %@ before initialization.",
872 @"The requested view ID is occupied.");
873 [_viewControllers setObject:controller forKey:@(viewIdentifier)];
874 [controller setUpWithEngine:self viewIdentifier:viewIdentifier];
875 NSAssert(controller.
viewIdentifier == viewIdentifier,
@"Failed to assign view ID.");
879 NSAssert(controller.
attached,
@"The FlutterViewController should switch to the attached mode "
880 @"after it is added to a FlutterEngine.");
882 @"The FlutterViewController was added to %@, but its engine unexpectedly became %@.",
885 if (controller.viewLoaded) {
886 [
self viewControllerViewDidLoad:controller];
889 if (viewIdentifier != kFlutterImplicitViewId) {
901 .view_metrics = &metrics,
904 auto added =
reinterpret_cast<bool*
>(r->
user_data);
908 _embedderAPI.AddView(_engine, &info);
911 NSLog(
@"Failed to add view with ID %llu", viewIdentifier);
921 block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
924 uint64_t targetTimeNanos =
926 FlutterEngine* engine = weakSelf;
928 engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
933 [_vsyncWaiters setObject:waiter forKey:@(viewController.viewIdentifier)];
938 if (viewIdentifier != kFlutterImplicitViewId) {
939 bool removed =
false;
948 auto removed =
reinterpret_cast<bool*
>(r->user_data);
949 [FlutterRunLoop.mainRunLoop performBlock:^{
953 _embedderAPI.RemoveView(_engine, &info);
955 [[FlutterRunLoop mainRunLoop] pollFlutterMessagesOnce];
964 if (controller != nil) {
965 [controller detachFromEngine];
967 @"The FlutterViewController unexpectedly stays attached after being removed. "
968 @"In unit tests, this is likely because either the FlutterViewController or "
969 @"the FlutterEngine is mocked. Please subclass these classes instead.");
971 [_viewControllers removeObjectForKey:@(viewIdentifier)];
975 waiter = [_vsyncWaiters objectForKey:@(viewIdentifier)];
976 [_vsyncWaiters removeObjectForKey:@(viewIdentifier)];
981- (void)shutDownIfNeeded {
983 [
self shutDownEngine];
989 NSAssert(controller == nil || controller.
viewIdentifier == viewIdentifier,
990 @"The stored controller has unexpected view ID.");
996 [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
997 if (currentController == controller) {
1001 if (currentController == nil && controller != nil) {
1003 NSAssert(controller.
engine == nil,
1004 @"Failed to set view controller to the engine: "
1005 @"The given FlutterViewController is already attached to an engine %@. "
1006 @"If you wanted to create an FlutterViewController and set it to an existing engine, "
1007 @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
1009 [
self registerViewController:controller forIdentifier:kFlutterImplicitViewId];
1010 }
else if (currentController != nil && controller == nil) {
1011 NSAssert(currentController.
viewIdentifier == kFlutterImplicitViewId,
1012 @"The default controller has an unexpected ID %llu", currentController.
viewIdentifier);
1014 [
self deregisterViewControllerForIdentifier:kFlutterImplicitViewId];
1015 [
self shutDownIfNeeded];
1019 @"Failed to set view controller to the engine: "
1020 @"The engine already has an implicit view controller %@. "
1021 @"If you wanted to make the implicit view render in a different window, "
1022 @"you should attach the current view controller to the window instead.",
1028 return [
self viewControllerForIdentifier:kFlutterImplicitViewId];
1041 config, backing_store_out);
1050 ->Present(info->
view_id, info->layers, info->layers_count);
1058- (
id<FlutterBinaryMessenger>)binaryMessenger {
1062#pragma mark - Framework-internal methods
1068 NSAssert(
self.viewController == nil,
1069 @"The engine already has a view controller for the implicit view.");
1070 self.viewController = controller;
1075 [
self registerViewController:controller forIdentifier:viewIdentifier];
1079- (void)enableMultiView {
1081 NSAssert(
self.viewController == nil,
1082 @"Multiview can only be enabled before adding any view controllers.");
1094 _embedderAPI.SendViewFocusEvent(_engine, &event);
1104 _embedderAPI.SendViewFocusEvent(_engine, &event);
1108 [
self deregisterViewControllerForIdentifier:viewController.viewIdentifier];
1109 [
self shutDownIfNeeded];
1113 return _engine !=
nullptr;
1116- (void)updateDisplayConfig:(NSNotification*)notification {
1117 [
self updateDisplayConfig];
1120- (NSArray<NSScreen*>*)screens {
1121 return [NSScreen screens];
1124- (void)updateDisplayConfig {
1129 std::vector<FlutterEngineDisplay>
displays;
1130 for (NSScreen* screen : [
self screens]) {
1131 CGDirectDisplayID displayID =
1132 static_cast<CGDirectDisplayID
>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
1134 double devicePixelRatio = screen.backingScaleFactor;
1139 display.
width =
static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
1140 display.
height =
static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
1143 CVDisplayLinkRef displayLinkRef = nil;
1144 CVReturn
error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
1147 CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
1148 if (!(nominal.flags & kCVTimeIsIndefinite)) {
1149 double refreshRate =
static_cast<double>(nominal.timeScale) / nominal.timeValue;
1152 CVDisplayLinkRelease(displayLinkRef);
1163- (void)onSettingsChanged:(NSNotification*)notification {
1165 NSString* brightness =
1166 [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
1167 [_settingsChannel sendMessage:@{
1168 @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
1170 @"textScaleFactor" : @1.0,
1175- (void)sendInitialSettings {
1177 [[NSDistributedNotificationCenter defaultCenter]
1179 selector:@selector(onSettingsChanged:)
1180 name:@"AppleInterfaceThemeChangedNotification"
1182 [
self onSettingsChanged:nil];
1186 return _embedderAPI;
1189- (nonnull NSString*)executableName {
1190 return [[[NSProcessInfo processInfo] arguments] firstObject] ?:
@"Flutter";
1198 @"The provided view controller is not attached to this engine.");
1200 CGRect scaledBounds = [view convertRectToBacking:view.bounds];
1201 CGSize scaledSize = scaledBounds.size;
1202 double pixelRatio =
view.layer.contentsScale;
1203 auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
1206 .
width =
static_cast<size_t>(scaledSize.width),
1207 .height =
static_cast<size_t>(scaledSize.height),
1208 .pixel_ratio = pixelRatio,
1209 .left =
static_cast<size_t>(scaledBounds.origin.x),
1210 .top =
static_cast<size_t>(scaledBounds.origin.y),
1211 .display_id =
static_cast<uint64_t
>(displayId),
1214 if (
view.sizedToContents) {
1215 CGSize maximumContentSize = [view convertSizeToBacking:view.maximumContentSize];
1216 CGSize minimumContentSize = [view convertSizeToBacking:view.minimumContentSize];
1228 _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
1232 _embedderAPI.SendPointerEvent(_engine, &event, 1);
1236- (void)setSemanticsEnabled:(
BOOL)enabled {
1237 if (_semanticsEnabled == enabled) {
1240 _semanticsEnabled = enabled;
1243 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1245 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1246 [nextViewController notifySemanticsEnabledChanged];
1249 _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
1253 toTarget:(uint16_t)target
1254 withData:(
fml::MallocMapping)data {
1255 _embedderAPI.DispatchSemanticsAction(_engine,
target,
action,
data.GetMapping(),
data.GetSize());
1262#pragma mark - Private methods
1264- (void)sendUserLocales {
1265 if (!
self.running) {
1270 NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
1271 std::vector<FlutterLocale> flutterLocales;
1272 flutterLocales.reserve(locales.count);
1273 for (NSString* localeID in [NSLocale preferredLanguages]) {
1274 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1275 [locales addObject:locale];
1279 std::vector<const FlutterLocale*> flutterLocaleList;
1280 flutterLocaleList.reserve(flutterLocales.size());
1281 std::transform(flutterLocales.begin(), flutterLocales.end(),
1282 std::back_inserter(flutterLocaleList),
1283 [](
const auto& arg) ->
const auto* { return &arg; });
1284 _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
1288 NSData* messageData = nil;
1289 if (
message->message_size > 0) {
1290 messageData = [NSData dataWithBytesNoCopy:(void*)message->message
1291 length:message->message_size
1297 NSMutableArray* isResponseValid =
self.isResponseValid;
1299 _embedderAPI.SendPlatformMessageResponse;
1301 @
synchronized(isResponseValid) {
1302 if (![isResponseValid[0] boolValue]) {
1306 if (responseHandle) {
1307 sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
1308 static_cast<const uint8_t*
>(response.bytes), response.length);
1309 responseHandle = NULL;
1311 NSLog(
@"Error: Message responses can be sent only once. Ignoring duplicate response "
1320 handlerInfo.
handler(messageData, binaryResponseHandler);
1322 binaryResponseHandler(nil);
1326- (void)engineCallbackOnPreEngineRestart {
1327 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1329 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1332 [_windowController closeAllWindows];
1333 [_platformViewController reset];
1339- (void)onVSync:(uintptr_t)baton {
1344 [_vsyncWaiters objectForKey:[_vsyncWaiters.keyEnumerator nextObject]];
1345 if (waiter != nil) {
1351 self.embedderAPI.OnVsync(_engine, baton, 0, 0);
1354 if ([NSThread isMainThread]) {
1357 [FlutterRunLoop.mainRunLoop performBlock:block];
1364- (void)shutDownEngine {
1365 if (_engine ==
nullptr) {
1371 NSLog(
@"Could not de-initialize the Flutter engine: error %d", result);
1374 result = _embedderAPI.Shutdown(_engine);
1376 NSLog(
@"Failed to shut down Flutter engine: error %d", result);
1382 NSAssert([[NSThread currentThread] isMainThread],
@"Must be called on the main thread.");
1383 return (__bridge
FlutterEngine*)
reinterpret_cast<void*
>(identifier);
1386- (void)setUpPlatformViewChannel {
1393 [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1394 [[weakSelf platformViewController] handleMethodCall:call result:result];
1398- (void)setUpAccessibilityChannel {
1404 [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1405 [weakSelf handleAccessibilityEvent:message];
1408- (void)setUpNotificationCenterListeners {
1409 NSNotificationCenter*
center = [NSNotificationCenter defaultCenter];
1411 [center addObserver:self
1412 selector:@selector(onAccessibilityStatusChanged:)
1413 name:kEnhancedUserInterfaceNotification
1415 [center addObserver:self
1416 selector:@selector(applicationWillTerminate:)
1417 name:NSApplicationWillTerminateNotification
1419 [center addObserver:self
1420 selector:@selector(windowDidChangeScreen:)
1421 name:NSWindowDidChangeScreenNotification
1423 [center addObserver:self
1424 selector:@selector(updateDisplayConfig:)
1425 name:NSApplicationDidChangeScreenParametersNotification
1429- (void)addInternalPlugins {
1443 [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1444 [weakSelf handleMethodCall:call result:result];
1451 [_screenshotChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1455 message:@"Engine deallocated."
1459 FlutterViewController* viewController =
1460 [strongSelf viewControllerForIdentifier:flutter::kFlutterImplicitViewId];
1461 if (!viewController) {
1463 message:@"No view controller."
1467 NSArray<FlutterSurface*>* frontSurfaces =
1468 viewController.flutterView.surfaceManager.frontSurfaces;
1469 if (frontSurfaces.count == 0) {
1476 FlutterSurface* surface = frontSurfaces.firstObject;
1477 IOSurfaceRef ioSurface = surface.ioSurface;
1479 size_t width = IOSurfaceGetWidth(ioSurface);
1480 size_t height = IOSurfaceGetHeight(ioSurface);
1481 size_t bytesPerRow = IOSurfaceGetBytesPerRow(ioSurface);
1482 size_t bytesPerElement = IOSurfaceGetBytesPerElement(ioSurface);
1483 uint32_t pixelFormat = (uint32_t)IOSurfaceGetPixelFormat(ioSurface);
1485 NSString* formatString;
1486 switch (pixelFormat) {
1487 case kCVPixelFormatType_40ARGBLEWideGamut:
1488 formatString = @"MTLPixelFormatBGRA10_XR";
1490 case kCVPixelFormatType_32BGRA:
1491 formatString = @"MTLPixelFormatBGRA8Unorm";
1494 formatString = [NSString stringWithFormat:@"Unknown(%u)", pixelFormat];
1498 IOSurfaceLock(ioSurface, kIOSurfaceLockReadOnly, nil);
1499 void* baseAddress = IOSurfaceGetBaseAddress(ioSurface);
1502 size_t packedBytesPerRow = width * bytesPerElement;
1503 NSMutableData* packedData = [NSMutableData dataWithLength:packedBytesPerRow * height];
1504 uint8_t* dest = (uint8_t*)packedData.mutableBytes;
1505 for (size_t row = 0; row < height; row++) {
1506 memcpy(dest + row * packedBytesPerRow, (uint8_t*)baseAddress + row * bytesPerRow,
1510 IOSurfaceUnlock(ioSurface, kIOSurfaceLockReadOnly, nil);
1521- (void)didUpdateMouseCursor:(NSCursor*)cursor {
1525 [_lastViewWithPointerEvent didUpdateMouseCursor:cursor];
1528- (void)applicationWillTerminate:(NSNotification*)notification {
1529 [
self shutDownEngine];
1532- (void)windowDidChangeScreen:(NSNotification*)notification {
1535 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1537 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1538 [
self updateWindowMetricsForViewController:nextViewController];
1539 [nextViewController updateWideGamutForScreen];
1543- (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1544 BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1545 NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1547 while ((nextViewController = [viewControllerEnumerator nextObject])) {
1551 self.semanticsEnabled = enabled;
1553- (void)handleAccessibilityEvent:(NSDictionary<NSString*,
id>*)annotatedEvent {
1554 NSString*
type = annotatedEvent[@"type"];
1555 if ([
type isEqualToString:
@"announce"]) {
1556 NSString*
message = annotatedEvent[@"data"][@"message"];
1557 NSNumber*
assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1562 NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1563 ? NSAccessibilityPriorityHigh
1564 : NSAccessibilityPriorityMedium;
1566 [
self announceAccessibilityMessage:message withPriority:priority];
1570- (void)announceAccessibilityMessage:(NSString*)message
1571 withPriority:(NSAccessibilityPriorityLevel)priority {
1572 NSAccessibilityPostNotificationWithUserInfo(
1574 NSAccessibilityAnnouncementRequestedNotification,
1575 @{NSAccessibilityAnnouncementKey :
message, NSAccessibilityPriorityKey : @(priority)});
1578 if ([call.
method isEqualToString:
@"SystemNavigator.pop"]) {
1579 [[NSApplication sharedApplication] terminate:self];
1581 }
else if ([call.
method isEqualToString:
@"SystemSound.play"]) {
1582 [
self playSystemSound:call.arguments];
1584 }
else if ([call.
method isEqualToString:
@"Clipboard.getData"]) {
1585 result([
self getClipboardData:call.arguments]);
1586 }
else if ([call.
method isEqualToString:
@"Clipboard.setData"]) {
1587 [
self setClipboardData:call.arguments];
1589 }
else if ([call.
method isEqualToString:
@"Clipboard.hasStrings"]) {
1590 result(@{
@"value" : @([
self clipboardHasStrings])});
1591 }
else if ([call.
method isEqualToString:
@"System.exitApplication"]) {
1592 if ([
self terminationHandler] == nil) {
1597 [NSApp terminate:self];
1600 [[
self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1602 }
else if ([call.
method isEqualToString:
@"System.initializationComplete"]) {
1603 if ([
self terminationHandler] != nil) {
1604 [
self terminationHandler].acceptingRequests = YES;
1612- (void)playSystemSound:(NSString*)soundType {
1613 if ([soundType isEqualToString:
@"SystemSoundType.alert"]) {
1618- (NSDictionary*)getClipboardData:(NSString*)format {
1620 NSString* stringInPasteboard = [
self.pasteboard stringForType:NSPasteboardTypeString];
1621 return stringInPasteboard == nil ? nil : @{
@"text" : stringInPasteboard};
1626- (void)setClipboardData:(NSDictionary*)data {
1628 [
self.pasteboard clearContents];
1629 if (
text && ![
text isEqual:[NSNull null]]) {
1630 [
self.pasteboard setString:text forType:NSPasteboardTypeString];
1634- (
BOOL)clipboardHasStrings {
1635 return [
self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1638- (
std::vector<std::string>)switches {
1642#pragma mark - FlutterAppLifecycleDelegate
1645 NSString* nextState =
1646 [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1647 [
self sendOnChannel:kFlutterLifecycleChannel
1648 message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1655- (void)handleWillBecomeActive:(NSNotification*)notification {
1658 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1660 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1668- (void)handleWillResignActive:(NSNotification*)notification {
1671 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1673 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1681- (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1682 NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1683 if (occlusionState & NSApplicationOcclusionStateVisible) {
1686 [
self setApplicationState:flutter::AppLifecycleState::kResumed];
1688 [
self setApplicationState:flutter::AppLifecycleState::kInactive];
1692 [
self setApplicationState:flutter::AppLifecycleState::kHidden];
1696#pragma mark - FlutterBinaryMessenger
1698- (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1699 [
self sendOnChannel:channel message:message binaryReply:nil];
1702- (void)sendOnChannel:(NSString*)channel
1703 message:(NSData* _Nullable)message
1710 auto captures = std::make_unique<Captures>();
1712 auto message_reply = [](
const uint8_t*
data,
size_t data_size,
void*
user_data) {
1713 auto captures =
reinterpret_cast<Captures*
>(
user_data);
1714 NSData* reply_data = nil;
1715 if (data !=
nullptr && data_size > 0) {
1716 reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1718 captures->reply(reply_data);
1723 _engine, message_reply, captures.get(), &response_handle);
1725 NSLog(
@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1735 .message_size =
message.length,
1736 .response_handle = response_handle,
1739 FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1741 NSLog(
@"Failed to send message to Flutter engine on channel '%@' (%d).",
channel,
1745 if (response_handle !=
nullptr) {
1747 _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1749 NSLog(
@"Failed to release the response handle (%d).", release_result);
1755 binaryMessageHandler:
1760 handler:[handler copy]];
1767 NSString* foundChannel = nil;
1770 if ([handlerInfo.
connection isEqual:@(connection)]) {
1776 [_messengerHandlers removeObjectForKey:foundChannel];
1780#pragma mark - FlutterPluginRegistry
1782- (
id<FlutterPluginRegistrar>)registrarForPlugin:(NSString*)pluginName {
1783 id<FlutterPluginRegistrar> registrar =
self.pluginRegistrars[pluginName];
1787 self.pluginRegistrars[pluginName] = registrarImpl;
1788 registrar = registrarImpl;
1793- (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1797#pragma mark - FlutterTextureRegistrar
1800 return [_renderer registerTexture:texture];
1803- (
BOOL)registerTextureWithID:(int64_t)textureId {
1804 return _embedderAPI.RegisterExternalTexture(_engine, textureId) ==
kSuccess;
1807- (void)textureFrameAvailable:(int64_t)textureID {
1808 [_renderer textureFrameAvailable:textureID];
1811- (
BOOL)markTextureFrameAvailable:(int64_t)textureID {
1812 return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) ==
kSuccess;
1815- (void)unregisterTexture:(int64_t)textureID {
1816 [_renderer unregisterTexture:textureID];
1819- (
BOOL)unregisterTextureWithID:(int64_t)textureID {
1820 return _embedderAPI.UnregisterExternalTexture(_engine, textureID) ==
kSuccess;
1823#pragma mark - Task runner integration
1825- (void)postMainThreadTask:(
FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1828 const auto engine_time = _embedderAPI.GetCurrentTime();
1829 [FlutterRunLoop.mainRunLoop
1830 performAfterDelay:(targetTime - (double)engine_time) / NSEC_PER_SEC
1833 if (self != nil && self->_engine != nil) {
1834 auto result = _embedderAPI.RunTask(self->_engine, &task);
1835 if (result != kSuccess) {
1836 NSLog(@"Could not post a task to the Flutter engine.");
1843- (
flutter::FlutterCompositor*)macOSCompositor {
1847#pragma mark - FlutterKeyboardManagerDelegate
1854 userData:(
void*)userData {
1855 _embedderAPI.SendKeyEvent(_engine, &event,
callback, userData);
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterBinaryReply)(NSData *_Nullable reply)
void(^ FlutterBinaryMessageHandler)(NSData *_Nullable message, FlutterBinaryReply reply)
int64_t FlutterBinaryMessengerConnection
void(^ FlutterResult)(id _Nullable result)
FLUTTER_DARWIN_EXPORT NSObject const * FlutterMethodNotImplemented
FlutterBinaryMessengerConnection _connection
NSInteger clearContents()
FlutterEngineResult FlutterEngineGetProcAddresses(FlutterEngineProcTable *table)
Gets the table of engine function pointers.
#define FLUTTER_API_SYMBOL(symbol)
@ kUnfocused
Specifies that a view does not have platform focus.
@ kFocused
Specifies that a view has platform focus.
@ kFlutterEngineAOTDataSourceTypeElfPath
void(* FlutterPlatformMessageCallback)(const FlutterPlatformMessage *, void *)
@ kFlutterEngineDisplaysUpdateTypeStartup
FlutterThreadPriority
Valid values for priority of Thread.
@ kDisplay
Suitable for threads which generate data for the display.
@ kRaster
Suitable for thread which raster data.
void(* FlutterKeyEventCallback)(bool, void *)
FlutterEngineResult(* FlutterEngineSendPlatformMessageResponseFnPtr)(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessageResponseHandle *handle, const uint8_t *data, size_t data_length)
#define FLUTTER_ENGINE_VERSION
const char FlTextDirection FlAssertiveness assertiveness
const gchar FlBinaryMessengerMessageHandler handler
const uint8_t uint32_t uint32_t GError ** error
G_BEGIN_DECLS FlutterViewId view_id
HWND(* FlutterPlatformViewFactory)(const FlutterPlatformViewCreationParameters *)
FlutterDesktopBinaryReply callback
#define FML_LOG(severity)
#define FML_DCHECK(condition)
instancetype messageChannelWithName:binaryMessenger:codec:(NSString *name,[binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger,[codec] NSObject< FlutterMessageCodec > *codec)
void(* rootIsolateCreateCallback)(void *_Nullable)
NSString * lookupKeyForAsset:fromPackage:(NSString *asset,[fromPackage] NSString *package)
NSString * lookupKeyForAsset:(NSString *asset)
instancetype displayLinkWithView:(NSView *view)
FlutterBinaryMessageHandler handler
NSObject< FlutterBinaryMessenger > * binaryMessenger
NSObject * publishedValue
instancetype errorWithCode:message:details:(NSString *code,[message] NSString *_Nullable message,[details] id _Nullable details)
instancetype methodCallWithMethodName:arguments:(NSString *method,[arguments] id _Nullable arguments)
void setMethodCallHandler:(FlutterMethodCallHandler _Nullable handler)
instancetype methodChannelWithName:binaryMessenger:codec:(NSString *name,[binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger,[codec] NSObject< FlutterMethodCodec > *codec)
void registerWithRegistrar:delegate:(nonnull id< FlutterPluginRegistrar > registrar,[delegate] nullable id< FlutterMouseCursorPluginDelegate > delegate)
instancetype typedDataWithBytes:(NSData *data)
Converts between the time representation used by Flutter Engine and CAMediaTime.
uint64_t CAMediaTimeToEngineTime:(CFTimeInterval time)
void waitForVSync:(uintptr_t baton)
void onPreEngineRestart()
FlutterViewIdentifier viewIdentifier
void onAccessibilityStatusChanged:(BOOL enabled)
FlutterBinaryMessengerRelay * _binaryMessenger
FlutterViewController * viewController
FlutterMethodChannel * _platformViewsChannel
_FlutterEngineAOTData * _aotData
std::unique_ptr< flutter::FlutterCompositor > _macOSCompositor
static const int kMainThreadPriority
static void OnPlatformMessage(const FlutterPlatformMessage *message, void *user_data)
FlutterPlatformViewController * _platformViewController
FlutterBasicMessageChannel * _accessibilityChannel
FlutterBasicMessageChannel * _settingsChannel
static FlutterLocale FlutterLocaleFromNSLocale(NSLocale *locale)
BOOL _allowHeadlessExecution
NSMutableDictionary< NSString *, FlutterEngineHandlerInfo * > * _messengerHandlers
FlutterBinaryMessengerConnection _currentMessengerConnection
FlutterMethodChannel * _platformChannel
NSString *const kFlutterLifecycleChannel
static NSString *const kEnhancedUserInterfaceNotification
The private notification for voice over.
NSMapTable< NSNumber *, FlutterVSyncWaiter * > * _vsyncWaiters
FlutterViewIdentifier _nextViewIdentifier
NSString *const kFlutterPlatformChannel
FlutterMethodChannel * _screenshotChannel
FlutterTextInputPlugin * _textInputPlugin
FlutterDartProject * _project
NSMapTable * _viewControllers
FlutterCompositor _compositor
__weak FlutterView * _lastViewWithPointerEvent
FlutterKeyboardManager * _keyboardManager
FlutterWindowController * _windowController
FlutterTerminationCallback _terminator
constexpr char kTextPlainFormat[]
Clipboard plain text format.
__weak FlutterEngine * _flutterEngine
FlutterBinaryMessengerRelay * _binaryMessenger
static NSString *const kEnhancedUserInterfaceKey
NSString *const kFlutterSettingsChannel
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterTerminationCallback)(id _Nullable sender)
constexpr int64_t kFlutterImplicitViewId
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot data
std::vector< std::string > GetSwitchesFromEnvironment()
instancetype sharedInstance()
impeller::ShaderType type
void * user_data
The |FlutterAddViewInfo.user_data|.
FlutterBackingStoreCreateCallback create_backing_store_callback
bool avoid_backing_store_cache
size_t struct_size
This size of this struct. Must be sizeof(FlutterCompositor).
FlutterPresentViewCallback present_view_callback
FlutterBackingStoreCollectCallback collect_backing_store_callback
size_t struct_size
The size of this struct. Must be sizeof(FlutterCustomTaskRunners).
FlutterEngineAOTDataSourceType type
const char * elf_path
Absolute path to an ELF library file.
size_t height
The height of the display, in physical pixels.
double device_pixel_ratio
size_t struct_size
The size of this struct. Must be sizeof(FlutterEngineDisplay).
size_t width
The width of the display, in physical pixels.
FlutterEngineDisplayId display_id
Function-pointer-based versions of the APIs above.
const char * language_code
size_t struct_size
This size of this struct. Must be sizeof(FlutterLocale).
const char * country_code
const char * variant_code
FlutterPlatformMessageCallback platform_message_callback
FlutterLogMessageCallback log_message_callback
FlutterViewFocusChangeRequestCallback view_focus_change_request_callback
VsyncCallback vsync_callback
OnPreEngineRestartCallback on_pre_engine_restart_callback
FlutterEngineAOTData aot_data
const char *const * dart_entrypoint_argv
size_t struct_size
The size of this struct. Must be sizeof(FlutterProjectArgs).
FlutterUpdateSemanticsCallback2 update_semantics_callback2
const char *const * command_line_argv
const char * icu_data_path
bool shutdown_dart_vm_when_done
const char * custom_dart_entrypoint
const FlutterCustomTaskRunners * custom_task_runners
int command_line_argc
The command line argument count used to initialize the project.
VoidCallback root_isolate_create_callback
const FlutterCompositor * compositor
FlutterRemoveViewCallback remove_view_callback
A batch of updates to semantics nodes and custom actions.
size_t struct_size
The size of this struct. Must be sizeof(FlutterTaskRunnerDescription).
FlutterViewFocusState state
The focus state of the view.
size_t struct_size
The size of this struct. Must be sizeof(FlutterWindowMetricsEvent).
size_t min_height_constraint
size_t min_width_constraint
size_t max_width_constraint
size_t max_height_constraint