Merge: add your own fonts in Settings

This commit is contained in:
2026-11-04 18:45:25 +00:00
28 changed files with 2329 additions and 122 deletions
@@ -0,0 +1,153 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../ui/theme/app_font_controller.dart';
import '../../ui/theme/custom_fonts/custom_font.dart';
import '../../ui/theme/custom_fonts/custom_font_draft.dart';
import '../../ui/theme/custom_fonts/font_file_picker.dart';
import 'settings_custom_font_dialogs.dart';
import 'settings_theme.dart';
const addCustomFontText = 'Add font…';
const addingCustomFontText = 'Adding…';
const renameCustomFontText = 'Rename';
const removeCustomFontText = 'Remove';
const customFontActionsTooltip = 'Font options';
/// Pick files, check them, ask for the family's name, then register, store
/// and choose the font. Every refusal is said in a dialog; nothing is
/// stored unless the whole family loaded.
Future<void> addCustomFont(
BuildContext context,
AppFontController fonts,
FontFilePicker pick,
) async {
Future<void> problem(String message) async {
if (context.mounted) {
await showFontProblem(context, addCustomFontFailedTitle, message);
}
}
final List<PickedFontFile>? files;
try {
files = await pick();
} on CustomFontRejected catch (error) {
return problem(error.message);
} catch (_) {
return problem('The chosen files could not be read.');
}
if (files == null || !context.mounted) return;
final CustomFontDraft draft;
try {
draft = await fonts.inspect(files);
} on CustomFontRejected catch (error) {
return problem(error.message);
}
if (!context.mounted) return;
final name = await showFontNameDialog(
context,
title: addCustomFontTitle,
initial: draft.suggestedName,
confirm: 'Add',
detail: draft.faces.map((f) => '${f.styleName} · ${f.fileName}').join('\n'),
);
if (name == null) return;
try {
await fonts.addCustom(draft, name);
} on CustomFontRejected catch (error) {
return problem(error.message);
}
}
enum _CustomFontAction { rename, remove }
/// The overflow control on an added font's row: Rename and Remove.
class CustomFontMenu extends StatelessWidget {
const CustomFontMenu({super.key, required this.fonts, required this.font});
final AppFontController fonts;
final CustomFont font;
Future<void> _run(BuildContext context, _CustomFontAction action) async {
switch (action) {
case _CustomFontAction.rename:
final name = await showFontNameDialog(
context,
title: renameCustomFontTitle,
initial: font.name,
confirm: renameCustomFontText,
);
if (name == null || name == font.name) return;
try {
await fonts.renameCustom(font, name);
} on CustomFontRejected catch (error) {
if (context.mounted) {
await showFontProblem(
context,
renameCustomFontTitle,
error.message,
);
}
}
case _CustomFontAction.remove:
if (await confirmRemoveFont(context, font.name)) {
await fonts.removeCustom(font);
}
}
}
Future<void> _cupertinoSheet(BuildContext context) async {
final action = await showCupertinoModalPopup<_CustomFontAction>(
context: context,
builder: (context) => CupertinoActionSheet(
title: Text(font.name),
actions: <Widget>[
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context, _CustomFontAction.rename),
child: const Text(renameCustomFontText),
),
CupertinoActionSheetAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, _CustomFontAction.remove),
child: const Text(removeCustomFontText),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
);
if (action != null && context.mounted) await _run(context, action);
}
@override
Widget build(BuildContext context) {
if (usesCupertinoControls(context)) {
return Semantics(
label: customFontActionsTooltip,
button: true,
excludeSemantics: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => _cupertinoSheet(context),
child: const Icon(CupertinoIcons.ellipsis_circle),
),
);
}
return PopupMenuButton<_CustomFontAction>(
tooltip: customFontActionsTooltip,
onSelected: (action) => _run(context, action),
itemBuilder: (context) => const <PopupMenuEntry<_CustomFontAction>>[
PopupMenuItem(
value: _CustomFontAction.rename,
child: Text(renameCustomFontText),
),
PopupMenuItem(
value: _CustomFontAction.remove,
child: Text(removeCustomFontText),
),
],
);
}
}
@@ -0,0 +1,213 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../ui/theme/custom_fonts/custom_font_draft.dart';
import 'settings_theme.dart';
const customFontNameLabel = 'Name';
const addCustomFontTitle = 'Add font';
const renameCustomFontTitle = 'Rename font';
const addCustomFontFailedTitle = 'Could not add font';
/// Asks for a font family's name, prefilled with [initial]; null when
/// cancelled. [detail] lists what is being added.
Future<String?> showFontNameDialog(
BuildContext context, {
required String title,
required String initial,
required String confirm,
String? detail,
}) {
final dialog = _FontNameDialog(
title: title,
initial: initial,
confirm: confirm,
detail: detail,
);
return usesCupertinoControls(context)
? showCupertinoDialog<String>(context: context, builder: (_) => dialog)
: showDialog<String>(context: context, builder: (_) => dialog);
}
class _FontNameDialog extends StatefulWidget {
const _FontNameDialog({
required this.title,
required this.initial,
required this.confirm,
this.detail,
});
final String title;
final String initial;
final String confirm;
final String? detail;
@override
State<_FontNameDialog> createState() => _FontNameDialogState();
}
class _FontNameDialogState extends State<_FontNameDialog> {
late final TextEditingController _name = TextEditingController(
text: widget.initial,
);
String? _problem;
@override
void dispose() {
_name.dispose();
super.dispose();
}
void _submit() {
final problem = CustomFontLimits.nameProblem(_name.text);
if (problem != null) {
setState(() => _problem = problem);
return;
}
Navigator.pop(context, _name.text.trim());
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoControls(context);
final field = cupertino
? CupertinoTextField(
controller: _name,
autofocus: true,
placeholder: customFontNameLabel,
maxLength: CustomFontLimits.maxNameLength,
onSubmitted: (_) => _submit(),
)
: TextField(
controller: _name,
autofocus: true,
maxLength: CustomFontLimits.maxNameLength,
decoration: InputDecoration(
labelText: customFontNameLabel,
errorText: _problem,
),
onSubmitted: (_) => _submit(),
);
final content = Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (widget.detail != null) ...<Widget>[
Text(widget.detail!),
const SizedBox(height: 12),
],
field,
if (cupertino && _problem != null)
Text(_problem!, style: TextStyle(color: settingsErrorColor(context))),
],
);
if (cupertino) {
return CupertinoAlertDialog(
title: Text(widget.title),
content: Padding(
padding: const EdgeInsets.only(top: 8),
child: content,
),
actions: <Widget>[
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: _submit,
child: Text(widget.confirm),
),
],
);
}
return AlertDialog(
title: Text(widget.title),
content: SingleChildScrollView(child: content),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
TextButton(onPressed: _submit, child: Text(widget.confirm)),
],
);
}
}
/// Confirms deleting an added font; true when the user agrees.
Future<bool> confirmRemoveFont(BuildContext context, String name) async {
final title = Text('Remove $name?');
const body = Text('Its files are deleted from this device.');
final confirmed = usesCupertinoControls(context)
? await showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: title,
content: body,
actions: <Widget>[
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, true),
child: const Text('Remove'),
),
],
),
)
: await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: title,
content: body,
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Remove'),
),
],
),
);
return confirmed ?? false;
}
/// Says why a font could not be added or changed.
Future<void> showFontProblem(
BuildContext context,
String title,
String message,
) => usesCupertinoControls(context)
? showCupertinoDialog<void>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: Text(title),
content: Text(message),
actions: <Widget>[
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
)
: showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: Text(message),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
@@ -5,49 +5,82 @@ import 'package:flutter/material.dart';
import '../../ui/theme/app_font.dart';
import '../../ui/theme/app_font_controller.dart';
import '../../ui/theme/custom_fonts/custom_font.dart';
import '../../ui/theme/custom_fonts/font_file_picker.dart';
import '../../ui/theme/font_choice.dart';
import 'settings_custom_font_actions.dart';
import 'settings_group.dart';
import 'settings_row.dart';
import 'settings_theme.dart';
const fontSectionTitle = 'Font';
const fontSectionFooter =
'Saved on this device only. Code keeps its monospace font.';
'Saved on this device only. Code keeps its monospace font. '
'Added fonts: .ttf or .otf, up to 10 MB each.';
const fontLoadingText = 'Loading…';
const fontLoadFailedText = 'Could not load this font.';
const fontSaveFailedText = 'Not saved on this device; it applies until reload.';
ValueKey<String> settingsFontKey(AppFont font) =>
ValueKey<String> settingsFontKey(FontChoice font) =>
ValueKey<String>('settings-font-${font.id}');
const ValueKey<String> settingsAddFontKey = ValueKey<String>(
'settings-font-add',
);
/// The device's interface font: one row per option, each named in its own
/// face. Material rows are radio tiles, Cupertino rows carry the checkmark.
/// face, the user's added fonts below the bundled ones, then "Add font…".
/// Material rows are radio tiles, Cupertino rows carry the checkmark.
/// A choice is stored locally and applies as soon as its files load.
class SettingsFontSection extends StatefulWidget {
const SettingsFontSection({super.key, required this.controller});
const SettingsFontSection({
super.key,
required this.controller,
this.pickFiles = pickFontFiles,
});
final AppFontController controller;
/// The host file picker; tests substitute chosen files.
final FontFilePicker pickFiles;
@override
State<SettingsFontSection> createState() => _SettingsFontSectionState();
}
class _SettingsFontSectionState extends State<SettingsFontSection> {
bool _adding = false;
@override
void initState() {
super.initState();
_preview();
unawaited(_preview());
}
@override
void didUpdateWidget(SettingsFontSection oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) _preview();
if (oldWidget.controller != widget.controller) unawaited(_preview());
}
/// Only the regular weight of each option, only once Settings is shown.
void _preview() {
Future<void> _preview() async {
final controller = widget.controller;
for (final font in AppFont.values) {
unawaited(widget.controller.preview(font));
unawaited(controller.preview(font));
}
await controller.loadCustomFonts();
for (final font in controller.customFonts) {
unawaited(controller.preview(font));
}
}
Future<void> _add() async {
setState(() => _adding = true);
try {
await addCustomFont(context, widget.controller, widget.pickFiles);
} finally {
if (mounted) setState(() => _adding = false);
}
}
@@ -60,6 +93,7 @@ class _SettingsFontSectionState extends State<SettingsFontSection> {
Widget _group(BuildContext context) {
final controller = widget.controller;
final cupertino = usesCupertinoControls(context);
final options = <FontChoice>[...AppFont.values, ...controller.customFonts];
final group = SettingsGroup(
title: fontSectionTitle,
footer: Column(
@@ -74,19 +108,28 @@ class _SettingsFontSectionState extends State<SettingsFontSection> {
],
),
children: <Widget>[
for (final font in AppFont.values)
for (final font in options)
cupertino
? _cupertinoRow(context, font)
: RadioListTile<AppFont>(
key: settingsFontKey(font),
value: font,
title: _name(context, font),
subtitle: _status(context, font),
),
: _materialRow(context, font),
// Its own node: a bare list tile would lend its label and tap to the
// section around it.
Semantics(
container: true,
child: SettingsRow(
key: settingsAddFontKey,
action: true,
enabled: !_adding,
leading: Icon(cupertino ? CupertinoIcons.add : Icons.add),
title: const Text(addCustomFontText),
subtitle: _adding ? const Text(addingCustomFontText) : null,
onTap: () => unawaited(_add()),
),
),
],
);
if (cupertino) return group;
return RadioGroup<AppFont>(
return RadioGroup<FontChoice>(
groupValue: controller.selected,
onChanged: (font) {
if (font != null) unawaited(controller.select(font));
@@ -95,38 +138,84 @@ class _SettingsFontSectionState extends State<SettingsFontSection> {
);
}
Widget _cupertinoRow(BuildContext context, AppFont font) => SettingsRow(
key: settingsFontKey(font),
title: _name(context, font),
subtitle: _status(context, font),
trailing: widget.controller.selected == font
Widget _materialRow(BuildContext context, FontChoice font) {
final tile = RadioListTile<FontChoice>(
key: settingsFontKey(font),
value: font,
title: _name(context, font),
subtitle: _status(context, font),
);
if (font is! CustomFont) return tile;
// The options button sits beside the tile rather than in its
// `secondary` slot: the tile merges its children's semantics, which
// would leave the button unreachable on its own.
return Row(
children: <Widget>[
Expanded(child: tile),
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: CustomFontMenu(fonts: widget.controller, font: font),
),
],
);
}
Widget _cupertinoRow(BuildContext context, FontChoice font) {
final check = widget.controller.selected == font
? Icon(
CupertinoIcons.check_mark,
color: CupertinoTheme.of(context).primaryColor,
)
: null,
onTap: () => unawaited(widget.controller.select(font)),
);
: null;
// One node per option, announced as selected.
final row = Semantics(
container: true,
selected: check != null,
child: SettingsRow(
key: settingsFontKey(font),
title: _name(context, font),
subtitle: _status(context, font),
trailing: check,
onTap: () => unawaited(widget.controller.select(font)),
),
);
if (font is! CustomFont) return row;
// Beside the row, not in it: the list tile merges its children's
// semantics (see [_materialRow]).
return Row(
children: <Widget>[
Expanded(child: row),
Padding(
padding: const EdgeInsetsDirectional.only(end: 12),
child: CustomFontMenu(fonts: widget.controller, font: font),
),
],
);
}
/// The option's name in its own face once its regular weight has loaded;
/// the system face until then (and always for the system option).
Widget _name(BuildContext context, AppFont font) {
Widget _name(BuildContext context, FontChoice font) {
final family = widget.controller.canPreview(font)
? font.family ?? _systemFamily(context)
: _systemFamily(context);
return Text(font.label, style: TextStyle(fontFamily: family));
}
Widget? _status(BuildContext context, AppFont font) {
/// Loading or failure for the chosen option; an added font otherwise
/// lists its styles.
Widget? _status(BuildContext context, FontChoice font) {
final controller = widget.controller;
if (controller.selected != font) return null;
if (controller.loadFailed == font) {
return Text(
fontLoadFailedText,
style: TextStyle(color: settingsErrorColor(context)),
);
if (controller.selected == font) {
if (controller.loadFailed == font) {
return Text(
fontLoadFailedText,
style: TextStyle(color: settingsErrorColor(context)),
);
}
if (controller.loading) return const Text(fontLoadingText);
}
return controller.loading ? const Text(fontLoadingText) : null;
return font is CustomFont ? Text(font.styles) : null;
}
}
+13 -5
View File
@@ -1,9 +1,11 @@
/// The interface typefaces a device can choose. [AppFont.system] keeps the
import 'font_choice.dart';
/// The bundled interface typefaces a device can choose. [AppFont.system] keeps the
/// platform's own typography (Roboto on Android and the web, SF on iOS); every
/// other option is an open-licence (SIL OFL 1.1) family bundled under
/// `fonts/<directory>/` as plain assets, not under pubspec `fonts:`, so a web
/// page downloads only the family it actually shows.
enum AppFont {
enum AppFont implements FontChoice {
system('system', 'System default', null, null, <String>[]),
inter('inter', 'Inter', 'Inter', 'inter', <String>[
'Inter-Regular.ttf',
@@ -50,13 +52,13 @@ enum AppFont {
const AppFont(this.id, this.label, this.family, this._directory, this._files);
/// The stored value. Stable across releases; never the display label.
@override
final String id;
/// The picker's name for the option.
@override
final String label;
/// The registered family name; null keeps the platform typography.
@override
final String? family;
final String? _directory;
@@ -70,6 +72,12 @@ enum AppFont {
/// The regular weight alone: enough to preview the option's name.
String? get previewAsset => _files.isEmpty ? null : assets.first;
@override
List<String> get sources => assets;
@override
String? get previewSource => previewAsset;
/// The licence shipped beside the files.
String? get licenseAsset =>
_directory == null ? null : 'fonts/$_directory/OFL.txt';
+122 -46
View File
@@ -1,28 +1,21 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'app_font.dart';
import 'app_font_loaders.dart';
import 'app_font_store.dart';
import 'custom_fonts/custom_font.dart';
import 'custom_fonts/custom_font_draft.dart';
import 'custom_fonts/custom_font_library.dart';
import 'font_choice.dart';
/// Registers [assets] under [family]. Production reads them from the bundle;
/// tests substitute a recorder.
typedef AppFontAssetLoader =
Future<void> Function(String family, List<String> assets);
/// Loads bundled font files on demand with a [FontLoader]. On the web each
/// asset is fetched only now, when its family is first previewed or chosen.
Future<void> loadBundledFontAssets(String family, List<String> assets) async {
final loader = FontLoader(family);
for (final asset in assets) {
loader.addFont(rootBundle.load(asset));
}
await loader.load();
}
export 'app_font_loaders.dart';
/// The device's interface font: the stored choice, the family the theme
/// actually uses, and the on-demand loading between the two.
/// actually uses, the on-demand loading between the two, and the fonts the
/// user added.
///
/// The theme keeps the previous family (at first the platform's) until the
/// chosen files are registered, then switches once; text never lays out in a
@@ -30,51 +23,69 @@ Future<void> loadBundledFontAssets(String family, List<String> assets) async {
class AppFontController extends ChangeNotifier {
AppFontController({
this._store = const SharedPreferencesAppFontStore(),
this._loader = loadBundledFontAssets,
});
AppFontAssetLoader? loader,
this._bytesLoader = loadFontBytes,
CustomFontLibrary? library,
}) : _library = library ?? CustomFontLibrary() {
_loader = loader ?? appFontSourceLoader(_library.read);
}
/// The app's own controller: one per running app, shared by the theme
/// hosts and the Settings picker.
static final AppFontController instance = AppFontController();
final AppFontStore _store;
final AppFontAssetLoader _loader;
late final AppFontAssetLoader _loader;
final AppFontBytesLoader _bytesLoader;
final CustomFontLibrary _library;
final Map<String, Future<void>> _assetLoads = <String, Future<void>>{};
final Set<String> _loadedAssets = <String>{};
Future<void>? _libraryLoad;
AppFont _selected = AppFont.system;
AppFont _applied = AppFont.system;
FontChoice _selected = AppFont.system;
FontChoice _applied = AppFont.system;
bool _saveFailed = false;
AppFont? _loadFailed;
FontChoice? _loadFailed;
/// The option the picker shows as chosen.
AppFont get selected => _selected;
FontChoice get selected => _selected;
/// The option the theme uses now.
AppFont get applied => _applied;
FontChoice get applied => _applied;
/// The theme's family; null keeps the platform typography.
String? get family => _applied.family;
/// The chosen family's files are still downloading.
/// The fonts the user added on this device, in the order added.
List<CustomFont> get customFonts => _library.fonts;
/// The chosen family's files are still loading.
bool get loading => _selected != _applied && _loadFailed != _selected;
/// The last choice could not be stored on this device.
bool get saveFailed => _saveFailed;
/// The chosen family's files could not be loaded; the theme kept [applied].
AppFont? get loadFailed => _loadFailed;
FontChoice? get loadFailed => _loadFailed;
/// Whether [font]'s regular weight is registered, so its name can be drawn
/// in its own face.
bool canPreview(AppFont font) =>
font.previewAsset == null || _loadedAssets.contains(font.previewAsset);
bool canPreview(FontChoice font) =>
font.previewSource == null || _loadedAssets.contains(font.previewSource);
/// Reads the added fonts' index once.
Future<void> loadCustomFonts() => _libraryLoad ??= () async {
await _library.load();
notifyListeners();
}();
/// Reads the stored choice and starts loading it. With [wait], returns once
/// it is applied or after [wait], whichever is first; a slower load still
/// applies when it finishes.
Future<void> restore({Duration? wait}) async {
final font = await _store.load();
final id = await _store.load();
if (id == null || id == AppFont.system.id) return;
final font = await _resolve(id);
if (font == AppFont.system || font == _selected) return;
_selected = font;
notifyListeners();
@@ -86,13 +97,25 @@ class AppFontController extends ChangeNotifier {
]);
}
Future<FontChoice> _resolve(String id) async {
for (final font in AppFont.values) {
if (font.id == id) return font;
}
if (!id.startsWith(CustomFont.idPrefix)) return AppFont.system;
await loadCustomFonts();
for (final font in customFonts) {
if (font.id == id) return font;
}
return AppFont.system;
}
/// Chooses [font], stores it, and applies it once its files are loaded.
Future<void> select(AppFont font) async {
Future<void> select(FontChoice font) async {
if (font == _selected && _loadFailed != font) return;
_selected = font;
_loadFailed = null;
notifyListeners();
final saved = await _store.save(font);
final saved = await _store.save(font.id);
if (saved == _saveFailed) {
_saveFailed = !saved;
notifyListeners();
@@ -102,25 +125,78 @@ class AppFontController extends ChangeNotifier {
/// Loads [font]'s regular weight for its picker row. Failures are quiet: the
/// row keeps the current face and choosing it reports the problem.
Future<void> preview(AppFont font) async {
final asset = font.previewAsset;
Future<void> preview(FontChoice font) async {
final source = font.previewSource;
final family = font.family;
if (asset == null || family == null || _loadedAssets.contains(asset)) {
if (source == null || family == null || _loadedAssets.contains(source)) {
return;
}
try {
await _ensure(family, <String>[asset]);
await _ensure(family, <String>[source]);
} catch (_) {
return;
}
notifyListeners();
}
Future<void> _apply(AppFont font) async {
/// Checks picked files before they are named; see
/// [CustomFontDraft.inspect]. Throws [CustomFontRejected].
Future<CustomFontDraft> inspect(List<PickedFontFile> files) async {
await loadCustomFonts();
return CustomFontDraft.inspect(files, storedBytes: _library.storedBytes);
}
/// Registers [draft]'s files with the engine, and only if that works
/// stores them as [name] and chooses the new font. Throws
/// [CustomFontRejected]; a rejected font is never stored.
Future<CustomFont> addCustom(CustomFontDraft draft, String name) async {
final problem = CustomFontLimits.nameProblem(name);
if (problem != null) throw CustomFontRejected(problem);
await loadCustomFonts();
final font = _library.prepare(draft, name.trim());
try {
await _bytesLoader(font.family, <Uint8List>[
for (final face in draft.faces) face.bytes,
]);
} catch (_) {
throw const CustomFontRejected('This font could not be loaded.');
}
await _library.store(font, draft);
for (final source in font.sources) {
_assetLoads[source] = Future<void>.value();
_loadedAssets.add(source);
}
notifyListeners();
await select(font);
return font;
}
/// Renames an added font; the choice and the theme keep it.
Future<void> renameCustom(CustomFont font, String name) async {
final problem = CustomFontLimits.nameProblem(name);
if (problem != null) throw CustomFontRejected(problem);
final renamed = await _library.rename(font, name.trim());
if (_selected == font) _selected = renamed;
if (_applied == font) _applied = renamed;
notifyListeners();
}
/// Deletes an added font. When it is chosen (or still shown), the device
/// returns to the system default.
Future<void> removeCustom(CustomFont font) async {
await _library.remove(font);
if (_selected == font || _applied == font) {
_applied = AppFont.system;
await select(AppFont.system);
}
notifyListeners();
}
Future<void> _apply(FontChoice font) async {
final family = font.family;
if (family != null) {
try {
await _ensure(family, font.assets);
await _ensure(family, font.sources);
} catch (_) {
if (_selected == font) {
_loadFailed = font;
@@ -135,22 +211,22 @@ class AppFontController extends ChangeNotifier {
notifyListeners();
}
/// Registers the assets not yet loaded or loading, in one [FontLoader], and
/// waits for all of [assets]. A failed asset can be retried.
Future<void> _ensure(String family, List<String> assets) {
final missing = assets.where((a) => !_assetLoads.containsKey(a)).toList();
/// Registers the sources not yet loaded or loading, in one [FontLoader],
/// and waits for all of [sources]. A failed source can be retried.
Future<void> _ensure(String family, List<String> sources) {
final missing = sources.where((s) => !_assetLoads.containsKey(s)).toList();
if (missing.isNotEmpty) {
final load = _loader(family, missing);
for (final asset in missing) {
_assetLoads[asset] = load.then(
(_) => _loadedAssets.add(asset),
for (final source in missing) {
_assetLoads[source] = load.then(
(_) => _loadedAssets.add(source),
onError: (Object error, StackTrace stack) {
_assetLoads.remove(asset);
_assetLoads.remove(source);
Error.throwWithStackTrace(error, stack);
},
);
}
}
return Future.wait(assets.map((a) => _assetLoads[a]!));
return Future.wait(sources.map((s) => _assetLoads[s]!));
}
}
+43
View File
@@ -0,0 +1,43 @@
import 'package:flutter/services.dart';
import 'font_choice.dart';
/// Registers [sources] under [family]. Production reads them from the bundle
/// or the custom font store; tests substitute a recorder.
typedef AppFontAssetLoader =
Future<void> Function(String family, List<String> sources);
/// Registers font files already in memory under [family]; used to check an
/// added font before it is stored.
typedef AppFontBytesLoader =
Future<void> Function(String family, List<Uint8List> faces);
/// Reads the bytes of an added face by its store key.
typedef CustomFontReader = Future<Uint8List> Function(String key);
/// Loads font files on demand with a [FontLoader]: bundle assets (on the web
/// each is fetched only now, when its family is first previewed or chosen)
/// and [customFontSource] keys, read through [readCustom].
AppFontAssetLoader appFontSourceLoader(CustomFontReader readCustom) =>
(family, sources) async {
final loader = FontLoader(family);
for (final source in sources) {
loader.addFont(
source.startsWith(customFontSourcePrefix)
? readCustom(
source.substring(customFontSourcePrefix.length),
).then(ByteData.sublistView)
: rootBundle.load(source),
);
}
await loader.load();
};
/// Registers in-memory font files with a [FontLoader].
Future<void> loadFontBytes(String family, List<Uint8List> faces) async {
final loader = FontLoader(family);
for (final face in faces) {
loader.addFont(Future<ByteData>.value(ByteData.sublistView(face)));
}
await loader.load();
}
+15 -15
View File
@@ -1,18 +1,18 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'app_font.dart';
/// The device's font choice. It lives in this device's (or browser's) own
/// preferences and is never sent to a server, so a phone and a browser signed
/// in to the same server keep their own choice.
const String appFontKey = 'pipelines.next.font.v1';
/// The persistence seam for the font choice.
/// The persistence seam for the font choice: the chosen option's stable id
/// (a bundled `AppFont.id` or an added `CustomFont.id`).
abstract interface class AppFontStore {
Future<AppFont> load();
/// The stored id; null when nothing is stored or it cannot be read.
Future<String?> load();
/// Whether the choice is actually stored.
Future<bool> save(AppFont font);
Future<bool> save(String id);
}
/// `shared_preferences` storage. An unavailable or unreadable store means the
@@ -21,20 +21,20 @@ class SharedPreferencesAppFontStore implements AppFontStore {
const SharedPreferencesAppFontStore();
@override
Future<AppFont> load() async {
Future<String?> load() async {
try {
final preferences = await SharedPreferences.getInstance();
return AppFont.fromId(preferences.getString(appFontKey));
return preferences.getString(appFontKey);
} catch (_) {
return AppFont.system;
return null;
}
}
@override
Future<bool> save(AppFont font) async {
Future<bool> save(String id) async {
try {
final preferences = await SharedPreferences.getInstance();
return await preferences.setString(appFontKey, font.id);
return await preferences.setString(appFontKey, id);
} catch (_) {
return false;
}
@@ -43,18 +43,18 @@ class SharedPreferencesAppFontStore implements AppFontStore {
/// An in-memory store for tests and fixtures.
class MemoryAppFontStore implements AppFontStore {
MemoryAppFontStore([this.font = AppFont.system]);
MemoryAppFontStore([this.id]);
AppFont font;
String? id;
bool failSaves = false;
@override
Future<AppFont> load() async => font;
Future<String?> load() async => id;
@override
Future<bool> save(AppFont font) async {
Future<bool> save(String id) async {
if (failSaves) return false;
this.font = font;
this.id = id;
return true;
}
}
@@ -0,0 +1,141 @@
import '../font_choice.dart';
import 'font_file_info.dart';
/// One file of a [CustomFont]: where its bytes are stored and the weight
/// and style it declares.
class CustomFontFace {
const CustomFontFace({
required this.key,
required this.fileName,
required this.weight,
required this.italic,
required this.size,
});
/// The bytes' key in the custom font store.
final String key;
/// The name the file had when it was added (shown, never used as a path).
final String fileName;
final int weight;
final bool italic;
final int size;
String get styleName => fontStyleName(weight, italic: italic);
Map<String, Object> toJson() => <String, Object>{
'key': key,
'file': fileName,
'weight': weight,
'italic': italic,
'size': size,
};
static CustomFontFace? fromJson(Object? json) {
if (json is! Map) return null;
final key = json['key'];
final file = json['file'];
final weight = json['weight'];
final italic = json['italic'];
final size = json['size'];
if (key is! String || key.isEmpty || file is! String) return null;
if (weight is! int || italic is! bool || size is! int) return null;
return CustomFontFace(
key: key,
fileName: file,
weight: weight,
italic: italic,
size: size,
);
}
}
/// A family the user added from their own font files. Its registered
/// [family] is derived from the stable [id], so a rename changes only the
/// [label] and never re-registers the files.
class CustomFont implements FontChoice {
const CustomFont({required this.id, required this.name, required this.faces});
static const String idPrefix = 'custom-';
@override
final String id;
/// The user's name for the family.
final String name;
/// At least one face, in the order they were added.
final List<CustomFontFace> faces;
@override
String get label => name;
@override
String get family => 'Pipelines $id';
@override
List<String> get sources => <String>[
for (final face in faces) customFontSource(face.key),
];
/// The upright face nearest to 400, else the face nearest to 400.
@override
String? get previewSource {
CustomFontFace? best;
int score(CustomFontFace face) =>
(face.weight - 400).abs() + (face.italic ? 2000 : 0);
for (final face in faces) {
if (best == null || score(face) < score(best)) best = face;
}
return best == null ? null : customFontSource(best.key);
}
/// The styles it has, lightest first: "Regular, Bold".
String get styles {
final sorted = [...faces]
..sort(
(a, b) => a.weight != b.weight
? a.weight.compareTo(b.weight)
: (a.italic ? 1 : 0).compareTo(b.italic ? 1 : 0),
);
return sorted.map((face) => face.styleName).join(', ');
}
int get size => faces.fold(0, (total, face) => total + face.size);
CustomFont renamed(String name) =>
CustomFont(id: id, name: name, faces: faces);
Map<String, Object> toJson() => <String, Object>{
'id': id,
'name': name,
'faces': <Object>[for (final face in faces) face.toJson()],
};
/// A stored entry, or null when it is not one this version can use.
static CustomFont? fromJson(Object? json) {
if (json is! Map) return null;
final id = json['id'];
final name = json['name'];
final faces = json['faces'];
if (id is! String || !id.startsWith(idPrefix) || name is! String) {
return null;
}
if (faces is! List) return null;
final parsed = <CustomFontFace>[];
for (final face in faces) {
final value = CustomFontFace.fromJson(face);
if (value == null) return null;
parsed.add(value);
}
if (parsed.isEmpty || name.trim().isEmpty) return null;
return CustomFont(id: id, name: name, faces: parsed);
}
/// The same option whatever its current name.
@override
bool operator ==(Object other) => other is CustomFont && other.id == id;
@override
int get hashCode => id.hashCode;
}
@@ -0,0 +1,144 @@
import 'dart:typed_data';
import 'font_file_info.dart';
/// One file the user picked, with the bytes the picker read.
class PickedFontFile {
const PickedFontFile({required this.name, required this.bytes});
final String name;
final Uint8List bytes;
}
/// Why picked files cannot be added; [message] is shown as is.
class CustomFontRejected implements Exception {
const CustomFontRejected(this.message);
final String message;
@override
String toString() => message;
}
/// The limits that keep added fonts within what a device and a browser's
/// storage hold comfortably.
abstract final class CustomFontLimits {
static const int maxFileBytes = 10 * 1024 * 1024;
static const int maxTotalBytes = 40 * 1024 * 1024;
static const int maxFilesPerFamily = 16;
static const int maxNameLength = 64;
static const List<String> extensions = <String>['ttf', 'otf'];
/// Why [name] cannot name a font, or null when it can.
static String? nameProblem(String name) {
final trimmed = name.trim();
if (trimmed.isEmpty) return 'Enter a name.';
if (trimmed.length > maxNameLength) {
return 'Use at most $maxNameLength characters.';
}
return null;
}
}
/// A face that passed inspection but is not stored yet.
class DraftFontFace {
const DraftFontFace({
required this.fileName,
required this.bytes,
required this.info,
});
final String fileName;
final Uint8List bytes;
final FontFileInfo info;
String get styleName => fontStyleName(info.weight, italic: info.italic);
}
/// Picked files grouped into one family, ready for the user to name.
class CustomFontDraft {
const CustomFontDraft({required this.suggestedName, required this.faces});
/// The family the files name most often, else the first file's name
/// without its extension.
final String suggestedName;
final List<DraftFontFace> faces;
int get size => faces.fold(0, (total, face) => total + face.bytes.length);
/// Checks [files] and reads their names and weights. [storedBytes] is what
/// added fonts already occupy. Throws [CustomFontRejected] naming the
/// first problem; nothing is stored either way.
static CustomFontDraft inspect(
List<PickedFontFile> files, {
int storedBytes = 0,
}) {
if (files.isEmpty) throw const CustomFontRejected('No font file chosen.');
if (files.length > CustomFontLimits.maxFilesPerFamily) {
throw const CustomFontRejected(
'Choose at most ${CustomFontLimits.maxFilesPerFamily} files at once.',
);
}
final faces = <DraftFontFace>[];
for (final file in files) {
final name = file.name;
final dot = name.lastIndexOf('.');
final extension = dot < 0 ? '' : name.substring(dot + 1).toLowerCase();
if (!CustomFontLimits.extensions.contains(extension)) {
throw CustomFontRejected('“$name” is not a .ttf or .otf font file.');
}
if (file.bytes.length > CustomFontLimits.maxFileBytes) {
throw CustomFontRejected(
'“$name” is larger than ${_mb(CustomFontLimits.maxFileBytes)}.',
);
}
final FontFileInfo info;
try {
info = FontFileInfo.parse(file.bytes);
} on FormatException catch (error) {
throw CustomFontRejected('“$name” cannot be used: ${error.message}');
}
final face = DraftFontFace(fileName: name, bytes: file.bytes, info: info);
final twin = faces.where(
(f) => f.info.weight == info.weight && f.info.italic == info.italic,
);
if (twin.isNotEmpty) {
throw CustomFontRejected(
'“${twin.first.fileName}” and “$name” are both ${face.styleName}; '
'add them as separate fonts.',
);
}
faces.add(face);
}
final draft = CustomFontDraft(
suggestedName: _suggestName(faces),
faces: faces,
);
if (storedBytes + draft.size > CustomFontLimits.maxTotalBytes) {
throw CustomFontRejected(
'Added fonts can use up to ${_mb(CustomFontLimits.maxTotalBytes)} '
'on this device; remove one first.',
);
}
return draft;
}
static String _suggestName(List<DraftFontFace> faces) {
final counts = <String, int>{};
for (final face in faces) {
final family = face.info.family;
if (family != null) counts[family] = (counts[family] ?? 0) + 1;
}
if (counts.isNotEmpty) {
return counts.entries.reduce((a, b) => b.value > a.value ? b : a).key;
}
final name = faces.first.fileName;
final dot = name.lastIndexOf('.');
final stem = (dot > 0 ? name.substring(0, dot) : name).trim();
return stem.length > CustomFontLimits.maxNameLength
? stem.substring(0, CustomFontLimits.maxNameLength)
: stem;
}
static String _mb(int bytes) => '${bytes ~/ (1024 * 1024)} MB';
}
@@ -0,0 +1,148 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:shared_preferences/shared_preferences.dart';
import 'custom_font.dart';
import 'custom_font_draft.dart';
import 'font_bytes_store.dart';
/// The index of added fonts, in this device's preferences beside the font
/// choice. It is small (names, weights, keys); the bytes live in a
/// [FontBytesStore].
const String customFontsKey = 'pipelines.next.custom-fonts.v1';
/// The fonts the user added on this device: an index in preferences and
/// the files' bytes in [FontBytesStore].
///
/// Bytes are written before the index names them and the index drops an
/// entry before its bytes are deleted, so the index never names a file that
/// was not completely stored.
class CustomFontLibrary {
CustomFontLibrary({FontBytesStore? bytes, DateTime Function()? clock})
: _bytesStore = bytes,
_clock = clock ?? DateTime.now;
FontBytesStore? _bytesStore;
final DateTime Function() _clock;
List<CustomFont> _fonts = const <CustomFont>[];
FontBytesStore get _bytes => _bytesStore ??= hostFontBytesStore();
/// The added fonts, in the order they were added.
List<CustomFont> get fonts => _fonts;
/// What the added fonts occupy, for [CustomFontDraft.inspect].
int get storedBytes => _fonts.fold(0, (total, font) => total + font.size);
/// Reads the index. An unreadable index or entry is skipped, not fatal.
Future<List<CustomFont>> load() async {
try {
final preferences = await SharedPreferences.getInstance();
final raw = preferences.getString(customFontsKey);
final decoded = raw == null ? null : jsonDecode(raw);
_fonts = <CustomFont>[
if (decoded is List)
for (final entry in decoded) ?CustomFont.fromJson(entry),
];
} catch (_) {
_fonts = const <CustomFont>[];
}
return _fonts;
}
/// The bytes of the face stored under [key].
Future<Uint8List> read(String key) => _bytes.read(key);
/// The entry [draft] would become under [name], with a fresh id and keys;
/// nothing is stored until [store].
CustomFont prepare(CustomFontDraft draft, String name) {
final id = _newId();
return CustomFont(
id: id,
name: name,
faces: <CustomFontFace>[
for (final (index, face) in draft.faces.indexed)
CustomFontFace(
key: '$id-$index',
fileName: face.fileName,
weight: face.info.weight,
italic: face.info.italic,
size: face.bytes.length,
),
],
);
}
/// Stores [font] (from [prepare]) with [draft]'s bytes. Throws
/// [CustomFontRejected] when the files or the index cannot be stored;
/// nothing is left behind.
Future<CustomFont> store(CustomFont font, CustomFontDraft draft) async {
final written = <String>[];
try {
for (final (index, face) in font.faces.indexed) {
await _bytes.write(face.key, draft.faces[index].bytes);
written.add(face.key);
}
await _saveIndex(<CustomFont>[..._fonts, font]);
return font;
} catch (error) {
for (final key in written) {
await _quietly(() => _bytes.delete(key));
}
if (error is CustomFontRejected) rethrow;
throw const CustomFontRejected(
'The font could not be stored on this device.',
);
}
}
/// Renames [font]; returns the renamed entry.
Future<CustomFont> rename(CustomFont font, String name) async {
final renamed = font.renamed(name);
await _saveIndex(<CustomFont>[
for (final f in _fonts) f == font ? renamed : f,
]);
return renamed;
}
/// Forgets [font] and deletes its files.
Future<void> remove(CustomFont font) async {
await _saveIndex(<CustomFont>[
for (final f in _fonts)
if (f != font) f,
]);
for (final face in font.faces) {
await _quietly(() => _bytes.delete(face.key));
}
}
Future<void> _saveIndex(List<CustomFont> fonts) async {
final preferences = await SharedPreferences.getInstance();
final saved = await preferences.setString(
customFontsKey,
jsonEncode(<Object>[for (final font in fonts) font.toJson()]),
);
if (!saved) {
throw const CustomFontRejected(
'The font list could not be saved on this device.',
);
}
_fonts = List<CustomFont>.unmodifiable(fonts);
}
String _newId() {
var stamp = _clock().microsecondsSinceEpoch;
String id() => '${CustomFont.idPrefix}${stamp.toRadixString(36)}';
while (_fonts.any((font) => font.id == id())) {
stamp += 1;
}
return id();
}
static Future<void> _quietly(Future<void> Function() action) async {
try {
await action();
} catch (_) {}
}
}
@@ -0,0 +1,45 @@
import 'dart:typed_data';
import 'font_bytes_store_stub.dart'
if (dart.library.js_interop) 'font_bytes_store_web.dart'
if (dart.library.io) 'font_bytes_store_io.dart'
as platform;
/// Where the bytes of user-added font files live on this device. The index
/// that names them is kept separately (`CustomFontLibrary`).
///
/// Native hosts keep one file per face in the app's support directory; the
/// web keeps them in IndexedDB, because `localStorage` (where
/// `shared_preferences` stores everything on the web) holds only about
/// 5 MB of UTF-16 text per origin, shared with every other preference.
abstract interface class FontBytesStore {
Future<void> write(String key, Uint8List bytes);
/// The stored bytes; throws when [key] is missing or unreadable.
Future<Uint8List> read(String key);
/// Removes [key]; a missing key is not an error.
Future<void> delete(String key);
}
/// The running host's store.
FontBytesStore hostFontBytesStore() => platform.hostFontBytesStore();
/// An in-memory store for tests and fixtures.
class MemoryFontBytesStore implements FontBytesStore {
final Map<String, Uint8List> files = <String, Uint8List>{};
bool failWrites = false;
@override
Future<void> write(String key, Uint8List bytes) async {
if (failWrites) throw StateError('write refused');
files[key] = Uint8List.fromList(bytes);
}
@override
Future<Uint8List> read(String key) async =>
files[key] ?? (throw StateError('no stored font $key'));
@override
Future<void> delete(String key) async => files.remove(key);
}
@@ -0,0 +1,50 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
import 'font_bytes_store.dart';
FontBytesStore hostFontBytesStore() => DirectoryFontBytesStore(
() async => Directory(
'${(await getApplicationSupportDirectory()).path}'
'${Platform.pathSeparator}custom-fonts',
),
);
/// One file per key in a private directory. The app support directory is
/// used rather than Documents: it is not shown in the iOS Files app and is
/// removed with the app.
class DirectoryFontBytesStore implements FontBytesStore {
DirectoryFontBytesStore(this._directory);
final Future<Directory> Function() _directory;
static final RegExp _safeKey = RegExp(r'^[A-Za-z0-9_-]+$');
Future<File> _file(String key) async {
// Keys are generated by the library; refuse anything path-like.
if (!_safeKey.hasMatch(key)) throw ArgumentError.value(key, 'key');
final directory = await _directory();
return File('${directory.path}${Platform.pathSeparator}$key');
}
@override
Future<void> write(String key, Uint8List bytes) async {
final file = await _file(key);
await file.parent.create(recursive: true);
// Write beside, then rename, so a failed write never leaves half a file.
final partial = File('${file.path}.partial');
await partial.writeAsBytes(bytes, flush: true);
await partial.rename(file.path);
}
@override
Future<Uint8List> read(String key) async => (await _file(key)).readAsBytes();
@override
Future<void> delete(String key) async {
final file = await _file(key);
if (await file.exists()) await file.delete();
}
}
@@ -0,0 +1,5 @@
import 'font_bytes_store.dart';
/// A host with neither files nor IndexedDB cannot keep added fonts.
FontBytesStore hostFontBytesStore() =>
throw UnsupportedError('Added fonts need file or IndexedDB storage.');
@@ -0,0 +1,105 @@
import 'dart:async';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:web/web.dart' as web;
import 'font_bytes_store.dart';
FontBytesStore hostFontBytesStore() => IndexedDbFontBytesStore();
/// Font bytes in this origin's IndexedDB, one record per key.
///
/// IndexedDB stores binary values directly (no base64) and its quota is a
/// share of the disk, not localStorage's ~5 MB; it also works on a plain
/// `http://` LAN address, where Cache Storage is unavailable. Each write
/// asks the browser to keep the origin's storage persistent, so a browser
/// under disk pressure does not evict the fonts silently; if it still does,
/// the font fails to load and the picker says so.
class IndexedDbFontBytesStore implements FontBytesStore {
IndexedDbFontBytesStore({this.database = 'pipelines-custom-fonts'});
final String database;
static const String _store = 'fonts';
Future<web.IDBDatabase>? _opening;
Future<web.IDBDatabase> _open() => _opening ??= () {
final request = web.window.indexedDB.open(database, 1);
request.onupgradeneeded = ((web.Event _) {
final db = request.result! as web.IDBDatabase;
if (!db.objectStoreNames.contains(_store)) db.createObjectStore(_store);
}).toJS;
return _settle<web.IDBDatabase>(request).catchError((Object error) {
_opening = null;
throw error;
});
}();
Future<T> _settle<T extends JSAny?>(web.IDBRequest request) {
final done = Completer<T>();
request.onsuccess = ((web.Event _) => done.complete(
request.result as T,
)).toJS;
request.onerror = ((web.Event _) => done.completeError(
StateError(request.error?.message ?? 'IndexedDB request failed'),
)).toJS;
return done.future;
}
Future<void> _commit(web.IDBTransaction transaction) {
final done = Completer<void>();
transaction.oncomplete = ((web.Event _) => done.complete()).toJS;
void fail(web.Event _) {
if (done.isCompleted) return;
done.completeError(
StateError(transaction.error?.message ?? 'IndexedDB write failed'),
);
}
transaction.onerror = fail.toJS;
transaction.onabort = fail.toJS;
return done.future;
}
@override
Future<void> write(String key, Uint8List bytes) async {
final db = await _open();
final transaction = db.transaction(_store.toJS, 'readwrite');
final committed = _commit(transaction);
transaction.objectStore(_store).put(bytes.toJS, key.toJS);
await committed;
unawaited(_persist());
}
@override
Future<Uint8List> read(String key) async {
final db = await _open();
final request = db
.transaction(_store.toJS, 'readonly')
.objectStore(_store)
.get(key.toJS);
final value = await _settle<JSAny?>(request);
if (value == null || !value.isA<JSUint8Array>()) {
throw StateError('No stored font $key');
}
return (value as JSUint8Array).toDart;
}
@override
Future<void> delete(String key) async {
final db = await _open();
final transaction = db.transaction(_store.toJS, 'readwrite');
final committed = _commit(transaction);
transaction.objectStore(_store).delete(key.toJS);
await committed;
}
/// Best effort: some browsers grant it silently, others only for
/// installed or bookmarked sites. A refusal changes nothing.
Future<void> _persist() async {
try {
await web.window.navigator.storage.persist().toDart;
} catch (_) {}
}
}
@@ -0,0 +1,183 @@
import 'dart:typed_data';
/// What a TrueType or OpenType file says about itself: enough to name the
/// family it belongs to and to tell its weights apart.
///
/// [FontFileInfo.parse] is a small, bounded reader of the sfnt table
/// directory, the `name` table and the `OS/2` table. Every offset is checked
/// against the file before it is read, so a damaged or hostile file fails
/// with a [FormatException], never a range error or a long loop.
class FontFileInfo {
const FontFileInfo({
required this.family,
required this.subfamily,
required this.weight,
required this.italic,
});
/// The typographic family (name ID 16), else the legacy family (ID 1);
/// null when the file names neither readably.
final String? family;
/// The style name (ID 17, else ID 2), e.g. "Bold Italic"; may be null.
final String? subfamily;
/// `OS/2.usWeightClass` (1–1000), 400 when the table is absent or odd.
final int weight;
/// `OS/2.fsSelection` bit 0, else a subfamily naming italic or oblique.
final bool italic;
static const int _maxTables = 512;
static const int _maxNameRecords = 4096;
static const int _maxNameLength = 64;
/// Reads [bytes]. Throws [FormatException] with a user-facing message
/// when they are not a single TrueType/OpenType font.
static FontFileInfo parse(Uint8List bytes) {
final data = ByteData.sublistView(bytes);
if (bytes.length < 12) {
throw const FormatException('The file is too short.');
}
final version = data.getUint32(0);
switch (version) {
case 0x00010000 || 0x4F54544F || 0x74727565: // 1.0, 'OTTO', 'true'
break;
case 0x74746366: // 'ttcf'
throw const FormatException(
'Font collections (.ttc) are not supported; add single fonts.',
);
case 0x774F4646 || 0x774F4632: // 'wOFF', 'wOF2'
throw const FormatException('WOFF web fonts are not supported.');
default:
throw const FormatException('Not a TrueType or OpenType font.');
}
final count = data.getUint16(4);
if (count == 0 || count > _maxTables || 12 + count * 16 > bytes.length) {
throw const FormatException('The font table directory is damaged.');
}
final tables = <String, (int, int)>{};
for (var i = 0; i < count; i++) {
final record = 12 + i * 16;
final tag = String.fromCharCodes(bytes, record, record + 4);
final offset = data.getUint32(record + 8);
final length = data.getUint32(record + 12);
if (offset + length > bytes.length) {
throw const FormatException('A font table lies outside the file.');
}
tables[tag] = (offset, length);
}
final outlines =
(tables.containsKey('glyf') && tables.containsKey('loca')) ||
tables.containsKey('CFF ') ||
tables.containsKey('CFF2');
if (!tables.containsKey('cmap') ||
!tables.containsKey('head') ||
!outlines) {
throw const FormatException('The font is missing required tables.');
}
final names = _names(data, tables['name']);
final subfamily = names[17] ?? names[2];
final os2 = tables['OS/2'];
var weight = 400;
bool? italic;
if (os2 != null && os2.$2 >= 6) {
final value = data.getUint16(os2.$1 + 4);
if (value >= 1 && value <= 1000) weight = value;
if (os2.$2 >= 64) italic = data.getUint16(os2.$1 + 62) & 1 == 1;
}
italic ??= RegExp(
'italic|oblique',
caseSensitive: false,
).hasMatch(subfamily ?? '');
return FontFileInfo(
family: names[16] ?? names[1],
subfamily: subfamily,
weight: weight,
italic: italic,
);
}
/// Name IDs 1, 2, 16 and 17, each from the best record: Windows English,
/// then any Windows, then Unicode, then Mac Roman.
static Map<int, String> _names(ByteData data, (int, int)? table) {
final found = <int, (int, String)>{};
if (table == null || table.$2 < 6) return const <int, String>{};
final (start, length) = table;
final end = start + length;
final count = data.getUint16(start + 2);
final strings = start + data.getUint16(start + 4);
if (count > _maxNameRecords || start + 6 + count * 12 > end) {
return const <int, String>{};
}
for (var i = 0; i < count; i++) {
final record = start + 6 + i * 12;
final platform = data.getUint16(record);
final encoding = data.getUint16(record + 2);
final language = data.getUint16(record + 4);
final id = data.getUint16(record + 6);
if (id != 1 && id != 2 && id != 16 && id != 17) continue;
final rank = switch (platform) {
3 when encoding == 1 || encoding == 10 => language == 0x409 ? 4 : 3,
0 => 2,
1 when encoding == 0 && language == 0 => 1,
_ => 0,
};
if (rank == 0 || (found[id]?.$1 ?? 0) >= rank) continue;
final size = data.getUint16(record + 8);
final offset = strings + data.getUint16(record + 10);
if (offset + size > end || size > _maxNameLength * 4) continue;
final text = _clean(
platform == 1
? _macRoman(data, offset, size)
: _utf16(data, offset, size),
);
if (text.isNotEmpty) found[id] = (rank, text);
}
return <int, String>{
for (final entry in found.entries) entry.key: entry.value.$2,
};
}
static String _utf16(ByteData data, int offset, int size) =>
String.fromCharCodes(<int>[
for (var i = 0; i + 1 < size; i += 2) data.getUint16(offset + i),
]);
/// ASCII from Mac Roman; the rare accented byte becomes a space.
static String _macRoman(ByteData data, int offset, int size) =>
String.fromCharCodes(<int>[
for (var i = 0; i < size; i++)
data.getUint8(offset + i) < 0x80 ? data.getUint8(offset + i) : 0x20,
]);
/// Drops control characters, collapses runs of space and caps the length.
static String _clean(String raw) {
final text = raw
.replaceAll(RegExp(r'[\x00-\x1F\x7F�]'), '')
.replaceAll(RegExp(r'\s+'), ' ')
.trim();
return text.length > _maxNameLength
? text.substring(0, _maxNameLength).trim()
: text;
}
}
/// The conventional name of an OpenType weight class, plus "Italic".
String fontStyleName(int weight, {bool italic = false}) {
const names = <String>[
'Thin',
'ExtraLight',
'Light',
'Regular',
'Medium',
'SemiBold',
'Bold',
'ExtraBold',
'Black',
];
final index = ((weight.clamp(100, 900) + 50) ~/ 100) - 1;
final name = names[index.clamp(0, names.length - 1)];
if (!italic) return name;
return name == 'Regular' ? 'Italic' : '$name Italic';
}
@@ -0,0 +1,34 @@
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'custom_font_draft.dart';
/// Opens the host's file picker for font files; null when the user cancels.
/// Throws [CustomFontRejected] for a file too large to read.
typedef FontFilePicker = Future<List<PickedFontFile>?> Function();
/// The host picker through `file_picker`. The web and Apple pickers filter
/// to .ttf/.otf; Android's document picker filters by MIME type, which many
/// providers do not report for fonts, so there every file is offered and
/// [CustomFontDraft.inspect] rejects the rest by name.
Future<List<PickedFontFile>?> pickFontFiles() async {
final android = !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
final picked = await FilePicker.pickFiles(
type: android ? FileType.any : FileType.custom,
allowedExtensions: android ? null : CustomFontLimits.extensions,
);
if (picked.isEmpty) return null;
final files = <PickedFontFile>[];
for (final file in picked) {
final length = file.lengthSync() ?? await file.length();
if (length != null && length > CustomFontLimits.maxFileBytes) {
// Refuse before reading a huge file into memory.
throw CustomFontRejected(
'“${file.name}” is larger than '
'${CustomFontLimits.maxFileBytes ~/ (1024 * 1024)} MB.',
);
}
files.add(PickedFontFile(name: file.name, bytes: await file.readAsBytes()));
}
return files;
}
+25
View File
@@ -0,0 +1,25 @@
/// One interface font option the device can choose: a bundled family
/// (`AppFont`) or one the user added (`CustomFont`).
abstract interface class FontChoice {
/// The stored value; stable across releases and renames.
String get id;
/// The picker's name for the option.
String get label;
/// The registered family name; null keeps the platform typography.
String? get family;
/// Every file the family needs, as loader sources: bundle asset paths, or
/// [customFontSource] keys for files the user added.
List<String> get sources;
/// The one source that previews the option's name (its regular weight).
String? get previewSource;
}
/// Loader sources naming a user-added file start with this prefix; the rest
/// is the file's key in the custom font store.
const String customFontSourcePrefix = 'custom-font:';
String customFontSource(String key) => '$customFontSourcePrefix$key';
+76
View File
@@ -42,3 +42,79 @@ same compressed amount (not measured).
RobotoMono; they now follow the chosen font too.
- On the web Cupertino fixture, "System default" names an unregistered
`CupertinoSystemText` family, which the browser engine substitutes.
## Fonts the user adds
Settings > Font ends with **Add font…**. It opens the host picker
(`file_picker`; .ttf/.otf filter on the web and Apple hosts, every file on
Android, whose document picker filters by MIME type), then:
1. `CustomFontDraft.inspect` refuses other extensions, files over 10 MB,
more than 16 files at once, two files of the same weight and style, and a
total over 40 MB of added fonts. Each file is read by
`custom_fonts/font_file_info.dart`, a bounded pure-Dart sfnt reader: it
rejects TTC collections, WOFF, damaged table directories and fonts
without `cmap`/`head`/outlines, reads the family from the `name` table
(ID 16, else ID 1; Windows English first) and the weight from
`OS/2.usWeightClass` (400 when absent) plus the italic bit.
2. A name dialog is prefilled from the font's family (else the file name)
and lists each file's style; the user can rename it there or later.
3. `AppFontController.addCustom` registers the bytes with a `FontLoader`
under the new family first; only if that succeeds are the bytes and the
index stored, and the font is chosen. A failure stores nothing. (The
engine ignores undecodable bytes rather than throwing, so the structural
check in step 1 is the real gate; the loader catches the rest.)
Rows for added fonts sit below the bundled ones, named in their own face,
with their styles ("Regular, Bold") and an options button (Rename, Remove)
beside the row, outside the tile's merged semantics. Remove asks first and
deletes the files; if the font was chosen, the device returns to System
default. The engine keeps a removed family registered until the next start,
but nothing uses it.
The choice key is unchanged (`pipelines.next.font.v1` now holds either a
bundled id or `custom-<id>`). A stored added font loads at startup within
the same bounded wait; missing bytes keep the system face and the picker
says "Could not load this font."
### Storage
- Index: `shared_preferences` key `pipelines.next.custom-fonts.v1`, JSON of
names, weights and byte keys (a few hundred bytes per font).
- Native bytes: one file per face under the app support directory
(`custom-fonts/<key>`), written to a `.partial` file and renamed. Support,
not Documents: it is private (not in the iOS Files app) and leaves with
the app.
- Web bytes: IndexedDB database `pipelines-custom-fonts` via `package:web`.
`localStorage` (which `shared_preferences` uses on the web) was rejected:
browsers cap it at about 5 MB of UTF-16 text per origin, shared with every
other preference, and base64 inflates a four-weight family to 1–2 MB, so a
15 MB cap could never be honoured and an overflow would break other
settings. Cache Storage needs a secure context, which a plain `http://`
LAN address is not. IndexedDB stores binary values directly with a
disk-sized quota; each write asks `navigator.storage.persist()` so the
browser keeps the fonts under disk pressure (best effort).
- Bytes are written before the index names them, and the index forgets a
font before its bytes are deleted, so the index never names a partial
font.
### Evidence
Tests: `test/ui/theme/custom_fonts/` (parser on the bundled fonts and
damaged/hostile inputs; draft limits; library round trip with an in-memory
byte store; native directory store on a temp dir; controller add, reject,
rename, remove, restore, missing bytes, real `FontLoader`) and
`test/features/settings/settings_custom_font_test.dart` (Material and
Cupertino add/rename/remove, invalid file, cancel). The IndexedDB store has
no VM test (it needs a browser); the browser run below covers it.
Browser (`tool/capture/`, new `files=` step answering the file chooser):
the fixture app at 880x1400, Material and Cupertino, adding the bundled
Atkinson Hyperlegible Next Regular and Bold as a user font named
"My Atkinson". Shots: the name dialog prefilled "Atkinson Hyperlegible
Next" with both styles; the added row chosen and the app redrawn in it; the
same after a page reload (restored from IndexedDB); run 7 in the added
face; the options menu and action sheet; rename to "Body face"; the remove
confirmation; the fallback to System default; and a fake `.ttf` refused
with "“fake.ttf” cannot be used: The file is too short." Android and iOS
were not run on a device.
@@ -0,0 +1,201 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_custom_font_actions.dart';
import 'package:pipelines_app/features/settings/settings_custom_font_dialogs.dart';
import 'package:pipelines_app/features/settings/settings_font_section.dart';
import 'package:pipelines_app/ui/theme/app_font.dart';
import 'package:pipelines_app/ui/theme/app_font_controller.dart';
import 'package:pipelines_app/ui/theme/app_font_store.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_draft.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_library.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_bytes_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
PickedFontFile _pick(String path) => PickedFontFile(
name: path.split('/').last,
bytes: File(path).readAsBytesSync(),
);
class _Harness {
final store = MemoryAppFontStore();
final bytes = MemoryFontBytesStore();
List<PickedFontFile>? next;
late final fonts = AppFontController(
store: store,
library: CustomFontLibrary(bytes: bytes),
loader: (family, sources) async {},
bytesLoader: (family, faces) async {},
);
Future<List<PickedFontFile>?> pick() async => next;
}
Future<void> _pump(
WidgetTester tester,
_Harness harness, {
bool cupertino = false,
}) async {
final section = SingleChildScrollView(
child: SettingsFontSection(
controller: harness.fonts,
pickFiles: harness.pick,
),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: section))
: MaterialApp(home: Scaffold(body: section)),
);
await tester.pumpAndSettle();
}
void main() {
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
final regular = _pick('fonts/inter/Inter-Regular.ttf');
final bold = _pick('fonts/inter/Inter-Bold.ttf');
testWidgets('Material: add, name, rename and remove an added font', (
tester,
) async {
final harness = _Harness()..next = <PickedFontFile>[regular, bold];
await _pump(tester, harness);
await tester.tap(find.text(addCustomFontText));
await tester.pumpAndSettle();
// The family name comes from the font; the files are listed.
expect(find.text(addCustomFontTitle), findsOneWidget);
expect(
find.text('Regular · Inter-Regular.ttf\nBold · Inter-Bold.ttf'),
findsOneWidget,
);
final field = find.byType(TextField);
expect(tester.widget<TextField>(field).controller!.text, 'Inter');
await tester.enterText(field, 'My Inter');
await tester.tap(find.text('Add'));
await tester.pumpAndSettle();
final font = harness.fonts.customFonts.single;
expect(font.name, 'My Inter');
expect(harness.store.id, font.id, reason: 'a new font is chosen');
final row = find.byKey(settingsFontKey(font));
expect(row, findsOneWidget);
// Below the bundled options, named in its own face.
expect(
tester.getTopLeft(row).dy,
greaterThan(
tester.getTopLeft(find.byKey(settingsFontKey(AppFont.values.last))).dy,
),
);
final name = tester.widget<Text>(
find.descendant(of: row, matching: find.text('My Inter')),
);
expect(name.style?.fontFamily, font.family);
expect(
find.descendant(of: row, matching: find.text('Regular, Bold')),
findsOneWidget,
);
// Its own control, not merged into the radio tile.
final options = tester.getSemantics(
find.byTooltip(customFontActionsTooltip),
);
expect(options.tooltip, customFontActionsTooltip);
expect(options.label, isNot(contains('My Inter')));
expect(find.bySemanticsLabel(addCustomFontText), findsOneWidget);
await tester.tap(find.byTooltip(customFontActionsTooltip));
await tester.pumpAndSettle();
await tester.tap(find.text(renameCustomFontText));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'Body');
await tester.tap(find.widgetWithText(TextButton, renameCustomFontText));
await tester.pumpAndSettle();
expect(find.text('Body'), findsOneWidget);
expect(harness.fonts.selected.label, 'Body');
await tester.tap(find.byTooltip(customFontActionsTooltip));
await tester.pumpAndSettle();
await tester.tap(find.text(removeCustomFontText));
await tester.pumpAndSettle();
expect(find.text('Remove Body?'), findsOneWidget);
await tester.tap(find.widgetWithText(TextButton, 'Remove'));
await tester.pumpAndSettle();
expect(find.text('Body'), findsNothing);
expect(harness.fonts.selected, AppFont.system);
expect(harness.store.id, AppFont.system.id);
expect(harness.bytes.files, isEmpty);
});
testWidgets('an invalid file is refused with a message, nothing stored', (
tester,
) async {
final harness = _Harness()
..next = <PickedFontFile>[
PickedFontFile(name: 'fake.ttf', bytes: utf8.encode('not a font')),
];
await _pump(tester, harness);
await tester.tap(find.text(addCustomFontText));
await tester.pumpAndSettle();
expect(find.text(addCustomFontFailedTitle), findsOneWidget);
expect(find.textContaining('“fake.ttf” cannot be used'), findsOneWidget);
expect(find.text(addCustomFontTitle), findsNothing);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
expect(harness.fonts.customFonts, isEmpty);
expect(harness.bytes.files, isEmpty);
});
testWidgets('a cancelled pick or name dialog adds nothing', (tester) async {
final harness = _Harness();
await _pump(tester, harness);
await tester.tap(find.text(addCustomFontText));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
harness.next = <PickedFontFile>[regular];
await tester.tap(find.text(addCustomFontText));
await tester.pumpAndSettle();
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(harness.fonts.customFonts, isEmpty);
});
testWidgets('Cupertino: an added font has the checkmark and options', (
tester,
) async {
final harness = _Harness()..next = <PickedFontFile>[regular];
await _pump(tester, harness, cupertino: true);
await tester.tap(find.text(addCustomFontText));
await tester.pumpAndSettle();
await tester.tap(find.text('Add'));
await tester.pumpAndSettle();
final CustomFont font = harness.fonts.customFonts.single;
final row = find.byKey(settingsFontKey(font));
expect(
find.descendant(
of: row,
matching: find.byIcon(CupertinoIcons.check_mark),
),
findsOneWidget,
);
// The options button is its own control beside the row.
expect(find.bySemanticsLabel(customFontActionsTooltip), findsOneWidget);
await tester.tap(find.byIcon(CupertinoIcons.ellipsis_circle));
await tester.pumpAndSettle();
await tester.tap(find.text(removeCustomFontText));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(CupertinoDialogAction, 'Remove'));
await tester.pumpAndSettle();
expect(harness.fonts.customFonts, isEmpty);
expect(harness.fonts.selected, AppFont.system);
});
}
@@ -7,6 +7,7 @@ import 'package:pipelines_app/features/settings/settings_font_section.dart';
import 'package:pipelines_app/ui/theme/app_font.dart';
import 'package:pipelines_app/ui/theme/app_font_controller.dart';
import 'package:pipelines_app/ui/theme/app_font_store.dart';
import 'package:pipelines_app/ui/theme/font_choice.dart';
class _Harness {
_Harness({this.hold = false});
@@ -71,8 +72,8 @@ void main() {
for (final font in AppFont.values)
if (font.previewAsset != null) font.previewAsset,
]);
final group = tester.widget<RadioGroup<AppFont>>(
find.byType(RadioGroup<AppFont>),
final group = tester.widget<RadioGroup<FontChoice>>(
find.byType(RadioGroup<FontChoice>),
);
expect(group.groupValue, AppFont.system);
});
@@ -85,10 +86,10 @@ void main() {
await tester.tap(find.text('Source Sans 3'));
await tester.pump();
expect(harness.store.font, AppFont.sourceSans3);
expect(harness.store.id, AppFont.sourceSans3.id);
expect(
tester
.widget<RadioGroup<AppFont>>(find.byType(RadioGroup<AppFont>))
.widget<RadioGroup<FontChoice>>(find.byType(RadioGroup<FontChoice>))
.groupValue,
AppFont.sourceSans3,
);
@@ -107,7 +108,7 @@ void main() {
final harness = _Harness();
await _pump(tester, harness, cupertino: true);
expect(find.byType(RadioListTile<AppFont>), findsNothing);
expect(find.byType(RadioListTile<FontChoice>), findsNothing);
expect(_familyOf(tester, AppFont.system), 'CupertinoSystemText');
Finder check(AppFont font) => find.descendant(
of: find.byKey(settingsFontKey(font)),
@@ -119,7 +120,7 @@ void main() {
await tester.pumpAndSettle();
expect(check(AppFont.system), findsNothing);
expect(check(AppFont.inter), findsOneWidget);
expect(harness.store.font, AppFont.inter);
expect(harness.store.id, AppFont.inter.id);
expect(harness.fonts.family, 'Inter');
});
@@ -36,7 +36,7 @@ void main() {
test('restore loads only the stored family, then applies it', () async {
final loads = _Loads()..immediate = false;
final fonts = AppFontController(
store: MemoryAppFontStore(AppFont.inter),
store: MemoryAppFontStore(AppFont.inter.id),
loader: loads.call,
);
final restoring = fonts.restore();
@@ -57,7 +57,7 @@ void main() {
() async {
final loads = _Loads()..immediate = false;
final fonts = AppFontController(
store: MemoryAppFontStore(AppFont.sourceSans3),
store: MemoryAppFontStore(AppFont.sourceSans3.id),
loader: loads.call,
);
await fonts.restore(wait: const Duration(milliseconds: 10));
@@ -75,10 +75,10 @@ void main() {
final loads = _Loads();
final fonts = AppFontController(store: store, loader: loads.call);
await fonts.select(AppFont.atkinsonHyperlegible);
expect(store.font, AppFont.atkinsonHyperlegible);
expect(store.id, AppFont.atkinsonHyperlegible.id);
expect(fonts.family, 'Atkinson Hyperlegible Next');
await fonts.select(AppFont.system);
expect(store.font, AppFont.system);
expect(store.id, AppFont.system.id);
expect(fonts.family, isNull);
expect(loads.calls, hasLength(1));
},
+6 -13
View File
@@ -10,32 +10,25 @@ void main() {
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
test('nothing stored is the system default', () async {
expect(await const SharedPreferencesAppFontStore().load(), AppFont.system);
test('nothing stored reads as no choice', () async {
expect(await const SharedPreferencesAppFontStore().load(), isNull);
});
test(
'a choice round-trips under its stable id, on the device only',
() async {
const store = SharedPreferencesAppFontStore();
expect(await store.save(AppFont.ibmPlexSans), isTrue);
expect(await store.save(AppFont.ibmPlexSans.id), isTrue);
final preferences = await SharedPreferences.getInstance();
expect(preferences.getKeys(), <String>{appFontKey});
expect(preferences.getString(appFontKey), 'ibm-plex-sans');
expect(await store.load(), AppFont.ibmPlexSans);
expect(await store.load(), AppFont.ibmPlexSans.id);
expect(await store.save(AppFont.system), isTrue);
expect(await store.load(), AppFont.system);
expect(await store.save(AppFont.system.id), isTrue);
expect(await store.load(), 'system');
},
);
test('an unknown stored id falls back to the system default', () async {
SharedPreferences.setMockInitialValues(<String, Object>{
appFontKey: 'comic-sans',
});
expect(await const SharedPreferencesAppFontStore().load(), AppFont.system);
});
test('every bundled option has its four weights and its licence', () {
for (final font in AppFont.values) {
if (font == AppFont.system) {
@@ -0,0 +1,160 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/theme/app_font.dart';
import 'package:pipelines_app/ui/theme/app_font_controller.dart';
import 'package:pipelines_app/ui/theme/app_font_store.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_draft.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_library.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_bytes_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
PickedFontFile _pick(String path) => PickedFontFile(
name: path.split('/').last,
bytes: File(path).readAsBytesSync(),
);
class _Device {
_Device({MemoryAppFontStore? store, MemoryFontBytesStore? bytes})
: store = store ?? MemoryAppFontStore(),
bytes = bytes ?? MemoryFontBytesStore();
final MemoryAppFontStore store;
final MemoryFontBytesStore bytes;
final loads = <List<String>>[];
final checked = <String>[];
bool rejectBytes = false;
/// A fresh app start on this device: real index, the given byte store.
late final AppFontController fonts = AppFontController(
store: store,
library: CustomFontLibrary(bytes: bytes),
loader: (family, sources) async => loads.add(sources),
bytesLoader: (family, faces) async {
checked.add(family);
if (rejectBytes) throw StateError('engine refused');
},
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
final regular = _pick('fonts/inter/Inter-Regular.ttf');
final bold = _pick('fonts/inter/Inter-Bold.ttf');
test(
'adding checks the files with the engine, stores and chooses them',
() async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular, bold]);
final font = await device.fonts.addCustom(draft, ' My Inter ');
expect(font.name, 'My Inter');
expect(device.checked, <String>[font.family]);
expect(device.fonts.customFonts, <CustomFont>[font]);
expect(device.fonts.selected, font);
expect(device.fonts.family, font.family);
expect(device.loads, isEmpty, reason: 'already registered by the check');
expect(device.store.id, font.id);
expect(device.bytes.files, hasLength(2));
},
);
test('a font the engine cannot load is rejected and never stored', () async {
final device = _Device()..rejectBytes = true;
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
await expectLater(
device.fonts.addCustom(draft, 'Broken'),
throwsA(isA<CustomFontRejected>()),
);
expect(device.bytes.files, isEmpty);
expect(device.fonts.customFonts, isEmpty);
expect(device.fonts.selected, AppFont.system);
expect(device.store.id, isNull);
});
test('an empty name is refused before anything is stored', () async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
await expectLater(
device.fonts.addCustom(draft, ' '),
throwsA(isA<CustomFontRejected>()),
);
expect(device.checked, isEmpty);
});
test('a stored added font loads at startup from the byte store', () async {
final first = _Device();
final draft = await first.fonts.inspect(<PickedFontFile>[regular, bold]);
final font = await first.fonts.addCustom(draft, 'Mine');
final next = _Device(store: first.store, bytes: first.bytes);
await next.fonts.restore(wait: const Duration(seconds: 1));
expect(next.fonts.selected, font);
expect(next.fonts.family, font.family);
expect(next.loads.single, font.sources);
});
test('a stored id with no font behind it is the system default', () async {
for (final id in <String>['comic-sans', 'custom-gone']) {
final device = _Device(store: MemoryAppFontStore(id));
await device.fonts.restore();
expect(device.fonts.selected, AppFont.system);
expect(device.loads, isEmpty);
}
});
test('missing bytes at startup keep the system face and say so', () async {
final first = _Device();
final draft = await first.fonts.inspect(<PickedFontFile>[regular]);
final font = await first.fonts.addCustom(draft, 'Mine');
first.bytes.files.clear();
final next = AppFontController(
store: first.store,
library: CustomFontLibrary(bytes: first.bytes),
loader: appFontSourceLoader(first.bytes.read),
);
await next.restore();
expect(next.selected, font);
expect(next.loadFailed, font);
expect(next.family, isNull);
});
test('renaming keeps the choice; removing it falls back to system', () async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
final font = await device.fonts.addCustom(draft, 'Mine');
await device.fonts.renameCustom(font, 'Body');
expect(device.fonts.selected.label, 'Body');
expect(device.fonts.family, font.family);
expect(device.store.id, font.id);
await device.fonts.removeCustom(device.fonts.customFonts.single);
expect(device.fonts.customFonts, isEmpty);
expect(device.fonts.selected, AppFont.system);
expect(device.fonts.family, isNull);
expect(device.store.id, AppFont.system.id);
expect(device.bytes.files, isEmpty);
});
test('removing a font that is not chosen keeps the choice', () async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
final font = await device.fonts.addCustom(draft, 'Mine');
await device.fonts.select(AppFont.inter);
await device.fonts.removeCustom(font);
expect(device.fonts.selected, AppFont.inter);
expect(device.store.id, AppFont.inter.id);
});
test('the real FontLoader accepts a bundled file as a user font', () async {
// The engine path production uses; bytes come from a fixture file.
await loadFontBytes('Fixture user font', <Uint8List>[regular.bytes]);
});
}
@@ -0,0 +1,197 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_draft.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_library.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_bytes_store.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_bytes_store_io.dart';
import 'package:pipelines_app/ui/theme/font_choice.dart';
import 'package:shared_preferences/shared_preferences.dart';
PickedFontFile _pick(String path, [String? name]) => PickedFontFile(
name: name ?? path.split('/').last,
bytes: File(path).readAsBytesSync(),
);
final _regular = _pick('fonts/inter/Inter-Regular.ttf');
final _bold = _pick('fonts/inter/Inter-Bold.ttf');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
group('inspect', () {
test('groups files into one family named from the name table', () {
final draft = CustomFontDraft.inspect(<PickedFontFile>[_regular, _bold]);
expect(draft.suggestedName, 'Inter');
expect(draft.faces.map((f) => f.styleName), <String>['Regular', 'Bold']);
});
test('a file without names is named after the file', () {
final copy = Uint8List.fromList(_regular.bytes);
final data = ByteData.sublistView(copy);
for (var i = 0; i < data.getUint16(4); i++) {
final record = 12 + i * 16;
if (String.fromCharCodes(copy, record, record + 4) == 'name') {
copy.setAll(record, 'zzzz'.codeUnits);
}
}
final draft = CustomFontDraft.inspect(<PickedFontFile>[
PickedFontFile(name: 'My Face.OTF', bytes: copy),
]);
expect(draft.suggestedName, 'My Face');
});
test('refuses other files, damaged fonts, twins and oversize', () {
void refuses(List<PickedFontFile> files, String text, {int stored = 0}) =>
expect(
() => CustomFontDraft.inspect(files, storedBytes: stored),
throwsA(
isA<CustomFontRejected>().having(
(e) => e.message,
'message',
contains(text),
),
),
);
refuses(<PickedFontFile>[], 'No font file');
refuses(<PickedFontFile>[
PickedFontFile(name: 'notes.txt', bytes: _regular.bytes),
], 'not a .ttf or .otf');
refuses(<PickedFontFile>[
PickedFontFile(name: 'fake.ttf', bytes: utf8.encode('hello')),
], 'cannot be used');
refuses(<PickedFontFile>[
PickedFontFile(
name: 'huge.ttf',
bytes: Uint8List(CustomFontLimits.maxFileBytes + 1),
),
], 'larger than 10 MB');
refuses(<PickedFontFile>[
_regular,
_pick('fonts/source-sans-3/SourceSans3-Regular.ttf'),
], 'both Regular');
refuses(
<PickedFontFile>[_regular],
'up to 40 MB',
stored: CustomFontLimits.maxTotalBytes - 1000,
);
});
test('names are trimmed, required and bounded', () {
expect(CustomFontLimits.nameProblem(' '), isNotNull);
expect(CustomFontLimits.nameProblem('x' * 65), isNotNull);
expect(CustomFontLimits.nameProblem(' Mine '), isNull);
});
});
group('library', () {
test('round-trips the index and bytes, then removes both', () async {
final bytes = MemoryFontBytesStore();
final library = CustomFontLibrary(bytes: bytes);
await library.load();
final draft = CustomFontDraft.inspect(<PickedFontFile>[_regular, _bold]);
final font = await library.store(library.prepare(draft, 'Mine'), draft);
expect(font.styles, 'Regular, Bold');
expect(font.sources, <String>[
for (final face in font.faces) customFontSource(face.key),
]);
expect(font.previewSource, customFontSource(font.faces.first.key));
expect(bytes.files.keys, font.faces.map((f) => f.key));
final reopened = CustomFontLibrary(bytes: bytes);
final fonts = await reopened.load();
expect(fonts.single.name, 'Mine');
expect(fonts.single.faces.map((f) => f.weight), <int>[400, 700]);
expect(await reopened.read(font.faces.last.key), _bold.bytes);
expect(reopened.storedBytes, draft.size);
final renamed = await reopened.rename(fonts.single, 'Body');
expect(renamed.family, font.family, reason: 'registration is kept');
expect(
(await CustomFontLibrary(bytes: bytes).load()).single.label,
'Body',
);
await reopened.remove(renamed);
expect(bytes.files, isEmpty);
expect(await CustomFontLibrary(bytes: bytes).load(), isEmpty);
});
test('a failed write stores nothing and says so', () async {
final bytes = MemoryFontBytesStore()..failWrites = true;
final library = CustomFontLibrary(bytes: bytes);
final draft = CustomFontDraft.inspect(<PickedFontFile>[_regular]);
await expectLater(
library.store(library.prepare(draft, 'Mine'), draft),
throwsA(isA<CustomFontRejected>()),
);
expect(bytes.files, isEmpty);
expect(await library.load(), isEmpty);
});
test('an unreadable index or entry is skipped', () async {
SharedPreferences.setMockInitialValues(<String, Object>{
customFontsKey: jsonEncode(<Object>[
<String, Object>{'id': 'evil', 'name': 'x', 'faces': <Object>[]},
const CustomFont(
id: 'custom-1',
name: 'Kept',
faces: <CustomFontFace>[
CustomFontFace(
key: 'custom-1-0',
fileName: 'a.ttf',
weight: 400,
italic: false,
size: 3,
),
],
).toJson(),
]),
});
final fonts = await CustomFontLibrary(
bytes: MemoryFontBytesStore(),
).load();
expect(fonts.map((f) => f.name), <String>['Kept']);
SharedPreferences.setMockInitialValues(<String, Object>{
customFontsKey: '{not json',
});
expect(
await CustomFontLibrary(bytes: MemoryFontBytesStore()).load(),
isEmpty,
);
});
});
group('native file store', () {
late Directory temp;
setUp(() => temp = Directory.systemTemp.createTempSync('custom-fonts'));
tearDown(() => temp.deleteSync(recursive: true));
test('writes, reads and deletes one file per key', () async {
final dir = Directory('${temp.path}/custom-fonts');
final store = DirectoryFontBytesStore(() async => dir);
await store.write('custom-1-0', _regular.bytes);
expect(File('${dir.path}/custom-1-0').existsSync(), isTrue);
expect(dir.listSync(), hasLength(1), reason: 'no partial file left');
expect(await store.read('custom-1-0'), _regular.bytes);
await store.delete('custom-1-0');
await store.delete('custom-1-0');
expect(dir.listSync(), isEmpty);
await expectLater(store.read('custom-1-0'), throwsA(anything));
});
test('refuses a key that could name another path', () async {
final store = DirectoryFontBytesStore(() async => temp);
await expectLater(
store.write('../escape', _regular.bytes),
throwsArgumentError,
);
});
});
}
@@ -0,0 +1,103 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_file_info.dart';
Uint8List _font(String path) => File(path).readAsBytesSync();
/// [bytes] with the table directory's [tag] renamed, so the table is gone.
Uint8List _withoutTable(Uint8List bytes, String tag) {
final copy = Uint8List.fromList(bytes);
final data = ByteData.sublistView(copy);
for (var i = 0; i < data.getUint16(4); i++) {
final record = 12 + i * 16;
if (String.fromCharCodes(copy, record, record + 4) == tag) {
copy.setAll(record, 'zzzz'.codeUnits);
}
}
return copy;
}
void main() {
test('reads family, style and weight from the bundled fonts', () {
final regular = FontFileInfo.parse(_font('fonts/inter/Inter-Regular.ttf'));
expect(regular.family, 'Inter');
expect(regular.subfamily, 'Regular');
expect(regular.weight, 400);
expect(regular.italic, isFalse);
final bold = FontFileInfo.parse(_font('fonts/inter/Inter-Bold.ttf'));
expect(bold.family, 'Inter');
expect(bold.weight, 700);
final semibold = FontFileInfo.parse(
_font('fonts/source-sans-3/SourceSans3-Semibold.ttf'),
);
expect(semibold.family, 'Source Sans 3');
expect(semibold.weight, 600);
final plex = FontFileInfo.parse(
_font('fonts/ibm-plex-sans/IBMPlexSans-Medium.ttf'),
);
expect(plex.family, 'IBM Plex Sans');
expect(plex.weight, 500);
final mono = FontFileInfo.parse(_font('fonts/RobotoMono-Bold.ttf'));
expect(mono.family, 'Roboto Mono');
expect(mono.weight, 700);
});
test('a font without OS/2 is weight 400; without names, no family', () {
final bold = _font('fonts/inter/Inter-Bold.ttf');
expect(FontFileInfo.parse(_withoutTable(bold, 'OS/2')).weight, 400);
expect(FontFileInfo.parse(_withoutTable(bold, 'name')).family, isNull);
});
test('rejects what is not a single TrueType/OpenType font', () {
final inter = _font('fonts/inter/Inter-Regular.ttf');
void rejects(List<int> bytes, String message) => expect(
() => FontFileInfo.parse(Uint8List.fromList(bytes)),
throwsA(
isA<FormatException>().having(
(e) => e.message,
'message',
contains(message),
),
),
);
rejects(<int>[], 'too short');
rejects('just some text, not a font'.codeUnits, 'Not a TrueType');
rejects(<int>[...'ttcf'.codeUnits, ...List.filled(12, 0)], 'collections');
rejects(<int>[...'wOFF'.codeUnits, ...List.filled(12, 0)], 'WOFF');
// The directory promises tables the file does not hold.
rejects(inter.sublist(0, 2000), 'outside the file');
rejects(inter.sublist(0, 20), 'directory is damaged');
rejects(_withoutTable(inter, 'cmap'), 'missing required tables');
});
test('a hostile name table is bounded, not trusted', () {
final copy = Uint8List.fromList(_font('fonts/inter/Inter-Regular.ttf'));
final data = ByteData.sublistView(copy);
for (var i = 0; i < data.getUint16(4); i++) {
final record = 12 + i * 16;
if (String.fromCharCodes(copy, record, record + 4) == 'name') {
// An absurd record count: ignored, the font still parses.
data.setUint16(data.getUint32(record + 8) + 2, 0xFFFF);
}
}
final info = FontFileInfo.parse(copy);
expect(info.family, isNull);
expect(info.weight, 400);
});
test('style names follow the weight classes', () {
expect(fontStyleName(400), 'Regular');
expect(fontStyleName(700), 'Bold');
expect(fontStyleName(600, italic: true), 'SemiBold Italic');
expect(fontStyleName(400, italic: true), 'Italic');
expect(fontStyleName(1000), 'Black');
expect(fontStyleName(1), 'Thin');
});
}
+1
View File
@@ -53,6 +53,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`.
| `labels=name` | write the visible semantics labels, keys and rects to JSON |
| `film=<target>` | screencast a click for `--film-ms` (900) and write the frames plus a contact sheet |
| `wait=ms` | sleep |
| `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker |
| `swipe=<target>>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) |
| `pinch=<target>>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) |
| `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab |
+2
View File
@@ -23,6 +23,7 @@ options: --script <steps.json> --size WxH (880x1000) --platform material|cuperti
--touch true (emulate a touch screen: mobile metrics, touch input)
steps: open=<route>[@WxH] wait=<ms> shot=<name> click=<target> waitfor=<target>
type=<text> press=<Enter|Escape|Tab|...> scroll=<dy> size=WxH
files=<path>[,<path>] (answers the next file chooser)
film=<target> labels=<name> tabs=<name> eval=<js> expect=<js> hover=<target>
drag=<target>><dx>,<dy> (JSON: drag, dx, dy, steps, gap, hold)
swipe=<target>><dx>,<dy> pinch=<target>><scale> (with --touch true)
@@ -113,6 +114,7 @@ try {
break;
}
case 'waitfor': await page.waitFor(value, step.timeout ?? 10000); break;
case 'files': await page.armFiles(String(value).split(',').map((p) => resolve(p))); break;
case 'type': await page.type(String(value)); await delay(step.wait ?? settle); break;
case 'press': await page.press(String(value)); await delay(step.wait ?? settle); break;
case 'scroll': {
+11
View File
@@ -122,6 +122,17 @@ export function flutterPage(browser, log, { touch = false } = {}) {
return point;
},
waitFor: (target, timeout) => locate(target, timeout),
/** Answers the next file chooser the page opens with [paths] (absolute). */
async armFiles(paths) {
await send('Page.setInterceptFileChooserDialog', { enabled: true });
const off = browser.on('Page.fileChooserOpened', (p) => {
off();
send('DOM.setFileInputFiles', { files: paths, backendNodeId: p.backendNodeId })
.then(() => log(` chose ${paths.join(', ')}`))
.catch((e) => errors.push(`files: ${e.message}`))
.finally(() => send('Page.setInterceptFileChooserDialog', { enabled: false }).catch(() => {}));
});
},
async type(text) {
const focused = await evaluate(`(() => {
const a = document.activeElement;