diff --git a/web/src/apply.ts b/web/src/apply.ts index 72be108..0e1602a 100644 --- a/web/src/apply.ts +++ b/web/src/apply.ts @@ -1,9 +1,9 @@ import { exec, shellQuote, toast } from './ksu'; -import { copyFont, pickWghtRange, refreshEnSubset, renderSlots, setApplying, slots } from './slots'; -import { applyWghtOverride, getSelectedWghtMode, writeWghtMode } from './wght'; -import { invalidateTestFonts } from './testFonts'; +import { canApply, copyFont, refreshEnSubset, renderSlots, setApplying, slots } from './slots'; +import { getSelectedWghtMode, writeWghtMode } from './wght'; +import { writeSlotModes } from './fontFiles'; import { applyBtn } from './dom'; -import { FONTS_DIR } from './constants'; +import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS } from './constants'; const logDialog = document.getElementById('log-dialog') as any; const logContent = document.getElementById('log-content')!; @@ -12,67 +12,65 @@ document.getElementById('log-close')?.addEventListener('click', () => { logDialog.open = false; }); +async function syncSingleSlot(key: 'hans' | 'hant' | 'en' | 'mono' | 'emoji'): Promise { + const slot = slots[key]; + const dest = `${FONTS_DIR}/${key}.ttf`; + if (slot.path) { + if (slot.path !== dest) await copyFont(slot.path, dest); + } else { + await exec(`rm -f ${shellQuote(dest)}`); + } +} + +async function syncMultiSlot(key: 'hans' | 'hant' | 'en'): Promise { + const slot = slots[key]; + const dir = `${MULTI_DIR}/${key}`; + await exec(`mkdir -p ${shellQuote(dir)}`); + for (const w of MULTI_WEIGHTS) { + const entry = slot.multiWeights?.[w]; + const dest = `${dir}/${w}.ttf`; + if (entry?.path) { + if (entry.path !== dest) await copyFont(entry.path, dest); + } else { + const sub = key === 'en' ? ` ${shellQuote(`${dir}/.subset-${w}.ttf`)}` : ''; + await exec(`rm -f ${shellQuote(dest)}${sub}`); + } + } +} + async function apply() { - if (!slots.hans.path) return; + if (!canApply()) return; setApplying(true); renderSlots(); try { - // 字重范围覆写: 用 UI 当前模式 (持久化到 FONTS/wght-mode.txt), 仅当存在可变字体且模式非 0 时处理 - const wghtMode = getSelectedWghtMode(); - await writeWghtMode(wghtMode); - const wghtPick = pickWghtRange(); - if (wghtMode !== 0 && wghtPick) { - // Go 程序自行读取 wght-map.txt (mode 3) - await applyWghtOverride(wghtMode, wghtPick.min, wghtPick.max); - } + // 保存各槽位模式 (可变字体/多字重) 与字重覆写模式; 两种模式的字体文件互不删除 + await writeSlotModes({ + hans: slots.hans.mode, + hant: slots.hant.mode, + en: slots.en.mode, + }); + await writeWghtMode(getSelectedWghtMode()); - // 启动加载的字体 path 即 FONT/ 内的文件, 无需再复制 - if (slots.hans.path !== `${FONTS_DIR}/hans.ttf`) { - await copyFont(slots.hans.path, `${FONTS_DIR}/hans.ttf`); - } - - if (slots.hant.path) { - if (slots.hant.path !== `${FONTS_DIR}/hant.ttf`) { - await copyFont(slots.hant.path, `${FONTS_DIR}/hant.ttf`); + for (const key of ['hans', 'hant', 'en'] as const) { + if (slots[key].mode === 'multi') { + await syncMultiSlot(key); + } else { + await syncSingleSlot(key); } - } else { - await exec(`rm -f ${shellQuote(`${FONTS_DIR}/hant.ttf`)}`); - } - - if (slots.en.path) { - if (slots.en.path !== `${FONTS_DIR}/en.ttf`) { - await copyFont(slots.en.path, `${FONTS_DIR}/en.ttf`); - } - } else { - await exec(`rm -f ${shellQuote(`${FONTS_DIR}/en.ttf`)}`); - } - - if (slots.mono.path) { - if (slots.mono.path !== `${FONTS_DIR}/mono.ttf`) { - await copyFont(slots.mono.path, `${FONTS_DIR}/mono.ttf`); - } - } else { - await exec(`rm -f ${shellQuote(`${FONTS_DIR}/mono.ttf`)}`); - } - - if (slots.emoji.path) { - if (slots.emoji.path !== `${FONTS_DIR}/emoji.ttf`) { - await copyFont(slots.emoji.path, `${FONTS_DIR}/emoji.ttf`); - } - } else { - await exec(`rm -f ${shellQuote(`${FONTS_DIR}/emoji.ttf`)}`); } + await syncSingleSlot('mono'); + await syncSingleSlot('emoji'); + // apply.sh 会完成系统字体复制、英文单/多字重子集化以及 fontmm-wght -sync XML 同步 const { errno, stdout, stderr } = await exec('sh /data/adb/modules/FontMM/apply.sh'); - if (errno !== 0) throw new Error(stderr || 'apply.sh 执行失败'); + if (errno !== 0) throw new Error(stderr || stdout || 'apply.sh 执行失败'); if (logContent && logDialog) { logContent.textContent = stdout; logDialog.open = true; } toast('字体已应用,重启后生效'); - // 字体已变化: 下次进入测试页时重新加载 - invalidateTestFonts(); + document.dispatchEvent(new CustomEvent('fonts-changed')); } catch (e) { toast(`应用失败: ${String(e)}`); } finally { diff --git a/web/src/constants.ts b/web/src/constants.ts index 2504c38..4f6bbbb 100644 --- a/web/src/constants.ts +++ b/web/src/constants.ts @@ -1,10 +1,27 @@ // 全局路径与外部链接常量 export const FONTS_DIR = '/data/adb/modules/FontMM/FONTS'; +export const MULTI_DIR = `${FONTS_DIR}/multi`; +export const SLOT_MODES_FILE = `${FONTS_DIR}/slot-modes.txt`; export const WEBROOT_DIR = '/data/adb/modules/FontMM/webroot'; export const TEST_FONT_DIR = `${WEBROOT_DIR}/fonts-test`; // 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制) export const WGHT_BIN = '/data/adb/modules/FontMM/tools/fontmm-wght'; +// 多字重模式支持的标准 9 档字重 +export const MULTI_WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900] as const; + +export const WEIGHT_LABELS: Record = { + 100: '淡体', + 200: '特细', + 300: '细体', + 400: '标准', + 500: '适中', + 600: '次粗', + 700: '粗体', + 800: '特粗', + 900: '浓体', +}; + // 捐献 (支付宝/爱发电) 与开发者主页 (浏览器) 链接 export const DONATE_ALIPAY_URI = 'alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/2m615805eflrafv8ipc2p15'; diff --git a/web/src/fontFiles.ts b/web/src/fontFiles.ts index b028f96..08ccd4f 100644 --- a/web/src/fontFiles.ts +++ b/web/src/fontFiles.ts @@ -1,26 +1,33 @@ import { exec, shellQuote } from './ksu'; -import { FONTS_DIR, TEST_FONT_DIR } from './constants'; +import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS, SLOT_MODES_FILE, TEST_FONT_DIR } from './constants'; import { formatSize } from './fontInfo'; +import type { MultiSlotKey, SlotMode, WeightLevel } from './types'; -// 复制 FONT/ 到 webroot/fonts-test, 供页面加载与名称解析 +// 复制 FONTS/ 到 webroot/fonts-test, 供页面加载与名称解析 // (WebView 无法直接访问模块外部目录, 符号链接在真机也不可靠, 直接复制) // -// 只复制 5 个槽位对应的文件: FONTS/ 下还可能有 apply.sh 生成的中转文件 -// (如 .en-subset.ttf), 它们不是用户选择的字体, 复制过去只是浪费开销。 -// -// 注意结尾必须加 `:` —— 否则最后一个不存在的槽位会让整段脚本以非 0 退出 -// ([ -f ] 条件失败), 而 exec 只看整体退出码, 上游就会误判为"复制失败" -// 并把所有槽位当空处理 (issue #11: 只选中文字体时名称全不显示)。 +// 只复制单字体槽位与多字重槽位的用户字体, 跳过 .en-subset.ttf / .subset-*.ttf 等中转文件。 +// 结尾加 `:` 保证任一可选文件不存在时整体退出码仍为 0 (issue #11)。 const SLOT_FILES = ['hans.ttf', 'hant.ttf', 'en.ttf', 'mono.ttf', 'emoji.ttf']; +const MULTI_SLOTS: MultiSlotKey[] = ['hans', 'hant', 'en']; export async function ensureFontsCopy(): Promise { + const multiCmds: string[] = []; + for (const s of MULTI_SLOTS) { + for (const w of MULTI_WEIGHTS) { + multiCmds.push( + `[ -f '${MULTI_DIR}/${s}/${w}.ttf' ] && cp -f '${MULTI_DIR}/${s}/${w}.ttf' '${TEST_FONT_DIR}/multi-${s}-${w}.ttf'`, + ); + } + } const copyCmd = [ `rm -rf '${TEST_FONT_DIR}'`, `mkdir -p '${TEST_FONT_DIR}'`, ...SLOT_FILES.map( (f) => `[ -f '${FONTS_DIR}/${f}' ] && cp -f '${FONTS_DIR}/${f}' '${TEST_FONT_DIR}/${f}'`, ), - ':', // 兜底: 保证整体退出码为 0 (见上) + ...multiCmds, + ':', // 兜底: 保证整体退出码为 0 ].join('\n'); try { const { errno } = await exec(copyCmd); @@ -31,7 +38,7 @@ export async function ensureFontsCopy(): Promise { return listFontsDir(); } -// 列出 fonts-test/ 下的字体文件 (每行一个完整路径) +// 列出 fonts-test/ 下的字体文件名 (不含目录前缀) export async function listFontsDir(): Promise { try { const { errno, stdout } = await exec( @@ -48,11 +55,41 @@ export async function listFontsDir(): Promise { } } +// 读取槽位模式配置 (FONTS/slot-modes.txt), 缺失时全部默认 'single' +export async function readSlotModes(): Promise> { + const modes: Record = { hans: 'single', hant: 'single', en: 'single' }; + try { + const { errno, stdout } = await exec(`cat ${shellQuote(SLOT_MODES_FILE)} 2>/dev/null || true`); + if (errno !== 0) return modes; + for (const raw of stdout.split('\n')) { + const line = raw.split('#')[0].trim(); + const idx = line.indexOf('='); + if (idx <= 0) continue; + const k = line.slice(0, idx).trim(); + const v = line.slice(idx + 1).trim(); + if ((k === 'hans' || k === 'hant' || k === 'en') && (v === 'single' || v === 'multi')) { + modes[k] = v; + } + } + } catch { + // 忽略读取失败 + } + return modes; +} + +// 写入槽位模式配置 (FONTS/slot-modes.txt) +export async function writeSlotModes(modes: Record): Promise { + const content = `hans=${modes.hans}\nhant=${modes.hant}\nen=${modes.en}`; + await exec( + `mkdir -p ${shellQuote(FONTS_DIR)} && printf '%s\\n' ${shellQuote(content)} > ${shellQuote(SLOT_MODES_FILE)}`, + ); +} + // 英文字体子集文件: apply.sh 子集化成功时写入 FONTS/.en-subset.ttf (issue #10), // 安装到 system/fonts 的就是它, 大小通常比原字体小两个数量级 (issue #14)。 export const EN_SUBSET_FILE = `${FONTS_DIR}/.en-subset.ttf`; -// 读取英文子集大小 (无子集返回 null)。 +// 读取英文单字体子集大小 (无子集返回 null)。 // 要求子集比 en.ttf 新 —— 换过英文字体但还没重新应用时, 旧子集不该继续展示。 export async function getEnSubsetSizeText(): Promise { // dev 假数据: 真机没应用过就没有该文件, 徽标无从预览 @@ -69,3 +106,34 @@ export async function getEnSubsetSizeText(): Promise { return null; } } + +// 读取英文多字重各档位的子集大小 (无子集时不包含该字重) +export async function getEnMultiSubsetSizes( + weights: WeightLevel[], +): Promise>> { + const out: Partial> = {}; + if (weights.length === 0) return out; + if (import.meta.env.DEV) { + for (const w of weights) out[w] = `${170 + Math.round(w / 20)} KB`; + return out; + } + const checks = weights.map((w) => { + const sub = shellQuote(`${MULTI_DIR}/en/.subset-${w}.ttf`); + const orig = shellQuote(`${MULTI_DIR}/en/${w}.ttf`); + return `if [ -f ${sub} ] && [ ${sub} -nt ${orig} ]; then echo "${w}:$(wc -c < ${sub})"; fi`; + }); + try { + const { errno, stdout } = await exec(checks.join('; ')); + if (errno !== 0) return out; + for (const line of stdout.split('\n')) { + const m = line.trim().match(/^(\d+):(\d+)$/); + if (!m) continue; + const w = Number(m[1]) as WeightLevel; + const bytes = Number(m[2]); + if (Number.isFinite(bytes) && bytes > 0) out[w] = formatSize(bytes); + } + } catch { + // 忽略读取失败 + } + return out; +} diff --git a/web/src/fontInfo.ts b/web/src/fontInfo.ts index d2d530a..f49d5aa 100644 --- a/web/src/fontInfo.ts +++ b/web/src/fontInfo.ts @@ -52,14 +52,38 @@ export async function readFontInfo(file: string): Promise { 'emoji.ttf': { name: 'Noto Color Emoji', size: '9.8 MB', variable: false }, }; const mock = MOCK_FONT_INFO[file]; - return mock - ? { - name: mock.name, - sizeText: mock.size, - isVariable: mock.variable, - wghtRange: mock.wght, - } - : {}; + if (mock) { + return { + name: mock.name, + sizeText: mock.size, + isVariable: mock.variable, + wghtRange: mock.wght, + }; + } + const multiMatch = file.match(/^multi-(hans|hant|en)-(\d+)\.ttf$/); + if (multiMatch) { + const slot = multiMatch[1]; + const w = multiMatch[2]; + const baseName = + slot === 'hans' ? 'PingFang SC' : slot === 'hant' ? 'PingFang TC' : 'SF Pro Text'; + const weightLabel: Record = { + '100': 'Thin', + '200': 'ExtraLight', + '300': 'Light', + '400': 'Regular', + '500': 'Medium', + '600': 'SemiBold', + '700': 'Bold', + '800': 'ExtraBold', + '900': 'Black', + }; + return { + name: `${baseName} ${weightLabel[w] ?? w}`, + sizeText: slot === 'en' ? '640 KB' : '11.8 MB', + isVariable: false, + }; + } + return {}; } try { const res = await fetch(`fonts-test/${file}`); diff --git a/web/src/fontsXml.ts b/web/src/fontsXml.ts index fb2622a..5da31af 100644 --- a/web/src/fontsXml.ts +++ b/web/src/fontsXml.ts @@ -9,3 +9,25 @@ export function averagedAxis(min: number, max: number, w: number): number { if (w < 400) return Math.floor(min + ((400 - min) * (w - 100)) / 300); return Math.floor(400 + ((max - 400) * (w - 400)) / 500); } + +/** + * 从已选字重列表中挑选最接近 target 的档位 (与 Go 引擎 NearestWeight 保持一致)。 + * 距离相等时: target >= 400 偏向更重档位, target < 400 偏向更轻档位。 + */ +export function nearestWeight(available: number[], target: number): number { + if (available.length === 0) return 400; + let best = available[0]; + let bestDist = Math.abs(best - target); + for (let i = 1; i < available.length; i++) { + const w = available[i]; + const d = Math.abs(w - target); + if ( + d < bestDist || + (d === bestDist && ((target >= 400 && w > best) || (target < 400 && w < best))) + ) { + best = w; + bestDist = d; + } + } + return best; +} diff --git a/web/src/ksu.ts b/web/src/ksu.ts index 248481b..7a113a1 100644 --- a/web/src/ksu.ts +++ b/web/src/ksu.ts @@ -31,14 +31,41 @@ const FAKE_FS: Record { const fake = (stdout = ''): ExecResult => ({ errno: 0, stdout, stderr: '' }); const fail = (stderr: string): ExecResult => ({ errno: 1, stdout: '', stderr }); @@ -47,6 +74,15 @@ async function mockExec(command: string): Promise { const slowFail = (stderr: string) => new Promise((r) => setTimeout(() => r(fail(stderr)), 200)); + // 字体测试: 模拟 FONT 字体已放入 webroot/fonts-test, 返回可用字体列表 + // (须放在通用 find 匹配之前, 否则 listFontsDir 的无 -print0 命令会被拦截) + if (command.includes('fonts-test')) { + if (command.includes('-type f')) { + return slow(MOCK_TEST_FONTS.join('\n')); + } + return fake(''); + } + // find 命令: 解析路径与类型 (d/f), 返回假目录/文件, 以 NUL 分隔 (与 -print0 一致) if (command.startsWith('find ')) { const m = command.match( @@ -61,15 +97,29 @@ async function mockExec(command: string): Promise { return slow(lines.join('\0')); } - // 字体测试: 模拟 FONT 字体已放入 webroot/fonts-test, 返回可用字体列表 - if (command.includes('fonts-test')) { - return slow('hans.ttf\nhant.ttf\nen.ttf\nmono.ttf\nemoji.ttf'); + // 槽位模式读写: FONTS/slot-modes.txt + if (command.includes('slot-modes.txt')) { + if (command.includes('printf')) { + const m = command.match(/printf '%s\\n' '([^']*)'/); + if (m) mockSlotModes = m[1]; + return fake(''); + } + return slow(mockSlotModes); } + if (command.includes('mkdir -p')) return fake(''); if (command.includes('rm -f')) return fake(''); if (command.includes('cp -f')) return fake(''); if (command.includes('apply.sh')) { - return fake('[*] 安装: SysSans-Hans-Regular.ttf (模拟)\n[*] 全部完成, 重启后生效 (模拟)'); + const lines = ['[*] 安装简体字体...', '[*] 安装: SysSans-Hans-Regular.ttf (模拟)']; + if (mockSlotModes.includes('hans=multi')) { + lines.push('[*] 安装: FontMM-Hans-300.ttf (模拟)', '[*] 安装: FontMM-Hans-700.ttf (模拟)'); + } + if (mockSlotModes.includes('en=multi')) { + lines.push('[*] 检查英文多字重 400 (模拟)', '[*] 安装: FontMM-En-700.ttf (模拟)'); + } + lines.push('[✓] 字体配置 XML 同步完成 (模拟)', '[*] 全部完成, 重启后生效 (模拟)'); + return fake(lines.join('\n')); } // 字重覆写模式: cat 返回已选 '1' (裁切), echo 写入模拟成功 if (command.includes('wght-mode.txt')) { @@ -284,15 +334,19 @@ export async function getSystemInfo(): Promise { 'ro.product.cpu.abi', ]; const { errno, stdout } = await exec( - `${props.map((p) => `getprop ${p}`).join('; ')}; ls -1 '${MODULE_FONTS_DIR}'/*.ttf 2>/dev/null`, + `${props.map((p) => `getprop ${p}`).join('; ')}; find '${MODULE_FONTS_DIR}' -maxdepth 3 -type f -name '*.ttf' 2>/dev/null || true`, ); if (errno === 0) { const lines = stdout.split('\n'); [info.androidVersion, info.sdk, info.deviceModel, info.abi] = lines .slice(0, 4) .map((l) => l.trim()); - // 剩余行是 FONTS/ 中实际存在的字体文件名 - info.fontCount = lines.slice(4).filter((l) => l.trim() && l.endsWith('.ttf')).length; + // 剩余行是 FONTS/ 与 FONTS/multi/ 中的用户字体 (排除隐藏中转文件如 .en-subset.ttf) + info.fontCount = lines.slice(4).filter((raw) => { + const p = raw.trim(); + const base = p.slice(p.lastIndexOf('/') + 1); + return p.endsWith('.ttf') && !base.startsWith('.'); + }).length; } } catch { // 读取失败时保持空值, 由 UI 显示占位 diff --git a/web/src/navigation.ts b/web/src/navigation.ts index 7558651..7c945e0 100644 --- a/web/src/navigation.ts +++ b/web/src/navigation.ts @@ -1,4 +1,4 @@ -import { slots } from './slots'; +import { canApply } from './slots'; import { loadHome } from './home'; import { loadTestFonts } from './testFonts'; import { applyBtn, rebootBtn } from './dom'; @@ -42,8 +42,8 @@ function showView(index: number) { views.forEach((v, i) => v.classList.toggle('active', i === target)); // 轨道滑动切换动画 viewTrack.style.transform = `translateX(${-target * 100}%)`; - // 悬浮应用按钮仅配置页显示, 且未选简体字体时不展示 - applyFab.style.display = target === 1 && slots.hans.path ? '' : 'none'; + // 悬浮应用按钮仅配置页显示, 且简体槽位在当前模式下已配置字体时才展示 + applyFab.style.display = target === 1 && canApply() ? '' : 'none'; // 重启按钮仅主页显示 (visibility 保持顶栏布局不跳动) if (rebootBtn) rebootBtn.style.visibility = target === 0 ? 'visible' : 'hidden'; // 同步底部导航高亮 diff --git a/web/src/slots.ts b/web/src/slots.ts index 02a1553..996a9f6 100644 --- a/web/src/slots.ts +++ b/web/src/slots.ts @@ -1,42 +1,76 @@ import { fontPicker } from './fontPicker'; import { exec, shellQuote } from './ksu'; import { readFontInfo } from './fontInfo'; -import { ensureFontsCopy, getEnSubsetSizeText } from './fontFiles'; -import { FONTS_DIR, TEST_FONT_DIR } from './constants'; +import { + ensureFontsCopy, + getEnMultiSubsetSizes, + getEnSubsetSizeText, + readSlotModes, +} from './fontFiles'; +import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS, TEST_FONT_DIR, WEIGHT_LABELS } from './constants'; +import { nearestWeight } from './fontsXml'; import { applyBtn } from './dom'; -import type { FontSlot } from './types'; +import type { + FontSlot, + MultiSlotKey, + MultiWeightEntry, + SlotKey, + SlotMode, + WeightLevel, +} from './types'; export const SLOT_KEYS = ['hans', 'hant', 'en', 'mono', 'emoji'] as const; -export type SlotKey = (typeof SLOT_KEYS)[number]; +export type { SlotKey }; + +function createEmptyMultiWeights(): Record { + const out = {} as Record; + for (const w of MULTI_WEIGHTS) { + out[w] = { weight: w, path: null, fileName: '' }; + } + return out; +} export const slots: Record = { hans: { key: 'hans', title: '中文简体', + supportsMulti: true, + mode: 'single', path: null, fileName: '', + multiWeights: createEmptyMultiWeights(), }, hant: { key: 'hant', title: '中文繁体', + supportsMulti: true, + mode: 'single', path: null, fileName: '', + multiWeights: createEmptyMultiWeights(), }, en: { key: 'en', title: '英文 & 数字', + supportsMulti: true, + mode: 'single', path: null, fileName: '', + multiWeights: createEmptyMultiWeights(), }, mono: { key: 'mono', title: '等宽字体', + supportsMulti: false, + mode: 'single', path: null, fileName: '', }, emoji: { key: 'emoji', title: 'Emoji 表情', + supportsMulti: false, + mode: 'single', path: null, fileName: '', }, @@ -47,7 +81,8 @@ const slotsEl = document.getElementById('slots')!; const wghtModeSelect = document.getElementById('wght-mode-select') as any; const wghtModeSub = document.getElementById('wght-mode-sub'); -let pickingKey: SlotKey = 'hans'; +// 记住上次选择文件的目录, 多字重连续挑选同目录字体时无需重复层层翻找 +let lastPickerDir = '/storage/emulated/0'; // 应用流程进行中: renderSlots 据此禁用/启用应用按钮 export let applying = false; @@ -55,119 +90,327 @@ export function setApplying(v: boolean): void { applying = v; } +function escapeHtml(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +function notifyFontsChanged(): void { + document.dispatchEvent(new CustomEvent('fonts-changed')); +} + +function rememberDir(filePath: string): void { + const idx = filePath.lastIndexOf('/'); + if (idx > 0) lastPickerDir = filePath.slice(0, idx); +} + +/** 返回某个多字重槽位已选的升序字重列表 */ +export function getSelectedMultiWeights(slot: FontSlot): WeightLevel[] { + if (!slot.multiWeights) return []; + return MULTI_WEIGHTS.filter((w) => Boolean(slot.multiWeights?.[w]?.path)); +} + +/** 判断槽位在当前激活模式下是否已配置字体 */ +export function isSlotConfigured(slot: FontSlot): boolean { + if (slot.mode === 'multi') return getSelectedMultiWeights(slot).length > 0; + return Boolean(slot.path); +} + +/** 是否满足应用前提 (中文简体必须在当前模式下至少配好 1 份字体) */ +export function canApply(): boolean { + return isSlotConfigured(slots.hans); +} + function pickFontFor(key: SlotKey): void { - pickingKey = key; - fontPicker.show('/storage/emulated/0', (path, name) => { - const slot = slots[pickingKey]; + fontPicker.show(lastPickerDir, (path, name) => { + rememberDir(path); + const slot = slots[key]; slot.path = path; slot.fileName = name; + notifyFontsChanged(); renderSlots(); void refreshSlotInfo(slot); }); } +function pickMultiFontFor(key: MultiSlotKey, weight: WeightLevel): void { + fontPicker.show(lastPickerDir, (path, name) => { + rememberDir(path); + const slot = slots[key]; + if (!slot.multiWeights) slot.multiWeights = createEmptyMultiWeights(); + const entry = slot.multiWeights[weight]; + entry.path = path; + entry.fileName = name; + entry.sizeText = undefined; + entry.subsetSizeText = undefined; + notifyFontsChanged(); + renderSlots(); + void refreshMultiWeightInfo(slot, weight); + }); +} + +function hansFallbackSummary(): string { + if (slots.hans.mode === 'multi') { + const count = getSelectedMultiWeights(slots.hans).length; + return count > 0 ? `中文简体(多字重 ${count} 档)` : '中文简体'; + } + return slots.hans.fileName || '中文简体'; +} + // 未选择时的占位文案: 回退可视化 (WYSIWYG) function slotPlaceholder(slot: FontSlot): string { if (slot.path) return slot.fileName; if (slot.key === 'hans') return '未选择字体文件'; - if (slots.hans.path) { + if (isSlotConfigured(slots.hans)) { if (slot.key === 'mono') return '未选择,保持系统等宽字体'; if (slot.key === 'emoji') return '未选择,保持系统 Emoji'; - return `默认使用:${slots.hans.fileName}`; + return `默认使用:${hansFallbackSummary()}`; } return '未选择字体文件'; } -// 根据是否有可变字体决定是否禁用字重覆写 (emoji/mono 不计入) +// 根据单字体模式是否存在可变字体决定是否启用字重覆写 (多字重槽位 / mono / emoji 不计入) export function updateWghtModeDisabled(): void { - const hasVar = ['hans', 'hant', 'en'].some((k) => slots[k as 'hans']?.isVariable); + const hasVar = (['hans', 'hant', 'en'] as const).some( + (k) => slots[k].mode === 'single' && Boolean(slots[k].path) && Boolean(slots[k].isVariable), + ); + const hasAnyMulti = (['hans', 'hant', 'en'] as const).some((k) => slots[k].mode === 'multi'); + if (wghtModeSelect) wghtModeSelect.disabled = !hasVar; if (wghtModeSub) { - wghtModeSub.textContent = hasVar - ? '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置' - : '当前未选择可变字体 (中文/繁体/英文), 此功能不可用'; + if (hasVar) { + wghtModeSub.textContent = hasAnyMulti + ? '单字体模式下的可变字体 wght 范围与实际字重等级不符时, 覆写对应家族配置 (多字重槽位不受影响)' + : '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置'; + } else if (hasAnyMulti) { + wghtModeSub.textContent = '多字重模式下各档位使用独立字体文件, 字重覆写已自动禁用'; + } else { + wghtModeSub.textContent = '当前未选择可变字体 (中文/繁体/英文), 此功能不可用'; + } } } +function renderModeToggle(slot: FontSlot): string { + if (!slot.supportsMulti) { + return `chevron_right`; + } + const singleActive = slot.mode === 'single' ? 'active' : ''; + const multiActive = slot.mode === 'multi' ? 'active' : ''; + return ` +
+ + +
+ `; +} + +function renderSingleBody(slot: FontSlot, required: boolean): string { + const nameText = required ? '未选择字体,此项为必选项' : slotPlaceholder(slot); + const ext = slot.path ? (slot.path.split('.').pop() ?? '').toUpperCase() : ''; + const sizeText = slot.subsetSizeText + ? `${slot.sizeText || '…'} → ${slot.subsetSizeText}` + : slot.sizeText || '…'; + const subsetBadge = slot.subsetSizeText + ? `已子集化` + : ''; + return ` +
+ ${ + slot.path + ? ` + close + ` + : '' + } +
+
${escapeHtml(nameText)}
+ ${ + slot.path + ? `
${escapeHtml(sizeText)}${ext ? `${escapeHtml(ext)}` : ''}${subsetBadge}${slot.isVariable ? `可变字体${slot.wghtRange ? ` ${escapeHtml(slot.wghtRange)}` : ''}` : ''}
` + : '' + } +
+ ${slot.supportsMulti ? `chevron_right` : ''} +
+ `; +} + +function renderMultiBody(slot: FontSlot, required: boolean): string { + const selected = getSelectedMultiWeights(slot); + let bannerText = ''; + let bannerCls = 'slot-multi-summary'; + if (selected.length === 0) { + if (slot.key === 'hans') { + bannerText = required + ? '请至少选择一个字重的字体文件(此项为必选项)' + : '请点击下方档位选择字体,未选档位将自动匹配最接近字重'; + if (required) bannerCls += ' required'; + } else if (isSlotConfigured(slots.hans)) { + bannerText = `未选任何字重,默认回退使用:${hansFallbackSummary()}`; + } else { + bannerText = '未选任何字重(可选),点击下方档位即可配置'; + } + } else { + bannerText = `已选 ${selected.length}/9 档 · 缺失档位自动就近匹配`; + } + + const rows = MULTI_WEIGHTS.map((w) => { + const entry = slot.multiWeights?.[w] ?? { weight: w, path: null, fileName: '' }; + const label = WEIGHT_LABELS[w] ?? ''; + const hasFile = Boolean(entry.path); + let text = ''; + if (hasFile) { + text = entry.fileName; + } else if (selected.length > 0) { + text = `未选(使用 ${nearestWeight(selected, w)})`; + } else if (slot.key !== 'hans' && isSlotConfigured(slots.hans)) { + text = '回退中文简体'; + } else { + text = '点击选择字体'; + } + + const ext = entry.path ? (entry.path.split('.').pop() ?? '').toUpperCase() : ''; + const sizeText = entry.subsetSizeText + ? `${entry.sizeText || '…'} → ${entry.subsetSizeText}` + : entry.sizeText || '…'; + const subsetBadge = entry.subsetSizeText + ? `已子集化` + : ''; + + return ` +
+
+ ${w} + ${label} +
+
+
${escapeHtml(text)}
+ ${ + hasFile + ? `
${escapeHtml(sizeText)}${ext ? `${escapeHtml(ext)}` : ''}${subsetBadge}
` + : '' + } +
+ ${ + hasFile + ? ` + close + ` + : `chevron_right` + } +
+ `; + }).join(''); + + return ` +
${escapeHtml(bannerText)}
+
${rows}
+ `; +} + export function renderSlots() { + const anyOtherConfigured = Object.values(slots).some( + (s) => s.key !== 'hans' && isSlotConfigured(s), + ); slotsEl.innerHTML = Object.values(slots) .map((slot) => { - // 选了其他槽位但未选简体时, 简体卡片提示"必选" - const required = - slot.key === 'hans' && - !slot.path && - Object.values(slots).some((s) => s.key !== 'hans' && s.path); - const nameText = required ? '未选择字体,此项为必选项' : slotPlaceholder(slot); - // 扩展名大写 (TTF/OTF...), 从源文件路径动态提取, 不硬编码 - const ext = slot.path ? (slot.path.split('.').pop() ?? '').toUpperCase() : ''; - // 英文字体被裁成拉丁子集后, 卡片上同时给出「原大小 → 子集大小」与徽标, - // 否则用户看到原字体大小, 会以为裁切没生效 (issue #14) - const sizeText = slot.subsetSizeText - ? `${slot.sizeText || '…'} → ${slot.subsetSizeText}` - : slot.sizeText || '…'; - const subsetBadge = slot.subsetSizeText - ? `已子集化` - : ''; + const configured = isSlotConfigured(slot); + const required = slot.key === 'hans' && !configured && anyOtherConfigured; + const body = + slot.mode === 'multi' && slot.supportsMulti + ? renderMultiBody(slot, required) + : renderSingleBody(slot, required); + return ` - +
${slot.title}
- chevron_right -
- -
- ${ - slot.path - ? ` - close - ` - : '' - } -
-
${nameText}
- ${ - slot.path - ? `
${sizeText}${ext ? `${ext}` : ''}${subsetBadge}${slot.isVariable ? `可变字体${slot.wghtRange ? ` ${slot.wghtRange}` : ''}` : ''}
` - : '' - } -
+ ${renderModeToggle(slot)}
+ ${body}
`; }) .join(''); - // 绑定事件: 整卡点击选择字体 (回调按点击的槽位处理) + // 绑定事件: 模式切换按钮 (可变字体 / 多字重) + slotsEl.querySelectorAll('.slot-mode-btn').forEach((btn) => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + const key = btn.dataset.key as MultiSlotKey; + const mode = btn.dataset.mode as SlotMode; + const slot = slots[key]; + if (!slot || slot.mode === mode) return; + slot.mode = mode; + notifyFontsChanged(); + renderSlots(); + }); + }); + + // 绑定事件: 单字体整卡点击选择 slotsEl.querySelectorAll('.slot-card').forEach((card) => { card.addEventListener('click', () => { + if (card.dataset.mode === 'multi') return; pickFontFor(card.dataset.key as SlotKey); }); }); + + // 绑定事件: 单字体清除 slotsEl.querySelectorAll('.slot-clear').forEach((btn) => { btn.addEventListener('click', (e) => { - e.stopPropagation(); // 阻止冒泡触发卡片选择 + e.stopPropagation(); const slot = slots[btn.dataset.key as SlotKey]; slot.path = null; slot.fileName = ''; - // 解析结果一并清掉: 否则字重映射的轴范围 (取各槽位最小跨度) 与可变字体标记 - // 会停留在被删掉的字体上 —— 删掉 200-900 的字体后仍只能选 200-900 slot.sizeText = undefined; slot.isVariable = false; slot.wghtRange = undefined; slot.subsetSizeText = undefined; + void exec(`rm -f ${shellQuote(`${TEST_FONT_DIR}/${slot.key}.ttf`)}`); + notifyFontsChanged(); + renderSlots(); + }); + }); + + // 绑定事件: 多字重行点击选择 + slotsEl.querySelectorAll('.slot-weight-row').forEach((row) => { + row.addEventListener('click', (e) => { + e.stopPropagation(); + const key = row.dataset.key as MultiSlotKey; + const weight = Number(row.dataset.weight) as WeightLevel; + pickMultiFontFor(key, weight); + }); + }); + + // 绑定事件: 多字重单档清除 + slotsEl.querySelectorAll('.slot-weight-clear').forEach((btn) => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + const key = btn.dataset.key as MultiSlotKey; + const weight = Number(btn.dataset.weight) as WeightLevel; + const entry = slots[key].multiWeights?.[weight]; + if (!entry) return; + entry.path = null; + entry.fileName = ''; + entry.sizeText = undefined; + entry.subsetSizeText = undefined; + void exec(`rm -f ${shellQuote(`${TEST_FONT_DIR}/multi-${key}-${weight}.ttf`)}`); + notifyFontsChanged(); renderSlots(); }); }); if (applyBtn) { - // 未选择简体字体时直接隐藏按钮 (不做半透明禁用); 应用过程中禁用 - applyBtn.style.display = !slots.hans.path ? 'none' : ''; + const onConfig = document.getElementById('config-view')?.classList.contains('active') ?? false; + applyBtn.style.display = onConfig && canApply() ? '' : 'none'; applyBtn.disabled = applying; } updateWghtModeDisabled(); - // 通知其他模块 (如字重映射预览) 槽位已变化 document.dispatchEvent(new CustomEvent('slots-rendered')); } @@ -176,11 +419,12 @@ export async function copyFont(src: string, dest: string) { if (errno !== 0) throw new Error(`复制失败: ${stderr}`); } -// 选择用于覆写的 wght 范围: 从 hans/hant/en 收集 (emoji/mono 除外), 取跨度最小者; 无可变返回 null +// 选择用于覆写的 wght 范围: 仅从当前处于单字体模式的 hans/hant/en 收集, 取跨度最小者; 无可变返回 null export function pickWghtRange(): { min: number; max: number } | null { let best: { min: number; max: number } | null = null; let bestSpan = Infinity; for (const key of ['hans', 'hant', 'en'] as const) { + if (slots[key].mode !== 'single' || !slots[key].path) continue; const r = slots[key]?.wghtRange; if (!r) continue; const m = r.match(/^(\d+)-(\d+)$/); @@ -196,17 +440,15 @@ export function pickWghtRange(): { min: number; max: number } | null { return best; } -// 选择新字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小 +// 选择单字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小 async function refreshSlotInfo(slot: FontSlot) { if (!slot.path) return; - // 换了英文字体: 旧的子集标记描述的是「上次应用」的状态, 先撤下, 应用后再刷新 if (slot.key === 'en') slot.subsetSizeText = undefined; try { await exec(`cp -f ${shellQuote(slot.path)} ${shellQuote(`${TEST_FONT_DIR}/${slot.key}.ttf`)}`); const info = await readFontInfo(`${slot.key}.ttf`); if (info.name) slot.fileName = info.name; if (info.sizeText) slot.sizeText = info.sizeText; - // 无条件同步: 防止换字体后旧的可变标记残留 slot.isVariable = Boolean(info.isVariable); slot.wghtRange = info.wghtRange; renderSlots(); @@ -215,26 +457,67 @@ async function refreshSlotInfo(slot: FontSlot) { } } -// 刷新英文槽位的子集信息 (打开 WebUI 时, 以及每次应用后)。不负责重绘。 -export async function refreshEnSubset(): Promise { - slots.en.subsetSizeText = (await getEnSubsetSizeText()) ?? undefined; +// 选择多字重后: 复制到 fonts-test 供解析与测试预览, 更新该档位名称/大小 +async function refreshMultiWeightInfo(slot: FontSlot, weight: WeightLevel) { + const entry = slot.multiWeights?.[weight]; + if (!entry?.path) return; + if (slot.key === 'en') entry.subsetSizeText = undefined; + const testFile = `multi-${slot.key}-${weight}.ttf`; + try { + await exec( + `mkdir -p ${shellQuote(TEST_FONT_DIR)} && cp -f ${shellQuote(entry.path)} ${shellQuote(`${TEST_FONT_DIR}/${testFile}`)}`, + ); + const info = await readFontInfo(testFile); + if (info.name) entry.fileName = info.name; + if (info.sizeText) entry.sizeText = info.sizeText; + renderSlots(); + } catch { + // 忽略解析失败 + } } -// 打开 WebUI 时: 复制 FONT/ 到 fonts-test, 读取已有字体的名称/大小填充卡片 +// 刷新英文槽位 (单字体及多字重各档) 的子集信息, 不负责重绘 +export async function refreshEnSubset(): Promise { + slots.en.subsetSizeText = (await getEnSubsetSizeText()) ?? undefined; + const enWeights = getSelectedMultiWeights(slots.en); + const subMap = await getEnMultiSubsetSizes(enWeights); + for (const w of MULTI_WEIGHTS) { + const entry = slots.en.multiWeights?.[w]; + if (entry) entry.subsetSizeText = subMap[w]; + } +} + +// 打开 WebUI 时: 复制 FONTS/ 到 fonts-test, 读取已有字体与模式配置填充卡片 async function loadExistingFonts() { - const available = await ensureFontsCopy(); + const [available, modes] = await Promise.all([ensureFontsCopy(), readSlotModes()]); for (const key of SLOT_KEYS) { - const file = `${key}.ttf`; - if (!available.includes(file)) continue; const slot = slots[key]; - const info = await readFontInfo(file); - slot.path = `${FONTS_DIR}/${file}`; - slot.fileName = info.name ?? file; - if (info.sizeText) slot.sizeText = info.sizeText; - slot.isVariable = Boolean(info.isVariable); - slot.wghtRange = info.wghtRange; + if (key === 'hans' || key === 'hant' || key === 'en') { + slot.mode = modes[key]; + } + const file = `${key}.ttf`; + if (available.includes(file)) { + const info = await readFontInfo(file); + slot.path = `${FONTS_DIR}/${file}`; + slot.fileName = info.name ?? file; + if (info.sizeText) slot.sizeText = info.sizeText; + slot.isVariable = Boolean(info.isVariable); + slot.wghtRange = info.wghtRange; + } + if (slot.supportsMulti && slot.multiWeights) { + for (const w of MULTI_WEIGHTS) { + const mf = `multi-${key}-${w}.ttf`; + if (!available.includes(mf)) continue; + const info = await readFontInfo(mf); + const entry = slot.multiWeights[w]; + entry.path = `${MULTI_DIR}/${key}/${w}.ttf`; + entry.fileName = info.name ?? `${w}.ttf`; + if (info.sizeText) entry.sizeText = info.sizeText; + } + } } await refreshEnSubset(); + notifyFontsChanged(); renderSlots(); } diff --git a/web/src/style.scss b/web/src/style.scss index 608502b..ea28179 100644 --- a/web/src/style.scss +++ b/web/src/style.scss @@ -125,14 +125,18 @@ md-filled-card.slot-card { --md-filled-card-container-color: var(--md-sys-color-surface-container-low); --md-filled-card-container-shape: var(--md-shape-corner-large); + // 整卡可点击选择 (多字重卡片由内部各字重行触发) + cursor: pointer; + + &.is-multi { + cursor: default; + } + // 已选择状态: tonal 高亮 (primary-container), M3 标准选中反馈 &.selected { --md-filled-card-container-color: var(--md-sys-color-primary-container); } - // 整卡可点击选择 - cursor: pointer; - .slot-header { display: flex; justify-content: space-between; @@ -154,6 +158,37 @@ md-filled-card.slot-card { color: var(--md-sys-color-on-surface); } + // 可变字体 / 多字重 分段切换胶囊 + .slot-mode-toggle { + display: inline-flex; + align-items: center; + flex-shrink: 0; + padding: 2px; + border-radius: var(--md-shape-corner-full); + background-color: var(--md-sys-color-surface-container-highest); + gap: 2px; + + .slot-mode-btn { + border: none; + background: transparent; + padding: 4px 10px; + border-radius: var(--md-shape-corner-full); + font-family: inherit; + font-size: var(--md-sys-typescale-label-small-size); + font-weight: 500; + color: var(--md-sys-color-on-surface-variant); + cursor: pointer; + transition: + background-color var(--md-duration-standard) var(--md-easing-standard), + color var(--md-duration-standard) var(--md-easing-standard); + + &.active { + background-color: var(--md-sys-color-primary); + color: var(--md-sys-color-on-primary); + } + } + } + // 右侧导航箭头 .slot-arrow { flex-shrink: 0; @@ -169,6 +204,12 @@ md-filled-card.slot-card { gap: 4px; min-width: 0; + .slot-arrow--inline { + flex-shrink: 0; + color: var(--md-sys-color-on-surface-variant); + font-size: 22px; + } + // 清除按钮位于字体名称左侧 .slot-clear { flex-shrink: 0; @@ -232,6 +273,123 @@ md-filled-card.slot-card { } } } + + // 多字重提示与 9 档列表 + .slot-multi-summary { + font-size: var(--md-sys-typescale-body-small-size); + color: var(--md-sys-color-on-surface-variant); + margin-bottom: 10px; + + &.required { + font-weight: 600; + color: var(--md-sys-color-tertiary); + } + } + + .slot-weight-list { + display: flex; + flex-direction: column; + border-top: 1px solid var(--md-sys-color-outline-variant); + + .slot-weight-row { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 4px; + min-height: 44px; + cursor: pointer; + border-bottom: 1px solid + color-mix(in srgb, var(--md-sys-color-outline-variant) 55%, transparent); + + &:last-child { + border-bottom: none; + padding-bottom: 2px; + } + + &:active { + opacity: 0.72; + } + + .slot-weight-tag { + display: flex; + flex-direction: column; + width: 44px; + flex-shrink: 0; + + .slot-weight-num { + font-size: var(--md-sys-typescale-label-large-size); + font-weight: 600; + font-variant-numeric: tabular-nums; + color: var(--md-sys-color-primary); + line-height: 1.1; + } + + .slot-weight-label { + font-size: 11px; + color: var(--md-sys-color-on-surface-variant); + line-height: 1.2; + } + } + + .slot-weight-info { + flex: 1; + min-width: 0; + + .slot-weight-name { + font-size: var(--md-sys-typescale-body-medium-size); + font-weight: 500; + color: var(--md-sys-color-on-surface); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + &.placeholder { + font-weight: 400; + color: var(--md-sys-color-on-surface-variant); + opacity: 0.75; + } + } + + .slot-meta { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-top: 2px; + + .slot-meta-badge { + display: inline-block; + padding: 1px 8px; + border-radius: var(--md-shape-corner-full); + background-color: var(--md-sys-color-surface-container-highest); + font-size: 11px; + color: var(--md-sys-color-on-surface-variant); + + &.slot-meta-badge--subset { + background-color: var(--md-sys-color-tertiary); + color: var(--md-sys-color-on-tertiary); + } + } + } + } + + .slot-weight-arrow { + flex-shrink: 0; + font-size: 20px; + color: var(--md-sys-color-on-surface-variant); + } + + .slot-weight-clear { + flex-shrink: 0; + width: 32px; + height: 32px; + --md-icon-button-state-layer-size: 32px; + + md-icon { + font-size: 18px; + } + } + } + } } // ---------------- 4. 悬浮应用按钮 (Extended FAB) ---------------- diff --git a/web/src/testFonts.ts b/web/src/testFonts.ts index 948da80..1ea2d52 100644 --- a/web/src/testFonts.ts +++ b/web/src/testFonts.ts @@ -1,82 +1,141 @@ -import { slots } from './slots'; +import { getSelectedMultiWeights, isSlotConfigured, slots } from './slots'; import { listFontsDir } from './fontFiles'; -import type { FontSlot } from './types'; +import { MULTI_WEIGHTS } from './constants'; +import { nearestWeight } from './fontsXml'; +import type { FontSlot, MultiSlotKey, WeightLevel } from './types'; const testStatusText = document.getElementById('test-status-text')!; const testContent = document.getElementById('test-content')!; -type TestSlot = 'hans' | 'hant' | 'en'; +type TestSlot = MultiSlotKey; -const TEST_FONTS: { slot: TestSlot; file: string; family: string }[] = [ - { slot: 'hans', file: 'hans.ttf', family: 'FontMM-Hans' }, - { slot: 'hant', file: 'hant.ttf', family: 'FontMM-Hant' }, - { slot: 'en', file: 'en.ttf', family: 'FontMM-En' }, -]; +const TEST_FAMILIES: Record = { + hans: 'FontMM-Hans', + hant: 'FontMM-Hant', + en: 'FontMM-En', +}; -async function registerFont(family: string, file: string): Promise { +// 记录已注册进 document.fonts 的 FontFace, 刷新时先清理避免旧字重描述符残留 +const registeredFaces: FontFace[] = []; + +function clearRegisteredFaces(): void { + for (const face of registeredFaces) { + document.fonts.delete(face); + } + registeredFaces.length = 0; +} + +async function registerFont( + family: string, + file: string, + weightRange = '100 900', +): Promise { try { - // 声明完整字重范围: 否则 FontFace 默认只覆盖 weight 400, - // CSS font-weight 100-900 将无法匹配到该字体 (真机表现: 100-400 无变化) - const font = new FontFace(family, `url('fonts-test/${file}')`, { weight: '100 900' }); + const font = new FontFace(family, `url('fonts-test/${file}')`, { weight: weightRange }); await font.load(); document.fonts.add(font); + registeredFaces.push(font); return true; } catch { return false; } } -// 测试页字体只加载一次 (进入时), 应用新字体后重置, 避免每次进入重复加载 +// 为多字重槽位按连续权重区间注册 FontFace (相同目标字体文件合并为一个区间, 只加载一次) +async function registerMultiSlotFonts( + family: string, + slotKey: TestSlot, + availWeights: WeightLevel[], + availableFiles: string[], +): Promise { + const usable = availWeights.filter((w) => availableFiles.includes(`multi-${slotKey}-${w}.ttf`)); + if (usable.length === 0) return false; + + // 按最接近匹配将 100..900 归并到连续字重区间 + const segments: { sourceW: WeightLevel; minW: number; maxW: number }[] = []; + for (const w of MULTI_WEIGHTS) { + const target = nearestWeight(usable, w) as WeightLevel; + const prev = segments[segments.length - 1]; + if (prev && prev.sourceW === target) { + prev.maxW = w; + } else { + segments.push({ sourceW: target, minW: w, maxW: w }); + } + } + + let anyLoaded = false; + for (const seg of segments) { + const descriptor = seg.minW === seg.maxW ? String(seg.minW) : `${seg.minW} ${seg.maxW}`; + const ok = await registerFont(family, `multi-${slotKey}-${seg.sourceW}.ttf`, descriptor); + if (ok) anyLoaded = true; + } + return anyLoaded; +} + +// 测试页字体只加载一次 (进入时), 槽位或模式变化后重置 let testLoaded = false; -// 字体已变化: 下次进入测试页时重新加载 export function invalidateTestFonts(): void { testLoaded = false; } +document.addEventListener('fonts-changed', () => invalidateTestFonts()); + +function describeSlot(key: TestSlot): string { + const slot = slots[key]; + if (slot.mode === 'multi') { + const ws = getSelectedMultiWeights(slot); + if (ws.length === 0) return ''; + const regName = slot.multiWeights?.[nearestWeight(ws, 400) as WeightLevel]?.fileName ?? ''; + return regName ? `多字重 ${ws.length} 档 · ${regName}` : `多字重 ${ws.length} 档`; + } + return slot.path ? slot.fileName : ''; +} + +async function loadSlotFamily(key: TestSlot, availableFiles: string[]): Promise { + const slot = slots[key]; + const family = TEST_FAMILIES[key]; + if (slot.mode === 'multi') { + const ws = getSelectedMultiWeights(slot); + return ws.length > 0 ? registerMultiSlotFonts(family, key, ws, availableFiles) : false; + } + const file = `${key}.ttf`; + return slot.path && availableFiles.includes(file) ? registerFont(family, file) : false; +} + export async function loadTestFonts(): Promise { if (testLoaded) return; testContent.hidden = true; testStatusText.textContent = '正在加载字体...'; - // 字体已在 WebUI 打开时复制到 fonts-test, 此处直接读取 + clearRegisteredFaces(); const available = await listFontsDir(); - // 注册字体, 记录每个槽位是否加载成功 const loaded = new Map(); - for (const tf of TEST_FONTS) { - loaded.set( - tf.slot, - available.includes(tf.file) ? await registerFont(tf.family, tf.file) : false, - ); + for (const key of ['hans', 'hant', 'en'] as const) { + loaded.set(key, await loadSlotFamily(key, available)); } - // fallback 逻辑: hant/en 缺失回退 hans - const hans = loaded.get('hans') ? 'FontMM-Hans' : 'sans-serif'; - const hant = loaded.get('hant') ? 'FontMM-Hant' : hans; - const en = loaded.get('en') ? 'FontMM-En' : hans; + // fallback 逻辑: hant/en 当前模式未配置时回退 hans + const hans = loaded.get('hans') ? TEST_FAMILIES.hans : 'sans-serif'; + const hant = loaded.get('hant') ? TEST_FAMILIES.hant : hans; + const en = loaded.get('en') ? TEST_FAMILIES.en : hans; - // 显示字体名称 (解析出的 family name; 未解析到时为文件名) - const slotLabel = (key: TestSlot): string => slots[key].fileName; - const hasFont = (key: TestSlot): boolean => available.includes(`${key}.ttf`); - const hansLabel = hasFont('hans') ? slotLabel('hans') : null; + const hansLabel = isSlotConfigured(slots.hans) ? describeSlot('hans') : null; + const hantLabel = isSlotConfigured(slots.hant) ? describeSlot('hant') : null; + const enLabel = isSlotConfigured(slots.en) ? describeSlot('en') : null; const setTag = (id: string, text: string) => { const el = document.getElementById(id); if (el) el.textContent = text; }; - setTag('hans-tag', hasFont('hans') ? slotLabel('hans') : '未设置, 使用系统字体'); - setTag( - 'hant-tag', - hasFont('hant') ? slotLabel('hant') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体', - ); - setTag( - 'en-tag', - hasFont('en') ? slotLabel('en') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体', - ); + setTag('hans-tag', hansLabel || '未设置, 使用系统字体'); + setTag('hant-tag', hantLabel || (hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体')); + setTag('en-tag', enLabel || (hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体')); setTag('weight-tag', `使用 ${hansLabel ?? '系统字体'}`); - // 可变字体提示: 若所选字体为可变字体, 显示 wght 轴范围 - const varSlot: FontSlot | null = slots.hans.isVariable ? slots.hans : null; + + const varSlot: FontSlot | null = + slots.hans.mode === 'single' && slots.hans.isVariable ? slots.hans : null; setTag( 'var-tag', `使用 ${hansLabel ?? '系统字体'}${varSlot?.wghtRange ? ` (可变字体 wght ${varSlot.wghtRange})` : ''}`, @@ -89,8 +148,7 @@ export async function loadTestFonts(): Promise { setFamily('test-hans', hans, 'sans-serif'); setFamily('test-hant', hant, `'${hans}', sans-serif`); setFamily('test-en', en, `'${hans}', sans-serif`); - // 字重 / 可变字体测试: 用完整 fallback 链渲染 (Hans → Hant → En 按用户选择顺序, - // 浏览器逐字形回退, 所见即所得地体现系统真实 fallback) + const fallbackChain = [...new Set([hans, hant, en])].map((f) => `'${f}'`).join(', '); const fullChain = `${fallbackChain}, sans-serif`; document.querySelectorAll('.test-w-text').forEach((el) => { @@ -98,12 +156,12 @@ export async function loadTestFonts(): Promise { }); const vp = document.getElementById('test-var-preview'); if (vp) vp.style.fontFamily = fullChain; - applyWght(400); // 与滑条初始值保持一致 + applyWght(400); - testStatusText.textContent = - available.length === 0 - ? '未找到已设置的字体 (FONTS 为空), 当前使用系统字体预览' - : '字体已加载, 下方为预览效果 (按 fallback 逻辑)'; + const hasAny = available.length > 0 && isSlotConfigured(slots.hans); + testStatusText.textContent = hasAny + ? '字体已加载, 下方为预览效果 (按实际模式与 fallback 逻辑)' + : '未找到已设置的字体 (FONTS 为空), 当前使用系统字体预览'; testContent.hidden = false; testLoaded = true; } @@ -128,7 +186,9 @@ const varPreview = document.getElementById('test-var-preview') as HTMLElement | let wghtTimer: number | undefined; function applyWght(weight: number) { - if (varPreview) varPreview.style.fontVariationSettings = `'wght' ${weight}`; + if (!varPreview) return; + varPreview.style.fontVariationSettings = `'wght' ${weight}`; + varPreview.style.fontWeight = String(Math.round(weight / 100) * 100); } function updateVarPreview(weight: number) { diff --git a/web/src/types.ts b/web/src/types.ts index cb2f7fd..a44bea3 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -1,6 +1,25 @@ +export type SlotKey = 'hans' | 'hant' | 'en' | 'mono' | 'emoji'; +export type MultiSlotKey = 'hans' | 'hant' | 'en'; +export type SlotMode = 'single' | 'multi'; +export type WeightLevel = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; + +export interface MultiWeightEntry { + weight: WeightLevel; + path: string | null; + fileName: string; + sizeText?: string; + /** 英文字体裁切后的子集大小 (如 "184 KB"), 仅 en 槽位子集有效时存在 */ + subsetSizeText?: string; +} + export interface FontSlot { - key: 'hans' | 'hant' | 'en' | 'mono' | 'emoji'; + key: SlotKey; title: string; + /** 是否支持切换多字重模式 (仅 hans/hant/en) */ + supportsMulti?: boolean; + /** 当前模式 ('single'=可变/单字体, 'multi'=多字重) */ + mode: SlotMode; + /** 单字体模式选中文件路径 (与 multiWeights 各自保留, 切换模式不丢失) */ path: string | null; fileName: string; /** 字体大小展示文本 (如 "12.5 MB"), 异步获取 */ @@ -11,4 +30,6 @@ export interface FontSlot { wghtRange?: string; /** 英文字体裁切后的子集大小 (如 "218 KB"), 仅英文槽位且子集有效时存在 (issue #14) */ subsetSizeText?: string; + /** 多字重模式下各档位字体配置 */ + multiWeights?: Record; } diff --git a/web/src/wght.ts b/web/src/wght.ts index 2ae4abc..cc0dee0 100644 --- a/web/src/wght.ts +++ b/web/src/wght.ts @@ -1,7 +1,7 @@ import { exec, toast } from './ksu'; import { pickWghtRange, updateWghtModeDisabled } from './slots'; import { WEIGHTS, averagedAxis } from './fontsXml'; -import { FONTS_DIR, WGHT_BIN } from './constants'; +import { FONTS_DIR } from './constants'; export type WghtMode = 0 | 1 | 2 | 3; @@ -64,31 +64,6 @@ async function readWghtMode(): Promise { return 0; } -// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (只改 fonts.xml, 再 -sync 到各派生配置) -export async function applyWghtOverride(mode: 1 | 2 | 3, min: number, max: number): Promise { - const mapArg = mode === 3 ? ` -map '${FONTS_DIR}/wght-map.txt'` : ''; - // 日志写到 FONTS/wght-apply.log 方便真机排查。 - // 工具在刷入后是 0644 (KernelSU 解压时不保留 zip 里的执行位), 故执行前临时 - // 加执行位、执行后还原; 末尾 exit $rc 保证 errno 仍是工具自身的退出码。 - const logFile = `${FONTS_DIR}/wght-apply.log`; - const cmd = `chmod 0755 '${WGHT_BIN}' 2>/dev/null; '${WGHT_BIN}' -mode ${mode} -min ${min} -max ${max}${mapArg} -sync > '${logFile}' 2>&1; rc=$?; chmod 0644 '${WGHT_BIN}' 2>/dev/null; exit $rc`; - try { - const { errno } = await exec(cmd); - // 读取并回显执行日志 (同时 console 输出供排查) - const { stdout: log } = await exec(`cat '${logFile}' 2>/dev/null || true`); - console.log(`[wght-override] mode=${mode} min=${min} max=${max} errno=${errno}`); - if (log) console.log(`[wght-override] log:\n${log}`); - if (errno !== 0) { - console.warn('[wght-override] 执行失败:', log); - // 覆写失败不阻断应用主流程, 但把失败原因带出 - throw new Error(log || `fontmm-wght 执行失败 (errno=${errno})`); - } - } catch (e) { - // 覆写失败不阻断应用主流程 - console.warn('字重范围覆写失败:', e); - } -} - // 读取自定义字重映射 (FONTS/wght-map.txt: 每行 "weight axis") async function readWghtMap(): Promise> { const map: Record = {};