feat(wght): 支持多字重静态映射与混合模式覆写

This commit is contained in:
YuleBest committed 2026-11-29 23:26:03 +08:00
1 parent 411498d98e
commit 93bdb86599
3 files changed
+343 -23

No files matched your search

+3 -2
View File
@@ -1,6 +1,7 @@
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围或多字重静态映射
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>] [-xml-dir <模块根>] [-sync]
// 说明: 只修改主配置 system/etc/fonts.xml, 加 -sync 后复制到各派生配置 (issue #7)
// 说明: 优先读取 backup/fonts.xml (若存在) 并结合 FONTS/slot-modes.txt 与 FONTS/multi/ 生成 system/etc/fonts.xml,
// 加 -sync 后复制到各派生配置 (issue #7)
package main
import (
+234 -21
View File
@@ -26,6 +26,7 @@ const (
// familySpec 描述一个需要覆写字重的家族及其条目格式
type familySpec struct {
slot string // 所属逻辑槽位: "en" | "hans" | "hant"
openTag string // 家族起始标签 (用于定位与生成)
fontFile string // 家族引用的字体文件
postScript string // postScriptName 属性 (无则为空)
@@ -36,14 +37,17 @@ type familySpec struct {
// 所有生效家族: 英文 (sans-serif / sys-sans-en) 与中文 (zh-Hans / zh-Hant) 都要覆盖,
// 否则中文或英文单独使用时字重映射不生效 (issue #7)
var FamilySpecs = []familySpec{
{openTag: `<family name="sans-serif">`, fontFile: "SysFont-Regular.ttf", axis: axisFull},
{openTag: `<family name="sys-sans-en">`, fontFile: "SysSans-En-Regular.ttf", postScript: "OPlusSansEn", axis: axisWghtOnly},
{openTag: `<family lang="zh-Hans">`, fontFile: "SysSans-Hans-Regular.ttf", postScript: "OPPO_Sans_4.0_SC", serifFallback: true, axis: axisWghtOnly},
{openTag: `<family lang="zh-Hant,zh-Bopo">`, fontFile: "SysSans-Hant-Regular.ttf", postScript: "OPPO_Sans_4.0_TC", serifFallback: true, axis: axisWghtOnly},
{slot: "en", openTag: `<family name="sans-serif">`, fontFile: "SysFont-Regular.ttf", axis: axisFull},
{slot: "en", openTag: `<family name="sys-sans-en">`, fontFile: "SysSans-En-Regular.ttf", postScript: "OPlusSansEn", axis: axisWghtOnly},
{slot: "hans", openTag: `<family lang="zh-Hans">`, fontFile: "SysSans-Hans-Regular.ttf", postScript: "OPPO_Sans_4.0_SC", serifFallback: true, axis: axisWghtOnly},
{slot: "hant", openTag: `<family lang="zh-Hant,zh-Bopo">`, fontFile: "SysSans-Hant-Regular.ttf", postScript: "OPPO_Sans_4.0_TC", serifFallback: true, axis: axisWghtOnly},
}
// 主配置文件名 (唯一源)
const SourceXMLRel = "system/etc/fonts.xml"
// 主配置文件名 (唯一源) 与纯净备份路径
const (
SourceXMLRel = "system/etc/fonts.xml"
BackupXMLRel = "backup/fonts.xml"
)
// 派生配置 (与 fonts.xml 内容一致, 由 -sync 复制生成)
var DerivedXMLRel = []string{
@@ -54,6 +58,80 @@ var DerivedXMLRel = []string{
"system/system_ext/etc/fonts_ule.xml",
}
// SlotMode 描述槽位当前字体模式 ("single" | "multi")
type SlotMode string
const (
SlotModeSingle SlotMode = "single"
SlotModeMulti SlotMode = "multi"
)
// MultiSlotConfig 描述一个生效后的多字重配置 (支持 hant/en 回退到 hans)
type MultiSlotConfig struct {
SourceSlot string // 实际使用的字体来源槽位: "hans" | "hant" | "en"
Available []int // 已选择的字重列表 (升序, 100..900)
}
// FamilyConfig 描述某家族最终生效的模式 (单字体覆写 或 多字重静态映射)
type FamilyConfig struct {
Multi *MultiSlotConfig // 非 nil 时按多字重生成, 忽略 wght 轴覆写
}
// NearestWeight 从已选字重列表中挑选最接近 target 的档位。
// 距离相等时: target >= 400 偏向更重档位 (如 400 取 500、600 取 700),
// target < 400 偏向更轻档位 (如 300 取 200)。
func NearestWeight(available []int, target int) int {
if len(available) == 0 {
return 400
}
best := available[0]
bestDist := absInt(best - target)
for _, w := range available[1:] {
d := absInt(w - target)
if d < bestDist || (d == bestDist && ((target >= 400 && w > best) || (target < 400 && w < best))) {
best = w
bestDist = d
}
}
return best
}
func absInt(x int) int {
if x < 0 {
return -x
}
return x
}
func slotCapName(slot string) string {
switch slot {
case "hans":
return "Hans"
case "hant":
return "Hant"
case "en":
return "En"
default:
return slot
}
}
// multiFontFile 返回多字重模式下指定已解析字重对应的系统字体文件名。
// 400 复用原有的 Regular 占位文件 (避免重复复制); 其他档位使用 FontMM-<Slot>-<W>.ttf。
func multiFontFile(spec familySpec, sourceSlot string, resolvedWeight int) string {
if resolvedWeight == 400 {
if sourceSlot == spec.slot {
return spec.fontFile
}
// 繁体或英文回退到简体多字重时直接指向简体的 Regular, 避免重复文件与多余缓存
if sourceSlot == "hans" {
return "SysSans-Hans-Regular.ttf"
}
return fmt.Sprintf("SysSans-%s-Regular.ttf", slotCapName(sourceSlot))
}
return fmt.Sprintf("FontMM-%s-%d.ttf", slotCapName(sourceSlot), resolvedWeight)
}
// 平均分配: weight w 对应的 axis 值 (400 固定, 两端 floor 线性插值)
func AveragedAxis(min, max, w int) int {
if w == 400 {
@@ -85,10 +163,33 @@ func fontEntryFor(spec familySpec, weight, axisWght int) string {
}
// 生成 zh-Hans/zh-Hant 家族的 fallbackFor="serif" 400 条目
func serifEntry(spec familySpec) string {
func serifEntry(spec familySpec, fontFile string) string {
return fmt.Sprintf(` <font weight="400" style="normal" fallbackFor="serif"
postScriptName="%s">%s
</font>`, spec.postScript, spec.fontFile)
</font>`, spec.postScript, fontFile)
}
// 生成单条静态多字重 <font> 条目 (不带 <axis tag="wght"/>)
func staticFontEntryFor(spec familySpec, weight int, fontFile string) string {
if spec.postScript != "" {
return fmt.Sprintf(` <font weight="%d" style="normal" postScriptName="%s" >%s</font>`,
weight, spec.postScript, fontFile)
}
return fmt.Sprintf(` <font weight="%d" style="normal">%s</font>`, weight, fontFile)
}
// 生成多字重家族段: 缺失档位按 NearestWeight 指向最接近的已选字重文件
func generateMultiFamily(spec familySpec, weights []int, multi MultiSlotConfig) string {
var lines []string
for _, w := range weights {
resolved := NearestWeight(multi.Available, w)
file := multiFontFile(spec, multi.SourceSlot, resolved)
lines = append(lines, staticFontEntryFor(spec, w, file))
if spec.serifFallback && w == 400 {
lines = append(lines, serifEntry(spec, file))
}
}
return " " + spec.openTag + "\n" + strings.Join(lines, "\n") + "\n </family>"
}
// 生成家族段 (mode 1=裁切 2=平均 3=自定义映射)
@@ -119,14 +220,14 @@ func generateFamily(spec familySpec, weights []int, min, max, mode int, customMa
}
lines = append(lines, fontEntryFor(spec, w, axis))
if spec.serifFallback && w == 400 {
lines = append(lines, serifEntry(spec))
lines = append(lines, serifEntry(spec, spec.fontFile))
}
}
return " " + spec.openTag + "\n" + strings.Join(lines, "\n") + "\n </family>"
}
// 在完整 XML 中覆写指定家族段; 家族不存在时原样返回
func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap map[int]int) string {
func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap map[int]int, multi *MultiSlotConfig) string {
start := findFamilyStart(xml, spec.openTag)
if start < 0 {
return xml
@@ -135,11 +236,15 @@ func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap ma
if end < 0 {
return xml
}
// 字重集选择: 裁切保留原家族声明字重 (兼容设备 XML), 平均分配固定 9 档完整粗细,
// 自定义映射由映射文件的键决定
block := xml[start:end]
if multi == nil && mode == 0 {
return xml
}
// 字重集选择: 多字重 / 裁切保留原家族声明字重 (兼容设备 XML, 含 1000),
// 平均分配固定 9 档完整粗细, 自定义映射由映射文件的键决定
weights := Weights
if mode == 1 {
if ex := extractWeights(xml[start:end]); len(ex) > 0 {
if multi != nil || mode == 1 {
if ex := extractWeights(block); len(ex) > 0 {
weights = ex
}
}
@@ -155,17 +260,33 @@ func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap ma
if lineEnd < len(xml) {
lineEnd++ // 吃掉换行
}
return xml[:lineStart] + generateFamily(spec, weights, min, max, mode, customMap) + "\n" + xml[lineEnd:]
var generated string
if multi != nil {
generated = generateMultiFamily(spec, weights, *multi)
} else {
generated = generateFamily(spec, weights, min, max, mode, customMap)
}
return xml[:lineStart] + generated + "\n" + xml[lineEnd:]
}
// 覆写全部生效家族 (mode 0 原样返回)
func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string {
if mode == 0 {
return xml
return ApplyWghtAndMulti(xml, mode, min, max, customMap, nil)
}
// ApplyWghtAndMulti 按槽位生效配置同时处理单字体字重覆写与多字重静态映射。
// slotMulti 的键为槽位名 ("hans" / "hant" / "en"), 非 nil 的槽位按多字重生成, 否则走单字体覆写。
func ApplyWghtAndMulti(xml string, mode, min, max int, customMap map[int]int, slotMulti map[string]*MultiSlotConfig) string {
result := xml
for _, spec := range FamilySpecs {
result = replaceFamily(result, spec, mode, min, max, customMap)
var multi *MultiSlotConfig
if slotMulti != nil {
multi = slotMulti[spec.slot]
}
if multi == nil && mode == 0 {
continue
}
result = replaceFamily(result, spec, mode, min, max, customMap, multi)
}
return result
}
@@ -282,17 +403,109 @@ func ReadCustomMap(path string) (map[int]int, error) {
return m, nil
}
// ReadSlotModes 读取 FONTS/slot-modes.txt (格式: slot=single|multi), 缺失时全部默认 single
func ReadSlotModes(xmlDir string) map[string]SlotMode {
modes := map[string]SlotMode{
"hans": SlotModeSingle,
"hant": SlotModeSingle,
"en": SlotModeSingle,
}
data, err := os.ReadFile(filepath.Join(xmlDir, "FONTS", "slot-modes.txt"))
if err != nil {
return modes
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
idx := strings.IndexByte(line, '=')
if idx <= 0 {
continue
}
k := strings.TrimSpace(line[:idx])
v := strings.TrimSpace(line[idx+1:])
if _, ok := modes[k]; !ok {
continue
}
if v == string(SlotModeMulti) {
modes[k] = SlotModeMulti
} else if v == string(SlotModeSingle) {
modes[k] = SlotModeSingle
}
}
return modes
}
func fileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
// scanMultiWeights 扫描 FONTS/multi/<slot>/<w>.ttf 中已设置的字重档位 (升序)
func scanMultiWeights(xmlDir, slot string) []int {
var out []int
for _, w := range Weights {
p := filepath.Join(xmlDir, "FONTS", "multi", slot, fmt.Sprintf("%d.ttf", w))
if fileExists(p) {
out = append(out, w)
}
}
return out
}
// ResolveMultiConfigs 根据 FONTS/slot-modes.txt 与 FONTS/ 实际字体计算各槽位多字重配置。
// hant/en 在自身模式下无字体时自动回退到 hans 的实际生效模式。
func ResolveMultiConfigs(xmlDir string) map[string]*MultiSlotConfig {
modes := ReadSlotModes(xmlDir)
result := map[string]*MultiSlotConfig{}
var hansMulti *MultiSlotConfig
if modes["hans"] == SlotModeMulti {
if ws := scanMultiWeights(xmlDir, "hans"); len(ws) > 0 {
hansMulti = &MultiSlotConfig{SourceSlot: "hans", Available: ws}
result["hans"] = hansMulti
}
}
for _, slot := range []string{"hant", "en"} {
if modes[slot] == SlotModeMulti {
if ws := scanMultiWeights(xmlDir, slot); len(ws) > 0 {
result[slot] = &MultiSlotConfig{SourceSlot: slot, Available: ws}
continue
}
// 多字重模式下 0 个字重时回退到 hans
if hansMulti != nil {
result[slot] = hansMulti
}
continue
}
// 单字体模式下未设置 <slot>.ttf 时回退到 hans
if !fileExists(filepath.Join(xmlDir, "FONTS", slot+".ttf")) && hansMulti != nil {
result[slot] = hansMulti
}
}
return result
}
// ApplyToDir 覆写模块根目录下的主配置 fonts.xml; sync 为 true 时复制到各派生配置
// 优先从 backup/fonts.xml 读取纯净模板 (存在时), 保证 single/multi 往返切换幂等。
// 返回覆写/同步的文件总数
func ApplyToDir(xmlDir string, mode, min, max int, customMap map[int]int, sync bool) (int, error) {
src := filepath.Join(xmlDir, SourceXMLRel)
data, err := os.ReadFile(src)
currentData, err := os.ReadFile(src)
if err != nil {
return 0, fmt.Errorf("读取 %s 失败: %w", SourceXMLRel, err)
}
replaced := ApplyWghtMode(string(data), mode, min, max, customMap)
baseData := currentData
backupPath := filepath.Join(xmlDir, BackupXMLRel)
if b, err := os.ReadFile(backupPath); err == nil && len(b) > 0 {
baseData = b
}
slotMulti := ResolveMultiConfigs(xmlDir)
replaced := ApplyWghtAndMulti(string(baseData), mode, min, max, customMap, slotMulti)
changed := 0
if replaced != string(data) {
if replaced != string(currentData) {
if err := os.WriteFile(src, []byte(replaced), 0o644); err != nil {
return changed, fmt.Errorf("写入失败 %s: %w", SourceXMLRel, err)
}
+106
View File
@@ -273,3 +273,109 @@ func TestApplyToDirSyncMode0(t *testing.T) {
}
}
}
func TestNearestWeight(t *testing.T) {
avail := []int{300, 400, 500, 700}
cases := map[int]int{
100: 300,
200: 300,
300: 300,
400: 400,
500: 500,
600: 700, // 与 500/700 等距, >=400 偏向更重
700: 700,
800: 700,
900: 700,
1000: 700,
}
for target, want := range cases {
if got := NearestWeight(avail, target); got != want {
t.Errorf("NearestWeight(%v, %d) = %d, want %d", avail, target, got, want)
}
}
// 无 400 时, 300/500 等距下 400 取 500, 200/400 等距下 300 取 200
if got := NearestWeight([]int{300, 500}, 400); got != 500 {
t.Errorf("NearestWeight([300,500], 400) = %d, want 500", got)
}
if got := NearestWeight([]int{200, 400}, 300); got != 200 {
t.Errorf("NearestWeight([200,400], 300) = %d, want 200", got)
}
}
// 混合模式 + 缺失字重回退 + 繁体/英文回退简体 + 切回单字体还原 backup
func TestApplyToDirMultiAndMixedRoundtrip(t *testing.T) {
dir := t.TempDir()
mkfile := func(rel, content string) {
p := filepath.Join(dir, rel)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
pristine := "<?xml version=\"1.0\"?>\n<familyset version=\"23\">\n" +
" <family name=\"sans-serif\">\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"100\" />\n </font>\n" +
" <font weight=\"400\" style=\"normal\">SysFont-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"400\" />\n </font>\n" +
" <font weight=\"700\" style=\"normal\">SysFont-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"700\" />\n </font>\n" +
" </family>\n" +
" <family name=\"sys-sans-en\">\n" +
" <font weight=\"100\" style=\"normal\" postScriptName=\"OPlusSansEn\">SysSans-En-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n" +
" <font weight=\"1000\" style=\"normal\" postScriptName=\"OPlusSansEn\">SysSans-En-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"1000\"/>\n </font>\n" +
" </family>\n" +
" <family lang=\"zh-Hans\">\n" +
" <font weight=\"100\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n" +
" <font weight=\"400\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"400\"/>\n </font>\n" +
" <font weight=\"400\" style=\"normal\" fallbackFor=\"serif\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf</font>\n" +
" <font weight=\"700\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"700\"/>\n </font>\n" +
" <font weight=\"1000\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"1000\"/>\n </font>\n" +
" </family>\n" +
" <family lang=\"zh-Hant,zh-Bopo\">\n" +
" <font weight=\"400\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_TC\">SysSans-Hant-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"400\"/>\n </font>\n" +
" <font weight=\"700\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_TC\">SysSans-Hant-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"700\"/>\n </font>\n" +
" </family>\n" +
"</familyset>\n"
mkfile(SourceXMLRel, pristine)
mkfile(BackupXMLRel, pristine)
// 场景 1: 简体多字重 (400, 700), 繁体未设回退简体多字重, 英文单字体可变覆写 (mode=2, 200-700)
mkfile("FONTS/slot-modes.txt", "hans=multi\nhant=single\nen=single\n")
mkfile("FONTS/multi/hans/400.ttf", "r")
mkfile("FONTS/multi/hans/700.ttf", "b")
mkfile("FONTS/en.ttf", "en")
if _, err := ApplyToDir(dir, 2, 200, 700, nil, true); err != nil {
t.Fatalf("ApplyToDir mixed: %v", err)
}
gotBytes, err := os.ReadFile(filepath.Join(dir, SourceXMLRel))
if err != nil {
t.Fatal(err)
}
got := string(gotBytes)
// sans-serif 仍应走可变覆写 (200 -> 266)
if !strings.Contains(got, `<axis tag="wght" stylevalue="266" />`) {
t.Errorf("英文单字体可变覆写未生效:\n%s", got)
}
// zh-Hans 应使用静态多字重映射: 400 -> SysSans-Hans-Regular.ttf, 700/1000 -> FontMM-Hans-700.ttf, 不含 wght 轴
if !strings.Contains(got, `>SysSans-Hans-Regular.ttf</font>`) || !strings.Contains(got, `>FontMM-Hans-700.ttf</font>`) {
t.Errorf("简体多字重条目缺失:\n%s", got)
}
// 繁体未设置 hant.ttf, 应回退指向 hans 的多字重文件
if strings.Contains(got, `SysSans-Hant-Regular.ttf`) {
t.Errorf("繁体未设置时应回退简体多字重文件:\n%s", got)
}
// 场景 2: 全部切回单字体且 wght mode=0, 应从 backup/fonts.xml 完整还原
mkfile("FONTS/slot-modes.txt", "hans=single\nhant=single\nen=single\n")
if _, err := ApplyToDir(dir, 0, 100, 900, nil, true); err != nil {
t.Fatalf("ApplyToDir reset: %v", err)
}
restored, err := os.ReadFile(filepath.Join(dir, SourceXMLRel))
if err != nil {
t.Fatal(err)
}
if string(restored) != pristine {
t.Errorf("切回 single mode=0 后未能完整还原纯净 XML:\n%s", string(restored))
}
}