Skip to content

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

:bug: Improve system font enumeration and localized name matching https://github.com/siyuan-note/siyuan/issues/18808

Daniel463f01e8cea3
diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.ts
index 150f6dad04..61a8867f41 100644
--- a/app/src/config/tabs/appearanceTab.ts
+++ b/app/src/config/tabs/appearanceTab.ts
@@ -43,6 +43,7 @@ interface IFontItem {
family: string;
weight: number;
displayName: string;
+ aliases?: string[];
}
const registerAppearanceContentGroup = (tab: SettingTabBuilder) => {
@@ -100,8 +101,9 @@ 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-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-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>`;
@@ -130,12 +132,18 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {
const curFamily = fontFamilyEl.dataset.family;
const curWeight = parseInt(fontFamilyEl.dataset.weight || "400", 10);
+ const fontItems = [...customFonts, ...systemFonts];
+ const selectedFont = fontItems.find((item) => item.family === curFamily && item.weight === curWeight);
+ if (selectedFont) {
+ fontFamilyEl.value = selectedFont.displayName;
+ fontFamilyEl.dataset.display = selectedFont.displayName;
+ }
const defaultItemHtml = genFontListItemHtml({
family: "",
displayName: window.siyuan.languages.default,
weight: 400,
}, curFamily === "");
- const fontItemHtml = [...customFonts, ...systemFonts].map((item) =>
+ const fontItemHtml = fontItems.map((item) =>
genFontListItemHtml(item, item.family === curFamily && item.weight === curWeight)
).join("");
const canManageCustomFonts = nativeMobile && !window.siyuan.config.readonly;
@@ -195,7 +203,7 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {
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.family.toLowerCase().includes(value) || name.toLowerCase().includes(value)));
+ item.dataset.search.includes(value)));
const idx = name.toLowerCase().indexOf(value);
item.replaceChildren(document.createTextNode(name));
if (idx !== -1 && value) {
diff --git a/app/src/util/customFont.ts b/app/src/util/customFont.ts
index 47210b4361..a15bda37a6 100644
--- a/app/src/util/customFont.ts
+++ b/app/src/util/customFont.ts
@@ -7,6 +7,7 @@ export interface ICustomFont {
family: string;
weight: number;
displayName: string;
+ aliases?: string[];
url: string;
}
diff --git a/kernel/util/custom_font.go b/kernel/util/custom_font.go
index 650ac79668..7aa906b8da 100644
--- a/kernel/util/custom_font.go
+++ b/kernel/util/custom_font.go
@@ -37,17 +37,19 @@ const (
)
type CustomFont struct {
- ID string `json:"id"`
- Family string `json:"family"`
- Weight int `json:"weight"`
- DisplayName string `json:"displayName"`
- URL string `json:"url"`
+ ID string `json:"id"`
+ Family string `json:"family"`
+ Weight int `json:"weight"`
+ DisplayName string `json:"displayName"`
+ Aliases []string `json:"aliases,omitempty"`
+ URL string `json:"url"`
path string
}
var (
customFonts []*CustomFont
customFontsLoaded bool
+ customFontsLang string
customFontsLock sync.Mutex
customFontTemps = map[string]struct{}{}
)
@@ -208,7 +210,7 @@ func GetCustomFontFile(id string) (string, *CustomFont, bool) {
}
func loadCustomFontsLocked() {
- if customFontsLoaded {
+ if customFontsLoaded && customFontsLang == Lang {
return
}
cleanupCustomFontTempsLocked()
@@ -217,6 +219,7 @@ func loadCustomFontsLocked() {
entries, err := os.ReadDir(CustomFontDir())
if err != nil {
customFontsLoaded = true
+ customFontsLang = Lang
return
}
@@ -274,6 +277,7 @@ func loadCustomFontsLocked() {
return customFonts[i].DisplayName < customFonts[j].DisplayName
})
customFontsLoaded = true
+ customFontsLang = Lang
}
func cleanupCustomFontTempsLocked() {
@@ -353,6 +357,7 @@ func newCustomFont(id, fontPath string, font *Font) *CustomFont {
Family: CustomFontFamilyPrefix + id,
Weight: weight,
DisplayName: font.DisplayName,
+ Aliases: mergeFontAliases(nil, append(append([]string(nil), font.Aliases...), font.Family), font.DisplayName),
URL: "/custom-fonts/" + id,
path: fontPath,
}
@@ -368,5 +373,6 @@ func cloneCustomFonts(fonts []*CustomFont) (ret []*CustomFont) {
func cloneCustomFont(font *CustomFont) *CustomFont {
ret := *font
+ ret.Aliases = append([]string(nil), font.Aliases...)
return &ret
}
diff --git a/kernel/util/custom_font_test.go b/kernel/util/custom_font_test.go
index 80b6d35521..b550df9f46 100644
--- a/kernel/util/custom_font_test.go
+++ b/kernel/util/custom_font_test.go
@@ -53,6 +53,9 @@ func TestCustomFontLifecycle(t *testing.T) {
if font.DisplayName == "" || font.Weight < 1 {
t.Fatalf("unexpected custom font metadata: %+v", font)
}
+ if len(font.Aliases) == 0 {
+ t.Fatalf("custom font aliases are missing: %+v", font)
+ }
fonts := LoadCustomFonts()
if len(fonts) != 1 || fonts[0].ID != font.ID {
@@ -192,6 +195,7 @@ func resetCustomFontCache() {
customFontsLock.Lock()
customFonts = nil
customFontsLoaded = false
+ customFontsLang = ""
customFontTemps = map[string]struct{}{}
customFontsLock.Unlock()
}
diff --git a/kernel/util/font.go b/kernel/util/font.go
index 76b2505e0c..95b1626f4b 100644
--- a/kernel/util/font.go
+++ b/kernel/util/font.go
@@ -25,6 +25,8 @@ import (
"strings"
"sync"
"time"
+ "unicode"
+ "unicode/utf8"
"github.com/ConradIrwin/font/sfnt"
"github.com/flopp/go-findfont"
@@ -33,6 +35,7 @@ import (
var (
sysFonts []*Font
+ sysFontsLang string
sysFontsLock = sync.Mutex{}
)
@@ -40,12 +43,13 @@ func LoadSysFonts() []*Font {
sysFontsLock.Lock()
defer sysFontsLock.Unlock()
- if 0 < len(sysFonts) {
+ if 0 < len(sysFonts) && sysFontsLang == Lang {
return sysFonts
}
start := time.Now()
sysFonts = loadFonts()
+ sysFontsLang = Lang
sort.Slice(sysFonts, func(i, j int) bool {
return sysFonts[i].DisplayName < sysFonts[j].DisplayName
@@ -56,9 +60,45 @@ func LoadSysFonts() []*Font {
}
type Font struct {
- Family string `json:"family"` // 对应 CSS font-family
- Weight int `json:"weight"` // 对应 CSS font-weight
- DisplayName string `json:"displayName"` // 给人看的名称 (Family + Subfamily)
+ Family string `json:"family"` // 对应 CSS font-family
+ Weight int `json:"weight"` // 对应 CSS font-weight
+ DisplayName string `json:"displayName"` // 给人看的名称 (Family + Subfamily)
+ Aliases []string `json:"aliases,omitempty"` // 用于字体搜索的本地化名称和内部名称
+}
+
+type fontLanguage struct {
+ PlatformID sfnt.PlatformID
+ LanguageID sfnt.PlatformLanguageID
+}
+
+var microsoftFontLanguageIDs = map[string][]sfnt.PlatformLanguageID{
+ "ar": {0x0401},
+ "de": {0x0407},
+ "en": {0x0409},
+ "es": {0x0c0a, 0x040a},
+ "fr": {0x040c},
+ "he": {0x040d},
+ "hi": {0x0439},
+ "id": {0x0421},
+ "it": {0x0410},
+ "ja": {0x0411},
+ "ko": {0x0412},
+ "nl": {0x0413},
+ "pl": {0x0415},
+ "pt-BR": {0x0416},
+ "ru": {0x0419},
+ "sk": {0x041b},
+ "th": {0x041e},
+ "tr": {0x041f},
+ "uk": {0x0422},
+ "zh-CN": {0x0804, 0x1004},
+ "zh-TW": {0x0404, 0x0c04, 0x1404},
+}
+
+var macFontLanguageIDs = map[string]sfnt.PlatformLanguageID{
+ "ar": 12, "de": 2, "en": 0, "es": 6, "fr": 1, "he": 10, "hi": 21, "id": 81,
+ "it": 3, "ja": 11, "ko": 23, "nl": 4, "pl": 25, "pt-BR": 8, "ru": 32, "sk": 39,
+ "th": 22, "tr": 17, "uk": 45, "zh-CN": 33, "zh-TW": 19,
}
func loadFonts() (ret []*Font) {
@@ -67,34 +107,34 @@ func loadFonts() (ret []*Font) {
if strings.HasSuffix(strings.ToLower(fontPath), ".ttc") {
families := parseTTCFontFamily(fontPath)
for _, f := range families {
- if existFont(f, ret) {
- continue
- }
-
- ret = append(ret, f)
+ ret = addFont(ret, f)
//LogInfof("[%s] [%s]", fontPath, family)
}
} else if strings.HasSuffix(strings.ToLower(fontPath), ".otf") || strings.HasSuffix(strings.ToLower(fontPath), ".ttf") {
for _, f := range parseTTFFontFamily(fontPath) {
- if existFont(f, ret) {
- continue
- }
-
- ret = append(ret, f)
+ ret = addFont(ret, f)
//logging.LogInfof("[%s] [%s]", fontPath, family)
}
}
}
+ for _, font := range loadPlatformFonts() {
+ ret = addFont(ret, font)
+ }
return
}
-func existFont(f *Font, fonts []*Font) bool {
+func addFont(fonts []*Font, f *Font) []*Font {
+ if nil == f || "" == f.Family {
+ return fonts
+ }
for _, font := range fonts {
if strings.EqualFold(f.Family, font.Family) && f.Weight == font.Weight {
- return true
+ font.Aliases = mergeFontAliases(font.Aliases, f.Aliases, font.Family, font.DisplayName)
+ return fonts
}
}
- return false
+ f.Aliases = mergeFontAliases(nil, f.Aliases, f.Family, f.DisplayName)
+ return append(fonts, f)
}
func parseTTCFontFamily(fontPath string) (ret []*Font) {
@@ -143,11 +183,11 @@ func parseFont(font *sfnt.Font) (ret []*Font) {
return nil
}
ret = append(ret, defaultFont)
- ret = append(ret, parseFontVariations(font, defaultFont.Family)...)
+ ret = append(ret, parseFontVariations(font, defaultFont)...)
return
}
-func parseFontVariations(font *sfnt.Font, family string) (ret []*Font) {
+func parseFontVariations(font *sfnt.Font, defaultFont *Font) (ret []*Font) {
defer logging.Recover()
// 可变字体通过 fvar 表声明字重等可变轴,named instances 提供了命名的字重实例
@@ -186,6 +226,10 @@ func parseFontVariations(font *sfnt.Font, family string) (ret []*Font) {
return nil
}
entries := t.List()
+ localizedFamily := selectLocalizedFontName(entries, sfnt.NamePreferredFamily, sfnt.NameFontFamily)
+ if "" == localizedFamily {
+ localizedFamily = defaultFont.Family
+ }
instancesBase := axesArrayOffset + axisCount*axisSize
for i := 0; i < instanceCount; i++ {
base := instancesBase + i*instanceSize
@@ -199,12 +243,23 @@ func parseFontVariations(font *sfnt.Font, family string) (ret []*Font) {
if "" == subfamily {
continue
}
+ localizedSubfamily := selectLocalizedFontName(entries, sfnt.NameID(subfamilyNameID))
+ if "" == localizedSubfamily {
+ localizedSubfamily = subfamily
+ }
- displayName := family
+ displayName := localizedFamily
if !strings.EqualFold(subfamily, "Regular") {
- displayName = family + " " + subfamily
+ displayName = localizedFamily + " " + localizedSubfamily
}
- ret = append(ret, &Font{Family: family, Weight: weight, DisplayName: displayName})
+ aliases := collectFontAliases(entries, sfnt.NameID(subfamilyNameID))
+ aliases = append(aliases, defaultFont.Aliases...)
+ ret = append(ret, &Font{
+ Family: defaultFont.Family,
+ Weight: weight,
+ DisplayName: displayName,
+ Aliases: aliases,
+ })
}
return
}
@@ -218,6 +273,14 @@ func parseFontInfo(font *sfnt.Font) (*Font, error) {
entries := t.List()
family := selectFontName(entries, sfnt.NamePreferredFamily, sfnt.NameFontFamily)
subfamily := selectFontName(entries, sfnt.NamePreferredSubfamily, sfnt.NameFontSubfamily)
+ localizedFamily := selectLocalizedFontName(entries, sfnt.NamePreferredFamily, sfnt.NameFontFamily)
+ localizedSubfamily := selectLocalizedFontName(entries, sfnt.NamePreferredSubfamily, sfnt.NameFontSubfamily)
+ if "" == localizedFamily {
+ localizedFamily = family
+ }
+ if "" == localizedSubfamily {
+ localizedSubfamily = subfamily
+ }
weight := 400
os2, err := font.OS2Table()
@@ -225,85 +288,75 @@ func parseFontInfo(font *sfnt.Font) (*Font, error) {
weight = int(os2.USWeightClass)
}
- if weight == 400 && subfamily != "" {
- s := strings.ToLower(subfamily)
- // 自动匹配 W01-W09
- for i := 1; i <= 9; i++ {
- wStr := "w0" + strconv.Itoa(i)
- if strings.Contains(s, wStr) {
- weight = i * 100
- break
- }
- }
-
- // 自动匹配 W1-W9(部分字体使用不带前导零的缩写)
- if weight == 400 {
- for i := 1; i <= 9; i++ {
- wStr := "w" + strconv.Itoa(i)
- if strings.Contains(s, wStr) {
- weight = i * 100
- break
- }
- }
- }
-
- // 自动匹配标准关键词
- if weight == 400 { // 如果 W 系列没匹配到
- switch {
- case strings.Contains(s, "thin"):
- weight = 100
- case strings.Contains(s, "light"):
- weight = 300
- case strings.Contains(s, "medium"):
- weight = 500
- case strings.Contains(s, "semibold") || strings.Contains(s, "demi"):
- weight = 600
- case strings.Contains(s, "bold"):
- weight = 700
- case strings.Contains(s, "black") || strings.Contains(s, "heavy"):
- weight = 900
- }
- }
- }
+ weight = inferFontWeight(weight, subfamily)
if family == "" || strings.HasPrefix(family, ".") {
return nil, errors.New("font family is empty")
}
- displayName := family
+ displayName := localizedFamily
if subfamily != "" && !strings.EqualFold(subfamily, "Regular") {
- displayName = family + " " + subfamily
+ displayName = localizedFamily + " " + localizedSubfamily
}
+ aliases := collectFontAliases(entries,
+ sfnt.NamePreferredFamily, sfnt.NameFontFamily, sfnt.NameWWSFamily,
+ sfnt.NamePreferredSubfamily, sfnt.NameFontSubfamily, sfnt.NameWWSSubfamily,
+ sfnt.NameFull, sfnt.NameCompatibleFull, sfnt.NamePostscript)
return &Font{
Family: family,
Weight: weight,
DisplayName: displayName,
+ Aliases: aliases,
}, nil
}
func selectFontName(entries []*sfnt.NameEntry, nameIDs ...sfnt.NameID) string {
+ return selectFontNameWithLanguages(entries, []fontLanguage{
+ {PlatformID: sfnt.PlatformMicrosoft, LanguageID: sfnt.PlatformLanguageID(1033)},
+ {PlatformID: sfnt.PlatformMac, LanguageID: sfnt.PlatformLanguageID(0)},
+ }, nameIDs...)
+}
+
+func selectLocalizedFontName(entries []*sfnt.NameEntry, nameIDs ...sfnt.NameID) string {
+ for _, language := range preferredFontLanguages(Lang) {
+ for _, nameID := range nameIDs {
+ for _, entry := range entries {
+ if entry.NameID == nameID && entry.PlatformID == language.PlatformID &&
+ entry.LanguageID == language.LanguageID {
+ if value := fontNameValue(entry); "" != value {
+ return value
+ }
+ }
+ }
+ }
+ }
+ return selectFontName(entries, nameIDs...)
+}
+
+func selectFontNameWithLanguages(entries []*sfnt.NameEntry, languages []fontLanguage, nameIDs ...sfnt.NameID) string {
for _, nameID := range nameIDs {
var selected string
- selectedScore := 4
+ selectedScore := len(languages) + 2
for _, entry := range entries {
if entry.NameID != nameID {
continue
}
- value := strings.Trim(strings.TrimSpace(entry.String()), "\x00")
+ value := fontNameValue(entry)
if value == "" {
continue
}
- score := 3
- switch {
- case entry.LanguageID == sfnt.PlatformLanguageID(1033):
- score = 0
- case entry.LanguageID == sfnt.PlatformLanguageID(2052):
- score = 1
- case entry.PlatformID == sfnt.PlatformUnicode:
- score = 2
+ score := len(languages) + 1
+ for i, language := range languages {
+ if entry.PlatformID == language.PlatformID && entry.LanguageID == language.LanguageID {
+ score = i
+ break
+ }
+ }
+ if score == len(languages)+1 && entry.PlatformID == sfnt.PlatformUnicode {
+ score = len(languages)
}
if score < selectedScore {
selected = value
@@ -316,3 +369,147 @@ func selectFontName(entries []*sfnt.NameEntry, nameIDs ...sfnt.NameID) string {
}
return ""
}
+
+func preferredFontLanguages(lang string) (ret []fontLanguage) {
+ lang = LangToBCP47(lang)
+ for _, languageID := range microsoftFontLanguageIDs[lang] {
+ ret = append(ret, fontLanguage{PlatformID: sfnt.PlatformMicrosoft, LanguageID: languageID})
+ }
+ if languageID, ok := macFontLanguageIDs[lang]; ok {
+ ret = append(ret, fontLanguage{PlatformID: sfnt.PlatformMac, LanguageID: languageID})
+ }
+ return
+}
+
+func fontNameValue(entry *sfnt.NameEntry) string {
+ value := strings.Trim(strings.TrimSpace(entry.String()), "\x00")
+ if "" == value || !utf8.ValidString(value) {
+ return ""
+ }
+ for _, r := range value {
+ if unicode.IsControl(r) && !unicode.IsSpace(r) {
+ return ""
+ }
+ }
+ return value
+}
+
+func collectFontAliases(entries []*sfnt.NameEntry, nameIDs ...sfnt.NameID) (ret []string) {
+ for _, entry := range entries {
+ matched := false
+ for _, nameID := range nameIDs {
+ if entry.NameID == nameID {
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ continue
+ }
+ if value := fontNameValue(entry); "" != value {
+ ret = appendFontAlias(ret, value)
+ }
+ }
+ return
+}
+
+func mergeFontAliases(base, aliases []string, excluded ...string) (ret []string) {
+ for _, alias := range base {
+ ret = appendFontAlias(ret, alias)
+ }
+ for _, alias := range aliases {
+ ret = appendFontAlias(ret, alias)
+ }
+ filtered := ret[:0]
+ for _, alias := range ret {
+ exclude := false
+ for _, value := range excluded {
+ if strings.EqualFold(alias, value) {
+ exclude = true
+ break
+ }
+ }
+ if !exclude {
+ filtered = append(filtered, alias)
+ }
+ }
+ return filtered
+}
+
+func appendFontAlias(aliases []string, alias string) []string {
+ alias = strings.TrimSpace(alias)
+ if "" == alias {
+ return aliases
+ }
+ for _, existing := range aliases {
+ if strings.EqualFold(existing, alias) {
+ return aliases
+ }
+ }
+ return append(aliases, alias)
+}
+
+func inferFontWeight(weight int, subfamily string) int {
+ if weight != 400 || "" == subfamily {
+ return weight
+ }
+ s := strings.ToLower(subfamily)
+ // 自动匹配 W01-W09
+ for i := 1; i <= 9; i++ {
+ if strings.Contains(s, "w0"+strconv.Itoa(i)) {
+ return i * 100
+ }
+ }
+ // 自动匹配 W1-W9(部分字体使用不带前导零的缩写)
+ for i := 1; i <= 9; i++ {
+ if strings.Contains(s, "w"+strconv.Itoa(i)) {
+ return i * 100
+ }
+ }
+ // 自动匹配标准关键词
+ switch {
+ case strings.Contains(s, "thin") || strings.Contains(s, "hairline"):
+ return 100
+ case strings.Contains(s, "extra light") || strings.Contains(s, "extralight") || strings.Contains(s, "ultra light") || strings.Contains(s, "ultralight"):
+ return 200
+ case strings.Contains(s, "light"):
+ return 300
+ case strings.Contains(s, "medium"):
+ return 500
+ case strings.Contains(s, "semibold") || strings.Contains(s, "semi bold") || strings.Contains(s, "demi"):
+ return 600
+ case strings.Contains(s, "extra bold") || strings.Contains(s, "extrabold") || strings.Contains(s, "ultra bold") || strings.Contains(s, "ultrabold"):
+ return 800
+ case strings.Contains(s, "bold"):
+ return 700
+ case strings.Contains(s, "black"):
+ return 900
+ case strings.Contains(s, "heavy"):
+ return 900
+ }
+ return weight
+}
+
+func fontWeightFromNormalizedTrait(weight float64, style string) int {
+ if inferred := inferFontWeight(400, style); inferred != 400 {
+ return inferred
+ }
+ switch {
+ case weight <= -0.5:
+ return 100
+ case weight <= -0.25:
+ return 300
+ case weight < 0.15:
+ return 400
+ case weight < 0.28:
+ return 500
+ case weight < 0.35:
+ return 600
+ case weight < 0.5:
+ return 700
+ case weight < 0.6:
+ return 800
+ default:
+ return 900
+ }
+}
diff --git a/kernel/util/font_platform_darwin.go b/kernel/util/font_platform_darwin.go
new file mode 100644
index 0000000000..6cf82edca1
--- /dev/null
+++ b/kernel/util/font_platform_darwin.go
@@ -0,0 +1,167 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//go:build darwin && !ios
+
+package util
+
+/*
+#cgo CFLAGS: -x objective-c
+#cgo LDFLAGS: -framework CoreText -framework Foundation
+#include <stdlib.h>
+#include <string.h>
+#import <CoreText/CoreText.h>
+#import <Foundation/Foundation.h>
+
+// siyuanCopyDescriptorString 读取字体描述符字符串,并在需要时使用系统首选语言返回本地化值。
+static NSString *siyuanCopyDescriptorString(CTFontDescriptorRef descriptor, CFStringRef attribute, BOOL localized) {
+ CFTypeRef value = localized
+ ? CTFontDescriptorCopyLocalizedAttribute(descriptor, attribute, NULL)
+ : CTFontDescriptorCopyAttribute(descriptor, attribute);
+ if (!value) return nil;
+
+ NSString *ret = nil;
+ if (CFGetTypeID(value) == CFStringGetTypeID()) {
+ ret = [(NSString *)value copy];
+ }
+ CFRelease(value);
+ return [ret autorelease];
+}
+
+// siyuanAppendFontAlias 添加非空且不重复的字体检索别名。
+static void siyuanAppendFontAlias(NSMutableArray *aliases, NSString *value) {
+ if ([value length] == 0 || [aliases containsObject:value]) return;
+ [aliases addObject:value];
+}
+
+// siyuanCopyAvailableFontsJSON 通过 CoreText 枚举当前应用可用字体,包括不在常规字体目录中的系统字体。
+static char *siyuanCopyAvailableFontsJSON(void) {
+ @autoreleasepool {
+ NSMutableArray *fonts = [NSMutableArray array];
+ CTFontCollectionRef collection = CTFontCollectionCreateFromAvailableFonts(NULL);
+ if (collection) {
+ CFArrayRef descriptors = CTFontCollectionCreateMatchingFontDescriptors(collection);
+ CFRelease(collection);
+ if (descriptors) {
+ CFIndex count = CFArrayGetCount(descriptors);
+ for (CFIndex i = 0; i < count; i++) {
+ CTFontDescriptorRef descriptor =
+ (CTFontDescriptorRef)CFArrayGetValueAtIndex(descriptors, i);
+ NSString *family = siyuanCopyDescriptorString(descriptor, kCTFontFamilyNameAttribute, NO);
+ if ([family length] == 0 || [family hasPrefix:@"."]) continue;
+
+ NSString *localizedFamily =
+ siyuanCopyDescriptorString(descriptor, kCTFontFamilyNameAttribute, YES);
+ NSString *style = siyuanCopyDescriptorString(descriptor, kCTFontStyleNameAttribute, NO);
+ NSString *localizedStyle =
+ siyuanCopyDescriptorString(descriptor, kCTFontStyleNameAttribute, YES);
+ NSString *displayName =
+ siyuanCopyDescriptorString(descriptor, kCTFontDisplayNameAttribute, NO);
+ NSString *localizedDisplayName =
+ siyuanCopyDescriptorString(descriptor, kCTFontDisplayNameAttribute, YES);
+ NSString *postscriptName =
+ siyuanCopyDescriptorString(descriptor, kCTFontNameAttribute, NO);
+
+ double weight = 0;
+ CFTypeRef traitsValue = CTFontDescriptorCopyAttribute(descriptor, kCTFontTraitsAttribute);
+ if (traitsValue && CFGetTypeID(traitsValue) == CFDictionaryGetTypeID()) {
+ CFNumberRef weightValue = (CFNumberRef)CFDictionaryGetValue(
+ (CFDictionaryRef)traitsValue, kCTFontWeightTrait);
+ if (weightValue && CFGetTypeID(weightValue) == CFNumberGetTypeID()) {
+ CFNumberGetValue(weightValue, kCFNumberDoubleType, &weight);
+ }
+ }
+ if (traitsValue) CFRelease(traitsValue);
+
+ NSMutableArray *aliases = [NSMutableArray array];
+ siyuanAppendFontAlias(aliases, localizedFamily);
+ siyuanAppendFontAlias(aliases, style);
+ siyuanAppendFontAlias(aliases, localizedStyle);
+ siyuanAppendFontAlias(aliases, displayName);
+ siyuanAppendFontAlias(aliases, localizedDisplayName);
+ siyuanAppendFontAlias(aliases, postscriptName);
+
+ [fonts addObject:@{
+ @"family": family,
+ @"displayName": [localizedDisplayName length] ? localizedDisplayName :
+ ([displayName length] ? displayName : family),
+ @"style": [style length] ? style : @"",
+ @"weight": @(weight),
+ @"aliases": aliases,
+ }];
+ }
+ CFRelease(descriptors);
+ }
+ }
+
+ NSData *data = [NSJSONSerialization dataWithJSONObject:fonts options:0 error:nil];
+ if (!data) return strdup("[]");
+ char *ret = malloc([data length] + 1);
+ if (!ret) return NULL;
+ memcpy(ret, [data bytes], [data length]);
+ ret[[data length]] = '\0';
+ return ret;
+ }
+}
+*/
+import "C"
+
+import (
+ "encoding/json"
+ "strings"
+ "unsafe"
+
+ "github.com/siyuan-note/logging"
+)
+
+type coreTextFont struct {
+ Family string `json:"family"`
+ DisplayName string `json:"displayName"`
+ Style string `json:"style"`
+ Weight float64 `json:"weight"`
+ Aliases []string `json:"aliases"`
+}
+
+func loadPlatformFonts() (ret []*Font) {
+ data := C.siyuanCopyAvailableFontsJSON()
+ if nil == data {
+ return nil
+ }
+ defer C.free(unsafe.Pointer(data))
+
+ var coreTextFonts []*coreTextFont
+ if err := json.Unmarshal([]byte(C.GoString(data)), &coreTextFonts); err != nil {
+ logging.LogWarnf("load CoreText fonts failed: %s", err)
+ return nil
+ }
+ for _, font := range coreTextFonts {
+ font.Family = strings.TrimSpace(font.Family)
+ font.DisplayName = strings.TrimSpace(font.DisplayName)
+ if "" == font.Family || strings.HasPrefix(font.Family, ".") {
+ continue
+ }
+ if "" == font.DisplayName {
+ font.DisplayName = font.Family
+ }
+ ret = addFont(ret, &Font{
+ Family: font.Family,
+ Weight: fontWeightFromNormalizedTrait(font.Weight, font.Style),
+ DisplayName: font.DisplayName,
+ Aliases: font.Aliases,
+ })
+ }
+ return
+}
diff --git a/kernel/util/font_platform_darwin_test.go b/kernel/util/font_platform_darwin_test.go
new file mode 100644
index 0000000000..c1251a4547
--- /dev/null
+++ b/kernel/util/font_platform_darwin_test.go
@@ -0,0 +1,33 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//go:build darwin && !ios
+
+package util
+
+import "testing"
+
+func TestLoadPlatformFonts(t *testing.T) {
+ fonts := loadPlatformFonts()
+ if len(fonts) == 0 {
+ t.Fatal("CoreText returned no available fonts")
+ }
+ for _, font := range fonts {
+ if "" == font.Family || "" == font.DisplayName || font.Weight < 1 || 1000 < font.Weight {
+ t.Fatalf("invalid CoreText font: %+v", font)
+ }
+ }
+}
diff --git a/kernel/util/font_platform_other.go b/kernel/util/font_platform_other.go
new file mode 100644
index 0000000000..e5b8fb53f0
--- /dev/null
+++ b/kernel/util/font_platform_other.go
@@ -0,0 +1,23 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//go:build !darwin || ios
+
+package util
+
+func loadPlatformFonts() []*Font {
+ return nil
+}
diff --git a/kernel/util/font_test.go b/kernel/util/font_test.go
new file mode 100644
index 0000000000..70bb1ddc68
--- /dev/null
+++ b/kernel/util/font_test.go
@@ -0,0 +1,147 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package util
+
+import (
+ "encoding/binary"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "unicode/utf16"
+
+ "github.com/ConradIrwin/font/sfnt"
+)
+
+func TestLocalizedFontNamesAndAliases(t *testing.T) {
+ oldLang := Lang
+ Lang = "zh-CN"
+ t.Cleanup(func() {
+ Lang = oldLang
+ })
+
+ entries := []*sfnt.NameEntry{
+ newMicrosoftFontNameEntry(sfnt.NamePreferredFamily, 1033, "LXGW WenKai"),
+ newMicrosoftFontNameEntry(sfnt.NameFontFamily, 2052, "霞鹜文楷"),
+ newMicrosoftFontNameEntry(sfnt.NamePreferredSubfamily, 1033, "Regular"),
+ newMicrosoftFontNameEntry(sfnt.NamePreferredSubfamily, 2052, "常规体"),
+ newMicrosoftFontNameEntry(sfnt.NameFull, 1033, "LXGW WenKai Regular"),
+ newMicrosoftFontNameEntry(sfnt.NameFull, 2052, "霞鹜文楷 常规体"),
+ }
+
+ if actual := selectFontName(entries, sfnt.NamePreferredFamily); actual != "LXGW WenKai" {
+ t.Fatalf("unexpected stable font family: %s", actual)
+ }
+ if actual := selectLocalizedFontName(entries, sfnt.NamePreferredFamily, sfnt.NameFontFamily); actual != "霞鹜文楷" {
+ t.Fatalf("unexpected localized font family: %s", actual)
+ }
+ aliases := collectFontAliases(entries, sfnt.NamePreferredFamily, sfnt.NameFontFamily, sfnt.NameFull)
+ for _, expected := range []string{"LXGW WenKai", "霞鹜文楷", "LXGW WenKai Regular", "霞鹜文楷 常规体"} {
+ if !slices.Contains(aliases, expected) {
+ t.Fatalf("font alias %q is missing from %v", expected, aliases)
+ }
+ }
+}
+
+func TestAddFontMergesAliases(t *testing.T) {
+ fonts := addFont(nil, &Font{
+ Family: "LXGW WenKai",
+ Weight: 400,
+ DisplayName: "霞鹜文楷",
+ Aliases: []string{"LXGW WenKai Regular"},
+ })
+ fonts = addFont(fonts, &Font{
+ Family: "LXGW WenKai",
+ Weight: 400,
+ DisplayName: "LXGW WenKai",
+ Aliases: []string{"霞鹜文楷 常规体"},
+ })
+
+ if len(fonts) != 1 {
+ t.Fatalf("duplicate font was not merged: %+v", fonts)
+ }
+ for _, expected := range []string{"LXGW WenKai Regular", "霞鹜文楷 常规体"} {
+ if !slices.Contains(fonts[0].Aliases, expected) {
+ t.Fatalf("merged font alias %q is missing from %v", expected, fonts[0].Aliases)
+ }
+ }
+}
+
+func TestParseBundledFontLocalizedName(t *testing.T) {
+ oldLang := Lang
+ Lang = "zh-CN"
+ t.Cleanup(func() {
+ Lang = oldLang
+ })
+
+ fontPath := filepath.Join("..", "..", "app", "appearance", "fonts", "LxgwWenKai-Lite-1.501",
+ "LXGWWenKaiLite-Regular.ttf")
+ fontFile, err := os.Open(fontPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer fontFile.Close()
+ parsed, err := sfnt.Parse(fontFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ font, err := parseFontInfo(parsed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(font.DisplayName, "霞鹜") {
+ t.Fatalf("unexpected localized font display name: %+v", font)
+ }
+ if !slices.Contains(font.Aliases, font.Family) {
+ t.Fatalf("stable font family is missing from aliases: %+v", font)
+ }
+}
+
+func TestInferFontWeight(t *testing.T) {
+ tests := map[string]int{
+ "UltraLight": 200,
+ "Light": 300,
+ "Medium": 500,
+ "SemiBold": 600,
+ "Bold": 700,
+ "ExtraBold": 800,
+ "Heavy": 900,
+ "Black": 900,
+ "W03": 300,
+ }
+ for style, expected := range tests {
+ if actual := inferFontWeight(400, style); actual != expected {
+ t.Fatalf("unexpected weight for %s: %d", style, actual)
+ }
+ }
+}
+
+func newMicrosoftFontNameEntry(nameID sfnt.NameID, languageID uint16, value string) *sfnt.NameEntry {
+ encodedRunes := utf16.Encode([]rune(value))
+ encoded := make([]byte, len(encodedRunes)*2)
+ for i, r := range encodedRunes {
+ binary.BigEndian.PutUint16(encoded[i*2:], r)
+ }
+ return &sfnt.NameEntry{
+ PlatformID: sfnt.PlatformMicrosoft,
+ EncodingID: sfnt.PlatformEncodingMicrosoftUnicode,
+ LanguageID: sfnt.PlatformLanguageID(languageID),
+ NameID: nameID,
+ Value: encoded,
+ }
+}