Merge: add your own fonts in Settings
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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]!));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
Reference in New Issue
Block a user