macos.dart 14.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import '../../artifacts.dart';
6
import '../../base/build.dart';
7 8
import '../../base/file_system.dart';
import '../../base/io.dart';
9
import '../../base/process.dart';
10
import '../../build_info.dart';
11
import '../../globals.dart' as globals;
12
import '../../macos/xcode.dart';
13
import '../build_system.dart';
14
import '../depfile.dart';
15
import '../exceptions.dart';
16
import 'assets.dart';
17
import 'dart.dart';
18

19
const String _kOutputPrefix = '{OUTPUT_DIR}/FlutterMacOS.framework';
20 21 22

/// Copy the macOS framework to the correct copy dir by invoking 'cp -R'.
///
23
/// This class is abstract to share logic between the three concrete
24 25
/// implementations. The shelling out is done to avoid complications with
/// preserving special files (e.g., symbolic links) in the framework structure.
26 27 28
///
/// Removes any previous version of the framework that already exists in the
/// target directory.
29 30 31 32 33 34
///
/// The real implementations are:
///   * [DebugUnpackMacOS]
///   * [ProfileUnpackMacOS]
///   * [ReleaseUnpackMacOS]
///
35
// TODO(jonahwilliams): remove shell out.
36 37 38 39
// TODO(jonahwilliams): the subtypes are required to specify the different
// input dependencies as a current limitation of the build system planning.
// This should be resolved after https://github.com/flutter/flutter/issues/38937.
abstract class UnpackMacOS extends Target {
40
  const UnpackMacOS();
41

42 43 44 45 46 47 48
  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/macos.dart'),
  ];

  @override
  List<Source> get outputs => const <Source>[
49 50
    Source.pattern('$_kOutputPrefix/FlutterMacOS'),
    // Headers
51 52 53
    Source.pattern('$_kOutputPrefix/Headers/FlutterDartProject.h'),
    Source.pattern('$_kOutputPrefix/Headers/FlutterEngine.h'),
    Source.pattern('$_kOutputPrefix/Headers/FlutterViewController.h'),
54 55 56
    Source.pattern('$_kOutputPrefix/Headers/FlutterBinaryMessenger.h'),
    Source.pattern('$_kOutputPrefix/Headers/FlutterChannels.h'),
    Source.pattern('$_kOutputPrefix/Headers/FlutterCodecs.h'),
57
    Source.pattern('$_kOutputPrefix/Headers/FlutterMacros.h'),
58 59
    Source.pattern('$_kOutputPrefix/Headers/FlutterPluginMacOS.h'),
    Source.pattern('$_kOutputPrefix/Headers/FlutterPluginRegistrarMacOS.h'),
60
    Source.pattern('$_kOutputPrefix/Headers/FlutterMacOS.h'),
61 62 63 64
    // Modules
    Source.pattern('$_kOutputPrefix/Modules/module.modulemap'),
    // Resources
    Source.pattern('$_kOutputPrefix/Resources/icudtl.dat'),
65
    Source.pattern('$_kOutputPrefix/Resources/Info.plist'),
66
    // Ignore Versions folder for now
67 68 69 70
  ];

  @override
  List<Target> get dependencies => <Target>[];
71

72
  @override
73
  Future<void> build(Environment environment) async {
74 75 76 77
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'unpack_macos');
    }
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
78
    final String basePath = globals.artifacts.getArtifactPath(Artifact.flutterMacOSFramework, mode: buildMode);
79 80
    final Directory targetDirectory = environment
      .outputDir
81
      .childDirectory('FlutterMacOS.framework');
82 83 84
    if (targetDirectory.existsSync()) {
      targetDirectory.deleteSync(recursive: true);
    }
85
    final ProcessResult result = await globals.processManager
86 87 88 89 90 91 92 93 94
        .run(<String>['cp', '-R', basePath, targetDirectory.path]);
    if (result.exitCode != 0) {
      throw Exception(
        'Failed to copy framework (exit ${result.exitCode}:\n'
        '${result.stdout}\n---\n${result.stderr}',
      );
    }
  }
}
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
/// Unpack the release prebuilt engine framework.
class ReleaseUnpackMacOS extends UnpackMacOS {
  const ReleaseUnpackMacOS();

  @override
  String get name => 'release_unpack_macos';

  @override
  List<Source> get inputs => <Source>[
    ...super.inputs,
    const Source.artifact(Artifact.flutterMacOSFramework, mode: BuildMode.release),
  ];
}

/// Unpack the profile prebuilt engine framework.
class ProfileUnpackMacOS extends UnpackMacOS {
  const ProfileUnpackMacOS();

  @override
  String get name => 'profile_unpack_macos';

  @override
  List<Source> get inputs => <Source>[
    ...super.inputs,
    const Source.artifact(Artifact.flutterMacOSFramework, mode: BuildMode.profile),
  ];
}

/// Unpack the debug prebuilt engine framework.
class DebugUnpackMacOS extends UnpackMacOS {
  const DebugUnpackMacOS();

