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.
This commit is contained in:
2026-11-04 18:45:01 +00:00
parent e0d7b720f5
commit c24e7f40b4
28 changed files with 2329 additions and 122 deletions
@@ -36,7 +36,7 @@ void main() {
test('restore loads only the stored family, then applies it', () async {
final loads = _Loads()..immediate = false;
final fonts = AppFontController(
store: MemoryAppFontStore(AppFont.inter),
store: MemoryAppFontStore(AppFont.inter.id),
loader: loads.call,
);
final restoring = fonts.restore();
@@ -57,7 +57,7 @@ void main() {
() async {
final loads = _Loads()..immediate = false;
final fonts = AppFontController(
store: MemoryAppFontStore(AppFont.sourceSans3),
store: MemoryAppFontStore(AppFont.sourceSans3.id),
loader: loads.call,
);
await fonts.restore(wait: const Duration(milliseconds: 10));
@@ -75,10 +75,10 @@ void main() {
final loads = _Loads();
final fonts = AppFontController(store: store, loader: loads.call);
await fonts.select(AppFont.atkinsonHyperlegible);
expect(store.font, AppFont.atkinsonHyperlegible);
expect(store.id, AppFont.atkinsonHyperlegible.id);
expect(fonts.family, 'Atkinson Hyperlegible Next');
await fonts.select(AppFont.system);
expect(store.font, AppFont.system);
expect(store.id, AppFont.system.id);
expect(fonts.family, isNull);
expect(loads.calls, hasLength(1));
},
+6 -13
View File
@@ -10,32 +10,25 @@ void main() {
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
test('nothing stored is the system default', () async {
expect(await const SharedPreferencesAppFontStore().load(), AppFont.system);
test('nothing stored reads as no choice', () async {
expect(await const SharedPreferencesAppFontStore().load(), isNull);
});
test(
'a choice round-trips under its stable id, on the device only',
() async {
const store = SharedPreferencesAppFontStore();
expect(await store.save(AppFont.ibmPlexSans), isTrue);
expect(await store.save(AppFont.ibmPlexSans.id), isTrue);
final preferences = await SharedPreferences.getInstance();
expect(preferences.getKeys(), <String>{appFontKey});
expect(preferences.getString(appFontKey), 'ibm-plex-sans');
expect(await store.load(), AppFont.ibmPlexSans);
expect(await store.load(), AppFont.ibmPlexSans.id);
expect(await store.save(AppFont.system), isTrue);
expect(await store.load(), AppFont.system);
expect(await store.save(AppFont.system.id), isTrue);
expect(await store.load(), 'system');
},
);
test('an unknown stored id falls back to the system default', () async {
SharedPreferences.setMockInitialValues(<String, Object>{
appFontKey: 'comic-sans',
});
expect(await const SharedPreferencesAppFontStore().load(), AppFont.system);
});
test('every bundled option has its four weights and its licence', () {
for (final font in AppFont.values) {
if (font == AppFont.system) {
@@ -0,0 +1,160 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/theme/app_font.dart';
import 'package:pipelines_app/ui/theme/app_font_controller.dart';
import 'package:pipelines_app/ui/theme/app_font_store.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_draft.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_library.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_bytes_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
PickedFontFile _pick(String path) => PickedFontFile(
name: path.split('/').last,
bytes: File(path).readAsBytesSync(),
);
class _Device {
_Device({MemoryAppFontStore? store, MemoryFontBytesStore? bytes})
: store = store ?? MemoryAppFontStore(),
bytes = bytes ?? MemoryFontBytesStore();
final MemoryAppFontStore store;
final MemoryFontBytesStore bytes;
final loads = <List<String>>[];
final checked = <String>[];
bool rejectBytes = false;
/// A fresh app start on this device: real index, the given byte store.
late final AppFontController fonts = AppFontController(
store: store,
library: CustomFontLibrary(bytes: bytes),
loader: (family, sources) async => loads.add(sources),
bytesLoader: (family, faces) async {
checked.add(family);
if (rejectBytes) throw StateError('engine refused');
},
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
final regular = _pick('fonts/inter/Inter-Regular.ttf');
final bold = _pick('fonts/inter/Inter-Bold.ttf');
test(
'adding checks the files with the engine, stores and chooses them',
() async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular, bold]);
final font = await device.fonts.addCustom(draft, ' My Inter ');
expect(font.name, 'My Inter');
expect(device.checked, <String>[font.family]);
expect(device.fonts.customFonts, <CustomFont>[font]);
expect(device.fonts.selected, font);
expect(device.fonts.family, font.family);
expect(device.loads, isEmpty, reason: 'already registered by the check');
expect(device.store.id, font.id);
expect(device.bytes.files, hasLength(2));
},
);
test('a font the engine cannot load is rejected and never stored', () async {
final device = _Device()..rejectBytes = true;
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
await expectLater(
device.fonts.addCustom(draft, 'Broken'),
throwsA(isA<CustomFontRejected>()),
);
expect(device.bytes.files, isEmpty);
expect(device.fonts.customFonts, isEmpty);
expect(device.fonts.selected, AppFont.system);
expect(device.store.id, isNull);
});
test('an empty name is refused before anything is stored', () async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
await expectLater(
device.fonts.addCustom(draft, ' '),
throwsA(isA<CustomFontRejected>()),
);
expect(device.checked, isEmpty);
});
test('a stored added font loads at startup from the byte store', () async {
final first = _Device();
final draft = await first.fonts.inspect(<PickedFontFile>[regular, bold]);
final font = await first.fonts.addCustom(draft, 'Mine');
final next = _Device(store: first.store, bytes: first.bytes);
await next.fonts.restore(wait: const Duration(seconds: 1));
expect(next.fonts.selected, font);
expect(next.fonts.family, font.family);
expect(next.loads.single, font.sources);
});
test('a stored id with no font behind it is the system default', () async {
for (final id in <String>['comic-sans', 'custom-gone']) {
final device = _Device(store: MemoryAppFontStore(id));
await device.fonts.restore();
expect(device.fonts.selected, AppFont.system);
expect(device.loads, isEmpty);
}
});
test('missing bytes at startup keep the system face and say so', () async {
final first = _Device();
final draft = await first.fonts.inspect(<PickedFontFile>[regular]);
final font = await first.fonts.addCustom(draft, 'Mine');
first.bytes.files.clear();
final next = AppFontController(
store: first.store,
library: CustomFontLibrary(bytes: first.bytes),
loader: appFontSourceLoader(first.bytes.read),
);
await next.restore();
expect(next.selected, font);
expect(next.loadFailed, font);
expect(next.family, isNull);
});
test('renaming keeps the choice; removing it falls back to system', () async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
final font = await device.fonts.addCustom(draft, 'Mine');
await device.fonts.renameCustom(font, 'Body');
expect(device.fonts.selected.label, 'Body');
expect(device.fonts.family, font.family);
expect(device.store.id, font.id);
await device.fonts.removeCustom(device.fonts.customFonts.single);
expect(device.fonts.customFonts, isEmpty);
expect(device.fonts.selected, AppFont.system);
expect(device.fonts.family, isNull);
expect(device.store.id, AppFont.system.id);
expect(device.bytes.files, isEmpty);
});
test('removing a font that is not chosen keeps the choice', () async {
final device = _Device();
final draft = await device.fonts.inspect(<PickedFontFile>[regular]);
final font = await device.fonts.addCustom(draft, 'Mine');
await device.fonts.select(AppFont.inter);
await device.fonts.removeCustom(font);
expect(device.fonts.selected, AppFont.inter);
expect(device.store.id, AppFont.inter.id);
});
test('the real FontLoader accepts a bundled file as a user font', () async {
// The engine path production uses; bytes come from a fixture file.
await loadFontBytes('Fixture user font', <Uint8List>[regular.bytes]);
});
}
@@ -0,0 +1,197 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_draft.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_library.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_bytes_store.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_bytes_store_io.dart';
import 'package:pipelines_app/ui/theme/font_choice.dart';
import 'package:shared_preferences/shared_preferences.dart';
PickedFontFile _pick(String path, [String? name]) => PickedFontFile(
name: name ?? path.split('/').last,
bytes: File(path).readAsBytesSync(),
);
final _regular = _pick('fonts/inter/Inter-Regular.ttf');
final _bold = _pick('fonts/inter/Inter-Bold.ttf');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues(<String, Object>{}));
group('inspect', () {
test('groups files into one family named from the name table', () {
final draft = CustomFontDraft.inspect(<PickedFontFile>[_regular, _bold]);
expect(draft.suggestedName, 'Inter');
expect(draft.faces.map((f) => f.styleName), <String>['Regular', 'Bold']);
});
test('a file without names is named after the file', () {
final copy = Uint8List.fromList(_regular.bytes);
final data = ByteData.sublistView(copy);
for (var i = 0; i < data.getUint16(4); i++) {
final record = 12 + i * 16;
if (String.fromCharCodes(copy, record, record + 4) == 'name') {
copy.setAll(record, 'zzzz'.codeUnits);
}
}
final draft = CustomFontDraft.inspect(<PickedFontFile>[
PickedFontFile(name: 'My Face.OTF', bytes: copy),
]);
expect(draft.suggestedName, 'My Face');
});
test('refuses other files, damaged fonts, twins and oversize', () {
void refuses(List<PickedFontFile> files, String text, {int stored = 0}) =>
expect(
() => CustomFontDraft.inspect(files, storedBytes: stored),
throwsA(
isA<CustomFontRejected>().having(
(e) => e.message,
'message',
contains(text),
),
),
);
refuses(<PickedFontFile>[], 'No font file');
refuses(<PickedFontFile>[
PickedFontFile(name: 'notes.txt', bytes: _regular.bytes),
], 'not a .ttf or .otf');
refuses(<PickedFontFile>[
PickedFontFile(name: 'fake.ttf', bytes: utf8.encode('hello')),
], 'cannot be used');
refuses(<PickedFontFile>[
PickedFontFile(
name: 'huge.ttf',
bytes: Uint8List(CustomFontLimits.maxFileBytes + 1),
),
], 'larger than 10 MB');
refuses(<PickedFontFile>[
_regular,
_pick('fonts/source-sans-3/SourceSans3-Regular.ttf'),
], 'both Regular');
refuses(
<PickedFontFile>[_regular],
'up to 40 MB',
stored: CustomFontLimits.maxTotalBytes - 1000,
);
});
test('names are trimmed, required and bounded', () {
expect(CustomFontLimits.nameProblem(' '), isNotNull);
expect(CustomFontLimits.nameProblem('x' * 65), isNotNull);
expect(CustomFontLimits.nameProblem(' Mine '), isNull);
});
});
group('library', () {
test('round-trips the index and bytes, then removes both', () async {
final bytes = MemoryFontBytesStore();
final library = CustomFontLibrary(bytes: bytes);
await library.load();
final draft = CustomFontDraft.inspect(<PickedFontFile>[_regular, _bold]);
final font = await library.store(library.prepare(draft, 'Mine'), draft);
expect(font.styles, 'Regular, Bold');
expect(font.sources, <String>[
for (final face in font.faces) customFontSource(face.key),
]);
expect(font.previewSource, customFontSource(font.faces.first.key));
expect(bytes.files.keys, font.faces.map((f) => f.key));
final reopened = CustomFontLibrary(bytes: bytes);
final fonts = await reopened.load();
expect(fonts.single.name, 'Mine');
expect(fonts.single.faces.map((f) => f.weight), <int>[400, 700]);
expect(await reopened.read(font.faces.last.key), _bold.bytes);
expect(reopened.storedBytes, draft.size);
final renamed = await reopened.rename(fonts.single, 'Body');
expect(renamed.family, font.family, reason: 'registration is kept');
expect(
(await CustomFontLibrary(bytes: bytes).load()).single.label,
'Body',
);
await reopened.remove(renamed);
expect(bytes.files, isEmpty);
expect(await CustomFontLibrary(bytes: bytes).load(), isEmpty);
});
test('a failed write stores nothing and says so', () async {
final bytes = MemoryFontBytesStore()..failWrites = true;
final library = CustomFontLibrary(bytes: bytes);
final draft = CustomFontDraft.inspect(<PickedFontFile>[_regular]);
await expectLater(
library.store(library.prepare(draft, 'Mine'), draft),
throwsA(isA<CustomFontRejected>()),
);
expect(bytes.files, isEmpty);
expect(await library.load(), isEmpty);
});
test('an unreadable index or entry is skipped', () async {
SharedPreferences.setMockInitialValues(<String, Object>{
customFontsKey: jsonEncode(<Object>[
<String, Object>{'id': 'evil', 'name': 'x', 'faces': <Object>[]},
const CustomFont(
id: 'custom-1',
name: 'Kept',
faces: <CustomFontFace>[
CustomFontFace(
key: 'custom-1-0',
fileName: 'a.ttf',
weight: 400,
italic: false,
size: 3,
),
],
).toJson(),
]),
});
final fonts = await CustomFontLibrary(
bytes: MemoryFontBytesStore(),
).load();
expect(fonts.map((f) => f.name), <String>['Kept']);
SharedPreferences.setMockInitialValues(<String, Object>{
customFontsKey: '{not json',
});
expect(
await CustomFontLibrary(bytes: MemoryFontBytesStore()).load(),
isEmpty,
);
});
});
group('native file store', () {
late Directory temp;
setUp(() => temp = Directory.systemTemp.createTempSync('custom-fonts'));
tearDown(() => temp.deleteSync(recursive: true));
test('writes, reads and deletes one file per key', () async {
final dir = Directory('${temp.path}/custom-fonts');
final store = DirectoryFontBytesStore(() async => dir);
await store.write('custom-1-0', _regular.bytes);
expect(File('${dir.path}/custom-1-0').existsSync(), isTrue);
expect(dir.listSync(), hasLength(1), reason: 'no partial file left');
expect(await store.read('custom-1-0'), _regular.bytes);
await store.delete('custom-1-0');
await store.delete('custom-1-0');
expect(dir.listSync(), isEmpty);
await expectLater(store.read('custom-1-0'), throwsA(anything));
});
test('refuses a key that could name another path', () async {
final store = DirectoryFontBytesStore(() async => temp);
await expectLater(
store.write('../escape', _regular.bytes),
throwsArgumentError,
);
});
});
}
@@ -0,0 +1,103 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/theme/custom_fonts/font_file_info.dart';
Uint8List _font(String path) => File(path).readAsBytesSync();
/// [bytes] with the table directory's [tag] renamed, so the table is gone.
Uint8List _withoutTable(Uint8List bytes, String tag) {
final copy = Uint8List.fromList(bytes);
final data = ByteData.sublistView(copy);
for (var i = 0; i < data.getUint16(4); i++) {
final record = 12 + i * 16;
if (String.fromCharCodes(copy, record, record + 4) == tag) {
copy.setAll(record, 'zzzz'.codeUnits);
}
}
return copy;
}
void main() {
test('reads family, style and weight from the bundled fonts', () {
final regular = FontFileInfo.parse(_font('fonts/inter/Inter-Regular.ttf'));
expect(regular.family, 'Inter');
expect(regular.subfamily, 'Regular');
expect(regular.weight, 400);
expect(regular.italic, isFalse);
final bold = FontFileInfo.parse(_font('fonts/inter/Inter-Bold.ttf'));
expect(bold.family, 'Inter');
expect(bold.weight, 700);
final semibold = FontFileInfo.parse(
_font('fonts/source-sans-3/SourceSans3-Semibold.ttf'),
);
expect(semibold.family, 'Source Sans 3');
expect(semibold.weight, 600);
final plex = FontFileInfo.parse(
_font('fonts/ibm-plex-sans/IBMPlexSans-Medium.ttf'),
);
expect(plex.family, 'IBM Plex Sans');
expect(plex.weight, 500);
final mono = FontFileInfo.parse(_font('fonts/RobotoMono-Bold.ttf'));
expect(mono.family, 'Roboto Mono');
expect(mono.weight, 700);
});
test('a font without OS/2 is weight 400; without names, no family', () {
final bold = _font('fonts/inter/Inter-Bold.ttf');
expect(FontFileInfo.parse(_withoutTable(bold, 'OS/2')).weight, 400);
expect(FontFileInfo.parse(_withoutTable(bold, 'name')).family, isNull);
});
test('rejects what is not a single TrueType/OpenType font', () {
final inter = _font('fonts/inter/Inter-Regular.ttf');
void rejects(List<int> bytes, String message) => expect(
() => FontFileInfo.parse(Uint8List.fromList(bytes)),
throwsA(
isA<FormatException>().having(
(e) => e.message,
'message',
contains(message),
),
),
);
rejects(<int>[], 'too short');
rejects('just some text, not a font'.codeUnits, 'Not a TrueType');
rejects(<int>[...'ttcf'.codeUnits, ...List.filled(12, 0)], 'collections');
rejects(<int>[...'wOFF'.codeUnits, ...List.filled(12, 0)], 'WOFF');
// The directory promises tables the file does not hold.
rejects(inter.sublist(0, 2000), 'outside the file');
rejects(inter.sublist(0, 20), 'directory is damaged');
rejects(_withoutTable(inter, 'cmap'), 'missing required tables');
});
test('a hostile name table is bounded, not trusted', () {
final copy = Uint8List.fromList(_font('fonts/inter/Inter-Regular.ttf'));
final data = ByteData.sublistView(copy);
for (var i = 0; i < data.getUint16(4); i++) {
final record = 12 + i * 16;
if (String.fromCharCodes(copy, record, record + 4) == 'name') {
// An absurd record count: ignored, the font still parses.
data.setUint16(data.getUint32(record + 8) + 2, 0xFFFF);
}
}
final info = FontFileInfo.parse(copy);
expect(info.family, isNull);
expect(info.weight, 400);
});
test('style names follow the weight classes', () {
expect(fontStyleName(400), 'Regular');
expect(fontStyleName(700), 'Bold');
expect(fontStyleName(600, italic: true), 'SemiBold Italic');
expect(fontStyleName(400, italic: true), 'Italic');
expect(fontStyleName(1000), 'Black');
expect(fontStyleName(1), 'Thin');
});
}