FlutterDartProject.mm 9.9 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
6

A
Adam Barth 已提交
7
#include "flutter/common/threads.h"
8
#include "flutter/shell/common/shell.h"
9
#include "flutter/shell/common/switches.h"
A
Adam Barth 已提交
10
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h"
11
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_main_ios.h"
12
#include "lib/fxl/strings/string_view.h"
13
#include "third_party/dart/runtime/include/dart_api.h"
14

15
static NSURL* URLForSwitch(const fxl::StringView name) {
16
  const auto& cmd = shell::Shell::Shared().GetCommandLine();
17 18
  NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];

19 20 21
  std::string switch_value;
  if (cmd.GetOptionValue(name, &switch_value)) {
    auto url = [NSURL fileURLWithPath:@(switch_value.c_str())];
22
    [defaults setURL:url forKey:@(name.data())];
23 24 25 26
    [defaults synchronize];
    return url;
  }

27
  return [defaults URLForKey:@(name.data())];
28 29
}

30 31 32 33 34 35 36
@implementation FlutterDartProject {
  NSBundle* _precompiledDartBundle;
  FlutterDartSource* _dartSource;

  VMType _vmTypeRequirement;
}

37 38 39 40 41 42
+ (void)initialize {
  if (self == [FlutterDartProject class]) {
    shell::FlutterMain();
  }
}

43 44 45
#pragma mark - Override base class designated initializers

- (instancetype)init {
46
  return [self initWithFlutterAssets:nil dartMain:nil packages:nil];
47 48 49 50 51 52 53 54
}

#pragma mark - Designated initializers

- (instancetype)initWithPrecompiledDartBundle:(NSBundle*)bundle {
  self = [super init];

  if (self) {
55
    _precompiledDartBundle = [bundle retain];
56 57 58 59 60 61 62

    [self checkReadiness];
  }

  return self;
}

63 64 65
- (instancetype)initWithFlutterAssets:(NSURL*)flutterAssetsURL
                             dartMain:(NSURL*)dartMainURL
                             packages:(NSURL*)dartPackages {
66 67 68 69
  self = [super init];

  if (self) {
    _dartSource = [[FlutterDartSource alloc] initWithDartMain:dartMainURL
70
                                                     packages:dartPackages
71
                                                flutterAssets:flutterAssetsURL];
72 73 74 75 76 77 78

    [self checkReadiness];
  }

  return self;
}

79
- (instancetype)initWithFlutterAssetsWithScriptSnapshot:(NSURL*)flutterAssetsURL {
80 81 82
  self = [super init];

  if (self) {
83 84
    _dartSource =
        [[FlutterDartSource alloc] initWithFlutterAssetsWithScriptSnapshot:flutterAssetsURL];
85 86 87 88 89 90 91

    [self checkReadiness];
  }

  return self;
}

92 93 94
#pragma mark - Convenience initializers

- (instancetype)initFromDefaultSourceForConfiguration {
95
  NSBundle* bundle = [NSBundle mainBundle];
96 97 98

  if (Dart_IsPrecompiledRuntime()) {
    // Load from an AOTC snapshot.
99
    return [self initWithPrecompiledDartBundle:bundle];
100 101 102 103
  } else {
    // Load directly from sources if the appropriate command line flags are
    // specified. If not, try loading from a script snapshot in the framework
    // bundle.
104
    NSURL* flutterAssetsURL = URLForSwitch(shell::FlagForSwitch(shell::Switch::FlutterAssetsDir));
105

106
    if (flutterAssetsURL == nil) {
107 108
      // If the URL was not specified on the command line, look inside the
      // FlutterApplication bundle.
109
      NSString* flutterAssetsPath = [FlutterDartProject pathForFlutterAssetsFromBundle:bundle];
110 111
      if (flutterAssetsPath != nil) {
        flutterAssetsURL = [NSURL fileURLWithPath:flutterAssetsPath isDirectory:NO];
112 113 114
      }
    }

115 116
    if (flutterAssetsURL == nil) {
      NSLog(@"Error: flutterAssets directory not present in bundle; unable to start app.");
117 118
      [self release];
      return nil;
119 120
    }

121 122
    NSURL* dartMainURL = URLForSwitch(shell::FlagForSwitch(shell::Switch::MainDartFile));
    NSURL* dartPackagesURL = URLForSwitch(shell::FlagForSwitch(shell::Switch::Packages));
123

124 125
    return
        [self initWithFlutterAssets:flutterAssetsURL dartMain:dartMainURL packages:dartPackagesURL];
126 127 128 129 130
  }

  NSAssert(NO, @"Unreachable");
  [self release];
  return nil;
131 132
}

