feat: 字重范围覆写 (Go 方案 + 可视化映射编辑器)

- 新增 Go 程序 fontmm-wght (golang/ 多程序结构: cmd/fontmm-wght + internal/wght)
- WebUI 配置页高级配置: 覆写模式(不处理/裁切/平均/自定义) + 字重映射编辑器
  (滑条+输入框联动, 支持 1-1000 动态增删映射)
- 应用时 exec 调 fontmm-wght 本地读写 6 个字体配置 XML, 修复之前
  fetch/base64 分块导致的 32KB 截断与 XML 格式损坏
- 二进制 tools/fontmm-wght 随模块打包 (dev/build-wght.sh 自动交叉编译, chmod 755)
- CI: 新增 go.yml workflow (vet/test/android-arm64 交叉编译)
- 移除 fontsXml.ts 中的 XML 生成逻辑, 避免双实现漂移
This commit is contained in:
YuleBest committed 2026-08-08 03:24:51 +08:00
1 parent 2ec6c45c80
commit e6e7784e0b
15 files changed
+734 -116

No files matched your search

+49 -11
View File
@@ -100,19 +100,57 @@
<main id="config-view" class="view view-config">
<div class="home-title">字体配置</div>
<div class="wght-mode-row">
<div class="wght-mode-info">
<div class="wght-mode-title">字重覆写模式</div>
<div class="wght-mode-sub" id="wght-mode-sub">
可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置
<!-- 高级配置 -->
<md-elevated-card class="wght-advanced">
<div class="wght-advanced-title">高级配置</div>
<div class="wght-mode-row">
<div class="wght-mode-info">
<div class="wght-mode-title">字重覆写模式</div>
<div class="wght-mode-sub" id="wght-mode-sub">
可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置
</div>
</div>
<md-outlined-select id="wght-mode-select" label="覆写模式">
<md-select-option value="0" selected>不处理</md-select-option>
<md-select-option value="1">裁切粗细等级</md-select-option>
<md-select-option value="2">平均分配字重</md-select-option>
<md-select-option value="3">自定义映射</md-select-option>
</md-outlined-select>
</div>
<md-outlined-select id="wght-mode-select" label="覆写模式">
<md-select-option value="0" selected>不处理</md-select-option>
<md-select-option value="1">裁切粗细等级</md-select-option>
<md-select-option value="2">平均分配字重</md-select-option>
</md-outlined-select>
</div>
<!-- 自定义字重映射 (模式=自定义映射时显示) -->
<div class="wght-map" id="wght-map" hidden>
<div class="wght-map-title">字重映射</div>
<div class="wght-map-sub">
设置每个字重等级对应的实际 wght 轴值 (字重等级 1-1000, 可增删)
</div>
<div id="wght-map-rows"></div>
<md-text-button id="wght-map-add" class="wght-map-add">
<md-icon slot="icon">add</md-icon>
新增映射
</md-text-button>
</div>
<!-- 新增字重映射对话框 -->
<md-dialog id="wght-map-add-dialog">
<div slot="headline">新增字重映射</div>
<div slot="content">
<input
type="number"
id="wght-map-add-weight"
class="wght-map-input wght-map-add-input"
min="1"
max="1000"
placeholder="字重等级 (1-1000)"
/>
</div>
<div slot="actions">
<md-text-button id="wght-map-add-cancel">取消</md-text-button>
<md-text-button id="wght-map-add-confirm">添加</md-text-button>
</div>
</md-dialog>
</md-elevated-card>
<div id="slots"></div>
</main>
+2 -53
View File
@@ -1,9 +1,5 @@
// fontsXml.ts — 字重范围覆写 fonts.xml 的 sans-serif family 段
// 覆写采用字符串级替换 (保留文件全部 #ifdef 注释与格式), fast-xml-parser 仅用于结果校验
import { XMLValidator } from 'fast-xml-parser';
/** 覆写模式: 0=不处理 1=裁切粗细等级 2=平均分配字重 */
export type WghtMode = 0 | 1 | 2;
// fontsXml.ts — 字重覆写 UI 辅助 (生成逻辑已迁移至 Go 程序 fontmm-wght)
// 仅保留 UI 渲染滑块默认值所需的函数
export const WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900];
@@ -13,50 +9,3 @@ 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);
}
/** 生成单条 <font> 条目 (缩进与现有 fonts.xml 一致) */
function fontEntry(weight: number, axisWght: number): string {
return ` <font weight="${weight}" style="normal">SysFont-Regular.ttf
<axis tag="ital" stylevalue="0" />
<axis tag="wdth" stylevalue="100" />
<axis tag="wght" stylevalue="${axisWght}" />
</font>`;
}
/**
* 生成 sans-serif family 段
* @param mode 1=裁切 (仅保留 weight ∈ [min,max]) 2=平均 (全保留, axis 按范围插值)
*/
export function generateSansSerifFamily(min: number, max: number, mode: 1 | 2): string {
const kept = mode === 1 ? WEIGHTS.filter((w) => w >= min && w <= max) : WEIGHTS;
const lines = kept.map((w) => {
const axisWght = mode === 2 ? averagedAxis(min, max, w) : w;
return fontEntry(w, axisWght);
});
return ` <family name="sans-serif">\n${lines.join('\n')}\n </family>`;
}
/**
* 在完整 fonts.xml 文本中替换 sans-serif family 段
* mode=0 或无范围时原样返回
*/
export function applyWghtMode(xml: string, mode: WghtMode, min?: number, max?: number): string {
if (mode === 0 || min === undefined || max === undefined) return xml;
const startTag = '<family name="sans-serif">';
const start = xml.indexOf(startTag);
if (start < 0) return xml;
const end = xml.indexOf('</family>', start);
if (end < 0) return xml;
const before = xml.slice(0, start);
const after = xml.slice(end + '</family>'.length);
return before + generateSansSerifFamily(min, max, mode) + after;
}
/** 校验 XML 合法性 (fast-xml-parser) */
export function validateXml(xml: string): boolean {
try {
return XMLValidator.validate(xml) === true;
} catch {
return false;
}
}
+15
View File
@@ -75,6 +75,21 @@ async function mockExec(command: string): Promise<ExecResult> {
if (command.includes('wght-mode.txt')) {
return command.includes('echo') ? fake('') : slow('1');
}
// 字重覆写: Go 程序 fontmm-wght (模拟成功日志)
if (command.includes('fontmm-wght')) {
return slow(
'[✓] 已覆写: system/etc/fonts.xml\n[✓] 已覆写: system/etc/fonts_base.xml\n[✓] 已覆写: system/etc/fonts_ule.xml\n[✓] 已覆写: system/etc/font_fallback.xml\n[✓] 已覆写: system/system_ext/etc/fonts_base.xml\n[✓] 已覆写: system/system_ext/etc/fonts_ule.xml\n[*] 完成, 共覆写 6 个文件',
);
}
// 覆写日志回显: cat wght-apply.log
if (command.includes('wght-apply.log')) {
return slow('[✓] 已覆写: system/etc/fonts.xml\n[✓] 完成, 共覆写 6 个文件');
}
// 自定义字重映射: cat 返回模拟映射, rm/echo 写入模拟成功
if (command.includes('wght-map.txt')) {
if (command.includes('rm -f') || command.includes('echo')) return fake('');
return slow('100 160\n200 250\n300 330\n400 400\n500 480\n600 560\n700 650\n800 680\n900 700');
}
// 覆写 fonts.xml: cp 模拟成功 (fetch work/fonts.xml 在 dev 下 404, 覆写被跳过, 不阻断应用)
if (command.includes('fonts.xml')) {
return slow('');
+197 -32
View File
@@ -29,7 +29,7 @@ import {
} from './ksu';
import { FontFilePicker } from './fontPicker';
import { FontEditorToolDef, MiFontToolDef, ToolHost } from './tools';
import { applyWghtMode } from './fontsXml';
import { averagedAxis, WEIGHTS } from './fontsXml';
import type { FontSlot } from './types';
import * as opentype from 'opentype.js';
@@ -303,12 +303,12 @@ function pickWghtRange(): { min: number; max: number } | null {
}
// 读取字重覆写模式 (FONTS/wght-mode.txt), 默认 0 不处理
async function readWghtMode(): Promise<0 | 1 | 2> {
async function readWghtMode(): Promise<0 | 1 | 2 | 3> {
try {
const { errno, stdout } = await exec(`cat '${FONTS_DIR}/wght-mode.txt' 2>/dev/null || true`);
if (errno === 0) {
const n = Number(stdout.trim());
if (n === 1 || n === 2) return n as 0 | 1 | 2;
if (n === 1 || n === 2 || n === 3) return n as 0 | 1 | 2 | 3;
}
} catch {
// 忽略
@@ -316,35 +316,25 @@ async function readWghtMode(): Promise<0 | 1 | 2> {
return 0;
}
function bytesToBase64(bytes: Uint8Array): string {
let s = '';
for (let i = 0; i < bytes.length; i += 0x8000) {
s += btoa(String.fromCharCode(...bytes.subarray(i, i + 0x8000)));
}
return s;
}
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制)
const WGHT_BIN = '/data/adb/modules/FontMM/tools/fontmm-wght';
// 覆写模块 fonts.xml 的 sans-serif family 段: cp -> fetch -> 字符串替换 -> base64 分块写回
async function applyWghtOverride(mode: 1 | 2, min: number, max: number): Promise<void> {
const modXml = '/data/adb/modules/FontMM/system/etc/fonts.xml';
const tmp = `${WEBROOT_DIR}/work/fonts.new.xml`;
async function applyWghtOverride(mode: 1 | 2 | 3, min: number, max: number): Promise<void> {
const mapArg = mode === 3 ? ` -map '${FONTS_DIR}/wght-map.txt'` : '';
// 日志写到 FONTS/wght-apply.log 方便真机排查; 先 chmod +x 保证可执行
const logFile = `${FONTS_DIR}/wght-apply.log`;
const cmd = `chmod +x '${WGHT_BIN}' 2>/dev/null; '${WGHT_BIN}' -mode ${mode} -min ${min} -max ${max}${mapArg} > '${logFile}' 2>&1`;
try {
await exec(
`mkdir -p '${WEBROOT_DIR}/work' && cp -f '${modXml}' '${WEBROOT_DIR}/work/fonts.xml'`,
);
const res = await fetch('work/fonts.xml');
if (!res.ok) throw new Error(`读取 fonts.xml 失败 (${res.status})`);
const xml = await res.text();
const replaced = applyWghtMode(xml, mode, min, max);
if (replaced === xml) return; // 无变化 (mode 0 或无 sans-serif family)
const b64 = bytesToBase64(new TextEncoder().encode(replaced));
await exec(`rm -f '${tmp}'`);
const CHUNK = 30000;
for (let i = 0; i < b64.length; i += CHUNK) {
const part = b64.slice(i, i + CHUNK);
await exec(`echo '${part}' | base64 -d >> '${tmp}'`);
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})`);
}
await exec(`cp -f '${tmp}' '${modXml}'`);
} catch (e) {
// 覆写失败不阻断应用主流程
console.warn('字重范围覆写失败:', e);
@@ -357,10 +347,11 @@ async function apply() {
renderSlots();
try {
// 字重范围覆写: 用 UI 当前模式 (持久化到 FONTS/wght-mode.txt), 仅当存在可变字体且模式非 0 时处理
const wghtMode = (Number(wghtModeSelect?.value ?? 0) || 0) as 0 | 1 | 2;
const wghtMode = (Number(wghtModeSelect?.value ?? 0) || 0) as 0 | 1 | 2 | 3;
await writeWghtMode(wghtMode);
const wghtPick = pickWghtRange();
if (wghtMode !== 0 && wghtPick) {
// Go 程序自行读取 wght-map.txt (mode 3)
await applyWghtOverride(wghtMode, wghtPick.min, wghtPick.max);
}
@@ -423,9 +414,11 @@ applyBtn?.addEventListener('click', apply);
renderSlots();
// ---------------- 字重覆写模式选择 ----------------
const wghtMapEl = document.getElementById('wght-map');
const wghtMapRows = document.getElementById('wght-map-rows');
// 写入模式到 FONTS/wght-mode.txt
async function writeWghtMode(mode: 0 | 1 | 2): Promise<void> {
async function writeWghtMode(mode: 0 | 1 | 2 | 3): Promise<void> {
try {
await exec(`echo '${mode}' > '${FONTS_DIR}/wght-mode.txt'`);
} catch {
@@ -433,11 +426,144 @@ async function writeWghtMode(mode: 0 | 1 | 2): Promise<void> {
}
}
// 读取自定义字重映射 (FONTS/wght-map.txt: 每行 "weight axis")
async function readWghtMap(): Promise<Record<number, number>> {
const map: Record<number, number> = {};
try {
const { errno, stdout } = await exec(`cat '${FONTS_DIR}/wght-map.txt' 2>/dev/null || true`);
if (errno === 0) {
for (const line of stdout.split('\n')) {
const m = line.trim().match(/^(\d+)\s+(\d+)$/);
if (m) map[Number(m[1])] = Number(m[2]);
}
}
} catch {
// 忽略
}
return map;
}
// 保存自定义字重映射 (DOM 驱动: 每行 data-weight + 输入值)
async function saveWghtMap(): Promise<void> {
const lines: string[] = [];
document.querySelectorAll<HTMLElement>('#wght-map-rows .wght-map-row').forEach((row) => {
const w = Number(row.dataset.weight);
const input = row.querySelector<HTMLInputElement>('.wght-map-input');
const v = Number(input?.value);
if (Number.isFinite(w) && Number.isFinite(v)) lines.push(`${w} ${Math.round(v)}`);
});
try {
await exec(`rm -f '${FONTS_DIR}/wght-map.txt'`);
for (const line of lines) {
await exec(`echo '${line}' >> '${FONTS_DIR}/wght-map.txt'`);
}
} catch {
// 忽略写入失败
}
}
// 追加一行映射 (weight 标签 + 滑块 + 输入框 + 删除按钮)
function appendWghtMapRow(
rowsEl: HTMLElement,
w: number,
axis: number,
min: number,
max: number,
): void {
const row = document.createElement('div');
row.className = 'wght-map-row';
row.dataset.weight = String(w);
const label = document.createElement('span');
label.className = 'wght-map-label';
label.textContent = String(w);
const slider = document.createElement('md-slider') as any;
slider.min = min;
slider.max = max;
slider.step = 1;
const input = document.createElement('input');
input.type = 'number';
input.min = String(min);
input.max = String(max);
input.className = 'wght-map-input';
input.ariaLabel = `weight ${w} 的轴值`;
const setBoth = (v: number) => {
const clamped = Math.min(max, Math.max(min, Math.round(v)));
slider.value = clamped;
input.value = String(clamped);
};
setBoth(axis);
slider.addEventListener('input', () => {
input.value = String(slider.value);
});
slider.addEventListener('change', () => void saveWghtMap());
input.addEventListener('input', () => {
const v = Number(input.value);
if (Number.isFinite(v)) slider.value = Math.min(max, Math.max(min, v));
});
input.addEventListener('change', () => {
const v = Number(input.value);
if (!Number.isFinite(v)) {
input.value = String(slider.value);
return;
}
setBoth(v);
void saveWghtMap();
});
const delBtn = document.createElement('md-icon-button') as any;
delBtn.ariaLabel = `删除字重 ${w} 映射`;
delBtn.className = 'wght-map-del';
const delIcon = document.createElement('md-icon');
delIcon.textContent = 'close';
delBtn.appendChild(delIcon);
delBtn.addEventListener('click', () => {
row.remove();
void saveWghtMap();
});
row.append(label, slider, input, delBtn);
rowsEl.appendChild(row);
}
// 渲染字重映射行 (读 wght-map.txt; 空时默认 9 档平均插值)
function renderWghtMapRows(): void {
if (!wghtMapRows) return;
const range = pickWghtRange();
const min = range?.min ?? 1;
const max = range?.max ?? 1000;
void readWghtMap().then((saved) => {
if (!wghtMapRows) return;
wghtMapRows.textContent = '';
const map: Record<number, number> = Object.keys(saved).length > 0 ? saved : {};
if (Object.keys(map).length === 0) {
for (const w of WEIGHTS) map[w] = averagedAxis(min, max, w);
}
for (const w of Object.keys(map)
.map(Number)
.sort((a, b) => a - b)) {
appendWghtMapRow(wghtMapRows, w, map[w], min, max);
}
});
}
// 根据模式显示/隐藏映射编辑区
function updateWghtMapVisibility(): void {
const isCustom = Number(wghtModeSelect?.value) === 3;
if (wghtMapEl) wghtMapEl.hidden = !isCustom;
if (isCustom) renderWghtMapRows();
}
// 回填模式选择
async function initWghtModeUI(): Promise<void> {
const mode = await readWghtMode();
if (wghtModeSelect) wghtModeSelect.value = String(mode);
updateWghtModeDisabled();
updateWghtMapVisibility();
}
// 根据是否有可变字体决定是否禁用 (emoji/mono 不计入)
@@ -453,10 +579,49 @@ function updateWghtModeDisabled(): void {
wghtModeSelect?.addEventListener('change', () => {
const v = Number(wghtModeSelect.value);
if (v === 0 || v === 1 || v === 2) void writeWghtMode(v as 0 | 1 | 2);
if (v === 0 || v === 1 || v === 2 || v === 3) {
void writeWghtMode(v as 0 | 1 | 2 | 3);
updateWghtMapVisibility();
}
});
void initWghtModeUI();
// ---------------- 新增字重映射 ----------------
const wghtMapAddBtn = document.getElementById('wght-map-add');
const wghtMapAddDialog = document.getElementById('wght-map-add-dialog') as any;
const wghtMapAddWeight = document.getElementById('wght-map-add-weight') as HTMLInputElement;
wghtMapAddBtn?.addEventListener('click', () => {
if (wghtMapAddWeight) wghtMapAddWeight.value = '';
if (wghtMapAddDialog) wghtMapAddDialog.open = true;
});
document.getElementById('wght-map-add-cancel')?.addEventListener('click', () => {
if (wghtMapAddDialog) wghtMapAddDialog.open = false;
});
document.getElementById('wght-map-add-confirm')?.addEventListener('click', () => {
if (wghtMapAddDialog) wghtMapAddDialog.open = false;
const w = Number(wghtMapAddWeight?.value);
if (!Number.isFinite(w) || w < 1 || w > 1000) {
toast('字重等级需为 1-1000 的整数');
return;
}
const weight = Math.round(w);
// 重复 weight 则更新, 否则新增一行
const existing = document.querySelector<HTMLElement>(
`#wght-map-rows .wght-map-row[data-weight="${weight}"]`,
);
if (!wghtMapRows) return;
const range = pickWghtRange();
const min = range?.min ?? 1;
const max = range?.max ?? 1000;
if (existing) {
existing.scrollIntoView({ block: 'center' });
} else {
appendWghtMapRow(wghtMapRows, weight, averagedAxis(min, max, weight), min, max);
}
void saveWghtMap();
});
// ---------------- 导航与视图切换 ----------------
const homeView = document.getElementById('home-view')!;
const configView = document.getElementById('config-view')!;
+115 -18
View File
@@ -1143,33 +1143,130 @@ md-dialog {
}
// ---- 字重覆写模式选择 ----
.wght-mode-row {
display: flex;
align-items: center;
gap: 12px;
// ---- 高级配置 (字重覆写 + 自定义映射) ----
.wght-advanced {
margin-bottom: 16px;
padding: 14px 16px;
border-radius: var(--md-shape-corner-large);
background: var(--md-sys-color-surface-container-low);
padding: 16px;
--md-elevated-card-container-shape: var(--md-shape-corner-large);
.wght-mode-info {
flex: 1;
min-width: 0;
.wght-advanced-title {
font-size: var(--md-sys-typescale-title-medium-size);
font-weight: var(--md-sys-typescale-title-medium-weight);
margin-bottom: 4px;
}
.wght-mode-title {
font-size: var(--md-sys-typescale-title-medium-size);
font-weight: var(--md-sys-typescale-title-medium-weight);
.wght-mode-row {
display: flex;
align-items: center;
gap: 12px;
.wght-mode-info {
flex: 1;
min-width: 0;
.wght-mode-title {
font-size: var(--md-sys-typescale-body-large-size);
font-weight: 500;
}
.wght-mode-sub {
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
margin-top: 2px;
}
}
.wght-mode-sub {
md-outlined-select {
flex-shrink: 0;
min-width: 150px;
}
}
.wght-map {
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--md-sys-color-outline-variant);
.wght-map-title {
font-size: var(--md-sys-typescale-title-small-size);
font-weight: 500;
}
.wght-map-sub {
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
margin-top: 2px;
margin-bottom: 8px;
}
.wght-map-row {
display: flex;
align-items: center;
gap: 8px;
padding: 2px 0;
.wght-map-label {
flex-shrink: 0;
width: 28px;
text-align: right;
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
}
md-slider {
flex: 1;
// 覆盖组件默认 min-inline-size: 200px, 适配手机窄屏
min-inline-size: 64px;
min-width: 64px;
}
.wght-map-input {
flex-shrink: 0;
width: 64px;
}
.wght-map-del {
flex-shrink: 0;
width: 32px;
height: 32px;
--md-icon-button-state-layer-size: 32px;
md-icon {
font-size: 18px;
}
}
}
.wght-map-add {
margin-top: 8px;
}
}
}
md-outlined-select {
flex-shrink: 0;
min-width: 150px;
// 字重映射输入框: 底线式 (顶层通用, 行内与新增弹窗共用)
.wght-map-input {
padding: 4px 0 4px 4px;
border: none;
border-bottom: 1px solid var(--md-sys-color-outline);
background: transparent;
color: var(--md-sys-color-on-surface);
font-size: var(--md-sys-typescale-body-medium-size);
outline: none;
transition: border-color 0.15s ease;
&:focus {
border-bottom-color: var(--md-sys-color-primary);
border-bottom-width: 2px;
}
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
}
.wght-map-add-input {
width: 100%;
box-sizing: border-box;
}
+2 -1
View File
@@ -654,7 +654,8 @@ class FontEditorPage {
const tmp = `${WEBROOT_DIR}/work/export.tmp`;
await exec(`rm -f ${shellQuote(tmp)} && mkdir -p ${shellQuote(outDir)}`);
const CHUNK = 60000; // base64 字符, 约 45KB 二进制
// exec 命令长度真机受限 (~32KB), 分块必须远小于该限制 (60000 会截断导出)
const CHUNK = 8000; // base64 字符, 约 6KB 二进制
const total = Math.ceil(b64.length / CHUNK);
for (let i = 0; i < b64.length; i += CHUNK) {
const part = b64.slice(i, i + CHUNK);