[reland] Canvaskit get googlefont data (flutter/engine#35646)

This commit is contained in:
Harry Terkelsen
2022-08-24 16:19:31 -07:00
committed by GitHub
parent f06d0b1487
commit eb8f7b4a22
14 changed files with 823 additions and 649 deletions

View File

@@ -1140,6 +1140,7 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/color_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views_diff.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/font_fallback_data.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/font_fallbacks.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/fonts.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/image.dart
@@ -1152,6 +1153,7 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.d
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/layer_tree.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/mask_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/n_way_canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/noto_font.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/painting.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/path.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/path_metrics.dart

View File

@@ -205,6 +205,19 @@ directly), follow these steps to roll to the new version:
If you have questions, contact the Flutter Web team on Flutter Discord on the
#hackers-web-🌍 channel.
### 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:args/command_runner.dart';
import 'build.dart';
import 'clean.dart';
import 'exceptions.dart';
import 'generate_fallback_font_data.dart';
import 'licenses.dart';
import 'run.dart';
import 'test_runner.dart';
@@ -20,6 +21,7 @@ CommandRunner<bool> runner = CommandRunner<bool>(
)
..addCommand(BuildCommand())
..addCommand(CleanCommand())
..addCommand(GenerateFallbackFontDataCommand())
..addCommand(LicensesCommand())
..addCommand(RunCommand())
..addCommand(TestCommand());

View File

@@ -0,0 +1,289 @@
// 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);
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]!;
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 'noto_font.dart';");
sb.writeln();
sb.writeln('final List<NotoFont> fallbackFonts = <NotoFont>[');
for (final String family in fallbackFonts) {
sb.write(" NotoFont.fromFlatRanges('$family', '${urlForFamily[family]!}', "
'<int>[');
for (final String range in charsetForFamily[family]!.split(' ')) {
String? start;
String? end;
final List<String> parts = range.split('-');
if (parts.length == 1) {
start = parts[0];
end = parts[0];
} else {
start = parts[0];
end = parts[1];
}
sb.write('0x$start,0x$end,');
}
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 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 N Ko',
'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',
];

View File

@@ -112,6 +112,7 @@ set debugEmulateFlutterTesterEnvironment(bool value) {
engine.window.webOnlyDebugPhysicalSizeOverride =
logicalSize * window.devicePixelRatio;
}
engine.debugDisableFontFallbacks = value;
}
bool _debugEmulateFlutterTesterEnvironment = false;

View File

@@ -26,6 +26,7 @@ export 'engine/canvaskit/canvaskit_canvas.dart';
export 'engine/canvaskit/color_filter.dart';
export 'engine/canvaskit/embedded_views.dart';
export 'engine/canvaskit/embedded_views_diff.dart';
export 'engine/canvaskit/font_fallback_data.dart';
export 'engine/canvaskit/font_fallbacks.dart';
export 'engine/canvaskit/fonts.dart';
export 'engine/canvaskit/image.dart';
@@ -38,6 +39,7 @@ export 'engine/canvaskit/layer_scene_builder.dart';
export 'engine/canvaskit/layer_tree.dart';
export 'engine/canvaskit/mask_filter.dart';
export 'engine/canvaskit/n_way_canvas.dart';
export 'engine/canvaskit/noto_font.dart';
export 'engine/canvaskit/painting.dart';
export 'engine/canvaskit/path.dart';
export 'engine/canvaskit/path_metrics.dart';

File diff suppressed because one or more lines are too long

View File