133 134 135 136 137 138 139 140 141 142 143 144 145 146
#pragma mark - Common initialization tasks

- (void)checkReadiness {
  if (_precompiledDartBundle != nil) {
    _vmTypeRequirement = VMTypePrecompilation;
    return;
  }

  if (_dartSource != nil) {
    _vmTypeRequirement = VMTypeInterpreter;
    return;
  }
}

147 148 149
#pragma mark - Assets-related utilities

+ (NSString*)pathForFlutterAssetsFromBundle:(NSBundle*)bundle {
150 151 152 153
  NSString* flutterAssetsName = [bundle objectForInfoDictionaryKey:@"FLTAssetsPath"];
  if (flutterAssetsName == nil) {
    // Default to "flutter_assets"
    flutterAssetsName = @"flutter_assets";
154 155
  }

156
  return [bundle pathForResource:flutterAssetsName ofType:nil];
157 158
}

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
#pragma mark - Launching the project in a preconfigured engine.

static NSString* NSStringFromVMType(VMType type) {
  switch (type) {
    case VMTypeInvalid:
      return @"Invalid";
    case VMTypeInterpreter:
      return @"Interpreter";
    case VMTypePrecompilation:
      return @"Precompilation";
  }

  return @"Unknown";
}

A
Adam Barth 已提交
174
- (void)launchInEngine:(shell::Engine*)engine
175
        withEntrypoint:(NSString*)entrypoint
176 177 178 179 180 181 182 183 184 185 186 187 188
        embedderVMType:(VMType)embedderVMType
                result:(LaunchResult)result {
  if (_vmTypeRequirement == VMTypeInvalid) {
    result(NO, @"The Dart project is invalid and cannot be loaded by any VM.");
    return;
  }

  if (embedderVMType == VMTypeInvalid) {
    result(NO, @"The embedder is invalid.");
    return;
  }

  if (_vmTypeRequirement != embedderVMType) {
189
    NSString* message =
190 191 192 193 194
        [NSString stringWithFormat:
                      @"Could not load the project because of differing project type. "
                      @"The project can run in '%@' but the embedder is configured as "
                      @"'%@'",
                      NSStringFromVMType(_vmTypeRequirement), NSStringFromVMType(embedderVMType)];
195 196 197 198 199 200
    result(NO, message);
    return;
  }

  switch (_vmTypeRequirement) {
    case VMTypeInterpreter:
201
      [self runFromSourceInEngine:engine withEntrypoint:entrypoint result:result];
202 203
      return;
    case VMTypePrecompilation:
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
      [self runFromPrecompiledSourceInEngine:engine withEntrypoint:entrypoint result:result];
      return;
    case VMTypeInvalid:
      break;
  }

  return result(NO, @"Internal error");
}

