Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(desktop): the terminal can use any installed font, monospaced first (#856)

0xken15e7ee09f2a5fb
diff --git a/desktop/lib/settings/sections/terminal_section.dart b/desktop/lib/settings/sections/terminal_section.dart
index fc6a3e796..a3852175c 100644
--- a/desktop/lib/settings/sections/terminal_section.dart
+++ b/desktop/lib/settings/sections/terminal_section.dart
@@ -9,6 +9,7 @@ import '../../shared/widgets/app_icon_button.dart';
import '../../shared/widgets/app_select_field.dart';
import '../../shared/widgets/setting_row.dart';
import '../../shortcuts/app_shortcuts.dart' show linuxKeyLabels;
+import '../../terminal/installed_fonts.dart';
import '../../terminal/terminal_font_store.dart';
import '../../terminal/terminal_theme.dart';
import '../../terminal/terminal_theme_store.dart';
@@ -69,7 +70,7 @@ class _Controls extends StatelessWidget {
const SizedBox(height: 10),
SettingRow(
title: 'Font',
- control: _FamilyField(family: terminalFontStore.family),
+ control: _FamilyField(selection: terminalFontStore.selection),
),
const SizedBox(height: 10),
SettingRow(
@@ -125,34 +126,72 @@ class _SchemeField extends StatelessWidget {
/// nearly indistinguishable in two glyphs, so it read as a stray mark in front
/// of every name rather than as a preview. The place a face can actually be
/// judged is [_Preview], at the size it will really be drawn.
-class _FamilyField extends StatelessWidget {
- const _FamilyField({required this.family});
+class _FamilyField extends StatefulWidget {
+ const _FamilyField({required this.selection});
- final TerminalFontChoice family;
+ final TerminalFontSelection selection;
+
+ @override
+ State<_FamilyField> createState() => _FamilyFieldState();
+}
+
+class _FamilyFieldState extends State<_FamilyField> {
+ /// The families installed here, monospaced first — empty until the OS has answered, and for good
+ /// on the web, which draws only the face it bundles.
+ List<InstalledFont> _installed = const [];
+
+ @override
+ void initState() {
+ super.initState();
+ // Asked when Settings opens, not at launch: only this picker wants the answer.
+ unawaited(
+ listInstalledFonts().then((fonts) {
+ if (mounted) setState(() => _installed = fonts);
+ }),
+ );
+ }
+
+ /// The presets this OS has first (SF Mono stays the default), then every installed family —
+ /// monospaced before the rest, as [listInstalledFonts] orders them — then the current choice if
+ /// it is none of those. That last part matters: a `state.json` carried over from another computer
+ /// can name a face this one lacks, and [AppSelectField] draws a value it cannot find among its
+ /// options as an EMPTY field — so the user's chosen face would read as no choice at all.
+ List<TerminalFontSelection> _choices() {
+ final presets = [
+ for (final choice in TerminalFontChoice.available) PresetFont(choice),
+ ];
+ // An installed family a preset already offers (Menlo, Monaco…) is that preset, with its
+ // fallback chain — not a second row with the same name.
+ final taken = {
+ for (final preset in presets) ...[
+ preset.label.toLowerCase(),
+ preset.fontFamily.toLowerCase(),
+ ],
+ };
+ return {
+ ...presets,
+ for (final font in _installed)
+ if (!taken.contains(font.family.toLowerCase()))
+ InstalledFontFamily(font.family),
+ widget.selection,
+ }.toList();
+ }
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- return AppSelectField<TerminalFontChoice>(
+ return AppSelectField<TerminalFontSelection>(
key: const Key('terminal-font-family-dropdown'),
semanticLabel: 'Terminal font',
width: SettingRow.controlWidth,
- value: family,
- // The faces this OS actually has, plus whatever is selected. The second
- // half matters: a `state.json` carried over from a Mac selects a face
- // Linux does not offer, and [AppSelectField] draws a value it cannot find
- // among its options as an EMPTY field — so the user's chosen face would
- // read as no choice at all. Showing it, rather than silently rewriting
- // what they picked, keeps the pane honest about what is on.
- //
- // (Material's `DropdownButton` asserts instead of blanking. This app does
- // not use it — see [AppSelectField] — but the list has to be right for
- // the same reason either way.)
+ value: widget.selection,
+ // A few hundred families on a typical Mac: typing narrows the list.
+ filterable: true,
options: [
- for (final choice in {...TerminalFontChoice.available, family})
+ for (final choice in _choices())
SelectOption(value: choice, label: choice.label),
],
- onChanged: (choice) => unawaited(terminalFontStore.setFamily(choice)),
+ onChanged: (choice) => unawaited(terminalFontStore.setSelection(choice)),
);
}
}
diff --git a/desktop/lib/terminal/installed_fonts.dart b/desktop/lib/terminal/installed_fonts.dart
new file mode 100644
index 000000000..57eecad9f
--- /dev/null
+++ b/desktop/lib/terminal/installed_fonts.dart
@@ -0,0 +1,151 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+
+import '../core/runtime_platform.dart';
+import '../core/test_run.dart';
+
+/// One font family installed on this computer, for the terminal font picker.
+class InstalledFont {
+ const InstalledFont(this.family, {required this.monospace});
+
+ final String family;
+
+ /// Every glyph the same width — a face the terminal grid can be drawn in without columns drifting.
+ final bool monospace;
+
+ @override
+ bool operator ==(Object other) =>
+ other is InstalledFont &&
+ other.family == family &&
+ other.monospace == monospace;
+
+ @override
+ int get hashCode => Object.hash(family, monospace);
+
+ @override
+ String toString() => 'InstalledFont($family, monospace: $monospace)';
+}
+
+/// Reads the installed families from the OS. Swapped out in tests.
+typedef FontLister = Future<List<InstalledFont>> Function();
+
+/// The font families installed on this computer, monospaced first, then by name.
+///
+/// Asked once and kept: the answer only changes when somebody installs a font, and the picker is
+/// the only reader. A failure answers an empty list — the picker still has its presets — and is
+/// not cached, so the next open asks again.
+///
+/// - macOS: `NSFontManager` over `harness/fonts` (`macos/Runner/MainFlutterWindow.swift`), which
+/// also says which families are monospaced. (`system_profiler`, what Orca uses, takes ~10s and
+/// cannot.)
+/// - Linux: `fc-list : family spacing`, where `spacing=100` is monospaced.
+/// - Web and anything else: nothing — the browser build draws only the font it bundles.
+Future<List<InstalledFont>> listInstalledFonts() {
+ final cached = _cached;
+ if (cached != null) return cached;
+ final load = _load();
+ _cached = load;
+ // An empty answer (a failure, or nothing to ask) is not remembered: the next open asks again.
+ unawaited(
+ load.then((fonts) {
+ if (fonts.isEmpty && identical(_cached, load)) _cached = null;
+ }),
+ );
+ return load;
+}
+
+Future<List<InstalledFont>>? _cached;
+
+/// Replaces how fonts are read, and forgets what was read. Tests only.
+FontLister? debugFontLister;
+void debugResetInstalledFonts() => _cached = null;
+
+Future<List<InstalledFont>> _load() async {
+ try {
+ // Under `flutter test` the OS is never asked — no channel handler answers there, and a test
+ // that wants fonts says which with [debugFontLister].
+ final lister =
+ debugFontLister ??
+ (kUnderTest
+ ? null
+ : RuntimePlatform.isMacOS
+ ? _listMacFonts
+ : RuntimePlatform.isLinux
+ ? _listLinuxFonts
+ : null);
+ if (lister == null) return const [];
+ return sortInstalledFonts(
+ await lister().timeout(const Duration(seconds: 10)),
+ );
+ } catch (_) {
+ return const [];
+ }
+}
+
+const _channel = MethodChannel('harness/fonts');
+
+Future<List<InstalledFont>> _listMacFonts() async {
+ final raw = await _channel.invokeListMethod<Object?>('listFonts') ?? const [];
+ return [
+ for (final entry in raw)
+ if (entry is Map && entry['family'] is String)
+ InstalledFont(
+ entry['family'] as String,
+ monospace: entry['mono'] == true,
+ ),
+ ];
+}
+
+Future<List<InstalledFont>> _listLinuxFonts() async {
+ final result = await Process.run('fc-list', [
+ ':',
+ 'family',
+ 'spacing',
+ ]).timeout(const Duration(seconds: 5));
+ if (result.exitCode != 0) return const [];
+ return parseFcList(result.stdout as String);
+}
+
+/// Reads `fc-list : family spacing` output: one line per face, e.g.
+/// `DejaVu Sans Mono:spacing=100` or `Noto Sans,Noto Sans Display:` (no spacing ⇒ proportional).
+/// A face listing several names is filed under its first. A family is monospaced when any of its
+/// faces is `spacing=100`; dual-width (`90`, CJK) and charcell (`110`) are not.
+List<InstalledFont> parseFcList(String output) {
+ final monospace = <String, bool>{};
+ for (final line in output.split('\n')) {
+ final trimmed = line.trim();
+ if (trimmed.isEmpty) continue;
+ final colon = trimmed.indexOf(':');
+ final names = colon < 0 ? trimmed : trimmed.substring(0, colon);
+ final family = names.split(',').first.trim();
+ if (family.isEmpty || family.startsWith('.')) continue;
+ final isMono =
+ colon >= 0 && trimmed.substring(colon).contains('spacing=100');
+ monospace[family] = (monospace[family] ?? false) || isMono;
+ }
+ return [
+ for (final entry in monospace.entries)
+ InstalledFont(entry.key, monospace: entry.value),
+ ];
+}
+
+/// One entry per family (monospaced wins), monospaced families first, each half by name.
+List<InstalledFont> sortInstalledFonts(Iterable<InstalledFont> fonts) {
+ final byFamily = <String, bool>{};
+ for (final font in fonts) {
+ final family = font.family.trim();
+ if (family.isEmpty || family.startsWith('.')) continue;
+ byFamily[family] = (byFamily[family] ?? false) || font.monospace;
+ }
+ final sorted = [
+ for (final entry in byFamily.entries)
+ InstalledFont(entry.key, monospace: entry.value),
+ ];
+ sorted.sort((a, b) {
+ if (a.monospace != b.monospace) return a.monospace ? -1 : 1;
+ return a.family.toLowerCase().compareTo(b.family.toLowerCase());
+ });
+ return sorted;
+}
diff --git a/desktop/lib/terminal/terminal_font_store.dart b/desktop/lib/terminal/terminal_font_store.dart
index d822bf483..c0d506c65 100644
--- a/desktop/lib/terminal/terminal_font_store.dart
+++ b/desktop/lib/terminal/terminal_font_store.dart
@@ -95,6 +95,92 @@ enum TerminalFontChoice {
kIsWeb ? robotoMono : (hasAppleFonts ? sfMono : dejaVuSansMono);
}
+/// What the terminal is drawn in: one of the [TerminalFontChoice] presets, or any family installed on
+/// this computer (`installed_fonts.dart`).
+///
+/// The presets stay because they carry what a bare family name cannot: SF Mono is reached through
+/// a CoreText alias, and each has a fallback chain chosen for its platform. An installed family gets
+/// the platform's default chain behind it, so a glyph it lacks — a Vietnamese tone mark, a box
+/// drawing — still comes from a monospaced face.
+sealed class TerminalFontSelection {
+ const TerminalFontSelection();
+
+ String get fontFamily;
+ List<String> get fontFamilyFallback;
+ String get label;
+
+ /// How the choice is saved: a preset by its enum name (what every older build wrote), an
+ /// installed family as `font:<family>`.
+ String get storageKey;
+
+ static const _installedPrefix = 'font:';
+
+ /// The selection a saved [storageKey] names, or null when it names nothing this build knows.
+ static TerminalFontSelection? fromStorage(String? saved) {
+ if (saved == null || saved.isEmpty) return null;
+ if (saved.startsWith(_installedPrefix)) {
+ final family = saved.substring(_installedPrefix.length).trim();
+ if (family.isEmpty || kIsWeb) return null;
+ return InstalledFontFamily(family);
+ }
+ final preset = TerminalFontChoice.values
+ .where(
+ (c) =>
+ c.name == saved &&
+ (!kIsWeb || c == TerminalFontChoice.robotoMono),
+ )
+ .firstOrNull;
+ return preset == null ? null : PresetFont(preset);
+ }
+}
+
+final class PresetFont extends TerminalFontSelection {
+ const PresetFont(this.choice);
+
+ final TerminalFontChoice choice;
+
+ @override
+ String get fontFamily => choice.fontFamily;
+ @override
+ List<String> get fontFamilyFallback => choice.fontFamilyFallback;
+ @override
+ String get label => choice.label;
+ @override
+ String get storageKey => choice.name;
+
+ @override
+ bool operator ==(Object other) =>
+ other is PresetFont && other.choice == choice;
+ @override
+ int get hashCode => choice.hashCode;
+}
+
+final class InstalledFontFamily extends TerminalFontSelection {
+ const InstalledFontFamily(this.family);
+
+ final String family;
+
+ @override
+ String get fontFamily => family;
+
+ /// The platform default first (on a Mac, SF Mono through its alias), then its own chain.
+ @override
+ List<String> get fontFamilyFallback => [
+ terminalFontFamily,
+ ...terminalFontFallback,
+ ];
+ @override
+ String get label => family;
+ @override
+ String get storageKey => '${TerminalFontSelection._installedPrefix}$family';
+
+ @override
+ bool operator ==(Object other) =>
+ other is InstalledFontFamily && other.family == family;
+ @override
+ int get hashCode => family.hashCode;
+}
+
/// The user's chosen terminal typography (family + size), remembered across
/// launches.
///
@@ -114,7 +200,12 @@ enum TerminalFontChoice {
class TerminalFontStore extends ValueNotifier<TerminalStyle> {
TerminalFontStore({LocalKeyValueStore? storage})
: _storage = storage ?? HarnessFileStore.shared,
- super(_styleFor(TerminalFontChoice.defaultForPlatform, terminalFontSize));
+ super(_styleFor(_defaultSelection, terminalFontSize));
+
+ static TerminalFontSelection get _defaultSelection =>
+ PresetFont(TerminalFontChoice.defaultForPlatform);
+
+ TerminalFontSelection _selection = _defaultSelection;
static const _familyKey = 'terminal_font_family';
static const _sizeKey = 'terminal_font_size';
@@ -128,22 +219,28 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
final LocalKeyValueStore _storage;
- static final _cache = <(TerminalFontChoice, double), TerminalStyle>{};
- static TerminalStyle _styleFor(TerminalFontChoice choice, double size) =>
- _cache.putIfAbsent(
- (choice, size),
- () => TerminalStyle(
- fontSize: size,
- fontFamily: choice.fontFamily,
- fontFamilyFallback: choice.fontFamilyFallback,
- ),
- );
-
- TerminalFontChoice get family => TerminalFontChoice.values.firstWhere(
- (choice) => choice.fontFamily == value.fontFamily,
- orElse: () => TerminalFontChoice.defaultForPlatform,
+ static final _cache = <(TerminalFontSelection, double), TerminalStyle>{};
+ static TerminalStyle _styleFor(
+ TerminalFontSelection selection,
+ double size,
+ ) => _cache.putIfAbsent(
+ (selection, size),
+ () => TerminalStyle(
+ fontSize: size,
+ fontFamily: selection.fontFamily,
+ fontFamilyFallback: selection.fontFamilyFallback,
+ ),
);
+ /// What the terminal is drawn in now — a preset or an installed family.
+ TerminalFontSelection get selection => _selection;
+
+ /// The preset in use, or null while an installed family is.
+ TerminalFontChoice? get family => switch (_selection) {
+ PresetFont(:final choice) => choice,
+ InstalledFontFamily() => null,
+ };
+
double get size => value.fontSize;
/// Read the saved choice, if there is one. Failure (or a stale/unknown
@@ -152,51 +249,47 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
Future<void> load() async {
try {
final saved = await _storage.readMany([_familyKey, _sizeKey]);
- final savedFamily = saved[_familyKey];
final savedSize = saved[_sizeKey];
- final choice = TerminalFontChoice.values
- .where(
- (c) =>
- c.name == savedFamily &&
- (!kIsWeb || c == TerminalFontChoice.robotoMono),
- )
- .firstOrNull;
+ // An installed family is not checked for still being installed: that would hold up start-up
+ // on a font scan, and a family that has gone renders through its fallback chain anyway.
+ _selection =
+ TerminalFontSelection.fromStorage(saved[_familyKey]) ??
+ _defaultSelection;
final size = savedSize == null ? null : double.tryParse(savedSize);
- value = _styleFor(
- choice ?? TerminalFontChoice.defaultForPlatform,
- _clamp(size ?? terminalFontSize),
- );
+ value = _styleFor(_selection, _clamp(size ?? terminalFontSize));
} catch (_) {
- value = _styleFor(
- TerminalFontChoice.defaultForPlatform,
- terminalFontSize,
- );
+ _selection = _defaultSelection;
+ value = _styleFor(_selection, terminalFontSize);
}
}
- Future<void> setFamily(TerminalFontChoice choice) => _set(choice, size);
+ Future<void> setFamily(TerminalFontChoice choice) =>
+ _set(PresetFont(choice), size);
+
+ /// Draw the terminal in [selection] — a preset or a family installed here.
+ Future<void> setSelection(TerminalFontSelection selection) =>
+ _set(selection, size);
- Future<void> increaseSize() => _set(family, size + _step);
- Future<void> decreaseSize() => _set(family, size - _step);
- Future<void> setSize(double size) => _set(family, size);
+ Future<void> increaseSize() => _set(_selection, size + _step);
+ Future<void> decreaseSize() => _set(_selection, size - _step);
+ Future<void> setSize(double size) => _set(_selection, size);
- Future<void> reset() =>
- _set(TerminalFontChoice.defaultForPlatform, terminalFontSize);
+ Future<void> reset() => _set(_defaultSelection, terminalFontSize);
/// Whether the current pick *is* the default — what [reset] would leave the
/// store at, so a Reset control can say it has nothing to do.
bool get isDefault =>
- family == TerminalFontChoice.defaultForPlatform &&
- size == terminalFontSize;
+ _selection == _defaultSelection && size == terminalFontSize;
double _clamp(double size) => size.clamp(minSize, maxSize);
- Future<void> _set(TerminalFontChoice choice, double size) async {
- final next = _styleFor(choice, _clamp(size));
+ Future<void> _set(TerminalFontSelection selection, double size) async {
+ final next = _styleFor(selection, _clamp(size));
+ _selection = selection;
if (next == value) return;
value = next;
try {
- await _storage.write(_familyKey, choice.name);
+ await _storage.write(_familyKey, selection.storageKey);
await _storage.write(_sizeKey, next.fontSize.toString());
} catch (_) {
// Kept in memory for this run; see load()'s doc.
diff --git a/desktop/macos/Runner/MainFlutterWindow.swift b/desktop/macos/Runner/MainFlutterWindow.swift
index 2e260d592..197684e4b 100644
--- a/desktop/macos/Runner/MainFlutterWindow.swift
+++ b/desktop/macos/Runner/MainFlutterWindow.swift
@@ -15,10 +15,16 @@ private let kMenuChannel = "harness/app_menu"
/// holds (`readFilePaths`), which Flutter's `Clipboard` cannot see either.
private let kClipboardImageChannel = "harness/clipboard_image"
+/// Channel Dart asks for the font families installed on this Mac, for the terminal font picker
+/// (`lib/terminal/installed_fonts.dart`). `NSFontManager` answers in a fraction of a second where
+/// `system_profiler SPFontsDataType` takes ~10s, and it can say which families are monospaced.
+private let kFontsChannel = "harness/fonts"
+
class MainFlutterWindow: NSWindow {
private var swarmTitlebar: SwarmTitlebar?
private var menuChannel: FlutterMethodChannel?
private var clipboardImageChannel: FlutterMethodChannel?
+ private var fontsChannel: FlutterMethodChannel?
private var notifications: HarnessNotifications?
override func awakeFromNib() {
@@ -35,6 +41,7 @@ class MainFlutterWindow: NSWindow {
)
swarmTitlebar = SwarmTitlebar(window: self, messenger: flutterViewController.engine.binaryMessenger)
installClipboardImageChannel(messenger: flutterViewController.engine.binaryMessenger)
+ installFontsChannel(messenger: flutterViewController.engine.binaryMessenger)
notifications = HarnessNotifications(messenger: flutterViewController.engine.binaryMessenger)
// Flutter's own theme does not reach AppKit — every native surface (the
@@ -323,6 +330,57 @@ class MainFlutterWindow: NSWindow {
menuChannel?.invokeMethod("resetTerminalFontSize", arguments: nil)
}
+ private func installFontsChannel(messenger: FlutterBinaryMessenger) {
+ let channel = FlutterMethodChannel(name: kFontsChannel, binaryMessenger: messenger)
+ channel.setMethodCallHandler { call, result in
+ guard call.method == "listFonts" else {
+ result(FlutterMethodNotImplemented)
+ return
+ }
+ DispatchQueue.global(qos: .userInitiated).async {
+ let fonts = MainFlutterWindow.installedFontFamilies()
+ DispatchQueue.main.async { result(fonts) }
+ }
+ }
+ fontsChannel = channel
+ }
+
+ /// Every installed family as `{family, mono}`, hidden system families (a leading `.`) left out.
+ ///
+ /// CoreText, not `NSFontManager`: this runs off the main thread so a large font catalog never
+ /// stalls the window, and AppKit's font manager is not documented safe there; CoreText is.
+ private static func installedFontFamilies() -> [[String: Any]] {
+ guard let names = CTFontManagerCopyAvailableFontFamilyNames() as? [String] else { return [] }
+ var fonts: [[String: Any]] = []
+ for family in names where !family.hasPrefix(".") {
+ let descriptor = CTFontDescriptorCreateWithAttributes(
+ [kCTFontFamilyNameAttribute: family] as CFDictionary)
+ let font = CTFontCreateWithFontDescriptor(descriptor, 12, nil)
+ fonts.append(["family": family, "mono": isMonospaced(font)])
+ }
+ return fonts
+ }
+
+ /// The font's own monospace trait, OR equal advances for `i`, `W` and `m` — some monospaced
+ /// families (Nerd Fonts among them) do not set the trait. A symbol font (Wingdings and the like)
+ /// is never monospaced here, whatever its advances: its letters are pictures.
+ private static func isMonospaced(_ font: CTFont) -> Bool {
+ let traits = CTFontGetSymbolicTraits(font)
+ let fontClass = CTFontStylisticClass(
+ rawValue: traits.rawValue & CTFontSymbolicTraits.traitClassMask.rawValue)
+ if fontClass == .classSymbolic { return false }
+ if traits.contains(.traitMonoSpace) { return true }
+ var characters = Array("iWm".utf16)
+ var glyphs = [CGGlyph](repeating: 0, count: characters.count)
+ guard CTFontGetGlyphsForCharacters(font, &characters, &glyphs, characters.count),
+ !glyphs.contains(0)
+ else { return false }
+ var advances = [CGSize](repeating: .zero, count: glyphs.count)
+ CTFontGetAdvancesForGlyphs(font, .horizontal, glyphs, &advances, glyphs.count)
+ guard let first = advances.first?.width, first > 0 else { return false }
+ return advances.allSatisfy { abs($0.width - first) < 0.01 }
+ }
+
private func installClipboardImageChannel(messenger: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(name: kClipboardImageChannel, binaryMessenger: messenger)
channel.setMethodCallHandler { call, result in
diff --git a/desktop/test/installed_fonts_test.dart b/desktop/test/installed_fonts_test.dart
new file mode 100644
index 000000000..767040a21
--- /dev/null
+++ b/desktop/test/installed_fonts_test.dart
@@ -0,0 +1,61 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/terminal/installed_fonts.dart';
+
+void main() {
+ tearDown(() {
+ debugFontLister = null;
+ debugResetInstalledFonts();
+ });
+
+ test('fc-list: spacing=100 is monospaced, a face with several names files under its first', () {
+ final fonts = parseFcList('''
+DejaVu Sans Mono:spacing=100
+DejaVu Sans Mono,DejaVu Sans Mono Bold:spacing=100
+Noto Sans,Noto Sans Display:
+Noto Sans CJK JP,Noto Sans CJK JP Regular:spacing=90
+Ubuntu Mono:spacing=100
+.Hidden System:spacing=100
+
+''');
+ expect(sortInstalledFonts(fonts), const [
+ InstalledFont('DejaVu Sans Mono', monospace: true),
+ InstalledFont('Ubuntu Mono', monospace: true),
+ InstalledFont('Noto Sans', monospace: false),
+ InstalledFont('Noto Sans CJK JP', monospace: false),
+ ]);
+ });
+
+ test('monospaced families first, each half by name, one row per family', () {
+ expect(
+ sortInstalledFonts(const [
+ InstalledFont('Helvetica', monospace: false),
+ InstalledFont('menlo', monospace: true),
+ InstalledFont('Arial', monospace: false),
+ InstalledFont('Andale Mono', monospace: true),
+ InstalledFont('Helvetica', monospace: false),
+ InstalledFont('', monospace: true),
+ ]),
+ const [
+ InstalledFont('Andale Mono', monospace: true),
+ InstalledFont('menlo', monospace: true),
+ InstalledFont('Arial', monospace: false),
+ InstalledFont('Helvetica', monospace: false),
+ ],
+ );
+ });
+
+ test('asks the OS once, and again only after a failure', () async {
+ var asked = 0;
+ debugFontLister = () async {
+ asked++;
+ if (asked == 1) throw StateError('no answer');
+ return const [InstalledFont('PT Mono', monospace: true)];
+ };
+ expect(await listInstalledFonts(), isEmpty);
+ expect(await listInstalledFonts(), const [
+ InstalledFont('PT Mono', monospace: true),
+ ]);
+ expect(await listInstalledFonts(), hasLength(1));
+ expect(asked, 2);
+ });
+}
diff --git a/desktop/test/terminal_font_store_test.dart b/desktop/test/terminal_font_store_test.dart
index 80833946b..0c1e38c43 100644
--- a/desktop/test/terminal_font_store_test.dart
+++ b/desktop/test/terminal_font_store_test.dart
@@ -140,4 +140,51 @@ void main() {
expect(store.family, TerminalFontChoice.defaultForPlatform);
},
);
+
+ test('an installed family is saved by name and comes back with its fallback chain', () async {
+ final storage = _FakeStore();
+ final store = TerminalFontStore(storage: storage);
+ await store.setSelection(const InstalledFontFamily('JetBrains Mono'));
+
+ expect(storage.values['terminal_font_family'], 'font:JetBrains Mono');
+ expect(store.family, isNull);
+ expect(store.value.fontFamily, 'JetBrains Mono');
+ // A glyph the face lacks still comes from a monospaced one: the platform's default first.
+ expect(store.value.fontFamilyFallback, [
+ terminalFontFamily,
+ ...terminalFontFallback,
+ ]);
+ expect(store.isDefault, isFalse);
+
+ final reopened = TerminalFontStore(storage: storage);
+ await reopened.load();
+ expect(reopened.selection, const InstalledFontFamily('JetBrains Mono'));
+ expect(reopened.value.fontFamily, 'JetBrains Mono');
+
+ await reopened.reset();
+ expect(reopened.family, TerminalFontChoice.defaultForPlatform);
+ expect(reopened.isDefault, isTrue);
+ });
+
+ test(
+ 'the same choice is the same style object, preset or installed',
+ () async {
+ final store = TerminalFontStore(storage: _FakeStore());
+ await store.setSelection(const InstalledFontFamily('PT Mono'));
+ final first = store.value;
+ await store.setFamily(TerminalFontChoice.menlo);
+ await store.setSelection(const InstalledFontFamily('PT Mono'));
+ expect(identical(store.value, first), isTrue);
+ },
+ );
+
+ test(
+ 'an empty installed name in the file falls back to the default',
+ () async {
+ final storage = _FakeStore()..values['terminal_font_family'] = 'font: ';
+ final store = TerminalFontStore(storage: storage);
+ await store.load();
+ expect(store.family, TerminalFontChoice.defaultForPlatform);
+ },
+ );
}
diff --git a/desktop/test/terminal_settings_section_test.dart b/desktop/test/terminal_settings_section_test.dart
index 9dadf2114..c2a3510f5 100644
--- a/desktop/test/terminal_settings_section_test.dart
+++ b/desktop/test/terminal_settings_section_test.dart
@@ -10,6 +10,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/settings/sections/terminal_section.dart';
import 'package:harness/shared/theme/app_theme.dart';
import 'package:harness/shared/widgets/app_select_field.dart';
+import 'package:harness/terminal/installed_fonts.dart';
import 'package:harness/terminal/terminal_font_store.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
@@ -58,7 +59,7 @@ void main() {
expect(colors.label, 'Terminal colors');
expect(colors.value, terminalThemeStore.value.label);
expect(font.label, 'Terminal font');
- expect(font.value, terminalFontStore.family.label);
+ expect(font.value, terminalFontStore.selection.label);
} finally {
semantics.dispose();
}
@@ -107,6 +108,43 @@ void main() {
expect(find.text('Match app appearance'), findsWidgets);
});
+ testWidgets(
+ 'the font list is the presets, then installed monospaced faces, then the rest',
+ (tester) async {
+ debugResetInstalledFonts();
+ debugFontLister = () async => const [
+ InstalledFont('Helvetica', monospace: false),
+ InstalledFont('PT Mono', monospace: true),
+ // A preset by another route: offered once, as the preset with its fallback chain.
+ InstalledFont('Menlo', monospace: true),
+ InstalledFont('Andale Mono', monospace: true),
+ ];
+ addTearDown(() {
+ debugFontLister = null;
+ debugResetInstalledFonts();
+ });
+ tester.view.physicalSize = const Size(820 * 2, 700 * 2);
+ tester.view.devicePixelRatio = 2;
+ addTearDown(tester.view.reset);
+
+ await tester.pumpWidget(_host());
+ await tester.pumpAndSettle();
+
+ final field = tester.widget<AppSelectField<TerminalFontSelection>>(
+ find.byKey(const Key('terminal-font-family-dropdown')),
+ );
+ expect(field.filterable, isTrue);
+ expect(field.options.map((option) => option.label), [
+ for (final choice in TerminalFontChoice.available) choice.label,
+ 'Andale Mono',
+ 'PT Mono',
+ 'Helvetica',
+ ]);
+ // Read only — the store is the real singleton, see this file's header.
+ expect(field.value, terminalFontStore.selection);
+ },
+ );
+
testWidgets('the preview refuses the app-wide text scale', (tester) async {
// The fifth seam named in `appearance_section.dart`, and the one nothing
// guarded: the preview exists to show the size the TERMINAL will render