application_package.dart 10.6 KB
Newer Older
1 2 3 4
// Copyright 2015 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 6
import 'dart:async';

7
import 'package:meta/meta.dart' show required;
8
import 'package:xml/xml.dart' as xml;
9

10
import 'android/android_sdk.dart';
11
import 'android/gradle.dart';
12
import 'base/file_system.dart';
13
import 'base/os.dart' show os;
14
import 'base/process.dart';
15
import 'build_info.dart';
16
import 'globals.dart';
17
import 'ios/plist_utils.dart' as plist;
18
import 'ios/xcodeproj.dart';
19

20 21
abstract class ApplicationPackage {
  /// Package ID from the Android Manifest or equivalent.
22
  final String id;
23

24
  ApplicationPackage({ @required this.id }) {
25 26
    assert(id != null);
  }
27

28 29
  String get name;

30 31
  String get displayName => name;

32 33
  String get packagePath => null;

34
  @override
35
  String toString() => displayName;
36 37 38
}

class AndroidApk extends ApplicationPackage {
39 40 41
  /// Path to the actual apk file.
  final String apkPath;

42
  /// The path to the activity that should be launched.
43 44 45
  final String launchActivity;

  AndroidApk({
Adam Barth's avatar
Adam Barth committed
46
    String id,
47 48
    @required this.apkPath,
    @required this.launchActivity
49
  }) : super(id: id) {
50
    assert(apkPath != null);
51 52
    assert(launchActivity != null);
  }
53

54 55
  /// Creates a new AndroidApk from an existing APK.
  factory AndroidApk.fromApk(String applicationBinary) {
56
    final String aaptPath = androidSdk?.latestVersion?.aaptPath;
57 58 59 60 61
    if (aaptPath == null) {
      printError('Unable to locate the Android SDK; please run \'flutter doctor\'.');
      return null;
    }

62 63
    final List<String> aaptArgs = <String>[aaptPath, 'dump', 'badging', applicationBinary];
    final ApkManifestData data = ApkManifestData.parseFromAaptBadging(runCheckedSync(aaptArgs));
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

    if (data == null) {
      printError('Unable to read manifest info from $applicationBinary.');
      return null;
    }

    if (data.packageName == null || data.launchableActivityName == null) {
      printError('Unable to read manifest info from $applicationBinary.');
      return null;
    }

    return new AndroidApk(
      id: data.packageName,
      apkPath: applicationBinary,
      launchActivity: '${data.packageName}/${data.launchableActivityName}'
    );
  }

82
  /// Creates a new AndroidApk based on the information in the Android manifest.
83
  static Future<AndroidApk> fromCurrentDirectory() async {
84 85 86 87
    String manifestPath;
    String apkPath;

    if (isProjectUsingGradle()) {
88
      apkPath = await getGradleAppOut();
89
      if (fs.file(apkPath).existsSync()) {
90 91
        // Grab information from the .apk. The gradle build script might alter
        // the application Id, so we need to look at what was actually built.
92
        return new AndroidApk.fromApk(apkPath);
93 94 95 96
      }
      // The .apk hasn't been built yet, so we work with what we have. The run
      // command will grab a new AndroidApk after building, to get the updated
      // IDs.
97
      manifestPath = gradleManifestPath;
98
    } else {
99 100
      manifestPath = fs.path.join('android', 'AndroidManifest.xml');
      apkPath = fs.path.join(getAndroidBuildDirectory(), 'app.apk');
101 102
    }

103
    if (!fs.isFileSync(manifestPath))
104
      return null;
105

106 107
    final String manifestString = fs.file(manifestPath).readAsStringSync();
    final xml.XmlDocument document = xml.parse(manifestString);
108

109
    final Iterable<xml.XmlElement> manifests = document.findElements('manifest');
110 111
    if (manifests.isEmpty)
      return null;
112
    final String packageId = manifests.first.getAttribute('package');
113 114 115 116

    String launchActivity;
    for (xml.XmlElement category in document.findAllElements('category')) {
      if (category.getAttribute('android:name') == 'android.intent.category.LAUNCHER') {
117 118
        final xml.XmlElement activity = category.parent.parent;
        final String activityName = activity.getAttribute('android:name');
119
        launchActivity = "$packageId/$activityName";
120 121 122
        break;
      }
    }
123 124

    if (packageId == null || launchActivity == null)
125 126
      return null;

127
    return new AndroidApk(
128
      id: packageId,
129
      apkPath: apkPath,
130 131
      launchActivity: launchActivity
    );
132
  }
133

134 135 136
  @override
  String get packagePath => apkPath;

137
  @override
138
  String get name => fs.path.basename(apkPath);
139 140
}

