application_package.dart 10.1 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 'package:xml/xml.dart' as xml;
6

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

17 18
abstract class ApplicationPackage {
  /// Package ID from the Android Manifest or equivalent.
19
  final String id;
20

21
  ApplicationPackage({ this.id }) {
22 23
    assert(id != null);
  }
24

25 26
  String get name;

27 28
  String get displayName => name;

29 30
  String get packagePath => null;

31
  @override
32
  String toString() => displayName;
33 34 35
}

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

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

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

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

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

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

79
  /// Creates a new AndroidApk based on the information in the Android manifest.
80
  factory AndroidApk.fromCurrentDirectory() {
81 82 83 84
    String manifestPath;
    String apkPath;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

185
    return new BuildableIOSApp(
186
      appDirectory: fs.path.join('ios'),
187
      projectBundleId: id
188
    );
189
  }
190

191
  @override
192
  String get displayName => id;
193

194 195 196 197 198 199 200 201 202 203 204 205 206
  String get simulatorBundlePath;

  String get deviceBundlePath;
}

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

  BuildableIOSApp({
    this.appDirectory,
    String projectBundleId,
  }) : super(projectBundleId: projectBundleId);

207 208
  final String appDirectory;

209 210 211 212
  @override
  String get name => kBundleName;

  @override
213 214
  String get simulatorBundlePath => _buildAppPath('iphonesimulator');

215
  @override
216 217 218
  String get deviceBundlePath => _buildAppPath('iphoneos');

  String _buildAppPath(String type) {
219
    return fs.path.join(getIosBuildDirectory(), 'Release-$type', kBundleName);
220
  }
221 222
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
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;
}

247 248 249
ApplicationPackage getApplicationPackageForPlatform(TargetPlatform platform, {
  String applicationBinary
}) {
250 251 252
  switch (platform) {
    case TargetPlatform.android_arm:
    case TargetPlatform.android_x64:
253
    case TargetPlatform.android_x86:
254 255 256
      return applicationBinary == null
          ? new AndroidApk.fromCurrentDirectory()
          : new AndroidApk.fromApk(applicationBinary);
257
    case TargetPlatform.ios:
258 259 260
      return applicationBinary == null
          ? new IOSApp.fromCurrentDirectory()
          : new IOSApp.fromIpa(applicationBinary);
261 262
    case TargetPlatform.darwin_x64:
    case TargetPlatform.linux_x64:
263
    case TargetPlatform.windows_x64:
264
    case TargetPlatform.fuchsia:
265 266
      return null;
  }
pq's avatar
pq committed
267
  assert(platform != null);
pq's avatar
pq committed
268
  return null;
269 270
}

271
class ApplicationPackageStore {
272 273
  AndroidApk android;
  IOSApp iOS;
274

275
  ApplicationPackageStore({ this.android, this.iOS });
276

277
  ApplicationPackage getPackageForPlatform(TargetPlatform platform) {
278
    switch (platform) {
279
      case TargetPlatform.android_arm:
280
      case TargetPlatform.android_x64:
281
      case TargetPlatform.android_x86:
282
        android ??= new AndroidApk.fromCurrentDirectory();
283
        return android;
284
      case TargetPlatform.ios:
285
        iOS ??= new IOSApp.fromCurrentDirectory();
286
        return iOS;
287 288
      case TargetPlatform.darwin_x64:
      case TargetPlatform.linux_x64:
289
      case TargetPlatform.windows_x64:
290
      case TargetPlatform.fuchsia:
291 292
        return null;
    }
pq's avatar
pq committed
293
    return null;
294 295
  }
}
296 297 298 299 300 301 302 303 304

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'
305
    // launchable-activity: name='io.flutter.app.FlutterActivity'  label='' icon=''
306
    final Map<String, Map<String, String>> map = <String, Map<String, String>>{};
307 308

    for (String line in data.split('\n')) {
309
      final int index = line.indexOf(':');
310
      if (index != -1) {
311
        final String name = line.substring(0, index);
312 313
        line = line.substring(index + 1).trim();

314
        final Map<String, String> entries = <String, String>{};
315 316 317 318 319
        map[name] = entries;

        for (String entry in line.split(' ')) {
          entry = entry.trim();
          if (entry.isNotEmpty && entry.contains('=')) {
320 321
            final int split = entry.indexOf('=');
            final String key = entry.substring(0, split);
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
            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();
}