import 'dart:async'; import 'dart:typed_data'; 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'; export 'app_font_loaders.dart'; /// The device's interface font: the stored choice, the family the theme /// 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 /// family that has not loaded, so nothing reflows more than once. class AppFontController extends ChangeNotifier { AppFontController({ this._store = const SharedPreferencesAppFontStore(), 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; late final AppFontAssetLoader _loader; final AppFontBytesLoader _bytesLoader; final CustomFontLibrary _library; final Map> _assetLoads = >{}; final Set _loadedAssets = {}; Future? _libraryLoad; FontChoice _selected = AppFont.system; FontChoice _applied = AppFont.system; bool _saveFailed = false; FontChoice? _loadFailed; /// The option the picker shows as chosen. FontChoice get selected => _selected; /// The option the theme uses now. FontChoice get applied => _applied; /// The theme's family; null keeps the platform typography. String? get family => _applied.family; /// The fonts the user added on this device, in the order added. List 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]. FontChoice? get loadFailed => _loadFailed; /// Whether [font]'s regular weight is registered, so its name can be drawn /// in its own face. bool canPreview(FontChoice font) => font.previewSource == null || _loadedAssets.contains(font.previewSource); /// Reads the added fonts' index once. Future 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 restore({Duration? wait}) async { 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(); final applying = _apply(font); if (wait == null) return applying; await Future.any(>[ applying, Future.delayed(wait), ]); } Future _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 select(FontChoice font) async { if (font == _selected && _loadFailed != font) return; _selected = font; _loadFailed = null; notifyListeners(); final saved = await _store.save(font.id); if (saved == _saveFailed) { _saveFailed = !saved; notifyListeners(); } await _apply(font); } /// 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 preview(FontChoice font) async { final source = font.previewSource; final family = font.family; if (source == null || family == null || _loadedAssets.contains(source)) { return; } try { await _ensure(family, [source]); } catch (_) { return; } notifyListeners(); } /// Checks picked files before they are named; see /// [CustomFontDraft.inspect]. Throws [CustomFontRejected]. Future inspect(List 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 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, [ 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.value(); _loadedAssets.add(source); } notifyListeners(); await select(font); return font; } /// Renames an added font; the choice and the theme keep it. Future 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 removeCustom(CustomFont font) async { await _library.remove(font); if (_selected == font || _applied == font) { _applied = AppFont.system; await select(AppFont.system); } notifyListeners(); } Future _apply(FontChoice font) async { final family = font.family; if (family != null) { try { await _ensure(family, font.sources); } catch (_) { if (_selected == font) { _loadFailed = font; notifyListeners(); } return; } } // A later choice supersedes this one. if (_selected != font || _applied == font) return; _applied = font; notifyListeners(); } /// Registers the sources not yet loaded or loading, in one [FontLoader], /// and waits for all of [sources]. A failed source can be retried. Future _ensure(String family, List sources) { final missing = sources.where((s) => !_assetLoads.containsKey(s)).toList(); if (missing.isNotEmpty) { final load = _loader(family, missing); for (final source in missing) { _assetLoads[source] = load.then( (_) => _loadedAssets.add(source), onError: (Object error, StackTrace stack) { _assetLoads.remove(source); Error.throwWithStackTrace(error, stack); }, ); } } return Future.wait(sources.map((s) => _assetLoads[s]!)); } }