94 Commits
  • 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
  • fix(webui): 恢复应用按钮可用状态
    重构时丢失 renderSlots 中 applyBtn.disabled = applying 一行,
    按钮停留在 HTML 初始 disabled 状态无法点击。恢复共享 applying 标志,
    选中字体后按钮启用, 应用过程中禁用
  • chore: 发布 v26.8.0-beta.4 (260800004)
    更新 changelog 与 update.json, 版本号提升至 26.8.0-beta.4
  • feat(webui): 重构 main.ts 模块化 + 字重映射编辑器完善
    - main.ts 从 1039 行拆分为 material/constants/dom/slots/wght/apply/
      testFonts/home/navigation 等模块
    - 字重映射区: 撤销/导出/导入/重置工具栏, 各模式实时预览,
      修改自动切自定义模式, 轴值对比标注, 按住并水平滑动才触发滑条
    - 高级配置卡片默认收起, 映射行取消限高
    - 首页捐赠新增爱发电入口 (am start 默认浏览器)
    - fix(wght): Go XML 覆写用深度计数匹配嵌套 family, 整行替换避免
      重复缩进, 修复段被切掉导致无法开机的严重问题
  • feat: 字重范围覆写 (Go 方案 + 可视化映射编辑器)
    - 新增 Go 程序 fontmm-wght (golang/ 多程序结构: cmd/fontmm-wght + internal/wght)
    - WebUI 配置页高级配置: 覆写模式(不处理/裁切/平均/自定义) + 字重映射编辑器
      (滑条+输入框联动, 支持 1-1000 动态增删映射)
    - 应用时 exec 调 fontmm-wght 本地读写 6 个字体配置 XML, 修复之前
      fetch/base64 分块导致的 32KB 截断与 XML 格式损坏
    - 二进制 tools/fontmm-wght 随模块打包 (dev/build-wght.sh 自动交叉编译, chmod 755)
    - CI: 新增 go.yml workflow (vet/test/android-arm64 交叉编译)
    - 移除 fontsXml.ts 中的 XML 生成逻辑, 避免双实现漂移
  • feat(webui): 字重范围覆写 fonts.xml — 裁切/平均分配两种模式
    - 新增 web/src/fontsXml.ts: generateSansSerifFamily / applyWghtMode (字符串级
      替换 sans-serif family 段, 保留 #ifdef 注释与格式) + fast-xml-parser 校验
    - 配置页新增「字重覆写模式」: 不处理 / 裁切粗细等级 / 平均分配字重
      (模式持久化到 FONTS/wght-mode.txt, 无可变字体时禁用提示)
    - 应用时覆写流程: 从 hans/hant/en 收集 wght 范围 (emoji/mono 除外),
      多可变取跨度最小者; cp fonts.xml -> fetch -> 替换 -> base64 分块写回
      模块 system/etc/fonts.xml; 无可变或模式 0 时跳过, 失败不阻断应用
    - 平均分配: 400 固定, 两端按范围线性插值 (floor); 裁切: 仅保留范围内的字重
    - README 特性与使用说明更新
  • feat(webui): 可变字体 wght 轴范围展示与集成
    - 新增 src/tools/wght-range.sh: shell 读取可变字体 fvar wght 轴范围 (od/dd 解析, 无依赖)
    - WebUI 前端直读 fvar (opentype.js / fontTools) 展示 wght 范围:
      - 配置页徽标: "可变字体" -> "可变字体 100-900" (无 wght 轴时仍显示"可变字体")
      - 字体测试页: var-tag 加 "(可变字体 wght 100-900)" 提示
      - 字体编辑信息卡: Variable Font -> "是 (wght 100-900)"
    - FontSlot 类型扩展 wghtRange 字段
  • perf(tools): 字体编辑性能重构 — Canvas 预览 + 快照重置 + lazy 解析 + numpy
    - 预览彻底摆脱字体文件: fontTools 提取轮廓点 (getCoordinates 展开复合字形),
      主线程 Canvas 二次贝塞尔渲染 + advance 布局/折行/行距 (previewRenderer.ts)
      - 22.7MB/29422 字形中文字体实测: 首次预览 2.1s, 滑条调整 12ms (原 15-30s)
      - 数据经 JSON 传递, 规避 PyProxy postMessage 克隆失败
    - 编辑引擎重构:
      - TTFont(lazy=True) + 字形懒快照: 首次预览只解析用到的字形
      - 快照-重置: list 浅拷贝快照 (coordinates/flags/endPts/bytecode/组件),
        每次编辑从原始快照重置再变换, 多次调整不累积
      - numpy 批量矩阵变换 (简单字形), 复合组件内联算术 — 导出提速 62s->11.5s
      - 修复: items()/instructions/transform 缺失, Program.fromBytecode 返回 None,
        组件 transform 2x2 嵌套/tr[2] 越界 (Eth 等复合字形导出失败)
    - 移除滑动手势切页 (仅底栏点击, 防误触)
    - numpy whl 本地化进 webroot
  • feat(tools): 引入 Pyodide + fontTools 字体编辑工具, 重构工具页为可扩展框架
    - 引入 Pyodide 314 + fontTools 4.62.1: 资源全部本地化 (webroot 随包 14MB, 零外部依赖)
    - 字体编辑工具 v0.0.1 (实验性):
      - 打开 ttf (文件选择器 / dev 内置 demo), 展示并编辑字体信息 (17 个 name 字段,
        默认折叠仅显 Font Family/Subfamily/Version + 只读技术字段, 展开更多)
      - 字形编辑: 缩放 50-150% / 水平垂直偏移 / 字间距 / 行间距 (实时预览, 防抖)
      - 自定义预览文本, 导出 base64 分块写盘 -> Download/FontMM/ (弹窗反馈)
    - 性能: Pyodide 移入 Web Worker (ESM worker + transferable 回传), 编辑大字体不阻塞 UI
    - 工具页重构: ToolHost 注册表框架, 每个工具独立页面 (template/mount/unmount),
      为创意工坊等大量工具扩展铺路; 小米主题字体工具迁移至框架
    - 修复: oxlint ignore public/pyodide; md-linear-progress hidden 被 :host 覆盖
  • chore: release v26.8.0-beta.3 (260800003)
    - module.prop / update.json 版本号更新
    - changelog.md 新增 beta.3 条目 (工具页, 等宽/emoji 替换系统字体修复, emoji 迁移补全)
  • fix(fonts): 等宽/emoji 改回替换系统字体 (overlay), 不再自创独立字体文件
    - mono.ttf -> 直接替换系统 DroidSansMono.ttf; 未设置时移除模块内文件恢复系统原字体
    - emoji.ttf -> 直接替换系统 NotoColorEmoji.ttf; 首次设置前备份内嵌补充字库
      到模块 backup/, 清除槽位时自动还原 (customize.sh 安装时备份)
    - fonts.xml monospace/und-Zsye 家族移除 FontMM-Mono/FontMM-Emoji 引用
      (同步 5 个派生配置文件)
    - customize.sh IMPORT_OLD_FONTS 继承列表补全 emoji.ttf
    - README 映射表与回退规则更新
  • feat(tools): 新增工具页「下载国际版小米主题字体」v1.0.0
    - 底部导航新增「工具」页 (第 4 tab), 工具以页面形式呈现(列表->详情->返回)
    - 小米主题字体工具: 搜索(跨域走 root shell curl) + 预览图(thumbnail/webp 格式) + 分页
    - 下载/解压由模块内置脚本 src/tools/mi-font-download.sh 完成:
      后台运行 + 日志写入 webroot 文件 + 前端 1s 轮询展示日志 (__DONE__ 结束标记)
      (KernelSU 原生 exec 在主线程执行 shell, 长任务必须后台化, 避免 UI 卡死)
    - 下载后自动解压 mtz 提取 fonts/ 目录字体并显示路径
    - dev mock 完整模拟搜索/详情/下载日志
  • feat(emoji): 新增 Emoji 字体槽位 (emoji.ttf → FontMM-Emoji.ttf)
    - fonts.xml und-Zsye 家族优先引用 FontMM-Emoji.ttf, 未设置时回退系统默认
    - apply.sh 新增 emoji 复制/删除逻辑 (独立文件方案, 不覆盖补充字库)
    - WebUI 新增「Emoji 表情」槽位 (types/main/占位文案/应用/加载)
    - dev mock 补 emoji 假数据
    - README 更新五槽位映射与回退规则
  • feat(webui): 重构三页导航 + 视口 pager 滑动切换 + 多项 UI 优化
    - 三页结构: 主页(模块状态/捐献/开发者/设备信息) / 配置(字体槽位) / 测试(字体预览)
    - 视口 pager 重构: body 高度锁定 + 轨道滑动切换 + 跟手拖拽/边界阻尼,
      修复 flex 轨道高度撑起与 transform+overflow 合成层渲染 bug
    - 主页: 顶栏滚动标题固定、重启按钮(二次确认, 仅主页)、元模块信息、
      状态卡/入口卡/设备信息卡 M3 化(圆角调大)
    - 配置页: filled-card 替代 elevated(无阴影), 整卡点击选择(右侧箭头替代按钮),
      slot-meta 徽标组(大小/扩展名/可变字体), 动态扩展名提取
    - 测试页: 字重 100-900 全档, 可变字体滑条(字重/字号), 测试文本可点击编辑,
      加载缓存(应用后重置), info 状态卡常驻
    - 滑动手势: RAF 节流修复滑过头, touchcancel 处理, 滑条组件触摸排除
    - 文件选择器: find -print0 支持换行路径, 长路径换行显示
    - 修复: 卡片嵌套(md-filled-card 闭合标签)、可变徽标同色融合、
      isVariable 残留、点击回顶、阴影删减等
  • docs: 重写 README 并发布 v26.8.0-beta.2
    - README 重写: 无 emoji, 安装部分说明 preplace/template 两版区别与适用场景,
      等宽字体映射同步 FontMM-Mono 方案
    - WebUI 关于页致谢补充 MakeFontsGreatAgain
    - 版本号 26.8.0-beta.1 -> 26.8.0-beta.2(260800002), versionCode 26080002
    - changelog/update.json 更新至 beta.2
  • feat(fonts): 补充字库集成与单一源字体配置
    - 补充字库(OFL/MIT): Plangothic(CJK 扩展 I/J)、PlanschriftSeal(Seal 小篆 11328 字符 100%)、
      ArchaicCuneiformNumerals、NotoUnicode、NotoColorEmoji 等 20 个字体, fonts.xml 末尾全局 fallback
    - 单一源: fonts.xml 为唯一源, dev/sync-fonts-xml.sh 生成派生 XML, 接入 cd.sh 打包流程
    - 新增 dev/check-unicode-coverage.py 本地模拟 fallback 链统计 Unicode 区块覆盖
    - README/changelog 更新
  • feat: v26 重构 — WebUI、双版本打包与字体名称解析
    - 新架构: src/ 模块源 + web/ WebUI (Vite + TS + Material Web MD3)
    - WebUI: 字体槽位/应用、字体测试(字重/可变字体/字号)、关于页、底部导航、edge-to-edge、跟随系统主题
    - 打开 WebUI 时用 opentype.js 解析 FONT/ 字体名称填充卡片
    - 打包: preplace/template 两版 + build:only-web (webroot.zip)
    - 工具链: oxlint/oxfmt/type-check/shellcheck; 移除旧 template/ v1 结构与 CI
    - 新增 MIT LICENSE
  • chore(lib): 增加 libbz2 库
    解决部分设备无法使用 zip
  • refactor(fonttool): 更换自制的字体处理工具
    更换自制 fonttool-rs
    优化环境处理,确保权限
    优化代码格式
  • feat(packer): 新增解析 ttf 元信息内的 name
    - 使用 fonttool 的 ttx 实现解析 ttf 的 Meta 内 name 表,从而获取字体名称
    - 增加了对应的环境检测
  • revert(template): 删除系统不存在的xml以解决检测问题
    `template/system/etc/fonts_ule.xml` 和 `template/system/etc/fonts_base.xml` 在系统中原本不存在
    新增文件会导致环境泄露
  • feat(ttc_splitter): 新增 TTC 拆分功能
    TTC 是一种字体集合格式,它将多个相关的 TTF(TrueType)字体打包进同一个文件
  • fix: 修复某些管理器的字体应用问题
    增加:刷入时SHA256校验
    增加:刷入时权限设置
    增加:提前创建空字体文件
  • feat(fonts.xml): 增加几个转换工具
    增加 json - xml 互转
    增加 yaml - xml 互转
    增加 yq 依赖实现上述功能
    删除过时的 jq 依赖
122 changed files with 15601 additions and 216 deletions

No files matched your search

Executable → Regular
+20 -1
View File
@@ -1 +1,20 @@
template/*.zip filter=lfs diff=lfs merge=lfs -text
# 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
+84
View File
@@ -0,0 +1,84 @@
name: Build & Upload Artifacts
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 11
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
cache-dependency-path: |
pnpm-lock.yaml
web/pnpm-lock.yaml
- 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: 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
dist/*.zip.sha256
retention-days: 14
+50
View File
@@ -0,0 +1,50 @@
name: Go
on:
push:
paths:
- 'golang/**'
- 'dev/build-wght.mjs'
- 'dev/lib/go.mjs'
pull_request:
paths:
- 'golang/**'
- 'dev/build-wght.mjs'
- 'dev/lib/go.mjs'
workflow_dispatch:
jobs:
test-and-build:
runs-on: ubuntu-latest
steps:
- 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.mod 声明的工具链版本, 避免宽泛的 '1.24' 解析到最新补丁版
# (CI 曾装 1.24.13 而本地是 1.24.4, 编译产物因此不同)
go-version-file: golang/go.mod
- name: Vet
run: cd golang && go vet ./...
- name: Test
run: cd golang && go test ./...
# 用与本地一致的构建脚本 (含 -trimpath -buildvcs=false), 保证 CI 产物
# 与开发者本地构建的二进制哈希一致
- name: Cross-compile (android/arm64)
run: node dev/build-wght.mjs
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: 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
-50
View File
@@ -1,50 +0,0 @@
name: Release Package & Attach
# 触发条件:当发布(published)一个 Release 时
on:
release:
types: [published]
jobs:
upload-assets:
runs-on: ubuntu-latest
# 授予写入 Release 内容的权限
permissions:
contents: write
steps:
# 1. 拉取代码并包含 LFS
- name: Checkout Code
uses: actions/checkout@v4
with:
lfs: true
- name: Pull LFS objects
run: git lfs pull
# 2. 准备打包环境并压缩
- name: Cleanup and Zip
id: pack
run: |
# 删除 .gitattributes
rm -f .gitattributes
# 获取当前 Release 的 Tag 名字 (比如 V1.1)
TAG_NAME="${{ github.event.release.tag_name }}"
# 按照你的要求命名:FontMM-[Tag]-release.zip
FILENAME="FontMM-${TAG_NAME}-release.zip"
# 执行最高压缩
zip -r -9 "$FILENAME" . -x "*.git*" ".github*"
# 存入环境变量供下一步引用
echo "ZIP_PATH=$FILENAME" >> $GITHUB_ENV
# 3. 将打包好的文件上传到当前的 Release 页面
- name: Upload Release Asset
uses: softprops/action-gh-release@v2
with:
# files 指向刚才生成的压缩包路径
files: ${{ env.ZIP_PATH }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+86
View File
@@ -0,0 +1,86 @@
name: Release
on:
release:
types: [published]
jobs:
build-and-release:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 11
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
cache-dependency-path: |
pnpm-lock.yaml
web/pnpm-lock.yaml
- 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: 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
dist/*.zip.sha256
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+41
View File
@@ -0,0 +1,41 @@
node_modules/
web/node_modules/
dist/
src/webroot/
reasonix.toml
.reasonix/
.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
}
+7
View File
@@ -0,0 +1,7 @@
{
"recommendations": [
"oxc.oxc-vscode",
"llvm-vs-code-extensions.vscode-clangd",
"ms-vscode.cpptools"
]
}
+17
View File
@@ -0,0 +1,17 @@
{
// 官方推荐: https://oxc.rs/docs/guide/usage/linter/editors.html
// https://oxc.rs/docs/guide/usage/formatter/editors.html
// 使用 Oxc 扩展 (oxlint --lsp / oxfmt --lsp), 需本地安装 oxlint 与 oxfmt
"editor.defaultFormatter": "oxc.oxc-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.oxc": "always"
},
// 显式指定 JavaScript/TypeScript 由 oxfmt 格式化
"[javascript]": {
"editor.defaultFormatter": "oxc.oxc-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "oxc.oxc-vscode"
}
}
+311
View File
@@ -0,0 +1,311 @@
# 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 预热字体清单与 `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`,属中转产物,
> 不是用户槽位,不被 WebUI 读取。
### 补充字库
模块内置一组 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 → 更新模式检测与旧字体继承 → 扫描设备系统 XML 生成派生字体配置
→ 调用 `apply.sh` 完成首次字体安装
2. **换字体阶段**(WebUI):选择文件 → 复制到 `FONTS/` → 调用同一个 `apply.sh`,两条路径行为一致
3. **`apply.sh` 核心逻辑**:按字体映射表把 `FONTS/` 中的字体复制到 `system/fonts/` 的对应文件,
缺繁体/英文时回退简体;英文槽位在复制前会检测并裁掉 CJK 字形(issue #10)
4. **字体生效**:ColorOS 通过 `/system/etc/fonts.xml` 等配置引用 `SysFont*` / `SysSans*` 字体族,
模块只内置 `fonts.xml` 主配置,各派生配置(`fonts_base.xml` / `fonts_ule.xml` /
`font_fallback.xml`)由安装时扫描设备系统 XML 生成(缺失时回退内置),字重覆写时
`fontmm-wght -sync` 统一同步,提升跨 ColorOS 版本兼容性
5. **字体预加载**(`zygisk/arm64-v8a.so`):App 进程 specialize 前,模块把 FontMM 的字体文件
预读进系统字体缓存,使被「卸载模块」的 App 仍能正常渲染字体
## 相关文档
- [README](./README.md) — 用户文档
- [changelog.md](./changelog.md) — 版本变更记录
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
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.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
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>.
+156
View File
@@ -0,0 +1,156 @@
<h1 align="center">FontMM</h1>
<div align="center">
一个用于快速更换系统字体的 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>
</div>
## 特性
- Material 风格的管理界面,在支持 WebUI 的 Root 管理器中直接打开
- 多槽位字体分别选择,满足你的个性化需求
- 可变字体 wght 范围与实际字重等级不符时可选择覆写配置,保证正确映射
- 内置字库补充字体,兜底 CJK 扩展区、Unicode 18.0 全覆盖
- 内置字体预加载,无需额外安装 Fontloader
## 支持环境
| 项目 | 要求 |
| --------- | ----------------------- |
| 系统 | >= ColorOS 16.0 |
| Root 环境 | Magisk 20.4+ / KernelSU |
| 字体格式 | `.ttf` |
## 安装
> 安装完成后,请在系统设置中选择 Roboto 作为字体,这样才能得到正确的字重映射!
### 选择刷入包
每个 Release 提供两个压缩包,区别仅在于是否预置字体:
| 包名 | 内容 | 适用场景 |
| -------------------- | ------------------------------- | ----------------------------------------------- |
| `..._preplace.zip` | 含预置简体字体 `FONTS/hans.ttf` | **全新安装**,刷入后开箱即用 |
| `..._template.zip` | `FONTS/` 为空目录 | **更新模块**,自动继承旧模块字体,包体积更小 |
> 若用 `_template` 版全新安装,需自行在 `FONTS/` 放入简体字体 `hans.ttf`,否则安装会失败。
### 安装依赖
按你的 Root 管理器完成下表配置。三行都需要满足:
| 依赖 | KernelSU 及分支 | Magisk 及分支 |
| --------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------ |
| **元模块** | 若管理器支持元模块则**必须**安装,否则模块无法挂载。参见[什么是元模块](https://kernelsu.org/zh_CN/guide/metamodule.html)。已测试:[mountify](https://github.com/backslashxx/mountify/releases) | 不适用 |
| **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 中把「排除列表策略」改为**仅还原挂载**。
- **管理器配置**:本模块已内置字体预加载,可以不必关闭「默认卸载模块」以及「卸载模块(内核级)」,**但仍建议关闭**——关闭后模块才能尽可能全场景覆盖。若选择不关闭,可用 App Profile 单独为某个应用关闭「卸载模块」并重启该应用。
> **不再需要 Fontloader**:从 Android 12 起字体改为 App 启动时按需加载,被「卸载模块」的 App 会因找不到字体而异常。Fontloader 这类模块的作用就是提前把字体读进缓存,**本模块已内置该能力**。若你此前装过 Fontloader,刷入时会自动为其添加 `disable` 文件停用(不影响其数据,删除该文件即可恢复)。
## 使用
### 更换字体
1. 打开 Root 管理器的 WebUI,进入 FontMM,切到「配置」页
2. 在槽位中选择字体,然后点「应用字体」,重启设备生效
各槽位说明:
| 槽位 | 是否必选 | 未选择时 |
| --------------- | -------- | ---------------------- |
| **中文简体** | **必选** | 无法应用 |
| **中文繁体** | 可选 | 自动使用简体 |
| **英文 & 数字** | 可选 | 自动使用简体 |
| **等宽字体** | 可选 | 不覆盖系统等宽字体 |
| **Emoji 表情** | 可选 | 使用系统默认 Emoji |
> **关于「英文 & 数字」槽位**:若所选字体本身自带中文字形(例如某些中文字体的英文版、或包含 CJK 的西文字体),应用时会**自动裁剪成纯拉丁子集**。系统字体配置里西文排在中文之前,不裁剪的话它自带的汉字会盖掉你选的中文字体,表现为"中文没换干净"。裁剪只影响西文槽位,中文字体不做处理,且会完整保留可变字体特性(字重轴不受影响)。
### 字重覆写(高级)
所选字体为**可变字体**时,若其 wght 轴范围与实际字重等级不符,可在「高级配置」中覆写映射:
| 模式 | 说明 |
| ---------------- | -------------------------------------------- |
| **不处理** | 默认,超出范围的字重由系统处理 |
| **裁切粗细等级** | 删除范围外的字重条目 |
| **平均分配字重** | 保留 9 档完整粗细,400 不变,两端平均插值 |
| **自定义映射** | 自行定义 1-1000 字重的映射关系 |
### 手动放置字体
也可以不经 WebUI,直接把字体放进 `/data/adb/modules/FontMM/FONTS/`:
| 文件名 | 用途 |
| ----------- | ---------------- |
| `hans.ttf` | 中文简体(必选) |
| `hant.ttf` | 中文繁体 |
| `en.ttf` | 英文与数字 |
| `mono.ttf` | 等宽字体 |
| `emoji.ttf` | Emoji 表情 |
之后执行 `sh /data/adb/modules/FontMM/apply.sh` 并重启设备。回退逻辑与 WebUI 一致。
### 校验模块完整性
校验模块内脚本与二进制是否被篡改或损坏:
```sh
sh /data/adb/modules/FontMM/tools/verify-sha256.sh
```
GitHub Release 的 zip 附件旁均提供 `.sha256` 文件,可用 `sha256sum -c` 验证下载完整性。
## 常见问题
**Q:装完模块后字体没变?**
A:确认系统是 ColorOS 16+ 并已完成[安装依赖](#安装依赖),然后重启设备。
**Q:更新模块会丢失我设置好的字体吗?**
A:不会。检测到已安装的 FontMM 时会进入更新模式,从旧模块的 `FONTS/` 继承字体。
**Q:首页显示「字体预热器未生效」怎么办?**
A:说明没检测到可用的 Zygisk 环境。被「卸载模块」的应用可能字体异常,请按[安装依赖](#安装依赖)配置 Zygisk。
**Q:需要额外安装 Fontloader 吗?**
A:不需要,本模块已内置字体预加载。
**Q:选了英文字体,为什么它的中文部分没生效?**
A:这是有意为之。西文字体若自带汉字,会盖掉你选的中文字体(系统配置里西文排在中文前面),因此应用时会自动裁掉其 CJK 部分,只保留拉丁字符。
**Q:我用了自带中文的英文字体,担心字重变少?**
A:不会。裁剪会完整保留可变字体的字重轴,字重覆写不受影响。
## 致谢
- 字体映射与配置文件参考 ColorOS 16 系统字体体系
- 补充字库与 `fonts.xml` fallback 结构参考 [MakeFontsGreatAgain](https://github.com/Numbersf/MakeFontsGreatAgain)
- WebUI 基于 [Material Web](https://github.com/material-components/material-web)(Material Design 3)与 [kernelsu](https://www.npmjs.com/package/kernelsu) 构建
## 许可
[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)。
-12
View File
@@ -1,12 +0,0 @@
1. 修改 module.prop
2. 在 ttf 里面放入你的字体
ch.ttf -- 中文(简体)
tc.ttf -- 中文(繁体)
en.ttf -- 英文
你也可以只放入一个 ch.ttf
这样的话,中文(繁体)和英文都会使用 ch.ttf
3. 运行 打包.sh
+89
View File
@@ -0,0 +1,89 @@
# Changelog
## 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` 配置
- 支持三种模式:**裁切粗细等级** / **平均分配字重**(9 档线性插值)/ **自定义映射**
- 字重映射编辑器:实时预览、新增/删除映射、滑块拖拽(按住并水平滑动才触发,防误触)、轴值对比标注(+25 / -100)
- 工具栏:撤销(30 步历史)、导出/导入(base64 JSON,跨设备备份恢复)、重置
- 内置 Go 程序 `fontmm-wght` 本地覆写全部 6 个字体配置 XML,无命令长度限制;修复嵌套 family 深度配对,杜绝段被切掉导致无法开机的严重问题
- **新增「字体编辑」工具**(实验性,Pyodide + fontTools):打开 `.ttf` 编辑字体信息与字形
- 17 个 name 字段编辑;字形缩放 50-150% / 水平垂直偏移 / 字间距 / 行间距(Canvas 实时预览)
- 性能重构:lazy 解析 + 快照-重置 + numpy 批量矩阵变换,大字体导出提速 62s → 11.5s
- 编辑结果 base64 分块导出到 `Download/FontMM/`;Pyodide 全部本地化(零外部依赖),移入 Web Worker 不阻塞 UI
- **工具页重构**:ToolHost 注册表框架,每个工具独立页面(template/mount/unmount),为创意工坊等扩展铺路
- **安装体验**:非 ColorOS / 版本过低不再拒绝安装,改为音量键确认风险后继续(音量上继续 / 音量下中止)
- **WebUI 架构重构**:`main.ts`(1039 行)按职责拆分为 slots / wght / apply / home / navigation 等模块;修复动态 shell 参数未加引号的安全问题
- **文档完善**:README 重写(支持环境、KernelSU/Magisk 分支、元模块、Fontloader 配置说明)
## v26.8.0-beta.3
- **新增「工具」页**(底部导航第 4 个 tab):下载国际版小米主题字体 v1.0.0
- 搜索小米主题商店字体(跨域走 root shell 解决)、缩略图预览、分页浏览
- 下载 mtz 并自动解压提取 `fonts/` 目录字体,日志实时展示(后台运行 + 轮询,避免阻塞 WebUI)
- **等宽/Emoji 修复**:`mono.ttf` 与 `emoji.ttf` 改回**直接替换系统字体**(`DroidSansMono.ttf` / `NotoColorEmoji.ttf`,overlay 生效),不再使用自创独立字体文件(`FontMM-Mono` / `FontMM-Emoji` 不生效)
- **Emoji 槽位完善**:清除 emoji 槽位时从模块 `backup/` 恢复内嵌补充字库 Emoji(安装时自动备份);旧包更新继承列表补全 `emoji.ttf`
## v26.8.0-beta.2
- **补充字库**:内置 OFL-1.1 / MIT 许可字体,在 `fonts.xml` 末尾作为全局 fallback:
- PlangothicP1/P2——CJK 扩展区覆盖(Ext-B、G/H、**I、J** 等生僻字与新汉字)
- PlanschriftSeal——**Seal(小篆)区块 11328 字符 100% 覆盖**(Unicode 18 新增,子集化 34M,MIT/OFL 双许可)
- ArchaicCuneiformNumerals、NotoUnicode、NotoColorEmoji、UnicodiaFunky、Unknown-symbol 等
- **等宽字体修复**:改为独立文件 `FontMM-Mono.ttf`(monospace 家族优先引用),不再覆盖系统 `DroidSansMono`,解决设置等宽字体后不生效的问题
- **单一源字体配置**:`fonts.xml` 为唯一源,`dev/sync-fonts-xml.sh` 自动生成 `fonts_base.xml` / `fonts_ule.xml` / `font_fallback.xml`
- **Unicode 覆盖测试**:新增 `dev/check-unicode-coverage.py`,本地模拟 fallback 链统计各区块覆盖率
- 致谢补充字库来源 [MakeFontsGreatAgain](https://github.com/Numbersf/MakeFontsGreatAgain)
## v26.8.0-beta.1
全新 v26 架构重构:
- **WebUI 重写**(Material Design 3 + 底部导航):字体槽位选择/应用、字体测试(字重 100–900、可变字体滑条、字号调节)、关于页、深色模式跟随系统、edge-to-edge 延伸至小白条
- **字体名称解析**:打开 WebUI 时用 opentype.js 读取 FONT/ 内字体的真实名称并显示在卡片(如 OPPO Sans 4.0)
- **双版本打包**:`_preplace`(含预置字体)与 `_template`(FONT 空目录)两版;新增 `build:only-web` 快速调试产物
- **开发工具链**:oxlint / oxfmt / type-check / shellcheck 脚本化
- 新增 MIT LICENSE
+391
View File
@@ -0,0 +1,391 @@
# Blocks-18.0.0.txt
# Date: 2026-02-03
# © 2026 Unicode®, Inc.
# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries.
# For terms of use and license, see https://www.unicode.org/terms_of_use.html
#
# Unicode Character Database
# For documentation, see https://www.unicode.org/reports/tr44/
#
# Format:
# Start Code..End Code; Block Name
# ================================================
# Note: When comparing block names, casing, whitespace, hyphens,
# and underbars are ignored.
# For example, "Latin Extended-A" and "latin extended a" are equivalent.
# For more information on the comparison of property values,
# see UAX #44: https://www.unicode.org/reports/tr44/
#
# All block ranges start with a value where (cp MOD 16) = 0,
# and end with a value where (cp MOD 16) = 15. In other words,
# the last hexadecimal digit of the start of range is ...0
# and the last hexadecimal digit of the end of range is ...F.
# This constraint on block ranges guarantees that allocations
# are done in terms of whole columns, and that code chart display
# never involves splitting columns in the charts.
#
# All code points not explicitly listed for Block
# have the value No_Block.
# Property: Block
#
# @missing: 0000..10FFFF; No_Block
0000..007F; Basic Latin
0080..00FF; Latin-1 Supplement
0100..017F; Latin Extended-A
0180..024F; Latin Extended-B
0250..02AF; IPA Extensions
02B0..02FF; Spacing Modifier Letters
0300..036F; Combining Diacritical Marks
0370..03FF; Greek and Coptic
0400..04FF; Cyrillic
0500..052F; Cyrillic Supplement
0530..058F; Armenian
0590..05FF; Hebrew
0600..06FF; Arabic
0700..074F; Syriac
0750..077F; Arabic Supplement
0780..07BF; Thaana
07C0..07FF; NKo
0800..083F; Samaritan
0840..085F; Mandaic
0860..086F; Syriac Supplement
0870..089F; Arabic Extended-B
08A0..08FF; Arabic Extended-A
0900..097F; Devanagari
0980..09FF; Bengali
0A00..0A7F; Gurmukhi
0A80..0AFF; Gujarati
0B00..0B7F; Oriya
0B80..0BFF; Tamil
0C00..0C7F; Telugu
0C80..0CFF; Kannada
0D00..0D7F; Malayalam
0D80..0DFF; Sinhala
0E00..0E7F; Thai
0E80..0EFF; Lao
0F00..0FFF; Tibetan
1000..109F; Myanmar
10A0..10FF; Georgian
1100..11FF; Hangul Jamo
1200..137F; Ethiopic
1380..139F; Ethiopic Supplement
13A0..13FF; Cherokee
1400..167F; Unified Canadian Aboriginal Syllabics
1680..169F; Ogham
16A0..16FF; Runic
1700..171F; Tagalog
1720..173F; Hanunoo
1740..175F; Buhid
1760..177F; Tagbanwa
1780..17FF; Khmer
1800..18AF; Mongolian
18B0..18FF; Unified Canadian Aboriginal Syllabics Extended
1900..194F; Limbu
1950..197F; Tai Le
1980..19DF; New Tai Lue
19E0..19FF; Khmer Symbols
1A00..1A1F; Buginese
1A20..1AAF; Tai Tham
1AB0..1AFF; Combining Diacritical Marks Extended
1B00..1B7F; Balinese
1B80..1BBF; Sundanese
1BC0..1BFF; Batak
1C00..1C4F; Lepcha
1C50..1C7F; Ol Chiki
1C80..1C8F; Cyrillic Extended-C
1C90..1CBF; Georgian Extended
1CC0..1CCF; Sundanese Supplement
1CD0..1CFF; Vedic Extensions
1D00..1D7F; Phonetic Extensions
1D80..1DBF; Phonetic Extensions Supplement
1DC0..1DFF; Combining Diacritical Marks Supplement
1E00..1EFF; Latin Extended Additional
1F00..1FFF; Greek Extended
2000..206F; General Punctuation
2070..209F; Superscripts and Subscripts
20A0..20CF; Currency Symbols
20D0..20FF; Combining Diacritical Marks for Symbols
2100..214F; Letterlike Symbols
2150..218F; Number Forms
2190..21FF; Arrows
2200..22FF; Mathematical Operators
2300..23FF; Miscellaneous Technical
2400..243F; Control Pictures
2440..245F; Optical Character Recognition
2460..24FF; Enclosed Alphanumerics
2500..257F; Box Drawing
2580..259F; Block Elements
25A0..25FF; Geometric Shapes
2600..26FF; Miscellaneous Symbols
2700..27BF; Dingbats
27C0..27EF; Miscellaneous Mathematical Symbols-A
27F0..27FF; Supplemental Arrows-A
2800..28FF; Braille Patterns
2900..297F; Supplemental Arrows-B
2980..29FF; Miscellaneous Mathematical Symbols-B
2A00..2AFF; Supplemental Mathematical Operators
2B00..2BFF; Miscellaneous Symbols and Arrows
2C00..2C5F; Glagolitic
2C60..2C7F; Latin Extended-C
2C80..2CFF; Coptic
2D00..2D2F; Georgian Supplement
2D30..2D7F; Tifinagh
2D80..2DDF; Ethiopic Extended
2DE0..2DFF; Cyrillic Extended-A
2E00..2E7F; Supplemental Punctuation
2E80..2EFF; CJK Radicals Supplement
2F00..2FDF; Kangxi Radicals
2FF0..2FFF; Ideographic Description Characters
3000..303F; CJK Symbols and Punctuation
3040..309F; Hiragana
30A0..30FF; Katakana
3100..312F; Bopomofo
3130..318F; Hangul Compatibility Jamo
3190..319F; Kanbun
31A0..31BF; Bopomofo Extended
31C0..31EF; CJK Strokes
31F0..31FF; Katakana Phonetic Extensions
3200..32FF; Enclosed CJK Letters and Months
3300..33FF; CJK Compatibility
3400..4DBF; CJK Unified Ideographs Extension A
4DC0..4DFF; Yijing Hexagram Symbols
4E00..9FFF; CJK Unified Ideographs
A000..A48F; Yi Syllables
A490..A4CF; Yi Radicals
A4D0..A4FF; Lisu
A500..A63F; Vai
A640..A69F; Cyrillic Extended-B
A6A0..A6FF; Bamum
A700..A71F; Modifier Tone Letters
A720..A7FF; Latin Extended-D
A800..A82F; Syloti Nagri
A830..A83F; Common Indic Number Forms
A840..A87F; Phags-pa
A880..A8DF; Saurashtra
A8E0..A8FF; Devanagari Extended
A900..A92F; Kayah Li
A930..A95F; Rejang
A960..A97F; Hangul Jamo Extended-A
A980..A9DF; Javanese
A9E0..A9FF; Myanmar Extended-B
AA00..AA5F; Cham
AA60..AA7F; Myanmar Extended-A
AA80..AADF; Tai Viet
AAE0..AAFF; Meetei Mayek Extensions
AB00..AB2F; Ethiopic Extended-A
AB30..AB6F; Latin Extended-E
AB70..ABBF; Cherokee Supplement
ABC0..ABFF; Meetei Mayek
AC00..D7AF; Hangul Syllables
D7B0..D7FF; Hangul Jamo Extended-B
D800..DB7F; High Surrogates
DB80..DBFF; High Private Use Surrogates
DC00..DFFF; Low Surrogates
E000..F8FF; Private Use Area
F900..FAFF; CJK Compatibility Ideographs
FB00..FB4F; Alphabetic Presentation Forms
FB50..FDFF; Arabic Presentation Forms-A
FE00..FE0F; Variation Selectors
FE10..FE1F; Vertical Forms
FE20..FE2F; Combining Half Marks
FE30..FE4F; CJK Compatibility Forms
FE50..FE6F; Small Form Variants
FE70..FEFF; Arabic Presentation Forms-B
FF00..FFEF; Halfwidth and Fullwidth Forms
FFF0..FFFF; Specials
10000..1007F; Linear B Syllabary
10080..100FF; Linear B Ideograms
10100..1013F; Aegean Numbers
10140..1018F; Ancient Greek Numbers
10190..101CF; Ancient Symbols
101D0..101FF; Phaistos Disc
10280..1029F; Lycian
102A0..102DF; Carian
102E0..102FF; Coptic Epact Numbers
10300..1032F; Old Italic
10330..1034F; Gothic
10350..1037F; Old Permic
10380..1039F; Ugaritic
103A0..103DF; Old Persian
10400..1044F; Deseret
10450..1047F; Shavian
10480..104AF; Osmanya
104B0..104FF; Osage
10500..1052F; Elbasan
10530..1056F; Caucasian Albanian
10570..105BF; Vithkuqi
105C0..105FF; Todhri
10600..1077F; Linear A
10780..107BF; Latin Extended-F
10800..1083F; Cypriot Syllabary
10840..1085F; Imperial Aramaic
10860..1087F; Palmyrene
10880..108AF; Nabataean
108E0..108FF; Hatran
10900..1091F; Phoenician
10920..1093F; Lydian
10940..1095F; Sidetic
10980..1099F; Meroitic Hieroglyphs
109A0..109FF; Meroitic Cursive
10A00..10A5F; Kharoshthi
10A60..10A7F; Old South Arabian
10A80..10A9F; Old North Arabian
10AC0..10AFF; Manichaean
10B00..10B3F; Avestan
10B40..10B5F; Inscriptional Parthian
10B60..10B7F; Inscriptional Pahlavi
10B80..10BAF; Psalter Pahlavi
10C00..10C4F; Old Turkic
10C80..10CFF; Old Hungarian
10D00..10D3F; Hanifi Rohingya
10D40..10D8F; Garay
10E60..10E7F; Rumi Numeral Symbols
10E80..10EBF; Yezidi
10EC0..10EFF; Arabic Extended-C
10F00..10F2F; Old Sogdian
10F30..10F6F; Sogdian
10F70..10FAF; Old Uyghur
10FB0..10FDF; Chorasmian
10FE0..10FFF; Elymaic
11000..1107F; Brahmi
11080..110CF; Kaithi
110D0..110FF; Sora Sompeng
11100..1114F; Chakma
11150..1117F; Mahajani
11180..111DF; Sharada
111E0..111FF; Sinhala Archaic Numbers
11200..1124F; Khojki
11280..112AF; Multani
112B0..112FF; Khudawadi
11300..1137F; Grantha
11380..113FF; Tulu-Tigalari
11400..1147F; Newa
11480..114DF; Tirhuta
11580..115FF; Siddham
11600..1165F; Modi
11660..1167F; Mongolian Supplement
11680..116CF; Takri
116D0..116FF; Myanmar Extended-C
11700..1174F; Ahom
11800..1184F; Dogra
118A0..118FF; Warang Citi
11900..1195F; Dives Akuru
119A0..119FF; Nandinagari
11A00..11A4F; Zanabazar Square
11A50..11AAF; Soyombo
11AB0..11ABF; Unified Canadian Aboriginal Syllabics Extended-A
11AC0..11AFF; Pau Cin Hau
11B00..11B5F; Devanagari Extended-A
11B60..11B7F; Sharada Supplement
11BC0..11BFF; Sunuwar
11C00..11C6F; Bhaiksuki
11C70..11CBF; Marchen
11D00..11D5F; Masaram Gondi
11D60..11DAF; Gunjala Gondi
11DB0..11DEF; Tolong Siki
11DF0..11DFF; Bengali Supplement
11EE0..11EFF; Makasar
11F00..11F5F; Kawi
11FB0..11FBF; Lisu Supplement
11FC0..11FFF; Tamil Supplement
12000..123FF; Cuneiform
12400..1247F; Cuneiform Numbers and Punctuation
12480..1254F; Early Dynastic Cuneiform
12550..1268F; Archaic Cuneiform Numerals
12F90..12FFF; Cypro-Minoan
13000..1342F; Egyptian Hieroglyphs
13430..1345F; Egyptian Hieroglyph Format Controls
13460..143FF; Egyptian Hieroglyphs Extended-A
14400..1467F; Anatolian Hieroglyphs
16100..1613F; Gurung Khema
16800..16A3F; Bamum Supplement
16A40..16A6F; Mro
16A70..16ACF; Tangsa
16AD0..16AFF; Bassa Vah
16B00..16B8F; Pahawh Hmong
16D40..16D7F; Kirat Rai
16D80..16DAF; Chisoi
16E40..16E9F; Medefaidrin
16EA0..16EDF; Beria Erfe
16F00..16F9F; Miao
16FE0..16FFF; Ideographic Symbols and Punctuation
17000..187FF; Tangut
18800..18AFF; Tangut Components
18B00..18CFF; Khitan Small Script
18D00..18D7F; Tangut Supplement
18D80..18DFF; Tangut Components Supplement
18E00..1919F; Jurchen
191A0..191DF; Jurchen Radicals
1AFF0..1AFFF; Kana Extended-B
1B000..1B0FF; Kana Supplement
1B100..1B12F; Kana Extended-A
1B130..1B16F; Small Kana Extension
1B170..1B2FF; Nushu
1BC00..1BC9F; Duployan
1BCA0..1BCAF; Shorthand Format Controls
1CC00..1CEBF; Symbols for Legacy Computing Supplement
1CEC0..1CEFF; Miscellaneous Symbols Supplement
1CF00..1CFCF; Znamenny Musical Notation
1D000..1D0FF; Byzantine Musical Symbols
1D100..1D1FF; Musical Symbols
1D200..1D24F; Ancient Greek Musical Notation
1D250..1D28F; Musical Symbols Supplement
1D2C0..1D2DF; Kaktovik Numerals
1D2E0..1D2FF; Mayan Numerals
1D300..1D35F; Tai Xuan Jing Symbols
1D360..1D37F; Counting Rod Numerals
1D400..1D7FF; Mathematical Alphanumeric Symbols
1D800..1DAAF; Sutton SignWriting
1DB00..1DBFF; Miscellaneous Symbols and Arrows Extended
1DF00..1DFFF; Latin Extended-G
1E000..1E02F; Glagolitic Supplement
1E030..1E08F; Cyrillic Extended-D
1E100..1E14F; Nyiakeng Puachue Hmong
1E290..1E2BF; Toto
1E2C0..1E2FF; Wancho
1E4D0..1E4FF; Nag Mundari
1E5D0..1E5FF; Ol Onal
1E6C0..1E6FF; Tai Yo
1E7E0..1E7FF; Ethiopic Extended-B
1E800..1E8DF; Mende Kikakui
1E900..1E95F; Adlam
1EC70..1ECBF; Indic Siyaq Numbers
1ED00..1ED4F; Ottoman Siyaq Numbers
1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols
1F000..1F02F; Mahjong Tiles
1F030..1F09F; Domino Tiles
1F0A0..1F0FF; Playing Cards
1F100..1F1FF; Enclosed Alphanumeric Supplement
1F200..1F2FF; Enclosed Ideographic Supplement
1F300..1F5FF; Miscellaneous Symbols and Pictographs
1F600..1F64F; Emoticons
1F650..1F67F; Ornamental Dingbats
1F680..1F6FF; Transport and Map Symbols
1F700..1F77F; Alchemical Symbols
1F780..1F7FF; Geometric Shapes Extended
1F800..1F8FF; Supplemental Arrows-C
1F900..1F9FF; Supplemental Symbols and Pictographs
1FA00..1FA6F; Chess Symbols
1FA70..1FAFF; Symbols and Pictographs Extended-A
1FB00..1FBFF; Symbols for Legacy Computing
20000..2A6DF; CJK Unified Ideographs Extension B
2A700..2B73F; CJK Unified Ideographs Extension C
2B740..2B81F; CJK Unified Ideographs Extension D
2B820..2CEAF; CJK Unified Ideographs Extension E
2CEB0..2EBEF; CJK Unified Ideographs Extension F
2EBF0..2EE5F; CJK Unified Ideographs Extension I
2F800..2FA1F; CJK Compatibility Ideographs Supplement
30000..3134F; CJK Unified Ideographs Extension G
31350..323AF; CJK Unified Ideographs Extension H
323B0..3347F; CJK Unified Ideographs Extension J
3D000..3FC3F; Seal
E0000..E007F; Tags
E0100..E01EF; Variation Selectors Supplement
F0000..FFFFF; Supplementary Private Use Area-A
100000..10FFFF; Supplementary Private Use Area-B
# EOF
+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} 字节)`);
+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)`);
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""check-unicode-coverage.py — 本地模拟 Android 字体 fallback 链, 统计 Unicode 区块覆盖率.
原理: 按 fonts.xml 中 family 的声明顺序构成 fallback 链, 逐字形检查覆盖;
用 fontTools 读取各字体 cmap, 对照 Unicode Blocks.txt 统计每个区块的覆盖率.
用法:
python3 dev/check-unicode-coverage.py # 全部区块 (自动获取 Blocks.txt 缓存到 dev/)
python3 dev/check-unicode-coverage.py --blocks-file Blocks.txt
python3 dev/check-unicode-coverage.py Hebrew "Archaic" # 只测匹配的区块名 (子串)
"""
import argparse
import os
import urllib.request
import xml.etree.ElementTree as ET
from fontTools.ttLib import TTFont
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FONTS_DIR = os.path.join(ROOT, 'src', 'system', 'fonts')
FONTS_XML = os.path.join(ROOT, 'src', 'system', 'etc', 'fonts.xml')
BLOCKS_URL = 'https://www.unicode.org/Public/draft/ucd/Blocks.txt'
def load_chain(xml_path):
"""按 fonts.xml 声明顺序提取 fallback 链 (全部 font 文件名, 去重)."""
root = ET.parse(xml_path).getroot()
chain, seen = [], set()
for family in root.iter('family'):
for font in family.iter('font'):
name = (font.text or '').strip()
if name and name not in seen:
seen.add(name)
chain.append(name)
return chain
def load_cmaps(fonts_dir, chain):
cmaps, missing = {}, []
for name in chain:
path = os.path.join(fonts_dir, name)
if not os.path.exists(path):
missing.append(name)
continue
try:
cmaps[name] = TTFont(path, lazy=True).getBestCmap()
except Exception as exc: # 解析失败 (如特殊字体) 跳过
missing.append(f'{name} ({exc})')
return cmaps, missing
def load_blocks(path):
blocks = []
with open(path, encoding='utf-8') as fh:
for line in fh:
line = line.strip()
if not line or line.startswith('#') or '..' not in line:
continue
rng, name = line.split(';')
start, end = (int(x, 16) for x in rng.strip().split('..'))
blocks.append((name.strip(), start, end))
return blocks
def fetch_blocks(dest):
print(f'[i] 获取 Blocks.txt: {BLOCKS_URL}')
urllib.request.urlretrieve(BLOCKS_URL, dest)
return dest
def main():
ap = argparse.ArgumentParser(description='本地 Unicode 覆盖测试 (模拟 fonts.xml fallback 链)')
ap.add_argument('blocks', nargs='*', help='只测试匹配的区块名 (子串, 如 Hebrew)')
ap.add_argument('--blocks-file', help='本地 Blocks.txt 路径 (默认自动下载缓存到 dev/Blocks.txt)')
args = ap.parse_args()
chain = load_chain(FONTS_XML)
print(f'[i] fallback 链: {len(chain)} 个字体 ({FONTS_XML})')
cmaps, missing = load_cmaps(FONTS_DIR, chain)
if missing:
print(f'[!] 缺失/无法解析的字体: {missing}')
if not cmaps:
print('[!] 无可用字体, 退出', file=os.sys.stderr)
return 1
# 合并全部 cmap 为并集, 快速判字形
union = set()
for cm in cmaps.values():
union.update(cm)
print(f'[i] 可用字体 {len(cmaps)} 个, 字形码位并集 {len(union):,}')
blocks_file = args.blocks_file
if not blocks_file:
blocks_file = os.path.join(ROOT, 'dev', 'Blocks.txt')
if not os.path.exists(blocks_file):
fetch_blocks(blocks_file)
blocks = load_blocks(blocks_file)
if args.blocks:
blocks = [b for b in blocks if any(k.lower() in b[0].lower() for k in args.blocks)]
print(f'\n{"Block":<42}{"Covered":>9}{"Total":>8}{"Pct":>9} Status')
print('-' * 76)
failed = []
for name, start, end in blocks:
total = end - start + 1
covered = sum(1 for cp in range(start, end + 1) if cp in union)
pct = covered / total * 100 if total else 0
status = 'PASS' if covered == total else ('FAIL' if pct < 95 else '')
if status == 'FAIL':
failed.append(name)
print(f'{name:<42}{covered:>9}{total:>8}{pct:>8.2f}% {status}')
print(f'\n[=] 共 {len(blocks)} 个区块, FAIL (<95%): {len(failed)} 个')
for name in failed:
print(f' - {name}')
return 1 if failed else 0
if __name__ == '__main__':
raise SystemExit(main())
+268
View File
@@ -0,0 +1,268 @@
#!/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) —— 会被用户字体覆盖的
// SysFont*/SysSans* 占位文件, 必须与 empty-font.mjs 的 PLACEHOLDERS 一一对应
// 2. 单行的系统字体名 (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')) 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('全部检查通过');
+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)}`);
+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} 个派生文件`);
+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} 目录)`);
+42
View File
@@ -0,0 +1,42 @@
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>] [-xml-dir <模块根>] [-sync]
// 说明: 只修改主配置 system/etc/fonts.xml, 加 -sync 后复制到各派生配置 (issue #7)
package main
import (
"flag"
"fmt"
"os"
"fontmm/internal/wght"
)
func main() {
mode := flag.Int("mode", 0, "覆写模式: 0=不处理 1=裁切 2=平均分配 3=自定义映射")
min := flag.Int("min", 100, "裁切/平均最小字重")
max := flag.Int("max", 900, "裁切/平均最大字重")
mapPath := flag.String("map", "", "自定义映射文件 (mode 3): 每行 'weight axis'")
xmlDir := flag.String("xml-dir", "/data/adb/modules/FontMM", "模块根目录 (含 system/etc/fonts.xml)")
sync := flag.Bool("sync", false, "覆写后复制 fonts.xml 到各派生配置")
flag.Parse()
var customMap map[int]int
if *mode == 3 {
var err error
customMap, err = wght.ReadCustomMap(*mapPath)
if err != nil {
fmt.Printf("[x] 读取映射文件失败: %v\n", err)
os.Exit(1)
}
if len(customMap) == 0 {
fmt.Println("[-] 映射文件为空, 使用平均分配回退")
}
}
changed, err := wght.ApplyToDir(*xmlDir, *mode, *min, *max, customMap, *sync)
if err != nil {
fmt.Printf("[x] %v\n", err)
os.Exit(1)
}
fmt.Printf("[✓] 完成, 共处理 %d 个文件\n", changed)
}
+3
View File
@@ -0,0 +1,3 @@
module fontmm
go 1.24.4
+318
View File
@@ -0,0 +1,318 @@
// Package wght 提供字体配置 XML 的字重范围覆写逻辑
package wght
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
)
// 标准 9 档字重
var Weights = []int{100, 200, 300, 400, 500, 600, 700, 800, 900}
// 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 {
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{
{openTag: `<family name="sans-serif">`, fontFile: "SysFont-Regular.ttf", axis: axisFull},
{openTag: `<family name="sys-sans-en">`, fontFile: "SysSans-En-Regular.ttf", postScript: "OPlusSansEn", axis: axisWghtOnly},
{openTag: `<family lang="zh-Hans">`, fontFile: "SysSans-Hans-Regular.ttf", postScript: "OPPO_Sans_4.0_SC", serifFallback: true, axis: axisWghtOnly},
{openTag: `<family lang="zh-Hant,zh-Bopo">`, fontFile: "SysSans-Hant-Regular.ttf", postScript: "OPPO_Sans_4.0_TC", serifFallback: true, axis: axisWghtOnly},
}
// 主配置文件名 (唯一源)
const SourceXMLRel = "system/etc/fonts.xml"
// 派生配置 (与 fonts.xml 内容一致, 由 -sync 复制生成)
var DerivedXMLRel = []string{
"system/etc/fonts_base.xml",
"system/etc/fonts_ule.xml",
"system/etc/font_fallback.xml",
"system/system_ext/etc/fonts_base.xml",
"system/system_ext/etc/fonts_ule.xml",
}
// 平均分配: weight w 对应的 axis 值 (400 固定, 两端 floor 线性插值)
func AveragedAxis(min, max, w int) int {
if w == 400 {
return 400
}
if w < 400 {
return min + (400-min)*(w-100)/300
}
return 400 + (max-400)*(w-400)/500
}
// 生成 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, 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)
}
// 生成 zh-Hans/zh-Hant 家族的 fallbackFor="serif" 400 条目
func serifEntry(spec familySpec) string {
return fmt.Sprintf(` <font weight="400" style="normal" fallbackFor="serif"
postScriptName="%s">%s
</font>`, spec.postScript, spec.fontFile)
}
// 生成家族段 (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))
for w := range customMap {
ws = append(ws, w)
}
sort.Ints(ws)
}
var lines []string
for _, w := range ws {
if mode == 1 && (w < min || w > max) {
continue
}
axis := w
if mode == 2 {
axis = AveragedAxis(min, max, w)
} else if mode == 3 {
if v, ok := customMap[w]; ok {
axis = v
} else {
axis = AveragedAxis(min, max, w)
}
}
lines = append(lines, fontEntryFor(spec, w, axis))
if spec.serifFallback && w == 400 {
lines = append(lines, serifEntry(spec))
}
}
return " " + spec.openTag + "\n" + strings.Join(lines, "\n") + "\n </family>"
}
// 在完整 XML 中覆写指定家族段; 家族不存在时原样返回
func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap map[int]int) string {
start := findFamilyStart(xml, spec.openTag)
if start < 0 {
return xml
}
end := matchFamilyClose(xml, start+len(spec.openTag))
if end < 0 {
return xml
}
// 字重集选择: 裁切保留原家族声明字重 (兼容设备 XML), 平均分配固定 9 档完整粗细,
// 自定义映射由映射文件的键决定
weights := Weights
if mode == 1 {
if ex := extractWeights(xml[start:end]); len(ex) > 0 {
weights = ex
}
}
// 整行替换 (含行首缩进与闭合标签后的换行), 保持与原有段一致的缩进
lineStart := start
for lineStart > 0 && xml[lineStart-1] != '\n' {
lineStart--
}
lineEnd := end
for lineEnd < len(xml) && xml[lineEnd] != '\n' {
lineEnd++
}
if lineEnd < len(xml) {
lineEnd++ // 吃掉换行
}
return xml[:lineStart] + generateFamily(spec, weights, min, max, mode, customMap) + "\n" + xml[lineEnd:]
}
// 覆写全部生效家族 (mode 0 原样返回)
func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string {
if mode == 0 {
return xml
}
result := xml
for _, spec := range FamilySpecs {
result = replaceFamily(result, spec, mode, min, max, customMap)
}
return result
}
// 查找 startTag 的位置 (跳过 XML 注释, 避免误匹配注释内的文本)
func findFamilyStart(xml, startTag string) int {
searchFrom := 0
for {
i := strings.Index(xml[searchFrom:], startTag)
if i < 0 {
return -1
}
i += searchFrom
open := strings.LastIndex(xml[:i], "<!--")
if open < 0 {
return i
}
if rel := strings.Index(xml[open:], "-->"); rel < 0 || open+rel+3 > i {
// 命中位置在注释内, 继续向后找
searchFrom = i + 1
continue
}
return i
}
}
// 从紧随 <family ...> 之后的位置开始, 找到配对的 </family> (含嵌套),
// 返回其结束位置 (含标签); 未找到返回 -1
func matchFamilyClose(xml string, start int) int {
depth := 1
i := start
for i < len(xml) {
// 跳过注释
if strings.HasPrefix(xml[i:], "<!--") {
if rel := strings.Index(xml[i:], "-->"); rel >= 0 {
i += rel + len("-->")
continue
}
}
// 找下一个 '<'
lt := strings.IndexByte(xml[i:], '<')
if lt < 0 {
return -1
}
i += lt
if strings.HasPrefix(xml[i:], "</family>") {
depth--
if depth == 0 {
return i + len("</family>")
}
i += len("</family>")
continue
}
if strings.HasPrefix(xml[i:], "<family") {
gt := strings.IndexByte(xml[i:], '>')
if gt < 0 {
return -1
}
// 自闭合 <family .../> 不增加嵌套深度
if xml[i+gt-1] != '/' {
depth++
}
i += gt + 1
continue
}
// 其他标签: 跳到 '>' 之后
gt := strings.IndexByte(xml[i:], '>')
if gt < 0 {
return -1
}
i += gt + 1
}
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{}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Fields(line)
if len(parts) != 2 {
continue
}
w, err1 := strconv.Atoi(parts[0])
v, err2 := strconv.Atoi(parts[1])
if err1 == nil && err2 == nil {
m[w] = v
}
}
return m, nil
}
// ApplyToDir 覆写模块根目录下的主配置 fonts.xml; sync 为 true 时复制到各派生配置
// 返回覆写/同步的文件总数
func ApplyToDir(xmlDir string, mode, min, max int, customMap map[int]int, sync bool) (int, error) {
src := filepath.Join(xmlDir, SourceXMLRel)
data, err := os.ReadFile(src)
if err != nil {
return 0, fmt.Errorf("读取 %s 失败: %w", SourceXMLRel, err)
}
replaced := ApplyWghtMode(string(data), mode, min, max, customMap)
changed := 0
if replaced != string(data) {
if err := os.WriteFile(src, []byte(replaced), 0o644); err != nil {
return changed, fmt.Errorf("写入失败 %s: %w", SourceXMLRel, err)
}
changed++
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
}
+275
View File
@@ -0,0 +1,275 @@
package wght
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// 平均分配公式 (MiSansVF 150-700, 与用户示例一致)
func TestAveragedAxis(t *testing.T) {
want := map[int]int{100: 150, 200: 233, 300: 316, 400: 400, 500: 460, 600: 520, 700: 580, 800: 640, 900: 700}
for w, v := range want {
if got := AveragedAxis(150, 700, w); got != v {
t.Errorf("AveragedAxis(150,700,%d) = %d, want %d", w, got, v)
}
}
}
func extractAttrs(family string) ([]int, []int) {
var ws, axes []int
for _, line := range strings.Split(family, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "<font weight=") {
var w int
if _, err := fmt.Sscanf(line, "<font weight=\"%d\"", &w); err == nil {
ws = append(ws, w)
}
}
if strings.Contains(line, `<axis tag="wght" stylevalue="`) {
var v int
if _, err := fmt.Sscanf(line, "<axis tag=\"wght\" stylevalue=\"%d\"", &v); err == nil {
axes = append(axes, v)
}
}
}
return ws, axes
}
func TestGenerateFamilyTrim(t *testing.T) {
family := GenerateFamily(150, 700, 1, nil)
ws, axes := extractAttrs(family)
want := []int{200, 300, 400, 500, 600, 700}
if len(ws) != len(want) {
t.Fatalf("裁切 weight = %v, want %v", ws, want)
}
for i := range want {
if ws[i] != want[i] || axes[i] != want[i] {
t.Errorf("裁切第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], want[i], want[i])
}
}
}
func TestGenerateFamilyAvg(t *testing.T) {
family := GenerateFamily(150, 700, 2, nil)
ws, axes := extractAttrs(family)
wantW := []int{100, 200, 300, 400, 500, 600, 700, 800, 900}
wantA := []int{150, 233, 316, 400, 460, 520, 580, 640, 700}
if len(ws) != 9 {
t.Fatalf("平均 weight = %v", ws)
}
for i := range wantW {
if ws[i] != wantW[i] || axes[i] != wantA[i] {
t.Errorf("平均第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], wantW[i], wantA[i])
}
}
}
func TestGenerateFamilyCustom(t *testing.T) {
m := map[int]int{150: 180, 250: 300, 400: 400, 700: 650}
family := GenerateFamily(150, 700, 3, m)
ws, axes := extractAttrs(family)
wantW := []int{150, 250, 400, 700}
wantA := []int{180, 300, 400, 650}
for i := range wantW {
if ws[i] != wantW[i] || axes[i] != wantA[i] {
t.Errorf("自定义第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], wantW[i], wantA[i])
}
}
}
func TestApplyWghtMode(t *testing.T) {
xml := "<?xml version=\"1.0\"?>\n<familyset>\n <!-- #ifdef OPLUS_FEATURE_FONT_FLIP -->\n" +
" <family name=\"sans-serif\">\n <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n </font>\n </family>\n" +
" <!-- #endif -->\n</familyset>\n"
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
if !strings.Contains(replaced, "OPLUS_FEATURE_FONT_FLIP") {
t.Error("覆写后 #ifdef 注释丢失")
}
if !strings.Contains(replaced, `stylevalue="233"`) {
t.Error("覆写后缺少平均分配值 233")
}
if strings.Count(replaced, "<family name=\"sans-serif\">") != 1 {
t.Error("sans-serif family 数量异常")
}
// mode 0 原样
if ApplyWghtMode(xml, 0, 150, 700, nil) != xml {
t.Error("mode=0 应原样返回")
}
}
// 所有生效家族 (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) {
xml := "<?xml version=\"1.0\"?>\n<familyset>\n" +
" <!-- #ifdef OPLUS_FEATURE_FONT_FLIP -->\n" +
" <family name=\"sans-serif\">\n" +
" <family name=\"sans-serif-black\">\n" +
" <font weight=\"900\" style=\"normal\">Black.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"900\" />\n" +
" </font>\n" +
" </family>\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n" +
" </font>\n" +
" </family>\n" +
" <!-- #endif -->\n" +
" <family name=\"sans-serif-medium\">\n" +
" <font weight=\"500\" style=\"normal\">Medium.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"500\" />\n" +
" </font>\n" +
" </family>\n" +
"</familyset>\n"
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
// 后续的 sans-serif-medium 段必须完整保留 (嵌套闭合误配会导致其被切掉)
if !strings.Contains(replaced, `<family name="sans-serif-medium">`) {
t.Fatal("覆写后丢失了 sans-serif-medium 段")
}
if strings.Contains(replaced, `<family name="sans-serif-black">`) {
t.Error("sans-serif-black 嵌套段未随段替换被移除")
}
// 闭合标签数量应与开始标签数量一致 (结构完整)
open := strings.Count(replaced, "<family ")
closeN := strings.Count(replaced, "</family>")
if open != closeN {
t.Errorf("family 标签不平衡: open=%d close=%d\n%s", open, closeN, replaced)
}
if !strings.HasSuffix(replaced, "</familyset>\n") {
t.Errorf("文件末尾被破坏:\n%s", replaced)
}
}
// 段首不应被重复缩进 (原行缩进 + 生成段自带缩进)
func TestApplyWghtModeNoDoubleIndent(t *testing.T) {
xml := "<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"
replaced := ApplyWghtMode(xml, 1, 100, 900, nil)
if strings.Contains(replaced, " <family name=\"sans-serif\">") {
t.Errorf("段首出现重复缩进 (8 空格):\n%s", replaced)
}
if !strings.Contains(replaced, " <family name=\"sans-serif\">") {
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)
}
}
}
-6
View File
@@ -1,6 +0,0 @@
id=MyFontModule
name=我的字体模块
version=1.0
versionCode=10
author=Yule
description=我的字体模块
+162
View File
@@ -0,0 +1,162 @@
// 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/SysSans-Hant-Regular.ttf",
"/system/fonts/SysFont-Hant-Regular.ttf",
// 英文 & 数字槽位
"/system/fonts/SysSans-En-Regular.ttf",
"/system/fonts/SysFont-Regular.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"
+33
View File
@@ -0,0 +1,33 @@
{
"name": "fontmm",
"private": true,
"scripts": {
"dev": "pnpm -C web dev",
"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 -d",
"shfmt:fix": "find src -name '*.sh' -print0 | xargs -0 shfmt -i 4 -w",
"go:test": "cd golang && go vet ./... && go test ./...",
"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"
}
}
+23
View File
@@ -0,0 +1,23 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
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': {}
BIN
View File
Binary file not shown.
@@ -0,0 +1,33 @@
#!/sbin/sh
#################
# Initialization
#################
umask 022
# echo before loading util_functions
ui_print() { echo "$1"; }
require_new_magisk() {
ui_print "*******************************"
ui_print " Please install Magisk v20.4+! "
ui_print "*******************************"
exit 1
}
#########################
# Load util_functions.sh
#########################
OUTFD=$2
ZIPFILE=$3
mount /data 2>/dev/null
[ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk
. /data/adb/magisk/util_functions.sh
[ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk
install_module
exit 0
@@ -0,0 +1 @@
#MAGISK
+145
View File
@@ -0,0 +1,145 @@
#!/system/bin/sh
# shellcheck shell=ash
# FontMM apply.sh — 应用字体: 把 FONTS/ 里的字体安装到 system/fonts
# 用法: apply.sh [模块目录] 默认 /data/adb/modules/FontMM
# 回退逻辑: 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'
hant_fonts='SysSans-Hant-Regular.ttf
SysFont-Hant-Regular.ttf'
en_fonts='SysSans-En-Regular.ttf
SysFont-Regular.ttf'
[ -f "$FONTS_DIR/hans.ttf" ] || {
echo "[✗] FONTS/hans.ttf 不存在, 请先在 WebUI 选择字体"
exit 1
}
mkdir -p "$SYS_FONT_DIR"
install_from() {
local src="$1" list="$2" line=""
while IFS= read -r line; do
cp -f "$src" "$SYS_FONT_DIR/$line" || {
echo "[✗] 复制 $line 失败"
exit 1
}
echo "[*] 安装: $line"
done <<EOF
$list
EOF
}
# 准备英文字体: 含 CJK 字形时裁成纯拉丁子集, 否则原样使用 (issue #10)
# 用法: prepare_english_font <源字体> <子集输出路径>
# 成功 (含子集化) 时输出子集路径; 无需处理或工具不可用时返回非 0, 调用方回退原字体。
#
# 不做结果缓存: 实测检测与子集化各约 13-21ms (x86; 设备端同量级),
# 每次重算比维护缓存 (失效判断、陈旧文件清理) 更简单可靠。
prepare_english_font() {
local src="$1"
local out="$2"
local tool="$MODDIR/tools/fontmm-subset"
[ -f "$src" ] || return 1
# 工具缺失 (旧版本模块升级、文件被删): 跳过, 用原字体
if [ ! -x "$tool" ]; then
echo "[-] 未找到字体子集化工具, 跳过英文子集化"
return 1
fi
# 先检测是否含 CJK: 不含则无需处理 (常见情况, 无额外开销)
# 退出码: 0=不含 CJK, 1=含 CJK, 2=文件无效/读取失败, 126/127=工具无法执行
# 只有明确返回 1 (含 CJK) 才做子集化; 其余情况一律跳过,
# 避免工具损坏时还去调用一次子集化 (那样会误报「子集化失败」)
"$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 ! "$tool" -in "$src" -out "$out" 2>&1; then
# 子集化失败不阻断安装: 退回原字体, 并提示可能出现的问题
echo "[!] 子集化失败, 使用原字体 (中文可能被英文字体的字形覆盖)"
rm -f "$out"
return 1
fi
echo "[✓] 已生成子集, 汉字字形不再覆盖中文字体"
return 0
}
echo "[*] 安装简体字体..."
install_from "$FONTS_DIR/hans.ttf" "$hans_fonts"
echo "[*] 处理繁体字体..."
if [ -f "$FONTS_DIR/hant.ttf" ]; then
install_from "$FONTS_DIR/hant.ttf" "$hant_fonts"
else
echo "[-] 未设置繁体, 回退使用简体"
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
fi
# 英文槽位: 若 en.ttf 自带 CJK 字形需先子集化 (issue #10)
# fonts.xml 中 sans-serif / sys-sans-en 排在 zh-Hans / zh-Hant 之前, 因此 en.ttf
# 里的汉字字形会被用于中文渲染, 盖掉 hans.ttf / hant.ttf, 表现为「中文没换干净」。
# Android 的 fonts.xml 无法限定字体只负责英文, 所以只能在应用前把 CJK 裁掉。
echo "[*] 处理英文&数字..."
EN_SUBSET="$FONTS_DIR/.en-subset.ttf"
EN_SRC="$FONTS_DIR/en.ttf"
if [ ! -f "$FONTS_DIR/en.ttf" ]; then
echo "[-] 未设置英文, 回退使用简体"
rm -f "$EN_SUBSET" # 清理上一次留下的子集, 避免残留
# 未选西文时仍用简体覆盖英文槽位; 西文字体在 fonts.xml 中排最前,
# 简体仅在缺字形时兜底 (issue #6)
install_from "$FONTS_DIR/hans.ttf" "$en_fonts"
else
# 子集化成功则改用子集文件, 否则沿用原字体 (失败不阻断安装)
if prepare_english_font "$FONTS_DIR/en.ttf" "$EN_SUBSET"; then
EN_SRC="$EN_SUBSET"
fi
install_from "$EN_SRC" "$en_fonts"
fi
echo "[*] 处理等宽字体..."
if [ -f "$FONTS_DIR/mono.ttf" ]; then
# 直接替换系统等宽字体 DroidSansMono.ttf (overlay 生效)
install_from "$FONTS_DIR/mono.ttf" 'DroidSansMono.ttf'
else
echo "[-] 未设置等宽字体, 恢复系统等宽字体"
rm -f "$SYS_FONT_DIR/DroidSansMono.ttf"
fi
echo "[*] 处理 Emoji 字体..."
if [ -f "$FONTS_DIR/emoji.ttf" ]; then
# 首次设置前备份模块内嵌的补充字库 NotoColorEmoji.ttf, 供清除时恢复
if [ -f "$SYS_FONT_DIR/NotoColorEmoji.ttf" ] && [ ! -f "$MODDIR/backup/NotoColorEmoji.ttf" ]; then
mkdir -p "$MODDIR/backup"
cp -f "$SYS_FONT_DIR/NotoColorEmoji.ttf" "$MODDIR/backup/NotoColorEmoji.ttf"
fi
# 直接替换系统 emoji 字体 NotoColorEmoji.ttf (overlay 生效)
install_from "$FONTS_DIR/emoji.ttf" 'NotoColorEmoji.ttf'
else
echo "[-] 未设置 Emoji 字体, 恢复默认"
if [ -f "$MODDIR/backup/NotoColorEmoji.ttf" ]; then
cp -f "$MODDIR/backup/NotoColorEmoji.ttf" "$SYS_FONT_DIR/NotoColorEmoji.ttf"
fi
fi
echo "[*] 全部完成, 重启后生效"
+368
View File
@@ -0,0 +1,368 @@
#!/system/bin/sh
# shellcheck shell=ash
# shellcheck disable=SC2034
# FontMM ColorOS 16 — 刷入脚本
# 字体安装统一交给 apply.sh (与 WebUI 共用同一套逻辑)
REPLACE=""
REMOVE=""
# ---------- 路径 ----------
if [ -z "${MODPATH+x}" ]; then
case "$0" in
*/*) MODPATH="${0%/*}" ;;
*) MODPATH="." ;;
esac
fi
MOD_WORK_PATH="$MODPATH/FONTS"
UPDATE_MODE=0
# ---------- 日志 ----------
log() {
local msg="$1"
echo "[-] $msg"
}
log_err() {
local msg="$1"
local code="${2:-1}"
if command -v abort >/dev/null 2>&1; then
abort "$msg"
fi
echo "[✗] $msg"
exit "$code"
}
log_succ() {
local msg="$1"
echo "[*] $msg"
}
log_warn() {
local msg="$1"
echo "[!] $msg"
}
# ---------- 更新模式 ----------
# 检测旧版 FontMM 是否已安装
DETECT_UPDATE_MODE() {
if [ -d /data/adb/modules/FontMM ]; then
UPDATE_MODE=1
log "检测到已安装的 FontMM, 进入更新模式"
else
log "全新安装"
fi
}
# 更新模式: 以旧包为主继承字体
IMPORT_OLD_FONTS() {
[ "$UPDATE_MODE" -eq 1 ] || return 0
local old_fonts="/data/adb/modules/FontMM/FONTS"
if [ ! -d "$old_fonts" ]; then
log "注意: 旧模块中没有 FONTS 目录, 将使用新包字体"
return 0
fi
mkdir -p "$MOD_WORK_PATH"
local f=""
for f in hans.ttf hant.ttf en.ttf mono.ttf emoji.ttf; do
if [ -f "$old_fonts/$f" ]; then
if cp -f "$old_fonts/$f" "$MOD_WORK_PATH/$f"; then
log_succ "已从旧模块继承字体: $f"
else
log_err "继承字体 $f 失败"
fi
else
log "旧包没有 $f, 使用新包字体"
fi
done
}
# ---------- 系统检查 ----------
# 不阻止安装: 非 ColorOS 16 时仅提示兼容性风险
CHECK_COLOROS() {
local oplus_api=""
oplus_api="$(getprop ro.build.version.oplus.api 2>/dev/null || true)"
if [ -z "$oplus_api" ]; then
log_warn "当前系统不是 ColorOS, 可能无法正常替换字体, 存在兼容性风险"
CONFIRM_RISK "当前系统不是 ColorOS" "字体替换可能无法生效, 且可能导致字体渲染异常"
return 0
fi
local oplus_display=""
oplus_display="$(getprop ro.build.version.oplusrom.display 2>/dev/null || true)"
local major="${oplus_display%%.*}"
if [ "${major:-0}" -lt 16 ] 2>/dev/null; then
log_warn "ColorOS 版本过低 (${oplus_display:-未知}), 建议 16.0 及以上, 低版本可能存在兼容性风险"
CONFIRM_RISK "ColorOS 版本过低 (${oplus_display:-未知})" "建议 16.0 及以上, 低版本可能存在兼容性风险"
return 0
fi
log_succ "ColorOS ${oplus_display}"
}
# ---------- 检查元模块 ----------
CHECK_META_MODULE() {
if [ ! -f /data/adb/ksud ]; then
log "非 KernelSU 环境, 跳过元模块检查"
return 0
fi
local ksud_version=""
ksud_version="$(/data/adb/ksud --version 2>/dev/null | tr -d '\r' || true)"
local ver_num
ver_num="$(printf '%s' "$ksud_version" |
grep -o '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*' |
head -n 1 || true)"
log_succ "KernelSU v${ver_num}"
local major="${ver_num%%.*}"
if [ "${major:-0}" -lt 3 ] 2>/dev/null; then
log "KernelSU 版本 ${ver_num:-未知} < 3.0.0, 无需元模块"
return 0
fi
if [ ! -f /data/adb/metamodule/module.prop ]; then
log "警告: KernelSU >= 3.0.0 需要元模块, 请先安装"
return 1
fi
local meta_name=""
meta_name="$(sed -n 's/^name=//p' /data/adb/metamodule/module.prop | head -n 1 || true)"
if [ -n "$meta_name" ]; then
log_succ "元模块已安装: $meta_name"
else
log "元模块已安装 (但读不到 name 字段)"
fi
return 0
}
# ---------- 音量键确认 ----------
# 音量上键确认继续, 音量下键中止安装
btn() {
while :; do
local c
c="$(getevent -qlc 1 2>/dev/null | awk '{ print $3 }')"
case "$c" in
KEY_VOLUMEUP)
echo "0"
return
;;
KEY_VOLUMEDOWN)
echo "1"
return
;;
esac
done
}
# 通用风险确认 (兼容性等场景)
CONFIRM_RISK() {
local reason="$1"
local detail="$2"
echo
log "警告: $reason"
[ -n "$detail" ] && log "$detail"
log "请按音量上键确认继续安装, 按音量下键取消安装。"
if [ "$(btn)" = "1" ]; then
log_err "用户取消安装"
fi
}
# ---------- 判断 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
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 复制与主配置不一致)
if [ -x "$MODPATH/tools/fontmm-wght" ]; then
if "$MODPATH/tools/fontmm-wght" -mode 0 -sync -xml-dir "$MODPATH" >/dev/null 2>&1; then
log "已同步派生字体配置"
else
log "同步派生配置失败 (可忽略, 使用内置副本)"
fi
fi
}
# ---------- 判断 FontLoader ----------
# 本模块已内置字体预加载 (zygisk/arm64-v8a.so), 与外部 FontLoader 模块功能重叠。
# 两者同时启用会重复预热、并可能互相干扰, 因此检测到旧 FontLoader 时建议禁用它。
# 禁用方式: 在其模块目录放置 disable 文件 (模块的通用停用约定, 重启后生效),
# 不删除其数据, 用户可随时移除该文件恢复。
DISABLE_OLD_FONTLOADER() {
local found=""
local hit=""
# 按目录名候选 + 内容特征双重识别:
# - 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
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 [ -n "$found" ]; then
log "本模块已内置字体预加载, 无需外部 FontLoader; 重启后以本模块为准"
fi
}
# ---------- 主流程 ----------
MAIN() {
CHECK_COLOROS
if ! CHECK_META_MODULE; then
log_err "元模块检查不通过"
fi
CHECK_ZYGISK_ENV
DISABLE_OLD_FONTLOADER
echo && log "开始准备字体..."
DETECT_UPDATE_MODE
IMPORT_OLD_FONTS
# 同步派生字体配置 (设备 XML 扫描 + fontmm-wght -sync)
SYNC_FONT_XMLS
# 校验内置的 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"
cp -f "$MODPATH/system/fonts/NotoColorEmoji.ttf" "$MODPATH/backup/NotoColorEmoji.ttf"
fi
echo && log "开始安装字体..."
if sh "$MODPATH/apply.sh" "$MODPATH"; then
echo && log_succ "所有字体安装成功, 重启设备后生效"
else
echo && log_err "字体安装出现问题, 请联系开发者"
fi
}
MAIN
+7
View File
@@ -0,0 +1,7 @@
id=FontMM
name=FontMM
version=26.8.0-beta.8
versionCode=26080008
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
Binary file not shown.
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2018–2022 Cyano Hao
Copyright (c) 2022 Shiroki Satsuki
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Losketch
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
+94
View File
@@ -0,0 +1,94 @@
Copyright 2025 The Noto Project Authors (https://github.com/notofonts)
Copyright 2025 Mercury13 (https://github.com/Mercury13/unicodia)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+91
View File
@@ -0,0 +1,91 @@
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
View File
File renamed without changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+61
View File
@@ -0,0 +1,61 @@
#!/system/bin/sh
# FontMM 工具: 下载国际版小米主题字体并解压提取 (v1.0.0)
# 用法: mi-font-download.sh "<标题>" "<主题ID>" "<URL编码标题>"
# 流程: 详情API取下载地址 -> 下载 .mtz -> 解压提取 fonts/ 目录字体
DOWN_DIR="/storage/emulated/0/Download/xttdown"
DETAILS_API="https://api.zhuti.intl.xiaomi.com/app/v9/uipages/theme/"
DL_BASE="https://f17.market.xiaomi.com/issue/"
TITLE="$1"
ID="$2"
ENCODED="$3"
[ -z "$TITLE" ] || [ -z "$ID" ] || [ -z "$ENCODED" ] && {
echo "[x] 参数不足: <标题> <主题ID> <URL编码标题>"
echo "__DONE__"
exit 1
}
# 文件名安全化
SAFE_TITLE=$(printf "%s" "$TITLE" | tr -c 'A-Za-z0-9._-' '_')
echo "[*] 获取「$TITLE」下载链接..."
DOWN_URL=$(curl -s "${DETAILS_API}${ID}" | sed -n 's/.*"downloadUrl":"\([^"]*\)".*/\1/p' | head -1)
[ -z "$DOWN_URL" ] && {
echo "[x] 获取下载链接失败"
echo "__DONE__"
exit 1
}
DL_URL="${DL_BASE}${DOWN_URL}/${ENCODED}.mtz"
SAVE="${DOWN_DIR}/${SAFE_TITLE}.mtz"
echo "[*] 下载: ${DL_URL}"
mkdir -p "$DOWN_DIR"
if ! curl -sL -o "$SAVE" "$DL_URL" || [ ! -s "$SAVE" ]; then
echo "[x] 下载失败"
echo "__DONE__"
exit 1
fi
echo "[✓] 下载完成: ${SAVE} ($(du -h "$SAVE" | cut -f1))"
EXTRACT_DIR="${DOWN_DIR}/extracted/${SAFE_TITLE}"
echo "[*] 解压 mtz 并提取字体..."
mkdir -p "$EXTRACT_DIR"
unzip -o -j "$SAVE" 'fonts/*' -d "$EXTRACT_DIR" >/dev/null 2>&1
# 收集提取出的字体文件 (ttf/otf)
FONTS=''
for f in "$EXTRACT_DIR"/*.ttf "$EXTRACT_DIR"/*.otf; do
[ -f "$f" ] && FONTS="${FONTS} $(basename "$f")"
done
if [ -n "$FONTS" ]; then
echo "[✓] 提取字体:"
for f in $FONTS; do
echo " ${EXTRACT_DIR}/${f}"
done
else
echo "[-] 未在 mtz 中找到字体文件, 原始包保留在 ${SAVE}"
fi
echo "__DONE__"
+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
+90
View File
@@ -0,0 +1,90 @@
#!/bin/sh
# wght-range.sh - 读取可变字体 wght 轴范围,输出 "min max"
# 用法: sh wght-range.sh <字体.ttf>
font=$1
[ -n "$font" ] || {
echo "usage: sh $0 <font.ttf>" >&2
exit 1
}
[ -f "$font" ] || {
echo "error: file not found: $font" >&2
exit 1
}
# 读 1 字节
byte() {
od -An -tu1 -j "$1" -N1 "$font" 2>/dev/null | tr -d ' '
}
# 读 2 字节大端无符号整数
u16() {
b0=$(byte "$1") || return 1
b1=$(byte "$(($1 + 1))") || return 1
[ -n "$b0" ] && [ -n "$b1" ] || return 1
echo $(((b0 << 8) | b1))
}
# 读 4 字节大端无符号整数
u32() {
b0=$(byte "$1") || return 1
b1=$(byte "$(($1 + 1))") || return 1
b2=$(byte "$(($1 + 2))") || return 1
b3=$(byte "$(($1 + 3))") || return 1
[ -n "$b0" ] && [ -n "$b1" ] && [ -n "$b2" ] && [ -n "$b3" ] || return 1
echo $(((b0 << 24) | (b1 << 16) | (b2 << 8) | b3))
}
# 读 4 字节 ASCII tag
tag4() {
dd if="$font" bs=1 skip="$1" count=4 2>/dev/null
}
num_tables=$(u16 4) || {
echo "error: cannot read font: $font" >&2
exit 1
}
# 在 sfnt 表目录里找 fvar 表
# offset 12 起,每条 16 字节:tag/checksum/offset/length
i=0
fvar_off=
while [ "$i" -lt "$num_tables" ]; do
pos=$((12 + i * 16))
if [ "$(tag4 "$pos")" = "fvar" ]; then
fvar_off=$(u32 "$((pos + 8))")
break
fi
i=$((i + 1))
done
[ -n "$fvar_off" ] || {
echo "error: no fvar table (not a variable font?)" >&2
exit 1
}
axis_off=$((fvar_off + $(u16 "$((fvar_off + 4))")))
axis_count=$(u16 "$((fvar_off + 8))")
axis_size=$(u16 "$((fvar_off + 10))")
# 遍历轴找 wght
# min/max 是 Signed Fixed 16.16,整数部分 = 高 16 位
j=0
while [ "$j" -lt "$axis_count" ]; do
p=$((axis_off + j * axis_size))
if [ "$(tag4 "$p")" = "wght" ]; then
hi=$(u16 "$((p + 4))") # minValue 高 16 位
[ "$hi" -ge 32768 ] && hi=$((hi - 65536))
min=$hi
hi=$(u16 "$((p + 12))") # maxValue 高 16 位
[ "$hi" -ge 32768 ] && hi=$((hi - 65536))
max=$hi
echo "$min $max"
exit 0
fi
j=$((j + 1))
done
echo "error: no wght axis in font" >&2
exit 1
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f54da868866e46a56c39820d34f6f3c4f3d7b0922fe09d3ae938c9bd41e75f41
size 112703062
+6
View File
@@ -0,0 +1,6 @@
{
"versionCode": 26080008,
"version": "v26.8.0-beta.8",
"zipUrl": "https://github.com/YuleBest/FontMM/releases/download/v26.8.0-beta.8/FontMM_v26.8.0-beta.8_template.zip",
"changelog": "https://raw.githubusercontent.com/YuleBest/FontMM/main/changelog.md"
}
+5
View File
@@ -0,0 +1,5 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"singleQuote": true,
"ignorePatterns": []
}
+12
View File
@@ -0,0 +1,12 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["typescript", "unicorn", "oxc"],
"categories": {
"correctness": "error"
},
"rules": {},
"ignorePatterns": ["public/pyodide/**"],
"env": {
"builtin": true
}
}
+413
View File
@@ -0,0 +1,413 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover"
/>
<title>FontMM</title>
</head>
<body>
<!-- Top App Bar (滚动后标题固定在左侧, 右上角重启按钮) -->
<header class="top-app-bar">
<span class="top-app-bar__title" id="top-bar-title"></span>
<div class="top-app-bar__actions">
<md-icon-button id="reboot-btn" aria-label="重启设备">
<md-icon>autorenew</md-icon>
</md-icon-button>
</div>
</header>
<!-- 滑动视图轨道 (三页横排, 切换/手势滑动) -->
<div class="view-track" id="view-track">
<!-- 主页视图 -->
<main id="home-view" class="view view-home active">
<div class="home-title">FontMM</div>
<!-- 模块状态 -->
<md-elevated-card class="home-card home-status-card">
<div class="home-status-icon">
<md-icon>check</md-icon>
</div>
<div class="home-status-text">
<div class="home-status-title" id="home-status">已挂载字体</div>
<div class="home-status-sub">版本 <span id="home-version">-</span></div>
</div>
</md-elevated-card>
<!-- 请我喝咖啡 -->
<md-elevated-card class="home-card home-entry-card" id="donate-card">
<div class="home-entry-row" id="donate-entry">
<div class="home-entry-icon">
<md-icon>coffee</md-icon>
</div>
<div class="home-entry-text">
<div class="home-entry-title">请我喝咖啡</div>
<div class="home-entry-sub">FontMM 将保持免费开源</div>
</div>
<md-icon class="home-entry-arrow" id="donate-arrow">expand_more</md-icon>
</div>
<div class="home-entry-expand" id="donate-expand" hidden>
<div class="home-donate-note">感谢您的自愿捐献</div>
<div class="home-donate-row">
<button class="home-donate-item" id="donate-alipay">
<span class="home-donate-logo">支付宝</span>
</button>
<button class="home-donate-item" id="donate-ifdian">
<span class="home-donate-logo">爱发电</span>
</button>
</div>
</div>
</md-elevated-card>
<!-- 开发者 -->
<md-elevated-card class="home-card home-entry-card">
<div class="home-entry-row" id="dev-entry">
<div class="home-entry-icon">
<md-icon>code</md-icon>
</div>
<div class="home-entry-text">
<div class="home-entry-title">开发者</div>
<div class="home-entry-sub">Yule</div>
</div>
<md-icon class="home-entry-arrow">chevron_right</md-icon>
</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-android-version">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">设备型号</div>
<div class="home-info-value" id="home-device-model">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">系统架构</div>
<div class="home-info-value" id="home-abi">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">已安装字体</div>
<div class="home-info-value" id="home-font-count">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">元模块</div>
<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>
<!-- 配置视图 -->
<main id="config-view" class="view view-config">
<div class="home-title">字体配置</div>
<div id="slots"></div>
<!-- 高级配置 (可折叠/展开) -->
<md-filled-card class="wght-advanced">
<div class="wght-advanced-header" id="wght-advanced-header">
<div class="wght-advanced-title">高级配置</div>
<md-icon class="wght-advanced-arrow">expand_more</md-icon>
</div>
<div class="wght-advanced-body">
<div class="wght-advanced-content">
<div class="wght-mode-row">
<div class="wght-mode-info">
<div class="wght-mode-title">字重覆写模式</div>
<div class="wght-mode-sub" id="wght-mode-sub">
可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置
</div>
</div>
<md-outlined-select id="wght-mode-select" label="覆写模式">
<md-select-option value="0" selected>不处理</md-select-option>
<md-select-option value="1">裁切粗细等级</md-select-option>
<md-select-option value="2">平均分配字重</md-select-option>
<md-select-option value="3">自定义映射</md-select-option>
</md-outlined-select>
</div>
<!-- 字重映射 (各模式实时预览, 修改即切为自定义) -->
<div class="wght-map" id="wght-map">
<div class="wght-map-inner">
<div class="wght-map-title">字重映射</div>
<div class="wght-map-sub">
各模式的实时映射结果 (字重等级 → wght 轴值),
修改任意值将自动切换为「自定义映射」
</div>
<div id="wght-map-rows"></div>
<div class="wght-map-footer">
<md-text-button id="wght-map-add" class="wght-map-add">
<md-icon slot="icon">add</md-icon>
新增映射
</md-text-button>
<div class="wght-map-toolbar">
<md-icon-button id="wght-map-undo" aria-label="撤销">
<md-icon>undo</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-export" aria-label="导出映射">
<md-icon>file_upload</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-import" aria-label="导入映射">
<md-icon>file_download</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-reset" aria-label="重置映射">
<md-icon>restart_alt</md-icon>
</md-icon-button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 新增字重映射对话框 -->
<md-dialog id="wght-map-add-dialog">
<div slot="headline">新增字重映射</div>
<div slot="content">
<input
type="number"
id="wght-map-add-weight"
class="wght-map-input wght-map-add-input"
min="1"
max="1000"
placeholder="字重等级 (1-1000)"
/>
</div>
<div slot="actions">
<md-text-button id="wght-map-add-cancel">取消</md-text-button>
<md-text-button id="wght-map-add-confirm">添加</md-text-button>
</div>
</md-dialog>
<!-- 映射导入/导出对话框 (base64 JSON 文本) -->
<md-dialog id="wght-map-transfer-dialog">
<div slot="headline" id="wght-map-transfer-title">导出映射</div>
<div slot="content">
<div class="wght-map-transfer-note" id="wght-map-transfer-note"></div>
<textarea
id="wght-map-transfer-input"
class="wght-map-transfer-input"
rows="4"
spellcheck="false"
></textarea>
</div>
<div slot="actions">
<md-text-button id="wght-map-transfer-cancel">取消</md-text-button>
<md-text-button id="wght-map-transfer-confirm">关闭</md-text-button>
</div>
</md-dialog>
</md-filled-card>
</main>
<!-- 字体测试视图 -->
<div id="test-view" class="view view-test">
<div class="home-title">字体测试</div>
<md-elevated-card class="test-status-card" id="test-status">
<div class="test-status-icon">
<md-icon>info</md-icon>
</div>
<div class="test-status-text" id="test-status-text">正在加载字体...</div>
</md-elevated-card>
<div id="test-content" class="test-content" hidden>
<md-elevated-card class="test-card test-card-editable" data-edit-target="test-hans">
<div class="test-section-title">
中文简体 <span class="test-tag" id="hans-tag"></span>
</div>
<div class="test-sample test-sample-hans" id="test-hans">
天地玄黄,宇宙洪荒。日月盈昃,辰宿列张。寒来暑往,秋收冬藏。ABCDE 12345
</div>
</md-elevated-card>
<md-elevated-card class="test-card test-card-editable" data-edit-target="test-hant">
<div class="test-section-title">
中文繁体 <span class="test-tag" id="hant-tag"></span>
</div>
<div class="test-sample" id="test-hant">
天地玄黃,宇宙洪荒。日月盈昃,辰宿列張。寒來暑往,秋收冬藏。ABCDE 12345
</div>
</md-elevated-card>
<md-elevated-card class="test-card test-card-editable" data-edit-target="test-en">
<div class="test-section-title">
英文 & 数字 <span class="test-tag" id="en-tag"></span>
</div>
<div class="test-sample" id="test-en">
The quick brown fox jumps over the lazy dog. 0123456789
</div>
</md-elevated-card>
<md-elevated-card class="test-card">
<div class="test-section-title">字重<span class="test-tag" id="weight-tag"></span></div>
<div class="test-var-note">
若各字重显示相同,说明字体为静态单字重或未包含对应字重。
</div>
<div class="test-w-row" style="font-weight: 100">
<span class="test-w-text">100 - 淡体 Thin</span>
</div>
<div class="test-w-row" style="font-weight: 200">
<span class="test-w-text">200 - 特细 ExtraLight</span>
</div>
<div class="test-w-row" style="font-weight: 300">
<span class="test-w-text">300 - 细体 Light</span>
</div>
<div class="test-w-row" style="font-weight: 400">
<span class="test-w-text">400 - 标准 Regular</span>
</div>
<div class="test-w-row" style="font-weight: 500">
<span class="test-w-text">500 - 适中 Medium</span>
</div>
<div class="test-w-row" style="font-weight: 600">
<span class="test-w-text">600 - 次粗 SemiBold</span>
</div>
<div class="test-w-row" style="font-weight: 700">
<span class="test-w-text">700 - 粗体 Bold</span>
</div>
<div class="test-w-row" style="font-weight: 800">
<span class="test-w-text">800 - 特粗 ExtraBold</span>
</div>
<div class="test-w-row" style="font-weight: 900">
<span class="test-w-text">900 - 浓体 Black</span>
</div>
</md-elevated-card>
<md-elevated-card class="test-card">
<div class="test-section-title">
可变字体<span class="test-tag" id="var-tag"></span>
</div>
<div class="test-var-note">
拖动滑条调整字重,停止滑动后应用;仅对可变字体 (VF) 生效,静态字体下无变化。
</div>
<div class="test-wght-row">
<span class="test-wght-label">字重</span>
<md-slider
id="wght-slider"
min="100"
max="900"
step="1"
value="400"
aria-label="字重滑条"
></md-slider>
<span class="test-wght-value" id="wght-value">400</span>
</div>
<div class="test-wght-row">
<span class="test-wght-label">字号</span>
<md-slider
id="size-slider"
min="12"
max="40"
step="1"
value="16"
aria-label="字号滑条"
></md-slider>
<span class="test-wght-value" id="size-value">16</span>
</div>
<div class="test-var-preview" id="test-var-preview">400 - 标准 Regular</div>
</md-elevated-card>
</div>
</div>
<!-- 工具视图 -->
<div id="tools-view" class="view view-tools">
<!-- 工具列表 (ToolHost 渲染卡片) -->
<div id="tools-list">
<div class="home-title">工具</div>
<div id="tools-grid"></div>
</div>
<!-- 工具页面挂载点 (打开工具时由 ToolHost 渲染) -->
<div id="tools-pages"></div>
</div>
</div>
<!-- 悬浮应用按钮 (仅配置页, 向下滚动时隐藏) -->
<button id="apply-btn" class="fab" disabled aria-label="应用字体">
<md-icon>check_circle</md-icon>
<span>应用</span>
</button>
<!-- 测试文本编辑对话框 -->
<md-dialog id="edit-text-dialog">
<div slot="headline">编辑测试文本</div>
<div slot="content">
<md-outlined-text-field
id="edit-text-input"
type="textarea"
rows="3"
label="测试文本"
style="width: 100%"
></md-outlined-text-field>
</div>
<div slot="actions">
<md-text-button id="edit-text-cancel">取消</md-text-button>
<md-text-button id="edit-text-save">保存</md-text-button>
</div>
</md-dialog>
<!-- 重启确认对话框 -->
<md-dialog id="reboot-dialog">
<div slot="headline">重启设备?</div>
<div slot="content">重启后字体才会生效,确定要立即重启设备吗?</div>
<div slot="actions">
<md-text-button id="reboot-cancel">取消</md-text-button>
<md-text-button id="reboot-confirm">重启</md-text-button>
</div>
</md-dialog>
<!-- 日志弹窗 -->
<md-dialog id="log-dialog">
<div slot="headline">应用日志</div>
<div slot="content">
<pre
id="log-content"
style="white-space: pre-wrap; font-family: monospace; font-size: 0.8rem"
></pre>
</div>
<div slot="actions">
<md-text-button id="log-close">关闭</md-text-button>
</div>
</md-dialog>
<!-- 底部导航栏 -->
<nav class="bottom-nav">
<md-navigation-bar id="nav-bar" active-index="0">
<md-navigation-tab label="主页">
<md-icon slot="active-icon">home</md-icon>
<md-icon slot="inactive-icon">home</md-icon>
</md-navigation-tab>
<md-navigation-tab label="配置">
<md-icon slot="active-icon">tune</md-icon>
<md-icon slot="inactive-icon">tune</md-icon>
</md-navigation-tab>
<md-navigation-tab label="字体测试">
<md-icon slot="active-icon">text_fields</md-icon>
<md-icon slot="inactive-icon">text_fields</md-icon>
</md-navigation-tab>
<md-navigation-tab label="工具">
<md-icon slot="active-icon">build</md-icon>
<md-icon slot="inactive-icon">build</md-icon>
</md-navigation-tab>
</md-navigation-bar>
</nav>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+31
View File
@@ -0,0 +1,31 @@
{
"name": "fontmm-webui",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"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",
"fmt:check": "oxfmt --check",
"type-check": "tsc --noEmit"
},
"dependencies": {
"@material/web": "^2.4.1",
"fast-xml-parser": "^5.10.1",
"kernelsu": "^3.0.2",
"material-symbols": "^0.28.0",
"opentype.js": "^2.0.0",
"pyodide": "^314.0.3"
},
"devDependencies": {
"oxfmt": "^0.61.0",
"oxlint": "^1.76.0",
"sass": "^1.86.0",
"typescript": "^5.8.0",
"vite": "^6.0.11"
}
}
+1494
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
allowBuilds:
'@parcel/watcher': true
esbuild: true
BIN
View File
Binary file not shown.
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();
+84
View File
@@ -0,0 +1,84 @@
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 { applyBtn } from './dom';
import { FONTS_DIR } from './constants';
const logDialog = document.getElementById('log-dialog') as any;
const logContent = document.getElementById('log-content')!;
document.getElementById('log-close')?.addEventListener('click', () => {
logDialog.open = false;
});
async function apply() {
if (!slots.hans.path) 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);
}
// 启动加载的字体 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`);
}
} 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`)}`);
}
const { errno, stdout, stderr } = await exec('sh /data/adb/modules/FontMM/apply.sh');
if (errno !== 0) throw new Error(stderr || 'apply.sh 执行失败');
if (logContent && logDialog) {
logContent.textContent = stdout;
logDialog.open = true;
}
toast('字体已应用,重启后生效');
// 字体已变化: 下次进入测试页时重新加载
invalidateTestFonts();
} catch (e) {
toast(`应用失败: ${String(e)}`);
} finally {
setApplying(false);
renderSlots();
}
}
applyBtn?.addEventListener('click', apply);
+13
View File
@@ -0,0 +1,13 @@
// 全局路径与外部链接常量
export const FONTS_DIR = '/data/adb/modules/FontMM/FONTS';
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';
// 捐献 (支付宝/爱发电) 与开发者主页 (浏览器) 链接
export const DONATE_ALIPAY_URI =
'alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/2m615805eflrafv8ipc2p15';
export const ALIPAY_PKG = 'com.eg.android.AlipayGphone';
export const DONATE_IFDIAN_URL = 'https://www.ifdian.net/a/xiaoyule';
export const DEV_PROFILE_URL = 'https://github.com/YuleBest';
+3
View File
@@ -0,0 +1,3 @@
// 跨模块共享的 DOM 元素引用
export const applyBtn = document.getElementById('apply-btn') as HTMLButtonElement;
export const rebootBtn = document.getElementById('reboot-btn');
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more