  @override
  String get name => 'debug_unpack_macos';

  @override
  List<Source> get inputs => <Source>[
    ...super.inputs,
    const Source.artifact(Artifact.flutterMacOSFramework, mode: BuildMode.debug),
  ];
}

138 139 140 141 142 143 144 145 146 147 148 149
/// Create an App.framework for debug macOS targets.
///
/// This framework needs to exist for the Xcode project to link/bundle,
/// but it isn't actually executed. To generate something valid, we compile a trivial
/// constant.
class DebugMacOSFramework extends Target {
  const DebugMacOSFramework();

  @override
  String get name => 'debug_macos_framework';

  @override
150
  Future<void> build(Environment environment) async {
151
    final File outputFile = globals.fs.file(globals.fs.path.join(
152
        environment.buildDir.path, 'App.framework', 'App'));
153 154 155 156 157 158 159 160 161 162 163 164 165 166
    outputFile.createSync(recursive: true);
    final File debugApp = environment.buildDir.childFile('debug_app.cc')
        ..writeAsStringSync(r'''
static const int Moo = 88;
''');
    final RunResult result = await xcode.clang(<String>[
      '-x',
      'c',
      debugApp.path,
      '-arch', 'x86_64',
      '-dynamiclib',
      '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
      '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
      '-install_name', '@rpath/App.framework/App',
167
      '-o', outputFile.path,
168 169 170 171 172
    ]);
    if (result.exitCode != 0) {
      throw Exception('Failed to compile debug App.framework');
    }
  }
173 174

  @override
175
  List<Target> get dependencies => const <Target>[];
176 177 178

  @override
  List<Source> get inputs => const <Source>[
179
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/macos.dart'),
180 181 182 183
  ];

  @override
  List<Source> get outputs => const <Source>[
184
    Source.pattern('{BUILD_DIR}/App.framework/App'),
185
  ];
186 187
}

188 189 190 191 192 193 194
class CompileMacOSFramework extends Target {
  const CompileMacOSFramework();

  @override
  String get name => 'compile_macos_framework';

  @override
195
  Future<void> build(Environment environment) async {
196 197 198 199 200 201 202 203 204 205 206 207 208 209
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'compile_macos_framework');
    }
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
    if (buildMode == BuildMode.debug) {
      throw Exception('precompiled macOS framework only supported in release/profile builds.');
    }
    final int result = await AOTSnapshotter(reportTimings: false).build(
      bitcode: false,
      buildMode: buildMode,
      mainPath: environment.buildDir.childFile('app.dill').path,
      outputPath: environment.buildDir.path,
      platform: TargetPlatform.darwin_x64,
      darwinArch: DarwinArch.x86_64,
210
      packagesPath: environment.projectDir.childFile('.packages').path,
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    );
    if (result != 0) {
      throw Exception('gen shapshot failed.');
    }
  }

  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
  ];

  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{BUILD_DIR}/app.dill'),
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/macos.dart'),
    Source.artifact(Artifact.genSnapshot, mode: BuildMode.release, platform: TargetPlatform.darwin_x64),
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{BUILD_DIR}/App.framework/App'),
  ];
}

/// Bundle the flutter assets into the App.framework.
///
/// In debug mode, also include the app.dill and precompiled runtimes.
238 239 240
///
/// See https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkAnatomy.html
/// for more information on Framework structure.
241 242
abstract class MacOSBundleFlutterAssets extends Target {
  const MacOSBundleFlutterAssets();
243 244

  @override
245
  List<Source> get inputs => const <Source>[
246
    Source.pattern('{BUILD_DIR}/App.framework/App'),
247 248 249 250
  ];

  @override
  List<Source> get outputs => const <Source>[
251 252
    Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/App'),
    Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/Info.plist'),
253 254 255 256 257
  ];

  @override
  List<String> get depfiles => const <String>[
    'flutter_assets.d',
258
  ];
259 260

  @override
261
  Future<void> build(Environment environment) async {
262 263 264 265
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'compile_macos_framework');
    }
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
266 267
    final Directory frameworkRootDirectory = environment
        .outputDir
268 269 270 271 272 273 274 275 276 277 278 279
        .childDirectory('App.framework');
    final Directory outputDirectory = frameworkRootDirectory
        .childDirectory('Versions')
        .childDirectory('A')
        ..createSync(recursive: true);

    // Copy App into framework directory.
    environment.buildDir
      .childDirectory('App.framework')
      .childFile('App')
      .copySync(outputDirectory.childFile('App').path);

280
    // Copy assets into asset directory.
281 282 283 284
    final Directory assetDirectory = outputDirectory
      .childDirectory('Resources')
      .childDirectory('flutter_assets');
    assetDirectory.createSync(recursive: true);
