Skip to content

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

:bug: Improve Linux system font enumeration with Fontconfig https://github.com/siyuan-note/siyuan/issues/18808

Danielb401f300f952
diff --git a/kernel/util/font_platform_linux.go b/kernel/util/font_platform_linux.go
new file mode 100644
index 0000000000..9557e1ecb7
--- /dev/null
+++ b/kernel/util/font_platform_linux.go
@@ -0,0 +1,47 @@
+// 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 linux && !android
+
+package util
+
+import (
+ "context"
+ "os/exec"
+ "time"
+
+ "github.com/siyuan-note/logging"
+)
+
+func loadPlatformFonts() []*Font {
+ path, err := exec.LookPath("fc-list")
+ if nil != err {
+ return nil
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ output, err := exec.CommandContext(ctx, path, "-f", fontconfigListFormat).Output()
+ if nil != err {
+ if ctx.Err() == context.DeadlineExceeded {
+ logging.LogWarnf("load Fontconfig fonts timed out")
+ } else {
+ logging.LogWarnf("load Fontconfig fonts failed: %s", err)
+ }
+ return nil
+ }
+ return parseFontconfigFonts(output, Lang)
+}
diff --git a/kernel/util/font_platform_linux_test.go b/kernel/util/font_platform_linux_test.go
new file mode 100644
index 0000000000..a3c2b42e44
--- /dev/null
+++ b/kernel/util/font_platform_linux_test.go
@@ -0,0 +1,42 @@
+// 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 linux && !android
+
+package util
+
+import (
+ "os/exec"
+ "testing"
+)
+
+func TestLoadFontconfigFonts(t *testing.T) {
+ if _, err := exec.LookPath("fc-list"); nil != err {
+ t.Skip("fc-list is unavailable")
+ }
+ fonts := loadPlatformFonts()
+ if 0 == len(fonts) {
+ t.Fatal("Fontconfig should return at least one system font")
+ }
+ for _, font := range fonts {
+ if "" == font.Family || "" == font.DisplayName {
+ t.Fatalf("Fontconfig returned an invalid font: %+v", font)
+ }
+ if font.Weight < 1 || 1000 < font.Weight {
+ t.Fatalf("Fontconfig returned an invalid font weight: %+v", font)
+ }
+ }
+}
diff --git a/kernel/util/font_platform_other.go b/kernel/util/font_platform_other.go
index 4dd44ebdcf..c3c9b424ba 100644
--- a/kernel/util/font_platform_other.go
+++ b/kernel/util/font_platform_other.go
@@ -14,7 +14,7 @@
// 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 && !windows) || ios
+//go:build (!darwin && !windows && !linux) || ios || android
package util
diff --git a/kernel/util/fontconfig.go b/kernel/util/fontconfig.go
new file mode 100644
index 0000000000..d3435a5bc5
--- /dev/null
+++ b/kernel/util/fontconfig.go
@@ -0,0 +1,219 @@
+// 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 (
+ "bytes"
+ "math"
+ "strconv"
+ "strings"
+)
+
+const (
+ fontconfigPairSeparator = "\x1c"
+ fontconfigValueSeparator = "\x1d"
+ fontconfigRecordSeparator = "\x1e"
+ fontconfigFieldSeparator = "\x1f"
+ fontconfigListFormat = "%{[]family,familylang{" + fontconfigValueSeparator + "%{family}" +
+ fontconfigPairSeparator + "%{familylang}}}" + fontconfigFieldSeparator +
+ "%{[]style,stylelang{" + fontconfigValueSeparator + "%{style}" + fontconfigPairSeparator +
+ "%{stylelang}}}" + fontconfigFieldSeparator +
+ "%{[]fullname,fullnamelang{" + fontconfigValueSeparator + "%{fullname}" + fontconfigPairSeparator +
+ "%{fullnamelang}}}" + fontconfigFieldSeparator +
+ "%{[]postscriptname{" + fontconfigValueSeparator + "%{postscriptname}}}" + fontconfigFieldSeparator +
+ "%{weight}" + fontconfigRecordSeparator
+)
+
+type fontconfigLocalizedName struct {
+ Value string
+ Lang string
+}
+
+func parseFontconfigFonts(data []byte, lang string) (ret []*Font) {
+ for _, record := range bytes.Split(data, []byte(fontconfigRecordSeparator)) {
+ if 0 == len(record) {
+ continue
+ }
+ fields := bytes.Split(record, []byte(fontconfigFieldSeparator))
+ if 5 != len(fields) {
+ continue
+ }
+
+ families := parseFontconfigLocalizedNames(string(fields[0]))
+ styles := parseFontconfigLocalizedNames(string(fields[1]))
+ fullNames := parseFontconfigLocalizedNames(string(fields[2]))
+ postscriptNames := parseFontconfigValues(string(fields[3]))
+ family := selectFontconfigName(families, "en")
+ if "" == family {
+ family = selectFontconfigName(families, lang)
+ }
+ if "" == family || strings.HasPrefix(family, ".") {
+ continue
+ }
+
+ localizedFamily := selectFontconfigName(families, lang)
+ if "" == localizedFamily {
+ localizedFamily = family
+ }
+ style := selectFontconfigName(styles, "en")
+ localizedStyle := selectFontconfigName(styles, lang)
+ if "" == localizedStyle {
+ localizedStyle = style
+ }
+ displayName := localizedFamily
+ if "" != style && !strings.EqualFold(style, "Regular") {
+ displayName += " " + localizedStyle
+ }
+
+ var aliases []string
+ aliases = appendFontconfigLocalizedAliases(aliases, families)
+ aliases = appendFontconfigLocalizedAliases(aliases, styles)
+ aliases = appendFontconfigLocalizedAliases(aliases, fullNames)
+ for _, name := range postscriptNames {
+ aliases = appendFontAlias(aliases, name)
+ }
+ weight := parseFontconfigWeight(string(fields[4]), style)
+ ret = addFont(ret, &Font{
+ Family: family,
+ Weight: weight,
+ DisplayName: displayName,
+ Aliases: aliases,
+ })
+ }
+ return
+}
+
+func parseFontconfigLocalizedNames(value string) (ret []fontconfigLocalizedName) {
+ for _, item := range strings.Split(value, fontconfigValueSeparator) {
+ item = strings.TrimSpace(item)
+ if "" == item {
+ continue
+ }
+ parts := strings.SplitN(item, fontconfigPairSeparator, 2)
+ name := strings.TrimSpace(parts[0])
+ if "" == name {
+ continue
+ }
+ localizedName := fontconfigLocalizedName{Value: name}
+ if 1 < len(parts) {
+ localizedName.Lang = normalizeFontconfigLanguage(parts[1])
+ }
+ ret = append(ret, localizedName)
+ }
+ return
+}
+
+func parseFontconfigValues(value string) (ret []string) {
+ for _, item := range strings.Split(value, fontconfigValueSeparator) {
+ if item = strings.TrimSpace(item); "" != item {
+ ret = append(ret, item)
+ }
+ }
+ return
+}
+
+func selectFontconfigName(names []fontconfigLocalizedName, lang string) string {
+ lang = normalizeFontconfigLanguage(LangToBCP47(lang))
+ for _, name := range names {
+ if lang == name.Lang && "" != name.Value {
+ return name.Value
+ }
+ }
+ for _, name := range names {
+ if fontconfigLanguagesMatch(lang, name.Lang) && "" != name.Value {
+ return name.Value
+ }
+ }
+ for _, name := range names {
+ if "" != name.Value {
+ return name.Value
+ }
+ }
+ return ""
+}
+
+func fontconfigLanguagesMatch(left, right string) bool {
+ if "" == left || "" == right {
+ return false
+ }
+ leftPrimary := strings.SplitN(left, "-", 2)[0]
+ rightPrimary := strings.SplitN(right, "-", 2)[0]
+ if leftPrimary != rightPrimary {
+ return false
+ }
+ if "zh" != leftPrimary {
+ return true
+ }
+ leftGroup := fontconfigChineseLanguageGroup(left)
+ rightGroup := fontconfigChineseLanguageGroup(right)
+ return "" == leftGroup || "" == rightGroup || leftGroup == rightGroup
+}
+
+func fontconfigChineseLanguageGroup(lang string) string {
+ switch normalizeFontconfigLanguage(lang) {
+ case "zh-cn", "zh-sg", "zh-hans":
+ return "simplified"
+ case "zh-tw", "zh-hk", "zh-mo", "zh-hant":
+ return "traditional"
+ default:
+ return ""
+ }
+}
+
+func normalizeFontconfigLanguage(lang string) string {
+ return strings.ToLower(strings.ReplaceAll(strings.TrimSpace(lang), "_", "-"))
+}
+
+func appendFontconfigLocalizedAliases(aliases []string, names []fontconfigLocalizedName) []string {
+ for _, name := range names {
+ aliases = appendFontAlias(aliases, name.Value)
+ }
+ return aliases
+}
+
+func parseFontconfigWeight(value, style string) int {
+ weight, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
+ if nil != err || weight < 0 || 215 < weight {
+ return inferFontWeight(400, style)
+ }
+ points := [...]struct {
+ fontconfig float64
+ css float64
+ }{
+ {fontconfig: 0, css: 100},
+ {fontconfig: 40, css: 200},
+ {fontconfig: 50, css: 300},
+ {fontconfig: 55, css: 350},
+ {fontconfig: 75, css: 380},
+ {fontconfig: 80, css: 400},
+ {fontconfig: 100, css: 500},
+ {fontconfig: 180, css: 600},
+ {fontconfig: 200, css: 700},
+ {fontconfig: 205, css: 800},
+ {fontconfig: 210, css: 900},
+ {fontconfig: 215, css: 1000},
+ }
+ for i := 1; i < len(points); i++ {
+ if weight <= points[i].fontconfig {
+ previous := points[i-1]
+ current := points[i]
+ ratio := (weight - previous.fontconfig) / (current.fontconfig - previous.fontconfig)
+ return int(math.Round(previous.css + ratio*(current.css-previous.css)))
+ }
+ }
+ return 1000
+}
diff --git a/kernel/util/fontconfig_test.go b/kernel/util/fontconfig_test.go
new file mode 100644
index 0000000000..af123ede59
--- /dev/null
+++ b/kernel/util/fontconfig_test.go
@@ -0,0 +1,91 @@
+// 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 "testing"
+
+func TestParseFontconfigFonts(t *testing.T) {
+ data := fontconfigValueSeparator + "LXGW WenKai" + fontconfigPairSeparator + "en" +
+ fontconfigValueSeparator + "霞鹜文楷" + fontconfigPairSeparator + "zh-cn" + fontconfigFieldSeparator +
+ fontconfigValueSeparator + "Regular" + fontconfigPairSeparator + "en" +
+ fontconfigValueSeparator + "常规" + fontconfigPairSeparator + "zh-cn" + fontconfigFieldSeparator +
+ fontconfigValueSeparator + "LXGW WenKai Regular" + fontconfigPairSeparator + "en" +
+ fontconfigValueSeparator + "霞鹜文楷 常规" + fontconfigPairSeparator + "zh-cn" +
+ fontconfigFieldSeparator + fontconfigValueSeparator + "LXGWWenKai-Regular" +
+ fontconfigFieldSeparator + "80" + 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 {
+ t.Fatalf("unexpected font: %+v", font)
+ }
+ for _, expected := range []string{"常规", "LXGW WenKai Regular", "LXGWWenKai-Regular"} {
+ if !containsFontconfigAlias(font.Aliases, expected) {
+ t.Fatalf("expected alias %q in %+v", expected, font.Aliases)
+ }
+ }
+}
+
+func TestSelectFontconfigNameKeepsChineseVariantsSeparate(t *testing.T) {
+ names := []fontconfigLocalizedName{
+ {Value: "Simplified", Lang: "zh-CN"},
+ {Value: "Traditional", Lang: "zh-TW"},
+ }
+ if actual := selectFontconfigName(names, "zh-Hant"); "Traditional" != actual {
+ t.Fatalf("expected Traditional, got %q", actual)
+ }
+ if actual := selectFontconfigName(names, "zh-Hans"); "Simplified" != actual {
+ t.Fatalf("expected Simplified, got %q", actual)
+ }
+}
+
+func TestParseFontconfigWeight(t *testing.T) {
+ tests := map[string]int{
+ "0": 100,
+ "40": 200,
+ "50": 300,
+ "55": 350,
+ "75": 380,
+ "80": 400,
+ "100": 500,
+ "180": 600,
+ "200": 700,
+ "205": 800,
+ "210": 900,
+ "215": 1000,
+ }
+ for input, expected := range tests {
+ if actual := parseFontconfigWeight(input, ""); expected != actual {
+ t.Fatalf("expected weight %d for %s, got %d", expected, input, actual)
+ }
+ }
+ if actual := parseFontconfigWeight("invalid", "Bold"); 700 != actual {
+ t.Fatalf("expected inferred bold weight, got %d", actual)
+ }
+}
+
+func containsFontconfigAlias(aliases []string, expected string) bool {
+ for _, alias := range aliases {
+ if alias == expected {
+ return true
+ }
+ }
+ return false
+}