Flutter iOS Embedder
FlutterDartProject.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 
5 #define FML_USED_ON_EMBEDDER
6 
8 
9 #import <Metal/Metal.h>
10 #import <UIKit/UIKit.h>
11 
12 #include <sstream>
13 
14 #include "flutter/common/constants.h"
15 #include "flutter/fml/build_config.h"
16 #include "flutter/shell/common/switches.h"
17 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
19 
21 
22 extern "C" {
23 #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
24 // Used for debugging dart:* sources.
25 extern const uint8_t kPlatformStrongDill[];
26 extern const intptr_t kPlatformStrongDillSize;
27 #endif
28 }
29 
30 static const char* kApplicationKernelSnapshotFileName = "kernel_blob.bin";
31 
33  static BOOL result = NO;
34  static dispatch_once_t once_token = 0;
35  dispatch_once(&once_token, ^{
36  id<MTLDevice> device = MTLCreateSystemDefaultDevice();
37  result = [device supportsFamily:MTLGPUFamilyApple2];
38  });
39  return result;
40 }
41 
42 NSNumber* _Nullable FLTEnableWideGamutFromBundle(NSBundle* _Nullable bundle,
43  NSBundle* _Nullable mainBundle) {
44  NSNumber* nsEnableWideGamut = [bundle objectForInfoDictionaryKey:@"FLTEnableWideGamut"];
45  if (nsEnableWideGamut == nil && bundle != mainBundle) {
46  nsEnableWideGamut = [mainBundle objectForInfoDictionaryKey:@"FLTEnableWideGamut"];
47  }
48  return nsEnableWideGamut;
49 }
50 
51 flutter::Settings FLTDefaultSettingsForBundle(NSBundle* bundle, NSProcessInfo* processInfoOrNil) {
52  auto command_line = flutter::CommandLineFromNSProcessInfo(processInfoOrNil);
53 
54  // Precedence:
55  // 1. Settings from the specified NSBundle.
56  // 2. Settings passed explicitly via command-line arguments.
57  // 3. Settings from the NSBundle with the default bundle ID.
58  // 4. Settings from the main NSBundle and default values.
59 
60  NSBundle* mainBundle = FLTGetApplicationBundle();
61  NSBundle* engineBundle = [NSBundle bundleForClass:[FlutterDartProject class]];
62 
63  bool hasExplicitBundle = bundle != nil;
64  if (bundle == nil) {
65  bundle = FLTFrameworkBundleWithIdentifier([FlutterDartProject defaultBundleIdentifier]);
66  }
67 
68  auto settings = flutter::SettingsFromCommandLine(command_line, true);
69 
70  FML_CHECK(settings.merged_platform_ui_thread !=
71  flutter::Settings::MergedPlatformUIThread::kMergeAfterLaunch)
72  << "merged-platform-ui-thread=mergeAfterLaunch is not supported on iOS.";
73 
74  settings.task_observer_add = [](intptr_t key, const fml::closure& callback) {
75  fml::TaskQueueId queue_id = fml::MessageLoop::GetCurrentTaskQueueId();
76  fml::MessageLoopTaskQueues::GetInstance()->AddTaskObserver(queue_id, key, callback);
77  return queue_id;
78  };
79 
80  settings.task_observer_remove = [](fml::TaskQueueId queue_id, intptr_t key) {
81  fml::MessageLoopTaskQueues::GetInstance()->RemoveTaskObserver(queue_id, key);
82  };
83 
84  settings.log_message_callback = [](const std::string& tag, const std::string& message) {
85  std::stringstream stream;
86  if (!tag.empty()) {
87  stream << tag << ": ";
88  }
89  stream << message;
90  std::string log = stream.str();
91  [FlutterLogger logDirect:[NSString stringWithUTF8String:log.c_str()]];
92  };
93 
94  settings.enable_platform_isolates = true;
95 
96  // The command line arguments may not always be complete. If they aren't, attempt to fill in
97  // defaults.
98 
99  // Flutter ships the ICU data file in the bundle of the engine. Look for it there.
100  if (settings.icu_data_path.empty()) {
101  NSString* icuDataPath = [engineBundle pathForResource:@"icudtl" ofType:@"dat"];
102  if (icuDataPath.length > 0) {
103  settings.icu_data_path = icuDataPath.UTF8String;
104  }
105  }
106 
107  if (flutter::DartVM::IsRunningPrecompiledCode()) {
108  if (hasExplicitBundle) {
109  NSString* executablePath = bundle.executablePath;
110  if ([[NSFileManager defaultManager] fileExistsAtPath:executablePath]) {
111  settings.application_library_paths.push_back(executablePath.UTF8String);
112  }
113  }
114 
115  // No application bundle specified. Try a known location from the main bundle's Info.plist.
116  if (settings.application_library_paths.empty()) {
117  NSString* libraryName = [mainBundle objectForInfoDictionaryKey:@"FLTLibraryPath"];
118  NSString* libraryPath = [mainBundle pathForResource:libraryName ofType:@""];
119  if (libraryPath.length > 0) {
120  NSString* executablePath = [NSBundle bundleWithPath:libraryPath].executablePath;
121  if (executablePath.length > 0) {
122  settings.application_library_paths.push_back(executablePath.UTF8String);
123  }
124  }
125  }
126 
127  // In case the application bundle is still not specified, look for the App.framework in the
128  // Frameworks directory.
129  if (settings.application_library_paths.empty()) {
130  NSString* applicationFrameworkPath = [mainBundle pathForResource:@"Frameworks/App.framework"
131  ofType:@""];
132  if (applicationFrameworkPath.length > 0) {
133  NSString* executablePath =
134  [NSBundle bundleWithPath:applicationFrameworkPath].executablePath;
135  if (executablePath.length > 0) {
136  settings.application_library_paths.push_back(executablePath.UTF8String);
137  }
138  }
139  }
140  }
141 
142  // Checks to see if the flutter assets directory is already present.
143  if (settings.assets_path.empty()) {
144  NSString* assetsPath = FLTAssetsPathFromBundle(bundle);
145 
146  if (assetsPath.length == 0) {
147  NSLog(@"Failed to find assets path for \"%@\"", bundle);
148  } else {
149  settings.assets_path = assetsPath.UTF8String;
150 
151  // Check if there is an application kernel snapshot in the assets directory we could
152  // potentially use. Looking for the snapshot makes sense only if we have a VM that can use
153  // it.
154  if (!flutter::DartVM::IsRunningPrecompiledCode()) {
155  NSURL* applicationKernelSnapshotURL =
156  [NSURL URLWithString:@(kApplicationKernelSnapshotFileName)
157  relativeToURL:[NSURL fileURLWithPath:assetsPath]];
158  NSError* error;
159  if ([applicationKernelSnapshotURL checkResourceIsReachableAndReturnError:&error]) {
160  settings.application_kernel_asset = applicationKernelSnapshotURL.path.UTF8String;
161  } else {
162  NSLog(@"Failed to find snapshot at %@: %@", applicationKernelSnapshotURL.path, error);
163  }
164  }
165  }
166  }
167 
168  // Domain network configuration
169  // Disabled in https://github.com/flutter/flutter/issues/72723.
170  // Re-enable in https://github.com/flutter/flutter/issues/54448.
171  settings.may_insecurely_connect_to_all_domains = true;
172  settings.domain_network_policy = "";
173 
174  // Whether to enable wide gamut colors.
175 #if TARGET_OS_SIMULATOR
176  // As of Xcode 14.1, the wide gamut surface pixel formats are not supported by
177  // the simulator.
178  settings.enable_wide_gamut = false;
179  // Removes unused function warning.
181 #else
182  NSNumber* nsEnableWideGamut = FLTEnableWideGamutFromBundle(bundle, mainBundle);
183  BOOL enableWideGamut =
184  (nsEnableWideGamut ? nsEnableWideGamut.boolValue : YES) && DoesHardwareSupportWideGamut();
185  settings.enable_wide_gamut = enableWideGamut;
186 #endif
187 
188  settings.warn_on_impeller_opt_out = true;
189 
190  NSNumber* nsEnableSDFs = [mainBundle objectForInfoDictionaryKey:@"FLTEnableSDFs"];
191  settings.impeller_use_sdfs = (nsEnableSDFs ? nsEnableSDFs.boolValue : NO);
192 
193  NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTTraceSystrace"];
194  // Change the default only if the option is present.
195  if (enableTraceSystrace != nil) {
196  settings.trace_systrace = enableTraceSystrace.boolValue;
197  }
198 
199  NSNumber* profileMicrotasks = [mainBundle objectForInfoDictionaryKey:@"FLTProfileMicrotasks"];
200  // Change the default only if the option is present.
201  if (profileMicrotasks != nil) {
202  settings.profile_microtasks = profileMicrotasks.boolValue;
203  }
204 
205  NSNumber* enableDartAsserts = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartAsserts"];
206  if (enableDartAsserts != nil) {
207  settings.dart_flags.push_back("--enable-asserts");
208  }
209 
210  NSNumber* enableDartProfiling = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartProfiling"];
211  // Change the default only if the option is present.
212  if (enableDartProfiling != nil) {
213  settings.enable_dart_profiling = enableDartProfiling.boolValue;
214  }
215 
216  NSNumber* profileStartup = [mainBundle objectForInfoDictionaryKey:@"FLTProfileStartup"];
217  // Change the default only if the option is present.
218  if (profileStartup != nil) {
219  settings.profile_startup = profileStartup.boolValue;
220  }
221 
222  // Leak Dart VM settings, set whether leave or clean up the VM after the last shell shuts down.
223  NSNumber* leakDartVM = [mainBundle objectForInfoDictionaryKey:@"FLTLeakDartVM"];
224  // It will change the default leak_vm value in settings only if the key exists.
225  if (leakDartVM != nil) {
226  settings.leak_vm = leakDartVM.boolValue;
227  }
228 
229  NSNumber* enableMergedPlatformUIThread =
230  [mainBundle objectForInfoDictionaryKey:@"FLTEnableMergedPlatformUIThread"];
231  if (enableMergedPlatformUIThread != nil) {
232  FML_CHECK(enableMergedPlatformUIThread.boolValue)
233  << "FLTEnableMergedPlatformUIThread=false is no longer allowed.";
234  }
235 
236  NSNumber* enableFlutterGPU = [mainBundle objectForInfoDictionaryKey:@"FLTEnableFlutterGPU"];
237  if (enableFlutterGPU != nil) {
238  settings.enable_flutter_gpu = enableFlutterGPU.boolValue;
239  }
240 
241 #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
242  // There are no ownership concerns here as all mappings are owned by the
243  // embedder and not the engine.
244  auto make_mapping_callback = [](const uint8_t* mapping, size_t size) {
245  return [mapping, size]() { return std::make_unique<fml::NonOwnedMapping>(mapping, size); };
246  };
247 
248  settings.dart_library_sources_kernel =
249  make_mapping_callback(kPlatformStrongDill, kPlatformStrongDillSize);
250 #endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
251 
252  // If we even support setting this e.g. from the command line or the plist,
253  // we should let the user override it.
254  // Otherwise, we want to set this to a value that will avoid having the OS
255  // kill us. On most iOS devices, that happens somewhere near half
256  // the available memory.
257  // The VM expects this value to be in megabytes.
258  if (settings.old_gen_heap_size <= 0) {
259  settings.old_gen_heap_size = std::round([NSProcessInfo processInfo].physicalMemory * .48 /
260  flutter::kMegaByteSizeInBytes);
261  }
262 
263  // This is the formula Android uses.
264  // https://android.googlesource.com/platform/frameworks/base/+/39ae5bac216757bc201490f4c7b8c0f63006c6cd/libs/hwui/renderthread/CacheManager.cpp#45
265  CGFloat scale = [UIScreen mainScreen].scale;
266  CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width * scale;
267  CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height * scale;
268  settings.resource_cache_max_bytes_threshold = screenWidth * screenHeight * 12 * 4;
269 
270  // Whether to run the iOS embedder on top of the embedder API rather than `Shell` directly.
271  //
272  // This is an opt-in flag while we add support for running on top of the embedder API. Once the
273  // embedder API implementation reaches parity with the default implementation directly on `Shell`
274  // and friends, we'll eventually make this default and support opt-out, before being removed
275  // altogether.
276  //
277  // See: https://github.com/flutter/flutter/issues/112232
278  NSNumber* enable_embedder_api =
279  [mainBundle objectForInfoDictionaryKey:@"FLTEnableIOSEmbedderAPI"];
280  // Change the default only if the option is present.
281  if (enable_embedder_api) {
282  settings.enable_embedder_api = enable_embedder_api.boolValue;
283  }
284 
285  return settings;
286 }
287 
288 @implementation FlutterDartProject {
289  flutter::Settings _settings;
290 }
291 
292 // This property is marked unavailable on iOS in the common header.
293 // That doesn't seem to be enough to prevent this property from being synthesized.
294 // Mark dynamic to avoid warnings.
295 @dynamic dartEntrypointArguments;
296 
297 #pragma mark - Override base class designated initializers
298 
299 - (instancetype)init {
300  return [self initWithPrecompiledDartBundle:nil];
301 }
302 
303 #pragma mark - Designated initializers
304 
305 - (instancetype)initWithPrecompiledDartBundle:(nullable NSBundle*)bundle {
306  self = [super init];
307 
308  if (self) {
309  _settings = FLTDefaultSettingsForBundle(bundle);
310  }
311 
312  return self;
313 }
314 
315 - (instancetype)initWithSettings:(const flutter::Settings&)settings {
316  self = [self initWithPrecompiledDartBundle:nil];
317 
318  if (self) {
319  _settings = settings;
320  }
321 
322  return self;
323 }
324 
325 #pragma mark - PlatformData accessors
326 
327 - (const flutter::PlatformData)defaultPlatformData {
328  flutter::PlatformData PlatformData;
329  PlatformData.lifecycle_state = std::string("AppLifecycleState.detached");
330  return PlatformData;
331 }
332 
333 #pragma mark - Settings accessors
334 
335 - (const flutter::Settings&)settings {
336  return _settings;
337 }
338 
339 - (flutter::RunConfiguration)runConfiguration {
340  return [self runConfigurationForEntrypoint:nil];
341 }
342 
343 - (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil {
344  return [self runConfigurationForEntrypoint:entrypointOrNil libraryOrNil:nil];
345 }
346 
347 - (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil
348  libraryOrNil:(nullable NSString*)dartLibraryOrNil {
349  return [self runConfigurationForEntrypoint:entrypointOrNil
350  libraryOrNil:dartLibraryOrNil
351  entrypointArgs:nil];
352 }
353 
354 - (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil
355  libraryOrNil:(nullable NSString*)dartLibraryOrNil
356  entrypointArgs:
357  (nullable NSArray<NSString*>*)entrypointArgs {
358  auto config = flutter::RunConfiguration::InferFromSettings(_settings);
359  if (dartLibraryOrNil && entrypointOrNil) {
360  config.SetEntrypointAndLibrary(std::string([entrypointOrNil UTF8String]),
361  std::string([dartLibraryOrNil UTF8String]));
362 
363  } else if (entrypointOrNil) {
364  config.SetEntrypoint(std::string([entrypointOrNil UTF8String]));
365  }
366 
367  if (entrypointArgs.count) {
368  std::vector<std::string> cppEntrypointArgs;
369  for (NSString* arg in entrypointArgs) {
370  cppEntrypointArgs.push_back(std::string([arg UTF8String]));
371  }
372  config.SetEntrypointArgs(std::move(cppEntrypointArgs));
373  }
374 
375  return config;
376 }
377 
378 #pragma mark - Assets-related utilities
379 
380 + (NSString*)flutterAssetsName:(NSBundle*)bundle {
381  if (bundle == nil) {
382  bundle = FLTFrameworkBundleWithIdentifier([FlutterDartProject defaultBundleIdentifier]);
383  }
384  return FLTAssetPath(bundle);
385 }
386 
387 + (NSString*)domainNetworkPolicy:(NSDictionary*)appTransportSecurity {
388  // https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsexceptiondomains
389  NSDictionary* exceptionDomains = appTransportSecurity[@"NSExceptionDomains"];
390  if (exceptionDomains == nil) {
391  return @"";
392  }
393  NSMutableArray* networkConfigArray = [[NSMutableArray alloc] init];
394  for (NSString* domain in exceptionDomains) {
395  NSDictionary* domainConfiguration = exceptionDomains[domain];
396  // Default value is false.
397  bool includesSubDomains = [domainConfiguration[@"NSIncludesSubdomains"] boolValue];
398  bool allowsCleartextCommunication =
399  [domainConfiguration[@"NSExceptionAllowsInsecureHTTPLoads"] boolValue];
400  [networkConfigArray addObject:@[
401  domain, includesSubDomains ? @YES : @NO, allowsCleartextCommunication ? @YES : @NO
402  ]];
403  }
404  NSData* jsonData = [NSJSONSerialization dataWithJSONObject:networkConfigArray
405  options:0
406  error:NULL];
407  return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
408 }
409 
410 + (bool)allowsArbitraryLoads:(NSDictionary*)appTransportSecurity {
411  return [appTransportSecurity[@"NSAllowsArbitraryLoads"] boolValue];
412 }
413 
414 + (NSString*)lookupKeyForAsset:(NSString*)asset {
415  return [self lookupKeyForAsset:asset fromBundle:nil];
416 }
417 
418 + (NSString*)lookupKeyForAsset:(NSString*)asset fromBundle:(nullable NSBundle*)bundle {
419  NSString* flutterAssetsName = [FlutterDartProject flutterAssetsName:bundle];
420  return [NSString stringWithFormat:@"%@/%@", flutterAssetsName, asset];
421 }
422 
423 + (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
424  return [self lookupKeyForAsset:asset fromPackage:package fromBundle:nil];
425 }
426 
427 + (NSString*)lookupKeyForAsset:(NSString*)asset
428  fromPackage:(NSString*)package
429  fromBundle:(nullable NSBundle*)bundle {
430  return [self lookupKeyForAsset:[NSString stringWithFormat:@"packages/%@/%@", package, asset]
431  fromBundle:bundle];
432 }
433 
434 + (NSString*)defaultBundleIdentifier {
435  return @"io.flutter.flutter.app";
436 }
437 
438 - (BOOL)isWideGamutEnabled {
439  return _settings.enable_wide_gamut;
440 }
441 
442 @end
NSNumber *_Nullable FLTEnableWideGamutFromBundle(NSBundle *_Nullable bundle, NSBundle *_Nullable mainBundle)
static const char * kApplicationKernelSnapshotFileName
const intptr_t kPlatformStrongDillSize
FLUTTER_ASSERT_ARC const uint8_t kPlatformStrongDill[]
flutter::Settings FLTDefaultSettingsForBundle(NSBundle *bundle, NSProcessInfo *processInfoOrNil)
static BOOL DoesHardwareSupportWideGamut()
NSString * FLTAssetPath(NSBundle *bundle)
NSBundle * FLTGetApplicationBundle()
NSBundle * FLTFrameworkBundleWithIdentifier(NSString *flutterFrameworkBundleID)
NSString * FLTAssetsPathFromBundle(NSBundle *bundle)
NSString * flutterAssetsName:(NSBundle *bundle)
fml::CommandLine CommandLineFromNSProcessInfo(NSProcessInfo *processInfoOrNil=nil)
Definition: command_line.mm:13