application_package.dart 19.4 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
import 'dart:async';
6
import 'dart:collection';
7

8
import 'package:meta/meta.dart';
9
import 'package:xml/xml.dart' as xml;
10

11
import 'android/android_sdk.dart';
12
import 'android/gradle.dart';
13
import 'base/common.dart';
14
import 'base/context.dart';
15
import 'base/file_system.dart';
16
import 'base/os.dart' show os;
17
import 'base/process.dart';
18
import 'base/user_messages.dart';
19
import 'build_info.dart';
20
import 'fuchsia/application_package.dart';
21
import 'globals.dart';
22
import 'ios/ios_workflow.dart';
23
import 'ios/plist_utils.dart' as plist;
24
import 'linux/application_package.dart';
25
import 'macos/application_package.dart';
26
import 'project.dart';
27
import 'tester/flutter_tester.dart';
28
import 'web/web_device.dart';
29
import 'windows/application_package.dart';
30

31
class ApplicationPackageFactory {
32
  static ApplicationPackageFactory get instance => context.get<ApplicationPackageFactory>();
33 34

  Future<ApplicationPackage> getPackageForPlatform(
35 36 37
    TargetPlatform platform, {
    File applicationBinary,
  }) async {
38 39 40 41 42
    switch (platform) {
      case TargetPlatform.android_arm:
      case TargetPlatform.android_arm64:
      case TargetPlatform.android_x64:
      case TargetPlatform.android_x86:
43 44 45
        if (androidSdk?.licensesAvailable == true  && androidSdk.latestVersion == null) {
          await checkGradleDependencies();
        }
46
        return applicationBinary == null
47
            ? await AndroidApk.fromAndroidProject(FlutterProject.current().android)
48 49 50
            : AndroidApk.fromApk(applicationBinary);
      case TargetPlatform.ios:
        return applicationBinary == null
51
            ? IOSApp.fromIosProject(FlutterProject.current().ios)
52 53 54 55
            : IOSApp.fromPrebuiltApp(applicationBinary);
      case TargetPlatform.tester:
        return FlutterTesterApp.fromCurrentDirectory();
      case TargetPlatform.darwin_x64:
56
        return applicationBinary == null
57
            ? MacOSApp.fromMacOSProject(FlutterProject.current().macos)
58
            : MacOSApp.fromPrebuiltApp(applicationBinary);
59
      case TargetPlatform.web:
60
        return WebApplicationPackage(FlutterProject.current());
61
      case TargetPlatform.linux_x64:
62
        return applicationBinary == null
63
            ? LinuxApp.fromLinuxProject(FlutterProject.current().linux)
64
            : LinuxApp.fromPrebuiltApp(applicationBinary);
65
      case TargetPlatform.windows_x64:
66
        return applicationBinary == null
67
            ? WindowsApp.fromWindowsProject(FlutterProject.current().windows)
68
            : WindowsApp.fromPrebuiltApp(applicationBinary);
69
      case TargetPlatform.fuchsia:
70 71 72
        return applicationBinary == null
            ? FuchsiaApp.fromFuchsiaProject(FlutterProject.current().fuchsia)
            : FuchsiaApp.fromPrebuiltApp(applicationBinary);
73 74 75 76 77 78
    }
    assert(platform != null);
    return null;
  }
}

79
abstract class ApplicationPackage {
80 81
  ApplicationPackage({ @required this.id })
    : assert(id != null);
82

83 84 85
  /// Package ID from the Android Manifest or equivalent.
  final String id;

86 87
  String get name;

88 89
  String get displayName => name;

90
  File get packagesFile => null;
91

92
  @override
93
  String toString() => displayName ?? id;
94 95 96
}

