fix(metrics): 去掉度量载体, 只保留字体行距统一 (issue #17)

实测定位: 删掉 fonts.xml 里那段度量载体引用就能正常开机, 保留槽位字体 (同样被改了度量
与包围盒) 也能开机 —— 即问题出在那个合成载体字体本身, 而「统一字体行距度量」这条路是
安全的。载体只影响 paint 度量那一侧, 对行距贡献次要, 因此整个移除:

- 删除 src/system/fonts/FontMM-Metrics.ttf 与其许可文本
- fontmm-wght: 移除 -metrics 开关与载体条目插入/移除逻辑 (ApplyMetrics/ResolveMetrics
  等), ApplyToDir 回到原签名; 相应单测删除
- fontmm-subset: 移除用来挖空载体的 -metrics 模式 (保留 -line-metrics)
- apply.sh: 只做「按开关与档位统一装入字体的行距 + 收紧包围盒」, 不再插任何字体条目;
  也不再调用 fontmm-wght 做同步 (字重覆写由 WebUI 直接调用, 该调用已冗余)
- ci.mjs: 载体相关校验改为「开关与档位文件一致 (apply.sh / WebUI)」
- 文档同步, 并把这次的坑写进 DEVELOPMENT (合成度量载体在设备上会导致开机失败)

保留并新增的安全措施:
- -line-metrics 改写后回读自检 (harfbuzz 重新解析 + 度量比对), 不通过就拒绝写出、保留原字体
- 逃生开关: FONTS/.no-tighten-ink 存在时只统一度量、不动包围盒 (便于实机二分)

端到端实测 (你的 Sarasa 字体 + Noto CJK 集合): 装入后 hhea=1161/-289 (1.45 em)、
head 包围盒由 y[-1048,1808] 收紧到 y[-289,1161], 段落上下空白归零; fonts.xml 中已无
任何载体引用。
This commit is contained in:
YuleBest committed 2026-09-16 18:47:03 +08:00
1 parent 43b6a62fd7
commit 309cba2d29
13 files changed
+112 -553

No files matched your search

+2 -4
View File
@@ -1,7 +1,7 @@
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围与行距字距载体
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>]
//
// [-metrics on|off|auto] [-xml-dir <模块根>] [-sync]
// [-xml-dir <模块根>] [-sync]
//
// 说明: 只修改主配置 system/etc/fonts.xml, 加 -sync 后复制到各派生配置 (issue #7)
package main
@@ -21,7 +21,6 @@ func main() {
mapPath := flag.String("map", "", "自定义映射文件 (mode 3): 每行 'weight axis'")
xmlDir := flag.String("xml-dir", "/data/adb/modules/FontMM", "模块根目录 (含 system/etc/fonts.xml)")
sync := flag.Bool("sync", false, "覆写后复制 fonts.xml 到各派生配置")
metrics := flag.String("metrics", "auto", "固定行距字距 (issue #17): on|off|auto (auto 读 FONTS/metrics.txt)")
flag.Parse()
var customMap map[int]int
@@ -37,8 +36,7 @@ func main() {
}
}
enabled := wght.ResolveMetrics(*xmlDir, *metrics)
changed, err := wght.ApplyToDir(*xmlDir, *mode, *min, *max, customMap, *sync, enabled)
changed, err := wght.ApplyToDir(*xmlDir, *mode, *min, *max, customMap, *sync)
if err != nil {
fmt.Printf("[x] %v\n", err)
os.Exit(1)
+2 -108
View File
@@ -45,105 +45,6 @@ var FamilySpecs = []familySpec{
// 主配置文件名 (唯一源)
const SourceXMLRel = "system/etc/fonts.xml"
// MetricsFontFile 度量载体文件名 (issue #17): 由 apply.sh 把系统自带的现成字体
// 挖空后写到 system/fonts/ 下 —— 只留度量与空格字形, 作为家族首个条目充当
// base 字体, 把行距/字距钉在标准值上。
const MetricsFontFile = "FontMM-Metrics.ttf"
// 载体条目的标记注释: 插入与移除都以它为锚点, 保证可重复执行
const (
metricsMarkerStart = "<!-- FontMM-Metrics start: 固定行距字距的度量载体 (issue #17) -->"
metricsMarkerEnd = "<!-- FontMM-Metrics end -->"
)
// metricsEntryIndent 与家族内其他 <font> 条目一致的缩进
const metricsEntryIndent = " "
// metricsBlock 生成载体条目块 (全 9 档字重)。
// 覆盖所有字重是必需的: Android 取家族里与请求字重最接近的条目作为 base 字体
// (Minikin baseFontFaked), 只放 400 档的话粗体等字重仍会落到用户字体上。
func metricsBlock() string {
lines := []string{metricsEntryIndent + metricsMarkerStart}
for _, w := range Weights {
lines = append(lines, fmt.Sprintf("%s<font weight=\"%d\" style=\"normal\">%s</font>", metricsEntryIndent, w, MetricsFontFile))
}
lines = append(lines, metricsEntryIndent+metricsMarkerEnd)
return strings.Join(lines, "\n") + "\n"
}
// ApplyMetrics 开启时在每个生效家族首位插入载体条目, 关闭时移除 (均幂等)。
// 先移除再插入, 因此同一输入重复调用结果一致; 关闭时能还原到原 XML。
func ApplyMetrics(xml string, enabled bool) string {
out := removeMetricsBlock(xml)
if !enabled {
return out
}
for _, spec := range FamilySpecs {
out = insertMetricsBlock(out, spec)
}
return out
}
// 移除载体条目块 (含标记行与整行换行); 无标记时原样返回
func removeMetricsBlock(xml string) string {
for {
start := strings.Index(xml, metricsMarkerStart)
if start < 0 {
return xml
}
// 连同该行行首缩进一起删除
lineStart := start
for lineStart > 0 && xml[lineStart-1] != '\n' {
lineStart--
}
end := strings.Index(xml[start:], metricsMarkerEnd)
if end < 0 {
return xml // 标记不完整: 不动它, 避免误删
}
end += start + len(metricsMarkerEnd)
// 吃掉标记行尾的换行
if end < len(xml) && xml[end] == '\n' {
end++
}
xml = xml[:lineStart] + xml[end:]
}
}
// 在家族起始标签行之后插入载体条目块; 家族不存在时原样返回
func insertMetricsBlock(xml string, spec familySpec) string {
start := findFamilyStart(xml, spec.openTag)
if start < 0 {
return xml
}
openEnd := strings.IndexByte(xml[start:], '>')
if openEnd < 0 {
return xml
}
openEnd += start + 1
// 插入点: 家族标签所在行的行尾之后
insertAt := openEnd
if nl := strings.IndexByte(xml[insertAt:], '\n'); nl >= 0 {
insertAt += nl + 1
}
return xml[:insertAt] + metricsBlock() + xml[insertAt:]
}
// ResolveMetrics 解析 -metrics 取值: "on"/"off"/"auto" (auto 读 FONTS/metrics.txt,
// 内容为 "1" 视为开启)。默认 auto, 让 WebUI 与刷入脚本只维护一个开关文件。
func ResolveMetrics(xmlDir, mode string) bool {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "on":
return true
case "off", "":
return false
}
data, err := os.ReadFile(filepath.Join(xmlDir, "FONTS", "metrics.txt"))
if err != nil {
return false
}
return strings.TrimSpace(string(data)) == "1"
}
// 派生配置 (与 fonts.xml 内容一致, 由 -sync 复制生成)
var DerivedXMLRel = []string{
"system/etc/fonts_base.xml",
@@ -383,20 +284,13 @@ func ReadCustomMap(path string) (map[int]int, error) {
// ApplyToDir 覆写模块根目录下的主配置 fonts.xml; sync 为 true 时复制到各派生配置
// 返回覆写/同步的文件总数
func ApplyToDir(xmlDir string, mode, min, max int, customMap map[int]int, sync bool, metrics bool) (int, error) {
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)
if err != nil {
return 0, fmt.Errorf("读取 %s 失败: %w", SourceXMLRel, err)
}
// 载体文件不存在就不插入条目: 否则 fonts.xml 会引用一个缺失的字体
if metrics {
if _, err := os.Stat(filepath.Join(xmlDir, "system", "fonts", MetricsFontFile)); err != nil {
fmt.Printf("[-] 未找到度量载体 %s, 跳过固定行距字距\n", MetricsFontFile)
metrics = false
}
}
replaced := ApplyMetrics(ApplyWghtMode(string(data), mode, min, max, customMap), metrics)
replaced := ApplyWghtMode(string(data), mode, min, max, customMap)
changed := 0
if replaced != string(data) {
if err := os.WriteFile(src, []byte(replaced), 0o644); err != nil {
+2 -176
View File
@@ -220,7 +220,7 @@ func TestApplyToDirSync(t *testing.T) {
mkfile(rel, "<familyset>\n</familyset>\n")
}
changed, err := ApplyToDir(dir, 2, 150, 700, nil, true, false)
changed, err := ApplyToDir(dir, 2, 150, 700, nil, true)
if err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
@@ -256,7 +256,7 @@ func TestApplyToDirSyncMode0(t *testing.T) {
if err := os.WriteFile(dir+"/"+SourceXMLRel, []byte(base), 0o644); err != nil {
t.Fatal(err)
}
changed, err := ApplyToDir(dir, 0, 100, 900, nil, true, false)
changed, err := ApplyToDir(dir, 0, 100, 900, nil, true)
if err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
@@ -273,177 +273,3 @@ func TestApplyToDirSyncMode0(t *testing.T) {
}
}
}
// ---------- 固定行距字距的度量载体 (issue #17) ----------
// 四个生效家族各带一个条目, 用于验证载体插入位置与数量
const metricsSampleXML = `<familyset version="23">
<family name="sans-serif">
<font weight="400" style="normal">SysFont-Regular.ttf
<axis tag="wght" stylevalue="400" />
</font>
</family>
<family name="sys-sans-en">
<font weight="400" style="normal" postScriptName="OPlusSansEn" >SysSans-En-Regular.ttf
<axis tag="wght" stylevalue="400"/>
</font>
</family>
<family lang="zh-Hans">
<font weight="400" style="normal" fallbackFor="serif"
postScriptName="OPPO_Sans_4.0_SC">SysSans-Hans-Regular.ttf
</font>
</family>
<family lang="zh-Hant,zh-Bopo">
<font weight="400" style="normal">SysSans-Hant-Regular.ttf
</font>
</family>
</familyset>
`
// 开启: 每个家族首位都有全 9 档字重的载体条目, 且排在原条目之前
func TestApplyMetricsInsert(t *testing.T) {
on := ApplyMetrics(metricsSampleXML, true)
if got := strings.Count(on, MetricsFontFile); got != 9*len(FamilySpecs) {
t.Fatalf("载体条目数 = %d, want %d", got, 9*len(FamilySpecs))
}
// 逐个家族检查: 载体必须出现在家族内第一个原条目之前
for _, spec := range FamilySpecs {
famStart := strings.Index(on, spec.openTag)
if famStart < 0 {
t.Fatalf("找不到家族 %s", spec.openTag)
}
famEnd := strings.Index(on[famStart:], "</family>")
block := on[famStart : famStart+famEnd]
firstCarrier := strings.Index(block, MetricsFontFile)
firstOriginal := strings.Index(block, spec.fontFile)
if firstCarrier < 0 || firstOriginal < 0 || firstCarrier > firstOriginal {
t.Errorf("%s: 载体未排在家族首位 (carrier=%d original=%d)", spec.openTag, firstCarrier, firstOriginal)
}
for _, w := range Weights {
if !strings.Contains(block, fmt.Sprintf(`<font weight="%d" style="normal">%s</font>`, w, MetricsFontFile)) {
t.Errorf("%s: 缺少字重 %d 的载体条目", spec.openTag, w)
}
}
}
// 结构完整性
if open, closeN := strings.Count(on, "<family "), strings.Count(on, "</family>"); open != closeN {
t.Errorf("family 标签不平衡: open=%d close=%d", open, closeN)
}
}
// 关闭: 恢复到与原始 XML 逐字节一致 (先移除再插入, 不留残余)
func TestApplyMetricsRemoveRestores(t *testing.T) {
on := ApplyMetrics(metricsSampleXML, true)
off := ApplyMetrics(on, false)
if off != metricsSampleXML {
t.Errorf("关闭后未还原原 XML:\n%s", off)
}
}
// 幂等: 重复开启结果一致; 原 XML 无标记时关闭也不改动
func TestApplyMetricsIdempotent(t *testing.T) {
once := ApplyMetrics(metricsSampleXML, true)
twice := ApplyMetrics(once, true)
if once != twice {
t.Errorf("重复开启结果不一致")
}
if off := ApplyMetrics(metricsSampleXML, false); off != metricsSampleXML {
t.Errorf("未开启过的 XML 在关闭时被改动")
}
}
// 家族缺失时不应报错, 也不应改动其余内容
func TestApplyMetricsMissingFamily(t *testing.T) {
xml := "<familyset>\n <family name=\"serif\">\n </family>\n</familyset>\n"
if got := ApplyMetrics(xml, true); got != xml {
t.Errorf("无生效家族时被改动:\n%s", got)
}
}
// 与字重覆写叠加: 两者互不破坏
func TestApplyMetricsWithWghtMode(t *testing.T) {
wghtDone := ApplyWghtMode(metricsSampleXML, 1, 300, 700, nil)
both := ApplyMetrics(wghtDone, true)
if !strings.Contains(both, MetricsFontFile) {
t.Fatal("叠加后丢失载体条目")
}
// 关闭载体后应回到字重覆写的结果
if got := ApplyMetrics(both, false); got != wghtDone {
t.Errorf("关闭载体后未回到字重覆写结果:\n%s", got)
}
}
// -metrics auto: 读 FONTS/metrics.txt, 内容为 "1" 才开启
func TestResolveMetrics(t *testing.T) {
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "FONTS"), 0o755); err != nil {
t.Fatal(err)
}
cases := []struct {
mode, file string
want bool
}{
{"on", "", true},
{"off", "1", false},
{"auto", "", false}, // 文件不存在
{"auto", "0", false}, // 显式关闭
{"auto", "1", true}, // 开启
{"auto", "1\n", true}, // 容忍行尾换行
}
for _, c := range cases {
p := filepath.Join(dir, "FONTS", "metrics.txt")
if c.file == "" {
_ = os.Remove(p)
} else if err := os.WriteFile(p, []byte(c.file), 0o644); err != nil {
t.Fatal(err)
}
if got := ResolveMetrics(dir, c.mode); got != c.want {
t.Errorf("ResolveMetrics(mode=%q, file=%q) = %v, want %v", c.mode, c.file, got, c.want)
}
}
}
// 载体文件缺失时不插入条目 (避免 fonts.xml 引用不存在的字体)
func TestApplyToDirMetricsWithoutFile(t *testing.T) {
dir := t.TempDir()
if err := os.MkdirAll(dir+"/system/etc", 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dir+"/"+SourceXMLRel, []byte(metricsSampleXML), 0o644); err != nil {
t.Fatal(err)
}
if _, err := ApplyToDir(dir, 0, 100, 900, nil, false, true); err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
data, err := os.ReadFile(dir + "/" + SourceXMLRel)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), MetricsFontFile) {
t.Error("载体文件缺失时仍写入了条目")
}
}
// 载体文件存在时写入条目
func TestApplyToDirMetricsWithFile(t *testing.T) {
dir := t.TempDir()
if err := os.MkdirAll(dir+"/system/fonts", 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dir+"/system/etc", 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dir+"/system/fonts/"+MetricsFontFile, []byte("stub"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dir+"/"+SourceXMLRel, []byte(metricsSampleXML), 0o644); err != nil {
t.Fatal(err)
}
if _, err := ApplyToDir(dir, 0, 100, 900, nil, false, true); err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
data, _ := os.ReadFile(dir + "/" + SourceXMLRel)
if !strings.Contains(string(data), MetricsFontFile) {
t.Error("载体文件存在时未写入条目")
}
}