mirror of
https://github.com/YuleBest/FontMM.git
synced 2026-12-04 03:11:48 +08:00
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:
1 parent
43b6a62fd7
commit
309cba2d29
13 files changed
+112
-553
No files matched your search
+28
-42
@@ -201,35 +201,33 @@ src/tools/fontmm-subset -check src/FONTS/hans.ttf # 应返回 cjk=<非0> /
|
||||
里 `lineAscent = min(paint.getFontMetrics().ascent, 该行字体的 ascent)`(descent 取 max),
|
||||
其中 paint 度量取自 typeface 家族里与请求字重最接近的条目(hwui
|
||||
`Paint::getMetricsInternal` → Minikin `FontCollection::baseFontFaked`)。并集**只能抬高、
|
||||
不能压低**,所以只要装入字体的行距各不相同,换字体行距就会变;只在家族首位放一个度量载体,
|
||||
也压不住比它更高的字体(第一版就是这么失败的)。
|
||||
不能压低**,因此只要装入字体的行距各不相同,换字体行距就会变。
|
||||
|
||||
**做法**(两件事一起做才真的固定住):
|
||||
另外「一段文字上下那圈留白」与行距无关:它来自 `includeFontPadding`(默认开启),
|
||||
`StaticLayout` 里 `mTopPadding = above - top`、`mBottomPadding = bottom - below`,而
|
||||
`top`/`bottom` 是 Skia 的 `SkFontMetrics.fTop/fBottom`,**取自 `head` 表的包围盒**。
|
||||
字体包围盒被极少数大字形撑大时(实测某 Sarasa 变体:hhea 1.45 em 而包围盒 2.86 em),
|
||||
每段会多出约 1.4 em 的空白。
|
||||
|
||||
1. **统一装入字体的行距度量**(关键):`fontmm-subset -line-metrics` 把 `apply.sh` 装入
|
||||
`system/fonts` 的字体(8 个槽位目标 + `DroidSansMono.ttf` + `NotoColorEmoji.ttf`)的
|
||||
`hhea` / `OS/2` 行距**按比例**缩放到同一总量,`lineGap` 归零、上下比例保持不变(避免基线
|
||||
跳变与文字重叠)。只改度量字段,字形、`hmtx`、布局表原样保留,表长度不变所以无需重排文件;
|
||||
只有 `hhea` / `OS/2` 的表校验和与 `head.checkSumAdjustment` 需要重算。
|
||||
`FONTS/` 里的原始字体不动,改写只作用于装入的那一份。
|
||||
**同时收紧 `head` 包围盒**:段落上下的空白不是行距,而是
|
||||
`includeFontPadding`(默认开启)用 `mTopPadding = above - top`、`mBottomPadding =
|
||||
bottom - below` 撑出来的,其中 `top`/`bottom` 是 Skia 的 `SkFontMetrics.fTop/fBottom`,
|
||||
取自 **`head` 表的包围盒**(不是 `hhea`)。字体包围盒被极少数大字形撑大时(实测某个
|
||||
Sarasa 变体:hhea 1.45 em 而包围盒 2.86 em),每段会多出约 1.4 em 的空白 —— 这正是
|
||||
「段高离谱」的来源。因此改写时把包围盒**只收紧、不放大**到行距盒(`yMax ≤ ascent`、
|
||||
`yMin ≥ descender`),正常字体不受影响。
|
||||
**字体集合(`.ttc` / `.otc`)同样支持**:逐个 face 处理,并按表偏移去重(集合里多个 face
|
||||
常共享同一份 `hhea`/`OS/2`,重复改写会把已缩放的度量再缩一次);`checkSumAdjustment`
|
||||
先把所有 head 的该字段归零、对全文件求和一次,再写回同一个值;`head` 的目录校验和按
|
||||
`checkSumAdjustment` 归零计算(与该表本身的约定一致)。
|
||||
应用日志会逐字体回显旧/新度量与包围盒,便于核对(不同 upem 数值不同,看 em 占比是否一致)。
|
||||
2. **度量载体**:`src/system/fonts/FontMM-Metrics.ttf`(16KB,由 Roboto Flex 挖空而来,只有
|
||||
度量与空格字形)插到各家族首位,让 paint 度量那一侧也一致。9 档字重全覆盖 —— 家族匹配是
|
||||
「取与请求字重最接近的条目」,只放 400 档的话粗体等仍会落到用户字体上。
|
||||
**做法**:`apply.sh` 在开关打开时,对装入 `system/fonts` 的字体(8 个槽位目标 +
|
||||
`DroidSansMono.ttf` + `NotoColorEmoji.ttf`)调用 `fontmm-subset -line-metrics`:
|
||||
|
||||
1. 把 `hhea` / `OS/2`(typo 与 win)行距**按比例**缩放到同一总量,`lineGap` 归零、
|
||||
上下比例保持不变(避免基线跳变与文字重叠)。
|
||||
2. 把 `head` 包围盒**只收紧、不放大**到行距盒(`yMax ≤ 上升部`、`yMin ≥ 下降部`),
|
||||
收掉段落上下那圈空白;包围盒本来就正常的字体不受影响。
|
||||
|
||||
只改这些字段,字形 / `hmtx` / 布局表原样保留,表长度不变;`hhea` / `OS/2` / `head` 的
|
||||
表校验和与 `head.checkSumAdjustment` 重算。`FONTS/` 里的原始字体不动。改写后会**回读自检**
|
||||
(harfbuzz 重新解析 + 度量比对),不通过就拒绝写出、保留原字体,避免坏字体进入 system/fonts。
|
||||
|
||||
**字体集合(`.ttc` / `.otc`)同样支持**:逐个 face 处理并按表偏移去重(集合里多个 face 常
|
||||
共享同一份 `hhea`/`OS/2`,重复改写会把已缩放的度量再缩一次);`checkSumAdjustment` 先把所有
|
||||
head 的该字段归零、对全文件求和一次再写回同一个值;`head` 的目录校验和按 `checkSumAdjustment`
|
||||
归零计算(与该表自身约定一致)。
|
||||
|
||||
档位(行距总量,千分比 em)由 WebUI 选,写在 `FONTS/line-height.txt`:紧凑 `1200` /
|
||||
标准 `1450` / 宽松 `1600`,缺省 1450。设备端工具用法:
|
||||
标准 `1450` / 宽松 `1600`,缺省 1450;开关在 `FONTS/metrics.txt`。设备端用法:
|
||||
|
||||
```bash
|
||||
fontmm-subset -line-metrics -in <font.ttf> -out <out.ttf> -line-total <permille>
|
||||
@@ -237,23 +235,11 @@ fontmm-subset -line-metrics -in <font.ttf> -out <out.ttf> -line-total <permille>
|
||||
# 包围盒被收紧时追加: ink_y=-1048/1808
|
||||
```
|
||||
|
||||
**载体来源与重新生成**(换度量来源只需换 `-in` 的文件):
|
||||
**调试/二分**:在 `FONTS/` 放一个空文件 `.no-tighten-ink`,就只统一度量、不动包围盒。
|
||||
|
||||
```bash
|
||||
curl -Lo /tmp/RobotoFlex.ttf 'https://github.com/google/fonts/raw/main/ofl/robotoflex/RobotoFlex%5BGRAD,XOPQ,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght%5D.ttf'
|
||||
g++ -O1 -std=c++17 -DHB_NO_MT -I dev/.cache/harfbuzz/harfbuzz-*/src \
|
||||
dev/.cache/harfbuzz/harfbuzz-*/src/harfbuzz-subset.cc \
|
||||
native/src/subset/fontmm-subset.cc -o /tmp/fontmm-subset-host
|
||||
/tmp/fontmm-subset-host -metrics -in /tmp/RobotoFlex.ttf -out src/system/fonts/FontMM-Metrics.ttf
|
||||
```
|
||||
|
||||
Roboto Flex 为 OFL-1.1 且无保留字体名,许可文本见 `src/system/fonts/LICENSE-OFL-RobotoFlex`。
|
||||
|
||||
**分工**:`apply.sh` 读 `FONTS/metrics.txt`(开关)与 `FONTS/line-height.txt`(档位)→
|
||||
统一各字体与载体的行距 → 调 `fontmm-wght -mode 0 -metrics on|off -sync` 插入/移除载体条目
|
||||
(`auto` 表示由工具自己读开关文件)。载体缺失时不插入条目,避免 `fonts.xml` 引用缺失字体;
|
||||
关闭是幂等的,能把 XML 逐字节还原(Go 单测覆盖)。`dev/ci.mjs` 校验载体文件名在 `apply.sh`
|
||||
与 Go 两侧一致、载体确实随仓库提供、档位缺省值与 WebUI 常量一致。
|
||||
**踩过的坑(勿重蹈)**:早先的实现是「挖空一个现成字体做度量载体,插到各家族首位」——
|
||||
实测这种合成字体在设备上会让**开机失败**(引用它的 fonts.xml 一恢复即可开机)。载体只影响
|
||||
paint 度量那一侧、对行距贡献次要,因此该方案已整个移除。
|
||||
|
||||
**已知限制**:
|
||||
|
||||
@@ -261,7 +247,7 @@ Roboto Flex 为 OFL-1.1 且无保留字体名,许可文本见 `src/system/font
|
||||
Braille 等)**有意不统一**:用户所选字体通常已覆盖日常用字,为极少数生僻字每次应用
|
||||
多改写 100MB+ 文件不划算;且它们字形本来就高(Tibetan 约 2.8 em、SatisarSharada
|
||||
约 4.2 em),强行压低会叠行。含这些字形的行仍会比标准行更高。
|
||||
- DenyList 应用里载体不会被预加载,行距退回字体自身(字体已被统一,因此仍是同一档)。
|
||||
- DenyList 应用里字体不会被预热,但字体本身已被统一,行距仍是同一档。
|
||||
|
||||
## 可复现构建
|
||||
|
||||
|
||||
@@ -91,11 +91,7 @@
|
||||
|
||||
安卓的行高由「字体家族里与请求字重最接近的那个字体」与「每行实际用到的字体」共同决定,而且**只能抬高不能压低** —— 本模块的配置里排在 `sans-serif` 最前面的正是「英文 & 数字」槽位,所以换英文字体时,中文行距也会跟着变。
|
||||
|
||||
开启后模块会做两件事,让行距只由你选的档位决定,不再随字体变化:
|
||||
|
||||
- 把装入系统的字体(中英日韩等槽位字体、等宽、Emoji)的行距度量**按比例统一**到同一档位(字体上下的比例保持不变,字形完全不动;`FONTS/` 里的原始字体不动)
|
||||
- 同时收紧字体的「包围盒」——它决定段落**上下那圈空白**的大小。有些字体这个值虚高,会让每段多出一大圈留白,一并收掉
|
||||
- 额外把一个只含度量、没有文字字形的内置载体放到各家族最前面,让系统读取的那一侧也一致
|
||||
开启后,模块会在应用字体时把装入系统的字体(中英日韩等槽位字体、等宽、Emoji)**行距统一**到你选的档位,并顺手收掉虚高的「上下留白」(有些字体这个值离谱,会让每段多出一大圈空白)。字形完全不动,`FONTS/` 里的原始字体也不动。
|
||||
|
||||
档位(按字身框倍数):
|
||||
|
||||
|
||||
+15
-32
@@ -196,50 +196,33 @@ await check('Zygisk 预热字体清单与 apply.sh 一致', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
// 固定行距字距 (issue #17): apply.sh 生成载体、Go 工具插入条目, 两边靠文件名耦合。
|
||||
// 名字一旦漂移, fonts.xml 就会引用一个不存在的字体, 表现为功能静默失效。
|
||||
await check('度量载体与开关文件名一致 (apply.sh / Go / WebUI)', async () => {
|
||||
// 固定行距 (issue #17): 开关与档位由 WebUI 写、apply.sh 读, 文件名/取值必须一致。
|
||||
// (早先版本还有一个「度量载体」字体插到 fonts.xml, 因设备上会导致开机失败已移除)
|
||||
await check('行距开关与档位一致 (apply.sh / WebUI)', async () => {
|
||||
const applySh = await fsp.readFile(path.join(SRC_DIR, 'apply.sh'), 'utf8');
|
||||
const go = await fsp.readFile(path.join(ROOT, 'golang', 'internal', 'wght', 'wght.go'), 'utf8');
|
||||
const metricsTs = await fsp.readFile(path.join(WEB_DIR, 'src', 'metrics.ts'), 'utf8');
|
||||
|
||||
const carrier = applySh.match(/METRICS_CARRIER="\$SYS_FONT_DIR\/([A-Za-z0-9_.-]+)"/);
|
||||
if (!carrier) throw new Error('apply.sh 中未找到 METRICS_CARRIER 定义');
|
||||
const goCarrier = go.match(/MetricsFontFile\s*=\s*"([A-Za-z0-9_.-]+)"/);
|
||||
if (!goCarrier) throw new Error('wght.go 中未找到 MetricsFontFile 常量');
|
||||
if (carrier[1] !== goCarrier[1]) {
|
||||
throw new Error(`载体文件名不一致: apply.sh=${carrier[1]}, Go=${goCarrier[1]}`);
|
||||
const shSwitch = /\$\{?FONTS_DIR\}?\/metrics\.txt/.test(applySh);
|
||||
const webSwitch = /FONTS_DIR\}\/metrics\.txt/.test(metricsTs);
|
||||
if (!shSwitch || !webSwitch) {
|
||||
throw new Error(`开关文件名不一致 (apply.sh=${shSwitch}, WebUI=${webSwitch})`);
|
||||
}
|
||||
|
||||
// 载体随模块打包, 缺失时开关会静默失效
|
||||
const carrierFile = path.join(SRC_DIR, 'system', 'fonts', carrier[1]);
|
||||
try {
|
||||
const { size } = await fsp.stat(carrierFile);
|
||||
if (size === 0) throw new Error('文件为空');
|
||||
} catch (e) {
|
||||
throw new Error(`缺少度量载体 ${path.relative(ROOT, carrierFile)} (${e.message})`);
|
||||
const shLevel = /\$\{?FONTS_DIR\}?\/line-height\.txt/.test(applySh);
|
||||
const webLevel = /FONTS_DIR\}\/line-height\.txt/.test(metricsTs);
|
||||
if (!shLevel || !webLevel) {
|
||||
throw new Error(`档位文件名不一致 (apply.sh=${shLevel}, WebUI=${webLevel})`);
|
||||
}
|
||||
|
||||
// 占位字体脚本会把列表内的文件清空, 载体不能被卷进去
|
||||
const emptyFont = await fsp.readFile(path.join(ROOT, 'dev', 'empty-font.mjs'), 'utf8');
|
||||
if (emptyFont.includes(carrier[1])) {
|
||||
throw new Error(`dev/empty-font.mjs 的占位列表包含度量载体 ${carrier[1]}, 会被清空`);
|
||||
}
|
||||
|
||||
// 开关文件名: apply.sh 与 Go 读、WebUI 写, 三处必须同名
|
||||
const sh = /\$\{?FONTS_DIR\}?\/metrics\.txt/.test(applySh);
|
||||
const golang = /"FONTS", "metrics\.txt"/.test(go);
|
||||
const web = /FONTS_DIR\}\/metrics\.txt/.test(metricsTs);
|
||||
if (!sh || !golang || !web) {
|
||||
throw new Error(`开关文件名不一致 (apply.sh=${sh}, Go=${golang}, WebUI=${web})`);
|
||||
}
|
||||
|
||||
// 行距档位: WebUI 的常量必须包含 apply.sh 的缺省值, 否则界面显示与刷入结果会不一致
|
||||
// 档位缺省值: WebUI 的常量必须包含 apply.sh 的缺省值, 否则界面显示与刷入结果不一致
|
||||
const shDefault = applySh.match(/METRICS_TOTAL=(\d+)/);
|
||||
if (!shDefault) throw new Error('apply.sh 中未找到行距档位缺省值');
|
||||
if (!metricsTs.includes(shDefault[1])) {
|
||||
throw new Error(`WebUI 未定义 apply.sh 的缺省档位 ${shDefault[1]}`);
|
||||
}
|
||||
|
||||
// 字体行距统一只作用于 apply.sh 安装的字体, 清单不能卷进占位/系统字体之外的名字
|
||||
if (!/^MANAGED_FONTS='/m.test(applySh)) throw new Error('apply.sh 中未找到 MANAGED_FONTS 清单');
|
||||
});
|
||||
|
||||
// 前端脚本引用的 dev 入口必须存在 (避免重命名后 package.json 指向不存在的文件)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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("载体文件存在时未写入条目")
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,6 @@
|
||||
// 生成子集。默认保留拉丁/希腊/西里尔与常用符号;
|
||||
// -minimal 仅保留 ASCII/西欧 (体积更小, 但希腊/西里尔会缺字);
|
||||
// -keep-cjk 额外保留 CJK 区块 (默认不保留)。
|
||||
// fontmm-subset -metrics -in <font.ttf> -out <carrier.ttf>
|
||||
// 把现成字体挖空: 只留度量与各类空格字形, 用作固定行距/字距的载体 (issue #17)。
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -114,21 +112,6 @@ static unsigned countCoverage(hb_face_t *face, const Range (&ranges)[N]) {
|
||||
return total;
|
||||
}
|
||||
|
||||
// 度量载体模式 (-metrics, issue #17) 保留的码点: 仅各类空格。
|
||||
//
|
||||
// 目的不是裁文字, 而是把一份现成字体「内部挖空」: 只留 .notdef 与空格字形,
|
||||
// 行距与空格字宽等度量 (hhea / OS/2 / hmtx) 原样保留, 得到一个没有文字字形、
|
||||
// 却能提供标准行字距的度量载体, 作为 fonts.xml 家族首个条目充当 base 字体
|
||||
// (Android 的 paint 度量取自家族里与请求字重最接近的条目)。
|
||||
//
|
||||
// 为什么连空格也保留: 这是该字体唯一能影响「字距」的地方 —— 文字仍由用户
|
||||
// 选择的字体渲染, 只有空格宽度被钉在这份标准上。
|
||||
static const hb_codepoint_t kMetricsSpaceCodes[] = {
|
||||
0x0020, // 空格
|
||||
0x00A0, // 不换行空格
|
||||
0x3000, // 全角空格
|
||||
};
|
||||
|
||||
// ---------- 行距度量改写 (-line-metrics, issue #17) ----------
|
||||
//
|
||||
// 为什么必须改字体本身: Android 的行高是「paint 度量」与「该行实际使用字体度量」的
|
||||
@@ -239,8 +222,9 @@ static unsigned unitsPerEm(const unsigned char *data, size_t size) {
|
||||
// 把行距总量缩放到 targetTotal (字体单位), 上下比例保持; 返回是否改动。
|
||||
// 支持字体集合 (.ttc/.otc): 逐个 face 处理, 按表偏移去重 —— 集合里多个 face 常共享
|
||||
// 同一份 hhea/OS/2, 重复改写会把已经缩放的度量再缩放一次。
|
||||
static bool scaleLineMetrics(std::vector<unsigned char> &buf, unsigned targetTotal, int &oldAsc,
|
||||
int &oldDesc, int &newAsc, int &newDesc, int &oldYMin, int &oldYMax) {
|
||||
static bool scaleLineMetrics(std::vector<unsigned char> &buf, unsigned targetTotal, bool tightenInk,
|
||||
int &oldAsc, int &oldDesc, int &newAsc, int &newDesc, int &oldYMin,
|
||||
int &oldYMax) {
|
||||
unsigned char *data = buf.data();
|
||||
size_t size = buf.size();
|
||||
|
||||
@@ -307,7 +291,7 @@ static bool scaleLineMetrics(std::vector<unsigned char> &buf, unsigned targetTot
|
||||
// SkFontMetrics.fTop/fBottom, 而那两个值取自 head 的包围盒)。字体包围盒虚高时
|
||||
// (某些字体被极少数大字形撑大), 段落就会多出一大圈空白 —— 只收紧、不放大,
|
||||
// 避免把正常字体的包围盒撑得比实际墨迹还大。
|
||||
if (head.found && head.length >= 44 && !seen(patched, head.offset)) {
|
||||
if (tightenInk && head.found && head.length >= 44 && !seen(patched, head.offset)) {
|
||||
const int yMin = rdI16(data, head.offset + 38);
|
||||
const int yMax = rdI16(data, head.offset + 42);
|
||||
if (oldYMax == 0 && oldYMin == 0) {
|
||||
@@ -392,11 +376,9 @@ static void usage(const char *argv0) {
|
||||
" %s -in <font.ttf> -out <out.ttf> 生成英文子集\n"
|
||||
" [-minimal] 仅保留 ASCII/西欧 (默认含希腊/西里尔)\n"
|
||||
" [-keep-cjk] 额外保留 CJK 区块 (默认不保留)\n"
|
||||
" %s -metrics -in <font.ttf> -out <out.ttf>\n"
|
||||
" 挖空: 只留度量与空格, 用作行距字距载体\n"
|
||||
" %s -line-metrics -in <font.ttf> -out <out.ttf> -line-total <permille>\n"
|
||||
" 把行距度量缩放到统一总量 (千分比 em)\n",
|
||||
argv0, argv0, argv0, argv0);
|
||||
argv0, argv0, argv0);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
@@ -405,8 +387,8 @@ int main(int argc, char **argv) {
|
||||
const char *outPath = nullptr;
|
||||
bool keepCjk = false;
|
||||
bool minimal = false;
|
||||
bool metricsMode = false;
|
||||
bool lineMetricsMode = false;
|
||||
bool tightenInk = true;
|
||||
int lineTotal = 0;
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
@@ -422,10 +404,10 @@ int main(int argc, char **argv) {
|
||||
keepCjk = true;
|
||||
} else if (strcmp(argv[i], "-minimal") == 0) {
|
||||
minimal = true;
|
||||
} else if (strcmp(argv[i], "-metrics") == 0) {
|
||||
metricsMode = true;
|
||||
} else if (strcmp(argv[i], "-line-metrics") == 0) {
|
||||
lineMetricsMode = true;
|
||||
} else if (strcmp(argv[i], "-no-tighten-ink") == 0) {
|
||||
tightenInk = false;
|
||||
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
|
||||
usage(argv[0]);
|
||||
return 0;
|
||||
@@ -482,10 +464,33 @@ int main(int argc, char **argv) {
|
||||
unsigned target = static_cast<unsigned>(static_cast<long long>(upem) * lineTotal / 1000);
|
||||
int oldAsc = 0, oldDesc = 0, newAsc = 0, newDesc = 0;
|
||||
int oldYMin = 0, oldYMax = 0;
|
||||
if (!scaleLineMetrics(buf, target, oldAsc, oldDesc, newAsc, newDesc, oldYMin, oldYMax)) {
|
||||
if (!scaleLineMetrics(buf, target, tightenInk, oldAsc, oldDesc, newAsc, newDesc, oldYMin,
|
||||
oldYMax)) {
|
||||
fprintf(stderr, "[x] 改写行距度量失败 (不受支持的字体结构): %s\n", inPath);
|
||||
return 1;
|
||||
}
|
||||
// 自检: 回读改写后的数据, 确认仍是可解析字体、度量确为目标值。
|
||||
// 不通过就拒绝写出 —— 调用方会保留原字体, 绝不把坏字体装进 system/fonts。
|
||||
{
|
||||
hb_blob_t *chkBlob = hb_blob_create(reinterpret_cast<const char *>(buf.data()),
|
||||
static_cast<unsigned>(buf.size()),
|
||||
HB_MEMORY_MODE_READONLY, nullptr, nullptr);
|
||||
hb_face_t *chkFace = hb_face_create(chkBlob, 0);
|
||||
hb_font_t *chkFont = hb_font_create(chkFace);
|
||||
hb_font_extents_t ext;
|
||||
memset(&ext, 0, sizeof(ext));
|
||||
const bool ok = hb_face_get_glyph_count(chkFace) > 0 &&
|
||||
hb_font_get_h_extents(chkFont, &ext) &&
|
||||
static_cast<int>(ext.ascender) == newAsc &&
|
||||
static_cast<int>(ext.descender) == newDesc;
|
||||
hb_font_destroy(chkFont);
|
||||
hb_face_destroy(chkFace);
|
||||
hb_blob_destroy(chkBlob);
|
||||
if (!ok) {
|
||||
fprintf(stderr, "[x] 自检失败: 改写后的字体无法解析或度量不符, 已放弃: %s\n", inPath);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (!writeFile(outPath, reinterpret_cast<const char *>(buf.data()), buf.size())) {
|
||||
fprintf(stderr, "[x] 写入失败: %s\n", outPath);
|
||||
return 1;
|
||||
@@ -527,18 +532,15 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
|
||||
hb_set_t *unicodes = hb_subset_input_unicode_set(input);
|
||||
if (metricsMode) {
|
||||
for (hb_codepoint_t cp : kMetricsSpaceCodes) hb_set_add(unicodes, cp);
|
||||
} else if (minimal) {
|
||||
if (minimal) {
|
||||
addRanges(unicodes, kMinimalRanges, face);
|
||||
} else {
|
||||
addRanges(unicodes, kLatinRanges, face);
|
||||
}
|
||||
if (!metricsMode && keepCjk) addRanges(unicodes, kCjkRanges, face);
|
||||
if (keepCjk) addRanges(unicodes, kCjkRanges, face);
|
||||
|
||||
// NOTDEF_OUTLINE: 保留 .notdef 字形轮廓。缺失时部分渲染器会显示空白框异常。
|
||||
// 度量载体不需要: 它只覆盖空格, .notdef 永远不会被用到, 留空更小。
|
||||
if (!metricsMode) hb_subset_input_set_flags(input, HB_SUBSET_FLAGS_NOTDEF_OUTLINE);
|
||||
// NOTDEF_OUTLINE: 保留 .notdef 字形轮廓。缺失时部分渲染器会显示空白框异常
|
||||
hb_subset_input_set_flags(input, HB_SUBSET_FLAGS_NOTDEF_OUTLINE);
|
||||
// 注: 不设置 NO_HINTING —— 保留渲染提示, 小字号下更清晰
|
||||
// 注: 不设置 NO_LAYOUT_CLOSURE —— 保留 GSUB/GPOS 闭包, 连字与字距正常
|
||||
|
||||
@@ -571,19 +573,6 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
printf("in=%zu out=%u residual_cjk=%u\n", data.size(), len, residual);
|
||||
|
||||
// 度量载体: 报告挖空后剩下的度量, 调用方据此在日志里确认行距来源与量级
|
||||
if (metricsMode) {
|
||||
hb_font_t *metricsFont = hb_font_create(subset);
|
||||
hb_font_extents_t ext;
|
||||
memset(&ext, 0, sizeof(ext));
|
||||
if (hb_font_get_h_extents(metricsFont, &ext)) {
|
||||
printf("metrics ascender=%d descender=%d line_gap=%d\n",
|
||||
static_cast<int>(ext.ascender), static_cast<int>(ext.descender),
|
||||
static_cast<int>(ext.line_gap));
|
||||
}
|
||||
hb_font_destroy(metricsFont);
|
||||
}
|
||||
|
||||
hb_blob_destroy(outBlob);
|
||||
hb_face_destroy(subset);
|
||||
hb_subset_input_destroy(input);
|
||||
|
||||
+21
-41
@@ -162,15 +162,13 @@ else
|
||||
fi
|
||||
|
||||
echo "[*] 处理行距字距..."
|
||||
# 固定行距/字距 (issue #17)。行高在 Android 里是「paint 度量」与「该行实际使用字体度量」
|
||||
# 的并集 (StaticLayout: lineAscent = min(paint 上升部, 该行字体上升部)), 只能抬高不能压低,
|
||||
# 因此两件事一起做才能真的固定住:
|
||||
# 1. 把装入 system/fonts 的字体行距度量按比例缩放到同一个总量 (上下比例不变) —— 字形不动,
|
||||
# 换字体行距不再变化; 这是关键, 只放载体压不住比它更高的字体
|
||||
# 2. 把一个只有度量、没有文字字形的载体放到家族首位, 让 paint 度量那一侧也一致
|
||||
# 载体随模块打包 (src/system/fonts/), 无需设备端生成; 档位 (行距总量) 由 WebUI 选。
|
||||
METRICS_CARRIER="$SYS_FONT_DIR/FontMM-Metrics.ttf"
|
||||
# apply.sh 会写入 system/fonts 的字体清单 (与上方安装列表一致)
|
||||
# 固定行距 (issue #17)。行高在 Android 里是「paint 度量」与「该行实际使用字体度量」的并集
|
||||
# (StaticLayout: lineAscent = min(paint 上升部, 该行字体上升部)), 只能抬高不能压低, 所以
|
||||
# 唯一的做法是**把装入 system/fonts 的字体度量统一到同一档**, 换字体行距才不会变。
|
||||
# 另外段落上下的空白来自 includeFontPadding + 字体的 head 包围盒 (虚高时会顶出一大圈),
|
||||
# 一并在改写时收紧。档位由 WebUI 选 (FONTS/line-height.txt), 开关在 FONTS/metrics.txt。
|
||||
# 注: 早先版本还会插一个「度量载体」字体到家族首位, 实测该字体在设备上会导致开机失败,
|
||||
# 已整个移除 —— 它本来也只影响 paint 度量那一侧, 对行距的贡献是次要的。
|
||||
MANAGED_FONTS='SysFont-Regular.ttf
|
||||
SysSans-En-Regular.ttf
|
||||
SysFont-Static-Regular.ttf
|
||||
@@ -182,7 +180,7 @@ SysSans-Hant-Regular.ttf
|
||||
DroidSansMono.ttf
|
||||
NotoColorEmoji.ttf'
|
||||
|
||||
# 把单个字体的行距度量统一到 target (千分比 em, 如 1450); 只动度量字段, 其余部分不变。
|
||||
# 把单个字体的行距度量统一到 target (千分比 em, 如 1450); 只动度量与包围盒, 字形不变。
|
||||
# 临时文件写在模块根目录, 避免半成品出现在 system/fonts 的 overlay 里。
|
||||
unify_one() {
|
||||
local target="$1" file="$2"
|
||||
@@ -191,7 +189,7 @@ unify_one() {
|
||||
local out=""
|
||||
|
||||
[ -s "$file" ] || return 0 # 空占位文件跳过
|
||||
if out=$(run_tool "$tool" -line-metrics -in "$file" -out "$tmp" -line-total "$target" 2>&1); then
|
||||
if out=$(run_tool "$tool" -line-metrics -in "$file" -out "$tmp" -line-total "$target" $UNIFY_EXTRA 2>&1); then
|
||||
mv -f "$tmp" "$file"
|
||||
# 逐字体回显旧/新度量, 便于实机核对 (upem 不同则数值不同, 看 em 占比)
|
||||
echo "[*] $(basename "$file"): $(echo "$out" | tr '\n' ' ' | sed 's/line_metrics //')"
|
||||
@@ -203,21 +201,6 @@ unify_one() {
|
||||
return 1
|
||||
}
|
||||
|
||||
unify_line_metrics() {
|
||||
local target="$1"
|
||||
local f=""
|
||||
[ -f "$MODDIR/tools/fontmm-subset" ] || {
|
||||
echo "[-] 未找到字体工具, 跳过行距统一"
|
||||
return 1
|
||||
}
|
||||
for f in $MANAGED_FONTS; do
|
||||
unify_one "$target" "$SYS_FONT_DIR/$f"
|
||||
done
|
||||
# 度量载体不在上面的清单里 (它不参与字体安装), 但同样要用这一档度量
|
||||
unify_one "$target" "$METRICS_CARRIER"
|
||||
return 0
|
||||
}
|
||||
|
||||
# 开关与档位由 WebUI 写在 FONTS/ 下 (随 FONTS 一起保留)
|
||||
METRICS_TOTAL="$(cat "$FONTS_DIR/line-height.txt" 2>/dev/null)"
|
||||
case "$METRICS_TOTAL" in
|
||||
@@ -225,24 +208,21 @@ case "$METRICS_TOTAL" in
|
||||
*) METRICS_TOTAL=1450 ;; # 缺省 = 标准档
|
||||
esac
|
||||
|
||||
METRICS_MODE="off"
|
||||
if [ ! -f "$METRICS_CARRIER" ]; then
|
||||
echo "[-] 缺少度量载体 $METRICS_CARRIER, 跳过固定行距字距"
|
||||
elif [ "$(cat "$FONTS_DIR/metrics.txt" 2>/dev/null)" = "1" ]; then
|
||||
METRICS_MODE="on"
|
||||
echo "[*] 已启用固定行距字距 (行距总量 $METRICS_TOTAL/1000 em)"
|
||||
unify_line_metrics "$METRICS_TOTAL"
|
||||
else
|
||||
echo "[-] 未启用固定行距字距"
|
||||
fi
|
||||
# 调试/二分用: 放一个 FONTS/.no-tighten-ink 就只统一度量、不动包围盒
|
||||
UNIFY_EXTRA=""
|
||||
[ -f "$FONTS_DIR/.no-tighten-ink" ] && UNIFY_EXTRA="-no-tighten-ink"
|
||||
|
||||
# 按开关插/移载体条目 (mode 0 不动字重, 与 WebUI 的字重覆写互不影响)
|
||||
if [ -f "$MODDIR/tools/fontmm-wght" ]; then
|
||||
if run_tool "$MODDIR/tools/fontmm-wght" -mode 0 -metrics "$METRICS_MODE" -xml-dir "$MODDIR" -sync >/dev/null 2>&1; then
|
||||
echo "[✓] 已同步字体配置 (固定行距字距: $METRICS_MODE)"
|
||||
if [ "$(cat "$FONTS_DIR/metrics.txt" 2>/dev/null)" = "1" ]; then
|
||||
if [ -f "$MODDIR/tools/fontmm-subset" ]; then
|
||||
echo "[*] 已启用固定行距 (行距总量 $METRICS_TOTAL/1000 em)"
|
||||
for f in $MANAGED_FONTS; do
|
||||
unify_one "$METRICS_TOTAL" "$SYS_FONT_DIR/$f"
|
||||
done
|
||||
else
|
||||
echo "[!] 同步字体配置失败, 固定行距字距可能未生效"
|
||||
echo "[-] 未找到字体工具, 跳过固定行距"
|
||||
fi
|
||||
else
|
||||
echo "[-] 未启用固定行距"
|
||||
fi
|
||||
|
||||
echo "[*] 全部完成, 重启后生效"
|
||||
+1
-1
@@ -276,7 +276,7 @@ system/system_ext/etc/fonts_ule.xml"
|
||||
local wght="$MODPATH/tools/fontmm-wght"
|
||||
if [ -f "$wght" ]; then
|
||||
chmod 0755 "$wght" 2>/dev/null
|
||||
if "$wght" -mode 0 -metrics auto -sync -xml-dir "$MODPATH" >/dev/null 2>&1; then
|
||||
if "$wght" -mode 0 -sync -xml-dir "$MODPATH" >/dev/null 2>&1; then
|
||||
log "已同步派生字体配置"
|
||||
else
|
||||
log "同步派生配置失败 (可忽略, 使用内置副本)"
|
||||
|
||||
Vendored
BIN
Binary file not shown.
-93
@@ -1,93 +0,0 @@
|
||||
Copyright 2017 The Roboto Flex Project Authors (https://github.com/TypeNetwork/Roboto-Flex)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
+1
-1
@@ -150,7 +150,7 @@
|
||||
<div class="wght-mode-info">
|
||||
<div class="wght-mode-title">固定行距 & 字距</div>
|
||||
<div class="wght-mode-sub" id="metrics-sub">
|
||||
把装入字体的行距度量统一到下面的档位,换字体后行距不再跟着变。开启后需重新「应用」。
|
||||
把装入字体的行距统一到下面档位、并收掉虚高的上下留白;换字体后行距不再跟着变。开启后需重新「应用」。
|
||||
</div>
|
||||
</div>
|
||||
<md-switch id="metrics-switch" aria-label="固定行距字距"></md-switch>
|
||||
|
||||
+3
-3
@@ -5,9 +5,9 @@
|
||||
// system/fonts 的字体行距各不相同, 换字体行距就会变; 只在家族首位放一个度量载体
|
||||
// 也压不住比它更高的字体。
|
||||
//
|
||||
// 做法: apply.sh 按本页开关与档位做两件事 —— 把装入的字体行距度量按比例统一到同一
|
||||
// 总量 (字形不动), 再把内置的度量载体插到各家族首位。开关存 FONTS/metrics.txt,
|
||||
// 档位 (千分比 em) 存 FONTS/line-height.txt。
|
||||
// 做法: apply.sh 按本页开关与档位, 把装入 system/fonts 的字体行距度量按比例统一到同一
|
||||
// 总量, 并收紧虚高的包围盒 (段落上下留白来自它)。字形完全不动。
|
||||
// 开关存 FONTS/metrics.txt, 档位 (千分比 em) 存 FONTS/line-height.txt。
|
||||
import '@material/web/switch/switch.js';
|
||||
import { exec, toast } from './ksu';
|
||||
import { FONTS_DIR } from './constants';
|
||||
|
||||
Reference in new issue
Block a user