From 4e402a6c56ee7df033abf2c1ee10fb873c167ca6 Mon Sep 17 00:00:00 2001 From: vic-7945hx Date: Tue, 24 Nov 2026 15:17:01 +0800 Subject: [PATCH 1/4] fix(appearance): keep Linux code and terminal fonts monospaced --- lib/ide/terminal/terminal_render_theme.dart | 14 +++----- lib/theme/app_theme.dart | 14 ++++++-- test/theme/code_font_test.dart | 40 +++++++++++++++++++++ 3 files changed, 57 insertions(+), 11 deletions(-) diff --git a/lib/ide/terminal/terminal_render_theme.dart b/lib/ide/terminal/terminal_render_theme.dart index d175a3272..e6f2d6caa 100644 --- a/lib/ide/terminal/terminal_render_theme.dart +++ b/lib/ide/terminal/terminal_render_theme.dart @@ -416,16 +416,12 @@ ITheme vscodeTerminalTheme([TerminalColorTheme? theme]) => (theme ?? terminalColorTheme.value).toXtermTheme(); /// The terminal font, as VS Code's `getFont` resolves it without a -/// `terminal.integrated.fontFamily`: the editor's families (this app's -/// editor draws in [CodeFont.families]), then `monospace` and, on macOS, -/// AppleBraille. On Windows the app's fallbacks ([AppFonts.windowsFallbacks], -/// ending in `monospace`) follow them as the theme puts them. +/// `terminal.integrated.fontFamily`: the same stack as the editor and +/// `monospace` if it isn't in that stack, followed by AppleBraille on macOS. String vscodeTerminalFontFamily() { - final families = [ - ...CodeFont.families.value, - if (AppPlatform.isWindows) ...AppFonts.windowsFallbacks else 'monospace', - if (AppPlatform.isMacOS) 'AppleBraille', - ]; + final families = [AppFonts.mono, ...AppFonts.monoFallbacks]; + if (!families.contains('monospace')) families.add('monospace'); + if (AppPlatform.isMacOS) families.add('AppleBraille'); return families.map((f) => f.contains(' ') ? "'$f'" : f).join(', '); } diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart index aae99900d..c1d2303b2 100644 --- a/lib/theme/app_theme.dart +++ b/lib/theme/app_theme.dart @@ -256,11 +256,21 @@ abstract final class AppFonts { /// [CodeFont.families], which the user may change. static String get mono => CodeFont.families.value.first; - /// What code falls back on, in order: the families after [mono], then on - /// Windows [windowsFallbacks]. A family not installed is passed over. + /// What code falls back on: the remaining configured families, then the + /// platform's fallbacks. A family not installed is passed over. static List get monoFallbacks => [ ...CodeFont.families.value.skip(1), if (AppPlatform.isWindows) ...windowsFallbacks, + if (AppPlatform.isLinux) ..._linuxMonoFallbacks, + ]; + + /// The default code families need not be installed on Linux. Use common + /// system monospace families before Flutter falls back to its default face. + static const _linuxMonoFallbacks = [ + 'DejaVu Sans Mono', + 'Liberation Mono', + 'Noto Sans Mono', + 'monospace', ]; /// A style for code drawn at [size], as the code's size is moved (see diff --git a/test/theme/code_font_test.dart b/test/theme/code_font_test.dart index 0f8024284..1cb5cdc32 100644 --- a/test/theme/code_font_test.dart +++ b/test/theme/code_font_test.dart @@ -1,6 +1,8 @@ +import 'package:baocode/ide/terminal/terminal_render_metrics.dart'; import 'package:baocode/ide/terminal/terminal_render_theme.dart'; import 'package:baocode/theme/app_theme.dart'; import 'package:baocode/theme/code_font.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -59,6 +61,8 @@ void main() { test('the code style: the family, its fallbacks and the size; ligatures ' 'come with it', () { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); CodeFont.families.value = ['Iosevka', 'Menlo']; CodeFont.size.value = 16; final style = AppFonts.codeStyle(13); @@ -70,6 +74,42 @@ void main() { expect(AppFonts.codeStyle(13).fontFeatures, isNotNull); }); + test( + 'Linux code and terminal share an explicit monospace fallback stack', + () { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const systemFamilies = [ + 'DejaVu Sans Mono', + 'Liberation Mono', + 'Noto Sans Mono', + 'monospace', + ]; + + for (final configured in [ + CodeFont.defaultFamilies, + ['Custom Font', 'Custom Fallback'], + ]) { + CodeFont.families.value = configured; + final style = AppFonts.codeStyle(13); + expect(style.fontFamily, configured.first); + expect(style.fontFamilyFallback, [ + ...configured.skip(1), + ...systemFamilies, + ]); + expect( + AppFonts.uiCodeStyle(13).fontFamilyFallback, + style.fontFamilyFallback, + ); + expect(parseFontFamilies(vscodeTerminalFontFamily()), [ + ...configured, + ...systemFamilies, + ]); + expect(CodeFont.families.value, configured); + } + }, + ); + test('ligatures are on unless settings.json says off, and off turns ' 'their features off', () { expect(CodeFont.parseLigatures(null), isTrue); From 21e6958bc3d62649f0ffba0e714d7cfb4b3370b7 Mon Sep 17 00:00:00 2001 From: vic-7945hx Date: Wed, 25 Nov 2026 12:45:44 +0800 Subject: [PATCH 2/4] fix(appearance): resolve Linux code fonts before Skia fallback --- lib/ide/terminal/terminal_instance.dart | 3 + lib/main.dart | 3 + lib/settings/pages/appearance_page.dart | 3 + lib/theme/app_theme.dart | 25 +++----- lib/theme/linux_code_fonts.dart | 82 +++++++++++++++++++++++++ linux/runner/CMakeLists.txt | 2 + linux/runner/my_application.cc | 54 +++++++++++++++- test/theme/linux_code_fonts_test.dart | 63 +++++++++++++++++++ 8 files changed, 218 insertions(+), 17 deletions(-) create mode 100644 lib/theme/linux_code_fonts.dart create mode 100644 test/theme/linux_code_fonts_test.dart diff --git a/lib/ide/terminal/terminal_instance.dart b/lib/ide/terminal/terminal_instance.dart index 6d29d0db4..1b1dbea4c 100644 --- a/lib/ide/terminal/terminal_instance.dart +++ b/lib/ide/terminal/terminal_instance.dart @@ -31,6 +31,7 @@ import 'package:path/path.dart' as p; import '../../settings/user_settings.dart'; import '../../theme/code_font.dart'; +import '../../theme/linux_code_fonts.dart'; import 'pty.dart'; import 'shell_integration/shell_integration.dart'; import 'shell_integration/shell_integration_injection.dart'; @@ -210,6 +211,7 @@ class TerminalInstance extends ChangeNotifier { ); _colorTheme.addListener(_updateTheme); CodeFont.families.addListener(_updateFont); + LinuxCodeFonts.resolved.addListener(_updateFont); source = TerminalCoreSource(terminal, decorationService: decorations); clipboard = TerminalClipboard( selection: selection, @@ -830,6 +832,7 @@ class TerminalInstance extends ChangeNotifier { _disposed = true; _colorTheme.removeListener(_updateTheme); CodeFont.families.removeListener(_updateFont); + LinuxCodeFonts.resolved.removeListener(_updateFont); if (!_exited) _pty?.kill(); unawaited(_printing?.cancel()); unawaited(_output.close()); diff --git a/lib/main.dart b/lib/main.dart index 582e87992..786d680b3 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -126,6 +126,7 @@ import 'telemetry/telemetry_service.dart'; import 'telemetry/telemetry_store.dart'; import 'theme/app_theme.dart'; import 'theme/code_font.dart'; +import 'theme/linux_code_fonts.dart'; import 'theme/pixel_snapped_text_scaler.dart'; import 'theme/ui_zoom.dart'; import 'theme/window_blur.dart'; @@ -208,6 +209,7 @@ Future main(List arguments) async { (key) => files.settings[key], ).timeout(const Duration(seconds: 1), onTimeout: () {}); followSettingsFiles(files); + await LinuxCodeFonts.start(); // The channel build's first start: set up before anything else shows. await _beginChannelSetup(files); _openChannelGate(files); @@ -884,6 +886,7 @@ class _BaoCodeAppState extends State /// windows' blur, which every surface over it is tinted for. static final Listenable _codeFont = Listenable.merge([ CodeFont.families, + LinuxCodeFonts.resolved, CodeFont.size, CodeFont.ligatures, WindowBlur.enabled, diff --git a/lib/settings/pages/appearance_page.dart b/lib/settings/pages/appearance_page.dart index 6d9e0e906..d9c1a0f66 100644 --- a/lib/settings/pages/appearance_page.dart +++ b/lib/settings/pages/appearance_page.dart @@ -27,6 +27,7 @@ import '../../l10n/l10n.dart'; import '../../platform/event_log.dart' show appEvent; import '../../theme/app_theme.dart'; import '../../theme/code_font.dart'; +import '../../theme/linux_code_fonts.dart'; import '../../theme/window_blur.dart'; import '../../theme/workbench_theme.dart' show ThemeSettingDefaults; import '../user_settings.dart'; @@ -403,6 +404,7 @@ class AppearanceSettingsPage extends StatelessWidget { WindowBlur.enabled, for (final role in PixelLoaderRole.values) ...[role.style, role.speed], CodeFont.families, + LinuxCodeFonts.resolved, CodeFont.size, CodeFont.ligatures, CodeFont.uiScale, @@ -827,6 +829,7 @@ class _TerminalFontPreview extends StatelessWidget { listenable: Listenable.merge([ terminalColorTheme, CodeFont.families, + LinuxCodeFonts.resolved, CodeFont.terminalSize, ]), builder: (context, _) { diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart index c1d2303b2..7fb5aead4 100644 --- a/lib/theme/app_theme.dart +++ b/lib/theme/app_theme.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../ide/terminal/terminal_colors.dart'; import '../platform/app_platform.dart'; import 'code_font.dart'; +import 'linux_code_fonts.dart'; import 'window_blur.dart'; import 'workbench_theme.dart' hide ColorScheme; @@ -252,25 +253,17 @@ abstract final class AppMetrics { } abstract final class AppFonts { - /// The font code, paths and commands are drawn in: the first of - /// [CodeFont.families], which the user may change. - static String get mono => CodeFont.families.value.first; + /// The primary code font, resolved to a registered face on Linux. + static String get mono => + LinuxCodeFonts.resolved.value?.first ?? CodeFont.families.value.first; - /// What code falls back on: the remaining configured families, then the - /// platform's fallbacks. A family not installed is passed over. + /// The other code fonts, followed by the platform's fallbacks. static List get monoFallbacks => [ - ...CodeFont.families.value.skip(1), + ...(LinuxCodeFonts.resolved.value?.skip(1) ?? + CodeFont.families.value.skip(1)), if (AppPlatform.isWindows) ...windowsFallbacks, - if (AppPlatform.isLinux) ..._linuxMonoFallbacks, - ]; - - /// The default code families need not be installed on Linux. Use common - /// system monospace families before Flutter falls back to its default face. - static const _linuxMonoFallbacks = [ - 'DejaVu Sans Mono', - 'Liberation Mono', - 'Noto Sans Mono', - 'monospace', + if (AppPlatform.isLinux && LinuxCodeFonts.resolved.value == null) + ...LinuxCodeFonts.fallbacks, ]; /// A style for code drawn at [size], as the code's size is moved (see diff --git a/lib/theme/linux_code_fonts.dart b/lib/theme/linux_code_fonts.dart new file mode 100644 index 000000000..8bb1378b5 --- /dev/null +++ b/lib/theme/linux_code_fonts.dart @@ -0,0 +1,82 @@ +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import '../platform/app_platform.dart'; +import 'code_font.dart'; + +/// Linux's Skia family lookup can pick a different face under a CJK locale. +/// Register the exact Fontconfig matches under private names, so the fix +/// applies only to code and never changes the window's font matching locale. +abstract final class LinuxCodeFonts { + static const fallbacks = [ + 'DejaVu Sans Mono', + 'Liberation Mono', + 'Noto Sans Mono', + 'monospace', + ]; + static const _channel = MethodChannel('baocode/window'); + static final _loaded = >{}; + static final _resolved = ValueNotifier?>(null); + static ValueListenable?> get resolved => _resolved; + + static Future start() async { + if (!AppPlatform.isLinux) return; + CodeFont.families.addListener(_refresh); + await _refresh(); + } + + static Future _refresh() async { + final configured = CodeFont.families.value; + final families = {...configured, ...fallbacks}; + try { + final uncached = families.where((name) => !_loaded.containsKey(name)); + final paths = uncached.isEmpty + ? null + : await _channel.invokeMapMethod( + 'codeFontFiles', + uncached.toList(), + ); + for (final MapEntry(:key, :value) + in paths?.entries ?? const >[]) { + _loaded.putIfAbsent( + key, + () => _register((value as List).cast()), + ); + } + final aliases = [ + for (final name in families) + if (await _loaded[name] case final String alias) alias, + ]; + if (identical(configured, CodeFont.families.value)) { + final next = aliases.isEmpty ? null : aliases; + if (!listEquals(_resolved.value, next)) _resolved.value = next; + } + } on PlatformException catch (error) { + debugPrint('Code fonts could not be resolved: $error'); + } on MissingPluginException { + // Non-desktop Flutter hosts have no Linux runner. + } + } + + static int _nextAlias = 0; + + static Future _register(List files) async { + final alias = 'BaoCodeCodeFont${_nextAlias++}'; + var loaded = false; + for (final path in files.toSet()) { + try { + await ui.loadFontFromList( + await File(path).readAsBytes(), + fontFamily: alias, + ); + loaded = true; + } on FileSystemException { + // The font was removed or is no longer readable. + } + } + return loaded ? alias : null; + } +} diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt index 2b8d68b2a..514f9c516 100644 --- a/linux/runner/CMakeLists.txt +++ b/linux/runner/CMakeLists.txt @@ -24,6 +24,8 @@ add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) +pkg_check_modules(FONTCONFIG REQUIRED IMPORTED_TARGET fontconfig) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::FONTCONFIG) # WebKitGTK, for the channel build's login window (login_window.cc): only in # the channel build (BAOCODE_CHANNEL=true in the environment, as diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index cee191a7d..d6261a085 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -6,7 +6,9 @@ #include "login_window.h" #include "flutter/generated_plugin_registrant.h" +#include #include +#include #include struct _MyApplication { @@ -243,6 +245,53 @@ static void reveal_path(const char* path) { nullptr, nullptr); } +// Resolve named code fonts before Skia's locale-sensitive family lookup. +// FcFontMatch also returns substitutes, so verify the family before accepting +// a file. Flutter's byte loader reads the first face of a collection only. +static FlValue* code_font_files(FlValue* args) { + FlValue* result = fl_value_new_map(); + if (fl_value_get_type(args) != FL_VALUE_TYPE_LIST) return result; + for (size_t i = 0; i < fl_value_get_length(args); ++i) { + FlValue* value = fl_value_get_list_value(args, i); + if (fl_value_get_type(value) != FL_VALUE_TYPE_STRING) continue; + const auto* family = reinterpret_cast(fl_value_get_string(value)); + g_autoptr(FlValue) files = fl_value_new_list(); + for (int weight : {FC_WEIGHT_REGULAR, FC_WEIGHT_BOLD}) { + for (int slant : {FC_SLANT_ROMAN, FC_SLANT_ITALIC}) { + FcPattern* query = FcPatternCreate(); + FcPatternAddString(query, FC_FAMILY, family); + FcPatternAddInteger(query, FC_WEIGHT, weight); + FcPatternAddInteger(query, FC_SLANT, slant); + FcConfigSubstitute(nullptr, query, FcMatchPattern); + FcDefaultSubstitute(query); + FcResult status; + FcPattern* match = FcFontMatch(nullptr, query, &status); + FcPatternDestroy(query); + if (match == nullptr) continue; + FcChar8* name; + bool exact = false; + for (int j = 0; FcPatternGetString(match, FC_FAMILY, j, &name) == FcResultMatch; ++j) { + if (FcStrCmpIgnoreCase(family, name) == 0) exact = true; + } + int spacing = 0; + if (FcStrCmpIgnoreCase(family, reinterpret_cast("monospace")) == 0) { + exact = FcPatternGetInteger(match, FC_SPACING, 0, &spacing) == FcResultMatch && + spacing == FC_MONO; + } + FcChar8* path; + int index; + if (exact && FcPatternGetInteger(match, FC_INDEX, 0, &index) == FcResultMatch && + index == 0 && FcPatternGetString(match, FC_FILE, 0, &path) == FcResultMatch) { + fl_value_append_take(files, fl_value_new_string(reinterpret_cast(path))); + } + FcPatternDestroy(match); + } + } + fl_value_set_string_take(result, fl_value_get_string(value), g_steal_pointer(&files)); + } + return result; +} + // baocode/window: the calls WindowControls makes when this host is a desktop. // Menus, clipboard images and drag-out stay unimplemented (MissingPlugin); // the app already treats those as optional. @@ -253,7 +302,10 @@ static void window_method_call_cb(FlMethodChannel* channel, FlMethodCall* call, FlValue* args = fl_method_call_get_args(call); g_autoptr(FlMethodResponse) response = nullptr; - if (strcmp(name, "heldModifiers") == 0) { + if (strcmp(name, "codeFontFiles") == 0) { + g_autoptr(FlValue) result = code_font_files(args); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); + } else if (strcmp(name, "heldModifiers") == 0) { // The modifiers held now, as the system has them: the app's own may // have missed one going up (see held_keys.dart). GdkKeymap* keymap = gdk_keymap_get_for_display(gdk_display_get_default()); diff --git a/test/theme/linux_code_fonts_test.dart b/test/theme/linux_code_fonts_test.dart new file mode 100644 index 000000000..b3d993563 --- /dev/null +++ b/test/theme/linux_code_fonts_test.dart @@ -0,0 +1,63 @@ +import 'dart:async'; + +import 'package:baocode/ide/terminal/terminal_render_metrics.dart'; +import 'package:baocode/ide/terminal/terminal_render_theme.dart'; +import 'package:baocode/theme/app_theme.dart'; +import 'package:baocode/theme/code_font.dart'; +import 'package:baocode/theme/linux_code_fonts.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'Linux resolves code and terminal fonts without rewriting settings', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + const channel = MethodChannel('baocode/window'); + final requests = >[]; + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'codeFontFiles'); + final families = (call.arguments as List).cast(); + requests.add(families); + return { + for (final family in families) + family: switch (family) { + 'Unavailable Font' => [], + 'Installed Font' || + 'DejaVu Sans Mono' => ['assets/codicons/codicon.ttf'], + _ => [], + }, + }; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + CodeFont.families.value = ['Unavailable Font']; + await LinuxCodeFonts.start(); + final fallback = AppFonts.mono; + expect(fallback, startsWith('BaoCodeCodeFont')); + expect(AppFonts.monoFallbacks, isEmpty); + expect(requests.single.first, 'Unavailable Font'); + + final changed = LinuxCodeFonts.resolved; + final next = Completer(); + void onChange() => next.complete(); + changed.addListener(onChange); + addTearDown(() => changed.removeListener(onChange)); + CodeFont.families.value = ['Installed Font', 'Unavailable Font']; + await next.future.timeout(const Duration(seconds: 5)); + expect(requests.last, ['Installed Font']); + expect(changed.value, [AppFonts.mono, fallback]); + expect( + parseFontFamilies(vscodeTerminalFontFamily()).take(2), + changed.value, + ); + expect(CodeFont.families.value, ['Installed Font', 'Unavailable Font']); + }, + ); +} From 1b624b57cf008de9726b25aff90c34d7d52f053e Mon Sep 17 00:00:00 2001 From: vic-7945hx Date: Wed, 25 Nov 2026 13:53:23 +0800 Subject: [PATCH 3/4] fix(appearance): preload Linux code font presets --- lib/settings/pages/appearance_page.dart | 13 +------------ lib/theme/code_font.dart | 11 +++++++++++ lib/theme/linux_code_fonts.dart | 16 +++++++++++++--- test/theme/linux_code_fonts_test.dart | 13 +++++++++++++ 4 files changed, 38 insertions(+), 15 deletions(-) diff --git a/lib/settings/pages/appearance_page.dart b/lib/settings/pages/appearance_page.dart index d9c1a0f66..66a89350b 100644 --- a/lib/settings/pages/appearance_page.dart +++ b/lib/settings/pages/appearance_page.dart @@ -110,17 +110,6 @@ class AppearanceSettingsPage extends StatelessWidget { }), ); - /// The families the dropdown offers: each is put first, then the defaults. - static const _codeFontPresets = [ - 'JetBrains Mono', - 'Fira Code', - 'Cascadia Code', - 'Consolas', - 'Menlo', - 'Monaco', - 'Courier New', - ]; - /// The step of [steps] nearest [value]: the slider's position. static int _nearest(List steps, num value) { var nearest = 0; @@ -701,7 +690,7 @@ class AppearanceSettingsPage extends StatelessWidget { onSelected: () => _selectFamilies(CodeFont.defaultFamilies), ), - for (final name in _codeFontPresets) + for (final name in CodeFont.familyPresets) IdeMenuAction( name, checked: listEquals(families, _presetOf(name)), diff --git a/lib/theme/code_font.dart b/lib/theme/code_font.dart index 302bbc0ed..3fa195997 100644 --- a/lib/theme/code_font.dart +++ b/lib/theme/code_font.dart @@ -30,6 +30,17 @@ abstract final class CodeFont { 'Cascadia Mono', ]; + /// The families offered by the Appearance picker, in display order. + static const familyPresets = [ + 'JetBrains Mono', + 'Fira Code', + 'Cascadia Code', + 'Consolas', + 'Menlo', + 'Monaco', + 'Courier New', + ]; + /// The size the editor draws code at on macOS. Code is drawn from it: /// every other code size is moved by the same amount the user moves this /// one (see [sized]). diff --git a/lib/theme/linux_code_fonts.dart b/lib/theme/linux_code_fonts.dart index 8bb1378b5..9fbe254ba 100644 --- a/lib/theme/linux_code_fonts.dart +++ b/lib/theme/linux_code_fonts.dart @@ -25,14 +25,21 @@ abstract final class LinuxCodeFonts { static Future start() async { if (!AppPlatform.isLinux) return; CodeFont.families.addListener(_refresh); - await _refresh(); + await _refresh(preloadPresets: true); } - static Future _refresh() async { + static Future _refresh({bool preloadPresets = false}) async { final configured = CodeFont.families.value; final families = {...configured, ...fallbacks}; + // Register the picker fonts before the first frame. Loading font bytes + // clears Flutter's font caches, including those for unrelated UI text. + final requested = { + ...families, + if (preloadPresets) ...CodeFont.defaultFamilies, + if (preloadPresets) ...CodeFont.familyPresets, + }; try { - final uncached = families.where((name) => !_loaded.containsKey(name)); + final uncached = requested.where((name) => !_loaded.containsKey(name)); final paths = uncached.isEmpty ? null : await _channel.invokeMapMethod( @@ -46,6 +53,9 @@ abstract final class LinuxCodeFonts { () => _register((value as List).cast()), ); } + if (preloadPresets) { + await Future.wait(_loaded.values); + } final aliases = [ for (final name in families) if (await _loaded[name] case final String alias) alias, diff --git a/test/theme/linux_code_fonts_test.dart b/test/theme/linux_code_fonts_test.dart index b3d993563..bf7fcbc3d 100644 --- a/test/theme/linux_code_fonts_test.dart +++ b/test/theme/linux_code_fonts_test.dart @@ -30,6 +30,7 @@ void main() { family: switch (family) { 'Unavailable Font' => [], 'Installed Font' || + 'Courier New' || 'DejaVu Sans Mono' => ['assets/codicons/codicon.ttf'], _ => [], }, @@ -43,8 +44,20 @@ void main() { expect(fallback, startsWith('BaoCodeCodeFont')); expect(AppFonts.monoFallbacks, isEmpty); expect(requests.single.first, 'Unavailable Font'); + expect(requests.single, containsAll(CodeFont.familyPresets)); final changed = LinuxCodeFonts.resolved; + final preset = Completer(); + void onPreset() => preset.complete(); + changed.addListener(onPreset); + CodeFont.families.value = ['Courier New']; + try { + await preset.future.timeout(const Duration(seconds: 5)); + } finally { + changed.removeListener(onPreset); + } + expect(requests, hasLength(1)); + expect(changed.value, [isNot(fallback), fallback]); final next = Completer(); void onChange() => next.complete(); changed.addListener(onChange); From aed193210486880a7a9cebf8ca38dbd6f5af5b3a Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 25 Nov 2026 14:07:48 +0800 Subject: [PATCH 4/4] fix(appearance): keep unloadable Linux code fonts by name; load presets as the menu opens - A family installed but not loadable (in a font collection, not its first face) is drawn by its own name, as before, instead of left out: codeFontFiles now tells whether each family is installed besides its files. - Only the families set and the fallbacks are loaded before the first frame; the Appearance menu's presets are loaded as the menu opens, not at every start. - The root cause is noted: Skia's Fontconfig StyleSet::matchStyle picks among an alias's faces without the family, fixed in Skia a4d18ba482 (flutter/flutter#195102); this can go with a Flutter that has it. Co-Authored-By: BaoCode --- lib/ide/terminal/terminal_render_theme.dart | 6 +- lib/settings/pages/appearance_page.dart | 39 +++--- lib/theme/app_theme.dart | 9 +- lib/theme/code_font.dart | 3 +- lib/theme/linux_code_fonts.dart | 135 +++++++++++++------- linux/runner/my_application.cc | 17 ++- test/theme/linux_code_fonts_test.dart | 123 ++++++++++-------- 7 files changed, 204 insertions(+), 128 deletions(-) diff --git a/lib/ide/terminal/terminal_render_theme.dart b/lib/ide/terminal/terminal_render_theme.dart index e6f2d6caa..63c4122de 100644 --- a/lib/ide/terminal/terminal_render_theme.dart +++ b/lib/ide/terminal/terminal_render_theme.dart @@ -416,8 +416,10 @@ ITheme vscodeTerminalTheme([TerminalColorTheme? theme]) => (theme ?? terminalColorTheme.value).toXtermTheme(); /// The terminal font, as VS Code's `getFont` resolves it without a -/// `terminal.integrated.fontFamily`: the same stack as the editor and -/// `monospace` if it isn't in that stack, followed by AppleBraille on macOS. +/// `terminal.integrated.fontFamily`: the editor's ([AppFonts.mono] and +/// [AppFonts.monoFallbacks], as this app's editor draws code: on Windows the +/// app's fallbacks, ending in `monospace`; on Linux the families as loaded), +/// then `monospace` where they have not it and, on macOS, AppleBraille. String vscodeTerminalFontFamily() { final families = [AppFonts.mono, ...AppFonts.monoFallbacks]; if (!families.contains('monospace')) families.add('monospace'); diff --git a/lib/settings/pages/appearance_page.dart b/lib/settings/pages/appearance_page.dart index 66a89350b..066e6ec8e 100644 --- a/lib/settings/pages/appearance_page.dart +++ b/lib/settings/pages/appearance_page.dart @@ -679,25 +679,30 @@ class AppearanceSettingsPage extends StatelessWidget { semanticLabel: l10n.appearanceSettingsCodeFontLabel( _familyName(context, families), ), - entries: () => ideMenuGroups([ - [ - IdeMenuAction( - l10n.appearanceSettingsCodeFontDefault, - checked: listEquals( - families, - CodeFont.defaultFamilies, - ), - onSelected: () => - _selectFamilies(CodeFont.defaultFamilies), - ), - for (final name in CodeFont.familyPresets) + entries: () { + // On Linux, what it offers loaded ahead of a pick. + unawaited(LinuxCodeFonts.preloadPresets()); + return ideMenuGroups([ + [ IdeMenuAction( - name, - checked: listEquals(families, _presetOf(name)), - onSelected: () => _selectFamilies(_presetOf(name)), + l10n.appearanceSettingsCodeFontDefault, + checked: listEquals( + families, + CodeFont.defaultFamilies, + ), + onSelected: () => + _selectFamilies(CodeFont.defaultFamilies), ), - ], - ]), + for (final name in CodeFont.familyPresets) + IdeMenuAction( + name, + checked: listEquals(families, _presetOf(name)), + onSelected: () => + _selectFamilies(_presetOf(name)), + ), + ], + ]); + }, ), ), // Not const: it must redraw as the font, size or ligatures diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart index 7fb5aead4..06a39caf2 100644 --- a/lib/theme/app_theme.dart +++ b/lib/theme/app_theme.dart @@ -253,11 +253,16 @@ abstract final class AppMetrics { } abstract final class AppFonts { - /// The primary code font, resolved to a registered face on Linux. + /// The font code, paths and commands are drawn in: the first of + /// [CodeFont.families], which the user may change; on Linux the first + /// installed, as loaded ([LinuxCodeFonts.resolved]). static String get mono => LinuxCodeFonts.resolved.value?.first ?? CodeFont.families.value.first; - /// The other code fonts, followed by the platform's fallbacks. + /// What code falls back on, in order: the families after [mono], then on + /// Windows [windowsFallbacks]. A family not installed is passed over. On + /// Linux the rest as loaded, [LinuxCodeFonts.fallbacks] among them, or + /// while they are not, by their names. static List get monoFallbacks => [ ...(LinuxCodeFonts.resolved.value?.skip(1) ?? CodeFont.families.value.skip(1)), diff --git a/lib/theme/code_font.dart b/lib/theme/code_font.dart index 3fa195997..f81fb1032 100644 --- a/lib/theme/code_font.dart +++ b/lib/theme/code_font.dart @@ -30,7 +30,8 @@ abstract final class CodeFont { 'Cascadia Mono', ]; - /// The families offered by the Appearance picker, in display order. + /// The families the Appearance page's menu offers: each is put first, + /// then the defaults. static const familyPresets = [ 'JetBrains Mono', 'Fira Code', diff --git a/lib/theme/linux_code_fonts.dart b/lib/theme/linux_code_fonts.dart index 9fbe254ba..1225b20b8 100644 --- a/lib/theme/linux_code_fonts.dart +++ b/lib/theme/linux_code_fonts.dart @@ -7,74 +7,116 @@ import 'package:flutter/services.dart'; import '../platform/app_platform.dart'; import 'code_font.dart'; -/// Linux's Skia family lookup can pick a different face under a CJK locale. -/// Register the exact Fontconfig matches under private names, so the fix -/// applies only to code and never changes the window's font matching locale. +/// Code drawn on Linux in the families set ([CodeFont.families]), each +/// loaded from the files Fontconfig matches for it, under a name of the +/// app's own. +/// +/// By their own names, Skia may draw them in another face under a CJK +/// locale (#1304): its Fontconfig lookup gathers the faces of every family +/// the configuration puts with the name (a CJK one, first, for `zh`), then +/// picks among them by style and the locale's language, not by family, and +/// the CJK face comes out, proportional at times. Skia keeps the family +/// since a4d18ba482 (flutter/flutter#195102); with a Flutter whose Skia has +/// it, this can go. `FC_LANG=en` works around it too, but for the whole app +/// and what it starts, and the language is not the app's to change. abstract final class LinuxCodeFonts { + /// What code falls back on after the families set: monospaced ones most + /// Linux systems have, then whichever Fontconfig calls monospaced. static const fallbacks = [ 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono', 'monospace', ]; + + /// The window's channel (WindowControls'), whose Linux host answers + /// `codeFontFiles` (see my_application.cc). static const _channel = MethodChannel('baocode/window'); - static final _loaded = >{}; + + /// Each family asked for: the name to draw it by (the one it was loaded + /// under; its own, installed where it cannot be loaded), or null, not + /// installed. + static final _faces = >{}; + + static int _aliases = 0; + static final _resolved = ValueNotifier?>(null); + + /// The families code is drawn in, by the names to draw them by: those set, + /// then [fallbacks], the ones not installed left out. Null off Linux, and + /// while none is known. static ValueListenable?> get resolved => _resolved; + /// Loads the families set, before the first frame, and those set later. static Future start() async { if (!AppPlatform.isLinux) return; CodeFont.families.addListener(_refresh); - await _refresh(preloadPresets: true); + await _refresh(); } - static Future _refresh({bool preloadPresets = false}) async { + /// Loads the families the Appearance page's menu offers, as it opens: a + /// font loaded has Flutter lay all its text out again, which picked from + /// the menu left the old glyphs on screen a long while. + static Future preloadPresets() async { + if (!AppPlatform.isLinux) return; + await _load({...CodeFont.defaultFamilies, ...CodeFont.familyPresets}); + } + + static Future _refresh() async { final configured = CodeFont.families.value; final families = {...configured, ...fallbacks}; - // Register the picker fonts before the first frame. Loading font bytes - // clears Flutter's font caches, including those for unrelated UI text. - final requested = { - ...families, - if (preloadPresets) ...CodeFont.defaultFamilies, - if (preloadPresets) ...CodeFont.familyPresets, - }; - try { - final uncached = requested.where((name) => !_loaded.containsKey(name)); - final paths = uncached.isEmpty - ? null - : await _channel.invokeMapMethod( - 'codeFontFiles', - uncached.toList(), - ); - for (final MapEntry(:key, :value) - in paths?.entries ?? const >[]) { - _loaded.putIfAbsent( - key, - () => _register((value as List).cast()), + await _load(families); + final faces = [for (final name in families) ?await _faces[name]]; + // Set again meanwhile: that one's to tell. + if (!identical(configured, CodeFont.families.value)) return; + final next = faces.isEmpty ? null : faces; + if (!listEquals(_resolved.value, next)) _resolved.value = next; + } + + /// Asks for the files of those of [families] not asked for yet, and loads + /// them. Asked again later where the host could not answer. + static Future _load(Set families) async { + final asking = [ + for (final name in families) + if (!_faces.containsKey(name)) name, + ]; + if (asking.isNotEmpty) { + final Map? answer; + try { + answer = await _channel.invokeMapMethod( + 'codeFontFiles', + asking, ); + } on PlatformException catch (error) { + debugPrint('Code fonts could not be resolved: $error'); + return; + } on MissingPluginException { + // A host without the Linux runner's channel. + return; } - if (preloadPresets) { - await Future.wait(_loaded.values); - } - final aliases = [ - for (final name in families) - if (await _loaded[name] case final String alias) alias, - ]; - if (identical(configured, CodeFont.families.value)) { - final next = aliases.isEmpty ? null : aliases; - if (!listEquals(_resolved.value, next)) _resolved.value = next; + for (final name in asking) { + final entry = answer?[name]; + final (files, installed) = entry is Map + ? ( + [...?(entry['files'] as List?)?.cast()], + entry['installed'] == true, + ) + : (const [], false); + _faces.putIfAbsent(name, () => _register(name, files, installed)); } - } on PlatformException catch (error) { - debugPrint('Code fonts could not be resolved: $error'); - } on MissingPluginException { - // Non-desktop Flutter hosts have no Linux runner. } + await Future.wait([for (final name in families) ?_faces[name]]); } - static int _nextAlias = 0; - - static Future _register(List files) async { - final alias = 'BaoCodeCodeFont${_nextAlias++}'; + /// The name to draw [family] by: its [files] loaded under one of the + /// app's own; where none could be and it is [installed] (in a font + /// collection but its first face), its own name, Skia's to find as before. + static Future _register( + String family, + List files, + bool installed, + ) async { + final alias = 'BaoCodeCodeFont${_aliases++}'; var loaded = false; for (final path in files.toSet()) { try { @@ -84,9 +126,10 @@ abstract final class LinuxCodeFonts { ); loaded = true; } on FileSystemException { - // The font was removed or is no longer readable. + // Removed since, or not readable. } } - return loaded ? alias : null; + if (loaded) return alias; + return installed ? family : null; } } diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index d6261a085..69d967e1a 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -245,9 +245,13 @@ static void reveal_path(const char* path) { nullptr, nullptr); } -// Resolve named code fonts before Skia's locale-sensitive family lookup. -// FcFontMatch also returns substitutes, so verify the family before accepting -// a file. Flutter's byte loader reads the first face of a collection only. +// codeFontFiles: for each family named, the files of its regular, bold, +// italic and bold italic faces as Fontconfig matches them, for the app to +// load itself (see linux_code_fonts.dart), and whether it is installed at +// all. FcFontMatch answers with a substitute too, so only a face of the +// family itself counts (for `monospace`, any monospaced one). A face in a +// collection but its first is installed without a file: Flutter's loader +// reads only the first. static FlValue* code_font_files(FlValue* args) { FlValue* result = fl_value_new_map(); if (fl_value_get_type(args) != FL_VALUE_TYPE_LIST) return result; @@ -256,6 +260,7 @@ static FlValue* code_font_files(FlValue* args) { if (fl_value_get_type(value) != FL_VALUE_TYPE_STRING) continue; const auto* family = reinterpret_cast(fl_value_get_string(value)); g_autoptr(FlValue) files = fl_value_new_list(); + bool installed = false; for (int weight : {FC_WEIGHT_REGULAR, FC_WEIGHT_BOLD}) { for (int slant : {FC_SLANT_ROMAN, FC_SLANT_ITALIC}) { FcPattern* query = FcPatternCreate(); @@ -278,6 +283,7 @@ static FlValue* code_font_files(FlValue* args) { exact = FcPatternGetInteger(match, FC_SPACING, 0, &spacing) == FcResultMatch && spacing == FC_MONO; } + installed = installed || exact; FcChar8* path; int index; if (exact && FcPatternGetInteger(match, FC_INDEX, 0, &index) == FcResultMatch && @@ -287,7 +293,10 @@ static FlValue* code_font_files(FlValue* args) { FcPatternDestroy(match); } } - fl_value_set_string_take(result, fl_value_get_string(value), g_steal_pointer(&files)); + FlValue* entry = fl_value_new_map(); + fl_value_set_string_take(entry, "files", g_steal_pointer(&files)); + fl_value_set_string_take(entry, "installed", fl_value_new_bool(installed)); + fl_value_set_string_take(result, fl_value_get_string(value), entry); } return result; } diff --git a/test/theme/linux_code_fonts_test.dart b/test/theme/linux_code_fonts_test.dart index bf7fcbc3d..763aac41c 100644 --- a/test/theme/linux_code_fonts_test.dart +++ b/test/theme/linux_code_fonts_test.dart @@ -12,65 +12,76 @@ import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - test( - 'Linux resolves code and terminal fonts without rewriting settings', - () async { - debugDefaultTargetPlatformOverride = TargetPlatform.linux; - addTearDown(() => debugDefaultTargetPlatformOverride = null); - final messenger = - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; - const channel = MethodChannel('baocode/window'); - final requests = >[]; - messenger.setMockMethodCallHandler(channel, (call) async { - expect(call.method, 'codeFontFiles'); - final families = (call.arguments as List).cast(); - requests.add(families); - return { - for (final family in families) - family: switch (family) { - 'Unavailable Font' => [], - 'Installed Font' || - 'Courier New' || - 'DejaVu Sans Mono' => ['assets/codicons/codicon.ttf'], - _ => [], + test('Linux draws code in the families as loaded, without rewriting ' + 'settings', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + const channel = MethodChannel('baocode/window'); + final requests = >[]; + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'codeFontFiles'); + final families = (call.arguments as List).cast(); + requests.add(families); + return { + for (final family in families) + family: switch (family) { + 'Installed Font' || 'Courier New' || 'DejaVu Sans Mono' => { + 'files': ['assets/codicons/codicon.ttf'], + 'installed': true, }, - }; - }); - addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + // In a collection, not its first face: none to load. + 'Collection Font' => {'files': [], 'installed': true}, + _ => {'files': [], 'installed': false}, + }, + }; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); - CodeFont.families.value = ['Unavailable Font']; - await LinuxCodeFonts.start(); - final fallback = AppFonts.mono; - expect(fallback, startsWith('BaoCodeCodeFont')); - expect(AppFonts.monoFallbacks, isEmpty); - expect(requests.single.first, 'Unavailable Font'); - expect(requests.single, containsAll(CodeFont.familyPresets)); - - final changed = LinuxCodeFonts.resolved; - final preset = Completer(); - void onPreset() => preset.complete(); - changed.addListener(onPreset); - CodeFont.families.value = ['Courier New']; + /// Sets the families, and waits for them as loaded. + Future set(List families) async { + final changed = Completer(); + void onChange() => changed.complete(); + LinuxCodeFonts.resolved.addListener(onChange); + CodeFont.families.value = families; try { - await preset.future.timeout(const Duration(seconds: 5)); + await changed.future.timeout(const Duration(seconds: 5)); } finally { - changed.removeListener(onPreset); + LinuxCodeFonts.resolved.removeListener(onChange); } - expect(requests, hasLength(1)); - expect(changed.value, [isNot(fallback), fallback]); - final next = Completer(); - void onChange() => next.complete(); - changed.addListener(onChange); - addTearDown(() => changed.removeListener(onChange)); - CodeFont.families.value = ['Installed Font', 'Unavailable Font']; - await next.future.timeout(const Duration(seconds: 5)); - expect(requests.last, ['Installed Font']); - expect(changed.value, [AppFonts.mono, fallback]); - expect( - parseFontFamilies(vscodeTerminalFontFamily()).take(2), - changed.value, - ); - expect(CodeFont.families.value, ['Installed Font', 'Unavailable Font']); - }, - ); + } + + // Before the first frame: only those set and the fallbacks. + CodeFont.families.value = ['Unavailable Font']; + await LinuxCodeFonts.start(); + expect(requests.single, ['Unavailable Font', ...LinuxCodeFonts.fallbacks]); + final fallback = AppFonts.mono; + expect(fallback, startsWith('BaoCodeCodeFont')); + expect(AppFonts.monoFallbacks, isEmpty); + + // The menu opened: what it offers, not asked for yet. + await LinuxCodeFonts.preloadPresets(); + expect(requests, hasLength(2)); + expect(requests.last, contains('Courier New')); + expect(requests.last, isNot(contains('DejaVu Sans Mono'))); + + // Picked from it: loaded already. + await set(['Courier New']); + expect(requests, hasLength(2)); + expect(LinuxCodeFonts.resolved.value, [isNot(fallback), fallback]); + + await set(['Installed Font', 'Unavailable Font']); + expect(requests.last, ['Installed Font']); + expect(LinuxCodeFonts.resolved.value, [AppFonts.mono, fallback]); + expect( + parseFontFamilies(vscodeTerminalFontFamily()).take(2), + LinuxCodeFonts.resolved.value, + ); + + // Installed where it cannot be loaded: by its own name, as before. + await set(['Collection Font']); + expect(LinuxCodeFonts.resolved.value, ['Collection Font', fallback]); + expect(CodeFont.families.value, ['Collection Font']); + }); }