FlutterDartProject.mm 8.0 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 7

#include "base/command_line.h"
8
#include "dart/runtime/include/dart_api.h"
A
Adam Barth 已提交
9
#include "flutter/common/threads.h"
10
#include "flutter/shell/common/switches.h"
A
Adam Barth 已提交
11
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h"
12
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_main_ios.h"
13

14
static NSURL* URLForSwitch(const char* name) {
15 16 17 18 19 20 21 22 23 24 25 26 27
  auto cmd = *base::CommandLine::ForCurrentProcess();
  NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];

  if (cmd.HasSwitch(name)) {
    auto url = [NSURL fileURLWithPath:@(cmd.GetSwitchValueASCII(name).c_str())];
    [defaults setURL:url forKey:@(name)];
    [defaults synchronize];
    return url;
  }

  return [defaults URLForKey:@(name)];
}

28 29 30 31 32 33 34
@implementation FlutterDartProject {
  NSBundle* _precompiledDartBundle;
  FlutterDartSource* _dartSource;

  VMType _vmTypeRequirement;
}

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

41 42 43
#pragma mark - Override base class designated initializers

- (instancetype)init {
44
  return [self initWithFLXArchive:nil dartMain:nil packages:nil];
45 46 47 48 49 50 51 52
}

#pragma mark - Designated initializers

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

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

    [self checkReadiness];
  }

  return self;
}

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

  if (self) {
    _dartSource = [[FlutterDartSource alloc] initWithDartMain:dartMainURL
68
                                                     packages:dartPackages
69 70 71 72 73 74 75 76
                                                   flxArchive:archiveURL];

    [self checkReadiness];
  }

  return self;
}

77 78 79 80 81 82 83 84 85 86 87 88 89
- (instancetype)initWithFLXArchiveWithScriptSnapshot:(NSURL*)archiveURL {
  self = [super init];

  if (self) {
    _dartSource = [[FlutterDartSource alloc]
        initWithFLXArchiveWithScriptSnapshot:archiveURL];

    [self checkReadiness];
  }

  return self;
}

90 91 92
#pragma mark - Convenience initializers

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

  if (Dart_IsPrecompiledRuntime()) {
    // Load from an AOTC snapshot.
97
    return [self initWithPrecompiledDartBundle:bundle];
98 99 100 101
  } 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.
102
    NSURL* flxURL = URLForSwitch(shell::FlagForSwitch(shell::Switch::FLX));
103 104 105 106

    if (flxURL == nil) {
      // If the URL was not specified on the command line, look inside the
      // FlutterApplication bundle.
107 108 109 110 111 112 113 114 115 116
      NSString* flxPath = [self pathForFLXFromBundle:bundle];
      if (flxPath != nil) {
        flxURL = [NSURL fileURLWithPath:flxPath isDirectory:NO];
      }
    }

    if (flxURL == nil) {
      NSLog(@"Error: FLX file not present in bundle; unable to start app.");
      [self release];
      return nil;
117 118
    }

119 120 121 122
    NSURL* dartMainURL =
        URLForSwitch(shell::FlagForSwitch(shell::Switch::MainDartFile));
    NSURL* dartPackagesURL =
        URLForSwitch(shell::FlagForSwitch(shell::Switch::Packages));
123 124 125 126 127 128 129 130 131

    return [self initWithFLXArchive:flxURL
                           dartMain:dartMainURL
                           packages:dartPackagesURL];
  }

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

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

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

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

148 149 150 151 152 153 154 155 156 157
- (NSString*)pathForFLXFromBundle:(NSBundle*)bundle {
  NSString* flxName = [bundle objectForInfoDictionaryKey:@"FLTFlxName"];
  if (flxName == nil) {
    // Default to "app.flx"
    flxName = @"app";
  }

  return [bundle pathForResource:flxName ofType:@"flx"];
}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
#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 已提交
173
- (void)launchInEngine:(shell::Engine*)engine
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
        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 result:result];
      return;
    case VMTypePrecompilation:
      [self runFromPrecompiledSourceInEngine:engine result:result];
204
      return;
205 206 207 208 209 210 211 212 213
    case VMTypeInvalid:
      break;
  }

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

#pragma mark - Running from precompiled application bundles

A
Adam Barth 已提交
214
- (void)runFromPrecompiledSourceInEngine:(shell::Engine*)engine
215
                                  result:(LaunchResult)result {
216 217 218 219 220 221 222 223 224
  if (![_precompiledDartBundle load]) {
    NSString* message = [NSString
        stringWithFormat:
            @"Could not load the framework ('%@') containing precompiled code.",
            _precompiledDartBundle.bundleIdentifier];
    result(NO, message);
    return;
  }

225
  NSString* path = [self pathForFLXFromBundle:_precompiledDartBundle];
226 227 228 229 230 231 232 233 234
  if (path.length == 0) {
    NSString* message =
        [NSString stringWithFormat:@"Could not find the 'app.flx' archive in "
                                   @"the precompiled Dart bundle with ID '%@'",
                                   _precompiledDartBundle.bundleIdentifier];
    result(NO, message);
    return;
  }

A
Adam Barth 已提交
235 236 237 238 239 240 241
  std::string bundle_path = path.UTF8String;
  blink::Threads::UI()->PostTask(
      [ engine = engine->GetWeakPtr(), bundle_path ] {
        if (engine)
          engine->RunBundle(bundle_path);
      });

242 243 244 245 246
  result(YES, @"Success");
}

#pragma mark - Running from source

A
Adam Barth 已提交
247
- (void)runFromSourceInEngine:(shell::Engine*)engine
248 249 250 251 252 253 254 255 256 257 258
                       result:(LaunchResult)result {
  if (_dartSource == nil) {
    result(NO, @"Dart source not specified.");
    return;
  }

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

A
Adam Barth 已提交
259 260 261
    std::string bundle_path =
        _dartSource.flxArchive.absoluteURL.path.UTF8String;

262
    if (_dartSource.archiveContainsScriptSnapshot) {
A
Adam Barth 已提交
263 264 265 266 267
      blink::Threads::UI()->PostTask(
          [ engine = engine->GetWeakPtr(), bundle_path ] {
            if (engine)
              engine->RunBundle(bundle_path);
          });
268
    } else {
A
Adam Barth 已提交
269 270 271 272 273 274 275
      std::string main = _dartSource.dartMain.absoluteURL.path.UTF8String;
      std::string packages = _dartSource.packages.absoluteURL.path.UTF8String;
      blink::Threads::UI()->PostTask(
          [ engine = engine->GetWeakPtr(), bundle_path, main, packages ] {
            if (engine)
              engine->RunBundleAndSource(bundle_path, main, packages);
          });
276 277
    }

278 279 280 281 282 283 284
    result(YES, @"Success");
  }];
}

#pragma mark - Misc.

- (void)dealloc {
285
  [_precompiledDartBundle unload];
286 287 288 289 290 291 292
  [_precompiledDartBundle release];
  [_dartSource release];

  [super dealloc];
}

@end