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 _fonts = const []; FontBytesStore get _bytes => _bytesStore ??= hostFontBytesStore(); /// The added fonts, in the order they were added. List 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> load() async { try { final preferences = await SharedPreferences.getInstance(); final raw = preferences.getString(customFontsKey); final decoded = raw == null ? null : jsonDecode(raw); _fonts = [ if (decoded is List) for (final entry in decoded) ?CustomFont.fromJson(entry), ]; } catch (_) { _fonts = const []; } return _fonts; } /// The bytes of the face stored under [key]. Future 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: [ 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 store(CustomFont font, CustomFontDraft draft) async { final written = []; try { for (final (index, face) in font.faces.indexed) { await _bytes.write(face.key, draft.faces[index].bytes); written.add(face.key); } await _saveIndex([..._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 rename(CustomFont font, String name) async { final renamed = font.renamed(name); await _saveIndex([ for (final f in _fonts) f == font ? renamed : f, ]); return renamed; } /// Forgets [font] and deletes its files. Future remove(CustomFont font) async { await _saveIndex([ for (final f in _fonts) if (f != font) f, ]); for (final face in font.faces) { await _quietly(() => _bytes.delete(face.key)); } } Future _saveIndex(List fonts) async { final preferences = await SharedPreferences.getInstance(); final saved = await preferences.setString( customFontsKey, jsonEncode([for (final font in fonts) font.toJson()]), ); if (!saved) { throw const CustomFontRejected( 'The font list could not be saved on this device.', ); } _fonts = List.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 _quietly(Future Function() action) async { try { await action(); } catch (_) {} } }