141 142 143 144 145 146 147 148 149 150 151
/// Tests whether a [FileSystemEntity] is an iOS bundle directory
bool _isBundleDirectory(FileSystemEntity entity) =>
    entity is Directory && entity.path.endsWith('.app');

abstract class IOSApp extends ApplicationPackage {
  IOSApp({String projectBundleId}) : super(id: projectBundleId);

  /// Creates a new IOSApp from an existing IPA.
  factory IOSApp.fromIpa(String applicationBinary) {
    Directory bundleDir;
    try {
152
      final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app_');
153 154 155
      addShutdownHook(() async {
        await tempDir.delete(recursive: true);
      }, ShutdownStage.STILL_RECORDING);
156
      os.unzip(fs.file(applicationBinary), tempDir);
157
      final Directory payloadDir = fs.directory(fs.path.join(tempDir.path, 'Payload'));
158 159
      bundleDir = payloadDir.listSync().singleWhere(_isBundleDirectory);
    } on StateError catch (e, stackTrace) {
160
      printError('Invalid prebuilt iOS binary: ${e.toString()}', stackTrace: stackTrace);
161 162
      return null;
    }
163

164 165
    final String plistPath = fs.path.join(bundleDir.path, 'Info.plist');
    final String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
166 167 168 169 170 171
    if (id == null)
      return null;

    return new PrebuiltIOSApp(
      ipaPath: applicationBinary,
      bundleDir: bundleDir,
172
      bundleName: fs.path.basename(bundleDir.path),
173 174 175
      projectBundleId: id,
    );
  }
176

177 178
  factory IOSApp.fromCurrentDirectory() {
    if (getCurrentHostPlatform() != HostPlatform.darwin_x64)
179 180
      return null;

181
    final String plistPath = fs.path.join('ios', 'Runner', 'Info.plist');
182 183
    String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
    if (id == null)
184
      return null;
185
    final String projectPath = fs.path.join('ios', 'Runner.xcodeproj');
186 187
    final Map<String, String> buildSettings = getXcodeBuildSettings(projectPath, 'Runner');
    id = substituteXcodeVariables(id, buildSettings);
188

189
    return new BuildableIOSApp(
190
      appDirectory: fs.path.join('ios'),
191 192
      projectBundleId: id,
      buildSettings: buildSettings,
193
    );
194
  }
195

196
  @override
197
  String get displayName => id;
198

199 200 201 202 203 204 205 206 207 208 209
  String get simulatorBundlePath;

  String get deviceBundlePath;
}

class BuildableIOSApp extends IOSApp {
  static final String kBundleName = 'Runner.app';

  BuildableIOSApp({
    this.appDirectory,
    String projectBundleId,
210
    this.buildSettings,
211 212
  }) : super(projectBundleId: projectBundleId);

213 214
  final String appDirectory;

215 216 217
  /// Build settings of the app's XCode project.
  final Map<String, String> buildSettings;

218 219 220 221
  @override
  String get name => kBundleName;