class AndroidApk extends ApplicationPackage {
97
  AndroidApk({
Adam Barth's avatar
Adam Barth committed
98
    String id,
99
    @required this.file,
100
    @required this.versionCode,
101
    @required this.launchActivity,
102
  }) : assert(file != null),
103 104
       assert(launchActivity != null),
       super(id: id);
105

106
  /// Creates a new AndroidApk from an existing APK.
107
  factory AndroidApk.fromApk(File apk) {
108
    final String aaptPath = androidSdk?.latestVersion?.aaptPath;
109
    if (aaptPath == null) {
110
      printError(userMessages.aaptNotFound);
111 112 113
      return null;
    }

114
    final List<String> aaptArgs = <String>[
115 116 117
       aaptPath,
      'dump',
      'xmltree',
118
      apk.path,
119 120 121 122 123
      'AndroidManifest.xml',
    ];

    final ApkManifestData data = ApkManifestData
        .parseFromXmlDump(runCheckedSync(aaptArgs));
124 125

    if (data == null) {
126
      printError('Unable to read manifest info from ${apk.path}.');
127 128 129 130
      return null;
    }

    if (data.packageName == null || data.launchableActivityName == null) {
131
      printError('Unable to read manifest info from ${apk.path}.');
132 133 134
      return null;
    }

135
    return AndroidApk(
136
      id: data.packageName,
137
      file: apk,
138
      versionCode: int.tryParse(data.versionCode),
139
      launchActivity: '${data.packageName}/${data.launchableActivityName}',
140 141 142
    );
  }

143 144 145 146 147 148
  /// Path to the actual apk file.
  final File file;

  /// The path to the activity that should be launched.
  final String launchActivity;

149 150 151
  /// The version code of the APK.
  final int versionCode;

152
  /// Creates a new AndroidApk based on the information in the Android manifest.
153 154
  static Future<AndroidApk> fromAndroidProject(AndroidProject androidProject) async {
    File apkFile;
155

156
    if (androidProject.isUsingGradle) {
157 158
      apkFile = await getGradleAppOut(androidProject);
      if (apkFile.existsSync()) {
159 160
        // Grab information from the .apk. The gradle build script might alter
        // the application Id, so we need to look at what was actually built.
161
        return AndroidApk.fromApk(apkFile);
162 163 164 165
      }
      // 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.
166
    } else {
167
      apkFile = fs.file(fs.path.join(getAndroidBuildDirectory(), 'app.apk'));
168 169
    }

170
    final File manifest = androidProject.appManifestFile;
171

172 173 174
    if (!manifest.existsSync()) {
      printError('AndroidManifest.xml could not be found.');
      printError('Please check ${manifest.path} for errors.');
175
      return null;
176
    }
177

178
    final String manifestString = manifest.readAsStringSync();
179 180 181 182 183 184 185 186 187 188 189 190 191 192
    xml.XmlDocument document;
    try {
      document = xml.parse(manifestString);
    } on xml.XmlParserException catch (exception) {
      String manifestLocation;
      if (androidProject.isUsingGradle) {
        manifestLocation = fs.path.join(androidProject.hostAppGradleRoot.path, 'app', 'src', 'main', 'AndroidManifest.xml');
      } else {
        manifestLocation = fs.path.join(androidProject.hostAppGradleRoot.path, 'AndroidManifest.xml');
      }
      printError('AndroidManifest.xml is not a valid XML document.');
      printError('Please check $manifestLocation for errors.');
      throwToolExit('XML Parser error message: ${exception.toString()}');
    }
193

194
    final Iterable<xml.XmlElement> manifests = document.findElements('manifest');
195 196 197
    if (manifests.isEmpty) {
      printError('AndroidManifest.xml has no manifest element.');
      printError('Please check ${manifest.path} for errors.');
198
      return null;
199
    }
200
    final String packageId = manifests.first.getAttribute('package');
201 202

    String launchActivity;
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    for (xml.XmlElement activity in document.findAllElements('activity')) {
      final String enabled = activity.getAttribute('android:enabled');
      if (enabled != null && enabled == 'false') {
        continue;
      }

      for (xml.XmlElement element in activity.findElements('intent-filter')) {
        String actionName = '';
        String categoryName = '';
        for (xml.XmlNode node in element.children) {
          if (!(node is xml.XmlElement)) {
            continue;
          }
          final xml.XmlElement xmlElement = node;
          final String name = xmlElement.getAttribute('android:name');
          if (name == 'android.intent.action.MAIN') {
            actionName = name;
          } else if (name == 'android.intent.category.LAUNCHER') {
            categoryName = name;
          }
        }
        if (actionName.isNotEmpty && categoryName.isNotEmpty) {
225 226 227 228
          final String activityName = activity.getAttribute('android:name');
          launchActivity = '$packageId/$activityName';
          break;
        }
229 230
      }
    }
231

232 233 234
    if (packageId == null || launchActivity == null) {
      printError('package identifier or launch activity not found.');
      printError('Please check ${manifest.path} for errors.');
235
      return null;
236
    }
237

238
    return AndroidApk(
239
      id: packageId,
240
      file: apkFile,
241
      versionCode: null,
242
      launchActivity: launchActivity,
243
    );
244
  }
245

246
  @override
247
  File get packagesFile => file;
248

249
  @override
250
  String get name => file.basename;
251 252
}

