An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support importing custom fonts on mobile https://github.com/siyuan-note/siyuan/issues/18422
Daniel6fa0d99c8202
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex c667cea954..8ca0faf7fe 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "هل تريد حذف الخط المخصص <b>${x}</b>؟",+ "fontFileTip": "تُدعم فقط ملفات خطوط TTF وOTF التي يصل حجمها إلى 64 ميغابايت",+ "importFont": "استيراد خط","returnLabel": "عودة","useDefaultVerticalAlign": "استخدام المحاذاة العمودية الافتراضية","useDefaultHorizontalAlign": "استخدام المحاذاة الأفقية الافتراضية",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 937743cd86..c0616cabed 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Benutzerdefinierte Schriftart <b>${x}</b> löschen?",+ "fontFileTip": "Es werden nur TTF- und OTF-Schriftdateien bis 64 MB unterstützt",+ "importFont": "Schriftart importieren","returnLabel": "Zurück","useDefaultVerticalAlign": "Standardmäßige vertikale Ausrichtung verwenden","useDefaultHorizontalAlign": "Standardmäßige horizontale Ausrichtung verwenden",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex cce1a7b34f..e3202b8579 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Delete custom font <b>${x}</b>?",+ "fontFileTip": "Only TTF and OTF font files up to 64 MB are supported",+ "importFont": "Import font","returnLabel": "Return","useDefaultVerticalAlign": "Use default vertical alignment","useDefaultHorizontalAlign": "Use default horizontal alignment",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex f642fe7b2a..37e139abff 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "¿Eliminar la fuente personalizada <b>${x}</b>?",+ "fontFileTip": "Solo se admiten archivos de fuentes TTF y OTF de hasta 64 MB",+ "importFont": "Importar fuente","returnLabel": "Volver","useDefaultVerticalAlign": "Usar alineación vertical predeterminada","useDefaultHorizontalAlign": "Usar alineación horizontal predeterminada",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex a21259eda0..4f39ae153f 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Supprimer la police personnalisée <b>${x}</b> ?",+ "fontFileTip": "Seuls les fichiers de police TTF et OTF jusqu’à 64 Mo sont pris en charge",+ "importFont": "Importer une police","returnLabel": "Retour","useDefaultVerticalAlign": "Utiliser l’alignement vertical par défaut","useDefaultHorizontalAlign": "Utiliser l’alignement horizontal par défaut",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 6e824b0ed5..6154bfed63 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "למחוק את הגופן המותאם אישית <b>${x}</b>?",+ "fontFileTip": "נתמכים רק קובצי גופן מסוג TTF ו-OTF בגודל של עד 64 MB",+ "importFont": "ייבוא גופן","returnLabel": "חזרה","useDefaultVerticalAlign": "שימוש ביישור האנכי המוגדר כברירת מחדל","useDefaultHorizontalAlign": "שימוש ביישור האופקי המוגדר כברירת מחדל",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 596f7f5843..3a00628ae7 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "कस्टम फ़ॉन्ट <b>${x}</b> हटाएँ?",+ "fontFileTip": "केवल 64 MB तक की TTF और OTF फ़ॉन्ट फ़ाइलें समर्थित हैं",+ "importFont": "फ़ॉन्ट आयात करें","returnLabel": "वापस","useDefaultVerticalAlign": "डिफ़ॉल्ट लंबवत संरेखण का उपयोग करें","useDefaultHorizontalAlign": "डिफ़ॉल्ट क्षैतिज संरेखण का उपयोग करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 9a25ba125f..c98c3a55f2 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Hapus font khusus <b>${x}</b>?",+ "fontFileTip": "Hanya file font TTF dan OTF hingga 64 MB yang didukung",+ "importFont": "Impor font","returnLabel": "Kembali","useDefaultVerticalAlign": "Gunakan perataan vertikal bawaan","useDefaultHorizontalAlign": "Gunakan perataan horizontal bawaan",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex babb467314..2d06a7cae3 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Eliminare il carattere personalizzato <b>${x}</b>?",+ "fontFileTip": "Sono supportati solo file di caratteri TTF e OTF fino a 64 MB",+ "importFont": "Importa carattere","returnLabel": "Indietro","useDefaultVerticalAlign": "Usa l’allineamento verticale predefinito","useDefaultHorizontalAlign": "Usa l’allineamento orizzontale predefinito",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 041225711f..6ad0cdec46 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "カスタムフォント <b>${x}</b> を削除しますか?",+ "fontFileTip": "64 MB 以下の TTF および OTF フォントファイルのみ対応しています",+ "importFont": "フォントをインポート","returnLabel": "戻る","useDefaultVerticalAlign": "デフォルトの垂直方向配置を使用","useDefaultHorizontalAlign": "デフォルトの水平方向配置を使用",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 9fba1d8cbf..2dc952b9c1 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "사용자 정의 글꼴 <b>${x}</b>을(를) 삭제하시겠습니까?",+ "fontFileTip": "64 MB 이하의 TTF 및 OTF 글꼴 파일만 지원됩니다",+ "importFont": "글꼴 가져오기","returnLabel": "돌아가기","useDefaultVerticalAlign": "기본 세로 맞춤 사용","useDefaultHorizontalAlign": "기본 가로 맞춤 사용",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 5b463c1bab..3bd6e8d000 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Aangepast lettertype <b>${x}</b> verwijderen?",+ "fontFileTip": "Alleen TTF- en OTF-lettertypebestanden tot 64 MB worden ondersteund",+ "importFont": "Lettertype importeren","returnLabel": "Terug","useDefaultVerticalAlign": "Standaard verticale uitlijning gebruiken","useDefaultHorizontalAlign": "Standaard horizontale uitlijning gebruiken",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex ca882167fa..41c1ac4163 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Usunąć niestandardową czcionkę <b>${x}</b>?",+ "fontFileTip": "Obsługiwane są tylko pliki czcionek TTF i OTF o rozmiarze do 64 MB",+ "importFont": "Importuj czcionkę","returnLabel": "Wróć","useDefaultVerticalAlign": "Użyj domyślnego wyrównania w pionie","useDefaultHorizontalAlign": "Użyj domyślnego wyrównania w poziomie",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 62c21f119b..9bd8992ded 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Excluir a fonte personalizada <b>${x}</b>?",+ "fontFileTip": "Apenas arquivos de fonte TTF e OTF de até 64 MB são compatíveis",+ "importFont": "Importar fonte","returnLabel": "Voltar","useDefaultVerticalAlign": "Usar alinhamento vertical padrão","useDefaultHorizontalAlign": "Usar alinhamento horizontal padrão",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 29a7ac4813..81e33422ee 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Удалить пользовательский шрифт <b>${x}</b>?",+ "fontFileTip": "Поддерживаются только файлы шрифтов TTF и OTF размером до 64 МБ",+ "importFont": "Импортировать шрифт","returnLabel": "Вернуться","useDefaultVerticalAlign": "Использовать вертикальное выравнивание по умолчанию","useDefaultHorizontalAlign": "Использовать горизонтальное выравнивание по умолчанию",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex c548bd71ba..4146d7f4fb 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Odstrániť vlastné písmo <b>${x}</b>?",+ "fontFileTip": "Podporované sú iba súbory písiem TTF a OTF s veľkosťou do 64 MB",+ "importFont": "Importovať písmo","returnLabel": "Späť","useDefaultVerticalAlign": "Použiť predvolené zvislé zarovnanie","useDefaultHorizontalAlign": "Použiť predvolené vodorovné zarovnanie",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex dd5514b84e..599a1794bf 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "ลบแบบอักษรกำหนดเอง <b>${x}</b> หรือไม่?",+ "fontFileTip": "รองรับเฉพาะไฟล์แบบอักษร TTF และ OTF ที่มีขนาดไม่เกิน 64 MB",+ "importFont": "นำเข้าแบบอักษร","returnLabel": "กลับ","useDefaultVerticalAlign": "ใช้การจัดแนวตั้งเริ่มต้น","useDefaultHorizontalAlign": "ใช้การจัดแนวนอนเริ่มต้น",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 193bc2e0f4..4696f63e08 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Özel yazı tipi <b>${x}</b> silinsin mi?",+ "fontFileTip": "Yalnızca 64 MB boyutuna kadar TTF ve OTF yazı tipi dosyaları desteklenir",+ "importFont": "Yazı tipi içe aktar","returnLabel": "Geri dön","useDefaultVerticalAlign": "Varsayılan dikey hizalamayı kullan","useDefaultHorizontalAlign": "Varsayılan yatay hizalamayı kullan",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex e079498b33..71f27aa4ef 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "Видалити користувацький шрифт <b>${x}</b>?",+ "fontFileTip": "Підтримуються лише файли шрифтів TTF і OTF розміром до 64 МБ",+ "importFont": "Імпортувати шрифт","returnLabel": "Повернутися","useDefaultVerticalAlign": "Використовувати вертикальне вирівнювання за замовчуванням","useDefaultHorizontalAlign": "Використовувати горизонтальне вирівнювання за замовчуванням",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex cb9a0b3a1d..cddb35465b 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "确定删除自定义字体 <b>${x}</b> 吗?",+ "fontFileTip": "仅支持不超过 64 MB 的 TTF 和 OTF 字体文件",+ "importFont": "导入字体","returnLabel": "返回","useDefaultVerticalAlign": "使用默认垂直对齐","useDefaultHorizontalAlign": "使用默认水平对齐",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex b8f47eff29..af51676836 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,7 @@{+ "deleteFontConfirm": "確定刪除自訂字型 <b>${x}</b> 嗎?",+ "fontFileTip": "僅支援不超過 64 MB 的 TTF 和 OTF 字型檔案",+ "importFont": "匯入字型","returnLabel": "返回","useDefaultVerticalAlign": "使用預設垂直對齊","useDefaultHorizontalAlign": "使用預設水平對齊",diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.tsindex 43b9eab552..0ef511d6d7 100644--- a/app/src/config/tabs/appearanceTab.ts+++ b/app/src/config/tabs/appearanceTab.ts@@ -11,21 +11,31 @@ import {updateHotkeyTip} from "../../protyle/util/compatibility";import {desktopModeCookie} from "../../util/cookie";import {isMobile, objEquals} from "../../util/functions";import {exitSiYuan} from "../../dialog/processSystem";-import {fetchPost} from "../../util/fetch";+import {fetchPost, fetchSyncPost} from "../../util/fetch";import {openByMobile} from "../../editor/openLink";import {openSnippets} from "../util/snippets";import {confirmDialog} from "../../dialog/confirmDialog";import {Dialog} from "../../dialog";import {Menu} from "../../plugin/Menu";-import {escapeAttr} from "../../util/escape";+import {escapeAttr, escapeHtml} from "../../util/escape";import {genConfigItemMainHtml, genListSwitchItemHtml} from "../render/fragments";import {genStackHtml} from "../render/render";import {controlBoolean} from "../setting/control";import {editorConfigApi} from "./editorRuntime";import {appearanceThemeModeValue, saveThemeMode} from "./appearanceRuntime";import {upDownHint} from "../../util/upDownHint";+import {+ ICustomFont,+ invalidateCustomFonts,+ isNativeMobileContainer,+ loadCustomFonts,+ registerCustomFont,+ unregisterCustomFont+} from "../../util/customFont";+import {showMessage} from "../../dialog/message";interface IFontItem {+ id?: string;family: string;weight: number;displayName: string;@@ -49,8 +59,6 @@ const registerAppearanceContentGroup = (tab: SettingTabBuilder) => {data-display="${escapeAttr(window.siyuan.config.editor.fontFamilyDisplay)}"value="${escapeAttr(window.siyuan.config.editor.fontFamilyDisplay || window.siyuan.config.editor.fontFamily || window.siyuan.languages.default)}"readonly- style="font-family: ${window.siyuan.config.editor.fontFamily ? window.siyuan.config.editor.fontFamily + ", var(--b3-font-family)" : "var(--b3-font-family)"};- ${window.siyuan.config.editor.fontWeight ? `font-weight: ${window.siyuan.config.editor.fontWeight};` : ""}"></div>`,afterMount: mountAppearanceFontFamily,@@ -88,9 +96,10 @@ const registerAppearanceContentGroup = (tab: SettingTabBuilder) => {};const genFontListItemHtml = (item: IFontItem, checked: boolean) => {- return `<div class="b3-list-item b3-list-item--narrow">- <span class="b3-menu__label" data-family="${item.family}" style='font-family:"${item.family}", var(--b3-font-family);${item.weight ? ` font-weight: ${item.weight};` : ""}'>${item.displayName}</span>+ 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>${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>`;};@@ -99,97 +108,168 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {if (!fontFamilyEl) {return;}- fontFamilyEl.addEventListener("click", () => {- fetchPost("/api/system/getSysFonts", {}, (response) => {- const curFamily = fontFamilyEl.dataset.family;- const curWeight = parseInt(fontFamilyEl.style.fontWeight || "400", 10);- const defaultItemHtml = genFontListItemHtml({- family: "",- displayName: window.siyuan.languages.default,- weight: 400,- }, curFamily === "");- const fontItemHtml = response.data.map((item: IFontItem) =>- genFontListItemHtml(item, item.family === curFamily && item.weight === curWeight)- ).join("");- const fontMenu = new Menu();- fontMenu.addItem({- iconHTML: "",- type: "empty",- label: `<div class="fn__flex-column b3-menu__filter">- <input class="b3-text-field fn__block" placeholder="${window.siyuan.languages.search}">+ updateFontInput(window.siyuan.config.editor);+ fontFamilyEl.addEventListener("click", async () => {+ const nativeMobile = isNativeMobileContainer();+ let systemResponse: IWebSocketData;+ let customFonts: ICustomFont[];+ try {+ [systemResponse, customFonts] = await Promise.all([+ fetchSyncPost("/api/system/getSysFonts"),+ nativeMobile ? loadCustomFonts() : Promise.resolve([] as ICustomFont[])+ ]);+ } catch (error) {+ console.warn("load font list failed", error);+ return;+ }+ const systemFonts = Array.isArray(systemResponse.data) ? systemResponse.data as IFontItem[] : [];+ customFonts.forEach(registerCustomFont);++ const curFamily = fontFamilyEl.dataset.family;+ const curWeight = parseInt(fontFamilyEl.dataset.weight || "400", 10);+ const defaultItemHtml = genFontListItemHtml({+ family: "",+ displayName: window.siyuan.languages.default,+ weight: 400,+ }, curFamily === "");+ const fontItemHtml = [...customFonts, ...systemFonts].map((item) =>+ genFontListItemHtml(item, item.family === curFamily && item.weight === curWeight)+ ).join("");+ const canManageCustomFonts = nativeMobile && !window.siyuan.config.readonly;+ const fontMenu = new Menu();+ fontMenu.addItem({+ iconHTML: "",+ type: "empty",+ 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.search)}">+ ${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>` : ""}+ ${canManageCustomFonts ? '<input class="fn__none" data-type="font-file" type="file" accept=".ttf,.otf,font/ttf,font/otf">' : ""}<div class="fn__hr"></div><div class="b3-list fn__flex-1 b3-list--background">${defaultItemHtml}${fontItemHtml}</div></div>`,- bind(element) {- const listElement = element.querySelector(".b3-list");- listElement.firstElementChild.classList.add("b3-list-item--focus");- const inputElement = element.querySelector("input");- const filterFontList = () => {- const value = inputElement.value.toLowerCase().trim();- listElement.querySelector(".b3-list-item--focus")?.classList.add("b3-list-item--focus");- listElement.querySelectorAll<HTMLElement>(".b3-list-item .b3-menu__label").forEach((item) => {- const name = item.textContent.trim();- item.parentElement.classList.toggle("fn__none", !(!value || item.dataset.family.toLowerCase().includes(value) || name.toLowerCase().includes(value)));- const idx = name.toLowerCase().indexOf(value);- if (idx === -1 || !value) {- item.innerHTML = name;- } else {- item.innerHTML = `${name.slice(0, idx)}<mark>${name.slice(idx, idx + value.length)}</mark>${name.slice(idx + value.length)}`;- }- });- listElement.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");- };- inputElement.addEventListener("keydown", (event: KeyboardEvent) => {- event.stopPropagation();- if (event.isComposing) {- return;- }- upDownHint(listElement, event);- if (event.key === "Enter") {- const itemEl = listElement.querySelector(".b3-list-item--focus .b3-menu__label") as HTMLElement;- persistEditorFont({- family: itemEl.dataset.family,- displayName: itemEl.textContent.trim(),- weight: parseInt(itemEl.style.fontWeight) || 400- });- fontMenu.close();- } else if (event.key === "Escape") {- window.siyuan.menus.menu.remove();+ bind(element) {+ const listElement = element.querySelector<HTMLElement>(".b3-list");+ listElement.firstElementChild.classList.add("b3-list-item--focus");+ const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-search"]');+ listElement.querySelectorAll<HTMLElement>(".b3-menu__label").forEach((item) => {+ item.style.fontFamily = item.dataset.family;+ item.style.fontWeight = item.dataset.weight;+ });+ const 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.family.toLowerCase().includes(value) || name.toLowerCase().includes(value)));+ const idx = name.toLowerCase().indexOf(value);+ item.replaceChildren(document.createTextNode(name));+ if (idx !== -1 && value) {+ const markElement = document.createElement("mark");+ markElement.textContent = name.slice(idx, idx + value.length);+ item.replaceChildren(+ document.createTextNode(name.slice(0, idx)),+ markElement,+ document.createTextNode(name.slice(idx + value.length))+ );}});- inputElement.addEventListener("input", (event: InputEvent) => {- if (event.isComposing) {- return;+ listElement.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");+ };+ inputElement.addEventListener("keydown", (event: KeyboardEvent) => {+ event.stopPropagation();+ if (event.isComposing) {+ return;+ }+ upDownHint(listElement, event);+ if (event.key === "Enter") {+ const itemEl = listElement.querySelector<HTMLElement>(".b3-list-item--focus .b3-menu__label");+ if (itemEl) {+ persistEditorFont(fontItemFromElement(itemEl));+ fontMenu.close();}+ } else if (event.key === "Escape") {+ window.siyuan.menus.menu.remove();+ }+ });+ inputElement.addEventListener("input", (event: InputEvent) => {+ if (!event.isComposing) {filterFontList();- });- inputElement.addEventListener("compositionend", filterFontList);- // 列表点击委托,读取 dataset 应用选中逻辑- listElement.addEventListener("click", (event) => {- const target = event.target as HTMLElement;- const itemEl = target.closest(".b3-list-item")?.querySelector(".b3-menu__label") as HTMLElement;- if (!itemEl) {- return;- }- persistEditorFont({- family: itemEl.dataset.family,- displayName: itemEl.textContent.trim(),- weight: parseInt(itemEl.style.fontWeight) || 400- });+ }+ });+ inputElement.addEventListener("compositionend", filterFontList);+ element.querySelector<HTMLElement>('[data-type="import-font"]')?.addEventListener("click", () => {+ element.querySelector<HTMLInputElement>('[data-type="font-file"]').click();+ });+ element.querySelector<HTMLInputElement>('[data-type="font-file"]')?.addEventListener("change", (event) => {+ const fileInput = event.currentTarget as HTMLInputElement;+ const file = fileInput.files?.[0];+ fileInput.value = "";+ if (!file) {+ return;+ }+ if (file.size > 64 * 1024 * 1024) {+ showMessage(window.siyuan.languages.fontFileTip, 6000, "error");+ return;+ }+ const formData = new FormData();+ formData.append("file", file);+ fetchPost("/api/system/importCustomFont", formData, (response) => {+ const font = response.data as ICustomFont;+ invalidateCustomFonts();+ registerCustomFont(font);+ persistEditorFont(font);+ showMessage(window.siyuan.languages.imported);fontMenu.close();});- }- });- const rect = fontFamilyEl.getBoundingClientRect();- fontMenu.open({x: rect.left, y: rect.bottom, h: rect.height});- // 内部列表自行滚动,搜索框保持固定- fontMenu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");- fontMenu.element.querySelector("input").focus();+ });+ listElement.addEventListener("click", (event) => {+ const target = event.target as HTMLElement;+ const itemElement = target.closest<HTMLElement>(".b3-list-item");+ const itemEl = itemElement?.querySelector<HTMLElement>(".b3-menu__label");+ if (!itemEl) {+ return;+ }+ if (target.closest('[data-type="delete-font"]')) {+ const id = itemElement.dataset.id;+ confirmDialog(+ window.siyuan.languages.deleteOpConfirm,+ window.siyuan.languages.deleteFontConfirm.replace(+ "${x}", `<b>${escapeHtml(itemEl.dataset.name)}</b>`),+ () => {+ fetchPost("/api/system/removeCustomFont", {id}, (response) => {+ unregisterCustomFont(id);+ invalidateCustomFonts();+ if (response.data.editor) {+ editorConfigApi.apply(response.data.editor);+ updateFontInput(response.data.editor);+ }+ fontMenu.close();+ });+ },+ undefined,+ true+ );+ return;+ }+ persistEditorFont(fontItemFromElement(itemEl));+ fontMenu.close();+ });+ }});+ const rect = fontFamilyEl.getBoundingClientRect();+ fontMenu.open({x: rect.left, y: rect.bottom, h: rect.height});+ // 内部列表自行滚动,搜索框保持固定+ fontMenu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");+ fontMenu.element.querySelector<HTMLInputElement>('[data-type="font-search"]').focus();});function persistEditorFont(item: IFontItem) {- if (fontFamilyEl.dataset.family === item.family && parseInt(fontFamilyEl.style.fontWeight) === item.weight) {+ if (fontFamilyEl.dataset.family === item.family &&+ parseInt(fontFamilyEl.dataset.weight || "400", 10) === item.weight) {return;}fetchPost(@@ -203,15 +283,26 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {(response) => {const data = response.data as Config.IEditor;editorConfigApi.apply(data);- fontFamilyEl.value = data.fontFamilyDisplay || data.fontFamily || window.siyuan.languages.default;- fontFamilyEl.dataset.family = data.fontFamily;- fontFamilyEl.style.fontFamily = `${data.fontFamily ? data.fontFamily + ", " : ""}var(--b3-font-family)`;- fontFamilyEl.style.fontWeight = data.fontWeight ? String(data.fontWeight) : "400";+ updateFontInput(data);});}++ function updateFontInput(data: Config.IEditor) {+ fontFamilyEl.value = data.fontFamilyDisplay || data.fontFamily || window.siyuan.languages.default;+ fontFamilyEl.dataset.family = data.fontFamily;+ fontFamilyEl.dataset.weight = String(data.fontWeight || 400);+ fontFamilyEl.style.fontFamily = data.fontFamily;+ fontFamilyEl.style.fontWeight = String(data.fontWeight || 400);+ }};+const fontItemFromElement = (item: HTMLElement): IFontItem => ({+ family: item.dataset.family,+ displayName: item.dataset.name,+ weight: parseInt(item.dataset.weight, 10) || 400,+});+const registerAppearanceInterfaceGroup = (tab: SettingTabBuilder) => {const group = tab.group("interface", window.siyuan.languages.configGroupInterface);diff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex e4b9794cbb..86d3f0232c 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -21,6 +21,7 @@ import {import {setCodeTheme} from "../protyle/render/util";import {getBackend, getFrontend} from "./functions";import {getWorkspaceName} from "./processTitle";+import {ensureSelectedCustomFont} from "./customFont";let headingNumberMeasurementRefreshTimer: number;@@ -230,6 +231,9 @@ export const initAssets = () => {};export const setInlineStyle = async (set = true, servePath = "../../../") => {+ if (set) {+ await ensureSelectedCustomFont(window.siyuan.config.editor.fontFamily, window.siyuan.config.editor.fontWeight);+ }let style;// Emojis Reset: 字体中包含了 emoji,需重置// Emojis Additional: 苹果/win11 字体中没有的 emoji@@ -310,7 +314,7 @@ export const setInlineStyle = async (set = true, servePath = "../../../") => {style += `\n:root { --b3-font-size-editor: ${window.siyuan.config.editor.fontSize}px }.b3-typography code:not(.hljs), .protyle-wysiwyg span[data-type~=code] { font-variant-ligatures: ${window.siyuan.config.editor.codeLigatures ? "normal" : "none"} }${window.siyuan.config.editor.justify ? "\n.protyle-wysiwyg [data-node-id] { text-align: justify }" : ""}`;if (window.siyuan.config.editor.fontFamily) {- style += `\n.b3-typography:not(.b3-typography--default), .protyle-wysiwyg, .protyle-title {${window.siyuan.config.editor.fontWeight ? `font-weight: ${window.siyuan.config.editor.fontWeight};` : ""}font-family: "Emojis Additional", "Emojis Reset", "${window.siyuan.config.editor.fontFamily}", var(--b3-font-family)}`;+ style += `\n.b3-typography:not(.b3-typography--default), .protyle-wysiwyg, .protyle-title {${window.siyuan.config.editor.fontWeight ? `font-weight: ${window.siyuan.config.editor.fontWeight};` : ""}font-family: "Emojis Additional", "Emojis Reset", ${CSS.escape(window.siyuan.config.editor.fontFamily)}, var(--b3-font-family)}`;}// pad 端菜单移除显示,如工作空间if ("ontouchend" in document) {diff --git a/app/src/util/customFont.ts b/app/src/util/customFont.tsnew file mode 100644index 0000000000..49b53a9bcb--- /dev/null+++ b/app/src/util/customFont.ts@@ -0,0 +1,101 @@+import {fetchSyncPost} from "./fetch";++export const CUSTOM_FONT_FAMILY_PREFIX = "SiYuanCustomFont-";++export interface ICustomFont {+ id: string;+ family: string;+ weight: number;+ displayName: string;+ url: string;+}++let customFontsPromise: Promise<ICustomFont[]> | undefined;+const registeredFonts = new Map<string, ICustomFont>();++export const isNativeMobileContainer = () => {+ return ["android", "ios", "harmony"].includes(window.siyuan.config.system.container);+};++export const loadCustomFonts = () => {+ if (!customFontsPromise) {+ customFontsPromise = fetchSyncPost("/api/system/getCustomFonts").then((response) => {+ return Array.isArray(response.data) ? response.data as ICustomFont[] : [];+ }).catch((error) => {+ customFontsPromise = undefined;+ throw error;+ });+ }+ return customFontsPromise;+};++export const invalidateCustomFonts = () => {+ customFontsPromise = undefined;+};++export const registerCustomFont = (font: ICustomFont) => {+ if (window.siyuan.config.system.safeMode || !isValidCustomFont(font)) {+ return;+ }+ registeredFonts.set(font.id, {+ ...font,+ family: CUSTOM_FONT_FAMILY_PREFIX + font.id,+ url: `/custom-fonts/${font.id}`,+ weight: Math.max(1, Math.min(1000, font.weight || 400)),+ });+ renderCustomFontStyles();+};++export const unregisterCustomFont = (id: string) => {+ if (registeredFonts.delete(id)) {+ renderCustomFontStyles();+ }+};++export const ensureSelectedCustomFont = async (family: string, weight: number) => {+ if (window.siyuan.config.system.safeMode || !family.startsWith(CUSTOM_FONT_FAMILY_PREFIX)) {+ return;+ }++ const id = family.slice(CUSTOM_FONT_FAMILY_PREFIX.length);+ if (!isValidCustomFontID(id)) {+ return;+ }+ try {+ const fonts = await loadCustomFonts();+ const font = fonts.find((item) => item.id === id && item.family === family);+ if (!font) {+ return;+ }+ registerCustomFont(font);+ await document.fonts.load(`${weight || font.weight || 400} 16px "${family}"`);+ } catch (error) {+ console.warn("load custom font failed", error);+ }+};++const renderCustomFontStyles = () => {+ let styleElement = document.getElementById("customFontStyle") as HTMLStyleElement;+ if (registeredFonts.size === 0) {+ styleElement?.remove();+ return;+ }+ if (!styleElement) {+ styleElement = document.createElement("style");+ styleElement.id = "customFontStyle";+ document.head.append(styleElement);+ }+ styleElement.textContent = Array.from(registeredFonts.values()).map((font) => `@font-face {+ font-family: "${font.family}";+ src: url("${font.url}");+ font-style: normal;+ font-weight: ${font.weight};+ font-display: swap;+}`).join("\n");+};++const isValidCustomFont = (font: ICustomFont) => {+ return font && isValidCustomFontID(font.id) && font.family === CUSTOM_FONT_FAMILY_PREFIX + font.id;+};++const isValidCustomFontID = (id: string) => /^[a-f0-9]{64}$/.test(id);diff --git a/kernel/api/router.go b/kernel/api/router.goindex 6245420182..03428224b0 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -68,6 +68,9 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/system/setAppearanceMode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAppearanceMode)ginServer.Handle("POST", "/api/system/setUILayout", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setUILayout)ginServer.Handle("POST", "/api/system/getSysFonts", model.CheckAuth, model.CheckAdminRole, getSysFonts)+ ginServer.Handle("POST", "/api/system/getCustomFonts", model.CheckAuth, getCustomFonts)+ ginServer.Handle("POST", "/api/system/importCustomFont", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importCustomFont)+ ginServer.Handle("POST", "/api/system/removeCustomFont", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeCustomFont)ginServer.Handle("POST", "/api/system/exit", model.CheckAuth, model.CheckAdminRole, exit)ginServer.Handle("POST", "/api/system/getConf", model.CheckAuth, getConf)ginServer.Handle("POST", "/api/system/ensureOnboarding", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, ensureOnboarding)diff --git a/kernel/api/system.go b/kernel/api/system.goindex 08cb992b3c..e302f14de8 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -19,6 +19,7 @@ package apiimport ("bytes""encoding/json"+ "errors""fmt""image""io"@@ -439,6 +440,11 @@ func exportConf(c *gin.Context) {}if nil != clonedConf.Editor {clonedConf.Editor.Emoji = []string{}+ if strings.HasPrefix(clonedConf.Editor.FontFamily, util.CustomFontFamilyPrefix) {+ clonedConf.Editor.FontFamily = ""+ clonedConf.Editor.FontWeight = 400+ clonedConf.Editor.FontFamilyDisplay = ""+ }}if nil != clonedConf.Export {clonedConf.Export.PandocBin = ""@@ -891,6 +897,119 @@ func getSysFonts(c *gin.Context) {ret.Data = fonts}+func getCustomFonts(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ ret.Data = util.LoadCustomFonts()+}++func importCustomFont(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, util.MaxCustomFontSize+1024*1024)+ fileHeader, err := c.FormFile("file")+ if err != nil {+ var maxBytesError *http.MaxBytesError+ if errors.As(err, &maxBytesError) {+ ret.Code = http.StatusRequestEntityTooLarge+ ret.Msg = "font file is too large"+ } else {+ ret.Code = http.StatusBadRequest+ ret.Msg = "Field [file] must not be empty"+ }+ return+ }+ if util.MaxCustomFontSize < fileHeader.Size {+ ret.Code = http.StatusRequestEntityTooLarge+ ret.Msg = "font file is too large"+ return+ }++ file, err := fileHeader.Open()+ if err != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = err.Error()+ return+ }+ defer file.Close()++ if err = os.MkdirAll(util.CustomFontDir(), 0755); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ tempFile, err := os.CreateTemp(util.CustomFontDir(), ".font-*")+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ tempPath := tempFile.Name()+ defer os.Remove(tempPath)++ written, copyErr := io.Copy(tempFile, io.LimitReader(file, util.MaxCustomFontSize+1))+ closeErr := tempFile.Close()+ if copyErr != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = copyErr.Error()+ return+ }+ if closeErr != nil {+ ret.Code = -1+ ret.Msg = closeErr.Error()+ return+ }+ if util.MaxCustomFontSize < written {+ ret.Code = http.StatusRequestEntityTooLarge+ ret.Msg = "font file is too large"+ return+ }++ font, _, err := util.InstallCustomFont(tempPath)+ if err != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = err.Error()+ return+ }+ ret.Data = font+}++func removeCustomFont(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ id, _ := arg["id"].(string)+ font, err := util.RemoveCustomFont(id)+ if err != nil {+ if os.IsNotExist(err) {+ ret.Code = http.StatusNotFound+ } else {+ ret.Code = http.StatusBadRequest+ }+ ret.Msg = err.Error()+ return+ }++ var editor *conf.Editor+ if model.Conf.Editor.FontFamily == font.Family {+ model.Conf.Editor.FontFamily = ""+ model.Conf.Editor.FontWeight = 400+ model.Conf.Editor.FontFamilyDisplay = ""+ model.Conf.Save()+ editor = model.Conf.Editor+ }+ ret.Data = map[string]any{+ "font": font,+ "editor": editor,+ }+}+func version(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 1f45b812f1..d7ebc3442e 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -165,6 +165,7 @@ func Serve(fastMode bool, cookieKey string) {serveDebug(ginServer)serveAssets(ginServer)+ serveCustomFonts(ginServer)serveAppearance(ginServer)serveWebSocket(ginServer)serveMCP(ginServer)@@ -590,6 +591,29 @@ func serveStaticFile(c *gin.Context, root, relativePath string, packageScoped bohttp.ServeFile(c.Writer, c.Request, targetRealPath)}+func serveCustomFonts(ginServer *gin.Engine) {+ ginServer.GET("/custom-fonts/:id", model.CheckAuth, func(c *gin.Context) {+ fontPath, _, ok := util.GetCustomFontFile(c.Param("id"))+ if !ok {+ c.Status(http.StatusNotFound)+ return+ }++ switch strings.ToLower(filepath.Ext(fontPath)) {+ case ".ttf":+ c.Header("Content-Type", "font/ttf")+ case ".otf":+ c.Header("Content-Type", "font/otf")+ default:+ c.Status(http.StatusNotFound)+ return+ }+ c.Header("Cache-Control", "private, max-age=31536000, immutable")+ c.Header("X-Content-Type-Options", "nosniff")+ c.File(fontPath)+ })+}+func serveAppearance(ginServer *gin.Engine) {siyuan := ginServer.Group("", model.CheckAuth)diff --git a/kernel/util/custom_font.go b/kernel/util/custom_font.gonew file mode 100644index 0000000000..ad4ef947ac--- /dev/null+++ b/kernel/util/custom_font.go@@ -0,0 +1,327 @@+// SiYuan - Refactor your thinking+// 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 (+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"++ "github.com/ConradIrwin/font/sfnt"+)++const (+ MaxCustomFontSize int64 = 64 * 1024 * 1024+ CustomFontFamilyPrefix = "SiYuanCustomFont-"+)++type CustomFont struct {+ ID string `json:"id"`+ Family string `json:"family"`+ Weight int `json:"weight"`+ DisplayName string `json:"displayName"`+ URL string `json:"url"`+ path string+}++var (+ customFonts []*CustomFont+ customFontsLoaded bool+ customFontsLock sync.Mutex+)++func CustomFontDir() string {+ return filepath.Join(AppearancePath, "fonts", "custom")+}++func LoadCustomFonts() []*CustomFont {+ customFontsLock.Lock()+ defer customFontsLock.Unlock()++ loadCustomFontsLocked()+ return cloneCustomFonts(customFonts)+}++func InstallCustomFont(tempPath string) (*CustomFont, bool, error) {+ customFontsLock.Lock()+ defer customFontsLock.Unlock()++ info, err := os.Stat(tempPath)+ if err != nil {+ return nil, false, err+ }+ if !info.Mode().IsRegular() || info.Size() < 1 {+ return nil, false, errors.New("font file is empty")+ }+ if MaxCustomFontSize < info.Size() {+ return nil, false, errors.New("font file is too large")+ }++ fontFile, err := os.Open(tempPath)+ if err != nil {+ return nil, false, err+ }++ extension, err := detectCustomFontExtension(fontFile)+ if err != nil {+ fontFile.Close()+ return nil, false, err+ }+ if _, err = fontFile.Seek(0, io.SeekStart); err != nil {+ fontFile.Close()+ return nil, false, err+ }++ id, err := customFontHash(fontFile)+ if err != nil {+ fontFile.Close()+ return nil, false, err+ }++ if _, err = fontFile.Seek(0, io.SeekStart); err != nil {+ fontFile.Close()+ return nil, false, err+ }+ font, err := parseCustomFontFile(fontFile)+ if closeErr := fontFile.Close(); err == nil {+ err = closeErr+ }+ if err != nil {+ return nil, false, err+ }++ if err = os.MkdirAll(CustomFontDir(), 0755); err != nil {+ return nil, false, err+ }+ targetPath := filepath.Join(CustomFontDir(), id+extension)+ if _, statErr := os.Stat(targetPath); statErr == nil {+ _ = os.Remove(tempPath)+ customFontsLoaded = false+ ret := newCustomFont(id, targetPath, font)+ return ret, false, nil+ } else if !os.IsNotExist(statErr) {+ return nil, false, statErr+ }++ if err = os.Rename(tempPath, targetPath); err != nil {+ return nil, false, err+ }+ if err = os.Chmod(targetPath, 0644); err != nil {+ _ = os.Remove(targetPath)+ return nil, false, err+ }++ customFontsLoaded = false+ return newCustomFont(id, targetPath, font), true, nil+}++func RemoveCustomFont(id string) (*CustomFont, error) {+ if !validCustomFontID(id) {+ return nil, errors.New("invalid custom font ID")+ }++ customFontsLock.Lock()+ defer customFontsLock.Unlock()++ loadCustomFontsLocked()+ for _, font := range customFonts {+ if font.ID != id {+ continue+ }+ if err := os.Remove(font.path); err != nil {+ return nil, err+ }+ customFontsLoaded = false+ return cloneCustomFont(font), nil+ }+ return nil, os.ErrNotExist+}++func GetCustomFontFile(id string) (string, *CustomFont, bool) {+ if !validCustomFontID(id) {+ return "", nil, false+ }++ customFontsLock.Lock()+ defer customFontsLock.Unlock()++ loadCustomFontsLocked()+ for _, font := range customFonts {+ if font.ID == id {+ info, err := os.Lstat(font.path)+ if err != nil || !info.Mode().IsRegular() || info.Size() < 1 || MaxCustomFontSize < info.Size() {+ return "", nil, false+ }+ return font.path, cloneCustomFont(font), true+ }+ }+ return "", nil, false+}++func loadCustomFontsLocked() {+ if customFontsLoaded {+ return+ }++ customFonts = []*CustomFont{}+ entries, err := os.ReadDir(CustomFontDir())+ if err != nil {+ customFontsLoaded = true+ return+ }++ for _, entry := range entries {+ if entry.IsDir() {+ continue+ }++ name := strings.ToLower(entry.Name())+ extension := filepath.Ext(name)+ id := strings.TrimSuffix(name, extension)+ if (extension != ".ttf" && extension != ".otf") || !validCustomFontID(id) {+ continue+ }++ fontPath := filepath.Join(CustomFontDir(), entry.Name())+ info, statErr := os.Lstat(fontPath)+ if statErr != nil || !info.Mode().IsRegular() || info.Size() < 1 || MaxCustomFontSize < info.Size() {+ continue+ }+ fontFile, openErr := os.Open(fontPath)+ if openErr != nil {+ continue+ }+ detectedExtension, detectErr := detectCustomFontExtension(fontFile)+ if detectErr != nil || detectedExtension != extension {+ fontFile.Close()+ continue+ }+ if _, seekErr := fontFile.Seek(0, io.SeekStart); seekErr != nil {+ fontFile.Close()+ continue+ }+ actualID, hashErr := customFontHash(fontFile)+ if hashErr != nil || actualID != id {+ fontFile.Close()+ continue+ }+ if _, seekErr := fontFile.Seek(0, io.SeekStart); seekErr != nil {+ fontFile.Close()+ continue+ }+ font, parseErr := parseCustomFontFile(fontFile)+ fontFile.Close()+ if parseErr != nil {+ continue+ }+ customFonts = append(customFonts, newCustomFont(id, fontPath, font))+ }++ sort.Slice(customFonts, func(i, j int) bool {+ if customFonts[i].DisplayName == customFonts[j].DisplayName {+ return customFonts[i].ID < customFonts[j].ID+ }+ return customFonts[i].DisplayName < customFonts[j].DisplayName+ })+ customFontsLoaded = true+}++func detectCustomFontExtension(reader io.Reader) (string, error) {+ header := make([]byte, 4)+ if _, err := io.ReadFull(reader, header); err != nil {+ return "", errors.New("font file is invalid")+ }++ switch string(header) {+ case "\x00\x01\x00\x00", "true":+ return ".ttf", nil+ case "OTTO":+ return ".otf", nil+ default:+ return "", errors.New("only TTF and OTF font files are supported")+ }+}++func customFontHash(reader io.Reader) (string, error) {+ hash := sha256.New()+ if _, err := io.Copy(hash, reader); err != nil {+ return "", err+ }+ return hex.EncodeToString(hash.Sum(nil)), nil+}++func parseCustomFontFile(fontFile *os.File) (ret *Font, err error) {+ defer func() {+ if recovered := recover(); recovered != nil {+ ret = nil+ err = fmt.Errorf("parse font failed: %v", recovered)+ }+ }()++ parsed, err := sfnt.Parse(fontFile)+ if err != nil {+ return nil, fmt.Errorf("parse font failed: %w", err)+ }+ ret, err = parseFontInfo(parsed)+ if err != nil {+ return nil, fmt.Errorf("parse font metadata failed: %w", err)+ }+ return ret, nil+}++func validCustomFontID(id string) bool {+ if len(id) != sha256.Size*2 || strings.ToLower(id) != id {+ return false+ }+ decoded, err := hex.DecodeString(id)+ return err == nil && len(decoded) == sha256.Size+}++func newCustomFont(id, fontPath string, font *Font) *CustomFont {+ weight := font.Weight+ if weight < 1 || 1000 < weight {+ weight = 400+ }+ return &CustomFont{+ ID: id,+ Family: CustomFontFamilyPrefix + id,+ Weight: weight,+ DisplayName: font.DisplayName,+ URL: "/custom-fonts/" + id,+ path: fontPath,+ }+}++func cloneCustomFonts(fonts []*CustomFont) (ret []*CustomFont) {+ ret = make([]*CustomFont, 0, len(fonts))+ for _, font := range fonts {+ ret = append(ret, cloneCustomFont(font))+ }+ return+}++func cloneCustomFont(font *CustomFont) *CustomFont {+ ret := *font+ return &ret+}diff --git a/kernel/util/custom_font_test.go b/kernel/util/custom_font_test.gonew file mode 100644index 0000000000..c021bbe44b--- /dev/null+++ b/kernel/util/custom_font_test.go@@ -0,0 +1,152 @@+// SiYuan - Refactor your thinking+// 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 (+ "io"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestCustomFontLifecycle(t *testing.T) {+ oldAppearancePath := AppearancePath+ AppearancePath = t.TempDir()+ resetCustomFontCache()+ t.Cleanup(func() {+ AppearancePath = oldAppearancePath+ resetCustomFontCache()+ })++ if err := os.MkdirAll(CustomFontDir(), 0755); err != nil {+ t.Fatal(err)+ }+ sourcePath := filepath.Join("..", "..", "app", "appearance", "fonts", "LxgwWenKai-Lite-1.501",+ "LXGWWenKaiLite-Regular.ttf")+ tempPath := copyCustomFontForTest(t, sourcePath)++ font, created, err := InstallCustomFont(tempPath)+ if err != nil {+ t.Fatal(err)+ }+ if !created {+ t.Fatal("the first import should create the font")+ }+ if len(font.ID) != 64 || font.Family != CustomFontFamilyPrefix+font.ID {+ t.Fatalf("unexpected custom font identity: %+v", font)+ }+ if font.DisplayName == "" || font.Weight < 1 {+ t.Fatalf("unexpected custom font metadata: %+v", font)+ }++ fonts := LoadCustomFonts()+ if len(fonts) != 1 || fonts[0].ID != font.ID {+ t.Fatalf("unexpected custom fonts: %+v", fonts)+ }+ fontPath, loaded, ok := GetCustomFontFile(font.ID)+ if !ok || loaded.ID != font.ID {+ t.Fatalf("custom font lookup failed: %+v", loaded)+ }+ if filepath.Ext(fontPath) != ".ttf" {+ t.Fatalf("unexpected font path: %s", fontPath)+ }++ duplicatePath := copyCustomFontForTest(t, sourcePath)+ duplicate, created, err := InstallCustomFont(duplicatePath)+ if err != nil {+ t.Fatal(err)+ }+ if created || duplicate.ID != font.ID {+ t.Fatalf("duplicate import was not detected: %+v", duplicate)+ }+ if _, err = os.Stat(duplicatePath); !os.IsNotExist(err) {+ t.Fatalf("duplicate temporary file was not removed: %v", err)+ }++ removed, err := RemoveCustomFont(font.ID)+ if err != nil {+ t.Fatal(err)+ }+ if removed.ID != font.ID || len(LoadCustomFonts()) != 0 {+ t.Fatalf("custom font was not removed: %+v", removed)+ }+}++func TestInstallCustomFontRejectsInvalidData(t *testing.T) {+ oldAppearancePath := AppearancePath+ AppearancePath = t.TempDir()+ resetCustomFontCache()+ t.Cleanup(func() {+ AppearancePath = oldAppearancePath+ resetCustomFontCache()+ })++ if err := os.MkdirAll(CustomFontDir(), 0755); err != nil {+ t.Fatal(err)+ }+ tempFile, err := os.CreateTemp(CustomFontDir(), ".font-*")+ if err != nil {+ t.Fatal(err)+ }+ tempPath := tempFile.Name()+ if _, err = tempFile.WriteString("not a font"); err != nil {+ t.Fatal(err)+ }+ if err = tempFile.Close(); err != nil {+ t.Fatal(err)+ }++ if _, _, err = InstallCustomFont(tempPath); err == nil ||+ !strings.Contains(err.Error(), "only TTF and OTF") {+ t.Fatalf("invalid font data should be rejected: %v", err)+ }+ if _, _, ok := GetCustomFontFile("../invalid"); ok {+ t.Fatal("invalid custom font ID should not resolve")+ }+}++func copyCustomFontForTest(t *testing.T, sourcePath string) string {+ t.Helper()++ source, err := os.Open(sourcePath)+ if err != nil {+ t.Fatal(err)+ }+ defer source.Close()++ target, err := os.CreateTemp(CustomFontDir(), ".font-*")+ if err != nil {+ t.Fatal(err)+ }+ targetPath := target.Name()+ if _, err = io.Copy(target, source); err != nil {+ target.Close()+ t.Fatal(err)+ }+ if err = target.Close(); err != nil {+ t.Fatal(err)+ }+ return targetPath+}++func resetCustomFontCache() {+ customFontsLock.Lock()+ customFonts = nil+ customFontsLoaded = false+ customFontsLock.Unlock()+}diff --git a/kernel/util/font.go b/kernel/util/font.goindex 465c5ac6d9..ef0748656a 100644--- a/kernel/util/font.go+++ b/kernel/util/font.go@@ -17,6 +17,7 @@package utilimport (+ "errors""os""sort""strconv"@@ -27,8 +28,6 @@ import ("github.com/ConradIrwin/font/sfnt""github.com/flopp/go-findfont""github.com/siyuan-note/logging"- textUnicode "golang.org/x/text/encoding/unicode"- "golang.org/x/text/transform")var (@@ -142,39 +141,19 @@ func parseTTFFontFamily(fontPath string) *Font {}func parseFont(font *sfnt.Font) *Font {+ ret, _ := parseFontInfo(font)+ return ret+}++func parseFontInfo(font *sfnt.Font) (*Font, error) {t, err := font.NameTable()if err != nil {- //logging.LogErrorf("parse font name table failed: %s", err)- return nil+ return nil, err}- var family, subfamily string- for _, e := range t.List() {- if sfnt.NameFontFamily == e.NameID && (sfnt.PlatformLanguageID(1033) == e.LanguageID || sfnt.PlatformLanguageID(2052) == e.LanguageID) {- v, _, err := transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.IgnoreBOM).NewDecoder(), e.Value)- if err == nil {- family = strings.TrimSpace(string(v))- }- }- if sfnt.NamePreferredFamily == e.NameID && (sfnt.PlatformLanguageID(1033) == e.LanguageID || sfnt.PlatformLanguageID(2052) == e.LanguageID) {- v, _, err := transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.IgnoreBOM).NewDecoder(), e.Value)- if err == nil {- family = strings.TrimSpace(string(v))- }- }- if sfnt.NameFontSubfamily == e.NameID && (sfnt.PlatformLanguageID(1033) == e.LanguageID || sfnt.PlatformLanguageID(2052) == e.LanguageID) {- v, _, err := transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.IgnoreBOM).NewDecoder(), e.Value)- if err == nil {- subfamily = strings.TrimSpace(string(v))- }- }- if sfnt.NamePreferredSubfamily == e.NameID && (sfnt.PlatformLanguageID(1033) == e.LanguageID || sfnt.PlatformLanguageID(2052) == e.LanguageID) {- v, _, err := transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.IgnoreBOM).NewDecoder(), e.Value)- if err == nil {- subfamily = strings.TrimSpace(string(v))- }- }- }+ entries := t.List()+ family := selectFontName(entries, sfnt.NamePreferredFamily, sfnt.NameFontFamily)+ subfamily := selectFontName(entries, sfnt.NamePreferredSubfamily, sfnt.NameFontSubfamily)weight := 400os2, err := font.OS2Table()@@ -223,17 +202,53 @@ func parseFont(font *sfnt.Font) *Font {}}- if family != "" && !strings.HasPrefix(family, ".") {- displayName := family- if subfamily != "" && !strings.EqualFold(subfamily, "Regular") {- displayName = family + " " + subfamily- }+ if family == "" || strings.HasPrefix(family, ".") {+ return nil, errors.New("font family is empty")+ }++ displayName := family+ if subfamily != "" && !strings.EqualFold(subfamily, "Regular") {+ displayName = family + " " + subfamily+ }++ return &Font{+ Family: family,+ Weight: weight,+ DisplayName: displayName,+ }, nil+}++func selectFontName(entries []*sfnt.NameEntry, nameIDs ...sfnt.NameID) string {+ for _, nameID := range nameIDs {+ var selected string+ selectedScore := 4+ for _, entry := range entries {+ if entry.NameID != nameID {+ continue+ }- return &Font{- Family: family,- Weight: weight,- DisplayName: displayName,+ value := strings.Trim(strings.TrimSpace(entry.String()), "\x00")+ 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+ }+ if score < selectedScore {+ selected = value+ selectedScore = score+ }+ }+ if selected != "" {+ return selected}}- return nil+ return ""}