52 Commits
  • fix: 识别 KernelSU/Sukisu 内置 Zygisk
    首页字体预热器与刷入时的 CHECK_ZYGISK_ENV 此前仅识别 Magisk 内置
    Zygisk 与 Zygisk Next / ReZygisk 等独立提供者, 无法识别 KernelSU /
    Sukisu 内置 Zygisk, 导致首页误报「未检测到可用的 Zygisk 环境」。
    在现有识别均未命中时, 检查 /data/adb/ksu/.builtin_zygisk 是否存在,
    存在则识别为「管理器内置 Zygisk」。
  • chore: 发布 v26.8.0-beta.10 (26080010)
    beta.9 已撤回 (固定行距字距导致开机失败), 其 release 已删除但 update.json 仍指向它,
    用户检查更新会拿到 404 的 zipUrl。这里直接发 beta.10: 版本号前移、update.json 指向
    新 release、changelog 重写为与 beta.8 的对比 (含 #12-#16 修复与行距功能移除),
    不再保留 beta.9 条目。
  • revert(metrics): 移除固定行距字距功能, 不再改动字体本身 (issue #17)
    实测只要在 WebUI 改动「固定行距 & 字距」就会触发开机失败, 把设置恢复默认同样触发,
    不动该设置则一切正常; beta.9 已因此撤回。为保险起见整套功能删除:
    
    - apply.sh: 删掉 unify_one / MANAGED_FONTS 与 metrics.txt、line-height.txt 读取
    - fontmm-subset: 删掉 -line-metrics 模式 (sfnt/字体集合解析与 hhea/OS-2/head 改写)
    - WebUI: 删掉高级配置里的开关与档位, 以及 dev 模式的伪 exec 分支
    - customize.sh: 设置继承清单去掉 metrics.txt / line-height.txt
    - README / DEVELOPMENT / dev/ci.mjs 同步移除相关章节与检查
  • fix(webui): 清空槽位后字重映射的轴范围不刷新
    字重映射的 wght 轴范围取自各槽位可变字体里跨度最小的那个 (pickWghtRange), 而
    「清空槽位」只清了 path/fileName, 解析出来的 isVariable/wghtRange 留了下来 ——
    于是删掉 200-900 的字体后, 范围仍被限制在 200-900, 可变字体标记也残留。
    
    清空时一并重置 sizeText / isVariable / wghtRange / subsetSizeText:
    - 映射范围回到剩余可变字体的范围 (renderSlots 会触发 slots-rendered 重绘映射行)
    - 大小、可变字体徽标、英文子集徽标不会停留在已删除的字体上
    
    浏览器实测: 选中 100-900(简) + 200-700(英) 后映射限制在 200-700, 清掉英文字体后
    恢复为 100-900, 简体的可变字体状态保持正确。
  • 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 中已无
    任何载体引用。
  • fix(metrics): 收紧 head 包围盒, 消除段落上下多出来的空白 (issue #17)
    用户实测仍不正常, 拿到问题字体后定位到: 它的 hhea/OS2 已被统一到 1.45 em, 但
    head 包围盒是 2.856 em (y[-1048,1808]), 于是每段多出约 1.4 em 空白。
    
    机制: 段落上下的空白不是行距, 而是 includeFontPadding (默认开启) 用
    StaticLayout 的 mTopPadding = above - top / mBottomPadding = bottom - below 撑出来的,
    其中 top/bottom 是 Skia 的 SkFontMetrics.fTop/fBottom, 取自 head 表的包围盒 —— 与
    hhea/OS2 无关。包围盒被极少数大字形撑大的字体就会顶着这圈虚高空白。
    
    - -line-metrics 顺带把 head.yMin/yMax **只收紧、不放大**到行距盒
      (yMax <= ascent, yMin >= descender); 正常字体 (包围盒本就在行距盒内) 不动
    - head 的目录校验和按 checkSumAdjustment 归零计算, 与该表自身约定一致
    - 工具输出追加 ink_y=<旧>, 便于在日志里核对
    - 实测问题字体: hhea 1.45 em 时段落上/下空白 647/759 (千分比 em) -> 归零;
      改写后表校验和与 head.checkSumAdjustment 全部通过, FreeType/harfbuzz 正常解析
    
    文档补充该机制 (DEVELOPMENT) 与用户说明 (README)。
  • fix(metrics): 行距统一支持字体集合 (.ttc/.otc) 并逐字体回显结果 (issue #17)
    实测反馈: 某个字体的段高仍然离谱。原因是它作为字体集合 (.ttc/.otc) 被 -line-metrics
    直接跳过 —— 而中文场景里 .ttc 相当常见, 跳过就等于没统一。
    
    - sfntFaces(): 解析 ttcf 头, 逐个 face 处理; 按表偏移去重, 集合内多个 face 共享的
      hhea/OS2 只改一次 (否则会把已缩放的度量再缩一次)
    - 表校验和: 更新所有引用被改表的目录项 (集合里可能多个 face 指向同一张表)
    - head.checkSumAdjustment: 先把所有 head 的该字段归零再对全文件求和一次, 写回同一个值
      (原先逐个 head 累加, 集合多 head 时会算错)
    - apply.sh: 逐字体回显旧/新度量 (upem 不同则数值不同, 看 em 占比), 失败时带上工具输出;
      跳过 0 字节占位文件
    - 补充字库 (Plangothic/Tibetan/Braille 等) 有意不参与统一: 用户字体通常已覆盖日常用字,
      为极少数生僻字每次应用多写 100MB+ 不划算, 且它们字形本就高, 压低会叠行
    
    验证: .ttc (Noto CJK, 5 face 共享表) 与单体字体改写后表校验和、head 调整值全部通过,
    FreeType 正常解析; 端到端跑 apply.sh: 装入的 .ttc 字体由 1160/-288 变为 1161/-289
    (1.45 em), 各 upem 字体按同一 em 占比统一。
  • feat(metrics): 统一字体行距度量 + 档位可选, 让固定行距真正生效 (issue #17)
    上一版只在家族首位放了度量载体, 实测无效: Android 的行高是「paint 度量」与「该行
    实际使用字体度量」的**并集** (StaticLayout: lineAscent = min(两者), descent 取 max),
    只能抬高不能压低 —— 载体 1.171em 压不住比它高的字体, 等于没起作用。
    
    - fontmm-subset 新增 -line-metrics: 把字体 hhea/OS2 的行距按比例缩放到统一总量
      (上下比例保持不变, lineGap 归零, 避免基线跳变与文字重叠), 只改度量字段, 字形 /
      hmtx / 布局表原样保留, 表长度不变; 重算 hhea / OS2 的表校验和与
      head.checkSumAdjustment。实测 1020/-300 (1.32em) -> 927/-273 (1.20em),
      2048 upem 的字体按同一 em 比例换算成 1959/-498
    - apply.sh: 开关打开时统一装入 system/fonts 的字体 (8 个槽位目标 + DroidSansMono +
      NotoColorEmoji) 与度量载体的行距; FONTS/ 里的原始字体不动; 字体集合 (.ttc) 跳过
      且不阻断安装
    - 行距档位可选 (千分比 em): 紧凑 1200 / 标准 1450 / 宽松 1600, 存 FONTS/line-height.txt;
      WebUI 高级配置新增档位选择, 开关关闭时置灰; 开关与档位改动即落盘 (便于模块更新继承)
    - customize.sh 继承 line-height.txt
    - ci.mjs: 增加档位缺省值与 WebUI 常量的一致性检查; 「占位映射」检查改为显式排除直接
      替换的系统字体 (原先靠「单行/多行」启发式, 新增多行清单会误判为占位文件)
    - README / DEVELOPMENT 同步, 含已知限制 (生僻字 fallback 不参与统一、.ttc 跳过、
      DenyList 应用回退到字体自身度量)
  • refactor(metrics): 度量载体改为内置 Roboto Flex, 去掉设备端生成 (issue #17)
    原方案在设备上按候选列表挖空系统字体, 依赖设备端字体文件名与是否存在, 既复杂又脆。
    改为从 Google Fonts 取 Roboto Flex 裁出只有度量的载体 (1.79MB -> 16KB) 直接入库:
    
    - src/system/fonts/FontMM-Metrics.ttf: 度量 1900/-500 (upem 2048) = 1.171 em,
      即 AOSP Roboto 拉丁基线; 字符集只剩 U+0020/U+00A0; OFL-1.1 且无保留字体名,
      许可文本随包附上 (LICENSE-OFL-RobotoFlex)
    - apply.sh 只引用该文件并按开关调 fontmm-wght 插/移条目, 设备端不再生成字体:
      删掉候选字体列表、挖空步骤与相应失败分支; 关闭开关也不再删载体 (它是模块自带文件)
    - fontmm-subset -metrics 保留为维护端工具, 重新生成命令写进 DEVELOPMENT.md
    - dev/ci.mjs 增加「载体文件必须存在」与「不得被占位脚本清空」两项检查
    - README / DEVELOPMENT 措辞同步
  • feat: 固定行距/字距, 用系统字体挖出度量载体 (close #17)
    安卓的行高取 Paint 度量与「该行实际使用字体」度量的并集, 而 Paint 度量来自
    typeface 家族里与请求字重最接近的条目 (hwui Paint::getMetricsInternal ->
    Minikin FontCollection::baseFontFaked; StaticLayout 再取 min(ascent)/max(descent))。
    本模块 fonts.xml 中 sans-serif 首位正是英文槽位字体, 因此换英文字体时连中文行距
    都会跟着变。
    
    - fontmm-subset 新增 -metrics: 把现成字体「挖空」, 只留 hhea/OS2 度量与
      U+0020/U+00A0/U+3000 空格字形。实测 Noto CJK 19.6MB -> 2.2KB, 度量 1160/-288
      原样保留, 字符集只剩三个空格码点
    - apply.sh: 开关打开时按优先级取系统自带且未被本模块覆盖的字体 (Noto CJK,
      退回 Roboto) 挖空成 system/fonts/FontMM-Metrics.ttf, 再调 fontmm-wght 插入条目;
      关闭时删除载体; 找不到来源字体则跳过 (功能降级, 不影响字体安装)
    - fontmm-wght 新增 -metrics on|off|auto: 在 4 个生效家族首位插入 9 档字重的载体
      条目 —— 必须覆盖全部字重, 否则粗体等字重仍会落到用户字体上。幂等 (先移除再插入),
      关闭能把 XML 逐字节还原, 载体文件不存在时不插入 (避免引用缺失字体)
    - WebUI: 高级配置新增「固定行距 & 字距」开关, 开关存 FONTS/metrics.txt, 应用时下发
    - customize.sh 顺带继承 wght-mode.txt / wght-map.txt / metrics.txt: 模块更新会重建
      整个模块目录, 此前字重模式与自定义映射每次都要重设
    - dev/ci.mjs 增加载体文件名与开关文件名的跨文件一致性检查
    
    验证: Go 单测覆盖插入/移除/幂等/与字重覆写叠加/auto 解析/缺文件跳过; 用同一份
    源码编出宿主端工具跑通 apply.sh 全流程 (生成 2.2KB 载体、36 条条目写入 XML、
    关闭后与原始 XML 逐字节一致); 浏览器实测开关切换与读写往返。
  • feat(webui): 展示英文字体子集化结果 (close #14)
    英文字体自带中文字形时, apply.sh 会先裁成纯拉丁子集再安装 (issue #10), 但
    WebUI 上仍显示原字体大小、也没有任何标记, 看起来像裁切没生效。
    
    - 新增英文子集大小读取: 读 FONTS/.en-subset.ttf, 且要求它比 en.ttf 新
      (换过英文字体但还没重新应用时, 旧子集不该继续展示)
    - 英文槽位卡片改为「原大小 → 子集大小」并加「已子集化」徽标; 子集常在
      百 KB 量级, 小于 1MB 时改用 KB, 否则会显示成 0.2 MB 看不出量级
    - 应用完成后自动刷新该状态; 重新选择英文字体时先撤下徽标 (它描述的是
      上次应用的结果, 不是当前选择的)
    - apply.sh 未使用子集时清掉残留的子集文件, 使该文件的存在即代表本次应用
      确实用了子集
  • docs(webui): 可变字体滑条说明改为「仅预览」措辞 (close #15)
    原文案「停止滑动后应用」容易被读成会修改系统字重, 实际只作用于字体测试页
    的预览。改为明确说明仅影响本页预览、不修改系统字体。
  • fix(webui): 编辑测试文本时输入框出现空行 (close #16)
    测试文本节点的 textContent 含 HTML 标签间的缩进与换行, 原样填入文本域后
    会显示成首尾各一个空行。填入前 trim 掉。
  • fix(webui): 字体选择器返回跳两层、在非 Download 目录选字体无效 (close #13)
    选择器的对话框 DOM 是单例 (按 id 复用), 但配置页与字体编辑页各自 new 了
    一个 FontFilePicker。第二个实例命中已有 DOM 时 initDialog 直接返回, 因此
    返回/取消按钮的监听仍属于第一个实例: 返回键按第一个实例的过期路径导航
    (从 Download 返回会退到 /storage, 看起来跳了两级), 重新渲染后列表项的
    回调也变成第一个实例的, 于是选中文件只更新配置页槽位、编辑页收不到。
    
    改为全局唯一实例, 选中回调改由 show() 每次传入 (每次打开的意图本就不同),
    列表点击改用事件委托只绑定一次, 不再逐次渲染重复挂监听。
  • fix: 工具在刷入后为 0644 导致找不到子集化工具 (close #12)
    KernelSU 解压模块时不保留 zip 内记录的执行位, 安装后 tools/ 下全是 0644。
    apply.sh 用 [ -x ] 判断子集化工具是否可用, 因此恒为假, 每次都提示
    「未找到字体子集化工具」并跳过英文子集化; customize.sh 里 fontmm-wght
    的 -x 判断同样失效, 刷入时不会同步派生字体配置。
    
    改为按文件存在判断, 执行前临时 chmod 0755, 执行后立即还原 0644, 不长期
    留下可执行文件。WebUI 调用 fontmm-wght 原本就 chmod +x, 一并补上用后还原
    (并保留工具自身的退出码, 不被还原动作覆盖)。
    
    实测: 工具为 0644 时可正常检出 CJK 并生成子集, 运行后权限仍为 0644;
    工具缺失时与修复前一致回退原字体, 不阻断安装。
  • fix(webui): 只选中文字体时槽位与字重覆写状态全部消失 (close #11)
    报告: 从 beta5 升级到 beta7 后, 只设置中文字体时, WebUI 槽位不显示已加载
    的字体名称, 字重覆写模式也变灰不可用; 实际字体已生效。
    
    根因是 beta.7 引入的回归。WebUI 打开时会执行一段多行脚本, 把 FONTS/ 下的
    槽位字体逐个复制到 webroot 供名称解析:
    
      [ -f '.../hans.ttf' ] && cp -f ... hans.ttf
      [ -f '.../hant.ttf' ] && cp -f ... hant.ttf
    
    改成逐槽位复制时没注意到 shell 的退出码语义: [ -f ] 条件失败会使该行以
    非 0 结束, 而 exec 只看整段退出码 -- 最后一个槽位不存在时整段就是非 0。
    用户只选中文字体, hant/en/mono/emoji 四行全部失败, 于是 WebUI 误判为
    "复制失败", 把所有槽位当空处理: 名称不显示、可变字体信息丢失、字重覆写
    因"无可变字体"而禁用。与报告现象完全吻合 (beta5 用 cp 通配符复制, 通配符
    总能正常结束, 所以没这个问题)。
    
    修法: 脚本末尾补一行 ':', 兜底整体退出码为 0。已验证三种场景 (只有
    hans / 五槽位齐全 / FONTS 为空) 退出码均为 0 且复制结果正确。
  • fix(zygisk): 修正提供者检测误将普通 Zygisk 模块识别为提供者
    报告: 安装了 Zygisk Next (模块 ID zygisksu), 但检测到的是另一个模块
    Hide My Applist Zygisk (hma_oss_zygisk)。
    
    根因: 判据用错了。原先以 [ -d "$dir/zygisk" ] 作为提供者标志, 但那其实是
    「Zygisk 模块」(消费者) 的标志 —— 任何自带 zygisk/<abi>.so 的模块都有,
    本模块自己也有。因此只要装了别的 Zygisk 模块就会被误判为提供者, 而按目录
    顺序遍历时先命中的往往是消费者而非真正的提供者。
    
    对照 Zygisk Next 官方发布包 (1.5.0) 的安装布局核实后修正判据 —— 改用提供者
    独有、普通模块不会用到的文件名:
    
    - lib{64}/libzygisk.so    核心库
    - lib{64}/libzn_loader.so Zygisk Next 的加载器
    - bin/zygiskd{64,32}      守护进程
    
    两个提供者的实际布局 (对照各自安装脚本):
      Zygisk Next (zygisksu): bin/zygiskd64 + lib64/libzygisk.so + libzn_loader.so
      ReZygisk    (rezygisk): bin/zygiskd64 + lib64/libzygisk.so + bin/zygisk-ptrace64
    共同特征即 libzygisk.so 与 zygiskd。
    
    同时修正:
    - 前端友好名映射补充 zygisksu -> Zygisk Next (此前只有 zygisknext 等猜测值)
    - dev mock 与真实模块 ID 对齐
    
    customize.sh 与 web/src/ksu.ts 两处逻辑保持一致 —— 判断标准不同会让用户看到
    「刷入时说可用、首页说不可用」这类矛盾结论。
    
    已按真实布局构造场景验证: 消费者模块 (仅 zygisk/ 目录) 不再误报, Zygisk Next
    与 ReZygisk 均能正确识别, 已停用的提供者正确跳过。
  • build(web): Pyodide 运行时改为构建时从 npm 包复制, 不再入库
    web/public/pyodide/ 下的 6 个运行时文件与 npm 依赖 `pyodide` 中的是同一份,
    提交进仓库有两个坏处: 占用仓库体积, 且依赖升版后容易留下不一致的旧副本。
    现改为构建时复制 (web/scripts/sync-pyodide.mjs, 由 dev/build 脚本自动调用)。
    
    - 移出仓库 6 个文件 (13.3MB): pyodide.asm.{mjs,wasm} / pyodide.{js,mjs}
      / pyodide-lock.json / python_stdlib.zip
    - 保留 2 个 wheel (3.9MB): fonttools 与 numpy 不在 npm 包内 (Pyodide 的依赖
      清单只登记而不随包分发), 仍需仓库提供
    
    顺带解决一个隐患: 此前仓库里的副本是格式化版本, npm 包里是压缩版本, 二者
    字节不同但功能等价。改用同源文件后, 本地与 CI 加载的 pyodide 版本必然与
    package.json 声明的依赖一致。
    
    sync-pyodide.mjs 内含配套校验: 比对保留的 wheel 与 pyodide-lock.json 登记的
    sha256, 并在 lock.json 未登记该 wheel 时提示依赖版本可能已升版。这一层是
    必要的 —— wheel 在仓库、lock.json 在 npm 包, 两者可能各自漂移, 而版本错配
    只在用户点开「字体编辑」时才暴露。
    
    已验证: 浏览器中实际加载 pyodide, 引擎报「就绪 (fontTools 4.62.1)」,
    并成功解析 demo 字体 (6253 字形, 家族名与 Canvas 预览均正常)。
    另测校验逻辑: 篡改 wheel 字节后被正确拦截 (退出码 1)。
  • chore: 添加 .gitattributes 排除第三方文件的语言统计
    GitHub 的 Languages 条此前被 Pyodide 运行时污染: web/public/pyodide/ 下是
    从官方 release 下载的预构建产物, 其中 pyodide.asm.mjs 有 1.5MB, 被 Linguist
    当作 JavaScript 统计, 一度占本项目语言统计的 87%, 掩盖了真实源码构成。
    
    用 linguist-vendored 标记这些第三方 / 二进制资源:
    
    - web/public/pyodide/**: Pyodide 运行时 (Emscripten 产物 + wheel)
    - web/public 下的 .ttf / .whl / .wasm / .zip: 演示字体与运行时资源
    - src/system/fonts/ 与 src/FONTS/ 下的字体文件
    
    只影响 GitHub 的语言占比展示, 不改变文件是否入库、也不影响构建。
    已用 git check-attr 核对: 上述文件标记为 set, 而 web/src、dev/、native/、
    golang/、src/*.sh 等真实源码仍为 unspecified (正常计入统计)。
  • fix(build): harfbuzz 编译未去除源码绝对路径, 导致产物不可复现
    首次在 CI 上构建 fontmm-subset 后发现其产物与本地的哈希不一致。
    排查: 差异在入口点地址与约 120 字节的布局偏移, 而非元数据 ——
    根因是 harfbuzz 通过 __FILE__ 与调试信息把源码绝对路径嵌进了目标文件
    (CI 为 /home/runner/work/..., 本地为 /home/yule/Project/...)。
    
    修法: 编译 harfbuzz 时加 -ffile-prefix-map, 把源码根映射为相对名。
    这与 fontmm-wght 用 -trimpath 是同一目的, 此前只在该处做了处理,
    新引入的 harfbuzz 编译漏了, 属同类问题的新实例。
    
    同时把该标志并入缓存键: 否则改动它不会使已有缓存失效, 会继续用到
    按旧标志编译的对象文件。
    
    已验证: 在两个完全不同的目录下构建, 产物逐字节一致。
    
    注: 该问题只影响哈希一致性, 不影响功能 —— 修复前后的二进制均可正常
    完成子集化, 差异仅在嵌入路径。
  • docs: 补充英文子集化说明, 添加 v26.8.0-beta.7 changelog
    - README: 槽位说明补充「英文字体自带中文时会被自动裁剪」的行为与原因;
      常见问题新增两条 (中文部分为何不生效、担心字重变少)
    - DEVELOPMENT: 新增「英文字体子集化工具」章节 (设计取舍、可变字体验证、
      CLI 用法、harfbuzz 构建缓存); 字体挂载一节补充子集化说明
    - changelog: v26.8.0-beta.7 条目
  • feat(apply): 英文槽位自动子集化, 避免覆盖中文字体 (close #10)
    apply.sh 在安装 en.ttf 前调用 fontmm-subset 检测: 含 CJK 字形则裁成拉丁
    子集后再安装, 不含则原样使用 (常见情况, 无额外开销)。
    
    - 只处理英文槽位; 中文字体不做任何处理
    - 子集文件写入 FONTS/.en-subset.ttf (中转产物)
    - 工具缺失 / 损坏 / 字体无法解析时一律回退原字体, 不阻断字体安装
    - 检测严格区分退出码: 仅 1 (含 CJK) 才子集化, 工具返回 126/127 时
      明确提示「无法检测」而非误报「子集化失败」
    
    WebUI 侧 (fontFiles.ts): 复制到 fonts-test 时改为只复制 5 个槽位文件,
    不再用 *.ttf 通配 —— 否则会把 .en-subset.ttf 等中转文件一并复制过去。
    
    已实测四种边界: 含 CJK 时正确子集化 (223KB, 无残留 CJK)、不含 CJK 时
    跳过、工具缺失时跳过、工具损坏时准确报「无法检测」, 四种情况均不阻断安装。
  • feat(subset): 新增 fontmm-subset 英文字体子集化工具
    为 issue #10 提供工具与构建支持 (apply.sh 的接入见下一个提交)。
    
    问题: fonts.xml 中 sans-serif / sys-sans-en 排在 zh-Hans / zh-Hant 之前,
    因此 en.ttf 一旦自带 CJK 字形, 这些字会被用于中文渲染并盖掉 hans/hant,
    表现为「换了中文字体但部分汉字没变」。Android 的字体配置无法限定某字体
    只负责英文, 只能在应用前把 CJK 裁掉。
    
    实现选择 (与 issue 中建议的 PyInstaller + fontTools 不同):
    - issue #9 的建议经查证不成立: PyInstaller 官方不支持交叉编译, 更不支持
      Android; 且其产物依赖宿主的 CPython (glibc), 无法在 Android 的 bionic
      libc 上运行。python-for-android 只产出 APK/AAB/AAR, 非 CLI 二进制。
    - 改用 harfbuzz 的 subset API 静态链接, 编译为设备端 CLI (3.1MB):
      无 Python 运行时开销, 且 CLI 形式让 WebUI 与手动放字体两条路径都能覆盖。
    - 实测子集化 21MB 字体仅约 21ms, 因此不做结果缓存 —— 每次重算比维护
      缓存的失效判断与陈旧文件清理更简单可靠。
    
    可变字体 (重点验证, 因为字重覆写功能依赖它):
    - fvar 轴完整保留 (wght 范围与默认值不变)
    - gvar 变形数据按字形成比例保留 (原 29226/29422 → 子集 1065/1118)
    - STAT 与 GSUB/GPOS/GDEF 排版表不丢失
    
    默认保留拉丁/希腊/西里尔与常用符号 (约 223KB); -minimal 可收窄到
    ASCII/西欧 (约 108KB) 但会缺字, 故 apply.sh 不暴露该选项。
    子集后会自检残留 CJK, 非 0 则报错, 避免用户误以为已生效。
    
    构建 (dev/lib/harfbuzz.mjs):
    - harfbuzz 源码解压后 97MB 不入库, 构建时下载
    - 编译耗时约 88s 是瓶颈, 故缓存编译产物而非源码; 缓存键 =
      harfbuzz 版本 + NDK 版本 + 编译选项, 任一变化即重新编译
    - 首次约 100s, 之后约 1s (改动 fontmm-subset.cc 无需重编 harfbuzz)
    - CI 用 actions/cache 缓存, key 由 harfbuzz.mjs 内容派生
  • chore: 发布 v26.8.0-beta.6 (26080006)
    - update.json 指向 v26.8.0-beta.6 的 Release 资产
    - changelog 补充首页「字体预热器」状态展示
  • docs: 拆分用户文档与开发文档, 精简 README 层级
    README 面向普通用户, 原先混入了大量构建/技术细节, 且「安装」部分用了
    四级标题层层嵌套。现按读者拆分:
    
    README (411 -> 146 行)
    - 保留: 特性 / 支持环境 / 安装 / 使用 / 常见问题 / 致谢 / 许可
    - 「安装」由 4 级标题压平为 2 张表: 「选择刷入包」与「安装依赖」。
      后者把 KernelSU / Magisk 两条路径并排成一张表 (元模块 / Zygisk / WebUI
      支持三行), 并把「Zygisk 只能启用一个」「Zygisk Next 需改排除列表策略」
      等补充说明归到表下, 不再各占一个标题
    - 「使用」的槽位说明与字重覆写模式同样改为表格
    - 新增两个常见问题: 预热器未生效的处理、是否需要 Fontloader
    - 涉及技术细节的表述改为面向用户的说法 (如不说 native/ 与 C++ 行数)
    
    DEVELOPMENT.md (新增)
    - 迁入全部开发内容: 环境要求、构建打包、脚本清单、预压缩缓存、
      Zygisk 模块的编译约束、可复现构建、代码检查、Unicode 覆盖测试、
      占位字体机制, 以及原「技术细节」「工作原理」两节
    - 补上原先缺失的「快速开始」与「项目结构」, 便于新贡献者上手
    - 与 README 互相引用
    
    已校验: 内部锚点全部有效、11 张表格列数一致、技术章节无遗漏。
  • ci: 修正 NDK/Go 工具链未被固定, 导致 CI 与本地产物不一致
    排查 CI 产物与本地产物的差异时发现两个问题, 都源于 workflow 声明的版本
    没有真正生效:
    
    1. NDK 声明与实装不符
       nttld/setup-ndk 只下载并暴露路径, 不会自动设置 ANDROID_NDK_HOME。原先
       注释里以为它会设置, 实际 dev/lib/ndk.mjs 回退到了 runner 预装的 NDK —
       CI 日志显示用的是 27.3.13750724 (r27d), 而声明的是 r27c, 那个 r27c
       白下载了 45 秒。现按该 action 的官方用法, 显式把 ndk-path 传给构建步骤。
    
    2. Go 版本用宽泛写法
       go-version: '1.24' 会解析到最新补丁版, CI 实际装的是 1.24.13 而 go.mod
       声明 1.24.4。改用 go-version-file: golang/go.mod 跟随声明版本。
    
    影响: 这两个版本号会以指纹形式留在二进制里 (Go 版本嵌在 fontmm-wght,
    clang/NDK 版本嵌在 arm64-v8a.so 的 .comment 段), 使 CI 产物的哈希与本地
    不同。修正后 CI 使用与本地一致的 NDK r27c。
    
    需要说明的是: 修正前两者功能完全等价 —— 已逐项对比过段结构、重定位类型与
    依赖符号, 差异仅在 .comment 指纹段 (197 字节), 代码段完全一致。所以这不是
    功能缺陷, 而是"可复现构建"不到位。
    
    README 的可复现构建章节相应改写, 按「源码路径/时间戳/工具链」三类因素说明,
    并记录 setup-ndk 与 go-version 这两个坑。
  • feat(webui): 首页显示字体预热器状态
    首页设备信息下方新增「字体预热器」卡片, 展示预加载是否生效以及所依赖的
    Zygisk 提供者。
    
    之所以要把这个状态放到首页: 预热器失效时不会有任何报错, 只表现为
    被「卸载模块」的应用字体异常 —— 用户很难自己定位。首页显式告知就绪与否,
    未就绪时直接说明原因与处理办法 (启用 Magisk 内置 Zygisk, 或安装
    Zygisk Next / ReZygisk), 而不是只标一个笼统的红字。
    
    - ksu.ts: getPreloaderStatus() 一次 root shell 调用取回全部信息
      (库是否存在 / Magisk 内置 Zygisk 开关 / 独立提供者模块), 每项用显式前缀
      标记, 避免靠输出内容猜测 (如 Magisk 开关值恰好也是 "1")
    - Zygisk 提供者识别规则与 src/customize.sh 的 CHECK_ZYGISK_ENV 保持一致:
      两处判断标准不同会让用户看到互相矛盾的结论。覆盖三种布局 —— 带 zygisk/
      目录的、ReZygisk 的 lib64+bin 布局、Zygisk Next 早期版本
    - home.ts: 就绪 = 库已安装 且 检测到 Zygisk 环境, 未就绪时给出对应原因
    - style.scss: 异常状态用 error 色, 与测试页的提示语义一致
    
    已用四种模块目录布局验证检测逻辑 (Zygisk Next 风格 / ReZygisk 风格 /
    库缺失 / 提供者被 disable), 并在浏览器中确认正常与异常两种状态的渲染。
  • perf(build): 预压缩缓存, 打包耗时减半
    打包耗时几乎全在压缩, 其中 system/fonts/ (131MB 原始 / 71MB 压缩) 占整包
    压缩量的约 70%, 而这部分只在发布新字体时才变化。现将该子树预先压缩并缓存,
    后续打包直接搬运已压缩数据 (zip.js passThrough, 不重新 deflate)。
    
    本地构建 28s -> 13s (~2.2x), 产物不变。
    
    实现:
    - dev/lib/zipcache.mjs: 缓存片段读写。指纹为「文件名 + 大小 + mtime + 权限位」,
      任一项变化即失效; 缓存目录 dev/.cache/ 不入库
    - dev/lib/zip.mjs: packDir 支持 passThrough 复用缓存条目。此处有个易错点 ——
      zip.js 把压缩级别编码进 zip 通用标志位 (bit 1-2), passThrough 时若不传 level,
      写出的标志位与现场压缩不同, 会导致整包哈希漂移 (已修复并验证)
    - dev/pack.mjs: 命中则复用, 未命中现场压缩后自动建立缓存; 新增 --no-cache
    - dev/cache.mjs: status / clean / test 三个管理命令
    - CI 构建加 --no-cache (一次性构建无收益, 也避免引入与构建机相关的状态)
    
    缓存是纯本地的构建加速, 不影响产物也不参与分发:
    - 命中缓存与不使用缓存的 zip 逐字节相同 (以 SOURCE_DATE_EPOCH 固定时间戳验证)
    - 缓存缺失 / 索引损坏 / 数据文件截断 / 格式版本不符, 四种情况均回退现场压缩
      (已逐一测试), 不会导致构建失败
    
    dev/cache.mjs test 可校验缓存内容与源文件逐一相符。
  • chore: 许可证改为 GPL-3.0, 发布 v26.8.0-beta.6 (26080006)
    - LICENSE: MIT -> GPL-3.0。内置的 Zygisk 字体预加载参考了以 GPL-3.0 发布的
      Fontloader 实现, 故整体采用同一许可; README 补充来源说明
    - README: 移除「需预装 Fontloader」等已过时说明, 改为内置预加载的说明与
      Zygisk 环境要求; 开发指南补充 NDK 与 Zygisk 模块的构建说明
    - module.prop: 版本升至 26.8.0-beta.6 / 26080006
    
    本次版本主要内容见 changelog: 内置字体预加载 (不再依赖 Fontloader)、
    构建流程改为 Node 脚本、修复小米主题字体工具的搜索与下载。
  • feat(zygisk): 内置字体预加载, 不再依赖外部 Fontloader
    Android 12 起字体由 app 进程按需加载, 被 Root 管理器「卸载模块」的 app
    会因读不到模块字体而字体异常甚至闪退。原先依赖第三方 FontLoader 模块
    解决, 但该模块上游 (RikkaW/FontLoader) 已删库, 现存分支亦有停更风险。
    现将其核心逻辑内置于本模块。
    
    原理: 在 app specialize 之前 (此时进程仍有 zygote 的挂载视图) 调用
      Typeface.nativeWarmUpCache(), 把字体预读进 Skia 的静态数据缓存
      (以路径为 key, 进程内不清除)。specialize 后即使路径不可访问,
      仍能命中缓存正常渲染。
      已验证该方法自 Android 12 至 16 均存在, 签名 (Ljava/lang/String;)V。
    
    实现 (native/src/fontmm.cpp, 约 200 行):
    - 只预热 FontMM 自己的字体: 清单在编译期已知, 因此不需要参考实现那样的
      root companion 进程与 socket IPC, 代码量与攻击面都显著更小
    - 不包含参考实现中的 HideFromMaps: 该函数在原实现里是死代码, 且非渲染必需
    - 不按 uid 过滤: ColorOS 大量系统应用以 android.uid.system 运行, 它们同样
      会被加入 DenyList, 正是最需要预热的对象
    
    编译约束 (dev/lib/ndk.mjs, 构建时自动校验):
    - 不得依赖 libc++_shared.so —— Zygisk 提供者用自研 ELF 加载器, 只从系统库
      目录解析依赖, 找不到该库会导致模块加载失败
    - 不得引用 __cxa_guard_* —— 这两个符号不在 bionic libc 导出表中 (仅 libc++
      提供), 故用 -fno-threadsafe-statics 取消静态局部变量的线程安全保护
    - 产物 6.8KB, 仅导出 zygisk_module_entry, 依赖 liblog/libm/libdl/libc
    
    安装脚本 (src/customize.sh):
    - 原 CHECK_FONTLOADER (要求预装并检查版本) 替换为 CHECK_ZYGISK_ENV:
      识别 Magisk 内置 Zygisk 与独立提供者 (Zygisk Next / ReZygisk), 缺失时
      音量键确认后继续而非阻断
    - 新增 DISABLE_OLD_FONTLOADER: 检测到外部 Fontloader 时自动添加 disable
      文件停用 (保留其数据, 删除该文件即可恢复)
    
    构建:
    - dev/build-zygisk.mjs + dev/lib/ndk.mjs (NDK 定位/交叉编译/产物校验)
    - 顺带生成 compile_commands.json, 修复 IDE 找不到 jni.h 的 IntelliSense 报错
    - CI 新增 native.yml, build/release 增加 NDK setup
    
    许可证: 因内置部分参考 GPL-3.0 的 Fontloader 实现, 整体改为 GPL-3.0。
    native/src/zygisk.hpp 为 topjohnwu 的宽松许可头文件, 可自由内联。
    
    实机 (ColorOS 16 / arm64) 验证通过。
  • fix(webui): 修复小米字体下载按钮拿不到主题 ID 导致下载始终失败
    renderItems 渲染下载按钮时从未写入 data-link, 而 startDownload 读取的
    正是 dataset.link, 取到的永远是空字符串。空 ID 传给 mi-font-download.sh
    后, 详情接口必然返回不了 downloadUrl, 脚本直接以「获取下载链接失败」退出 ——
    即下载按钮在真机上完全不可用。
    
    - renderItems 在按钮上写入 data-link / data-title
    - startDownload 直接从按钮读取, 不再经由 DOM 文本反查标题
    - 缺少 ID 时给出明确提示, 而不是把空参数传进脚本
    - 保留既有的 shellQuote 处理, 标题含空格/引号时仍安全
    
    已用真实接口验证: 搜索 -> 取 link -> 详情取 downloadUrl -> 下载 .mtz
    返回 HTTP 206 / application/mtz, 全链路可用。
  • fix(webui): 修正小米字体搜索的响应解析, 搜索此前一直无结果
    原解析读 data.data.items, 与接口实际结构不符 —— 真实响应为
    apiData.cards[].items[].schema.clicks[], 字段是 title/link/pic。
    实测同一响应下原代码解析出 0 条, 界面恒显示「未找到相关字体」。
    
    - 抽出 parseSearchResponse() 按真实结构解析, 并跳过无 title/link 的
      占位项 (无结果时接口返回 type=noResultMessage 的 item)
    - 分页改用接口的 hasMore: 接口每页固定 12 条, 原按「>=20 条才有下一页」
      估算总数会误判总页数 (第一页即显示 100 页)
    - 移除 it.time / it.certified 字段引用 (接口不返回)
    - dev mock 同步为真实结构, 并让 page=1 返回空页以便验证下一页按钮
    
    已用真实接口响应 (12 条) 验证解析结果正确。
  • build: 构建流程由 shell 改为 Node 脚本
    原 dev/*.sh 依赖 zip/unzip 等系统命令, 在 Windows、精简容器与部分 CI
    镜像中缺失或行为不一致。全部改写为 Node 脚本, 只需 Node 即可构建。
    
    - dev/pack.mjs: 打包主流程 (取代 cd.sh), 含产物回读校验
    - dev/webzip.mjs / gen-sha256.mjs / build-wght.mjs / ci.mjs
    - dev/empty-font.mjs / sync-fonts-xml.mjs (开发辅助)
    - dev/lib/: zip 封装 (@zip.js/zip.js) / 路径 / 日志 / 命令 / Go 构建
    - package.json 与 3 个 workflow 改用 node/pnpm 入口
    - README 开发章节重写
    
    顺带修复:
    - Go 构建加 -trimpath -buildvcs=false: 原先会把源码绝对路径与
      vcs.modified 嵌进二进制, 导致同一份源码在不同目录构建、或工作树有
      未提交改动时产物哈希不同, SHA256SUMS 随构建环境漂移
    - zip 权限位与控制流: fontmm-wght 保持 0755, 目录条目与派生配置排除
      均与原 zip 行为一致; SHA256SUMS 权限固定 0644
    - shfmt 参数 -w -d 相互矛盾 (一个改写一个只 diff), 拆为 shfmt 与 shfmt:fix
    - .gitignore 补充派生字体配置, 避免 dev/sync-fonts-xml.mjs 的产物被误提交
    
    产物验证: 与迁移前对比条目名/权限位/内容哈希一致; 模拟干净克隆 CI
    流程构建, 内容与权限位完全一致, 设 SOURCE_DATE_EPOCH 后 zip 逐字节相同。
  • fix(webui): 修复西文覆盖问题 + 字重覆写多家族 + SHA256 校验
    - 修复中文字体完全覆盖西文字体 (issue #6): SysFont-Regular.ttf 改由英文槽位填充,
      未设置英文时仍回退简体
    - 字重覆写覆盖全部生效家族 (issue #7): sans-serif/sys-sans-en/zh-Hans/zh-Hant
    - fontmm-wght 只修改 fonts.xml 主配置, -sync 同步到各派生配置
    - 派生配置不再打包, 由 customize.sh 扫描设备系统 XML 生成, 提升兼容性
    - 新增 SHA256 校验 (issue #8): dev/gen-sha256.sh + tools/verify-sha256.sh,
      CI/Release 产物附带 .sha256
83 changed files with 7018 additions and 58205 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
# GitHub Linguist 语言统计配置
#
# 作用: 标注第三方 / 生成的文件, 避免它们计入仓库的语言统计 (Languages 条)。
# 这些文件不进统计不代表不参与构建, 只影响 GitHub 的语言占比展示。
# Pyodide 运行时 (WebUI「字体编辑」工具用): 从官方 release 下载的预构建产物,
# 包含 Emscripten 编译出的 pyodide.asm.mjs (1.5MB) 等。
# 它们会被 Linguist 当作 JavaScript 统计, 一度占本项目语言统计的 87%,
# 掩盖了真正的源码构成 —— 故标记为第三方代码排除在外。
web/public/pyodide/** linguist-vendored
# 同理: 字体文件与 wheel 包等二进制资源不是源码, 明确排除
web/public/*.ttf linguist-vendored
web/public/**/*.whl linguist-vendored
web/public/**/*.wasm linguist-vendored
web/public/**/*.zip linguist-vendored
# 模块内的字体资源 (含补充字库) 同上
src/system/fonts/* linguist-vendored
src/FONTS/* linguist-vendored
+48 -4
View File
@@ -21,20 +21,64 @@ jobs:
with:
node-version: 22
cache: pnpm
cache-dependency-path: web/pnpm-lock.yaml
cache-dependency-path: |
pnpm-lock.yaml
web/pnpm-lock.yaml
- name: Install dependencies
- name: Setup Go
uses: actions/setup-go@v5
with:
# 跟随 go.mod 声明的工具链版本, 避免宽泛的 '1.24' 解析到最新补丁版
# (CI 曾装 1.24.13 而本地是 1.24.4, 编译产物因此不同)
go-version-file: golang/go.mod
# Zygisk 模块 (C++) 需要 NDK 交叉编译。
# 注意: setup-ndk 只下载并暴露路径, 不会自动设置 ANDROID_NDK_HOME,
# 必须由使用方显式传入, 否则 dev/lib/ndk.mjs 会回退到 runner 预装的
# 其它 NDK 版本 (实测踩过: 声明 r27c 却用了预装的 r27d)
- name: Setup Android NDK
id: setup-ndk
uses: nttld/setup-ndk@v1
with:
ndk-version: r27c
# harfbuzz 的编译约需 88 秒 (fontmm-subset 的构建瓶颈), 故缓存源码与编译产物。
# 缓存键含 harfbuzz 版本与 NDK 版本 —— 二者任一变化即不命中。
- name: Cache harfbuzz
uses: actions/cache@v4
with:
path: |
dev/.cache/harfbuzz
dev/.cache/harfbuzz-obj
key: harfbuzz-${{ runner.os }}-${{ hashFiles('dev/lib/harfbuzz.mjs') }}
# 根依赖提供打包所需的 zip 库 (@zip.js/zip.js),
# 打包脚本不再依赖 zip / unzip 命令, 故无需系统级安装
- name: Install root dependencies
run: pnpm install --frozen-lockfile
- name: Install WebUI dependencies
run: pnpm -C web install --frozen-lockfile
- name: Build WebUI
run: pnpm -C web build
# 打包内部会编译 fontmm-wght (Go) 与 Zygisk 模块 (C++),
# 并生成两版产物与 .sha256 校验文件
# 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的
# 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突
# --no-cache: CI 是一次性构建, 预压缩缓存没有收益, 也避免引入
# 与构建机相关的状态 (缓存目录不入库, 本地开发时才生效)
- name: Pack module (preplace / template)
run: bash dev/cd.sh
run: pnpm run pack -- --no-cache
env:
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: fontmm-build
path: dist/*.zip
path: |
dist/*.zip
dist/*.zip.sha256
retention-days: 14
+16 -5
View File
@@ -4,11 +4,13 @@ on:
push:
paths:
- 'golang/**'
- 'dev/build-wght.sh'
- 'dev/build-wght.mjs'
- 'dev/lib/go.mjs'
pull_request:
paths:
- 'golang/**'
- 'dev/build-wght.sh'
- 'dev/build-wght.mjs'
- 'dev/lib/go.mjs'
workflow_dispatch:
jobs:
@@ -18,10 +20,17 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
# 跟随 go.mod 声明的工具链版本, 避免宽泛的 '1.24' 解析到最新补丁版
# (CI 曾装 1.24.13 而本地是 1.24.4, 编译产物因此不同)
go-version-file: golang/go.mod
- name: Vet
run: cd golang && go vet ./...
@@ -29,11 +38,13 @@ jobs:
- name: Test
run: cd golang && go test ./...
# 用与本地一致的构建脚本 (含 -trimpath -buildvcs=false), 保证 CI 产物
# 与开发者本地构建的二进制哈希一致
- 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
run: node dev/build-wght.mjs
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: fontmm-wght
path: /tmp/fontmm-wght
path: src/tools/fontmm-wght
+72
View File
@@ -0,0 +1,72 @@
name: Native (Zygisk / Subset)
on:
push:
paths:
- 'native/**'
- 'dev/build-zygisk.mjs'
- 'dev/build-subset.mjs'
- 'dev/lib/ndk.mjs'
- 'dev/lib/harfbuzz.mjs'
pull_request:
paths:
- 'native/**'
- 'dev/build-zygisk.mjs'
- 'dev/build-subset.mjs'
- 'dev/lib/ndk.mjs'
- 'dev/lib/harfbuzz.mjs'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
# 固定 NDK 版本, 保证 CI 与开发者本地编译出的二进制一致 (至少工具链同版本)。
# 必须显式把 ndk-path 传给构建脚本: setup-ndk 不会自动设置 ANDROID_NDK_HOME,
# 否则 dev/lib/ndk.mjs 会回退到 runner 预装的其它 NDK 版本 (实测踩过:
# 声明 r27c 却用了预装的 r27d)
- name: Setup Android NDK
id: setup-ndk
uses: nttld/setup-ndk@v1
with:
ndk-version: r27c
# harfbuzz 的编译约需 88 秒 (占 fontmm-subset 构建的绝大部分), 故缓存其
# 源码与编译产物。缓存键含 harfbuzz 版本与 NDK 版本 —— 二者任一变化即
# 不命中, 不会用到与当前工具链不匹配的对象文件。
- name: Cache harfbuzz
uses: actions/cache@v4
with:
path: |
dev/.cache/harfbuzz
dev/.cache/harfbuzz-obj
key: harfbuzz-${{ runner.os }}-${{ hashFiles('dev/lib/harfbuzz.mjs') }}
# 构建脚本自身会校验导出符号与动态依赖 (不得依赖 libc++_shared 等
# 不在 Zygisk 加载器搜索路径中的库), 校验失败即退出非 0
- name: Build Zygisk module (arm64-v8a)
run: node dev/build-zygisk.mjs
env:
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
- name: Build subset tool (arm64)
run: node dev/build-subset.mjs
env:
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: fontmm-native
path: |
src/zygisk/arm64-v8a.so
src/tools/fontmm-subset
retention-days: 14
+48 -4
View File
@@ -23,20 +23,64 @@ jobs:
with:
node-version: 22
cache: pnpm
cache-dependency-path: web/pnpm-lock.yaml
cache-dependency-path: |
pnpm-lock.yaml
web/pnpm-lock.yaml
- name: Install dependencies
- name: Setup Go
uses: actions/setup-go@v5
with:
# 跟随 go.mod 声明的工具链版本, 避免宽泛的 '1.24' 解析到最新补丁版
# (CI 曾装 1.24.13 而本地是 1.24.4, 编译产物因此不同)
go-version-file: golang/go.mod
# Zygisk 模块 (C++) 需要 NDK 交叉编译。
# 注意: setup-ndk 只下载并暴露路径, 不会自动设置 ANDROID_NDK_HOME,
# 必须由使用方显式传入, 否则 dev/lib/ndk.mjs 会回退到 runner 预装的
# 其它 NDK 版本 (实测踩过: 声明 r27c 却用了预装的 r27d)
- name: Setup Android NDK
id: setup-ndk
uses: nttld/setup-ndk@v1
with:
ndk-version: r27c
# harfbuzz 的编译约需 88 秒 (fontmm-subset 的构建瓶颈), 故缓存源码与编译产物。
# 缓存键含 harfbuzz 版本与 NDK 版本 —— 二者任一变化即不命中。
- name: Cache harfbuzz
uses: actions/cache@v4
with:
path: |
dev/.cache/harfbuzz
dev/.cache/harfbuzz-obj
key: harfbuzz-${{ runner.os }}-${{ hashFiles('dev/lib/harfbuzz.mjs') }}
# 根依赖提供打包所需的 zip 库 (@zip.js/zip.js),
# 打包脚本不再依赖 zip / unzip 命令, 故无需系统级安装
- name: Install root dependencies
run: pnpm install --frozen-lockfile
- name: Install WebUI dependencies
run: pnpm -C web install --frozen-lockfile
- name: Build WebUI
run: pnpm -C web build
# 打包内部会编译 fontmm-wght (Go) 与 Zygisk 模块 (C++),
# 并生成两版产物与 .sha256 校验文件
# 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的
# 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突
# --no-cache: CI 是一次性构建, 预压缩缓存没有收益, 也避免引入
# 与构建机相关的状态 (缓存目录不入库, 本地开发时才生效)
- name: Pack module (preplace / template)
run: bash dev/cd.sh
run: pnpm run pack -- --no-cache
env:
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
- name: Upload release assets
uses: softprops/action-gh-release@v2
with:
files: dist/*.zip
files: |
dist/*.zip
dist/*.zip.sha256
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+30
View File
@@ -7,5 +7,35 @@ reasonix.toml
.agent/
.ref/
# 构建产物: 模块内二进制 (由 dev/build-*.mjs 交叉编译)
src/tools/fontmm-wght
src/tools/fontmm-subset
golang/bin/
src/SHA256SUMS
# 派生字体配置: 由设备端 customize.sh 扫描系统 XML 生成, 不随仓库分发。
# dev/sync-fonts-xml.mjs 会在本地生成这些文件供调试, 需避免误提交。
src/system/etc/fonts_base.xml
src/system/etc/fonts_ule.xml
src/system/etc/font_fallback.xml
src/system/system_ext/
# Zygisk 模块产物 (由 dev/build-zygisk.mjs 生成)
src/zygisk/
native/build/
# 编辑器 C++ 索引数据 (由 dev/build-zygisk.mjs 生成)
compile_commands.json
# 预压缩构建缓存 (dev/pack.mjs 自动生成, 体积大且与机器相关的 mtime 绑定)
dev/.cache/
# Pyodide 运行时: 由 web/scripts/sync-pyodide.mjs 在构建时从 npm 的 pyodide
# 包复制 (与依赖同源, 避免仓库里留一份易过期的副本)。
# 例外: 两个 wheel 不在 npm 包内, 仍需随仓库提供, 故不在此忽略。
web/public/pyodide/pyodide.asm.mjs
web/public/pyodide/pyodide.asm.wasm
web/public/pyodide/pyodide.js
web/public/pyodide/pyodide.mjs
web/public/pyodide/pyodide-lock.json
web/public/pyodide/python_stdlib.zip
+20
View File
@@ -0,0 +1,20 @@
{
// C/C++ 智能提示配置。
//
// native/ 下的 Zygisk 模块用 Android NDK 交叉编译, 头文件 (jni.h / android/log.h 等)
// 不在系统路径中, 因此交给 compile_commands.json 提供真实构建参数 —— 该文件由
// `pnpm zygisk:build` (或 pnpm build) 生成, 首次克隆后需先构建一次。
//
// clangd 扩展会自动发现仓库根的 compile_commands.json, 无需此文件;
// 这里是为 Microsoft C/C++ 扩展 (ms-vscode.cpptools) 提供同等配置。
"configurations": [
{
"name": "Android arm64-v8a",
"compileCommands": "${workspaceFolder}/compile_commands.json",
"cStandard": "c17",
"cppStandard": "c++20",
"intelliSenseMode": "linux-clang-arm64"
}
],
"version": 4
}
+5 -1
View File
@@ -1,3 +1,7 @@
{
"recommendations": ["oxc.oxc-vscode"]
"recommendations": [
"oxc.oxc-vscode",
"llvm-vs-code-extensions.vscode-clangd",
"ms-vscode.cpptools"
]
}
+340
View File
@@ -0,0 +1,340 @@
# FontMM 开发指南
面向本仓库的开发者与贡献者。用户文档见 [README](./README.md)。
## 环境要求
- **Node.js ≥ 18** + [pnpm](https://pnpm.io/)(构建脚本全部为 Node 脚本,不依赖 shell 工具链)
- **Golang**(编译字重覆写工具 `fontmm-wght`)
- **Android NDK**(编译 Zygisk 字体预加载模块 `zygisk/arm64-v8a.so`)
- `Python 3` + `fontTools`(仅 Unicode 覆盖测试需要)
- `shellcheck` + `shfmt`(可选,装上后 `pnpm check` 会额外检查 `src/` 下的 shell 脚本)
NDK 通过环境变量 `ANDROID_NDK_HOME` 指定,或放在以下位置之一(按优先级查找):
`~/opt/android-ndk-r27c`、`~/Android/Sdk/ndk`、`/opt/android-ndk`。
```bash
# 下载 NDK (约 630MB)
curl -LO https://dl.google.com/android/repository/android-ndk-r27c-linux.zip
unzip android-ndk-r27c-linux.zip -d ~/opt/
```
> 构建流程不需要 `zip` / `unzip` 命令:打包由 Node 脚本调用
> [@zip.js/zip.js](https://github.com/gildas-lormeau/zip.js) 完成,
> 在 Windows、精简容器与各类 CI 镜像中均可直接运行。
## 快速开始
```bash
pnpm install && cd web && pnpm install # 安装依赖
pnpm dev # 本地预览 WebUI
pnpm build # 完整构建
```
`pnpm dev` 下 `ksu.ts` 使用内置 mock 文件系统,文件选择、槽位切换、应用字体
全流程可脱离真机调试。
## 项目结构
| 目录 | 内容 |
| ---- | ---- |
| `src/` | 模块本体(打包进 zip 的根目录):刷入脚本、`apply.sh`、字体配置、设备端工具 |
| `web/` | WebUI 源码(Vite + TypeScript + Material Web),构建产物输出到 `src/webroot` |
| `native/` | Zygisk 字体预加载模块(C++) |
| `golang/` | `fontmm-wght`,字重覆写工具 |
| `dev/` | 构建与开发脚本 |
## 构建与打包
```bash
pnpm build # WebUI + 模块打包 -> dist/FontMM_v<版本>_{preplace,template}.zip
```
单独执行某一步:
```bash
pnpm -C web build # 仅构建 WebUI 到 src/webroot
pnpm run pack # 仅打包模块 (含 Go/C++ 交叉编译, 生成 .sha256)
pnpm build:only-web # 仅打包 WebUI 产物 -> dist/webroot.zip (调试用)
pnpm go:build # 仅交叉编译 fontmm-wght -> src/tools/
pnpm zygisk:build # 仅交叉编译 Zygisk 模块 -> src/zygisk/
```
> 注意用 `pnpm run pack` 而非 `pnpm pack`——后者是 pnpm 内置的 npm 包打包命令。
构建脚本位于 `dev/`,公共逻辑在 `dev/lib/`:
| 脚本 | 作用 |
| ---- | ---- |
| `dev/pack.mjs` | 模块打包主流程(编译 Go/C++ → 生成校验表 → 打包两版 → 校验产物) |
| `dev/webzip.mjs` | 仅打包 WebUI 产物 |
| `dev/gen-sha256.mjs` | 生成 `src/SHA256SUMS` 与 `dist/*.zip.sha256` |
| `dev/build-wght.mjs` | 交叉编译 `fontmm-wght`(android/arm64) |
| `dev/build-zygisk.mjs` | 交叉编译 Zygisk 字体预加载模块(android/arm64-v8a) |
| `dev/build-subset.mjs` | 交叉编译 `fontmm-subset`(英文字体子集化工具) |
| `dev/ci.mjs` | 代码检查(结构校验 + shellcheck/shfmt + 前端 lint/format/类型) |
| `dev/empty-font.mjs` | 重新生成占位字体文件 |
| `dev/sync-fonts-xml.mjs` | 本地生成派生字体配置(仅调试用) |
| `dev/cache.mjs` | 预压缩缓存管理(status / clean / test) |
| `dev/lib/zip.mjs` | ZIP 读写封装(打包 + 回读校验) |
| `dev/lib/zipcache.mjs` | 预压缩缓存(复用已压缩数据,跳过 deflate) |
| `dev/lib/ndk.mjs` | NDK 定位与 C++ 交叉编译(含产物兼容性校验) |
| `dev/lib/harfbuzz.mjs` | harfbuzz 源码获取与静态库编译(供 `fontmm-subset` 用) |
## 代码检查
> 前端 lint/format 由 [oxlint](https://oxc.rs/) 与 [oxfmt](https://oxc.rs/) 提供
```bash
pnpm check # 全部检查 (缺 shellcheck/shfmt 时自动跳过)
pnpm check:strict # CI 模式: 缺少 shellcheck/shfmt 直接失败
pnpm lint # 前端 oxlint 检查
pnpm fmt # 前端 oxfmt 格式化
pnpm fmt:check # 前端 oxfmt 格式检查
pnpm shfmt # 检查 src/ 下 shell 脚本格式 (不改写)
pnpm shfmt:fix # 格式化 src/ 下 shell 脚本
```
`pnpm check` 除了跑 lint 与类型检查,还会做几项结构一致性校验:`module.prop` 字段完整性、
`fonts.xml` 标签配对、`apply.sh` 的基础占位映射与 `empty-font.mjs` 清单是否一一对应、
Zygisk 预热字体清单(含多字重 `FontMM-*` 扩展文件)与 `apply.sh` 是否一致、派生配置是否被误提交等。
## 预压缩缓存
打包耗时几乎全在压缩,而 `system/fonts/`(131MB 原始数据、压缩后 71MB)占了压缩量的
约 70%,且它只在发布新字体时才会变化。因此 `dev/pack.mjs` 会把这部分**预先压缩并缓存**到
`dev/.cache/`,后续打包直接搬运已压缩数据(不重新 deflate),本地构建从约 28s 降到约 13s。
缓存以「文件名 + 大小 + mtime + 权限位」为指纹,任一项变化即失效并自动重建。它是纯本地的
构建加速,**不入库、不影响产物**:命中缓存与不使用缓存产出的 zip 逐字节相同(可用
`SOURCE_DATE_EPOCH` 固定时间戳复现验证)。缓存缺失、损坏或版本不符时一律回退为现场压缩。
```bash
pnpm cache:status # 查看缓存片段、大小、文件数
pnpm cache:test # 校验缓存内容与源文件逐一相符
pnpm cache:clean # 清空缓存
node dev/pack.mjs --no-cache # 本次构建禁用缓存
```
> CI 中使用 `--no-cache`:缓存对一次性构建没有收益,也避免引入与构建机相关的状态。
## Zygisk 字体预加载模块
源码在 `native/`,编译产物 `src/zygisk/arm64-v8a.so` 随包分发。它做的事很小:在 App 进程
specialize 之前调用系统的 `Typeface.nativeWarmUpCache()`,把 FontMM 的字体文件预读进
系统字体缓存(详见 `native/src/fontmm.cpp` 顶部注释)。
编译选项有两条硬约束,改动时需留意 `dev/lib/ndk.mjs` 里的校验:
- **不得依赖 `libc++_shared.so`**:Zygisk 提供者使用自研 ELF 加载器(不用系统 `dlopen`),
其库搜索路径只含系统目录,找不到 `libc++_shared.so` 会导致模块加载失败。
- **不得引用 `__cxa_guard_acquire` / `__cxa_guard_release`**:这两个符号不在 bionic libc
的导出表中(仅 libc++ 提供),因此用 `-fno-threadsafe-statics` 取消静态局部变量的
线程安全保护(`zygisk.hpp` 的 `entry_impl` 使用了静态局部变量)。
构建脚本会自动校验导出符号只有 `zygisk_module_entry`、且未链接 libc++,不满足即报错。
改动 `native/` 后建议检查产物:
```bash
node dev/build-zygisk.mjs
llvm-nm -D --defined-only src/zygisk/arm64-v8a.so # 应只有 zygisk_module_entry
llvm-readelf -d src/zygisk/arm64-v8a.so | grep NEEDED # 应不含 libc++_shared
```
## 英文字体子集化工具
源码在 `native/src/subset/`,产物 `src/tools/fontmm-subset`,由 `apply.sh` 在设备端调用。
**为什么需要它**:`fonts.xml` 中 `sans-serif` / `sys-sans-en` 排在 `zh-Hans` / `zh-Hant`
之前,因此 `en.ttf` 一旦自带 CJK 字形,这些字就会被用于中文渲染,盖掉 `hans.ttf` /
`hant.ttf`。Android 的 `fonts.xml` 无法限定字体"只负责英文",只能在应用前把 CJK 裁掉。
**实现选择**:用 harfbuzz 的 subset API 并静态链接,编译成设备端 CLI。相比
PyInstaller + fontTools 的方案:
- 无需在设备上引入 Python 运行时(PyInstaller 也不支持交叉编译到 Android,
且其产物依赖 glibc,无法在 Android 的 bionic libc 上运行)
- 子集化耗时约 21ms(21MB 字体),因此**不做结果缓存**——每次重算比维护缓存的
失效判断与陈旧文件清理更简单可靠
- CLI 形式使 WebUI 与「手动放字体」两条路径都能覆盖
**可变字体**:已实测确认 `fvar` 轴(wght 范围与默认值)、`gvar` 变形数据(按字形
成比例保留)、`STAT` 与 `GSUB` / `GPOS` / `GDEF` 排版表均不丢失,字重覆写功能不受影响。
**CLI**:
```bash
fontmm-subset -check <font.ttf> # 检测含 CJK 则退出码 1
fontmm-subset -in <f.ttf> -out <o.ttf> # 生成子集 (默认保留拉丁/希腊/西里尔)
[-minimal] # 仅 ASCII/西欧 (体积更小, 但会缺字)
[-keep-cjk] # 额外保留 CJK 区块
```
**harfbuzz 构建缓存**:harfbuzz 源码解压后 97MB,不入库,由 `dev/lib/harfbuzz.mjs`
在构建时下载。其中**编译耗时约 88 秒**(占整个构建绝大部分),因此缓存编译产物而非
源码:缓存键 = harfbuzz 版本 + NDK 版本 + 编译选项,任一变化即重新编译。
首次构建约 100s,之后约 1s。缓存位于 `dev/.cache/harfbuzz{,-obj}/`。
改动后检查产物:
```bash
node dev/build-subset.mjs
src/tools/fontmm-subset -check src/FONTS/hans.ttf # 应返回 cjk=<非0> / 退出码 1
```
## 可复现构建
产物由三类因素决定,本仓库分别做了处理:
**1. 源码路径与 VCS 状态** — 已消除。`fontmm-wght` 用 `-trimpath -buildvcs=false` 编译,
否则 Go 会把源码绝对路径与 `vcs.modified` 等状态嵌进二进制,导致产物哈希随构建目录、
以及工作树是否干净而变化。
**2. 条目的时间戳** — 可控。设置 `SOURCE_DATE_EPOCH` 固定所有 zip 条目时间戳,
即可得到逐字节相同的 zip(用于留档比对、镜像分发):
```bash
SOURCE_DATE_EPOCH=1700000000 pnpm run pack
```
不设置时沿用源文件的修改时间,与 `zip` 的默认行为一致。
**3. 工具链版本** — 通过固定版本对齐。编译器版本会以指纹形式留在二进制里
(`fontmm-wght` 嵌 Go 版本,`arm64-v8a.so` 的 `.comment` 段嵌 clang 与 NDK 版本),
所以 CI 与本地必须用**相同版本**的工具链才能得到相同哈希:
| 工具 | 本地 | CI 如何对齐 |
| ---- | ---- | ---- |
| Go | 以 `golang/go.mod` 声明为准 | `go-version-file: golang/go.mod` |
| NDK | `~/opt/android-ndk-r27c` | `ndk-version: r27c` |
> 踩过的坑:`nttld/setup-ndk` **不会**自动设置 `ANDROID_NDK_HOME`,必须由 workflow
> 显式传入 `steps.setup-ndk.outputs.ndk-path`;否则会静默回退到 runner 预装的其它
> NDK 版本(曾出现声明 r27c 却用 r27d)。同理,`go-version: '1.24'` 这种宽泛写法会
> 解析到最新补丁版(CI 装 1.24.13 而本地 1.24.4),故改用 `go-version-file`。
即使工具链版本不同,产物也只是 `.comment` 指纹段有差异 —— 代码段、重定位与依赖符号
完全一致,功能等价。
## Unicode 覆盖测试
> 本地模拟 `fonts.xml` 的 fallback 链,对照 Unicode Blocks.txt 统计每个区块覆盖率,
> 首次运行会自动下载 Blocks.txt 缓存到 `dev/`
```bash
python3 dev/check-unicode-coverage.py # 全部区块
python3 dev/check-unicode-coverage.py "Archaic" "Seal" # 只测指定区块
```
## 占位字体机制
`src/system/fonts/` 下的 `SysFont*` / `SysSans*` 是 **0 字节占位文件**,避免把大字体文件
提交进仓库;安装或应用字体时由 `apply.sh` 用 `FONTS/` 里的真实字体覆盖。
- 开发时可用 `pnpm empty-font` 重新生成这些占位文件
- `src/FONTS/hans.ttf` 是内置默认简体字体(仅 preplace 版打包)
## 技术细节
### 字体挂载
模块把 5 个用户字体槽位挂载到系统字体文件:
| 槽位 | 用户文件 | 挂载的系统字体文件 | 回退逻辑(字体缺失时) |
| ----------- | ----------- | :------------------------------------------------------------------- | --------------------------- |
| 中文简体 | `hans.ttf` | `SysSans-Hans-Regular.ttf`、`SysFont-Static-Regular.ttf`、`SysFont-Myanmar.ttf`、`SysFont-Hans-Regular.ttf` | 拒绝安装和应用 |
| 中文繁体 | `hant.ttf` | `SysSans-Hant-Regular.ttf`、`SysFont-Hant-Regular.ttf` | 使用中文简体字体 `hans.ttf` |
| 英文 & 数字 | `en.ttf` | `SysSans-En-Regular.ttf`、`SysFont-Regular.ttf` | 使用中文简体字体 `hans.ttf` |
| 等宽字体 | `mono.ttf` | `DroidSansMono.ttf` | 不挂载 |
| Emoji 表情 | `emoji.ttf` | `NotoColorEmoji.ttf` | 不挂载 |
> 注:`SysFont-Regular.ttf` 是 `fonts.xml` 中 `sans-serif` 家族默认字体,由英文槽位填充
> (未设置时回退简体)。西文字体在配置中排在最前,中文字体自带的西文字形仅作兜底,
> 避免中文完全覆盖西文(issue #6)。
>
> 英文槽位在安装前会经 `fontmm-subset` 检测,含 CJK 字形时自动裁成拉丁子集
> (issue #10,见上节)。单字体子集为 `FONTS/.en-subset.ttf`,多字重模式为
> `FONTS/multi/en/.subset-<w>.ttf`,均属中转产物,不是用户槽位。
#### 多字重模式映射
`hans` / `hant` / `en` 支持通过 `FONTS/slot-modes.txt` 独立切换 `single` / `multi`,多字重源文件存放于 `FONTS/multi/<slot>/<100..900>.ttf`:
- **文件复用与扩展名**:`400` 档位(或无 `400` 时最接近 `400` 的档位)直接填充原有占位文件(如 `SysSans-Hans-Regular.ttf`),其余已选档位安装至 `system/fonts/FontMM-{Hans,Hant,En}-{100,200,300,500,600,700,800,900}.ttf`(已列入 Zygisk `kFontFiles[]`,按需预热),未选档位自动清理。
- **XML 静态映射与就近匹配**:`fontmm-wght` 读取 `FONTS/slot-modes.txt` 与 `FONTS/multi/`,为处于 `multi` 模式的家族生成不含 `<axis tag="wght"/>` 的静态 `<font>` 列表,缺失档位按 `NearestWeight` 指向最接近的已选字重;`hant` / `en` 未配置而回退 `hans` 多字重时,XML 直接指向 `hans` 的系统文件,不重复复制大字体。
- **往返切换幂等**:`customize.sh` / `apply.sh` 会在首次修改前把纯净 `system/etc/fonts.xml` 备份到 `backup/fonts.xml`,`fontmm-wght` 始终以该备份为基准重写 `fonts.xml` 并 `-sync` 到各派生配置,保证 `可变字体 <-> 多字重` 任意切换与混合模式完全可逆。
### 补充字库
模块内置一组 OFL-1.1 / MIT 许可的补充字体,作为 `fonts.xml` 末尾的全局 fallback,
兜底用户字体与系统字体未覆盖的字形(CJK 扩展区生僻字、最新 Unicode 字符、小篆等):
| 字体 | 说明 |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PlangothicP1/P2.ttf` | CJK 扩展区覆盖(Ext-B、G/H、**I、J** 等生僻字与新汉字) |
| `PlanschriftSeal-Regular.ttf` | **Seal(小篆)区块 11328 字符全覆盖**(Unicode 18 新增,子集化 34M;MIT/OFL 双许可,源自 [Planschrift_Project](https://github.com/Fitzgerald-Porthmouth-Koenigsegg/Planschrift_Project)) |
| `NotoSansPro.otf` | 多 Noto 家族合并,覆盖广泛语言字形 |
| `Unicode16/17/18-new.ttf` | Unicode 最新版本已定义字符覆盖 |
| `ZUno-Number.ttf` | 保留符号 / 私用区未定义符号显示编码信息 |
补充字库不参与用户槽位替换,仅在缺字形时按顺序兜底。字体来源与许可详见模块内
`system/fonts/LICENSE-*` 及 [MakeFontsGreatAgain](https://github.com/Numbersf/MakeFontsGreatAgain) 的 LICENSES。
### 工作原理
```
┌─────────────────────────────────────────────────────────┐
│ KernelSU 管理器 │
│ ┌──────────────────────────────┐ │
│ │ WebUI (web/ 构建产物) │ ksu.exec / toast │
│ └──────────────┬───────────────┘ │
└───────────────────┼─────────────────────────────────────┘
│ sh /data/adb/modules/FontMM/apply.sh
▼
┌───────────────────────┐ cp -f ┌──────────────────────┐
│ FONTS/ 用户字体 │ ──────────► │ system/fonts/ │
│ hans.ttf │ │ SysFont/SysSans 等 │
│ hant.ttf (可选) │ └──────────────────────┘
│ en.ttf (可选) │
└───────────────────────┘
```
1. **安装阶段**(`customize.sh`):系统检查(ColorOS 版本、KernelSU 元模块、Zygisk 环境)
→ 停用重叠的外部 Fontloader → 更新模式检测与旧字体/配置继承(含 `slot-modes.txt`、`wght-mode.txt`、`wght-map.txt` 与 `FONTS/multi/`)
→ 扫描设备系统 XML 生成派生字体配置并备份纯净 `backup/fonts.xml`
→ 调用 `apply.sh` 完成首次字体安装
2. **换字体阶段**(WebUI):选择文件 → 写入 `FONTS/slot-modes.txt` 与对应单/多字重文件(不删除另一模式已选文件)→ 调用同一个 `apply.sh`,两条路径行为一致
3. **`apply.sh` 核心逻辑**:按槽位模式把 `FONTS/` 或 `FONTS/multi/` 中的字体复制到 `system/fonts/`(缺失繁体/英文时回退简体;英文单/多字重均检测并裁掉 CJK 字形),随后统一调用 `fontmm-wght -sync` 生成单字体 `wght` 覆写与多字重静态 XML 映射
4. **字体生效**:ColorOS 通过 `/system/etc/fonts.xml` 等配置引用 `SysFont*` / `SysSans*` / `FontMM-*` 字体,
模块只内置 `fonts.xml` 主配置,各派生配置(`fonts_base.xml` / `fonts_ule.xml` /
`font_fallback.xml`)由安装时扫描设备系统 XML 生成(缺失时回退内置),统一经 `fontmm-wght -sync` 同步,提升跨 ColorOS 版本兼容性
5. **字体预加载**(`zygisk/arm64-v8a.so`):App 进程 specialize 前,模块把 FontMM 实际挂载的字体文件
预读进系统字体缓存(未设置的槽位或字重通过 `access()` 自动跳过),使被「卸载模块」的 App 仍能正常渲染字体
## 发布流程
**发布资产由 CI 构建,不要在本地打包后手动上传** —— `Release` 工作流在 release 发布时
(`on: release: [published]`)会重新构建并上传 `dist/*.zip` 与 `dist/*.zip.sha256`;
手动传一遍既慢又会被 CI 覆盖(本地 zip 的时间戳与 CI 不同,校验和也不一样)。
1. 改 `src/module.prop` 的 `version` / `versionCode`,同步 `update.json`(版本号与 `zipUrl`)
2. `changelog.md` 写本次条目:**相对上一个已发布版本的用户可见变化**,不必逐条罗列 commit
3. `pnpm check` → commit(`chore: 发布 vX (版本码)`)→ push → 等 `Build & Upload Artifacts` 通过
4. 打 tag 并推送:`git tag -a vX -m "FontMM vX" && git push origin vX`
5. 创建预发布(**不传文件**):
```bash
gh release create vX --title "vX" --notes-file /tmp/relnotes.md --prerelease
```
`Release` 工作流随即构建并上传 4 个资产(template / preplace 的 zip 与 `.sha256`)
6. 等 `Release` 工作流成功后,验证 `update.json` 的 `zipUrl` 可达(HTTP 200)——
资产上传完成前该链接是 404
> 本地 `pnpm build` 只用于本地测试与实机验证;发布产物一律以 CI 为准。
## 相关文档
- [README](./README.md) — 用户文档
- [changelog.md](./changelog.md) — 版本变更记录
+670 -17
View File
@@ -1,21 +1,674 @@
MIT License
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2026 Yule
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+143 -227
View File
@@ -1,265 +1,173 @@
<div align="center">
<img src="./docs/assets/logo.png" alt="FontMM" width="160" />
</div>
<h1 align="center">FontMM</h1>
<div align="center">
一个用于快速更换系统字体的 Magisk 模块,内置 WebUI 以及一些好用的功能
一个用于快速更换 ColorOS 字体的 Magisk 模块,内置 WebUI 以及一些好用的功能
</div>
<div align="center">
<a href="#特性">特性</a> | <a href="#安装">安装</a> | <a href="#使用">使用</a> | <a href="#技术细节">开发</a> | <a href="#致谢">致谢</a> | <a href="#许可">许可</a><br>
<a href="#特性">特性</a> | <a href="#安装">安装</a> | <a href="#使用">使用</a> | <a href="#常见问题">常见问题</a> | <a href="#致谢">致谢</a> | <a href="#许可">许可</a><br>
</div>
## 特性
<div align="center">
<table>
<tr>
<td align="center"><img src="./docs/assets/webui_主页.webp" alt="WebUI 主页" width="230" /></td>
<td align="center"><img src="./docs/assets/webui_配置.webp" alt="WebUI 字体配置(多字重)" width="230" /></td>
<td align="center"><img src="./docs/assets/webui_字体测试.webp" alt="WebUI 字体测试" width="230" /></td>
</tr>
<tr>
<td align="center">主页</td>
<td align="center">字体配置(多字重)</td>
<td align="center">字体测试</td>
</tr>
</table>
</div>
- Material 风格的管理界面,在支持 WebUI 的 Root 管理器中直接打开
- 多槽位字体分别选择,满足你的个性化需求
- 支持按槽位独立切换可变字体 / 多字重模式
- 可变字体 wght 范围与实际字重等级不符时可选择覆写配置,保证正确映射
- 内置字库补充字体,兜底 CJK 扩展区、Unicode 18.0 全覆盖
- 内置字体预加载,无需额外安装 Fontloader
## 支持环境
| 项目 | 要求 |
| ------- | ----------------------- |
| 系统 | >= ColorOS 16.0 |
| Root 环境 | Magisk 20.4+ / KernelSU |
| 字体格式 | `.ttf` |
| 项目 | 要求 |
| ------------------ | ----------------------- |
| 已测试的系统 | ColorOS 16 - 17 |
| 已测试的 Root 环境 | Magisk 20.4+ / KernelSU |
| 支持的字体格式 | `.ttf` |
## 安装
### 选择版本
> 安装完成后,请在系统设置中选择 Roboto 作为字体,这样才能得到正确的字重映射!
### 选择刷入包
每个 Release 提供两个压缩包,区别仅在于是否预置字体:
| 版本 | FONT 目录 | 适用场景 |
| ------------------ | ------------------------ | ----------------------------------------------- |
| `..._preplace.zip` | 含预置简体字体 `FONTS/hans.ttf` | **全新安装**:刷入后立即可用默认字体,随后可再在 WebUI 更换 |
| `..._template.zip` | `FONTS/` 为空目录 | **更新已有模块**:`customize.sh` 会自动从旧模块继承已设置的字体,包体积更小 |
- **首次安装**:用 `_preplace` 版,开箱即用;如果用 `_template` 版,刷入前需先在 `FONT/` 至少放置简体字体 `hans.ttf`,否则 `apply.sh` 会报错并拒绝安装
- **更新已安装的模块**:用 `_template` 版——更新模式会从旧模块的 `FONTS/` 目录继承已设置的字体,无需重新设置字体
### KernelSU 及其分支版本
> KernelSU 的分支版本包括但不限于:SukiSU Ultra, KernelSU Next, ReSukiSU
#### 元模块
如果您的 Root 管理器支持元模块,则必须预先安装一个有效的元模块,这样本模块才能成功挂载并生效,参见:[什么是元模块](https://kernelsu.org/zh_CN/guide/metamodule.html)。
目前经过测试可以与本模块兼容的元模块有:
- [mountify](https://github.com/backslashxx/mountify/releases)
#### 管理器配置
一般而言,如果你**正确安装了 Fontloader**,可以无需关闭「默认卸载模块」以及「卸载模块(内核级)」功能,**但我们始终建议关闭**,因为关闭后模块才能做到尽可能的全场景覆盖。
若您选择不关闭「默认卸载模块」以及「卸载模块(内核级)」功能,则被卸载的应用可能会出现字体不生效的情况,此时您可以通过 App Profile 功能单独关闭该应用的「卸载模块」选项,并重启应用。
### Magisk 及其分支版本
#### WebUI 支持
由于 Magisk 默认是不支持 WebUI 的,这意味着你需要安装一个外置的 WebUI 支持 App,比如:
- [WebUI X Portable](https://github.com/MMRLApp/WebUI-X-Portable)
- [KsuWebUI Standalone](https://github.com/5ec1cff/KsuWebUIStandalone)
### 通用依赖
#### Zygisk
因为 Fontloader 依赖于 Zygisk 进行运行,所以你需要安装一个可用的 Zygisk 实现,例如:
- [Zygisk Next](https://github.com/Dr-TSNG/ZygiskNext/releases)
- [ReZygisk](https://github.com/PerformanC/ReZygisk/releases)
**如果您选择使用 Zygisk Next,则还需要到其 WebUI 页面中将「排除列表策略」选项更改为「仅还原挂载」**。
#### Fontloader
**我们建议您在安装本模块前预先安装 Fontloader,否则可能出现应用闪退、开机卡第二屏、字体显示错误等严重错误**。
从 Android 12 起,系统加载字体的方式变为了在 App 启动时按需加载,这会导致被管理器卸载模块的 App 找不到字体文件,从而崩溃,**包括 Android 系统 App**。Fontloader 就是用来解决这个问题的,它会在 App 尚未失去字体访问权限时为 App 预加载字体。
由于 `RikkaW/FontLoader` 已经停更,推荐使用:
- [aviraxp/fontloader](https://github.com/KernelSU-Modules-Repo/fontloader/releases)
---
## 使用方法
### 通过 WebUI 更换字体(推荐)
#### 基础配置
1. 打开 KernelSU 或 WebUI 管理器,进入 FontMM 模块的 WebUI 界面,切换至「配置」页面
2. 在槽位中分别选择字体:
- **中文简体**:**必选**
- **中文繁体**:可选,未选择时自动使用简体
- **英文 & 数字**:可选,未选择时自动使用简体
- **等宽字体**:可选,未选择时不覆盖系统等宽字体
- **Emoji 表情**:可选,未选择时使用系统默认 Emoji
3. 点击「应用字体」,重启设备后生效
#### 高级配置
##### 字重覆写
当所选字体为可变字体时,可在配置页「字重覆写模式」选择字重映射的处理方式:
- **不处理**:默认,超出范围的字重由系统处理
- **裁切粗细等级**:删除范围外的字重条目
- **平均分配字重**:保留 9 档完整粗细,400 字重不变,两端按范围平均插值
- **自定义映射**:可以自定义 1-1000 字重的映射关系
### 手动放置字体
> 字体的 Fallback 逻辑同上
1. 把字体放入 `/data/adb/modules/FontMM/FONTS/`,命名规则:
- `hans.ttf`:中文简体(必选)
- `hant.ttf`:中文繁体(可选)
- `en.ttf`:英文与数字(可选)
- `mono.ttf`:等宽字体(可选)
- `emoji.ttf`:Emoji 表情(可选)
2. 执行 `sh /data/adb/modules/FontMM/apply.sh`
3. 重启设备
---
## 技术细节
### 字体挂载
模块把 5 个用户字体槽位挂载到系统字体文件:
| 槽位 | 用户文件 | 挂载的系统字体文件 | 回退逻辑(字体缺失时) |
| -------- | ----------- |:------------------------------------------------------------------------------------------------------------------------------ | ------------------- |
| 中文简体 | `hans.ttf` | `SysSans-Hans-Regular.ttf`、`SysFont-Static-Regular.ttf`、`SysFont-Myanmar.ttf`、`SysFont-Hans-Regular.ttf`、`SysFont-Regular.ttf` | 拒绝安装和应用 |
| 中文繁体 | `hant.ttf` | `SysSans-Hant-Regular.ttf`、`SysFont-Hant-Regular.ttf` | 使用中文简体字体 `hans.ttf` |
| 英文 & 数字 | `en.ttf` | `SysSans-En-Regular.ttf` | 使用中文简体字体 `hans.ttf` |
| 等宽字体 | `mono.ttf` | `DroidSansMono.ttf` | 不挂载 |
| Emoji 表情 | `emoji.ttf` | `NotoColorEmoji.ttf` | 不挂载 |
### 补充字库
模块内置一组 OFL-1.1 / MIT 许可的补充字体,作为 `fonts.xml` 末尾的全局 fallback,兜底用户字体与系统字体未覆盖的字形(CJK 扩展区生僻字、最新 Unicode 字符、小篆等):
| 字体 | 说明 |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PlangothicP1/P2.ttf` | CJK 扩展区覆盖(Ext-B、G/H、**I、J** 等生僻字与新汉字) |
| `PlanschriftSeal-Regular.ttf` | **Seal(小篆)区块 11328 字符全覆盖**(Unicode 18 新增,子集化 34M;MIT/OFL 双许可,源自 [Planschrift_Project](https://github.com/Fitzgerald-Porthmouth-Koenigsegg/Planschrift_Project)) |
| `NotoSansPro.otf` | 多 Noto 家族合并,覆盖广泛语言字形 |
| `Unicode16/17/18-new.ttf` | Unicode 最新版本已定义字符覆盖 |
| `ZUno-Number.ttf` | 保留符号 / 私用区未定义符号显示编码信息 |
补充字库不参与用户槽位替换,仅在缺字形时按顺序兜底。字体来源与许可详见模块内 `system/fonts/LICENSE-*` 及 [MakeFontsGreatAgain](https://github.com/Numbersf/MakeFontsGreatAgain) 的 LICENSES。
## 工作原理
```
┌─────────────────────────────────────────────────────────┐
│ KernelSU 管理器 │
│ ┌──────────────────────────────┐ │
│ │ WebUI (web/ 构建产物) │ ksu.exec / toast │
│ └──────────────┬───────────────┘ │
└───────────────────┼─────────────────────────────────────┘
│ sh /data/adb/modules/FontMM/apply.sh
▼
┌───────────────────────┐ cp -f ┌──────────────────────┐
│ FONTS/ 用户字体 │ ──────────► │ system/fonts/ │
│ hans.ttf │ │ SysFont/SysSans 等 │
│ hant.ttf (可选) │ └──────────────────────┘
│ en.ttf (可选) │
└───────────────────────┘
```
1. **安装阶段**(`customize.sh`):系统检查(ColorOS 版本、KernelSU 元模块、FontLoader)→ 更新模式检测与旧字体继承 → 调用 `apply.sh` 完成首次字体安装
2. **换字体阶段**(WebUI):选择文件 → 复制到 `FONTS/` → 调用同一个 `apply.sh`,两条路径行为一致
3. **`apply.sh` 核心逻辑**:按字体映射表把 `FONTS/` 中的字体复制到 `system/fonts/` 的对应文件,缺繁体/英文时回退简体
4. **字体生效**:ColorOS 通过 `/system/etc/fonts.xml` 等配置引用 `SysFont*` / `SysSans*` 字体族,模块内嵌从 ColorOS 16 提取的配置(`fonts.xml` 为唯一源,开发阶段自动生成 `fonts_base.xml` / `fonts_ule.xml` / `font_fallback.xml`),替换字体文件即可全局生效
## 开发指南
### 环境要求
- Node.js ≥ 18 + [pnpm](https://pnpm.io/)
- `zip` / `unzip`
- `shellcheck` + `shfmt`(仅 CI 检查需要)
- `Python 3` + `fontTools`(Unicode 覆盖测试)
- `Golang`
- 任意可运行 `ash` 的环境(验证 shell 脚本)
| 包名 | 内容 | 适用场景 |
| ------------------ | -------------------------------------------- | ------------------------------------------------------------ |
| `..._preplace.zip` | 含预置简体字体 `FONTS/hans.ttf`(OPPO Sans) | **全新安装**,刷入后开箱即用 |
| `..._template.zip` | `FONTS/` 为空目录 | **更新模块**,自动继承旧模块字体,包体积更小,若用此版全新安装,需自行在 `FONTS/` 至少放入简体字体 `hans.ttf`,否则安装会失败 |
### 安装依赖
```bash
pnpm install && cd web && pnpm install
按你的 Root 管理器完成下表配置:
| 依赖 | KernelSU 及分支 | Magisk 及分支 |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| **元模块** | 已测试:[mountify](https://github.com/backslashxx/mountify/releases), [hybrid_mount](https://github.com/Hybrid-Mount/meta-hybrid_mount)。若管理器支持元模块则**必须**安装,否则模块无法挂载。参见[什么是元模块](https://kernelsu.org/zh_CN/guide/metamodule.html)。 | 不需要 |
| **Zygisk** | [Zygisk Next](https://github.com/Dr-TSNG/ZygiskNext/releases) 或 [ReZygisk](https://github.com/PerformanC/ReZygisk/releases) | 在设置中启用内置 Zygisk |
| **WebUI 支持** | 管理器自带,无需额外安装 | 需外置 App:[WebUI X Portable](https://github.com/MMRLApp/WebUI-X-Portable) 或 [KsuWebUI Standalone](https://github.com/5ec1cff/KsuWebUIStandalone) |
补充说明:
- **Zygisk 只能启用一个**:Magisk 内置 Zygisk 与独立提供者不可同时启用。使用 ReZygisk 等独立实现时,请关闭 Magisk 内置 Zygisk。
- **Zygisk Next 用户**:需在其 WebUI 中把「排除列表策略」改为**仅还原挂载**。
<img src="./docs/assets/zygisk-next_仅还原挂载演示.webp" alt="Zygisk Next 排除列表策略设为仅还原挂载" width="460" />
- **管理器配置**:本模块已内置字体预加载,可以不必关闭「默认卸载模块」以及「卸载模块(内核级)」,**但仍建议关闭**——关闭后模块才能尽可能全场景覆盖。若选择不关闭,可用 App Profile 单独为某个应用关闭「卸载模块」并重启该应用。
> **不再需要 Fontloader**:**本模块已内置同款能力**。若你此前装过 Fontloader,刷入时会自动为其添加 `disable` 文件停用(不影响其数据,删除该文件即可恢复)。
## 使用
### 更换字体
1. 打开 Root 管理器的 WebUI,进入 FontMM,切到「配置」页
2. 在槽位中选择字体,然后点「应用字体」,重启设备生效
各槽位说明:
| 槽位 | 是否必选 | 未选择时 |
| --------------- | -------- | ------------------ |
| **中文简体** | **必选** | 无法应用 |
| **中文繁体** | 可选 | 自动使用简体 |
| **英文 & 数字** | 可选 | 自动使用简体 |
| **等宽字体** | 可选 | 不覆盖系统等宽字体 |
| **Emoji 表情** | 可选 | 使用系统默认 Emoji |
> **关于「英文 & 数字」槽位**:若所选字体本身自带中文字形(例如某些中文字体的英文版、或包含 CJK 的西文字体),应用时会**自动裁剪成纯拉丁子集**(多字重模式下也会对各档位分别裁剪)。系统字体配置里西文排在中文之前,不裁剪的话它自带的汉字会盖掉你选的中文字体,表现为"中文没换干净"。裁剪只影响西文槽位,中文字体不做处理,且会完整保留可变字体特性(字重轴不受影响)。
### 多字重模式(静态分档)
对于提供多个独立粗细文件(如 Thin / Light / Regular / Medium / Bold / Black)的字体家族,可在「配置」页的**中文简体、中文繁体、英文 & 数字**卡片右上角独立切换「**可变字体 | 多字重**」(等宽与 Emoji 保持单文件):
- **支持 9 档字重**:`100` 淡体、`200` 特细、`300` 细体、`400` 标准、`500` 适中、`600` 次粗、`700` 粗体、`800` 特粗、`900` 浓体
- **自由选档与自动补齐**:简体在多字重模式下至少选 1 档即可,未选的档位会在字体配置中自动指向最接近的已选字重;繁体 / 英文若在多字重模式下未选任何档位,则自动回退到简体设置
- **独立保留配置**:切换「可变字体 / 多字重」不会删除另一种模式下已选择的字体,可随时切回
- **自动禁用字重覆写**:当所有已配置的可变字体槽位均处于多字重模式(或无生效可变字体)时,「高级配置 → 字重覆写模式」会自动禁用;若混用(如中文多字重 + 英文可变字体),覆写仅对可变字体槽位生效
### 字重覆写(高级)
所选字体为**可变字体**时,若其 wght 轴范围与实际字重等级不符,可在「高级配置」中覆写映射:
| 模式 | 说明 |
| ---------------- | ----------------------------------------- |
| **不处理** | 默认,超出范围的字重由系统处理 |
| **裁切粗细等级** | 删除范围外的字重条目 |
| **平均分配字重** | 保留 9 档完整粗细,400 不变,两端平均插值 |
| **自定义映射** | 自行定义 1-1000 字重的映射关系 |
### 手动放置字体
也可以不经 WebUI,直接把字体放进 `/data/adb/modules/FontMM/FONTS/`:
| 文件名 | 用途 |
| ----------- | ---------------- |
| `hans.ttf` | 中文简体(必选) |
| `hant.ttf` | 中文繁体 |
| `en.ttf` | 英文与数字 |
| `mono.ttf` | 等宽字体 |
| `emoji.ttf` | Emoji 表情 |
若需手动使用多字重模式,可将对应字重放进 `FONTS/multi/<槽位>/<字重>.ttf`(`<槽位>` 为 `hans`/`hant`/`en`,`<字重>` 为 `100`–`900`),并在 `FONTS/slot-modes.txt` 中写入对应开关(如 `hans=multi`、`en=single`)。
之后执行 `sh /data/adb/modules/FontMM/apply.sh` 并重启设备。回退逻辑与 WebUI 一致。
### 校验模块完整性
校验模块内脚本与二进制是否被篡改或损坏:
```sh
sh /data/adb/modules/FontMM/tools/verify-sha256.sh
```
### 本地预览 WebUI
```bash
pnpm dev
```
`dev` 模式下 `ksu.ts` 使用内置 mock 文件系统,文件选择、槽位切换、应用字体全流程可脱离真机调试。
### 构建与打包
完整构建:
```bash
pnpm build
```
单独构建 WebUI 产物(调试用):
```bash
pnpm build:only-web # 产出 dist/webroot.zip
```
### 代码检查
> 前端 lint/format 由 [oxlint](https://oxc.rs/) 与 [oxfmt](https://oxc.rs/) 提供
```bash
pnpm lint # 前端 oxlint 检查
pnpm fmt # 前端 oxfmt 格式化
pnpm fmt:check # 前端 oxfmt 格式检查
bash dev/ci.sh # src/ 下所有 .sh 的 shellcheck + shfmt 检查
```
### Unicode 覆盖测试
> 本地模拟 `fonts.xml` 的 fallback 链,对照 Unicode Blocks.txt 统计每个区块覆盖率,首次运行会自动下载 Blocks.txt 缓存到 `dev/`
```bash
python3 dev/check-unicode-coverage.py # 全部区块
python3 dev/check-unicode-coverage.py "Archaic" "Seal" # 只测指定区块
```
### 占位字体机制
`src/system/fonts/` 下的 `SysFont*` / `SysSans*` 是 **0 字节占位文件**,避免把大字体文件提交进仓库;安装或应用字体时由 `apply.sh` 用 `FONTS/` 里的真实字体覆盖。
- 开发时可用 `dev/empty_font.sh` 重新生成这些占位文件
- `src/FONTS/hans.ttf` 是内置默认简体字体(仅 preplace 版打包)
GitHub Release 的 zip 附件旁均提供 `.sha256` 文件,可用 `sha256sum -c` 验证下载完整性。
## 常见问题
**Q:装完模块后字体没变?**
A:确认系统是 ColorOS 16+,并完成 [安装前的配置](#安装),记得重启
A:确认系统是 ColorOS 16+ 并已完成[安装依赖](#安装依赖),然后重启设备。
**Q:更新模块会丢失我设置好的字体吗?**
A:不会,检测到已安装的 FontMM 时会进入更新模式,从旧模块的 `FONTS/` 目录继承字体
A:不会。检测到已安装的 FontMM 时会进入更新模式,从旧模块的 `FONTS/` 继承字体。
**Q:首页显示「字体预热器未生效」怎么办?**
A:说明没检测到可用的 Zygisk 环境。被「卸载模块」的应用可能字体异常,请按[安装依赖](#安装依赖)配置 Zygisk。
**Q:需要额外安装 Fontloader 吗?**
A:不需要,本模块已内置字体预加载。
**Q:选了英文字体,为什么它的中文部分没生效?**
A:这是有意为之。西文字体若自带汉字,会盖掉你选的中文字体(系统配置里西文排在中文前面),因此应用时会自动裁掉其 CJK 部分,只保留拉丁字符。
**Q:我用了自带中文的英文字体,担心字重变少?**
A:不会。裁剪会完整保留可变字体的字重轴,字重覆写不受影响。
## 致谢
@@ -269,4 +177,12 @@ A:不会,检测到已安装的 FontMM 时会进入更新模式,从旧模
## 许可
[MIT License](./LICENSE)
[GNU General Public License v3.0](./LICENSE)
本模块内置的 Zygisk 字体预加载部分(`native/`)参考了 [FontLoader](https://github.com/JingMatrix/FontLoader) 的实现思路,
其上游 Zygisk Next 以 GPL-3.0 发布,故本项目整体采用 GPL-3.0。
`native/src/zygisk.hpp` 为 [topjohnwu](https://github.com/topjohnwu/zygisk-module-sample) 的宽松许可(MIT 式)头文件,可自由内联。
---
开发相关内容(构建、打包、技术细节)见 [DEVELOPMENT.md](./DEVELOPMENT.md)。
+63
View File
@@ -1,5 +1,68 @@
# Changelog
## v26.11.0-beta.1
- **新增「多字重模式」(按槽位独立切换)**(issue #25):为提供独立粗细文件(如 Thin / Light / Regular / Medium / Bold / Black)的静态字体包提供完整支持
- 「配置」页的**中文简体、中文繁体、英文 & 数字**槽位支持各自独立切换「**可变字体 | 多字重**」(等宽与 Emoji 保持单文件),支持多字重与可变字体混用
- 支持 `100`–`900` 标准 9 档字重,简体至少选择 1 档即可;缺失档位在字体配置中自动指向最接近的已选字重,繁体 / 英文未选任何字重时自动回退简体
- 两种模式各自保留已选字体,来回切换不丢失原配置
- 当无生效的单字体可变字体时,「高级配置 → 字重覆写模式」自动禁用;混用时仅对可变字体槽位生效
- 英文槽位在多字重模式下同样支持按档位自动裁剪 CJK 字形并显示子集大小徽标;「字体测试」页同步支持 100–900 多字重真实预览
- 模块更新时自动继承多字重字体目录与槽位模式、字重覆写配置;Zygisk 字体预热器同步适配多字重文件
## v26.8.0-beta.10
- **修复英文字体子集化实际未生效**(issue #12):汉字仍会盖掉中文字体。KernelSU 解压不保留 zip 里的执行位,工具在设备上是 0644,而脚本按 `-x` 判断可用性 → 每次都提示「找不到子集化工具」并跳过。改为按文件存在判断、执行前临时加执行位、用完还原;刷入时 `fontmm-wght` 的同类判断失效(派生字体配置未同步)一并修好
- **修复字体选择器**(issue #13):从 Download 目录返回会跳两级、在其它目录选中字体无效
- **英文槽位显示子集化结果**(issue #14):卡片上显示「原大小 → 子集大小」并加「已子集化」徽标,一眼能看出裁切生效了
- **修复字体测试页**:编辑测试文本时输入框出现空行(issue #16);可变字体滑条说明改为明确的「仅预览」措辞(issue #15)
- **修复清空槽位后字重映射轴范围不刷新**:删掉 200-900 的字体后仍被限制在 200-900
- **模块更新后保留用户设置**:字重覆写模式与自定义字重映射此前会在更新时丢失,现在随 `FONTS/` 一起继承
- **移除字体度量改写**:测试版尝试过的「固定行距 & 字距」会导致部分设备**开机失败**,已整体删除。模块不再改动字体本身的度量与包围盒 —— 换字体后行距跟着字体走
## v26.8.0-beta.8
- **修复只选中文(或任一单槽位)字体时 WebUI 状态全空**(issue #11):槽位与字重覆写被误判为未设置,实际字体已生效
- 成因:作为字体安装结果的判据,逐槽位复制脚本的最后一行条件失败导致整段退出码非 0
- 感谢 [@HelloCxin](https://github.com/HelloCxin) 提供详细的复现步骤
- **修复 Zygisk 提供者误判**:安装了 Zygisk Next 时,首页的字体预热器状态可能显示为另一个普通 Zygisk 模块(如 Hide My Applist)
- 成因:此前以 `zygisk/` 目录判定提供者,而该目录是任何 Zygisk 模块(含本模块自身的消费者角色)都有的标记
- 现改用提供者专有产物判定(`libzygisk.so` / `zygiskd` / `libzn_loader.so` 等),对照 Zygisk Next 实际安装包核实
- **仓库瘦身**:Pyodide 运行时(约 12MB)不再入库,改由构建脚本从 npm 依赖复制,消除仓库内一份易过期的混淆副本
## v26.8.0-beta.7
- **英文槽位自动子集化**(issue #10):所选英文字体若自带中文字形,应用时自动裁剪为纯拉丁子集
- 起因:`fonts.xml` 中西文家族排在中文之前,英文字体自带的汉字会盖掉中文字体,表现为「中文没换干净」;而 Android 的字体配置无法限定某字体只负责英文
- 只处理英文槽位,中文字体不动;子集化约 21ms,因此不做缓存,每次重算
- **完整保留可变字体特性**:`fvar` 字重轴、`gvar` 变形数据、`STAT` 与 `GSUB`/`GPOS`/`GDEF` 排版表均不丢失,字重覆写不受影响
- 工具异常(缺失/损坏/字体无法解析)一律回退为原字体,不阻断字体安装
- 实测效果:21.7MB 字体 → 223KB(默认保留拉丁/希腊/西里尔,避免缺字显示豆腐块)
- 新增设备端工具 `fontmm-subset`(harfbuzz 静态链接),WebUI 与手动放置字体两条路径均生效
## v26.8.0-beta.6
- **内置字体预加载,不再依赖 Fontloader**:把 Fontloader 的核心逻辑(约 200 行 C++)集成进模块(`native/`,产物 `zygisk/arm64-v8a.so`,6.8KB)
- 原理:App 进程 specialize 前调用 `Typeface.nativeWarmUpCache()` 把字体预读进系统缓存,使被「卸载模块」的 App 仍能正常渲染字体
- 只预热 FontMM 自己的字体(编译期常量表),无需 Fontloader 那样的 root companion 进程与 socket IPC
- 刷入时自动为已安装的外部 Fontloader 添加 `disable` 停用(保留其数据,删除该文件即可恢复)
- 不再要求用户预先安装 Fontloader(`RikkaW/FontLoader` 已删库,其余分支亦有停更风险)
- **Zygisk 环境检查**:替代原先的 Fontloader 版本检查,识别 Magisk 内置 Zygisk 与独立提供者(Zygisk Next / ReZygisk),缺失时提示而非阻断
- **首页显示字体预热器状态**:直接告知预加载是否生效、依赖哪个 Zygisk 提供者;未生效时说明原因与处理办法(预热失效不会报错,只表现为部分应用字体异常,用户难以自行定位)
- **许可证变更为 GPL-3.0**:因内置部分参考了 GPL-3.0 的 Fontloader 实现
- **构建流程由 shell 改为 Node 脚本**:`dev/*.sh` 全部重写为 `dev/*.mjs`,摆脱对 `zip`/`unzip` 的依赖,Windows / 精简容器 / CI 镜像均可构建
- 修复 Go 构建不可复现问题(`-trimpath -buildvcs=false`):原先产物哈希随构建目录与工作树状态变化
- 修复 SHA256 校验文件写绝对路径导致用户无法 `sha256sum -c` 校验
- 新增 `pnpm check` 结构校验(含预热字体清单与 `apply.sh` 的一致性检查)
- **修复小米主题字体工具**:搜索此前因响应解析结构与接口不符而恒无结果;下载按钮因未写入主题 ID 而始终失败
## v26.8.0-beta.5
- **修复中文字体完全覆盖西文字体**(issue #6):`SysFont-Regular.ttf` 改为英文槽位填充(未设置英文时仍回退简体),不再被中文字体占用,西文字形可正常显示
- **字重覆写覆盖全部生效家族**(issue #7):不再只改 `sans-serif`,同时覆写 `sys-sans-en` / `zh-Hans` / `zh-Hant` 家族,保证中英文一致映射
- **字重覆写只改一份配置**(issue #7):`fontmm-wght` 只修改 `fonts.xml` 主配置,再 `-sync` 同步到各派生配置;派生配置不再打包进模块,改由刷入脚本(`customize.sh`)扫描设备系统 XML 生成,提升跨 ColorOS 版本兼容性
- **SHA256 完整性校验**(issue #8):新增 `dev/gen-sha256.sh` 生成可执行文件校验(随模块打包),设备端 `tools/verify-sha256.sh` 一键校验;GitHub Release/CI 产物附带 `*.sha256` 校验文件
## v26.8.0-beta.4
- **字重范围覆写**(可变字体映射引擎,Go 方案):可变字体 wght 轴范围与实际字重等级不符时,可视化覆写 `sans-serif` 配置
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env node
// dev/build-subset.mjs — 编译 fontmm-subset (英文字体子集化工具, issue #10)
//
// 产物输出到 src/tools/fontmm-subset, 随模块 zip 打包, 由 apply.sh 在设备端调用。
// 依赖 harfbuzz 的 subset API (静态链接), 源码与编译产物均带缓存, 详见 dev/lib/harfbuzz.mjs。
//
// 用法: node dev/build-subset.mjs
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log, die } from './lib/log.mjs';
import { ROOT, SRC_DIR } from './lib/paths.mjs';
import { findNdk } from './lib/ndk.mjs';
import { buildSubsetTool, HARFBUZZ_VERSION } from './lib/harfbuzz.mjs';
const ndkRoot = await findNdk();
if (!ndkRoot) {
die(
'未找到 Android NDK。请设置 ANDROID_NDK_HOME, 或下载到 ~/opt/android-ndk-r27c\n' +
' 下载: https://developer.android.com/ndk/downloads',
);
}
log.info(`NDK: ${ndkRoot}`);
log.info(`harfbuzz: ${HARFBUZZ_VERSION}`);
const out = path.join(SRC_DIR, 'tools', 'fontmm-subset');
const size = await buildSubsetTool(ndkRoot, out);
// 保证可执行位: 打包时按磁盘权限位写入 zip, 设备端才能直接运行
await fsp.chmod(out, 0o755);
log.ok(`产物: ${path.relative(ROOT, out)} (${(size / 1048576).toFixed(1)}MB)`);
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env node
// dev/build-wght.mjs — 交叉编译 fontmm-wght (Go -> android/arm64, 无需 NDK)
// 产物输出到 src/tools/fontmm-wght, 随模块 zip 打包 (与 mi-font-download.sh 等工具脚本同层)
//
// 说明: Go 的 android 目标无需 NDK (CGO_ENABLED=0), 产物是静态链接的 arm64 ELF,
// 可直接在设备的 shell 中执行。
//
// 可复现构建: 见 dev/lib/go.mjs 中的 GO_BUILD_FLAGS 说明。若不加 -trimpath 与
// -buildvcs=false, Go 会把源码绝对路径和 VCS 状态嵌进二进制, 使同一份源码在不同
// 目录构建、或工作树有未提交改动时产物哈希不同, 导致 SHA256SUMS 随构建环境漂移。
//
// 用法: node dev/build-wght.mjs
import { log, die } from './lib/log.mjs';
import { hasCommand } from './lib/exec.mjs';
import { buildWght, wghtBinRel } from './lib/go.mjs';
if (!hasCommand('go')) die('未找到 go 命令, 请先安装 Go 工具链');
log.step('交叉编译 fontmm-wght (android/arm64)...');
const size = await buildWght();
log.ok(`产物: ${wghtBinRel()} (${size} 字节)`);
-10
View File
@@ -1,10 +0,0 @@
#!/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) 字节)"
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env node
// dev/build-zygisk.mjs — 交叉编译 Zygisk 模块 (C++ -> arm64-v8a.so)
//
// 产物输出到 src/zygisk/<abi>.so, 随模块 zip 打包。Zygisk 加载器按约定路径
// /data/adb/modules/<模块名>/zygisk/<abi>.so 查找模块, 因此文件名必须精确匹配
// (Magisk 与 ReZygisk 等实现均使用 ABI 全名, 如 arm64-v8a.so)。
//
// 需要 Android NDK。设置 ANDROID_NDK_HOME 指定, 或放到常见位置 (见 dev/lib/ndk.mjs)。
//
// 用法: node dev/build-zygisk.mjs
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log, die } from './lib/log.mjs';
import { ROOT, SRC_DIR } from './lib/paths.mjs';
import { findNdk, buildZygiskModule, TARGET_ABI } from './lib/ndk.mjs';
const ndkRoot = await findNdk();
if (!ndkRoot) {
die(
'未找到 Android NDK。请设置 ANDROID_NDK_HOME, 或下载到 ~/opt/android-ndk-r27c\n' +
' 下载: https://developer.android.com/ndk/downloads',
);
}
log.info(`NDK: ${ndkRoot}`);
log.step(`交叉编译 Zygisk 模块 (android/${TARGET_ABI})...`);
const { outFile, size } = await buildZygiskModule(ndkRoot, {
onLog: (m) => log.info(m),
});
// 复制到模块目录 (打包时按此路径收录)
const destDir = path.join(SRC_DIR, 'zygisk');
const dest = path.join(destDir, `${TARGET_ABI}.so`);
await fsp.mkdir(destDir, { recursive: true });
await fsp.copyFile(outFile, dest);
// 库文件不需要执行位, 但需要可读
await fsp.chmod(dest, 0o644);
log.ok(`产物: ${path.relative(ROOT, dest)} (${size} 字节)`);
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env node
// dev/cache.mjs — 预压缩缓存管理
//
// 用法:
// node dev/cache.mjs status 查看缓存状态 (片段/大小/文件数/建立时间)
// node dev/cache.mjs clean 清空缓存
// node dev/cache.mjs test 校验缓存可用性: 用缓存重建一遍并与源文件逐条比对
//
// 缓存由 dev/pack.mjs 在打包时自动建立与复用; 本脚本仅用于查看/清理/校验。
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log, die } from './lib/log.mjs';
import { ROOT, SRC_DIR } from './lib/paths.mjs';
import { indexZip, hashFile } from './lib/zip.mjs';
import { cacheStatus, clearCache, CACHE_DIR } from './lib/zipcache.mjs';
const cmd = process.argv[2] ?? 'status';
const mb = (n) => `${(n / 1048576).toFixed(1)}MB`;
if (cmd === 'status') {
const list = await cacheStatus();
if (list.length === 0) {
log.info(`无缓存 (${path.relative(ROOT, CACHE_DIR)} 不存在或为空)`);
log.detail('下次运行 pnpm run pack 会自动建立');
process.exit(0);
}
log.step(`缓存目录: ${path.relative(ROOT, CACHE_DIR)}`);
for (const c of list) {
const flag = c.usable ? '✓ 可用' : '✗ 不可用 (将回退现场压缩)';
log.detail(`[${c.segment}] ${flag}`);
log.detail(` 大小 ${mb(c.size)} 含 ${c.files} 个文件 建立于 ${c.createdAt ?? '未知'}`);
}
process.exit(0);
}
if (cmd === 'clean') {
await clearCache();
log.ok('缓存已清空');
process.exit(0);
}
if (cmd === 'test') {
// 校验: 把缓存里的每个条目解压出来, 与源文件比对内容
const list = await cacheStatus();
if (list.length === 0) die('无缓存可校验');
let failures = 0;
for (const c of list.filter((x) => x.usable)) {
const segZip = path.join(CACHE_DIR, `${c.segment}.zip`);
log.step(`校验片段 ${c.segment} (${mb(c.size)})...`);
const index = await indexZip(segZip);
let checked = 0;
for (const [rel, info] of index) {
if (info.isDir) continue;
const src = path.join(SRC_DIR, rel);
let expected;
try {
expected = hashFile(src);
} catch {
log.fail(`源文件不存在: ${rel}`);
failures++;
continue;
}
if (expected !== info.sha256) {
log.fail(`内容不一致: ${rel}`);
failures++;
}
checked++;
}
log.ok(` ${c.segment}: ${checked} 个文件全部与源文件一致`);
}
if (failures > 0) die(`${failures} 项校验失败`);
log.ok('缓存校验通过');
process.exit(0);
}
die(`未知命令: ${cmd} (可用: status / clean / test)`);
-85
View File
@@ -1,85 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# dev/cd.sh — 打包 FontMM 模块 (preplace / template 两版)
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC_DIR="$ROOT_DIR/src"
DIST_DIR="$ROOT_DIR/dist"
PROP_FILE="$SRC_DIR/module.prop"
command -v zip >/dev/null 2>&1 || {
echo "[!] 未找到 zip 命令, 请先安装" >&2
exit 1
}
# 1. 从 module.prop 读版本号: version=26.8.0-beta.1(260800001)
VERSION="$(sed -n 's/^version=//p' "$PROP_FILE" 2>/dev/null | head -n 1 | tr -d '\r' || true)"
if [ -z "$VERSION" ]; then
echo "[!] 无法从 $PROP_FILE 读取 version 字段" >&2
exit 1
fi
# 文件名安全化: 括号 -> 点 (GitHub Release 网页上传会把括号改写为点, 导致 URL 不一致)
# 26.8.0-beta.1(260800001) -> 26.8.0-beta.1.260800001
FILE_VERSION="$(printf '%s' "$VERSION" | sed 's/(/./g; s/)//g')"
PRE_OUT="$DIST_DIR/FontMM_v${FILE_VERSION}_preplace.zip"
TPL_OUT="$DIST_DIR/FontMM_v${FILE_VERSION}_template.zip"
mkdir -p "$DIST_DIR"
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() {
local out="$1" extra="${2:-}"
local args=(-r -2 "$out" . -x '*.git*' -x '*.DS_Store' -x '*.swp' -x '*~' -x '*.bak')
if [ -n "$extra" ]; then
args+=(-x "$extra")
fi
(
cd "$SRC_DIR"
zip "${args[@]}"
)
}
echo "[*] 打包 preplace 版 (含预置字体)..."
pack "$PRE_OUT"
echo "[*] 打包 template 版 (FONT 目录为空)..."
pack "$TPL_OUT" 'FONTS/*'
# -x 'FONTS/*' 会连目录条目一起排除, 这里补回空的 FONTS/ 目录
(
cd "$SRC_DIR"
zip -g "$TPL_OUT" 'FONTS/'
)
# 3. 产物校验: 必须含 module.prop, 防止打包错目录
# 注意: 不能用 grep -q, 它匹配后立即退出会使上游 unzip 收到 SIGPIPE (141),
# 在 pipefail 下整个管道被判失败, 产生"缺少 module.prop"的偶发误报
check() {
local out="$1"
if ! unzip -l "$out" | grep 'module\.prop' >/dev/null; then
echo "[!] 打包产物缺少 module.prop: $out" >&2
exit 1
fi
}
check "$PRE_OUT"
check "$TPL_OUT"
# 4. template 版校验: FONTS 目录必须不含字体文件 (保留空目录)
if unzip -l "$TPL_OUT" | grep 'FONTS/.*\.ttf' >/dev/null; then
echo "[!] template 版不应包含 FONTS 字体文件" >&2
exit 1
fi
echo "[✓] 打包完成:"
echo " preplace: $PRE_OUT ($(du -h "$PRE_OUT" | cut -f1))"
echo " template: $TPL_OUT ($(du -h "$TPL_OUT" | cut -f1))"
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env node
// dev/ci.mjs — 代码检查 (取代 ci.sh)
//
// 检查分两层:
// 1. Node 原生检查 (始终运行, 无需任何外部工具): 关键文件结构、XML 合法性、
// module.prop 字段、apply.sh 字体映射与占位文件的一致性等
// 2. shell 静态检查: 若 PATH 中存在 shellcheck / shfmt 则一并运行
// (CI 中用 --strict 强制要求, 缺失即失败)
//
// 之所以不在 npm 里包装 shellcheck: 它的 npm 包只是下载器, 会从 GitHub Releases
// 拉取二进制, 在受限网络/限流下会失败 —— 这恰恰是要摆脱的不确定性。
//
// 用法: node dev/ci.mjs [--strict]
// --strict: shellcheck / shfmt 缺失时报错退出 (CI 使用)
import fsp from 'node:fs/promises';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { log, die } from './lib/log.mjs';
import { ROOT, SRC_DIR, WEB_DIR, MODULE_PROP, FONTS_XML, DERIVED_XML_RELS, NATIVE_DIR } from './lib/paths.mjs';
import { run, hasCommand } from './lib/exec.mjs';
const strict = process.argv.includes('--strict');
let failures = 0;
function check(name, fn) {
return Promise.resolve()
.then(fn)
.then(() => log.ok(name))
.catch((e) => {
log.fail(`${name}: ${e.message}`);
failures++;
});
}
/** 递归收集目录下匹配的文件 (相对路径, `/` 分隔) */
async function collect(dir, match, skipDirs = []) {
const out = [];
async function recurse(current) {
let items;
try {
items = await fsp.readdir(current, { withFileTypes: true });
} catch {
return;
}
for (const item of items) {
if (item.isDirectory()) {
if (skipDirs.includes(item.name)) continue;
await recurse(path.join(current, item.name));
} else if (item.isFile() && match(item.name)) {
out.push(path.relative(dir, path.join(current, item.name)).split(path.sep).join('/'));
}
}
}
await recurse(dir);
return out.sort();
}
// ---------------- 1. Node 原生检查 ----------------
// module.prop 必需字段 (id/name/version/versionCode/author/description)
await check('module.prop 字段完整', async () => {
const text = await fsp.readFile(MODULE_PROP, 'utf8');
const keys = new Map();
for (const line of text.split('\n')) {
const idx = line.indexOf('=');
if (idx > 0) keys.set(line.slice(0, idx).trim(), line.slice(idx + 1).trim());
}
const required = ['id', 'name', 'version', 'versionCode', 'author', 'description'];
const missing = required.filter((k) => !keys.get(k));
if (missing.length) throw new Error(`缺少字段: ${missing.join(', ')}`);
if (keys.get('id') !== 'FontMM') throw new Error(`id 应为 FontMM, 实际 ${keys.get('id')}`);
if (!/^\d+$/.test(keys.get('versionCode'))) {
throw new Error(`versionCode 必须为纯数字: ${keys.get('versionCode')}`);
}
});
// fonts.xml 必须是合法 XML (设备端解析失败会导致无法开机)
await check('fonts.xml 为合法 XML', async () => {
const text = await fsp.readFile(FONTS_XML, 'utf8');
// 轻量标签配对检查: 去掉注释与声明后, 校验 <familyset> 与内部 <family>/<font> 的配对。
// 不引入 XML 解析依赖 (设备端是 libexpat, 严格但容错策略不同), 这里只抓最常见的标签失衡。
const stripped = text.replace(/<!--[\s\S]*?-->/g, '').replace(/<\?[\s\S]*?\?>/g, '');
const opens = (stripped.match(/<family[ >]/g) ?? []).length;
const closes = (stripped.match(/<\/family>/g) ?? []).length;
if (opens !== closes) {
throw new Error(`<family> 标签失衡: ${opens} 个开始 / ${closes} 个结束`);
}
if (!/<familyset[\s>]/.test(stripped)) throw new Error('缺少 <familyset> 根元素');
if (!/<\/familyset>/.test(stripped)) throw new Error('缺少 </familyset> 结束标签');
if (!/name="sans-serif"/.test(stripped)) throw new Error('缺少 sans-serif 家族');
});
// 派生配置不应被提交 (由设备端 customize.sh 生成, 打包时也会自动排除)
// 本地调试时可能存在 (dev/sync-fonts-xml.mjs 生成), 因此只提示不报错;
// 真正要拦的是「被 git 跟踪」——那才会让派生配置随仓库分发出去。
await check('派生字体配置未被 git 跟踪', async () => {
const tracked = [];
for (const rel of DERIVED_XML_RELS) {
const { stdout } = spawnSync('git', ['ls-files', '--error-unmatch', `src/${rel}`], {
cwd: ROOT,
encoding: 'utf8',
});
if (stdout && stdout.trim()) tracked.push(rel);
}
if (tracked.length) {
throw new Error(`以下派生配置被 git 跟踪, 应删除并加入 .gitignore: ${tracked.join(', ')}`);
}
// 本地存在但未跟踪: 属于正常调试状态, 只提示
const present = [];
for (const rel of DERIVED_XML_RELS) {
try {
await fsp.access(path.join(SRC_DIR, rel));
present.push(rel);
} catch {
// 不存在
}
}
if (present.length) {
log.info(`检测到本地生成的派生配置 ${present.length} 个 (未跟踪, 打包时会自动排除)`);
}
});
// apply.sh 的占位字体映射 与 empty-font.mjs 的占位清单 必须一致
//
// apply.sh 里有三类单引号字体名:
// 1. 多行的基础占位赋值 (hans_fonts/hant_fonts/en_fonts) —— 0 字节占位文件,
// 必须与 empty-font.mjs 的 PLACEHOLDERS 一一对应
// 2. 多字重扩展文件名 (FontMM-{Hans,Hant,En}-{100..900}.ttf) —— 按需生成,
// 不经过占位机制, 不属于 PLACEHOLDERS, 但必须被 Zygisk 预热清单覆盖
// 3. 单行的系统字体名 (DroidSansMono.ttf / NotoColorEmoji.ttf) —— 直接替换系统
// 字体文件, 不经过占位机制, 不属于占位清单
await check('apply.sh 占位映射与占位清单一致', async () => {
const applySh = await fsp.readFile(path.join(SRC_DIR, 'apply.sh'), 'utf8');
const mapped = new Set();
for (const m of applySh.matchAll(/'([^']*)'/g)) {
const value = m[1];
if (!value.includes('\n')) continue; // 跳过单行字体名
for (const line of value.split('\n')) {
const name = line.trim();
if (name.endsWith('.ttf') && !name.startsWith('FontMM-')) mapped.add(name);
}
}
if (mapped.size === 0) throw new Error('未从 apply.sh 解析到占位字体列表 (解析逻辑可能已失效)');
const emptyFont = await fsp.readFile(path.join(ROOT, 'dev', 'empty-font.mjs'), 'utf8');
const decl = emptyFont.match(/const PLACEHOLDERS = \[([\s\S]*?)\];/);
if (!decl) throw new Error('empty-font.mjs 中未找到 PLACEHOLDERS 列表');
const placeholders = new Set(
(decl[1].match(/'([^']+\.ttf)'/g) ?? []).map((s) => s.slice(1, -1)),
);
const onlyInApply = [...mapped].filter((n) => !placeholders.has(n));
const onlyInPlaceholders = [...placeholders].filter((n) => !mapped.has(n));
if (onlyInApply.length) {
throw new Error(`apply.sh 使用了未列入占位清单的字体: ${onlyInApply.join(', ')}`);
}
if (onlyInPlaceholders.length) {
throw new Error(`占位清单中的字体未被 apply.sh 使用: ${onlyInPlaceholders.join(', ')}`);
}
});
// Zygisk 预加载的字体清单必须覆盖 apply.sh 会替换的全部字体文件。
// 两者若不一致, 缺失的字体在 DenyList 应用里会静默渲染失败, 问题极难定位。
await check('Zygisk 预热字体清单与 apply.sh 一致', async () => {
const applySh = await fsp.readFile(path.join(SRC_DIR, 'apply.sh'), 'utf8');
// apply.sh 会写入 system/fonts/ 的全部文件名:
// 1. 占位字体 (hans/hant/en 三组多行列表)
// 2. 直接替换的系统字体 (DroidSansMono / NotoColorEmoji, 单行)
const expected = new Set();
for (const m of applySh.matchAll(/'([^']*)'/g)) {
const value = m[1];
const lines = value.includes('\n') ? value.split('\n') : [value];
for (const line of lines) {
const name = line.trim();
// 只看形如 xxx.ttf 的纯文件名 (排除含路径或变量的内容)
if (/^[A-Za-z0-9_-]+\.ttf$/.test(name)) expected.add(name);
}
}
if (expected.size === 0) throw new Error('未从 apply.sh 解析到字体文件名 (解析逻辑可能已失效)');
const cpp = await fsp.readFile(path.join(NATIVE_DIR, 'src', 'fontmm.cpp'), 'utf8');
const block = cpp.match(/kFontFiles\[\]\s*=\s*\{([\s\S]*?)\};/);
if (!block) throw new Error('fontmm.cpp 中未找到 kFontFiles 列表');
const actual = new Set(
[...block[1].matchAll(/"\/system\/fonts\/([A-Za-z0-9_-]+\.ttf)"/g)].map((m) => m[1]),
);
const missing = [...expected].filter((n) => !actual.has(n));
const extra = [...actual].filter((n) => !expected.has(n));
if (missing.length) {
throw new Error(`fontmm.cpp 缺少以下字体的预热 (apply.sh 会替换它们): ${missing.join(', ')}`);
}
if (extra.length) {
throw new Error(`fontmm.cpp 预热了 apply.sh 不会替换的字体: ${extra.join(', ')}`);
}
});
// 前端脚本引用的 dev 入口必须存在 (避免重命名后 package.json 指向不存在的文件)
await check('package.json 中引用的 dev 脚本存在', async () => {
const pkg = JSON.parse(await fsp.readFile(path.join(ROOT, 'package.json'), 'utf8'));
const missing = [];
for (const [name, cmd] of Object.entries({ ...pkg.scripts })) {
for (const m of cmd.matchAll(/node\s+(\S+\.mjs)/g)) {
const target = path.join(ROOT, m[1]);
try {
await fsp.access(target);
} catch {
missing.push(`${name} -> ${m[1]}`);
}
}
}
if (missing.length) throw new Error(`引用了不存在的脚本: ${missing.join(', ')}`);
});
// ---------------- 2. shell 静态检查 ----------------
const shFiles = await collect(SRC_DIR, (n) => n.endsWith('.sh'), ['webroot']);
log.step(`src/ 下共 ${shFiles.length} 个 shell 脚本`);
if (hasCommand('shellcheck')) {
await check(`shellcheck (${shFiles.length} 个文件)`, () => {
run('shellcheck', shFiles.map((f) => path.join(SRC_DIR, f)), { cwd: ROOT });
});
} else if (strict) {
log.fail('未找到 shellcheck (--strict 要求必须存在)');
failures++;
} else {
log.warn('未找到 shellcheck, 跳过 (安装后自动启用)');
}
if (hasCommand('shfmt')) {
// -d: 只报告格式差异, 不修改文件 (与 checks 语义一致)
await check('shfmt 格式检查', () => {
run('shfmt', ['-i', '4', '-d', ...shFiles.map((f) => path.join(SRC_DIR, f))], { cwd: ROOT });
});
} else if (strict) {
log.fail('未找到 shfmt (--strict 要求必须存在)');
failures++;
} else {
log.warn('未找到 shfmt, 跳过 (安装后自动启用)');
}
// ---------------- 3. 前端检查 ----------------
if (hasCommand('pnpm')) {
await check('前端 lint (oxlint)', () => {
run('pnpm', ['-C', WEB_DIR, 'lint'], { cwd: ROOT });
});
await check('前端格式检查 (oxfmt)', () => {
run('pnpm', ['-C', WEB_DIR, 'fmt:check'], { cwd: ROOT });
});
await check('前端类型检查 (tsc)', () => {
run('pnpm', ['-C', WEB_DIR, 'type-check'], { cwd: ROOT });
});
} else if (strict) {
log.fail('未找到 pnpm, 无法运行前端检查');
failures++;
} else {
log.warn('未找到 pnpm, 跳过前端检查');
}
// ---------------- 结果 ----------------
console.log();
if (failures > 0) {
die(`${failures} 项检查未通过`);
}
log.ok('全部检查通过');
-38
View File
@@ -1,38 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$SCRIPT_DIR"
# ---------- Termux 兼容 ----------
# Termux 的 shellcheck / shfmt 安装在 app 私有目录, 需手动加入 PATH 与 LD_LIBRARY_PATH;
# 其他环境 (Linux/macOS 等) 直接使用系统 PATH 中的工具
if [ -n "${PREFIX:-}" ] && [ -d "$PREFIX/bin" ]; then
export PATH="$PREFIX/bin:${PATH}"
export LD_LIBRARY_PATH="$PREFIX/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
elif [ -d /data/user/0/com.termux/files/usr/bin ]; then
export PATH="/data/user/0/com.termux/files/usr/bin:${PATH}"
export LD_LIBRARY_PATH="/data/user/0/com.termux/files/usr/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
fi
# 工具可用性检查
command -v shellcheck > /dev/null 2>&1 || {
echo "[!] 未找到 shellcheck, 请先安装" >&2
exit 1
}
command -v shfmt > /dev/null 2>&1 || {
echo "[!] 未找到 shfmt, 请先安装" >&2
exit 1
}
shopt -s nullglob globstar
files=("$SCRIPT_DIR/src"/**/*.sh)
for f in "${files[@]}"; do
echo "> Checking: $f"
shellcheck "$f" || exit 1
done
for f in "${files[@]}"; do
echo "> Formatting: $f"
shfmt -i 4 -w -d "$f"
done
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env node
// dev/empty-font.mjs — 生成系统字体占位文件 (取代 empty_font.sh)
//
// src/system/fonts/ 下的 SysFont* / SysSans* 是 0 字节占位文件, 避免把大字体提交进仓库;
// 安装或应用字体时由 apply.sh 用 FONTS/ 里的真实字体覆盖。
// 开发过程中这些占位文件可能被真实字体覆盖, 用本脚本重新置空。
//
// 用法: node dev/empty-font.mjs
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log } from './lib/log.mjs';
import { SRC_DIR } from './lib/paths.mjs';
const FONT_DIR = path.join(SRC_DIR, 'system', 'fonts');
// 需要置空的占位文件 (与 src/apply.sh 的映射表保持一致)
const PLACEHOLDERS = [
'SysSans-Hans-Regular.ttf',
'SysFont-Static-Regular.ttf',
'SysFont-Myanmar.ttf',
'SysFont-Hans-Regular.ttf',
'SysFont-Regular.ttf',
'SysSans-Hant-Regular.ttf',
'SysFont-Hant-Regular.ttf',
'SysSans-En-Regular.ttf',
];
await fsp.mkdir(FONT_DIR, { recursive: true });
for (const name of PLACEHOLDERS) {
const file = path.join(FONT_DIR, name);
// 写入空内容 (等价于 shell 的 `: > file`)
await fsp.writeFile(file, '');
log.step(`已生成空字体: ${name}`);
}
log.ok(`完成, 共 ${PLACEHOLDERS.length} 个空字体 -> ${path.relative(process.cwd(), FONT_DIR)}`);
-27
View File
@@ -1,27 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
FONT_DIR="$SCRIPT_DIR/src/system/fonts"
# 字体清单(记得和 customize.sh 保持一致)
all_fonts='SysSans-Hans-Regular.ttf
SysFont-Static-Regular.ttf
SysFont-Myanmar.ttf
SysFont-Hans-Regular.ttf
SysFont-Regular.ttf
SysSans-Hant-Regular.ttf
SysFont-Hant-Regular.ttf
SysSans-En-Regular.ttf'
mkdir -p "$FONT_DIR"
count=0
while IFS= read -r font; do
[ -z "$font" ] && continue
: > "$FONT_DIR/$font"
echo "[*] 已生成空字体: $font"
count=$((count + 1))
done <<< "$all_fonts"
echo "[✓] 完成,共 $count 个空字体 -> $FONT_DIR"
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env node
// dev/gen-sha256.mjs — 生成 SHA256 校验文件 (取代 gen-sha256.sh)
//
// 1. src/SHA256SUMS: 模块内可执行文件 (脚本/二进制) 的 sha256, 随 zip 打包,
// 供设备端 tools/verify-sha256.sh 一键校验
// 2. dist/*.zip.sha256: 发布产物的 sha256, 作为 Release 资产
//
// 用法: node dev/gen-sha256.mjs [--no-dist]
// --no-dist: 只生成 src/SHA256SUMS (供 pack.mjs 打包前调用; 此时 dist 产物尚未生成)
//
// 注意: 校验文件中只写**文件名**而非绝对路径。原实现用 `sha256sum "$abs_path"`,
// 会把打包机的绝对路径写进校验文件, 导致用户下载后无法用 `sha256sum -c` 校验
// (CI 里又写成 dist/xxx.zip 相对路径, 与本地不一致)。统一为 basename 后,
// 只要 zip 与 .sha256 放在同一目录即可直接校验。
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log } from './lib/log.mjs';
import { SRC_DIR, DIST_DIR } from './lib/paths.mjs';
import { hashFile } from './lib/zip.mjs';
const noDist = process.argv.includes('--no-dist');
/** 模块内需要校验的文件: shell 脚本 + 模块二进制 + Zygisk 库 + Magisk 安装脚本 */
const SUM_PATTERNS = [
(name) => name.endsWith('.sh'),
(name) => name === 'fontmm-wght',
(name) => name === 'fontmm-subset',
(name) => name.endsWith('.so'), // Zygisk 模块 (zygisk/arm64-v8a.so)
(name) => name === 'update-binary',
(name) => name === 'updater-script',
];
/** 递归收集待校验文件 (排除 webroot: 那是构建产物, 体积大且每次不同) */
async function collectFiles(root) {
const out = [];
async function recurse(dir) {
const items = await fsp.readdir(dir, { withFileTypes: true });
for (const item of items) {
const abs = path.join(dir, item.name);
if (item.isDirectory()) {
if (item.name === 'webroot') continue;
await recurse(abs);
} else if (item.isFile() && SUM_PATTERNS.some((fn) => fn(item.name))) {
out.push(abs);
}
}
}
await recurse(root);
// 稳定排序: 大小写不敏感优先 (与原 `find | sort` 的字典序一致), 相同时再按原文比较。
// 不用 localeCompare: 其结果依赖运行环境的 locale, 会造成产物不可复现。
return out.sort((a, b) => {
const la = a.toLowerCase();
const lb = b.toLowerCase();
if (la !== lb) return la < lb ? -1 : 1;
return a < b ? -1 : a > b ? 1 : 0;
});
}
/** 生成模块内可执行文件校验表 (src/SHA256SUMS) */
async function genModuleSums() {
const files = await collectFiles(SRC_DIR);
const lines = [];
for (const abs of files) {
const rel = path.relative(SRC_DIR, abs).split(path.sep).join('/');
lines.push(`${hashFile(abs)} ${rel}`);
}
const out = path.join(SRC_DIR, 'SHA256SUMS');
await fsp.writeFile(out, `${lines.join('\n')}\n`, 'utf8');
// 显式固定权限位: writeFile 会继承已存在文件的模式, 若上一版由 mktemp 等创建 (0600)
// 就会带着 600 进 zip, 使产物随文件历史而变。固定 0644 保证可复现。
await fsp.chmod(out, 0o644);
log.ok(`已生成 ${path.relative(process.cwd(), out)} (${lines.length} 条可执行文件校验)`);
return lines.length;
}
/** 生成发布产物校验文件 (dist/*.zip.sha256)
* 只针对模块发布包 (FontMM_v*.zip); webroot.zip 是 build:only-web 的调试产物, 跳过 */
async function genDistSums() {
let zips;
try {
zips = (await fsp.readdir(DIST_DIR)).filter((f) => f.startsWith('FontMM_v') && f.endsWith('.zip')).sort();
} catch {
log.info('无 dist 目录, 跳过');
return 0;
}
if (zips.length === 0) {
log.info('dist 下无 zip 产物, 跳过');
return 0;
}
for (const name of zips) {
const sum = hashFile(path.join(DIST_DIR, name));
await fsp.writeFile(path.join(DIST_DIR, `${name}.sha256`), `${sum} ${name}\n`, 'utf8');
log.ok(`已生成 dist/${name}.sha256`);
}
return zips.length;
}
const count = await genModuleSums();
if (!noDist) await genDistSums();
log.ok(`SHA256 校验文件生成完成 (模块内 ${count} 个可执行文件)`);
+53
View File
@@ -0,0 +1,53 @@
// dev/lib/exec.mjs — 外部命令调用封装 (取代 shell 里的直接调用)
// 统一处理: 命令缺失的友好提示、退出码检查、stdout 透传
import { spawnSync } from 'node:child_process';
import { log } from './log.mjs';
/** 命令是否存在于 PATH (只探测可执行性, 不关心退出码) */
export function hasCommand(cmd) {
const probe = spawnSync(cmd, [], { stdio: 'ignore', shell: false });
// ENOENT 表示命令不存在; 其余情况 (包括参数缺失导致的非 0 退出) 都说明命令可用
return !(probe.error && probe.error.code === 'ENOENT');
}
/**
* 运行命令, 失败即抛错 (由调用方捕获或用 runOrDie)。
* @param {string} cmd
* @param {string[]} args
* @param {{cwd?: string, env?: Record<string,string>, quiet?: boolean}} [opts]
*/
export function run(cmd, args, opts = {}) {
const { cwd, env, quiet = false } = opts;
const res = spawnSync(cmd, args, {
cwd,
env: env ? { ...process.env, ...env } : process.env,
stdio: quiet ? ['ignore', 'pipe', 'pipe'] : ['ignore', 'inherit', 'inherit'],
encoding: 'utf8',
shell: false,
});
if (res.error) {
if (res.error.code === 'ENOENT') throw new Error(`未找到命令: ${cmd} (请先安装)`);
throw new Error(`${cmd} 执行失败: ${res.error.message}`);
}
if (res.status !== 0) {
const detail = quiet ? (res.stderr || res.stdout || '').trim() : '';
throw new Error(`${cmd} 退出码 ${res.status}${detail ? `: ${detail}` : ''}`);
}
return res;
}
/** 运行命令并返回 stdout (不打印) */
export function capture(cmd, args, opts = {}) {
const res = run(cmd, args, { ...opts, quiet: true });
return res.stdout ?? '';
}
/** 运行命令失败即终止脚本 (用于构建流程中的必需步骤) */
export function runOrDie(cmd, args, opts = {}) {
try {
return run(cmd, args, opts);
} catch (e) {
log.fail(e.message);
process.exit(1);
}
}
+37
View File
@@ -0,0 +1,37 @@
// dev/lib/go.mjs — fontmm-wght 的交叉编译 (pack 与 build-wght 共用, 避免标志漂移)
import fsp from 'node:fs/promises';
import path from 'node:path';
import { ROOT, GOLANG_DIR, SRC_DIR } from './paths.mjs';
import { run } from './exec.mjs';
/**
* 构建标志:
* -trimpath 去掉源码绝对路径 (否则换目录构建产物就变)
* -buildvcs=false 不嵌入 VCS 状态 (否则 vcs.modified 会随工作树是否干净而变化)
* 两者共同保证同一份源码在任何环境构建出的二进制完全一致。
*/
export const GO_BUILD_FLAGS = ['-trimpath', '-buildvcs=false', '-ldflags=-s -w'];
/** fontmm-wght 产物路径 */
export const WGHT_BIN = path.join(SRC_DIR, 'tools', 'fontmm-wght');
/**
* 交叉编译 fontmm-wght -> src/tools/fontmm-wght
* @returns {Promise<number>} 产物字节数
*/
export async function buildWght() {
await fsp.mkdir(path.dirname(WGHT_BIN), { recursive: true });
run('go', ['build', ...GO_BUILD_FLAGS, '-o', WGHT_BIN, './cmd/fontmm-wght'], {
cwd: GOLANG_DIR,
env: { GOOS: 'android', GOARCH: 'arm64', CGO_ENABLED: '0' },
});
// 保证可执行位: 打包按磁盘权限位写入 zip, Magisk 安装后才能直接运行
await fsp.chmod(WGHT_BIN, 0o755);
const { size } = await fsp.stat(WGHT_BIN);
return size;
}
/** 产物相对仓库根的路径 (日志用) */
export function wghtBinRel() {
return path.relative(ROOT, WGHT_BIN);
}
+245
View File
@@ -0,0 +1,245 @@
// dev/lib/harfbuzz.mjs — harfbuzz 源码获取与静态库编译 (fontmm-subset 用)
//
// fontmm-subset 依赖 harfbuzz 的 subset API。harfbuzz 源码解压后 97MB,
// 不适合提交进仓库, 因此构建时按需下载。
//
// 缓存: harfbuzz 的编译占整个构建的绝大部分时间 (实测约 88s, 而下载 8.6s、
// 解压 1.3s、链接 1.1s)。因此缓存的是**编译好的对象文件**, 而不是源码 ——
// 这样只改 fontmm-subset.cc 时无需重编 harfbuzz。
// 缓存键 = harfbuzz 版本 + NDK 版本 + 编译选项
// 三者任一变化即重新编译, 避免用到不匹配的对象文件。
import fsp from 'node:fs/promises';
import fs from 'node:fs';
import path from 'node:path';
import { ROOT, NATIVE_DIR } from './paths.mjs';
import { log } from './log.mjs';
import { run } from './exec.mjs';
import { toolchainBin, MIN_API } from './ndk.mjs';
/** harfbuzz 版本 (固定: 该版本已实测编译通过且保留可变字体特性) */
export const HARFBUZZ_VERSION = '11.5.0';
/** harfbuzz 源码缓存目录 (下载的压缩包 + 解压结果都放这里) */
const SOURCE_CACHE_DIR = path.join(ROOT, 'dev', '.cache', 'harfbuzz');
/** 编译产物缓存目录 */
const OBJ_CACHE_DIR = path.join(ROOT, 'dev', '.cache', 'harfbuzz-obj');
/** 下载地址 (官方 release 资产) */
function downloadUrl(version) {
return `https://github.com/harfbuzz/harfbuzz/releases/download/${version}/harfbuzz-${version}.tar.xz`;
}
/** 编译 harfbuzz 用的选项 (构成缓存键的一部分) */
/**
* 编译 harfbuzz 用的选项 (不含 -ffile-prefix-map, 它需要源码根路径, 在编译处追加)。
*
* 为何需要 prefix-map: harfbuzz 会通过 __FILE__ 与调试信息把源码绝对路径嵌进
* 目标文件, 使产物哈希随构建目录变化 (CI 的 /home/runner/... 与本地不同)。
* 映射为相对路径后消除该差异 —— 与 fontmm-wght 用 -trimpath 是同一目的。
*/
const HARFBUZZ_CXXFLAGS = ['-std=c++11', '-O2', '-fPIC'];
/**
* 计算编译缓存键: harfbuzz 版本 + NDK 版本 + 编译选项。
* NDK 版本从 source.properties 读 (精确到补丁号, 因为不同补丁的 clang 产物不同)。
*/
async function objectCacheKey(ndkRoot) {
let ndkVersion = 'unknown';
try {
const props = await fsp.readFile(path.join(ndkRoot, 'source.properties'), 'utf8');
const m = props.match(/^Pkg\.Revision\s*=\s*(.+)$/m);
if (m) ndkVersion = m[1].trim();
} catch {
// 读不到就用 unknown; 缓存键仍包含 harfbuzz 版本与选项, 只是粒度变粗
}
// 键须覆盖全部影响产物的因素。CACHE_KEY_FLAGS 是编译时实际使用的标志集
// (不含依赖源码路径的 -ffile-prefix-map, 那部分固定在源码头). 若新增编译标志,
// 一并加入此列表, 否则改标志不会使缓存失效。
const flags = [...HARFBUZZ_CXXFLAGS, ...CACHE_KEY_FLAGS];
return `${HARFBUZZ_VERSION}|ndk=${ndkVersion}|api=${MIN_API}|${flags.join(' ')}`;
}
/** 参与缓存键、但不随编译调用显式传递的标志 (记录在此以便改动能失效缓存) */
const CACHE_KEY_FLAGS = ['-ffile-prefix-map=<srcRoot>=harfbuzz'];
/** 标记文件: 记录该对象文件对应的缓存键 */
function keyFile(objPath) {
return `${objPath}.key`;
}
/**
* 确保 harfbuzz 源码已就绪 (解压到缓存目录)。
* 已解压则直接复用, 不重复下载。
* @returns {Promise<string>} harfbuzz 源码根目录 (含 src/)
*/
export async function ensureHarfBuzzSource() {
const srcRoot = path.join(SOURCE_CACHE_DIR, `harfbuzz-${HARFBUZZ_VERSION}`);
const srcDir = path.join(srcRoot, 'src');
// 关键文件存在即认为源码完整 (与压缩包内容对应)
const sentinel = path.join(srcDir, 'harfbuzz-subset.cc');
try {
await fsp.access(sentinel);
log.info(`harfbuzz 源码已缓存 (${HARFBUZZ_VERSION})`);
return srcRoot;
} catch {
// 需要下载
}
const archive = path.join(SOURCE_CACHE_DIR, `harfbuzz-${HARFBUZZ_VERSION}.tar.xz`);
await fsp.mkdir(SOURCE_CACHE_DIR, { recursive: true });
// 压缩包已存在且非空则跳过下载 (网络抖动时重跑不必重下)
let needDownload = true;
try {
const st = await fsp.stat(archive);
if (st.size > 0) {
log.info(`harfbuzz 压缩包已缓存 (${(st.size / 1048576).toFixed(1)}MB)`);
needDownload = false;
}
} catch {
// 不存在, 需下载
}
if (needDownload) {
log.step(`下载 harfbuzz ${HARFBUZZ_VERSION} 源码...`);
const url = downloadUrl(HARFBUZZ_VERSION);
// 用 curl/wget: Node 的 fetch 对 GitHub 重定向与大文件支持较繁琐
const curlOk = await downloadWith('curl', ['-fsSL', '-o', archive, url]);
if (!curlOk) {
const wgetOk = await downloadWith('wget', ['-q', '-O', archive, url]);
if (!wgetOk) {
throw new Error(
`下载 harfbuzz 源码失败。请检查网络, 或手动下载后放到:\n ${archive}\n ${url}`,
);
}
}
const { size } = await fsp.stat(archive);
log.ok(`已下载 (${(size / 1048576).toFixed(1)}MB)`);
}
log.step('解压 harfbuzz 源码...');
await fsp.mkdir(srcRoot, { recursive: true });
run('tar', ['xf', archive, '-C', SOURCE_CACHE_DIR]);
// 解压后应出现 harfbuzz-<版本>/src
try {
await fsp.access(sentinel);
} catch {
throw new Error(`解压后未找到 ${sentinel}, 压缩包可能损坏 (可删除后重试)`);
}
log.ok('源码就绪');
return srcRoot;
}
/** 尝试用某个工具下载, 成功返回 true */
async function downloadWith(cmd, args) {
try {
run(cmd, args, { quiet: true });
return true;
} catch {
return false;
}
}
/**
* 获取 (必要时编译) harfbuzz 的 subset 对象文件, 带缓存。
*
* @param {string} ndkRoot NDK 根目录
* @returns {Promise<string>} 对象文件路径
*/
export async function ensureHarfBuzzObject(ndkRoot) {
const srcRoot = await ensureHarfBuzzSource();
const bin = toolchainBin(ndkRoot);
const cxx = path.join(bin, `aarch64-linux-android${MIN_API}-clang++`);
const key = await objectCacheKey(ndkRoot);
const objName = `harfbuzz-subset-${shortHash(key)}.o`;
const objPath = path.join(OBJ_CACHE_DIR, objName);
// 命中检查: 对象文件存在 + 标记文件的键一致
try {
await fsp.access(objPath);
const savedKey = (await fsp.readFile(keyFile(objPath), 'utf8')).trim();
if (savedKey === key) {
const { size } = await fsp.stat(objPath);
log.info(`复用 harfbuzz 编译缓存 (${(size / 1048576).toFixed(1)}MB, 免去约 88s 重编)`);
return objPath;
}
log.info('harfbuzz 缓存键不匹配 (版本/NDK/选项已变), 重新编译');
} catch {
// 无缓存
}
log.step('编译 harfbuzz subset (首次约 1-2 分钟, 之后走缓存)...');
await fsp.mkdir(OBJ_CACHE_DIR, { recursive: true });
run(
cxx,
[
...HARFBUZZ_CXXFLAGS,
'-c',
// 去掉源码绝对路径: 否则需嵌入源码路径的宏/调试信息会随构建目录变化,
// 使 CI 与本地编译出的对象文件字节不同 (进而产物哈希不同)
`-ffile-prefix-map=${srcRoot}=harfbuzz`,
'-I',
path.join(srcRoot, 'src'),
'-o',
objPath,
path.join(srcRoot, 'src', 'harfbuzz-subset.cc'),
],
{ cwd: ROOT },
);
// 先写对象文件再写键: 中途失败时键文件不存在 → 视为无缓存, 不会用到半成品
await fsp.writeFile(keyFile(objPath), key, 'utf8');
const { size } = await fsp.stat(objPath);
log.ok(`已编译并缓存 (${(size / 1048576).toFixed(1)}MB)`);
return objPath;
}
/** 由缓存键派生短哈希, 作为对象文件名 (避免键含特殊字符) */
function shortHash(key) {
// 用简单稳定的哈希即可: 只需在键变化时文件名也变化
let h = 0x811c9dc5;
for (let i = 0; i < key.length; i++) {
h ^= key.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h.toString(16).padStart(8, '0');
}
/**
* 编译 fontmm-subset 可执行文件。
* @param {string} ndkRoot
* @param {string} outFile 输出路径
* @returns {Promise<number>} 产物字节数
*/
export async function buildSubsetTool(ndkRoot, outFile) {
const srcRoot = await ensureHarfBuzzSource();
const objPath = await ensureHarfBuzzObject(ndkRoot);
const bin = toolchainBin(ndkRoot);
const cxx = path.join(bin, `aarch64-linux-android${MIN_API}-clang++`);
log.step('链接 fontmm-subset...');
await fsp.mkdir(path.dirname(outFile), { recursive: true });
run(
cxx,
[
'-std=c++11',
'-O2',
'-fPIC',
'-ffixed-x18',
// 可复现构建: 去掉源码绝对路径
'-ffile-prefix-map=' + NATIVE_DIR + '=.',
'-I',
path.join(srcRoot, 'src'),
'-o',
outFile,
path.join(NATIVE_DIR, 'src', 'subset', 'fontmm-subset.cc'),
objPath,
// 静态链接 libc++: 设备端无需额外 .so, 与 fontmm-wght 的做法一致
'-static-libstdc++',
],
{ cwd: ROOT },
);
const { size } = await fsp.stat(outFile);
return size;
}
+35
View File
@@ -0,0 +1,35 @@
// dev/lib/log.mjs — 统一日志输出 (沿用原 shell 脚本的 [*] [✓] [!] [✗] 前缀风格)
// 颜色仅在终端下启用, 重定向到文件/CI 时自动降级为纯文本
const useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
function paint(code, text) {
return useColor ? `\u001b[${code}m${text}\u001b[0m` : text;
}
export const log = {
/** 流程节点 */
step: (msg) => console.log(`[*] ${msg}`),
/** 成功 */
ok: (msg) => console.log(paint('32', `[✓] ${msg}`)),
/** 中性信息 */
info: (msg) => console.log(`[-] ${msg}`),
/** 警告 (不中断) */
warn: (msg) => console.log(paint('33', `[!] ${msg}`)),
/** 错误 (不中断, 由调用方决定是否终止) */
fail: (msg) => console.error(paint('31', `[✗] ${msg}`)),
/** 缩进明细 */
detail: (msg) => console.log(` ${msg}`),
};
/** 打印错误并以非 0 退出 */
export function die(msg, code = 1) {
log.fail(msg);
process.exit(code);
}
/** 秒表: 返回一个函数, 调用后得到 "x.xs" 文本 */
export function stopwatch() {
const t0 = Date.now();
return () => `${((Date.now() - t0) / 1000).toFixed(1)}s`;
}
+194
View File
@@ -0,0 +1,194 @@
// dev/lib/ndk.mjs — Android NDK 工具链定位与 C++ 交叉编译
//
// Zygisk 模块必须编译成 aarch64 的 ELF 共享库, 因此需要 Android NDK。
// NDK 体积很大 (约 600MB) 且不进仓库, 通过环境变量或常见安装位置查找。
import fsp from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { ROOT, NATIVE_DIR } from './paths.mjs';
import { run } from './exec.mjs';
/** 目标 ABI: ColorOS 16 设备均为 arm64 */
export const TARGET_ABI = 'arm64-v8a';
/** 最低 API 级别: 与 nativeWarmUpCache 的引入版本一致 (Android 12) */
export const MIN_API = 31;
/** NDK 常见安装位置 (按优先级) */
const NDK_CANDIDATES = [
process.env.ANDROID_NDK_HOME,
process.env.ANDROID_NDK_ROOT,
process.env.NDK_HOME,
path.join(os.homedir(), 'opt', 'android-ndk-r27c'),
path.join(os.homedir(), 'Android', 'Sdk', 'ndk'),
'/opt/android-ndk',
'/usr/lib/android-ndk',
];
/**
* 定位 NDK 根目录。
* @returns {Promise<string|null>} NDK 根目录, 未找到返回 null
*/
export async function findNdk() {
for (const candidate of NDK_CANDIDATES) {
if (!candidate) continue;
// 直接指向 NDK 根
const sourceProps = path.join(candidate, 'source.properties');
try {
await fsp.access(sourceProps);
return candidate;
} catch {
// 不是 NDK 根, 继续; 也可能是 ndk/<版本>/ 形式 (Android SDK 布局)
}
// Android SDK 的 ndk/ 目录: 取版本号最大的一个
try {
const entries = (await fsp.readdir(candidate, { withFileTypes: true }))
.filter((e) => e.isDirectory())
.map((e) => e.name)
.sort()
.reverse();
for (const name of entries) {
const dir = path.join(candidate, name);
try {
await fsp.access(path.join(dir, 'source.properties'));
return dir;
} catch {
// 继续找下一个
}
}
} catch {
// 目录不存在, 继续
}
}
return null;
}
/** 由 NDK 根目录推导出 prebuilt 工具链的 bin 目录 */
export function toolchainBin(ndkRoot) {
return path.join(ndkRoot, 'toolchains', 'llvm', 'prebuilt', 'linux-x86_64', 'bin');
}
/**
* 生成 compile_commands.json, 让编辑器 (clangd / VSCode C/C++ 扩展) 用与真实构建
* 完全相同的参数解析源码, 从而正确找到 NDK 的头文件 (jni.h / android/log.h 等),
* 否则编辑器会满屏 "无法打开源文件" 的 IntelliSense 报错。
*
* 不依赖 CMake: 我们只有单个源文件, 直接按 clang 的 JSON Compilation Database 格式
* 写一条记录即可。写入仓库根, 便于编辑器自动发现; 该文件是构建产物, 已被 .gitignore 忽略。
*
* @param {string} cxx 编译器绝对路径
* @param {string[]} args 构建参数
*/
async function writeCompileCommands(cxx, args) {
const sourceRel = path.join('native', 'src', 'fontmm.cpp');
const sourceAbs = path.join(ROOT, sourceRel);
const entry = {
directory: ROOT,
arguments: [cxx, ...args.map((a) => (a === sourceRel ? sourceAbs : a))],
file: sourceAbs,
};
await fsp.writeFile(
path.join(ROOT, 'compile_commands.json'),
JSON.stringify([entry], null, 2),
'utf8',
);
}
/**
* 编译 Zygisk 模块。
*
* 编译选项说明 (每一项都影响产物能否被 Zygisk 加载器正确加载):
* -fPIC / -shared 共享库基础
* -fvisibility=hidden 只导出显式标记的符号 (zygisk_module_entry)
* -ffixed-x18 ARM64 平台寄存器约定, Android 要求
* -fno-exceptions -fno-rtti 减小体积, 且异常跨 .so 边界无意义
* -fno-threadsafe-statics 取消静态局部变量的线程安全 guard。
* 否则会引入 __cxa_guard_acquire/release, 这两个符号
* 不在 bionic libc 的导出表里 (仅 libc++ 提供), 而
* Zygisk 的自研加载器只解析系统库, 会导致加载失败。
* -nostdlib++ 不链接 libc++ (我们的代码不需要), 产物从 464KB 降到 10KB,
* 同时避免依赖 libc++_shared.so (它不在加载器的搜索路径中)。
* 静态初始化改由 C++ 编译器直接发射, 无需运行时支持。
*
* @param {string} ndkRoot NDK 根目录
* @param {{onLog?: (msg: string) => void}} [opts]
* @returns {Promise<{ outFile: string, size: number }>}
*/
export async function buildZygiskModule(ndkRoot, opts = {}) {
const bin = toolchainBin(ndkRoot);
const cxx = path.join(bin, `aarch64-linux-android${MIN_API}-clang++`);
const nm = path.join(bin, 'llvm-nm');
const strip = path.join(bin, 'llvm-strip');
const outDir = path.join(NATIVE_DIR, 'build');
const outFile = path.join(outDir, `${TARGET_ABI}.so`);
await fsp.mkdir(outDir, { recursive: true });
const args = [
'-std=c++20',
'-O2',
'-fPIC',
'-shared',
'-Wall',
'-Wextra',
'-fvisibility=hidden',
'-fvisibility-inlines-hidden',
'-ffixed-x18',
'-fno-exceptions',
'-fno-rtti',
'-fno-threadsafe-statics',
'-nostdlib++',
// 可复现构建: 去掉源码绝对路径
'-ffile-prefix-map=' + NATIVE_DIR + '=.',
'-o',
outFile,
path.join(NATIVE_DIR, 'src', 'fontmm.cpp'),
'-llog',
];
run(cxx, args, { cwd: ROOT });
// 去掉调试符号与本地符号 (6.8KB vs 10.4KB), 动态符号表不受影响
run(strip, ['--strip-unneeded', outFile], { cwd: ROOT });
opts.onLog?.(`编译完成: ${path.relative(ROOT, outFile)}`);
// 生成 compile_commands.json: 供 clangd / VSCode C/C++ 扩展解析本文件,
// 使其能定位 NDK 的头文件 (jni.h / android/log.h 等), 否则编辑器会满屏
// "无法打开源文件" 的 IntelliSense 报错。
await writeCompileCommands(cxx, args);
// 校验导出符号: Zygisk 只认 zygisk_module_entry, 多导出会污染宿主进程符号表
const symbols = (run(nm, ['-D', '--defined-only', outFile], { quiet: true }).stdout ?? '')
.split('\n')
.map((l) => l.trim().split(/\s+/).pop())
.filter(Boolean);
const expected = 'zygisk_module_entry';
const unexpected = symbols.filter((s) => s !== expected);
if (!symbols.includes(expected)) {
throw new Error(`产物缺少 ${expected} 导出符号 (Zygisk 无法识别该模块)`);
}
if (unexpected.length > 0) {
throw new Error(`产物导出了预期外的符号: ${unexpected.join(', ')}`);
}
// 校验没有链接 libc++_shared: 它不在 Zygisk 加载器的库搜索路径中
const needed = (run(
path.join(bin, 'llvm-readelf'),
['-d', outFile],
{ quiet: true },
).stdout ?? '')
.split('\n')
.filter((l) => l.includes('NEEDED'))
.map((l) => l.match(/\[(.*)\]/)?.[1])
.filter(Boolean);
const libcxx = needed.find((l) => l.includes('libc++'));
if (libcxx) {
throw new Error(
`产物依赖 ${libcxx}, 该库不在 Zygisk 加载器的搜索路径中, 会导致模块加载失败`,
);
}
opts.onLog?.(`动态依赖: ${needed.join(', ')}`);
const { size } = await fsp.stat(outFile);
return { outFile, size };
}
+49
View File
@@ -0,0 +1,49 @@
// dev/lib/paths.mjs — 项目路径常量 (统一从本文件推导, 避免各脚本各自 dirname 拼接)
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import fs from 'node:fs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
/** 项目根目录 (dev/lib/ 往上两级) */
export const ROOT = path.resolve(HERE, '..', '..');
export const SRC_DIR = path.join(ROOT, 'src');
export const WEB_DIR = path.join(ROOT, 'web');
export const DIST_DIR = path.join(ROOT, 'dist');
export const GOLANG_DIR = path.join(ROOT, 'golang');
/** Zygisk 原生模块 (C++) 源码目录 */
export const NATIVE_DIR = path.join(ROOT, 'native');
export const WEBROOT_DIR = path.join(SRC_DIR, 'webroot');
export const MODULE_PROP = path.join(SRC_DIR, 'module.prop');
export const FONTS_XML = path.join(SRC_DIR, 'system', 'etc', 'fonts.xml');
/** 模块内 Zygisk 库目录 (相对模块根): 加载器约定读 zygisk/<abi>.so */
export const ZYGISK_DIR_REL = 'zygisk';
/** 派生字体配置 (不打包, 由设备端 customize.sh 生成; 开发期用 sync-fonts-xml 本地生成) */
export const DERIVED_XML_RELS = [
'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',
];
/** 从 module.prop 读取 version= 字段 */
export function readVersion() {
const text = fs.readFileSync(MODULE_PROP, 'utf8');
for (const line of text.split('\n')) {
const m = line.match(/^version=(.*)$/);
if (m) return m[1].trim();
}
throw new Error(`无法从 ${MODULE_PROP} 读取 version 字段`);
}
/**
* 版本号 -> 安全文件名。
* GitHub Release 网页上传会把括号改写为点, 导致 URL 与本地文件名不一致,
* 因此打包时就把括号统一替换为点: 26.8.0-beta.1(260800001) -> 26.8.0-beta.1.260800001
*/
export function safeFileVersion(version) {
return version.replace(/\(/g, '.').replace(/\)/g, '');
}
+250
View File
@@ -0,0 +1,250 @@
// dev/lib/zip.mjs — ZIP 打包与回读校验 (基于 @zip.js/zip.js)
//
// 取代原 shell 流程对 `zip` / `unzip` 外部命令的依赖: 两者在 Windows、精简容器
// 与部分 CI 镜像中常常缺失或行为不一致。zip.js 是纯 JS 实现, 只需 Node 即可运行,
// 并支持精确设置 unix 权限位 (模块内脚本与 fontmm-wght 二进制需要正确的可执行位)。
//
// 权限位策略: 沿用源文件自身的权限位 (与原 Info-ZIP 行为一致, 保证产物不变),
// 同时给普通文件兜底 0644、目录兜底 0755, 避免开发者 umask 过严 (如 077) 时
// 打包出无读权限的文件导致设备端安装失败。
import * as zip from '@zip.js/zip.js';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';
import { Writable } from 'node:stream';
import { log } from './log.mjs';
/** 普通文件权限位下限 (含 S_IFREG) */
export const FILE_MODE = 0o100644;
/** 目录权限位下限 (含 S_IFDIR) */
export const DIR_MODE = 0o40755;
/** 权限位掩码: 仅保留读/写/执行位 */
const PERM_MASK = 0o777;
/** 文件权限位: 源文件权限, 至少 0644 */
export function fileModeOf(stat) {
return 0o100000 | ((stat.mode & PERM_MASK) | 0o644);
}
/** 目录权限位: 源目录权限, 至少 0755 */
export function dirModeOf(stat) {
return 0o040000 | ((stat.mode & PERM_MASK) | 0o755);
}
/**
* 把 Info-ZIP 风格的 glob (其中 `*` 匹配任意字符, 含 `/`) 编译为正则列表。
* 与 zip -x 的语义保持一致, 便于原脚本的排除规则直接沿用。
*/
export function compileGlobs(patterns) {
return patterns.map((p) => {
const escaped = p.replace(/[.+^${}()|[\]\\?]/g, '\\$&').replace(/\*/g, '.*');
return new RegExp(`^${escaped}$`);
});
}
/** 递归收集目录内容 (排序保证产物顺序稳定), rel 以 `/` 结尾表示目录 */
async function walk(root) {
const out = [];
async function recurse(dir) {
const items = await fsp.readdir(dir, { withFileTypes: true });
items.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
for (const item of items) {
const abs = path.join(dir, item.name);
const rel = path.relative(root, abs).split(path.sep).join('/');
if (item.isDirectory()) {
out.push({ abs, rel: `${rel}/`, type: 'dir' });
await recurse(abs);
} else if (item.isFile()) {
out.push({ abs, rel, type: 'file' });
}
// 其他类型 (符号链接等) 跳过: 模块包内不需要, 且 zip 语义易产生歧义
}
}
await recurse(root);
return out;
}
/**
* 打包目录为 zip。
* @param {object} opts
* @param {string} opts.srcDir 源目录 (其内容作为 zip 根, 不含该目录名这一层)
* @param {string} opts.outFile 输出 zip 路径
* @param {string[]} [opts.exclude] Info-ZIP 风格 glob, 命中的条目被排除
* @param {string[]} [opts.excludeFilePrefixes] 仅排除这些前缀下的**文件** (保留目录条目)
* @param {string[]} [opts.onlyPrefixes] 只收录这些前缀下的条目 (其他一律跳过)。
* 用于单独打包某个子树以建立缓存: 条目名仍是相对 srcDir 的完整路径,
* 与整包打包时完全一致, 因此可以按路径直接复用。
* @param {number} [opts.level] 压缩级别 0-9 (默认 2, 与原 zip -2 一致)
* @param {Date} [opts.fixedDate] 固定所有条目的时间戳 (SOURCE_DATE_EPOCH 式可复现打包);
* 不传则沿用源文件 mtime, 与 Info-ZIP 行为一致
* @param {(rel: string) => void} [opts.onEntry] 每个文件写入后的回调
* @param {{ get(rel: string): { compressed: () => Promise<Blob>, crc32: number, uncompressedSize: number } | undefined }} [opts.cache]
* 预压缩缓存 (见 dev/lib/zipcache.mjs): 命中的条目直接搬运已压缩数据, 不做 deflate
* @returns {Promise<{ files: number, dirs: number, reused: number }>}
*/
export async function packDir({
srcDir,
outFile,
exclude = [],
excludeFilePrefixes = [],
onlyPrefixes,
level = 2,
fixedDate,
onEntry,
cache,
}) {
const globs = compileGlobs(exclude);
const entries = await walk(srcDir);
await fsp.mkdir(path.dirname(outFile), { recursive: true });
const fd = fs.createWriteStream(outFile);
const closed = new Promise((resolve, reject) => {
fd.on('close', resolve);
fd.on('error', reject);
});
const writer = new zip.ZipWriter(Writable.toWeb(fd), { bufferedWrite: false, level });
// 统一的时间戳来源: fixedDate 优先, 否则用源文件 mtime
const dateOf = (stat) => fixedDate ?? stat.mtime;
let files = 0;
let dirs = 0;
let reused = 0;
try {
for (const entry of entries) {
if (globs.some((re) => re.test(entry.rel))) continue;
if (onlyPrefixes && !onlyPrefixes.some((p) => entry.rel.startsWith(p))) continue;
if (
entry.type === 'file' &&
excludeFilePrefixes.some((prefix) => entry.rel.startsWith(prefix))
) {
continue;
}
const stat = await fsp.stat(entry.abs);
if (entry.type === 'dir') {
await writer.add(entry.rel, new zip.TextReader(''), {
directory: true,
unixMode: dirModeOf(stat),
lastModDate: dateOf(stat),
});
dirs++;
continue;
}
const lastModDate = dateOf(stat);
const unixMode = fileModeOf(stat);
// 预压缩缓存: 命中则直接搬运已压缩数据 (passThrough), 跳过 deflate。
// 需同时提供下列字段, 否则 zip.js 在没有压缩阶段的情况下无法写出正确的条目头:
// uncompressedSize / crc32 / compressionMethod —— 条目头必需
// level —— zip.js 把压缩级别编码进通用标志位 (bit 1-2), 不传会与现场
// 压缩的产物产生字节差异 (整包哈希不一致)
const cached = cache?.get(entry.rel);
if (cached) {
try {
const compressed = await cached.compressed();
await writer.add(entry.rel, new zip.BlobReader(compressed), {
unixMode,
lastModDate,
passThrough: true,
uncompressedSize: cached.uncompressedSize,
crc32: cached.crc32,
compressionMethod: 8, // deflate, 与压缩期一致
level,
});
files++;
reused++;
onEntry?.(entry.rel);
continue;
} catch (e) {
// 单条搬运失败不应中断构建: 回退为现场压缩
log.warn(`缓存条目不可用, 回退现场压缩: ${entry.rel} (${e.message})`);
}
}
// 未命中: 现场压缩。BlobReader + openAsBlob 流式读取, 不整体载入内存
const blob = await fs.openAsBlob(entry.abs);
await writer.add(entry.rel, new zip.BlobReader(blob), {
unixMode,
lastModDate,
});
files++;
onEntry?.(entry.rel);
}
await writer.close();
await closed;
} catch (e) {
fd.destroy();
throw e;
}
return { files, dirs, reused };
}
/** 打开 zip 读取器 (调用方负责 close) */
async function openReader(zipPath) {
const blob = await fs.openAsBlob(zipPath);
return new zip.ZipReader(new zip.BlobReader(blob));
}
/** 列出 zip 内全部条目的名称 (目录条目带结尾 `/`) */
export async function listEntries(zipPath) {
const reader = await openReader(zipPath);
try {
const entries = await reader.getEntries();
return entries.map((e) => e.filename);
} finally {
await reader.close();
}
}
/**
* 回读 zip 并计算每个文件条目的 SHA256 与权限位, 用于校验打包结果。
* 流式读取 (逐个 entry 喂给哈希), 不会把大字体一次性读进内存。
* @returns {Promise<Map<string, { sha256: string, mode: number, isDir: boolean }>>}
*/
export async function indexZip(zipPath) {
const reader = await openReader(zipPath);
const result = new Map();
try {
const entries = await reader.getEntries();
for (const entry of entries) {
const mode = (entry.externalFileAttributes ?? 0) >>> 16;
if (entry.directory) {
result.set(entry.filename, { sha256: '', mode, isDir: true });
continue;
}
const hash = crypto.createHash('sha256');
const sink = new WritableStream({
write(chunk) {
hash.update(chunk);
},
});
await entry.getData(sink);
result.set(entry.filename, { sha256: hash.digest('hex'), mode, isDir: false });
}
return result;
} finally {
await reader.close();
}
}
/** 计算磁盘文件的 SHA256 */
export function hashFile(file) {
const hash = crypto.createHash('sha256');
const fd = fs.openSync(file, 'r');
try {
const buf = Buffer.allocUnsafe(1 << 20);
for (;;) {
const n = fs.readSync(fd, buf, 0, buf.length, null);
if (n <= 0) break;
hash.update(buf.subarray(0, n));
}
} finally {
fs.closeSync(fd);
}
return hash.digest('hex');
}
+236
View File
@@ -0,0 +1,236 @@
// dev/lib/zipcache.mjs — 预压缩构建缓存
//
// 动机: 打包耗时几乎全在压缩。system/fonts/ 有 131MB 原始数据 (压缩后 71MB),
// 占整包压缩量的 ~70%, 而这部分内容在大多数构建中是**不变的** (只有发布新版本
// 字体时才会动)。把它预先压缩并缓存起来, 后续打包只需把已压缩的数据"搬运"进
// 新 zip (passThrough, 不重新 deflate), 再压缩其余变动文件即可。
//
// 设计: 缓存是若干个"目录片段" (segment), 每个片段对应源目录下的一个子目录,
// 并对该子树计算指纹 (文件名 + 大小 + mtime + 权限位)。指纹一致才能复用。
// - 用文件大小 + mtime 而非内容哈希做指纹: 对 131MB 字体算哈希本身就要 1s 左右,
// 而 mtime/size 变化足以判定"内容可能变了"。缓存是本地构建加速, 不是安全边界,
// 真要去校验内容, 打包后的产物校验 (dev/pack.mjs 的 verify) 会兜住。
// - 缓存不含任何"必须存在"的假设: 缺失/版本不符/指纹不符一律回退为现场压缩。
//
// 缓存目录: dev/.cache/ (已 gitignore, 不随仓库分发)
import fsp from 'node:fs/promises';
import path from 'node:path';
import { ROOT } from './paths.mjs';
import { log } from './log.mjs';
/** 缓存目录 (不入库) */
export const CACHE_DIR = path.join(ROOT, 'dev', '.cache');
/** 缓存格式版本: 结构变更时递增, 旧缓存自动失效 */
const CACHE_VERSION = 1;
/** 单个片段的索引文件名 */
function indexFile(segment) {
return path.join(CACHE_DIR, `${segment}.index.json`);
}
/** 单个片段的预压缩 zip 路径 */
function dataFile(segment) {
return path.join(CACHE_DIR, `${segment}.zip`);
}
/**
* 递归收集子树的条目 (相对 srcDir 的路径, 排序稳定), 用于计算指纹。
* 目录条目也计入 —— 目录的增删同样会使缓存失效。
*/
async function collectTree(rootDir) {
const out = [];
async function recurse(dir) {
const items = await fsp.readdir(dir, { withFileTypes: true });
items.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
for (const item of items) {
const abs = path.join(dir, item.name);
const rel = path.relative(rootDir, abs).split(path.sep).join('/');
if (item.isDirectory()) {
out.push({ rel: `${rel}/`, type: 'dir' });
await recurse(abs);
} else if (item.isFile()) {
const st = await fsp.stat(abs);
out.push({
rel,
type: 'file',
size: st.size,
// mtimeMs 取整: 不同文件系统的时间精度不同, 避免无意义的失配
mtime: Math.floor(st.mtimeMs),
mode: st.mode & 0o777,
});
}
// 其他类型 (符号链接等) 跳过, 与打包逻辑一致
}
}
await recurse(rootDir);
return out;
}
/** 由条目列表计算指纹 (稳定序列化后哈希) */
function fingerprint(entries) {
return JSON.stringify(entries);
}
/**
* 计算某个源目录子树的缓存键。
* @param {string} subtreeDir 绝对路径
* @returns {Promise<string>} 指纹字符串
*/
export async function subtreeKey(subtreeDir) {
return fingerprint(await collectTree(subtreeDir));
}
/**
* 读取缓存片段 (若有效)。
* @param {string} segment 片段名 (同时作为缓存文件名, 仅用 [a-z0-9-])
* @param {string} expectedKey 期望的指纹
* @returns {Promise<{ file: string, entries: object[] } | null>} 有效则返回缓存信息
*/
export async function readCache(segment, expectedKey) {
try {
const raw = await fsp.readFile(indexFile(segment), 'utf8');
const idx = JSON.parse(raw);
if (idx.version !== CACHE_VERSION) return null;
if (idx.key !== expectedKey) return null;
// 缓存数据文件必须存在且有内容
const st = await fsp.stat(dataFile(segment));
if (st.size === 0) return null;
return { file: dataFile(segment), entries: idx.entries ?? [] };
} catch {
// 任何读取/解析失败都视为无缓存 —— 优雅降级
return null;
}
}
/**
* 打开缓存片段, 返回按相对路径取用的压缩数据查找表。
*
* 返回的对象持有 ZipReader; 每一条的压缩数据按需读取 (getData(passThrough) 只做
* 字节搬运, 不解压), 因此不会把整个片段一次性读进内存。用完需调用 close()。
*
* @param {string} segment 片段名
* @param {string} key 指纹
* @returns {Promise<{ get(rel: string): { compressed: () => Promise<Blob>, crc32: number, uncompressedSize: number } | undefined, entries: string[], close(): Promise<void> } | null>}
*/
export async function openCache(segment, key) {
const cached = await readCache(segment, key);
if (!cached) return null;
let reader = null;
try {
const { ZipReader, BlobReader, BlobWriter } = await import('@zip.js/zip.js');
const fs = await import('node:fs');
// openAsBlob: 流式读取缓存文件, 不整体载入内存
const blob = await fs.openAsBlob(dataFile(segment));
reader = new ZipReader(new BlobReader(blob));
const entries = await reader.getEntries();
const table = new Map();
for (const e of entries) {
if (e.directory) continue;
table.set(e.filename, {
// 惰性取用: 每次调用只搬运该条目的已压缩字节, 不重新压缩
compressed: () => e.getData(new BlobWriter(), { passThrough: true }),
crc32: e.crc32,
uncompressedSize: e.uncompressedSize,
});
}
return {
get: (rel) => table.get(rel),
entries: [...table.keys()],
close: async () => {
await reader.close();
},
};
} catch (e) {
log.warn(`打开缓存片段 ${segment} 失败 (将现场压缩): ${e.message}`);
try {
await reader?.close();
} catch {
// 忽略
}
return null;
}
}
/**
* 由"已完成压缩的 zip"建立缓存片段。
* 该 zip 内条目名需与打包时的相对路径一致 (即相对 srcDir 的路径)。
*
* @param {string} segment 片段名
* @param {string} key 指纹
* @param {string} zipFile 已压缩的 zip 路径
* @param {number} level 压缩级别 (写入索引, 级别变化会使缓存失效)
*/
export async function saveCacheFromZip(segment, key, zipFile, level) {
try {
await fsp.mkdir(CACHE_DIR, { recursive: true });
const { ZipReader, BlobReader } = await import('@zip.js/zip.js');
const fs = await import('node:fs');
const blob = await fs.openAsBlob(zipFile);
const reader = new ZipReader(new BlobReader(blob));
const entries = await reader.getEntries();
const meta = entries.map((e) => ({
rel: e.filename,
size: e.uncompressedSize,
compressedSize: e.compressedSize,
direct: e.directory,
}));
await reader.close();
const idx = {
version: CACHE_VERSION,
key,
level,
createdAt: new Date().toISOString(),
entries: meta,
};
// 先落数据文件再落索引: 若中途失败, 索引缺失 → 视为无缓存, 不会读到半成品
await fsp.copyFile(zipFile, dataFile(segment));
await fsp.writeFile(indexFile(segment), JSON.stringify(idx, null, 2), 'utf8');
return true;
} catch (e) {
log.warn(`写入缓存失败 (不影响构建): ${e.message}`);
return false;
}
}
/** 清空全部缓存 */
export async function clearCache() {
await fsp.rm(CACHE_DIR, { recursive: true, force: true });
}
/** 缓存片段的当前状态 (供 pnpm cache:status 展示) */
export async function cacheStatus() {
try {
const files = await fsp.readdir(CACHE_DIR);
const out = [];
for (const name of files.filter((f) => f.endsWith('.index.json'))) {
const segment = name.replace(/\.index\.json$/, '');
try {
const idx = JSON.parse(await fsp.readFile(path.join(CACHE_DIR, name), 'utf8'));
let size = 0;
try {
size = (await fsp.stat(dataFile(segment))).size;
} catch {
// 数据文件缺失
}
out.push({
segment,
version: idx.version,
usable: idx.version === CACHE_VERSION && size > 0,
size,
files: (idx.entries ?? []).filter((e) => !e.direct).length,
createdAt: idx.createdAt,
});
} catch {
// 索引损坏
}
}
return out;
} catch {
return [];
}
}
+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env node
// dev/pack.mjs — 打包 FontMM 模块 (取代 cd.sh)
//
// 产出两个版本, 区别仅在于是否预置字体:
// _preplace: 含 FONTS/hans.ttf, 适合全新安装
// _template: FONTS/ 为空目录, 适合更新已有模块 (customize.sh 从旧模块继承字体)
//
// 流程: 编译 fontmm-wght (Go) / Zygisk 模块 (C++) / fontmm-subset (C++)
// -> 生成 SHA256SUMS -> 打包两版 (复用预压缩缓存) -> 校验产物 -> 生成发布校验文件
//
// 用法: node dev/pack.mjs [--skip-go] [--skip-zygisk] [--skip-subset] [--no-cache]
// --skip-go: 跳过 Go 交叉编译 (CI 中已单独构建时使用)
// --skip-zygisk: 跳过 Zygisk 模块编译 (无 NDK 或已构建好时使用)
// --skip-subset: 跳过 fontmm-subset 编译 (无网络或已构建好时使用)
// --no-cache: 禁用预压缩缓存 (用于验证缓存与非缓存产物一致)
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log, die, stopwatch } from './lib/log.mjs';
import { ROOT, SRC_DIR, DIST_DIR, DERIVED_XML_RELS, readVersion, safeFileVersion } from './lib/paths.mjs';
import { packDir, listEntries, indexZip, hashFile } from './lib/zip.mjs';
import { run, hasCommand } from './lib/exec.mjs';
import { buildWght, wghtBinRel, WGHT_BIN } from './lib/go.mjs';
import { subtreeKey, openCache, saveCacheFromZip } from './lib/zipcache.mjs';
import { findNdk, buildZygiskModule, TARGET_ABI } from './lib/ndk.mjs';
import { buildSubsetTool } from './lib/harfbuzz.mjs';
const skipGo = process.argv.includes('--skip-go');
const skipZygisk = process.argv.includes('--skip-zygisk');
const skipSubset = process.argv.includes('--skip-subset');
/** 预压缩缓存开关 (--no-cache 关闭; CI 中禁用可避免缓存目录带来的不确定性) */
const CACHE_ENABLED = !process.argv.includes('--no-cache');
/** 打包压缩级别 (与原 zip -2 一致); 也是缓存片段的压缩级别, 变更会使缓存失效 */
const COMPRESS_LEVEL = 2;
const elapsed = stopwatch();
// 可复现打包: 设置 SOURCE_DATE_EPOCH 时, 所有 zip 条目使用该固定时间戳,
// 使同一份源码在任意时间/机器构建出的 zip 逐字节一致。
// 未设置时沿用源文件 mtime (与 Info-ZIP 行为一致)。
const sourceDateEpoch = process.env.SOURCE_DATE_EPOCH;
let fixedDate;
if (sourceDateEpoch) {
const secs = Number(sourceDateEpoch);
if (!Number.isFinite(secs)) die(`SOURCE_DATE_EPOCH 必须是秒级时间戳: ${sourceDateEpoch}`);
fixedDate = new Date(secs * 1000);
}
const version = readVersion();
const fileVersion = safeFileVersion(version);
const preOut = path.join(DIST_DIR, `FontMM_v${fileVersion}_preplace.zip`);
const tplOut = path.join(DIST_DIR, `FontMM_v${fileVersion}_template.zip`);
log.step(`打包 FontMM v${version} -> ${path.relative(ROOT, DIST_DIR)}/`);
if (fixedDate) log.info(`SOURCE_DATE_EPOCH=${sourceDateEpoch} (固定时间戳, 可复现打包)`);
// ---------- 1. 交叉编译 fontmm-wght (字重覆写用的 Go 程序) ----------
if (skipGo) {
log.info('已跳过 Go 交叉编译 (--skip-go)');
try {
await fsp.access(WGHT_BIN);
} catch {
die(`缺少 ${wghtBinRel()}, 请先运行 pnpm go:build`);
}
// 仍要保证可执行位 (CI 中二进制由 artifact 下载而来, 可能丢失权限)
await fsp.chmod(WGHT_BIN, 0o755);
} else {
if (!hasCommand('go')) die('未找到 go 命令, 请先安装 Go 工具链');
log.step('交叉编译 fontmm-wght (android/arm64)...');
const size = await buildWght();
log.ok(`产物: ${wghtBinRel()} (${size} 字节)`);
}
// ---------- 2. 交叉编译 Zygisk 模块 (字体预加载用的 C++ 程序) ----------
const zygiskBin = path.join(SRC_DIR, 'zygisk', `${TARGET_ABI}.so`);
if (skipZygisk) {
log.info('已跳过 Zygisk 模块编译 (--skip-zygisk)');
try {
await fsp.access(zygiskBin);
} catch {
die(`缺少 ${path.relative(ROOT, zygiskBin)}, 请先运行 pnpm zygisk:build`);
}
} else {
const ndkRoot = await findNdk();
if (!ndkRoot) {
die(
'未找到 Android NDK, 无法编译 Zygisk 模块。\n' +
' 请设置 ANDROID_NDK_HOME, 或下载到 ~/opt/android-ndk-r27c\n' +
' 仅打包现有产物: node dev/pack.mjs --skip-zygisk',
);
}
log.step(`交叉编译 Zygisk 模块 (android/${TARGET_ABI})...`);
const { size } = await buildZygiskModule(ndkRoot, { onLog: (m) => log.detail(m) });
await fsp.mkdir(path.dirname(zygiskBin), { recursive: true });
await fsp.copyFile(path.join(ROOT, 'native', 'build', `${TARGET_ABI}.so`), zygiskBin);
await fsp.chmod(zygiskBin, 0o644);
log.ok(`产物: ${path.relative(ROOT, zygiskBin)} (${size} 字节)`);
}
// ---------- 3. 编译 fontmm-subset (英文字体子集化工具, issue #10) ----------
// 依赖 harfbuzz (静态链接); 其源码需联网获取, 编译产物带缓存见 dev/lib/harfbuzz.mjs
const subsetBin = path.join(SRC_DIR, 'tools', 'fontmm-subset');
if (skipSubset) {
log.info('已跳过 fontmm-subset 编译 (--skip-subset)');
try {
await fsp.access(subsetBin);
} catch {
die(`缺少 ${path.relative(ROOT, subsetBin)}, 请先运行 pnpm subset:build`);
}
} else {
// 复用上一步已定位的 NDK (未走 Zygisk 分支时需重新定位)
const ndkRoot = await findNdk();
if (!ndkRoot) {
die(
'未找到 Android NDK, 无法编译 fontmm-subset。\n' +
' 请设置 ANDROID_NDK_HOME, 或下载到 ~/opt/android-ndk-r27c\n' +
' 仅打包现有产物: node dev/pack.mjs --skip-subset',
);
}
const size = await buildSubsetTool(ndkRoot, subsetBin);
await fsp.chmod(subsetBin, 0o755);
log.ok(`产物: ${path.relative(ROOT, subsetBin)} (${(size / 1048576).toFixed(1)}MB)`);
}
// ---------- 4. 生成模块内可执行文件校验表 (src/SHA256SUMS) ----------
log.step('生成 SHA256 校验文件...');
run(process.execPath, [path.join(ROOT, 'dev', 'gen-sha256.mjs'), '--no-dist'], { cwd: ROOT });
// ---------- 5. 打包 ----------
// 派生字体配置 (fonts_base/ule/font_fallback) 由设备端 customize.sh 扫描生成,
// 不随包分发; 这里一律排除, 避免与设备端生成结果冲突。
const exclude = ['*.git*', '*.DS_Store', '*.swp', '*~', '*.bak', ...DERIVED_XML_RELS];
// 先删旧产物: 避免上一轮的文件残留进新 zip
await fsp.mkdir(DIST_DIR, { recursive: true });
await Promise.all([
fsp.rm(preOut, { force: true }),
fsp.rm(tplOut, { force: true }),
fsp.rm(`${preOut}.sha256`, { force: true }),
fsp.rm(`${tplOut}.sha256`, { force: true }),
]);
// ---------- 6. 预压缩缓存 ----------
// system/fonts/ 占整包压缩量的 ~70%, 而它在多数构建中不变 (仅发布字体时才动)。
// 内容未变时直接复用已压缩数据 (passThrough, 不重新 deflate), 显著缩短打包时间。
//
// 缓存按子树分别管理, 以「文件名 + 大小 + mtime + 权限位」为指纹; 任一项变化即失效,
// 回退为现场压缩并重建缓存。缓存目录 dev/.cache/ 不入库, 缺失/损坏一律优雅降级。
const fontCacheSegment = 'system-fonts';
const fontCachePrefix = 'system/fonts/';
const fontsDir = path.join(SRC_DIR, 'system', 'fonts');
let fontCache = null;
if (CACHE_ENABLED) {
const cacheKey = await subtreeKey(fontsDir);
fontCache = await openCache(fontCacheSegment, cacheKey);
if (fontCache) {
log.ok(`命中预压缩缓存 (${fontCache.entries.length} 个字体文件, 跳过压缩)`);
} else {
log.info('无可用预压缩缓存, 本次将现场压缩并在完成后建立缓存');
}
}
log.step('打包 preplace 版 (含预置字体)...');
const pre = await packDir({
srcDir: SRC_DIR,
outFile: preOut,
exclude,
fixedDate,
cache: fontCache ?? undefined,
});
log.ok(
`preplace: ${pre.files} 文件 / ${pre.dirs} 目录${pre.reused ? ` (复用缓存 ${pre.reused} 个)` : ''}`,
);
log.step('打包 template 版 (FONTS 目录为空)...');
// 排除 FONTS/ 下的字体文件, 但保留目录条目本身 (设备端需要该目录存在)
const tpl = await packDir({
srcDir: SRC_DIR,
outFile: tplOut,
exclude,
excludeFilePrefixes: ['FONTS/'],
fixedDate,
cache: fontCache ?? undefined,
});
log.ok(
`template: ${tpl.files} 文件 / ${tpl.dirs} 目录${tpl.reused ? ` (复用缓存 ${tpl.reused} 个)` : ''}`,
);
await fontCache?.close();
// 未命中且本次确实压缩了字体文件时, 用刚产出的产物建立缓存。
// 以 preplace 包为缓存来源 (它含完整的 system/fonts/); 需确认确实包含字体条目。
if (CACHE_ENABLED && !fontCache && pre.reused === 0) {
const cacheKey = await subtreeKey(fontsDir);
// 从 preplace 包中抽取 system/fonts/ 部分作为缓存片段:
// 直接把整包复制过去会让缓存体积翻倍, 故重建一个只含该子树的 zip。
log.step('建立预压缩缓存...');
const segTmp = path.join(DIST_DIR, '.cache-segment.zip');
try {
await packDir({
srcDir: SRC_DIR,
outFile: segTmp,
exclude,
onlyPrefixes: [fontCachePrefix],
level: COMPRESS_LEVEL,
fixedDate,
});
const ok = await saveCacheFromZip(fontCacheSegment, cacheKey, segTmp, COMPRESS_LEVEL);
if (ok) log.ok('缓存已建立 (下次打包将自动复用)');
} catch (e) {
log.warn(`建立缓存失败 (不影响本次构建): ${e.message}`);
} finally {
await fsp.rm(segTmp, { force: true });
}
}
// ---------- 7. 校验产物 ----------
// 取代原 shell 的 unzip -l / unzip -p 检查: 直接回读 zip 内容并与源文件比对,
// 同时校验条目名、目录条目与派生配置排除情况。
async function verify(zipPath, { label, requireFonts, forbidFonts }) {
const entries = await listEntries(zipPath);
const present = new Set(entries);
if (!present.has('module.prop')) {
die(`${label} 缺少 module.prop (打包目录层级可能有误)`);
}
if (!present.has('FONTS/')) {
die(`${label} 缺少 FONTS/ 目录条目 (设备端需要该目录存在)`);
}
for (const rel of DERIVED_XML_RELS) {
if (present.has(rel)) {
die(`${label} 不应包含派生配置 ${rel} (由设备端生成)`);
}
}
const fontEntries = entries.filter((n) => n.startsWith('FONTS/') && n.endsWith('.ttf'));
if (forbidFonts && fontEntries.length > 0) {
die(`${label} 不应包含 FONTS 字体文件: ${fontEntries.join(', ')}`);
}
if (requireFonts && !fontEntries.includes('FONTS/hans.ttf')) {
die(`${label} 缺少预置简体字体 FONTS/hans.ttf`);
}
// 内容校验: 逐个条目回读并比对磁盘源文件的 sha256
const index = await indexZip(zipPath);
let checked = 0;
for (const [name, info] of index) {
if (info.isDir) continue;
let expected;
try {
expected = hashFile(path.join(SRC_DIR, name));
} catch {
die(`${label} 含源目录不存在的条目: ${name}`);
}
if (expected !== info.sha256) {
die(`${label} 内容校验失败 (与源文件不一致): ${name}`);
}
checked++;
}
return { total: entries.length, checked };
}
const preInfo = await verify(preOut, { label: 'preplace 版', requireFonts: true, forbidFonts: false });
const tplInfo = await verify(tplOut, { label: 'template 版', requireFonts: false, forbidFonts: true });
log.ok(`产物校验通过 (preplace ${preInfo.checked}/${preInfo.total} 条, template ${tplInfo.checked}/${tplInfo.total} 条)`);
// ---------- 8. 生成发布产物校验文件 ----------
run(process.execPath, [path.join(ROOT, 'dev', 'gen-sha256.mjs')], { cwd: ROOT });
// ---------- 完成 ----------
const [preStat, tplStat] = await Promise.all([fsp.stat(preOut), fsp.stat(tplOut)]);
const mb = (n) => `${(n / 1048576).toFixed(1)}MB`;
console.log();
log.ok(`打包完成 (${elapsed()})`);
log.detail(`preplace: ${path.basename(preOut)} (${mb(preStat.size)})`);
log.detail(`template: ${path.basename(tplOut)} (${mb(tplStat.size)})`);
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env node
// dev/sync-fonts-xml.mjs — 以 fonts.xml 为唯一源, 复制生成各派生字体配置 (取代 sync-fonts-xml.sh)
//
// 仅用于开发期本地对照/调试: 模块打包 (dev/pack.mjs) 不再包含派生配置,
// 由刷入脚本 (src/customize.sh) 在设备端扫描系统 XML 生成, 以提升跨 ColorOS 版本兼容性。
//
// 用法: node dev/sync-fonts-xml.mjs
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log, die } from './lib/log.mjs';
import { ROOT, SRC_DIR, FONTS_XML, DERIVED_XML_RELS } from './lib/paths.mjs';
try {
await fsp.access(FONTS_XML);
} catch {
die(`找不到源文件: ${path.relative(ROOT, FONTS_XML)}`);
}
const content = await fsp.readFile(FONTS_XML);
for (const rel of DERIVED_XML_RELS) {
const dest = path.join(SRC_DIR, rel);
await fsp.mkdir(path.dirname(dest), { recursive: true });
await fsp.writeFile(dest, content);
log.ok(`已同步: ${path.relative(ROOT, dest)}`);
}
log.ok(`完成, 共 ${DERIVED_XML_RELS.length} 个派生文件`);
-29
View File
@@ -1,29 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# dev/sync-fonts-xml.sh — 以 fonts.xml 为唯一源, 复制生成各派生字体配置
# ColorOS 在不同场景加载 fonts.xml / fonts_base.xml / fonts_ule.xml / font_fallback.xml,
# 参考 MakeFontsGreatAgain 的做法, 开发阶段直接复制, 避免维护多份几乎重复的 XML
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC="$ROOT_DIR/src/system/etc/fonts.xml"
[ -f "$SRC" ] || {
echo "[!] 找不到源文件: $SRC" >&2
exit 1
}
DEST=(
"$ROOT_DIR/src/system/etc/fonts_base.xml"
"$ROOT_DIR/src/system/etc/fonts_ule.xml"
"$ROOT_DIR/src/system/etc/font_fallback.xml"
"$ROOT_DIR/src/system/system_ext/etc/fonts_base.xml"
"$ROOT_DIR/src/system/system_ext/etc/fonts_ule.xml"
)
for f in "${DEST[@]}"; do
cp -f "$SRC" "$f"
echo "[✓] 已同步: $f"
done
echo "[✓] 完成, 共 ${#DEST[@]} 个派生文件"
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env node
// dev/webzip.mjs — 把 WebUI 构建产物 src/webroot 压成 dist/webroot.zip (调试用)
// 用于单独验证前端产物, 不含字体模块内容; 完整模块打包见 dev/pack.mjs
//
// 用法: node dev/webzip.mjs
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log, die } from './lib/log.mjs';
import { ROOT, WEBROOT_DIR, DIST_DIR } from './lib/paths.mjs';
import { packDir } from './lib/zip.mjs';
try {
await fsp.access(WEBROOT_DIR);
} catch {
die(`${path.relative(ROOT, WEBROOT_DIR)} 不存在, 请先执行 pnpm -C web build`);
}
const out = path.join(DIST_DIR, 'webroot.zip');
// 先删旧产物, 避免残留文件混入
await fsp.rm(out, { force: true });
// SOURCE_DATE_EPOCH: 固定时间戳实现可复现打包 (见 dev/pack.mjs 说明)
const epoch = process.env.SOURCE_DATE_EPOCH;
const fixedDate = epoch ? new Date(Number(epoch) * 1000) : undefined;
// zip 根 = webroot 内容 (不含 webroot 这一层目录)
const { files, dirs } = await packDir({
srcDir: WEBROOT_DIR,
outFile: out,
exclude: ['*.git*', '*.DS_Store'],
level: 9, // 调试产物追求体积最小, 与完整模块打包的 -2 不同
fixedDate,
});
const { size } = await fsp.stat(out);
log.ok(`已打包: ${path.relative(ROOT, out)} (${(size / 1048576).toFixed(1)}MB, ${files} 文件 / ${dirs} 目录)`);
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# dev/webzip.sh — 仅把构建产物 src/webroot 压缩为 dist/webroot.zip (调试 WebUI 用)
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC="$ROOT_DIR/src/webroot"
OUT="$ROOT_DIR/dist/webroot.zip"
command -v zip >/dev/null 2>&1 || {
echo "[!] 未找到 zip 命令, 请先安装" >&2
exit 1
}
[ -d "$SRC" ] || {
echo "[!] $SRC 不存在, 请先执行 pnpm -C web build" >&2
exit 1
}
mkdir -p "$(dirname "$OUT")"
rm -f "$OUT"
# zip 根 = webroot 内容 (不含 webroot 这层目录)
(
cd "$SRC"
zip -r -9 "$OUT" . \
-x '*.git*' \
-x '*.DS_Store'
)
echo "[✓] 已打包: $OUT ($(du -h "$OUT" | cut -f1))"
Binary file not shown.

After

Width:  |  Height:  |  Size: 715 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+7 -9
View File
@@ -1,5 +1,7 @@
// fontmm-wght: 覆写模块字体配置 XML 的 sans-serif family 字重范围
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>] [-xml-dir <模块根>]
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围或多字重静态映射
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>] [-xml-dir <模块根>] [-sync]
// 说明: 优先读取 backup/fonts.xml (若存在) 并结合 FONTS/slot-modes.txt 与 FONTS/multi/ 生成 system/etc/fonts.xml,
// 加 -sync 后复制到各派生配置 (issue #7)
package main
import (
@@ -16,13 +18,9 @@ func main() {
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)")
sync := flag.Bool("sync", false, "覆写后复制 fonts.xml 到各派生配置")
flag.Parse()
if *mode == 0 {
fmt.Println("[-] mode 0: 不处理")
return
}
var customMap map[int]int
if *mode == 3 {
var err error
@@ -36,10 +34,10 @@ func main() {
}
}
changed, err := wght.ApplyToDir(*xmlDir, *mode, *min, *max, customMap)
changed, err := wght.ApplyToDir(*xmlDir, *mode, *min, *max, customMap, *sync)
if err != nil {
fmt.Printf("[x] %v\n", err)
os.Exit(1)
}
fmt.Printf("[✓] 完成, 共覆写 %d 个文件\n", changed)
fmt.Printf("[✓] 完成, 共处理 %d 个文件\n", changed)
}
+360 -58
View File
@@ -4,6 +4,8 @@ package wght
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
@@ -12,9 +14,43 @@ import (
// 标准 9 档字重
var Weights = []int{100, 200, 300, 400, 500, 600, 700, 800, 900}
// 模块内需要覆写的字体配置 XML (相对模块根)
var XMLRelPaths = []string{
"system/etc/fonts.xml",
// axisStyle 描述家族内 <font> 条目的轴配置风格
type axisStyle int
const (
// axisFull: sans-serif 全轴 (ital/wdth/wght)
axisFull axisStyle = iota
// axisWghtOnly: sys-sans-en / zh-* 仅 wght 轴
axisWghtOnly
)
// familySpec 描述一个需要覆写字重的家族及其条目格式
type familySpec struct {
slot string // 所属逻辑槽位: "en" | "hans" | "hant"
openTag string // 家族起始标签 (用于定位与生成)
fontFile string // 家族引用的字体文件
postScript string // postScriptName 属性 (无则为空)
serifFallback bool // 是否包含 fallbackFor="serif" 的 400 条目 (zh-Hans/zh-Hant)
axis axisStyle
}
// 所有生效家族: 英文 (sans-serif / sys-sans-en) 与中文 (zh-Hans / zh-Hant) 都要覆盖,
// 否则中文或英文单独使用时字重映射不生效 (issue #7)
var FamilySpecs = []familySpec{
{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"
BackupXMLRel = "backup/fonts.xml"
)
// 派生配置 (与 fonts.xml 内容一致, 由 -sync 复制生成)
var DerivedXMLRel = []string{
"system/etc/fonts_base.xml",
"system/etc/fonts_ule.xml",
"system/etc/font_fallback.xml",
@@ -22,6 +58,80 @@ var XMLRelPaths = []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 {
@@ -33,66 +143,111 @@ func AveragedAxis(min, max, w int) int {
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
// 生成 sans-serif 家族段 (mode 1/2/3), 使用标准 9 档字重
func GenerateFamily(min, max, mode int, customMap map[int]int) string {
return generateFamily(FamilySpecs[0], Weights, min, max, mode, customMap)
}
// 生成单条 <font> 条目 (按家族风格)
func fontEntryFor(spec familySpec, weight, axisWght int) string {
if spec.axis == axisFull {
return fmt.Sprintf(` <font weight="%d" style="normal">%s
<axis tag="ital" stylevalue="0" />
<axis tag="wdth" stylevalue="100" />
<axis tag="wght" stylevalue="%d" />
</font>`, weight, axisWght)
</font>`, weight, spec.fontFile, axisWght)
}
return fmt.Sprintf(` <font weight="%d" style="normal" postScriptName="%s" >%s
<axis tag="wght" stylevalue="%d"/>
</font>`, weight, spec.postScript, spec.fontFile, 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 {
// 生成 zh-Hans/zh-Hant 家族的 fallbackFor="serif" 400 条目
func serifEntry(spec familySpec, fontFile string) string {
return fmt.Sprintf(` <font weight="400" style="normal" fallbackFor="serif"
postScriptName="%s">%s
</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=自定义映射)
// weights 为声明字重集 (取自原家族, 保持设备 XML 一致性)
func generateFamily(spec familySpec, weights []int, min, max, mode int, customMap map[int]int) string {
ws := weights
if mode == 3 && len(customMap) > 0 {
ws := make([]int, 0, len(customMap))
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]))
}
var lines []string
for _, w := range ws {
if mode == 1 && (w < min || w > max) {
continue
}
} 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)
axis := w
if mode == 2 {
axis = AveragedAxis(min, max, w)
} else if mode == 3 {
if v, ok := customMap[w]; ok {
axis = v
} else {
axis = w
axis = AveragedAxis(min, max, w)
}
lines = append(lines, fontEntry(w, axis))
}
lines = append(lines, fontEntryFor(spec, w, axis))
if spec.serifFallback && w == 400 {
lines = append(lines, serifEntry(spec, spec.fontFile))
}
}
return " <family name=\"sans-serif\">\n" + strings.Join(lines, "\n") + "\n </family>"
return " " + spec.openTag + "\n" + strings.Join(lines, "\n") + "\n </family>"
}
// 在完整 XML 中替换 sans-serif family 段; 未找到或 mode 0 时原样返回
// 通过深度计数匹配对应的 </family> (防止嵌套 family 误切), 并整行替换避免段首被重复缩进
func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string {
if mode == 0 {
return xml
}
const startTag = `<family name="sans-serif">`
start := findFamilyStart(xml, startTag)
// 在完整 XML 中覆写指定家族段; 家族不存在时原样返回
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
}
end := matchFamilyClose(xml, start+len(startTag))
end := matchFamilyClose(xml, start+len(spec.openTag))
if end < 0 {
return xml
}
block := xml[start:end]
if multi == nil && mode == 0 {
return xml
}
// 字重集选择: 多字重 / 裁切保留原家族声明字重 (兼容设备 XML, 含 1000),
// 平均分配固定 9 档完整粗细, 自定义映射由映射文件的键决定
weights := Weights
if multi != nil || mode == 1 {
if ex := extractWeights(block); len(ex) > 0 {
weights = ex
}
}
// 整行替换 (含行首缩进与闭合标签后的换行), 保持与原有段一致的缩进
lineStart := start
for lineStart > 0 && xml[lineStart-1] != '\n' {
@@ -105,7 +260,35 @@ func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string
if lineEnd < len(xml) {
lineEnd++ // 吃掉换行
}
return xml[:lineStart] + GenerateFamily(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 {
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 {
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
}
// 查找 startTag 的位置 (跳过 XML 注释, 避免误匹配注释内的文本)
@@ -130,7 +313,7 @@ func findFamilyStart(xml, startTag string) int {
}
}
// 从紧随 <family name="sans-serif"> 之后的位置开始, 找到配对的 </family> (含嵌套),
// 从紧随 <family ...> 之后的位置开始, 找到配对的 </family> (含嵌套),
// 返回其结束位置 (含标签); 未找到返回 -1
func matchFamilyClose(xml string, start int) int {
depth := 1
@@ -179,6 +362,22 @@ func matchFamilyClose(xml string, start int) int {
return -1
}
var weightRe = regexp.MustCompile(`<font weight="(\d+)"`)
// 提取家族段内声明字重 (去重并升序), 保留设备 XML 的字重集
func extractWeights(block string) []int {
var ws []int
seen := map[int]bool{}
for _, m := range weightRe.FindAllStringSubmatch(block, -1) {
if n, err := strconv.Atoi(m[1]); err == nil && !seen[n] {
ws = append(ws, n)
seen[n] = true
}
}
sort.Ints(ws)
return ws
}
// 读取自定义映射文件 (每行 "weight axis")
func ReadCustomMap(path string) (map[int]int, error) {
m := map[int]int{}
@@ -204,26 +403,129 @@ func ReadCustomMap(path string) (map[int]int, error) {
return m, nil
}
// ApplyToDir 覆写模块根目录下的全部字体配置 XML, 返回覆写文件数
func ApplyToDir(xmlDir string, mode, min, max int, customMap map[int]int) (int, error) {
// 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)
currentData, err := os.ReadFile(src)
if err != nil {
return 0, fmt.Errorf("读取 %s 失败: %w", SourceXMLRel, err)
}
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
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)
if replaced != string(currentData) {
if err := os.WriteFile(src, []byte(replaced), 0o644); err != nil {
return changed, fmt.Errorf("写入失败 %s: %w", SourceXMLRel, err)
}
changed++
fmt.Printf("[✓] 已覆写: %s\n", rel)
fmt.Printf("[✓] 已覆写: %s\n", SourceXMLRel)
} else {
fmt.Printf("[-] 无变化: %s\n", SourceXMLRel)
}
if sync {
for _, rel := range DerivedXMLRel {
p := filepath.Join(xmlDir, rel)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return changed, fmt.Errorf("创建目录失败 %s: %w", filepath.Dir(p), err)
}
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
}
+222
View File
@@ -2,6 +2,8 @@ package wght
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
@@ -99,6 +101,41 @@ func TestApplyWghtMode(t *testing.T) {
}
}
// 所有生效家族 (sans-serif / sys-sans-en / zh-Hans / zh-Hant) 都应被覆写,
// 保证中英文都有正确的字重映射 (issue #7)
func TestApplyWghtModeAllFamilies(t *testing.T) {
xml := "<?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 </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 </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\" fallbackFor=\"serif\"\n" +
" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n </font>\n </family>\n" +
" <family lang=\"zh-Hant,zh-Bopo\">\n <font weight=\"100\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_TC\">SysSans-Hant-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n </family>\n" +
"</familyset>\n"
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
for _, tag := range []string{
`<family name="sans-serif">`,
`<family name="sys-sans-en">`,
`<family lang="zh-Hans">`,
`<family lang="zh-Hant,zh-Bopo">`,
} {
if strings.Count(replaced, tag) != 1 {
t.Errorf("覆写后应保留且只出现一次 %s", tag)
}
}
// zh-Hans 家族应保留 serif fallback 条目
if !strings.Contains(replaced, `fallbackFor="serif"`) {
t.Error("zh-Hans 家族丢失 fallbackFor=\"serif\" 条目")
}
// 各家族字号都应含平均分配后的 200 -> 233
if strings.Count(replaced, `stylevalue="233"`) != 4 {
t.Errorf("各家族应有 4 处 233 轴值, 实际 %d", strings.Count(replaced, `stylevalue="233"`))
}
}
// 段内有嵌套 family (如 sans-serif-black) 时, 必须配对正确的 </family>,
// 不能把嵌套段的闭合当成外层闭合导致尾部丢失 (曾导致无法开机)
func TestApplyWghtModeNestedFamily(t *testing.T) {
@@ -157,3 +194,188 @@ func TestApplyWghtModeNoDoubleIndent(t *testing.T) {
t.Errorf("段首应为 4 空格缩进:\n%s", replaced)
}
}
// ApplyToDir 只覆写主配置 fonts.xml, sync 时复制到各派生配置 (issue #7)
func TestApplyToDirSync(t *testing.T) {
dir := t.TempDir()
mkfile := func(rel, content string) {
p := 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)
}
}
base := "<familyset>\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" +
"</familyset>\n"
mkfile(SourceXMLRel, base)
// 派生配置预置旧内容, 验证被覆盖
for _, rel := range DerivedXMLRel {
mkfile(rel, "<familyset>\n</familyset>\n")
}
changed, err := ApplyToDir(dir, 2, 150, 700, nil, true)
if err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
// 1 份主配置 + 5 份派生 = 6
if changed != 1+len(DerivedXMLRel) {
t.Fatalf("changed = %d, want %d", changed, 1+len(DerivedXMLRel))
}
src, err := os.ReadFile(dir + "/" + SourceXMLRel)
if err != nil {
t.Fatal(err)
}
for _, rel := range DerivedXMLRel {
data, err := os.ReadFile(dir + "/" + rel)
if err != nil {
t.Fatalf("派生配置缺失 %s: %v", rel, err)
}
if string(data) != string(src) {
t.Errorf("派生配置 %s 与 fonts.xml 不一致", rel)
}
}
if !strings.Contains(string(src), `stylevalue="233"`) {
t.Error("覆写后应含平均分配值 233")
}
}
// mode 0 + sync: 不改内容, 仅把 fonts.xml 复制到派生配置 (customize.sh 用)
func TestApplyToDirSyncMode0(t *testing.T) {
dir := t.TempDir()
base := "<familyset>\n</familyset>\n"
if err := os.MkdirAll(dir+"/system/etc", 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dir+"/"+SourceXMLRel, []byte(base), 0o644); err != nil {
t.Fatal(err)
}
changed, err := ApplyToDir(dir, 0, 100, 900, nil, true)
if err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
if changed != len(DerivedXMLRel) {
t.Fatalf("mode0+sync changed = %d, want %d", changed, len(DerivedXMLRel))
}
for _, rel := range DerivedXMLRel {
data, err := os.ReadFile(dir + "/" + rel)
if err != nil {
t.Fatalf("派生配置缺失 %s: %v", rel, err)
}
if string(data) != base {
t.Errorf("派生配置 %s 内容不一致", rel)
}
}
}
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))
}
}
+186
View File
@@ -0,0 +1,186 @@
// FontMM Zygisk 模块 — 字体预加载
// SPDX-License-Identifier: GPL-3.0
//
// 背景: Android 12 起字体不再由 zygote 预加载, 而是各 app 进程按需读取。
// 当 Root 管理器对某个 app 执行「卸载模块」(DenyList / App Profile), 该 app 的
// 挂载视图里就没有模块的字体了; 但 app 启动早期仍会去读这些字体, 结果读不到,
// 表现为字体显示异常甚至闪退。
//
// 解法: 在 app specialize *之前* (此时进程仍是 zygote 的挂载视图) 让 ART 把字体
// 数据读进 Skia 的全局缓存。缓存的 key 是字体路径, 且进程生命周期内不清除, 因此
// specialize 之后即使路径已不可访问, 仍能命中缓存正常渲染。
//
// 与参考实现 (JingMatrix/FontLoader) 的差异:
// 1. 只预热 FontMM 自己的字体 —— 字体清单在编译期已知, 无需 root companion
// 进程扫描 /data/adb/modules/*/system/fonts 再通过 socket 传回。
// 这样省掉了整个 companion 与 IPC, 代码量与攻击面都大幅缩小。
// 2. 不包含 HideFromMaps (把字体从 /proc/self/maps 摘除的反检测逻辑)。
// 参考实现里该函数是死代码, 从未被调用; 且它对字体正常渲染并非必需。
//
// 目标架构: arm64 (ColorOS 16 设备), 产物 zygisk/arm64-v8a.so
//
// 加载约束 (编译选项据此确定, 见 dev/lib/ndk.mjs):
// Zygisk 提供者 (Magisk / Zygisk Next / ReZygisk 等) 用自己的 ELF 加载器装载本库,
// 不使用系统 dlopen。该加载器只从系统库目录解析依赖, 因此本库不得依赖
// libc++_shared.so, 也不得引用其提供的 __cxa_guard_* (故禁用线程安全静态初始化)。
#include <jni.h>
#include <unistd.h>
#include <android/log.h>
#include <cstring>
#include "zygisk.hpp"
using zygisk::Api;
using zygisk::AppSpecializeArgs;
using zygisk::ServerSpecializeArgs;
#define LOG_TAG "FontMM"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
// 需要预热的字体 (系统路径)。
//
// 这些正是 apply.sh 会写入 system/fonts/ 的文件, 也是在 fonts.xml 中被
// sans-serif / sys-sans-en / zh-Hans / zh-Hant 等家族引用的文件。缺一个都可能
// 让某个家族在 DenyList 应用里渲染失败。
//
// 注意: 仅列出 FontMM 确实会替换的文件 (与 src/apply.sh 的映射表保持一致);
// 未设置的槽位不会产生对应文件, 此时该项会被 prepare 阶段跳过。
static const char *const kFontFiles[] = {
// 中文简体槽位
"/system/fonts/SysSans-Hans-Regular.ttf",
"/system/fonts/SysFont-Static-Regular.ttf",
"/system/fonts/SysFont-Myanmar.ttf",
"/system/fonts/SysFont-Hans-Regular.ttf",
"/system/fonts/FontMM-Hans-100.ttf",
"/system/fonts/FontMM-Hans-200.ttf",
"/system/fonts/FontMM-Hans-300.ttf",
"/system/fonts/FontMM-Hans-500.ttf",
"/system/fonts/FontMM-Hans-600.ttf",
"/system/fonts/FontMM-Hans-700.ttf",
"/system/fonts/FontMM-Hans-800.ttf",
"/system/fonts/FontMM-Hans-900.ttf",
// 中文繁体槽位
"/system/fonts/SysSans-Hant-Regular.ttf",
"/system/fonts/SysFont-Hant-Regular.ttf",
"/system/fonts/FontMM-Hant-100.ttf",
"/system/fonts/FontMM-Hant-200.ttf",
"/system/fonts/FontMM-Hant-300.ttf",
"/system/fonts/FontMM-Hant-500.ttf",
"/system/fonts/FontMM-Hant-600.ttf",
"/system/fonts/FontMM-Hant-700.ttf",
"/system/fonts/FontMM-Hant-800.ttf",
"/system/fonts/FontMM-Hant-900.ttf",
// 英文 & 数字槽位
"/system/fonts/SysSans-En-Regular.ttf",
"/system/fonts/SysFont-Regular.ttf",
"/system/fonts/FontMM-En-100.ttf",
"/system/fonts/FontMM-En-200.ttf",
"/system/fonts/FontMM-En-300.ttf",
"/system/fonts/FontMM-En-500.ttf",
"/system/fonts/FontMM-En-600.ttf",
"/system/fonts/FontMM-En-700.ttf",
"/system/fonts/FontMM-En-800.ttf",
"/system/fonts/FontMM-En-900.ttf",
// 等宽槽位
"/system/fonts/DroidSansMono.ttf",
// Emoji 槽位
"/system/fonts/NotoColorEmoji.ttf",
};
/**
* 预热单个字体: 调用 Typeface.nativeWarmUpCache(String)。
*
* 该方法在 AOSP 中是 private static native (Typeface.java), 签名 "(Ljava/lang/String;)V",
* 从 Android 12 到 16 均存在。其原生实现为 Typeface_warmUpCache -> makeSkDataCached,
* 把字体文件 mmap 进 Skia 的静态数据缓存 (以路径字符串为 key, 进程内不清除)。
*
* 这里通过 GetStaticMethodID 直接获取, 不做权限检查 —— 在 preAppSpecialize
* 阶段进程仍具备 zygote 权限, 可以正常拿到该私有方法。
*/
static bool WarmUpFont(JNIEnv *env, jclass typefaceCls, jmethodID methodId, const char *path) {
// 只预热确实存在的文件: 未设置的槽位不会有对应文件
if (access(path, F_OK) != 0) return false;
jstring jPath = env->NewStringUTF(path);
if (jPath == nullptr) {
env->ExceptionClear();
return false;
}
env->CallStaticVoidMethod(typefaceCls, methodId, jPath);
env->DeleteLocalRef(jPath);
if (env->ExceptionCheck()) {
LOGW("预热失败: %s", path);
// 打印并清除异常, 避免影响 zygote 后续的 specialize 流程
env->ExceptionDescribe();
env->ExceptionClear();
return false;
}
LOGD("已预热: %s", path);
return true;
}
class FontMMModule : public zygisk::ModuleBase {
public:
void onLoad(Api *api, JNIEnv *env) override {
this->api = api;
this->env = env;
}
void preAppSpecialize([[maybe_unused]] AppSpecializeArgs *args) override {
// 对所有 app 进程都预热, 不按 uid 过滤。
//
// 这里刻意不做「跳过系统进程」的优化: ColorOS 有大量以 android.uid.system
// (uid 1000) 运行的系统应用, 它们同样会被加入 DenyList 而失去字体访问权,
// 正是最需要预热的对象。按 uid 过滤会恰好漏掉这类进程, 导致系统应用字体异常。
//
// 每个 app 进程只预热一次, 且只读已挂载的字体文件, 开销可接受。
PreloadFonts();
// 本模块只做一次性预热, 不留任何 hook, 可以安全卸载
api->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);
}
void preServerSpecialize([[maybe_unused]] ServerSpecializeArgs *args) override {
api->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);
}
private:
Api *api{};
JNIEnv *env{};
void PreloadFonts() {
jclass typefaceCls = env->FindClass("android/graphics/Typeface");
if (typefaceCls == nullptr) {
env->ExceptionClear();
LOGE("找不到 android.graphics.Typeface");
return;
}
jmethodID methodId = env->GetStaticMethodID(typefaceCls, "nativeWarmUpCache",
"(Ljava/lang/String;)V");
if (methodId == nullptr) {
env->ExceptionClear();
LOGE("找不到 Typeface.nativeWarmUpCache (系统版本不兼容?)");
env->DeleteLocalRef(typefaceCls);
return;
}
int ok = 0;
for (const char *path : kFontFiles) {
if (WarmUpFont(env, typefaceCls, methodId, path)) ok++;
}
LOGD("字体预热完成: %d/%zu", ok, sizeof(kFontFiles) / sizeof(kFontFiles[0]));
env->DeleteLocalRef(typefaceCls);
}
};
REGISTER_ZYGISK_MODULE(FontMMModule)
+288
View File
@@ -0,0 +1,288 @@
// fontmm-subset — 英文字体自动子集化 (issue #10)
// SPDX-License-Identifier: GPL-3.0
//
// 背景: fonts.xml 中 sans-serif / sys-sans-en 家族排在 zh-Hans / zh-Hant 之前,
// 因此 en.ttf 一旦自带 CJK 字形, 就会把这些字形也用于中文渲染, 从而盖掉
// hans.ttf / hant.ttf —— 表现为「换了中文字体但部分汉字没变」。
//
// Android 的 fonts.xml 无法限定某个字体「只负责英文」, 唯一可靠做法是在应用前
// 把 en.ttf 裁剪成只含拉丁字符的子集。
//
// 实现: 直接使用 harfbuzz 的 subset API (静态链接进本程序)。
// - 相比 Pyodide + fontTools: 体积与启动开销小几个数量级 (无需 Python 运行时)
// - 可作为独立 CLI 运行于设备端, 因此 WebUI 与手动放字体两条路径都能覆盖
// - 完整保留可变字体特性: fvar / gvar / STAT 与 GSUB / GPOS / GDEF 均不丢失
// (已实测: 子集后 wght 轴范围与各字形变形数据都在, 字重覆写功能不受影响)
//
// 用法:
// fontmm-subset -check <font.ttf>
// 检测字体是否含 CJK 字形。含则退出码 1, 不含则 0 (供调用方判断是否需要处理)。
// fontmm-subset -in <font.ttf> -out <subset.ttf> [-minimal] [-keep-cjk]
// 生成子集。默认保留拉丁/希腊/西里尔与常用符号;
// -minimal 仅保留 ASCII/西欧 (体积更小, 但希腊/西里尔会缺字);
// -keep-cjk 额外保留 CJK 区块 (默认不保留)。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <string>
#include <hb.h>
#include <hb-subset.h>
#include <hb-ot.h>
// ---------- 字符集定义 ----------
// 基础拉丁 + 数字 + 常用标点 (保留范围, 与 en 槽位的用途对应)
struct Range {
hb_codepoint_t first;
hb_codepoint_t last;
};
// 完整范围 (默认): 覆盖拉丁、希腊、西里尔与常用符号。
// 为何不默认收窄: 西里尔/希腊字母虽不常用, 但缺字会直接显示豆腐块,
// 而它们只占几十 KB —— 相对原字体 (常达数十 MB) 可忽略, 不值得为体积冒险。
static const Range kLatinRanges[] = {
{0x0000, 0x00FF}, // 拉丁字母补充 (Basic Latin + Latin-1)
{0x0100, 0x024F}, // 拉丁字母扩展 A/B
{0x0250, 0x036F}, // 国际音标 / 修饰字母 / 组合附加符号 (重音排版必需)
{0x0370, 0x03FF}, // 希腊字母
{0x0400, 0x04FF}, // 西里尔字母
{0x2000, 0x206F}, // 常用标点 (省略号、破折号、各类空格)
{0x2070, 0x209F}, // 上下标
{0x20A0, 0x20CF}, // 货币符号
{0x2100, 0x214F}, // 字母式符号
{0x2150, 0x218F}, // 数字形式 (分数等)
{0x2190, 0x21FF}, // 箭头
{0x2200, 0x22FF}, // 数学运算符
{0x2460, 0x24FF}, // 带圈数字
{0x25A0, 0x26FF}, // 几何图形 / 杂项符号
{0x3000, 0x303F}, // CJK 标点 (中文排版需要, 但不算「汉字字形」)
{0xFF00, 0xFFEF}, // 全角形式 (全角标点/字母)
};
// 精简范围 (-minimal): 仅 ASCII + 西欧 + 常用标点。
// 适用于明确只要英文/数字的场景, 体积更小; 代价是希腊/西里尔等会缺字。
static const Range kMinimalRanges[] = {
{0x0000, 0x00FF}, // Basic Latin + Latin-1 (含西欧重音字母)
{0x0100, 0x017F}, // 拉丁字母扩展 A
{0x2000, 0x206F}, // 常用标点
{0x20A0, 0x20CF}, // 货币符号
{0xFF00, 0xFFEF}, // 全角形式
};
// CJK 判定范围: 命中即认为该字体自带中文字形, 需要子集化
static const Range kCjkRanges[] = {
{0x3400, 0x4DBF}, // CJK 扩展 A
{0x4E00, 0x9FFF}, // CJK 统一表意文字
{0xF900, 0xFAFF}, // CJK 兼容表意文字
{0x20000, 0x2A6DF}, // CJK 扩展 B
{0x2A700, 0x2EBEF}, // CJK 扩展 C-F
{0x2F800, 0x2FA1F}, // CJK 兼容表意文字补充
{0x30000, 0x323AF}, // CJK 扩展 G-I
{0x3040, 0x30FF}, // 日文假名 (CJK 字体通常连带覆盖)
{0xAC00, 0xD7AF}, // 谚文音节
};
template <size_t N>
static void addRanges(hb_set_t *set, const Range (&ranges)[N], hb_face_t *face) {
// 用 hb_set_add_range 逐段加入; harfbuzz 会与实际 cmap 求交,
// 因此不存在的字形范围不会带来额外体积
for (const auto &r : ranges) {
hb_set_add_range(set, r.first, r.last);
}
(void) face;
}
// 统计指定范围内字体实际覆盖的码点数
template <size_t N>
static unsigned countCoverage(hb_face_t *face, const Range (&ranges)[N]) {
hb_set_t *faceUnicodes = hb_set_create();
hb_face_collect_unicodes(face, faceUnicodes);
unsigned total = 0;
for (const auto &r : ranges) {
hb_set_t *probe = hb_set_create();
hb_set_add_range(probe, r.first, r.last);
hb_set_intersect(probe, faceUnicodes);
total += hb_set_get_population(probe);
hb_set_destroy(probe);
}
hb_set_destroy(faceUnicodes);
return total;
}
// ---------- 文件读写 ----------
static bool readFile(const char *path, std::vector<char> &out) {
FILE *f = fopen(path, "rb");
if (!f) return false;
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
if (n <= 0) {
fclose(f);
return false;
}
out.resize(static_cast<size_t>(n));
size_t got = fread(out.data(), 1, out.size(), f);
fclose(f);
return got == out.size();
}
static bool writeFile(const char *path, const char *data, size_t len) {
FILE *f = fopen(path, "wb");
if (!f) return false;
size_t put = fwrite(data, 1, len, f);
fclose(f);
return put == len;
}
// ---------- 主流程 ----------
static void usage(const char *argv0) {
fprintf(stderr,
"用法:\n"
" %s -check <font.ttf> 检测是否含 CJK 字形 (含则退出码 1)\n"
" %s -in <font.ttf> -out <out.ttf> 生成英文子集\n"
" [-minimal] 仅保留 ASCII/西欧 (默认含希腊/西里尔)\n"
" [-keep-cjk] 额外保留 CJK 区块 (默认不保留)\n",
argv0, argv0);
}
int main(int argc, char **argv) {
const char *checkPath = nullptr;
const char *inPath = nullptr;
const char *outPath = nullptr;
bool keepCjk = false;
bool minimal = false;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-check") == 0 && i + 1 < argc) {
checkPath = argv[++i];
} else if (strcmp(argv[i], "-in") == 0 && i + 1 < argc) {
inPath = argv[++i];
} else if (strcmp(argv[i], "-out") == 0 && i + 1 < argc) {
outPath = argv[++i];
} else if (strcmp(argv[i], "-keep-cjk") == 0) {
keepCjk = true;
} else if (strcmp(argv[i], "-minimal") == 0) {
minimal = true;
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
usage(argv[0]);
return 0;
} else {
fprintf(stderr, "[x] 未知参数: %s\n", argv[i]);
usage(argv[0]);
return 2;
}
}
// ---- 检测模式 ----
if (checkPath) {
std::vector<char> data;
if (!readFile(checkPath, data)) {
fprintf(stderr, "[x] 无法读取: %s\n", checkPath);
return 2;
}
hb_blob_t *blob = hb_blob_create(data.data(), data.size(), HB_MEMORY_MODE_READONLY, nullptr, nullptr);
hb_face_t *face = hb_face_create(blob, 0);
if (hb_face_get_glyph_count(face) == 0) {
fprintf(stderr, "[x] 不是有效的字体文件: %s\n", checkPath);
hb_face_destroy(face);
hb_blob_destroy(blob);
return 2;
}
unsigned cjk = countCoverage(face, kCjkRanges);
unsigned latin = countCoverage(face, kLatinRanges);
hb_face_destroy(face);
hb_blob_destroy(blob);
// 输出统计, 供调用方展示 (stdout 保持机器可读)
printf("cjk=%u latin=%u\n", cjk, latin);
// 含 CJK 字形 → 退出码 1 (需要子集化)
return cjk > 0 ? 1 : 0;
}
// ---- 子集化模式 ----
if (!inPath || !outPath) {
usage(argv[0]);
return 2;
}
std::vector<char> data;
if (!readFile(inPath, data)) {
fprintf(stderr, "[x] 无法读取: %s\n", inPath);
return 2;
}
hb_blob_t *blob = hb_blob_create(data.data(), data.size(), HB_MEMORY_MODE_READONLY, nullptr, nullptr);
hb_face_t *face = hb_face_create(blob, 0);
if (hb_face_get_glyph_count(face) == 0) {
fprintf(stderr, "[x] 不是有效的字体文件: %s\n", inPath);
hb_face_destroy(face);
hb_blob_destroy(blob);
return 2;
}
hb_subset_input_t *input = hb_subset_input_create_or_fail();
if (!input) {
fprintf(stderr, "[x] 初始化子集器失败\n");
hb_face_destroy(face);
hb_blob_destroy(blob);
return 1;
}
hb_set_t *unicodes = hb_subset_input_unicode_set(input);
if (minimal) {
addRanges(unicodes, kMinimalRanges, face);
} else {
addRanges(unicodes, kLatinRanges, face);
}
if (keepCjk) addRanges(unicodes, kCjkRanges, face);
// NOTDEF_OUTLINE: 保留 .notdef 字形轮廓。缺失时部分渲染器会显示空白框异常
hb_subset_input_set_flags(input, HB_SUBSET_FLAGS_NOTDEF_OUTLINE);
// 注: 不设置 NO_HINTING —— 保留渲染提示, 小字号下更清晰
// 注: 不设置 NO_LAYOUT_CLOSURE —— 保留 GSUB/GPOS 闭包, 连字与字距正常
hb_face_t *subset = hb_subset_or_fail(face, input);
if (!subset) {
fprintf(stderr, "[x] 子集化失败 (字体可能损坏或格式不受支持)\n");
hb_subset_input_destroy(input);
hb_face_destroy(face);
hb_blob_destroy(blob);
return 1;
}
hb_blob_t *outBlob = hb_face_reference_blob(subset);
unsigned int len = 0;
const char *ptr = hb_blob_get_data(outBlob, &len);
if (!ptr || len == 0 || !writeFile(outPath, ptr, len)) {
fprintf(stderr, "[x] 写入失败: %s\n", outPath);
hb_blob_destroy(outBlob);
hb_face_destroy(subset);
hb_subset_input_destroy(input);
hb_face_destroy(face);
hb_blob_destroy(blob);
return 1;
}
// 校验子集确实不含 CJK 字形 (除非显式要求保留)
unsigned residual = 0;
if (!keepCjk) {
residual = countCoverage(subset, kCjkRanges);
}
printf("in=%zu out=%u residual_cjk=%u\n", data.size(), len, residual);
hb_blob_destroy(outBlob);
hb_face_destroy(subset);
hb_subset_input_destroy(input);
hb_face_destroy(face);
hb_blob_destroy(blob);
// 子集后仍残留 CJK 说明裁剪未达预期, 应视为失败以免用户以为已生效
if (residual > 0) {
fprintf(stderr, "[!] 子集后仍含 %u 个 CJK 码点\n", residual);
return 1;
}
return 0;
}
+395
View File
@@ -0,0 +1,395 @@
/* Copyright 2022-2023 John "topjohnwu" Wu
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
// This is the public API for Zygisk modules.
// DO NOT MODIFY ANY CODE IN THIS HEADER.
#pragma once
#include <jni.h>
#define ZYGISK_API_VERSION 5
/*
***************
* Introduction
***************
On Android, all app processes are forked from a special daemon called "Zygote".
For each new app process, zygote will fork a new process and perform "specialization".
This specialization operation enforces the Android security sandbox on the newly forked
process to make sure that 3rd party application code is only loaded after it is being
restricted within a sandbox.
On Android, there is also this special process called "system_server". This single
process hosts a significant portion of system services, which controls how the
Android operating system and apps interact with each other.
The Zygisk framework provides a way to allow developers to build modules and run custom
code before and after system_server and any app processes' specialization.
This enable developers to inject code and alter the behavior of system_server and app processes.
Please note that modules will only be loaded after zygote has forked the child process.
THIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM_SERVER PROCESS, NOT THE ZYGOTE DAEMON!
*********************
* Development Guide
*********************
Define a class and inherit zygisk::ModuleBase to implement the functionality of your module.
Use the macro REGISTER_ZYGISK_MODULE(className) to register that class to Zygisk.
Example code:
static jint (*orig_logger_entry_max)(JNIEnv *env);
static jint my_logger_entry_max(JNIEnv *env) { return orig_logger_entry_max(env); }
class ExampleModule : public zygisk::ModuleBase {
public:
void onLoad(zygisk::Api *api, JNIEnv *env) override {
this->api = api;
this->env = env;
}
void preAppSpecialize(zygisk::AppSpecializeArgs *args) override {
JNINativeMethod methods[] = {
{ "logger_entry_max_payload_native", "()I", (void*) my_logger_entry_max },
};
api->hookJniNativeMethods(env, "android/util/Log", methods, 1);
*(void **) &orig_logger_entry_max = methods[0].fnPtr;
}
private:
zygisk::Api *api;
JNIEnv *env;
};
REGISTER_ZYGISK_MODULE(ExampleModule)
-----------------------------------------------------------------------------------------
Since your module class's code runs with either Zygote's privilege in pre[XXX]Specialize,
or runs in the sandbox of the target process in post[XXX]Specialize, the code in your class
never runs in a true superuser environment.
If your module require access to superuser permissions, you can create and register
a root companion handler function. This function runs in a separate root companion
daemon process, and an Unix domain socket is provided to allow you to perform IPC between
your target process and the root companion process.
Example code:
static void example_handler(int socket) { ... }
REGISTER_ZYGISK_COMPANION(example_handler)
*/
namespace zygisk {
struct Api;
struct AppSpecializeArgs;
struct ServerSpecializeArgs;
class ModuleBase {
public:
// This method is called as soon as the module is loaded into the target process.
// A Zygisk API handle will be passed as an argument.
virtual void onLoad([[maybe_unused]] Api *api, [[maybe_unused]] JNIEnv *env) {}
// This method is called before the app process is specialized.
// At this point, the process just got forked from zygote, but no app specific specialization
// is applied. This means that the process does not have any sandbox restrictions and
// still runs with the same privilege of zygote.
//
// All the arguments that will be sent and used for app specialization is passed as a single
// AppSpecializeArgs object. You can read and overwrite these arguments to change how the app
// process will be specialized.
//
// If you need to run some operations as superuser, you can call Api::connectCompanion() to
// get a socket to do IPC calls with a root companion process.
// See Api::connectCompanion() for more info.
virtual void preAppSpecialize([[maybe_unused]] AppSpecializeArgs *args) {}
// This method is called after the app process is specialized.
// At this point, the process has all sandbox restrictions enabled for this application.
// This means that this method runs with the same privilege of the app's own code.
virtual void postAppSpecialize([[maybe_unused]] const AppSpecializeArgs *args) {}
// This method is called before the system server process is specialized.
// See preAppSpecialize(args) for more info.
virtual void preServerSpecialize([[maybe_unused]] ServerSpecializeArgs *args) {}
// This method is called after the system server process is specialized.
// At this point, the process runs with the privilege of system_server.
virtual void postServerSpecialize([[maybe_unused]] const ServerSpecializeArgs *args) {}
};
struct AppSpecializeArgs {
// Required arguments. These arguments are guaranteed to exist on all Android versions.
jint &uid;
jint &gid;
jintArray &gids;
jint &runtime_flags;
jobjectArray &rlimits;
jint &mount_external;
jstring &se_info;
jstring &nice_name;
jstring &instruction_set;
jstring &app_data_dir;
// Optional arguments. Please check whether the pointer is null before de-referencing
jintArray *const fds_to_ignore;
jboolean *const is_child_zygote;
jboolean *const is_top_app;
jobjectArray *const pkg_data_info_list;
jobjectArray *const whitelisted_data_info_list;
jboolean *const mount_data_dirs;
jboolean *const mount_storage_dirs;
jboolean *const mount_sysprop_overrides;
AppSpecializeArgs() = delete;
};
struct ServerSpecializeArgs {
jint &uid;
jint &gid;
jintArray &gids;
jint &runtime_flags;
jlong &permitted_capabilities;
jlong &effective_capabilities;
ServerSpecializeArgs() = delete;
};
namespace internal {
struct api_table;
template <class T> void entry_impl(api_table *, JNIEnv *);
}
// These values are used in Api::setOption(Option)
enum Option : int {
// Force Magisk's denylist unmount routines to run on this process.
//
// Setting this option only makes sense in preAppSpecialize.
// The actual unmounting happens during app process specialization.
//
// Set this option to force all Magisk and modules' files to be unmounted from the
// mount namespace of the process, regardless of the denylist enforcement status.
FORCE_DENYLIST_UNMOUNT = 0,
// When this option is set, your module's library will be dlclose-ed after post[XXX]Specialize.
// Be aware that after dlclose-ing your module, all of your code will be unmapped from memory.
// YOU MUST NOT ENABLE THIS OPTION AFTER HOOKING ANY FUNCTIONS IN THE PROCESS.
DLCLOSE_MODULE_LIBRARY = 1,
};
// Bit masks of the return value of Api::getFlags()
enum StateFlag : uint32_t {
// The user has granted root access to the current process
PROCESS_GRANTED_ROOT = (1u << 0),
// The current process was added on the denylist
PROCESS_ON_DENYLIST = (1u << 1),
};
// All API methods will stop working after post[XXX]Specialize as Zygisk will be unloaded
// from the specialized process afterwards.
struct Api {
// Connect to a root companion process and get a Unix domain socket for IPC.
//
// This API only works in the pre[XXX]Specialize methods due to SELinux restrictions.
//
// The pre[XXX]Specialize methods run with the same privilege of zygote.
// If you would like to do some operations with superuser permissions, register a handler
// function that would be called in the root process with REGISTER_ZYGISK_COMPANION(func).
// Another good use case for a companion process is that if you want to share some resources
// across multiple processes, hold the resources in the companion process and pass it over.
//
// The root companion process is ABI aware; that is, when calling this method from a 32-bit
// process, you will be connected to a 32-bit companion process, and vice versa for 64-bit.
//
// Returns a file descriptor to a socket that is connected to the socket passed to your
// module's companion request handler. Returns -1 if the connection attempt failed.
int connectCompanion();
// Get the file descriptor of the root folder of the current module.
//
// This API only works in the pre[XXX]Specialize methods.
// Accessing the directory returned is only possible in the pre[XXX]Specialize methods
// or in the root companion process (assuming that you sent the fd over the socket).
// Both restrictions are due to SELinux and UID.
//
// Module should also make sure zygote is allowed to read module dir (e.g. module dir has
// system_file context) due to SELinux restrictions on socket messages.
//
// Returns -1 if errors occurred.
int getModuleDir();
// Set various options for your module.
// Please note that this method accepts one single option at a time.
// Check zygisk::Option for the full list of options available.
void setOption(Option opt);
// Get information about the current process.
// Returns bitwise-or'd zygisk::StateFlag values.
uint32_t getFlags();
// Exempt the provided file descriptor from being automatically closed.
//
// This API only make sense in preAppSpecialize; calling this method in any other situation
// is either a no-op (returns true) or an error (returns false).
//
// When false is returned, the provided file descriptor will eventually be closed by zygote.
bool exemptFd(int fd);
// Hook JNI native methods for a class
//
// Lookup all registered JNI native methods and replace it with your own methods.
// The original function pointer will be saved in each JNINativeMethod's fnPtr.
// If no matching class, method name, or signature is found, that specific JNINativeMethod.fnPtr
// will be set to nullptr.
void hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods);
// Hook functions in the PLT (Procedure Linkage Table) of ELFs loaded in memory.
//
// Parsing /proc/[PID]/maps will give you the memory map of a process. As an example:
//
// <address> <perms> <offset> <dev> <inode> <pathname>
// 56b4346000-56b4347000 r-xp 00002000 fe:00 235 /system/bin/app_process64
// (More details: https://man7.org/linux/man-pages/man5/proc.5.html)
//
// The `dev` and `inode` pair uniquely identifies a file being mapped into memory.
// For matching ELFs loaded in memory, replace function `symbol` with `newFunc`.
// If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`.
void pltHookRegister(dev_t dev, ino_t inode, const char *symbol, void *newFunc, void **oldFunc);
// Commit all the hooks that was previously registered.
// Returns false if an error occurred.
bool pltHookCommit();
private:
internal::api_table *tbl;
template <class T> friend void internal::entry_impl(internal::api_table *, JNIEnv *);
};
// Register a class as a Zygisk module
#define REGISTER_ZYGISK_MODULE(clazz) \
void zygisk_module_entry(zygisk::internal::api_table *table, JNIEnv *env) { \
zygisk::internal::entry_impl<clazz>(table, env); \
}
// Register a root companion request handler function for your module
//
// The function runs in a superuser daemon process and handles a root companion request from
// your module running in a target process. The function has to accept an integer value,
// which is a Unix domain socket that is connected to the target process.
// See Api::connectCompanion() for more info.
//
// NOTE: the function can run concurrently on multiple threads.
// Be aware of race conditions if you have globally shared resources.
#define REGISTER_ZYGISK_COMPANION(func) \
void zygisk_companion_entry(int client) { func(client); }
/*********************************************************
* The following is internal ABI implementation detail.
* You do not have to understand what it is doing.
*********************************************************/
namespace internal {
struct module_abi {
long api_version;
ModuleBase *impl;
void (*preAppSpecialize)(ModuleBase *, AppSpecializeArgs *);
void (*postAppSpecialize)(ModuleBase *, const AppSpecializeArgs *);
void (*preServerSpecialize)(ModuleBase *, ServerSpecializeArgs *);
void (*postServerSpecialize)(ModuleBase *, const ServerSpecializeArgs *);
module_abi(ModuleBase *module) : api_version(ZYGISK_API_VERSION), impl(module) {
preAppSpecialize = [](auto m, auto args) { m->preAppSpecialize(args); };
postAppSpecialize = [](auto m, auto args) { m->postAppSpecialize(args); };
preServerSpecialize = [](auto m, auto args) { m->preServerSpecialize(args); };
postServerSpecialize = [](auto m, auto args) { m->postServerSpecialize(args); };
}
};
struct api_table {
// Base
void *impl;
bool (*registerModule)(api_table *, module_abi *);
void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int);
void (*pltHookRegister)(dev_t, ino_t, const char *, void *, void **);
bool (*exemptFd)(int);
bool (*pltHookCommit)();
int (*connectCompanion)(void * /* impl */);
void (*setOption)(void * /* impl */, Option);
int (*getModuleDir)(void * /* impl */);
uint32_t (*getFlags)(void * /* impl */);
};
template <class T>
void entry_impl(api_table *table, JNIEnv *env) {
static Api api;
api.tbl = table;
static T module;
ModuleBase *m = &module;
static module_abi abi(m);
if (!table->registerModule(table, &abi)) return;
m->onLoad(&api, env);
}
} // namespace internal
inline int Api::connectCompanion() {
return tbl->connectCompanion ? tbl->connectCompanion(tbl->impl) : -1;
}
inline int Api::getModuleDir() {
return tbl->getModuleDir ? tbl->getModuleDir(tbl->impl) : -1;
}
inline void Api::setOption(Option opt) {
if (tbl->setOption) tbl->setOption(tbl->impl, opt);
}
inline uint32_t Api::getFlags() {
return tbl->getFlags ? tbl->getFlags(tbl->impl) : 0;
}
inline bool Api::exemptFd(int fd) {
return tbl->exemptFd != nullptr && tbl->exemptFd(fd);
}
inline void Api::hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods) {
if (tbl->hookJniNativeMethods) tbl->hookJniNativeMethods(env, className, methods, numMethods);
}
inline void Api::pltHookRegister(dev_t dev, ino_t inode, const char *symbol, void *newFunc, void **oldFunc) {
if (tbl->pltHookRegister) tbl->pltHookRegister(dev, inode, symbol, newFunc, oldFunc);
}
inline bool Api::pltHookCommit() {
return tbl->pltHookCommit != nullptr && tbl->pltHookCommit();
}
} // namespace zygisk
extern "C" {
[[gnu::visibility("default"), maybe_unused]]
void zygisk_module_entry(zygisk::internal::api_table *, JNIEnv *);
[[gnu::visibility("default"), maybe_unused]]
void zygisk_companion_entry(int);
} // extern "C"
+21 -6
View File
@@ -3,16 +3,31 @@
"private": true,
"scripts": {
"dev": "pnpm -C web dev",
"build": "pnpm -C web build && bash dev/cd.sh",
"build:only-web": "pnpm -C web build && bash dev/webzip.sh",
"build": "pnpm -C web build && node dev/pack.mjs",
"build:only-web": "pnpm -C web build && node dev/webzip.mjs",
"pack": "node dev/pack.mjs",
"lint": "pnpm -C web lint",
"fmt": "pnpm -C web fmt",
"fmt:check": "pnpm -C web fmt:check",
"type-check": "pnpm -C web type-check",
"check": "node dev/ci.mjs",
"check:strict": "node dev/ci.mjs --strict",
"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 -d",
"shfmt:fix": "find src -name '*.sh' -print0 | xargs -0 shfmt -i 4 -w",
"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"
"go:build": "node dev/build-wght.mjs",
"go:build:local": "cd golang && go build -o /tmp/fontmm-wght ./cmd/fontmm-wght",
"zygisk:build": "node dev/build-zygisk.mjs",
"subset:build": "node dev/build-subset.mjs",
"sha256": "node dev/gen-sha256.mjs",
"cache:status": "node dev/cache.mjs status",
"cache:clean": "node dev/cache.mjs clean",
"cache:test": "node dev/cache.mjs test",
"sync:fonts-xml": "node dev/sync-fonts-xml.mjs",
"empty-font": "node dev/empty-font.mjs"
},
"devDependencies": {
"@zip.js/zip.js": "^2.15.0"
}
}
}
+15 -1
View File
@@ -6,4 +6,18 @@ settings:
importers:
.: {}
.:
devDependencies:
'@zip.js/zip.js':
specifier: ^2.15.0
version: 2.15.0
packages:
'@zip.js/zip.js@2.15.0':
resolution: {integrity: sha512-hYAuHAaWjt0axbofaDL5XUlmrQPsBDcK3f45ApZuh6N+8UGVk26GoGdtGDvcvzahsHytTQ6DtBVXwG9IcCMjjQ==}
engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=18.0.0'}
snapshots:
'@zip.js/zip.js@2.15.0': {}
+373 -15
View File
@@ -1,31 +1,57 @@
#!/system/bin/sh
# shellcheck shell=ash
# FontMM apply.sh — 应用字体: 把 FONTS/ 里的字体安装到 system/fonts
# FontMM apply.sh — 应用字体: 把 FONTS/ 里的字体安装到 system/fonts 并同步 fonts.xml
# 用法: apply.sh [模块目录] 默认 /data/adb/modules/FontMM
# 回退逻辑: hant/en 缺失时回退到 hans; mono/emoji 缺失时恢复系统原字体
# 回退逻辑: hant/en 当前模式未配置时回退到 hans; mono/emoji 缺失时恢复系统原字体
MODDIR="${1:-/data/adb/modules/FontMM}"
FONTS_DIR="$MODDIR/FONTS"
SYS_FONT_DIR="$MODDIR/system/fonts"
# 注意: SysFont-Regular.ttf 是 fonts.xml 中 sans-serif 家族第一位的默认字体,
# 作为西文槽位处理 (中文字体自带西文字形, 若同时占用该槽位会覆盖西文字体, issue #6)
hans_fonts='SysSans-Hans-Regular.ttf
SysFont-Static-Regular.ttf
SysFont-Myanmar.ttf
SysFont-Hans-Regular.ttf
SysFont-Regular.ttf'
SysFont-Hans-Regular.ttf'
hant_fonts='SysSans-Hant-Regular.ttf
SysFont-Hant-Regular.ttf'
en_fonts='SysSans-En-Regular.ttf'
en_fonts='SysSans-En-Regular.ttf
SysFont-Regular.ttf'
[ -f "$FONTS_DIR/hans.ttf" ] || {
echo "[✗] FONTS/hans.ttf 不存在, 请先在 WebUI 选择字体"
exit 1
}
# 多字重扩展文件 (按需生成, 400 复用上方 Regular 占位; 清单与 native/src/fontmm.cpp 保持一致)
hans_multi_fonts='FontMM-Hans-100.ttf
FontMM-Hans-200.ttf
FontMM-Hans-300.ttf
FontMM-Hans-500.ttf
FontMM-Hans-600.ttf
FontMM-Hans-700.ttf
FontMM-Hans-800.ttf
FontMM-Hans-900.ttf'
hant_multi_fonts='FontMM-Hant-100.ttf
FontMM-Hant-200.ttf
FontMM-Hant-300.ttf
FontMM-Hant-500.ttf
FontMM-Hant-600.ttf
FontMM-Hant-700.ttf
FontMM-Hant-800.ttf
FontMM-Hant-900.ttf'
en_multi_fonts='FontMM-En-100.ttf
FontMM-En-200.ttf
FontMM-En-300.ttf
FontMM-En-500.ttf
FontMM-En-600.ttf
FontMM-En-700.ttf
FontMM-En-800.ttf
FontMM-En-900.ttf'
ALL_WEIGHTS="100 200 300 400 500 600 700 800 900"
mkdir -p "$SYS_FONT_DIR"
install_from() {
local src="$1" list="$2" line=""
while IFS= read -r line; do
[ -z "$line" ] && continue
cp -f "$src" "$SYS_FONT_DIR/$line" || {
echo "[✗] 复制 $line 失败"
exit 1
@@ -36,23 +62,279 @@ $list
EOF
}
clear_files() {
local list="$1" line=""
while IFS= read -r line; do
[ -z "$line" ] && continue
rm -f "$SYS_FONT_DIR/$line"
done <<EOF
$list
EOF
}
# 读取槽位模式 ("single" | "multi"), 缺失时默认 "single"
get_slot_mode() {
local slot="$1" mode="single" line="" k="" v=""
if [ -f "$FONTS_DIR/slot-modes.txt" ]; then
while IFS= read -r line; do
line="${line%%#*}"
case "$line" in
*=*)
k="${line%%=*}"
v="${line#*=}"
k="$(printf '%s' "$k" | tr -d ' \t\r')"
v="$(printf '%s' "$v" | tr -d ' \t\r')"
if [ "$k" = "$slot" ] && [ "$v" = "multi" ]; then
mode="multi"
elif [ "$k" = "$slot" ] && [ "$v" = "single" ]; then
mode="single"
fi
;;
esac
done <"$FONTS_DIR/slot-modes.txt"
fi
printf '%s' "$mode"
}
# 列出 FONTS/multi/<slot>/ 中实际存在的字重 (升序空格分隔)
list_multi_weights() {
local slot="$1" w="" out=""
for w in $ALL_WEIGHTS; do
if [ -f "$FONTS_DIR/multi/$slot/$w.ttf" ]; then
out="${out:+$out }$w"
fi
done
printf '%s' "$out"
}
# 从已选字重列表中挑选最接近 target 的档位 (与 golang/internal/wght/wght.go 一致)
nearest_weight() {
local avail="$1" target="$2" best="" best_dist=99999 w="" d=0
for w in $avail; do
if [ "$w" -ge "$target" ]; then
d=$((w - target))
else
d=$((target - w))
fi
if [ -z "$best" ] || [ "$d" -lt "$best_dist" ]; then
best="$w"
best_dist="$d"
elif [ "$d" -eq "$best_dist" ]; then
if [ "$target" -ge 400 ] && [ "$w" -gt "$best" ]; then
best="$w"
elif [ "$target" -lt 400 ] && [ "$w" -lt "$best" ]; then
best="$w"
fi
fi
done
printf '%s' "$best"
}
# 执行模块内的原生工具。
# 刷入后 tools/ 下的文件权限是 0644 (KernelSU 解压时不保留 zip 里的执行位),
# 因此不能靠 -x 判断可用性, 而是执行前临时加执行位、执行后立即还原,
# 避免长期留下可执行文件。退出码为工具自身的退出码, 工具缺失返回 127。
run_tool() {
local tool="$1"
shift
[ -f "$tool" ] || return 127
chmod 0755 "$tool" 2>/dev/null
"$tool" "$@"
local rc=$?
chmod 0644 "$tool" 2>/dev/null
return "$rc"
}
# 准备英文字体: 含 CJK 字形时裁成纯拉丁子集, 否则原样使用 (issue #10)
# 用法: prepare_english_font <源字体> <子集输出路径>
# 成功 (含子集化) 时返回 0 并写入 <子集输出路径>; 无需处理或工具不可用时返回非 0。
#
# 不做结果缓存: 实测检测与子集化各约 13-21ms (x86; 设备端同量级),
# 每次重算比维护缓存 (失效判断、陈旧文件清理) 更简单可靠。
prepare_english_font() {
local src="$1"
local out="$2"
local tool="$MODDIR/tools/fontmm-subset"
[ -f "$src" ] || return 1
# 工具缺失 (旧版本模块升级、文件被删): 跳过, 用原字体
if [ ! -f "$tool" ]; then
echo "[-] 未找到字体子集化工具, 跳过英文子集化"
return 1
fi
# 先检测是否含 CJK: 不含则无需处理 (常见情况, 无额外开销)
# 退出码: 0=不含 CJK, 1=含 CJK, 2=文件无效/读取失败, 126/127=工具无法执行
run_tool "$tool" -check "$src" >/dev/null 2>&1
local rc=$?
if [ "$rc" -eq 0 ]; then
echo "[-] 英文字体不含 CJK 字形, 无需子集化"
return 1
fi
if [ "$rc" -ne 1 ]; then
echo "[-] 无法检测字体 (工具返回 $rc), 跳过英文子集化"
return 1
fi
echo "[*] 英文字体含 CJK 字形, 生成拉丁子集..."
if ! run_tool "$tool" -in "$src" -out "$out" 2>&1; then
# 子集化失败不阻断安装: 退回原字体, 并提示可能出现的问题
echo "[!] 子集化失败, 使用原字体 (中文可能被英文字体的字形覆盖)"
rm -f "$out"
return 1
fi
echo "[✓] 已生成子集, 汉字字形不再覆盖中文字体"
return 0
}
# 取多字重槽位某一档的实际源文件 (英文优先取 .subset-<w>.ttf)
multi_weight_src() {
local slot="$1" w="$2" is_en="$3"
local subset="$FONTS_DIR/multi/en/.subset-$w.ttf"
if [ "$is_en" -eq 1 ] && [ -f "$subset" ]; then
printf '%s' "$subset"
else
printf '%s' "$FONTS_DIR/multi/$slot/$w.ttf"
fi
}
# 安装多字重槽位: 400 (或最接近 400) 填充基础占位, 其余已选档位写入 FontMM-<Slot>-<W>.ttf
install_multi_slot() {
local slot="$1" cap="$2" avail="$3" base_list="$4" multi_list="$5" is_en="$6"
local w="" reg_w="" src=""
clear_files "$multi_list"
if [ "$is_en" -eq 1 ]; then
rm -f "$FONTS_DIR/multi/en"/.subset-*.ttf
for w in $avail; do
echo "[*] 检查英文多字重 $w..."
if ! prepare_english_font "$FONTS_DIR/multi/en/$w.ttf" "$FONTS_DIR/multi/en/.subset-$w.ttf"; then
rm -f "$FONTS_DIR/multi/en/.subset-$w.ttf"
fi
done
fi
reg_w="$(nearest_weight "$avail" 400)"
src="$(multi_weight_src "$slot" "$reg_w" "$is_en")"
install_from "$src" "$base_list"
for w in $avail; do
[ "$w" -eq 400 ] && continue
src="$(multi_weight_src "$slot" "$w" "$is_en")"
cp -f "$src" "$SYS_FONT_DIR/FontMM-${cap}-${w}.ttf" || {
echo "[✗] 复制 FontMM-${cap}-${w}.ttf 失败"
exit 1
}
echo "[*] 安装: FontMM-${cap}-${w}.ttf"
done
}
HANS_MODE="$(get_slot_mode hans)"
HANT_MODE="$(get_slot_mode hant)"
EN_MODE="$(get_slot_mode en)"
HANS_AVAIL=""
HANS_EFF_MODE="single"
if [ "$HANS_MODE" = "multi" ]; then
HANS_AVAIL="$(list_multi_weights hans)"
if [ -z "$HANS_AVAIL" ]; then
echo "[✗] 多字重模式下 FONTS/multi/hans/ 中未设置任何字重字体"
exit 1
fi
HANS_EFF_MODE="multi"
else
[ -f "$FONTS_DIR/hans.ttf" ] || {
echo "[✗] FONTS/hans.ttf 不存在, 请先在 WebUI 选择字体"
exit 1
}
fi
echo "[*] 安装简体字体..."
install_from "$FONTS_DIR/hans.ttf" "$hans_fonts"
if [ "$HANS_EFF_MODE" = "multi" ]; then
install_multi_slot hans Hans "$HANS_AVAIL" "$hans_fonts" "$hans_multi_fonts" 0
else
clear_files "$hans_multi_fonts"
install_from "$FONTS_DIR/hans.ttf" "$hans_fonts"
fi
echo "[*] 处理繁体字体..."
if [ -f "$FONTS_DIR/hant.ttf" ]; then
HANT_EFF_MODE="single"
HANT_AVAIL=""
if [ "$HANT_MODE" = "multi" ]; then
HANT_AVAIL="$(list_multi_weights hant)"
if [ -n "$HANT_AVAIL" ]; then
HANT_EFF_MODE="multi"
install_multi_slot hant Hant "$HANT_AVAIL" "$hant_fonts" "$hant_multi_fonts" 0
else
echo "[-] 多字重繁体未选字重, 回退使用简体"
clear_files "$hant_multi_fonts"
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$hant_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
fi
fi
elif [ -f "$FONTS_DIR/hant.ttf" ]; then
clear_files "$hant_multi_fonts"
install_from "$FONTS_DIR/hant.ttf" "$hant_fonts"
else
echo "[-] 未设置繁体, 回退使用简体"
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
clear_files "$hant_multi_fonts"
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$hant_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
fi
fi
# 英文槽位: 若在单字体或任何多字重下自带 CJK 字形, 需先子集化 (issue #10)
echo "[*] 处理英文&数字..."
if [ -f "$FONTS_DIR/en.ttf" ]; then
install_from "$FONTS_DIR/en.ttf" "$en_fonts"
EN_SUBSET="$FONTS_DIR/.en-subset.ttf"
EN_SRC="$FONTS_DIR/en.ttf"
EN_EFF_MODE="single"
EN_OWN_SINGLE=0
if [ "$EN_MODE" = "multi" ]; then
EN_AVAIL="$(list_multi_weights en)"
if [ -n "$EN_AVAIL" ]; then
EN_EFF_MODE="multi"
rm -f "$EN_SUBSET"
install_multi_slot en En "$EN_AVAIL" "$en_fonts" "$en_multi_fonts" 1
else
echo "[-] 多字重英文未选字重, 回退使用简体"
clear_files "$en_multi_fonts"
rm -f "$EN_SUBSET" "$FONTS_DIR/multi/en"/.subset-*.ttf
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$en_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$en_fonts"
fi
fi
elif [ -f "$FONTS_DIR/en.ttf" ]; then
EN_OWN_SINGLE=1
clear_files "$en_multi_fonts"
rm -f "$FONTS_DIR/multi/en"/.subset-*.ttf
if prepare_english_font "$FONTS_DIR/en.ttf" "$EN_SUBSET"; then
EN_SRC="$EN_SUBSET"
else
rm -f "$EN_SUBSET"
fi
install_from "$EN_SRC" "$en_fonts"
else
echo "[-] 未设置英文, 回退使用简体"
install_from "$FONTS_DIR/hans.ttf" "$en_fonts"
clear_files "$en_multi_fonts"
rm -f "$EN_SUBSET" "$FONTS_DIR/multi/en"/.subset-*.ttf
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$en_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$en_fonts"
fi
fi
echo "[*] 处理等宽字体..."
@@ -80,4 +362,80 @@ else
fi
fi
# 首次修改 XML 前备份纯净 fonts.xml, 供后续 single <-> multi 切换还原
if [ -f "$MODDIR/system/etc/fonts.xml" ] && [ ! -f "$MODDIR/backup/fonts.xml" ]; then
mkdir -p "$MODDIR/backup"
cp -f "$MODDIR/system/etc/fonts.xml" "$MODDIR/backup/fonts.xml"
fi
# 同步字重映射与多字重 XML 配置 (同时处理单字体 wght 覆写与多字重静态映射)
echo "[*] 同步字体配置 XML..."
WGHT_MODE=0
if [ -f "$FONTS_DIR/wght-mode.txt" ]; then
raw_mode="$(tr -d ' \t\r\n' <"$FONTS_DIR/wght-mode.txt" 2>/dev/null || true)"
case "$raw_mode" in
1 | 2 | 3) WGHT_MODE="$raw_mode" ;;
esac
fi
WGHT_MIN=100
WGHT_MAX=900
if [ "$WGHT_MODE" -ne 0 ] && [ -f "$MODDIR/tools/wght-range.sh" ]; then
best_span=99999
single_candidates=""
[ "$HANS_EFF_MODE" = "single" ] && single_candidates="$FONTS_DIR/hans.ttf"
if [ "$HANT_EFF_MODE" = "single" ] && [ -f "$FONTS_DIR/hant.ttf" ]; then
single_candidates="${single_candidates:+$single_candidates
}$FONTS_DIR/hant.ttf"
fi
if [ "$EN_EFF_MODE" = "single" ] && [ "$EN_OWN_SINGLE" -eq 1 ]; then
single_candidates="${single_candidates:+$single_candidates
}$EN_SRC"
fi
while IFS= read -r cand; do
[ -z "$cand" ] && continue
[ -f "$cand" ] || continue
rng="$(sh "$MODDIR/tools/wght-range.sh" "$cand" 2>/dev/null || true)"
if [ -n "$rng" ]; then
cmin="${rng%% *}"
cmax="${rng#* }"
cspan=$((cmax - cmin))
if [ "$cspan" -lt "$best_span" ]; then
best_span="$cspan"
WGHT_MIN="$cmin"
WGHT_MAX="$cmax"
fi
fi
done <<EOF
$single_candidates
EOF
fi
WGHT_BIN="$MODDIR/tools/fontmm-wght"
if [ -f "$WGHT_BIN" ]; then
if [ "$WGHT_MODE" -eq 3 ] && [ -f "$FONTS_DIR/wght-map.txt" ]; then
run_tool "$WGHT_BIN" -mode "$WGHT_MODE" -min "$WGHT_MIN" -max "$WGHT_MAX" -map "$FONTS_DIR/wght-map.txt" -xml-dir "$MODDIR" -sync >"$FONTS_DIR/wght-apply.log" 2>&1
wght_rc=$?
else
[ "$WGHT_MODE" -eq 3 ] && WGHT_MODE=0
run_tool "$WGHT_BIN" -mode "$WGHT_MODE" -min "$WGHT_MIN" -max "$WGHT_MAX" -xml-dir "$MODDIR" -sync >"$FONTS_DIR/wght-apply.log" 2>&1
wght_rc=$?
fi
if [ "$wght_rc" -eq 0 ]; then
echo "[✓] 字体配置 XML 同步完成"
else
echo "[✗] 字体配置 XML 同步失败:"
cat "$FONTS_DIR/wght-apply.log" 2>/dev/null || true
if [ "$HANS_EFF_MODE" = "multi" ] || [ "$HANT_EFF_MODE" = "multi" ] || [ "$EN_EFF_MODE" = "multi" ]; then
exit 1
fi
fi
else
echo "[!] 未找到 fontmm-wght, 跳过字体配置同步"
if [ "$HANS_EFF_MODE" = "multi" ] || [ "$HANT_EFF_MODE" = "multi" ] || [ "$EN_EFF_MODE" = "multi" ]; then
echo "[✗] 多字重模式依赖 fontmm-wght 更新字体配置, 请重新刷入完整模块"
exit 1
fi
fi
echo "[*] 全部完成, 重启后生效"
+186 -41
View File
@@ -55,7 +55,7 @@ DETECT_UPDATE_MODE() {
fi
}
# 更新模式: 以旧包为主继承字体
# 更新模式: 以旧包为主继承字体与配置
IMPORT_OLD_FONTS() {
[ "$UPDATE_MODE" -eq 1 ] || return 0
@@ -67,17 +67,24 @@ IMPORT_OLD_FONTS() {
mkdir -p "$MOD_WORK_PATH"
local f=""
for f in hans.ttf hant.ttf en.ttf mono.ttf emoji.ttf; do
for f in hans.ttf hant.ttf en.ttf mono.ttf emoji.ttf slot-modes.txt wght-mode.txt wght-map.txt; do
if [ -f "$old_fonts/$f" ]; then
if cp -f "$old_fonts/$f" "$MOD_WORK_PATH/$f"; then
log_succ "已从旧模块继承字体: $f"
log_succ "已从旧模块继承: $f"
else
log_err "继承字体 $f 失败"
log_err "继承 $f 失败"
fi
else
log "旧包没有 $f, 使用新包字体"
fi
done
if [ -d "$old_fonts/multi" ]; then
if cp -af "$old_fonts/multi" "$MOD_WORK_PATH/"; then
rm -f "$MOD_WORK_PATH/multi/en"/.subset-*.ttf 2>/dev/null
log_succ "已从旧模块继承多字重字体目录"
else
log_err "继承多字重目录失败"
fi
fi
}
# ---------- 系统检查 ----------
@@ -173,49 +180,172 @@ CONFIRM_RISK() {
fi
}
CONFIRM_FONTLOADER_RISK() {
local reason="$1"
echo
log "警告: $reason"
log "未安装或版本过低的 FontLoader 可能导致开机卡死、字体渲染错误或系统异常。"
log "请按音量上键确认继续安装, 按音量下键取消安装。"
if [ "$(btn)" = "1" ]; then
log_err "用户取消安装"
# ---------- 判断 Zygisk 环境 ----------
# 模块自带字体预加载 (zygisk/arm64-v8a.so), 但 Zygisk 框架本身需要由 Root 管理器
# 或独立的 Zygisk 提供者 (Magisk 内置 Zygisk / Zygisk Next / ReZygisk 等) 提供。
# 缺少时模块仍可安装, 只是被 DenyList 的应用可能字体异常, 故仅提示不阻断。
CHECK_ZYGISK_ENV() {
local ok=0
# Magisk 内置 Zygisk: 以是否开启 Zygisk 为准 (magisk --sqlite 查询数据库开关)
if [ -f /data/adb/magisk/magisk ]; then
local zg=""
zg="$(/data/adb/magisk/magisk --sqlite "SELECT value FROM settings WHERE key='zygisk';" 2>/dev/null | tr -d '\r')"
if [ "$zg" = "1" ]; then
log_succ "Magisk 内置 Zygisk 已启用"
ok=1
fi
fi
# 独立 Zygisk 提供者模块。判据是提供者**独有**的文件, 而不是目录名或 zygisk/ 目录 ——
# 后者是「Zygisk 模块」(消费者) 的标志, 任何自带 zygisk/<abi>.so 的模块都有,
# 本模块自己也有。曾据此误判 (把 Hide My Applist 之类的消费者当成提供者)。
#
# 判据取自两个提供者的实际安装布局 (核对过发布包与安装脚本):
# Zygisk Next (模块 ID: zygisksu)
# bin/zygiskd64 守护进程
# lib64/libzygisk.so / lib64/libzn_loader.so / lib64/libpayload.so
# ReZygisk (模块 ID: rezygisk)
# bin/zygiskd64 / bin/zygisk-ptrace64
# lib64/libzygisk.so
# 共同且充分的特征: lib{64}/libzygisk.so (核心库) 或 bin/zygiskd{64,32} (守护进程)。
# 这两个文件名是提供者专有的, 普通 Zygisk 模块不会用到。
if [ "$ok" -eq 0 ]; then
local dir="" name="" f=""
for dir in /data/adb/modules/*; do
[ -d "$dir" ] || continue
name="$(basename "$dir")"
[ "$name" = "FontMM" ] && continue
[ -f "$dir/disable" ] && continue
local hit=""
for f in "$dir"/lib64/libzygisk.so "$dir"/lib/libzygisk.so \
"$dir"/bin/zygiskd64 "$dir"/bin/zygiskd32 "$dir"/bin/zygiskd \
"$dir"/lib64/libzn_loader.so "$dir"/lib/libzn_loader.so; do
if [ -f "$f" ]; then
hit="${f#"$dir"/}"
break
fi
done
[ -z "$hit" ] && continue
log_succ "检测到 Zygisk 提供者: $name ($hit)"
ok=1
break
done
fi
# 管理器内置 Zygisk (如 KernelSU / Sukisu 的内置实现): 无独立提供者模块,
# 仅由管理器自身提供, 以内置标记文件是否存在为准。
if [ "$ok" -eq 0 ] && [ -f /data/adb/ksu/.builtin_zygisk ]; then
log_succ "检测到管理器内置 Zygisk"
ok=1
fi
if [ "$ok" -eq 0 ]; then
log_warn "未检测到可用的 Zygisk 环境"
log "模块的字体预加载依赖 Zygisk, 缺少时被卸载模块的应用可能字体异常"
log "请启用 Magisk 内置 Zygisk, 或安装 Zygisk Next / ReZygisk"
CONFIRM_RISK "未检测到 Zygisk 环境" "字体预加载不会生效, 被 DenyList 的应用可能字体显示异常"
fi
}
# ---------- 字体配置 XML: 扫描设备 + 同步派生配置 ----------
# 模块只内置 fonts.xml 一份主配置; 各派生配置 (fonts_base/ule/font_fallback) 按设备实际文件补齐,
# 设备缺失时回退内置 fonts.xml, 提升跨 ColorOS 版本的兼容性 (issue #7)
# 随后用模块内置 fontmm-wght -sync 把主配置同步到全部派生配置
SYNC_FONT_XMLS() {
local xml_src="$MODPATH/system/etc/fonts.xml"
# 派生配置在设备上的真实路径 (模块内 overlay 的对应位置)
local device_xmls="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"
local rel=""
for rel in $device_xmls; do
mkdir -p "$MODPATH/$(dirname "$rel")"
if [ -f "/system/$rel" ]; then
cp -f "/system/$rel" "$MODPATH/$rel"
log "已从设备复制配置: $rel"
else
cp -f "$xml_src" "$MODPATH/$rel"
log "设备无 $rel, 回退内置 fonts.xml"
fi
done
# 用 Go 程序把主配置同步到派生配置 (避免 shell 复制与主配置不一致)。
# 工具在刷入后是 0644 (KernelSU 解压时不保留 zip 里的执行位), 故不能靠 -x
# 判断可用性; 执行前临时加执行位, 用完立即还原。
local wght="$MODPATH/tools/fontmm-wght"
if [ -f "$wght" ]; then
chmod 0755 "$wght" 2>/dev/null
if "$wght" -mode 0 -sync -xml-dir "$MODPATH" >/dev/null 2>&1; then
log "已同步派生字体配置"
else
log "同步派生配置失败 (可忽略, 使用内置副本)"
fi
chmod 0644 "$wght" 2>/dev/null
fi
}
# ---------- 判断 FontLoader ----------
CHECK_FONTLOADER() {
local fontloader_moddir="/data/adb/modules/fontloader"
local fontloader_github="https://github.com/KernelSU-Modules-Repo/fontloader/releases"
# 本模块已内置字体预加载 (zygisk/arm64-v8a.so), 与外部 FontLoader 模块功能重叠。
# 两者同时启用会重复预热、并可能互相干扰, 因此检测到旧 FontLoader 时建议禁用它。
# 禁用方式: 在其模块目录放置 disable 文件 (模块的通用停用约定, 重启后生效),
# 不删除其数据, 用户可随时移除该文件恢复。
DISABLE_OLD_FONTLOADER() {
local found=""
local hit=""
if [ ! -d "$fontloader_moddir" ]; then
log "注意: 你还没安装 FontLoader"
log "前往 $fontloader_github 安装 FontLoader"
CONFIRM_FONTLOADER_RISK "当前设备未安装 FontLoader。"
return 0
# 按目录名候选 + 内容特征双重识别:
# - RikkaW/FontLoader 原版: 模块目录名多为 fontloader
# - JingMatrix/FontLoader: build.gradle 中 moduleId = 'font-loader'
# - 兜底: 扫描各模块 module.prop 描述中明确含 FontLoader 字样者
local names="fontloader font-loader font_loader"
local name="" dir=""
for name in $names; do
dir="/data/adb/modules/$name"
if [ -d "$dir" ]; then
hit="$name"
break
fi
done
# 目录名未命中时, 扫描其它模块的 module.prop 描述
if [ -z "$hit" ]; then
local d="" prop=""
for d in /data/adb/modules/*; do
[ -d "$d" ] || continue
[ "$(basename "$d")" = "FontMM" ] && continue
prop="$d/module.prop"
[ -f "$prop" ] || continue
# 只认明确声明为 FontLoader 的模块, 避免误伤其他模块
if grep -qiE '^description=.*font.?loader' "$prop" 2>/dev/null; then
hit="$(basename "$d")"
break
fi
done
fi
local prop_file="$fontloader_moddir/module.prop"
local version_code=""
if [ -f "$prop_file" ]; then
version_code="$(sed -n 's/^versionCode=//p' "$prop_file")"
fi
version_code="$(printf '%s' "$version_code" | tr -cd '0-9')"
if [ -z "$version_code" ]; then
log "注意: 无法读取 FontLoader 版本号, 建议更新到最新版"
log "前往 $fontloader_github 更新 FontLoader"
CONFIRM_FONTLOADER_RISK "无法确认 FontLoader 版本。"
return 0
if [ -n "$hit" ]; then
dir="/data/adb/modules/$hit"
if [ -f "$dir/disable" ]; then
log "外部 FontLoader ($hit) 已处于停用状态"
elif touch "$dir/disable" 2>/dev/null; then
log_succ "已停用外部 FontLoader 模块: $hit"
found="$hit"
else
log_warn "检测到外部 FontLoader ($hit) 但无法停用, 建议手动在管理器中关闭"
found="$hit"
fi
fi
if [ "$version_code" -lt 33 ] 2>/dev/null; then
log "注意: 你的 FontLoader 版本过低, 建议更新到 v1.2.3+"
log "前往 $fontloader_github 更新 FontLoader"
CONFIRM_FONTLOADER_RISK "当前 FontLoader 版本低于 v1.2.3。"
else
log_succ "FontLoader 版本正常"
if [ -n "$found" ]; then
log "本模块已内置字体预加载, 无需外部 FontLoader; 重启后以本模块为准"
fi
}
@@ -225,12 +355,27 @@ MAIN() {
if ! CHECK_META_MODULE; then
log_err "元模块检查不通过"
fi
CHECK_FONTLOADER
CHECK_ZYGISK_ENV
DISABLE_OLD_FONTLOADER
echo && log "开始准备字体..."
DETECT_UPDATE_MODE
IMPORT_OLD_FONTS
# 同步派生字体配置 (设备 XML 扫描 + fontmm-wght -sync)
SYNC_FONT_XMLS
# 备份纯净的 fonts.xml, 供 apply.sh 在单字体 <-> 多字重间往返切换
if [ -f "$MODPATH/system/etc/fonts.xml" ]; then
mkdir -p "$MODPATH/backup"
cp -f "$MODPATH/system/etc/fonts.xml" "$MODPATH/backup/fonts.xml"
fi
# 校验内置的 Zygisk 字体预加载模块存在 (缺失则 DenyList 应用可能字体异常)
if [ ! -f "$MODPATH/zygisk/arm64-v8a.so" ]; then
log_warn "缺少 zygisk/arm64-v8a.so, 字体预加载不可用 (DenyList 应用可能字体异常)"
fi
# 备份模块内嵌的补充字库 Emoji 字体, 供用户清除 emoji 槽位时恢复
if [ -f "$MODPATH/system/fonts/NotoColorEmoji.ttf" ] && [ ! -f "$MODPATH/backup/NotoColorEmoji.ttf" ]; then
mkdir -p "$MODPATH/backup"
+2 -2
View File
@@ -1,7 +1,7 @@
id=FontMM
name=FontMM
version=26.8.0-beta.4
versionCode=26080004
version=26.11.0-beta.1
versionCode=26110001
author=Yule
description=ColorOS 16 字体模块模板
updateJson=https://raw.githubusercontent.com/YuleBest/FontMM/main/update.json
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
#!/system/bin/sh
# shellcheck shell=ash
# FontMM 一键校验: 校验模块内可执行文件的 SHA256 完整性
# 用法: sh verify-sha256.sh [模块目录] 默认 /data/adb/modules/FontMM
# 依赖: SHA256SUMS (随模块打包), sha256sum (toybox 自带)
MODDIR="${1:-/data/adb/modules/FontMM}"
SUMS="$MODDIR/SHA256SUMS"
[ -f "$SUMS" ] || {
echo "[✗] 未找到 $SUMS, 请确认模块已正确安装"
exit 1
}
command -v sha256sum >/dev/null 2>&1 || {
echo "[✗] 系统缺少 sha256sum 命令"
exit 1
}
cd "$MODDIR" || exit 1
echo "[*] 正在校验 $(wc -l <"$SUMS") 个文件..."
# 逐条校验, 便于指出具体是哪个文件不匹配
FAIL=0
while IFS= read -r line; do
[ -z "$line" ] && continue
expected="${line%% *}"
file="${line#* }"
[ -f "$file" ] || {
echo "[✗] 文件缺失: $file"
FAIL=1
continue
}
actual="$(sha256sum "$file" | awk '{ print $1 }')"
if [ "$actual" = "$expected" ]; then
echo "[✓] $file"
else
echo "[✗] 校验失败: $file"
FAIL=1
fi
done <"$SUMS"
if [ "$FAIL" -eq 0 ]; then
echo "[*] 全部文件校验通过"
else
echo "[✗] 存在校验失败的文件, 建议重新安装模块"
exit 1
fi
+3 -3
View File
@@ -1,6 +1,6 @@
{
"versionCode": 26080004,
"version": "v26.8.0-beta.4",
"zipUrl": "https://github.com/YuleBest/FontMM/releases/download/v26.8.0-beta.4/FontMM_v26.8.0-beta.4_template.zip",
"versionCode": 26110001,
"version": "v26.11.0-beta.1",
"zipUrl": "https://github.com/YuleBest/FontMM/releases/download/v26.11.0-beta.1/FontMM_v26.11.0-beta.1_template.zip",
"changelog": "https://raw.githubusercontent.com/YuleBest/FontMM/main/changelog.md"
}
+16 -1
View File
@@ -99,6 +99,20 @@
<div class="home-info-value" id="home-metamodule">-</div>
</div>
</md-elevated-card>
<!-- 字体预热器: 让被「卸载模块」的应用仍能正常渲染字体 -->
<md-elevated-card class="home-card home-info-card">
<div class="home-info-title">字体预热器</div>
<div class="home-info-row">
<div class="home-info-label">运行状态</div>
<div class="home-info-value" id="home-preload-status">检测中…</div>
</div>
<div class="home-info-row">
<div class="home-info-label">Zygisk 提供者</div>
<div class="home-info-value" id="home-preload-provider">-</div>
</div>
<div class="home-preload-note" id="home-preload-note" hidden></div>
</md-elevated-card>
</main>
<!-- 配置视图 -->
@@ -281,7 +295,8 @@
可变字体<span class="test-tag" id="var-tag"></span>
</div>
<div class="test-var-note">
拖动滑条调整字重,停止滑动后应用;仅对可变字体 (VF) 生效,静态字体下无变化。
拖动滑条可预览该字体在各字重、字号下的效果,仅影响本页预览,不会修改系统字体。字重仅对可变字体
(VF) 生效,静态字体下无变化。
</div>
<div class="test-wght-row">
<span class="test-wght-label">字重</span>
+3 -2
View File
@@ -4,8 +4,9 @@
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"sync:pyodide": "node scripts/sync-pyodide.mjs",
"dev": "npm run sync:pyodide && vite",
"build": "npm run sync:pyodide && vite build",
"preview": "vite preview",
"lint": "oxlint",
"fmt": "oxfmt",
File diff suppressed because it is too large. Load diff
-42338
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
-836
View File
@@ -1,836 +0,0 @@
'use strict';
var loadPyodide = (() => {
var ne = Object.create;
var F = Object.defineProperty;
var re = Object.getOwnPropertyDescriptor;
var oe = Object.getOwnPropertyNames;
var ie = Object.getPrototypeOf,
ae = Object.prototype.hasOwnProperty;
var i = (e, t) => F(e, 'name', { value: t, configurable: !0 }),
m = ((e) =>
typeof require < 'u'
? require
: typeof Proxy < 'u'
? new Proxy(e, { get: (t, n) => (typeof require < 'u' ? require : t)[n] })
: e)(function (e) {
if (typeof require < 'u') return require.apply(this, arguments);
throw Error('Dynamic require of "' + e + '" is not supported');
});
var se = (e, t) => {
for (var n in t) F(e, n, { get: t[n], enumerable: !0 });
},
$ = (e, t, n, o) => {
if ((t && typeof t == 'object') || typeof t == 'function')
for (let s of oe(t))
!ae.call(e, s) &&
s !== n &&
F(e, s, { get: () => t[s], enumerable: !(o = re(t, s)) || o.enumerable });
return e;
};
var v = (e, t, n) => (
(n = e != null ? ne(ie(e)) : {}),
$(t || !e || !e.__esModule ? F(n, 'default', { value: e, enumerable: !0 }) : n, e)
),
le = (e) => $(F({}, '__esModule', { value: !0 }), e);
var j = (() => {
for (var e = new Uint8Array(128), t = 0; t < 64; t++)
e[t < 26 ? t + 65 : t < 52 ? t + 71 : t < 62 ? t - 4 : t * 4 - 205] = t;
return (n) => {
for (
var o = n.length,
s = new Uint8Array((((o - (n[o - 1] == '=') - (n[o - 2] == '=')) * 3) / 4) | 0),
r = 0,
a = 0;
r < o;
) {
var c = e[n.charCodeAt(r++)],
l = e[n.charCodeAt(r++)],
d = e[n.charCodeAt(r++)],
u = e[n.charCodeAt(r++)];
((s[a++] = (c << 2) | (l >> 4)), (s[a++] = (l << 4) | (d >> 2)), (s[a++] = (d << 6) | u));
}
return s;
};
})();
var je = {};
se(je, { loadPyodide: () => B, version: () => O });
function ce(e) {
return !isNaN(parseFloat(e)) && isFinite(e);
}
i(ce, '_isNumber');
function N(e) {
return e.charAt(0).toUpperCase() + e.substring(1);
}
i(N, '_capitalize');
function C(e) {
return function () {
return this[e];
};
}
i(C, '_getter');
var S = ['isConstructor', 'isEval', 'isNative', 'isToplevel'],
w = ['columnNumber', 'lineNumber'],
_ = ['fileName', 'functionName', 'source'],
de = ['args'],
ue = ['evalOrigin'],
D = S.concat(w, _, de, ue);
function y(e) {
if (e) for (var t = 0; t < D.length; t++) e[D[t]] !== void 0 && this['set' + N(D[t])](e[D[t]]);
}
i(y, 'StackFrame');
y.prototype = {
getArgs: i(function () {
return this.args;
}, 'getArgs'),
setArgs: i(function (e) {
if (Object.prototype.toString.call(e) !== '[object Array]')
throw new TypeError('Args must be an Array');
this.args = e;
}, 'setArgs'),
getEvalOrigin: i(function () {
return this.evalOrigin;
}, 'getEvalOrigin'),
setEvalOrigin: i(function (e) {
if (e instanceof y) this.evalOrigin = e;
else if (e instanceof Object) this.evalOrigin = new y(e);
else throw new TypeError('Eval Origin must be an Object or StackFrame');
}, 'setEvalOrigin'),
toString: i(function () {
var e = this.getFileName() || '',
t = this.getLineNumber() || '',
n = this.getColumnNumber() || '',
o = this.getFunctionName() || '';
return this.getIsEval()
? e
? '[eval] (' + e + ':' + t + ':' + n + ')'
: '[eval]:' + t + ':' + n
: o
? o + ' (' + e + ':' + t + ':' + n + ')'
: e + ':' + t + ':' + n;
}, 'toString'),
};
y.fromString = i(function (t) {
var n = t.indexOf('('),
o = t.lastIndexOf(')'),
s = t.substring(0, n),
r = t.substring(n + 1, o).split(','),
a = t.substring(o + 1);
if (a.indexOf('@') === 0)
var c = /@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(a, ''),
l = c[1],
d = c[2],
u = c[3];
return new y({
functionName: s,
args: r || void 0,
fileName: l,
lineNumber: d || void 0,
columnNumber: u || void 0,
});
}, 'StackFrame$$fromString');
for (E = 0; E < S.length; E++)
((y.prototype['get' + N(S[E])] = C(S[E])),
(y.prototype['set' + N(S[E])] = (function (e) {
return function (t) {
this[e] = !!t;
};
})(S[E])));
var E;
for (P = 0; P < w.length; P++)
((y.prototype['get' + N(w[P])] = C(w[P])),
(y.prototype['set' + N(w[P])] = (function (e) {
return function (t) {
if (!ce(t)) throw new TypeError(e + ' must be a Number');
this[e] = Number(t);
};
})(w[P])));
var P;
for (h = 0; h < _.length; h++)
((y.prototype['get' + N(_[h])] = C(_[h])),
(y.prototype['set' + N(_[h])] = (function (e) {
return function (t) {
this[e] = String(t);
};
})(_[h])));
var h,
x = y;
function fe() {
var e = /^\s*at .*(\S+:\d+|\(native\))/m,
t = /^(eval@)?(\[native code])?$/;
return {
parse: i(function (o) {
if (o.stack && o.stack.match(e)) return this.parseV8OrIE(o);
if (o.stack) return this.parseFFOrSafari(o);
throw new Error('Cannot parse given Error object');
}, 'ErrorStackParser$$parse'),
extractLocation: i(function (o) {
if (o.indexOf(':') === -1) return [o];
var s = /(.+?)(?::(\d+))?(?::(\d+))?$/,
r = s.exec(o.replace(/[()]/g, ''));
return [r[1], r[2] || void 0, r[3] || void 0];
}, 'ErrorStackParser$$extractLocation'),
parseV8OrIE: i(function (o) {
var s = o.stack
.split(`
`)
.filter(function (r) {
return !!r.match(e);
}, this);
return s.map(function (r) {
r.indexOf('(eval ') > -1 &&
(r = r.replace(/eval code/g, 'eval').replace(/(\(eval at [^()]*)|(,.*$)/g, ''));
var a = r
.replace(/^\s+/, '')
.replace(/\(eval code/g, '(')
.replace(/^.*?\s+/, ''),
c = a.match(/ (\(.+\)$)/);
a = c ? a.replace(c[0], '') : a;
var l = this.extractLocation(c ? c[1] : a),
d = (c && a) || void 0,
u = ['eval', '<anonymous>'].indexOf(l[0]) > -1 ? void 0 : l[0];
return new x({
functionName: d,
fileName: u,
lineNumber: l[1],
columnNumber: l[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseV8OrIE'),
parseFFOrSafari: i(function (o) {
var s = o.stack
.split(`
`)
.filter(function (r) {
return !r.match(t);
}, this);
return s.map(function (r) {
if (
(r.indexOf(' > eval') > -1 &&
(r = r.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ':$1')),
r.indexOf('@') === -1 && r.indexOf(':') === -1)
)
return new x({ functionName: r });
var a = /((.*".+"[^@]*)?[^@]*)(?:@)/,
c = r.match(a),
l = c && c[1] ? c[1] : void 0,
d = this.extractLocation(r.replace(a, ''));
return new x({
functionName: l,
fileName: d[0],
lineNumber: d[1],
columnNumber: d[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseFFOrSafari'),
};
}
i(fe, 'ErrorStackParser');
var me = new fe();
var H = me;
function pe() {
if (typeof API < 'u' && API !== globalThis.API) return API.runtimeEnv;
let e = typeof Bun < 'u',
t = typeof Deno < 'u',
n =
typeof process == 'object' &&
typeof process.versions == 'object' &&
typeof process.versions.node == 'string' &&
!process.browser,
o =
typeof navigator == 'object' &&
typeof navigator.userAgent == 'string' &&
navigator.userAgent.indexOf('Chrome') === -1 &&
navigator.userAgent.indexOf('Safari') > -1,
s = typeof read == 'function' && typeof load == 'function',
r = typeof navigator == 'object' && navigator.userAgent?.includes('Cloudflare-Workers');
return ye({ IN_BUN: e, IN_DENO: t, IN_NODE: n, IN_SAFARI: o, IN_SHELL: s, IN_WORKERD: r });
}
i(pe, 'getGlobalRuntimeEnv');
var f = pe();
function ye(e) {
let t =
e.IN_NODE &&
typeof module < 'u' &&
module.exports &&
typeof m == 'function' &&
typeof __dirname == 'string',
n = e.IN_NODE && !t,
o = !e.IN_NODE && !e.IN_DENO && !e.IN_BUN,
s =
o &&
typeof window < 'u' &&
typeof window.document < 'u' &&
typeof document.createElement == 'function' &&
'sessionStorage' in window &&
typeof globalThis.importScripts != 'function',
r =
o &&
typeof globalThis.WorkerGlobalScope < 'u' &&
typeof globalThis.self < 'u' &&
globalThis.self instanceof globalThis.WorkerGlobalScope;
if (r && ge()) throw new Error('Classic web workers are not supported');
let a = {
...e,
IN_BROWSER: o,
IN_BROWSER_MAIN_THREAD: s,
IN_BROWSER_WEB_WORKER: r,
IN_NODE_COMMONJS: t,
IN_NODE_ESM: n,
};
if (
!(
a.IN_BROWSER_MAIN_THREAD ||
a.IN_BROWSER_WEB_WORKER ||
a.IN_NODE ||
a.IN_SHELL ||
a.IN_WORKERD
)
)
throw new Error(`Cannot determine runtime environment: ${JSON.stringify(a)}`);
return a;
}
i(ye, 'calculateDerivedFlags');
function ge() {
try {
return (globalThis.importScripts('data:text/javascript,'), !0);
} catch {
return !1;
}
}
i(ge, 'isClassicWorker');
var V, T, ve, J, U;
async function W() {
if (
!f.IN_NODE ||
((V = (await import(/* webpackIgnore */ 'node:url')).default),
(J = await import(/* webpackIgnore */ 'node:fs')),
(U = await import(/* webpackIgnore */ 'node:fs/promises')),
(ve = (await import(/* webpackIgnore */ 'node:vm')).default),
(T = await import(/* webpackIgnore */ 'node:path')),
(M = T.sep),
typeof m < 'u')
)
return;
let e = J,
t = await import(/* webpackIgnore */ 'node:crypto'),
n = await import(/* webpackIgnore */ 'ws'),
o = await import(/* webpackIgnore */ 'node:child_process'),
s = { fs: e, crypto: t, ws: n, child_process: o };
globalThis.require = function (r) {
return s[r];
};
}
i(W, 'initNodeModules');
function be(e, t) {
return T.resolve(t || '.', e);
}
i(be, 'node_resolvePath');
function Ee(e, t) {
return (t === void 0 && (t = location), new URL(e, t).toString());
}
i(Ee, 'browser_resolvePath');
var k;
f.IN_NODE ? (k = be) : f.IN_SHELL ? (k = i((e) => e, 'resolvePath')) : (k = Ee);
var M;
f.IN_NODE || (M = '/');
function Pe(e, t) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://')
? { response: fetch(e) }
: {
binary: U.readFile(e).then((n) => new Uint8Array(n.buffer, n.byteOffset, n.byteLength)),
}
);
}
i(Pe, 'node_getBinaryResponse');
function he(e, t) {
if ((e.startsWith('file://') && (e = e.slice(7)), e.includes('://')))
throw new Error('Shell cannot fetch urls');
return { binary: Promise.resolve(new Uint8Array(readbuffer(e))) };
}
i(he, 'shell_getBinaryResponse');
function Ne(e, t) {
let n = new URL(e, location);
return { response: fetch(n, t ? { integrity: t } : {}) };
}
i(Ne, 'browser_getBinaryResponse');
var R;
f.IN_NODE ? (R = Pe) : f.IN_SHELL ? (R = he) : (R = Ne);
async function z(e, t) {
let { response: n, binary: o } = R(e, t);
if (o) return o;
let s = await n;
if (!s.ok) throw new Error(`Failed to load '${e}': request failed.`);
return new Uint8Array(await s.arrayBuffer());
}
i(z, 'loadBinaryFile');
var L;
f.IN_NODE ? (L = Ie) : (L = i(async (e) => await import(/* webpackIgnore */ e), 'loadScript'));
async function Ie(e) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://')
? await import(/* webpackIgnore */ e)
: await import(/* webpackIgnore */ V.pathToFileURL(e).href)
);
}
i(Ie, 'nodeLoadScript');
async function G(e) {
if (f.IN_NODE) {
await W();
let t = await U.readFile(e, { encoding: 'utf8' });
return JSON.parse(t);
} else if (f.IN_SHELL) {
let t = read(e);
return JSON.parse(t);
} else return await (await fetch(e)).json();
}
i(G, 'loadLockFile');
async function K() {
if (f.IN_NODE_COMMONJS) return __dirname;
let e;
try {
throw new Error();
} catch (o) {
e = o;
}
let t = H.parse(e)[0].fileName;
if ((f.IN_NODE && !t.startsWith('file://') && (t = `file://${t}`), f.IN_NODE_ESM)) {
let o = await import(/* webpackIgnore */ 'node:path');
return (await import(/* webpackIgnore */ 'node:url')).fileURLToPath(o.dirname(t));
}
let n = t.lastIndexOf(M);
if (n === -1)
throw new Error(
'Could not extract indexURL path from pyodide module location. Please pass the indexURL explicitly to loadPyodide.',
);
return t.slice(0, n);
}
i(K, 'calculateDirname');
function q(e) {
return e.substring(0, e.lastIndexOf('/') + 1) || globalThis.location?.toString() || '.';
}
i(q, 'calculateInstallBaseUrl');
function Y(e) {
let t = e.FS,
n = e.FS.filesystems.MEMFS,
o = e.PATH,
s = {
DIR_MODE: 16895,
FILE_MODE: 33279,
mount: i(function (r) {
if (!r.opts.fileSystemHandle) throw new Error('opts.fileSystemHandle is required');
return n.mount.apply(null, arguments);
}, 'mount'),
syncfs: i(async (r, a, c) => {
try {
let l = s.getLocalSet(r),
d = await s.getRemoteSet(r),
u = a ? d : l,
g = a ? l : d;
(await s.reconcile(r, u, g), c(null));
} catch (l) {
c(l);
}
}, 'syncfs'),
getLocalSet: i((r) => {
let a = Object.create(null);
function c(u) {
return u !== '.' && u !== '..';
}
i(c, 'isRealDir');
function l(u) {
return (g) => o.join2(u, g);
}
i(l, 'toAbsolute');
let d = t.readdir(r.mountpoint).filter(c).map(l(r.mountpoint));
for (; d.length;) {
let u = d.pop(),
g = t.stat(u);
(t.isDir(g.mode) && d.push.apply(d, t.readdir(u).filter(c).map(l(u))),
(a[u] = { timestamp: g.mtime, mode: g.mode }));
}
return { type: 'local', entries: a };
}, 'getLocalSet'),
getRemoteSet: i(async (r) => {
let a = Object.create(null),
c = await Se(r.opts.fileSystemHandle);
for (let [l, d] of c)
l !== '.' &&
(a[o.join2(r.mountpoint, l)] = {
timestamp:
d.kind === 'file' ? new Date((await d.getFile()).lastModified) : new Date(),
mode: d.kind === 'file' ? s.FILE_MODE : s.DIR_MODE,
});
return { type: 'remote', entries: a, handles: c };
}, 'getRemoteSet'),
loadLocalEntry: i((r) => {
let c = t.lookupPath(r, {}).node,
l = t.stat(r);
if (t.isDir(l.mode)) return { timestamp: l.mtime, mode: l.mode };
if (t.isFile(l.mode))
return (
(c.contents = n.getFileDataAsTypedArray(c)),
{ timestamp: l.mtime, mode: l.mode, contents: c.contents }
);
throw new Error('node type not supported');
}, 'loadLocalEntry'),
storeLocalEntry: i((r, a) => {
if (t.isDir(a.mode)) t.mkdirTree(r, a.mode);
else if (t.isFile(a.mode)) t.writeFile(r, a.contents, { canOwn: !0 });
else throw new Error('node type not supported');
(t.chmod(r, a.mode), t.utime(r, a.timestamp, a.timestamp));
}, 'storeLocalEntry'),
removeLocalEntry: i((r) => {
var a = t.stat(r);
t.isDir(a.mode) ? t.rmdir(r) : t.isFile(a.mode) && t.unlink(r);
}, 'removeLocalEntry'),
loadRemoteEntry: i(async (r) => {
if (r.kind === 'file') {
let a = await r.getFile();
return {
contents: new Uint8Array(await a.arrayBuffer()),
mode: s.FILE_MODE,
timestamp: new Date(a.lastModified),
};
} else {
if (r.kind === 'directory') return { mode: s.DIR_MODE, timestamp: new Date() };
throw new Error('unknown kind: ' + r.kind);
}
}, 'loadRemoteEntry'),
storeRemoteEntry: i(async (r, a, c) => {
let l = r.get(o.dirname(a)),
d = t.isFile(c.mode)
? await l.getFileHandle(o.basename(a), { create: !0 })
: await l.getDirectoryHandle(o.basename(a), { create: !0 });
if (d.kind === 'file') {
let u = await d.createWritable();
(await u.write(c.contents), await u.close());
}
r.set(a, d);
}, 'storeRemoteEntry'),
removeRemoteEntry: i(async (r, a) => {
(await r.get(o.dirname(a)).removeEntry(o.basename(a)), r.delete(a));
}, 'removeRemoteEntry'),
reconcile: i(async (r, a, c) => {
let l = 0,
d = [];
(Object.keys(a.entries).forEach(function (p) {
let b = a.entries[p],
I = c.entries[p];
(!I || (t.isFile(b.mode) && b.timestamp.getTime() > I.timestamp.getTime())) &&
(d.push(p), l++);
}),
d.sort());
let u = [];
if (
(Object.keys(c.entries).forEach(function (p) {
a.entries[p] || (u.push(p), l++);
}),
u.sort().reverse(),
!l)
)
return;
let g = a.type === 'remote' ? a.handles : c.handles;
for (let p of d) {
let b = o.normalize(p.replace(r.mountpoint, '/')).substring(1);
if (c.type === 'local') {
let I = g.get(b),
te = await s.loadRemoteEntry(I);
s.storeLocalEntry(p, te);
} else {
let I = s.loadLocalEntry(p);
await s.storeRemoteEntry(g, b, I);
}
}
for (let p of u)
if (c.type === 'local') s.removeLocalEntry(p);
else {
let b = o.normalize(p.replace(r.mountpoint, '/')).substring(1);
await s.removeRemoteEntry(g, b);
}
}, 'reconcile'),
};
e.FS.filesystems.NATIVEFS_ASYNC = s;
}
i(Y, 'initializeNativeFS');
var Se = i(async (e) => {
let t = [];
async function n(s) {
for await (let r of s.values()) (t.push(r), r.kind === 'directory' && (await n(r)));
}
(i(n, 'collect'), await n(e));
let o = new Map();
o.set('.', e);
for (let s of t) {
let r = (await e.resolve(s)).join('/');
o.set(r, s);
}
return o;
}, 'getFsHandles');
var X = j(
'AGFzbQEAAAABDANfAGAAAW9gAW8BfwMDAgECBygCE0pzdl9HZXRFcnJvcl9pbXBvcnQAAA5Kc3ZFcnJvcl9DaGVjawABChMCBwD7AQD7GwsJACAA+xr7FAAL',
);
var _e = (async function () {
if (
!(
globalThis.navigator &&
(/iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' &&
typeof navigator.maxTouchPoints < 'u' &&
navigator.maxTouchPoints > 1))
)
)
try {
let t = await WebAssembly.compile(X);
return await WebAssembly.instantiate(t);
} catch (t) {
if (t instanceof WebAssembly.CompileError) return;
throw t;
}
})();
async function Q() {
let e = await _e;
if (e) return e.exports;
let t = Symbol('error marker');
return {
Jsv_GetError_import: i(() => t, 'Jsv_GetError_import'),
JsvError_Check: i((n) => n === t, 'JsvError_Check'),
};
}
i(Q, 'getJsvErrorImport');
function Z(e) {
let t = { config: e, runtimeEnv: f },
n = {
noImageDecoding: !0,
noAudioDecoding: !0,
noWasmDecoding: !1,
preRun: De(e),
print: e.stdout,
printErr: e.stderr,
onExit(o) {
n.exitCode = o;
},
thisProgram: e._sysExecutable,
arguments: e.args,
API: t,
locateFile: i((o) => e.indexURL + o, 'locateFile'),
instantiateWasm: xe(e.indexURL),
};
return n;
}
i(Z, 'createSettings');
function ke(e) {
return function (t) {
let n = '/';
try {
t.FS.mkdirTree(e);
} catch (o) {
(console.error(`Error occurred while making a home directory '${e}':`),
console.error(o),
console.error(`Using '${n}' for a home directory instead`),
(e = n));
}
t.FS.chdir(e);
};
}
i(ke, 'createHomeDirectory');
function Re(e) {
return function (t) {
Object.assign(t.ENV, e);
};
}
i(Re, 'setEnvironment');
function Fe(e) {
return e
? [
async (t) => {
t.addRunDependency('fsInitHook');
try {
await e(t.FS, { sitePackages: t.API.sitePackages });
} finally {
t.removeRunDependency('fsInitHook');
}
},
]
: [];
}
i(Fe, 'callFsInitHook');
function Ae(e) {
let t = e.HEAPU32[e._Py_Version >>> 2],
n = (t >>> 24) & 255,
o = (t >>> 16) & 255,
s = (t >>> 8) & 255;
return [n, o, s];
}
i(Ae, 'computeVersionTuple');
function Oe(e) {
let t = z(e);
return async (n) => {
n.API.pyVersionTuple = Ae(n);
let [o, s] = n.API.pyVersionTuple;
(n.FS.mkdirTree('/lib'),
(n.API.sitePackages = `/lib/python${o}.${s}/site-packages`),
n.FS.mkdirTree(n.API.sitePackages),
n.addRunDependency('install-stdlib'));
try {
let r = await t;
n.FS.writeFile(`/lib/python${o}${s}.zip`, r);
} catch (r) {
(console.error('Error occurred while installing the standard library:'), console.error(r));
} finally {
n.removeRunDependency('install-stdlib');
}
};
}
i(Oe, 'installStdlib');
function De(e) {
let t;
return (
e.stdLibURL != null ? (t = e.stdLibURL) : (t = e.indexURL + 'python_stdlib.zip'),
[Oe(t), ke(e.env.HOME), Re(e.env), Y, ...Fe(e.fsInit)]
);
}
i(De, 'getFileSystemInitializationFuncs');
function xe(e) {
if (typeof WasmOffsetConverter < 'u') return;
let { binary: t, response: n } = R(e + 'pyodide.asm.wasm'),
o = Q();
return function (s, r) {
return (
(async function () {
let { Jsv_GetError_import: a, JsvError_Check: c } = await o;
((s.env.Jsv_GetError_import = a), (s.env.JsvError_Check = c));
try {
let l;
n
? (l = await WebAssembly.instantiateStreaming(n, s))
: (l = await WebAssembly.instantiate(await t, s));
let { instance: d, module: u } = l;
r(d, u);
} catch (l) {
(console.warn('wasm instantiation failed!'), console.warn(l));
}
})(),
{}
);
};
}
i(xe, 'getInstantiateWasmFunc');
var ee = '314.0.3';
function A(e) {
return e === void 0 || e.endsWith('/') ? e : e + '/';
}
i(A, 'withTrailingSlash');
var O = ee;
async function Le(e = {}) {
if ((await W(), e.lockFileContents && e.lockFileURL))
throw new Error("Can't pass both lockFileContents and lockFileURL");
let t = e.indexURL || (await K());
if (
((t = A(k(t))),
(e.packageBaseUrl = A(e.packageBaseUrl)),
(e.cdnUrl = A(e.packageBaseUrl ?? `https://cdn.jsdelivr.net/pyodide/v${O}/full/`)),
!e.lockFileContents)
) {
let s = e.lockFileURL ?? t + 'pyodide-lock.json';
((e.lockFileContents = G(s)), (e.packageBaseUrl ??= q(s)));
}
((e.indexURL = t), e.packageCacheDir && (e.packageCacheDir = A(k(e.packageCacheDir))));
let n = {
jsglobals: globalThis,
stdin: globalThis.prompt ? () => globalThis.prompt() : void 0,
args: [],
env: {},
packages: [],
packageCacheDir: e.packageBaseUrl,
enableRunUntilComplete: !0,
checkAPIVersion: !0,
BUILD_ID: '2cf7085e96ffaa58f5400af724c388859f9e21586cf6f254da008c60685a5d05',
},
o = Object.assign(n, e);
return ((o.env.HOME ??= '/home/pyodide'), (o.env.PYTHONINSPECT ??= '1'), o);
}
i(Le, 'initializeConfiguration');
function Ce(e) {
let t = Z(e),
n = t.API;
return ((n.lockFilePromise = Promise.resolve(e.lockFileContents)), t);
}
i(Ce, 'createEmscriptenSettings');
async function Te(e) {
if (e.createPyodideModule) return e.createPyodideModule;
let t = `${e.indexURL}pyodide.asm.mjs`;
return (await L(t)).default;
}
i(Te, 'loadWasmScript');
async function Ue(e, t) {
if (!e._loadSnapshot) return;
let n = await e._loadSnapshot,
o = ArrayBuffer.isView(n) ? n : new Uint8Array(n);
return ((t.noInitialRun = !0), (t.INITIAL_MEMORY = o.length), o);
}
i(Ue, 'prepareSnapshot');
async function We(e, t) {
let n = await e(t);
if (t.exitCode !== void 0) throw new n.ExitStatus(t.exitCode);
return n;
}
i(We, 'instantiatePyodideModule');
function Me(e, t) {
let n = e.API;
if (
(t.pyproxyToStringRepr && n.setPyProxyToStringMethod(!0),
t.convertNullToNone && n.setCompatNullToNone(!0),
t.toJsLiteralMap && n.setCompatToJsLiteralMap(!0),
n.version !== O && t.checkAPIVersion)
)
throw new Error(
`Pyodide version does not match: '${O}' <==> '${n.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`,
);
e.locateFile = (o) => {
throw o.endsWith('.so')
? new Error(`Failed to find dynamic library "${o}"`)
: new Error(`Unexpected call to locateFile("${o}")`);
};
}
i(Me, 'configureAPI');
function Be(e, t, n) {
let o = e.API,
s;
return (t && (s = o.restoreSnapshot(t)), o.finalizeBootstrap(s, n._snapshotDeserializer));
}
i(Be, 'bootstrapPyodide');
async function $e(e, t) {
let n = e._api;
return (
n.sys.path.insert(0, ''),
n._pyodide.set_excepthook(),
await n.packageIndexReady,
n.initializeStreams(t.stdin, t.stdout, t.stderr),
e
);
}
i($e, 'finalizeSetup');
async function B(e = {}) {
let t = await Le(e),
n = Ce(t),
o = await Te(t),
s = await Ue(t, n),
r = await We(o, n);
Me(r, t);
let a = Be(r, s, t);
return await $e(a, t);
}
i(B, 'loadPyodide');
globalThis.loadPyodide = B;
return le(je);
})();
try {
Object.assign(exports, loadPyodide);
} catch (_) {}
globalThis.loadPyodide = loadPyodide.loadPyodide;
//# sourceMappingURL=pyodide.js.map
-801
View File
@@ -1,801 +0,0 @@
var Q = Object.defineProperty;
var o = (e, t) => Q(e, 'name', { value: t, configurable: !0 }),
R = ((e) =>
typeof require < 'u'
? require
: typeof Proxy < 'u'
? new Proxy(e, { get: (t, n) => (typeof require < 'u' ? require : t)[n] })
: e)(function (e) {
if (typeof require < 'u') return require.apply(this, arguments);
throw Error('Dynamic require of "' + e + '" is not supported');
});
var W = (() => {
for (var e = new Uint8Array(128), t = 0; t < 64; t++)
e[t < 26 ? t + 65 : t < 52 ? t + 71 : t < 62 ? t - 4 : t * 4 - 205] = t;
return (n) => {
for (
var i = n.length,
s = new Uint8Array((((i - (n[i - 1] == '=') - (n[i - 2] == '=')) * 3) / 4) | 0),
r = 0,
a = 0;
r < i;
) {
var c = e[n.charCodeAt(r++)],
l = e[n.charCodeAt(r++)],
d = e[n.charCodeAt(r++)],
u = e[n.charCodeAt(r++)];
((s[a++] = (c << 2) | (l >> 4)), (s[a++] = (l << 4) | (d >> 2)), (s[a++] = (d << 6) | u));
}
return s;
};
})();
function Z(e) {
return !isNaN(parseFloat(e)) && isFinite(e);
}
o(Z, '_isNumber');
function P(e) {
return e.charAt(0).toUpperCase() + e.substring(1);
}
o(P, '_capitalize');
function D(e) {
return function () {
return this[e];
};
}
o(D, '_getter');
var N = ['isConstructor', 'isEval', 'isNative', 'isToplevel'],
I = ['columnNumber', 'lineNumber'],
S = ['fileName', 'functionName', 'source'],
ee = ['args'],
te = ['evalOrigin'],
F = N.concat(I, S, ee, te);
function p(e) {
if (e) for (var t = 0; t < F.length; t++) e[F[t]] !== void 0 && this['set' + P(F[t])](e[F[t]]);
}
o(p, 'StackFrame');
p.prototype = {
getArgs: o(function () {
return this.args;
}, 'getArgs'),
setArgs: o(function (e) {
if (Object.prototype.toString.call(e) !== '[object Array]')
throw new TypeError('Args must be an Array');
this.args = e;
}, 'setArgs'),
getEvalOrigin: o(function () {
return this.evalOrigin;
}, 'getEvalOrigin'),
setEvalOrigin: o(function (e) {
if (e instanceof p) this.evalOrigin = e;
else if (e instanceof Object) this.evalOrigin = new p(e);
else throw new TypeError('Eval Origin must be an Object or StackFrame');
}, 'setEvalOrigin'),
toString: o(function () {
var e = this.getFileName() || '',
t = this.getLineNumber() || '',
n = this.getColumnNumber() || '',
i = this.getFunctionName() || '';
return this.getIsEval()
? e
? '[eval] (' + e + ':' + t + ':' + n + ')'
: '[eval]:' + t + ':' + n
: i
? i + ' (' + e + ':' + t + ':' + n + ')'
: e + ':' + t + ':' + n;
}, 'toString'),
};
p.fromString = o(function (t) {
var n = t.indexOf('('),
i = t.lastIndexOf(')'),
s = t.substring(0, n),
r = t.substring(n + 1, i).split(','),
a = t.substring(i + 1);
if (a.indexOf('@') === 0)
var c = /@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(a, ''),
l = c[1],
d = c[2],
u = c[3];
return new p({
functionName: s,
args: r || void 0,
fileName: l,
lineNumber: d || void 0,
columnNumber: u || void 0,
});
}, 'StackFrame$$fromString');
for (v = 0; v < N.length; v++)
((p.prototype['get' + P(N[v])] = D(N[v])),
(p.prototype['set' + P(N[v])] = (function (e) {
return function (t) {
this[e] = !!t;
};
})(N[v])));
var v;
for (b = 0; b < I.length; b++)
((p.prototype['get' + P(I[b])] = D(I[b])),
(p.prototype['set' + P(I[b])] = (function (e) {
return function (t) {
if (!Z(t)) throw new TypeError(e + ' must be a Number');
this[e] = Number(t);
};
})(I[b])));
var b;
for (E = 0; E < S.length; E++)
((p.prototype['get' + P(S[E])] = D(S[E])),
(p.prototype['set' + P(S[E])] = (function (e) {
return function (t) {
this[e] = String(t);
};
})(S[E])));
var E,
A = p;
function ne() {
var e = /^\s*at .*(\S+:\d+|\(native\))/m,
t = /^(eval@)?(\[native code])?$/;
return {
parse: o(function (i) {
if (i.stack && i.stack.match(e)) return this.parseV8OrIE(i);
if (i.stack) return this.parseFFOrSafari(i);
throw new Error('Cannot parse given Error object');
}, 'ErrorStackParser$$parse'),
extractLocation: o(function (i) {
if (i.indexOf(':') === -1) return [i];
var s = /(.+?)(?::(\d+))?(?::(\d+))?$/,
r = s.exec(i.replace(/[()]/g, ''));
return [r[1], r[2] || void 0, r[3] || void 0];
}, 'ErrorStackParser$$extractLocation'),
parseV8OrIE: o(function (i) {
var s = i.stack
.split(`
`)
.filter(function (r) {
return !!r.match(e);
}, this);
return s.map(function (r) {
r.indexOf('(eval ') > -1 &&
(r = r.replace(/eval code/g, 'eval').replace(/(\(eval at [^()]*)|(,.*$)/g, ''));
var a = r
.replace(/^\s+/, '')
.replace(/\(eval code/g, '(')
.replace(/^.*?\s+/, ''),
c = a.match(/ (\(.+\)$)/);
a = c ? a.replace(c[0], '') : a;
var l = this.extractLocation(c ? c[1] : a),
d = (c && a) || void 0,
u = ['eval', '<anonymous>'].indexOf(l[0]) > -1 ? void 0 : l[0];
return new A({
functionName: d,
fileName: u,
lineNumber: l[1],
columnNumber: l[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseV8OrIE'),
parseFFOrSafari: o(function (i) {
var s = i.stack
.split(`
`)
.filter(function (r) {
return !r.match(t);
}, this);
return s.map(function (r) {
if (
(r.indexOf(' > eval') > -1 &&
(r = r.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ':$1')),
r.indexOf('@') === -1 && r.indexOf(':') === -1)
)
return new A({ functionName: r });
var a = /((.*".+"[^@]*)?[^@]*)(?:@)/,
c = r.match(a),
l = c && c[1] ? c[1] : void 0,
d = this.extractLocation(r.replace(a, ''));
return new A({
functionName: l,
fileName: d[0],
lineNumber: d[1],
columnNumber: d[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseFFOrSafari'),
};
}
o(ne, 'ErrorStackParser');
var re = new ne();
var M = re;
function ie() {
if (typeof API < 'u' && API !== globalThis.API) return API.runtimeEnv;
let e = typeof Bun < 'u',
t = typeof Deno < 'u',
n =
typeof process == 'object' &&
typeof process.versions == 'object' &&
typeof process.versions.node == 'string' &&
!process.browser,
i =
typeof navigator == 'object' &&
typeof navigator.userAgent == 'string' &&
navigator.userAgent.indexOf('Chrome') === -1 &&
navigator.userAgent.indexOf('Safari') > -1,
s = typeof read == 'function' && typeof load == 'function',
r = typeof navigator == 'object' && navigator.userAgent?.includes('Cloudflare-Workers');
return oe({ IN_BUN: e, IN_DENO: t, IN_NODE: n, IN_SAFARI: i, IN_SHELL: s, IN_WORKERD: r });
}
o(ie, 'getGlobalRuntimeEnv');
var f = ie();
function oe(e) {
let t =
e.IN_NODE &&
typeof module < 'u' &&
module.exports &&
typeof R == 'function' &&
typeof __dirname == 'string',
n = e.IN_NODE && !t,
i = !e.IN_NODE && !e.IN_DENO && !e.IN_BUN,
s =
i &&
typeof window < 'u' &&
typeof window.document < 'u' &&
typeof document.createElement == 'function' &&
'sessionStorage' in window &&
typeof globalThis.importScripts != 'function',
r =
i &&
typeof globalThis.WorkerGlobalScope < 'u' &&
typeof globalThis.self < 'u' &&
globalThis.self instanceof globalThis.WorkerGlobalScope;
if (r && ae()) throw new Error('Classic web workers are not supported');
let a = {
...e,
IN_BROWSER: i,
IN_BROWSER_MAIN_THREAD: s,
IN_BROWSER_WEB_WORKER: r,
IN_NODE_COMMONJS: t,
IN_NODE_ESM: n,
};
if (
!(
a.IN_BROWSER_MAIN_THREAD ||
a.IN_BROWSER_WEB_WORKER ||
a.IN_NODE ||
a.IN_SHELL ||
a.IN_WORKERD
)
)
throw new Error(`Cannot determine runtime environment: ${JSON.stringify(a)}`);
return a;
}
o(oe, 'calculateDerivedFlags');
function ae() {
try {
return (globalThis.importScripts('data:text/javascript,'), !0);
} catch {
return !1;
}
}
o(ae, 'isClassicWorker');
var $, x, se, B, L;
async function C() {
if (
!f.IN_NODE ||
(($ = (await import('node:url')).default),
(B = await import('node:fs')),
(L = await import('node:fs/promises')),
(se = (await import('node:vm')).default),
(x = await import('node:path')),
(T = x.sep),
typeof R < 'u')
)
return;
let e = B,
t = await import('node:crypto'),
n = await import('ws'),
i = await import('node:child_process'),
s = { fs: e, crypto: t, ws: n, child_process: i };
globalThis.require = function (r) {
return s[r];
};
}
o(C, 'initNodeModules');
function le(e, t) {
return x.resolve(t || '.', e);
}
o(le, 'node_resolvePath');
function ce(e, t) {
return (t === void 0 && (t = location), new URL(e, t).toString());
}
o(ce, 'browser_resolvePath');
var w;
f.IN_NODE ? (w = le) : f.IN_SHELL ? (w = o((e) => e, 'resolvePath')) : (w = ce);
var T;
f.IN_NODE || (T = '/');
function de(e, t) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://')
? { response: fetch(e) }
: { binary: L.readFile(e).then((n) => new Uint8Array(n.buffer, n.byteOffset, n.byteLength)) }
);
}
o(de, 'node_getBinaryResponse');
function ue(e, t) {
if ((e.startsWith('file://') && (e = e.slice(7)), e.includes('://')))
throw new Error('Shell cannot fetch urls');
return { binary: Promise.resolve(new Uint8Array(readbuffer(e))) };
}
o(ue, 'shell_getBinaryResponse');
function fe(e, t) {
let n = new URL(e, location);
return { response: fetch(n, t ? { integrity: t } : {}) };
}
o(fe, 'browser_getBinaryResponse');
var _;
f.IN_NODE ? (_ = de) : f.IN_SHELL ? (_ = ue) : (_ = fe);
async function j(e, t) {
let { response: n, binary: i } = _(e, t);
if (i) return i;
let s = await n;
if (!s.ok) throw new Error(`Failed to load '${e}': request failed.`);
return new Uint8Array(await s.arrayBuffer());
}
o(j, 'loadBinaryFile');
var O;
f.IN_NODE ? (O = me) : (O = o(async (e) => await import(e), 'loadScript'));
async function me(e) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://') ? await import(e) : await import($.pathToFileURL(e).href)
);
}
o(me, 'nodeLoadScript');
async function H(e) {
if (f.IN_NODE) {
await C();
let t = await L.readFile(e, { encoding: 'utf8' });
return JSON.parse(t);
} else if (f.IN_SHELL) {
let t = read(e);
return JSON.parse(t);
} else return await (await fetch(e)).json();
}
o(H, 'loadLockFile');
async function J() {
if (f.IN_NODE_COMMONJS) return __dirname;
let e;
try {
throw new Error();
} catch (i) {
e = i;
}
let t = M.parse(e)[0].fileName;
if ((f.IN_NODE && !t.startsWith('file://') && (t = `file://${t}`), f.IN_NODE_ESM)) {
let i = await import('node:path');
return (await import('node:url')).fileURLToPath(i.dirname(t));
}
let n = t.lastIndexOf(T);
if (n === -1)
throw new Error(
'Could not extract indexURL path from pyodide module location. Please pass the indexURL explicitly to loadPyodide.',
);
return t.slice(0, n);
}
o(J, 'calculateDirname');
function V(e) {
return e.substring(0, e.lastIndexOf('/') + 1) || globalThis.location?.toString() || '.';
}
o(V, 'calculateInstallBaseUrl');
function z(e) {
let t = e.FS,
n = e.FS.filesystems.MEMFS,
i = e.PATH,
s = {
DIR_MODE: 16895,
FILE_MODE: 33279,
mount: o(function (r) {
if (!r.opts.fileSystemHandle) throw new Error('opts.fileSystemHandle is required');
return n.mount.apply(null, arguments);
}, 'mount'),
syncfs: o(async (r, a, c) => {
try {
let l = s.getLocalSet(r),
d = await s.getRemoteSet(r),
u = a ? d : l,
y = a ? l : d;
(await s.reconcile(r, u, y), c(null));
} catch (l) {
c(l);
}
}, 'syncfs'),
getLocalSet: o((r) => {
let a = Object.create(null);
function c(u) {
return u !== '.' && u !== '..';
}
o(c, 'isRealDir');
function l(u) {
return (y) => i.join2(u, y);
}
o(l, 'toAbsolute');
let d = t.readdir(r.mountpoint).filter(c).map(l(r.mountpoint));
for (; d.length;) {
let u = d.pop(),
y = t.stat(u);
(t.isDir(y.mode) && d.push.apply(d, t.readdir(u).filter(c).map(l(u))),
(a[u] = { timestamp: y.mtime, mode: y.mode }));
}
return { type: 'local', entries: a };
}, 'getLocalSet'),
getRemoteSet: o(async (r) => {
let a = Object.create(null),
c = await pe(r.opts.fileSystemHandle);
for (let [l, d] of c)
l !== '.' &&
(a[i.join2(r.mountpoint, l)] = {
timestamp:
d.kind === 'file' ? new Date((await d.getFile()).lastModified) : new Date(),
mode: d.kind === 'file' ? s.FILE_MODE : s.DIR_MODE,
});
return { type: 'remote', entries: a, handles: c };
}, 'getRemoteSet'),
loadLocalEntry: o((r) => {
let c = t.lookupPath(r, {}).node,
l = t.stat(r);
if (t.isDir(l.mode)) return { timestamp: l.mtime, mode: l.mode };
if (t.isFile(l.mode))
return (
(c.contents = n.getFileDataAsTypedArray(c)),
{ timestamp: l.mtime, mode: l.mode, contents: c.contents }
);
throw new Error('node type not supported');
}, 'loadLocalEntry'),
storeLocalEntry: o((r, a) => {
if (t.isDir(a.mode)) t.mkdirTree(r, a.mode);
else if (t.isFile(a.mode)) t.writeFile(r, a.contents, { canOwn: !0 });
else throw new Error('node type not supported');
(t.chmod(r, a.mode), t.utime(r, a.timestamp, a.timestamp));
}, 'storeLocalEntry'),
removeLocalEntry: o((r) => {
var a = t.stat(r);
t.isDir(a.mode) ? t.rmdir(r) : t.isFile(a.mode) && t.unlink(r);
}, 'removeLocalEntry'),
loadRemoteEntry: o(async (r) => {
if (r.kind === 'file') {
let a = await r.getFile();
return {
contents: new Uint8Array(await a.arrayBuffer()),
mode: s.FILE_MODE,
timestamp: new Date(a.lastModified),
};
} else {
if (r.kind === 'directory') return { mode: s.DIR_MODE, timestamp: new Date() };
throw new Error('unknown kind: ' + r.kind);
}
}, 'loadRemoteEntry'),
storeRemoteEntry: o(async (r, a, c) => {
let l = r.get(i.dirname(a)),
d = t.isFile(c.mode)
? await l.getFileHandle(i.basename(a), { create: !0 })
: await l.getDirectoryHandle(i.basename(a), { create: !0 });
if (d.kind === 'file') {
let u = await d.createWritable();
(await u.write(c.contents), await u.close());
}
r.set(a, d);
}, 'storeRemoteEntry'),
removeRemoteEntry: o(async (r, a) => {
(await r.get(i.dirname(a)).removeEntry(i.basename(a)), r.delete(a));
}, 'removeRemoteEntry'),
reconcile: o(async (r, a, c) => {
let l = 0,
d = [];
(Object.keys(a.entries).forEach(function (m) {
let g = a.entries[m],
h = c.entries[m];
(!h || (t.isFile(g.mode) && g.timestamp.getTime() > h.timestamp.getTime())) &&
(d.push(m), l++);
}),
d.sort());
let u = [];
if (
(Object.keys(c.entries).forEach(function (m) {
a.entries[m] || (u.push(m), l++);
}),
u.sort().reverse(),
!l)
)
return;
let y = a.type === 'remote' ? a.handles : c.handles;
for (let m of d) {
let g = i.normalize(m.replace(r.mountpoint, '/')).substring(1);
if (c.type === 'local') {
let h = y.get(g),
X = await s.loadRemoteEntry(h);
s.storeLocalEntry(m, X);
} else {
let h = s.loadLocalEntry(m);
await s.storeRemoteEntry(y, g, h);
}
}
for (let m of u)
if (c.type === 'local') s.removeLocalEntry(m);
else {
let g = i.normalize(m.replace(r.mountpoint, '/')).substring(1);
await s.removeRemoteEntry(y, g);
}
}, 'reconcile'),
};
e.FS.filesystems.NATIVEFS_ASYNC = s;
}
o(z, 'initializeNativeFS');
var pe = o(async (e) => {
let t = [];
async function n(s) {
for await (let r of s.values()) (t.push(r), r.kind === 'directory' && (await n(r)));
}
(o(n, 'collect'), await n(e));
let i = new Map();
i.set('.', e);
for (let s of t) {
let r = (await e.resolve(s)).join('/');
i.set(r, s);
}
return i;
}, 'getFsHandles');
var G = W(
'AGFzbQEAAAABDANfAGAAAW9gAW8BfwMDAgECBygCE0pzdl9HZXRFcnJvcl9pbXBvcnQAAA5Kc3ZFcnJvcl9DaGVjawABChMCBwD7AQD7GwsJACAA+xr7FAAL',
);
var ge = (async function () {
if (
!(
globalThis.navigator &&
(/iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' &&
typeof navigator.maxTouchPoints < 'u' &&
navigator.maxTouchPoints > 1))
)
)
try {
let t = await WebAssembly.compile(G);
return await WebAssembly.instantiate(t);
} catch (t) {
if (t instanceof WebAssembly.CompileError) return;
throw t;
}
})();
async function K() {
let e = await ge;
if (e) return e.exports;
let t = Symbol('error marker');
return {
Jsv_GetError_import: o(() => t, 'Jsv_GetError_import'),
JsvError_Check: o((n) => n === t, 'JsvError_Check'),
};
}
o(K, 'getJsvErrorImport');
function q(e) {
let t = { config: e, runtimeEnv: f },
n = {
noImageDecoding: !0,
noAudioDecoding: !0,
noWasmDecoding: !1,
preRun: Ne(e),
print: e.stdout,
printErr: e.stderr,
onExit(i) {
n.exitCode = i;
},
thisProgram: e._sysExecutable,
arguments: e.args,
API: t,
locateFile: o((i) => e.indexURL + i, 'locateFile'),
instantiateWasm: Ie(e.indexURL),
};
return n;
}
o(q, 'createSettings');
function ve(e) {
return function (t) {
let n = '/';
try {
t.FS.mkdirTree(e);
} catch (i) {
(console.error(`Error occurred while making a home directory '${e}':`),
console.error(i),
console.error(`Using '${n}' for a home directory instead`),
(e = n));
}
t.FS.chdir(e);
};
}
o(ve, 'createHomeDirectory');
function be(e) {
return function (t) {
Object.assign(t.ENV, e);
};
}
o(be, 'setEnvironment');
function Ee(e) {
return e
? [
async (t) => {
t.addRunDependency('fsInitHook');
try {
await e(t.FS, { sitePackages: t.API.sitePackages });
} finally {
t.removeRunDependency('fsInitHook');
}
},
]
: [];
}
o(Ee, 'callFsInitHook');
function Pe(e) {
let t = e.HEAPU32[e._Py_Version >>> 2],
n = (t >>> 24) & 255,
i = (t >>> 16) & 255,
s = (t >>> 8) & 255;
return [n, i, s];
}
o(Pe, 'computeVersionTuple');
function he(e) {
let t = j(e);
return async (n) => {
n.API.pyVersionTuple = Pe(n);
let [i, s] = n.API.pyVersionTuple;
(n.FS.mkdirTree('/lib'),
(n.API.sitePackages = `/lib/python${i}.${s}/site-packages`),
n.FS.mkdirTree(n.API.sitePackages),
n.addRunDependency('install-stdlib'));
try {
let r = await t;
n.FS.writeFile(`/lib/python${i}${s}.zip`, r);
} catch (r) {
(console.error('Error occurred while installing the standard library:'), console.error(r));
} finally {
n.removeRunDependency('install-stdlib');
}
};
}
o(he, 'installStdlib');
function Ne(e) {
let t;
return (
e.stdLibURL != null ? (t = e.stdLibURL) : (t = e.indexURL + 'python_stdlib.zip'),
[he(t), ve(e.env.HOME), be(e.env), z, ...Ee(e.fsInit)]
);
}
o(Ne, 'getFileSystemInitializationFuncs');
function Ie(e) {
if (typeof WasmOffsetConverter < 'u') return;
let { binary: t, response: n } = _(e + 'pyodide.asm.wasm'),
i = K();
return function (s, r) {
return (
(async function () {
let { Jsv_GetError_import: a, JsvError_Check: c } = await i;
((s.env.Jsv_GetError_import = a), (s.env.JsvError_Check = c));
try {
let l;
n
? (l = await WebAssembly.instantiateStreaming(n, s))
: (l = await WebAssembly.instantiate(await t, s));
let { instance: d, module: u } = l;
r(d, u);
} catch (l) {
(console.warn('wasm instantiation failed!'), console.warn(l));
}
})(),
{}
);
};
}
o(Ie, 'getInstantiateWasmFunc');
var Y = '314.0.3';
function k(e) {
return e === void 0 || e.endsWith('/') ? e : e + '/';
}
o(k, 'withTrailingSlash');
var U = Y;
async function Se(e = {}) {
if ((await C(), e.lockFileContents && e.lockFileURL))
throw new Error("Can't pass both lockFileContents and lockFileURL");
let t = e.indexURL || (await J());
if (
((t = k(w(t))),
(e.packageBaseUrl = k(e.packageBaseUrl)),
(e.cdnUrl = k(e.packageBaseUrl ?? `https://cdn.jsdelivr.net/pyodide/v${U}/full/`)),
!e.lockFileContents)
) {
let s = e.lockFileURL ?? t + 'pyodide-lock.json';
((e.lockFileContents = H(s)), (e.packageBaseUrl ??= V(s)));
}
((e.indexURL = t), e.packageCacheDir && (e.packageCacheDir = k(w(e.packageCacheDir))));
let n = {
jsglobals: globalThis,
stdin: globalThis.prompt ? () => globalThis.prompt() : void 0,
args: [],
env: {},
packages: [],
packageCacheDir: e.packageBaseUrl,
enableRunUntilComplete: !0,
checkAPIVersion: !0,
BUILD_ID: '2cf7085e96ffaa58f5400af724c388859f9e21586cf6f254da008c60685a5d05',
},
i = Object.assign(n, e);
return ((i.env.HOME ??= '/home/pyodide'), (i.env.PYTHONINSPECT ??= '1'), i);
}
o(Se, 'initializeConfiguration');
function we(e) {
let t = q(e),
n = t.API;
return ((n.lockFilePromise = Promise.resolve(e.lockFileContents)), t);
}
o(we, 'createEmscriptenSettings');
async function _e(e) {
if (e.createPyodideModule) return e.createPyodideModule;
let t = `${e.indexURL}pyodide.asm.mjs`;
return (await O(t)).default;
}
o(_e, 'loadWasmScript');
async function ke(e, t) {
if (!e._loadSnapshot) return;
let n = await e._loadSnapshot,
i = ArrayBuffer.isView(n) ? n : new Uint8Array(n);
return ((t.noInitialRun = !0), (t.INITIAL_MEMORY = i.length), i);
}
o(ke, 'prepareSnapshot');
async function Re(e, t) {
let n = await e(t);
if (t.exitCode !== void 0) throw new n.ExitStatus(t.exitCode);
return n;
}
o(Re, 'instantiatePyodideModule');
function Fe(e, t) {
let n = e.API;
if (
(t.pyproxyToStringRepr && n.setPyProxyToStringMethod(!0),
t.convertNullToNone && n.setCompatNullToNone(!0),
t.toJsLiteralMap && n.setCompatToJsLiteralMap(!0),
n.version !== U && t.checkAPIVersion)
)
throw new Error(
`Pyodide version does not match: '${U}' <==> '${n.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`,
);
e.locateFile = (i) => {
throw i.endsWith('.so')
? new Error(`Failed to find dynamic library "${i}"`)
: new Error(`Unexpected call to locateFile("${i}")`);
};
}
o(Fe, 'configureAPI');
function Ae(e, t, n) {
let i = e.API,
s;
return (t && (s = i.restoreSnapshot(t)), i.finalizeBootstrap(s, n._snapshotDeserializer));
}
o(Ae, 'bootstrapPyodide');
async function Oe(e, t) {
let n = e._api;
return (
n.sys.path.insert(0, ''),
n._pyodide.set_excepthook(),
await n.packageIndexReady,
n.initializeStreams(t.stdin, t.stdout, t.stderr),
e
);
}
o(Oe, 'finalizeSetup');
async function dt(e = {}) {
let t = await Se(e),
n = we(t),
i = await _e(t),
s = await ke(t, n),
r = await Re(i, n);
Fe(r, t);
let a = Ae(r, s, t);
return await Oe(a, t);
}
o(dt, 'loadPyodide');
export { dt as loadPyodide, U as version };
//# sourceMappingURL=pyodide.mjs.map
Binary file not shown.
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env node
// web/scripts/sync-pyodide.mjs — 从 npm 包同步 Pyodide 运行时到 public/pyodide/
//
// 背景: web/public/pyodide/ 下的 Pyodide 运行时 (asm.mjs / asm.wasm / stdlib 等)
// 与 npm 依赖 `pyodide` 里的文件是同一份。把它们提交进仓库有两个坏处 ——
// 一是占仓库体积, 二是 npm 包升版后容易留下不一致的旧副本。
// 因此这 6 个文件改为构建/开发时从 node_modules 复制, 不进仓库。
//
// 例外: fonttools / numpy 两个 wheel 不在 npm 包里 (Pyodide 的依赖清单只登记
// 但不随包分发), 仍需仓库提供, 故保留在 public/pyodide/ 下。
//
// 用法: 由 pnpm dev / pnpm build 自动调用, 也可单独执行以校验环境
// node scripts/sync-pyodide.mjs
import fsp from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const WEB_DIR = path.resolve(HERE, '..');
/** npm 包里的 Pyodide 运行时目录 */
const SRC_DIR = path.join(WEB_DIR, 'node_modules', 'pyodide');
/** Vite 的静态资源目录 (原样拷贝到构建产物) */
const DEST_DIR = path.join(WEB_DIR, 'public', 'pyodide');
/**
* 从 npm 包复制的文件。与 npm 包内同名文件一一对应。
* 增删此列表时, 需同步更新 .gitignore 中对应的忽略项。
*/
const COPY_FILES = [
'pyodide.asm.mjs',
'pyodide.asm.wasm',
'pyodide.js',
'pyodide.mjs',
'pyodide-lock.json',
'python_stdlib.zip',
];
/**
* 仓库保留的文件 (不在 npm 包内), 以及它们应满足的完整性校验。
* 这些 wheel 由 pyodide-lock.json 登记, 版本必须与之一致 ——
* 否则 Pyodide 在 loadPackage() 时会因校验失败而报错。
*/
const KEEP_FILES = [
'fonttools-4.62.1-py3-none-any.whl',
'numpy-2.4.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl',
];
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
/** 读取并解析 lock.json, 返回 { 包名: 条目 } */
async function readLock(p) {
const d = JSON.parse(await fsp.readFile(p, 'utf8'));
return d.packages ?? {};
}
/**
* 校验保留下来的 wheel 与 lock.json 配套。
*
* 这是本机制的主要风险点: wheel 在仓库、lock.json 在 npm 包, 两者的版本可能
* 各自漂移。例如 npm 的 pyodide 升版后 lock.json 引用了新版 fonttools, 而仓库里
* 仍是旧 wheel —— 此时运行时 loadPackage('fonttools') 会因 sha256 不匹配而失败,
* 且只在用户点开「字体编辑」时才暴露。故在此提前拦截。
*/
async function verifyWheels(lock) {
const problems = [];
for (const name of KEEP_FILES) {
const file = path.join(DEST_DIR, name);
let buf;
try {
buf = await fsp.readFile(file);
} catch {
problems.push(`缺少 ${name} (需随仓库提供, 不在 npm 包内)`);
continue;
}
// 在 lock.json 中找到登记该文件的条目, 比对 sha256
const entry = Object.values(lock).find((e) => e.file_name === name);
if (!entry) {
problems.push(
`${name} 未被 pyodide-lock.json 登记 —— npm 的 pyodide 可能已升版, ` +
`请改用新版 wheel 或调整 pyodide 依赖版本`,
);
continue;
}
const expected = entry.sha256;
if (expected && sha256(buf) !== expected) {
problems.push(`${name} 与 lock.json 登记的 sha256 不符 (文件可能损坏或被替换)`);
}
}
return problems;
}
async function main() {
// npm 依赖是否存在 (未安装依赖时给出明确提示, 而不是沉默地跳过)
try {
await fsp.access(SRC_DIR);
} catch {
console.error(`[✗] 未找到 ${path.relative(WEB_DIR, SRC_DIR)}, 请先运行 pnpm install`);
process.exit(1);
}
await fsp.mkdir(DEST_DIR, { recursive: true });
// 1. 从 npm 包复制运行时文件
let copied = 0;
for (const name of COPY_FILES) {
const src = path.join(SRC_DIR, name);
const dest = path.join(DEST_DIR, name);
try {
// 源与目标内容一致时跳过写入: 避免每次构建都触碰文件, 也便于观察实际变化
const [a, b] = await Promise.all([fsp.readFile(src), fsp.readFile(dest).catch(() => null)]);
if (b && a.equals(b)) continue;
await fsp.copyFile(src, dest);
copied++;
} catch (e) {
console.error(`[✗] 复制 ${name} 失败: ${e.message}`);
process.exit(1);
}
}
// 2. 校验留在仓库的 wheel 与 lock.json 配套
const lock = await readLock(path.join(DEST_DIR, 'pyodide-lock.json'));
const problems = await verifyWheels(lock);
if (problems.length) {
console.error('[✗] Pyodide 依赖校验失败:');
for (const p of problems) console.error(` ${p}`);
process.exit(1);
}
const total = (
await Promise.all(
[...COPY_FILES, ...KEEP_FILES].map(async (n) => {
try {
return (await fsp.stat(path.join(DEST_DIR, n))).size;
} catch {
return 0;
}
}),
)
).reduce((a, b) => a + b, 0);
console.log(
copied > 0
? `[*] Pyodide 运行时已同步 (更新 ${copied} 个文件, 共 ${(total / 1048576).toFixed(1)}MB)`
: `[*] Pyodide 运行时已就绪 (${(total / 1048576).toFixed(1)}MB)`,
);
}
await main();
+50 -50
View File
@@ -1,9 +1,9 @@
import { exec, shellQuote, toast } from './ksu';
import { copyFont, pickWghtRange, renderSlots, setApplying, slots } from './slots';
import { applyWghtOverride, getSelectedWghtMode, writeWghtMode } from './wght';
import { invalidateTestFonts } from './testFonts';
import { canApply, copyFont, refreshEnSubset, renderSlots, setApplying, slots } from './slots';
import { getSelectedWghtMode, writeWghtMode } from './wght';
import { writeSlotModes } from './fontFiles';
import { applyBtn } from './dom';
import { FONTS_DIR } from './constants';
import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS } from './constants';
const logDialog = document.getElementById('log-dialog') as any;
const logContent = document.getElementById('log-content')!;
@@ -12,71 +12,71 @@ document.getElementById('log-close')?.addEventListener('click', () => {
logDialog.open = false;
});
async function syncSingleSlot(key: 'hans' | 'hant' | 'en' | 'mono' | 'emoji'): Promise<void> {
const slot = slots[key];
const dest = `${FONTS_DIR}/${key}.ttf`;
if (slot.path) {
if (slot.path !== dest) await copyFont(slot.path, dest);
} else {
await exec(`rm -f ${shellQuote(dest)}`);
}
}
async function syncMultiSlot(key: 'hans' | 'hant' | 'en'): Promise<void> {
const slot = slots[key];
const dir = `${MULTI_DIR}/${key}`;
await exec(`mkdir -p ${shellQuote(dir)}`);
for (const w of MULTI_WEIGHTS) {
const entry = slot.multiWeights?.[w];
const dest = `${dir}/${w}.ttf`;
if (entry?.path) {
if (entry.path !== dest) await copyFont(entry.path, dest);
} else {
const sub = key === 'en' ? ` ${shellQuote(`${dir}/.subset-${w}.ttf`)}` : '';
await exec(`rm -f ${shellQuote(dest)}${sub}`);
}
}
}
async function apply() {
if (!slots.hans.path) return;
if (!canApply()) return;
setApplying(true);
renderSlots();
try {
// 字重范围覆写: 用 UI 当前模式 (持久化到 FONTS/wght-mode.txt), 仅当存在可变字体且模式非 0 时处理
const wghtMode = getSelectedWghtMode();
await writeWghtMode(wghtMode);
const wghtPick = pickWghtRange();
if (wghtMode !== 0 && wghtPick) {
// Go 程序自行读取 wght-map.txt (mode 3)
await applyWghtOverride(wghtMode, wghtPick.min, wghtPick.max);
}
// 保存各槽位模式 (可变字体/多字重) 与字重覆写模式; 两种模式的字体文件互不删除
await writeSlotModes({
hans: slots.hans.mode,
hant: slots.hant.mode,
en: slots.en.mode,
});
await writeWghtMode(getSelectedWghtMode());
// 启动加载的字体 path 即 FONT/ 内的文件, 无需再复制
if (slots.hans.path !== `${FONTS_DIR}/hans.ttf`) {
await copyFont(slots.hans.path, `${FONTS_DIR}/hans.ttf`);
}
if (slots.hant.path) {
if (slots.hant.path !== `${FONTS_DIR}/hant.ttf`) {
await copyFont(slots.hant.path, `${FONTS_DIR}/hant.ttf`);
for (const key of ['hans', 'hant', 'en'] as const) {
if (slots[key].mode === 'multi') {
await syncMultiSlot(key);
} else {
await syncSingleSlot(key);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/hant.ttf`)}`);
}
if (slots.en.path) {
if (slots.en.path !== `${FONTS_DIR}/en.ttf`) {
await copyFont(slots.en.path, `${FONTS_DIR}/en.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/en.ttf`)}`);
}
if (slots.mono.path) {
if (slots.mono.path !== `${FONTS_DIR}/mono.ttf`) {
await copyFont(slots.mono.path, `${FONTS_DIR}/mono.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/mono.ttf`)}`);
}
if (slots.emoji.path) {
if (slots.emoji.path !== `${FONTS_DIR}/emoji.ttf`) {
await copyFont(slots.emoji.path, `${FONTS_DIR}/emoji.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/emoji.ttf`)}`);
}
await syncSingleSlot('mono');
await syncSingleSlot('emoji');
// apply.sh 会完成系统字体复制、英文单/多字重子集化以及 fontmm-wght -sync XML 同步
const { errno, stdout, stderr } = await exec('sh /data/adb/modules/FontMM/apply.sh');
if (errno !== 0) throw new Error(stderr || 'apply.sh 执行失败');
if (errno !== 0) throw new Error(stderr || stdout || 'apply.sh 执行失败');
if (logContent && logDialog) {
logContent.textContent = stdout;
logDialog.open = true;
}
toast('字体已应用,重启后生效');
// 字体已变化: 下次进入测试页时重新加载
invalidateTestFonts();
document.dispatchEvent(new CustomEvent('fonts-changed'));
} catch (e) {
toast(`应用失败: ${String(e)}`);
} finally {
setApplying(false);
// 应用后刷新英文子集结果 (issue #14): 子集大小只有跑过 apply.sh 才知道
await refreshEnSubset();
renderSlots();
}
}
+17
View File
@@ -1,10 +1,27 @@
// 全局路径与外部链接常量
export const FONTS_DIR = '/data/adb/modules/FontMM/FONTS';
export const MULTI_DIR = `${FONTS_DIR}/multi`;
export const SLOT_MODES_FILE = `${FONTS_DIR}/slot-modes.txt`;
export const WEBROOT_DIR = '/data/adb/modules/FontMM/webroot';
export const TEST_FONT_DIR = `${WEBROOT_DIR}/fonts-test`;
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制)
export const WGHT_BIN = '/data/adb/modules/FontMM/tools/fontmm-wght';
// 多字重模式支持的标准 9 档字重
export const MULTI_WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900] as const;
export const WEIGHT_LABELS: Record<number, string> = {
100: '淡体',
200: '特细',
300: '细体',
400: '标准',
500: '适中',
600: '次粗',
700: '粗体',
800: '特粗',
900: '浓体',
};
// 捐献 (支付宝/爱发电) 与开发者主页 (浏览器) 链接
export const DONATE_ALIPAY_URI =
'alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/2m615805eflrafv8ipc2p15';
+107 -4
View File
@@ -1,13 +1,33 @@
import { exec, shellQuote } from './ksu';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS, SLOT_MODES_FILE, TEST_FONT_DIR } from './constants';
import { formatSize } from './fontInfo';
import type { MultiSlotKey, SlotMode, WeightLevel } from './types';
// 复制 FONT/ 到 webroot/fonts-test, 供页面加载与名称解析
// 复制 FONTS/ 到 webroot/fonts-test, 供页面加载与名称解析
// (WebView 无法直接访问模块外部目录, 符号链接在真机也不可靠, 直接复制)
//
// 只复制单字体槽位与多字重槽位的用户字体, 跳过 .en-subset.ttf / .subset-*.ttf 等中转文件。
// 结尾加 `:` 保证任一可选文件不存在时整体退出码仍为 0 (issue #11)。
const SLOT_FILES = ['hans.ttf', 'hant.ttf', 'en.ttf', 'mono.ttf', 'emoji.ttf'];
const MULTI_SLOTS: MultiSlotKey[] = ['hans', 'hant', 'en'];
export async function ensureFontsCopy(): Promise<string[]> {
const multiCmds: string[] = [];
for (const s of MULTI_SLOTS) {
for (const w of MULTI_WEIGHTS) {
multiCmds.push(
`[ -f '${MULTI_DIR}/${s}/${w}.ttf' ] && cp -f '${MULTI_DIR}/${s}/${w}.ttf' '${TEST_FONT_DIR}/multi-${s}-${w}.ttf'`,
);
}
}
const copyCmd = [
`rm -rf '${TEST_FONT_DIR}'`,
`mkdir -p '${TEST_FONT_DIR}'`,
`cp -f '${FONTS_DIR}'/*.ttf '${TEST_FONT_DIR}'/ 2>/dev/null`,
...SLOT_FILES.map(
(f) => `[ -f '${FONTS_DIR}/${f}' ] && cp -f '${FONTS_DIR}/${f}' '${TEST_FONT_DIR}/${f}'`,
),
...multiCmds,
':', // 兜底: 保证整体退出码为 0
].join('\n');
try {
const { errno } = await exec(copyCmd);
@@ -18,7 +38,7 @@ export async function ensureFontsCopy(): Promise<string[]> {
return listFontsDir();
}
// 列出 fonts-test/ 下的字体文件 (每行一个完整路径)
// 列出 fonts-test/ 下的字体文件名 (不含目录前缀)
export async function listFontsDir(): Promise<string[]> {
try {
const { errno, stdout } = await exec(
@@ -34,3 +54,86 @@ export async function listFontsDir(): Promise<string[]> {
return [];
}
}
// 读取槽位模式配置 (FONTS/slot-modes.txt), 缺失时全部默认 'single'
export async function readSlotModes(): Promise<Record<MultiSlotKey, SlotMode>> {
const modes: Record<MultiSlotKey, SlotMode> = { hans: 'single', hant: 'single', en: 'single' };
try {
const { errno, stdout } = await exec(`cat ${shellQuote(SLOT_MODES_FILE)} 2>/dev/null || true`);
if (errno !== 0) return modes;
for (const raw of stdout.split('\n')) {
const line = raw.split('#')[0].trim();
const idx = line.indexOf('=');
if (idx <= 0) continue;
const k = line.slice(0, idx).trim();
const v = line.slice(idx + 1).trim();
if ((k === 'hans' || k === 'hant' || k === 'en') && (v === 'single' || v === 'multi')) {
modes[k] = v;
}
}
} catch {
// 忽略读取失败
}
return modes;
}
// 写入槽位模式配置 (FONTS/slot-modes.txt)
export async function writeSlotModes(modes: Record<MultiSlotKey, SlotMode>): Promise<void> {
const content = `hans=${modes.hans}\nhant=${modes.hant}\nen=${modes.en}`;
await exec(
`mkdir -p ${shellQuote(FONTS_DIR)} && printf '%s\\n' ${shellQuote(content)} > ${shellQuote(SLOT_MODES_FILE)}`,
);
}
// 英文字体子集文件: apply.sh 子集化成功时写入 FONTS/.en-subset.ttf (issue #10),
// 安装到 system/fonts 的就是它, 大小通常比原字体小两个数量级 (issue #14)。
export const EN_SUBSET_FILE = `${FONTS_DIR}/.en-subset.ttf`;
// 读取英文单字体子集大小 (无子集返回 null)。
// 要求子集比 en.ttf 新 —— 换过英文字体但还没重新应用时, 旧子集不该继续展示。
export async function getEnSubsetSizeText(): Promise<string | null> {
// dev 假数据: 真机没应用过就没有该文件, 徽标无从预览
if (import.meta.env.DEV) return '218 KB';
try {
const subset = shellQuote(EN_SUBSET_FILE);
const { errno, stdout } = await exec(
`[ -f ${subset} ] && [ ${subset} -nt ${shellQuote(`${FONTS_DIR}/en.ttf`)} ] && wc -c < ${subset}`,
);
if (errno !== 0) return null;
const bytes = Number(stdout.trim());
return Number.isFinite(bytes) && bytes > 0 ? formatSize(bytes) : null;
} catch {
return null;
}
}
// 读取英文多字重各档位的子集大小 (无子集时不包含该字重)
export async function getEnMultiSubsetSizes(
weights: WeightLevel[],
): Promise<Partial<Record<WeightLevel, string>>> {
const out: Partial<Record<WeightLevel, string>> = {};
if (weights.length === 0) return out;
if (import.meta.env.DEV) {
for (const w of weights) out[w] = `${170 + Math.round(w / 20)} KB`;
return out;
}
const checks = weights.map((w) => {
const sub = shellQuote(`${MULTI_DIR}/en/.subset-${w}.ttf`);
const orig = shellQuote(`${MULTI_DIR}/en/${w}.ttf`);
return `if [ -f ${sub} ] && [ ${sub} -nt ${orig} ]; then echo "${w}:$(wc -c < ${sub})"; fi`;
});
try {
const { errno, stdout } = await exec(checks.join('; '));
if (errno !== 0) return out;
for (const line of stdout.split('\n')) {
const m = line.trim().match(/^(\d+):(\d+)$/);
if (!m) continue;
const w = Number(m[1]) as WeightLevel;
const bytes = Number(m[2]);
if (Number.isFinite(bytes) && bytes > 0) out[w] = formatSize(bytes);
}
} catch {
// 忽略读取失败
}
return out;
}
+39 -9
View File
@@ -31,6 +31,12 @@ function extractWghtRange(font: any): string | undefined {
return `${Math.round(wght.minValue)}-${Math.round(wght.maxValue)}`;
}
// 字体体积展示: 1MB 以下用 KB (子集化结果常在百 KB 量级, 用 MB 会显示成 0.2 MB 看不出量级)
export function formatSize(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
// 读取 fonts-test/ 下字体文件的名称与大小 (WebView 仅能访问 webroot 内文件)
export async function readFontInfo(file: string): Promise<FontInfo> {
// dev 假数据: 模拟各槽位字体的名称/大小/可变标识
@@ -46,14 +52,38 @@ export async function readFontInfo(file: string): Promise<FontInfo> {
'emoji.ttf': { name: 'Noto Color Emoji', size: '9.8 MB', variable: false },
};
const mock = MOCK_FONT_INFO[file];
return mock
? {
name: mock.name,
sizeText: mock.size,
isVariable: mock.variable,
wghtRange: mock.wght,
}
: {};
if (mock) {
return {
name: mock.name,
sizeText: mock.size,
isVariable: mock.variable,
wghtRange: mock.wght,
};
}
const multiMatch = file.match(/^multi-(hans|hant|en)-(\d+)\.ttf$/);
if (multiMatch) {
const slot = multiMatch[1];
const w = multiMatch[2];
const baseName =
slot === 'hans' ? 'PingFang SC' : slot === 'hant' ? 'PingFang TC' : 'SF Pro Text';
const weightLabel: Record<string, string> = {
'100': 'Thin',
'200': 'ExtraLight',
'300': 'Light',
'400': 'Regular',
'500': 'Medium',
'600': 'SemiBold',
'700': 'Bold',
'800': 'ExtraBold',
'900': 'Black',
};
return {
name: `${baseName} ${weightLabel[w] ?? w}`,
sizeText: slot === 'en' ? '640 KB' : '11.8 MB',
isVariable: false,
};
}
return {};
}
try {
const res = await fetch(`fonts-test/${file}`);
@@ -61,7 +91,7 @@ export async function readFontInfo(file: string): Promise<FontInfo> {
const buf = await res.arrayBuffer();
const font = opentype.parse(buf);
const name = extractFamilyName(font);
const sizeText = `${(buf.byteLength / 1024 / 1024).toFixed(1)} MB`;
const sizeText = formatSize(buf.byteLength);
return {
name: name ?? undefined,
sizeText,
+60 -49
View File
@@ -12,25 +12,42 @@ export interface FileItem {
size?: string;
}
export class FontFilePicker {
private currentPath = '/storage/emulated/0';
private dialogEl!: HTMLElement;
private listEl!: HTMLElement;
private pathEl!: HTMLElement;
private onSelectCallback: (path: string, fileName: string) => void;
/** 选中文件时的回调: 完整路径与文件名 */
export type FontSelectHandler = (path: string, fileName: string) => void;
constructor(onSelect: (path: string, fileName: string) => void) {
this.onSelectCallback = onSelect;
const DEFAULT_PATH = '/storage/emulated/0';
/**
* 文件选择器。全局只应存在一个实例 (下方导出 fontPicker) —— 对话框 DOM 是
* 单例 (按 id 复用), 若允许第二个实例, 它会复用这份 DOM 却拿不到返回/取消
* 按钮的监听 (initDialog 命中已有元素时直接返回), 于是返回键按上一个实例的
* 过期路径导航、选中文件也回调给上一个实例, 表现为「返回跳两层」「在别的
* 目录选文件没反应」(issue #13)。因此选中回调改为每次 show 时传入。
*/
class FontFilePicker {
private currentPath = DEFAULT_PATH;
private dialogEl: any = null;
private listEl: HTMLElement | null = null;
private pathEl: HTMLElement | null = null;
private onSelect: FontSelectHandler | null = null;
/** 打开选择器: initialPath 为起始目录, onSelect 为本次选择的处理函数 */
public show(initialPath: string, onSelect: FontSelectHandler): void {
this.initDialog();
this.onSelect = onSelect;
this.currentPath = initialPath || DEFAULT_PATH;
this.pathEl!.textContent = this.currentPath;
this.dialogEl.open = true;
void this.loadDirectory(this.currentPath);
}
public hide(): void {
if (this.dialogEl) this.dialogEl.open = false;
this.onSelect = null;
}
private initDialog(): void {
if (document.getElementById('picker-dialog')) {
this.dialogEl = document.getElementById('picker-dialog')!;
this.listEl = document.getElementById('picker-list')!;
this.pathEl = document.getElementById('picker-path')!;
return;
}
if (this.dialogEl) return;
const dialogHTML = `
<md-dialog id="picker-dialog" class="font-picker-dialog">
@@ -41,7 +58,7 @@ export class FontFilePicker {
</md-icon-button>
<div class="picker-path-group">
<div class="picker-subtitle">选择字体文件</div>
<div id="picker-path" class="picker-path-text">/storage/emulated/0</div>
<div id="picker-path" class="picker-path-text">${DEFAULT_PATH}</div>
</div>
</div>
</div>
@@ -57,22 +74,29 @@ export class FontFilePicker {
`;
document.body.insertAdjacentHTML('beforeend', dialogHTML);
this.dialogEl = document.getElementById('picker-dialog')!;
this.listEl = document.getElementById('picker-list')!;
this.pathEl = document.getElementById('picker-path')!;
this.dialogEl = document.getElementById('picker-dialog');
this.listEl = document.getElementById('picker-list');
this.pathEl = document.getElementById('picker-path');
document.getElementById('picker-back-btn')?.addEventListener('click', () => this.navigateUp());
document.getElementById('picker-cancel-btn')?.addEventListener('click', () => this.hide());
}
public show(initialPath = '/storage/emulated/0'): void {
this.currentPath = initialPath;
(this.dialogEl as any).open = true;
this.loadDirectory(this.currentPath);
}
// 列表项用事件委托: 只绑定一次, 渲染只替换内容, 不重复挂监听
this.listEl!.addEventListener('click', (e) => {
const item = (e.target as HTMLElement).closest('.picker-item') as HTMLElement | null;
if (!item) return;
const name = item.dataset.name!;
public hide(): void {
(this.dialogEl as any).open = false;
if (item.dataset.isdir === 'true') {
this.currentPath = this.currentPath === '/' ? `/${name}` : `${this.currentPath}/${name}`;
void this.loadDirectory(this.currentPath);
} else {
const fullPath = `${this.currentPath}/${name}`;
const handler = this.onSelect;
this.hide();
handler?.(fullPath, name);
}
});
}
private navigateUp(): void {
@@ -80,22 +104,22 @@ export class FontFilePicker {
const parts = this.currentPath.split('/').filter(Boolean);
parts.pop();
this.currentPath = parts.length === 0 ? '/' : '/' + parts.join('/');
this.loadDirectory(this.currentPath);
void this.loadDirectory(this.currentPath);
}
private async loadDirectory(path: string): Promise<void> {
this.pathEl.textContent = path;
this.listEl.innerHTML = `<div class="picker-loading">正在读取目录...</div>`;
this.pathEl!.textContent = path;
this.listEl!.innerHTML = `<div class="picker-loading">正在读取目录...</div>`;
try {
const { items, failed } = await this.readDir(path);
if (failed) {
this.listEl.innerHTML = `<div class="picker-error">无法读取该目录</div>`;
this.listEl!.innerHTML = `<div class="picker-error">无法读取该目录</div>`;
return;
}
this.renderList(items);
} catch (e) {
this.listEl.innerHTML = `<div class="picker-error">读取目录异常: ${String(e)}</div>`;
this.listEl!.innerHTML = `<div class="picker-error">读取目录异常: ${String(e)}</div>`;
}
}
@@ -140,7 +164,7 @@ export class FontFilePicker {
private renderList(items: FileItem[]): void {
if (items.length === 0) {
this.listEl.innerHTML = `
this.listEl!.innerHTML = `
<div class="picker-empty">
<md-icon>find_in_page</md-icon>
<span>此目录下没有 .ttf 字体文件</span>
@@ -148,7 +172,7 @@ export class FontFilePicker {
return;
}
this.listEl.innerHTML = items
this.listEl!.innerHTML = items
.map(
(item) => `
<md-list-item class="picker-item ${item.isDir ? 'is-dir' : 'is-file'}" data-name="${item.name}" data-isdir="${item.isDir}">
@@ -165,21 +189,8 @@ export class FontFilePicker {
`,
)
.join('');
this.listEl.querySelectorAll('.picker-item').forEach((el) => {
el.addEventListener('click', () => {
const name = (el as HTMLElement).dataset.name!;
const isDir = (el as HTMLElement).dataset.isdir === 'true';
if (isDir) {
this.currentPath = this.currentPath === '/' ? `/${name}` : `${this.currentPath}/${name}`;
this.loadDirectory(this.currentPath);
} else {
const fullPath = `${this.currentPath}/${name}`;
this.onSelectCallback(fullPath, name);
this.hide();
}
});
});
}
}
/** 全局唯一的文件选择器实例 (见 FontFilePicker 的说明) */
export const fontPicker = new FontFilePicker();
+22
View File
@@ -9,3 +9,25 @@ 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);
}
/**
* 从已选字重列表中挑选最接近 target 的档位 (与 Go 引擎 NearestWeight 保持一致)。
* 距离相等时: target >= 400 偏向更重档位, target < 400 偏向更轻档位。
*/
export function nearestWeight(available: number[], target: number): number {
if (available.length === 0) return 400;
let best = available[0];
let bestDist = Math.abs(best - target);
for (let i = 1; i < available.length; i++) {
const w = available[i];
const d = Math.abs(w - target);
if (
d < bestDist ||
(d === bestDist && ((target >= 400 && w > best) || (target < 400 && w < best)))
) {
best = w;
bestDist = d;
}
}
return best;
}
+34 -1
View File
@@ -1,4 +1,4 @@
import { amStart, exec, getSystemInfo, moduleInfo } from './ksu';
import { amStart, exec, getPreloaderStatus, getSystemInfo, moduleInfo } from './ksu';
import { rebootBtn } from './dom';
import { ALIPAY_PKG, DEV_PROFILE_URL, DONATE_ALIPAY_URI, DONATE_IFDIAN_URL } from './constants';
@@ -61,6 +61,39 @@ export async function loadHome(): Promise<void> {
} catch {
set('home-metamodule', '未安装');
}
await loadPreloader();
}
// 渲染字体预热器状态。
// 就绪条件: 预加载库随模块安装 + 存在可用的 Zygisk 环境 (两者缺一不可)。
async function loadPreloader(): Promise<void> {
const status = await getPreloaderStatus();
const statusEl = document.getElementById('home-preload-status');
const providerEl = document.getElementById('home-preload-provider');
const noteEl = document.getElementById('home-preload-note');
if (!statusEl || !providerEl || !noteEl) return;
const ready = status.libInstalled && status.zygiskReady;
// 状态色: 就绪用主题主色, 未就绪用错误色 (与其他状态提示一致的语义)
statusEl.textContent = ready ? '已启用' : '未生效';
statusEl.classList.toggle('is-error', !ready);
providerEl.textContent = status.provider || '未检测到';
// 未就绪时给出具体原因, 而不是只显示一个笼统的失败状态
if (ready) {
noteEl.hidden = true;
noteEl.textContent = '';
} else if (!status.libInstalled) {
noteEl.hidden = false;
noteEl.textContent = '模块内未找到 zygisk/arm64-v8a.so, 请重新刷入模块。';
} else {
noteEl.hidden = false;
noteEl.textContent =
'未检测到可用的 Zygisk 环境, 字体预热不会生效, 被「卸载模块」的应用可能字体异常。请在 Root 管理器中启用内置 Zygisk, 或安装 Zygisk Next / ReZygisk。';
}
}
// 支付宝捐献: 必须在 WebUI 外打开 (am start), 否则 alipays 协议无法唤起
+176 -11
View File
@@ -31,14 +31,41 @@ const FAKE_FS: Record<string, { dirs: string[]; fonts: string[]; files: string[]
files: ['a.pdf'],
},
'/storage/emulated/0/Fonts': {
dirs: [],
dirs: ['PingFang_SC'],
fonts: ['OPPOSans.ttf', 'SourceHanSansCN.ttf', 'Inter-Variable.otf'],
files: [],
},
'/storage/emulated/0/Fonts/PingFang_SC': {
dirs: [],
fonts: [
'PingFangSC-Thin.ttf',
'PingFangSC-Light.ttf',
'PingFangSC-Regular.ttf',
'PingFangSC-Medium.ttf',
'PingFangSC-Semibold.ttf',
'PingFangSC-Bold.ttf',
],
files: [],
},
'/storage/emulated/0/Documents': { dirs: [], fonts: [], files: ['notes.txt'] },
'/storage/emulated/0/字体': { dirs: [], fonts: ['思源黑体.ttf', '霞鹜文楷.ttf'], files: [] },
};
// dev 模式保存内存状态, 便于测试单/多字重切换与页面刷新状态一致
let mockSlotModes = 'hans=single\nhant=single\nen=single';
const MOCK_TEST_FONTS = [
'hans.ttf',
'hant.ttf',
'en.ttf',
'mono.ttf',
'emoji.ttf',
'multi-hans-300.ttf',
'multi-hans-400.ttf',
'multi-hans-700.ttf',
'multi-en-400.ttf',
'multi-en-700.ttf',
];
async function mockExec(command: string): Promise<ExecResult> {
const fake = (stdout = ''): ExecResult => ({ errno: 0, stdout, stderr: '' });
const fail = (stderr: string): ExecResult => ({ errno: 1, stdout: '', stderr });
@@ -47,6 +74,15 @@ async function mockExec(command: string): Promise<ExecResult> {
const slowFail = (stderr: string) =>
new Promise<ExecResult>((r) => setTimeout(() => r(fail(stderr)), 200));
// 字体测试: 模拟 FONT 字体已放入 webroot/fonts-test, 返回可用字体列表
// (须放在通用 find 匹配之前, 否则 listFontsDir 的无 -print0 命令会被拦截)
if (command.includes('fonts-test')) {
if (command.includes('-type f')) {
return slow(MOCK_TEST_FONTS.join('\n'));
}
return fake('');
}
// find 命令: 解析路径与类型 (d/f), 返回假目录/文件, 以 NUL 分隔 (与 -print0 一致)
if (command.startsWith('find ')) {
const m = command.match(
@@ -61,15 +97,29 @@ async function mockExec(command: string): Promise<ExecResult> {
return slow(lines.join('\0'));
}
// 字体测试: 模拟 FONT 字体已放入 webroot/fonts-test, 返回可用字体列表
if (command.includes('fonts-test')) {
return slow('hans.ttf\nhant.ttf\nen.ttf\nmono.ttf\nemoji.ttf');
// 槽位模式读写: FONTS/slot-modes.txt
if (command.includes('slot-modes.txt')) {
if (command.includes('printf')) {
const m = command.match(/printf '%s\\n' '([^']*)'/);
if (m) mockSlotModes = m[1];
return fake('');
}
return slow(mockSlotModes);
}
if (command.includes('mkdir -p')) return fake('');
if (command.includes('rm -f')) return fake('');
if (command.includes('cp -f')) return fake('');
if (command.includes('apply.sh')) {
return fake('[*] 安装: SysSans-Hans-Regular.ttf (模拟)\n[*] 全部完成, 重启后生效 (模拟)');
const lines = ['[*] 安装简体字体...', '[*] 安装: SysSans-Hans-Regular.ttf (模拟)'];
if (mockSlotModes.includes('hans=multi')) {
lines.push('[*] 安装: FontMM-Hans-300.ttf (模拟)', '[*] 安装: FontMM-Hans-700.ttf (模拟)');
}
if (mockSlotModes.includes('en=multi')) {
lines.push('[*] 检查英文多字重 400 (模拟)', '[*] 安装: FontMM-En-700.ttf (模拟)');
}
lines.push('[✓] 字体配置 XML 同步完成 (模拟)', '[*] 全部完成, 重启后生效 (模拟)');
return fake(lines.join('\n'));
}
// 字重覆写模式: cat 返回已选 '1' (裁切), echo 写入模拟成功
if (command.includes('wght-mode.txt')) {
@@ -100,19 +150,36 @@ async function mockExec(command: string): Promise<ExecResult> {
return slow('name=KernelSU MetaModule\nversion=v1.0\nauthor=KernelSU');
}
// 小米主题字体工具: 搜索/详情/下载 (模拟)
// 小米主题字体工具: 搜索 (模拟)
// 结构与真实接口一致: apiData.cards[].items[].schema.clicks[] 携带 title/link/pic,
// apiData.hasMore 标识是否还有下一页
if (command.includes('thm.market.intl.xiaomi.com')) {
// 第二页返回空, 用于验证「下一页」按钮状态
if (/[?&]page=1\b/.test(command)) {
return slow(JSON.stringify({ apiData: { hasMore: false, cards: [] } }));
}
return slow(
JSON.stringify({
apiData: {
hasMore: true,
cards: [
{
items: [
{
type: 'endlessList',
schema: {
type: 'Font',
clicks: [
{ title: 'MiSans Global (模拟)', link: 'mock-font-1' },
{ title: 'OPPO Sans (模拟)', link: 'mock-font-2' },
{
title: 'MiSans Global (模拟)',
link: 'mock-font-1',
pic: 'ThemeMarket/mock-pic-1',
},
{
title: 'OPPO Sans (模拟)',
link: 'mock-font-2',
pic: 'ThemeMarket/mock-pic-2',
},
],
},
},
@@ -159,6 +226,11 @@ async function mockExec(command: string): Promise<ExecResult> {
);
}
// 字体预热器状态检测 (模拟: 库已安装 + 检测到 Zygisk Next, 模块 ID 用真实的 zygisksu)
if (command.includes('LIB:yes') && command.includes('PROV:')) {
return slow('LIB:yes\nMAGISK:na\nPROV:zygisksu');
}
if (command.includes('ro.product.model')) return slow('Pixel 8 Pro (模拟设备)');
return slow(`(mock 未定义: ${command})`);
}
@@ -262,15 +334,19 @@ export async function getSystemInfo(): Promise<SystemInfo> {
'ro.product.cpu.abi',
];
const { errno, stdout } = await exec(
`${props.map((p) => `getprop ${p}`).join('; ')}; ls -1 '${MODULE_FONTS_DIR}'/*.ttf 2>/dev/null`,
`${props.map((p) => `getprop ${p}`).join('; ')}; find '${MODULE_FONTS_DIR}' -maxdepth 3 -type f -name '*.ttf' 2>/dev/null || true`,
);
if (errno === 0) {
const lines = stdout.split('\n');
[info.androidVersion, info.sdk, info.deviceModel, info.abi] = lines
.slice(0, 4)
.map((l) => l.trim());
// 剩余行是 FONTS/ 中实际存在的字体文件名
info.fontCount = lines.slice(4).filter((l) => l.trim() && l.endsWith('.ttf')).length;
// 剩余行是 FONTS/ 与 FONTS/multi/ 中的用户字体 (排除隐藏中转文件如 .en-subset.ttf)
info.fontCount = lines.slice(4).filter((raw) => {
const p = raw.trim();
const base = p.slice(p.lastIndexOf('/') + 1);
return p.endsWith('.ttf') && !base.startsWith('.');
}).length;
}
} catch {
// 读取失败时保持空值, 由 UI 显示占位
@@ -278,6 +354,95 @@ export async function getSystemInfo(): Promise<SystemInfo> {
return info;
}
// ---------------- 主页: 字体预热器状态 ----------------
export interface PreloaderStatus {
/** 预加载库是否随模块安装 (zygisk/arm64-v8a.so 存在) */
libInstalled: boolean;
/** 是否检测到可用的 Zygisk 环境 */
zygiskReady: boolean;
/** 检测到的 Zygisk 提供者名称 (如 "Magisk 内置" / "Zygisk Next"), 未检测到为空 */
provider: string;
}
// 模块内 Zygisk 库路径 (与 dev/lib/ndk.mjs 的产物名一致)
const ZYGISK_LIB = '/data/adb/modules/FontMM/zygisk/arm64-v8a.so';
/**
* 检测字体预热器状态。
*
* Zygisk 提供者的识别规则与 src/customize.sh 的 CHECK_ZYGISK_ENV 保持一致 ——
* 两处判断标准不同会让用户看到互相矛盾的结论 (刷入时说可用、首页说不可用)。
*/
export async function getPreloaderStatus(): Promise<PreloaderStatus> {
if (import.meta.env.DEV) {
return { libInstalled: true, zygiskReady: true, provider: 'Zygisk Next (模拟)' };
}
const status: PreloaderStatus = { libInstalled: false, zygiskReady: false, provider: '' };
try {
// 一条命令拿全部信息, 减少 root shell 往返。每项都用显式前缀标记,
// 避免靠输出内容猜测 (例如 Magisk 开关值恰好也是 "1")。
const cmd = [
// 1. 预加载库是否随模块安装
`if [ -f '${ZYGISK_LIB}' ]; then echo 'LIB:yes'; else echo 'LIB:no'; fi`,
// 2. Magisk 内置 Zygisk 开关 (值为 1 表示启用)
`if [ -f /data/adb/magisk/magisk ]; then v=$(/data/adb/magisk/magisk --sqlite "SELECT value FROM settings WHERE key='zygisk';" 2>/dev/null | tr -d '\\r'); if [ "$v" = "1" ]; then echo 'MAGISK:yes'; else echo 'MAGISK:no'; fi; else echo 'MAGISK:na'; fi`,
// 3. 独立 Zygisk 提供者模块
// 判据是提供者**独有**的文件: lib{64}/libzygisk.so (核心库) 或
// bin/zygiskd{64,32} (守护进程)。注意不能以 zygisk/ 目录判断 ——
// 那是「Zygisk 模块」(消费者) 的标志, 任何自带 zygisk/<abi>.so 的
// 模块都有 (本模块自己也有), 据此判断会把消费者误认成提供者。
// 这些文件名取自 Zygisk Next 与 ReZygisk 的实际安装布局。
`for d in /data/adb/modules/*; do [ -d "$d" ] || continue; n=$(basename "$d"); [ "$n" = "FontMM" ] && continue; [ -f "$d/disable" ] && continue; for f in "$d/lib64/libzygisk.so" "$d/lib/libzygisk.so" "$d/bin/zygiskd64" "$d/bin/zygiskd32" "$d/bin/zygiskd" "$d/lib64/libzn_loader.so" "$d/lib/libzn_loader.so"; do if [ -f "$f" ]; then echo "PROV:$n"; break; fi; done; done`,
// 4. 管理器内置 Zygisk (如 KernelSU / Sukisu 的内置实现): 无独立提供者模块,
// 仅由管理器自身提供, 以内置标记文件是否存在为准。
`if [ -f /data/adb/ksu/.builtin_zygisk ]; then echo 'KSU:yes'; else echo 'KSU:no'; fi`,
].join('; ');
const { errno, stdout } = await exec(cmd);
if (errno !== 0) return status;
const lines = stdout
.split('\n')
.map((l) => l.trim())
.filter(Boolean);
status.libInstalled = lines.includes('LIB:yes');
if (lines.includes('MAGISK:yes')) {
status.zygiskReady = true;
status.provider = 'Magisk 内置 Zygisk';
}
// 独立提供者模块 (Zygisk Next / ReZygisk 等)
const prov = lines.find((l) => l.startsWith('PROV:'));
if (prov) {
const name = prov.slice('PROV:'.length);
// 模块目录名可读性较差 (如 rezygisk), 做一次友好化映射
const friendly: Record<string, string> = {
rezygisk: 'ReZygisk',
// Zygisk Next 的模块 ID 是 zygisksu (取自其 module.prop)
zygisksu: 'Zygisk Next',
zygisknext: 'Zygisk Next',
'zygisk-next': 'Zygisk Next',
};
status.zygiskReady = true;
status.provider = friendly[name.toLowerCase()] ?? name;
}
// 管理器内置 Zygisk (KernelSU / Sukisu 等): 未识别到独立提供者时,
// 以内置标记文件的存在为准。
if (!status.zygiskReady && lines.includes('KSU:yes')) {
status.zygiskReady = true;
status.provider = '管理器内置 Zygisk';
}
} catch {
// 读取失败保持默认值 (未安装 / 不可用)
}
return status;
}
// 用 am start 在 WebUI 之外打开链接/应用 (避免在 WebView 内打开)
export async function amStart(uri: string, pkg?: string): Promise<void> {
const cmd = `am start -a android.intent.action.VIEW -d '${uri}'${pkg ? ` -p ${pkg}` : ''}`;
+3 -3
View File
@@ -1,4 +1,4 @@
import { slots } from './slots';
import { canApply } from './slots';
import { loadHome } from './home';
import { loadTestFonts } from './testFonts';
import { applyBtn, rebootBtn } from './dom';
@@ -42,8 +42,8 @@ function showView(index: number) {
views.forEach((v, i) => v.classList.toggle('active', i === target));
// 轨道滑动切换动画
viewTrack.style.transform = `translateX(${-target * 100}%)`;
// 悬浮应用按钮仅配置页显示, 且未选简体字体时不展示
applyFab.style.display = target === 1 && slots.hans.path ? '' : 'none';
// 悬浮应用按钮仅配置页显示, 且简体槽位在当前模式下已配置字体时才展示
applyFab.style.display = target === 1 && canApply() ? '' : 'none';
// 重启按钮仅主页显示 (visibility 保持顶栏布局不跳动)
if (rebootBtn) rebootBtn.style.visibility = target === 0 ? 'visible' : 'hidden';
// 同步底部导航高亮
+380 -73
View File
@@ -1,42 +1,76 @@
import { FontFilePicker } from './fontPicker';
import { fontPicker } from './fontPicker';
import { exec, shellQuote } from './ksu';
import { readFontInfo } from './fontInfo';
import { ensureFontsCopy } from './fontFiles';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
import {
ensureFontsCopy,
getEnMultiSubsetSizes,
getEnSubsetSizeText,
readSlotModes,
} from './fontFiles';
import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS, TEST_FONT_DIR, WEIGHT_LABELS } from './constants';
import { nearestWeight } from './fontsXml';
import { applyBtn } from './dom';
import type { FontSlot } from './types';
import type {
FontSlot,
MultiSlotKey,
MultiWeightEntry,
SlotKey,
SlotMode,
WeightLevel,
} from './types';
export const SLOT_KEYS = ['hans', 'hant', 'en', 'mono', 'emoji'] as const;
export type SlotKey = (typeof SLOT_KEYS)[number];
export type { SlotKey };
function createEmptyMultiWeights(): Record<WeightLevel, MultiWeightEntry> {
const out = {} as Record<WeightLevel, MultiWeightEntry>;
for (const w of MULTI_WEIGHTS) {
out[w] = { weight: w, path: null, fileName: '' };
}
return out;
}
export const slots: Record<SlotKey, FontSlot> = {
hans: {
key: 'hans',
title: '中文简体',
supportsMulti: true,
mode: 'single',
path: null,
fileName: '',
multiWeights: createEmptyMultiWeights(),
},
hant: {
key: 'hant',
title: '中文繁体',
supportsMulti: true,
mode: 'single',
path: null,
fileName: '',
multiWeights: createEmptyMultiWeights(),
},
en: {
key: 'en',
title: '英文 & 数字',
supportsMulti: true,
mode: 'single',
path: null,
fileName: '',
multiWeights: createEmptyMultiWeights(),
},
mono: {
key: 'mono',
title: '等宽字体',
supportsMulti: false,
mode: 'single',
path: null,
fileName: '',
},
emoji: {
key: 'emoji',
title: 'Emoji 表情',
supportsMulti: false,
mode: 'single',
path: null,
fileName: '',
},
@@ -47,7 +81,8 @@ const slotsEl = document.getElementById('slots')!;
const wghtModeSelect = document.getElementById('wght-mode-select') as any;
const wghtModeSub = document.getElementById('wght-mode-sub');
let pickingKey: SlotKey = 'hans';
// 记住上次选择文件的目录, 多字重连续挑选同目录字体时无需重复层层翻找
let lastPickerDir = '/storage/emulated/0';
// 应用流程进行中: renderSlots 据此禁用/启用应用按钮
export let applying = false;
@@ -55,103 +90,327 @@ export function setApplying(v: boolean): void {
applying = v;
}
const picker = new FontFilePicker((path, name) => {
const slot = slots[pickingKey];
slot.path = path;
slot.fileName = name;
renderSlots();
void refreshSlotInfo(slot);
});
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function notifyFontsChanged(): void {
document.dispatchEvent(new CustomEvent('fonts-changed'));
}
function rememberDir(filePath: string): void {
const idx = filePath.lastIndexOf('/');
if (idx > 0) lastPickerDir = filePath.slice(0, idx);
}
/** 返回某个多字重槽位已选的升序字重列表 */
export function getSelectedMultiWeights(slot: FontSlot): WeightLevel[] {
if (!slot.multiWeights) return [];
return MULTI_WEIGHTS.filter((w) => Boolean(slot.multiWeights?.[w]?.path));
}
/** 判断槽位在当前激活模式下是否已配置字体 */
export function isSlotConfigured(slot: FontSlot): boolean {
if (slot.mode === 'multi') return getSelectedMultiWeights(slot).length > 0;
return Boolean(slot.path);
}
/** 是否满足应用前提 (中文简体必须在当前模式下至少配好 1 份字体) */
export function canApply(): boolean {
return isSlotConfigured(slots.hans);
}
function pickFontFor(key: SlotKey): void {
fontPicker.show(lastPickerDir, (path, name) => {
rememberDir(path);
const slot = slots[key];
slot.path = path;
slot.fileName = name;
notifyFontsChanged();
renderSlots();
void refreshSlotInfo(slot);
});
}
function pickMultiFontFor(key: MultiSlotKey, weight: WeightLevel): void {
fontPicker.show(lastPickerDir, (path, name) => {
rememberDir(path);
const slot = slots[key];
if (!slot.multiWeights) slot.multiWeights = createEmptyMultiWeights();
const entry = slot.multiWeights[weight];
entry.path = path;
entry.fileName = name;
entry.sizeText = undefined;
entry.subsetSizeText = undefined;
notifyFontsChanged();
renderSlots();
void refreshMultiWeightInfo(slot, weight);
});
}
function hansFallbackSummary(): string {
if (slots.hans.mode === 'multi') {
const count = getSelectedMultiWeights(slots.hans).length;
return count > 0 ? `中文简体(多字重 ${count} 档)` : '中文简体';
}
return slots.hans.fileName || '中文简体';
}
// 未选择时的占位文案: 回退可视化 (WYSIWYG)
function slotPlaceholder(slot: FontSlot): string {
if (slot.path) return slot.fileName;
if (slot.key === 'hans') return '未选择字体文件';
if (slots.hans.path) {
if (isSlotConfigured(slots.hans)) {
if (slot.key === 'mono') return '未选择,保持系统等宽字体';
if (slot.key === 'emoji') return '未选择,保持系统 Emoji';
return `默认使用:${slots.hans.fileName}`;
return `默认使用:${hansFallbackSummary()}`;
}
return '未选择字体文件';
}
// 根据是否有可变字体决定是否禁用字重覆写 (emoji/mono 不计入)
// 根据单字体模式是否存在可变字体决定是否启用字重覆写 (多字重槽位 / mono / emoji 不计入)
export function updateWghtModeDisabled(): void {
const hasVar = ['hans', 'hant', 'en'].some((k) => slots[k as 'hans']?.isVariable);
const hasVar = (['hans', 'hant', 'en'] as const).some(
(k) => slots[k].mode === 'single' && Boolean(slots[k].path) && Boolean(slots[k].isVariable),
);
const hasAnyMulti = (['hans', 'hant', 'en'] as const).some((k) => slots[k].mode === 'multi');
if (wghtModeSelect) wghtModeSelect.disabled = !hasVar;
if (wghtModeSub) {
wghtModeSub.textContent = hasVar
? '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置'
: '当前未选择可变字体 (中文/繁体/英文), 此功能不可用';
if (hasVar) {
wghtModeSub.textContent = hasAnyMulti
? '单字体模式下的可变字体 wght 范围与实际字重等级不符时, 覆写对应家族配置 (多字重槽位不受影响)'
: '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置';
} else if (hasAnyMulti) {
wghtModeSub.textContent = '多字重模式下各档位使用独立字体文件, 字重覆写已自动禁用';
} else {
wghtModeSub.textContent = '当前未选择可变字体 (中文/繁体/英文), 此功能不可用';
}
}
}
function renderModeToggle(slot: FontSlot): string {
if (!slot.supportsMulti) {
return `<md-icon class="slot-arrow">chevron_right</md-icon>`;
}
const singleActive = slot.mode === 'single' ? 'active' : '';
const multiActive = slot.mode === 'multi' ? 'active' : '';
return `
<div class="slot-mode-toggle" role="group" aria-label="${slot.title}模式切换">
<button type="button" class="slot-mode-btn ${singleActive}" data-key="${slot.key}" data-mode="single">可变字体</button>
<button type="button" class="slot-mode-btn ${multiActive}" data-key="${slot.key}" data-mode="multi">多字重</button>
</div>
`;
}
function renderSingleBody(slot: FontSlot, required: boolean): string {
const nameText = required ? '未选择字体,此项为必选项' : slotPlaceholder(slot);
const ext = slot.path ? (slot.path.split('.').pop() ?? '').toUpperCase() : '';
const sizeText = slot.subsetSizeText
? `${slot.sizeText || '…'} → ${slot.subsetSizeText}`
: slot.sizeText || '…';
const subsetBadge = slot.subsetSizeText
? `<span class="slot-meta-badge slot-meta-badge--subset" title="英文字体自带中文字形, 安装时已裁切为纯拉丁子集; 装入系统的是这个子集">已子集化</span>`
: '';
return `
<div class="slot-file">
${
slot.path
? `<md-icon-button class="slot-clear" data-key="${slot.key}" aria-label="取消选择">
<md-icon>close</md-icon>
</md-icon-button>`
: ''
}
<div class="slot-file-text">
<div class="slot-name ${!slot.path ? 'placeholder' : ''} ${required ? 'required' : ''}">${escapeHtml(nameText)}</div>
${
slot.path
? `<div class="slot-meta"><span class="slot-meta-badge">${escapeHtml(sizeText)}</span>${ext ? `<span class="slot-meta-badge">${escapeHtml(ext)}</span>` : ''}${subsetBadge}${slot.isVariable ? `<span class="slot-meta-badge slot-meta-badge--variable">可变字体${slot.wghtRange ? ` ${escapeHtml(slot.wghtRange)}` : ''}</span>` : ''}</div>`
: ''
}
</div>
${slot.supportsMulti ? `<md-icon class="slot-arrow slot-arrow--inline">chevron_right</md-icon>` : ''}
</div>
`;
}
function renderMultiBody(slot: FontSlot, required: boolean): string {
const selected = getSelectedMultiWeights(slot);
let bannerText = '';
let bannerCls = 'slot-multi-summary';
if (selected.length === 0) {
if (slot.key === 'hans') {
bannerText = required
? '请至少选择一个字重的字体文件(此项为必选项)'
: '请点击下方档位选择字体,未选档位将自动匹配最接近字重';
if (required) bannerCls += ' required';
} else if (isSlotConfigured(slots.hans)) {
bannerText = `未选任何字重,默认回退使用:${hansFallbackSummary()}`;
} else {
bannerText = '未选任何字重(可选),点击下方档位即可配置';
}
} else {
bannerText = `已选 ${selected.length}/9 档 · 缺失档位自动就近匹配`;
}
const rows = MULTI_WEIGHTS.map((w) => {
const entry = slot.multiWeights?.[w] ?? { weight: w, path: null, fileName: '' };
const label = WEIGHT_LABELS[w] ?? '';
const hasFile = Boolean(entry.path);
let text = '';
if (hasFile) {
text = entry.fileName;
} else if (selected.length > 0) {
text = `未选(使用 ${nearestWeight(selected, w)})`;
} else if (slot.key !== 'hans' && isSlotConfigured(slots.hans)) {
text = '回退中文简体';
} else {
text = '点击选择字体';
}
const ext = entry.path ? (entry.path.split('.').pop() ?? '').toUpperCase() : '';
const sizeText = entry.subsetSizeText
? `${entry.sizeText || '…'} → ${entry.subsetSizeText}`
: entry.sizeText || '…';
const subsetBadge = entry.subsetSizeText
? `<span class="slot-meta-badge slot-meta-badge--subset" title="英文字体自带中文字形, 安装时已裁切为纯拉丁子集">已子集化</span>`
: '';
return `
<div class="slot-weight-row ${hasFile ? 'selected' : ''}" data-key="${slot.key}" data-weight="${w}">
<div class="slot-weight-tag">
<span class="slot-weight-num">${w}</span>
<span class="slot-weight-label">${label}</span>
</div>
<div class="slot-weight-info">
<div class="slot-weight-name ${hasFile ? '' : 'placeholder'}">${escapeHtml(text)}</div>
${
hasFile
? `<div class="slot-meta"><span class="slot-meta-badge">${escapeHtml(sizeText)}</span>${ext ? `<span class="slot-meta-badge">${escapeHtml(ext)}</span>` : ''}${subsetBadge}</div>`
: ''
}
</div>
${
hasFile
? `<md-icon-button class="slot-weight-clear" data-key="${slot.key}" data-weight="${w}" aria-label="清除 ${w} 字重">
<md-icon>close</md-icon>
</md-icon-button>`
: `<md-icon class="slot-weight-arrow">chevron_right</md-icon>`
}
</div>
`;
}).join('');
return `
<div class="${bannerCls}">${escapeHtml(bannerText)}</div>
<div class="slot-weight-list">${rows}</div>
`;
}
export function renderSlots() {
const anyOtherConfigured = Object.values(slots).some(
(s) => s.key !== 'hans' && isSlotConfigured(s),
);
slotsEl.innerHTML = Object.values(slots)
.map((slot) => {
// 选了其他槽位但未选简体时, 简体卡片提示"必选"
const required =
slot.key === 'hans' &&
!slot.path &&
Object.values(slots).some((s) => s.key !== 'hans' && s.path);
const nameText = required ? '未选择字体,此项为必选项' : slotPlaceholder(slot);
// 扩展名大写 (TTF/OTF...), 从源文件路径动态提取, 不硬编码
const ext = slot.path ? (slot.path.split('.').pop() ?? '').toUpperCase() : '';
const configured = isSlotConfigured(slot);
const required = slot.key === 'hans' && !configured && anyOtherConfigured;
const body =
slot.mode === 'multi' && slot.supportsMulti
? renderMultiBody(slot, required)
: renderSingleBody(slot, required);
return `
<md-filled-card class="slot-card ${slot.key === 'hans' ? 'slot-hans' : ''} ${slot.path ? 'selected' : ''}" data-key="${slot.key}">
<md-filled-card class="slot-card ${slot.key === 'hans' ? 'slot-hans' : ''} ${slot.mode === 'multi' ? 'is-multi' : ''} ${configured ? 'selected' : ''}" data-key="${slot.key}" data-mode="${slot.mode}">
<div class="slot-header">
<div class="slot-title-group">
<span class="slot-title">${slot.title}</span>
</div>
<md-icon class="slot-arrow">chevron_right</md-icon>
</div>
<div class="slot-file">
${
slot.path
? `<md-icon-button class="slot-clear" data-key="${slot.key}" aria-label="取消选择">
<md-icon>close</md-icon>
</md-icon-button>`
: ''
}
<div class="slot-file-text">
<div class="slot-name ${!slot.path ? 'placeholder' : ''} ${required ? 'required' : ''}">${nameText}</div>
${
slot.path
? `<div class="slot-meta"><span class="slot-meta-badge">${slot.sizeText || '…'}</span>${ext ? `<span class="slot-meta-badge">${ext}</span>` : ''}${slot.isVariable ? `<span class="slot-meta-badge slot-meta-badge--variable">可变字体${slot.wghtRange ? ` ${slot.wghtRange}` : ''}</span>` : ''}</div>`
: ''
}
</div>
${renderModeToggle(slot)}
</div>
${body}
</md-filled-card>
`;
})
.join('');
// 绑定事件: 整卡点击选择字体
slotsEl.querySelectorAll<HTMLElement>('.slot-card').forEach((card) => {
card.addEventListener('click', () => {
pickingKey = card.dataset.key as SlotKey;
picker.show();
// 绑定事件: 模式切换按钮 (可变字体 / 多字重)
slotsEl.querySelectorAll<HTMLButtonElement>('.slot-mode-btn').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const key = btn.dataset.key as MultiSlotKey;
const mode = btn.dataset.mode as SlotMode;
const slot = slots[key];
if (!slot || slot.mode === mode) return;
slot.mode = mode;
notifyFontsChanged();
renderSlots();
});
});
// 绑定事件: 单字体整卡点击选择
slotsEl.querySelectorAll<HTMLElement>('.slot-card').forEach((card) => {
card.addEventListener('click', () => {
if (card.dataset.mode === 'multi') return;
pickFontFor(card.dataset.key as SlotKey);
});
});
// 绑定事件: 单字体清除
slotsEl.querySelectorAll<HTMLElement>('.slot-clear').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation(); // 阻止冒泡触发卡片选择
e.stopPropagation();
const slot = slots[btn.dataset.key as SlotKey];
slot.path = null;
slot.fileName = '';
slot.sizeText = undefined;
slot.isVariable = false;
slot.wghtRange = undefined;
slot.subsetSizeText = undefined;
void exec(`rm -f ${shellQuote(`${TEST_FONT_DIR}/${slot.key}.ttf`)}`);
notifyFontsChanged();
renderSlots();
});
});
// 绑定事件: 多字重行点击选择
slotsEl.querySelectorAll<HTMLElement>('.slot-weight-row').forEach((row) => {
row.addEventListener('click', (e) => {
e.stopPropagation();
const key = row.dataset.key as MultiSlotKey;
const weight = Number(row.dataset.weight) as WeightLevel;
pickMultiFontFor(key, weight);
});
});
// 绑定事件: 多字重单档清除
slotsEl.querySelectorAll<HTMLElement>('.slot-weight-clear').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const key = btn.dataset.key as MultiSlotKey;
const weight = Number(btn.dataset.weight) as WeightLevel;
const entry = slots[key].multiWeights?.[weight];
if (!entry) return;
entry.path = null;
entry.fileName = '';
entry.sizeText = undefined;
entry.subsetSizeText = undefined;
void exec(`rm -f ${shellQuote(`${TEST_FONT_DIR}/multi-${key}-${weight}.ttf`)}`);
notifyFontsChanged();
renderSlots();
});
});
if (applyBtn) {
// 未选择简体字体时直接隐藏按钮 (不做半透明禁用); 应用过程中禁用
applyBtn.style.display = !slots.hans.path ? 'none' : '';
const onConfig = document.getElementById('config-view')?.classList.contains('active') ?? false;
applyBtn.style.display = onConfig && canApply() ? '' : 'none';
applyBtn.disabled = applying;
}
updateWghtModeDisabled();
// 通知其他模块 (如字重映射预览) 槽位已变化
document.dispatchEvent(new CustomEvent('slots-rendered'));
}
@@ -160,11 +419,12 @@ export async function copyFont(src: string, dest: string) {
if (errno !== 0) throw new Error(`复制失败: ${stderr}`);
}
// 选择用于覆写的 wght 范围: 从 hans/hant/en 收集 (emoji/mono 除外), 取跨度最小者; 无可变返回 null
// 选择用于覆写的 wght 范围: 仅从当前处于单字体模式的 hans/hant/en 收集, 取跨度最小者; 无可变返回 null
export function pickWghtRange(): { min: number; max: number } | null {
let best: { min: number; max: number } | null = null;
let bestSpan = Infinity;
for (const key of ['hans', 'hant', 'en'] as const) {
if (slots[key].mode !== 'single' || !slots[key].path) continue;
const r = slots[key]?.wghtRange;
if (!r) continue;
const m = r.match(/^(\d+)-(\d+)$/);
@@ -180,15 +440,15 @@ export function pickWghtRange(): { min: number; max: number } | null {
return best;
}
// 选择新字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小
// 选择单字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小
async function refreshSlotInfo(slot: FontSlot) {
if (!slot.path) return;
if (slot.key === 'en') slot.subsetSizeText = undefined;
try {
await exec(`cp -f ${shellQuote(slot.path)} ${shellQuote(`${TEST_FONT_DIR}/${slot.key}.ttf`)}`);
const info = await readFontInfo(`${slot.key}.ttf`);
if (info.name) slot.fileName = info.name;
if (info.sizeText) slot.sizeText = info.sizeText;
// 无条件同步: 防止换字体后旧的可变标记残留
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
renderSlots();
@@ -197,20 +457,67 @@ async function refreshSlotInfo(slot: FontSlot) {
}
}
// 打开 WebUI 时: 复制 FONT/ 到 fonts-test, 读取已有字体的名称/大小填充卡片
async function loadExistingFonts() {
const available = await ensureFontsCopy();
for (const key of SLOT_KEYS) {
const file = `${key}.ttf`;
if (!available.includes(file)) continue;
const slot = slots[key];
const info = await readFontInfo(file);
slot.path = `${FONTS_DIR}/${file}`;
slot.fileName = info.name ?? file;
if (info.sizeText) slot.sizeText = info.sizeText;
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
// 选择多字重后: 复制到 fonts-test 供解析与测试预览, 更新该档位名称/大小
async function refreshMultiWeightInfo(slot: FontSlot, weight: WeightLevel) {
const entry = slot.multiWeights?.[weight];
if (!entry?.path) return;
if (slot.key === 'en') entry.subsetSizeText = undefined;
const testFile = `multi-${slot.key}-${weight}.ttf`;
try {
await exec(
`mkdir -p ${shellQuote(TEST_FONT_DIR)} && cp -f ${shellQuote(entry.path)} ${shellQuote(`${TEST_FONT_DIR}/${testFile}`)}`,
);
const info = await readFontInfo(testFile);
if (info.name) entry.fileName = info.name;
if (info.sizeText) entry.sizeText = info.sizeText;
renderSlots();
} catch {
// 忽略解析失败
}
}
// 刷新英文槽位 (单字体及多字重各档) 的子集信息, 不负责重绘
export async function refreshEnSubset(): Promise<void> {
slots.en.subsetSizeText = (await getEnSubsetSizeText()) ?? undefined;
const enWeights = getSelectedMultiWeights(slots.en);
const subMap = await getEnMultiSubsetSizes(enWeights);
for (const w of MULTI_WEIGHTS) {
const entry = slots.en.multiWeights?.[w];
if (entry) entry.subsetSizeText = subMap[w];
}
}
// 打开 WebUI 时: 复制 FONTS/ 到 fonts-test, 读取已有字体与模式配置填充卡片
async function loadExistingFonts() {
const [available, modes] = await Promise.all([ensureFontsCopy(), readSlotModes()]);
for (const key of SLOT_KEYS) {
const slot = slots[key];
if (key === 'hans' || key === 'hant' || key === 'en') {
slot.mode = modes[key];
}
const file = `${key}.ttf`;
if (available.includes(file)) {
const info = await readFontInfo(file);
slot.path = `${FONTS_DIR}/${file}`;
slot.fileName = info.name ?? file;
if (info.sizeText) slot.sizeText = info.sizeText;
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
}
if (slot.supportsMulti && slot.multiWeights) {
for (const w of MULTI_WEIGHTS) {
const mf = `multi-${key}-${w}.ttf`;
if (!available.includes(mf)) continue;
const info = await readFontInfo(mf);
const entry = slot.multiWeights[w];
entry.path = `${MULTI_DIR}/${key}/${w}.ttf`;
entry.fileName = info.name ?? `${w}.ttf`;
if (info.sizeText) entry.sizeText = info.sizeText;
}
}
}
await refreshEnSubset();
notifyFontsChanged();
renderSlots();
}
+180 -3
View File
@@ -125,14 +125,18 @@ md-filled-card.slot-card {
--md-filled-card-container-color: var(--md-sys-color-surface-container-low);
--md-filled-card-container-shape: var(--md-shape-corner-large);
// 整卡可点击选择 (多字重卡片由内部各字重行触发)
cursor: pointer;
&.is-multi {
cursor: default;
}
// 已选择状态: tonal 高亮 (primary-container), M3 标准选中反馈
&.selected {
--md-filled-card-container-color: var(--md-sys-color-primary-container);
}
// 整卡可点击选择
cursor: pointer;
.slot-header {
display: flex;
justify-content: space-between;
@@ -154,6 +158,37 @@ md-filled-card.slot-card {
color: var(--md-sys-color-on-surface);
}
// 可变字体 / 多字重 分段切换胶囊
.slot-mode-toggle {
display: inline-flex;
align-items: center;
flex-shrink: 0;
padding: 2px;
border-radius: var(--md-shape-corner-full);
background-color: var(--md-sys-color-surface-container-highest);
gap: 2px;
.slot-mode-btn {
border: none;
background: transparent;
padding: 4px 10px;
border-radius: var(--md-shape-corner-full);
font-family: inherit;
font-size: var(--md-sys-typescale-label-small-size);
font-weight: 500;
color: var(--md-sys-color-on-surface-variant);
cursor: pointer;
transition:
background-color var(--md-duration-standard) var(--md-easing-standard),
color var(--md-duration-standard) var(--md-easing-standard);
&.active {
background-color: var(--md-sys-color-primary);
color: var(--md-sys-color-on-primary);
}
}
}
// 右侧导航箭头
.slot-arrow {
flex-shrink: 0;
@@ -169,6 +204,12 @@ md-filled-card.slot-card {
gap: 4px;
min-width: 0;
.slot-arrow--inline {
flex-shrink: 0;
color: var(--md-sys-color-on-surface-variant);
font-size: 22px;
}
// 清除按钮位于字体名称左侧
.slot-clear {
flex-shrink: 0;
@@ -222,6 +263,129 @@ md-filled-card.slot-card {
background-color: var(--md-sys-color-primary);
color: var(--md-sys-color-on-primary);
}
// 子集化徽标: 与可变字体徽标同级的实色提示 (仅英文字体被裁切时出现)
&.slot-meta-badge--subset {
background-color: var(--md-sys-color-tertiary);
color: var(--md-sys-color-on-tertiary);
}
}
}
}
}
// 多字重提示与 9 档列表
.slot-multi-summary {
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
margin-bottom: 10px;
&.required {
font-weight: 600;
color: var(--md-sys-color-tertiary);
}
}
.slot-weight-list {
display: flex;
flex-direction: column;
border-top: 1px solid var(--md-sys-color-outline-variant);
.slot-weight-row {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 4px;
min-height: 44px;
cursor: pointer;
border-bottom: 1px solid
color-mix(in srgb, var(--md-sys-color-outline-variant) 55%, transparent);
&:last-child {
border-bottom: none;
padding-bottom: 2px;
}
&:active {
opacity: 0.72;
}
.slot-weight-tag {
display: flex;
flex-direction: column;
width: 44px;
flex-shrink: 0;
.slot-weight-num {
font-size: var(--md-sys-typescale-label-large-size);
font-weight: 600;
font-variant-numeric: tabular-nums;
color: var(--md-sys-color-primary);
line-height: 1.1;
}
.slot-weight-label {
font-size: 11px;
color: var(--md-sys-color-on-surface-variant);
line-height: 1.2;
}
}
.slot-weight-info {
flex: 1;
min-width: 0;
.slot-weight-name {
font-size: var(--md-sys-typescale-body-medium-size);
font-weight: 500;
color: var(--md-sys-color-on-surface);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
&.placeholder {
font-weight: 400;
color: var(--md-sys-color-on-surface-variant);
opacity: 0.75;
}
}
.slot-meta {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 2px;
.slot-meta-badge {
display: inline-block;
padding: 1px 8px;
border-radius: var(--md-shape-corner-full);
background-color: var(--md-sys-color-surface-container-highest);
font-size: 11px;
color: var(--md-sys-color-on-surface-variant);
&.slot-meta-badge--subset {
background-color: var(--md-sys-color-tertiary);
color: var(--md-sys-color-on-tertiary);
}
}
}
}
.slot-weight-arrow {
flex-shrink: 0;
font-size: 20px;
color: var(--md-sys-color-on-surface-variant);
}
.slot-weight-clear {
flex-shrink: 0;
width: 32px;
height: 32px;
--md-icon-button-state-layer-size: 32px;
md-icon {
font-size: 18px;
}
}
}
@@ -522,8 +686,21 @@ md-dialog {
line-height: var(--md-sys-typescale-title-medium-line-height);
color: var(--md-sys-color-on-surface);
word-break: break-all;
// 异常状态 (如预热器未生效) 用错误色, 与测试页的提示语义一致
&.is-error {
color: var(--md-sys-color-error);
}
}
}
// 未就绪时的补充说明: 解释原因与处理办法, 比单纯标红更有用
.home-preload-note {
margin-top: 6px;
font-size: var(--md-sys-typescale-body-small-size);
line-height: 1.4;
color: var(--md-sys-color-outline);
}
}
// 测试状态提示 (info 卡片)
+110 -49
View File
@@ -1,82 +1,141 @@
import { slots } from './slots';
import { getSelectedMultiWeights, isSlotConfigured, slots } from './slots';
import { listFontsDir } from './fontFiles';
import type { FontSlot } from './types';
import { MULTI_WEIGHTS } from './constants';
import { nearestWeight } from './fontsXml';
import type { FontSlot, MultiSlotKey, WeightLevel } from './types';
const testStatusText = document.getElementById('test-status-text')!;
const testContent = document.getElementById('test-content')!;
type TestSlot = 'hans' | 'hant' | 'en';
type TestSlot = MultiSlotKey;
const TEST_FONTS: { slot: TestSlot; file: string; family: string }[] = [
{ slot: 'hans', file: 'hans.ttf', family: 'FontMM-Hans' },
{ slot: 'hant', file: 'hant.ttf', family: 'FontMM-Hant' },
{ slot: 'en', file: 'en.ttf', family: 'FontMM-En' },
];
const TEST_FAMILIES: Record<TestSlot, string> = {
hans: 'FontMM-Hans',
hant: 'FontMM-Hant',
en: 'FontMM-En',
};
async function registerFont(family: string, file: string): Promise<boolean> {
// 记录已注册进 document.fonts 的 FontFace, 刷新时先清理避免旧字重描述符残留
const registeredFaces: FontFace[] = [];
function clearRegisteredFaces(): void {
for (const face of registeredFaces) {
document.fonts.delete(face);
}
registeredFaces.length = 0;
}
async function registerFont(
family: string,
file: string,
weightRange = '100 900',
): Promise<boolean> {
try {
// 声明完整字重范围: 否则 FontFace 默认只覆盖 weight 400,
// CSS font-weight 100-900 将无法匹配到该字体 (真机表现: 100-400 无变化)
const font = new FontFace(family, `url('fonts-test/${file}')`, { weight: '100 900' });
const font = new FontFace(family, `url('fonts-test/${file}')`, { weight: weightRange });
await font.load();
document.fonts.add(font);
registeredFaces.push(font);
return true;
} catch {
return false;
}
}
// 测试页字体只加载一次 (进入时), 应用新字体后重置, 避免每次进入重复加载
// 为多字重槽位按连续权重区间注册 FontFace (相同目标字体文件合并为一个区间, 只加载一次)
async function registerMultiSlotFonts(
family: string,
slotKey: TestSlot,
availWeights: WeightLevel[],
availableFiles: string[],
): Promise<boolean> {
const usable = availWeights.filter((w) => availableFiles.includes(`multi-${slotKey}-${w}.ttf`));
if (usable.length === 0) return false;
// 按最接近匹配将 100..900 归并到连续字重区间
const segments: { sourceW: WeightLevel; minW: number; maxW: number }[] = [];
for (const w of MULTI_WEIGHTS) {
const target = nearestWeight(usable, w) as WeightLevel;
const prev = segments[segments.length - 1];
if (prev && prev.sourceW === target) {
prev.maxW = w;
} else {
segments.push({ sourceW: target, minW: w, maxW: w });
}
}
let anyLoaded = false;
for (const seg of segments) {
const descriptor = seg.minW === seg.maxW ? String(seg.minW) : `${seg.minW} ${seg.maxW}`;
const ok = await registerFont(family, `multi-${slotKey}-${seg.sourceW}.ttf`, descriptor);
if (ok) anyLoaded = true;
}
return anyLoaded;
}
// 测试页字体只加载一次 (进入时), 槽位或模式变化后重置
let testLoaded = false;
// 字体已变化: 下次进入测试页时重新加载
export function invalidateTestFonts(): void {
testLoaded = false;
}
document.addEventListener('fonts-changed', () => invalidateTestFonts());
function describeSlot(key: TestSlot): string {
const slot = slots[key];
if (slot.mode === 'multi') {
const ws = getSelectedMultiWeights(slot);
if (ws.length === 0) return '';
const regName = slot.multiWeights?.[nearestWeight(ws, 400) as WeightLevel]?.fileName ?? '';
return regName ? `多字重 ${ws.length} 档 · ${regName}` : `多字重 ${ws.length} 档`;
}
return slot.path ? slot.fileName : '';
}
async function loadSlotFamily(key: TestSlot, availableFiles: string[]): Promise<boolean> {
const slot = slots[key];
const family = TEST_FAMILIES[key];
if (slot.mode === 'multi') {
const ws = getSelectedMultiWeights(slot);
return ws.length > 0 ? registerMultiSlotFonts(family, key, ws, availableFiles) : false;
}
const file = `${key}.ttf`;
return slot.path && availableFiles.includes(file) ? registerFont(family, file) : false;
}
export async function loadTestFonts(): Promise<void> {
if (testLoaded) return;
testContent.hidden = true;
testStatusText.textContent = '正在加载字体...';
// 字体已在 WebUI 打开时复制到 fonts-test, 此处直接读取
clearRegisteredFaces();
const available = await listFontsDir();
// 注册字体, 记录每个槽位是否加载成功
const loaded = new Map<TestSlot, boolean>();
for (const tf of TEST_FONTS) {
loaded.set(
tf.slot,
available.includes(tf.file) ? await registerFont(tf.family, tf.file) : false,
);
for (const key of ['hans', 'hant', 'en'] as const) {
loaded.set(key, await loadSlotFamily(key, available));
}
// fallback 逻辑: hant/en 缺失回退 hans
const hans = loaded.get('hans') ? 'FontMM-Hans' : 'sans-serif';
const hant = loaded.get('hant') ? 'FontMM-Hant' : hans;
const en = loaded.get('en') ? 'FontMM-En' : hans;
// fallback 逻辑: hant/en 当前模式未配置时回退 hans
const hans = loaded.get('hans') ? TEST_FAMILIES.hans : 'sans-serif';
const hant = loaded.get('hant') ? TEST_FAMILIES.hant : hans;
const en = loaded.get('en') ? TEST_FAMILIES.en : hans;
// 显示字体名称 (解析出的 family name; 未解析到时为文件名)
const slotLabel = (key: TestSlot): string => slots[key].fileName;
const hasFont = (key: TestSlot): boolean => available.includes(`${key}.ttf`);
const hansLabel = hasFont('hans') ? slotLabel('hans') : null;
const hansLabel = isSlotConfigured(slots.hans) ? describeSlot('hans') : null;
const hantLabel = isSlotConfigured(slots.hant) ? describeSlot('hant') : null;
const enLabel = isSlotConfigured(slots.en) ? describeSlot('en') : null;
const setTag = (id: string, text: string) => {
const el = document.getElementById(id);
if (el) el.textContent = text;
};
setTag('hans-tag', hasFont('hans') ? slotLabel('hans') : '未设置, 使用系统字体');
setTag(
'hant-tag',
hasFont('hant') ? slotLabel('hant') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体',
);
setTag(
'en-tag',
hasFont('en') ? slotLabel('en') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体',
);
setTag('hans-tag', hansLabel || '未设置, 使用系统字体');
setTag('hant-tag', hantLabel || (hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体'));
setTag('en-tag', enLabel || (hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体'));
setTag('weight-tag', `使用 ${hansLabel ?? '系统字体'}`);
// 可变字体提示: 若所选字体为可变字体, 显示 wght 轴范围
const varSlot: FontSlot | null = slots.hans.isVariable ? slots.hans : null;
const varSlot: FontSlot | null =
slots.hans.mode === 'single' && slots.hans.isVariable ? slots.hans : null;
setTag(
'var-tag',
`使用 ${hansLabel ?? '系统字体'}${varSlot?.wghtRange ? ` (可变字体 wght ${varSlot.wghtRange})` : ''}`,
@@ -89,8 +148,7 @@ export async function loadTestFonts(): Promise<void> {
setFamily('test-hans', hans, 'sans-serif');
setFamily('test-hant', hant, `'${hans}', sans-serif`);
setFamily('test-en', en, `'${hans}', sans-serif`);
// 字重 / 可变字体测试: 用完整 fallback 链渲染 (Hans → Hant → En 按用户选择顺序,
// 浏览器逐字形回退, 所见即所得地体现系统真实 fallback)
const fallbackChain = [...new Set([hans, hant, en])].map((f) => `'${f}'`).join(', ');
const fullChain = `${fallbackChain}, sans-serif`;
document.querySelectorAll<HTMLElement>('.test-w-text').forEach((el) => {
@@ -98,12 +156,12 @@ export async function loadTestFonts(): Promise<void> {
});
const vp = document.getElementById('test-var-preview');
if (vp) vp.style.fontFamily = fullChain;
applyWght(400); // 与滑条初始值保持一致
applyWght(400);
testStatusText.textContent =
available.length === 0
? '未找到已设置的字体 (FONTS 为空), 当前使用系统字体预览'
: '字体已加载, 下方为预览效果 (按 fallback 逻辑)';
const hasAny = available.length > 0 && isSlotConfigured(slots.hans);
testStatusText.textContent = hasAny
? '字体已加载, 下方为预览效果 (按实际模式与 fallback 逻辑)'
: '未找到已设置的字体 (FONTS 为空), 当前使用系统字体预览';
testContent.hidden = false;
testLoaded = true;
}
@@ -128,7 +186,9 @@ const varPreview = document.getElementById('test-var-preview') as HTMLElement |
let wghtTimer: number | undefined;
function applyWght(weight: number) {
if (varPreview) varPreview.style.fontVariationSettings = `'wght' ${weight}`;
if (!varPreview) return;
varPreview.style.fontVariationSettings = `'wght' ${weight}`;
varPreview.style.fontWeight = String(Math.round(weight / 100) * 100);
}
function updateVarPreview(weight: number) {
@@ -174,7 +234,8 @@ document.querySelectorAll<HTMLElement>('.test-card-editable').forEach((card) =>
const target = document.getElementById(targetId);
if (!target) return;
editTargetId = targetId;
editInput.value = target.textContent ?? '';
// trim: textContent 带着标签间的缩进与换行, 原样填入会在输入框里显示成空行 (issue #16)
editInput.value = (target.textContent ?? '').trim();
if (editDialog) editDialog.open = true;
});
});
+58 -18
View File
@@ -1,6 +1,6 @@
import '@material/web/button/filled-button.js';
import { exec, shellQuote } from './ksu';
import { FontFilePicker } from './fontPicker';
import { fontPicker } from './fontPicker';
import { renderPreview, type PreviewData } from './previewRenderer';
// ---------------- 工具框架 ----------------
@@ -104,6 +104,36 @@ const SEARCH_API = 'https://thm.market.intl.xiaomi.com/thm/search/npage?category
// 格式: thumbnail/{format}/{尺寸参数}/{pic}, 如 thumbnail/webp/w120q70/ThemeMarket/xxx
const PIC_BASE = 'https://t17.market.mi-img.com/thumbnail/webp/w120q70/';
/** 搜索结果条目 (来自 apiData.cards[].items[].schema.clicks[]) */
interface MiFontItem {
title: string;
/** 主题 ID, 详情 API 用它换取下载地址 */
link: string;
/** 相对图片路径 */
pic: string;
}
/**
* 解析搜索响应。
* 真实结构: apiData.cards[].items[].schema.clicks[] —— 字段 title/link/pic;
* 找不到结果时返回 noResultMessage 类型的 item (clicks 为空)。
*/
function parseSearchResponse(data: any): MiFontItem[] {
const cards: any[] = data?.apiData?.cards ?? [];
const items: MiFontItem[] = [];
for (const card of cards) {
for (const item of card?.items ?? []) {
for (const click of item?.schema?.clicks ?? []) {
const title = String(click?.title ?? '').trim();
const link = String(click?.link ?? '').trim();
if (!title || !link) continue;
items.push({ title, link, pic: String(click?.pic ?? '') });
}
}
}
return items;
}
export const MiFontToolDef: ToolDef = {
id: 'mi-font',
title: '下载国际版小米主题字体',
@@ -141,36 +171,42 @@ export const MiFontToolDef: ToolDef = {
const escapeHtml = (s: string): string =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const renderItems = (items: any[]): void => {
const renderItems = (items: MiFontItem[]): void => {
resultEl.textContent = '';
for (const it of items) {
const card = document.createElement('div');
card.className = 'mi-item';
const pic = it.pic ? `${PIC_BASE}${it.pic}` : '';
const time = it.time ? new Date(it.time).toLocaleDateString() : '';
card.innerHTML = `
<div class="mi-item-info">
<div class="mi-item-title"></div>
<div class="mi-item-sub">${escapeHtml(it.certified ? '官方认证 · ' : '')}${time}</div>
</div>
${pic ? `<img class="mi-item-pic" src="${escapeHtml(pic)}" alt="" loading="lazy" onerror="this.remove()">` : ''}
<md-icon-button class="mi-item-dl" aria-label="下载">
<md-icon>download</md-icon>
</md-icon-button>
`;
card.querySelector('.mi-item-title')!.textContent = it.title ?? '';
card.querySelector('.mi-item-title')!.textContent = it.title;
// 下载所需的主题 ID 存在按钮上, 供点击时读取 (之前未写入导致下载始终失败)
const dlBtn = card.querySelector('.mi-item-dl') as HTMLElement;
dlBtn.dataset.link = it.link;
dlBtn.dataset.title = it.title;
resultEl.appendChild(card);
}
};
const renderPager = (total: number): void => {
const pages = Math.max(1, Math.ceil(total / 20));
// 分页: 接口每页固定返回 12 条并以 hasMore 标识是否还有下一页。
// 之前按「返回条数 >= 20 才算有下一页」估算总数, 与真实分页规则不符,
// 会导致第一页就显示 100 页。改为记录 hasMore, 只区分「有/无下一页」。
let hasMore = false;
const renderPager = (): void => {
const nav = document.createElement('div');
nav.className = 'mi-pager';
nav.innerHTML = `
<md-text-button id="mi-prev" ${pageNo === 0 ? 'disabled' : ''}>上一页</md-text-button>
<span class="mi-page">第 ${pageNo + 1} / ${pages} 页</span>
<md-text-button id="mi-next" ${pageNo + 1 >= pages ? 'disabled' : ''}>下一页</md-text-button>
<span class="mi-page">第 ${pageNo + 1} 页</span>
<md-text-button id="mi-next" ${hasMore ? '' : 'disabled'}>下一页</md-text-button>
`;
resultEl.appendChild(nav);
nav.querySelector('#mi-prev')?.addEventListener('click', () => {
@@ -180,7 +216,7 @@ export const MiFontToolDef: ToolDef = {
}
});
nav.querySelector('#mi-next')?.addEventListener('click', () => {
if (pageNo + 1 < pages) {
if (hasMore) {
pageNo++;
void search(pageNo);
}
@@ -198,13 +234,14 @@ export const MiFontToolDef: ToolDef = {
const { errno, stdout } = await exec(`curl -s ${shellQuote(url)}`);
if (errno !== 0) throw new Error('curl 执行失败');
const data = JSON.parse(stdout);
const items = data?.data?.items ?? [];
const items = parseSearchResponse(data);
if (items.length === 0) {
resultEl.textContent = '未找到相关字体, 换个关键词试试';
return;
}
hasMore = Boolean(data?.apiData?.hasMore);
renderItems(items);
renderPager(items.length >= 20 ? 100 : items.length);
renderPager();
} catch (e) {
resultEl.textContent = `搜索失败: ${(e as Error).message}`;
} finally {
@@ -231,9 +268,14 @@ export const MiFontToolDef: ToolDef = {
const startDownload = async (itemEl: HTMLElement): Promise<void> => {
if (downloading) return;
const card = itemEl.closest('.mi-item') as HTMLElement;
const title = card.querySelector('.mi-item-title')?.textContent ?? '';
const link = (card.querySelector('.mi-item-dl') as HTMLElement | null)?.dataset.link ?? '';
// link/title 由 renderItems 写在按钮的 data-* 上
const title = itemEl.dataset.title ?? '';
const link = itemEl.dataset.link ?? '';
if (!link) {
logEl.hidden = false;
logEl.textContent = '下载失败: 缺少主题 ID, 请重新搜索后再试';
return;
}
downloading = true;
try {
const logFile = '/data/adb/modules/FontMM/webroot/mi-download.log';
@@ -335,7 +377,6 @@ class FontEditorPage {
private originalBytes: Uint8Array | null = null;
private fileName = '';
private hasNameChanges = false;
private picker: FontFilePicker | null = null;
private previewText = DEFAULT_PREVIEW_TEXT;
private editTimer: number | null = null;
@@ -460,10 +501,9 @@ class FontEditorPage {
void this.loadFont('demo-font.ttf', 'demo-font.ttf');
return;
}
this.picker ??= new FontFilePicker((path, name) => {
fontPicker.show('/storage/emulated/0/Download', (path, name) => {
void this.copyAndLoad(path, name);
});
this.picker.show('/storage/emulated/0/Download');
}
private async copyAndLoad(path: string, name: string): Promise<void> {
+24 -1
View File
@@ -1,6 +1,25 @@
export type SlotKey = 'hans' | 'hant' | 'en' | 'mono' | 'emoji';
export type MultiSlotKey = 'hans' | 'hant' | 'en';
export type SlotMode = 'single' | 'multi';
export type WeightLevel = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
export interface MultiWeightEntry {
weight: WeightLevel;
path: string | null;
fileName: string;
sizeText?: string;
/** 英文字体裁切后的子集大小 (如 "184 KB"), 仅 en 槽位子集有效时存在 */
subsetSizeText?: string;
}
export interface FontSlot {
key: 'hans' | 'hant' | 'en' | 'mono' | 'emoji';
key: SlotKey;
title: string;
/** 是否支持切换多字重模式 (仅 hans/hant/en) */
supportsMulti?: boolean;
/** 当前模式 ('single'=可变/单字体, 'multi'=多字重) */
mode: SlotMode;
/** 单字体模式选中文件路径 (与 multiWeights 各自保留, 切换模式不丢失) */
path: string | null;
fileName: string;
/** 字体大小展示文本 (如 "12.5 MB"), 异步获取 */
@@ -9,4 +28,8 @@ export interface FontSlot {
isVariable?: boolean;
/** wght 轴范围 (如 "100-900"), 可变字体时有 */
wghtRange?: string;
/** 英文字体裁切后的子集大小 (如 "218 KB"), 仅英文槽位且子集有效时存在 (issue #14) */
subsetSizeText?: string;
/** 多字重模式下各档位字体配置 */
multiWeights?: Record<WeightLevel, MultiWeightEntry>;
}
+1 -24
View File
@@ -1,7 +1,7 @@
import { exec, toast } from './ksu';
import { pickWghtRange, updateWghtModeDisabled } from './slots';
import { WEIGHTS, averagedAxis } from './fontsXml';
import { FONTS_DIR, WGHT_BIN } from './constants';
import { FONTS_DIR } from './constants';
export type WghtMode = 0 | 1 | 2 | 3;
@@ -64,29 +64,6 @@ async function readWghtMode(): Promise<WghtMode> {
return 0;
}
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制)
export 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 {
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})`);
}
} catch (e) {
// 覆写失败不阻断应用主流程
console.warn('字重范围覆写失败:', e);
}
}
// 读取自定义字重映射 (FONTS/wght-map.txt: 每行 "weight axis")
async function readWghtMap(): Promise<Record<number, number>> {
const map: Record<number, number> = {};