- (void)launchInEngine:(shell::Engine*)engine
        embedderVMType:(VMType)embedderVMType
                result:(LaunchResult)result {
  if (_vmTypeRequirement == VMTypeInvalid) {
    result(NO, @"The Dart project is invalid and cannot be loaded by any VM.");
    return;
  }

  if (embedderVMType == VMTypeInvalid) {
    result(NO, @"The embedder is invalid.");
    return;
  }

  if (_vmTypeRequirement != embedderVMType) {
    NSString* message =
        [NSString stringWithFormat:
                      @"Could not load the project because of differing project type. "
                      @"The project can run in '%@' but the embedder is configured as "
                      @"'%@'",
                      NSStringFromVMType(_vmTypeRequirement), NSStringFromVMType(embedderVMType)];
    result(NO, message);
    return;
  }

  switch (_vmTypeRequirement) {
    case VMTypeInterpreter:
      [self runFromSourceInEngine:engine withEntrypoint:@"main" result:result];
      return;
    case VMTypePrecompilation:
      [self runFromPrecompiledSourceInEngine:engine withEntrypoint:@"main" result:result];
243
      return;
244 245 246 247 248 249 250 251 252
    case VMTypeInvalid:
      break;
  }

  return result(NO, @"Internal error");
}

#pragma mark - Running from precompiled application bundles

253 254 255
- (void)runFromPrecompiledSourceInEngine:(shell::Engine*)engine
                          withEntrypoint:(NSString*)entrypoint
                                  result:(LaunchResult)result {
256 257
  if (![_precompiledDartBundle load]) {
    NSString* message = [NSString
258 259
        stringWithFormat:@"Could not load the framework ('%@') containing precompiled code.",
                         _precompiledDartBundle.bundleIdentifier];
260 261 262 263
    result(NO, message);
    return;
  }

264
  NSString* path = [FlutterDartProject pathForFlutterAssetsFromBundle:_precompiledDartBundle];
265
  if (path.length == 0) {
266
    NSString* message = [NSString stringWithFormat:
267
                                      @"Could not find the 'flutter_assets' dir in "
268 269
                                      @"the precompiled Dart bundle with ID '%@'",
                                      _precompiledDartBundle.bundleIdentifier];
270 271 272 273
    result(NO, message);
    return;
  }

A
Adam Barth 已提交
274
  std::string bundle_path = path.UTF8String;
275 276 277
  blink::Threads::UI()->PostTask([
    engine = engine->GetWeakPtr(), bundle_path, entrypoint = std::string([entrypoint UTF8String])
  ] {
278
    if (engine)
279
      engine->RunBundle(bundle_path, entrypoint);
280
  });
A
Adam Barth 已提交
281

282 283 284 285 286
  result(YES, @"Success");
}

#pragma mark - Running from source

287 288 289
- (void)runFromSourceInEngine:(shell::Engine*)engine
               withEntrypoint:(NSString*)entrypoint
                       result:(LaunchResult)result {
290 291 292 293 294 295 296 297 298 299
  if (_dartSource == nil) {
    result(NO, @"Dart source not specified.");
    return;
  }

  [_dartSource validate:^(BOOL success, NSString* message) {
    if (!success) {
      return result(NO, message);
    }

300
    std::string bundle_path = _dartSource.flutterAssets.absoluteURL.path.UTF8String;
A
Adam Barth 已提交
301

302
    if (_dartSource.assetsDirContainsScriptSnapshot) {
303 304 305 306
      blink::Threads::UI()->PostTask([
        engine = engine->GetWeakPtr(), bundle_path,
        entrypoint = std::string([entrypoint UTF8String])
      ] {
307
        if (engine)
308
          engine->RunBundle(bundle_path, entrypoint);
309
      });
310
    } else {
A
Adam Barth 已提交
311 312
      std::string main = _dartSource.dartMain.absoluteURL.path.UTF8String;
      std::string packages = _dartSource.packages.absoluteURL.path.UTF8String;
313 314 315 316 317
      blink::Threads::UI()->PostTask(
          [ engine = engine->GetWeakPtr(), bundle_path, main, packages ] {
            if (engine)
              engine->RunBundleAndSource(bundle_path, main, packages);
          });
318 319
    }

320 321 322 323 324 325 326
    result(YES, @"Success");
  }];
}

#pragma mark - Misc.

- (void)dealloc {
327
  [_precompiledDartBundle unload];
328 329 330 331 332 333 334
  [_precompiledDartBundle release];
  [_dartSource release];

  [super dealloc];
}

@end