-
Notifications
You must be signed in to change notification settings - Fork 6k
/
FlutterDartProject.mm
380 lines (313 loc) · 14.4 KB
/
FlutterDartProject.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
#include <syslog.h>
#include <sstream>
#include <string>
#include "flutter/common/constants.h"
#include "flutter/common/task_runners.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/switches.h"
#import "flutter/shell/platform/darwin/common/command_line.h"
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
extern "C" {
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
// Used for debugging dart:* sources.
extern const uint8_t kPlatformStrongDill[];
extern const intptr_t kPlatformStrongDillSize;
#endif
}
static const char* kApplicationKernelSnapshotFileName = "kernel_blob.bin";
flutter::Settings FLTDefaultSettingsForBundle(NSBundle* bundle) {
auto command_line = flutter::CommandLineFromNSProcessInfo();
// Precedence:
// 1. Settings from the specified NSBundle.
// 2. Settings passed explicitly via command-line arguments.
// 3. Settings from the NSBundle with the default bundle ID.
// 4. Settings from the main NSBundle and default values.
NSBundle* mainBundle = [NSBundle mainBundle];
NSBundle* engineBundle = [NSBundle bundleForClass:[FlutterViewController class]];
bool hasExplicitBundle = bundle != nil;
if (bundle == nil) {
bundle = [NSBundle bundleWithIdentifier:[FlutterDartProject defaultBundleIdentifier]];
}
if (bundle == nil) {
bundle = mainBundle;
}
auto settings = flutter::SettingsFromCommandLine(command_line);
settings.task_observer_add = [](intptr_t key, const fml::closure& callback) {
fml::MessageLoop::GetCurrent().AddTaskObserver(key, callback);
};
settings.task_observer_remove = [](intptr_t key) {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
};
settings.log_message_callback = [](const std::string& tag, const std::string& message) {
// TODO(cbracken): replace this with os_log-based approach.
// https://github.com/flutter/flutter/issues/44030
std::stringstream stream;
if (!tag.empty()) {
stream << tag << ": ";
}
stream << message;
std::string log = stream.str();
syslog(LOG_ALERT, "%.*s", (int)log.size(), log.c_str());
};
// The command line arguments may not always be complete. If they aren't, attempt to fill in
// defaults.
// Flutter ships the ICU data file in the bundle of the engine. Look for it there.
if (settings.icu_data_path.empty()) {
NSString* icuDataPath = [engineBundle pathForResource:@"icudtl" ofType:@"dat"];
if (icuDataPath.length > 0) {
settings.icu_data_path = icuDataPath.UTF8String;
}
}
if (flutter::DartVM::IsRunningPrecompiledCode()) {
if (hasExplicitBundle) {
NSString* executablePath = bundle.executablePath;
if ([[NSFileManager defaultManager] fileExistsAtPath:executablePath]) {
settings.application_library_path.push_back(executablePath.UTF8String);
}
}
// No application bundle specified. Try a known location from the main bundle's Info.plist.
if (settings.application_library_path.empty()) {
NSString* libraryName = [mainBundle objectForInfoDictionaryKey:@"FLTLibraryPath"];
NSString* libraryPath = [mainBundle pathForResource:libraryName ofType:@""];
if (libraryPath.length > 0) {
NSString* executablePath = [NSBundle bundleWithPath:libraryPath].executablePath;
if (executablePath.length > 0) {
settings.application_library_path.push_back(executablePath.UTF8String);
}
}
}
// In case the application bundle is still not specified, look for the App.framework in the
// Frameworks directory.
if (settings.application_library_path.empty()) {
NSString* applicationFrameworkPath = [mainBundle pathForResource:@"Frameworks/App.framework"
ofType:@""];
if (applicationFrameworkPath.length > 0) {
NSString* executablePath =
[NSBundle bundleWithPath:applicationFrameworkPath].executablePath;
if (executablePath.length > 0) {
settings.application_library_path.push_back(executablePath.UTF8String);
}
}
}
}
// Checks to see if the flutter assets directory is already present.
if (settings.assets_path.empty()) {
NSString* assetsName = [FlutterDartProject flutterAssetsName:bundle];
NSString* assetsPath = [bundle pathForResource:assetsName ofType:@""];
if (assetsPath.length == 0) {
assetsPath = [mainBundle pathForResource:assetsName ofType:@""];
}
if (assetsPath.length == 0) {
NSLog(@"Failed to find assets path for \"%@\"", assetsName);
} else {
settings.assets_path = assetsPath.UTF8String;
// Check if there is an application kernel snapshot in the assets directory we could
// potentially use. Looking for the snapshot makes sense only if we have a VM that can use
// it.
if (!flutter::DartVM::IsRunningPrecompiledCode()) {
NSURL* applicationKernelSnapshotURL =
[NSURL URLWithString:@(kApplicationKernelSnapshotFileName)
relativeToURL:[NSURL fileURLWithPath:assetsPath]];
if ([[NSFileManager defaultManager] fileExistsAtPath:applicationKernelSnapshotURL.path]) {
settings.application_kernel_asset = applicationKernelSnapshotURL.path.UTF8String;
} else {
NSLog(@"Failed to find snapshot: %@", applicationKernelSnapshotURL.path);
}
}
}
}
// Domain network configuration
// Disabled in https://github.com/flutter/flutter/issues/72723.
// Re-enable in https://github.com/flutter/flutter/issues/54448.
settings.may_insecurely_connect_to_all_domains = true;
settings.domain_network_policy = "";
// Whether to enable Impeller.
NSNumber* nsEnableWideGamut = [mainBundle objectForInfoDictionaryKey:@"FLTEnableWideGamut"];
// TODO(gaaclarke): Make this value `on` by default (pending memory audit).
BOOL enableWideGamut = nsEnableWideGamut ? nsEnableWideGamut.boolValue : NO;
settings.enable_wide_gamut = enableWideGamut;
// Whether to enable Impeller.
NSNumber* enableImpeller = [mainBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"];
// Change the default only if the option is present.
if (enableImpeller != nil) {
settings.enable_impeller = enableImpeller.boolValue;
}
NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTTraceSystrace"];
// Change the default only if the option is present.
if (enableTraceSystrace != nil) {
settings.trace_systrace = enableTraceSystrace.boolValue;
}
NSNumber* enableDartProfiling = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartProfiling"];
// Change the default only if the option is present.
if (enableDartProfiling != nil) {
settings.enable_dart_profiling = enableDartProfiling.boolValue;
}
// Leak Dart VM settings, set whether leave or clean up the VM after the last shell shuts down.
NSNumber* leakDartVM = [mainBundle objectForInfoDictionaryKey:@"FLTLeakDartVM"];
// It will change the default leak_vm value in settings only if the key exists.
if (leakDartVM != nil) {
settings.leak_vm = leakDartVM.boolValue;
}
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
// There are no ownership concerns here as all mappings are owned by the
// embedder and not the engine.
auto make_mapping_callback = [](const uint8_t* mapping, size_t size) {
return [mapping, size]() { return std::make_unique<fml::NonOwnedMapping>(mapping, size); };
};
settings.dart_library_sources_kernel =
make_mapping_callback(kPlatformStrongDill, kPlatformStrongDillSize);
#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
// If we even support setting this e.g. from the command line or the plist,
// we should let the user override it.
// Otherwise, we want to set this to a value that will avoid having the OS
// kill us. On most iOS devices, that happens somewhere near half
// the available memory.
// The VM expects this value to be in megabytes.
if (settings.old_gen_heap_size <= 0) {
settings.old_gen_heap_size = std::round([NSProcessInfo processInfo].physicalMemory * .48 /
flutter::kMegaByteSizeInBytes);
}
// This is the formula Android uses.
// https://android.googlesource.com/platform/frameworks/base/+/39ae5bac216757bc201490f4c7b8c0f63006c6cd/libs/hwui/renderthread/CacheManager.cpp#45
CGFloat scale = [UIScreen mainScreen].scale;
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width * scale;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height * scale;
settings.resource_cache_max_bytes_threshold = screenWidth * screenHeight * 12 * 4;
return settings;
}
@implementation FlutterDartProject {
flutter::Settings _settings;
}
#pragma mark - Override base class designated initializers
- (instancetype)init {
return [self initWithPrecompiledDartBundle:nil];
}
#pragma mark - Designated initializers
- (instancetype)initWithPrecompiledDartBundle:(nullable NSBundle*)bundle {
self = [super init];
if (self) {
_settings = FLTDefaultSettingsForBundle(bundle);
}
return self;
}
- (instancetype)initWithSettings:(const flutter::Settings&)settings {
self = [self initWithPrecompiledDartBundle:nil];
if (self) {
_settings = settings;
}
return self;
}
#pragma mark - PlatformData accessors
- (const flutter::PlatformData)defaultPlatformData {
flutter::PlatformData PlatformData;
PlatformData.lifecycle_state = std::string("AppLifecycleState.detached");
return PlatformData;
}
#pragma mark - Settings accessors
- (const flutter::Settings&)settings {
return _settings;
}
- (flutter::RunConfiguration)runConfiguration {
return [self runConfigurationForEntrypoint:nil];
}
- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil {
return [self runConfigurationForEntrypoint:entrypointOrNil libraryOrNil:nil];
}
- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil
libraryOrNil:(nullable NSString*)dartLibraryOrNil {
return [self runConfigurationForEntrypoint:entrypointOrNil
libraryOrNil:dartLibraryOrNil
entrypointArgs:nil];
}
- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil
libraryOrNil:(nullable NSString*)dartLibraryOrNil
entrypointArgs:
(nullable NSArray<NSString*>*)entrypointArgs {
auto config = flutter::RunConfiguration::InferFromSettings(_settings);
if (dartLibraryOrNil && entrypointOrNil) {
config.SetEntrypointAndLibrary(std::string([entrypointOrNil UTF8String]),
std::string([dartLibraryOrNil UTF8String]));
} else if (entrypointOrNil) {
config.SetEntrypoint(std::string([entrypointOrNil UTF8String]));
}
if (entrypointArgs.count) {
std::vector<std::string> cppEntrypointArgs;
for (NSString* arg in entrypointArgs) {
cppEntrypointArgs.push_back(std::string([arg UTF8String]));
}
config.SetEntrypointArgs(std::move(cppEntrypointArgs));
}
return config;
}
#pragma mark - Assets-related utilities
+ (NSString*)flutterAssetsName:(NSBundle*)bundle {
if (bundle == nil) {
bundle = [NSBundle bundleWithIdentifier:[FlutterDartProject defaultBundleIdentifier]];
}
if (bundle == nil) {
bundle = [NSBundle mainBundle];
}
NSString* flutterAssetsName = [bundle objectForInfoDictionaryKey:@"FLTAssetsPath"];
if (flutterAssetsName == nil) {
flutterAssetsName = @"Frameworks/App.framework/flutter_assets";
}
return flutterAssetsName;
}
+ (NSString*)domainNetworkPolicy:(NSDictionary*)appTransportSecurity {
// https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsexceptiondomains
NSDictionary* exceptionDomains = [appTransportSecurity objectForKey:@"NSExceptionDomains"];
if (exceptionDomains == nil) {
return @"";
}
NSMutableArray* networkConfigArray = [[[NSMutableArray alloc] init] autorelease];
for (NSString* domain in exceptionDomains) {
NSDictionary* domainConfiguration = [exceptionDomains objectForKey:domain];
// Default value is false.
bool includesSubDomains =
[[domainConfiguration objectForKey:@"NSIncludesSubdomains"] boolValue];
bool allowsCleartextCommunication =
[[domainConfiguration objectForKey:@"NSExceptionAllowsInsecureHTTPLoads"] boolValue];
[networkConfigArray addObject:@[
domain, includesSubDomains ? @YES : @NO, allowsCleartextCommunication ? @YES : @NO
]];
}
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:networkConfigArray
options:0
error:NULL];
return [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
}
+ (bool)allowsArbitraryLoads:(NSDictionary*)appTransportSecurity {
return [[appTransportSecurity objectForKey:@"NSAllowsArbitraryLoads"] boolValue];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset {
return [self lookupKeyForAsset:asset fromBundle:nil];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset fromBundle:(nullable NSBundle*)bundle {
NSString* flutterAssetsName = [FlutterDartProject flutterAssetsName:bundle];
return [NSString stringWithFormat:@"%@/%@", flutterAssetsName, asset];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
return [self lookupKeyForAsset:asset fromPackage:package fromBundle:nil];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset
fromPackage:(NSString*)package
fromBundle:(nullable NSBundle*)bundle {
return [self lookupKeyForAsset:[NSString stringWithFormat:@"packages/%@/%@", package, asset]
fromBundle:bundle];
}
+ (NSString*)defaultBundleIdentifier {
return @"io.flutter.flutter.app";
}
- (BOOL)isWideGamutEnabled {
return _settings.enable_wide_gamut;
}
@end