mirror of
https://github.com/YuleBest/FontMM.git
synced 2026-12-04 03:11:48 +08:00
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:
1 parent
2ec6c45c80
commit
e6e7784e0b
15 files changed
+734
-116
No files matched your search
@@ -0,0 +1,39 @@
|
||||
name: Go
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'golang/**'
|
||||
- 'dev/build-wght.sh'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'golang/**'
|
||||
- 'dev/build-wght.sh'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test-and-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
|
||||
- name: Vet
|
||||
run: cd golang && go vet ./...
|
||||
|
||||
- name: Test
|
||||
run: cd golang && go test ./...
|
||||
|
||||
- name: Cross-compile (android/arm64)
|
||||
run: cd golang && GOOS=android GOARCH=arm64 CGO_ENABLED=0 go build -ldflags="-s -w" -o /tmp/fontmm-wght ./cmd/fontmm-wght
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: fontmm-wght
|
||||
path: /tmp/fontmm-wght
|
||||
@@ -7,3 +7,5 @@ reasonix.toml
|
||||
.agent/
|
||||
|
||||
.ref/
|
||||
src/tools/fontmm-wght
|
||||
golang/bin/
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
# build-wght.sh - 交叉编译 fontmm-wght (Go -> android-arm64, 无需 NDK)
|
||||
# 产物输出到 src/tools/fontmm-wght, 随模块 zip 打包 (与 mi-font-download.sh 等工具脚本同层)
|
||||
set -e
|
||||
cd "$(dirname "$0")/../golang"
|
||||
|
||||
echo "[*] 交叉编译 fontmm-wght (android/arm64)..."
|
||||
GOOS=android GOARCH=arm64 CGO_ENABLED=0 go build -ldflags="-s -w" -o ../src/tools/fontmm-wght ./cmd/fontmm-wght
|
||||
|
||||
echo "[✓] 产物: src/tools/fontmm-wght ($(wc -c < ../src/tools/fontmm-wght) 字节)"
|
||||
@@ -32,6 +32,11 @@ rm -f "$PRE_OUT" "$TPL_OUT" # 先删旧的, 防止 zip 增量更新残留已
|
||||
# 0. 同步派生字体配置 (fonts.xml 为唯一源, 复制生成 fonts_base/ule/font_fallback 等)
|
||||
bash "$ROOT_DIR/dev/sync-fonts-xml.sh"
|
||||
|
||||
# 0.5 交叉编译 fontmm-wght (Go -> android-arm64, 字重范围覆写用)
|
||||
bash "$ROOT_DIR/dev/build-wght.sh"
|
||||
# 保证工具二进制可执行 (zip 权限位 -> Magisk 安装后保持)
|
||||
chmod 755 "$SRC_DIR/tools/fontmm-wght"
|
||||
|
||||
# 2. 打包函数: $1=输出路径, $2=额外排除模式 (可选)
|
||||
# (zip 根 = 模块根, 不含 src 这层目录)
|
||||
pack() {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// fontmm-wght: 覆写模块字体配置 XML 的 sans-serif family 字重范围
|
||||
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>] [-xml-dir <模块根>]
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"fontmm/internal/wght"
|
||||
)
|
||||
|
||||
func main() {
|
||||
mode := flag.Int("mode", 0, "覆写模式: 0=不处理 1=裁切 2=平均分配 3=自定义映射")
|
||||
min := flag.Int("min", 100, "裁切/平均最小字重")
|
||||
max := flag.Int("max", 900, "裁切/平均最大字重")
|
||||
mapPath := flag.String("map", "", "自定义映射文件 (mode 3): 每行 'weight axis'")
|
||||
xmlDir := flag.String("xml-dir", "/data/adb/modules/FontMM", "模块根目录 (含 system/etc/fonts.xml)")
|
||||
flag.Parse()
|
||||
|
||||
if *mode == 0 {
|
||||
fmt.Println("[-] mode 0: 不处理")
|
||||
return
|
||||
}
|
||||
|
||||
var customMap map[int]int
|
||||
if *mode == 3 {
|
||||
var err error
|
||||
customMap, err = wght.ReadCustomMap(*mapPath)
|
||||
if err != nil {
|
||||
fmt.Printf("[x] 读取映射文件失败: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if len(customMap) == 0 {
|
||||
fmt.Println("[-] 映射文件为空, 使用平均分配回退")
|
||||
}
|
||||
}
|
||||
|
||||
changed, err := wght.ApplyToDir(*xmlDir, *mode, *min, *max, customMap)
|
||||
if err != nil {
|
||||
fmt.Printf("[x] %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("[✓] 完成, 共覆写 %d 个文件\n", changed)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module fontmm
|
||||
|
||||
go 1.24.4
|
||||
@@ -0,0 +1,146 @@
|
||||
// Package wght 提供字体配置 XML 的字重范围覆写逻辑
|
||||
package wght
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 标准 9 档字重
|
||||
var Weights = []int{100, 200, 300, 400, 500, 600, 700, 800, 900}
|
||||
|
||||
// 模块内需要覆写的字体配置 XML (相对模块根)
|
||||
var XMLRelPaths = []string{
|
||||
"system/etc/fonts.xml",
|
||||
"system/etc/fonts_base.xml",
|
||||
"system/etc/fonts_ule.xml",
|
||||
"system/etc/font_fallback.xml",
|
||||
"system/system_ext/etc/fonts_base.xml",
|
||||
"system/system_ext/etc/fonts_ule.xml",
|
||||
}
|
||||
|
||||
// 平均分配: weight w 对应的 axis 值 (400 固定, 两端 floor 线性插值)
|
||||
func AveragedAxis(min, max, w int) int {
|
||||
if w == 400 {
|
||||
return 400
|
||||
}
|
||||
if w < 400 {
|
||||
return min + (400-min)*(w-100)/300
|
||||
}
|
||||
return 400 + (max-400)*(w-400)/500
|
||||
}
|
||||
|
||||
// 生成单条 <font> 条目 (缩进与现有 fonts.xml 一致)
|
||||
func fontEntry(weight, axisWght int) string {
|
||||
return fmt.Sprintf(` <font weight="%d" style="normal">SysFont-Regular.ttf
|
||||
<axis tag="ital" stylevalue="0" />
|
||||
<axis tag="wdth" stylevalue="100" />
|
||||
<axis tag="wght" stylevalue="%d" />
|
||||
</font>`, weight, axisWght)
|
||||
}
|
||||
|
||||
// 生成 sans-serif family 段
|
||||
// mode 1=裁切 (weight ∈ [min,max]) 2=平均 (全保留, axis 插值) 3=自定义映射 (1-1000 任意)
|
||||
func GenerateFamily(min, max, mode int, customMap map[int]int) string {
|
||||
var lines []string
|
||||
if mode == 3 && len(customMap) > 0 {
|
||||
ws := make([]int, 0, len(customMap))
|
||||
for w := range customMap {
|
||||
ws = append(ws, w)
|
||||
}
|
||||
sort.Ints(ws)
|
||||
for _, w := range ws {
|
||||
lines = append(lines, fontEntry(w, customMap[w]))
|
||||
}
|
||||
} else {
|
||||
for _, w := range Weights {
|
||||
if mode == 1 && (w < min || w > max) {
|
||||
continue
|
||||
}
|
||||
var axis int
|
||||
if mode == 3 {
|
||||
if v, ok := customMap[w]; ok {
|
||||
axis = v
|
||||
} else {
|
||||
axis = AveragedAxis(min, max, w)
|
||||
}
|
||||
} else if mode == 2 {
|
||||
axis = AveragedAxis(min, max, w)
|
||||
} else {
|
||||
axis = w
|
||||
}
|
||||
lines = append(lines, fontEntry(w, axis))
|
||||
}
|
||||
}
|
||||
return " <family name=\"sans-serif\">\n" + strings.Join(lines, "\n") + "\n </family>"
|
||||
}
|
||||
|
||||
// 在完整 XML 中替换 sans-serif family 段; 未找到或 mode 0 时原样返回
|
||||
func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string {
|
||||
if mode == 0 {
|
||||
return xml
|
||||
}
|
||||
startTag := `<family name="sans-serif">`
|
||||
start := strings.Index(xml, startTag)
|
||||
if start < 0 {
|
||||
return xml
|
||||
}
|
||||
end := strings.Index(xml[start:], "</family>")
|
||||
if end < 0 {
|
||||
return xml
|
||||
}
|
||||
end += start + len("</family>")
|
||||
return xml[:start] + GenerateFamily(min, max, mode, customMap) + xml[end:]
|
||||
}
|
||||
|
||||
// 读取自定义映射文件 (每行 "weight axis")
|
||||
func ReadCustomMap(path string) (map[int]int, error) {
|
||||
m := map[int]int{}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
w, err1 := strconv.Atoi(parts[0])
|
||||
v, err2 := strconv.Atoi(parts[1])
|
||||
if err1 == nil && err2 == nil {
|
||||
m[w] = v
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// ApplyToDir 覆写模块根目录下的全部字体配置 XML, 返回覆写文件数
|
||||
func ApplyToDir(xmlDir string, mode, min, max int, customMap map[int]int) (int, error) {
|
||||
changed := 0
|
||||
for _, rel := range XMLRelPaths {
|
||||
p := xmlDir + "/" + rel
|
||||
data, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "[-] 跳过 %s: %v\n", rel, err)
|
||||
continue
|
||||
}
|
||||
replaced := ApplyWghtMode(string(data), mode, min, max, customMap)
|
||||
if replaced == string(data) {
|
||||
fmt.Printf("[-] 无变化: %s\n", rel)
|
||||
continue
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(replaced), 0o644); err != nil {
|
||||
return changed, fmt.Errorf("写入失败 %s: %w", rel, err)
|
||||
}
|
||||
changed++
|
||||
fmt.Printf("[✓] 已覆写: %s\n", rel)
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package wght
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 平均分配公式 (MiSansVF 150-700, 与用户示例一致)
|
||||
func TestAveragedAxis(t *testing.T) {
|
||||
want := map[int]int{100: 150, 200: 233, 300: 316, 400: 400, 500: 460, 600: 520, 700: 580, 800: 640, 900: 700}
|
||||
for w, v := range want {
|
||||
if got := AveragedAxis(150, 700, w); got != v {
|
||||
t.Errorf("AveragedAxis(150,700,%d) = %d, want %d", w, got, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func extractAttrs(family string) ([]int, []int) {
|
||||
var ws, axes []int
|
||||
for _, line := range strings.Split(family, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if strings.HasPrefix(line, "<font weight=") {
|
||||
var w int
|
||||
if _, err := fmt.Sscanf(line, "<font weight=\"%d\"", &w); err == nil {
|
||||
ws = append(ws, w)
|
||||
}
|
||||
}
|
||||
if strings.Contains(line, `<axis tag="wght" stylevalue="`) {
|
||||
var v int
|
||||
if _, err := fmt.Sscanf(line, "<axis tag=\"wght\" stylevalue=\"%d\"", &v); err == nil {
|
||||
axes = append(axes, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ws, axes
|
||||
}
|
||||
|
||||
func TestGenerateFamilyTrim(t *testing.T) {
|
||||
family := GenerateFamily(150, 700, 1, nil)
|
||||
ws, axes := extractAttrs(family)
|
||||
want := []int{200, 300, 400, 500, 600, 700}
|
||||
if len(ws) != len(want) {
|
||||
t.Fatalf("裁切 weight = %v, want %v", ws, want)
|
||||
}
|
||||
for i := range want {
|
||||
if ws[i] != want[i] || axes[i] != want[i] {
|
||||
t.Errorf("裁切第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], want[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateFamilyAvg(t *testing.T) {
|
||||
family := GenerateFamily(150, 700, 2, nil)
|
||||
ws, axes := extractAttrs(family)
|
||||
wantW := []int{100, 200, 300, 400, 500, 600, 700, 800, 900}
|
||||
wantA := []int{150, 233, 316, 400, 460, 520, 580, 640, 700}
|
||||
if len(ws) != 9 {
|
||||
t.Fatalf("平均 weight = %v", ws)
|
||||
}
|
||||
for i := range wantW {
|
||||
if ws[i] != wantW[i] || axes[i] != wantA[i] {
|
||||
t.Errorf("平均第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], wantW[i], wantA[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateFamilyCustom(t *testing.T) {
|
||||
m := map[int]int{150: 180, 250: 300, 400: 400, 700: 650}
|
||||
family := GenerateFamily(150, 700, 3, m)
|
||||
ws, axes := extractAttrs(family)
|
||||
wantW := []int{150, 250, 400, 700}
|
||||
wantA := []int{180, 300, 400, 650}
|
||||
for i := range wantW {
|
||||
if ws[i] != wantW[i] || axes[i] != wantA[i] {
|
||||
t.Errorf("自定义第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], wantW[i], wantA[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyWghtMode(t *testing.T) {
|
||||
xml := "<?xml version=\"1.0\"?>\n<familyset>\n <!-- #ifdef OPLUS_FEATURE_FONT_FLIP -->\n" +
|
||||
" <family name=\"sans-serif\">\n <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
|
||||
" <axis tag=\"wght\" stylevalue=\"100\" />\n </font>\n </family>\n" +
|
||||
" <!-- #endif -->\n</familyset>\n"
|
||||
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
|
||||
if !strings.Contains(replaced, "OPLUS_FEATURE_FONT_FLIP") {
|
||||
t.Error("覆写后 #ifdef 注释丢失")
|
||||
}
|
||||
if !strings.Contains(replaced, `stylevalue="233"`) {
|
||||
t.Error("覆写后缺少平均分配值 233")
|
||||
}
|
||||
if strings.Count(replaced, "<family name=\"sans-serif\">") != 1 {
|
||||
t.Error("sans-serif family 数量异常")
|
||||
}
|
||||
// mode 0 原样
|
||||
if ApplyWghtMode(xml, 0, 150, 700, nil) != xml {
|
||||
t.Error("mode=0 应原样返回")
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -10,6 +10,9 @@
|
||||
"fmt:check": "pnpm -C web fmt:check",
|
||||
"type-check": "pnpm -C web type-check",
|
||||
"shellcheck": "find src -name '*.sh' -print0 | xargs -0 shellcheck",
|
||||
"shfmt": "find src -name '*.sh' -print0 | xargs -0 shfmt -i 4 -w -d"
|
||||
"shfmt": "find src -name '*.sh' -print0 | xargs -0 shfmt -i 4 -w -d",
|
||||
"go:test": "cd golang && go vet ./... && go test ./...",
|
||||
"go:build": "bash dev/build-wght.sh",
|
||||
"go:build:local": "cd golang && go build -o /tmp/fontmm-wght ./cmd/fontmm-wght"
|
||||
}
|
||||
}
|
||||
+49
-11
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user