Files
pipelines/app/lib/ui/theme/custom_fonts/custom_font_library.dart
T
alan c24e7f40b4 Settings: add your own fonts (.ttf/.otf) per device
Add font… picks one or more files, checks them with a bounded sfnt reader
(name table family, OS/2 weight), registers them with FontLoader before
storing, and chooses the new family. Added fonts list below the bundled ones
with Rename and Remove; removing the chosen one falls back to System default.
Bytes live in the app support directory natively and in IndexedDB on the web
(localStorage is too small); a shared_preferences index names them. Limits:
10 MB per file, 40 MB total. The capture kit gains a files= step.
2026-11-04 18:45:01 +00:00

149 lines
4.6 KiB
Dart

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 (_) {}
}
}