loadSystemFontsImpl function

Future<FontFallbackChain> loadSystemFontsImpl({
  1. List<String>? preferredFonts,
  2. int maxFonts = 5,
  3. GraphicsFileSystem? filesystem,
})

Implementation

Future<FontFallbackChain> loadSystemFontsImpl({
  List<String>? preferredFonts,
  int maxFonts = 5,
  GraphicsFileSystem? filesystem,
}) async {
  final chain = FontFallbackChain();
  final fs = filesystem ?? const LocalGraphicsFileSystem();
  final platform = Platform.operatingSystem;
  final searchPaths = _systemFontPaths[platform] ?? [];

  final fontsToLoad = preferredFonts ?? _commonFonts;
  var loaded = 0;

  for (final fontName in fontsToLoad) {
    if (loaded >= maxFonts) break;

    for (final basePath in searchPaths) {
      final expandedPath = basePath.replaceFirst(
        '~',
        Platform.environment['HOME'] ?? '',
      );

      for (final ext in ['.ttf', '.otf', '.TTF', '.OTF']) {
        final fontPath = '$expandedPath$fontName$ext';
        final file = File(fontPath);

        if (await file.exists()) {
          try {
            await chain.addFontFromFile(fontPath, filesystem: fs);
            loaded++;
            logger.info('Loaded system font: $fontPath');
            break;
          } catch (_) {
            // Continue searching for other fonts/extensions
          }
        }
      }

      if (loaded >= maxFonts) break;
    }
  }

  if (loaded == 0) {
    logger.warning('No system fonts could be loaded');
  }

  return chain;
}