  @override
222 223
  String get simulatorBundlePath => _buildAppPath('iphonesimulator');

224
  @override
225 226
  String get deviceBundlePath => _buildAppPath('iphoneos');

227 228 229
  /// True if the app is built from a Swift project. Null if unknown.
  bool get isSwift => buildSettings?.containsKey('SWIFT_VERSION');

230
  String _buildAppPath(String type) {
231
    return fs.path.join(getIosBuildDirectory(), type, kBundleName);
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
class PrebuiltIOSApp extends IOSApp {
  final String ipaPath;
  final Directory bundleDir;
  final String bundleName;

  PrebuiltIOSApp({
    this.ipaPath,
    this.bundleDir,
    this.bundleName,
    String projectBundleId,
  }) : super(projectBundleId: projectBundleId);

  @override
  String get name => bundleName;

  @override
  String get simulatorBundlePath => _bundlePath;

  @override
  String get deviceBundlePath => _bundlePath;

  String get _bundlePath => bundleDir.path;
}

259
Future<ApplicationPackage> getApplicationPackageForPlatform(TargetPlatform platform, {
260
  String applicationBinary
261
}) async {
262 263 264
  switch (platform) {
    case TargetPlatform.android_arm:
    case TargetPlatform.android_x64:
265
    case TargetPlatform.android_x86:
266
      return applicationBinary == null
267
          ? await AndroidApk.fromCurrentDirectory()
268
          : new AndroidApk.fromApk(applicationBinary);
269
    case TargetPlatform.ios:
270 271 272
      return applicationBinary == null
          ? new IOSApp.fromCurrentDirectory()
          : new IOSApp.fromIpa(applicationBinary);
273 274
    case TargetPlatform.darwin_x64:
    case TargetPlatform.linux_x64:
275
    case TargetPlatform.windows_x64:
276
    case TargetPlatform.fuchsia:
277 278
      return null;
  }
pq's avatar
pq committed
279
  assert(platform != null);
pq's avatar
pq committed
280
  return null;
281 282
}

283
class ApplicationPackageStore {
284 285
  AndroidApk android;
  IOSApp iOS;
286

287
  ApplicationPackageStore({ this.android, this.iOS });
288

289
  Future<ApplicationPackage> getPackageForPlatform(TargetPlatform platform) async {
290
    switch (platform) {
291
      case TargetPlatform.android_arm:
292
      case TargetPlatform.android_x64:
293
      case TargetPlatform.android_x86:
294
        android ??= await AndroidApk.fromCurrentDirectory();
295
        return android;
296
      case TargetPlatform.ios:
297
        iOS ??= new IOSApp.fromCurrentDirectory();
298
        return iOS;
299 300
      case TargetPlatform.darwin_x64:
      case TargetPlatform.linux_x64:
301
      case TargetPlatform.windows_x64:
302
      case TargetPlatform.fuchsia:
303 304
        return null;
    }
pq's avatar
pq committed
305
    return null;
306 307
  }
}
308 309 310 311 312 313 314 315 316

class ApkManifestData {
  ApkManifestData._(this._data);

  static ApkManifestData parseFromAaptBadging(String data) {
    if (data == null || data.trim().isEmpty)
      return null;

    // package: name='io.flutter.gallery' versionCode='1' versionName='0.0.1' platformBuildVersionName='NMR1'
317
    // launchable-activity: name='io.flutter.app.FlutterActivity'  label='' icon=''
318
    final Map<String, Map<String, String>> map = <String, Map<String, String>>{};
319 320

    for (String line in data.split('\n')) {
321
      final int index = line.indexOf(':');
322
      if (index != -1) {
323
        final String name = line.substring(0, index);
324 325
        line = line.substring(index + 1).trim();

326
        final Map<String, String> entries = <String, String>{};
327 328 329 330 331
        map[name] = entries;

        for (String entry in line.split(' ')) {
          entry = entry.trim();
          if (entry.isNotEmpty && entry.contains('=')) {
332 333
            final int split = entry.indexOf('=');
            final String key = entry.substring(0, split);
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
            String value = entry.substring(split + 1);
            if (value.startsWith("'") && value.endsWith("'"))
              value = value.substring(1, value.length - 1);
            entries[key] = value;
          }
        }
      }
    }

    return new ApkManifestData._(map);
  }

  final Map<String, Map<String, String>> _data;

  String get packageName => _data['package'] == null ? null : _data['package']['name'];

  String get launchableActivityName {
    return _data['launchable-activity'] == null ? null : _data['launchable-activity']['name'];
  }

  @override
  String toString() => _data.toString();
}