Merge: Add font works with a real file dialog and always reports failures

This commit is contained in:
2026-11-04 20:48:03 +00:00
8 changed files with 361 additions and 32 deletions
@@ -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<void> addCustomFont(
BuildContext context,
AppFontController fonts,
FontFilePicker pick,
) async {
FontFilePicker pick, {
VoidCallback? onPicked,
}) async {
Future<void> problem(String message) async {
if (context.mounted) {
await showFontProblem(context, addCustomFontFailedTitle, message);
@@ -33,15 +36,18 @@ Future<void> 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<void> 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');
}
}
@@ -76,9 +76,15 @@ class _SettingsFontSectionState extends State<SettingsFontSection> {
}
Future<void> _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);
}
@@ -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<List<PickedFontFile>?> 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<List<PickedFontFile>?> 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<Uint8List?> 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<List<PickedFontFile>?> readFontSelection(
List<FontFileSource> selection,
) async {
if (selection.isEmpty) return null;
final files = <PickedFontFile>[];
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;
}
@@ -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<List<PickedFontFile>?> 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(<FontFileSource>[
for (final file in picked)
FontFileSource(
name: file.name,
size: file.lengthSync() ?? await file.length(),
read: file.readAsBytes,
),
]);
}
@@ -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 `<input type=file>`.
///
/// 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<List<PickedFontFile>?> 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<List<PickedFontFile>?>();
Future<void> settle(Future<List<PickedFontFile>?> 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<List<PickedFontFile>?>.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<FontFileSource> _sources(web.FileList? files) => <FontFileSource>[
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(),
),
];