Populate fallback fonts from CIPD in tests (flutter/engine#41656)

This fixes https://github.com/flutter/flutter/issues/85793

The script that generates the font fallback data also rolls a package to CIPD with these files and updates the DEPS to download those files from CIPD. This makes sure that these tests are hermetic.
This commit is contained in:
Jackson Gardner
2023-05-03 22:12:54 -07:00
committed by GitHub
parent 1535542946
commit 5189eda98b
20 changed files with 1099 additions and 876 deletions

10
DEPS
View File

@@ -913,6 +913,16 @@ deps = {
],
'condition': 'download_impeller_cmake_example and host_os == "mac"',
'dep_type': 'cipd',
},
'src/third_party/google_fonts_for_unit_tests': {
'packages': [
{
'package': 'flutter/flutter_font_fallbacks',
'version': 'f7459e412c5cfba5a654e96a5a00fff61e018d16b8b1c41dade17b7c6aa92299'
}
],
'dep_type': 'cipd',
}
}

View File

@@ -1988,6 +1988,7 @@
../../../third_party/glfw/examples
../../../third_party/glfw/src/CMakeLists.txt
../../../third_party/glfw/tests
../../../third_party/google_fonts_for_unit_tests
../../../third_party/googletest
../../../third_party/gradle
../../../third_party/gtest-parallel/.git

View File

@@ -1,2 +1,2 @@
Signature: f7b260cd821ec8f8838b3b739d9a4970
Signature: cb8556d451f3040815fe5ee661d5dbad

View File

@@ -141,6 +141,29 @@ fetched from CIPD.
Since the engine code and infra recipes do not live in the same repository
there are few steps to follow in order to upgrade a browser's version.
### Rolling fallback fonts
To generate new fallback font data and push the fallback fonts into a CIPD
package for engine unit tests to consume, run the following felt command:
```
cipd auth-login
felt roll-fallback-fonts --key=<Google Fonts API key>
```
This will take the following steps:
* Fetch a list of fonts from the Google Fonts API
* Download each font we use for fallbacks and calculate its unicode ranges
* Generate the `font_fallback_data.dart` file that is used in the engine
* Push the fonts up to a CIPD package called `flutter/flutter_font_fallbacks`
* Update the `DEPS` file in the engine to use the new version of the package
To perform all these steps except actually uploading the package to CIPD, pass
the `--dry-run` flag to the felt command.
NOTE: Because this script uses `fc-config`, this roll step only actually works
on Linux, not on macOS or Windows.
#### Chromium
Chromium is an independent project that gets rolled into Flutter manually, and as needed.
@@ -222,19 +245,6 @@ Resources:
2. LUCI web [recipe][5]
3. More general reading on CIPD packages [link][6]
### Rolling Noto Font Data
In order to generate new data for the Noto fallback fonts, you will need
a GoogleFonts API key. Once you have one, run:
```
./dev/felt generate-fallback-font-data --key=<your GoogleFonts API key>
```
This will generate the file `lib/src/engine/canvaskit/font_fallback_data.dart` with
the latest data from GoogleFonts. This generated file should then be rolled in with
a PR to the engine.
### Configuration files
`browser_lock.yaml` contains the version of browsers we use to test Flutter for

View File

