Flutter macOS Embedder
FlutterEngine.mm
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
7 
8 #include <algorithm>
9 #include <iostream>
10 #include <sstream>
11 #include <vector>
12 
13 #include "flutter/common/constants.h"
14 #include "flutter/fml/logging.h"
17 #include "flutter/shell/platform/embedder/embedder.h"
18 
19 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
21 #import "flutter/shell/platform/darwin/macos/InternalFlutterSwift/InternalFlutterSwift.h"
36 
37 #import <CoreVideo/CoreVideo.h>
38 #import <IOSurface/IOSurface.h>
39 
41 
42 NSString* const kFlutterPlatformChannel = @"flutter/platform";
43 NSString* const kFlutterSettingsChannel = @"flutter/settings";
44 NSString* const kFlutterLifecycleChannel = @"flutter/lifecycle";
45 
46 using flutter::kFlutterImplicitViewId;
47 
48 /**
49  * Constructs and returns a FlutterLocale struct corresponding to |locale|, which must outlive
50  * the returned struct.
51  */
52 static FlutterLocale FlutterLocaleFromNSLocale(NSLocale* locale) {
53  FlutterLocale flutterLocale = {};
54  flutterLocale.struct_size = sizeof(FlutterLocale);
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];
59  return flutterLocale;
60 }
61 
62 /// The private notification for voice over.
63 static NSString* const kEnhancedUserInterfaceNotification =
64  @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification";
65 static NSString* const kEnhancedUserInterfaceKey = @"AXEnhancedUserInterface";
66 
67 /// Clipboard plain text format.
68 constexpr char kTextPlainFormat[] = "text/plain";
69 
70 #pragma mark -
71 
72 // Records an active handler of the messenger (FlutterEngine) that listens to
73 // platform messages on a given channel.
74 @interface FlutterEngineHandlerInfo : NSObject
75 
76 - (instancetype)initWithConnection:(NSNumber*)connection
77  handler:(FlutterBinaryMessageHandler)handler;
78 
79 @property(nonatomic, readonly) FlutterBinaryMessageHandler handler;
80 @property(nonatomic, readonly) NSNumber* connection;
81 
82 @end
83 
84 @implementation FlutterEngineHandlerInfo
85 - (instancetype)initWithConnection:(NSNumber*)connection
86  handler:(FlutterBinaryMessageHandler)handler {
87  self = [super init];
88  NSAssert(self, @"Super init cannot be nil");
90  _handler = handler;
91  return self;
92 }
93 @end
94 
95 #pragma mark -
96 
97 /**
98  * Private interface declaration for FlutterEngine.
99  */
104 
105 /**
106  * A mutable array that holds one bool value that determines if responses to platform messages are
107  * clear to execute. This value should be read or written only inside of a synchronized block and
108  * will return `NO` after the FlutterEngine has been dealloc'd.
109  */
110 @property(nonatomic, strong) NSMutableArray<NSNumber*>* isResponseValid;
111 
112 /**
113  * All delegates added via plugin calls to addApplicationDelegate.
114  */
115 @property(nonatomic, strong) NSPointerArray* pluginAppDelegates;
116 
117 /**
118  * All registrars returned from registrarForPlugin:
119  */
120 @property(nonatomic, readonly)
121  NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* pluginRegistrars;
122 
123 - (nullable FlutterViewController*)viewControllerForIdentifier:
124  (FlutterViewIdentifier)viewIdentifier;
125 
126 /**
127  * An internal method that adds the view controller with the given ID.
128  *
129  * This method assigns the controller with the ID, puts the controller into the
130  * map, and does assertions related to the implicit view ID.
131  */
132 - (void)registerViewController:(FlutterViewController*)controller
133  forIdentifier:(FlutterViewIdentifier)viewIdentifier;
134 
135 /**
136  * An internal method that removes the view controller with the given ID.
137  *
138  * This method clears the ID of the controller, removes the controller from the
139  * map. This is an no-op if the view ID is not associated with any view
140  * controllers.
141  */
142 - (void)deregisterViewControllerForIdentifier:(FlutterViewIdentifier)viewIdentifier;
143 
144 /**
145  * Shuts down the engine if view requirement is not met, and headless execution
146  * is not allowed.
147  */
148 - (void)shutDownIfNeeded;
149 
150 /**
151  * Sends the list of user-preferred locales to the Flutter engine.
152  */
153 - (void)sendUserLocales;
154 
155 /**
156  * Handles a platform message from the engine.
157  */
158 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message;
159 
160 /**
161  * Requests that the task be posted back the to the Flutter engine at the target time. The target
162  * time is in the clock used by the Flutter engine.
163  */
164 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime;
165 
166 /**
167  * Loads the AOT snapshots and instructions from the elf bundle (app_elf_snapshot.so) into _aotData,
168  * if it is present in the assets directory.
169  */
170 - (void)loadAOTData:(NSString*)assetsDir;
171 
172 /**
173  * Creates a platform view channel and sets up the method handler.
174  */
175 - (void)setUpPlatformViewChannel;
176 
177 /**
178  * Creates an accessibility channel and sets up the message handler.
179  */
180 - (void)setUpAccessibilityChannel;
181 
182 /**
183  * Handles messages received from the Flutter engine on the _*Channel channels.
184  */
185 - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result;
186 
187 @end
188 
189 #pragma mark -
190 
192  __weak FlutterEngine* _engine;
194 }
195 
196 - (instancetype)initWithEngine:(FlutterEngine*)engine
197  terminator:(FlutterTerminationCallback)terminator {
198  self = [super init];
199  _acceptingRequests = NO;
200  _engine = engine;
201  _terminator = terminator ? terminator : ^(id sender) {
202  // Default to actually terminating the application. The terminator exists to
203  // allow tests to override it so that an actual exit doesn't occur.
204  [[NSApplication sharedApplication] terminate:sender];
205  };
206  id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
207  if ([appDelegate respondsToSelector:@selector(setTerminationHandler:)]) {
208  FlutterAppDelegate* flutterAppDelegate = reinterpret_cast<FlutterAppDelegate*>(appDelegate);
209  flutterAppDelegate.terminationHandler = self;
210  }
211  return self;
212 }
213 
214 // This is called by the method call handler in the engine when the application
215 // requests termination itself.
216 - (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*, id>*)arguments
217  result:(FlutterResult)result {
218  NSString* type = arguments[@"type"];
219  // Ignore the "exitCode" value in the arguments because AppKit doesn't have
220  // any good way to set the process exit code other than calling exit(), and
221  // that bypasses all of the native applicationShouldExit shutdown events,
222  // etc., which we don't want to skip.
223 
224  FlutterAppExitType exitType =
225  [type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired;
226 
227  [self requestApplicationTermination:[NSApplication sharedApplication]
228  exitType:exitType
229  result:result];
230 }
231 
232 // This is called by the FlutterAppDelegate whenever any termination request is
233 // received.
234 - (void)requestApplicationTermination:(id)sender
235  exitType:(FlutterAppExitType)type
236  result:(nullable FlutterResult)result {
237  _shouldTerminate = YES;
238  if (![self acceptingRequests]) {
239  // Until the Dart application has signaled that it is ready to handle
240  // termination requests, the app will just terminate when asked.
241  type = kFlutterAppExitTypeRequired;
242  }
243  switch (type) {
244  case kFlutterAppExitTypeCancelable: {
245  FlutterJSONMethodCodec* codec = [FlutterJSONMethodCodec sharedInstance];
246  FlutterMethodCall* methodCall =
247  [FlutterMethodCall methodCallWithMethodName:@"System.requestAppExit" arguments:nil];
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]]) {
254  FlutterError* error = (FlutterError*)decoded_reply;
255  NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message],
256  [error details]);
257  _terminator(sender);
258  return;
259  }
260  if (![decoded_reply isKindOfClass:[NSDictionary class]]) {
261  NSLog(@"Call to System.requestAppExit returned an unexpected object: %@",
262  decoded_reply);
263  _terminator(sender);
264  return;
265  }
266  NSDictionary* replyArgs = (NSDictionary*)decoded_reply;
267  if ([replyArgs[@"response"] isEqual:@"exit"]) {
268  _terminator(sender);
269  } else if ([replyArgs[@"response"] isEqual:@"cancel"]) {
270  _shouldTerminate = NO;
271  }
272  if (result != nil) {
273  result(replyArgs);
274  }
275  }];
276  break;
277  }
278  case kFlutterAppExitTypeRequired:
279  NSAssert(_terminator, @"terminator shouldn't be nil");
280  _terminator(sender);
281  break;
282  }
283 }
284 
285 @end
286 
287 #pragma mark -
288 
289 @implementation FlutterPasteboard
290 
291 - (NSInteger)clearContents {
292  return [[NSPasteboard generalPasteboard] clearContents];
293 }
294 
295 - (NSString*)stringForType:(NSPasteboardType)dataType {
296  return [[NSPasteboard generalPasteboard] stringForType:dataType];
297 }
298 
299 - (BOOL)setString:(nonnull NSString*)string forType:(nonnull NSPasteboardType)dataType {
300  return [[NSPasteboard generalPasteboard] setString:string forType:dataType];
301 }
302 
303 @end
304 
305 #pragma mark -
306 
307 /**
308  * `FlutterPluginRegistrar` implementation handling a single plugin.
309  */
311 - (instancetype)initWithPlugin:(nonnull NSString*)pluginKey
312  flutterEngine:(nonnull FlutterEngine*)flutterEngine;
313 
314 - (nullable NSView*)viewForIdentifier:(FlutterViewIdentifier)viewIdentifier;
315 
316 /**
317  * The value published by this plugin, or NSNull if nothing has been published.
318  *
319  * The unusual NSNull is for the documented behavior of valuePublishedByPlugin:.
320  */
321 @property(nonatomic, readonly, nonnull) NSObject* publishedValue;
322 @end
323 
324 @implementation FlutterEngineRegistrar {
325  NSString* _pluginKey;
327 }
328 
329 @dynamic view;
330 
331 - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine {
332  self = [super init];
333  if (self) {
334  _pluginKey = [pluginKey copy];
335  _flutterEngine = flutterEngine;
336  _publishedValue = [NSNull null];
337  }
338  return self;
339 }
340 
341 #pragma mark - FlutterPluginRegistrar
342 
343 - (int64_t)engineIdentifier {
344  return _flutterEngine.engineIdentifier;
345 }
346 
347 - (id<FlutterBinaryMessenger>)messenger {
349 }
350 
351 - (id<FlutterTextureRegistry>)textures {
352  return _flutterEngine.renderer;
353 }
354 
355 - (NSView*)view {
356  return [self viewForIdentifier:kFlutterImplicitViewId];
357 }
358 
359 - (NSView*)viewForIdentifier:(FlutterViewIdentifier)viewIdentifier {
360  FlutterViewController* controller = [_flutterEngine viewControllerForIdentifier:viewIdentifier];
361  if (controller == nil) {
362  return nil;
363  }
364  if (!controller.viewLoaded) {
365  [controller loadView];
366  }
367  return controller.flutterView;
368 }
369 
370 - (NSViewController*)viewController {
371  return [_flutterEngine viewControllerForIdentifier:kFlutterImplicitViewId];
372 }
373 
374 - (void)addMethodCallDelegate:(nonnull id<FlutterPlugin>)delegate
375  channel:(nonnull FlutterMethodChannel*)channel {
376  [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
377  [delegate handleMethodCall:call result:result];
378  }];
379 }
380 
381 - (void)addApplicationDelegate:(NSObject<FlutterAppLifecycleDelegate>*)delegate {
382  id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
383  if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
384  id<FlutterAppLifecycleProvider> lifeCycleProvider =
385  static_cast<id<FlutterAppLifecycleProvider>>(appDelegate);
386  [lifeCycleProvider addApplicationLifecycleDelegate:delegate];
387  [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
388  }
389 }
390 
391 - (void)registerViewFactory:(nonnull NSObject<FlutterPlatformViewFactory>*)factory
392  withId:(nonnull NSString*)factoryId {
393  [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
394 }
395 
396 - (void)publish:(NSObject*)value {
397  _publishedValue = value;
398 }
399 
400 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
401  return [_flutterEngine valuePublishedByPlugin:pluginKey];
402 }
403 
404 - (NSString*)lookupKeyForAsset:(NSString*)asset {
405  return [FlutterDartProject lookupKeyForAsset:asset];
406 }
407 
408 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
409  return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package];
410 }
411 
412 @end
413 
414 // Callbacks provided to the engine. See the called methods for documentation.
415 #pragma mark - Static methods provided to engine configuration
416 
417 static void OnPlatformMessage(const FlutterPlatformMessage* message, void* user_data) {
418  FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
419  [engine engineCallbackOnPlatformMessage:message];
420 }
421 
422 #pragma mark -
423 
424 @implementation FlutterEngine {
425  // The embedding-API-level engine object.
426  FLUTTER_API_SYMBOL(FlutterEngine) _engine;
427 
428  // The project being run by this engine.
430 
431  // A mapping of channel names to the registered information for those channels.
432  NSMutableDictionary<NSString*, FlutterEngineHandlerInfo*>* _messengerHandlers;
433 
434  // A self-incremental integer to assign to newly assigned channels as
435  // identification.
437 
438  // Whether the engine can continue running after the view controller is removed.
440 
441  // Pointer to the Dart AOT snapshot and instruction data.
442  _FlutterEngineAOTData* _aotData;
443 
444  // _macOSCompositor is created when the engine is created and its destruction is handled by ARC
445  // when the engine is destroyed.
446  std::unique_ptr<flutter::FlutterCompositor> _macOSCompositor;
447 
448  // The information of all views attached to this engine mapped from IDs.
449  //
450  // It can't use NSDictionary, because the values need to be weak references.
451  NSMapTable* _viewControllers;
452 
453  // FlutterCompositor is copied and used in embedder.cc.
454  FlutterCompositor _compositor;
455 
456  // Method channel for platform view functions. These functions include creating, disposing and
457  // mutating a platform view.
459 
460  // Used to support creation and deletion of platform views and registering platform view
461  // factories. Lifecycle is tied to the engine.
463 
464  // Used to manage Flutter windows created by the Dart application
466 
467  // A message channel for sending user settings to the flutter engine.
469 
470  // A message channel for accessibility.
472 
473  // A method channel for miscellaneous platform functionality.
475 
476  // A method channel for taking screenshots via the rasterizer.
478 
479  // Whether the application is currently the active application.
480  BOOL _active;
481 
482  // Whether any portion of the application is currently visible.
483  BOOL _visible;
484 
485  // Proxy to allow plugins, channels to hold a weak reference to the binary messenger (self).
487 
488  // Map from ViewId to vsync waiter. Note that this is modified on main thread
489  // but accessed on UI thread, so access must be @synchronized.
490  NSMapTable<NSNumber*, FlutterVSyncWaiter*>* _vsyncWaiters;
491 
492  // Weak reference to last view that received a pointer event. This is used to
493  // pair cursor change with a view.
495 
496  // Pointer to a keyboard manager.
498 
499  // The text input plugin that handles text editing state for text fields.
501 
502  // Whether the engine is running in multi-window mode. This affects behavior
503  // when adding view controller (it will fail when calling multiple times without
504  // _multiviewEnabled).
506 
507  // View identifier for the next view to be created.
508  // Only used when multiview is enabled.
510 }
511 
512 @synthesize windowController = _windowController;
513 @synthesize project = _project;
514 
515 - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project {
516  return [self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
517 }
518 
519 static const int kMainThreadPriority = 47;
520 
521 static void SetThreadPriority(FlutterThreadPriority priority) {
522  if (priority == kDisplay || priority == kRaster) {
523  pthread_t thread = pthread_self();
524  sched_param param;
525  int policy;
526  if (!pthread_getschedparam(thread, &policy, &param)) {
527  param.sched_priority = kMainThreadPriority;
528  pthread_setschedparam(thread, policy, &param);
529  }
530  pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
531  }
532 }
533 
534 - (instancetype)initWithName:(NSString*)labelPrefix
535  project:(FlutterDartProject*)project
536  allowHeadlessExecution:(BOOL)allowHeadlessExecution {
537  self = [super init];
538  NSAssert(self, @"Super init cannot be nil");
539 
540  [FlutterRunLoop ensureMainLoopInitialized];
541 
542  _pasteboard = [[FlutterPasteboard alloc] init];
543  _active = NO;
544  _visible = NO;
545  _project = project ?: [[FlutterDartProject alloc] init];
546  _messengerHandlers = [[NSMutableDictionary alloc] init];
547  _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
548  _pluginRegistrars = [[NSMutableDictionary alloc] init];
550  _allowHeadlessExecution = allowHeadlessExecution;
551  _semanticsEnabled = NO;
552  _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self];
553  _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
554  [_isResponseValid addObject:@YES];
555  _keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:self];
556  _textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:self];
557  _multiViewEnabled = NO;
559 
560  _embedderAPI.struct_size = sizeof(FlutterEngineProcTable);
561  FlutterEngineGetProcAddresses(&_embedderAPI);
562 
563  _viewControllers = [NSMapTable weakToWeakObjectsMapTable];
564  _renderer = [[FlutterRenderer alloc] initWithFlutterEngine:self];
565 
566  NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
567  [notificationCenter addObserver:self
568  selector:@selector(sendUserLocales)
569  name:NSCurrentLocaleDidChangeNotification
570  object:nil];
571 
573  // The macOS compositor must be initialized in the initializer because it is
574  // used when adding views, which might happen before runWithEntrypoint.
575  _macOSCompositor = std::make_unique<flutter::FlutterCompositor>(
576  [[FlutterViewEngineProvider alloc] initWithEngine:self],
577  [[FlutterTimeConverter alloc] initWithEngine:self], _platformViewController);
578 
579  [self setUpPlatformViewChannel];
580 
582  _windowController.engine = self;
583 
584  [self setUpAccessibilityChannel];
585  [self setUpNotificationCenterListeners];
586  id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
587  if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
588  _terminationHandler = [[FlutterEngineTerminationHandler alloc] initWithEngine:self
589  terminator:nil];
590  id<FlutterAppLifecycleProvider> lifecycleProvider =
591  static_cast<id<FlutterAppLifecycleProvider>>(appDelegate);
592  [lifecycleProvider addApplicationLifecycleDelegate:self];
593  } else {
594  _terminationHandler = nil;
595  }
596 
597  _vsyncWaiters = [NSMapTable strongToStrongObjectsMapTable];
598 
599  return self;
600 }
601 
602 - (void)dealloc {
603  id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
604  if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
605  id<FlutterAppLifecycleProvider> lifecycleProvider =
606  static_cast<id<FlutterAppLifecycleProvider>>(appDelegate);
607  [lifecycleProvider removeApplicationLifecycleDelegate:self];
608 
609  // Unregister any plugins that registered as app delegates, since they are not guaranteed to
610  // live after the engine is destroyed, and their delegation registration is intended to be bound
611  // to the engine and its lifetime.
612  for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
613  if (delegate) {
614  [lifecycleProvider removeApplicationLifecycleDelegate:delegate];
615  }
616  }
617  }
618  // Clear any published values, just in case a plugin has created a retain cycle with the
619  // registrar.
620  for (NSString* pluginName in _pluginRegistrars) {
621  [_pluginRegistrars[pluginName] publish:[NSNull null]];
622  }
623  @synchronized(_isResponseValid) {
624  [_isResponseValid removeAllObjects];
625  [_isResponseValid addObject:@NO];
626  }
627  [self shutDownEngine];
628  if (_aotData) {
629  _embedderAPI.CollectAOTData(_aotData);
630  }
631 }
632 
633 - (FlutterTaskRunnerDescription)createPlatformThreadTaskDescription {
634  static size_t sTaskRunnerIdentifiers = 0;
635  FlutterTaskRunnerDescription cocoa_task_runner_description = {
636  .struct_size = sizeof(FlutterTaskRunnerDescription),
637  // Retain for use in post_task_callback. Released in destruction_callback.
638  .user_data = (__bridge_retained void*)self,
639  .runs_task_on_current_thread_callback = [](void* user_data) -> bool {
640  return [[NSThread currentThread] isMainThread];
641  },
642  .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
643  void* user_data) -> void {
644  FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
645  [engine postMainThreadTask:task targetTimeInNanoseconds:target_time_nanos];
646  },
647  .identifier = ++sTaskRunnerIdentifiers,
648  .destruction_callback =
649  [](void* user_data) {
650  // Balancing release for the retain when setting user_data above.
651  FlutterEngine* engine = (__bridge_transfer FlutterEngine*)user_data;
652  engine = nil;
653  },
654  };
655  return cocoa_task_runner_description;
656 }
657 
658 - (void)onFocusChangeRequest:(const FlutterViewFocusChangeRequest*)request {
659  FlutterViewController* controller = [self viewControllerForIdentifier:request->view_id];
660  if (controller == nil) {
661  return;
662  }
663  if (request->state == kFocused) {
664  [controller.flutterView.window makeFirstResponder:controller.flutterView];
665  }
666 }
667 
668 - (BOOL)runWithEntrypoint:(NSString*)entrypoint {
669  if (self.running) {
670  return NO;
671  }
672 
673  if (!_allowHeadlessExecution && [_viewControllers count] == 0) {
674  NSLog(@"Attempted to run an engine with no view controller without headless mode enabled.");
675  return NO;
676  }
677 
678  [self addInternalPlugins];
679 
680  // The first argument of argv is required to be the executable name.
681  std::vector<const char*> argv = {[self.executableName UTF8String]};
682  std::vector<std::string> switches = self.switches;
683 
684  // Enable Impeller only if specifically asked for from the project or cmdline arguments.
685  if (std::find(switches.begin(), switches.end(), "--enable-impeller=false") != switches.end()) {
686  // Keep it disabled.
687  } else if (_project.enableImpeller || std::find(switches.begin(), switches.end(),
688  "--enable-impeller=true") != switches.end()) {
689  switches.push_back("--enable-impeller=true");
690  }
691 
692  if (std::find(switches.begin(), switches.end(), "--enable-impeller=true") == switches.end()) {
693  FML_LOG(IMPORTANT) << "Using the Skia rendering backend (Metal).";
694  }
695 
696  if (_project.enableSDFs ||
697  std::find(switches.begin(), switches.end(), "--impeller-use-sdfs=true") != switches.end()) {
698  switches.push_back("--impeller-use-sdfs=true");
699  }
700 
701  if (_project.enableFlutterGPU ||
702  std::find(switches.begin(), switches.end(), "--enable-flutter-gpu=true") != switches.end()) {
703  switches.push_back("--enable-flutter-gpu=true");
704  }
705 
706  std::transform(switches.begin(), switches.end(), std::back_inserter(argv),
707  [](const std::string& arg) -> const char* { return arg.c_str(); });
708 
709  std::vector<const char*> dartEntrypointArgs;
710  for (NSString* argument in [_project dartEntrypointArguments]) {
711  dartEntrypointArgs.push_back([argument UTF8String]);
712  }
713 
714  FlutterProjectArgs flutterArguments = {};
715  flutterArguments.struct_size = sizeof(FlutterProjectArgs);
716  flutterArguments.assets_path = _project.assetsPath.UTF8String;
717  flutterArguments.icu_data_path = _project.ICUDataPath.UTF8String;
718  flutterArguments.command_line_argc = static_cast<int>(argv.size());
719  flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data();
720  flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)OnPlatformMessage;
721  flutterArguments.update_semantics_callback2 = [](const FlutterSemanticsUpdate2* update,
722  void* user_data) {
723  // TODO(dkwingsmt): This callback only supports single-view, therefore it
724  // only operates on the implicit view. To support multi-view, we need a
725  // way to pass in the ID (probably through FlutterSemanticsUpdate).
726  FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
727  [[engine viewControllerForIdentifier:kFlutterImplicitViewId] updateSemantics:update];
728  };
729  flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String;
730  flutterArguments.shutdown_dart_vm_when_done = true;
731  flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size();
732  flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data();
733  flutterArguments.root_isolate_create_callback = _project.rootIsolateCreateCallback;
734  flutterArguments.log_message_callback = [](const char* tag, const char* message,
735  void* user_data) {
736  std::stringstream stream;
737  if (tag && tag[0]) {
738  stream << tag << ": ";
739  }
740  stream << message;
741  std::string log = stream.str();
742  [FlutterLogger logDirect:[NSString stringWithUTF8String:log.c_str()]];
743  };
744 
745  flutterArguments.engine_id = self.engineIdentifier;
746  BOOL enableWideGamut = _project.enableWideGamut;
747  if (std::find(switches.begin(), switches.end(), "--enable-impeller=false") != switches.end()) {
748  enableWideGamut = NO;
749  }
750  flutterArguments.enable_wide_gamut = enableWideGamut;
751 
752  BOOL mergedPlatformUIThread = YES;
753  NSNumber* enableMergedPlatformUIThread =
754  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableMergedPlatformUIThread"];
755  if (enableMergedPlatformUIThread != nil) {
756  mergedPlatformUIThread = enableMergedPlatformUIThread.boolValue;
757  }
758 
759  if (!mergedPlatformUIThread) {
760  NSLog(@"Warning: Merged threads is disabled. Running Flutter without merged threads is "
761  "deprecated and will be unsupported in a future release.\n"
762  "\n"
763  "To turn on merged threads, update your macos/Runner/Info.plist file:\n"
764  "\n"
765  " <key>FLTEnableMergedPlatformUIThread</key>\n"
766  " <true/>\n"
767  "\n"
768  "If you disabled merged threads to work around an issue, please report it here: "
769  "https://github.com/flutter/flutter/issues/150525.");
770  }
771 
772  // The task description needs to be created separately for platform task
773  // runner and UI task runner because each one has their own __bridge_retained
774  // engine user data.
775  FlutterTaskRunnerDescription platformTaskRunnerDescription =
776  [self createPlatformThreadTaskDescription];
777  std::optional<FlutterTaskRunnerDescription> uiTaskRunnerDescription;
778  if (mergedPlatformUIThread) {
779  uiTaskRunnerDescription = [self createPlatformThreadTaskDescription];
780  }
781 
782  const FlutterCustomTaskRunners custom_task_runners = {
783  .struct_size = sizeof(FlutterCustomTaskRunners),
784  .platform_task_runner = &platformTaskRunnerDescription,
785  .thread_priority_setter = SetThreadPriority,
786  .ui_task_runner = uiTaskRunnerDescription ? &uiTaskRunnerDescription.value() : nullptr,
787  };
788  flutterArguments.custom_task_runners = &custom_task_runners;
789 
790  [self loadAOTData:_project.assetsPath];
791  if (_aotData) {
792  flutterArguments.aot_data = _aotData;
793  }
794 
795  flutterArguments.compositor = [self createFlutterCompositor];
796 
797  flutterArguments.on_pre_engine_restart_callback = [](void* user_data) {
798  FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
799  [engine engineCallbackOnPreEngineRestart];
800  };
801 
802  flutterArguments.vsync_callback = [](void* user_data, intptr_t baton) {
803  FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
804  [engine onVSync:baton];
805  };
806 
807  flutterArguments.view_focus_change_request_callback =
808  [](const FlutterViewFocusChangeRequest* request, void* user_data) {
809  FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
810  [engine onFocusChangeRequest:request];
811  };
812 
813  FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
814  FlutterEngineResult result = _embedderAPI.Initialize(
815  FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge void*)(self), &_engine);
816  if (result != kSuccess) {
817  NSLog(@"Failed to initialize Flutter engine: error %d", result);
818  return NO;
819  }
820 
821  result = _embedderAPI.RunInitialized(_engine);
822  if (result != kSuccess) {
823  NSLog(@"Failed to run an initialized engine: error %d", result);
824  return NO;
825  }
826 
827  [self sendUserLocales];
828 
829  // Update window metric for all view controllers.
830  NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
831  FlutterViewController* nextViewController;
832  while ((nextViewController = [viewControllerEnumerator nextObject])) {
833  [self updateWindowMetricsForViewController:nextViewController];
834  }
835 
836  [self updateDisplayConfig];
837  // Send the initial user settings such as brightness and text scale factor
838  // to the engine.
839  [self sendInitialSettings];
840  return YES;
841 }
842 
843 - (void)loadAOTData:(NSString*)assetsDir {
844  if (!_embedderAPI.RunsAOTCompiledDartCode()) {
845  return;
846  }
847 
848  BOOL isDirOut = false; // required for NSFileManager fileExistsAtPath.
849  NSFileManager* fileManager = [NSFileManager defaultManager];
850 
851  // This is the location where the test fixture places the snapshot file.
852  // For applications built by Flutter tool, this is in "App.framework".
853  NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
854 
855  if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
856  return;
857  }
858 
859  FlutterEngineAOTDataSource source = {};
860  source.type = kFlutterEngineAOTDataSourceTypeElfPath;
861  source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
862 
863  auto result = _embedderAPI.CreateAOTData(&source, &_aotData);
864  if (result != kSuccess) {
865  NSLog(@"Failed to load AOT data from: %@", elfPath);
866  }
867 }
868 
869 - (void)registerViewController:(FlutterViewController*)controller
870  forIdentifier:(FlutterViewIdentifier)viewIdentifier {
871  _macOSCompositor->AddView(viewIdentifier);
872  NSAssert(controller != nil, @"The controller must not be nil.");
873  if (!_multiViewEnabled) {
874  NSAssert(controller.engine == nil,
875  @"The FlutterViewController is unexpectedly attached to "
876  @"engine %@ before initialization.",
877  controller.engine);
878  }
879  NSAssert([_viewControllers objectForKey:@(viewIdentifier)] == nil,
880  @"The requested view ID is occupied.");
881  [_viewControllers setObject:controller forKey:@(viewIdentifier)];
882  [controller setUpWithEngine:self viewIdentifier:viewIdentifier];
883  NSAssert(controller.viewIdentifier == viewIdentifier, @"Failed to assign view ID.");
884  // Verify that the controller's property are updated accordingly. Failing the
885  // assertions is likely because either the FlutterViewController or the
886  // FlutterEngine is mocked. Please subclass these classes instead.
887  NSAssert(controller.attached, @"The FlutterViewController should switch to the attached mode "
888  @"after it is added to a FlutterEngine.");
889  NSAssert(controller.engine == self,
890  @"The FlutterViewController was added to %@, but its engine unexpectedly became %@.",
891  self, controller.engine);
892 
893  if (controller.viewLoaded) {
894  [self viewControllerViewDidLoad:controller];
895  }
896 
897  if (viewIdentifier != kFlutterImplicitViewId) {
898  // These will be overriden immediately after the FlutterView is created
899  // by actual values.
900  FlutterWindowMetricsEvent metrics{
901  .struct_size = sizeof(FlutterWindowMetricsEvent),
902  .width = 0,
903  .height = 0,
904  .pixel_ratio = 1.0,
905  };
906  bool added = false;
907  FlutterAddViewInfo info{.struct_size = sizeof(FlutterAddViewInfo),
908  .view_id = viewIdentifier,
909  .view_metrics = &metrics,
910  .user_data = &added,
911  .add_view_callback = [](const FlutterAddViewResult* r) {
912  auto added = reinterpret_cast<bool*>(r->user_data);
913  *added = true;
914  }};
915  // The callback should be called synchronously from platform thread.
916  _embedderAPI.AddView(_engine, &info);
917  FML_DCHECK(added);
918  if (!added) {
919  NSLog(@"Failed to add view with ID %llu", viewIdentifier);
920  }
921  }
922 }
923 
924 - (void)viewControllerViewDidLoad:(FlutterViewController*)viewController {
925  __weak FlutterEngine* weakSelf = self;
926  FlutterTimeConverter* timeConverter = [[FlutterTimeConverter alloc] initWithEngine:self];
927  FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc]
928  initWithDisplayLink:[FlutterDisplayLink displayLinkWithView:viewController.view]
929  block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
930  uintptr_t baton) {
931  uint64_t timeNanos = [timeConverter CAMediaTimeToEngineTime:timestamp];
932  uint64_t targetTimeNanos =
933  [timeConverter CAMediaTimeToEngineTime:targetTimestamp];
934  FlutterEngine* engine = weakSelf;
935  if (engine) {
936  engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
937  }
938  }];
939  @synchronized(_vsyncWaiters) {
940  FML_DCHECK([_vsyncWaiters objectForKey:@(viewController.viewIdentifier)] == nil);
941  [_vsyncWaiters setObject:waiter forKey:@(viewController.viewIdentifier)];
942  }
943 }
944 
945 - (void)deregisterViewControllerForIdentifier:(FlutterViewIdentifier)viewIdentifier {
946  if (viewIdentifier != kFlutterImplicitViewId) {
947  bool removed = false;
948  FlutterRemoveViewInfo info;
949  info.struct_size = sizeof(FlutterRemoveViewInfo);
950  info.view_id = viewIdentifier;
951  info.user_data = &removed;
952  // RemoveViewCallback is not finished synchronously, the remove_view_callback
953  // is called from raster thread when the engine knows for sure that the resources
954  // associated with the view are no longer needed.
955  info.remove_view_callback = [](const FlutterRemoveViewResult* r) {
956  auto removed = reinterpret_cast<bool*>(r->user_data);
957  [FlutterRunLoop.mainRunLoop performBlock:^{
958  *removed = true;
959  }];
960  };
961  _embedderAPI.RemoveView(_engine, &info);
962  while (!removed) {
963  [[FlutterRunLoop mainRunLoop] pollFlutterMessagesOnce];
964  }
965  }
966 
967  _macOSCompositor->RemoveView(viewIdentifier);
968 
969  FlutterViewController* controller = [self viewControllerForIdentifier:viewIdentifier];
970  // The controller can be nil. The engine stores only a weak ref, and this
971  // method could have been called from the controller's dealloc.
972  if (controller != nil) {
973  [controller detachFromEngine];
974  NSAssert(!controller.attached,
975  @"The FlutterViewController unexpectedly stays attached after being removed. "
976  @"In unit tests, this is likely because either the FlutterViewController or "
977  @"the FlutterEngine is mocked. Please subclass these classes instead.");
978  }
979  [_viewControllers removeObjectForKey:@(viewIdentifier)];
980 
981  FlutterVSyncWaiter* waiter = nil;
982  @synchronized(_vsyncWaiters) {
983  waiter = [_vsyncWaiters objectForKey:@(viewIdentifier)];
984  [_vsyncWaiters removeObjectForKey:@(viewIdentifier)];
985  }
986  [waiter invalidate];
987 }
988 
989 - (void)shutDownIfNeeded {
990  if ([_viewControllers count] == 0 && !_allowHeadlessExecution) {
991  [self shutDownEngine];
992  }
993 }
994 
995 - (FlutterViewController*)viewControllerForIdentifier:(FlutterViewIdentifier)viewIdentifier {
996  FlutterViewController* controller = [_viewControllers objectForKey:@(viewIdentifier)];
997  NSAssert(controller == nil || controller.viewIdentifier == viewIdentifier,
998  @"The stored controller has unexpected view ID.");
999  return controller;
1000 }
1001 
1002 - (void)setViewController:(FlutterViewController*)controller {
1003  FlutterViewController* currentController =
1004  [_viewControllers objectForKey:@(kFlutterImplicitViewId)];
1005  if (currentController == controller) {
1006  // From nil to nil, or from non-nil to the same controller.
1007  return;
1008  }
1009  if (currentController == nil && controller != nil) {
1010  // From nil to non-nil.
1011  NSAssert(controller.engine == nil,
1012  @"Failed to set view controller to the engine: "
1013  @"The given FlutterViewController is already attached to an engine %@. "
1014  @"If you wanted to create an FlutterViewController and set it to an existing engine, "
1015  @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
1016  controller.engine);
1017  [self registerViewController:controller forIdentifier:kFlutterImplicitViewId];
1018  } else if (currentController != nil && controller == nil) {
1019  NSAssert(currentController.viewIdentifier == kFlutterImplicitViewId,
1020  @"The default controller has an unexpected ID %llu", currentController.viewIdentifier);
1021  // From non-nil to nil.
1022  [self deregisterViewControllerForIdentifier:kFlutterImplicitViewId];
1023  [self shutDownIfNeeded];
1024  } else {
1025  // From non-nil to a different non-nil view controller.
1026  NSAssert(NO,
1027  @"Failed to set view controller to the engine: "
1028  @"The engine already has an implicit view controller %@. "
1029  @"If you wanted to make the implicit view render in a different window, "
1030  @"you should attach the current view controller to the window instead.",
1031  [_viewControllers objectForKey:@(kFlutterImplicitViewId)]);
1032  }
1033 }
1034 
1035 - (FlutterViewController*)viewController {
1036  return [self viewControllerForIdentifier:kFlutterImplicitViewId];
1037 }
1038 
1039 - (FlutterCompositor*)createFlutterCompositor {
1040  _compositor = {};
1041  _compositor.struct_size = sizeof(FlutterCompositor);
1042  _compositor.user_data = _macOSCompositor.get();
1043 
1044  _compositor.create_backing_store_callback = [](const FlutterBackingStoreConfig* config, //
1045  FlutterBackingStore* backing_store_out, //
1046  void* user_data //
1047  ) {
1048  return reinterpret_cast<flutter::FlutterCompositor*>(user_data)->CreateBackingStore(
1049  config, backing_store_out);
1050  };
1051 
1052  _compositor.collect_backing_store_callback = [](const FlutterBackingStore* backing_store, //
1053  void* user_data //
1054  ) { return true; };
1055 
1056  _compositor.present_view_callback = [](const FlutterPresentViewInfo* info) {
1057  return reinterpret_cast<flutter::FlutterCompositor*>(info->user_data)
1058  ->Present(info->view_id, info->layers, info->layers_count);
1059  };
1060 
1061  _compositor.avoid_backing_store_cache = true;
1062 
1063  return &_compositor;
1064 }
1065 
1066 - (id<FlutterBinaryMessenger>)binaryMessenger {
1067  return _binaryMessenger;
1068 }
1069 
1070 #pragma mark - Framework-internal methods
1071 
1072 - (void)addViewController:(FlutterViewController*)controller {
1073  if (!_multiViewEnabled) {
1074  // When multiview is disabled, the engine will only assign views to the implicit view ID.
1075  // The implicit view ID can be reused if and only if the implicit view is unassigned.
1076  NSAssert(self.viewController == nil,
1077  @"The engine already has a view controller for the implicit view.");
1078  self.viewController = controller;
1079  } else {
1080  // When multiview is enabled, the engine will assign views to a self-incrementing ID.
1081  // The implicit view ID can not be reused.
1082  FlutterViewIdentifier viewIdentifier = _nextViewIdentifier++;
1083  [self registerViewController:controller forIdentifier:viewIdentifier];
1084  }
1085 }
1086 
1087 - (void)enableMultiView {
1088  if (!_multiViewEnabled) {
1089  NSAssert(self.viewController == nil,
1090  @"Multiview can only be enabled before adding any view controllers.");
1091  _multiViewEnabled = YES;
1092  }
1093 }
1094 
1095 - (void)windowDidBecomeKey:(FlutterViewIdentifier)viewIdentifier {
1096  FlutterViewFocusEvent event{
1097  .struct_size = sizeof(FlutterViewFocusEvent),
1098  .view_id = viewIdentifier,
1099  .state = kFocused,
1100  .direction = kUndefined,
1101  };
1102  _embedderAPI.SendViewFocusEvent(_engine, &event);
1103 }
1104 
1105 - (void)windowDidResignKey:(FlutterViewIdentifier)viewIdentifier {
1106  FlutterViewFocusEvent event{
1107  .struct_size = sizeof(FlutterViewFocusEvent),
1108  .view_id = viewIdentifier,
1109  .state = kUnfocused,
1110  .direction = kUndefined,
1111  };
1112  _embedderAPI.SendViewFocusEvent(_engine, &event);
1113 }
1114 
1115 - (void)removeViewController:(nonnull FlutterViewController*)viewController {
1116  [self deregisterViewControllerForIdentifier:viewController.viewIdentifier];
1117  [self shutDownIfNeeded];
1118 }
1119 
1120 - (BOOL)running {
1121  return _engine != nullptr;
1122 }
1123 
1124 - (void)updateDisplayConfig:(NSNotification*)notification {
1125  [self updateDisplayConfig];
1126 }
1127 
1128 - (NSArray<NSScreen*>*)screens {
1129  return [NSScreen screens];
1130 }
1131 
1132 - (void)updateDisplayConfig {
1133  if (!_engine) {
1134  return;
1135  }
1136 
1137  std::vector<FlutterEngineDisplay> displays;
1138  for (NSScreen* screen : [self screens]) {
1139  CGDirectDisplayID displayID =
1140  static_cast<CGDirectDisplayID>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
1141 
1142  double devicePixelRatio = screen.backingScaleFactor;
1143  FlutterEngineDisplay display;
1144  display.struct_size = sizeof(display);
1145  display.display_id = displayID;
1146  display.single_display = false;
1147  display.width = static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
1148  display.height = static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
1149  display.device_pixel_ratio = devicePixelRatio;
1150 
1151  CVDisplayLinkRef displayLinkRef = nil;
1152  CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
1153 
1154  if (error == 0) {
1155  CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
1156  if (!(nominal.flags & kCVTimeIsIndefinite)) {
1157  double refreshRate = static_cast<double>(nominal.timeScale) / nominal.timeValue;
1158  display.refresh_rate = round(refreshRate);
1159  }
1160  CVDisplayLinkRelease(displayLinkRef);
1161  } else {
1162  display.refresh_rate = 0;
1163  }
1164 
1165  displays.push_back(display);
1166  }
1167  _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
1168  displays.data(), displays.size());
1169 }
1170 
1171 - (void)onSettingsChanged:(NSNotification*)notification {
1172  // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015.
1173  NSString* brightness =
1174  [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
1175  [_settingsChannel sendMessage:@{
1176  @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
1177  // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32006.
1178  @"textScaleFactor" : @1.0,
1179  @"alwaysUse24HourFormat" : @([FlutterHourFormat isAlwaysUse24HourFormat]),
1180  }];
1181 }
1182 
1183 - (void)sendInitialSettings {
1184  // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015.
1185  [[NSDistributedNotificationCenter defaultCenter]
1186  addObserver:self
1187  selector:@selector(onSettingsChanged:)
1188  name:@"AppleInterfaceThemeChangedNotification"
1189  object:nil];
1190  [self onSettingsChanged:nil];
1191 }
1192 
1193 - (FlutterEngineProcTable&)embedderAPI {
1194  return _embedderAPI;
1195 }
1196 
1197 - (nonnull NSString*)executableName {
1198  return [[[NSProcessInfo processInfo] arguments] firstObject] ?: @"Flutter";
1199 }
1200 
1201 - (void)updateWindowMetricsForViewController:(FlutterViewController*)viewController {
1202  if (!_engine || !viewController || !viewController.viewLoaded) {
1203  return;
1204  }
1205  NSAssert([self viewControllerForIdentifier:viewController.viewIdentifier] == viewController,
1206  @"The provided view controller is not attached to this engine.");
1207  FlutterView* view = viewController.flutterView;
1208  CGRect scaledBounds = [view convertRectToBacking:view.bounds];
1209  CGSize scaledSize = scaledBounds.size;
1210  double pixelRatio = view.layer.contentsScale;
1211  auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
1212  FlutterWindowMetricsEvent windowMetricsEvent = {
1213  .struct_size = sizeof(windowMetricsEvent),
1214  .width = static_cast<size_t>(scaledSize.width),
1215  .height = static_cast<size_t>(scaledSize.height),
1216  .pixel_ratio = pixelRatio,
1217  .left = static_cast<size_t>(scaledBounds.origin.x),
1218  .top = static_cast<size_t>(scaledBounds.origin.y),
1219  .display_id = static_cast<uint64_t>(displayId),
1220  .view_id = viewController.viewIdentifier,
1221  };
1222  if (view.sizedToContents) {
1223  CGSize maximumContentSize = [view convertSizeToBacking:view.maximumContentSize];
1224  CGSize minimumContentSize = [view convertSizeToBacking:view.minimumContentSize];
1225  windowMetricsEvent.has_constraints = true;
1226  windowMetricsEvent.min_width_constraint = static_cast<size_t>(minimumContentSize.width);
1227  windowMetricsEvent.min_height_constraint = static_cast<size_t>(minimumContentSize.height);
1228  windowMetricsEvent.max_width_constraint = static_cast<size_t>(maximumContentSize.width);
1229  windowMetricsEvent.max_height_constraint = static_cast<size_t>(maximumContentSize.height);
1230  } else {
1231  windowMetricsEvent.min_width_constraint = static_cast<size_t>(scaledSize.width);
1232  windowMetricsEvent.min_height_constraint = static_cast<size_t>(scaledSize.height);
1233  windowMetricsEvent.max_width_constraint = static_cast<size_t>(scaledSize.width);
1234  windowMetricsEvent.max_height_constraint = static_cast<size_t>(scaledSize.height);
1235  }
1236  _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
1237 }
1238 
1239 - (void)sendPointerEvent:(const FlutterPointerEvent&)event {
1240  _embedderAPI.SendPointerEvent(_engine, &event, 1);
1241  _lastViewWithPointerEvent = [self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView;
1242 }
1243 
1244 - (void)setSemanticsEnabled:(BOOL)enabled {
1245  if (_semanticsEnabled == enabled) {
1246  return;
1247  }
1248  _semanticsEnabled = enabled;
1249 
1250  // Update all view controllers' bridges.
1251  NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1252  FlutterViewController* nextViewController;
1253  while ((nextViewController = [viewControllerEnumerator nextObject])) {
1254  [nextViewController notifySemanticsEnabledChanged];
1255  }
1256 
1257  _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
1258 }
1259 
1260 - (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
1261  toTarget:(uint16_t)target
1262  withData:(fml::MallocMapping)data {
1263  _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
1264 }
1265 
1266 - (FlutterPlatformViewController*)platformViewController {
1267  return _platformViewController;
1268 }
1269 
1270 #pragma mark - Private methods
1271 
1272 - (void)sendUserLocales {
1273  if (!self.running) {
1274  return;
1275  }
1276 
1277  // Create a list of FlutterLocales corresponding to the preferred languages.
1278  NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
1279  std::vector<FlutterLocale> flutterLocales;
1280  flutterLocales.reserve(locales.count);
1281  for (NSString* localeID in [NSLocale preferredLanguages]) {
1282  NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
1283  [locales addObject:locale];
1284  flutterLocales.push_back(FlutterLocaleFromNSLocale(locale));
1285  }
1286  // Convert to a list of pointers, and send to the engine.
1287  std::vector<const FlutterLocale*> flutterLocaleList;
1288  flutterLocaleList.reserve(flutterLocales.size());
1289  std::transform(flutterLocales.begin(), flutterLocales.end(),
1290  std::back_inserter(flutterLocaleList),
1291  [](const auto& arg) -> const auto* { return &arg; });
1292  _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
1293 }
1294 
1295 - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
1296  NSData* messageData = nil;
1297  if (message->message_size > 0) {
1298  messageData = [NSData dataWithBytesNoCopy:(void*)message->message
1299  length:message->message_size
1300  freeWhenDone:NO];
1301  }
1302  NSString* channel = @(message->channel);
1303  __block const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
1304  __block FlutterEngine* weakSelf = self;
1305  NSMutableArray* isResponseValid = self.isResponseValid;
1306  FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
1307  _embedderAPI.SendPlatformMessageResponse;
1308  FlutterBinaryReply binaryResponseHandler = ^(NSData* response) {
1309  @synchronized(isResponseValid) {
1310  if (![isResponseValid[0] boolValue]) {
1311  // Ignore, engine was killed.
1312  return;
1313  }
1314  if (responseHandle) {
1315  sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
1316  static_cast<const uint8_t*>(response.bytes), response.length);
1317  responseHandle = NULL;
1318  } else {
1319  NSLog(@"Error: Message responses can be sent only once. Ignoring duplicate response "
1320  "on channel '%@'.",
1321  channel);
1322  }
1323  }
1324  };
1325 
1326  FlutterEngineHandlerInfo* handlerInfo = _messengerHandlers[channel];
1327  if (handlerInfo) {
1328  handlerInfo.handler(messageData, binaryResponseHandler);
1329  } else {
1330  binaryResponseHandler(nil);
1331  }
1332 }
1333 
1334 - (void)engineCallbackOnPreEngineRestart {
1335  NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1336  FlutterViewController* nextViewController;
1337  while ((nextViewController = [viewControllerEnumerator nextObject])) {
1338  [nextViewController onPreEngineRestart];
1339  }
1340  [_windowController closeAllWindows];
1341  [_platformViewController reset];
1342  _keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:self];
1343 }
1344 
1345 // This will be called on UI thread, which maybe or may not be platform thread,
1346 // depending on the configuration.
1347 - (void)onVSync:(uintptr_t)baton {
1348  auto block = ^{
1349  // TODO(knopp): Use vsync waiter for correct view.
1350  // https://github.com/flutter/flutter/issues/142845
1351  FlutterVSyncWaiter* waiter =
1352  [_vsyncWaiters objectForKey:[_vsyncWaiters.keyEnumerator nextObject]];
1353  if (waiter != nil) {
1354  [waiter waitForVSync:baton];
1355  } else {
1356  // Sometimes there is a vsync request right after the last view is removed.
1357  // It still need to be handled, otherwise the engine will stop producing frames
1358  // even if a new view is added later.
1359  self.embedderAPI.OnVsync(_engine, baton, 0, 0);
1360  }
1361  };
1362  if ([NSThread isMainThread]) {
1363  block();
1364  } else {
1365  [FlutterRunLoop.mainRunLoop performBlock:block];
1366  }
1367 }
1368 
1369 /**
1370  * Note: Called from dealloc. Should not use accessors or other methods.
1371  */
1372 - (void)shutDownEngine {
1373  if (_engine == nullptr) {
1374  return;
1375  }
1376 
1377  FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
1378  if (result != kSuccess) {
1379  NSLog(@"Could not de-initialize the Flutter engine: error %d", result);
1380  }
1381 
1382  result = _embedderAPI.Shutdown(_engine);
1383  if (result != kSuccess) {
1384  NSLog(@"Failed to shut down Flutter engine: error %d", result);
1385  }
1386  _engine = nullptr;
1387 }
1388 
1389 - (int64_t)engineIdentifier {
1390  return reinterpret_cast<int64_t>((__bridge void*)self);
1391 }
1392 
1393 + (FlutterEngine*)engineForIdentifier:(int64_t)identifier {
1394  NSAssert([[NSThread currentThread] isMainThread], @"Must be called on the main thread.");
1395  return (__bridge FlutterEngine*)reinterpret_cast<void*>(identifier);
1396 }
1397 
1398 - (void)setUpPlatformViewChannel {
1400  [FlutterMethodChannel methodChannelWithName:@"flutter/platform_views"
1401  binaryMessenger:self.binaryMessenger
1402  codec:[FlutterStandardMethodCodec sharedInstance]];
1403 
1404  __weak FlutterEngine* weakSelf = self;
1405  [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1406  [[weakSelf platformViewController] handleMethodCall:call result:result];
1407  }];
1408 }
1409 
1410 - (void)setUpAccessibilityChannel {
1412  messageChannelWithName:@"flutter/accessibility"
1413  binaryMessenger:self.binaryMessenger
1415  __weak FlutterEngine* weakSelf = self;
1416  [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
1417  [weakSelf handleAccessibilityEvent:message];
1418  }];
1419 }
1420 - (void)setUpNotificationCenterListeners {
1421  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1422  // macOS fires this private message when VoiceOver turns on or off.
1423  [center addObserver:self
1424  selector:@selector(onAccessibilityStatusChanged:)
1425  name:kEnhancedUserInterfaceNotification
1426  object:nil];
1427  [center addObserver:self
1428  selector:@selector(applicationWillTerminate:)
1429  name:NSApplicationWillTerminateNotification
1430  object:nil];
1431  [center addObserver:self
1432  selector:@selector(windowDidChangeScreen:)
1433  name:NSWindowDidChangeScreenNotification
1434  object:nil];
1435  [center addObserver:self
1436  selector:@selector(updateDisplayConfig:)
1437  name:NSApplicationDidChangeScreenParametersNotification
1438  object:nil];
1439 }
1440 
1441 - (void)addInternalPlugins {
1442  __weak FlutterEngine* weakSelf = self;
1443  [FlutterMouseCursorPlugin registerWithRegistrar:[self registrarForPlugin:@"mousecursor"]
1444  delegate:self];
1445  [FlutterMenuPlugin registerWithRegistrar:[self registrarForPlugin:@"menu"]];
1446 
1448  [FlutterBasicMessageChannel messageChannelWithName:kFlutterSettingsChannel
1449  binaryMessenger:self.binaryMessenger
1452  [FlutterMethodChannel methodChannelWithName:kFlutterPlatformChannel
1453  binaryMessenger:self.binaryMessenger
1454  codec:[FlutterJSONMethodCodec sharedInstance]];
1455  [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1456  [weakSelf handleMethodCall:call result:result];
1457  }];
1458 
1460  [FlutterMethodChannel methodChannelWithName:@"flutter/screenshot"
1461  binaryMessenger:self.binaryMessenger
1462  codec:[FlutterStandardMethodCodec sharedInstance]];
1463  [_screenshotChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
1464  FlutterEngine* strongSelf = weakSelf;
1465  if (!strongSelf) {
1466  return result([FlutterError errorWithCode:@"invalid_state"
1467  message:@"Engine deallocated."
1468  details:nil]);
1469  }
1470 
1471  FlutterViewController* viewController =
1472  [strongSelf viewControllerForIdentifier:flutter::kFlutterImplicitViewId];
1473  if (!viewController) {
1474  return result([FlutterError errorWithCode:@"failure"
1475  message:@"No view controller."
1476  details:nil]);
1477  }
1478 
1479  NSArray<FlutterSurface*>* frontSurfaces =
1480  viewController.flutterView.surfaceManager.frontSurfaces;
1481  if (frontSurfaces.count == 0) {
1482  return result([FlutterError errorWithCode:@"failure"
1483  message:@"No front surfaces."
1484  details:nil]);
1485  }
1486 
1487  // Use the first front surface (the main backing store).
1488  FlutterSurface* surface = frontSurfaces.firstObject;
1489  IOSurfaceRef ioSurface = surface.ioSurface;
1490 
1491  size_t width = IOSurfaceGetWidth(ioSurface);
1492  size_t height = IOSurfaceGetHeight(ioSurface);
1493  size_t bytesPerRow = IOSurfaceGetBytesPerRow(ioSurface);
1494  size_t bytesPerElement = IOSurfaceGetBytesPerElement(ioSurface);
1495  uint32_t pixelFormat = (uint32_t)IOSurfaceGetPixelFormat(ioSurface);
1496 
1497  NSString* formatString;
1498  switch (pixelFormat) {
1499  case kCVPixelFormatType_40ARGBLEWideGamut:
1500  formatString = @"MTLPixelFormatBGRA10_XR";
1501  break;
1502  case kCVPixelFormatType_32BGRA:
1503  formatString = @"MTLPixelFormatBGRA8Unorm";
1504  break;
1505  default:
1506  formatString = [NSString stringWithFormat:@"Unknown(%u)", pixelFormat];
1507  break;
1508  }
1509 
1510  IOSurfaceLock(ioSurface, kIOSurfaceLockReadOnly, nil);
1511  void* baseAddress = IOSurfaceGetBaseAddress(ioSurface);
1512 
1513  // Copy pixel data row by row into a tightly-packed buffer.
1514  size_t packedBytesPerRow = width * bytesPerElement;
1515  NSMutableData* packedData = [NSMutableData dataWithLength:packedBytesPerRow * height];
1516  uint8_t* dest = (uint8_t*)packedData.mutableBytes;
1517  for (size_t row = 0; row < height; row++) {
1518  memcpy(dest + row * packedBytesPerRow, (uint8_t*)baseAddress + row * bytesPerRow,
1519  packedBytesPerRow);
1520  }
1521 
1522  IOSurfaceUnlock(ioSurface, kIOSurfaceLockReadOnly, nil);
1523 
1524  return result(@[
1525  @(width),
1526  @(height),
1527  formatString,
1529  ]);
1530  }];
1531 }
1532 
1533 - (void)didUpdateMouseCursor:(NSCursor*)cursor {
1534  // Mouse cursor plugin does not specify which view is responsible for changing the cursor,
1535  // so the reasonable assumption here is that cursor change is a result of a mouse movement
1536  // and thus the cursor will be paired with last Flutter view that reveived mouse event.
1537  [_lastViewWithPointerEvent didUpdateMouseCursor:cursor];
1538 }
1539 
1540 - (void)applicationWillTerminate:(NSNotification*)notification {
1541  [self shutDownEngine];
1542 }
1543 
1544 - (void)windowDidChangeScreen:(NSNotification*)notification {
1545  // Update window metric for all view controllers since the display_id has
1546  // changed.
1547  NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1548  FlutterViewController* nextViewController;
1549  while ((nextViewController = [viewControllerEnumerator nextObject])) {
1550  [self updateWindowMetricsForViewController:nextViewController];
1551  [nextViewController updateWideGamutForScreen];
1552  }
1553 }
1554 
1555 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1556  BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
1557  NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
1558  FlutterViewController* nextViewController;
1559  while ((nextViewController = [viewControllerEnumerator nextObject])) {
1560  [nextViewController onAccessibilityStatusChanged:enabled];
1561  }
1562 
1563  self.semanticsEnabled = enabled;
1564 }
1565 - (void)handleAccessibilityEvent:(NSDictionary<NSString*, id>*)annotatedEvent {
1566  NSString* type = annotatedEvent[@"type"];
1567  if ([type isEqualToString:@"announce"]) {
1568  NSString* message = annotatedEvent[@"data"][@"message"];
1569  NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
1570  if (message == nil) {
1571  return;
1572  }
1573 
1574  NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
1575  ? NSAccessibilityPriorityHigh
1576  : NSAccessibilityPriorityMedium;
1577 
1578  [self announceAccessibilityMessage:message withPriority:priority];
1579  }
1580 }
1581 
1582 - (void)announceAccessibilityMessage:(NSString*)message
1583  withPriority:(NSAccessibilityPriorityLevel)priority {
1584  NSAccessibilityPostNotificationWithUserInfo(
1585  [self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView,
1586  NSAccessibilityAnnouncementRequestedNotification,
1587  @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
1588 }
1589 - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
1590  if ([call.method isEqualToString:@"SystemNavigator.pop"]) {
1591  [[NSApplication sharedApplication] terminate:self];
1592  result(nil);
1593  } else if ([call.method isEqualToString:@"SystemSound.play"]) {
1594  [self playSystemSound:call.arguments];
1595  result(nil);
1596  } else if ([call.method isEqualToString:@"Clipboard.getData"]) {
1597  result([self getClipboardData:call.arguments]);
1598  } else if ([call.method isEqualToString:@"Clipboard.setData"]) {
1599  [self setClipboardData:call.arguments];
1600  result(nil);
1601  } else if ([call.method isEqualToString:@"Clipboard.hasStrings"]) {
1602  result(@{@"value" : @([self clipboardHasStrings])});
1603  } else if ([call.method isEqualToString:@"System.exitApplication"]) {
1604  if ([self terminationHandler] == nil) {
1605  // If the termination handler isn't set, then either we haven't
1606  // initialized it yet, or (more likely) the NSApp delegate isn't a
1607  // FlutterAppDelegate, so it can't cancel requests to exit. So, in that
1608  // case, just terminate when requested.
1609  [NSApp terminate:self];
1610  result(nil);
1611  } else {
1612  [[self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
1613  }
1614  } else if ([call.method isEqualToString:@"System.initializationComplete"]) {
1615  if ([self terminationHandler] != nil) {
1616  [self terminationHandler].acceptingRequests = YES;
1617  }
1618  result(nil);
1619  } else {
1621  }
1622 }
1623 
1624 - (void)playSystemSound:(NSString*)soundType {
1625  if ([soundType isEqualToString:@"SystemSoundType.alert"]) {
1626  NSBeep();
1627  }
1628 }
1629 
1630 - (NSDictionary*)getClipboardData:(NSString*)format {
1631  if ([format isEqualToString:@(kTextPlainFormat)]) {
1632  NSString* stringInPasteboard = [self.pasteboard stringForType:NSPasteboardTypeString];
1633  return stringInPasteboard == nil ? nil : @{@"text" : stringInPasteboard};
1634  }
1635  return nil;
1636 }
1637 
1638 - (void)setClipboardData:(NSDictionary*)data {
1639  NSString* text = data[@"text"];
1640  [self.pasteboard clearContents];
1641  if (text && ![text isEqual:[NSNull null]]) {
1642  [self.pasteboard setString:text forType:NSPasteboardTypeString];
1643  }
1644 }
1645 
1646 - (BOOL)clipboardHasStrings {
1647  return [self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
1648 }
1649 
1650 - (std::vector<std::string>)switches {
1652 }
1653 
1654 #pragma mark - FlutterAppLifecycleDelegate
1655 
1656 - (void)setApplicationState:(flutter::AppLifecycleState)state {
1657  NSString* nextState =
1658  [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
1659  [self sendOnChannel:kFlutterLifecycleChannel
1660  message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
1661 }
1662 
1663 /**
1664  * Called when the |FlutterAppDelegate| gets the applicationWillBecomeActive
1665  * notification.
1666  */
1667 - (void)handleWillBecomeActive:(NSNotification*)notification {
1668  _active = YES;
1669  // occlusionState can latch stale on an occlusion->visible transition (same-screen
1670  // Cmd-Tab / Mission Control), so `_visible` is unreliable here. Resume from
1671  // NSWindow.isVisible instead — NO for a minimized window, so it won't resume hidden.
1672  // https://github.com/flutter/flutter/issues/155977
1673  for (NSWindow* window in [NSApplication sharedApplication].windows) {
1674  if (window.isVisible) {
1675  _visible = YES;
1676  break;
1677  }
1678  }
1679  [self setApplicationState:_visible ? flutter::AppLifecycleState::kResumed
1680  : flutter::AppLifecycleState::kHidden];
1681 }
1682 
1683 /**
1684  * Called when the |FlutterAppDelegate| gets the applicationWillResignActive
1685  * notification.
1686  */
1687 - (void)handleWillResignActive:(NSNotification*)notification {
1688  _active = NO;
1689  if (!_visible) {
1690  [self setApplicationState:flutter::AppLifecycleState::kHidden];
1691  } else {
1692  [self setApplicationState:flutter::AppLifecycleState::kInactive];
1693  }
1694 }
1695 
1696 /**
1697  * Called when the application's occlusion state changes
1698  * (NSApplicationDidChangeOcclusionStateNotification).
1699  */
1700 - (void)handleDidChangeOcclusionState:(NSNotification*)notification {
1701  NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
1702  if (occlusionState & NSApplicationOcclusionStateVisible) {
1703  _visible = YES;
1704  if (_active) {
1705  [self setApplicationState:flutter::AppLifecycleState::kResumed];
1706  } else {
1707  [self setApplicationState:flutter::AppLifecycleState::kInactive];
1708  }
1709  } else {
1710  _visible = NO;
1711  [self setApplicationState:flutter::AppLifecycleState::kHidden];
1712  }
1713 }
1714 
1715 #pragma mark - FlutterBinaryMessenger
1716 
1717 - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
1718  [self sendOnChannel:channel message:message binaryReply:nil];
1719 }
1720 
1721 - (void)sendOnChannel:(NSString*)channel
1722  message:(NSData* _Nullable)message
1723  binaryReply:(FlutterBinaryReply _Nullable)callback {
1724  FlutterPlatformMessageResponseHandle* response_handle = nullptr;
1725  if (callback) {
1726  struct Captures {
1727  FlutterBinaryReply reply;
1728  };
1729  auto captures = std::make_unique<Captures>();
1730  captures->reply = callback;
1731  auto message_reply = [](const uint8_t* data, size_t data_size, void* user_data) {
1732  auto captures = reinterpret_cast<Captures*>(user_data);
1733  NSData* reply_data = nil;
1734  if (data != nullptr && data_size > 0) {
1735  reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
1736  }
1737  captures->reply(reply_data);
1738  delete captures;
1739  };
1740 
1741  FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
1742  _engine, message_reply, captures.get(), &response_handle);
1743  if (create_result != kSuccess) {
1744  NSLog(@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
1745  return;
1746  }
1747  captures.release();
1748  }
1749 
1750  FlutterPlatformMessage platformMessage = {
1751  .struct_size = sizeof(FlutterPlatformMessage),
1752  .channel = [channel UTF8String],
1753  .message = static_cast<const uint8_t*>(message.bytes),
1754  .message_size = message.length,
1755  .response_handle = response_handle,
1756  };
1757 
1758  FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
1759  if (message_result != kSuccess) {
1760  NSLog(@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
1761  message_result);
1762  }
1763 
1764  if (response_handle != nullptr) {
1765  FlutterEngineResult release_result =
1766  _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
1767  if (release_result != kSuccess) {
1768  NSLog(@"Failed to release the response handle (%d).", release_result);
1769  };
1770  }
1771 }
1772 
1773 - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(nonnull NSString*)channel
1774  binaryMessageHandler:
1775  (nullable FlutterBinaryMessageHandler)handler {
1777  _messengerHandlers[channel] =
1778  [[FlutterEngineHandlerInfo alloc] initWithConnection:@(_currentMessengerConnection)
1779  handler:[handler copy]];
1781 }
1782 
1783 - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection {
1784  // Find the _messengerHandlers that has the required connection, and record its
1785  // channel.
1786  NSString* foundChannel = nil;
1787  for (NSString* key in [_messengerHandlers allKeys]) {
1788  FlutterEngineHandlerInfo* handlerInfo = [_messengerHandlers objectForKey:key];
1789  if ([handlerInfo.connection isEqual:@(connection)]) {
1790  foundChannel = key;
1791  break;
1792  }
1793  }
1794  if (foundChannel) {
1795  [_messengerHandlers removeObjectForKey:foundChannel];
1796  }
1797 }
1798 
1799 #pragma mark - FlutterPluginRegistry
1800 
1801 - (id<FlutterPluginRegistrar>)registrarForPlugin:(NSString*)pluginName {
1802  id<FlutterPluginRegistrar> registrar = self.pluginRegistrars[pluginName];
1803  if (!registrar) {
1804  FlutterEngineRegistrar* registrarImpl =
1805  [[FlutterEngineRegistrar alloc] initWithPlugin:pluginName flutterEngine:self];
1806  self.pluginRegistrars[pluginName] = registrarImpl;
1807  registrar = registrarImpl;
1808  }
1809  return registrar;
1810 }
1811 
1812 - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
1813  return self.pluginRegistrars[pluginName].publishedValue;
1814 }
1815 
1816 #pragma mark - FlutterTextureRegistrar
1817 
1818 - (int64_t)registerTexture:(id<FlutterTexture>)texture {
1819  return [_renderer registerTexture:texture];
1820 }
1821 
1822 - (BOOL)registerTextureWithID:(int64_t)textureId {
1823  return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
1824 }
1825 
1826 - (void)textureFrameAvailable:(int64_t)textureID {
1827  [_renderer textureFrameAvailable:textureID];
1828 }
1829 
1830 - (BOOL)markTextureFrameAvailable:(int64_t)textureID {
1831  return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
1832 }
1833 
1834 - (void)unregisterTexture:(int64_t)textureID {
1835  [_renderer unregisterTexture:textureID];
1836 }
1837 
1838 - (BOOL)unregisterTextureWithID:(int64_t)textureID {
1839  return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
1840 }
1841 
1842 #pragma mark - Task runner integration
1843 
1844 - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
1845  __weak FlutterEngine* weakSelf = self;
1846 
1847  const auto engine_time = _embedderAPI.GetCurrentTime();
1848  [FlutterRunLoop.mainRunLoop
1849  performAfterDelay:(targetTime - (double)engine_time) / NSEC_PER_SEC
1850  block:^{
1851  FlutterEngine* self = weakSelf;
1852  if (self != nil && self->_engine != nil) {
1853  auto result = _embedderAPI.RunTask(self->_engine, &task);
1854  if (result != kSuccess) {
1855  NSLog(@"Could not post a task to the Flutter engine.");
1856  }
1857  }
1858  }];
1859 }
1860 
1861 // Getter used by test harness, only exposed through the FlutterEngine(Test) category
1862 - (flutter::FlutterCompositor*)macOSCompositor {
1863  return _macOSCompositor.get();
1864 }
1865 
1866 #pragma mark - FlutterKeyboardManagerDelegate
1867 
1868 /**
1869  * Dispatches the given pointer event data to engine.
1870  */
1871 - (void)sendKeyEvent:(const FlutterKeyEvent&)event
1872  callback:(FlutterKeyEventCallback)callback
1873  userData:(void*)userData {
1874  _embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
1875 }
1876 
1877 @end
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
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
BOOL _multiViewEnabled
FlutterCompositor _compositor
__weak FlutterView * _lastViewWithPointerEvent
FlutterKeyboardManager * _keyboardManager
FlutterWindowController * _windowController
FlutterTerminationCallback _terminator
constexpr char kTextPlainFormat[]
Clipboard plain text format.
__weak FlutterEngine * _flutterEngine
BOOL _visible
BOOL _active
FlutterBinaryMessengerRelay * _binaryMessenger
static NSString *const kEnhancedUserInterfaceKey
NSString *const kFlutterSettingsChannel
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterTerminationCallback)(id _Nullable sender)
int64_t FlutterViewIdentifier
NSString * lookupKeyForAsset:fromPackage:(NSString *asset,[fromPackage] NSString *package)
NSString * lookupKeyForAsset:(NSString *asset)
NSInteger clearContents()
instancetype messageChannelWithName:binaryMessenger:codec:(NSString *name,[binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger,[codec] NSObject< FlutterMessageCodec > *codec)
FlutterBinaryMessageHandler handler
id< FlutterBinaryMessenger > binaryMessenger
Definition: FlutterEngine.h:92
instancetype errorWithCode:message:details:(NSString *code,[message] NSString *_Nullable message,[details] id _Nullable details)
void registerWithRegistrar:(nonnull id< FlutterPluginRegistrar > registrar)
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)
FlutterViewIdentifier viewIdentifier
void onAccessibilityStatusChanged:(BOOL enabled)
BOOL sizedToContents
Definition: FlutterView.h:130
std::vector< std::string > GetSwitchesFromEnvironment()
instancetype sharedInstance()
void handleMethodCall:result:(FlutterMethodCall *call,[result] FlutterResult result)
void * user_data