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 25
  ApplicationPackage({ @required this.id })
    : assert(id != null);
26

27 28
  String get name;

29 30
  String get displayName => name;

31 32
  String get packagePath => null;

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

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

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

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

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

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

    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}'
    );
  }

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

    if (isProjectUsingGradle()) {
86
      apkPath = await getGradleAppOut();
87
      if (fs.file(apkPath).existsSync()) {
88 89
        // Grab information from the .apk. The gradle build script might alter
        // the application Id, so we need to look at what was actually built.
90
        return new AndroidApk.fromApk(apkPath);
91 92 93 94
      }
      // 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.
95
      manifestPath = gradleManifestPath;
96
    } else {
97 98
      manifestPath = fs.path.join('android', 'AndroidManifest.xml');
      apkPath = fs.path.join(getAndroidBuildDirectory(), 'app.apk');
99 100
    }

101
    if (!fs.isFileSync(manifestPath))
102
      return null;
103

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

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

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

    if (packageId == null || launchActivity == null)
123 124
      return null;

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

132 133 134
  @override
  String get packagePath => apkPath;

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

139 140 141 142 143 144 145 146 147 148 149
/// 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 {
150
      final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app_');
151 152 153
      addShutdownHook(() async {
        await tempDir.delete(recursive: true);
      }, ShutdownStage.STILL_RECORDING);
154
      os.unzip(fs.file(applicationBinary), tempDir);
155
      final Directory payloadDir = fs.directory(fs.path.join(tempDir.path, 'Payload'));
156 157
      bundleDir = payloadDir.listSync().singleWhere(_isBundleDirectory);
    } on StateError catch (e, stackTrace) {
158
      printError('Invalid prebuilt iOS binary: ${e.toString()}', stackTrace: stackTrace);
159 160
      return null;
    }
161

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

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

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

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

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

194
  @override
195
  String get displayName => id;
196

197 198 199 200 201 202 203 204 205 206 207
  String get simulatorBundlePath;

  String get deviceBundlePath;
}

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

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

211 212
  final String appDirectory;

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

216 217 218 219
  @override
  String get name => kBundleName;

  @override
220 221
  String get simulatorBundlePath => _buildAppPath('iphonesimulator');

222
  @override
223 224
  String get deviceBundlePath => _buildAppPath('iphoneos');

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

228
  String _buildAppPath(String type) {
229
    return fs.path.join(getIosBuildDirectory(), type, kBundleName);
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
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;
}

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

281
class ApplicationPackageStore {
282 283
  AndroidApk android;
  IOSApp iOS;
284

285
  ApplicationPackageStore({ this.android, this.iOS });
286

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

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'
315
    // launchable-activity: name='io.flutter.app.FlutterActivity'  label='' icon=''
316
    final Map<String, Map<String, String>> map = <String, Map<String, String>>{};
317 318

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

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

        for (String entry in line.split(' ')) {
          entry = entry.trim();
          if (entry.isNotEmpty && entry.contains('=')) {
330 331
            final int split = entry.indexOf('=');
            final String key = entry.substring(0, split);
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
            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();
}