forked from firka/flutter
Font subset in the tool (#49737)
This commit is contained in:
@@ -338,6 +338,9 @@ Future<void> buildGradleApp({
|
||||
if (androidBuildInfo.fastStart) {
|
||||
command.add('-Pfast-start=true');
|
||||
}
|
||||
if (androidBuildInfo.buildInfo.treeShakeIcons) {
|
||||
command.add('-Ptree-shake-icons=true');
|
||||
}
|
||||
command.add(assembleTask);
|
||||
|
||||
GradleHandledError detectedGradleError;
|
||||
@@ -546,6 +549,9 @@ Future<void> buildGradleAar({
|
||||
command.add('-Plocal-engine-repo=${localEngineRepo.path}');
|
||||
command.add('-Plocal-engine-build-mode=${androidBuildInfo.buildInfo.modeName}');
|
||||
command.add('-Plocal-engine-out=${localEngineArtifacts.engineOutPath}');
|
||||
if (androidBuildInfo.buildInfo.treeShakeIcons) {
|
||||
command.add('-Pfont-subset=true');
|
||||
}
|
||||
|
||||
// Copy the local engine repo in the output directory.
|
||||
try {
|
||||
@@ -738,10 +744,11 @@ Future<void> buildPluginsAsAar(
|
||||
try {
|
||||
await buildGradleAar(
|
||||
project: FlutterProject.fromDirectory(pluginDirectory),
|
||||
androidBuildInfo: const AndroidBuildInfo(
|
||||
androidBuildInfo: AndroidBuildInfo(
|
||||
BuildInfo(
|
||||
BuildMode.release, // Plugins are built as release.
|
||||
null, // Plugins don't define flavors.
|
||||
treeShakeIcons: androidBuildInfo.buildInfo.treeShakeIcons,
|
||||
),
|
||||
),
|
||||
target: '',
|
||||
|
||||
@@ -36,6 +36,7 @@ class AotBuilder {
|
||||
List<String> extraFrontEndOptions,
|
||||
List<String> extraGenSnapshotOptions,
|
||||
@required List<String> dartDefines,
|
||||
@required bool treeShakeIcons,
|
||||
}) async {
|
||||
if (platform == null) {
|
||||
throwToolExit('No AOT build platform specified');
|
||||
|
||||
@@ -367,7 +367,10 @@ class CachedArtifacts extends Artifacts {
|
||||
return _fileSystem.path.join(dartPackageDirectory.path, _artifactToFileName(artifact));
|
||||
case Artifact.fontSubset:
|
||||
case Artifact.constFinder:
|
||||
return _cache.getArtifactDirectory('font-subset').childFile(_artifactToFileName(artifact, platform, mode)).path;
|
||||
return _cache.getArtifactDirectory('engine')
|
||||
.childDirectory(getNameForTargetPlatform(platform))
|
||||
.childFile(_artifactToFileName(artifact, platform, mode))
|
||||
.path;
|
||||
default:
|
||||
assert(false, 'Artifact $artifact not available for platform $platform.');
|
||||
return null;
|
||||
|
||||
@@ -21,6 +21,8 @@ const AssetBundleFactory _kManifestFactory = _ManifestAssetBundleFactory();
|
||||
|
||||
const String defaultManifestPath = 'pubspec.yaml';
|
||||
|
||||
const String kFontManifestJson = 'FontManifest.json';
|
||||
|
||||
/// Injected factory class for spawning [AssetBundle] instances.
|
||||
abstract class AssetBundleFactory {
|
||||
/// The singleton instance, pulled from the [AppContext].
|
||||
@@ -71,7 +73,6 @@ class _ManifestAssetBundle implements AssetBundle {
|
||||
DateTime _lastBuildTimestamp;
|
||||
|
||||
static const String _assetManifestJson = 'AssetManifest.json';
|
||||
static const String _fontManifestJson = 'FontManifest.json';
|
||||
static const String _fontSetMaterial = 'material';
|
||||
static const String _license = 'LICENSE';
|
||||
|
||||
@@ -242,7 +243,7 @@ class _ManifestAssetBundle implements AssetBundle {
|
||||
|
||||
entries[_assetManifestJson] = _createAssetManifest(assetVariants);
|
||||
|
||||
entries[_fontManifestJson] = DevFSStringContent(json.encode(fonts));
|
||||
entries[kFontManifestJson] = DevFSStringContent(json.encode(fonts));
|
||||
|
||||
// TODO(ianh): Only do the following line if we've changed packages or if our LICENSE file changed
|
||||
entries[_license] = _obtainLicenses(packageMap, assetBasePath, reportPackages: reportLicensedPackages);
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
import 'base/context.dart';
|
||||
import 'base/utils.dart';
|
||||
import 'build_system/targets/icon_tree_shaker.dart';
|
||||
import 'globals.dart' as globals;
|
||||
|
||||
/// Information about a build to be performed or used.
|
||||
@@ -18,10 +21,14 @@ class BuildInfo {
|
||||
this.fileSystemScheme,
|
||||
this.buildNumber,
|
||||
this.buildName,
|
||||
@required this.treeShakeIcons,
|
||||
});
|
||||
|
||||
final BuildMode mode;
|
||||
|
||||
/// Whether the build should subdset icon fonts.
|
||||
final bool treeShakeIcons;
|
||||
|
||||
/// Represents a custom Android product flavor or an Xcode scheme, null for
|
||||
/// using the default.
|
||||
///
|
||||
@@ -55,10 +62,10 @@ class BuildInfo {
|
||||
/// On Xcode builds it is used as CFBundleShortVersionString,
|
||||
final String buildName;
|
||||
|
||||
static const BuildInfo debug = BuildInfo(BuildMode.debug, null);
|
||||
static const BuildInfo profile = BuildInfo(BuildMode.profile, null);
|
||||
static const BuildInfo jitRelease = BuildInfo(BuildMode.jitRelease, null);
|
||||
static const BuildInfo release = BuildInfo(BuildMode.release, null);
|
||||
static const BuildInfo debug = BuildInfo(BuildMode.debug, null, treeShakeIcons: false);
|
||||
static const BuildInfo profile = BuildInfo(BuildMode.profile, null, treeShakeIcons: kIconTreeShakerEnabledDefault);
|
||||
static const BuildInfo jitRelease = BuildInfo(BuildMode.jitRelease, null, treeShakeIcons: kIconTreeShakerEnabledDefault);
|
||||
static const BuildInfo release = BuildInfo(BuildMode.release, null, treeShakeIcons: kIconTreeShakerEnabledDefault);
|
||||
|
||||
/// Returns whether a debug build is requested.
|
||||
///
|
||||
|
||||
@@ -12,6 +12,7 @@ import '../depfile.dart';
|
||||
import '../exceptions.dart';
|
||||
import 'assets.dart';
|
||||
import 'dart.dart';
|
||||
import 'icon_tree_shaker.dart';
|
||||
|
||||
/// Prepares the asset bundle in the format expected by flutter.gradle.
|
||||
///
|
||||
@@ -25,6 +26,7 @@ abstract class AndroidAssetBundle extends Target {
|
||||
@override
|
||||
List<Source> get inputs => const <Source>[
|
||||
Source.pattern('{BUILD_DIR}/app.dill'),
|
||||
...IconTreeShaker.inputs,
|
||||
];
|
||||
|
||||
@override
|
||||
|
||||
@@ -12,6 +12,8 @@ import '../../plugins.dart';
|
||||
import '../../project.dart';
|
||||
import '../build_system.dart';
|
||||
import '../depfile.dart';
|
||||
import 'dart.dart';
|
||||
import 'icon_tree_shaker.dart';
|
||||
|
||||
/// A helper function to copy an asset bundle into an [environment]'s output
|
||||
/// directory.
|
||||
@@ -31,6 +33,16 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory) a
|
||||
pubspecFile,
|
||||
];
|
||||
final List<File> outputs = <File>[];
|
||||
|
||||
final IconTreeShaker iconTreeShaker = IconTreeShaker(
|
||||
environment,
|
||||
assetBundle.entries[kFontManifestJson] as DevFSStringContent,
|
||||
processManager: globals.processManager,
|
||||
logger: globals.logger,
|
||||
fileSystem: globals.fs,
|
||||
artifacts: globals.artifacts,
|
||||
);
|
||||
|
||||
await Future.wait<void>(
|
||||
assetBundle.entries.entries.map<Future<void>>((MapEntry<String, DevFSContent> entry) async {
|
||||
final PoolResource resource = await pool.request();
|
||||
@@ -46,7 +58,13 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory) a
|
||||
final DevFSContent content = entry.value;
|
||||
if (content is DevFSFileContent && content.file is File) {
|
||||
inputs.add(globals.fs.file(content.file.path));
|
||||
await (content.file as File).copy(file.path);
|
||||
if (!await iconTreeShaker.subsetFont(
|
||||
inputPath: content.file.path,
|
||||
outputPath: file.path,
|
||||
relativePath: entry.key,
|
||||
)) {
|
||||
await (content.file as File).copy(file.path);
|
||||
}
|
||||
} else {
|
||||
await file.writeAsBytes(await entry.value.contentsAsBytes());
|
||||
}
|
||||
@@ -65,11 +83,14 @@ class CopyAssets extends Target {
|
||||
String get name => 'copy_assets';
|
||||
|
||||
@override
|
||||
List<Target> get dependencies => const <Target>[];
|
||||
List<Target> get dependencies => const <Target>[
|
||||
KernelSnapshot(),
|
||||
];
|
||||
|
||||
@override
|
||||
List<Source> get inputs => const <Source>[
|
||||
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/assets.dart'),
|
||||
...IconTreeShaker.inputs,
|
||||
];
|
||||
|
||||
@override
|
||||
|
||||
@@ -14,6 +14,7 @@ import '../build_system.dart';
|
||||
import '../depfile.dart';
|
||||
import '../exceptions.dart';
|
||||
import 'assets.dart';
|
||||
import 'icon_tree_shaker.dart';
|
||||
|
||||
/// The define to pass a [BuildMode].
|
||||
const String kBuildMode= 'BuildMode';
|
||||
@@ -75,6 +76,7 @@ class CopyFlutterBundle extends Target {
|
||||
Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug),
|
||||
Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug),
|
||||
Source.pattern('{BUILD_DIR}/app.dill'),
|
||||
...IconTreeShaker.inputs,
|
||||
];
|
||||
|
||||
@override
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:process/process.dart';
|
||||
|
||||
import '../../artifacts.dart';
|
||||
import '../../base/common.dart';
|
||||
import '../../base/file_system.dart';
|
||||
import '../../base/io.dart';
|
||||
import '../../base/logger.dart';
|
||||
import '../../convert.dart';
|
||||
import '../../devfs.dart';
|
||||
import '../build_system.dart';
|
||||
import 'dart.dart';
|
||||
|
||||
/// The build define controlling whether icon fonts should be stripped down to
|
||||
/// only the glyphs used by the application.
|
||||
const String kIconTreeShakerFlag = 'TreeShakeIcons';
|
||||
|
||||
/// Whether icon font subsetting is enabled by default.
|
||||
const bool kIconTreeShakerEnabledDefault = false;
|
||||
|
||||
List<Map<String, dynamic>> _getList(dynamic object, String errorMessage) {
|
||||
try {
|
||||
return (object as List<dynamic>).cast<Map<String, dynamic>>();
|
||||
} on CastError catch (_) {
|
||||
throw IconTreeShakerException._(errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/// A class that wraps the functionality of the const finder package and the
|
||||
/// font subset utility to tree shake unused icons from fonts.
|
||||
class IconTreeShaker {
|
||||
/// Creates a wrapper for icon font subsetting.
|
||||
///
|
||||
/// The environment parameter must not be null.
|
||||
///
|
||||
/// If the `fontManifest` parameter is null, [enabled] will return false since
|
||||
/// there are no fonts to shake.
|
||||
///
|
||||
/// The constructor will validate the environment and print a warning if
|
||||
/// font subsetting has been requested in a debug build mode.
|
||||
IconTreeShaker(
|
||||
this._environment,
|
||||
DevFSStringContent fontManifest, {
|
||||
@required ProcessManager processManager,
|
||||
@required Logger logger,
|
||||
@required FileSystem fileSystem,
|
||||
@required Artifacts artifacts,
|
||||
}) : assert(_environment != null),
|
||||
assert(processManager != null),
|
||||
assert(logger != null),
|
||||
assert(fileSystem != null),
|
||||
assert(artifacts != null),
|
||||
_processManager = processManager,
|
||||
_logger = logger,
|
||||
_fs = fileSystem,
|
||||
_artifacts = artifacts,
|
||||
_fontManifest = fontManifest?.string {
|
||||
if (_environment.defines[kIconTreeShakerFlag] == 'true' &&
|
||||
_environment.defines[kBuildMode] == 'debug') {
|
||||
logger.printError('Font subetting is not supported in debug mode. The '
|
||||
'--tree-shake-icons flag will be ignored.');
|
||||
}
|
||||
}
|
||||
|
||||
/// The [Source] inputs that targets using this should depend on.
|
||||
///
|
||||
/// See [Target.inputs].
|
||||
static const List<Source> inputs = <Source>[
|
||||
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/icon_tree_shaker.dart'),
|
||||
Source.artifact(Artifact.constFinder),
|
||||
Source.artifact(Artifact.fontSubset),
|
||||
];
|
||||
|
||||
final Environment _environment;
|
||||
final String _fontManifest;
|
||||
Map<String, _IconTreeShakerData> _iconData;
|
||||
|
||||
final ProcessManager _processManager;
|
||||
final Logger _logger;
|
||||
final FileSystem _fs;
|
||||
final Artifacts _artifacts;
|
||||
|
||||
/// Whether font subsetting should be used for this [Environment].
|
||||
bool get enabled => _fontManifest != null
|
||||
&& _environment.defines[kIconTreeShakerFlag] == 'true'
|
||||
&& _environment.defines[kBuildMode] != 'debug';
|
||||
|
||||
/// Fills the [_iconData] map.
|
||||
Future<Map<String, _IconTreeShakerData>> _getIconData(Environment environment) async {
|
||||
if (!enabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final File appDill = environment.buildDir.childFile('app.dill');
|
||||
if (!appDill.existsSync()) {
|
||||
throw IconTreeShakerException._('Expected to find kernel file at ${appDill.path}, but no file found.');
|
||||
}
|
||||
final File constFinder = _fs.file(
|
||||
_artifacts.getArtifactPath(Artifact.constFinder),
|
||||
);
|
||||
final File dart = _fs.file(
|
||||
_artifacts.getArtifactPath(Artifact.engineDartBinary),
|
||||
);
|
||||
|
||||
final Map<String, List<int>> iconData = await _findConstants(
|
||||
dart,
|
||||
constFinder,
|
||||
appDill,
|
||||
);
|
||||
final Set<String> familyKeys = iconData.keys.toSet();
|
||||
|
||||
final Map<String, String> fonts = await _parseFontJson(
|
||||
_fontManifest,
|
||||
familyKeys,
|
||||
);
|
||||
|
||||
if (fonts.length != iconData.length) {
|
||||
throwToolExit('Expected to find fonts for ${iconData.keys}, but found '
|
||||
'${fonts.keys}. This usually means you are refering to '
|
||||
'font families in an IconData class but not including them '
|
||||
'in the assets section of your pubspec.yaml, are missing '
|
||||
'the package that would include them, or are missing '
|
||||
'"uses-material-design: true".');
|
||||
}
|
||||
|
||||
final Map<String, _IconTreeShakerData> result = <String, _IconTreeShakerData>{};
|
||||
for (final MapEntry<String, String> entry in fonts.entries) {
|
||||
result[entry.value] = _IconTreeShakerData(
|
||||
family: entry.key,
|
||||
relativePath: entry.value,
|
||||
codePoints: iconData[entry.key],
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Calls font-subset, which transforms the `inputPath` font file to a
|
||||
/// subsetted version at `outputPath`.
|
||||
///
|
||||
/// The `relativePath` parameter
|
||||
///
|
||||
/// All parameters are required.
|
||||
///
|
||||
/// If [enabled] is false, or the relative path is not recognized as an icon
|
||||
/// font used in the Flutter application, this returns false.
|
||||
/// If the font-subset subprocess fails, it will [throwToolExit].
|
||||
/// Otherwise, it will return true.
|
||||
Future<bool> subsetFont({
|
||||
@required String inputPath,
|
||||
@required String outputPath,
|
||||
@required String relativePath,
|
||||
}) async {
|
||||
if (!enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_iconData ??= await _getIconData(_environment);
|
||||
assert(_iconData != null);
|
||||
|
||||
final _IconTreeShakerData iconTreeShakerData = _iconData[relativePath];
|
||||
if (iconTreeShakerData == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final File fontSubset = _fs.file(
|
||||
_artifacts.getArtifactPath(Artifact.fontSubset),
|
||||
);
|
||||
if (!fontSubset.existsSync()) {
|
||||
throw IconTreeShakerException._('The font-subset utility is missing. Run "flutter doctor".');
|
||||
}
|
||||
|
||||
final List<String> cmd = <String>[
|
||||
fontSubset.path,
|
||||
outputPath,
|
||||
inputPath,
|
||||
];
|
||||
final String codePoints = iconTreeShakerData.codePoints.join(' ');
|
||||
_logger.printTrace('Running font-subset: ${cmd.join(' ')}, '
|
||||
'using codepoints $codePoints');
|
||||
final Process fontSubsetProcess = await _processManager.start(cmd);
|
||||
try {
|
||||
fontSubsetProcess.stdin.writeln(codePoints);
|
||||
await fontSubsetProcess.stdin.flush();
|
||||
await fontSubsetProcess.stdin.close();
|
||||
} on Exception catch (_) {
|
||||
// handled by checking the exit code.
|
||||
} on OSError catch (_) {
|
||||
// handled by checking the exit code.
|
||||
}
|
||||
|
||||
final int code = await fontSubsetProcess.exitCode;
|
||||
if (code != 0) {
|
||||
_logger.printTrace(await utf8.decodeStream(fontSubsetProcess.stdout));
|
||||
_logger.printError(await utf8.decodeStream(fontSubsetProcess.stderr));
|
||||
throw IconTreeShakerException._('Font subsetting failed with exit code $code.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Returns a map of { fontFamly: relativePath } pairs.
|
||||
Future<Map<String, String>> _parseFontJson(
|
||||
String fontManifestData,
|
||||
Set<String> families,
|
||||
) async {
|
||||
final Map<String, String> result = <String, String>{};
|
||||
final List<Map<String, dynamic>> fontList = _getList(
|
||||
json.decode(fontManifestData),
|
||||
'FontManifest.json invalid: expected top level to be a list of objects.',
|
||||
);
|
||||
|
||||
for (final Map<String, dynamic> map in fontList) {
|
||||
if (map['family'] is! String) {
|
||||
throw IconTreeShakerException._(
|
||||
'FontManifest.json invalid: expected the family value to be a string, '
|
||||
'got: ${map['family']}.');
|
||||
}
|
||||
final String familyKey = map['family'] as String;
|
||||
if (!families.contains(familyKey)) {
|
||||
continue;
|
||||
}
|
||||
final List<Map<String, dynamic>> fonts = _getList(
|
||||
map['fonts'],
|
||||
'FontManifest.json invalid: expected "fonts" to be a list of objects.',
|
||||
);
|
||||
if (fonts.length != 1) {
|
||||
throw IconTreeShakerException._(
|
||||
'This tool cannot process icon fonts with multiple fonts in a '
|
||||
'single family.');
|
||||
}
|
||||
if (fonts.first['asset'] is! String) {
|
||||
throw IconTreeShakerException._(
|
||||
'FontManifest.json invalid: expected "asset" value to be a string, '
|
||||
'got: ${map['assets']}.');
|
||||
}
|
||||
result[familyKey] = fonts.first['asset'] as String;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<Map<String, List<int>>> _findConstants(
|
||||
File dart,
|
||||
File constFinder,
|
||||
File appDill,
|
||||
) async {
|
||||
final List<String> cmd = <String>[
|
||||
dart.path,
|
||||
constFinder.path,
|
||||
'--kernel-file', appDill.path,
|
||||
'--class-library-uri', 'package:flutter/src/widgets/icon_data.dart',
|
||||
'--class-name', 'IconData',
|
||||
];
|
||||
_logger.printTrace('Running command: ${cmd.join(' ')}');
|
||||
final ProcessResult constFinderProcessResult = await _processManager.run(cmd);
|
||||
|
||||
if (constFinderProcessResult.exitCode != 0) {
|
||||
throw IconTreeShakerException._('ConstFinder failure: ${constFinderProcessResult.stderr}');
|
||||
}
|
||||
final dynamic jsonDecode = json.decode(constFinderProcessResult.stdout as String);
|
||||
if (jsonDecode is! Map<String, dynamic>) {
|
||||
throw IconTreeShakerException._(
|
||||
'Invalid ConstFinder output: expected a top level JSON object, '
|
||||
'got $jsonDecode.');
|
||||
}
|
||||
final Map<String, dynamic> constFinderMap = jsonDecode as Map<String, dynamic>;
|
||||
final _ConstFinderResult constFinderResult = _ConstFinderResult(constFinderMap);
|
||||
if (constFinderResult.hasNonConstantLocations) {
|
||||
_logger.printError('This application cannot tree shake icons fonts. '
|
||||
'It has non-constant instances of IconData at the '
|
||||
'following locations:', emphasis: true);
|
||||
for (final Map<String, dynamic> location in constFinderResult.nonConstantLocations) {
|
||||
_logger.printError(
|
||||
'- ${location['file']}:${location['line']}:${location['column']}',
|
||||
indent: 2,
|
||||
hangingIndent: 4,
|
||||
);
|
||||
}
|
||||
throwToolExit('Avoid non-constant invocations of IconData or try to '
|
||||
'build again with --no-tree-shake-icons.');
|
||||
}
|
||||
return _parseConstFinderResult(constFinderResult);
|
||||
}
|
||||
|
||||
Map<String, List<int>> _parseConstFinderResult(_ConstFinderResult consts) {
|
||||
final Map<String, List<int>> result = <String, List<int>>{};
|
||||
for (final Map<String, dynamic> iconDataMap in consts.constantInstances) {
|
||||
if ((iconDataMap['fontPackage'] ?? '') is! String || // Null is ok here.
|
||||
iconDataMap['fontFamily'] is! String ||
|
||||
iconDataMap['codePoint'] is! int) {
|
||||
throw IconTreeShakerException._(
|
||||
'Invalid ConstFinder result. Expected "fontPackage" to be a String, '
|
||||
'"fontFamily" to be a String, and "codePoint" to be an int, '
|
||||
'got: $iconDataMap.');
|
||||
}
|
||||
final String package = iconDataMap['fontPackage'] as String;
|
||||
final String family = iconDataMap['fontFamily'] as String;
|
||||
final String key = package == null
|
||||
? family
|
||||
: 'packages/$package/$family';
|
||||
result[key] ??= <int>[];
|
||||
result[key].add(iconDataMap['codePoint'] as int);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
class _ConstFinderResult {
|
||||
_ConstFinderResult(this.result);
|
||||
|
||||
final Map<String, dynamic> result;
|
||||
|
||||
List<Map<String, dynamic>> _constantInstances;
|
||||
List<Map<String, dynamic>> get constantInstances {
|
||||
_constantInstances ??= _getList(
|
||||
result['constantInstances'],
|
||||
'Invalid ConstFinder output: Expected "constInstances" to be a list of objects.',
|
||||
);
|
||||
return _constantInstances;
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> _nonConstantLocations;
|
||||
List<Map<String, dynamic>> get nonConstantLocations {
|
||||
_nonConstantLocations ??= _getList(
|
||||
result['nonConstantLocations'],
|
||||
'Invalid ConstFinder output: Expected "nonConstLocations" to be a list ofobjects',
|
||||
);
|
||||
return _nonConstantLocations;
|
||||
}
|
||||
|
||||
bool get hasNonConstantLocations => nonConstantLocations.isNotEmpty;
|
||||
}
|
||||
|
||||
/// The font family name, relative path to font file, and list of code points
|
||||
/// the application is using.
|
||||
class _IconTreeShakerData {
|
||||
/// All parameters are required.
|
||||
const _IconTreeShakerData({
|
||||
@required this.family,
|
||||
@required this.relativePath,
|
||||
@required this.codePoints,
|
||||
}) : assert(family != null),
|
||||
assert(relativePath != null),
|
||||
assert(codePoints != null);
|
||||
|
||||
/// The font family name, e.g. "MaterialIcons".
|
||||
final String family;
|
||||
|
||||
/// The relative path to the font file.
|
||||
final String relativePath;
|
||||
|
||||
/// The list of code points for the font.
|
||||
final List<int> codePoints;
|
||||
|
||||
@override
|
||||
String toString() => 'FontSubsetData($family, $relativePath, $codePoints)';
|
||||
}
|
||||
|
||||
class IconTreeShakerException implements Exception {
|
||||
IconTreeShakerException._(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => 'FontSubset error: $message';
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import '../depfile.dart';
|
||||
import '../exceptions.dart';
|
||||
import 'assets.dart';
|
||||
import 'dart.dart';
|
||||
import 'icon_tree_shaker.dart';
|
||||
|
||||
/// The only files/subdirectories we care out.
|
||||
const List<String> _kLinuxArtifacts = <String>[
|
||||
@@ -119,6 +120,7 @@ class DebugBundleLinuxAssets extends Target {
|
||||
Source.pattern('{BUILD_DIR}/app.dill'),
|
||||
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/linux.dart'),
|
||||
Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
|
||||
...IconTreeShaker.inputs,
|
||||
];
|
||||
|
||||
@override
|
||||
|
||||
@@ -14,6 +14,7 @@ import '../depfile.dart';
|
||||
import '../exceptions.dart';
|
||||
import 'assets.dart';
|
||||
import 'dart.dart';
|
||||
import 'icon_tree_shaker.dart';
|
||||
|
||||
const String _kOutputPrefix = '{OUTPUT_DIR}/FlutterMacOS.framework';
|
||||
|
||||
@@ -243,6 +244,7 @@ abstract class MacOSBundleFlutterAssets extends Target {
|
||||
@override
|
||||
List<Source> get inputs => const <Source>[
|
||||
Source.pattern('{BUILD_DIR}/App.framework/App'),
|
||||
...IconTreeShaker.inputs,
|
||||
];
|
||||
|
||||
@override
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'build_info.dart';
|
||||
import 'build_system/build_system.dart';
|
||||
import 'build_system/depfile.dart';
|
||||
import 'build_system/targets/dart.dart';
|
||||
import 'build_system/targets/icon_tree_shaker.dart';
|
||||
import 'cache.dart';
|
||||
import 'dart/package_map.dart';
|
||||
import 'devfs.dart';
|
||||
@@ -68,6 +69,7 @@ class BundleBuilder {
|
||||
List<String> extraGenSnapshotOptions = const <String>[],
|
||||
List<String> fileSystemRoots,
|
||||
String fileSystemScheme,
|
||||
@required bool treeShakeIcons,
|
||||
}) async {
|
||||
mainPath ??= defaultMainPath;
|
||||
depfilePath ??= defaultDepfilePath;
|
||||
@@ -83,6 +85,7 @@ class BundleBuilder {
|
||||
depfilePath: depfilePath,
|
||||
precompiled: precompiledSnapshot,
|
||||
trackWidgetCreation: trackWidgetCreation,
|
||||
treeShakeIcons: treeShakeIcons,
|
||||
);
|
||||
// Work around for flutter_tester placing kernel artifacts in odd places.
|
||||
if (applicationKernelFilePath != null) {
|
||||
@@ -107,6 +110,7 @@ Future<void> buildWithAssemble({
|
||||
@required String depfilePath,
|
||||
@required bool precompiled,
|
||||
bool trackWidgetCreation,
|
||||
@required bool treeShakeIcons,
|
||||
}) async {
|
||||
// If the precompiled flag was not passed, force us into debug mode.
|
||||
buildMode = precompiled ? buildMode : BuildMode.debug;
|
||||
@@ -121,6 +125,7 @@ Future<void> buildWithAssemble({
|
||||
kBuildMode: getNameForBuildMode(buildMode),
|
||||
kTargetPlatform: getNameForTargetPlatform(targetPlatform),
|
||||
kTrackWidgetCreation: trackWidgetCreation?.toString(),
|
||||
kIconTreeShakerFlag: treeShakeIcons ? 'true' : null,
|
||||
},
|
||||
);
|
||||
final Target target = buildMode == BuildMode.debug
|
||||
|
||||
@@ -34,6 +34,7 @@ class BuildAarCommand extends BuildSubCommand {
|
||||
defaultsTo: true,
|
||||
help: 'Build a release version of the current project.',
|
||||
);
|
||||
addTreeShakeIconsFlag();
|
||||
usesFlavorOption();
|
||||
usesBuildNumberOption();
|
||||
usesPubOption();
|
||||
@@ -104,7 +105,7 @@ class BuildAarCommand extends BuildSubCommand {
|
||||
for (final String buildMode in const <String>['debug', 'profile', 'release']) {
|
||||
if (boolArg(buildMode)) {
|
||||
androidBuildInfo.add(AndroidBuildInfo(
|
||||
BuildInfo(BuildMode.fromName(buildMode), stringArg('flavor')),
|
||||
BuildInfo(BuildMode.fromName(buildMode), stringArg('flavor'), treeShakeIcons: boolArg('tree-shake-icons')),
|
||||
targetArchs: targetArchitectures,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'build.dart';
|
||||
/// Builds AOT snapshots into platform specific library containers.
|
||||
class BuildAotCommand extends BuildSubCommand with TargetPlatformBasedDevelopmentArtifacts {
|
||||
BuildAotCommand({bool verboseHelp = false, this.aotBuilder}) {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
addBuildModeFlags();
|
||||
usesPubOption();
|
||||
@@ -88,6 +89,7 @@ class BuildAotCommand extends BuildSubCommand with TargetPlatformBasedDevelopmen
|
||||
extraFrontEndOptions: stringsArg(FlutterOptions.kExtraFrontEndOptions),
|
||||
extraGenSnapshotOptions: stringsArg(FlutterOptions.kExtraGenSnapshotOptions),
|
||||
dartDefines: dartDefines,
|
||||
treeShakeIcons: boolArg('tree-shake-icons'),
|
||||
);
|
||||
return FlutterCommandResult.success();
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import 'build.dart';
|
||||
|
||||
class BuildApkCommand extends BuildSubCommand {
|
||||
BuildApkCommand({bool verboseHelp = false}) {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
addBuildModeFlags(verboseHelp: verboseHelp);
|
||||
usesFlavorOption();
|
||||
@@ -25,7 +26,6 @@ class BuildApkCommand extends BuildSubCommand {
|
||||
usesBuildNumberOption();
|
||||
usesBuildNameOption();
|
||||
addShrinkingFlag();
|
||||
|
||||
argParser
|
||||
..addFlag('split-per-abi',
|
||||
negatable: false,
|
||||
|
||||
@@ -16,6 +16,7 @@ import 'build.dart';
|
||||
|
||||
class BuildAppBundleCommand extends BuildSubCommand {
|
||||
BuildAppBundleCommand({bool verboseHelp = false}) {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
addBuildModeFlags();
|
||||
usesFlavorOption();
|
||||
|
||||
@@ -16,6 +16,7 @@ import 'build.dart';
|
||||
|
||||
class BuildBundleCommand extends BuildSubCommand {
|
||||
BuildBundleCommand({bool verboseHelp = false, this.bundleBuilder}) {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
usesFilesystemOptions(hide: !verboseHelp);
|
||||
usesBuildNumberOption();
|
||||
@@ -138,6 +139,7 @@ class BuildBundleCommand extends BuildSubCommand {
|
||||
extraGenSnapshotOptions: stringsArg(FlutterOptions.kExtraGenSnapshotOptions),
|
||||
fileSystemScheme: stringArg('filesystem-scheme'),
|
||||
fileSystemRoots: stringsArg('filesystem-root'),
|
||||
treeShakeIcons: boolArg('tree-shake-icons'),
|
||||
);
|
||||
return FlutterCommandResult.success();
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import 'build.dart';
|
||||
/// A command to build a Fuchsia target.
|
||||
class BuildFuchsiaCommand extends BuildSubCommand {
|
||||
BuildFuchsiaCommand({bool verboseHelp = false}) {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
addBuildModeFlags(verboseHelp: verboseHelp);
|
||||
argParser.addOption(
|
||||
|
||||
@@ -18,6 +18,7 @@ import 'build.dart';
|
||||
/// .ipas, see https://flutter.dev/docs/deployment/ios.
|
||||
class BuildIOSCommand extends BuildSubCommand {
|
||||
BuildIOSCommand() {
|
||||
addTreeShakeIconsFlag();
|
||||
addBuildModeFlags(defaultToRelease: false);
|
||||
usesTargetOption();
|
||||
usesFlavorOption();
|
||||
|
||||
@@ -44,6 +44,7 @@ class BuildIOSFrameworkCommand extends BuildSubCommand {
|
||||
_bundleBuilder = bundleBuilder,
|
||||
_cache = cache,
|
||||
_platform = platform {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
usesFlavorOption();
|
||||
usesPubOption();
|
||||
@@ -361,6 +362,7 @@ end
|
||||
mainPath: globals.fs.path.absolute(targetFile),
|
||||
assetDirPath: destinationAppFrameworkDirectory.childDirectory('flutter_assets').path,
|
||||
precompiledSnapshot: mode != BuildMode.debug,
|
||||
treeShakeIcons: boolArg('tree-shake-icons')
|
||||
);
|
||||
} finally {
|
||||
status.stop();
|
||||
@@ -426,6 +428,7 @@ end
|
||||
reportTimings: false,
|
||||
iosBuildArchs: <DarwinArch>[DarwinArch.armv7, DarwinArch.arm64],
|
||||
dartDefines: dartDefines,
|
||||
treeShakeIcons: boolArg('tree-shake-icons'),
|
||||
);
|
||||
} finally {
|
||||
status.stop();
|
||||
|
||||
@@ -17,6 +17,7 @@ import 'build.dart';
|
||||
/// A command to build a linux desktop target through a build shell script.
|
||||
class BuildLinuxCommand extends BuildSubCommand {
|
||||
BuildLinuxCommand() {
|
||||
addTreeShakeIconsFlag();
|
||||
addBuildModeFlags();
|
||||
usesTargetOption();
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import 'build.dart';
|
||||
/// A command to build a macOS desktop target through a build shell script.
|
||||
class BuildMacosCommand extends BuildSubCommand {
|
||||
BuildMacosCommand() {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
addBuildModeFlags();
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'build.dart';
|
||||
|
||||
class BuildWebCommand extends BuildSubCommand {
|
||||
BuildWebCommand() {
|
||||
addTreeShakeIconsFlag();
|
||||
usesTargetOption();
|
||||
usesPubOption();
|
||||
addBuildModeFlags(excludeDebug: true);
|
||||
|
||||
@@ -17,6 +17,7 @@ import 'build.dart';
|
||||
/// A command to build a windows desktop target through a build shell script.
|
||||
class BuildWindowsCommand extends BuildSubCommand {
|
||||
BuildWindowsCommand() {
|
||||
addTreeShakeIconsFlag();
|
||||
addBuildModeFlags();
|
||||
usesTargetOption();
|
||||
}
|
||||
|
||||
@@ -209,7 +209,6 @@ Future<XcodeBuildResult> buildXcodeProject({
|
||||
bool buildForDevice,
|
||||
DarwinArch activeArch,
|
||||
bool codesign = true,
|
||||
|
||||
}) async {
|
||||
if (!upgradePbxProjWithFlutterAssets(app.project)) {
|
||||
return XcodeBuildResult(success: false);
|
||||
|
||||
@@ -428,7 +428,8 @@ class IOSSimulator extends Device {
|
||||
final BuildInfo debugBuildInfo = BuildInfo(BuildMode.debug, buildInfo.flavor,
|
||||
trackWidgetCreation: buildInfo.trackWidgetCreation,
|
||||
extraFrontEndOptions: buildInfo.extraFrontEndOptions,
|
||||
extraGenSnapshotOptions: buildInfo.extraGenSnapshotOptions);
|
||||
extraGenSnapshotOptions: buildInfo.extraGenSnapshotOptions,
|
||||
treeShakeIcons: buildInfo.treeShakeIcons);
|
||||
|
||||
final XcodeBuildResult buildResult = await buildXcodeProject(
|
||||
app: app,
|
||||
@@ -460,6 +461,7 @@ class IOSSimulator extends Device {
|
||||
precompiledSnapshot: false,
|
||||
buildMode: buildInfo.mode,
|
||||
trackWidgetCreation: buildInfo.trackWidgetCreation,
|
||||
treeShakeIcons: false,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -216,6 +216,10 @@ List<String> _xcodeBuildSettingsLines({
|
||||
xcodeBuildSettings.add('TRACK_WIDGET_CREATION=true');
|
||||
}
|
||||
|
||||
if (buildInfo.treeShakeIcons) {
|
||||
xcodeBuildSettings.add('TREE_SHAKE_ICONS=true');
|
||||
}
|
||||
|
||||
return xcodeBuildSettings;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,8 @@ Future<void> buildMacOS({
|
||||
'OBJROOT=${globals.fs.path.join(flutterBuildDir.absolute.path, 'Build', 'Intermediates.noindex')}',
|
||||
'SYMROOT=${globals.fs.path.join(flutterBuildDir.absolute.path, 'Build', 'Products')}',
|
||||
'COMPILER_INDEX_STORE_ENABLE=NO',
|
||||
if (buildInfo.treeShakeIcons)
|
||||
'TREE_SHAKE_ICONS=true',
|
||||
...environmentVariablesAsXcodeBuildSettings(globals.platform)
|
||||
], trace: true);
|
||||
} finally {
|
||||
|
||||
@@ -20,6 +20,7 @@ import '../base/time.dart';
|
||||
import '../base/user_messages.dart';
|
||||
import '../base/utils.dart';
|
||||
import '../build_info.dart';
|
||||
import '../build_system/targets/icon_tree_shaker.dart' show kIconTreeShakerEnabledDefault;
|
||||
import '../bundle.dart' as bundle;
|
||||
import '../cache.dart';
|
||||
import '../dart/package_map.dart';
|
||||
@@ -365,6 +366,14 @@ abstract class FlutterCommand extends Command<void> {
|
||||
help: 'Build a JIT release version of your app${defaultToRelease ? ' (default mode)' : ''}.');
|
||||
}
|
||||
|
||||
void addTreeShakeIconsFlag() {
|
||||
argParser.addFlag('tree-shake-icons',
|
||||
negatable: true,
|
||||
defaultsTo: kIconTreeShakerEnabledDefault,
|
||||
help: 'Tree shake icon fonts so that only glyphs used by the application remain.',
|
||||
);
|
||||
}
|
||||
|
||||
void addShrinkingFlag() {
|
||||
argParser.addFlag('shrink',
|
||||
negatable: true,
|
||||
@@ -490,6 +499,9 @@ abstract class FlutterCommand extends Command<void> {
|
||||
buildName: argParser.options.containsKey('build-name')
|
||||
? stringArg('build-name')
|
||||
: null,
|
||||
treeShakeIcons: argParser.options.containsKey('tree-shake-icons')
|
||||
? boolArg('tree-shake-icons')
|
||||
: kIconTreeShakerEnabledDefault,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -151,6 +151,7 @@ class FlutterTesterDevice extends Device {
|
||||
precompiledSnapshot: false,
|
||||
trackWidgetCreation: buildInfo.trackWidgetCreation,
|
||||
platform: getTargetPlatformForName(getNameForHostPlatform(getCurrentHostPlatform())),
|
||||
treeShakeIcons: buildInfo.treeShakeIcons,
|
||||
);
|
||||
command.add('--flutter-assets-dir=$assetDirPath');
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ Future<void> buildWeb(
|
||||
kHasWebPlugins: hasWebPlugins.toString(),
|
||||
kDartDefines: jsonEncode(dartDefines),
|
||||
kCspMode: csp.toString(),
|
||||
// TODO(dnfield): Enable font subset. We need to get a kernel file to do
|
||||
// that. https://github.com/flutter/flutter/issues/49730
|
||||
},
|
||||
));
|
||||
if (!result.success) {
|
||||
|
||||
Reference in New Issue
Block a user