253 254 255 256 257
/// 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 {
258
  IOSApp({@required String projectBundleId}) : super(id: projectBundleId);
259

260
  /// Creates a new IOSApp from an existing app bundle or IPA.
261 262
  factory IOSApp.fromPrebuiltApp(FileSystemEntity applicationBinary) {
    final FileSystemEntityType entityType = fs.typeSync(applicationBinary.path);
263 264
    if (entityType == FileSystemEntityType.notFound) {
      printError(
265
          'File "${applicationBinary.path}" does not exist. Use an app bundle or an ipa.');
266 267
      return null;
    }
268
    Directory bundleDir;
269 270 271
    if (entityType == FileSystemEntityType.directory) {
      final Directory directory = fs.directory(applicationBinary);
      if (!_isBundleDirectory(directory)) {
272
        printError('Folder "${applicationBinary.path}" is not an app bundle.');
273 274 275 276 277
        return null;
      }
      bundleDir = fs.directory(applicationBinary);
    } else {
      // Try to unpack as an ipa.
278
      final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app.');
279 280 281
      addShutdownHook(() async {
        await tempDir.delete(recursive: true);
      }, ShutdownStage.STILL_RECORDING);
282
      os.unzip(fs.file(applicationBinary), tempDir);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
      final Directory payloadDir = fs.directory(
        fs.path.join(tempDir.path, 'Payload'),
      );
      if (!payloadDir.existsSync()) {
        printError(
            'Invalid prebuilt iOS ipa. Does not contain a "Payload" directory.');
        return null;
      }
      try {
        bundleDir = payloadDir.listSync().singleWhere(_isBundleDirectory);
      } on StateError {
        printError(
            'Invalid prebuilt iOS ipa. Does not contain a single app bundle.');
        return null;
      }
298
    }
299
    final String plistPath = fs.path.join(bundleDir.path, 'Info.plist');
300 301 302 303 304 305 306 307 308 309
    if (!fs.file(plistPath).existsSync()) {
      printError('Invalid prebuilt iOS app. Does not contain Info.plist.');
      return null;
    }
    final String id = iosWorkflow.getPlistValueFromFile(
      plistPath,
      plist.kCFBundleIdentifierKey,
    );
    if (id == null) {
      printError('Invalid prebuilt iOS app. Info.plist does not contain bundle identifier');
310
      return null;
311
    }
312

313
    return PrebuiltIOSApp(
314
      bundleDir: bundleDir,
315
      bundleName: fs.path.basename(bundleDir.path),
316 317 318
      projectBundleId: id,
    );
  }
319

320
  factory IOSApp.fromIosProject(IosProject project) {
321
    if (getCurrentHostPlatform() != HostPlatform.darwin_x64) {
322
      return null;
323 324
    }
    if (!project.exists) {
325
      // If the project doesn't exist at all the current hint to run flutter
326 327 328 329 330
      // create is accurate.
      return null;
    }
    if (!project.xcodeProject.existsSync()) {
      printError('Expected ios/Runner.xcodeproj but this file is missing.');
331 332
      return null;
    }
333 334 335 336
    if (!project.xcodeProjectInfoFile.existsSync()) {
      printError('Expected ios/Runner.xcodeproj/project.pbxproj but this file is missing.');
      return null;
    }
337
    return BuildableIOSApp(project);
338
  }
339

340
  @override
341
  String get displayName => id;
342

