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 = {}; 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 _names(ByteData data, (int, int)? table) { final found = {}; if (table == null || table.$2 < 6) return const {}; 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 {}; } 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 { for (final entry in found.entries) entry.key: entry.value.$2, }; } static String _utf16(ByteData data, int offset, int size) => String.fromCharCodes([ 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([ 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 = [ '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'; }