Settings: per-device interface font choice

System default plus Inter, IBM Plex Sans, Source Sans 3 and Atkinson
Hyperlegible Next (OFL 1.1, bundled as on-demand assets and loaded with
FontLoader, so the web fetches only the previewed/chosen files). Stored in
shared_preferences, applied live to Material and Cupertino text themes;
RobotoMono styles unchanged. Licences registered with LicenseRegistry.
This commit is contained in:
2026-11-04 02:01:49 +00:00
parent fa6c0864db
commit 2853b18b9e
38 changed files with 1486 additions and 26 deletions
+22 -6
View File
@@ -1,4 +1,5 @@
import '../ui/adaptive/platform.dart';
import '../ui/theme/app_font_controller.dart';
import '../ui/theme/app_theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -16,6 +17,7 @@ class MyApp extends StatelessWidget {
this.cupertino,
this.destination,
this.onDestinationSelected,
this.fonts,
}) : routerConfig = null;
/// A host for a [Router]-owned location, so browser Back/Forward and deep
@@ -25,6 +27,7 @@ class MyApp extends StatelessWidget {
super.key,
required RouterConfig<Object> this.routerConfig,
this.cupertino,
this.fonts,
}) : destinationBodies = const {},
destination = null,
onDestinationSelected = null;
@@ -35,20 +38,33 @@ class MyApp extends StatelessWidget {
final ValueChanged<AppDestination>? onDestinationSelected;
final RouterConfig<Object>? routerConfig;
/// The device's interface font; defaults to the app's shared controller.
/// A change rebuilds the themes in place, without a restart.
final AppFontController? fonts;
@override
Widget build(BuildContext context) {
final fonts = this.fonts ?? AppFontController.instance;
return ListenableBuilder(
listenable: fonts,
builder: (context, _) => _host(fonts.family),
);
}
Widget _host(String? fontFamily) {
final router = routerConfig;
if (cupertino ?? _platformIsCupertino) {
final theme = appCupertinoThemeWith(fontFamily: fontFamily);
if (router != null) {
return CupertinoApp.router(
title: 'Pipelines',
theme: appCupertinoTheme,
theme: theme,
routerConfig: router,
);
}
return CupertinoApp(
title: 'Pipelines',
theme: appCupertinoTheme,
theme: theme,
home: AdaptiveShell(
destinationBodies: destinationBodies,
cupertino: true,
@@ -60,16 +76,16 @@ class MyApp extends StatelessWidget {
if (router != null) {
return MaterialApp.router(
title: 'Pipelines',
theme: appLightTheme(),
darkTheme: appDarkTheme(),
theme: appLightTheme(fontFamily: fontFamily),
darkTheme: appDarkTheme(fontFamily: fontFamily),
themeMode: ThemeMode.system,
routerConfig: router,
);
}
return MaterialApp(
title: 'Pipelines',
theme: appLightTheme(),
darkTheme: appDarkTheme(),
theme: appLightTheme(fontFamily: fontFamily),
darkTheme: appDarkTheme(fontFamily: fontFamily),
themeMode: ThemeMode.system,
home: AdaptiveShell(
destinationBodies: destinationBodies,
+11
View File
@@ -6,6 +6,8 @@ import 'app_url_strategy.dart';
import 'pipelines_root.dart';
import 'server_endpoint.dart';
import '../features/settings/settings_store.dart';
import '../ui/theme/app_font_controller.dart';
import '../ui/theme/app_font_licenses.dart';
/// Native builds must supply their server explicitly; there is no baked host.
const configuredServerUrl = String.fromEnvironment('PIPELINES_SERVER_URL');
@@ -38,6 +40,10 @@ Future<ServerEndpoint> resolveLaunchServer({
);
}
/// How long the first frame waits for a stored font before drawing in the
/// system font.
const appFontStartupWait = Duration(milliseconds: 1500);
/// Resolves the endpoint for this launch and starts the normal composition.
Future<void> runPipelinesApp({
Uri? base,
@@ -46,8 +52,13 @@ Future<void> runPipelinesApp({
}) async {
useAppUrlStrategy();
WidgetsFlutterBinding.ensureInitialized();
registerAppFontLicenses();
// The device's chosen font loads beside the session; a slow download does
// not hold the first frame, and applies when it lands.
final font = AppFontController.instance.restore(wait: appFontStartupWait);
// A phone behind the web login reconnects with its kept session.
await ServerSession.load();
await font;
final server = await resolveLaunchServer(
base: base,
configured: configured,
+19 -14
View File
@@ -14,6 +14,7 @@ import '../features/onboarding/onboarding_flow.dart';
import '../features/settings/server_connections.dart';
import '../features/settings/saved_servers_section.dart';
import '../features/settings/settings_store.dart';
import '../ui/theme/app_font_controller.dart';
import '../ui/theme/app_theme.dart';
import 'pipelines_app.dart';
import 'server_endpoint.dart';
@@ -294,19 +295,23 @@ class _PipelinesRootState extends State<PipelinesRoot> {
_servers.catalog.active?.endpoints.map(Uri.parse).toList() ??
const [],
);
return _cupertino
? CupertinoApp(
title: 'Pipelines',
theme: appCupertinoTheme,
debugShowCheckedModeBanner: false,
home: flow,
)
: MaterialApp(
title: 'Pipelines',
theme: appLightTheme(),
darkTheme: appDarkTheme(),
debugShowCheckedModeBanner: false,
home: flow,
);
final fonts = AppFontController.instance;
return ListenableBuilder(
listenable: fonts,
builder: (context, _) => _cupertino
? CupertinoApp(
title: 'Pipelines',
theme: appCupertinoThemeWith(fontFamily: fonts.family),
debugShowCheckedModeBanner: false,
home: flow,
)
: MaterialApp(
title: 'Pipelines',
theme: appLightTheme(fontFamily: fonts.family),
darkTheme: appDarkTheme(fontFamily: fonts.family),
debugShowCheckedModeBanner: false,
home: flow,
),
);
}
}
@@ -0,0 +1,139 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../ui/theme/app_font.dart';
import '../../ui/theme/app_font_controller.dart';
import 'settings_group.dart';
import 'settings_row.dart';
import 'settings_theme.dart';
const fontSectionTitle = 'Font';
const fontSectionFooter =
'Saved on this device only. Code keeps its monospace font.';
const fontLoadingText = 'Loading…';
const fontLoadFailedText = 'Could not load this font.';
const fontSaveFailedText = 'Not saved on this device; it applies until reload.';
ValueKey<String> settingsFontKey(AppFont font) =>
ValueKey<String>('settings-font-${font.id}');
/// The device's interface font: one row per option, each named in its own
/// face. Material rows are radio tiles, Cupertino rows carry the checkmark.
/// A choice is stored locally and applies as soon as its files load.
class SettingsFontSection extends StatefulWidget {
const SettingsFontSection({super.key, required this.controller});
final AppFontController controller;
@override
State<SettingsFontSection> createState() => _SettingsFontSectionState();
}
class _SettingsFontSectionState extends State<SettingsFontSection> {
@override
void initState() {
super.initState();
_preview();
}
@override
void didUpdateWidget(SettingsFontSection oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) _preview();
}
/// Only the regular weight of each option, only once Settings is shown.
void _preview() {
for (final font in AppFont.values) {
unawaited(widget.controller.preview(font));
}
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.controller,
builder: (context, _) => _group(context),
);
Widget _group(BuildContext context) {
final controller = widget.controller;
final cupertino = usesCupertinoControls(context);
final group = SettingsGroup(
title: fontSectionTitle,
footer: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const Text(fontSectionFooter),
if (controller.saveFailed)
Text(
fontSaveFailedText,
style: TextStyle(color: settingsErrorColor(context)),
),
],
),
children: <Widget>[
for (final font in AppFont.values)
cupertino
? _cupertinoRow(context, font)
: RadioListTile<AppFont>(
key: settingsFontKey(font),
value: font,
title: _name(context, font),
subtitle: _status(context, font),
),
],
);
if (cupertino) return group;
return RadioGroup<AppFont>(
groupValue: controller.selected,
onChanged: (font) {
if (font != null) unawaited(controller.select(font));
},
child: group,
);
}
Widget _cupertinoRow(BuildContext context, AppFont font) => SettingsRow(
key: settingsFontKey(font),
title: _name(context, font),
subtitle: _status(context, font),
trailing: widget.controller.selected == font
? Icon(
CupertinoIcons.check_mark,
color: CupertinoTheme.of(context).primaryColor,
)
: null,
onTap: () => unawaited(widget.controller.select(font)),
);
/// The option's name in its own face once its regular weight has loaded;
/// the system face until then (and always for the system option).
Widget _name(BuildContext context, AppFont font) {
final family = widget.controller.canPreview(font)
? font.family ?? _systemFamily(context)
: _systemFamily(context);
return Text(font.label, style: TextStyle(fontFamily: family));
}
Widget? _status(BuildContext context, AppFont font) {
final controller = widget.controller;
if (controller.selected != font) return null;
if (controller.loadFailed == font) {
return Text(
fontLoadFailedText,
style: TextStyle(color: settingsErrorColor(context)),
);
}
return controller.loading ? const Text(fontLoadingText) : null;
}
}
/// The platform's own interface family (Roboto, or the Cupertino system
/// face), independent of the font the theme currently applies.
String? _systemFamily(BuildContext context) => usesCupertinoControls(context)
? const CupertinoTextThemeData().textStyle.fontFamily
: Typography.material2021(
platform: Theme.of(context).platform,
).black.bodyLarge?.fontFamily;
@@ -10,6 +10,8 @@ import '../attention/notify/notification_controller.dart';
import 'default_endpoint.dart';
import 'settings_controller.dart';
import 'settings_controls.dart';
import 'settings_font_section.dart';
import '../../ui/theme/app_font_controller.dart';
import 'settings_group.dart';
import 'settings_page_body.dart';
import 'settings_notifications_section.dart';
@@ -53,8 +55,12 @@ class SettingsScreen extends StatefulWidget {
this.servers,
this.deliveryService,
this.deliveryServiceController,
this.fonts,
});
/// The device's interface font; defaults to the app's shared controller.
final AppFontController? fonts;
/// Android background delivery; hidden when absent or unsupported.
final NotificationServiceBridge? deliveryService;
final NotificationServiceController? deliveryServiceController;
@@ -190,6 +196,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
controller: _controller,
workspaceField: _workspaceField,
),
// A device-local choice: a browser and a phone keep their own.
SettingsFontSection(
controller: widget.fonts ?? AppFontController.instance,
),
if (widget.notifications case final notifications?)
SettingsNotificationsSection(controller: notifications),
if (widget.deliveryService case final service? when service.supported)
+82
View File
@@ -0,0 +1,82 @@
/// The interface typefaces a device can choose. [AppFont.system] keeps the
/// platform's own typography (Roboto on Android and the web, SF on iOS); every
/// other option is an open-licence (SIL OFL 1.1) family bundled under
/// `fonts/<directory>/` as plain assets, not under pubspec `fonts:`, so a web
/// page downloads only the family it actually shows.
enum AppFont {
system('system', 'System default', null, null, <String>[]),
inter('inter', 'Inter', 'Inter', 'inter', <String>[
'Inter-Regular.ttf',
'Inter-Medium.ttf',
'Inter-SemiBold.ttf',
'Inter-Bold.ttf',
]),
ibmPlexSans(
'ibm-plex-sans',
'IBM Plex Sans',
'IBM Plex Sans',
'ibm-plex-sans',
<String>[
'IBMPlexSans-Regular.ttf',
'IBMPlexSans-Medium.ttf',
'IBMPlexSans-SemiBold.ttf',
'IBMPlexSans-Bold.ttf',
],
),
sourceSans3(
'source-sans-3',
'Source Sans 3',
'Source Sans 3',
'source-sans-3',
<String>[
'SourceSans3-Regular.ttf',
'SourceSans3-Medium.ttf',
'SourceSans3-Semibold.ttf',
'SourceSans3-Bold.ttf',
],
),
atkinsonHyperlegible(
'atkinson-hyperlegible-next',
'Atkinson Hyperlegible Next',
'Atkinson Hyperlegible Next',
'atkinson-hyperlegible-next',
<String>[
'AtkinsonHyperlegibleNext-Regular.ttf',
'AtkinsonHyperlegibleNext-Medium.ttf',
'AtkinsonHyperlegibleNext-SemiBold.ttf',
'AtkinsonHyperlegibleNext-Bold.ttf',
],
);
const AppFont(this.id, this.label, this.family, this._directory, this._files);
/// The stored value. Stable across releases; never the display label.
final String id;
/// The picker's name for the option.
final String label;
/// The registered family name; null keeps the platform typography.
final String? family;
final String? _directory;
final List<String> _files;
/// Every weight's asset (400, 500, 600 and 700, in that order).
List<String> get assets => <String>[
for (final file in _files) 'fonts/$_directory/$file',
];
/// The regular weight alone: enough to preview the option's name.
String? get previewAsset => _files.isEmpty ? null : assets.first;
/// The licence shipped beside the files.
String? get licenseAsset =>
_directory == null ? null : 'fonts/$_directory/OFL.txt';
/// The option a stored id names; an unknown or missing id is the default.
static AppFont fromId(String? id) => AppFont.values.firstWhere(
(font) => font.id == id,
orElse: () => AppFont.system,
);
}
+156
View File
@@ -0,0 +1,156 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'app_font.dart';
import 'app_font_store.dart';
/// Registers [assets] under [family]. Production reads them from the bundle;
/// tests substitute a recorder.
typedef AppFontAssetLoader =
Future<void> Function(String family, List<String> assets);
/// Loads bundled font files on demand with a [FontLoader]. On the web each
/// asset is fetched only now, when its family is first previewed or chosen.
Future<void> loadBundledFontAssets(String family, List<String> assets) async {
final loader = FontLoader(family);
for (final asset in assets) {
loader.addFont(rootBundle.load(asset));
}
await loader.load();
}
/// The device's interface font: the stored choice, the family the theme
/// actually uses, and the on-demand loading between the two.
///
/// The theme keeps the previous family (at first the platform's) until the
/// chosen files are registered, then switches once; text never lays out in a
/// family that has not loaded, so nothing reflows more than once.
class AppFontController extends ChangeNotifier {
AppFontController({
this._store = const SharedPreferencesAppFontStore(),
this._loader = loadBundledFontAssets,
});
/// The app's own controller: one per running app, shared by the theme
/// hosts and the Settings picker.
static final AppFontController instance = AppFontController();
final AppFontStore _store;
final AppFontAssetLoader _loader;
final Map<String, Future<void>> _assetLoads = <String, Future<void>>{};
final Set<String> _loadedAssets = <String>{};
AppFont _selected = AppFont.system;
AppFont _applied = AppFont.system;
bool _saveFailed = false;
AppFont? _loadFailed;
/// The option the picker shows as chosen.
AppFont get selected => _selected;
/// The option the theme uses now.
AppFont get applied => _applied;
/// The theme's family; null keeps the platform typography.
String? get family => _applied.family;
/// The chosen family's files are still downloading.
bool get loading => _selected != _applied && _loadFailed != _selected;
/// The last choice could not be stored on this device.
bool get saveFailed => _saveFailed;
/// The chosen family's files could not be loaded; the theme kept [applied].
AppFont? get loadFailed => _loadFailed;
/// Whether [font]'s regular weight is registered, so its name can be drawn
/// in its own face.
bool canPreview(AppFont font) =>
font.previewAsset == null || _loadedAssets.contains(font.previewAsset);
/// Reads the stored choice and starts loading it. With [wait], returns once
/// it is applied or after [wait], whichever is first; a slower load still
/// applies when it finishes.
Future<void> restore({Duration? wait}) async {
final font = await _store.load();
if (font == AppFont.system || font == _selected) return;
_selected = font;
notifyListeners();
final applying = _apply(font);
if (wait == null) return applying;
await Future.any<void>(<Future<void>>[
applying,
Future<void>.delayed(wait),
]);
}
/// Chooses [font], stores it, and applies it once its files are loaded.
Future<void> select(AppFont font) async {
if (font == _selected && _loadFailed != font) return;
_selected = font;
_loadFailed = null;
notifyListeners();
final saved = await _store.save(font);
if (saved == _saveFailed) {
_saveFailed = !saved;
notifyListeners();
}
await _apply(font);
}
/// Loads [font]'s regular weight for its picker row. Failures are quiet: the
/// row keeps the current face and choosing it reports the problem.
Future<void> preview(AppFont font) async {
final asset = font.previewAsset;
final family = font.family;
if (asset == null || family == null || _loadedAssets.contains(asset)) {
return;
}
try {
await _ensure(family, <String>[asset]);
} catch (_) {
return;
}
notifyListeners();
}
Future<void> _apply(AppFont font) async {
final family = font.family;
if (family != null) {
try {
await _ensure(family, font.assets);
} catch (_) {
if (_selected == font) {
_loadFailed = font;
notifyListeners();
}
return;
}
}
// A later choice supersedes this one.
if (_selected != font || _applied == font) return;
_applied = font;
notifyListeners();
}
/// Registers the assets not yet loaded or loading, in one [FontLoader], and
/// waits for all of [assets]. A failed asset can be retried.
Future<void> _ensure(String family, List<String> assets) {
final missing = assets.where((a) => !_assetLoads.containsKey(a)).toList();
if (missing.isNotEmpty) {
final load = _loader(family, missing);
for (final asset in missing) {
_assetLoads[asset] = load.then(
(_) => _loadedAssets.add(asset),
onError: (Object error, StackTrace stack) {
_assetLoads.remove(asset);
Error.throwWithStackTrace(error, stack);
},
);
}
}
return Future.wait(assets.map((a) => _assetLoads[a]!));
}
}
+23
View File
@@ -0,0 +1,23 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'app_font.dart';
bool _registered = false;
/// Adds each bundled interface font's SIL Open Font License to the
/// [LicenseRegistry]. The texts are read from the bundle only when a licence
/// page asks for them.
void registerAppFontLicenses() {
if (_registered) return;
_registered = true;
LicenseRegistry.addLicense(() async* {
for (final font in AppFont.values) {
final asset = font.licenseAsset;
if (asset == null) continue;
yield LicenseEntryWithLineBreaks(<String>[
font.label,
], await rootBundle.loadString(asset));
}
});
}
+60
View File
@@ -0,0 +1,60 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'app_font.dart';
/// The device's font choice. It lives in this device's (or browser's) own
/// preferences and is never sent to a server, so a phone and a browser signed
/// in to the same server keep their own choice.
const String appFontKey = 'pipelines.next.font.v1';
/// The persistence seam for the font choice.
abstract interface class AppFontStore {
Future<AppFont> load();
/// Whether the choice is actually stored.
Future<bool> save(AppFont font);
}
/// `shared_preferences` storage. An unavailable or unreadable store means the
/// default; a failed save returns false rather than throwing.
class SharedPreferencesAppFontStore implements AppFontStore {
const SharedPreferencesAppFontStore();
@override
Future<AppFont> load() async {
try {
final preferences = await SharedPreferences.getInstance();
return AppFont.fromId(preferences.getString(appFontKey));
} catch (_) {
return AppFont.system;
}
}
@override
Future<bool> save(AppFont font) async {
try {
final preferences = await SharedPreferences.getInstance();
return await preferences.setString(appFontKey, font.id);
} catch (_) {
return false;
}
}
}
/// An in-memory store for tests and fixtures.
class MemoryAppFontStore implements AppFontStore {
MemoryAppFontStore([this.font = AppFont.system]);
AppFont font;
bool failSaves = false;
@override
Future<AppFont> load() async => font;
@override
Future<bool> save(AppFont font) async {
if (failSaves) return false;
this.font = font;
return true;
}
}
+59 -6
View File
@@ -26,11 +26,20 @@ abstract final class AppColors {
const _seed = Color(0xFF6750A4);
ThemeData appLightTheme() => ThemeData(
platform: kIsWeb ? TargetPlatform.android : null,
colorScheme: ColorScheme.fromSeed(seedColor: _seed),
pageTransitionsTheme: appPageTransitions,
);
/// [fontFamily] replaces the platform family throughout the text themes
/// (Material's, and Cupertino's for Cupertino widgets on a Material host),
/// keeping every size, weight and the text scaling; null keeps the system
/// typography.
ThemeData appLightTheme({String? fontFamily}) {
final scheme = ColorScheme.fromSeed(seedColor: _seed);
return ThemeData(
platform: kIsWeb ? TargetPlatform.android : null,
colorScheme: scheme,
pageTransitionsTheme: appPageTransitions,
fontFamily: fontFamily,
cupertinoOverrideTheme: _cupertinoOverride(fontFamily, scheme),
);
}
/// Android and iOS keep their native transitions and interactive back gestures.
/// Desktop hosts use the short horizontal slide.
@@ -80,7 +89,7 @@ class FastSlidePageTransitionsBuilder extends PageTransitionsBuilder {
}
/// Material's dark scheme with gray surfaces stepping up from the page.
ThemeData appDarkTheme() {
ThemeData appDarkTheme({String? fontFamily}) {
final scheme =
ColorScheme.fromSeed(
seedColor: _seed,
@@ -100,6 +109,8 @@ ThemeData appDarkTheme() {
colorScheme: scheme,
scaffoldBackgroundColor: scheme.surface,
pageTransitionsTheme: appPageTransitions,
fontFamily: fontFamily,
cupertinoOverrideTheme: _cupertinoOverride(fontFamily, scheme),
);
}
@@ -107,3 +118,45 @@ const appCupertinoTheme = CupertinoThemeData(
scaffoldBackgroundColor: AppColors.background,
barBackgroundColor: AppColors.bar,
);
/// [appCupertinoTheme] with every Cupertino text role in [fontFamily]; null
/// keeps the system typography.
CupertinoThemeData appCupertinoThemeWith({String? fontFamily}) =>
fontFamily == null
? appCupertinoTheme
: appCupertinoTheme.copyWith(textTheme: appCupertinoTextTheme(fontFamily));
/// The stock Cupertino text roles (sizes, weights, colours) in [fontFamily].
/// Action roles take [primaryColor], as the stock roles do.
CupertinoTextThemeData appCupertinoTextTheme(
String fontFamily, {
Color primaryColor = CupertinoColors.systemBlue,
}) {
final base = CupertinoTextThemeData(primaryColor: primaryColor);
TextStyle face(TextStyle style) => style.copyWith(fontFamily: fontFamily);
return CupertinoTextThemeData(
textStyle: face(base.textStyle),
actionTextStyle: face(base.actionTextStyle),
actionSmallTextStyle: face(base.actionSmallTextStyle),
tabLabelTextStyle: face(base.tabLabelTextStyle),
navTitleTextStyle: face(base.navTitleTextStyle),
navLargeTitleTextStyle: face(base.navLargeTitleTextStyle),
navActionTextStyle: face(base.navActionTextStyle),
pickerTextStyle: face(base.pickerTextStyle),
dateTimePickerTextStyle: face(base.dateTimePickerTextStyle),
);
}
/// Cupertino widgets on a Material host derive their theme from Material's;
/// only the family is overridden, with Material's primary for actions.
NoDefaultCupertinoThemeData? _cupertinoOverride(
String? fontFamily,
ColorScheme scheme,
) => fontFamily == null
? null
: CupertinoThemeData(
textTheme: appCupertinoTextTheme(
fontFamily,
primaryColor: scheme.primary,
),
);