From 081ae0957d920ea3471cf1b39b0baff90dc5991e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 4 Nov 2026 20:47:43 +0000 Subject: [PATCH] Add font: own web file chooser, so a picked font is never dropped silently file_picker's web picker treated the window regaining focus as a cancel when the files arrived more than 500 ms later, so a real dialog could return an empty pick and Add font did nothing. The web now uses its own file input that completes only on change or cancel; mobile browsers get no accept filter. Picker, check and save failures are shown in a dialog, and the row is busy only after files were chosen. --- .../settings_custom_font_actions.dart | 20 +++-- .../settings/settings_font_section.dart | 10 ++- .../theme/custom_fonts/font_file_picker.dart | 62 ++++++++----- .../custom_fonts/font_file_picker_native.dart | 26 ++++++ .../custom_fonts/font_file_picker_web.dart | 90 +++++++++++++++++++ app/notes/interface-font-choice.md | 27 +++++- .../settings/settings_custom_font_test.dart | 78 +++++++++++++++- .../custom_fonts/font_file_picker_test.dart | 80 +++++++++++++++++ 8 files changed, 361 insertions(+), 32 deletions(-) create mode 100644 app/lib/ui/theme/custom_fonts/font_file_picker_native.dart create mode 100644 app/lib/ui/theme/custom_fonts/font_file_picker_web.dart create mode 100644 app/test/ui/theme/custom_fonts/font_file_picker_test.dart diff --git a/app/lib/features/settings/settings_custom_font_actions.dart b/app/lib/features/settings/settings_custom_font_actions.dart index cf90c7b4..a6eb8d91 100644 --- a/app/lib/features/settings/settings_custom_font_actions.dart +++ b/app/lib/features/settings/settings_custom_font_actions.dart @@ -15,13 +15,16 @@ const removeCustomFontText = 'Remove'; const customFontActionsTooltip = 'Font options'; /// Pick files, check them, ask for the family's name, then register, store -/// and choose the font. Every refusal is said in a dialog; nothing is -/// stored unless the whole family loaded. +/// and choose the font. Every refusal or failure after the picker opens is +/// said in a dialog; nothing is stored unless the whole family loaded. +/// [onPicked] runs once files were chosen, not while the picker is open, so +/// a browser that never reports a cancel cannot leave the action disabled. Future addCustomFont( BuildContext context, AppFontController fonts, - FontFilePicker pick, -) async { + FontFilePicker pick, { + VoidCallback? onPicked, +}) async { Future problem(String message) async { if (context.mounted) { await showFontProblem(context, addCustomFontFailedTitle, message); @@ -33,15 +36,18 @@ Future addCustomFont( files = await pick(); } on CustomFontRejected catch (error) { return problem(error.message); - } catch (_) { - return problem('The chosen files could not be read.'); + } catch (error) { + return problem('The file chooser failed: $error'); } if (files == null || !context.mounted) return; + onPicked?.call(); final CustomFontDraft draft; try { draft = await fonts.inspect(files); } on CustomFontRejected catch (error) { return problem(error.message); + } catch (error) { + return problem('The chosen files could not be checked: $error'); } if (!context.mounted) return; final name = await showFontNameDialog( @@ -56,6 +62,8 @@ Future addCustomFont( await fonts.addCustom(draft, name); } on CustomFontRejected catch (error) { return problem(error.message); + } catch (error) { + return problem('The font could not be saved: $error'); } } diff --git a/app/lib/features/settings/settings_font_section.dart b/app/lib/features/settings/settings_font_section.dart index b6a83bce..44e501e0 100644 --- a/app/lib/features/settings/settings_font_section.dart +++ b/app/lib/features/settings/settings_font_section.dart @@ -76,9 +76,15 @@ class _SettingsFontSectionState extends State { } Future _add() async { - setState(() => _adding = true); try { - await addCustomFont(context, widget.controller, widget.pickFiles); + await addCustomFont( + context, + widget.controller, + widget.pickFiles, + onPicked: () { + if (mounted) setState(() => _adding = true); + }, + ); } finally { if (mounted) setState(() => _adding = false); } diff --git a/app/lib/ui/theme/custom_fonts/font_file_picker.dart b/app/lib/ui/theme/custom_fonts/font_file_picker.dart index 85db4c6b..2073864f 100644 --- a/app/lib/ui/theme/custom_fonts/font_file_picker.dart +++ b/app/lib/ui/theme/custom_fonts/font_file_picker.dart @@ -1,34 +1,56 @@ -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/foundation.dart'; +import 'dart:typed_data'; import 'custom_font_draft.dart'; +export 'font_file_picker_native.dart' + if (dart.library.js_interop) 'font_file_picker_web.dart' + show pickFontFiles; + /// Opens the host's file picker for font files; null when the user cancels. -/// Throws [CustomFontRejected] for a file too large to read. +/// Throws [CustomFontRejected] when a chosen file cannot be used as picked +/// (too large, unreadable); any other error means the picker itself failed. typedef FontFilePicker = Future?> Function(); -/// The host picker through `file_picker`. The web and Apple pickers filter -/// to .ttf/.otf; Android's document picker filters by MIME type, which many -/// providers do not report for fonts, so there every file is offered and -/// [CustomFontDraft.inspect] rejects the rest by name. -Future?> pickFontFiles() async { - final android = !kIsWeb && defaultTargetPlatform == TargetPlatform.android; - final picked = await FilePicker.pickFiles( - type: android ? FileType.any : FileType.custom, - allowedExtensions: android ? null : CustomFontLimits.extensions, - ); - if (picked.isEmpty) return null; +/// One file the host picker returned, before its bytes are read. +class FontFileSource { + const FontFileSource({required this.name, required this.read, this.size}); + + final String name; + + /// The size the host reports, if any; checked before [read]. + final int? size; + + /// Reads the file; null when the host could not provide its content. + final Future Function() read; +} + +/// Turns a picker's selection into [PickedFontFile]s. An empty selection is +/// a cancel (null). A file over [CustomFontLimits.maxFileBytes] is refused +/// before it is read; a file whose bytes cannot be read is refused by name. +/// Whether each file is a font is [CustomFontDraft.inspect]'s job. +Future?> readFontSelection( + List selection, +) async { + if (selection.isEmpty) return null; final files = []; - for (final file in picked) { - final length = file.lengthSync() ?? await file.length(); - if (length != null && length > CustomFontLimits.maxFileBytes) { - // Refuse before reading a huge file into memory. + for (final source in selection) { + final size = source.size; + if (size != null && size > CustomFontLimits.maxFileBytes) { throw CustomFontRejected( - '“${file.name}” is larger than ' + '“${source.name}” is larger than ' '${CustomFontLimits.maxFileBytes ~/ (1024 * 1024)} MB.', ); } - files.add(PickedFontFile(name: file.name, bytes: await file.readAsBytes())); + final Uint8List? bytes; + try { + bytes = await source.read(); + } catch (_) { + throw CustomFontRejected('“${source.name}” could not be read.'); + } + if (bytes == null) { + throw CustomFontRejected('“${source.name}” could not be read.'); + } + files.add(PickedFontFile(name: source.name, bytes: bytes)); } return files; } diff --git a/app/lib/ui/theme/custom_fonts/font_file_picker_native.dart b/app/lib/ui/theme/custom_fonts/font_file_picker_native.dart new file mode 100644 index 00000000..e99ce217 --- /dev/null +++ b/app/lib/ui/theme/custom_fonts/font_file_picker_native.dart @@ -0,0 +1,26 @@ +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; + +import 'custom_font_draft.dart'; +import 'font_file_picker.dart'; + +/// The native picker through `file_picker`. Apple and desktop pickers filter +/// to .ttf/.otf by type. Android's document picker filters by MIME type, +/// and providers report fonts as `font/ttf`, `application/x-font-ttf` or +/// `application/octet-stream`, so a filter greys the files out; there every +/// file is offered and [CustomFontDraft.inspect] refuses the rest by name. +Future?> pickFontFiles() async { + final android = defaultTargetPlatform == TargetPlatform.android; + final picked = await FilePicker.pickFiles( + type: android ? FileType.any : FileType.custom, + allowedExtensions: android ? null : CustomFontLimits.extensions, + ); + return readFontSelection([ + for (final file in picked) + FontFileSource( + name: file.name, + size: file.lengthSync() ?? await file.length(), + read: file.readAsBytes, + ), + ]); +} diff --git a/app/lib/ui/theme/custom_fonts/font_file_picker_web.dart b/app/lib/ui/theme/custom_fonts/font_file_picker_web.dart new file mode 100644 index 00000000..b7693270 --- /dev/null +++ b/app/lib/ui/theme/custom_fonts/font_file_picker_web.dart @@ -0,0 +1,90 @@ +import 'dart:async'; +import 'dart:js_interop'; + +import 'package:flutter/foundation.dart'; +import 'package:web/web.dart' as web; + +import 'custom_font_draft.dart'; +import 'font_file_picker.dart'; + +const String _inputId = 'pipelines-font-file-input'; + +/// The browser's own file chooser through an ``. +/// +/// Only the input's `change` (a selection) or `cancel` event completes the +/// pick. `file_picker`'s web picker also treats the window regaining focus +/// as a cancel when no files arrived within 500 ms; a real dialog returns +/// focus before the browser delivers the files, so a slow delivery became a +/// silent cancel and the picked font was dropped. +/// +/// Desktop browsers filter by extension. Mobile browsers filter by MIME +/// type, which they and the storage providers map inconsistently for fonts +/// (greying out the very file the user wants), so there every file is +/// offered and [CustomFontDraft.inspect] refuses the rest by name. +Future?> pickFontFiles() { + web.document.getElementById(_inputId)?.remove(); + final mobile = + defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS; + final input = web.HTMLInputElement() + ..id = _inputId + ..type = 'file' + ..multiple = true; + if (!mobile) { + input.accept = CustomFontLimits.extensions.map((e) => '.$e').join(','); + } + // In the layout but out of sight: some browsers refuse to open a + // display:none file input. + input.style + ..position = 'fixed' + ..left = '-10000px' + ..top = '0' + ..width = '1px' + ..height = '1px' + ..opacity = '0'; + + final done = Completer?>(); + + Future settle(Future?> result) async { + try { + final files = await result; + if (!done.isCompleted) done.complete(files); + } catch (error, stackTrace) { + if (!done.isCompleted) done.completeError(error, stackTrace); + } finally { + input.remove(); + } + } + + input.addEventListener( + 'change', + ((web.Event _) { + unawaited(settle(readFontSelection(_sources(input.files)))); + }).toJS, + ); + input.addEventListener( + 'cancel', + ((web.Event _) { + unawaited(settle(Future?>.value())); + }).toJS, + ); + + final body = web.document.body; + if (body == null) { + throw StateError('The page has no body to open a file chooser from.'); + } + body.appendChild(input); + input.click(); + return done.future; +} + +List _sources(web.FileList? files) => [ + for (var index = 0; index < (files?.length ?? 0); index += 1) + if (files!.item(index) case final web.File file) + FontFileSource( + name: file.name, + size: file.size, + read: () async => + (await file.arrayBuffer().toDart).toDart.asUint8List(), + ), +]; diff --git a/app/notes/interface-font-choice.md b/app/notes/interface-font-choice.md index 917c57fd..6d27ba72 100644 --- a/app/notes/interface-font-choice.md +++ b/app/notes/interface-font-choice.md @@ -45,9 +45,14 @@ same compressed amount (not measured). ## Fonts the user adds -Settings > Font ends with **Add font…**. It opens the host picker -(`file_picker`; .ttf/.otf filter on the web and Apple hosts, every file on -Android, whose document picker filters by MIME type), then: +Settings > Font ends with **Add font…**. It opens the host picker, then: +natively `file_picker` (.ttf/.otf filter on Apple and desktop hosts, every +file on Android, whose document picker filters by MIME type); on the web +its own `` (`custom_fonts/font_file_picker_web.dart`), +filtered to .ttf/.otf in desktop browsers and unfiltered in Android/iOS +browsers, where font MIME mapping is inconsistent. Every failure after the +pick (unreadable file, wrong type, picker, load or storage error) is said in +a dialog; the row is busy only once files were chosen. 1. `CustomFontDraft.inspect` refuses other extensions, files over 10 MB, more than 16 files at once, two files of the same weight and style, and a @@ -118,3 +123,19 @@ face; the options menu and action sheet; rename to "Body face"; the remove confirmation; the fallback to System default; and a fake `.ttf` refused with "“fake.ttf” cannot be used: The file is too short." Android and iOS were not run on a device. + +### Fix: “Add font… does nothing” in the browser + +`file_picker`'s web picker (`cancelUploadOnWindowBlur`, on by default) +treats the window regaining focus as a cancel unless the chosen files arrive +within 500 ms. A real dialog returns focus before the browser delivers the +files, so a slow delivery became an empty pick and the action returned +silently. The capture kit's `files=` step answers the chooser without any +focus change, which hid it. Reproduced on the release build (the installed +web app and the fixture) in Chrome with a canvas mouse click (semantics off), +`Page.setInterceptFileChooserDialog` + `DOM.setFileInputFiles`, and a window +`focus` 700 ms before the files: the old build dropped the font; the new one +shows the name dialog and adds it. Also checked: two files added and chosen, +OFL.txt refused with a message, and a 560x1600 Android-UA touch run (no +`accept` filter, name dialog shown). Safari/iOS and the Android app were not +run on a device. diff --git a/app/test/features/settings/settings_custom_font_test.dart b/app/test/features/settings/settings_custom_font_test.dart index 4b2ac360..efd5ebed 100644 --- a/app/test/features/settings/settings_custom_font_test.dart +++ b/app/test/features/settings/settings_custom_font_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -7,6 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/settings/settings_custom_font_actions.dart'; import 'package:pipelines_app/features/settings/settings_custom_font_dialogs.dart'; import 'package:pipelines_app/features/settings/settings_font_section.dart'; +import 'package:pipelines_app/features/settings/settings_row.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'; @@ -14,6 +16,7 @@ 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_file_picker.dart'; import 'package:shared_preferences/shared_preferences.dart'; PickedFontFile _pick(String path) => PickedFontFile( @@ -40,11 +43,12 @@ Future _pump( WidgetTester tester, _Harness harness, { bool cupertino = false, + FontFilePicker? pick, }) async { final section = SingleChildScrollView( child: SettingsFontSection( controller: harness.fonts, - pickFiles: harness.pick, + pickFiles: pick ?? harness.pick, ), ); await tester.pumpWidget( @@ -168,6 +172,78 @@ void main() { expect(harness.fonts.customFonts, isEmpty); }); + Future expectProblem(WidgetTester tester, Matcher message) async { + expect(find.text(addCustomFontFailedTitle), findsOneWidget); + expect( + find.byWidgetPredicate( + (w) => w is Text && message.matches(w.data, {}), + ), + findsOneWidget, + ); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + } + + testWidgets('every failure of the picker is said, never silent', ( + tester, + ) async { + Object? failure; + final harness = _Harness(); + await _pump( + tester, + harness, + pick: () async => failure == null ? harness.next : throw failure, + ); + + // A file the host could not read (null bytes). + failure = const CustomFontRejected('“A.ttf” could not be read.'); + await tester.tap(find.text(addCustomFontText)); + await tester.pumpAndSettle(); + await expectProblem(tester, equals('“A.ttf” could not be read.')); + + // Any other picker exception. + failure = StateError('boom'); + await tester.tap(find.text(addCustomFontText)); + await tester.pumpAndSettle(); + await expectProblem(tester, contains('The file chooser failed')); + + // The wrong type, now that mobile pickers offer every file. + failure = null; + harness.next = [ + PickedFontFile(name: 'photo.png', bytes: utf8.encode('png')), + ]; + await tester.tap(find.text(addCustomFontText)); + await tester.pumpAndSettle(); + await expectProblem(tester, contains('is not a .ttf or .otf font file')); + expect(harness.fonts.customFonts, isEmpty); + }); + + testWidgets('a font that fails to save is said, nothing stored', ( + tester, + ) async { + final harness = _Harness()..next = [regular]; + harness.bytes.failWrites = true; + await _pump(tester, harness); + await tester.tap(find.text(addCustomFontText)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Add')); + await tester.pumpAndSettle(); + expect(find.text(addCustomFontFailedTitle), findsOneWidget); + expect(harness.fonts.customFonts, isEmpty); + }); + + testWidgets('an open picker does not disable Add font…', (tester) async { + final harness = _Harness(); + final never = Completer?>(); + await _pump(tester, harness, pick: () => never.future); + await tester.tap(find.text(addCustomFontText)); + await tester.pump(); + // A browser that never reports the cancel must not leave it stuck. + expect(find.text(addingCustomFontText), findsNothing); + final row = tester.widget(find.byKey(settingsAddFontKey)); + expect(row.enabled, isTrue); + }); + testWidgets('Cupertino: an added font has the checkmark and options', ( tester, ) async { diff --git a/app/test/ui/theme/custom_fonts/font_file_picker_test.dart b/app/test/ui/theme/custom_fonts/font_file_picker_test.dart new file mode 100644 index 00000000..a487a33d --- /dev/null +++ b/app/test/ui/theme/custom_fonts/font_file_picker_test.dart @@ -0,0 +1,80 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/theme/custom_fonts/custom_font_draft.dart'; +import 'package:pipelines_app/ui/theme/custom_fonts/font_file_picker.dart'; + +FontFileSource _source( + String name, { + int? size, + Future Function()? read, +}) => FontFileSource( + name: name, + size: size, + read: read ?? () async => Uint8List.fromList([1, 2, 3]), +); + +Matcher _rejected(String message) => throwsA( + isA().having((e) => e.message, 'message', message), +); + +void main() { + test('an empty selection is a cancel', () async { + expect(await readFontSelection(const []), isNull); + }); + + test('chosen files come back with their bytes, in order', () async { + final files = await readFontSelection([ + _source('A.ttf', size: 3), + _source('B.otf'), + ]); + expect(files!.map((f) => f.name), ['A.ttf', 'B.otf']); + expect(files.first.bytes, [1, 2, 3]); + }); + + test('a file whose bytes the host cannot provide is refused', () async { + await expectLater( + readFontSelection([ + _source('A.ttf', read: () async => null), + ]), + _rejected('“A.ttf” could not be read.'), + ); + }); + + test('a read that throws is refused by name, not swallowed', () async { + await expectLater( + readFontSelection([ + _source('A.ttf', read: () async => throw StateError('NotReadable')), + ]), + _rejected('“A.ttf” could not be read.'), + ); + }); + + test('a file over the limit is refused before it is read', () async { + var read = false; + await expectLater( + readFontSelection([ + _source( + 'Huge.ttf', + size: CustomFontLimits.maxFileBytes + 1, + read: () async { + read = true; + return Uint8List(0); + }, + ), + ]), + _rejected('“Huge.ttf” is larger than 10 MB.'), + ); + expect(read, isFalse); + }); + + test('another file type passes through for inspect to refuse', () async { + final files = await readFontSelection([ + _source('photo.png'), + ]); + expect( + () => CustomFontDraft.inspect(files!), + _rejected('“photo.png” is not a .ttf or .otf font file.'), + ); + }); +}