343 344 345 346 347 348
  String get simulatorBundlePath;

  String get deviceBundlePath;
}

class BuildableIOSApp extends IOSApp {
349
  BuildableIOSApp(this.project) : super(projectBundleId: project.productBundleIdentifier);
350

351
  final IosProject project;
352

353
  @override
354
  String get name => project.hostAppBundleName;
355 356

  @override
357 358
  String get simulatorBundlePath => _buildAppPath('iphonesimulator');

359
  @override
360 361 362
  String get deviceBundlePath => _buildAppPath('iphoneos');

  String _buildAppPath(String type) {
363
    return fs.path.join(getIosBuildDirectory(), type, name);
364
  }
365 366
}

367 368 369 370
class PrebuiltIOSApp extends IOSApp {
  PrebuiltIOSApp({
    this.bundleDir,
    this.bundleName,
371
    @required String projectBundleId,
372 373
  }) : super(projectBundleId: projectBundleId);

374 375 376
  final Directory bundleDir;
  final String bundleName;

377 378 379 380 381 382 383 384 385 386 387 388
  @override
  String get name => bundleName;

  @override
  String get simulatorBundlePath => _bundlePath;

  @override
  String get deviceBundlePath => _bundlePath;

  String get _bundlePath => bundleDir.path;
}

389
class ApplicationPackageStore {
390 391
  ApplicationPackageStore({ this.android, this.iOS });

392 393
  AndroidApk android;
  IOSApp iOS;
394

395
  Future<ApplicationPackage> getPackageForPlatform(TargetPlatform platform) async {
396
    switch (platform) {
397
      case TargetPlatform.android_arm:
398
      case TargetPlatform.android_arm64:
399
      case TargetPlatform.android_x64:
400
      case TargetPlatform.android_x86:
401
        android ??= await AndroidApk.fromAndroidProject(FlutterProject.current().android);
402
        return android;
403
      case TargetPlatform.ios:
404
        iOS ??= IOSApp.fromIosProject(FlutterProject.current().ios);
405
        return iOS;
406 407
      case TargetPlatform.darwin_x64:
      case TargetPlatform.linux_x64:
408
      case TargetPlatform.windows_x64:
409
      case TargetPlatform.fuchsia:
410
      case TargetPlatform.tester:
411
      case TargetPlatform.web:
412 413
        return null;
    }
pq's avatar
pq committed
414
    return null;
415 416
  }
}
417

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
class _Entry {
  _Element parent;
  int level;
}

class _Element extends _Entry {
  _Element.fromLine(String line, _Element parent) {
    //      E: application (line=29)
    final List<String> parts = line.trimLeft().split(' ');
    name = parts[1];
    level = line.length - line.trimLeft().length;
    this.parent = parent;
    children = <_Entry>[];
  }

433 434 435
  List<_Entry> children;
  String name;

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  void addChild(_Entry child) {
    children.add(child);
  }

  _Attribute firstAttribute(String name) {
    return children.firstWhere(
        (_Entry e) => e is _Attribute && e.key.startsWith(name),
        orElse: () => null,
    );
  }

  _Element firstElement(String name) {
    return children.firstWhere(
        (_Entry e) => e is _Element && e.name.startsWith(name),
        orElse: () => null,
    );
  }

  Iterable<_Entry> allElements(String name) {
    return children.where(
            (_Entry e) => e is _Element && e.name.startsWith(name));
  }
}

class _Attribute extends _Entry {
  _Attribute.fromLine(String line, _Element parent) {
    //     A: android:label(0x01010001)="hello_world" (Raw: "hello_world")
    const String attributePrefix = 'A: ';
    final List<String> keyVal = line
        .substring(line.indexOf(attributePrefix) + attributePrefix.length)
        .split('=');
    key = keyVal[0];
    value = keyVal[1];
    level = line.length - line.trimLeft().length;
    this.parent = parent;
  }
472 473 474

  String key;
  String value;
475 476
}