@@ -3,18 +3,20 @@
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
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';
/// Global static font fallback data.
class FontFallbackData {
@@ -28,13 +30,9 @@ class FontFallbackData {
/// Used for tests.
static void debugReset() {
_instance = FontFallbackData();
notoDownloadQueue = FallbackFontDownloadQueue();
}
/// Whether or not "Noto Sans Symbols" and "Noto Color Emoji" fonts have been
/// downloaded. We download these as fallbacks when no other font covers the
/// given code units.
bool registeredSymbolsAndEmoji = false;
/// Code units that no known font has a glyph for.
final Set<int> codeUnitsWithNoKnownFont = <int>{};
@@ -48,15 +46,9 @@ class FontFallbackData {
final Map<NotoFont, List<CodeunitRange>> ranges =
<NotoFont, List<CodeunitRange>>{};
for (final NotoFont font in _notoFonts) {
// TODO(yjbanov): instead of mutating the font tree during reset, it's
// better to construct an immutable tree of resolved fonts
// pointing back to the original NotoFont objects. Then
// resetting the tree would be a matter of reconstructing
// the new resolved tree.
font.reset();
for (final NotoFont font in fallbackFonts) {
// ignore: prefer_foreach
for (final CodeunitRange range in font.approximateUnicodeRanges) {
for (final CodeunitRange range in font.computeUnicodeRanges()) {
ranges.putIfAbsent(font, () => <CodeunitRange>[]).add(range);
}
}
@@ -69,8 +61,6 @@ class FontFallbackData {
final List<String> globalFontFallbacks = <String>['Roboto'];
final Map<String, int> fontFallbackCounts = <String, int>{};
/// A list of code units to check against the global fallback fonts.
final Set<int> _codeUnitsToCheckAgainstFallbackFonts = <int>{};
@@ -85,6 +75,9 @@ class FontFallbackData {
void ensureFontsSupportText(String text, List<String> fontFamilies) {
// TODO(hterkelsen): Make this faster for the common case where the text
// is supported by the given fonts.
if (debugDisableFontFallbacks) {
return;
}
// If the text is ASCII, then skip this check.
bool isAscii = true;
@@ -164,6 +157,9 @@ class FontFallbackData {
_scheduledCodeUnitCheck = false;
// We don't know if the remaining code units are covered by our fallback
// fonts. Check them and update the cache.
if (_codeUnitsToCheckAgainstFallbackFonts.isEmpty) {
return;
}
final List<int> codeUnits = _codeUnitsToCheckAgainstFallbackFonts.toList();
_codeUnitsToCheckAgainstFallbackFonts.clear();
final List<bool> codeUnitsSupported =
@@ -224,23 +220,19 @@ class FontFallbackData {
printWarning('Failed to parse fallback font $family as a font.');
return;
}
fontFallbackCounts.putIfAbsent(family, () => 0);
final int fontFallbackTag = fontFallbackCounts[family]!;
fontFallbackCounts[family] = fontFallbackCounts[family]! + 1;
final String countedFamily = '$family $fontFallbackTag';
// Insert emoji font before all other fallback fonts so we use the emoji
// whenever it's available.
registeredFallbackFonts.add(RegisteredFont(bytes, countedFamily, typeface));
registeredFallbackFonts.add(RegisteredFont(bytes, family, typeface));
// Insert emoji font before all other fallback fonts so we use the emoji
// whenever it's available.
if (family == 'Noto Color Emoji Compat') {
if (family == 'Noto Emoji') {
if (globalFontFallbacks.first == 'Roboto') {
globalFontFallbacks.insert(1, countedFamily);
globalFontFallbacks.insert(1, family);
} else {
globalFontFallbacks.insert(0, countedFamily);
globalFontFallbacks.insert(0, family);
}
} else {
globalFontFallbacks.add(countedFamily);
globalFontFallbacks.add(family);
}
}
}
@@ -261,212 +253,25 @@ Future<void> findFontsForMissingCodeunits(List<int> codeUnits) async {
}
}
for (final NotoFont font in fonts) {
await font.ensureResolved();
}
// 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);
final Set<_ResolvedNotoSubset> resolvedFonts = <_ResolvedNotoSubset>{};
for (final int codeUnit in coveredCodeUnits) {
for (final NotoFont font in fonts) {
if (font.resolvedFont == null) {
// We failed to resolve the font earlier.
continue;
}
resolvedFonts.addAll(font.resolvedFont!.tree.intersections(codeUnit));
}
}
resolvedFonts.forEach(notoDownloadQueue.add);
fonts.forEach(notoDownloadQueue.add);
// We looked through the Noto font tree and didn't find any font families
// covering some code units, or we did find a font family, but when we
// downloaded the fonts we found that they actually didn't cover them. So
// we try looking them up in the symbols and emojis fonts.
// covering some code units.
if (missingCodeUnits.isNotEmpty || unmatchedCodeUnits.isNotEmpty) {
if (!data.registeredSymbolsAndEmoji) {
await _registerSymbolsAndEmoji();
} else {
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);
}
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);
}
}
}
/// Parse the CSS file for a font and make a list of resolved subsets.
///
/// A CSS file from Google Fonts looks like this:
///
/// /* [0] */
/// @font-face {
/// font-family: 'Noto Sans KR';
/// font-style: normal;
/// font-weight: 400;
/// src: url(https://fonts.gstatic.com/s/notosanskr/v13/PbykFmXiEBPT4ITbgNA5Cgm20xz64px_1hVWr0wuPNGmlQNMEfD4.0.woff2) format('woff2');
/// unicode-range: U+f9ca-fa0b, U+ff03-ff05, U+ff07, U+ff0a-ff0b, U+ff0d-ff19, U+ff1b, U+ff1d, U+ff20-ff5b, U+ff5d, U+ffe0-ffe3, U+ffe5-ffe6;
/// }
/// /* [1] */
/// @font-face {
/// font-family: 'Noto Sans KR';
/// font-style: normal;
/// font-weight: 400;
/// src: url(https://fonts.gstatic.com/s/notosanskr/v13/PbykFmXiEBPT4ITbgNA5Cgm20xz64px_1hVWr0wuPNGmlQNMEfD4.1.woff2) format('woff2');
/// unicode-range: U+f92f-f980, U+f982-f9c9;
/// }
/// /* [2] */
/// @font-face {
/// font-family: 'Noto Sans KR';
/// font-style: normal;
/// font-weight: 400;
/// src: url(https://fonts.gstatic.com/s/notosanskr/v13/PbykFmXiEBPT4ITbgNA5Cgm20xz64px_1hVWr0wuPNGmlQNMEfD4.2.woff2) format('woff2');
/// unicode-range: U+d723-d728, U+d72a-d733, U+d735-d748, U+d74a-d74f, U+d752-d753, U+d755-d757, U+d75a-d75f, U+d762-d764, U+d766-d768, U+d76a-d76b, U+d76d-d76f, U+d771-d787, U+d789-d78b, U+d78d-d78f, U+d791-d797, U+d79a, U+d79c, U+d79e-d7a3, U+f900-f909, U+f90b-f92e;
/// }
_ResolvedNotoFont? _makeResolvedNotoFontFromCss(String css, String name) {
final List<_ResolvedNotoSubset> subsets = <_ResolvedNotoSubset>[];
bool resolvingFontFace = false;
String? fontFaceUrl;
List<CodeunitRange>? fontFaceUnicodeRanges;
for (final String line in LineSplitter.split(css)) {
// Search for the beginning of a @font-face.
if (!resolvingFontFace) {
if (line == '@font-face {') {
resolvingFontFace = true;
} else {
continue;
}
} else {
// We are resolving a @font-face, read out the url and ranges.
if (line.startsWith(' src:')) {
final int urlStart = line.indexOf('url(');
if (urlStart == -1) {
printWarning('Unable to resolve Noto font URL: $line');
return null;
}
final int urlEnd = line.indexOf(')');
fontFaceUrl = line.substring(urlStart + 4, urlEnd);
} else if (line.startsWith(' unicode-range:')) {
fontFaceUnicodeRanges = <CodeunitRange>[];
final String rangeString = line.substring(17, line.length - 1);
final List<String> rawRanges = rangeString.split(', ');
for (final String rawRange in rawRanges) {
final List<String> startEnd = rawRange.split('-');
if (startEnd.length == 1) {
final String singleRange = startEnd.single;
assert(singleRange.startsWith('U+'));
final int rangeValue =
int.parse(singleRange.substring(2), radix: 16);
fontFaceUnicodeRanges.add(CodeunitRange(rangeValue, rangeValue));
} else {
assert(startEnd.length == 2);
final String startRange = startEnd[0];
final String endRange = startEnd[1];
assert(startRange.startsWith('U+'));
final int startValue =
int.parse(startRange.substring(2), radix: 16);
final int endValue = int.parse(endRange, radix: 16);
fontFaceUnicodeRanges.add(CodeunitRange(startValue, endValue));
}
}
} else if (line == '}') {
if (fontFaceUrl == null || fontFaceUnicodeRanges == null) {
printWarning('Unable to parse Google Fonts CSS: $css');
return null;
}
subsets
.add(_ResolvedNotoSubset(fontFaceUrl, name, fontFaceUnicodeRanges));
resolvingFontFace = false;
} else {
continue;
}
}
}
if (resolvingFontFace) {
printWarning('Unable to parse Google Fonts CSS: $css');
return null;
}
final Map<_ResolvedNotoSubset, List<CodeunitRange>> rangesMap =
<_ResolvedNotoSubset, List<CodeunitRange>>{};
for (final _ResolvedNotoSubset subset in subsets) {
// ignore: prefer_foreach
for (final CodeunitRange range in subset.ranges) {
rangesMap.putIfAbsent(subset, () => <CodeunitRange>[]).add(range);
}
}
if (rangesMap.isEmpty) {
printWarning('Parsed Google Fonts CSS was empty: $css');
return null;
}
final IntervalTree<_ResolvedNotoSubset> tree =
IntervalTree<_ResolvedNotoSubset>.createFromRanges(rangesMap);
return _ResolvedNotoFont(name, subsets, tree);
}
/// In the case where none of the known Noto Fonts cover a set of code units,
/// try the Symbols and Emoji fonts. We don't know the exact range of code units
/// that are covered by these fonts, so we download them and hope for the best.
Future<void> _registerSymbolsAndEmoji() async {
final FontFallbackData data = FontFallbackData.instance;
if (data.registeredSymbolsAndEmoji) {
return;
}
data.registeredSymbolsAndEmoji = true;
const String emojiUrl =
'https://fonts.googleapis.com/css2?family=Noto+Color+Emoji+Compat';
const String symbolsUrl =
'https://fonts.googleapis.com/css2?family=Noto+Sans+Symbols';
final String emojiCss =
await notoDownloadQueue.downloader.downloadAsString(emojiUrl);
final String symbolsCss =
await notoDownloadQueue.downloader.downloadAsString(symbolsUrl);
String? extractUrlFromCss(String css) {
for (final String line in LineSplitter.split(css)) {
if (line.startsWith(' src:')) {
final int urlStart = line.indexOf('url(');
if (urlStart == -1) {
printWarning('Unable to resolve Noto font URL: $line');
return null;
}
final int urlEnd = line.indexOf(')');
return line.substring(urlStart + 4, urlEnd);
}
}
printWarning('Unable to determine URL for Noto font');
return null;
}
final String? emojiFontUrl = extractUrlFromCss(emojiCss);
final String? symbolsFontUrl = extractUrlFromCss(symbolsCss);
if (emojiFontUrl != null) {
notoDownloadQueue.add(_ResolvedNotoSubset(
emojiFontUrl, 'Noto Color Emoji Compat', const <CodeunitRange>[]));
} else {
printWarning('Error parsing CSS for Noto Emoji font.');
}
if (symbolsFontUrl != null) {
notoDownloadQueue.add(_ResolvedNotoSubset(
symbolsFontUrl, 'Noto Sans Symbols', const <CodeunitRange>[]));
} else {
printWarning('Error parsing CSS for Noto Symbols font.');
}
}
/// Finds the minimum set of fonts which covers all of the [codeUnits].
///
/// Removes all code units covered by [fonts] from [codeUnits]. The code
@@ -492,7 +297,7 @@ Set<NotoFont> findMinimumFontsForCodeUnits(
for (final NotoFont font in fonts) {
int codeUnitsCovered = 0;
for (final int codeUnit in codeUnits) {
if (font.resolvedFont?.tree.containsDeep(codeUnit) ?? false) {
if (font.contains(codeUnit)) {
codeUnitsCovered++;
}
}
@@ -534,321 +339,47 @@ Set<NotoFont> findMinimumFontsForCodeUnits(
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.resolvedFont!.tree.containsDeep(codeUnit);
return bestFont.contains(codeUnit);
});
minimumFonts.addAll(bestFonts);
minimumFonts.add(bestFont);
}
return minimumFonts;
}
class NotoFont {
NotoFont(this.name, this.approximateUnicodeRanges);
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];
final String name;
final List<CodeunitRange> approximateUnicodeRanges;
Completer<void>? _decodingCompleter;
_ResolvedNotoFont? resolvedFont;
String get googleFontsCssUrl =>
'https://fonts.googleapis.com/css2?family=${name.replaceAll(' ', '+')}';
Future<void> ensureResolved() async {
if (resolvedFont == null) {
if (_decodingCompleter == null) {
_decodingCompleter = Completer<void>();
final String googleFontCss = await notoDownloadQueue.downloader
.downloadAsString(googleFontsCssUrl);
final _ResolvedNotoFont? googleFont =
_makeResolvedNotoFontFromCss(googleFontCss, name);
resolvedFont = googleFont;
_decodingCompleter!.complete();
} else {
await _decodingCompleter!.future;
}
}
}
void reset() {
resolvedFont = null;
_decodingCompleter = null;
}
}
class CodeunitRange {
const CodeunitRange(this.start, this.end);
final int start;
final int end;
bool contains(int codeUnit) {
return start <= codeUnit && codeUnit <= end;
}
@override
bool operator ==(dynamic other) {
if (other is! CodeunitRange) {
return false;
}
final CodeunitRange range = other;
return range.start == start && range.end == end;
}
@override
int get hashCode => Object.hash(start, end);
@override
String toString() => '[$start, $end]';
}
class _ResolvedNotoFont {
const _ResolvedNotoFont(this.name, this.subsets, this.tree);
final String name;
final List<_ResolvedNotoSubset> subsets;
final IntervalTree<_ResolvedNotoSubset> tree;
}
class _ResolvedNotoSubset {
_ResolvedNotoSubset(this.url, this.family, this.ranges);
final String url;
final String family;
final List<CodeunitRange> ranges;
@override
String toString() => '_ResolvedNotoSubset($family, $url)';
}
NotoFont _notoSansSC = NotoFont('Noto Sans SC', <CodeunitRange>[
const CodeunitRange(12288, 12591),
const CodeunitRange(12800, 13311),
const CodeunitRange(19968, 40959),
const CodeunitRange(65072, 65135),
const CodeunitRange(65280, 65519),
]);
NotoFont _notoSansTC = NotoFont('Noto Sans TC', <CodeunitRange>[
const CodeunitRange(12288, 12351),
const CodeunitRange(12549, 12585),
const CodeunitRange(19968, 40959),
]);
NotoFont _notoSansHK = NotoFont('Noto Sans HK', <CodeunitRange>[
const CodeunitRange(12288, 12351),
const CodeunitRange(12549, 12585),
const CodeunitRange(19968, 40959),
]);
NotoFont _notoSansJP = NotoFont('Noto Sans JP', <CodeunitRange>[
const CodeunitRange(12288, 12543),
const CodeunitRange(19968, 40959),
const CodeunitRange(65280, 65519),
]);
List<NotoFont> _cjkFonts = <NotoFont>[
_notoSansSC,
_notoSansTC,
_notoSansHK,
_notoSansJP,
];
List<NotoFont> _notoFonts = <NotoFont>[
_notoSansSC,
_notoSansTC,
_notoSansHK,
_notoSansJP,
NotoFont('Noto Naskh Arabic UI', <CodeunitRange>[
const CodeunitRange(1536, 1791),
const CodeunitRange(8204, 8206),
const CodeunitRange(8208, 8209),
const CodeunitRange(8271, 8271),
const CodeunitRange(11841, 11841),
const CodeunitRange(64336, 65023),
const CodeunitRange(65132, 65276),
]),
NotoFont('Noto Sans Armenian', <CodeunitRange>[
const CodeunitRange(1328, 1424),
const CodeunitRange(64275, 64279),
]),
NotoFont('Noto Sans Bengali UI', <CodeunitRange>[
const CodeunitRange(2404, 2405),
const CodeunitRange(2433, 2555),
const CodeunitRange(8204, 8205),
const CodeunitRange(8377, 8377),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Myanmar UI', <CodeunitRange>[
const CodeunitRange(4096, 4255),
const CodeunitRange(8204, 8205),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Egyptian Hieroglyphs', <CodeunitRange>[
const CodeunitRange(77824, 78894),
]),
NotoFont('Noto Sans Ethiopic', <CodeunitRange>[
const CodeunitRange(4608, 5017),
const CodeunitRange(11648, 11742),
const CodeunitRange(43777, 43822),
]),
NotoFont('Noto Sans Georgian', <CodeunitRange>[
const CodeunitRange(1417, 1417),
const CodeunitRange(4256, 4351),
const CodeunitRange(11520, 11567),
]),
NotoFont('Noto Sans Gujarati UI', <CodeunitRange>[
const CodeunitRange(2404, 2405),
const CodeunitRange(2688, 2815),
const CodeunitRange(8204, 8205),
const CodeunitRange(8377, 8377),
const CodeunitRange(9676, 9676),
const CodeunitRange(43056, 43065),
]),
NotoFont('Noto Sans Gurmukhi UI', <CodeunitRange>[
const CodeunitRange(2404, 2405),
const CodeunitRange(2561, 2677),
const CodeunitRange(8204, 8205),
const CodeunitRange(8377, 8377),
const CodeunitRange(9676, 9676),
const CodeunitRange(9772, 9772),
const CodeunitRange(43056, 43065),
]),
NotoFont('Noto Sans Hebrew', <CodeunitRange>[
const CodeunitRange(1424, 1535),
const CodeunitRange(8362, 8362),
const CodeunitRange(9676, 9676),
const CodeunitRange(64285, 64335),
]),
NotoFont('Noto Sans Devanagari UI', <CodeunitRange>[
const CodeunitRange(2304, 2431),
const CodeunitRange(7376, 7414),
const CodeunitRange(7416, 7417),
const CodeunitRange(8204, 8205),
const CodeunitRange(8360, 8360),
const CodeunitRange(8377, 8377),
const CodeunitRange(9676, 9676),
const CodeunitRange(43056, 43065),
const CodeunitRange(43232, 43259),
]),
NotoFont('Noto Sans Kannada UI', <CodeunitRange>[
const CodeunitRange(2404, 2405),
const CodeunitRange(3202, 3314),
const CodeunitRange(8204, 8205),
const CodeunitRange(8377, 8377),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Khmer UI', <CodeunitRange>[
const CodeunitRange(6016, 6143),
const CodeunitRange(8204, 8204),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans KR', <CodeunitRange>[
const CodeunitRange(12593, 12686),
const CodeunitRange(12800, 12828),
const CodeunitRange(12896, 12923),
const CodeunitRange(44032, 55215),
]),
NotoFont('Noto Sans Lao UI', <CodeunitRange>[
const CodeunitRange(3713, 3807),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Malayalam UI', <CodeunitRange>[
const CodeunitRange(775, 775),
const CodeunitRange(803, 803),
const CodeunitRange(2404, 2405),
const CodeunitRange(3330, 3455),
const CodeunitRange(8204, 8205),
const CodeunitRange(8377, 8377),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Sinhala', <CodeunitRange>[
const CodeunitRange(2404, 2405),
const CodeunitRange(3458, 3572),
const CodeunitRange(8204, 8205),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Tamil UI', <CodeunitRange>[
const CodeunitRange(2404, 2405),
const CodeunitRange(2946, 3066),
const CodeunitRange(8204, 8205),
const CodeunitRange(8377, 8377),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Telugu UI', <CodeunitRange>[
const CodeunitRange(2385, 2386),
const CodeunitRange(2404, 2405),
const CodeunitRange(3072, 3199),
const CodeunitRange(7386, 7386),
const CodeunitRange(8204, 8205),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans Thai UI', <CodeunitRange>[
const CodeunitRange(3585, 3675),
const CodeunitRange(8204, 8205),
const CodeunitRange(9676, 9676),
]),
NotoFont('Noto Sans', <CodeunitRange>[
const CodeunitRange(0, 255),
const CodeunitRange(305, 305),
const CodeunitRange(338, 339),
const CodeunitRange(699, 700),
const CodeunitRange(710, 710),
const CodeunitRange(730, 730),
const CodeunitRange(732, 732),
const CodeunitRange(8192, 8303),
const CodeunitRange(8308, 8308),
const CodeunitRange(8364, 8364),
const CodeunitRange(8482, 8482),
const CodeunitRange(8593, 8593),
const CodeunitRange(8595, 8595),
const CodeunitRange(8722, 8722),
const CodeunitRange(8725, 8725),
const CodeunitRange(65279, 65279),
const CodeunitRange(65533, 65533),
const CodeunitRange(1024, 1119),
const CodeunitRange(1168, 1169),
const CodeunitRange(1200, 1201),
const CodeunitRange(8470, 8470),
const CodeunitRange(1120, 1327),
const CodeunitRange(7296, 7304),
const CodeunitRange(8372, 8372),
const CodeunitRange(11744, 11775),
const CodeunitRange(42560, 42655),
const CodeunitRange(65070, 65071),
const CodeunitRange(880, 1023),
const CodeunitRange(7936, 8191),
const CodeunitRange(256, 591),
const CodeunitRange(601, 601),
const CodeunitRange(7680, 7935),
const CodeunitRange(8224, 8224),
const CodeunitRange(8352, 8363),
const CodeunitRange(8365, 8399),
const CodeunitRange(8467, 8467),
const CodeunitRange(11360, 11391),
const CodeunitRange(42784, 43007),
const CodeunitRange(258, 259),
const CodeunitRange(272, 273),
const CodeunitRange(296, 297),
const CodeunitRange(360, 361),
const CodeunitRange(416, 417),
const CodeunitRange(431, 432),
const CodeunitRange(7840, 7929),
const CodeunitRange(8363, 8363),
]),
];
NotoFont _notoSymbols = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans Symbols');
class FallbackFontDownloadQueue {
NotoDownloader downloader = NotoDownloader();
final Set<_ResolvedNotoSubset> downloadedSubsets = <_ResolvedNotoSubset>{};
final Map<String, _ResolvedNotoSubset> pendingSubsets =
<String, _ResolvedNotoSubset>{};
final Set<NotoFont> downloadedFonts = <NotoFont>{};
final Map<String, NotoFont> pendingFonts = <String, NotoFont>{};
bool get isPending => pendingSubsets.isNotEmpty || _fontsLoading != null;
bool get isPending => pendingFonts.isNotEmpty || _fontsLoading != null;
Future<void>? _fontsLoading;
bool get debugIsLoadingFonts => _fontsLoading != null;
@@ -860,9 +391,9 @@ class FallbackFontDownloadQueue {
if (_fontsLoading != null) {
await _fontsLoading;
}
if (pendingSubsets.isNotEmpty) {
if (pendingFonts.isNotEmpty) {
await Future<void>.delayed(const Duration(milliseconds: 100));
if (pendingSubsets.isEmpty) {
if (pendingFonts.isEmpty) {
await Future<void>.delayed(const Duration(milliseconds: 100));
}
}
@@ -872,13 +403,13 @@ class FallbackFontDownloadQueue {
}
}
void add(_ResolvedNotoSubset subset) {
if (downloadedSubsets.contains(subset) ||
pendingSubsets.containsKey(subset.url)) {
void add(NotoFont font) {
if (downloadedFonts.contains(font) ||
pendingFonts.containsKey(font.url)) {
return;
}
final bool firstInBatch = pendingSubsets.isEmpty;
pendingSubsets[subset.url] = subset;
final bool firstInBatch = pendingFonts.isEmpty;
pendingFonts[font.url] = font;
if (firstInBatch) {
Timer.run(startDownloads);
}
@@ -887,20 +418,20 @@ class FallbackFontDownloadQueue {
Future<void> startDownloads() async {
final Map<String, Future<void>> downloads = <String, Future<void>>{};
final Map<String, Uint8List> downloadedData = <String, Uint8List>{};
for (final _ResolvedNotoSubset subset in pendingSubsets.values) {
downloads[subset.url] = Future<void>(() async {
for (final NotoFont font in pendingFonts.values) {
downloads[font.url] = Future<void>(() async {
ByteBuffer buffer;
try {
buffer = await downloader.downloadAsBytes(subset.url,
debugDescription: subset.family);
buffer = await downloader.downloadAsBytes(font.url,
debugDescription: font.name);
} catch (e) {
pendingSubsets.remove(subset.url);
printWarning('Failed to load font ${subset.family} at ${subset.url}');
pendingFonts.remove(font.url);
printWarning('Failed to load font ${font.name} at ${font.url}');
printWarning(e.toString());
return;
}
downloadedSubsets.add(subset);
downloadedData[subset.url] = buffer.asUint8List();
downloadedFonts.add(font);
downloadedData[font.url] = buffer.asUint8List();
});
}
@@ -912,10 +443,10 @@ class FallbackFontDownloadQueue {
final List<String> downloadOrder =
(downloadedData.keys.toList()..sort()).reversed.toList();
for (final String url in downloadOrder) {
final _ResolvedNotoSubset subset = pendingSubsets.remove(url)!;
final NotoFont font = pendingFonts.remove(url)!;
final Uint8List bytes = downloadedData[url]!;
FontFallbackData.instance.registerFallbackFont(subset.family, bytes);
if (pendingSubsets.isEmpty) {
FontFallbackData.instance.registerFallbackFont(font.name, bytes);
if (pendingFonts.isEmpty) {
_fontsLoading = renderer.fontCollection.ensureFontsLoaded();
try {
await _fontsLoading;
@@ -926,7 +457,7 @@ class FallbackFontDownloadQueue {
}
}
if (pendingSubsets.isNotEmpty) {
if (pendingFonts.isNotEmpty) {
await startDownloads();
}
}

View File

@@ -4,7 +4,7 @@
import 'dart:math' as math;
import 'font_fallbacks.dart' show CodeunitRange;
import 'noto_font.dart' show CodeunitRange;
/// A tree which stores a set of intervals that can be queried for intersection.
class IntervalTree<T> {

View File

@@ -0,0 +1,98 @@
// 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.
class NotoFont {
const NotoFont(this.name, this.url, this._rangeStarts, this._rangeEnds);
factory NotoFont.fromFlatRanges(String name, String url, List<int> flatRanges) {
final List<int> starts = <int>[];
final List<int> ends = <int>[];
for (int i = 0; i < flatRanges.length; i += 2) {
starts.add(flatRanges[i]);
ends.add(flatRanges[i+1]);
}
return NotoFont(name, url, starts, ends);
}
final String name;
final String url;
// A sorted list of Unicode range start points.
final List<int> _rangeStarts;
// A sorted list of Unicode range end points.
final List<int> _rangeEnds;
List<CodeunitRange> computeUnicodeRanges() {
final List<CodeunitRange> result = <CodeunitRange>[];
for (int i = 0; i < _rangeStarts.length; i++) {
result.add(CodeunitRange(_rangeStarts[i], _rangeEnds[i]));
}
return result;
}
// Returns `true` if this font has a glyph for the given [codeunit].
bool contains(int codeUnit) {
// Binary search through the starts and ends to see if there
// is a range that contains the codeunit.
int min = 0;
int max = _rangeStarts.length - 1;
// Search for the first rangeStart that is greater than codeunit.
while (min < max) {
final int mid = (min + max) ~/ 2;
if (_rangeStarts[mid] > codeUnit) {
if (mid == 0) {
final int rangeStart = _rangeStarts[mid];
final int rangeEnd = _rangeEnds[mid];
return rangeStart <= codeUnit && codeUnit <= rangeEnd;
}
final int rangeStart = _rangeStarts[mid - 1];
if (rangeStart <= codeUnit) {
final int rangeEnd = _rangeEnds[mid - 1];
return rangeStart <= codeUnit && codeUnit <= rangeEnd;
} else {
max = mid - 1;
}
} else if (_rangeStarts[mid] < codeUnit) {
// If this is the last index, check if the codeunit is contained within it.
if (mid == _rangeStarts.length) {
final int rangeStart = _rangeStarts[mid];
final int rangeEnd = _rangeEnds[mid];
return rangeStart <= codeUnit && codeUnit <= rangeEnd;
}
min = mid + 1;
} else {
// _rangeStarts[mid] == codeUnit
return true;
}
}
return false;
}
}
class CodeunitRange {
const CodeunitRange(this.start, this.end);
final int start;
final int end;
bool contains(int codeUnit) {
return start <= codeUnit && codeUnit <= end;
}
@override
bool operator ==(dynamic other) {
if (other is! CodeunitRange) {
return false;
}
final CodeunitRange range = other;
return range.start == start && range.end == end;
}
@override
int get hashCode => Object.hash(start, end);
@override
String toString() => '[$start, $end]';
}

View File

@@ -272,6 +272,19 @@ void _addUrlStrategyListener() {
});
}
/// Whether to disable the font fallback system.
///
/// We need to disable font fallbacks for some framework tests because
/// Flutter error messages may contain an arrow symbol which is not
/// covered by ASCII fonts. This causes us to try to download the
/// Noto Sans Symbols font, which kicks off a `Timer` which doesn't
/// complete before the Widget tree is disposed (this is by design).
bool get debugDisableFontFallbacks => _debugDisableFontFallbacks;
set debugDisableFontFallbacks(bool value) {
_debugDisableFontFallbacks = value;
}
bool _debugDisableFontFallbacks = false;
/// The shared instance of PlatformViewManager shared across the engine to handle
/// rendering of PlatformViews into the web app.
// TODO(dit): How to make this overridable from tests?

View File

@@ -33,6 +33,7 @@ void testMain() {
setUp(() {
expect(notoDownloadQueue.downloader.debugActiveDownloadCount, 0);
expect(notoDownloadQueue.isPending, isFalse);
FontFallbackData.debugReset();
});
tearDown(() {
@@ -563,7 +564,6 @@ void testMain() {
// some of these symbols. To make sure the test produces predictable
// results we reset the fallback data forcing the engine to reload
// fallbacks, which for this test will only load Noto Symbols.
FontFallbackData.debugReset();
await testTextStyle(
'symbols',
outerText: '← ↑ → ↓ ',
@@ -819,7 +819,6 @@ void testMain() {
Future<void> testSampleText(String language, String text,
{ui.TextDirection textDirection = ui.TextDirection.ltr,
bool write = false}) async {
FontFallbackData.debugReset();
const double testWidth = 300;
double paragraphHeight = 0;
final CkPicture picture = await generatePictureWhenFontsStable(() {
@@ -1328,7 +1327,7 @@ Future<void> testTextStyle(
write: write,
);
expect(notoDownloadQueue.debugIsLoadingFonts, isFalse);
expect(notoDownloadQueue.pendingSubsets, isEmpty);
expect(notoDownloadQueue.pendingFonts, isEmpty);
expect(notoDownloadQueue.downloader.debugActiveDownloadCount, 0);
}

View File

@@ -23,6 +23,7 @@ void setUpCanvasKitTest() {
setUpAll(() async {
expect(renderer, isA<CanvasKitRenderer>(), reason: 'This test must run in CanvasKit mode.');
debugResetBrowserSupportsFinalizationRegistry();
debugDisableFontFallbacks = false;
await initializeEngine(assetManager: WebOnlyMockAssetManager());
});

View File

@@ -28,10 +28,20 @@ void testMain() {
ui.PlatformMessageCallback? savedCallback;
setUp(() {
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';
savedCallback = ui.window.onPlatformMessage;
FontFallbackData.debugReset();
});
tearDown(() {
@@ -42,21 +52,8 @@ void testMain() {
expect(FontFallbackData.instance.globalFontFallbacks, contains('Roboto'));
});
test('will download Noto Naskh Arabic if Arabic text is added', () async {
test('will download Noto Sans Arabic if Arabic text is added', () async {
final Rasterizer rasterizer = CanvasKitRenderer.instance.rasterizer;
TestDownloader.mockDownloads[
'https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic+UI'] =
'''
/* arabic */
@font-face {
font-family: 'Noto Naskh Arabic UI';
font-style: normal;
font-weight: 400;
src: url(/assets/fonts/NotoNaskhArabic-Regular.ttf) format('ttf');
unicode-range: U+0600-06FF, U+200C-200E, U+2010-2011, U+204F, U+2E41, U+FB50-FDFF, U+FE80-FEFC;
}
''';
expect(FontFallbackData.instance.globalFontFallbacks, <String>['Roboto']);
// Creating this paragraph should cause us to start to download the
@@ -70,7 +67,7 @@ void testMain() {
await notoDownloadQueue.debugWhenIdle();
expect(FontFallbackData.instance.globalFontFallbacks,
contains('Noto Naskh Arabic UI 0'));
contains('Noto Sans Arabic'));
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(kDefaultRegion);
@@ -97,28 +94,6 @@ void testMain() {
test('will put the Noto Emoji font before other fallback fonts in the list',
() async {
final Rasterizer rasterizer = CanvasKitRenderer.instance.rasterizer;
TestDownloader.mockDownloads[
'https://fonts.googleapis.com/css2?family=Noto+Color+Emoji+Compat'] =
'''
@font-face {
font-family: 'Noto Color Emoji';
src: url(/assets/fonts/NotoColorEmoji.ttf) format('ttf');
}
''';
TestDownloader.mockDownloads[
'https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic+UI'] =
'''
/* arabic */
@font-face {
font-family: 'Noto Naskh Arabic UI';
font-style: normal;
font-weight: 400;
src: url(/assets/fonts/NotoNaskhArabic-Regular.ttf) format('ttf');
unicode-range: U+0600-06FF, U+200C-200E, U+2010-2011, U+204F, U+2E41, U+FB50-FDFF, U+FE80-FEFC;
}
''';
expect(FontFallbackData.instance.globalFontFallbacks, <String>['Roboto']);
// Creating this paragraph should cause us to start to download the
@@ -132,7 +107,7 @@ void testMain() {
await notoDownloadQueue.debugWhenIdle();
expect(FontFallbackData.instance.globalFontFallbacks,
<String>['Roboto', 'Noto Naskh Arabic UI 0']);
<String>['Roboto', 'Noto Sans Arabic']);
pb = CkParagraphBuilder(
CkParagraphStyle(),
@@ -148,23 +123,14 @@ void testMain() {
expect(FontFallbackData.instance.globalFontFallbacks, <String>[
'Roboto',
'Noto Color Emoji Compat 0',
'Noto Naskh Arabic UI 0',
'Noto Emoji',
'Noto Sans Arabic',
]);
});
test('will download Noto Emojis and Noto Symbols if no matching Noto Font',
() async {
final Rasterizer rasterizer = CanvasKitRenderer.instance.rasterizer;
TestDownloader.mockDownloads[
'https://fonts.googleapis.com/css2?family=Noto+Color+Emoji+Compat'] =
'''
@font-face {
font-family: 'Noto Color Emoji';
src: url(/assets/fonts/NotoColorEmoji.ttf) format('ttf');
}
''';
expect(FontFallbackData.instance.globalFontFallbacks, <String>['Roboto']);
// Creating this paragraph should cause us to start to download the
@@ -178,7 +144,7 @@ void testMain() {
await notoDownloadQueue.debugWhenIdle();
expect(FontFallbackData.instance.globalFontFallbacks,
contains('Noto Color Emoji Compat 0'));
contains('Noto Emoji'));
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(kDefaultRegion);
@@ -202,30 +168,6 @@ void testMain() {
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
}, skip: isSafari || isFirefox);
test('will gracefully fail if we cannot parse the Google Fonts CSS',
() async {
final Rasterizer rasterizer = CanvasKitRenderer.instance.rasterizer;
TestDownloader.mockDownloads[
'https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic+UI'] =
'invalid CSS... this should cause our parser to fail';
expect(FontFallbackData.instance.globalFontFallbacks, <String>['Roboto']);
// Creating this paragraph should cause us to start to download the
// fallback font.
final CkParagraphBuilder pb = CkParagraphBuilder(
CkParagraphStyle(),
);
pb.addText('مرحبا');
// Flush microtasks and test that we didn't start any downloads.
rasterizer.debugRunPostFrameCallbacks();
await Future<void>.delayed(Duration.zero);
expect(notoDownloadQueue.isPending, isFalse);
expect(FontFallbackData.instance.globalFontFallbacks, <String>['Roboto']);
});
// Regression test for https://github.com/flutter/flutter/issues/75836
// When we had this bug our font fallback resolution logic would end up in an
// infinite loop and this test would freeze and time out.
@@ -240,16 +182,12 @@ void testMain() {
CkParagraphBuilder(CkParagraphStyle()).addText('ヽಠ');
rasterizer.debugRunPostFrameCallbacks();
await notoDownloadQueue.downloader.debugWhenIdle();
await notoDownloadQueue.debugWhenIdle();
expect(
loggingDownloader.log,
<String>[
'https://fonts.googleapis.com/css2?family=Noto+Sans+SC',
'https://fonts.googleapis.com/css2?family=Noto+Sans+JP',
'https://fonts.googleapis.com/css2?family=Noto+Sans+Kannada+UI',
'Noto Sans SC',
'Noto Sans JP',
'Noto Sans Kannada UI',
'Noto Sans Kannada',
],
);
@@ -257,7 +195,7 @@ void testMain() {
loggingDownloader.log.clear();
CkParagraphBuilder(CkParagraphStyle()).addText('ヽಠ');
rasterizer.debugRunPostFrameCallbacks();
await notoDownloadQueue.downloader.debugWhenIdle();
await notoDownloadQueue.debugWhenIdle();
expect(loggingDownloader.log, isEmpty);
});
@@ -274,7 +212,7 @@ void testMain() {
FontFallbackData.instance.notoTree;
for (final NotoFont font in notoTree.root.enumerateAllElements()) {
testedFonts.add(font.name);
for (final CodeunitRange range in font.approximateUnicodeRanges) {
for (final CodeunitRange range in font.computeUnicodeRanges()) {
for (int codeUnit = range.start;
codeUnit < range.end;
codeUnit += 1) {
@@ -289,30 +227,146 @@ void testMain() {
testedFonts,
unorderedEquals(<String>{
'Noto Sans',
'Noto Sans Malayalam UI',
'Noto Emoji',
'Noto Sans Symbols',
'Noto Sans Symbols 2',
'Noto Sans Adlam',
'Noto Sans Anatolian Hieroglyphs',
'Noto Sans Arabic',
'Noto Sans Armenian',
'Noto Sans Georgian',
'Noto Sans Hebrew',
'Noto Naskh Arabic UI',
'Noto Sans Devanagari UI',
'Noto Sans Telugu UI',
'Noto Sans Tamil UI',
'Noto Sans Kannada UI',
'Noto Sans Sinhala',
'Noto Sans Gurmukhi UI',
'Noto Sans Gujarati UI',
'Noto Sans Bengali UI',
'Noto Sans Thai UI',
'Noto Sans Lao UI',
'Noto Sans Myanmar UI',
'Noto Sans Ethiopic',
'Noto Sans Khmer UI',
'Noto Sans SC',
'Noto Sans JP',
'Noto Sans TC',
'Noto Sans HK',
'Noto Sans KR',
'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 N Ko',
'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',
}));
// Construct random paragraphs out of supported code units.
@@ -356,16 +410,34 @@ void testMain() {
}
class TestDownloader extends NotoDownloader {
// Where to redirect downloads to.
static final Map<String, String> mockDownloads = <String, String>{};
@override
Future<String> downloadAsString(String url,
{String? debugDescription}) async {
if (mockDownloads.containsKey(url)) {
return mockDownloads[url]!;
url = mockDownloads[url]!;
final Uri uri = Uri.parse(url);
expect(uri.isScheme('http'), isFalse);
expect(uri.isScheme('https'), isFalse);
return super.downloadAsString(url);
} else {
return '';
}
}
@override
Future<ByteBuffer> downloadAsBytes(String url, {String? debugDescription}) {
if (mockDownloads.containsKey(url)) {
url = mockDownloads[url]!;
final Uri uri = Uri.parse(url);
expect(uri.isScheme('http'), isFalse);
expect(uri.isScheme('https'), isFalse);
return super.downloadAsBytes(url);
} else {
return Future<ByteBuffer>.value(Uint8List(0).buffer);
}
}
}
class LoggingDownloader implements NotoDownloader {