Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve monospace font filtering https://github.com/siyuan-note/siyuan/issues/18968

Daniel55dd9afc9a3f
diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.ts
index 7c95266f85..8b807fe1da 100644
--- a/app/src/config/tabs/appearanceTab.ts
+++ b/app/src/config/tabs/appearanceTab.ts
@@ -49,6 +49,7 @@ interface IFontItem {
weight: number;
displayName: string;
aliases?: string[];
+ spacing?: string;
}
type FontFamiliesConfigKey = "fontFamilies" | "codeFontFamilies";
@@ -59,6 +60,9 @@ const getEditorFonts = (editor: Config.IEditor, configKey: FontFamiliesConfigKey
const getEditorFontDisplay = (fonts: IFontItem[]) =>
fonts.map((font) => font.displayName || font.family).join(", ");
+const isCodeFont = (font: Pick<IFontItem, "spacing">) =>
+ font.spacing === "monospace" || font.spacing === "dual" || font.spacing === "character-cell";
+
const genFontConfigHtml = (configKey: FontFamiliesConfigKey, title: string, description: string) => {
const fonts = getEditorFonts(window.siyuan.config.editor, configKey);
return `<div class="fn__flex b3-label config-item config-wrap" data-font-config-key="${configKey}">
@@ -129,7 +133,7 @@ const registerAppearanceContentGroup = (tab: SettingTabBuilder) => {
const genFontListItemHtml = (item: IFontItem, checked: boolean) => {
const searchText = [item.family, item.displayName, ...(item.aliases || [])].join("\n").toLowerCase();
return `<div class="b3-list-item b3-list-item--narrow" data-id="${escapeAttr(item.id || "")}">
- <span class="b3-menu__label" data-family="${escapeAttr(item.family)}" data-name="${escapeAttr(item.displayName)}" data-search="${escapeAttr(searchText)}" data-weight="${item.weight || 400}">${escapeHtml(item.displayName)}</span>
+ <span class="b3-menu__label" data-family="${escapeAttr(item.family)}" data-name="${escapeAttr(item.displayName)}" data-search="${escapeAttr(searchText)}" data-spacing="${escapeAttr(item.spacing || "")}" data-weight="${item.weight || 400}">${escapeHtml(item.displayName)}</span>
${checked ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}
${item.id && !window.siyuan.config.readonly ? `<span class="b3-menu__action ariaLabel" data-type="delete-font" aria-label="${escapeAttr(window.siyuan.languages.delete)}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>` : ""}
</div>`;
@@ -308,6 +312,7 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesCon
font.family === item.family && font.weight === item.weight))
).join("");
const canManageCustomFonts = nativeMobile && !window.siyuan.config.readonly;
+ const canShowAllFonts = configKey === "codeFontFamilies" && fontItems.some((font) => !isCodeFont(font));
const customFontsByID = new Map(customFonts.map((font) => [font.id, font]));
let fontPreviewObserver: IntersectionObserver;
const fontMenu = new Menu(undefined, () => {
@@ -320,6 +325,7 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesCon
label: `<div class="fn__flex-column b3-menu__filter">
<div class="fn__flex">
<input class="b3-text-field fn__flex-1" data-type="font-search" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">
+ ${canShowAllFonts ? `<span class="fn__space"></span><button class="b3-button b3-button--outline fn__flex-center" data-type="show-all-fonts">${escapeHtml(window.siyuan.languages.showAll)}</button>` : ""}
${canManageCustomFonts ? `<span class="fn__space"></span><button class="b3-button b3-button--outline fn__flex-center" data-type="import-font"><svg><use xlink:href="#iconUpload"></use></svg>${escapeHtml(window.siyuan.languages.importFont)}</button>` : ""}
</div>
${nativeMobile ? `<div class="b3-label__text ft__on-surface" style="margin-top: 8px">${escapeHtml(window.siyuan.languages.fontFileTip)}</div>` : ""}
@@ -330,6 +336,7 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesCon
bind(element) {
const listElement = element.querySelector<HTMLElement>('[data-type="available-fonts"]');
const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-search"]');
+ let showAllFonts = configKey !== "codeFontFamilies";
const refreshFontMenu = () => {
listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach((item) => {
const label = item.querySelector<HTMLElement>(".b3-menu__label");
@@ -341,7 +348,10 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesCon
}
});
};
- refreshOpenMenu = refreshFontMenu;
+ refreshOpenMenu = () => {
+ refreshFontMenu();
+ filterFontList();
+ };
refreshFontMenu();
if ("IntersectionObserver" in window) {
fontPreviewObserver = new IntersectionObserver((entries) => {
@@ -373,14 +383,16 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesCon
});
customFonts.forEach(registerCustomFont);
}
- listElement.firstElementChild.classList.add("b3-list-item--focus");
- const filterFontList = () => {
+ function filterFontList() {
const value = inputElement.value.toLowerCase().trim();
listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");
listElement.querySelectorAll<HTMLElement>(".b3-list-item .b3-menu__label").forEach((item) => {
const name = item.dataset.name;
- item.parentElement.classList.toggle("fn__none", !(!value ||
- item.dataset.search.includes(value)));
+ const selected = selectedFonts.some((font) =>
+ font.family === item.dataset.family && font.weight === parseInt(item.dataset.weight, 10));
+ const codeFontVisible = showAllFonts || selected || isCodeFont({spacing: item.dataset.spacing});
+ const searchVisible = !value || item.dataset.search.includes(value);
+ item.parentElement.classList.toggle("fn__none", !(codeFontVisible && searchVisible));
const idx = name.toLowerCase().indexOf(value);
item.replaceChildren(document.createTextNode(name));
if (idx !== -1 && value) {
@@ -394,7 +406,14 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesCon
}
});
listElement.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");
- };
+ }
+ filterFontList();
+ element.querySelector<HTMLElement>('[data-type="show-all-fonts"]')?.addEventListener("click", (event) => {
+ showAllFonts = true;
+ (event.currentTarget as HTMLElement).remove();
+ filterFontList();
+ inputElement.focus();
+ });
inputElement.addEventListener("keydown", (event: KeyboardEvent) => {
event.stopPropagation();
if (event.isComposing) {
@@ -532,6 +551,7 @@ const fontItemFromElement = (item: HTMLElement): IFontItem => ({
family: item.dataset.family,
displayName: item.dataset.name,
weight: parseInt(item.dataset.weight, 10) || 400,
+ spacing: item.dataset.spacing,
});
const registerAppearanceInterfaceGroup = (tab: SettingTabBuilder) => {
diff --git a/app/src/util/customFont.ts b/app/src/util/customFont.ts
index f95799bb26..4707d4a85c 100644
--- a/app/src/util/customFont.ts
+++ b/app/src/util/customFont.ts
@@ -8,6 +8,7 @@ export interface ICustomFont {
weight: number;
displayName: string;
aliases?: string[];
+ spacing?: string;
url: string;
}
diff --git a/kernel/util/custom_font.go b/kernel/util/custom_font.go
index 7aa906b8da..a8d3266df6 100644
--- a/kernel/util/custom_font.go
+++ b/kernel/util/custom_font.go
@@ -42,6 +42,7 @@ type CustomFont struct {
Weight int `json:"weight"`
DisplayName string `json:"displayName"`
Aliases []string `json:"aliases,omitempty"`
+ Spacing string `json:"spacing,omitempty"`
URL string `json:"url"`
path string
}
@@ -358,6 +359,7 @@ func newCustomFont(id, fontPath string, font *Font) *CustomFont {
Weight: weight,
DisplayName: font.DisplayName,
Aliases: mergeFontAliases(nil, append(append([]string(nil), font.Aliases...), font.Family), font.DisplayName),
+ Spacing: font.Spacing,
URL: "/custom-fonts/" + id,
path: fontPath,
}
diff --git a/kernel/util/custom_font_test.go b/kernel/util/custom_font_test.go
index b550df9f46..3d34ee9517 100644
--- a/kernel/util/custom_font_test.go
+++ b/kernel/util/custom_font_test.go
@@ -56,6 +56,9 @@ func TestCustomFontLifecycle(t *testing.T) {
if len(font.Aliases) == 0 {
t.Fatalf("custom font aliases are missing: %+v", font)
}
+ if FontSpacingProportional != font.Spacing {
+ t.Fatalf("unexpected custom font spacing: %+v", font)
+ }
fonts := LoadCustomFonts()
if len(fonts) != 1 || fonts[0].ID != font.ID {
diff --git a/kernel/util/font.go b/kernel/util/font.go
index 95b1626f4b..98447cc04b 100644
--- a/kernel/util/font.go
+++ b/kernel/util/font.go
@@ -64,8 +64,16 @@ type Font struct {
Weight int `json:"weight"` // 对应 CSS font-weight
DisplayName string `json:"displayName"` // 给人看的名称 (Family + Subfamily)
Aliases []string `json:"aliases,omitempty"` // 用于字体搜索的本地化名称和内部名称
+ Spacing string `json:"spacing,omitempty"` // 字体间距分类
}
+const (
+ FontSpacingProportional = "proportional"
+ FontSpacingDual = "dual"
+ FontSpacingMonospace = "monospace"
+ FontSpacingCharacterCell = "character-cell"
+)
+
type fontLanguage struct {
PlatformID sfnt.PlatformID
LanguageID sfnt.PlatformLanguageID
@@ -130,6 +138,7 @@ func addFont(fonts []*Font, f *Font) []*Font {
for _, font := range fonts {
if strings.EqualFold(f.Family, font.Family) && f.Weight == font.Weight {
font.Aliases = mergeFontAliases(font.Aliases, f.Aliases, font.Family, font.DisplayName)
+ font.Spacing = mergeFontSpacing(font.Spacing, f.Spacing)
return fonts
}
}
@@ -259,6 +268,7 @@ func parseFontVariations(font *sfnt.Font, defaultFont *Font) (ret []*Font) {
Weight: weight,
DisplayName: displayName,
Aliases: aliases,
+ Spacing: defaultFont.Spacing,
})
}
return
@@ -308,9 +318,98 @@ func parseFontInfo(font *sfnt.Font) (*Font, error) {
Weight: weight,
DisplayName: displayName,
Aliases: aliases,
+ Spacing: detectFontSpacing(font),
}, nil
}
+func detectFontSpacing(font *sfnt.Font) string {
+ postTable, postErr := font.Table(sfnt.MustNamedTag("post"))
+ postData := []byte(nil)
+ if nil == postErr {
+ postData = postTable.Bytes()
+ if 16 <= len(postData) && 0 != binary.BigEndian.Uint32(postData[12:16]) {
+ return FontSpacingMonospace
+ }
+ }
+
+ os2, os2Err := font.OS2Table()
+ if nil == os2Err && 2 == os2.Panose[0] && 9 == os2.Panose[3] {
+ return FontSpacingMonospace
+ }
+ if spacing := detectFontSpacingFromMetrics(font); "" != spacing {
+ return spacing
+ }
+ if 16 <= len(postData) {
+ return FontSpacingProportional
+ }
+ if nil == os2Err && 2 == os2.Panose[0] && 2 <= os2.Panose[3] && os2.Panose[3] <= 8 {
+ return FontSpacingProportional
+ }
+ return ""
+}
+
+func detectFontSpacingFromMetrics(font *sfnt.Font) string {
+ hhea, err := font.HheaTable()
+ if nil != err || hhea.NumOfLongHorMetrics < 32 {
+ return ""
+ }
+ hmtx, err := font.Table(sfnt.TagHmtx)
+ if nil != err {
+ return ""
+ }
+ metricCount := int(hhea.NumOfLongHorMetrics)
+ data := hmtx.Bytes()
+ if len(data) < metricCount*4 {
+ return ""
+ }
+
+ widths := make(map[uint16]struct{}, 3)
+ for i := 0; i < metricCount; i++ {
+ width := binary.BigEndian.Uint16(data[i*4 : i*4+2])
+ if 0 == width {
+ continue
+ }
+ widths[width] = struct{}{}
+ if 2 < len(widths) {
+ return ""
+ }
+ }
+ if 1 == len(widths) {
+ return FontSpacingMonospace
+ }
+ if 2 != len(widths) {
+ return ""
+ }
+ var first, second uint16
+ for width := range widths {
+ if 0 == first {
+ first = width
+ } else {
+ second = width
+ }
+ }
+ if second < first {
+ first, second = second, first
+ }
+ if uint32(first)*2 == uint32(second) {
+ return FontSpacingDual
+ }
+ return ""
+}
+
+func mergeFontSpacing(current, incoming string) string {
+ if "" == incoming {
+ return current
+ }
+ if "" == current || FontSpacingProportional == current {
+ return incoming
+ }
+ if FontSpacingProportional == incoming {
+ return current
+ }
+ return current
+}
+
func selectFontName(entries []*sfnt.NameEntry, nameIDs ...sfnt.NameID) string {
return selectFontNameWithLanguages(entries, []fontLanguage{
{PlatformID: sfnt.PlatformMicrosoft, LanguageID: sfnt.PlatformLanguageID(1033)},
diff --git a/kernel/util/font_platform_darwin.go b/kernel/util/font_platform_darwin.go
index 6cf82edca1..29248c09d0 100644
--- a/kernel/util/font_platform_darwin.go
+++ b/kernel/util/font_platform_darwin.go
@@ -76,6 +76,8 @@ static char *siyuanCopyAvailableFontsJSON(void) {
siyuanCopyDescriptorString(descriptor, kCTFontNameAttribute, NO);
double weight = 0;
+ CTFontSymbolicTraits symbolicTraits = 0;
+ BOOL hasSymbolicTraits = NO;
CFTypeRef traitsValue = CTFontDescriptorCopyAttribute(descriptor, kCTFontTraitsAttribute);
if (traitsValue && CFGetTypeID(traitsValue) == CFDictionaryGetTypeID()) {
CFNumberRef weightValue = (CFNumberRef)CFDictionaryGetValue(
@@ -83,8 +85,17 @@ static char *siyuanCopyAvailableFontsJSON(void) {
if (weightValue && CFGetTypeID(weightValue) == CFNumberGetTypeID()) {
CFNumberGetValue(weightValue, kCFNumberDoubleType, &weight);
}
+ CFNumberRef symbolicValue = (CFNumberRef)CFDictionaryGetValue(
+ (CFDictionaryRef)traitsValue, kCTFontSymbolicTrait);
+ if (symbolicValue && CFGetTypeID(symbolicValue) == CFNumberGetTypeID()) {
+ hasSymbolicTraits = CFNumberGetValue(
+ symbolicValue, kCFNumberSInt32Type, &symbolicTraits);
+ }
}
if (traitsValue) CFRelease(traitsValue);
+ NSString *spacing = hasSymbolicTraits
+ ? ((symbolicTraits & kCTFontTraitMonoSpace) ? @"monospace" : @"proportional")
+ : @"";
NSMutableArray *aliases = [NSMutableArray array];
siyuanAppendFontAlias(aliases, localizedFamily);
@@ -101,6 +112,7 @@ static char *siyuanCopyAvailableFontsJSON(void) {
@"style": [style length] ? style : @"",
@"weight": @(weight),
@"aliases": aliases,
+ @"spacing": spacing,
}];
}
CFRelease(descriptors);
@@ -133,6 +145,7 @@ type coreTextFont struct {
Style string `json:"style"`
Weight float64 `json:"weight"`
Aliases []string `json:"aliases"`
+ Spacing string `json:"spacing"`
}
func loadPlatformFonts() (ret []*Font) {
@@ -161,6 +174,7 @@ func loadPlatformFonts() (ret []*Font) {
Weight: fontWeightFromNormalizedTrait(font.Weight, font.Style),
DisplayName: font.DisplayName,
Aliases: font.Aliases,
+ Spacing: font.Spacing,
})
}
return
diff --git a/kernel/util/font_platform_darwin_test.go b/kernel/util/font_platform_darwin_test.go
index c1251a4547..065a0a0013 100644
--- a/kernel/util/font_platform_darwin_test.go
+++ b/kernel/util/font_platform_darwin_test.go
@@ -25,9 +25,18 @@ func TestLoadPlatformFonts(t *testing.T) {
if len(fonts) == 0 {
t.Fatal("CoreText returned no available fonts")
}
+ hasKnownSpacing := false
for _, font := range fonts {
if "" == font.Family || "" == font.DisplayName || font.Weight < 1 || 1000 < font.Weight {
t.Fatalf("invalid CoreText font: %+v", font)
}
+ if FontSpacingProportional == font.Spacing || FontSpacingMonospace == font.Spacing {
+ hasKnownSpacing = true
+ } else if "" != font.Spacing {
+ t.Fatalf("invalid CoreText font spacing: %+v", font)
+ }
+ }
+ if !hasKnownSpacing {
+ t.Fatal("CoreText should return font spacing metadata")
}
}
diff --git a/kernel/util/font_platform_linux_test.go b/kernel/util/font_platform_linux_test.go
index a3c2b42e44..3b905c65fc 100644
--- a/kernel/util/font_platform_linux_test.go
+++ b/kernel/util/font_platform_linux_test.go
@@ -38,5 +38,10 @@ func TestLoadFontconfigFonts(t *testing.T) {
if font.Weight < 1 || 1000 < font.Weight {
t.Fatalf("Fontconfig returned an invalid font weight: %+v", font)
}
+ switch font.Spacing {
+ case "", FontSpacingProportional, FontSpacingDual, FontSpacingMonospace, FontSpacingCharacterCell:
+ default:
+ t.Fatalf("Fontconfig returned an invalid font spacing: %+v", font)
+ }
}
}
diff --git a/kernel/util/font_platform_windows.go b/kernel/util/font_platform_windows.go
index 0e2d1b2a3b..d7936251e0 100644
--- a/kernel/util/font_platform_windows.go
+++ b/kernel/util/font_platform_windows.go
@@ -22,6 +22,7 @@ package util
#cgo LDFLAGS: -ldwrite
#define COBJMACROS
#include <dwrite.h>
+#include <dwrite_1.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -34,6 +35,7 @@ typedef struct {
char *style;
char *localizedStyle;
int weight;
+ int spacing;
char **aliases;
size_t aliasCount;
} SiyuanWindowsFont;
@@ -42,6 +44,26 @@ static const GUID siyuanIIDIDWriteFactory = {
0xb859ee5a, 0xd838, 0x4b5b, {0xa2, 0xe8, 0x1a, 0xdc, 0x7d, 0x93, 0xdb, 0x48}
};
+static const GUID siyuanIIDIDWriteFont1 = {
+ 0xacd16696, 0x8c14, 0x4f5d, {0x87, 0x7e, 0xfe, 0x3f, 0xc1, 0xd3, 0x27, 0x37}
+};
+
+enum {
+ SIYUAN_FONT_SPACING_UNKNOWN = 0,
+ SIYUAN_FONT_SPACING_PROPORTIONAL = 1,
+ SIYUAN_FONT_SPACING_MONOSPACE = 2,
+};
+
+// siyuanGetFontSpacing 读取 DirectWrite 对字体等宽属性的判断。
+static int siyuanGetFontSpacing(IDWriteFont *font) {
+ IDWriteFont1 *font1 = NULL;
+ HRESULT result = IDWriteFont_QueryInterface(font, &siyuanIIDIDWriteFont1, (void **)&font1);
+ if (FAILED(result) || !font1) return SIYUAN_FONT_SPACING_UNKNOWN;
+ BOOL monospace = IDWriteFont1_IsMonospacedFont(font1);
+ IDWriteFont1_Release(font1);
+ return monospace ? SIYUAN_FONT_SPACING_MONOSPACE : SIYUAN_FONT_SPACING_PROPORTIONAL;
+}
+
// siyuanCopyWideStringAsUTF8 将 UTF-16 字符串复制为由调用方释放的 UTF-8 字符串。
static char *siyuanCopyWideStringAsUTF8(const WCHAR *value) {
if (!value || !value[0]) return NULL;
@@ -263,6 +285,7 @@ static int32_t siyuanCopyAvailableFonts(const char *localeUTF8, SiyuanWindowsFon
font.style = siyuanCopyWideStringAsUTF8(stableStyle);
font.localizedStyle = siyuanCopyWideStringAsUTF8(localizedStyle);
font.weight = (int)IDWriteFont_GetWeight(directWriteFont);
+ font.spacing = siyuanGetFontSpacing(directWriteFont);
BOOL appended = font.family &&
siyuanAppendLocalizedAliases(&font, familyNames) &&
siyuanAppendLocalizedAliases(&font, faceNames) &&
@@ -351,6 +374,7 @@ func loadPlatformFonts() (ret []*Font) {
Weight: weight,
DisplayName: displayName,
Aliases: aliases,
+ Spacing: directWriteFontSpacing(int(font.spacing)),
})
}
return
@@ -362,3 +386,14 @@ func directWriteString(value *C.char) string {
}
return strings.TrimSpace(C.GoString(value))
}
+
+func directWriteFontSpacing(spacing int) string {
+ switch spacing {
+ case C.SIYUAN_FONT_SPACING_PROPORTIONAL:
+ return FontSpacingProportional
+ case C.SIYUAN_FONT_SPACING_MONOSPACE:
+ return FontSpacingMonospace
+ default:
+ return ""
+ }
+}
diff --git a/kernel/util/font_platform_windows_test.go b/kernel/util/font_platform_windows_test.go
index cf2259342f..7256612946 100644
--- a/kernel/util/font_platform_windows_test.go
+++ b/kernel/util/font_platform_windows_test.go
@@ -32,6 +32,7 @@ func TestLoadDirectWriteFonts(t *testing.T) {
t.Fatal("DirectWrite should return at least one system font")
}
hasAliases := false
+ hasKnownSpacing := false
for _, font := range fonts {
if font.Family == "" || font.DisplayName == "" {
t.Fatalf("DirectWrite returned an invalid font: %+v", font)
@@ -42,8 +43,16 @@ func TestLoadDirectWriteFonts(t *testing.T) {
if 0 < len(font.Aliases) {
hasAliases = true
}
+ if FontSpacingProportional == font.Spacing || FontSpacingMonospace == font.Spacing {
+ hasKnownSpacing = true
+ } else if "" != font.Spacing {
+ t.Fatalf("DirectWrite returned an invalid font spacing: %+v", font)
+ }
}
if !hasAliases {
t.Fatal("DirectWrite should return localized font aliases")
}
+ if !hasKnownSpacing {
+ t.Fatal("DirectWrite should return font spacing metadata")
+ }
}
diff --git a/kernel/util/font_test.go b/kernel/util/font_test.go
index 70bb1ddc68..c57dae004c 100644
--- a/kernel/util/font_test.go
+++ b/kernel/util/font_test.go
@@ -64,12 +64,14 @@ func TestAddFontMergesAliases(t *testing.T) {
Weight: 400,
DisplayName: "霞鹜文楷",
Aliases: []string{"LXGW WenKai Regular"},
+ Spacing: FontSpacingProportional,
})
fonts = addFont(fonts, &Font{
Family: "LXGW WenKai",
Weight: 400,
DisplayName: "LXGW WenKai",
Aliases: []string{"霞鹜文楷 常规体"},
+ Spacing: FontSpacingMonospace,
})
if len(fonts) != 1 {
@@ -80,6 +82,18 @@ func TestAddFontMergesAliases(t *testing.T) {
t.Fatalf("merged font alias %q is missing from %v", expected, fonts[0].Aliases)
}
}
+ if FontSpacingMonospace != fonts[0].Spacing {
+ t.Fatalf("unexpected merged font spacing: %+v", fonts[0])
+ }
+ fonts = addFont(fonts, &Font{
+ Family: "LXGW WenKai",
+ Weight: 400,
+ DisplayName: "LXGW WenKai",
+ Spacing: FontSpacingProportional,
+ })
+ if FontSpacingMonospace != fonts[0].Spacing {
+ t.Fatalf("proportional metadata replaced monospace metadata: %+v", fonts[0])
+ }
}
func TestParseBundledFontLocalizedName(t *testing.T) {
@@ -110,6 +124,9 @@ func TestParseBundledFontLocalizedName(t *testing.T) {
if !slices.Contains(font.Aliases, font.Family) {
t.Fatalf("stable font family is missing from aliases: %+v", font)
}
+ if FontSpacingProportional != font.Spacing {
+ t.Fatalf("unexpected bundled font spacing: %+v", font)
+ }
}
func TestInferFontWeight(t *testing.T) {
diff --git a/kernel/util/fontconfig.go b/kernel/util/fontconfig.go
index d3435a5bc5..890fffc357 100644
--- a/kernel/util/fontconfig.go
+++ b/kernel/util/fontconfig.go
@@ -35,7 +35,7 @@ const (
"%{[]fullname,fullnamelang{" + fontconfigValueSeparator + "%{fullname}" + fontconfigPairSeparator +
"%{fullnamelang}}}" + fontconfigFieldSeparator +
"%{[]postscriptname{" + fontconfigValueSeparator + "%{postscriptname}}}" + fontconfigFieldSeparator +
- "%{weight}" + fontconfigRecordSeparator
+ "%{weight}" + fontconfigFieldSeparator + "%{spacing}" + fontconfigRecordSeparator
)
type fontconfigLocalizedName struct {
@@ -49,7 +49,7 @@ func parseFontconfigFonts(data []byte, lang string) (ret []*Font) {
continue
}
fields := bytes.Split(record, []byte(fontconfigFieldSeparator))
- if 5 != len(fields) {
+ if 6 != len(fields) {
continue
}
@@ -92,6 +92,7 @@ func parseFontconfigFonts(data []byte, lang string) (ret []*Font) {
Weight: weight,
DisplayName: displayName,
Aliases: aliases,
+ Spacing: parseFontconfigSpacing(string(fields[5])),
})
}
return
@@ -217,3 +218,22 @@ func parseFontconfigWeight(value, style string) int {
}
return 1000
}
+
+func parseFontconfigSpacing(value string) string {
+ spacing, err := strconv.Atoi(strings.TrimSpace(value))
+ if nil != err {
+ return ""
+ }
+ switch spacing {
+ case 0:
+ return FontSpacingProportional
+ case 90:
+ return FontSpacingDual
+ case 100:
+ return FontSpacingMonospace
+ case 110:
+ return FontSpacingCharacterCell
+ default:
+ return ""
+ }
+}
diff --git a/kernel/util/fontconfig_test.go b/kernel/util/fontconfig_test.go
index af123ede59..624aede6c2 100644
--- a/kernel/util/fontconfig_test.go
+++ b/kernel/util/fontconfig_test.go
@@ -26,14 +26,15 @@ func TestParseFontconfigFonts(t *testing.T) {
fontconfigValueSeparator + "LXGW WenKai Regular" + fontconfigPairSeparator + "en" +
fontconfigValueSeparator + "霞鹜文楷 常规" + fontconfigPairSeparator + "zh-cn" +
fontconfigFieldSeparator + fontconfigValueSeparator + "LXGWWenKai-Regular" +
- fontconfigFieldSeparator + "80" + fontconfigRecordSeparator
+ fontconfigFieldSeparator + "80" + fontconfigFieldSeparator + "90" + fontconfigRecordSeparator
fonts := parseFontconfigFonts([]byte(data), "zh-CN")
if 1 != len(fonts) {
t.Fatalf("expected one font, got %d", len(fonts))
}
font := fonts[0]
- if "LXGW WenKai" != font.Family || "霞鹜文楷" != font.DisplayName || 400 != font.Weight {
+ if "LXGW WenKai" != font.Family || "霞鹜文楷" != font.DisplayName || 400 != font.Weight ||
+ FontSpacingDual != font.Spacing {
t.Fatalf("unexpected font: %+v", font)
}
for _, expected := range []string{"常规", "LXGW WenKai Regular", "LXGWWenKai-Regular"} {
@@ -81,6 +82,21 @@ func TestParseFontconfigWeight(t *testing.T) {
}
}
+func TestParseFontconfigSpacing(t *testing.T) {
+ tests := map[string]string{
+ "0": FontSpacingProportional,
+ "90": FontSpacingDual,
+ "100": FontSpacingMonospace,
+ "110": FontSpacingCharacterCell,
+ "": "",
+ }
+ for input, expected := range tests {
+ if actual := parseFontconfigSpacing(input); expected != actual {
+ t.Fatalf("expected spacing %q for %q, got %q", expected, input, actual)
+ }
+ }
+}
+
func containsFontconfigAlias(aliases []string, expected string) bool {
for _, alias := range aliases {
if alias == expected {