477 478 479
class ApkManifestData {
  ApkManifestData._(this._data);

480
  static ApkManifestData parseFromXmlDump(String data) {
481 482 483
    if (data == null || data.trim().isEmpty)
      return null;

484 485
    final List<String> lines = data.split('\n');
    assert(lines.length > 3);
486

487
    final _Element manifest = _Element.fromLine(lines[1], null);
488
    _Element currentElement = manifest;
489

490 491 492
    for (String line in lines.skip(2)) {
      final String trimLine = line.trimLeft();
      final int level = line.length - trimLine.length;
493

494
      // Handle level out
495
      while (level <= currentElement.level) {
496 497
        currentElement = currentElement.parent;
      }
498

499 500 501 502
      if (level > currentElement.level) {
        switch (trimLine[0]) {
          case 'A':
            currentElement
503
                .addChild(_Attribute.fromLine(line, currentElement));
504 505
            break;
          case 'E':
506
            final _Element element = _Element.fromLine(line, currentElement);
507 508
            currentElement.addChild(element);
            currentElement = element;
509 510 511 512
        }
      }
    }

513 514 515 516 517 518 519 520
    final _Element application = manifest.firstElement('application');
    assert(application != null);

    final Iterable<_Entry> activities = application.allElements('activity');

    _Element launchActivity;
    for (_Element activity in activities) {
      final _Attribute enabled = activity.firstAttribute('android:enabled');
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
      final Iterable<_Element> intentFilters = activity
          .allElements('intent-filter')
          .cast<_Element>();
      final bool isEnabledByDefault = enabled == null;
      final bool isExplicitlyEnabled = enabled != null && enabled.value.contains('0xffffffff');
      if (!(isEnabledByDefault || isExplicitlyEnabled)) {
        continue;
      }

      for (_Element element in intentFilters) {
        final _Element action = element.firstElement('action');
        final _Element category = element.firstElement('category');
        final String actionAttributeValue = action
            ?.firstAttribute('android:name')
            ?.value;
        final String categoryAttributeValue =
            category?.firstAttribute('android:name')?.value;
        final bool isMainAction = actionAttributeValue != null &&
            actionAttributeValue.startsWith('"android.intent.action.MAIN"');
        final bool isLauncherCategory = categoryAttributeValue != null &&
            categoryAttributeValue.startsWith('"android.intent.category.LAUNCHER"');
        if (isMainAction && isLauncherCategory) {
          launchActivity = activity;
          break;
        }
      }
      if (launchActivity != null) {
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
        break;
      }
    }

    final _Attribute package = manifest.firstAttribute('package');
    // "io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world")
    final String packageName = package.value.substring(1, package.value.indexOf('" '));

    if (launchActivity == null) {
      printError('Error running $packageName. Default activity not found');
      return null;
    }

    final _Attribute nameAttribute = launchActivity.firstAttribute('android:name');
    // "io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity")
    final String activityName = nameAttribute
        .value.substring(1, nameAttribute.value.indexOf('" '));

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    // Example format: (type 0x10)0x1
    final _Attribute versionCodeAttr = manifest.firstAttribute('android:versionCode');
    if (versionCodeAttr == null) {
      printError('Error running $packageName. Manifest versionCode not found');
      return null;
    }
    if (!versionCodeAttr.value.startsWith('(type 0x10)')) {
      printError('Error running $packageName. Manifest versionCode invalid');
      return null;
    }
    final int versionCode = int.tryParse(versionCodeAttr.value.substring(11));
    if (versionCode == null) {
      printError('Error running $packageName. Manifest versionCode invalid');
      return null;
    }

582 583
    final Map<String, Map<String, String>> map = <String, Map<String, String>>{};
    map['package'] = <String, String>{'name': packageName};
584
    map['version-code'] = <String, String>{'name': versionCode.toString()};
585 586
    map['launchable-activity'] = <String, String>{'name': activityName};

587
    return ApkManifestData._(map);
588 589 590 591
  }

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

592 593
  @visibleForTesting
  Map<String, Map<String, String>> get data =>
594
      UnmodifiableMapView<String, Map<String, String>>(_data);
595

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

598 599
  String get versionCode => _data['version-code'] == null ? null : _data['version-code']['name'];

600 601 602 603 604 605 606
  String get launchableActivityName {
    return _data['launchable-activity'] == null ? null : _data['launchable-activity']['name'];
  }

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