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