285 286 287
    final Depfile depfile = await copyAssets(environment, assetDirectory);
    depfile.writeToFile(environment.buildDir.childFile('flutter_assets.d'));

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    // Copy Info.plist template.
    assetDirectory.parent.childFile('Info.plist')
      ..createSync()
      ..writeAsStringSync(r'''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleExecutable</key>
	<string>App</string>
	<key>CFBundleIdentifier</key>
	<string>io.flutter.flutter.app</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>App</string>
	<key>CFBundlePackageType</key>
	<string>FMWK</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleVersion</key>
	<string>1.0</string>
</dict>
</plist>

''');
316 317 318 319 320 321 322 323 324 325
    if (buildMode == BuildMode.debug) {
      // Copy dill file.
      try {
        final File sourceFile = environment.buildDir.childFile('app.dill');
        sourceFile.copySync(assetDirectory.childFile('kernel_blob.bin').path);
      } catch (err) {
        throw Exception('Failed to copy app.dill: $err');
      }
      // Copy precompiled runtimes.
      try {
326
        final String vmSnapshotData = globals.artifacts.getArtifactPath(Artifact.vmSnapshotData,
327
            platform: TargetPlatform.darwin_x64, mode: BuildMode.debug);
328
        final String isolateSnapshotData = globals.artifacts.getArtifactPath(Artifact.isolateSnapshotData,
329
            platform: TargetPlatform.darwin_x64, mode: BuildMode.debug);
330
        globals.fs.file(vmSnapshotData).copySync(
331
            assetDirectory.childFile('vm_snapshot_data').path);
332
        globals.fs.file(isolateSnapshotData).copySync(
333 334 335 336
            assetDirectory.childFile('isolate_snapshot_data').path);
      } catch (err) {
        throw Exception('Failed to copy precompiled runtimes: $err');
      }
337
    }
338 339 340
    // Create symlink to current version. These must be relative, from the
    // framework root for Resources/App and from the versions root for
    // Current.
341 342 343 344
    try {
      final Link currentVersion = outputDirectory.parent
          .childLink('Current');
      if (!currentVersion.existsSync()) {
345
        final String linkPath = globals.fs.path.relative(outputDirectory.path,
346
            from: outputDirectory.parent.path);
347
        currentVersion.createSync(linkPath);
348 349 350 351 352
      }
      // Create symlink to current resources.
      final Link currentResources = frameworkRootDirectory
          .childLink('Resources');
      if (!currentResources.existsSync()) {
353
        final String linkPath = globals.fs.path.relative(globals.fs.path.join(currentVersion.path, 'Resources'),
354 355
            from: frameworkRootDirectory.path);
        currentResources.createSync(linkPath);
356 357 358 359 360
      }
      // Create symlink to current binary.
      final Link currentFramework = frameworkRootDirectory
          .childLink('App');
      if (!currentFramework.existsSync()) {
361
        final String linkPath = globals.fs.path.relative(globals.fs.path.join(currentVersion.path, 'App'),
362 363
            from: frameworkRootDirectory.path);
        currentFramework.createSync(linkPath);
364 365 366
      }
    } on FileSystemException {
      throw Exception('Failed to create symlinks for framework. try removing '
367
        'the "${environment.outputDir.path}" directory and rerunning');
368
    }
369
  }
370 371 372 373 374 375 376 377
}

/// Bundle the debug flutter assets into the App.framework.
class DebugMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
  const DebugMacOSBundleFlutterAssets();

  @override
  String get name => 'debug_macos_bundle_flutter_assets';
378 379 380 381

  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
382
    DebugMacOSFramework(),
383
    DebugUnpackMacOS(),
384 385 386
  ];

  @override
387 388 389 390 391
  List<Source> get inputs => <Source>[
    ...super.inputs,
    const Source.pattern('{BUILD_DIR}/app.dill'),
    const Source.artifact(Artifact.isolateSnapshotData, platform: TargetPlatform.darwin_x64, mode: BuildMode.debug),
    const Source.artifact(Artifact.vmSnapshotData, platform: TargetPlatform.darwin_x64, mode: BuildMode.debug),
392 393 394
  ];

  @override
395 396
  List<Source> get outputs => <Source>[
    ...super.outputs,
397 398 399
    const Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/flutter_assets/kernel_blob.bin'),
    const Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/flutter_assets/vm_snapshot_data'),
    const Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/flutter_assets/isolate_snapshot_data'),
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
  ];
}

/// Bundle the profile flutter assets into the App.framework.
class ProfileMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
  const ProfileMacOSBundleFlutterAssets();

  @override
  String get name => 'profile_macos_bundle_flutter_assets';

  @override
  List<Target> get dependencies => const <Target>[
    CompileMacOSFramework(),
    ProfileUnpackMacOS(),
  ];
}


/// Bundle the release flutter assets into the App.framework.
class ReleaseMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
  const ReleaseMacOSBundleFlutterAssets();

  @override
  String get name => 'release_macos_bundle_flutter_assets';

  @override
  List<Target> get dependencies => const <Target>[
    CompileMacOSFramework(),
    ReleaseUnpackMacOS(),
429 430
  ];
}