@@ -9,6 +9,7 @@ import 'package:http/http.dart';
import 'package:path/path.dart' as path;
import 'browser_lock.dart';
import 'cipd.dart';
import 'common.dart';
import 'utils.dart';
@@ -133,56 +134,6 @@ class _BrowserRoller {
}
}
// Returns the contents for the CIPD config required to publish a new chromium package.
String _getCipdChromiumConfig({
required String package,
required String majorVersion,
required String buildId,
required String root,
}) {
return '''
package: $package
description: Chromium $majorVersion (build $buildId) used for testing
preserve_writable: true
root: $root
data:
- dir: .
''';
}
// Returns the contents for the CIPD config required to publish a new chromedriver package.
String _getCipdChromedriverConfig({
required String package,
required String majorVersion,
required String buildId,
required String root,
}) {
return '''
package: $package
description: Chromedriver for Chromium $majorVersion (build $buildId) used for testing
preserve_writable: true
root: $root
data:
- dir: .
''';
}
// Returns the contents for the CIPD config required to publish a new Firefox package.
String _getCipdFirefoxConfig({
required String package,
required String majorVersion,
required String root,
}) {
return '''
package: $package
description: Firefox $majorVersion used for testing
preserve_writable: true
root: $root
data:
- dir: .
''';
}
// Download a file from the internet, and put it in a temporary location.
Future<io.File> _downloadTemporaryFile(String url) async {
// Use the hash of the Url to temporarily store a file under tmp
@@ -233,16 +184,6 @@ data:
await tarFile.delete();
}
// Write String `contents` to a file in `path`.
//
// This is used to write CIPD config files to disk.
Future<io.File> _writeFile(String path, String contents) async {
vprint(' Writing file [$path]');
final io.File file = io.File(path, );
await file.writeAsString(contents);
return file;
}
// Locate the first subdirectory that contains more than one file under `root`.
// (or one ".app" bundle for mac)
//
@@ -265,61 +206,6 @@ data:
return root;
}
// Runs a CIPD command to upload a package defined by its `config` file.
Future<int> _uploadToCipd({
required io.File config,
required String version,
required String buildId,
}) {
final String cipdCommand = dryRun ? 'pkg-build' : 'create';
// CIPD won't fully shut up even in 'error' mode
final String logLevel = verbose ? 'debug' : 'warning';
vprint(' Running CIPD $cipdCommand');
return runProcess('cipd', <String>[
cipdCommand,
'--pkg-def',
path.basename(config.path),
'--json-output',
'${path.basenameWithoutExtension(config.path)}.json',
'--log-level',
logLevel,
if (!dryRun) ...<String>[
'--tag',
'version:$version',
'--ref',
buildId,
],
if (dryRun) ...<String>[
'--out',
'${path.basenameWithoutExtension(config.path)}.zip',
],
], workingDirectory: _rollDir.path);
}
// Determine if a `package` tagged with version:`versionTag` already exists in CIPD.
Future<bool> _cipdKnowsPackageVersion({
required String package,
required String versionTag,
}) async {
// $ cipd search $package -tag version:$versionTag
// Instances:
// $package:CIPD_PACKAGE_ID
// or:
// No matching instances.
final String logLevel = verbose ? 'debug' : 'warning';
vprint(' Searching for $package version:$versionTag in CIPD');
final String stdout = await evalProcess('cipd', <String>[
'search',
package,
'--tag',
'version:$versionTag',
'--log-level',
logLevel,
], workingDirectory: _rollDir.path);
return stdout.contains('Instances:') && stdout.contains(package);
}
// Downloads Chromium from the internet, packs it in the directory structure
// that the LUCI script wants. The result of this will be then uploaded to CIPD.
Future<void> _rollChromium(_Platform platform) async {
@@ -330,7 +216,11 @@ data:
final io.Directory platformDir = io.Directory(path.join(_rollDir.path, platform.name));
print('\nRolling Chromium for ${platform.name} (version:$majorVersion, build $chromeBuild)');
// Bail out if CIPD already has version:$majorVersion for this package!
if (!dryRun && await _cipdKnowsPackageVersion(package: cipdPackageName, versionTag: majorVersion)) {
if (!dryRun && await cipdKnowsPackageVersion(
package: cipdPackageName,
versionTag: majorVersion,
isVerbose: verbose
)) {
print(' Skipping $cipdPackageName version:$majorVersion. Already uploaded to CIPD!');
vprint(' Update browser_lock.yaml and use a different version value.');
return;
@@ -353,17 +243,18 @@ data:
relativePlatformDirPath = path.relative(actualContentRoot!.path, from: _rollDir.path);
}
// Create the config manifest to upload to CIPD
final io.File cipdConfigFile = await _writeFile(
path.join(_rollDir.path, 'cipd.chromium.${platform.name}.yaml'),
_getCipdChromiumConfig(
package: cipdPackageName,
majorVersion: majorVersion,
buildId: chromeBuild,
root: relativePlatformDirPath,
));
// Run CIPD
await _uploadToCipd(config: cipdConfigFile, version: majorVersion, buildId: chromeBuild);
vprint(' Uploading Chromium (${platform.name}) to CIPD...');
await uploadDirectoryToCipd(
directory: _rollDir,
packageName: cipdPackageName,
configFileName: 'cipd.chromium.${platform.name}.yaml',
description: 'Chromium $majorVersion (build $chromeBuild) used for testing',
version: majorVersion,
buildId: chromeBuild,
root: relativePlatformDirPath,
isDryRun: dryRun,
isVerbose: verbose,
);
}
// Downloads Chromedriver from the internet, packs it in the directory structure
@@ -376,7 +267,11 @@ data:
final io.Directory platformDir = io.Directory(path.join(_rollDir.path, '${platform.name}_driver'));
print('\nRolling Chromedriver for ${platform.os}-${platform.arch} (version:$majorVersion, build $chromeBuild)');
// Bail out if CIPD already has version:$majorVersion for this package!
if (!dryRun && await _cipdKnowsPackageVersion(package: cipdPackageName, versionTag: majorVersion)) {
if (!dryRun && await cipdKnowsPackageVersion(
package: cipdPackageName,
versionTag: majorVersion,
isVerbose: verbose
)) {
print(' Skipping $cipdPackageName version:$majorVersion. Already uploaded to CIPD!');
vprint(' Update browser_lock.yaml and use a different version value.');
return;
@@ -394,17 +289,18 @@ data:
assert(actualContentRoot != null);
final String relativePlatformDirPath = path.relative(actualContentRoot!.path, from: _rollDir.path);
// Create the config manifest to upload to CIPD
final io.File cipdConfigFile = await _writeFile(
path.join(_rollDir.path, 'cipd.chromedriver.${platform.name}.yaml'),
_getCipdChromedriverConfig(
package: cipdPackageName,
majorVersion: majorVersion,
buildId: chromeBuild,
root: relativePlatformDirPath,
));
// Run CIPD
await _uploadToCipd(config: cipdConfigFile, version: majorVersion, buildId: chromeBuild);
vprint(' Uploading Chromedriver (${platform.name}) to CIPD...');
await uploadDirectoryToCipd(
directory: _rollDir,
packageName: cipdPackageName,
configFileName: 'cipd.chromedriver.${platform.name}.yaml',
description: 'Chromedriver for Chromium $majorVersion (build $chromeBuild) used for testing',
version: majorVersion,
buildId: chromeBuild,
root: relativePlatformDirPath,
isDryRun: dryRun,
isVerbose: verbose,
);
}
@@ -417,7 +313,11 @@ data:
final io.Directory platformDir = io.Directory(path.join(_rollDir.path, platform.name));
print('\nRolling Firefox for ${platform.name} (version:$version)');
// Bail out if CIPD already has version:$majorVersion for this package!
if (!dryRun && await _cipdKnowsPackageVersion(package: cipdPackageName, versionTag: version)) {
if (!dryRun && await cipdKnowsPackageVersion(
package: cipdPackageName,
versionTag: version,
isVerbose: verbose
)) {
print(' Skipping $cipdPackageName version:$version. Already uploaded to CIPD!');
vprint(' Update browser_lock.yaml and use a different version value.');
return;
@@ -434,15 +334,17 @@ data:
assert(actualContentRoot != null);
final String relativePlatformDirPath = path.relative(actualContentRoot!.path, from: _rollDir.path);
// Create the config manifest to upload to CIPD
final io.File cipdConfigFile = await _writeFile(
path.join(_rollDir.path, 'cipd.firefox.${platform.name}.yaml'),
_getCipdFirefoxConfig(
package: cipdPackageName,
majorVersion: version,
root: relativePlatformDirPath,
));
// Run CIPD
await _uploadToCipd(config: cipdConfigFile, version: version, buildId: version);
vprint(' Uploading Firefox (${platform.name}) to CIPD...');
await uploadDirectoryToCipd(
directory: _rollDir,
packageName: cipdPackageName,
configFileName: 'cipd.firefox.${platform.name}.yaml',
description: 'Firefox $version used for testing',
version: version,
buildId: version,
root: relativePlatformDirPath,
isDryRun: dryRun,
isVerbose: verbose,
);
}
}

View File

@@ -0,0 +1,82 @@
// Copyright 2013 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 'dart:io' as io;
import 'package:path/path.dart' as path;
import 'utils.dart';
// Determine if a `package` tagged with version:`versionTag` already exists in CIPD.
Future<bool> cipdKnowsPackageVersion({
required String package,
required String versionTag,
bool isVerbose = false,
}) async {
// $ cipd search $package -tag version:$versionTag
// Instances:
// $package:CIPD_PACKAGE_ID
// or:
// No matching instances.
final String logLevel = isVerbose ? 'debug' : 'warning';
final String stdout = await evalProcess('cipd', <String>[
'search',
package,
'--tag',
'version:$versionTag',
'--log-level',
logLevel,
]);
return stdout.contains('Instances:') && stdout.contains(package);
}
// Runs a CIPD command to upload a package defined by its `config` file.
Future<int> uploadDirectoryToCipd({
required io.Directory directory,
required String packageName,
required String configFileName,
required String description,
required String root,
required String version,
required String buildId,
bool isDryRun = false,
bool isVerbose = false,
}) async {
final String cipdConfig = '''
package: $packageName
description: $description
preserve_writable: true
root: $root
data:
- dir: .
''';
// Create the config manifest to upload to CIPD
final io.File configFile = io.File(path.join(directory.path, configFileName));
await configFile.writeAsString(cipdConfig);
final String cipdCommand = isDryRun ? 'pkg-build' : 'create';
// CIPD won't fully shut up even in 'error' mode
final String logLevel = isVerbose ? 'debug' : 'warning';
return runProcess('cipd', <String>[
cipdCommand,
'--pkg-def',
path.basename(configFile.path),
'--json-output',
'${path.basenameWithoutExtension(configFile.path)}.json',
'--log-level',
logLevel,
if (!isDryRun) ...<String>[
'--tag',
'version:$version',
'--ref',
buildId,
],
if (isDryRun) ...<String>[
'--out',
'${path.basenameWithoutExtension(configFile.path)}.zip',
],
], workingDirectory: directory.path);
}

View File

@@ -10,8 +10,8 @@ import 'analyze.dart';
import 'build.dart';
import 'clean.dart';
import 'exceptions.dart';
import 'generate_fallback_font_data.dart';
import 'licenses.dart';
import 'roll_fallback_fonts.dart';
import 'test_runner.dart';
import 'utils.dart';
@@ -22,7 +22,7 @@ CommandRunner<bool> runner = CommandRunner<bool>(
..addCommand(AnalyzeCommand())
..addCommand(BuildCommand())
..addCommand(CleanCommand())
..addCommand(GenerateFallbackFontDataCommand())
..addCommand(RollFallbackFontsCommand())
..addCommand(LicensesCommand())
..addCommand(TestCommand());

View File

@@ -1,336 +0,0 @@
// Copyright 2013 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 'dart:convert' show jsonDecode;
import 'dart:io' as io;
import 'package:args/command_runner.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
import 'environment.dart';
import 'exceptions.dart';
import 'utils.dart';
class GenerateFallbackFontDataCommand extends Command<bool>
with ArgUtils<bool> {
GenerateFallbackFontDataCommand() {
argParser.addOption(
'key',
defaultsTo: '',
help: 'The Google Fonts API key. Used to get data about fonts hosted on '
'Google Fonts.',
);
argParser.addFlag(
'download-test-fonts',
defaultsTo: true,
help: 'Whether to download the Noto fonts into a local folder to use in'
'tests.',
);
}
@override
final String name = 'generate-fallback-font-data';
@override
final String description = 'Generate fallback font data from GoogleFonts';
String get apiKey => stringArg('key');
bool get downloadTestFonts => boolArg('download-test-fonts');
@override
Future<bool> run() async {
await _generateFallbackFontData();
return true;
}
Future<void> _generateFallbackFontData() async {
if (apiKey.isEmpty) {
throw UsageException('No Google Fonts API key provided', argParser.usage);
}
final http.Client client = http.Client();
final http.Response response = await client.get(Uri.parse(
'https://www.googleapis.com/webfonts/v1/webfonts?key=$apiKey'));
if (response.statusCode != 200) {
throw ToolExit('Failed to download Google Fonts list.');
}
final Map<String, dynamic> googleFontsResult =
jsonDecode(response.body) as Map<String, dynamic>;
final List<Map<String, dynamic>> fontDatas =
(googleFontsResult['items'] as List<dynamic>)
.cast<Map<String, dynamic>>();
final Map<String, Uri> urlForFamily = <String, Uri>{};
for (final Map<String, dynamic> fontData in fontDatas) {
if (fallbackFonts.contains(fontData['family'])) {
final Uri uri = Uri.parse(fontData['files']['regular'] as String)
.replace(scheme: 'https');
urlForFamily[fontData['family'] as String] = uri;
}
}
final Map<String, String> charsetForFamily = <String, String>{};
final io.Directory fontDir = downloadTestFonts
? await io.Directory(path.join(
environment.webUiBuildDir.path,
'assets',
'noto',
)).create(recursive: true)
: await io.Directory.systemTemp.createTemp('fonts');
// Delete old fonts in the font directory.
await for (final io.FileSystemEntity file in fontDir.list()) {
await file.delete();
}
for (final String family in fallbackFonts) {
print('Downloading $family...');
final Uri? uri = urlForFamily[family];
if (uri == null) {
throw ToolExit('Unable to determine URL to download $family. '
'Check if it is still hosted on Google Fonts.');
}
final http.Response fontResponse = await client.get(uri);
if (fontResponse.statusCode != 200) {
throw ToolExit('Failed to download font for $family');
}
final io.File fontFile =
io.File(path.join(fontDir.path, path.basename(uri.path)));
await fontFile.writeAsBytes(fontResponse.bodyBytes);
final io.ProcessResult fcQueryResult =
await io.Process.run('fc-query', <String>[
'--format=%{charset}',
'--',
fontFile.path,
]);
final String encodedCharset = fcQueryResult.stdout as String;
charsetForFamily[family] = encodedCharset;
}
final StringBuffer sb = StringBuffer();
sb.writeln('// Copyright 2013 The Flutter Authors. All rights reserved.');
sb.writeln('// Use of this source code is governed by a BSD-style license '
'that can be');
sb.writeln('// found in the LICENSE file.');
sb.writeln();
sb.writeln('// DO NOT EDIT! This file is generated. See:');
sb.writeln('// dev/generate_fallback_font_data.dart');
sb.writeln("import '../configuration.dart';");
sb.writeln("import 'noto_font.dart';");
sb.writeln();
sb.writeln('final List<NotoFont> fallbackFonts = <NotoFont>[');
for (final String family in fallbackFonts) {
if (family == 'Noto Emoji') {
sb.write(' if (!configuration.useColorEmoji)');
}
if (family == 'Noto Color Emoji') {
sb.write(' if (configuration.useColorEmoji)');
}
sb.writeln(" NotoFont('$family', '${urlForFamily[family]!}',");
final List<String> starts = <String>[];
final List<String> ends = <String>[];
for (final String range in charsetForFamily[family]!.split(' ')) {
final List<String> parts = range.split('-');
if (parts.length == 1) {
starts.add(parts[0]);
ends.add(parts[0]);
} else {
starts.add(parts[0]);
ends.add(parts[1]);
}
}
// Print the unicode ranges in a readable format for easier review. This
// shouldn't affect code size because comments are removed in release mode.
sb.write(' // <int>[');
for (final String start in starts) {
sb.write('0x$start,');
}
sb.writeln('],');
sb.write(' // <int>[');
for (final String end in ends) {
sb.write('0x$end,');
}
sb.writeln(']');
sb.writeln(" '${_packFontRanges(starts, ends)}',");
sb.writeln(' ),');
}
sb.writeln('];');
final io.File fontDataFile = io.File(path.join(
environment.webUiRootDir.path,
'lib',
'src',
'engine',
'canvaskit',
'font_fallback_data.dart',
));
await fontDataFile.writeAsString(sb.toString());
}
}
const List<String> fallbackFonts = <String>[
'Noto Sans',
'Noto Color Emoji',
'Noto Emoji',
'Noto Sans Symbols',
'Noto Sans Symbols 2',
'Noto Sans Adlam',
'Noto Sans Anatolian Hieroglyphs',
'Noto Sans Arabic',
'Noto Sans Armenian',
'Noto Sans Avestan',
'Noto Sans Balinese',
'Noto Sans Bamum',
'Noto Sans Bassa Vah',
'Noto Sans Batak',
'Noto Sans Bengali',
'Noto Sans Bhaiksuki',
'Noto Sans Brahmi',
'Noto Sans Buginese',
'Noto Sans Buhid',
'Noto Sans Canadian Aboriginal',
'Noto Sans Carian',
'Noto Sans Caucasian Albanian',
'Noto Sans Chakma',
'Noto Sans Cham',
'Noto Sans Cherokee',
'Noto Sans Coptic',
'Noto Sans Cuneiform',
'Noto Sans Cypriot',
'Noto Sans Deseret',
'Noto Sans Devanagari',
'Noto Sans Duployan',
'Noto Sans Egyptian Hieroglyphs',
'Noto Sans Elbasan',
'Noto Sans Elymaic',
'Noto Sans Georgian',
'Noto Sans Glagolitic',
'Noto Sans Gothic',
'Noto Sans Grantha',
'Noto Sans Gujarati',
'Noto Sans Gunjala Gondi',
'Noto Sans Gurmukhi',
'Noto Sans HK',
'Noto Sans Hanunoo',
'Noto Sans Hatran',
'Noto Sans Hebrew',
'Noto Sans Imperial Aramaic',
'Noto Sans Indic Siyaq Numbers',
'Noto Sans Inscriptional Pahlavi',
'Noto Sans Inscriptional Parthian',
'Noto Sans JP',
'Noto Sans Javanese',
'Noto Sans KR',
'Noto Sans Kaithi',
'Noto Sans Kannada',
'Noto Sans Kayah Li',
'Noto Sans Kharoshthi',
'Noto Sans Khmer',
'Noto Sans Khojki',
'Noto Sans Khudawadi',
'Noto Sans Lao',
'Noto Sans Lepcha',
'Noto Sans Limbu',
'Noto Sans Linear A',
'Noto Sans Linear B',
'Noto Sans Lisu',
'Noto Sans Lycian',
'Noto Sans Lydian',
'Noto Sans Mahajani',
'Noto Sans Malayalam',
'Noto Sans Mandaic',
'Noto Sans Manichaean',
'Noto Sans Marchen',
'Noto Sans Masaram Gondi',
'Noto Sans Math',
'Noto Sans Mayan Numerals',
'Noto Sans Medefaidrin',
'Noto Sans Meetei Mayek',
'Noto Sans Meroitic',
'Noto Sans Miao',
'Noto Sans Modi',
'Noto Sans Mongolian',
'Noto Sans Mro',
'Noto Sans Multani',
'Noto Sans Myanmar',
'Noto Sans NKo',
'Noto Sans Nabataean',
'Noto Sans New Tai Lue',
'Noto Sans Newa',
'Noto Sans Nushu',
'Noto Sans Ogham',
'Noto Sans Ol Chiki',
'Noto Sans Old Hungarian',
'Noto Sans Old Italic',
'Noto Sans Old North Arabian',
'Noto Sans Old Permic',
'Noto Sans Old Persian',
'Noto Sans Old Sogdian',
'Noto Sans Old South Arabian',
'Noto Sans Old Turkic',
'Noto Sans Oriya',
'Noto Sans Osage',
'Noto Sans Osmanya',
'Noto Sans Pahawh Hmong',
'Noto Sans Palmyrene',
'Noto Sans Pau Cin Hau',
'Noto Sans Phags Pa',
'Noto Sans Phoenician',
'Noto Sans Psalter Pahlavi',
'Noto Sans Rejang',
'Noto Sans Runic',
'Noto Sans SC',
'Noto Sans Saurashtra',
'Noto Sans Sharada',
'Noto Sans Shavian',
'Noto Sans Siddham',
'Noto Sans Sinhala',
'Noto Sans Sogdian',
'Noto Sans Sora Sompeng',
'Noto Sans Soyombo',
'Noto Sans Sundanese',
'Noto Sans Syloti Nagri',
'Noto Sans Syriac',
'Noto Sans TC',
'Noto Sans Tagalog',
'Noto Sans Tagbanwa',
'Noto Sans Tai Le',
'Noto Sans Tai Tham',
'Noto Sans Tai Viet',
'Noto Sans Takri',
'Noto Sans Tamil',
'Noto Sans Tamil Supplement',
'Noto Sans Telugu',
'Noto Sans Thaana',
'Noto Sans Thai',
'Noto Sans Tifinagh',
'Noto Sans Tirhuta',
'Noto Sans Ugaritic',
'Noto Sans Vai',
'Noto Sans Wancho',
'Noto Sans Warang Citi',
'Noto Sans Yi',
'Noto Sans Zanabazar Square',
];
String _packFontRanges(List<String> starts, List<String> ends) {
assert(starts.length == ends.length);
final StringBuffer sb = StringBuffer();
for (int i = 0; i < starts.length; i++) {
final int start = int.parse(starts[i], radix: 16);
final int end = int.parse(ends[i], radix: 16);
sb.write(start.toRadixString(36));
sb.write('|');
if (start != end) {
sb.write((end - start).toRadixString(36));
}
sb.write(';');
}
return sb.toString();
}

View File

@@ -0,0 +1,512 @@
// Copyright 2013 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 'dart:convert' show ByteConversionSink, jsonDecode, utf8;
import 'dart:io' as io;
import 'dart:typed_data';
import 'package:args/command_runner.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart' as crypto;
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
import 'cipd.dart';
import 'environment.dart';
import 'exceptions.dart';
import 'utils.dart';
const String expectedUrlPrefix = 'https://fonts.gstatic.com/s/';
class RollFallbackFontsCommand extends Command<bool>
with ArgUtils<bool> {
RollFallbackFontsCommand() {
argParser.addOption(
'key',
defaultsTo: '',
help: 'The Google Fonts API key. Used to get data about fonts hosted on '
'Google Fonts.',
);
argParser.addFlag(
'dry-run',
help: 'Whether or not to push changes to CIPD. When --dry-run is set, the '
'script will download everything and attempt to prepare the bundle '
'but will stop before publishing. When not set, the bundle will be '
'published.',
negatable: false,
);
}
@override
final String name = 'roll-fallback-fonts';
@override
final String description = 'Generate fallback font data from GoogleFonts and '
'upload fonts to cipd.';
String get apiKey => stringArg('key');
bool get isDryRun => boolArg('dry-run');
@override
Future<bool> run() async {
await _generateFallbackFontData();
return true;
}
Future<void> _generateFallbackFontData() async {
if (apiKey.isEmpty) {
throw UsageException('No Google Fonts API key provided', argParser.usage);
}
final http.Client client = http.Client();
final http.Response response = await client.get(Uri.parse(
'https://www.googleapis.com/webfonts/v1/webfonts?key=$apiKey'));
if (response.statusCode != 200) {
throw ToolExit('Failed to download Google Fonts list.');
}
final Map<String, dynamic> googleFontsResult =
jsonDecode(response.body) as Map<String, dynamic>;
final List<Map<String, dynamic>> fontDatas =
(googleFontsResult['items'] as List<dynamic>)
.cast<Map<String, dynamic>>();
final Map<String, Uri> urlForFamily = <String, Uri>{};
for (final Map<String, dynamic> fontData in fontDatas) {
if (fallbackFonts.contains(fontData['family'])) {
final Uri uri = Uri.parse(fontData['files']['regular'] as String)
.replace(scheme: 'https');
urlForFamily[fontData['family'] as String] = uri;
}
}
final Map<String, String> charsetForFamily = <String, String>{};
final io.Directory fontDir = await io.Directory.systemTemp.createTemp('flutter_fallback_fonts');
print('Downloading fonts into temp directory: ${fontDir.path}');
final AccumulatorSink<crypto.Digest> hashSink = AccumulatorSink<crypto.Digest>();
final ByteConversionSink hasher = crypto.sha256.startChunkedConversion(hashSink);
for (final String family in fallbackFonts) {
print('Downloading $family...');
final Uri? uri = urlForFamily[family];
if (uri == null) {
throw ToolExit('Unable to determine URL to download $family. '
'Check if it is still hosted on Google Fonts.');
}
final http.Response fontResponse = await client.get(uri);
if (fontResponse.statusCode != 200) {
throw ToolExit('Failed to download font for $family');
}
final String urlString = uri.toString();
if (!urlString.startsWith(expectedUrlPrefix)) {
throw ToolExit('Unexpected url format received from Google Fonts API: $urlString.');
}
final String urlSuffix = urlString.substring(expectedUrlPrefix.length);
final io.File fontFile =
io.File(path.join(fontDir.path, urlSuffix));
final Uint8List bodyBytes = fontResponse.bodyBytes;
if (!_checkForLicenseAttribution(bodyBytes)) {
throw ToolExit('Expected license attribution not found in file: $urlString');
}
hasher.add(utf8.encode(urlSuffix));
hasher.add(bodyBytes);
await fontFile.create(recursive: true);
await fontFile.writeAsBytes(bodyBytes, flush: true);
final io.ProcessResult fcQueryResult =
await io.Process.run('fc-query', <String>[
'--format=%{charset}',
'--',
fontFile.path,
]);
final String encodedCharset = fcQueryResult.stdout as String;
charsetForFamily[family] = encodedCharset;
}
final StringBuffer sb = StringBuffer();
sb.writeln('// Copyright 2013 The Flutter Authors. All rights reserved.');
sb.writeln('// Use of this source code is governed by a BSD-style license '
'that can be');
sb.writeln('// found in the LICENSE file.');
sb.writeln();
sb.writeln('// DO NOT EDIT! This file is generated. See:');
sb.writeln('// dev/roll_fallback_fonts.dart');
sb.writeln("import 'noto_font.dart';");
sb.writeln();
sb.writeln('List<NotoFont> getFallbackFontData(bool useColorEmoji) => <NotoFont>[');
for (final String family in fallbackFonts) {
if (family == 'Noto Emoji') {
sb.write(' if (!useColorEmoji)');
}
if (family == 'Noto Color Emoji') {
sb.write(' if (useColorEmoji)');
}
final String urlString = urlForFamily[family]!.toString();
if (!urlString.startsWith(expectedUrlPrefix)) {
throw ToolExit('Unexpected url format received from Google Fonts API: $urlString.');
}
final String urlSuffix = urlString.substring(expectedUrlPrefix.length);
sb.writeln(" NotoFont('$family', '$urlSuffix',");
final List<String> starts = <String>[];
final List<String> ends = <String>[];
for (final String range in charsetForFamily[family]!.split(' ')) {
final List<String> parts = range.split('-');
if (parts.length == 1) {
starts.add(parts[0]);
ends.add(parts[0]);
} else {
starts.add(parts[0]);
ends.add(parts[1]);
}
}
// Print the unicode ranges in a readable format for easier review. This
// shouldn't affect code size because comments are removed in release mode.
sb.write(' // <int>[');
for (final String start in starts) {
sb.write('0x$start,');
}
sb.writeln('],');
sb.write(' // <int>[');
for (final String end in ends) {
sb.write('0x$end,');
}
sb.writeln(']');
sb.writeln(" '${_packFontRanges(starts, ends)}',");
sb.writeln(' ),');
}
sb.writeln('];');
final io.File fontDataFile = io.File(path.join(
environment.webUiRootDir.path,
'lib',
'src',
'engine',
'canvaskit',
'font_fallback_data.dart',
));
await fontDataFile.writeAsString(sb.toString());
final io.File licenseFile = io.File(path.join(
fontDir.path,
'LICENSE.txt',
));
const String licenseString = r'''
© Copyright 2015-2021 Google LLC. All Rights Reserved.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
''';
final List<int> licenseData = utf8.encode(licenseString);
await licenseFile.create(recursive: true);
await licenseFile.writeAsBytes(licenseData);
hasher.add(licenseData);
hasher.close();
final crypto.Digest digest = hashSink.events.single;
final String versionString = digest.toString();
const String packageName = 'flutter/flutter_font_fallbacks';
if (await cipdKnowsPackageVersion(
package: packageName,
versionTag: versionString)) {
print('Package already exists with hash $versionString. Skipping upload');
} else {
print('Uploading fallback fonts to CIPD with hash $versionString');
await uploadDirectoryToCipd(
directory: fontDir,
packageName: packageName,
configFileName: 'cipd.flutter_font_fallbacks.yaml',
description: 'A set of Noto fonts to fall back to for use in testing.',
root: fontDir.path,
version: versionString,
buildId: versionString,
isDryRun: isDryRun,
);
}
print('Setting new fallback fonts deps version to $versionString');
final String depFilePath = path.join(
environment.engineSrcDir.path,
'flutter',
'DEPS',
);
await runProcess('gclient', <String>[
'setdep',
'--revision=src/third_party/google_fonts_for_unit_tests:$packageName@$versionString',
'--deps-file=$depFilePath'
]);
}
}
const List<String> fallbackFonts = <String>[
'Noto Sans',
'Noto Color Emoji',
'Noto Emoji',
'Noto Sans Symbols',
'Noto Sans Symbols 2',
'Noto Sans Adlam',
'Noto Sans Anatolian Hieroglyphs',
'Noto Sans Arabic',
'Noto Sans Armenian',
'Noto Sans Avestan',
'Noto Sans Balinese',
'Noto Sans Bamum',
'Noto Sans Bassa Vah',
'Noto Sans Batak',
'Noto Sans Bengali',
'Noto Sans Bhaiksuki',
'Noto Sans Brahmi',
'Noto Sans Buginese',
'Noto Sans Buhid',
'Noto Sans Canadian Aboriginal',
'Noto Sans Carian',
'Noto Sans Caucasian Albanian',
'Noto Sans Chakma',
'Noto Sans Cham',
'Noto Sans Cherokee',
'Noto Sans Coptic',
'Noto Sans Cuneiform',
'Noto Sans Cypriot',
'Noto Sans Deseret',
'Noto Sans Devanagari',
'Noto Sans Duployan',
'Noto Sans Egyptian Hieroglyphs',
'Noto Sans Elbasan',
'Noto Sans Elymaic',
'Noto Sans Georgian',
'Noto Sans Glagolitic',
'Noto Sans Gothic',
'Noto Sans Grantha',
'Noto Sans Gujarati',
'Noto Sans Gunjala Gondi',
'Noto Sans Gurmukhi',
'Noto Sans HK',
'Noto Sans Hanunoo',
'Noto Sans Hatran',
'Noto Sans Hebrew',
'Noto Sans Imperial Aramaic',
'Noto Sans Indic Siyaq Numbers',
'Noto Sans Inscriptional Pahlavi',
'Noto Sans Inscriptional Parthian',
'Noto Sans JP',
'Noto Sans Javanese',
'Noto Sans KR',
'Noto Sans Kaithi',
'Noto Sans Kannada',
'Noto Sans Kayah Li',
'Noto Sans Kharoshthi',
'Noto Sans Khmer',
'Noto Sans Khojki',
'Noto Sans Khudawadi',
'Noto Sans Lao',
'Noto Sans Lepcha',
'Noto Sans Limbu',
'Noto Sans Linear A',
'Noto Sans Linear B',
'Noto Sans Lisu',
'Noto Sans Lycian',
'Noto Sans Lydian',
'Noto Sans Mahajani',
'Noto Sans Malayalam',
'Noto Sans Mandaic',
'Noto Sans Manichaean',
'Noto Sans Marchen',
'Noto Sans Masaram Gondi',
'Noto Sans Math',
'Noto Sans Mayan Numerals',
'Noto Sans Medefaidrin',
'Noto Sans Meetei Mayek',
'Noto Sans Meroitic',
'Noto Sans Miao',
'Noto Sans Modi',
'Noto Sans Mongolian',
'Noto Sans Mro',
'Noto Sans Multani',
'Noto Sans Myanmar',
'Noto Sans NKo',
'Noto Sans Nabataean',
'Noto Sans New Tai Lue',
'Noto Sans Newa',
'Noto Sans Nushu',
'Noto Sans Ogham',
'Noto Sans Ol Chiki',
'Noto Sans Old Hungarian',
'Noto Sans Old Italic',
'Noto Sans Old North Arabian',
'Noto Sans Old Permic',
'Noto Sans Old Persian',
'Noto Sans Old Sogdian',
'Noto Sans Old South Arabian',
'Noto Sans Old Turkic',
'Noto Sans Oriya',
'Noto Sans Osage',
'Noto Sans Osmanya',
'Noto Sans Pahawh Hmong',
'Noto Sans Palmyrene',
'Noto Sans Pau Cin Hau',
'Noto Sans Phags Pa',
'Noto Sans Phoenician',
'Noto Sans Psalter Pahlavi',
'Noto Sans Rejang',
'Noto Sans Runic',
'Noto Sans SC',
'Noto Sans Saurashtra',
'Noto Sans Sharada',
'Noto Sans Shavian',
'Noto Sans Siddham',
'Noto Sans Sinhala',
'Noto Sans Sogdian',
'Noto Sans Sora Sompeng',
'Noto Sans Soyombo',
'Noto Sans Sundanese',
'Noto Sans Syloti Nagri',
'Noto Sans Syriac',
'Noto Sans TC',
'Noto Sans Tagalog',
'Noto Sans Tagbanwa',
'Noto Sans Tai Le',
'Noto Sans Tai Tham',
'Noto Sans Tai Viet',
'Noto Sans Takri',
'Noto Sans Tamil',
'Noto Sans Tamil Supplement',
'Noto Sans Telugu',
'Noto Sans Thaana',
'Noto Sans Thai',
'Noto Sans Tifinagh',
'Noto Sans Tirhuta',
'Noto Sans Ugaritic',
'Noto Sans Vai',
'Noto Sans Wancho',
'Noto Sans Warang Citi',
'Noto Sans Yi',
'Noto Sans Zanabazar Square',
];
String _packFontRanges(List<String> starts, List<String> ends) {
assert(starts.length == ends.length);
final StringBuffer sb = StringBuffer();
for (int i = 0; i < starts.length; i++) {
final int start = int.parse(starts[i], radix: 16);
final int end = int.parse(ends[i], radix: 16);
sb.write(start.toRadixString(36));
sb.write('|');
if (start != end) {
sb.write((end - start).toRadixString(36));
}
sb.write(';');
}
return sb.toString();
}
bool _checkForLicenseAttribution(Uint8List fontBytes) {
final ByteData fontData = fontBytes.buffer.asByteData();
final int codePointCount = fontData.lengthInBytes ~/ 2;
const String attributionString = 'This Font Software is licensed under the SIL Open Font License, Version 1.1.';
for (int i = 0; i < codePointCount - attributionString.length; i++) {
bool match = true;
for (int j = 0; j < attributionString.length; j++) {
if (fontData.getUint16((i + j) * 2) != attributionString.codeUnitAt(j)) {
match = false;
break;
}
}
if (match) {
return true;
}
}
return false;
}

View File

@@ -114,6 +114,27 @@ class CopyArtifactsStep implements PipelineStep {
await fontManifestFile.writeAsString(
const JsonEncoder.withIndent(' ').convert(fontManifest),
);
final io.Directory fallbackFontsSource = io.Directory(pathlib.join(
environment.engineSrcDir.path,
'third_party',
'google_fonts_for_unit_tests',
));
final String fallbackFontsDestinationPath = pathlib.join(
environment.webTestsArtifactsDir.path,
'assets',
'fallback_fonts',
);
for (final io.File file in
fallbackFontsSource.listSync(recursive: true).whereType<io.File>()
) {
final String relativePath = pathlib.relative(file.path, from: fallbackFontsSource.path);
final io.File destinationFile = io.File(pathlib.join(fallbackFontsDestinationPath, relativePath));
if (!destinationFile.parent.existsSync()) {
destinationFile.parent.createSync(recursive: true);
}
file.copySync(destinationFile.path);
}
}
Future<void> copySkiaTestImages() async {

View File

@@ -84,6 +84,9 @@ class RunSuiteStep implements PipelineStep {
'--platform=${browserEnvironment.packageTestRuntime.identifier}',
'--precompiled=$bundleBuildPath',
'--configuration=$configurationFilePath',
// TODO(jacksongardner): Set the default timeout to five minutes when
// https://github.com/dart-lang/test/issues/2006 is fixed.
'--',
..._collectTestPaths(),
];

View File

@@ -470,6 +470,7 @@ class BrowserPlatform extends PlatformPlugin {
'.json': 'application/json',
'.map': 'application/json',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};

File diff suppressed because one or more lines are too long

View File

@@ -5,21 +5,23 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/src/engine/canvaskit/renderer.dart';
import '../dom.dart';
import '../font_change_util.dart';
import '../initialization.dart';
import '../renderer.dart';
import '../util.dart';
import 'canvaskit_api.dart';
import 'font_fallback_data.dart';
import 'fonts.dart';
import 'interval_tree.dart';
import 'noto_font.dart';
import 'package:ui/src/engine.dart';
/// Global static font fallback data.
class FontFallbackData {
factory FontFallbackData() =>
FontFallbackData._(getFallbackFontData(configuration.useColorEmoji));
FontFallbackData._(this.fallbackFonts) :
_notoSansSC = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans SC'),
_notoSansTC = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans TC'),
_notoSansHK = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans HK'),
_notoSansJP = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans JP'),
_notoSansKR = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans KR'),
_notoSymbols = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans Symbols'),
notoTree = createNotoFontTree(fallbackFonts);
static FontFallbackData get instance => _instance;
static FontFallbackData _instance = FontFallbackData();
@@ -39,10 +41,20 @@ class FontFallbackData {
/// Code units which are known to be covered by at least one fallback font.
final Set<int> knownCoveredCodeUnits = <int>{};
/// Index of all font families by code unit range.
final IntervalTree<NotoFont> notoTree = createNotoFontTree();
final List<NotoFont> fallbackFonts;
static IntervalTree<NotoFont> createNotoFontTree() {
/// Index of all font families by code unit range.
final IntervalTree<NotoFont> notoTree;
final NotoFont _notoSansSC;
final NotoFont _notoSansTC;
final NotoFont _notoSansHK;
final NotoFont _notoSansJP;
final NotoFont _notoSansKR;
final NotoFont _notoSymbols;
static IntervalTree<NotoFont> createNotoFontTree(List<NotoFont> fallbackFonts) {
final Map<NotoFont, List<CodeunitRange>> ranges =
<NotoFont, List<CodeunitRange>>{};
@@ -235,144 +247,141 @@ class FontFallbackData {
globalFontFallbacks.add(family);
}
}
}
Future<void> findFontsForMissingCodeunits(List<int> codeUnits) async {
final FontFallbackData data = FontFallbackData.instance;
Future<void> findFontsForMissingCodeunits(List<int> codeUnits) async {
final FontFallbackData data = FontFallbackData.instance;
Set<NotoFont> fonts = <NotoFont>{};
final Set<int> coveredCodeUnits = <int>{};
final Set<int> missingCodeUnits = <int>{};
for (final int codeUnit in codeUnits) {
final List<NotoFont> fontsForUnit = data.notoTree.intersections(codeUnit);
fonts.addAll(fontsForUnit);
if (fontsForUnit.isNotEmpty) {
coveredCodeUnits.add(codeUnit);
} else {
missingCodeUnits.add(codeUnit);
Set<NotoFont> fonts = <NotoFont>{};
final Set<int> coveredCodeUnits = <int>{};
final Set<int> missingCodeUnits = <int>{};
for (final int codeUnit in codeUnits) {
final List<NotoFont> fontsForUnit = data.notoTree.intersections(codeUnit);
fonts.addAll(fontsForUnit);
if (fontsForUnit.isNotEmpty) {
coveredCodeUnits.add(codeUnit);
} else {
missingCodeUnits.add(codeUnit);
}
}
// The call to `findMinimumFontsForCodeUnits` will remove all code units that
// were matched by `fonts` from `unmatchedCodeUnits`.
final Set<int> unmatchedCodeUnits = Set<int>.from(coveredCodeUnits);
fonts = findMinimumFontsForCodeUnits(unmatchedCodeUnits, fonts);
fonts.forEach(notoDownloadQueue.add);
// We looked through the Noto font tree and didn't find any font families
// covering some code units.
if (missingCodeUnits.isNotEmpty || unmatchedCodeUnits.isNotEmpty) {
if (!notoDownloadQueue.isPending) {
printWarning('Could not find a set of Noto fonts to display all missing '
'characters. Please add a font asset for the missing characters.'
' See: https://flutter.dev/docs/cookbook/design/fonts');
data.codeUnitsWithNoKnownFont.addAll(missingCodeUnits);
}
}
}
// The call to `findMinimumFontsForCodeUnits` will remove all code units that
// were matched by `fonts` from `unmatchedCodeUnits`.
final Set<int> unmatchedCodeUnits = Set<int>.from(coveredCodeUnits);
fonts = findMinimumFontsForCodeUnits(unmatchedCodeUnits, fonts);
/// Finds the minimum set of fonts which covers all of the [codeUnits].
///
/// Removes all code units covered by [fonts] from [codeUnits]. The code
/// units remaining in the [codeUnits] set after calling this function do not
/// have a font that covers them and can be omitted next time to avoid
/// searching for fonts unnecessarily.
///
/// Since set cover is NP-complete, we approximate using a greedy algorithm
/// which finds the font which covers the most code units. If multiple CJK
/// fonts match the same number of code units, we choose one based on the user's
/// locale.
Set<NotoFont> findMinimumFontsForCodeUnits(
Set<int> codeUnits, Set<NotoFont> fonts) {
assert(fonts.isNotEmpty || codeUnits.isEmpty);
final Set<NotoFont> minimumFonts = <NotoFont>{};
final List<NotoFont> bestFonts = <NotoFont>[];
fonts.forEach(notoDownloadQueue.add);
final String language = domWindow.navigator.language;
// We looked through the Noto font tree and didn't find any font families
// covering some code units.
if (missingCodeUnits.isNotEmpty || unmatchedCodeUnits.isNotEmpty) {
if (!notoDownloadQueue.isPending) {
printWarning('Could not find a set of Noto fonts to display all missing '
'characters. Please add a font asset for the missing characters.'
' See: https://flutter.dev/docs/cookbook/design/fonts');
data.codeUnitsWithNoKnownFont.addAll(missingCodeUnits);
}
}
}
/// Finds the minimum set of fonts which covers all of the [codeUnits].
///
/// Removes all code units covered by [fonts] from [codeUnits]. The code
/// units remaining in the [codeUnits] set after calling this function do not
/// have a font that covers them and can be omitted next time to avoid
/// searching for fonts unnecessarily.
///
/// Since set cover is NP-complete, we approximate using a greedy algorithm
/// which finds the font which covers the most code units. If multiple CJK
/// fonts match the same number of code units, we choose one based on the user's
/// locale.
Set<NotoFont> findMinimumFontsForCodeUnits(
Set<int> codeUnits, Set<NotoFont> fonts) {
assert(fonts.isNotEmpty || codeUnits.isEmpty);
final Set<NotoFont> minimumFonts = <NotoFont>{};
final List<NotoFont> bestFonts = <NotoFont>[];
final String language = domWindow.navigator.language;
while (codeUnits.isNotEmpty) {
int maxCodeUnitsCovered = 0;
bestFonts.clear();
for (final NotoFont font in fonts) {
int codeUnitsCovered = 0;
for (final int codeUnit in codeUnits) {
if (font.contains(codeUnit)) {
codeUnitsCovered++;
while (codeUnits.isNotEmpty) {
int maxCodeUnitsCovered = 0;
bestFonts.clear();
for (final NotoFont font in fonts) {
int codeUnitsCovered = 0;
for (final int codeUnit in codeUnits) {
if (font.contains(codeUnit)) {
codeUnitsCovered++;
}
}
if (codeUnitsCovered > maxCodeUnitsCovered) {
bestFonts.clear();
bestFonts.add(font);
maxCodeUnitsCovered = codeUnitsCovered;
} else if (codeUnitsCovered == maxCodeUnitsCovered) {
bestFonts.add(font);
}
}
if (codeUnitsCovered > maxCodeUnitsCovered) {
bestFonts.clear();
bestFonts.add(font);
maxCodeUnitsCovered = codeUnitsCovered;
} else if (codeUnitsCovered == maxCodeUnitsCovered) {
bestFonts.add(font);
if (maxCodeUnitsCovered == 0) {
// Fonts cannot cover remaining unmatched characters.
break;
}
}
if (maxCodeUnitsCovered == 0) {
// Fonts cannot cover remaining unmatched characters.
break;
}
// If the list of best fonts are all CJK fonts, choose the best one based
// on locale. Otherwise just choose the first font.
NotoFont bestFont = bestFonts.first;
if (bestFonts.length > 1) {
if (bestFonts.every((NotoFont font) => _cjkFonts.contains(font))) {
if (language == 'zh-Hans' ||
language == 'zh-CN' ||
language == 'zh-SG' ||
language == 'zh-MY') {
if (bestFonts.contains(_notoSansSC)) {
// If the list of best fonts are all CJK fonts, choose the best one based
// on locale. Otherwise just choose the first font.
NotoFont bestFont = bestFonts.first;
if (bestFonts.length > 1) {
if (bestFonts.every((NotoFont font) =>
font == _notoSansSC ||
font == _notoSansTC ||
font == _notoSansHK ||
font == _notoSansJP ||
font == _notoSansKR
)) {
if (language == 'zh-Hans' ||
language == 'zh-CN' ||
language == 'zh-SG' ||
language == 'zh-MY') {
if (bestFonts.contains(_notoSansSC)) {
bestFont = _notoSansSC;
}
} else if (language == 'zh-Hant' ||
language == 'zh-TW' ||
language == 'zh-MO') {
if (bestFonts.contains(_notoSansTC)) {
bestFont = _notoSansTC;
}
} else if (language == 'zh-HK') {
if (bestFonts.contains(_notoSansHK)) {
bestFont = _notoSansHK;
}
} else if (language == 'ja') {
if (bestFonts.contains(_notoSansJP)) {
bestFont = _notoSansJP;
}
} else if (language == 'ko') {
if (bestFonts.contains(_notoSansKR)) {
bestFont = _notoSansKR;
}
} else if (bestFonts.contains(_notoSansSC)) {
bestFont = _notoSansSC;
}
} else if (language == 'zh-Hant' ||
language == 'zh-TW' ||
language == 'zh-MO') {
if (bestFonts.contains(_notoSansTC)) {
bestFont = _notoSansTC;
} else {
// To be predictable, if there is a tie for best font, choose a font
// from this list first, then just choose the first font.
if (bestFonts.contains(_notoSymbols)) {
bestFont = _notoSymbols;
} else if (bestFonts.contains(_notoSansSC)) {
bestFont = _notoSansSC;
}
} else if (language == 'zh-HK') {
if (bestFonts.contains(_notoSansHK)) {
bestFont = _notoSansHK;
}
} else if (language == 'ja') {
if (bestFonts.contains(_notoSansJP)) {
bestFont = _notoSansJP;
}
} else if (language == 'ko') {
if (bestFonts.contains(_notoSansKR)) {
bestFont = _notoSansKR;
}
} else if (bestFonts.contains(_notoSansSC)) {
bestFont = _notoSansSC;
}
} else {
// To be predictable, if there is a tie for best font, choose a font
// from this list first, then just choose the first font.
if (bestFonts.contains(_notoSymbols)) {
bestFont = _notoSymbols;
} else if (bestFonts.contains(_notoSansSC)) {
bestFont = _notoSansSC;
}
}
codeUnits.removeWhere((int codeUnit) {
return bestFont.contains(codeUnit);
});
minimumFonts.add(bestFont);
}
codeUnits.removeWhere((int codeUnit) {
return bestFont.contains(codeUnit);
});
minimumFonts.add(bestFont);
return minimumFonts;
}
return minimumFonts;
}
NotoFont _notoSansSC = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans SC');
NotoFont _notoSansTC = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans TC');
NotoFont _notoSansHK = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans HK');
NotoFont _notoSansJP = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans JP');
NotoFont _notoSansKR = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans KR');
List<NotoFont> _cjkFonts = <NotoFont>[_notoSansSC, _notoSansTC, _notoSansHK, _notoSansJP, _notoSansKR];
NotoFont _notoSymbols = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans Symbols');
class FallbackFontDownloadQueue {
NotoDownloader downloader = NotoDownloader();
@@ -462,6 +471,10 @@ class NotoDownloader {
int get debugActiveDownloadCount => _debugActiveDownloadCount;
int _debugActiveDownloadCount = 0;
static const String _defaultFallbackFontsUrlPrefix = 'https://fonts.gstatic.com/s/';
String? fallbackFontUrlPrefixOverride;
String get fallbackFontUrlPrefix => fallbackFontUrlPrefixOverride ?? _defaultFallbackFontsUrlPrefix;
/// Returns a future that resolves when there are no pending downloads.
///
/// Useful in tests to make sure that fonts are loaded before working with
@@ -492,7 +505,7 @@ class NotoDownloader {
if (assertionsEnabled) {
_debugActiveDownloadCount += 1;
}
final Future<ByteBuffer> data = httpFetchByteBuffer(url);
final Future<ByteBuffer> data = httpFetchByteBuffer('$fallbackFontUrlPrefix$url');
if (assertionsEnabled) {
unawaited(data.whenComplete(() {
_debugActiveDownloadCount -= 1;
@@ -508,7 +521,7 @@ class NotoDownloader {
if (assertionsEnabled) {
_debugActiveDownloadCount += 1;
}
final Future<String> data = httpFetchText(url);
final Future<String> data = httpFetchText('$fallbackFontUrlPrefix$url');
if (assertionsEnabled) {
unawaited(data.whenComplete(() {
_debugActiveDownloadCount -= 1;

View File

@@ -6,24 +6,9 @@ import 'dart:async';
import 'dart:developer' as developer;
import 'dart:js_interop';
import 'package:ui/src/engine/assets.dart';
import 'package:ui/src/engine/browser_detection.dart';
import 'package:ui/src/engine/configuration.dart';
import 'package:ui/src/engine/embedder.dart';
import 'package:ui/src/engine/mouse_cursor.dart';
import 'package:ui/src/engine/navigation.dart';
import 'package:ui/src/engine/platform_dispatcher.dart';
import 'package:ui/src/engine/platform_views/content_manager.dart';
import 'package:ui/src/engine/profiler.dart';
import 'package:ui/src/engine/raw_keyboard.dart';
import 'package:ui/src/engine/renderer.dart';
import 'package:ui/src/engine/safe_browser_api.dart';
import 'package:ui/src/engine/semantics/accessibility.dart';
import 'package:ui/src/engine/window.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'dom.dart';
/// The mode the app is running in.
/// Keep these in sync with the same constants on the framework-side under foundation/constants.dart.
const bool kReleaseMode =

View File

@@ -21,6 +21,8 @@ dev_dependencies:
archive: 3.1.2
args: any
async: any
convert: any
crypto: any
html: 0.15.0
http: 0.13.5
http_multi_server: any

View File

@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:js_util' as js_util;
import 'dart:math' as math;
import 'dart:typed_data';
@@ -14,12 +15,6 @@ import 'package:web_engine_tester/golden_tester.dart';
import 'common.dart';
// TODO(yjbanov): tests that render using Noto are not hermetic, as those fonts
// come from fonts.google.com, where fonts can change any time.
// These tests are skipped.
// https://github.com/flutter/flutter/issues/86432
const bool kIssue86432Exists = true;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
@@ -33,7 +28,18 @@ void testMain() {
setUp(() {
expect(notoDownloadQueue.downloader.debugActiveDownloadCount, 0);
expect(notoDownloadQueue.isPending, isFalse);
// We render some color emojis in this test.
final FlutterConfiguration config = FlutterConfiguration()
..setUserConfiguration(
js_util.jsify(<String, Object?>{
'useColorEmoji': true,
}) as JsFlutterConfiguration);
debugSetConfiguration(config);
FontFallbackData.debugReset();
notoDownloadQueue.downloader.fallbackFontUrlPrefixOverride = 'assets/fallback_fonts/';
});
tearDown(() {
@@ -129,28 +135,28 @@ void testMain() {
outerText: '次 化 刃 直 入 令',
innerText: '',
paragraphLocale: const ui.Locale('zh', 'CN'));
}, skip: kIssue86432Exists);
});
test('text styles - paragraph locale zh_TW', () async {
await testTextStyle('paragraph locale zh_TW',
outerText: '次 化 刃 直 入 令',
innerText: '',
paragraphLocale: const ui.Locale('zh', 'TW'));
}, skip: kIssue86432Exists);
});
test('text styles - paragraph locale ja', () async {
await testTextStyle('paragraph locale ja',
outerText: '次 化 刃 直 入 令',
innerText: '',
paragraphLocale: const ui.Locale('ja'));
}, skip: kIssue86432Exists);
});
test('text styles - paragraph locale ko', () async {
await testTextStyle('paragraph locale ko',
outerText: '次 化 刃 直 入 令',
innerText: '',
paragraphLocale: const ui.Locale('ko'));
}, skip: kIssue86432Exists);
});
test('text styles - color', () async {
await testTextStyle('color', color: const ui.Color(0xFF009900));
@@ -266,28 +272,28 @@ void testMain() {
innerText: '次 化 刃 直 入 令',
outerText: '',
locale: const ui.Locale('zh', 'CN'));
}, skip: kIssue86432Exists);
});
test('text styles - locale zh_TW', () async {
await testTextStyle('locale zh_TW',
innerText: '次 化 刃 直 入 令',
outerText: '',
locale: const ui.Locale('zh', 'TW'));
}, skip: kIssue86432Exists);
});
test('text styles - locale ja', () async {
await testTextStyle('locale ja',
innerText: '次 化 刃 直 入 令',
outerText: '',
locale: const ui.Locale('ja'));
}, skip: kIssue86432Exists);
});
test('text styles - locale ko', () async {
await testTextStyle('locale ko',
innerText: '次 化 刃 直 入 令',
outerText: '',
locale: const ui.Locale('ko'));
}, skip: kIssue86432Exists);
});
test('text styles - background', () async {
await testTextStyle('background',
@@ -403,7 +409,7 @@ void testMain() {
outerText: '欢',
innerText: '',
);
}, skip: kIssue86432Exists);
});
test('text style - symbols', () async {
// One of the CJK fonts loaded in one of the tests above also contains
@@ -415,7 +421,7 @@ void testMain() {
outerText: '← ↑ → ↓ ',
innerText: '',
);
}, skip: kIssue86432Exists);
});
test(
'text style - foreground/background/color do not leak across paragraphs',
@@ -736,13 +742,11 @@ Future<void> testSampleText(String language, String text,
paragraphHeight = paragraph.height;
return recorder.endRecording();
});
if (!kIssue86432Exists) {
await matchPictureGolden(
'canvaskit_sample_text_$language.png',
picture,
region: ui.Rect.fromLTRB(0, 0, testWidth, paragraphHeight + 20),
);
}
await matchPictureGolden(
'canvaskit_sample_text_$language.png',
picture,
region: ui.Rect.fromLTRB(0, 0, testWidth, paragraphHeight + 20),
);
}
typedef ParagraphFactory = CkParagraph Function();

View File

@@ -25,6 +25,9 @@ void setUpCanvasKitTest() {
HtmlViewEmbedder.instance.debugClear();
SurfaceFactory.instance.debugClear();
});
setUp(() => notoDownloadQueue.downloader.fallbackFontUrlPrefixOverride = 'assets/fallback_fonts/');
tearDown(() => notoDownloadQueue.downloader.fallbackFontUrlPrefixOverride = null);
}
/// Utility function for CanvasKit tests to draw pictures without

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
import 'dart:async';
import 'dart:js_util' as js_util;
import 'dart:math' as math;
import 'dart:typed_data';
@@ -18,7 +19,7 @@ void main() {
internalBootstrapBrowserTest(() => testMain);
}
const ui.Rect kDefaultRegion = ui.Rect.fromLTRB(0, 0, 100, 50);
const ui.Rect kDefaultRegion = ui.Rect.fromLTRB(0, 0, 100, 100);
void testMain() {
group('Font fallbacks', () {
@@ -28,19 +29,16 @@ void testMain() {
ui.PlatformMessageCallback? savedCallback;
setUp(() {
// We render some color emojis in this test.
final FlutterConfiguration config = FlutterConfiguration()
..setUserConfiguration(
js_util.jsify(<String, Object?>{
'useColorEmoji': true,
}) as JsFlutterConfiguration);
debugSetConfiguration(config);
FontFallbackData.debugReset();
notoDownloadQueue.downloader = TestDownloader();
TestDownloader.mockDownloads.clear();
final String notoSansArabicUrl = fallbackFonts
.singleWhere((NotoFont font) => font.name == 'Noto Sans Arabic')
.url;
final String notoEmojiUrl = fallbackFonts
.singleWhere((NotoFont font) => font.name == 'Noto Emoji')
.url;
TestDownloader.mockDownloads[notoSansArabicUrl] =
'/assets/fonts/NotoNaskhArabic-Regular.ttf';
TestDownloader.mockDownloads[notoEmojiUrl] =
'/assets/fonts/NotoColorEmoji.ttf';
notoDownloadQueue.downloader.fallbackFontUrlPrefixOverride = 'assets/fallback_fonts/';
savedCallback = ui.window.onPlatformMessage;
});
@@ -91,7 +89,7 @@ void testMain() {
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
}, skip: isSafari || isFirefox);
test('will put the Noto Emoji font before other fallback fonts in the list',
test('will put the Noto Color Emoji font before other fallback fonts in the list',
() async {
final Rasterizer rasterizer = CanvasKitRenderer.instance.rasterizer;
expect(FontFallbackData.instance.globalFontFallbacks, <String>['Roboto']);
@@ -123,12 +121,12 @@ void testMain() {
expect(FontFallbackData.instance.globalFontFallbacks, <String>[
'Roboto',
'Noto Emoji',
'Noto Color Emoji',
'Noto Sans Arabic',
]);
});
test('will download Noto Emojis and Noto Symbols if no matching Noto Font',
test('will download Noto Color Emojis and Noto Symbols if no matching Noto Font',
() async {
final Rasterizer rasterizer = CanvasKitRenderer.instance.rasterizer;
expect(FontFallbackData.instance.globalFontFallbacks, <String>['Roboto']);
@@ -144,7 +142,7 @@ void testMain() {
await notoDownloadQueue.debugWhenIdle();
expect(FontFallbackData.instance.globalFontFallbacks,
contains('Noto Emoji'));
contains('Noto Color Emoji'));
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(kDefaultRegion);
@@ -235,7 +233,7 @@ void testMain() {
final Set<int> supportedUniqueCodeUnits = <int>{};
final IntervalTree<NotoFont> notoTree =
FontFallbackData.instance.notoTree;
for (final NotoFont font in fallbackFonts) {
for (final NotoFont font in FontFallbackData.instance.fallbackFonts) {
testedFonts.add(font.name);
for (final CodeunitRange range in font.computeUnicodeRanges()) {
for (int codeUnit = range.start; codeUnit < range.end; codeUnit++) {
@@ -250,7 +248,7 @@ void testMain() {
testedFonts,
unorderedEquals(<String>{
'Noto Sans',
'Noto Emoji',
'Noto Color Emoji',
'Noto Sans Symbols',
'Noto Sans Symbols 2',
'Noto Sans Adlam',
@@ -419,7 +417,7 @@ void testMain() {
}
try {
findMinimumFontsForCodeUnits(codeUnits, fonts);
FontFallbackData.instance.findMinimumFontsForCodeUnits(codeUnits, fonts);
} catch (e) {
print(
'findMinimumFontsForCodeunits failed:\n'
@@ -430,7 +428,9 @@ void testMain() {
}
}
});
}, skip: isSafari);
},
skip: isSafari,
timeout: const Timeout.factor(4));
}
class TestDownloader extends NotoDownloader {
@@ -490,4 +490,14 @@ class LoggingDownloader implements NotoDownloader {
@override
int get debugActiveDownloadCount => delegate.debugActiveDownloadCount;
@override
String? get fallbackFontUrlPrefixOverride =>
delegate.fallbackFontUrlPrefixOverride;
@override set fallbackFontUrlPrefixOverride(String? override) =>
delegate.fallbackFontUrlPrefixOverride;
@override
String get fallbackFontUrlPrefix => delegate.fallbackFontUrlPrefix;
}

View File

@@ -90,6 +90,7 @@ final Set<String> skippedPaths = <String>{
r'third_party/flatbuffers/python',
r'third_party/flatbuffers/rust',
r'third_party/flatbuffers/ts',
r'third_party/google_fonts_for_unit_tests', // only used in web unit tests
r'third_party/fontconfig', // not used in standard configurations
r'third_party/freetype2/builds',
r'third_party/freetype2/src/tools',