34 Commits
  • fix: 识别 KernelSU/Sukisu 内置 Zygisk
    首页字体预热器与刷入时的 CHECK_ZYGISK_ENV 此前仅识别 Magisk 内置
    Zygisk 与 Zygisk Next / ReZygisk 等独立提供者, 无法识别 KernelSU /
    Sukisu 内置 Zygisk, 导致首页误报「未检测到可用的 Zygisk 环境」。
    在现有识别均未命中时, 检查 /data/adb/ksu/.builtin_zygisk 是否存在,
    存在则识别为「管理器内置 Zygisk」。
  • chore: 发布 v26.8.0-beta.10 (26080010)
    beta.9 已撤回 (固定行距字距导致开机失败), 其 release 已删除但 update.json 仍指向它,
    用户检查更新会拿到 404 的 zipUrl。这里直接发 beta.10: 版本号前移、update.json 指向
    新 release、changelog 重写为与 beta.8 的对比 (含 #12-#16 修复与行距功能移除),
    不再保留 beta.9 条目。
  • revert(metrics): 移除固定行距字距功能, 不再改动字体本身 (issue #17)
    实测只要在 WebUI 改动「固定行距 & 字距」就会触发开机失败, 把设置恢复默认同样触发,
    不动该设置则一切正常; beta.9 已因此撤回。为保险起见整套功能删除:
    
    - apply.sh: 删掉 unify_one / MANAGED_FONTS 与 metrics.txt、line-height.txt 读取
    - fontmm-subset: 删掉 -line-metrics 模式 (sfnt/字体集合解析与 hhea/OS-2/head 改写)
    - WebUI: 删掉高级配置里的开关与档位, 以及 dev 模式的伪 exec 分支
    - customize.sh: 设置继承清单去掉 metrics.txt / line-height.txt
    - README / DEVELOPMENT / dev/ci.mjs 同步移除相关章节与检查
  • fix(webui): 清空槽位后字重映射的轴范围不刷新
    字重映射的 wght 轴范围取自各槽位可变字体里跨度最小的那个 (pickWghtRange), 而
    「清空槽位」只清了 path/fileName, 解析出来的 isVariable/wghtRange 留了下来 ——
    于是删掉 200-900 的字体后, 范围仍被限制在 200-900, 可变字体标记也残留。
    
    清空时一并重置 sizeText / isVariable / wghtRange / subsetSizeText:
    - 映射范围回到剩余可变字体的范围 (renderSlots 会触发 slots-rendered 重绘映射行)
    - 大小、可变字体徽标、英文子集徽标不会停留在已删除的字体上
    
    浏览器实测: 选中 100-900(简) + 200-700(英) 后映射限制在 200-700, 清掉英文字体后
    恢复为 100-900, 简体的可变字体状态保持正确。
  • fix(metrics): 去掉度量载体, 只保留字体行距统一 (issue #17)
    实测定位: 删掉 fonts.xml 里那段度量载体引用就能正常开机, 保留槽位字体 (同样被改了度量
    与包围盒) 也能开机 —— 即问题出在那个合成载体字体本身, 而「统一字体行距度量」这条路是
    安全的。载体只影响 paint 度量那一侧, 对行距贡献次要, 因此整个移除:
    
    - 删除 src/system/fonts/FontMM-Metrics.ttf 与其许可文本
    - fontmm-wght: 移除 -metrics 开关与载体条目插入/移除逻辑 (ApplyMetrics/ResolveMetrics
      等), ApplyToDir 回到原签名; 相应单测删除
    - fontmm-subset: 移除用来挖空载体的 -metrics 模式 (保留 -line-metrics)
    - apply.sh: 只做「按开关与档位统一装入字体的行距 + 收紧包围盒」, 不再插任何字体条目;
      也不再调用 fontmm-wght 做同步 (字重覆写由 WebUI 直接调用, 该调用已冗余)
    - ci.mjs: 载体相关校验改为「开关与档位文件一致 (apply.sh / WebUI)」
    - 文档同步, 并把这次的坑写进 DEVELOPMENT (合成度量载体在设备上会导致开机失败)
    
    保留并新增的安全措施:
    - -line-metrics 改写后回读自检 (harfbuzz 重新解析 + 度量比对), 不通过就拒绝写出、保留原字体
    - 逃生开关: FONTS/.no-tighten-ink 存在时只统一度量、不动包围盒 (便于实机二分)
    
    端到端实测 (你的 Sarasa 字体 + Noto CJK 集合): 装入后 hhea=1161/-289 (1.45 em)、
    head 包围盒由 y[-1048,1808] 收紧到 y[-289,1161], 段落上下空白归零; fonts.xml 中已无
    任何载体引用。
  • fix(metrics): 收紧 head 包围盒, 消除段落上下多出来的空白 (issue #17)
    用户实测仍不正常, 拿到问题字体后定位到: 它的 hhea/OS2 已被统一到 1.45 em, 但
    head 包围盒是 2.856 em (y[-1048,1808]), 于是每段多出约 1.4 em 空白。
    
    机制: 段落上下的空白不是行距, 而是 includeFontPadding (默认开启) 用
    StaticLayout 的 mTopPadding = above - top / mBottomPadding = bottom - below 撑出来的,
    其中 top/bottom 是 Skia 的 SkFontMetrics.fTop/fBottom, 取自 head 表的包围盒 —— 与
    hhea/OS2 无关。包围盒被极少数大字形撑大的字体就会顶着这圈虚高空白。
    
    - -line-metrics 顺带把 head.yMin/yMax **只收紧、不放大**到行距盒
      (yMax <= ascent, yMin >= descender); 正常字体 (包围盒本就在行距盒内) 不动
    - head 的目录校验和按 checkSumAdjustment 归零计算, 与该表自身约定一致
    - 工具输出追加 ink_y=<旧>, 便于在日志里核对
    - 实测问题字体: hhea 1.45 em 时段落上/下空白 647/759 (千分比 em) -> 归零;
      改写后表校验和与 head.checkSumAdjustment 全部通过, FreeType/harfbuzz 正常解析
    
    文档补充该机制 (DEVELOPMENT) 与用户说明 (README)。
  • fix(metrics): 行距统一支持字体集合 (.ttc/.otc) 并逐字体回显结果 (issue #17)
    实测反馈: 某个字体的段高仍然离谱。原因是它作为字体集合 (.ttc/.otc) 被 -line-metrics
    直接跳过 —— 而中文场景里 .ttc 相当常见, 跳过就等于没统一。
    
    - sfntFaces(): 解析 ttcf 头, 逐个 face 处理; 按表偏移去重, 集合内多个 face 共享的
      hhea/OS2 只改一次 (否则会把已缩放的度量再缩一次)
    - 表校验和: 更新所有引用被改表的目录项 (集合里可能多个 face 指向同一张表)
    - head.checkSumAdjustment: 先把所有 head 的该字段归零再对全文件求和一次, 写回同一个值
      (原先逐个 head 累加, 集合多 head 时会算错)
    - apply.sh: 逐字体回显旧/新度量 (upem 不同则数值不同, 看 em 占比), 失败时带上工具输出;
      跳过 0 字节占位文件
    - 补充字库 (Plangothic/Tibetan/Braille 等) 有意不参与统一: 用户字体通常已覆盖日常用字,
      为极少数生僻字每次应用多写 100MB+ 不划算, 且它们字形本就高, 压低会叠行
    
    验证: .ttc (Noto CJK, 5 face 共享表) 与单体字体改写后表校验和、head 调整值全部通过,
    FreeType 正常解析; 端到端跑 apply.sh: 装入的 .ttc 字体由 1160/-288 变为 1161/-289
    (1.45 em), 各 upem 字体按同一 em 占比统一。
  • feat(metrics): 统一字体行距度量 + 档位可选, 让固定行距真正生效 (issue #17)
    上一版只在家族首位放了度量载体, 实测无效: Android 的行高是「paint 度量」与「该行
    实际使用字体度量」的**并集** (StaticLayout: lineAscent = min(两者), descent 取 max),
    只能抬高不能压低 —— 载体 1.171em 压不住比它高的字体, 等于没起作用。
    
    - fontmm-subset 新增 -line-metrics: 把字体 hhea/OS2 的行距按比例缩放到统一总量
      (上下比例保持不变, lineGap 归零, 避免基线跳变与文字重叠), 只改度量字段, 字形 /
      hmtx / 布局表原样保留, 表长度不变; 重算 hhea / OS2 的表校验和与
      head.checkSumAdjustment。实测 1020/-300 (1.32em) -> 927/-273 (1.20em),
      2048 upem 的字体按同一 em 比例换算成 1959/-498
    - apply.sh: 开关打开时统一装入 system/fonts 的字体 (8 个槽位目标 + DroidSansMono +
      NotoColorEmoji) 与度量载体的行距; FONTS/ 里的原始字体不动; 字体集合 (.ttc) 跳过
      且不阻断安装
    - 行距档位可选 (千分比 em): 紧凑 1200 / 标准 1450 / 宽松 1600, 存 FONTS/line-height.txt;
      WebUI 高级配置新增档位选择, 开关关闭时置灰; 开关与档位改动即落盘 (便于模块更新继承)
    - customize.sh 继承 line-height.txt
    - ci.mjs: 增加档位缺省值与 WebUI 常量的一致性检查; 「占位映射」检查改为显式排除直接
      替换的系统字体 (原先靠「单行/多行」启发式, 新增多行清单会误判为占位文件)
    - README / DEVELOPMENT 同步, 含已知限制 (生僻字 fallback 不参与统一、.ttc 跳过、
      DenyList 应用回退到字体自身度量)
  • refactor(metrics): 度量载体改为内置 Roboto Flex, 去掉设备端生成 (issue #17)
    原方案在设备上按候选列表挖空系统字体, 依赖设备端字体文件名与是否存在, 既复杂又脆。
    改为从 Google Fonts 取 Roboto Flex 裁出只有度量的载体 (1.79MB -> 16KB) 直接入库:
    
    - src/system/fonts/FontMM-Metrics.ttf: 度量 1900/-500 (upem 2048) = 1.171 em,
      即 AOSP Roboto 拉丁基线; 字符集只剩 U+0020/U+00A0; OFL-1.1 且无保留字体名,
      许可文本随包附上 (LICENSE-OFL-RobotoFlex)
    - apply.sh 只引用该文件并按开关调 fontmm-wght 插/移条目, 设备端不再生成字体:
      删掉候选字体列表、挖空步骤与相应失败分支; 关闭开关也不再删载体 (它是模块自带文件)
    - fontmm-subset -metrics 保留为维护端工具, 重新生成命令写进 DEVELOPMENT.md
    - dev/ci.mjs 增加「载体文件必须存在」与「不得被占位脚本清空」两项检查
    - README / DEVELOPMENT 措辞同步
  • feat: 固定行距/字距, 用系统字体挖出度量载体 (close #17)
    安卓的行高取 Paint 度量与「该行实际使用字体」度量的并集, 而 Paint 度量来自
    typeface 家族里与请求字重最接近的条目 (hwui Paint::getMetricsInternal ->
    Minikin FontCollection::baseFontFaked; StaticLayout 再取 min(ascent)/max(descent))。
    本模块 fonts.xml 中 sans-serif 首位正是英文槽位字体, 因此换英文字体时连中文行距
    都会跟着变。
    
    - fontmm-subset 新增 -metrics: 把现成字体「挖空」, 只留 hhea/OS2 度量与
      U+0020/U+00A0/U+3000 空格字形。实测 Noto CJK 19.6MB -> 2.2KB, 度量 1160/-288
      原样保留, 字符集只剩三个空格码点
    - apply.sh: 开关打开时按优先级取系统自带且未被本模块覆盖的字体 (Noto CJK,
      退回 Roboto) 挖空成 system/fonts/FontMM-Metrics.ttf, 再调 fontmm-wght 插入条目;
      关闭时删除载体; 找不到来源字体则跳过 (功能降级, 不影响字体安装)
    - fontmm-wght 新增 -metrics on|off|auto: 在 4 个生效家族首位插入 9 档字重的载体
      条目 —— 必须覆盖全部字重, 否则粗体等字重仍会落到用户字体上。幂等 (先移除再插入),
      关闭能把 XML 逐字节还原, 载体文件不存在时不插入 (避免引用缺失字体)
    - WebUI: 高级配置新增「固定行距 & 字距」开关, 开关存 FONTS/metrics.txt, 应用时下发
    - customize.sh 顺带继承 wght-mode.txt / wght-map.txt / metrics.txt: 模块更新会重建
      整个模块目录, 此前字重模式与自定义映射每次都要重设
    - dev/ci.mjs 增加载体文件名与开关文件名的跨文件一致性检查
    
    验证: Go 单测覆盖插入/移除/幂等/与字重覆写叠加/auto 解析/缺文件跳过; 用同一份
    源码编出宿主端工具跑通 apply.sh 全流程 (生成 2.2KB 载体、36 条条目写入 XML、
    关闭后与原始 XML 逐字节一致); 浏览器实测开关切换与读写往返。
  • feat(webui): 展示英文字体子集化结果 (close #14)
    英文字体自带中文字形时, apply.sh 会先裁成纯拉丁子集再安装 (issue #10), 但
    WebUI 上仍显示原字体大小、也没有任何标记, 看起来像裁切没生效。
    
    - 新增英文子集大小读取: 读 FONTS/.en-subset.ttf, 且要求它比 en.ttf 新
      (换过英文字体但还没重新应用时, 旧子集不该继续展示)
    - 英文槽位卡片改为「原大小 → 子集大小」并加「已子集化」徽标; 子集常在
      百 KB 量级, 小于 1MB 时改用 KB, 否则会显示成 0.2 MB 看不出量级
    - 应用完成后自动刷新该状态; 重新选择英文字体时先撤下徽标 (它描述的是
      上次应用的结果, 不是当前选择的)
    - apply.sh 未使用子集时清掉残留的子集文件, 使该文件的存在即代表本次应用
      确实用了子集
  • docs(webui): 可变字体滑条说明改为「仅预览」措辞 (close #15)
    原文案「停止滑动后应用」容易被读成会修改系统字重, 实际只作用于字体测试页
    的预览。改为明确说明仅影响本页预览、不修改系统字体。
  • fix(webui): 编辑测试文本时输入框出现空行 (close #16)
    测试文本节点的 textContent 含 HTML 标签间的缩进与换行, 原样填入文本域后
    会显示成首尾各一个空行。填入前 trim 掉。
  • fix(webui): 字体选择器返回跳两层、在非 Download 目录选字体无效 (close #13)
    选择器的对话框 DOM 是单例 (按 id 复用), 但配置页与字体编辑页各自 new 了
    一个 FontFilePicker。第二个实例命中已有 DOM 时 initDialog 直接返回, 因此
    返回/取消按钮的监听仍属于第一个实例: 返回键按第一个实例的过期路径导航
    (从 Download 返回会退到 /storage, 看起来跳了两级), 重新渲染后列表项的
    回调也变成第一个实例的, 于是选中文件只更新配置页槽位、编辑页收不到。
    
    改为全局唯一实例, 选中回调改由 show() 每次传入 (每次打开的意图本就不同),
    列表点击改用事件委托只绑定一次, 不再逐次渲染重复挂监听。
  • fix: 工具在刷入后为 0644 导致找不到子集化工具 (close #12)
    KernelSU 解压模块时不保留 zip 内记录的执行位, 安装后 tools/ 下全是 0644。
    apply.sh 用 [ -x ] 判断子集化工具是否可用, 因此恒为假, 每次都提示
    「未找到字体子集化工具」并跳过英文子集化; customize.sh 里 fontmm-wght
    的 -x 判断同样失效, 刷入时不会同步派生字体配置。
    
    改为按文件存在判断, 执行前临时 chmod 0755, 执行后立即还原 0644, 不长期
    留下可执行文件。WebUI 调用 fontmm-wght 原本就 chmod +x, 一并补上用后还原
    (并保留工具自身的退出码, 不被还原动作覆盖)。
    
    实测: 工具为 0644 时可正常检出 CJK 并生成子集, 运行后权限仍为 0644;
    工具缺失时与修复前一致回退原字体, 不阻断安装。
  • fix(webui): 只选中文字体时槽位与字重覆写状态全部消失 (close #11)
    报告: 从 beta5 升级到 beta7 后, 只设置中文字体时, WebUI 槽位不显示已加载
    的字体名称, 字重覆写模式也变灰不可用; 实际字体已生效。
    
    根因是 beta.7 引入的回归。WebUI 打开时会执行一段多行脚本, 把 FONTS/ 下的
    槽位字体逐个复制到 webroot 供名称解析:
    
      [ -f '.../hans.ttf' ] && cp -f ... hans.ttf
      [ -f '.../hant.ttf' ] && cp -f ... hant.ttf
    
    改成逐槽位复制时没注意到 shell 的退出码语义: [ -f ] 条件失败会使该行以
    非 0 结束, 而 exec 只看整段退出码 -- 最后一个槽位不存在时整段就是非 0。
    用户只选中文字体, hant/en/mono/emoji 四行全部失败, 于是 WebUI 误判为
    "复制失败", 把所有槽位当空处理: 名称不显示、可变字体信息丢失、字重覆写
    因"无可变字体"而禁用。与报告现象完全吻合 (beta5 用 cp 通配符复制, 通配符
    总能正常结束, 所以没这个问题)。
    
    修法: 脚本末尾补一行 ':', 兜底整体退出码为 0。已验证三种场景 (只有
    hans / 五槽位齐全 / FONTS 为空) 退出码均为 0 且复制结果正确。
  • fix(zygisk): 修正提供者检测误将普通 Zygisk 模块识别为提供者
    报告: 安装了 Zygisk Next (模块 ID zygisksu), 但检测到的是另一个模块
    Hide My Applist Zygisk (hma_oss_zygisk)。
    
    根因: 判据用错了。原先以 [ -d "$dir/zygisk" ] 作为提供者标志, 但那其实是
    「Zygisk 模块」(消费者) 的标志 —— 任何自带 zygisk/<abi>.so 的模块都有,
    本模块自己也有。因此只要装了别的 Zygisk 模块就会被误判为提供者, 而按目录
    顺序遍历时先命中的往往是消费者而非真正的提供者。
    
    对照 Zygisk Next 官方发布包 (1.5.0) 的安装布局核实后修正判据 —— 改用提供者
    独有、普通模块不会用到的文件名:
    
    - lib{64}/libzygisk.so    核心库
    - lib{64}/libzn_loader.so Zygisk Next 的加载器
    - bin/zygiskd{64,32}      守护进程
    
    两个提供者的实际布局 (对照各自安装脚本):
      Zygisk Next (zygisksu): bin/zygiskd64 + lib64/libzygisk.so + libzn_loader.so
      ReZygisk    (rezygisk): bin/zygiskd64 + lib64/libzygisk.so + bin/zygisk-ptrace64
    共同特征即 libzygisk.so 与 zygiskd。
    
    同时修正:
    - 前端友好名映射补充 zygisksu -> Zygisk Next (此前只有 zygisknext 等猜测值)
    - dev mock 与真实模块 ID 对齐
    
    customize.sh 与 web/src/ksu.ts 两处逻辑保持一致 —— 判断标准不同会让用户看到
    「刷入时说可用、首页说不可用」这类矛盾结论。
    
    已按真实布局构造场景验证: 消费者模块 (仅 zygisk/ 目录) 不再误报, Zygisk Next
    与 ReZygisk 均能正确识别, 已停用的提供者正确跳过。
  • build(web): Pyodide 运行时改为构建时从 npm 包复制, 不再入库
    web/public/pyodide/ 下的 6 个运行时文件与 npm 依赖 `pyodide` 中的是同一份,
    提交进仓库有两个坏处: 占用仓库体积, 且依赖升版后容易留下不一致的旧副本。
    现改为构建时复制 (web/scripts/sync-pyodide.mjs, 由 dev/build 脚本自动调用)。
    
    - 移出仓库 6 个文件 (13.3MB): pyodide.asm.{mjs,wasm} / pyodide.{js,mjs}
      / pyodide-lock.json / python_stdlib.zip
    - 保留 2 个 wheel (3.9MB): fonttools 与 numpy 不在 npm 包内 (Pyodide 的依赖
      清单只登记而不随包分发), 仍需仓库提供
    
    顺带解决一个隐患: 此前仓库里的副本是格式化版本, npm 包里是压缩版本, 二者
    字节不同但功能等价。改用同源文件后, 本地与 CI 加载的 pyodide 版本必然与
    package.json 声明的依赖一致。
    
    sync-pyodide.mjs 内含配套校验: 比对保留的 wheel 与 pyodide-lock.json 登记的
    sha256, 并在 lock.json 未登记该 wheel 时提示依赖版本可能已升版。这一层是
    必要的 —— wheel 在仓库、lock.json 在 npm 包, 两者可能各自漂移, 而版本错配
    只在用户点开「字体编辑」时才暴露。
    
    已验证: 浏览器中实际加载 pyodide, 引擎报「就绪 (fontTools 4.62.1)」,
    并成功解析 demo 字体 (6253 字形, 家族名与 Canvas 预览均正常)。
    另测校验逻辑: 篡改 wheel 字节后被正确拦截 (退出码 1)。
  • chore: 添加 .gitattributes 排除第三方文件的语言统计
    GitHub 的 Languages 条此前被 Pyodide 运行时污染: web/public/pyodide/ 下是
    从官方 release 下载的预构建产物, 其中 pyodide.asm.mjs 有 1.5MB, 被 Linguist
    当作 JavaScript 统计, 一度占本项目语言统计的 87%, 掩盖了真实源码构成。
    
    用 linguist-vendored 标记这些第三方 / 二进制资源:
    
    - web/public/pyodide/**: Pyodide 运行时 (Emscripten 产物 + wheel)
    - web/public 下的 .ttf / .whl / .wasm / .zip: 演示字体与运行时资源
    - src/system/fonts/ 与 src/FONTS/ 下的字体文件
    
    只影响 GitHub 的语言占比展示, 不改变文件是否入库、也不影响构建。
    已用 git check-attr 核对: 上述文件标记为 set, 而 web/src、dev/、native/、
    golang/、src/*.sh 等真实源码仍为 unspecified (正常计入统计)。
42 changed files with 2140 additions and 48403 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
# GitHub Linguist 语言统计配置
#
# 作用: 标注第三方 / 生成的文件, 避免它们计入仓库的语言统计 (Languages 条)。
# 这些文件不进统计不代表不参与构建, 只影响 GitHub 的语言占比展示。
# Pyodide 运行时 (WebUI「字体编辑」工具用): 从官方 release 下载的预构建产物,
# 包含 Emscripten 编译出的 pyodide.asm.mjs (1.5MB) 等。
# 它们会被 Linguist 当作 JavaScript 统计, 一度占本项目语言统计的 87%,
# 掩盖了真正的源码构成 —— 故标记为第三方代码排除在外。
web/public/pyodide/** linguist-vendored
# 同理: 字体文件与 wheel 包等二进制资源不是源码, 明确排除
web/public/*.ttf linguist-vendored
web/public/**/*.whl linguist-vendored
web/public/**/*.wasm linguist-vendored
web/public/**/*.zip linguist-vendored
# 模块内的字体资源 (含补充字库) 同上
src/system/fonts/* linguist-vendored
src/FONTS/* linguist-vendored
+10
View File
@@ -29,3 +29,13 @@ 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
+42 -13
View File
@@ -96,8 +96,8 @@ pnpm shfmt:fix # 格式化 src/ 下 shell 脚本
```
`pnpm check` 除了跑 lint 与类型检查,还会做几项结构一致性校验:`module.prop` 字段完整性、
`fonts.xml` 标签配对、`apply.sh` 的占位字体映射与 `empty-font.mjs` 清单是否一一对应、
Zygisk 预热字体清单与 `apply.sh` 是否一致、派生配置是否被误提交等。
`fonts.xml` 标签配对、`apply.sh` 的基础占位映射与 `empty-font.mjs` 清单是否一一对应、
Zygisk 预热字体清单(含多字重 `FontMM-*` 扩展文件)与 `apply.sh` 是否一致、派生配置是否被误提交等。
## 预压缩缓存
@@ -254,8 +254,16 @@ python3 dev/check-unicode-coverage.py "Archaic" "Seal" # 只测指定区
> 避免中文完全覆盖西文(issue #6)。
>
> 英文槽位在安装前会经 `fontmm-subset` 检测,含 CJK 字形时自动裁成拉丁子集
> (issue #10,见上节)。子集文件为 `FONTS/.en-subset.ttf`,属中转产物,
> 不是用户槽位,不被 WebUI 读取。
> (issue #10,见上节)。单字体子集为 `FONTS/.en-subset.ttf`,多字重模式为
> `FONTS/multi/en/.subset-<w>.ttf`,均属中转产物,不是用户槽位。
#### 多字重模式映射
`hans` / `hant` / `en` 支持通过 `FONTS/slot-modes.txt` 独立切换 `single` / `multi`,多字重源文件存放于 `FONTS/multi/<slot>/<100..900>.ttf`:
- **文件复用与扩展名**:`400` 档位(或无 `400` 时最接近 `400` 的档位)直接填充原有占位文件(如 `SysSans-Hans-Regular.ttf`),其余已选档位安装至 `system/fonts/FontMM-{Hans,Hant,En}-{100,200,300,500,600,700,800,900}.ttf`(已列入 Zygisk `kFontFiles[]`,按需预热),未选档位自动清理。
- **XML 静态映射与就近匹配**:`fontmm-wght` 读取 `FONTS/slot-modes.txt` 与 `FONTS/multi/`,为处于 `multi` 模式的家族生成不含 `<axis tag="wght"/>` 的静态 `<font>` 列表,缺失档位按 `NearestWeight` 指向最接近的已选字重;`hant` / `en` 未配置而回退 `hans` 多字重时,XML 直接指向 `hans` 的系统文件,不重复复制大字体。
- **往返切换幂等**:`customize.sh` / `apply.sh` 会在首次修改前把纯净 `system/etc/fonts.xml` 备份到 `backup/fonts.xml`,`fontmm-wght` 始终以该备份为基准重写 `fonts.xml` 并 `-sync` 到各派生配置,保证 `可变字体 <-> 多字重` 任意切换与混合模式完全可逆。
### 补充字库
@@ -293,17 +301,38 @@ python3 dev/check-unicode-coverage.py "Archaic" "Seal" # 只测指定区
```
1. **安装阶段**(`customize.sh`):系统检查(ColorOS 版本、KernelSU 元模块、Zygisk 环境)
→ 停用重叠的外部 Fontloader → 更新模式检测与旧字体继承 → 扫描设备系统 XML 生成派生字体配置
→ 停用重叠的外部 Fontloader → 更新模式检测与旧字体/配置继承(含 `slot-modes.txt`、`wght-mode.txt`、`wght-map.txt` 与 `FONTS/multi/`)
→ 扫描设备系统 XML 生成派生字体配置并备份纯净 `backup/fonts.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*` 字体族,
2. **换字体阶段**(WebUI):选择文件 → 写入 `FONTS/slot-modes.txt` 与对应单/多字重文件(不删除另一模式已选文件)→ 调用同一个 `apply.sh`,两条路径行为一致
3. **`apply.sh` 核心逻辑**:按槽位模式把 `FONTS/` 或 `FONTS/multi/` 中的字体复制到 `system/fonts/`(缺失繁体/英文时回退简体;英文单/多字重均检测并裁掉 CJK 字形),随后统一调用 `fontmm-wght -sync` 生成单字体 `wght` 覆写与多字重静态 XML 映射
4. **字体生效**:ColorOS 通过 `/system/etc/fonts.xml` 等配置引用 `SysFont*` / `SysSans*` / `FontMM-*` 字体,
模块只内置 `fonts.xml` 主配置,各派生配置(`fonts_base.xml` / `fonts_ule.xml` /
`font_fallback.xml`)由安装时扫描设备系统 XML 生成(缺失时回退内置),字重覆写时
`fontmm-wght -sync` 统一同步,提升跨 ColorOS 版本兼容性
5. **字体预加载**(`zygisk/arm64-v8a.so`):App 进程 specialize 前,模块把 FontMM 的字体文件
预读进系统字体缓存,使被「卸载模块」的 App 仍能正常渲染字体
`font_fallback.xml`)由安装时扫描设备系统 XML 生成(缺失时回退内置),统一经 `fontmm-wght -sync` 同步,提升跨 ColorOS 版本兼容性
5. **字体预加载**(`zygisk/arm64-v8a.so`):App 进程 specialize 前,模块把 FontMM 实际挂载的字体文件
预读进系统字体缓存(未设置的槽位或字重通过 `access()` 自动跳过),使被「卸载模块」的 App 仍能正常渲染字体
## 发布流程
**发布资产由 CI 构建,不要在本地打包后手动上传** —— `Release` 工作流在 release 发布时
(`on: release: [published]`)会重新构建并上传 `dist/*.zip` 与 `dist/*.zip.sha256`;
手动传一遍既慢又会被 CI 覆盖(本地 zip 的时间戳与 CI 不同,校验和也不一样)。
1. 改 `src/module.prop` 的 `version` / `versionCode`,同步 `update.json`(版本号与 `zipUrl`)
2. `changelog.md` 写本次条目:**相对上一个已发布版本的用户可见变化**,不必逐条罗列 commit
3. `pnpm check` → commit(`chore: 发布 vX (版本码)`)→ push → 等 `Build & Upload Artifacts` 通过
4. 打 tag 并推送:`git tag -a vX -m "FontMM vX" && git push origin vX`
5. 创建预发布(**不传文件**):
```bash
gh release create vX --title "vX" --notes-file /tmp/relnotes.md --prerelease
```
`Release` 工作流随即构建并上传 4 个资产(template / preplace 的 zip 与 `.sha256`)
6. 等 `Release` 工作流成功后,验证 `update.json` 的 `zipUrl` 可达(HTTP 200)——
资产上传完成前该链接是 404
> 本地 `pnpm build` 只用于本地测试与实机验证;发布产物一律以 CI 为准。
## 相关文档
+66 -34
View File
@@ -1,7 +1,11 @@
<div align="center">
<img src="./docs/assets/logo.png" alt="FontMM" width="160" />
</div>
<h1 align="center">FontMM</h1>
<div align="center">
一个用于快速更换系统字体的 Magisk 模块,内置 WebUI 以及一些好用的功能
一个用于快速更换 ColorOS 字体的 Magisk 模块,内置 WebUI 以及一些好用的功能
</div>
<div align="center">
@@ -10,19 +14,35 @@
## 特性
<div align="center">
<table>
<tr>
<td align="center"><img src="./docs/assets/webui_主页.webp" alt="WebUI 主页" width="230" /></td>
<td align="center"><img src="./docs/assets/webui_配置.webp" alt="WebUI 字体配置(多字重)" width="230" /></td>
<td align="center"><img src="./docs/assets/webui_字体测试.webp" alt="WebUI 字体测试" width="230" /></td>
</tr>
<tr>
<td align="center">主页</td>
<td align="center">字体配置(多字重)</td>
<td align="center">字体测试</td>
</tr>
</table>
</div>
- Material 风格的管理界面,在支持 WebUI 的 Root 管理器中直接打开
- 多槽位字体分别选择,满足你的个性化需求
- 支持按槽位独立切换可变字体 / 多字重模式
- 可变字体 wght 范围与实际字重等级不符时可选择覆写配置,保证正确映射
- 内置字库补充字体,兜底 CJK 扩展区、Unicode 18.0 全覆盖
- 内置字体预加载,无需额外安装 Fontloader
## 支持环境
| 项目 | 要求 |
| --------- | ----------------------- |
| 系统 | >= ColorOS 16.0 |
| Root 环境 | Magisk 20.4+ / KernelSU |
| 字体格式 | `.ttf` |
| 项目 | 要求 |
| ------------------ | ----------------------- |
| 已测试的系统 | ColorOS 16 - 17 |
| 已测试的 Root 环境 | Magisk 20.4+ / KernelSU |
| 支持的字体格式 | `.ttf` |
## 安装
@@ -32,30 +52,31 @@
每个 Release 提供两个压缩包,区别仅在于是否预置字体:
| 包名 | 内容 | 适用场景 |
| -------------------- | ------------------------------- | ----------------------------------------------- |
| `..._preplace.zip` | 含预置简体字体 `FONTS/hans.ttf` | **全新安装**,刷入后开箱即用 |
| `..._template.zip` | `FONTS/` 为空目录 | **更新模块**,自动继承旧模块字体,包体积更小 |
> 若用 `_template` 版全新安装,需自行在 `FONTS/` 放入简体字体 `hans.ttf`,否则安装会失败。
| 包名 | 内容 | 适用场景 |
| ------------------ | -------------------------------------------- | ------------------------------------------------------------ |
| `..._preplace.zip` | 含预置简体字体 `FONTS/hans.ttf`(OPPO Sans) | **全新安装**,刷入后开箱即用 |
| `..._template.zip` | `FONTS/` 为空目录 | **更新模块**,自动继承旧模块字体,包体积更小,若用此版全新安装,需自行在 `FONTS/` 至少放入简体字体 `hans.ttf`,否则安装会失败 |
### 安装依赖
按你的 Root 管理器完成下表配置。三行都需要满足:
按你的 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) |
| 依赖 | KernelSU 及分支 | Magisk 及分支 |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| **元模块** | 已测试:[mountify](https://github.com/backslashxx/mountify/releases), [hybrid_mount](https://github.com/Hybrid-Mount/meta-hybrid_mount)。若管理器支持元模块则**必须**安装,否则模块无法挂载。参见[什么是元模块](https://kernelsu.org/zh_CN/guide/metamodule.html)。 | 不需要 |
| **Zygisk** | [Zygisk Next](https://github.com/Dr-TSNG/ZygiskNext/releases) 或 [ReZygisk](https://github.com/PerformanC/ReZygisk/releases) | 在设置中启用内置 Zygisk |
| **WebUI 支持** | 管理器自带,无需额外安装 | 需外置 App:[WebUI X Portable](https://github.com/MMRLApp/WebUI-X-Portable) 或 [KsuWebUI Standalone](https://github.com/5ec1cff/KsuWebUIStandalone) |
补充说明:
- **Zygisk 只能启用一个**:Magisk 内置 Zygisk 与独立提供者不可同时启用。使用 ReZygisk 等独立实现时,请关闭 Magisk 内置 Zygisk。
- **Zygisk Next 用户**:需在其 WebUI 中把「排除列表策略」改为**仅还原挂载**。
- **Zygisk Next 用户**:需在其 WebUI 中把「排除列表策略」改为**仅还原挂载**。
<img src="./docs/assets/zygisk-next_仅还原挂载演示.webp" alt="Zygisk Next 排除列表策略设为仅还原挂载" width="460" />
- **管理器配置**:本模块已内置字体预加载,可以不必关闭「默认卸载模块」以及「卸载模块(内核级)」,**但仍建议关闭**——关闭后模块才能尽可能全场景覆盖。若选择不关闭,可用 App Profile 单独为某个应用关闭「卸载模块」并重启该应用。
> **不再需要 Fontloader**:从 Android 12 起字体改为 App 启动时按需加载,被「卸载模块」的 App 会因找不到字体而异常。Fontloader 这类模块的作用就是提前把字体读进缓存,**本模块已内置该能力**。若你此前装过 Fontloader,刷入时会自动为其添加 `disable` 文件停用(不影响其数据,删除该文件即可恢复)。
> **不再需要 Fontloader**:**本模块已内置同款能力**。若你此前装过 Fontloader,刷入时会自动为其添加 `disable` 文件停用(不影响其数据,删除该文件即可恢复)。
## 使用
@@ -66,26 +87,35 @@
各槽位说明:
| 槽位 | 是否必选 | 未选择时 |
| --------------- | -------- | ---------------------- |
| **中文简体** | **必选** | 无法应用 |
| **中文繁体** | 可选 | 自动使用简体 |
| **英文 & 数字** | 可选 | 自动使用简体 |
| **等宽字体** | 可选 | 不覆盖系统等宽字体 |
| **Emoji 表情** | 可选 | 使用系统默认 Emoji |
| 槽位 | 是否必选 | 未选择时 |
| --------------- | -------- | ------------------ |
| **中文简体** | **必选** | 无法应用 |
| **中文繁体** | 可选 | 自动使用简体 |
| **英文 & 数字** | 可选 | 自动使用简体 |
| **等宽字体** | 可选 | 不覆盖系统等宽字体 |
| **Emoji 表情** | 可选 | 使用系统默认 Emoji |
> **关于「英文 & 数字」槽位**:若所选字体本身自带中文字形(例如某些中文字体的英文版、或包含 CJK 的西文字体),应用时会**自动裁剪成纯拉丁子集**。系统字体配置里西文排在中文之前,不裁剪的话它自带的汉字会盖掉你选的中文字体,表现为"中文没换干净"。裁剪只影响西文槽位,中文字体不做处理,且会完整保留可变字体特性(字重轴不受影响)。
> **关于「英文 & 数字」槽位**:若所选字体本身自带中文字形(例如某些中文字体的英文版、或包含 CJK 的西文字体),应用时会**自动裁剪成纯拉丁子集**(多字重模式下也会对各档位分别裁剪)。系统字体配置里西文排在中文之前,不裁剪的话它自带的汉字会盖掉你选的中文字体,表现为"中文没换干净"。裁剪只影响西文槽位,中文字体不做处理,且会完整保留可变字体特性(字重轴不受影响)。
### 多字重模式(静态分档)
对于提供多个独立粗细文件(如 Thin / Light / Regular / Medium / Bold / Black)的字体家族,可在「配置」页的**中文简体、中文繁体、英文 & 数字**卡片右上角独立切换「**可变字体 | 多字重**」(等宽与 Emoji 保持单文件):
- **支持 9 档字重**:`100` 淡体、`200` 特细、`300` 细体、`400` 标准、`500` 适中、`600` 次粗、`700` 粗体、`800` 特粗、`900` 浓体
- **自由选档与自动补齐**:简体在多字重模式下至少选 1 档即可,未选的档位会在字体配置中自动指向最接近的已选字重;繁体 / 英文若在多字重模式下未选任何档位,则自动回退到简体设置
- **独立保留配置**:切换「可变字体 / 多字重」不会删除另一种模式下已选择的字体,可随时切回
- **自动禁用字重覆写**:当所有已配置的可变字体槽位均处于多字重模式(或无生效可变字体)时,「高级配置 → 字重覆写模式」会自动禁用;若混用(如中文多字重 + 英文可变字体),覆写仅对可变字体槽位生效
### 字重覆写(高级)
所选字体为**可变字体**时,若其 wght 轴范围与实际字重等级不符,可在「高级配置」中覆写映射:
| 模式 | 说明 |
| ---------------- | -------------------------------------------- |
| **不处理** | 默认,超出范围的字重由系统处理 |
| **裁切粗细等级** | 删除范围外的字重条目 |
| **平均分配字重** | 保留 9 档完整粗细,400 不变,两端平均插值 |
| **自定义映射** | 自行定义 1-1000 字重的映射关系 |
| 模式 | 说明 |
| ---------------- | ----------------------------------------- |
| **不处理** | 默认,超出范围的字重由系统处理 |
| **裁切粗细等级** | 删除范围外的字重条目 |
| **平均分配字重** | 保留 9 档完整粗细,400 不变,两端平均插值 |
| **自定义映射** | 自行定义 1-1000 字重的映射关系 |
### 手动放置字体
@@ -99,6 +129,8 @@
| `mono.ttf` | 等宽字体 |
| `emoji.ttf` | Emoji 表情 |
若需手动使用多字重模式,可将对应字重放进 `FONTS/multi/<槽位>/<字重>.ttf`(`<槽位>` 为 `hans`/`hant`/`en`,`<字重>` 为 `100`–`900`),并在 `FONTS/slot-modes.txt` 中写入对应开关(如 `hans=multi`、`en=single`)。
之后执行 `sh /data/adb/modules/FontMM/apply.sh` 并重启设备。回退逻辑与 WebUI 一致。
### 校验模块完整性
+30
View File
@@ -1,5 +1,35 @@
# Changelog
## v26.11.0-beta.1
- **新增「多字重模式」(按槽位独立切换)**(issue #25):为提供独立粗细文件(如 Thin / Light / Regular / Medium / Bold / Black)的静态字体包提供完整支持
- 「配置」页的**中文简体、中文繁体、英文 & 数字**槽位支持各自独立切换「**可变字体 | 多字重**」(等宽与 Emoji 保持单文件),支持多字重与可变字体混用
- 支持 `100`–`900` 标准 9 档字重,简体至少选择 1 档即可;缺失档位在字体配置中自动指向最接近的已选字重,繁体 / 英文未选任何字重时自动回退简体
- 两种模式各自保留已选字体,来回切换不丢失原配置
- 当无生效的单字体可变字体时,「高级配置 → 字重覆写模式」自动禁用;混用时仅对可变字体槽位生效
- 英文槽位在多字重模式下同样支持按档位自动裁剪 CJK 字形并显示子集大小徽标;「字体测试」页同步支持 100–900 多字重真实预览
- 模块更新时自动继承多字重字体目录与槽位模式、字重覆写配置;Zygisk 字体预热器同步适配多字重文件
## v26.8.0-beta.10
- **修复英文字体子集化实际未生效**(issue #12):汉字仍会盖掉中文字体。KernelSU 解压不保留 zip 里的执行位,工具在设备上是 0644,而脚本按 `-x` 判断可用性 → 每次都提示「找不到子集化工具」并跳过。改为按文件存在判断、执行前临时加执行位、用完还原;刷入时 `fontmm-wght` 的同类判断失效(派生字体配置未同步)一并修好
- **修复字体选择器**(issue #13):从 Download 目录返回会跳两级、在其它目录选中字体无效
- **英文槽位显示子集化结果**(issue #14):卡片上显示「原大小 → 子集大小」并加「已子集化」徽标,一眼能看出裁切生效了
- **修复字体测试页**:编辑测试文本时输入框出现空行(issue #16);可变字体滑条说明改为明确的「仅预览」措辞(issue #15)
- **修复清空槽位后字重映射轴范围不刷新**:删掉 200-900 的字体后仍被限制在 200-900
- **模块更新后保留用户设置**:字重覆写模式与自定义字重映射此前会在更新时丢失,现在随 `FONTS/` 一起继承
- **移除字体度量改写**:测试版尝试过的「固定行距 & 字距」会导致部分设备**开机失败**,已整体删除。模块不再改动字体本身的度量与包围盒 —— 换字体后行距跟着字体走
## v26.8.0-beta.8
- **修复只选中文(或任一单槽位)字体时 WebUI 状态全空**(issue #11):槽位与字重覆写被误判为未设置,实际字体已生效
- 成因:作为字体安装结果的判据,逐槽位复制脚本的最后一行条件失败导致整段退出码非 0
- 感谢 [@HelloCxin](https://github.com/HelloCxin) 提供详细的复现步骤
- **修复 Zygisk 提供者误判**:安装了 Zygisk Next 时,首页的字体预热器状态可能显示为另一个普通 Zygisk 模块(如 Hide My Applist)
- 成因:此前以 `zygisk/` 目录判定提供者,而该目录是任何 Zygisk 模块(含本模块自身的消费者角色)都有的标记
- 现改用提供者专有产物判定(`libzygisk.so` / `zygiskd` / `libzn_loader.so` 等),对照 Zygisk Next 实际安装包核实
- **仓库瘦身**:Pyodide 运行时(约 12MB)不再入库,改由构建脚本从 npm 依赖复制,消除仓库内一份易过期的混淆副本
## v26.8.0-beta.7
- **英文槽位自动子集化**(issue #10):所选英文字体若自带中文字形,应用时自动裁剪为纯拉丁子集
+8 -7
View File
@@ -122,21 +122,22 @@ await check('派生字体配置未被 git 跟踪', async () => {
// 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) —— 直接替换系统
// apply.sh 里有三类单引号字体名:
// 1. 多行的基础占位赋值 (hans_fonts/hant_fonts/en_fonts) —— 0 字节占位文件,
// 必须与 empty-font.mjs 的 PLACEHOLDERS 一一对应
// 2. 多字重扩展文件名 (FontMM-{Hans,Hant,En}-{100..900}.ttf) —— 按需生成,
// 不经过占位机制, 不属于 PLACEHOLDERS, 但必须被 Zygisk 预热清单覆盖
// 3. 单行的系统字体名 (DroidSansMono.ttf / NotoColorEmoji.ttf) —— 直接替换系统
// 字体文件, 不经过占位机制, 不属于占位清单
// 按「是否含换行」区分这两类, 与源码结构一致。
await check('apply.sh 占位映射与占位清单一致', async () => {
const applySh = await fsp.readFile(path.join(SRC_DIR, 'apply.sh'), 'utf8');
const mapped = new Set();
for (const m of applySh.matchAll(/'([^']*)'/g)) {
const value = m[1];
if (!value.includes('\n')) continue; // 跳过单行系统字体名
if (!value.includes('\n')) continue; // 跳过单行字体名
for (const line of value.split('\n')) {
const name = line.trim();
if (name.endsWith('.ttf')) mapped.add(name);
if (name.endsWith('.ttf') && !name.startsWith('FontMM-')) mapped.add(name);
}
}
if (mapped.size === 0) throw new Error('未从 apply.sh 解析到占位字体列表 (解析逻辑可能已失效)');
Binary file not shown.

After

Width:  |  Height:  |  Size: 715 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+3 -2
View File
@@ -1,6 +1,7 @@
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围或多字重静态映射
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>] [-xml-dir <模块根>] [-sync]
// 说明: 只修改主配置 system/etc/fonts.xml, 加 -sync 后复制到各派生配置 (issue #7)
// 说明: 优先读取 backup/fonts.xml (若存在) 并结合 FONTS/slot-modes.txt 与 FONTS/multi/ 生成 system/etc/fonts.xml,
// 加 -sync 后复制到各派生配置 (issue #7)
package main
import (
+235 -22
View File
@@ -26,6 +26,7 @@ const (
// familySpec 描述一个需要覆写字重的家族及其条目格式
type familySpec struct {
slot string // 所属逻辑槽位: "en" | "hans" | "hant"
openTag string // 家族起始标签 (用于定位与生成)
fontFile string // 家族引用的字体文件
postScript string // postScriptName 属性 (无则为空)
@@ -36,14 +37,17 @@ type familySpec struct {
// 所有生效家族: 英文 (sans-serif / sys-sans-en) 与中文 (zh-Hans / zh-Hant) 都要覆盖,
// 否则中文或英文单独使用时字重映射不生效 (issue #7)
var FamilySpecs = []familySpec{
{openTag: `<family name="sans-serif">`, fontFile: "SysFont-Regular.ttf", axis: axisFull},
{openTag: `<family name="sys-sans-en">`, fontFile: "SysSans-En-Regular.ttf", postScript: "OPlusSansEn", axis: axisWghtOnly},
{openTag: `<family lang="zh-Hans">`, fontFile: "SysSans-Hans-Regular.ttf", postScript: "OPPO_Sans_4.0_SC", serifFallback: true, axis: axisWghtOnly},
{openTag: `<family lang="zh-Hant,zh-Bopo">`, fontFile: "SysSans-Hant-Regular.ttf", postScript: "OPPO_Sans_4.0_TC", serifFallback: true, axis: axisWghtOnly},
{slot: "en", openTag: `<family name="sans-serif">`, fontFile: "SysFont-Regular.ttf", axis: axisFull},
{slot: "en", openTag: `<family name="sys-sans-en">`, fontFile: "SysSans-En-Regular.ttf", postScript: "OPlusSansEn", axis: axisWghtOnly},
{slot: "hans", openTag: `<family lang="zh-Hans">`, fontFile: "SysSans-Hans-Regular.ttf", postScript: "OPPO_Sans_4.0_SC", serifFallback: true, axis: axisWghtOnly},
{slot: "hant", openTag: `<family lang="zh-Hant,zh-Bopo">`, fontFile: "SysSans-Hant-Regular.ttf", postScript: "OPPO_Sans_4.0_TC", serifFallback: true, axis: axisWghtOnly},
}
// 主配置文件名 (唯一源)
const SourceXMLRel = "system/etc/fonts.xml"
// 主配置文件名 (唯一源) 与纯净备份路径
const (
SourceXMLRel = "system/etc/fonts.xml"
BackupXMLRel = "backup/fonts.xml"
)
// 派生配置 (与 fonts.xml 内容一致, 由 -sync 复制生成)
var DerivedXMLRel = []string{
@@ -54,6 +58,80 @@ var DerivedXMLRel = []string{
"system/system_ext/etc/fonts_ule.xml",
}
// SlotMode 描述槽位当前字体模式 ("single" | "multi")
type SlotMode string
const (
SlotModeSingle SlotMode = "single"
SlotModeMulti SlotMode = "multi"
)
// MultiSlotConfig 描述一个生效后的多字重配置 (支持 hant/en 回退到 hans)
type MultiSlotConfig struct {
SourceSlot string // 实际使用的字体来源槽位: "hans" | "hant" | "en"
Available []int // 已选择的字重列表 (升序, 100..900)
}
// FamilyConfig 描述某家族最终生效的模式 (单字体覆写 或 多字重静态映射)
type FamilyConfig struct {
Multi *MultiSlotConfig // 非 nil 时按多字重生成, 忽略 wght 轴覆写
}
// NearestWeight 从已选字重列表中挑选最接近 target 的档位。
// 距离相等时: target >= 400 偏向更重档位 (如 400 取 500、600 取 700),
// target < 400 偏向更轻档位 (如 300 取 200)。
func NearestWeight(available []int, target int) int {
if len(available) == 0 {
return 400
}
best := available[0]
bestDist := absInt(best - target)
for _, w := range available[1:] {
d := absInt(w - target)
if d < bestDist || (d == bestDist && ((target >= 400 && w > best) || (target < 400 && w < best))) {
best = w
bestDist = d
}
}
return best
}
func absInt(x int) int {
if x < 0 {
return -x
}
return x
}
func slotCapName(slot string) string {
switch slot {
case "hans":
return "Hans"
case "hant":
return "Hant"
case "en":
return "En"
default:
return slot
}
}
// multiFontFile 返回多字重模式下指定已解析字重对应的系统字体文件名。
// 400 复用原有的 Regular 占位文件 (避免重复复制); 其他档位使用 FontMM-<Slot>-<W>.ttf。
func multiFontFile(spec familySpec, sourceSlot string, resolvedWeight int) string {
if resolvedWeight == 400 {
if sourceSlot == spec.slot {
return spec.fontFile
}
// 繁体或英文回退到简体多字重时直接指向简体的 Regular, 避免重复文件与多余缓存
if sourceSlot == "hans" {
return "SysSans-Hans-Regular.ttf"
}
return fmt.Sprintf("SysSans-%s-Regular.ttf", slotCapName(sourceSlot))
}
return fmt.Sprintf("FontMM-%s-%d.ttf", slotCapName(sourceSlot), resolvedWeight)
}
// 平均分配: weight w 对应的 axis 值 (400 固定, 两端 floor 线性插值)
func AveragedAxis(min, max, w int) int {
if w == 400 {
@@ -85,10 +163,33 @@ func fontEntryFor(spec familySpec, weight, axisWght int) string {
}
// 生成 zh-Hans/zh-Hant 家族的 fallbackFor="serif" 400 条目
func serifEntry(spec familySpec) string {
func serifEntry(spec familySpec, fontFile string) string {
return fmt.Sprintf(` <font weight="400" style="normal" fallbackFor="serif"
postScriptName="%s">%s
</font>`, spec.postScript, spec.fontFile)
</font>`, spec.postScript, fontFile)
}
// 生成单条静态多字重 <font> 条目 (不带 <axis tag="wght"/>)
func staticFontEntryFor(spec familySpec, weight int, fontFile string) string {
if spec.postScript != "" {
return fmt.Sprintf(` <font weight="%d" style="normal" postScriptName="%s" >%s</font>`,
weight, spec.postScript, fontFile)
}
return fmt.Sprintf(` <font weight="%d" style="normal">%s</font>`, weight, fontFile)
}
// 生成多字重家族段: 缺失档位按 NearestWeight 指向最接近的已选字重文件
func generateMultiFamily(spec familySpec, weights []int, multi MultiSlotConfig) string {
var lines []string
for _, w := range weights {
resolved := NearestWeight(multi.Available, w)
file := multiFontFile(spec, multi.SourceSlot, resolved)
lines = append(lines, staticFontEntryFor(spec, w, file))
if spec.serifFallback && w == 400 {
lines = append(lines, serifEntry(spec, file))
}
}
return " " + spec.openTag + "\n" + strings.Join(lines, "\n") + "\n </family>"
}
// 生成家族段 (mode 1=裁切 2=平均 3=自定义映射)
@@ -119,14 +220,14 @@ func generateFamily(spec familySpec, weights []int, min, max, mode int, customMa
}
lines = append(lines, fontEntryFor(spec, w, axis))
if spec.serifFallback && w == 400 {
lines = append(lines, serifEntry(spec))
lines = append(lines, serifEntry(spec, spec.fontFile))
}
}
return " " + spec.openTag + "\n" + strings.Join(lines, "\n") + "\n </family>"
}
// 在完整 XML 中覆写指定家族段; 家族不存在时原样返回
func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap map[int]int) string {
func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap map[int]int, multi *MultiSlotConfig) string {
start := findFamilyStart(xml, spec.openTag)
if start < 0 {
return xml
@@ -135,11 +236,15 @@ func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap ma
if end < 0 {
return xml
}
// 字重集选择: 裁切保留原家族声明字重 (兼容设备 XML), 平均分配固定 9 档完整粗细,
// 自定义映射由映射文件的键决定
block := xml[start:end]
if multi == nil && mode == 0 {
return xml
}
// 字重集选择: 多字重 / 裁切保留原家族声明字重 (兼容设备 XML, 含 1000),
// 平均分配固定 9 档完整粗细, 自定义映射由映射文件的键决定
weights := Weights
if mode == 1 {
if ex := extractWeights(xml[start:end]); len(ex) > 0 {
if multi != nil || mode == 1 {
if ex := extractWeights(block); len(ex) > 0 {
weights = ex
}
}
@@ -155,17 +260,33 @@ func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap ma
if lineEnd < len(xml) {
lineEnd++ // 吃掉换行
}
return xml[:lineStart] + generateFamily(spec, weights, min, max, mode, customMap) + "\n" + xml[lineEnd:]
var generated string
if multi != nil {
generated = generateMultiFamily(spec, weights, *multi)
} else {
generated = generateFamily(spec, weights, min, max, mode, customMap)
}
return xml[:lineStart] + generated + "\n" + xml[lineEnd:]
}
// 覆写全部生效家族 (mode 0 原样返回)
func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string {
if mode == 0 {
return xml
}
return ApplyWghtAndMulti(xml, mode, min, max, customMap, nil)
}
// ApplyWghtAndMulti 按槽位生效配置同时处理单字体字重覆写与多字重静态映射。
// slotMulti 的键为槽位名 ("hans" / "hant" / "en"), 非 nil 的槽位按多字重生成, 否则走单字体覆写。
func ApplyWghtAndMulti(xml string, mode, min, max int, customMap map[int]int, slotMulti map[string]*MultiSlotConfig) string {
result := xml
for _, spec := range FamilySpecs {
result = replaceFamily(result, spec, mode, min, max, customMap)
var multi *MultiSlotConfig
if slotMulti != nil {
multi = slotMulti[spec.slot]
}
if multi == nil && mode == 0 {
continue
}
result = replaceFamily(result, spec, mode, min, max, customMap, multi)
}
return result
}
@@ -282,17 +403,109 @@ func ReadCustomMap(path string) (map[int]int, error) {
return m, nil
}
// ReadSlotModes 读取 FONTS/slot-modes.txt (格式: slot=single|multi), 缺失时全部默认 single
func ReadSlotModes(xmlDir string) map[string]SlotMode {
modes := map[string]SlotMode{
"hans": SlotModeSingle,
"hant": SlotModeSingle,
"en": SlotModeSingle,
}
data, err := os.ReadFile(filepath.Join(xmlDir, "FONTS", "slot-modes.txt"))
if err != nil {
return modes
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
idx := strings.IndexByte(line, '=')
if idx <= 0 {
continue
}
k := strings.TrimSpace(line[:idx])
v := strings.TrimSpace(line[idx+1:])
if _, ok := modes[k]; !ok {
continue
}
if v == string(SlotModeMulti) {
modes[k] = SlotModeMulti
} else if v == string(SlotModeSingle) {
modes[k] = SlotModeSingle
}
}
return modes
}
func fileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
// scanMultiWeights 扫描 FONTS/multi/<slot>/<w>.ttf 中已设置的字重档位 (升序)
func scanMultiWeights(xmlDir, slot string) []int {
var out []int
for _, w := range Weights {
p := filepath.Join(xmlDir, "FONTS", "multi", slot, fmt.Sprintf("%d.ttf", w))
if fileExists(p) {
out = append(out, w)
}
}
return out
}
// ResolveMultiConfigs 根据 FONTS/slot-modes.txt 与 FONTS/ 实际字体计算各槽位多字重配置。
// hant/en 在自身模式下无字体时自动回退到 hans 的实际生效模式。
func ResolveMultiConfigs(xmlDir string) map[string]*MultiSlotConfig {
modes := ReadSlotModes(xmlDir)
result := map[string]*MultiSlotConfig{}
var hansMulti *MultiSlotConfig
if modes["hans"] == SlotModeMulti {
if ws := scanMultiWeights(xmlDir, "hans"); len(ws) > 0 {
hansMulti = &MultiSlotConfig{SourceSlot: "hans", Available: ws}
result["hans"] = hansMulti
}
}
for _, slot := range []string{"hant", "en"} {
if modes[slot] == SlotModeMulti {
if ws := scanMultiWeights(xmlDir, slot); len(ws) > 0 {
result[slot] = &MultiSlotConfig{SourceSlot: slot, Available: ws}
continue
}
// 多字重模式下 0 个字重时回退到 hans
if hansMulti != nil {
result[slot] = hansMulti
}
continue
}
// 单字体模式下未设置 <slot>.ttf 时回退到 hans
if !fileExists(filepath.Join(xmlDir, "FONTS", slot+".ttf")) && hansMulti != nil {
result[slot] = hansMulti
}
}
return result
}
// ApplyToDir 覆写模块根目录下的主配置 fonts.xml; sync 为 true 时复制到各派生配置
// 优先从 backup/fonts.xml 读取纯净模板 (存在时), 保证 single/multi 往返切换幂等。
// 返回覆写/同步的文件总数
func ApplyToDir(xmlDir string, mode, min, max int, customMap map[int]int, sync bool) (int, error) {
src := filepath.Join(xmlDir, SourceXMLRel)
data, err := os.ReadFile(src)
currentData, err := os.ReadFile(src)
if err != nil {
return 0, fmt.Errorf("读取 %s 失败: %w", SourceXMLRel, err)
}
replaced := ApplyWghtMode(string(data), mode, min, max, customMap)
baseData := currentData
backupPath := filepath.Join(xmlDir, BackupXMLRel)
if b, err := os.ReadFile(backupPath); err == nil && len(b) > 0 {
baseData = b
}
slotMulti := ResolveMultiConfigs(xmlDir)
replaced := ApplyWghtAndMulti(string(baseData), mode, min, max, customMap, slotMulti)
changed := 0
if replaced != string(data) {
if replaced != string(currentData) {
if err := os.WriteFile(src, []byte(replaced), 0o644); err != nil {
return changed, fmt.Errorf("写入失败 %s: %w", SourceXMLRel, err)
}
+106
View File
@@ -273,3 +273,109 @@ func TestApplyToDirSyncMode0(t *testing.T) {
}
}
}
func TestNearestWeight(t *testing.T) {
avail := []int{300, 400, 500, 700}
cases := map[int]int{
100: 300,
200: 300,
300: 300,
400: 400,
500: 500,
600: 700, // 与 500/700 等距, >=400 偏向更重
700: 700,
800: 700,
900: 700,
1000: 700,
}
for target, want := range cases {
if got := NearestWeight(avail, target); got != want {
t.Errorf("NearestWeight(%v, %d) = %d, want %d", avail, target, got, want)
}
}
// 无 400 时, 300/500 等距下 400 取 500, 200/400 等距下 300 取 200
if got := NearestWeight([]int{300, 500}, 400); got != 500 {
t.Errorf("NearestWeight([300,500], 400) = %d, want 500", got)
}
if got := NearestWeight([]int{200, 400}, 300); got != 200 {
t.Errorf("NearestWeight([200,400], 300) = %d, want 200", got)
}
}
// 混合模式 + 缺失字重回退 + 繁体/英文回退简体 + 切回单字体还原 backup
func TestApplyToDirMultiAndMixedRoundtrip(t *testing.T) {
dir := t.TempDir()
mkfile := func(rel, content string) {
p := filepath.Join(dir, rel)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
pristine := "<?xml version=\"1.0\"?>\n<familyset version=\"23\">\n" +
" <family name=\"sans-serif\">\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"100\" />\n </font>\n" +
" <font weight=\"400\" style=\"normal\">SysFont-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"400\" />\n </font>\n" +
" <font weight=\"700\" style=\"normal\">SysFont-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"700\" />\n </font>\n" +
" </family>\n" +
" <family name=\"sys-sans-en\">\n" +
" <font weight=\"100\" style=\"normal\" postScriptName=\"OPlusSansEn\">SysSans-En-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n" +
" <font weight=\"1000\" style=\"normal\" postScriptName=\"OPlusSansEn\">SysSans-En-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"1000\"/>\n </font>\n" +
" </family>\n" +
" <family lang=\"zh-Hans\">\n" +
" <font weight=\"100\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n" +
" <font weight=\"400\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"400\"/>\n </font>\n" +
" <font weight=\"400\" style=\"normal\" fallbackFor=\"serif\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf</font>\n" +
" <font weight=\"700\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"700\"/>\n </font>\n" +
" <font weight=\"1000\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"1000\"/>\n </font>\n" +
" </family>\n" +
" <family lang=\"zh-Hant,zh-Bopo\">\n" +
" <font weight=\"400\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_TC\">SysSans-Hant-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"400\"/>\n </font>\n" +
" <font weight=\"700\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_TC\">SysSans-Hant-Regular.ttf\n <axis tag=\"wght\" stylevalue=\"700\"/>\n </font>\n" +
" </family>\n" +
"</familyset>\n"
mkfile(SourceXMLRel, pristine)
mkfile(BackupXMLRel, pristine)
// 场景 1: 简体多字重 (400, 700), 繁体未设回退简体多字重, 英文单字体可变覆写 (mode=2, 200-700)
mkfile("FONTS/slot-modes.txt", "hans=multi\nhant=single\nen=single\n")
mkfile("FONTS/multi/hans/400.ttf", "r")
mkfile("FONTS/multi/hans/700.ttf", "b")
mkfile("FONTS/en.ttf", "en")
if _, err := ApplyToDir(dir, 2, 200, 700, nil, true); err != nil {
t.Fatalf("ApplyToDir mixed: %v", err)
}
gotBytes, err := os.ReadFile(filepath.Join(dir, SourceXMLRel))
if err != nil {
t.Fatal(err)
}
got := string(gotBytes)
// sans-serif 仍应走可变覆写 (200 -> 266)
if !strings.Contains(got, `<axis tag="wght" stylevalue="266" />`) {
t.Errorf("英文单字体可变覆写未生效:\n%s", got)
}
// zh-Hans 应使用静态多字重映射: 400 -> SysSans-Hans-Regular.ttf, 700/1000 -> FontMM-Hans-700.ttf, 不含 wght 轴
if !strings.Contains(got, `>SysSans-Hans-Regular.ttf</font>`) || !strings.Contains(got, `>FontMM-Hans-700.ttf</font>`) {
t.Errorf("简体多字重条目缺失:\n%s", got)
}
// 繁体未设置 hant.ttf, 应回退指向 hans 的多字重文件
if strings.Contains(got, `SysSans-Hant-Regular.ttf`) {
t.Errorf("繁体未设置时应回退简体多字重文件:\n%s", got)
}
// 场景 2: 全部切回单字体且 wght mode=0, 应从 backup/fonts.xml 完整还原
mkfile("FONTS/slot-modes.txt", "hans=single\nhant=single\nen=single\n")
if _, err := ApplyToDir(dir, 0, 100, 900, nil, true); err != nil {
t.Fatalf("ApplyToDir reset: %v", err)
}
restored, err := os.ReadFile(filepath.Join(dir, SourceXMLRel))
if err != nil {
t.Fatal(err)
}
if string(restored) != pristine {
t.Errorf("切回 single mode=0 后未能完整还原纯净 XML:\n%s", string(restored))
}
}
+24
View File
@@ -55,12 +55,36 @@ static const char *const kFontFiles[] = {
"/system/fonts/SysFont-Static-Regular.ttf",
"/system/fonts/SysFont-Myanmar.ttf",
"/system/fonts/SysFont-Hans-Regular.ttf",
"/system/fonts/FontMM-Hans-100.ttf",
"/system/fonts/FontMM-Hans-200.ttf",
"/system/fonts/FontMM-Hans-300.ttf",
"/system/fonts/FontMM-Hans-500.ttf",
"/system/fonts/FontMM-Hans-600.ttf",
"/system/fonts/FontMM-Hans-700.ttf",
"/system/fonts/FontMM-Hans-800.ttf",
"/system/fonts/FontMM-Hans-900.ttf",
// 中文繁体槽位
"/system/fonts/SysSans-Hant-Regular.ttf",
"/system/fonts/SysFont-Hant-Regular.ttf",
"/system/fonts/FontMM-Hant-100.ttf",
"/system/fonts/FontMM-Hant-200.ttf",
"/system/fonts/FontMM-Hant-300.ttf",
"/system/fonts/FontMM-Hant-500.ttf",
"/system/fonts/FontMM-Hant-600.ttf",
"/system/fonts/FontMM-Hant-700.ttf",
"/system/fonts/FontMM-Hant-800.ttf",
"/system/fonts/FontMM-Hant-900.ttf",
// 英文 & 数字槽位
"/system/fonts/SysSans-En-Regular.ttf",
"/system/fonts/SysFont-Regular.ttf",
"/system/fonts/FontMM-En-100.ttf",
"/system/fonts/FontMM-En-200.ttf",
"/system/fonts/FontMM-En-300.ttf",
"/system/fonts/FontMM-En-500.ttf",
"/system/fonts/FontMM-En-600.ttf",
"/system/fonts/FontMM-En-700.ttf",
"/system/fonts/FontMM-En-800.ttf",
"/system/fonts/FontMM-En-900.ttf",
// 等宽槽位
"/system/fonts/DroidSansMono.ttf",
// Emoji 槽位
+323 -27
View File
@@ -1,8 +1,8 @@
#!/system/bin/sh
# shellcheck shell=ash
# FontMM apply.sh — 应用字体: 把 FONTS/ 里的字体安装到 system/fonts
# FontMM apply.sh — 应用字体: 把 FONTS/ 里的字体安装到 system/fonts 并同步 fonts.xml
# 用法: apply.sh [模块目录] 默认 /data/adb/modules/FontMM
# 回退逻辑: hant/en 缺失时回退到 hans; mono/emoji 缺失时恢复系统原字体
# 回退逻辑: hant/en 当前模式未配置时回退到 hans; mono/emoji 缺失时恢复系统原字体
MODDIR="${1:-/data/adb/modules/FontMM}"
FONTS_DIR="$MODDIR/FONTS"
SYS_FONT_DIR="$MODDIR/system/fonts"
@@ -18,16 +18,40 @@ 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
}
# 多字重扩展文件 (按需生成, 400 复用上方 Regular 占位; 清单与 native/src/fontmm.cpp 保持一致)
hans_multi_fonts='FontMM-Hans-100.ttf
FontMM-Hans-200.ttf
FontMM-Hans-300.ttf
FontMM-Hans-500.ttf
FontMM-Hans-600.ttf
FontMM-Hans-700.ttf
FontMM-Hans-800.ttf
FontMM-Hans-900.ttf'
hant_multi_fonts='FontMM-Hant-100.ttf
FontMM-Hant-200.ttf
FontMM-Hant-300.ttf
FontMM-Hant-500.ttf
FontMM-Hant-600.ttf
FontMM-Hant-700.ttf
FontMM-Hant-800.ttf
FontMM-Hant-900.ttf'
en_multi_fonts='FontMM-En-100.ttf
FontMM-En-200.ttf
FontMM-En-300.ttf
FontMM-En-500.ttf
FontMM-En-600.ttf
FontMM-En-700.ttf
FontMM-En-800.ttf
FontMM-En-900.ttf'
ALL_WEIGHTS="100 200 300 400 500 600 700 800 900"
mkdir -p "$SYS_FONT_DIR"
install_from() {
local src="$1" list="$2" line=""
while IFS= read -r line; do
[ -z "$line" ] && continue
cp -f "$src" "$SYS_FONT_DIR/$line" || {
echo "[✗] 复制 $line 失败"
exit 1
@@ -38,9 +62,92 @@ $list
EOF
}
clear_files() {
local list="$1" line=""
while IFS= read -r line; do
[ -z "$line" ] && continue
rm -f "$SYS_FONT_DIR/$line"
done <<EOF
$list
EOF
}
# 读取槽位模式 ("single" | "multi"), 缺失时默认 "single"
get_slot_mode() {
local slot="$1" mode="single" line="" k="" v=""
if [ -f "$FONTS_DIR/slot-modes.txt" ]; then
while IFS= read -r line; do
line="${line%%#*}"
case "$line" in
*=*)
k="${line%%=*}"
v="${line#*=}"
k="$(printf '%s' "$k" | tr -d ' \t\r')"
v="$(printf '%s' "$v" | tr -d ' \t\r')"
if [ "$k" = "$slot" ] && [ "$v" = "multi" ]; then
mode="multi"
elif [ "$k" = "$slot" ] && [ "$v" = "single" ]; then
mode="single"
fi
;;
esac
done <"$FONTS_DIR/slot-modes.txt"
fi
printf '%s' "$mode"
}
# 列出 FONTS/multi/<slot>/ 中实际存在的字重 (升序空格分隔)
list_multi_weights() {
local slot="$1" w="" out=""
for w in $ALL_WEIGHTS; do
if [ -f "$FONTS_DIR/multi/$slot/$w.ttf" ]; then
out="${out:+$out }$w"
fi
done
printf '%s' "$out"
}
# 从已选字重列表中挑选最接近 target 的档位 (与 golang/internal/wght/wght.go 一致)
nearest_weight() {
local avail="$1" target="$2" best="" best_dist=99999 w="" d=0
for w in $avail; do
if [ "$w" -ge "$target" ]; then
d=$((w - target))
else
d=$((target - w))
fi
if [ -z "$best" ] || [ "$d" -lt "$best_dist" ]; then
best="$w"
best_dist="$d"
elif [ "$d" -eq "$best_dist" ]; then
if [ "$target" -ge 400 ] && [ "$w" -gt "$best" ]; then
best="$w"
elif [ "$target" -lt 400 ] && [ "$w" -lt "$best" ]; then
best="$w"
fi
fi
done
printf '%s' "$best"
}
# 执行模块内的原生工具。
# 刷入后 tools/ 下的文件权限是 0644 (KernelSU 解压时不保留 zip 里的执行位),
# 因此不能靠 -x 判断可用性, 而是执行前临时加执行位、执行后立即还原,
# 避免长期留下可执行文件。退出码为工具自身的退出码, 工具缺失返回 127。
run_tool() {
local tool="$1"
shift
[ -f "$tool" ] || return 127
chmod 0755 "$tool" 2>/dev/null
"$tool" "$@"
local rc=$?
chmod 0644 "$tool" 2>/dev/null
return "$rc"
}
# 准备英文字体: 含 CJK 字形时裁成纯拉丁子集, 否则原样使用 (issue #10)
# 用法: prepare_english_font <源字体> <子集输出路径>
# 成功 (含子集化) 时输出子集路径; 无需处理或工具不可用时返回非 0, 调用方回退原字体。
# 成功 (含子集化) 时返回 0 并写入 <子集输出路径>; 无需处理或工具不可用时返回非 0。
#
# 不做结果缓存: 实测检测与子集化各约 13-21ms (x86; 设备端同量级),
# 每次重算比维护缓存 (失效判断、陈旧文件清理) 更简单可靠。
@@ -52,16 +159,14 @@ prepare_english_font() {
[ -f "$src" ] || return 1
# 工具缺失 (旧版本模块升级、文件被删): 跳过, 用原字体
if [ ! -x "$tool" ]; then
if [ ! -f "$tool" ]; then
echo "[-] 未找到字体子集化工具, 跳过英文子集化"
return 1
fi
# 先检测是否含 CJK: 不含则无需处理 (常见情况, 无额外开销)
# 退出码: 0=不含 CJK, 1=含 CJK, 2=文件无效/读取失败, 126/127=工具无法执行
# 只有明确返回 1 (含 CJK) 才做子集化; 其余情况一律跳过,
# 避免工具损坏时还去调用一次子集化 (那样会误报「子集化失败」)
"$tool" -check "$src" >/dev/null 2>&1
run_tool "$tool" -check "$src" >/dev/null 2>&1
local rc=$?
if [ "$rc" -eq 0 ]; then
@@ -74,7 +179,7 @@ prepare_english_font() {
fi
echo "[*] 英文字体含 CJK 字形, 生成拉丁子集..."
if ! "$tool" -in "$src" -out "$out" 2>&1; then
if ! run_tool "$tool" -in "$src" -out "$out" 2>&1; then
# 子集化失败不阻断安装: 退回原字体, 并提示可能出现的问题
echo "[!] 子集化失败, 使用原字体 (中文可能被英文字体的字形覆盖)"
rm -f "$out"
@@ -85,36 +190,151 @@ prepare_english_font() {
return 0
}
# 取多字重槽位某一档的实际源文件 (英文优先取 .subset-<w>.ttf)
multi_weight_src() {
local slot="$1" w="$2" is_en="$3"
local subset="$FONTS_DIR/multi/en/.subset-$w.ttf"
if [ "$is_en" -eq 1 ] && [ -f "$subset" ]; then
printf '%s' "$subset"
else
printf '%s' "$FONTS_DIR/multi/$slot/$w.ttf"
fi
}
# 安装多字重槽位: 400 (或最接近 400) 填充基础占位, 其余已选档位写入 FontMM-<Slot>-<W>.ttf
install_multi_slot() {
local slot="$1" cap="$2" avail="$3" base_list="$4" multi_list="$5" is_en="$6"
local w="" reg_w="" src=""
clear_files "$multi_list"
if [ "$is_en" -eq 1 ]; then
rm -f "$FONTS_DIR/multi/en"/.subset-*.ttf
for w in $avail; do
echo "[*] 检查英文多字重 $w..."
if ! prepare_english_font "$FONTS_DIR/multi/en/$w.ttf" "$FONTS_DIR/multi/en/.subset-$w.ttf"; then
rm -f "$FONTS_DIR/multi/en/.subset-$w.ttf"
fi
done
fi
reg_w="$(nearest_weight "$avail" 400)"
src="$(multi_weight_src "$slot" "$reg_w" "$is_en")"
install_from "$src" "$base_list"
for w in $avail; do
[ "$w" -eq 400 ] && continue
src="$(multi_weight_src "$slot" "$w" "$is_en")"
cp -f "$src" "$SYS_FONT_DIR/FontMM-${cap}-${w}.ttf" || {
echo "[✗] 复制 FontMM-${cap}-${w}.ttf 失败"
exit 1
}
echo "[*] 安装: FontMM-${cap}-${w}.ttf"
done
}
HANS_MODE="$(get_slot_mode hans)"
HANT_MODE="$(get_slot_mode hant)"
EN_MODE="$(get_slot_mode en)"
HANS_AVAIL=""
HANS_EFF_MODE="single"
if [ "$HANS_MODE" = "multi" ]; then
HANS_AVAIL="$(list_multi_weights hans)"
if [ -z "$HANS_AVAIL" ]; then
echo "[✗] 多字重模式下 FONTS/multi/hans/ 中未设置任何字重字体"
exit 1
fi
HANS_EFF_MODE="multi"
else
[ -f "$FONTS_DIR/hans.ttf" ] || {
echo "[✗] FONTS/hans.ttf 不存在, 请先在 WebUI 选择字体"
exit 1
}
fi
echo "[*] 安装简体字体..."
install_from "$FONTS_DIR/hans.ttf" "$hans_fonts"
if [ "$HANS_EFF_MODE" = "multi" ]; then
install_multi_slot hans Hans "$HANS_AVAIL" "$hans_fonts" "$hans_multi_fonts" 0
else
clear_files "$hans_multi_fonts"
install_from "$FONTS_DIR/hans.ttf" "$hans_fonts"
fi
echo "[*] 处理繁体字体..."
if [ -f "$FONTS_DIR/hant.ttf" ]; then
HANT_EFF_MODE="single"
HANT_AVAIL=""
if [ "$HANT_MODE" = "multi" ]; then
HANT_AVAIL="$(list_multi_weights hant)"
if [ -n "$HANT_AVAIL" ]; then
HANT_EFF_MODE="multi"
install_multi_slot hant Hant "$HANT_AVAIL" "$hant_fonts" "$hant_multi_fonts" 0
else
echo "[-] 多字重繁体未选字重, 回退使用简体"
clear_files "$hant_multi_fonts"
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$hant_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
fi
fi
elif [ -f "$FONTS_DIR/hant.ttf" ]; then
clear_files "$hant_multi_fonts"
install_from "$FONTS_DIR/hant.ttf" "$hant_fonts"
else
echo "[-] 未设置繁体, 回退使用简体"
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
clear_files "$hant_multi_fonts"
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$hant_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
fi
fi
# 英文槽位: 若 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 裁掉。
# 英文槽位: 若在单字体或任何多字重下自带 CJK 字形, 需先子集化 (issue #10)
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
# 子集化成功则改用子集文件, 否则沿用原字体 (失败不阻断安装)
EN_EFF_MODE="single"
EN_OWN_SINGLE=0
if [ "$EN_MODE" = "multi" ]; then
EN_AVAIL="$(list_multi_weights en)"
if [ -n "$EN_AVAIL" ]; then
EN_EFF_MODE="multi"
rm -f "$EN_SUBSET"
install_multi_slot en En "$EN_AVAIL" "$en_fonts" "$en_multi_fonts" 1
else
echo "[-] 多字重英文未选字重, 回退使用简体"
clear_files "$en_multi_fonts"
rm -f "$EN_SUBSET" "$FONTS_DIR/multi/en"/.subset-*.ttf
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$en_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$en_fonts"
fi
fi
elif [ -f "$FONTS_DIR/en.ttf" ]; then
EN_OWN_SINGLE=1
clear_files "$en_multi_fonts"
rm -f "$FONTS_DIR/multi/en"/.subset-*.ttf
if prepare_english_font "$FONTS_DIR/en.ttf" "$EN_SUBSET"; then
EN_SRC="$EN_SUBSET"
else
rm -f "$EN_SUBSET"
fi
install_from "$EN_SRC" "$en_fonts"
else
echo "[-] 未设置英文, 回退使用简体"
clear_files "$en_multi_fonts"
rm -f "$EN_SUBSET" "$FONTS_DIR/multi/en"/.subset-*.ttf
if [ "$HANS_EFF_MODE" = "multi" ]; then
HANS_REG_W="$(nearest_weight "$HANS_AVAIL" 400)"
install_from "$FONTS_DIR/multi/hans/$HANS_REG_W.ttf" "$en_fonts"
else
install_from "$FONTS_DIR/hans.ttf" "$en_fonts"
fi
fi
echo "[*] 处理等宽字体..."
@@ -142,4 +362,80 @@ else
fi
fi
# 首次修改 XML 前备份纯净 fonts.xml, 供后续 single <-> multi 切换还原
if [ -f "$MODDIR/system/etc/fonts.xml" ] && [ ! -f "$MODDIR/backup/fonts.xml" ]; then
mkdir -p "$MODDIR/backup"
cp -f "$MODDIR/system/etc/fonts.xml" "$MODDIR/backup/fonts.xml"
fi
# 同步字重映射与多字重 XML 配置 (同时处理单字体 wght 覆写与多字重静态映射)
echo "[*] 同步字体配置 XML..."
WGHT_MODE=0
if [ -f "$FONTS_DIR/wght-mode.txt" ]; then
raw_mode="$(tr -d ' \t\r\n' <"$FONTS_DIR/wght-mode.txt" 2>/dev/null || true)"
case "$raw_mode" in
1 | 2 | 3) WGHT_MODE="$raw_mode" ;;
esac
fi
WGHT_MIN=100
WGHT_MAX=900
if [ "$WGHT_MODE" -ne 0 ] && [ -f "$MODDIR/tools/wght-range.sh" ]; then
best_span=99999
single_candidates=""
[ "$HANS_EFF_MODE" = "single" ] && single_candidates="$FONTS_DIR/hans.ttf"
if [ "$HANT_EFF_MODE" = "single" ] && [ -f "$FONTS_DIR/hant.ttf" ]; then
single_candidates="${single_candidates:+$single_candidates
}$FONTS_DIR/hant.ttf"
fi
if [ "$EN_EFF_MODE" = "single" ] && [ "$EN_OWN_SINGLE" -eq 1 ]; then
single_candidates="${single_candidates:+$single_candidates
}$EN_SRC"
fi
while IFS= read -r cand; do
[ -z "$cand" ] && continue
[ -f "$cand" ] || continue
rng="$(sh "$MODDIR/tools/wght-range.sh" "$cand" 2>/dev/null || true)"
if [ -n "$rng" ]; then
cmin="${rng%% *}"
cmax="${rng#* }"
cspan=$((cmax - cmin))
if [ "$cspan" -lt "$best_span" ]; then
best_span="$cspan"
WGHT_MIN="$cmin"
WGHT_MAX="$cmax"
fi
fi
done <<EOF
$single_candidates
EOF
fi
WGHT_BIN="$MODDIR/tools/fontmm-wght"
if [ -f "$WGHT_BIN" ]; then
if [ "$WGHT_MODE" -eq 3 ] && [ -f "$FONTS_DIR/wght-map.txt" ]; then
run_tool "$WGHT_BIN" -mode "$WGHT_MODE" -min "$WGHT_MIN" -max "$WGHT_MAX" -map "$FONTS_DIR/wght-map.txt" -xml-dir "$MODDIR" -sync >"$FONTS_DIR/wght-apply.log" 2>&1
wght_rc=$?
else
[ "$WGHT_MODE" -eq 3 ] && WGHT_MODE=0
run_tool "$WGHT_BIN" -mode "$WGHT_MODE" -min "$WGHT_MIN" -max "$WGHT_MAX" -xml-dir "$MODDIR" -sync >"$FONTS_DIR/wght-apply.log" 2>&1
wght_rc=$?
fi
if [ "$wght_rc" -eq 0 ]; then
echo "[✓] 字体配置 XML 同步完成"
else
echo "[✗] 字体配置 XML 同步失败:"
cat "$FONTS_DIR/wght-apply.log" 2>/dev/null || true
if [ "$HANS_EFF_MODE" = "multi" ] || [ "$HANT_EFF_MODE" = "multi" ] || [ "$EN_EFF_MODE" = "multi" ]; then
exit 1
fi
fi
else
echo "[!] 未找到 fontmm-wght, 跳过字体配置同步"
if [ "$HANS_EFF_MODE" = "multi" ] || [ "$HANT_EFF_MODE" = "multi" ] || [ "$EN_EFF_MODE" = "multi" ]; then
echo "[✗] 多字重模式依赖 fontmm-wght 更新字体配置, 请重新刷入完整模块"
exit 1
fi
fi
echo "[*] 全部完成, 重启后生效"
+55 -24
View File
@@ -55,7 +55,7 @@ DETECT_UPDATE_MODE() {
fi
}
# 更新模式: 以旧包为主继承字体
# 更新模式: 以旧包为主继承字体与配置
IMPORT_OLD_FONTS() {
[ "$UPDATE_MODE" -eq 1 ] || return 0
@@ -67,17 +67,24 @@ IMPORT_OLD_FONTS() {
mkdir -p "$MOD_WORK_PATH"
local f=""
for f in hans.ttf hant.ttf en.ttf mono.ttf emoji.ttf; do
for f in hans.ttf hant.ttf en.ttf mono.ttf emoji.ttf slot-modes.txt wght-mode.txt wght-map.txt; do
if [ -f "$old_fonts/$f" ]; then
if cp -f "$old_fonts/$f" "$MOD_WORK_PATH/$f"; then
log_succ "已从旧模块继承字体: $f"
log_succ "已从旧模块继承: $f"
else
log_err "继承字体 $f 失败"
log_err "继承 $f 失败"
fi
else
log "旧包没有 $f, 使用新包字体"
fi
done
if [ -d "$old_fonts/multi" ]; then
if cp -af "$old_fonts/multi" "$MOD_WORK_PATH/"; then
rm -f "$MOD_WORK_PATH/multi/en"/.subset-*.ttf 2>/dev/null
log_succ "已从旧模块继承多字重字体目录"
else
log_err "继承多字重目录失败"
fi
fi
}
# ---------- 系统检查 ----------
@@ -190,10 +197,19 @@ CHECK_ZYGISK_ENV() {
fi
fi
# 独立 Zygisk 提供者模块。各实现的内部布局不同, 逐一识别 (任一命中即算可用):
# - Zygisk Next / Magisk 兼容第三方: 自带 zygisk/ 目录
# - ReZygisk: lib64/libzygisk.so + bin/zygisk-ptrace64 (无 zygisk/ 目录)
# - Zygisk Next 早期版本: bin/zygiskd64
# 独立 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
@@ -203,17 +219,14 @@ CHECK_ZYGISK_ENV() {
[ -f "$dir/disable" ] && continue
local hit=""
if [ -d "$dir/zygisk" ]; then
hit="zygisk/"
else
for f in "$dir"/lib64/libzygisk.so "$dir"/lib/libzygisk.so \
"$dir"/bin/zygisk-ptrace64 "$dir"/bin/zygiskd64; do
if [ -f "$f" ]; then
hit="${f#"$dir"/}"
break
fi
done
fi
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)"
@@ -222,6 +235,13 @@ CHECK_ZYGISK_ENV() {
done
fi
# 管理器内置 Zygisk (如 KernelSU / Sukisu 的内置实现): 无独立提供者模块,
# 仅由管理器自身提供, 以内置标记文件是否存在为准。
if [ "$ok" -eq 0 ] && [ -f /data/adb/ksu/.builtin_zygisk ]; then
log_succ "检测到管理器内置 Zygisk"
ok=1
fi
if [ "$ok" -eq 0 ]; then
log_warn "未检测到可用的 Zygisk 环境"
log "模块的字体预加载依赖 Zygisk, 缺少时被卸载模块的应用可能字体异常"
@@ -256,13 +276,18 @@ system/system_ext/etc/fonts_ule.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
# 用 Go 程序把主配置同步到派生配置 (避免 shell 复制与主配置不一致)。
# 工具在刷入后是 0644 (KernelSU 解压时不保留 zip 里的执行位), 故不能靠 -x
# 判断可用性; 执行前临时加执行位, 用完立即还原。
local wght="$MODPATH/tools/fontmm-wght"
if [ -f "$wght" ]; then
chmod 0755 "$wght" 2>/dev/null
if "$wght" -mode 0 -sync -xml-dir "$MODPATH" >/dev/null 2>&1; then
log "已同步派生字体配置"
else
log "同步派生配置失败 (可忽略, 使用内置副本)"
fi
chmod 0644 "$wght" 2>/dev/null
fi
}
@@ -340,6 +365,12 @@ MAIN() {
# 同步派生字体配置 (设备 XML 扫描 + fontmm-wght -sync)
SYNC_FONT_XMLS
# 备份纯净的 fonts.xml, 供 apply.sh 在单字体 <-> 多字重间往返切换
if [ -f "$MODPATH/system/etc/fonts.xml" ]; then
mkdir -p "$MODPATH/backup"
cp -f "$MODPATH/system/etc/fonts.xml" "$MODPATH/backup/fonts.xml"
fi
# 校验内置的 Zygisk 字体预加载模块存在 (缺失则 DenyList 应用可能字体异常)
if [ ! -f "$MODPATH/zygisk/arm64-v8a.so" ]; then
log_warn "缺少 zygisk/arm64-v8a.so, 字体预加载不可用 (DenyList 应用可能字体异常)"
+2 -2
View File
@@ -1,7 +1,7 @@
id=FontMM
name=FontMM
version=26.8.0-beta.7
versionCode=26080007
version=26.11.0-beta.1
versionCode=26110001
author=Yule
description=ColorOS 16 字体模块模板
updateJson=https://raw.githubusercontent.com/YuleBest/FontMM/main/update.json
+3 -3
View File
@@ -1,6 +1,6 @@
{
"versionCode": 26080007,
"version": "v26.8.0-beta.7",
"zipUrl": "https://github.com/YuleBest/FontMM/releases/download/v26.8.0-beta.7/FontMM_v26.8.0-beta.7_template.zip",
"versionCode": 26110001,
"version": "v26.11.0-beta.1",
"zipUrl": "https://github.com/YuleBest/FontMM/releases/download/v26.11.0-beta.1/FontMM_v26.11.0-beta.1_template.zip",
"changelog": "https://raw.githubusercontent.com/YuleBest/FontMM/main/changelog.md"
}
+2 -1
View File
@@ -295,7 +295,8 @@
可变字体<span class="test-tag" id="var-tag"></span>
</div>
<div class="test-var-note">
拖动滑条调整字重,停止滑动后应用;仅对可变字体 (VF) 生效,静态字体下无变化。
拖动滑条可预览该字体在各字重、字号下的效果,仅影响本页预览,不会修改系统字体。字重仅对可变字体
(VF) 生效,静态字体下无变化。
</div>
<div class="test-wght-row">
<span class="test-wght-label">字重</span>
+3 -2
View File
@@ -4,8 +4,9 @@
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"sync:pyodide": "node scripts/sync-pyodide.mjs",
"dev": "npm run sync:pyodide && vite",
"build": "npm run sync:pyodide && vite build",
"preview": "vite preview",
"lint": "oxlint",
"fmt": "oxfmt",
File diff suppressed because it is too large. Load diff
-42338
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
-836
View File
@@ -1,836 +0,0 @@
'use strict';
var loadPyodide = (() => {
var ne = Object.create;
var F = Object.defineProperty;
var re = Object.getOwnPropertyDescriptor;
var oe = Object.getOwnPropertyNames;
var ie = Object.getPrototypeOf,
ae = Object.prototype.hasOwnProperty;
var i = (e, t) => F(e, 'name', { value: t, configurable: !0 }),
m = ((e) =>
typeof require < 'u'
? require
: typeof Proxy < 'u'
? new Proxy(e, { get: (t, n) => (typeof require < 'u' ? require : t)[n] })
: e)(function (e) {
if (typeof require < 'u') return require.apply(this, arguments);
throw Error('Dynamic require of "' + e + '" is not supported');
});
var se = (e, t) => {
for (var n in t) F(e, n, { get: t[n], enumerable: !0 });
},
$ = (e, t, n, o) => {
if ((t && typeof t == 'object') || typeof t == 'function')
for (let s of oe(t))
!ae.call(e, s) &&
s !== n &&
F(e, s, { get: () => t[s], enumerable: !(o = re(t, s)) || o.enumerable });
return e;
};
var v = (e, t, n) => (
(n = e != null ? ne(ie(e)) : {}),
$(t || !e || !e.__esModule ? F(n, 'default', { value: e, enumerable: !0 }) : n, e)
),
le = (e) => $(F({}, '__esModule', { value: !0 }), e);
var j = (() => {
for (var e = new Uint8Array(128), t = 0; t < 64; t++)
e[t < 26 ? t + 65 : t < 52 ? t + 71 : t < 62 ? t - 4 : t * 4 - 205] = t;
return (n) => {
for (
var o = n.length,
s = new Uint8Array((((o - (n[o - 1] == '=') - (n[o - 2] == '=')) * 3) / 4) | 0),
r = 0,
a = 0;
r < o;
) {
var c = e[n.charCodeAt(r++)],
l = e[n.charCodeAt(r++)],
d = e[n.charCodeAt(r++)],
u = e[n.charCodeAt(r++)];
((s[a++] = (c << 2) | (l >> 4)), (s[a++] = (l << 4) | (d >> 2)), (s[a++] = (d << 6) | u));
}
return s;
};
})();
var je = {};
se(je, { loadPyodide: () => B, version: () => O });
function ce(e) {
return !isNaN(parseFloat(e)) && isFinite(e);
}
i(ce, '_isNumber');
function N(e) {
return e.charAt(0).toUpperCase() + e.substring(1);
}
i(N, '_capitalize');
function C(e) {
return function () {
return this[e];
};
}
i(C, '_getter');
var S = ['isConstructor', 'isEval', 'isNative', 'isToplevel'],
w = ['columnNumber', 'lineNumber'],
_ = ['fileName', 'functionName', 'source'],
de = ['args'],
ue = ['evalOrigin'],
D = S.concat(w, _, de, ue);
function y(e) {
if (e) for (var t = 0; t < D.length; t++) e[D[t]] !== void 0 && this['set' + N(D[t])](e[D[t]]);
}
i(y, 'StackFrame');
y.prototype = {
getArgs: i(function () {
return this.args;
}, 'getArgs'),
setArgs: i(function (e) {
if (Object.prototype.toString.call(e) !== '[object Array]')
throw new TypeError('Args must be an Array');
this.args = e;
}, 'setArgs'),
getEvalOrigin: i(function () {
return this.evalOrigin;
}, 'getEvalOrigin'),
setEvalOrigin: i(function (e) {
if (e instanceof y) this.evalOrigin = e;
else if (e instanceof Object) this.evalOrigin = new y(e);
else throw new TypeError('Eval Origin must be an Object or StackFrame');
}, 'setEvalOrigin'),
toString: i(function () {
var e = this.getFileName() || '',
t = this.getLineNumber() || '',
n = this.getColumnNumber() || '',
o = this.getFunctionName() || '';
return this.getIsEval()
? e
? '[eval] (' + e + ':' + t + ':' + n + ')'
: '[eval]:' + t + ':' + n
: o
? o + ' (' + e + ':' + t + ':' + n + ')'
: e + ':' + t + ':' + n;
}, 'toString'),
};
y.fromString = i(function (t) {
var n = t.indexOf('('),
o = t.lastIndexOf(')'),
s = t.substring(0, n),
r = t.substring(n + 1, o).split(','),
a = t.substring(o + 1);
if (a.indexOf('@') === 0)
var c = /@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(a, ''),
l = c[1],
d = c[2],
u = c[3];
return new y({
functionName: s,
args: r || void 0,
fileName: l,
lineNumber: d || void 0,
columnNumber: u || void 0,
});
}, 'StackFrame$$fromString');
for (E = 0; E < S.length; E++)
((y.prototype['get' + N(S[E])] = C(S[E])),
(y.prototype['set' + N(S[E])] = (function (e) {
return function (t) {
this[e] = !!t;
};
})(S[E])));
var E;
for (P = 0; P < w.length; P++)
((y.prototype['get' + N(w[P])] = C(w[P])),
(y.prototype['set' + N(w[P])] = (function (e) {
return function (t) {
if (!ce(t)) throw new TypeError(e + ' must be a Number');
this[e] = Number(t);
};
})(w[P])));
var P;
for (h = 0; h < _.length; h++)
((y.prototype['get' + N(_[h])] = C(_[h])),
(y.prototype['set' + N(_[h])] = (function (e) {
return function (t) {
this[e] = String(t);
};
})(_[h])));
var h,
x = y;
function fe() {
var e = /^\s*at .*(\S+:\d+|\(native\))/m,
t = /^(eval@)?(\[native code])?$/;
return {
parse: i(function (o) {
if (o.stack && o.stack.match(e)) return this.parseV8OrIE(o);
if (o.stack) return this.parseFFOrSafari(o);
throw new Error('Cannot parse given Error object');
}, 'ErrorStackParser$$parse'),
extractLocation: i(function (o) {
if (o.indexOf(':') === -1) return [o];
var s = /(.+?)(?::(\d+))?(?::(\d+))?$/,
r = s.exec(o.replace(/[()]/g, ''));
return [r[1], r[2] || void 0, r[3] || void 0];
}, 'ErrorStackParser$$extractLocation'),
parseV8OrIE: i(function (o) {
var s = o.stack
.split(`
`)
.filter(function (r) {
return !!r.match(e);
}, this);
return s.map(function (r) {
r.indexOf('(eval ') > -1 &&
(r = r.replace(/eval code/g, 'eval').replace(/(\(eval at [^()]*)|(,.*$)/g, ''));
var a = r
.replace(/^\s+/, '')
.replace(/\(eval code/g, '(')
.replace(/^.*?\s+/, ''),
c = a.match(/ (\(.+\)$)/);
a = c ? a.replace(c[0], '') : a;
var l = this.extractLocation(c ? c[1] : a),
d = (c && a) || void 0,
u = ['eval', '<anonymous>'].indexOf(l[0]) > -1 ? void 0 : l[0];
return new x({
functionName: d,
fileName: u,
lineNumber: l[1],
columnNumber: l[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseV8OrIE'),
parseFFOrSafari: i(function (o) {
var s = o.stack
.split(`
`)
.filter(function (r) {
return !r.match(t);
}, this);
return s.map(function (r) {
if (
(r.indexOf(' > eval') > -1 &&
(r = r.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ':$1')),
r.indexOf('@') === -1 && r.indexOf(':') === -1)
)
return new x({ functionName: r });
var a = /((.*".+"[^@]*)?[^@]*)(?:@)/,
c = r.match(a),
l = c && c[1] ? c[1] : void 0,
d = this.extractLocation(r.replace(a, ''));
return new x({
functionName: l,
fileName: d[0],
lineNumber: d[1],
columnNumber: d[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseFFOrSafari'),
};
}
i(fe, 'ErrorStackParser');
var me = new fe();
var H = me;
function pe() {
if (typeof API < 'u' && API !== globalThis.API) return API.runtimeEnv;
let e = typeof Bun < 'u',
t = typeof Deno < 'u',
n =
typeof process == 'object' &&
typeof process.versions == 'object' &&
typeof process.versions.node == 'string' &&
!process.browser,
o =
typeof navigator == 'object' &&
typeof navigator.userAgent == 'string' &&
navigator.userAgent.indexOf('Chrome') === -1 &&
navigator.userAgent.indexOf('Safari') > -1,
s = typeof read == 'function' && typeof load == 'function',
r = typeof navigator == 'object' && navigator.userAgent?.includes('Cloudflare-Workers');
return ye({ IN_BUN: e, IN_DENO: t, IN_NODE: n, IN_SAFARI: o, IN_SHELL: s, IN_WORKERD: r });
}
i(pe, 'getGlobalRuntimeEnv');
var f = pe();
function ye(e) {
let t =
e.IN_NODE &&
typeof module < 'u' &&
module.exports &&
typeof m == 'function' &&
typeof __dirname == 'string',
n = e.IN_NODE && !t,
o = !e.IN_NODE && !e.IN_DENO && !e.IN_BUN,
s =
o &&
typeof window < 'u' &&
typeof window.document < 'u' &&
typeof document.createElement == 'function' &&
'sessionStorage' in window &&
typeof globalThis.importScripts != 'function',
r =
o &&
typeof globalThis.WorkerGlobalScope < 'u' &&
typeof globalThis.self < 'u' &&
globalThis.self instanceof globalThis.WorkerGlobalScope;
if (r && ge()) throw new Error('Classic web workers are not supported');
let a = {
...e,
IN_BROWSER: o,
IN_BROWSER_MAIN_THREAD: s,
IN_BROWSER_WEB_WORKER: r,
IN_NODE_COMMONJS: t,
IN_NODE_ESM: n,
};
if (
!(
a.IN_BROWSER_MAIN_THREAD ||
a.IN_BROWSER_WEB_WORKER ||
a.IN_NODE ||
a.IN_SHELL ||
a.IN_WORKERD
)
)
throw new Error(`Cannot determine runtime environment: ${JSON.stringify(a)}`);
return a;
}
i(ye, 'calculateDerivedFlags');
function ge() {
try {
return (globalThis.importScripts('data:text/javascript,'), !0);
} catch {
return !1;
}
}
i(ge, 'isClassicWorker');
var V, T, ve, J, U;
async function W() {
if (
!f.IN_NODE ||
((V = (await import(/* webpackIgnore */ 'node:url')).default),
(J = await import(/* webpackIgnore */ 'node:fs')),
(U = await import(/* webpackIgnore */ 'node:fs/promises')),
(ve = (await import(/* webpackIgnore */ 'node:vm')).default),
(T = await import(/* webpackIgnore */ 'node:path')),
(M = T.sep),
typeof m < 'u')
)
return;
let e = J,
t = await import(/* webpackIgnore */ 'node:crypto'),
n = await import(/* webpackIgnore */ 'ws'),
o = await import(/* webpackIgnore */ 'node:child_process'),
s = { fs: e, crypto: t, ws: n, child_process: o };
globalThis.require = function (r) {
return s[r];
};
}
i(W, 'initNodeModules');
function be(e, t) {
return T.resolve(t || '.', e);
}
i(be, 'node_resolvePath');
function Ee(e, t) {
return (t === void 0 && (t = location), new URL(e, t).toString());
}
i(Ee, 'browser_resolvePath');
var k;
f.IN_NODE ? (k = be) : f.IN_SHELL ? (k = i((e) => e, 'resolvePath')) : (k = Ee);
var M;
f.IN_NODE || (M = '/');
function Pe(e, t) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://')
? { response: fetch(e) }
: {
binary: U.readFile(e).then((n) => new Uint8Array(n.buffer, n.byteOffset, n.byteLength)),
}
);
}
i(Pe, 'node_getBinaryResponse');
function he(e, t) {
if ((e.startsWith('file://') && (e = e.slice(7)), e.includes('://')))
throw new Error('Shell cannot fetch urls');
return { binary: Promise.resolve(new Uint8Array(readbuffer(e))) };
}
i(he, 'shell_getBinaryResponse');
function Ne(e, t) {
let n = new URL(e, location);
return { response: fetch(n, t ? { integrity: t } : {}) };
}
i(Ne, 'browser_getBinaryResponse');
var R;
f.IN_NODE ? (R = Pe) : f.IN_SHELL ? (R = he) : (R = Ne);
async function z(e, t) {
let { response: n, binary: o } = R(e, t);
if (o) return o;
let s = await n;
if (!s.ok) throw new Error(`Failed to load '${e}': request failed.`);
return new Uint8Array(await s.arrayBuffer());
}
i(z, 'loadBinaryFile');
var L;
f.IN_NODE ? (L = Ie) : (L = i(async (e) => await import(/* webpackIgnore */ e), 'loadScript'));
async function Ie(e) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://')
? await import(/* webpackIgnore */ e)
: await import(/* webpackIgnore */ V.pathToFileURL(e).href)
);
}
i(Ie, 'nodeLoadScript');
async function G(e) {
if (f.IN_NODE) {
await W();
let t = await U.readFile(e, { encoding: 'utf8' });
return JSON.parse(t);
} else if (f.IN_SHELL) {
let t = read(e);
return JSON.parse(t);
} else return await (await fetch(e)).json();
}
i(G, 'loadLockFile');
async function K() {
if (f.IN_NODE_COMMONJS) return __dirname;
let e;
try {
throw new Error();
} catch (o) {
e = o;
}
let t = H.parse(e)[0].fileName;
if ((f.IN_NODE && !t.startsWith('file://') && (t = `file://${t}`), f.IN_NODE_ESM)) {
let o = await import(/* webpackIgnore */ 'node:path');
return (await import(/* webpackIgnore */ 'node:url')).fileURLToPath(o.dirname(t));
}
let n = t.lastIndexOf(M);
if (n === -1)
throw new Error(
'Could not extract indexURL path from pyodide module location. Please pass the indexURL explicitly to loadPyodide.',
);
return t.slice(0, n);
}
i(K, 'calculateDirname');
function q(e) {
return e.substring(0, e.lastIndexOf('/') + 1) || globalThis.location?.toString() || '.';
}
i(q, 'calculateInstallBaseUrl');
function Y(e) {
let t = e.FS,
n = e.FS.filesystems.MEMFS,
o = e.PATH,
s = {
DIR_MODE: 16895,
FILE_MODE: 33279,
mount: i(function (r) {
if (!r.opts.fileSystemHandle) throw new Error('opts.fileSystemHandle is required');
return n.mount.apply(null, arguments);
}, 'mount'),
syncfs: i(async (r, a, c) => {
try {
let l = s.getLocalSet(r),
d = await s.getRemoteSet(r),
u = a ? d : l,
g = a ? l : d;
(await s.reconcile(r, u, g), c(null));
} catch (l) {
c(l);
}
}, 'syncfs'),
getLocalSet: i((r) => {
let a = Object.create(null);
function c(u) {
return u !== '.' && u !== '..';
}
i(c, 'isRealDir');
function l(u) {
return (g) => o.join2(u, g);
}
i(l, 'toAbsolute');
let d = t.readdir(r.mountpoint).filter(c).map(l(r.mountpoint));
for (; d.length;) {
let u = d.pop(),
g = t.stat(u);
(t.isDir(g.mode) && d.push.apply(d, t.readdir(u).filter(c).map(l(u))),
(a[u] = { timestamp: g.mtime, mode: g.mode }));
}
return { type: 'local', entries: a };
}, 'getLocalSet'),
getRemoteSet: i(async (r) => {
let a = Object.create(null),
c = await Se(r.opts.fileSystemHandle);
for (let [l, d] of c)
l !== '.' &&
(a[o.join2(r.mountpoint, l)] = {
timestamp:
d.kind === 'file' ? new Date((await d.getFile()).lastModified) : new Date(),
mode: d.kind === 'file' ? s.FILE_MODE : s.DIR_MODE,
});
return { type: 'remote', entries: a, handles: c };
}, 'getRemoteSet'),
loadLocalEntry: i((r) => {
let c = t.lookupPath(r, {}).node,
l = t.stat(r);
if (t.isDir(l.mode)) return { timestamp: l.mtime, mode: l.mode };
if (t.isFile(l.mode))
return (
(c.contents = n.getFileDataAsTypedArray(c)),
{ timestamp: l.mtime, mode: l.mode, contents: c.contents }
);
throw new Error('node type not supported');
}, 'loadLocalEntry'),
storeLocalEntry: i((r, a) => {
if (t.isDir(a.mode)) t.mkdirTree(r, a.mode);
else if (t.isFile(a.mode)) t.writeFile(r, a.contents, { canOwn: !0 });
else throw new Error('node type not supported');
(t.chmod(r, a.mode), t.utime(r, a.timestamp, a.timestamp));
}, 'storeLocalEntry'),
removeLocalEntry: i((r) => {
var a = t.stat(r);
t.isDir(a.mode) ? t.rmdir(r) : t.isFile(a.mode) && t.unlink(r);
}, 'removeLocalEntry'),
loadRemoteEntry: i(async (r) => {
if (r.kind === 'file') {
let a = await r.getFile();
return {
contents: new Uint8Array(await a.arrayBuffer()),
mode: s.FILE_MODE,
timestamp: new Date(a.lastModified),
};
} else {
if (r.kind === 'directory') return { mode: s.DIR_MODE, timestamp: new Date() };
throw new Error('unknown kind: ' + r.kind);
}
}, 'loadRemoteEntry'),
storeRemoteEntry: i(async (r, a, c) => {
let l = r.get(o.dirname(a)),
d = t.isFile(c.mode)
? await l.getFileHandle(o.basename(a), { create: !0 })
: await l.getDirectoryHandle(o.basename(a), { create: !0 });
if (d.kind === 'file') {
let u = await d.createWritable();
(await u.write(c.contents), await u.close());
}
r.set(a, d);
}, 'storeRemoteEntry'),
removeRemoteEntry: i(async (r, a) => {
(await r.get(o.dirname(a)).removeEntry(o.basename(a)), r.delete(a));
}, 'removeRemoteEntry'),
reconcile: i(async (r, a, c) => {
let l = 0,
d = [];
(Object.keys(a.entries).forEach(function (p) {
let b = a.entries[p],
I = c.entries[p];
(!I || (t.isFile(b.mode) && b.timestamp.getTime() > I.timestamp.getTime())) &&
(d.push(p), l++);
}),
d.sort());
let u = [];
if (
(Object.keys(c.entries).forEach(function (p) {
a.entries[p] || (u.push(p), l++);
}),
u.sort().reverse(),
!l)
)
return;
let g = a.type === 'remote' ? a.handles : c.handles;
for (let p of d) {
let b = o.normalize(p.replace(r.mountpoint, '/')).substring(1);
if (c.type === 'local') {
let I = g.get(b),
te = await s.loadRemoteEntry(I);
s.storeLocalEntry(p, te);
} else {
let I = s.loadLocalEntry(p);
await s.storeRemoteEntry(g, b, I);
}
}
for (let p of u)
if (c.type === 'local') s.removeLocalEntry(p);
else {
let b = o.normalize(p.replace(r.mountpoint, '/')).substring(1);
await s.removeRemoteEntry(g, b);
}
}, 'reconcile'),
};
e.FS.filesystems.NATIVEFS_ASYNC = s;
}
i(Y, 'initializeNativeFS');
var Se = i(async (e) => {
let t = [];
async function n(s) {
for await (let r of s.values()) (t.push(r), r.kind === 'directory' && (await n(r)));
}
(i(n, 'collect'), await n(e));
let o = new Map();
o.set('.', e);
for (let s of t) {
let r = (await e.resolve(s)).join('/');
o.set(r, s);
}
return o;
}, 'getFsHandles');
var X = j(
'AGFzbQEAAAABDANfAGAAAW9gAW8BfwMDAgECBygCE0pzdl9HZXRFcnJvcl9pbXBvcnQAAA5Kc3ZFcnJvcl9DaGVjawABChMCBwD7AQD7GwsJACAA+xr7FAAL',
);
var _e = (async function () {
if (
!(
globalThis.navigator &&
(/iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' &&
typeof navigator.maxTouchPoints < 'u' &&
navigator.maxTouchPoints > 1))
)
)
try {
let t = await WebAssembly.compile(X);
return await WebAssembly.instantiate(t);
} catch (t) {
if (t instanceof WebAssembly.CompileError) return;
throw t;
}
})();
async function Q() {
let e = await _e;
if (e) return e.exports;
let t = Symbol('error marker');
return {
Jsv_GetError_import: i(() => t, 'Jsv_GetError_import'),
JsvError_Check: i((n) => n === t, 'JsvError_Check'),
};
}
i(Q, 'getJsvErrorImport');
function Z(e) {
let t = { config: e, runtimeEnv: f },
n = {
noImageDecoding: !0,
noAudioDecoding: !0,
noWasmDecoding: !1,
preRun: De(e),
print: e.stdout,
printErr: e.stderr,
onExit(o) {
n.exitCode = o;
},
thisProgram: e._sysExecutable,
arguments: e.args,
API: t,
locateFile: i((o) => e.indexURL + o, 'locateFile'),
instantiateWasm: xe(e.indexURL),
};
return n;
}
i(Z, 'createSettings');
function ke(e) {
return function (t) {
let n = '/';
try {
t.FS.mkdirTree(e);
} catch (o) {
(console.error(`Error occurred while making a home directory '${e}':`),
console.error(o),
console.error(`Using '${n}' for a home directory instead`),
(e = n));
}
t.FS.chdir(e);
};
}
i(ke, 'createHomeDirectory');
function Re(e) {
return function (t) {
Object.assign(t.ENV, e);
};
}
i(Re, 'setEnvironment');
function Fe(e) {
return e
? [
async (t) => {
t.addRunDependency('fsInitHook');
try {
await e(t.FS, { sitePackages: t.API.sitePackages });
} finally {
t.removeRunDependency('fsInitHook');
}
},
]
: [];
}
i(Fe, 'callFsInitHook');
function Ae(e) {
let t = e.HEAPU32[e._Py_Version >>> 2],
n = (t >>> 24) & 255,
o = (t >>> 16) & 255,
s = (t >>> 8) & 255;
return [n, o, s];
}
i(Ae, 'computeVersionTuple');
function Oe(e) {
let t = z(e);
return async (n) => {
n.API.pyVersionTuple = Ae(n);
let [o, s] = n.API.pyVersionTuple;
(n.FS.mkdirTree('/lib'),
(n.API.sitePackages = `/lib/python${o}.${s}/site-packages`),
n.FS.mkdirTree(n.API.sitePackages),
n.addRunDependency('install-stdlib'));
try {
let r = await t;
n.FS.writeFile(`/lib/python${o}${s}.zip`, r);
} catch (r) {
(console.error('Error occurred while installing the standard library:'), console.error(r));
} finally {
n.removeRunDependency('install-stdlib');
}
};
}
i(Oe, 'installStdlib');
function De(e) {
let t;
return (
e.stdLibURL != null ? (t = e.stdLibURL) : (t = e.indexURL + 'python_stdlib.zip'),
[Oe(t), ke(e.env.HOME), Re(e.env), Y, ...Fe(e.fsInit)]
);
}
i(De, 'getFileSystemInitializationFuncs');
function xe(e) {
if (typeof WasmOffsetConverter < 'u') return;
let { binary: t, response: n } = R(e + 'pyodide.asm.wasm'),
o = Q();
return function (s, r) {
return (
(async function () {
let { Jsv_GetError_import: a, JsvError_Check: c } = await o;
((s.env.Jsv_GetError_import = a), (s.env.JsvError_Check = c));
try {
let l;
n
? (l = await WebAssembly.instantiateStreaming(n, s))
: (l = await WebAssembly.instantiate(await t, s));
let { instance: d, module: u } = l;
r(d, u);
} catch (l) {
(console.warn('wasm instantiation failed!'), console.warn(l));
}
})(),
{}
);
};
}
i(xe, 'getInstantiateWasmFunc');
var ee = '314.0.3';
function A(e) {
return e === void 0 || e.endsWith('/') ? e : e + '/';
}
i(A, 'withTrailingSlash');
var O = ee;
async function Le(e = {}) {
if ((await W(), e.lockFileContents && e.lockFileURL))
throw new Error("Can't pass both lockFileContents and lockFileURL");
let t = e.indexURL || (await K());
if (
((t = A(k(t))),
(e.packageBaseUrl = A(e.packageBaseUrl)),
(e.cdnUrl = A(e.packageBaseUrl ?? `https://cdn.jsdelivr.net/pyodide/v${O}/full/`)),
!e.lockFileContents)
) {
let s = e.lockFileURL ?? t + 'pyodide-lock.json';
((e.lockFileContents = G(s)), (e.packageBaseUrl ??= q(s)));
}
((e.indexURL = t), e.packageCacheDir && (e.packageCacheDir = A(k(e.packageCacheDir))));
let n = {
jsglobals: globalThis,
stdin: globalThis.prompt ? () => globalThis.prompt() : void 0,
args: [],
env: {},
packages: [],
packageCacheDir: e.packageBaseUrl,
enableRunUntilComplete: !0,
checkAPIVersion: !0,
BUILD_ID: '2cf7085e96ffaa58f5400af724c388859f9e21586cf6f254da008c60685a5d05',
},
o = Object.assign(n, e);
return ((o.env.HOME ??= '/home/pyodide'), (o.env.PYTHONINSPECT ??= '1'), o);
}
i(Le, 'initializeConfiguration');
function Ce(e) {
let t = Z(e),
n = t.API;
return ((n.lockFilePromise = Promise.resolve(e.lockFileContents)), t);
}
i(Ce, 'createEmscriptenSettings');
async function Te(e) {
if (e.createPyodideModule) return e.createPyodideModule;
let t = `${e.indexURL}pyodide.asm.mjs`;
return (await L(t)).default;
}
i(Te, 'loadWasmScript');
async function Ue(e, t) {
if (!e._loadSnapshot) return;
let n = await e._loadSnapshot,
o = ArrayBuffer.isView(n) ? n : new Uint8Array(n);
return ((t.noInitialRun = !0), (t.INITIAL_MEMORY = o.length), o);
}
i(Ue, 'prepareSnapshot');
async function We(e, t) {
let n = await e(t);
if (t.exitCode !== void 0) throw new n.ExitStatus(t.exitCode);
return n;
}
i(We, 'instantiatePyodideModule');
function Me(e, t) {
let n = e.API;
if (
(t.pyproxyToStringRepr && n.setPyProxyToStringMethod(!0),
t.convertNullToNone && n.setCompatNullToNone(!0),
t.toJsLiteralMap && n.setCompatToJsLiteralMap(!0),
n.version !== O && t.checkAPIVersion)
)
throw new Error(
`Pyodide version does not match: '${O}' <==> '${n.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`,
);
e.locateFile = (o) => {
throw o.endsWith('.so')
? new Error(`Failed to find dynamic library "${o}"`)
: new Error(`Unexpected call to locateFile("${o}")`);
};
}
i(Me, 'configureAPI');
function Be(e, t, n) {
let o = e.API,
s;
return (t && (s = o.restoreSnapshot(t)), o.finalizeBootstrap(s, n._snapshotDeserializer));
}
i(Be, 'bootstrapPyodide');
async function $e(e, t) {
let n = e._api;
return (
n.sys.path.insert(0, ''),
n._pyodide.set_excepthook(),
await n.packageIndexReady,
n.initializeStreams(t.stdin, t.stdout, t.stderr),
e
);
}
i($e, 'finalizeSetup');
async function B(e = {}) {
let t = await Le(e),
n = Ce(t),
o = await Te(t),
s = await Ue(t, n),
r = await We(o, n);
Me(r, t);
let a = Be(r, s, t);
return await $e(a, t);
}
i(B, 'loadPyodide');
globalThis.loadPyodide = B;
return le(je);
})();
try {
Object.assign(exports, loadPyodide);
} catch (_) {}
globalThis.loadPyodide = loadPyodide.loadPyodide;
//# sourceMappingURL=pyodide.js.map
-801
View File
@@ -1,801 +0,0 @@
var Q = Object.defineProperty;
var o = (e, t) => Q(e, 'name', { value: t, configurable: !0 }),
R = ((e) =>
typeof require < 'u'
? require
: typeof Proxy < 'u'
? new Proxy(e, { get: (t, n) => (typeof require < 'u' ? require : t)[n] })
: e)(function (e) {
if (typeof require < 'u') return require.apply(this, arguments);
throw Error('Dynamic require of "' + e + '" is not supported');
});
var W = (() => {
for (var e = new Uint8Array(128), t = 0; t < 64; t++)
e[t < 26 ? t + 65 : t < 52 ? t + 71 : t < 62 ? t - 4 : t * 4 - 205] = t;
return (n) => {
for (
var i = n.length,
s = new Uint8Array((((i - (n[i - 1] == '=') - (n[i - 2] == '=')) * 3) / 4) | 0),
r = 0,
a = 0;
r < i;
) {
var c = e[n.charCodeAt(r++)],
l = e[n.charCodeAt(r++)],
d = e[n.charCodeAt(r++)],
u = e[n.charCodeAt(r++)];
((s[a++] = (c << 2) | (l >> 4)), (s[a++] = (l << 4) | (d >> 2)), (s[a++] = (d << 6) | u));
}
return s;
};
})();
function Z(e) {
return !isNaN(parseFloat(e)) && isFinite(e);
}
o(Z, '_isNumber');
function P(e) {
return e.charAt(0).toUpperCase() + e.substring(1);
}
o(P, '_capitalize');
function D(e) {
return function () {
return this[e];
};
}
o(D, '_getter');
var N = ['isConstructor', 'isEval', 'isNative', 'isToplevel'],
I = ['columnNumber', 'lineNumber'],
S = ['fileName', 'functionName', 'source'],
ee = ['args'],
te = ['evalOrigin'],
F = N.concat(I, S, ee, te);
function p(e) {
if (e) for (var t = 0; t < F.length; t++) e[F[t]] !== void 0 && this['set' + P(F[t])](e[F[t]]);
}
o(p, 'StackFrame');
p.prototype = {
getArgs: o(function () {
return this.args;
}, 'getArgs'),
setArgs: o(function (e) {
if (Object.prototype.toString.call(e) !== '[object Array]')
throw new TypeError('Args must be an Array');
this.args = e;
}, 'setArgs'),
getEvalOrigin: o(function () {
return this.evalOrigin;
}, 'getEvalOrigin'),
setEvalOrigin: o(function (e) {
if (e instanceof p) this.evalOrigin = e;
else if (e instanceof Object) this.evalOrigin = new p(e);
else throw new TypeError('Eval Origin must be an Object or StackFrame');
}, 'setEvalOrigin'),
toString: o(function () {
var e = this.getFileName() || '',
t = this.getLineNumber() || '',
n = this.getColumnNumber() || '',
i = this.getFunctionName() || '';
return this.getIsEval()
? e
? '[eval] (' + e + ':' + t + ':' + n + ')'
: '[eval]:' + t + ':' + n
: i
? i + ' (' + e + ':' + t + ':' + n + ')'
: e + ':' + t + ':' + n;
}, 'toString'),
};
p.fromString = o(function (t) {
var n = t.indexOf('('),
i = t.lastIndexOf(')'),
s = t.substring(0, n),
r = t.substring(n + 1, i).split(','),
a = t.substring(i + 1);
if (a.indexOf('@') === 0)
var c = /@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(a, ''),
l = c[1],
d = c[2],
u = c[3];
return new p({
functionName: s,
args: r || void 0,
fileName: l,
lineNumber: d || void 0,
columnNumber: u || void 0,
});
}, 'StackFrame$$fromString');
for (v = 0; v < N.length; v++)
((p.prototype['get' + P(N[v])] = D(N[v])),
(p.prototype['set' + P(N[v])] = (function (e) {
return function (t) {
this[e] = !!t;
};
})(N[v])));
var v;
for (b = 0; b < I.length; b++)
((p.prototype['get' + P(I[b])] = D(I[b])),
(p.prototype['set' + P(I[b])] = (function (e) {
return function (t) {
if (!Z(t)) throw new TypeError(e + ' must be a Number');
this[e] = Number(t);
};
})(I[b])));
var b;
for (E = 0; E < S.length; E++)
((p.prototype['get' + P(S[E])] = D(S[E])),
(p.prototype['set' + P(S[E])] = (function (e) {
return function (t) {
this[e] = String(t);
};
})(S[E])));
var E,
A = p;
function ne() {
var e = /^\s*at .*(\S+:\d+|\(native\))/m,
t = /^(eval@)?(\[native code])?$/;
return {
parse: o(function (i) {
if (i.stack && i.stack.match(e)) return this.parseV8OrIE(i);
if (i.stack) return this.parseFFOrSafari(i);
throw new Error('Cannot parse given Error object');
}, 'ErrorStackParser$$parse'),
extractLocation: o(function (i) {
if (i.indexOf(':') === -1) return [i];
var s = /(.+?)(?::(\d+))?(?::(\d+))?$/,
r = s.exec(i.replace(/[()]/g, ''));
return [r[1], r[2] || void 0, r[3] || void 0];
}, 'ErrorStackParser$$extractLocation'),
parseV8OrIE: o(function (i) {
var s = i.stack
.split(`
`)
.filter(function (r) {
return !!r.match(e);
}, this);
return s.map(function (r) {
r.indexOf('(eval ') > -1 &&
(r = r.replace(/eval code/g, 'eval').replace(/(\(eval at [^()]*)|(,.*$)/g, ''));
var a = r
.replace(/^\s+/, '')
.replace(/\(eval code/g, '(')
.replace(/^.*?\s+/, ''),
c = a.match(/ (\(.+\)$)/);
a = c ? a.replace(c[0], '') : a;
var l = this.extractLocation(c ? c[1] : a),
d = (c && a) || void 0,
u = ['eval', '<anonymous>'].indexOf(l[0]) > -1 ? void 0 : l[0];
return new A({
functionName: d,
fileName: u,
lineNumber: l[1],
columnNumber: l[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseV8OrIE'),
parseFFOrSafari: o(function (i) {
var s = i.stack
.split(`
`)
.filter(function (r) {
return !r.match(t);
}, this);
return s.map(function (r) {
if (
(r.indexOf(' > eval') > -1 &&
(r = r.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ':$1')),
r.indexOf('@') === -1 && r.indexOf(':') === -1)
)
return new A({ functionName: r });
var a = /((.*".+"[^@]*)?[^@]*)(?:@)/,
c = r.match(a),
l = c && c[1] ? c[1] : void 0,
d = this.extractLocation(r.replace(a, ''));
return new A({
functionName: l,
fileName: d[0],
lineNumber: d[1],
columnNumber: d[2],
source: r,
});
}, this);
}, 'ErrorStackParser$$parseFFOrSafari'),
};
}
o(ne, 'ErrorStackParser');
var re = new ne();
var M = re;
function ie() {
if (typeof API < 'u' && API !== globalThis.API) return API.runtimeEnv;
let e = typeof Bun < 'u',
t = typeof Deno < 'u',
n =
typeof process == 'object' &&
typeof process.versions == 'object' &&
typeof process.versions.node == 'string' &&
!process.browser,
i =
typeof navigator == 'object' &&
typeof navigator.userAgent == 'string' &&
navigator.userAgent.indexOf('Chrome') === -1 &&
navigator.userAgent.indexOf('Safari') > -1,
s = typeof read == 'function' && typeof load == 'function',
r = typeof navigator == 'object' && navigator.userAgent?.includes('Cloudflare-Workers');
return oe({ IN_BUN: e, IN_DENO: t, IN_NODE: n, IN_SAFARI: i, IN_SHELL: s, IN_WORKERD: r });
}
o(ie, 'getGlobalRuntimeEnv');
var f = ie();
function oe(e) {
let t =
e.IN_NODE &&
typeof module < 'u' &&
module.exports &&
typeof R == 'function' &&
typeof __dirname == 'string',
n = e.IN_NODE && !t,
i = !e.IN_NODE && !e.IN_DENO && !e.IN_BUN,
s =
i &&
typeof window < 'u' &&
typeof window.document < 'u' &&
typeof document.createElement == 'function' &&
'sessionStorage' in window &&
typeof globalThis.importScripts != 'function',
r =
i &&
typeof globalThis.WorkerGlobalScope < 'u' &&
typeof globalThis.self < 'u' &&
globalThis.self instanceof globalThis.WorkerGlobalScope;
if (r && ae()) throw new Error('Classic web workers are not supported');
let a = {
...e,
IN_BROWSER: i,
IN_BROWSER_MAIN_THREAD: s,
IN_BROWSER_WEB_WORKER: r,
IN_NODE_COMMONJS: t,
IN_NODE_ESM: n,
};
if (
!(
a.IN_BROWSER_MAIN_THREAD ||
a.IN_BROWSER_WEB_WORKER ||
a.IN_NODE ||
a.IN_SHELL ||
a.IN_WORKERD
)
)
throw new Error(`Cannot determine runtime environment: ${JSON.stringify(a)}`);
return a;
}
o(oe, 'calculateDerivedFlags');
function ae() {
try {
return (globalThis.importScripts('data:text/javascript,'), !0);
} catch {
return !1;
}
}
o(ae, 'isClassicWorker');
var $, x, se, B, L;
async function C() {
if (
!f.IN_NODE ||
(($ = (await import('node:url')).default),
(B = await import('node:fs')),
(L = await import('node:fs/promises')),
(se = (await import('node:vm')).default),
(x = await import('node:path')),
(T = x.sep),
typeof R < 'u')
)
return;
let e = B,
t = await import('node:crypto'),
n = await import('ws'),
i = await import('node:child_process'),
s = { fs: e, crypto: t, ws: n, child_process: i };
globalThis.require = function (r) {
return s[r];
};
}
o(C, 'initNodeModules');
function le(e, t) {
return x.resolve(t || '.', e);
}
o(le, 'node_resolvePath');
function ce(e, t) {
return (t === void 0 && (t = location), new URL(e, t).toString());
}
o(ce, 'browser_resolvePath');
var w;
f.IN_NODE ? (w = le) : f.IN_SHELL ? (w = o((e) => e, 'resolvePath')) : (w = ce);
var T;
f.IN_NODE || (T = '/');
function de(e, t) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://')
? { response: fetch(e) }
: { binary: L.readFile(e).then((n) => new Uint8Array(n.buffer, n.byteOffset, n.byteLength)) }
);
}
o(de, 'node_getBinaryResponse');
function ue(e, t) {
if ((e.startsWith('file://') && (e = e.slice(7)), e.includes('://')))
throw new Error('Shell cannot fetch urls');
return { binary: Promise.resolve(new Uint8Array(readbuffer(e))) };
}
o(ue, 'shell_getBinaryResponse');
function fe(e, t) {
let n = new URL(e, location);
return { response: fetch(n, t ? { integrity: t } : {}) };
}
o(fe, 'browser_getBinaryResponse');
var _;
f.IN_NODE ? (_ = de) : f.IN_SHELL ? (_ = ue) : (_ = fe);
async function j(e, t) {
let { response: n, binary: i } = _(e, t);
if (i) return i;
let s = await n;
if (!s.ok) throw new Error(`Failed to load '${e}': request failed.`);
return new Uint8Array(await s.arrayBuffer());
}
o(j, 'loadBinaryFile');
var O;
f.IN_NODE ? (O = me) : (O = o(async (e) => await import(e), 'loadScript'));
async function me(e) {
return (
e.startsWith('file://') && (e = e.slice(7)),
e.includes('://') ? await import(e) : await import($.pathToFileURL(e).href)
);
}
o(me, 'nodeLoadScript');
async function H(e) {
if (f.IN_NODE) {
await C();
let t = await L.readFile(e, { encoding: 'utf8' });
return JSON.parse(t);
} else if (f.IN_SHELL) {
let t = read(e);
return JSON.parse(t);
} else return await (await fetch(e)).json();
}
o(H, 'loadLockFile');
async function J() {
if (f.IN_NODE_COMMONJS) return __dirname;
let e;
try {
throw new Error();
} catch (i) {
e = i;
}
let t = M.parse(e)[0].fileName;
if ((f.IN_NODE && !t.startsWith('file://') && (t = `file://${t}`), f.IN_NODE_ESM)) {
let i = await import('node:path');
return (await import('node:url')).fileURLToPath(i.dirname(t));
}
let n = t.lastIndexOf(T);
if (n === -1)
throw new Error(
'Could not extract indexURL path from pyodide module location. Please pass the indexURL explicitly to loadPyodide.',
);
return t.slice(0, n);
}
o(J, 'calculateDirname');
function V(e) {
return e.substring(0, e.lastIndexOf('/') + 1) || globalThis.location?.toString() || '.';
}
o(V, 'calculateInstallBaseUrl');
function z(e) {
let t = e.FS,
n = e.FS.filesystems.MEMFS,
i = e.PATH,
s = {
DIR_MODE: 16895,
FILE_MODE: 33279,
mount: o(function (r) {
if (!r.opts.fileSystemHandle) throw new Error('opts.fileSystemHandle is required');
return n.mount.apply(null, arguments);
}, 'mount'),
syncfs: o(async (r, a, c) => {
try {
let l = s.getLocalSet(r),
d = await s.getRemoteSet(r),
u = a ? d : l,
y = a ? l : d;
(await s.reconcile(r, u, y), c(null));
} catch (l) {
c(l);
}
}, 'syncfs'),
getLocalSet: o((r) => {
let a = Object.create(null);
function c(u) {
return u !== '.' && u !== '..';
}
o(c, 'isRealDir');
function l(u) {
return (y) => i.join2(u, y);
}
o(l, 'toAbsolute');
let d = t.readdir(r.mountpoint).filter(c).map(l(r.mountpoint));
for (; d.length;) {
let u = d.pop(),
y = t.stat(u);
(t.isDir(y.mode) && d.push.apply(d, t.readdir(u).filter(c).map(l(u))),
(a[u] = { timestamp: y.mtime, mode: y.mode }));
}
return { type: 'local', entries: a };
}, 'getLocalSet'),
getRemoteSet: o(async (r) => {
let a = Object.create(null),
c = await pe(r.opts.fileSystemHandle);
for (let [l, d] of c)
l !== '.' &&
(a[i.join2(r.mountpoint, l)] = {
timestamp:
d.kind === 'file' ? new Date((await d.getFile()).lastModified) : new Date(),
mode: d.kind === 'file' ? s.FILE_MODE : s.DIR_MODE,
});
return { type: 'remote', entries: a, handles: c };
}, 'getRemoteSet'),
loadLocalEntry: o((r) => {
let c = t.lookupPath(r, {}).node,
l = t.stat(r);
if (t.isDir(l.mode)) return { timestamp: l.mtime, mode: l.mode };
if (t.isFile(l.mode))
return (
(c.contents = n.getFileDataAsTypedArray(c)),
{ timestamp: l.mtime, mode: l.mode, contents: c.contents }
);
throw new Error('node type not supported');
}, 'loadLocalEntry'),
storeLocalEntry: o((r, a) => {
if (t.isDir(a.mode)) t.mkdirTree(r, a.mode);
else if (t.isFile(a.mode)) t.writeFile(r, a.contents, { canOwn: !0 });
else throw new Error('node type not supported');
(t.chmod(r, a.mode), t.utime(r, a.timestamp, a.timestamp));
}, 'storeLocalEntry'),
removeLocalEntry: o((r) => {
var a = t.stat(r);
t.isDir(a.mode) ? t.rmdir(r) : t.isFile(a.mode) && t.unlink(r);
}, 'removeLocalEntry'),
loadRemoteEntry: o(async (r) => {
if (r.kind === 'file') {
let a = await r.getFile();
return {
contents: new Uint8Array(await a.arrayBuffer()),
mode: s.FILE_MODE,
timestamp: new Date(a.lastModified),
};
} else {
if (r.kind === 'directory') return { mode: s.DIR_MODE, timestamp: new Date() };
throw new Error('unknown kind: ' + r.kind);
}
}, 'loadRemoteEntry'),
storeRemoteEntry: o(async (r, a, c) => {
let l = r.get(i.dirname(a)),
d = t.isFile(c.mode)
? await l.getFileHandle(i.basename(a), { create: !0 })
: await l.getDirectoryHandle(i.basename(a), { create: !0 });
if (d.kind === 'file') {
let u = await d.createWritable();
(await u.write(c.contents), await u.close());
}
r.set(a, d);
}, 'storeRemoteEntry'),
removeRemoteEntry: o(async (r, a) => {
(await r.get(i.dirname(a)).removeEntry(i.basename(a)), r.delete(a));
}, 'removeRemoteEntry'),
reconcile: o(async (r, a, c) => {
let l = 0,
d = [];
(Object.keys(a.entries).forEach(function (m) {
let g = a.entries[m],
h = c.entries[m];
(!h || (t.isFile(g.mode) && g.timestamp.getTime() > h.timestamp.getTime())) &&
(d.push(m), l++);
}),
d.sort());
let u = [];
if (
(Object.keys(c.entries).forEach(function (m) {
a.entries[m] || (u.push(m), l++);
}),
u.sort().reverse(),
!l)
)
return;
let y = a.type === 'remote' ? a.handles : c.handles;
for (let m of d) {
let g = i.normalize(m.replace(r.mountpoint, '/')).substring(1);
if (c.type === 'local') {
let h = y.get(g),
X = await s.loadRemoteEntry(h);
s.storeLocalEntry(m, X);
} else {
let h = s.loadLocalEntry(m);
await s.storeRemoteEntry(y, g, h);
}
}
for (let m of u)
if (c.type === 'local') s.removeLocalEntry(m);
else {
let g = i.normalize(m.replace(r.mountpoint, '/')).substring(1);
await s.removeRemoteEntry(y, g);
}
}, 'reconcile'),
};
e.FS.filesystems.NATIVEFS_ASYNC = s;
}
o(z, 'initializeNativeFS');
var pe = o(async (e) => {
let t = [];
async function n(s) {
for await (let r of s.values()) (t.push(r), r.kind === 'directory' && (await n(r)));
}
(o(n, 'collect'), await n(e));
let i = new Map();
i.set('.', e);
for (let s of t) {
let r = (await e.resolve(s)).join('/');
i.set(r, s);
}
return i;
}, 'getFsHandles');
var G = W(
'AGFzbQEAAAABDANfAGAAAW9gAW8BfwMDAgECBygCE0pzdl9HZXRFcnJvcl9pbXBvcnQAAA5Kc3ZFcnJvcl9DaGVjawABChMCBwD7AQD7GwsJACAA+xr7FAAL',
);
var ge = (async function () {
if (
!(
globalThis.navigator &&
(/iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' &&
typeof navigator.maxTouchPoints < 'u' &&
navigator.maxTouchPoints > 1))
)
)
try {
let t = await WebAssembly.compile(G);
return await WebAssembly.instantiate(t);
} catch (t) {
if (t instanceof WebAssembly.CompileError) return;
throw t;
}
})();
async function K() {
let e = await ge;
if (e) return e.exports;
let t = Symbol('error marker');
return {
Jsv_GetError_import: o(() => t, 'Jsv_GetError_import'),
JsvError_Check: o((n) => n === t, 'JsvError_Check'),
};
}
o(K, 'getJsvErrorImport');
function q(e) {
let t = { config: e, runtimeEnv: f },
n = {
noImageDecoding: !0,
noAudioDecoding: !0,
noWasmDecoding: !1,
preRun: Ne(e),
print: e.stdout,
printErr: e.stderr,
onExit(i) {
n.exitCode = i;
},
thisProgram: e._sysExecutable,
arguments: e.args,
API: t,
locateFile: o((i) => e.indexURL + i, 'locateFile'),
instantiateWasm: Ie(e.indexURL),
};
return n;
}
o(q, 'createSettings');
function ve(e) {
return function (t) {
let n = '/';
try {
t.FS.mkdirTree(e);
} catch (i) {
(console.error(`Error occurred while making a home directory '${e}':`),
console.error(i),
console.error(`Using '${n}' for a home directory instead`),
(e = n));
}
t.FS.chdir(e);
};
}
o(ve, 'createHomeDirectory');
function be(e) {
return function (t) {
Object.assign(t.ENV, e);
};
}
o(be, 'setEnvironment');
function Ee(e) {
return e
? [
async (t) => {
t.addRunDependency('fsInitHook');
try {
await e(t.FS, { sitePackages: t.API.sitePackages });
} finally {
t.removeRunDependency('fsInitHook');
}
},
]
: [];
}
o(Ee, 'callFsInitHook');
function Pe(e) {
let t = e.HEAPU32[e._Py_Version >>> 2],
n = (t >>> 24) & 255,
i = (t >>> 16) & 255,
s = (t >>> 8) & 255;
return [n, i, s];
}
o(Pe, 'computeVersionTuple');
function he(e) {
let t = j(e);
return async (n) => {
n.API.pyVersionTuple = Pe(n);
let [i, s] = n.API.pyVersionTuple;
(n.FS.mkdirTree('/lib'),
(n.API.sitePackages = `/lib/python${i}.${s}/site-packages`),
n.FS.mkdirTree(n.API.sitePackages),
n.addRunDependency('install-stdlib'));
try {
let r = await t;
n.FS.writeFile(`/lib/python${i}${s}.zip`, r);
} catch (r) {
(console.error('Error occurred while installing the standard library:'), console.error(r));
} finally {
n.removeRunDependency('install-stdlib');
}
};
}
o(he, 'installStdlib');
function Ne(e) {
let t;
return (
e.stdLibURL != null ? (t = e.stdLibURL) : (t = e.indexURL + 'python_stdlib.zip'),
[he(t), ve(e.env.HOME), be(e.env), z, ...Ee(e.fsInit)]
);
}
o(Ne, 'getFileSystemInitializationFuncs');
function Ie(e) {
if (typeof WasmOffsetConverter < 'u') return;
let { binary: t, response: n } = _(e + 'pyodide.asm.wasm'),
i = K();
return function (s, r) {
return (
(async function () {
let { Jsv_GetError_import: a, JsvError_Check: c } = await i;
((s.env.Jsv_GetError_import = a), (s.env.JsvError_Check = c));
try {
let l;
n
? (l = await WebAssembly.instantiateStreaming(n, s))
: (l = await WebAssembly.instantiate(await t, s));
let { instance: d, module: u } = l;
r(d, u);
} catch (l) {
(console.warn('wasm instantiation failed!'), console.warn(l));
}
})(),
{}
);
};
}
o(Ie, 'getInstantiateWasmFunc');
var Y = '314.0.3';
function k(e) {
return e === void 0 || e.endsWith('/') ? e : e + '/';
}
o(k, 'withTrailingSlash');
var U = Y;
async function Se(e = {}) {
if ((await C(), e.lockFileContents && e.lockFileURL))
throw new Error("Can't pass both lockFileContents and lockFileURL");
let t = e.indexURL || (await J());
if (
((t = k(w(t))),
(e.packageBaseUrl = k(e.packageBaseUrl)),
(e.cdnUrl = k(e.packageBaseUrl ?? `https://cdn.jsdelivr.net/pyodide/v${U}/full/`)),
!e.lockFileContents)
) {
let s = e.lockFileURL ?? t + 'pyodide-lock.json';
((e.lockFileContents = H(s)), (e.packageBaseUrl ??= V(s)));
}
((e.indexURL = t), e.packageCacheDir && (e.packageCacheDir = k(w(e.packageCacheDir))));
let n = {
jsglobals: globalThis,
stdin: globalThis.prompt ? () => globalThis.prompt() : void 0,
args: [],
env: {},
packages: [],
packageCacheDir: e.packageBaseUrl,
enableRunUntilComplete: !0,
checkAPIVersion: !0,
BUILD_ID: '2cf7085e96ffaa58f5400af724c388859f9e21586cf6f254da008c60685a5d05',
},
i = Object.assign(n, e);
return ((i.env.HOME ??= '/home/pyodide'), (i.env.PYTHONINSPECT ??= '1'), i);
}
o(Se, 'initializeConfiguration');
function we(e) {
let t = q(e),
n = t.API;
return ((n.lockFilePromise = Promise.resolve(e.lockFileContents)), t);
}
o(we, 'createEmscriptenSettings');
async function _e(e) {
if (e.createPyodideModule) return e.createPyodideModule;
let t = `${e.indexURL}pyodide.asm.mjs`;
return (await O(t)).default;
}
o(_e, 'loadWasmScript');
async function ke(e, t) {
if (!e._loadSnapshot) return;
let n = await e._loadSnapshot,
i = ArrayBuffer.isView(n) ? n : new Uint8Array(n);
return ((t.noInitialRun = !0), (t.INITIAL_MEMORY = i.length), i);
}
o(ke, 'prepareSnapshot');
async function Re(e, t) {
let n = await e(t);
if (t.exitCode !== void 0) throw new n.ExitStatus(t.exitCode);
return n;
}
o(Re, 'instantiatePyodideModule');
function Fe(e, t) {
let n = e.API;
if (
(t.pyproxyToStringRepr && n.setPyProxyToStringMethod(!0),
t.convertNullToNone && n.setCompatNullToNone(!0),
t.toJsLiteralMap && n.setCompatToJsLiteralMap(!0),
n.version !== U && t.checkAPIVersion)
)
throw new Error(
`Pyodide version does not match: '${U}' <==> '${n.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`,
);
e.locateFile = (i) => {
throw i.endsWith('.so')
? new Error(`Failed to find dynamic library "${i}"`)
: new Error(`Unexpected call to locateFile("${i}")`);
};
}
o(Fe, 'configureAPI');
function Ae(e, t, n) {
let i = e.API,
s;
return (t && (s = i.restoreSnapshot(t)), i.finalizeBootstrap(s, n._snapshotDeserializer));
}
o(Ae, 'bootstrapPyodide');
async function Oe(e, t) {
let n = e._api;
return (
n.sys.path.insert(0, ''),
n._pyodide.set_excepthook(),
await n.packageIndexReady,
n.initializeStreams(t.stdin, t.stdout, t.stderr),
e
);
}
o(Oe, 'finalizeSetup');
async function dt(e = {}) {
let t = await Se(e),
n = we(t),
i = await _e(t),
s = await ke(t, n),
r = await Re(i, n);
Fe(r, t);
let a = Ae(r, s, t);
return await Oe(a, t);
}
o(dt, 'loadPyodide');
export { dt as loadPyodide, U as version };
//# sourceMappingURL=pyodide.mjs.map
Binary file not shown.
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env node
// web/scripts/sync-pyodide.mjs — 从 npm 包同步 Pyodide 运行时到 public/pyodide/
//
// 背景: web/public/pyodide/ 下的 Pyodide 运行时 (asm.mjs / asm.wasm / stdlib 等)
// 与 npm 依赖 `pyodide` 里的文件是同一份。把它们提交进仓库有两个坏处 ——
// 一是占仓库体积, 二是 npm 包升版后容易留下不一致的旧副本。
// 因此这 6 个文件改为构建/开发时从 node_modules 复制, 不进仓库。
//
// 例外: fonttools / numpy 两个 wheel 不在 npm 包里 (Pyodide 的依赖清单只登记
// 但不随包分发), 仍需仓库提供, 故保留在 public/pyodide/ 下。
//
// 用法: 由 pnpm dev / pnpm build 自动调用, 也可单独执行以校验环境
// node scripts/sync-pyodide.mjs
import fsp from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const WEB_DIR = path.resolve(HERE, '..');
/** npm 包里的 Pyodide 运行时目录 */
const SRC_DIR = path.join(WEB_DIR, 'node_modules', 'pyodide');
/** Vite 的静态资源目录 (原样拷贝到构建产物) */
const DEST_DIR = path.join(WEB_DIR, 'public', 'pyodide');
/**
* 从 npm 包复制的文件。与 npm 包内同名文件一一对应。
* 增删此列表时, 需同步更新 .gitignore 中对应的忽略项。
*/
const COPY_FILES = [
'pyodide.asm.mjs',
'pyodide.asm.wasm',
'pyodide.js',
'pyodide.mjs',
'pyodide-lock.json',
'python_stdlib.zip',
];
/**
* 仓库保留的文件 (不在 npm 包内), 以及它们应满足的完整性校验。
* 这些 wheel 由 pyodide-lock.json 登记, 版本必须与之一致 ——
* 否则 Pyodide 在 loadPackage() 时会因校验失败而报错。
*/
const KEEP_FILES = [
'fonttools-4.62.1-py3-none-any.whl',
'numpy-2.4.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl',
];
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
/** 读取并解析 lock.json, 返回 { 包名: 条目 } */
async function readLock(p) {
const d = JSON.parse(await fsp.readFile(p, 'utf8'));
return d.packages ?? {};
}
/**
* 校验保留下来的 wheel 与 lock.json 配套。
*
* 这是本机制的主要风险点: wheel 在仓库、lock.json 在 npm 包, 两者的版本可能
* 各自漂移。例如 npm 的 pyodide 升版后 lock.json 引用了新版 fonttools, 而仓库里
* 仍是旧 wheel —— 此时运行时 loadPackage('fonttools') 会因 sha256 不匹配而失败,
* 且只在用户点开「字体编辑」时才暴露。故在此提前拦截。
*/
async function verifyWheels(lock) {
const problems = [];
for (const name of KEEP_FILES) {
const file = path.join(DEST_DIR, name);
let buf;
try {
buf = await fsp.readFile(file);
} catch {
problems.push(`缺少 ${name} (需随仓库提供, 不在 npm 包内)`);
continue;
}
// 在 lock.json 中找到登记该文件的条目, 比对 sha256
const entry = Object.values(lock).find((e) => e.file_name === name);
if (!entry) {
problems.push(
`${name} 未被 pyodide-lock.json 登记 —— npm 的 pyodide 可能已升版, ` +
`请改用新版 wheel 或调整 pyodide 依赖版本`,
);
continue;
}
const expected = entry.sha256;
if (expected && sha256(buf) !== expected) {
problems.push(`${name} 与 lock.json 登记的 sha256 不符 (文件可能损坏或被替换)`);
}
}
return problems;
}
async function main() {
// npm 依赖是否存在 (未安装依赖时给出明确提示, 而不是沉默地跳过)
try {
await fsp.access(SRC_DIR);
} catch {
console.error(`[✗] 未找到 ${path.relative(WEB_DIR, SRC_DIR)}, 请先运行 pnpm install`);
process.exit(1);
}
await fsp.mkdir(DEST_DIR, { recursive: true });
// 1. 从 npm 包复制运行时文件
let copied = 0;
for (const name of COPY_FILES) {
const src = path.join(SRC_DIR, name);
const dest = path.join(DEST_DIR, name);
try {
// 源与目标内容一致时跳过写入: 避免每次构建都触碰文件, 也便于观察实际变化
const [a, b] = await Promise.all([fsp.readFile(src), fsp.readFile(dest).catch(() => null)]);
if (b && a.equals(b)) continue;
await fsp.copyFile(src, dest);
copied++;
} catch (e) {
console.error(`[✗] 复制 ${name} 失败: ${e.message}`);
process.exit(1);
}
}
// 2. 校验留在仓库的 wheel 与 lock.json 配套
const lock = await readLock(path.join(DEST_DIR, 'pyodide-lock.json'));
const problems = await verifyWheels(lock);
if (problems.length) {
console.error('[✗] Pyodide 依赖校验失败:');
for (const p of problems) console.error(` ${p}`);
process.exit(1);
}
const total = (
await Promise.all(
[...COPY_FILES, ...KEEP_FILES].map(async (n) => {
try {
return (await fsp.stat(path.join(DEST_DIR, n))).size;
} catch {
return 0;
}
}),
)
).reduce((a, b) => a + b, 0);
console.log(
copied > 0
? `[*] Pyodide 运行时已同步 (更新 ${copied} 个文件, 共 ${(total / 1048576).toFixed(1)}MB)`
: `[*] Pyodide 运行时已就绪 (${(total / 1048576).toFixed(1)}MB)`,
);
}
await main();
+50 -50
View File
@@ -1,9 +1,9 @@
import { exec, shellQuote, toast } from './ksu';
import { copyFont, pickWghtRange, renderSlots, setApplying, slots } from './slots';
import { applyWghtOverride, getSelectedWghtMode, writeWghtMode } from './wght';
import { invalidateTestFonts } from './testFonts';
import { canApply, copyFont, refreshEnSubset, renderSlots, setApplying, slots } from './slots';
import { getSelectedWghtMode, writeWghtMode } from './wght';
import { writeSlotModes } from './fontFiles';
import { applyBtn } from './dom';
import { FONTS_DIR } from './constants';
import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS } from './constants';
const logDialog = document.getElementById('log-dialog') as any;
const logContent = document.getElementById('log-content')!;
@@ -12,71 +12,71 @@ document.getElementById('log-close')?.addEventListener('click', () => {
logDialog.open = false;
});
async function syncSingleSlot(key: 'hans' | 'hant' | 'en' | 'mono' | 'emoji'): Promise<void> {
const slot = slots[key];
const dest = `${FONTS_DIR}/${key}.ttf`;
if (slot.path) {
if (slot.path !== dest) await copyFont(slot.path, dest);
} else {
await exec(`rm -f ${shellQuote(dest)}`);
}
}
async function syncMultiSlot(key: 'hans' | 'hant' | 'en'): Promise<void> {
const slot = slots[key];
const dir = `${MULTI_DIR}/${key}`;
await exec(`mkdir -p ${shellQuote(dir)}`);
for (const w of MULTI_WEIGHTS) {
const entry = slot.multiWeights?.[w];
const dest = `${dir}/${w}.ttf`;
if (entry?.path) {
if (entry.path !== dest) await copyFont(entry.path, dest);
} else {
const sub = key === 'en' ? ` ${shellQuote(`${dir}/.subset-${w}.ttf`)}` : '';
await exec(`rm -f ${shellQuote(dest)}${sub}`);
}
}
}
async function apply() {
if (!slots.hans.path) return;
if (!canApply()) return;
setApplying(true);
renderSlots();
try {
// 字重范围覆写: 用 UI 当前模式 (持久化到 FONTS/wght-mode.txt), 仅当存在可变字体且模式非 0 时处理
const wghtMode = getSelectedWghtMode();
await writeWghtMode(wghtMode);
const wghtPick = pickWghtRange();
if (wghtMode !== 0 && wghtPick) {
// Go 程序自行读取 wght-map.txt (mode 3)
await applyWghtOverride(wghtMode, wghtPick.min, wghtPick.max);
}
// 保存各槽位模式 (可变字体/多字重) 与字重覆写模式; 两种模式的字体文件互不删除
await writeSlotModes({
hans: slots.hans.mode,
hant: slots.hant.mode,
en: slots.en.mode,
});
await writeWghtMode(getSelectedWghtMode());
// 启动加载的字体 path 即 FONT/ 内的文件, 无需再复制
if (slots.hans.path !== `${FONTS_DIR}/hans.ttf`) {
await copyFont(slots.hans.path, `${FONTS_DIR}/hans.ttf`);
}
if (slots.hant.path) {
if (slots.hant.path !== `${FONTS_DIR}/hant.ttf`) {
await copyFont(slots.hant.path, `${FONTS_DIR}/hant.ttf`);
for (const key of ['hans', 'hant', 'en'] as const) {
if (slots[key].mode === 'multi') {
await syncMultiSlot(key);
} else {
await syncSingleSlot(key);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/hant.ttf`)}`);
}
if (slots.en.path) {
if (slots.en.path !== `${FONTS_DIR}/en.ttf`) {
await copyFont(slots.en.path, `${FONTS_DIR}/en.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/en.ttf`)}`);
}
if (slots.mono.path) {
if (slots.mono.path !== `${FONTS_DIR}/mono.ttf`) {
await copyFont(slots.mono.path, `${FONTS_DIR}/mono.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/mono.ttf`)}`);
}
if (slots.emoji.path) {
if (slots.emoji.path !== `${FONTS_DIR}/emoji.ttf`) {
await copyFont(slots.emoji.path, `${FONTS_DIR}/emoji.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/emoji.ttf`)}`);
}
await syncSingleSlot('mono');
await syncSingleSlot('emoji');
// apply.sh 会完成系统字体复制、英文单/多字重子集化以及 fontmm-wght -sync XML 同步
const { errno, stdout, stderr } = await exec('sh /data/adb/modules/FontMM/apply.sh');
if (errno !== 0) throw new Error(stderr || 'apply.sh 执行失败');
if (errno !== 0) throw new Error(stderr || stdout || 'apply.sh 执行失败');
if (logContent && logDialog) {
logContent.textContent = stdout;
logDialog.open = true;
}
toast('字体已应用,重启后生效');
// 字体已变化: 下次进入测试页时重新加载
invalidateTestFonts();
document.dispatchEvent(new CustomEvent('fonts-changed'));
} catch (e) {
toast(`应用失败: ${String(e)}`);
} finally {
setApplying(false);
// 应用后刷新英文子集结果 (issue #14): 子集大小只有跑过 apply.sh 才知道
await refreshEnSubset();
renderSlots();
}
}
+17
View File
@@ -1,10 +1,27 @@
// 全局路径与外部链接常量
export const FONTS_DIR = '/data/adb/modules/FontMM/FONTS';
export const MULTI_DIR = `${FONTS_DIR}/multi`;
export const SLOT_MODES_FILE = `${FONTS_DIR}/slot-modes.txt`;
export const WEBROOT_DIR = '/data/adb/modules/FontMM/webroot';
export const TEST_FONT_DIR = `${WEBROOT_DIR}/fonts-test`;
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制)
export const WGHT_BIN = '/data/adb/modules/FontMM/tools/fontmm-wght';
// 多字重模式支持的标准 9 档字重
export const MULTI_WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900] as const;
export const WEIGHT_LABELS: Record<number, string> = {
100: '淡体',
200: '特细',
300: '细体',
400: '标准',
500: '适中',
600: '次粗',
700: '粗体',
800: '特粗',
900: '浓体',
};
// 捐献 (支付宝/爱发电) 与开发者主页 (浏览器) 链接
export const DONATE_ALIPAY_URI =
'alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/2m615805eflrafv8ipc2p15';
+101 -5
View File
@@ -1,20 +1,33 @@
import { exec, shellQuote } from './ksu';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS, SLOT_MODES_FILE, TEST_FONT_DIR } from './constants';
import { formatSize } from './fontInfo';
import type { MultiSlotKey, SlotMode, WeightLevel } from './types';
// 复制 FONT/ 到 webroot/fonts-test, 供页面加载与名称解析
// 复制 FONTS/ 到 webroot/fonts-test, 供页面加载与名称解析
// (WebView 无法直接访问模块外部目录, 符号链接在真机也不可靠, 直接复制)
//
// 只复制 5 个槽位对应的文件: FONTS/ 下还可能有 apply.sh 生成的中转文件
// (如 .en-subset.ttf), 它们不是用户选择的字体, 复制过去只是浪费开销。
// 只复制单字体槽位与多字重槽位的用户字体, 跳过 .en-subset.ttf / .subset-*.ttf 等中转文件。
// 结尾加 `:` 保证任一可选文件不存在时整体退出码仍为 0 (issue #11)。
const SLOT_FILES = ['hans.ttf', 'hant.ttf', 'en.ttf', 'mono.ttf', 'emoji.ttf'];
const MULTI_SLOTS: MultiSlotKey[] = ['hans', 'hant', 'en'];
export async function ensureFontsCopy(): Promise<string[]> {
const multiCmds: string[] = [];
for (const s of MULTI_SLOTS) {
for (const w of MULTI_WEIGHTS) {
multiCmds.push(
`[ -f '${MULTI_DIR}/${s}/${w}.ttf' ] && cp -f '${MULTI_DIR}/${s}/${w}.ttf' '${TEST_FONT_DIR}/multi-${s}-${w}.ttf'`,
);
}
}
const copyCmd = [
`rm -rf '${TEST_FONT_DIR}'`,
`mkdir -p '${TEST_FONT_DIR}'`,
...SLOT_FILES.map(
(f) => `[ -f '${FONTS_DIR}/${f}' ] && cp -f '${FONTS_DIR}/${f}' '${TEST_FONT_DIR}/${f}'`,
),
...multiCmds,
':', // 兜底: 保证整体退出码为 0
].join('\n');
try {
const { errno } = await exec(copyCmd);
@@ -25,7 +38,7 @@ export async function ensureFontsCopy(): Promise<string[]> {
return listFontsDir();
}
// 列出 fonts-test/ 下的字体文件 (每行一个完整路径)
// 列出 fonts-test/ 下的字体文件名 (不含目录前缀)
export async function listFontsDir(): Promise<string[]> {
try {
const { errno, stdout } = await exec(
@@ -41,3 +54,86 @@ export async function listFontsDir(): Promise<string[]> {
return [];
}
}
// 读取槽位模式配置 (FONTS/slot-modes.txt), 缺失时全部默认 'single'
export async function readSlotModes(): Promise<Record<MultiSlotKey, SlotMode>> {
const modes: Record<MultiSlotKey, SlotMode> = { hans: 'single', hant: 'single', en: 'single' };
try {
const { errno, stdout } = await exec(`cat ${shellQuote(SLOT_MODES_FILE)} 2>/dev/null || true`);
if (errno !== 0) return modes;
for (const raw of stdout.split('\n')) {
const line = raw.split('#')[0].trim();
const idx = line.indexOf('=');
if (idx <= 0) continue;
const k = line.slice(0, idx).trim();
const v = line.slice(idx + 1).trim();
if ((k === 'hans' || k === 'hant' || k === 'en') && (v === 'single' || v === 'multi')) {
modes[k] = v;
}
}
} catch {
// 忽略读取失败
}
return modes;
}
// 写入槽位模式配置 (FONTS/slot-modes.txt)
export async function writeSlotModes(modes: Record<MultiSlotKey, SlotMode>): Promise<void> {
const content = `hans=${modes.hans}\nhant=${modes.hant}\nen=${modes.en}`;
await exec(
`mkdir -p ${shellQuote(FONTS_DIR)} && printf '%s\\n' ${shellQuote(content)} > ${shellQuote(SLOT_MODES_FILE)}`,
);
}
// 英文字体子集文件: apply.sh 子集化成功时写入 FONTS/.en-subset.ttf (issue #10),
// 安装到 system/fonts 的就是它, 大小通常比原字体小两个数量级 (issue #14)。
export const EN_SUBSET_FILE = `${FONTS_DIR}/.en-subset.ttf`;
// 读取英文单字体子集大小 (无子集返回 null)。
// 要求子集比 en.ttf 新 —— 换过英文字体但还没重新应用时, 旧子集不该继续展示。
export async function getEnSubsetSizeText(): Promise<string | null> {
// dev 假数据: 真机没应用过就没有该文件, 徽标无从预览
if (import.meta.env.DEV) return '218 KB';
try {
const subset = shellQuote(EN_SUBSET_FILE);
const { errno, stdout } = await exec(
`[ -f ${subset} ] && [ ${subset} -nt ${shellQuote(`${FONTS_DIR}/en.ttf`)} ] && wc -c < ${subset}`,
);
if (errno !== 0) return null;
const bytes = Number(stdout.trim());
return Number.isFinite(bytes) && bytes > 0 ? formatSize(bytes) : null;
} catch {
return null;
}
}
// 读取英文多字重各档位的子集大小 (无子集时不包含该字重)
export async function getEnMultiSubsetSizes(
weights: WeightLevel[],
): Promise<Partial<Record<WeightLevel, string>>> {
const out: Partial<Record<WeightLevel, string>> = {};
if (weights.length === 0) return out;
if (import.meta.env.DEV) {
for (const w of weights) out[w] = `${170 + Math.round(w / 20)} KB`;
return out;
}
const checks = weights.map((w) => {
const sub = shellQuote(`${MULTI_DIR}/en/.subset-${w}.ttf`);
const orig = shellQuote(`${MULTI_DIR}/en/${w}.ttf`);
return `if [ -f ${sub} ] && [ ${sub} -nt ${orig} ]; then echo "${w}:$(wc -c < ${sub})"; fi`;
});
try {
const { errno, stdout } = await exec(checks.join('; '));
if (errno !== 0) return out;
for (const line of stdout.split('\n')) {
const m = line.trim().match(/^(\d+):(\d+)$/);
if (!m) continue;
const w = Number(m[1]) as WeightLevel;
const bytes = Number(m[2]);
if (Number.isFinite(bytes) && bytes > 0) out[w] = formatSize(bytes);
}
} catch {
// 忽略读取失败
}
return out;
}
+39 -9
View File
@@ -31,6 +31,12 @@ function extractWghtRange(font: any): string | undefined {
return `${Math.round(wght.minValue)}-${Math.round(wght.maxValue)}`;
}
// 字体体积展示: 1MB 以下用 KB (子集化结果常在百 KB 量级, 用 MB 会显示成 0.2 MB 看不出量级)
export function formatSize(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
// 读取 fonts-test/ 下字体文件的名称与大小 (WebView 仅能访问 webroot 内文件)
export async function readFontInfo(file: string): Promise<FontInfo> {
// dev 假数据: 模拟各槽位字体的名称/大小/可变标识
@@ -46,14 +52,38 @@ export async function readFontInfo(file: string): Promise<FontInfo> {
'emoji.ttf': { name: 'Noto Color Emoji', size: '9.8 MB', variable: false },
};
const mock = MOCK_FONT_INFO[file];
return mock
? {
name: mock.name,
sizeText: mock.size,
isVariable: mock.variable,
wghtRange: mock.wght,
}
: {};
if (mock) {
return {
name: mock.name,
sizeText: mock.size,
isVariable: mock.variable,
wghtRange: mock.wght,
};
}
const multiMatch = file.match(/^multi-(hans|hant|en)-(\d+)\.ttf$/);
if (multiMatch) {
const slot = multiMatch[1];
const w = multiMatch[2];
const baseName =
slot === 'hans' ? 'PingFang SC' : slot === 'hant' ? 'PingFang TC' : 'SF Pro Text';
const weightLabel: Record<string, string> = {
'100': 'Thin',
'200': 'ExtraLight',
'300': 'Light',
'400': 'Regular',
'500': 'Medium',
'600': 'SemiBold',
'700': 'Bold',
'800': 'ExtraBold',
'900': 'Black',
};
return {
name: `${baseName} ${weightLabel[w] ?? w}`,
sizeText: slot === 'en' ? '640 KB' : '11.8 MB',
isVariable: false,
};
}
return {};
}
try {
const res = await fetch(`fonts-test/${file}`);
@@ -61,7 +91,7 @@ export async function readFontInfo(file: string): Promise<FontInfo> {
const buf = await res.arrayBuffer();
const font = opentype.parse(buf);
const name = extractFamilyName(font);
const sizeText = `${(buf.byteLength / 1024 / 1024).toFixed(1)} MB`;
const sizeText = formatSize(buf.byteLength);
return {
name: name ?? undefined,
sizeText,
+60 -49
View File
@@ -12,25 +12,42 @@ export interface FileItem {
size?: string;
}
export class FontFilePicker {
private currentPath = '/storage/emulated/0';
private dialogEl!: HTMLElement;
private listEl!: HTMLElement;
private pathEl!: HTMLElement;
private onSelectCallback: (path: string, fileName: string) => void;
/** 选中文件时的回调: 完整路径与文件名 */
export type FontSelectHandler = (path: string, fileName: string) => void;
constructor(onSelect: (path: string, fileName: string) => void) {
this.onSelectCallback = onSelect;
const DEFAULT_PATH = '/storage/emulated/0';
/**
* 文件选择器。全局只应存在一个实例 (下方导出 fontPicker) —— 对话框 DOM 是
* 单例 (按 id 复用), 若允许第二个实例, 它会复用这份 DOM 却拿不到返回/取消
* 按钮的监听 (initDialog 命中已有元素时直接返回), 于是返回键按上一个实例的
* 过期路径导航、选中文件也回调给上一个实例, 表现为「返回跳两层」「在别的
* 目录选文件没反应」(issue #13)。因此选中回调改为每次 show 时传入。
*/
class FontFilePicker {
private currentPath = DEFAULT_PATH;
private dialogEl: any = null;
private listEl: HTMLElement | null = null;
private pathEl: HTMLElement | null = null;
private onSelect: FontSelectHandler | null = null;
/** 打开选择器: initialPath 为起始目录, onSelect 为本次选择的处理函数 */
public show(initialPath: string, onSelect: FontSelectHandler): void {
this.initDialog();
this.onSelect = onSelect;
this.currentPath = initialPath || DEFAULT_PATH;
this.pathEl!.textContent = this.currentPath;
this.dialogEl.open = true;
void this.loadDirectory(this.currentPath);
}
public hide(): void {
if (this.dialogEl) this.dialogEl.open = false;
this.onSelect = null;
}
private initDialog(): void {
if (document.getElementById('picker-dialog')) {
this.dialogEl = document.getElementById('picker-dialog')!;
this.listEl = document.getElementById('picker-list')!;
this.pathEl = document.getElementById('picker-path')!;
return;
}
if (this.dialogEl) return;
const dialogHTML = `
<md-dialog id="picker-dialog" class="font-picker-dialog">
@@ -41,7 +58,7 @@ export class FontFilePicker {
</md-icon-button>
<div class="picker-path-group">
<div class="picker-subtitle">选择字体文件</div>
<div id="picker-path" class="picker-path-text">/storage/emulated/0</div>
<div id="picker-path" class="picker-path-text">${DEFAULT_PATH}</div>
</div>
</div>
</div>
@@ -57,22 +74,29 @@ export class FontFilePicker {
`;
document.body.insertAdjacentHTML('beforeend', dialogHTML);
this.dialogEl = document.getElementById('picker-dialog')!;
this.listEl = document.getElementById('picker-list')!;
this.pathEl = document.getElementById('picker-path')!;
this.dialogEl = document.getElementById('picker-dialog');
this.listEl = document.getElementById('picker-list');
this.pathEl = document.getElementById('picker-path');
document.getElementById('picker-back-btn')?.addEventListener('click', () => this.navigateUp());
document.getElementById('picker-cancel-btn')?.addEventListener('click', () => this.hide());
}
public show(initialPath = '/storage/emulated/0'): void {
this.currentPath = initialPath;
(this.dialogEl as any).open = true;
this.loadDirectory(this.currentPath);
}
// 列表项用事件委托: 只绑定一次, 渲染只替换内容, 不重复挂监听
this.listEl!.addEventListener('click', (e) => {
const item = (e.target as HTMLElement).closest('.picker-item') as HTMLElement | null;
if (!item) return;
const name = item.dataset.name!;
public hide(): void {
(this.dialogEl as any).open = false;
if (item.dataset.isdir === 'true') {
this.currentPath = this.currentPath === '/' ? `/${name}` : `${this.currentPath}/${name}`;
void this.loadDirectory(this.currentPath);
} else {
const fullPath = `${this.currentPath}/${name}`;
const handler = this.onSelect;
this.hide();
handler?.(fullPath, name);
}
});
}
private navigateUp(): void {
@@ -80,22 +104,22 @@ export class FontFilePicker {
const parts = this.currentPath.split('/').filter(Boolean);
parts.pop();
this.currentPath = parts.length === 0 ? '/' : '/' + parts.join('/');
this.loadDirectory(this.currentPath);
void this.loadDirectory(this.currentPath);
}
private async loadDirectory(path: string): Promise<void> {
this.pathEl.textContent = path;
this.listEl.innerHTML = `<div class="picker-loading">正在读取目录...</div>`;
this.pathEl!.textContent = path;
this.listEl!.innerHTML = `<div class="picker-loading">正在读取目录...</div>`;
try {
const { items, failed } = await this.readDir(path);
if (failed) {
this.listEl.innerHTML = `<div class="picker-error">无法读取该目录</div>`;
this.listEl!.innerHTML = `<div class="picker-error">无法读取该目录</div>`;
return;
}
this.renderList(items);
} catch (e) {
this.listEl.innerHTML = `<div class="picker-error">读取目录异常: ${String(e)}</div>`;
this.listEl!.innerHTML = `<div class="picker-error">读取目录异常: ${String(e)}</div>`;
}
}
@@ -140,7 +164,7 @@ export class FontFilePicker {
private renderList(items: FileItem[]): void {
if (items.length === 0) {
this.listEl.innerHTML = `
this.listEl!.innerHTML = `
<div class="picker-empty">
<md-icon>find_in_page</md-icon>
<span>此目录下没有 .ttf 字体文件</span>
@@ -148,7 +172,7 @@ export class FontFilePicker {
return;
}
this.listEl.innerHTML = items
this.listEl!.innerHTML = items
.map(
(item) => `
<md-list-item class="picker-item ${item.isDir ? 'is-dir' : 'is-file'}" data-name="${item.name}" data-isdir="${item.isDir}">
@@ -165,21 +189,8 @@ export class FontFilePicker {
`,
)
.join('');
this.listEl.querySelectorAll('.picker-item').forEach((el) => {
el.addEventListener('click', () => {
const name = (el as HTMLElement).dataset.name!;
const isDir = (el as HTMLElement).dataset.isdir === 'true';
if (isDir) {
this.currentPath = this.currentPath === '/' ? `/${name}` : `${this.currentPath}/${name}`;
this.loadDirectory(this.currentPath);
} else {
const fullPath = `${this.currentPath}/${name}`;
this.onSelectCallback(fullPath, name);
this.hide();
}
});
});
}
}
/** 全局唯一的文件选择器实例 (见 FontFilePicker 的说明) */
export const fontPicker = new FontFilePicker();
+22
View File
@@ -9,3 +9,25 @@ export function averagedAxis(min: number, max: number, w: number): number {
if (w < 400) return Math.floor(min + ((400 - min) * (w - 100)) / 300);
return Math.floor(400 + ((max - 400) * (w - 400)) / 500);
}
/**
* 从已选字重列表中挑选最接近 target 的档位 (与 Go 引擎 NearestWeight 保持一致)。
* 距离相等时: target >= 400 偏向更重档位, target < 400 偏向更轻档位。
*/
export function nearestWeight(available: number[], target: number): number {
if (available.length === 0) return 400;
let best = available[0];
let bestDist = Math.abs(best - target);
for (let i = 1; i < available.length; i++) {
const w = available[i];
const d = Math.abs(w - target);
if (
d < bestDist ||
(d === bestDist && ((target >= 400 && w > best) || (target < 400 && w < best)))
) {
best = w;
bestDist = d;
}
}
return best;
}
+83 -12
View File
@@ -31,14 +31,41 @@ const FAKE_FS: Record<string, { dirs: string[]; fonts: string[]; files: string[]
files: ['a.pdf'],
},
'/storage/emulated/0/Fonts': {
dirs: [],
dirs: ['PingFang_SC'],
fonts: ['OPPOSans.ttf', 'SourceHanSansCN.ttf', 'Inter-Variable.otf'],
files: [],
},
'/storage/emulated/0/Fonts/PingFang_SC': {
dirs: [],
fonts: [
'PingFangSC-Thin.ttf',
'PingFangSC-Light.ttf',
'PingFangSC-Regular.ttf',
'PingFangSC-Medium.ttf',
'PingFangSC-Semibold.ttf',
'PingFangSC-Bold.ttf',
],
files: [],
},
'/storage/emulated/0/Documents': { dirs: [], fonts: [], files: ['notes.txt'] },
'/storage/emulated/0/字体': { dirs: [], fonts: ['思源黑体.ttf', '霞鹜文楷.ttf'], files: [] },
};
// dev 模式保存内存状态, 便于测试单/多字重切换与页面刷新状态一致
let mockSlotModes = 'hans=single\nhant=single\nen=single';
const MOCK_TEST_FONTS = [
'hans.ttf',
'hant.ttf',
'en.ttf',
'mono.ttf',
'emoji.ttf',
'multi-hans-300.ttf',
'multi-hans-400.ttf',
'multi-hans-700.ttf',
'multi-en-400.ttf',
'multi-en-700.ttf',
];
async function mockExec(command: string): Promise<ExecResult> {
const fake = (stdout = ''): ExecResult => ({ errno: 0, stdout, stderr: '' });
const fail = (stderr: string): ExecResult => ({ errno: 1, stdout: '', stderr });
@@ -47,6 +74,15 @@ async function mockExec(command: string): Promise<ExecResult> {
const slowFail = (stderr: string) =>
new Promise<ExecResult>((r) => setTimeout(() => r(fail(stderr)), 200));
// 字体测试: 模拟 FONT 字体已放入 webroot/fonts-test, 返回可用字体列表
// (须放在通用 find 匹配之前, 否则 listFontsDir 的无 -print0 命令会被拦截)
if (command.includes('fonts-test')) {
if (command.includes('-type f')) {
return slow(MOCK_TEST_FONTS.join('\n'));
}
return fake('');
}
// find 命令: 解析路径与类型 (d/f), 返回假目录/文件, 以 NUL 分隔 (与 -print0 一致)
if (command.startsWith('find ')) {
const m = command.match(
@@ -61,15 +97,29 @@ async function mockExec(command: string): Promise<ExecResult> {
return slow(lines.join('\0'));
}
// 字体测试: 模拟 FONT 字体已放入 webroot/fonts-test, 返回可用字体列表
if (command.includes('fonts-test')) {
return slow('hans.ttf\nhant.ttf\nen.ttf\nmono.ttf\nemoji.ttf');
// 槽位模式读写: FONTS/slot-modes.txt
if (command.includes('slot-modes.txt')) {
if (command.includes('printf')) {
const m = command.match(/printf '%s\\n' '([^']*)'/);
if (m) mockSlotModes = m[1];
return fake('');
}
return slow(mockSlotModes);
}
if (command.includes('mkdir -p')) return fake('');
if (command.includes('rm -f')) return fake('');
if (command.includes('cp -f')) return fake('');
if (command.includes('apply.sh')) {
return fake('[*] 安装: SysSans-Hans-Regular.ttf (模拟)\n[*] 全部完成, 重启后生效 (模拟)');
const lines = ['[*] 安装简体字体...', '[*] 安装: SysSans-Hans-Regular.ttf (模拟)'];
if (mockSlotModes.includes('hans=multi')) {
lines.push('[*] 安装: FontMM-Hans-300.ttf (模拟)', '[*] 安装: FontMM-Hans-700.ttf (模拟)');
}
if (mockSlotModes.includes('en=multi')) {
lines.push('[*] 检查英文多字重 400 (模拟)', '[*] 安装: FontMM-En-700.ttf (模拟)');
}
lines.push('[✓] 字体配置 XML 同步完成 (模拟)', '[*] 全部完成, 重启后生效 (模拟)');
return fake(lines.join('\n'));
}
// 字重覆写模式: cat 返回已选 '1' (裁切), echo 写入模拟成功
if (command.includes('wght-mode.txt')) {
@@ -176,9 +226,9 @@ async function mockExec(command: string): Promise<ExecResult> {
);
}
// 字体预热器状态检测 (模拟: 库已安装 + 检测到 Zygisk Next)
// 字体预热器状态检测 (模拟: 库已安装 + 检测到 Zygisk Next, 模块 ID 用真实的 zygisksu)
if (command.includes('LIB:yes') && command.includes('PROV:')) {
return slow('LIB:yes\nMAGISK:na\nPROV:zygisknext');
return slow('LIB:yes\nMAGISK:na\nPROV:zygisksu');
}
if (command.includes('ro.product.model')) return slow('Pixel 8 Pro (模拟设备)');
@@ -284,15 +334,19 @@ export async function getSystemInfo(): Promise<SystemInfo> {
'ro.product.cpu.abi',
];
const { errno, stdout } = await exec(
`${props.map((p) => `getprop ${p}`).join('; ')}; ls -1 '${MODULE_FONTS_DIR}'/*.ttf 2>/dev/null`,
`${props.map((p) => `getprop ${p}`).join('; ')}; find '${MODULE_FONTS_DIR}' -maxdepth 3 -type f -name '*.ttf' 2>/dev/null || true`,
);
if (errno === 0) {
const lines = stdout.split('\n');
[info.androidVersion, info.sdk, info.deviceModel, info.abi] = lines
.slice(0, 4)
.map((l) => l.trim());
// 剩余行是 FONTS/ 中实际存在的字体文件名
info.fontCount = lines.slice(4).filter((l) => l.trim() && l.endsWith('.ttf')).length;
// 剩余行是 FONTS/ 与 FONTS/multi/ 中的用户字体 (排除隐藏中转文件如 .en-subset.ttf)
info.fontCount = lines.slice(4).filter((raw) => {
const p = raw.trim();
const base = p.slice(p.lastIndexOf('/') + 1);
return p.endsWith('.ttf') && !base.startsWith('.');
}).length;
}
} catch {
// 读取失败时保持空值, 由 UI 显示占位
@@ -334,8 +388,16 @@ export async function getPreloaderStatus(): Promise<PreloaderStatus> {
`if [ -f '${ZYGISK_LIB}' ]; then echo 'LIB:yes'; else echo 'LIB:no'; fi`,
// 2. Magisk 内置 Zygisk 开关 (值为 1 表示启用)
`if [ -f /data/adb/magisk/magisk ]; then v=$(/data/adb/magisk/magisk --sqlite "SELECT value FROM settings WHERE key='zygisk';" 2>/dev/null | tr -d '\\r'); if [ "$v" = "1" ]; then echo 'MAGISK:yes'; else echo 'MAGISK:no'; fi; else echo 'MAGISK:na'; fi`,
// 3. 独立 Zygisk 提供者模块 (各实现布局不同, 逐一识别)
`for d in /data/adb/modules/*; do [ -d "$d" ] || continue; n=$(basename "$d"); [ "$n" = "FontMM" ] && continue; [ -f "$d/disable" ] && continue; if [ -d "$d/zygisk" ]; then echo "PROV:$n"; elif [ -f "$d/lib64/libzygisk.so" ] || [ -f "$d/lib/libzygisk.so" ]; then echo "PROV:$n"; elif [ -f "$d/bin/zygisk-ptrace64" ] || [ -f "$d/bin/zygiskd64" ]; then echo "PROV:$n"; fi; done`,
// 3. 独立 Zygisk 提供者模块
// 判据是提供者**独有**的文件: lib{64}/libzygisk.so (核心库) 或
// bin/zygiskd{64,32} (守护进程)。注意不能以 zygisk/ 目录判断 ——
// 那是「Zygisk 模块」(消费者) 的标志, 任何自带 zygisk/<abi>.so 的
// 模块都有 (本模块自己也有), 据此判断会把消费者误认成提供者。
// 这些文件名取自 Zygisk Next 与 ReZygisk 的实际安装布局。
`for d in /data/adb/modules/*; do [ -d "$d" ] || continue; n=$(basename "$d"); [ "$n" = "FontMM" ] && continue; [ -f "$d/disable" ] && continue; for f in "$d/lib64/libzygisk.so" "$d/lib/libzygisk.so" "$d/bin/zygiskd64" "$d/bin/zygiskd32" "$d/bin/zygiskd" "$d/lib64/libzn_loader.so" "$d/lib/libzn_loader.so"; do if [ -f "$f" ]; then echo "PROV:$n"; break; fi; done; done`,
// 4. 管理器内置 Zygisk (如 KernelSU / Sukisu 的内置实现): 无独立提供者模块,
// 仅由管理器自身提供, 以内置标记文件是否存在为准。
`if [ -f /data/adb/ksu/.builtin_zygisk ]; then echo 'KSU:yes'; else echo 'KSU:no'; fi`,
].join('; ');
const { errno, stdout } = await exec(cmd);
@@ -360,12 +422,21 @@ export async function getPreloaderStatus(): Promise<PreloaderStatus> {
// 模块目录名可读性较差 (如 rezygisk), 做一次友好化映射
const friendly: Record<string, string> = {
rezygisk: 'ReZygisk',
// Zygisk Next 的模块 ID 是 zygisksu (取自其 module.prop)
zygisksu: 'Zygisk Next',
zygisknext: 'Zygisk Next',
'zygisk-next': 'Zygisk Next',
};
status.zygiskReady = true;
status.provider = friendly[name.toLowerCase()] ?? name;
}
// 管理器内置 Zygisk (KernelSU / Sukisu 等): 未识别到独立提供者时,
// 以内置标记文件的存在为准。
if (!status.zygiskReady && lines.includes('KSU:yes')) {
status.zygiskReady = true;
status.provider = '管理器内置 Zygisk';
}
} catch {
// 读取失败保持默认值 (未安装 / 不可用)
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { slots } from './slots';
import { canApply } from './slots';
import { loadHome } from './home';
import { loadTestFonts } from './testFonts';
import { applyBtn, rebootBtn } from './dom';
@@ -42,8 +42,8 @@ function showView(index: number) {
views.forEach((v, i) => v.classList.toggle('active', i === target));
// 轨道滑动切换动画
viewTrack.style.transform = `translateX(${-target * 100}%)`;
// 悬浮应用按钮仅配置页显示, 且未选简体字体时不展示
applyFab.style.display = target === 1 && slots.hans.path ? '' : 'none';
// 悬浮应用按钮仅配置页显示, 且简体槽位在当前模式下已配置字体时才展示
applyFab.style.display = target === 1 && canApply() ? '' : 'none';
// 重启按钮仅主页显示 (visibility 保持顶栏布局不跳动)
if (rebootBtn) rebootBtn.style.visibility = target === 0 ? 'visible' : 'hidden';
// 同步底部导航高亮
+380 -73
View File
@@ -1,42 +1,76 @@
import { FontFilePicker } from './fontPicker';
import { fontPicker } from './fontPicker';
import { exec, shellQuote } from './ksu';
import { readFontInfo } from './fontInfo';
import { ensureFontsCopy } from './fontFiles';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
import {
ensureFontsCopy,
getEnMultiSubsetSizes,
getEnSubsetSizeText,
readSlotModes,
} from './fontFiles';
import { FONTS_DIR, MULTI_DIR, MULTI_WEIGHTS, TEST_FONT_DIR, WEIGHT_LABELS } from './constants';
import { nearestWeight } from './fontsXml';
import { applyBtn } from './dom';
import type { FontSlot } from './types';
import type {
FontSlot,
MultiSlotKey,
MultiWeightEntry,
SlotKey,
SlotMode,
WeightLevel,
} from './types';
export const SLOT_KEYS = ['hans', 'hant', 'en', 'mono', 'emoji'] as const;
export type SlotKey = (typeof SLOT_KEYS)[number];
export type { SlotKey };
function createEmptyMultiWeights(): Record<WeightLevel, MultiWeightEntry> {
const out = {} as Record<WeightLevel, MultiWeightEntry>;
for (const w of MULTI_WEIGHTS) {
out[w] = { weight: w, path: null, fileName: '' };
}
return out;
}
export const slots: Record<SlotKey, FontSlot> = {
hans: {
key: 'hans',
title: '中文简体',
supportsMulti: true,
mode: 'single',
path: null,
fileName: '',
multiWeights: createEmptyMultiWeights(),
},
hant: {
key: 'hant',
title: '中文繁体',
supportsMulti: true,
mode: 'single',
path: null,
fileName: '',
multiWeights: createEmptyMultiWeights(),
},
en: {
key: 'en',
title: '英文 & 数字',
supportsMulti: true,
mode: 'single',
path: null,
fileName: '',
multiWeights: createEmptyMultiWeights(),
},
mono: {
key: 'mono',
title: '等宽字体',
supportsMulti: false,
mode: 'single',
path: null,
fileName: '',
},
emoji: {
key: 'emoji',
title: 'Emoji 表情',
supportsMulti: false,
mode: 'single',
path: null,
fileName: '',
},
@@ -47,7 +81,8 @@ const slotsEl = document.getElementById('slots')!;
const wghtModeSelect = document.getElementById('wght-mode-select') as any;
const wghtModeSub = document.getElementById('wght-mode-sub');
let pickingKey: SlotKey = 'hans';
// 记住上次选择文件的目录, 多字重连续挑选同目录字体时无需重复层层翻找
let lastPickerDir = '/storage/emulated/0';
// 应用流程进行中: renderSlots 据此禁用/启用应用按钮
export let applying = false;
@@ -55,103 +90,327 @@ export function setApplying(v: boolean): void {
applying = v;
}
const picker = new FontFilePicker((path, name) => {
const slot = slots[pickingKey];
slot.path = path;
slot.fileName = name;
renderSlots();
void refreshSlotInfo(slot);
});
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function notifyFontsChanged(): void {
document.dispatchEvent(new CustomEvent('fonts-changed'));
}
function rememberDir(filePath: string): void {
const idx = filePath.lastIndexOf('/');
if (idx > 0) lastPickerDir = filePath.slice(0, idx);
}
/** 返回某个多字重槽位已选的升序字重列表 */
export function getSelectedMultiWeights(slot: FontSlot): WeightLevel[] {
if (!slot.multiWeights) return [];
return MULTI_WEIGHTS.filter((w) => Boolean(slot.multiWeights?.[w]?.path));
}
/** 判断槽位在当前激活模式下是否已配置字体 */
export function isSlotConfigured(slot: FontSlot): boolean {
if (slot.mode === 'multi') return getSelectedMultiWeights(slot).length > 0;
return Boolean(slot.path);
}
/** 是否满足应用前提 (中文简体必须在当前模式下至少配好 1 份字体) */
export function canApply(): boolean {
return isSlotConfigured(slots.hans);
}
function pickFontFor(key: SlotKey): void {
fontPicker.show(lastPickerDir, (path, name) => {
rememberDir(path);
const slot = slots[key];
slot.path = path;
slot.fileName = name;
notifyFontsChanged();
renderSlots();
void refreshSlotInfo(slot);
});
}
function pickMultiFontFor(key: MultiSlotKey, weight: WeightLevel): void {
fontPicker.show(lastPickerDir, (path, name) => {
rememberDir(path);
const slot = slots[key];
if (!slot.multiWeights) slot.multiWeights = createEmptyMultiWeights();
const entry = slot.multiWeights[weight];
entry.path = path;
entry.fileName = name;
entry.sizeText = undefined;
entry.subsetSizeText = undefined;
notifyFontsChanged();
renderSlots();
void refreshMultiWeightInfo(slot, weight);
});
}
function hansFallbackSummary(): string {
if (slots.hans.mode === 'multi') {
const count = getSelectedMultiWeights(slots.hans).length;
return count > 0 ? `中文简体(多字重 ${count} 档)` : '中文简体';
}
return slots.hans.fileName || '中文简体';
}
// 未选择时的占位文案: 回退可视化 (WYSIWYG)
function slotPlaceholder(slot: FontSlot): string {
if (slot.path) return slot.fileName;
if (slot.key === 'hans') return '未选择字体文件';
if (slots.hans.path) {
if (isSlotConfigured(slots.hans)) {
if (slot.key === 'mono') return '未选择,保持系统等宽字体';
if (slot.key === 'emoji') return '未选择,保持系统 Emoji';
return `默认使用:${slots.hans.fileName}`;
return `默认使用:${hansFallbackSummary()}`;
}
return '未选择字体文件';
}
// 根据是否有可变字体决定是否禁用字重覆写 (emoji/mono 不计入)
// 根据单字体模式是否存在可变字体决定是否启用字重覆写 (多字重槽位 / mono / emoji 不计入)
export function updateWghtModeDisabled(): void {
const hasVar = ['hans', 'hant', 'en'].some((k) => slots[k as 'hans']?.isVariable);
const hasVar = (['hans', 'hant', 'en'] as const).some(
(k) => slots[k].mode === 'single' && Boolean(slots[k].path) && Boolean(slots[k].isVariable),
);
const hasAnyMulti = (['hans', 'hant', 'en'] as const).some((k) => slots[k].mode === 'multi');
if (wghtModeSelect) wghtModeSelect.disabled = !hasVar;
if (wghtModeSub) {
wghtModeSub.textContent = hasVar
? '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置'
: '当前未选择可变字体 (中文/繁体/英文), 此功能不可用';
if (hasVar) {
wghtModeSub.textContent = hasAnyMulti
? '单字体模式下的可变字体 wght 范围与实际字重等级不符时, 覆写对应家族配置 (多字重槽位不受影响)'
: '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置';
} else if (hasAnyMulti) {
wghtModeSub.textContent = '多字重模式下各档位使用独立字体文件, 字重覆写已自动禁用';
} else {
wghtModeSub.textContent = '当前未选择可变字体 (中文/繁体/英文), 此功能不可用';
}
}
}
function renderModeToggle(slot: FontSlot): string {
if (!slot.supportsMulti) {
return `<md-icon class="slot-arrow">chevron_right</md-icon>`;
}
const singleActive = slot.mode === 'single' ? 'active' : '';
const multiActive = slot.mode === 'multi' ? 'active' : '';
return `
<div class="slot-mode-toggle" role="group" aria-label="${slot.title}模式切换">
<button type="button" class="slot-mode-btn ${singleActive}" data-key="${slot.key}" data-mode="single">可变字体</button>
<button type="button" class="slot-mode-btn ${multiActive}" data-key="${slot.key}" data-mode="multi">多字重</button>
</div>
`;
}
function renderSingleBody(slot: FontSlot, required: boolean): string {
const nameText = required ? '未选择字体,此项为必选项' : slotPlaceholder(slot);
const ext = slot.path ? (slot.path.split('.').pop() ?? '').toUpperCase() : '';
const sizeText = slot.subsetSizeText
? `${slot.sizeText || '…'} → ${slot.subsetSizeText}`
: slot.sizeText || '…';
const subsetBadge = slot.subsetSizeText
? `<span class="slot-meta-badge slot-meta-badge--subset" title="英文字体自带中文字形, 安装时已裁切为纯拉丁子集; 装入系统的是这个子集">已子集化</span>`
: '';
return `
<div class="slot-file">
${
slot.path
? `<md-icon-button class="slot-clear" data-key="${slot.key}" aria-label="取消选择">
<md-icon>close</md-icon>
</md-icon-button>`
: ''
}
<div class="slot-file-text">
<div class="slot-name ${!slot.path ? 'placeholder' : ''} ${required ? 'required' : ''}">${escapeHtml(nameText)}</div>
${
slot.path
? `<div class="slot-meta"><span class="slot-meta-badge">${escapeHtml(sizeText)}</span>${ext ? `<span class="slot-meta-badge">${escapeHtml(ext)}</span>` : ''}${subsetBadge}${slot.isVariable ? `<span class="slot-meta-badge slot-meta-badge--variable">可变字体${slot.wghtRange ? ` ${escapeHtml(slot.wghtRange)}` : ''}</span>` : ''}</div>`
: ''
}
</div>
${slot.supportsMulti ? `<md-icon class="slot-arrow slot-arrow--inline">chevron_right</md-icon>` : ''}
</div>
`;
}
function renderMultiBody(slot: FontSlot, required: boolean): string {
const selected = getSelectedMultiWeights(slot);
let bannerText = '';
let bannerCls = 'slot-multi-summary';
if (selected.length === 0) {
if (slot.key === 'hans') {
bannerText = required
? '请至少选择一个字重的字体文件(此项为必选项)'
: '请点击下方档位选择字体,未选档位将自动匹配最接近字重';
if (required) bannerCls += ' required';
} else if (isSlotConfigured(slots.hans)) {
bannerText = `未选任何字重,默认回退使用:${hansFallbackSummary()}`;
} else {
bannerText = '未选任何字重(可选),点击下方档位即可配置';
}
} else {
bannerText = `已选 ${selected.length}/9 档 · 缺失档位自动就近匹配`;
}
const rows = MULTI_WEIGHTS.map((w) => {
const entry = slot.multiWeights?.[w] ?? { weight: w, path: null, fileName: '' };
const label = WEIGHT_LABELS[w] ?? '';
const hasFile = Boolean(entry.path);
let text = '';
if (hasFile) {
text = entry.fileName;
} else if (selected.length > 0) {
text = `未选(使用 ${nearestWeight(selected, w)})`;
} else if (slot.key !== 'hans' && isSlotConfigured(slots.hans)) {
text = '回退中文简体';
} else {
text = '点击选择字体';
}
const ext = entry.path ? (entry.path.split('.').pop() ?? '').toUpperCase() : '';
const sizeText = entry.subsetSizeText
? `${entry.sizeText || '…'} → ${entry.subsetSizeText}`
: entry.sizeText || '…';
const subsetBadge = entry.subsetSizeText
? `<span class="slot-meta-badge slot-meta-badge--subset" title="英文字体自带中文字形, 安装时已裁切为纯拉丁子集">已子集化</span>`
: '';
return `
<div class="slot-weight-row ${hasFile ? 'selected' : ''}" data-key="${slot.key}" data-weight="${w}">
<div class="slot-weight-tag">
<span class="slot-weight-num">${w}</span>
<span class="slot-weight-label">${label}</span>
</div>
<div class="slot-weight-info">
<div class="slot-weight-name ${hasFile ? '' : 'placeholder'}">${escapeHtml(text)}</div>
${
hasFile
? `<div class="slot-meta"><span class="slot-meta-badge">${escapeHtml(sizeText)}</span>${ext ? `<span class="slot-meta-badge">${escapeHtml(ext)}</span>` : ''}${subsetBadge}</div>`
: ''
}
</div>
${
hasFile
? `<md-icon-button class="slot-weight-clear" data-key="${slot.key}" data-weight="${w}" aria-label="清除 ${w} 字重">
<md-icon>close</md-icon>
</md-icon-button>`
: `<md-icon class="slot-weight-arrow">chevron_right</md-icon>`
}
</div>
`;
}).join('');
return `
<div class="${bannerCls}">${escapeHtml(bannerText)}</div>
<div class="slot-weight-list">${rows}</div>
`;
}
export function renderSlots() {
const anyOtherConfigured = Object.values(slots).some(
(s) => s.key !== 'hans' && isSlotConfigured(s),
);
slotsEl.innerHTML = Object.values(slots)
.map((slot) => {
// 选了其他槽位但未选简体时, 简体卡片提示"必选"
const required =
slot.key === 'hans' &&
!slot.path &&
Object.values(slots).some((s) => s.key !== 'hans' && s.path);
const nameText = required ? '未选择字体,此项为必选项' : slotPlaceholder(slot);
// 扩展名大写 (TTF/OTF...), 从源文件路径动态提取, 不硬编码
const ext = slot.path ? (slot.path.split('.').pop() ?? '').toUpperCase() : '';
const configured = isSlotConfigured(slot);
const required = slot.key === 'hans' && !configured && anyOtherConfigured;
const body =
slot.mode === 'multi' && slot.supportsMulti
? renderMultiBody(slot, required)
: renderSingleBody(slot, required);
return `
<md-filled-card class="slot-card ${slot.key === 'hans' ? 'slot-hans' : ''} ${slot.path ? 'selected' : ''}" data-key="${slot.key}">
<md-filled-card class="slot-card ${slot.key === 'hans' ? 'slot-hans' : ''} ${slot.mode === 'multi' ? 'is-multi' : ''} ${configured ? 'selected' : ''}" data-key="${slot.key}" data-mode="${slot.mode}">
<div class="slot-header">
<div class="slot-title-group">
<span class="slot-title">${slot.title}</span>
</div>
<md-icon class="slot-arrow">chevron_right</md-icon>
</div>
<div class="slot-file">
${
slot.path
? `<md-icon-button class="slot-clear" data-key="${slot.key}" aria-label="取消选择">
<md-icon>close</md-icon>
</md-icon-button>`
: ''
}
<div class="slot-file-text">
<div class="slot-name ${!slot.path ? 'placeholder' : ''} ${required ? 'required' : ''}">${nameText}</div>
${
slot.path
? `<div class="slot-meta"><span class="slot-meta-badge">${slot.sizeText || '…'}</span>${ext ? `<span class="slot-meta-badge">${ext}</span>` : ''}${slot.isVariable ? `<span class="slot-meta-badge slot-meta-badge--variable">可变字体${slot.wghtRange ? ` ${slot.wghtRange}` : ''}</span>` : ''}</div>`
: ''
}
</div>
${renderModeToggle(slot)}
</div>
${body}
</md-filled-card>
`;
})
.join('');
// 绑定事件: 整卡点击选择字体
slotsEl.querySelectorAll<HTMLElement>('.slot-card').forEach((card) => {
card.addEventListener('click', () => {
pickingKey = card.dataset.key as SlotKey;
picker.show();
// 绑定事件: 模式切换按钮 (可变字体 / 多字重)
slotsEl.querySelectorAll<HTMLButtonElement>('.slot-mode-btn').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const key = btn.dataset.key as MultiSlotKey;
const mode = btn.dataset.mode as SlotMode;
const slot = slots[key];
if (!slot || slot.mode === mode) return;
slot.mode = mode;
notifyFontsChanged();
renderSlots();
});
});
// 绑定事件: 单字体整卡点击选择
slotsEl.querySelectorAll<HTMLElement>('.slot-card').forEach((card) => {
card.addEventListener('click', () => {
if (card.dataset.mode === 'multi') return;
pickFontFor(card.dataset.key as SlotKey);
});
});
// 绑定事件: 单字体清除
slotsEl.querySelectorAll<HTMLElement>('.slot-clear').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation(); // 阻止冒泡触发卡片选择
e.stopPropagation();
const slot = slots[btn.dataset.key as SlotKey];
slot.path = null;
slot.fileName = '';
slot.sizeText = undefined;
slot.isVariable = false;
slot.wghtRange = undefined;
slot.subsetSizeText = undefined;
void exec(`rm -f ${shellQuote(`${TEST_FONT_DIR}/${slot.key}.ttf`)}`);
notifyFontsChanged();
renderSlots();
});
});
// 绑定事件: 多字重行点击选择
slotsEl.querySelectorAll<HTMLElement>('.slot-weight-row').forEach((row) => {
row.addEventListener('click', (e) => {
e.stopPropagation();
const key = row.dataset.key as MultiSlotKey;
const weight = Number(row.dataset.weight) as WeightLevel;
pickMultiFontFor(key, weight);
});
});
// 绑定事件: 多字重单档清除
slotsEl.querySelectorAll<HTMLElement>('.slot-weight-clear').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const key = btn.dataset.key as MultiSlotKey;
const weight = Number(btn.dataset.weight) as WeightLevel;
const entry = slots[key].multiWeights?.[weight];
if (!entry) return;
entry.path = null;
entry.fileName = '';
entry.sizeText = undefined;
entry.subsetSizeText = undefined;
void exec(`rm -f ${shellQuote(`${TEST_FONT_DIR}/multi-${key}-${weight}.ttf`)}`);
notifyFontsChanged();
renderSlots();
});
});
if (applyBtn) {
// 未选择简体字体时直接隐藏按钮 (不做半透明禁用); 应用过程中禁用
applyBtn.style.display = !slots.hans.path ? 'none' : '';
const onConfig = document.getElementById('config-view')?.classList.contains('active') ?? false;
applyBtn.style.display = onConfig && canApply() ? '' : 'none';
applyBtn.disabled = applying;
}
updateWghtModeDisabled();
// 通知其他模块 (如字重映射预览) 槽位已变化
document.dispatchEvent(new CustomEvent('slots-rendered'));
}
@@ -160,11 +419,12 @@ export async function copyFont(src: string, dest: string) {
if (errno !== 0) throw new Error(`复制失败: ${stderr}`);
}
// 选择用于覆写的 wght 范围: 从 hans/hant/en 收集 (emoji/mono 除外), 取跨度最小者; 无可变返回 null
// 选择用于覆写的 wght 范围: 仅从当前处于单字体模式的 hans/hant/en 收集, 取跨度最小者; 无可变返回 null
export function pickWghtRange(): { min: number; max: number } | null {
let best: { min: number; max: number } | null = null;
let bestSpan = Infinity;
for (const key of ['hans', 'hant', 'en'] as const) {
if (slots[key].mode !== 'single' || !slots[key].path) continue;
const r = slots[key]?.wghtRange;
if (!r) continue;
const m = r.match(/^(\d+)-(\d+)$/);
@@ -180,15 +440,15 @@ export function pickWghtRange(): { min: number; max: number } | null {
return best;
}
// 选择新字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小
// 选择单字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小
async function refreshSlotInfo(slot: FontSlot) {
if (!slot.path) return;
if (slot.key === 'en') slot.subsetSizeText = undefined;
try {
await exec(`cp -f ${shellQuote(slot.path)} ${shellQuote(`${TEST_FONT_DIR}/${slot.key}.ttf`)}`);
const info = await readFontInfo(`${slot.key}.ttf`);
if (info.name) slot.fileName = info.name;
if (info.sizeText) slot.sizeText = info.sizeText;
// 无条件同步: 防止换字体后旧的可变标记残留
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
renderSlots();
@@ -197,20 +457,67 @@ async function refreshSlotInfo(slot: FontSlot) {
}
}
// 打开 WebUI 时: 复制 FONT/ 到 fonts-test, 读取已有字体的名称/大小填充卡片
async function loadExistingFonts() {
const available = await ensureFontsCopy();
for (const key of SLOT_KEYS) {
const file = `${key}.ttf`;
if (!available.includes(file)) continue;
const slot = slots[key];
const info = await readFontInfo(file);
slot.path = `${FONTS_DIR}/${file}`;
slot.fileName = info.name ?? file;
if (info.sizeText) slot.sizeText = info.sizeText;
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
// 选择多字重后: 复制到 fonts-test 供解析与测试预览, 更新该档位名称/大小
async function refreshMultiWeightInfo(slot: FontSlot, weight: WeightLevel) {
const entry = slot.multiWeights?.[weight];
if (!entry?.path) return;
if (slot.key === 'en') entry.subsetSizeText = undefined;
const testFile = `multi-${slot.key}-${weight}.ttf`;
try {
await exec(
`mkdir -p ${shellQuote(TEST_FONT_DIR)} && cp -f ${shellQuote(entry.path)} ${shellQuote(`${TEST_FONT_DIR}/${testFile}`)}`,
);
const info = await readFontInfo(testFile);
if (info.name) entry.fileName = info.name;
if (info.sizeText) entry.sizeText = info.sizeText;
renderSlots();
} catch {
// 忽略解析失败
}
}
// 刷新英文槽位 (单字体及多字重各档) 的子集信息, 不负责重绘
export async function refreshEnSubset(): Promise<void> {
slots.en.subsetSizeText = (await getEnSubsetSizeText()) ?? undefined;
const enWeights = getSelectedMultiWeights(slots.en);
const subMap = await getEnMultiSubsetSizes(enWeights);
for (const w of MULTI_WEIGHTS) {
const entry = slots.en.multiWeights?.[w];
if (entry) entry.subsetSizeText = subMap[w];
}
}
// 打开 WebUI 时: 复制 FONTS/ 到 fonts-test, 读取已有字体与模式配置填充卡片
async function loadExistingFonts() {
const [available, modes] = await Promise.all([ensureFontsCopy(), readSlotModes()]);
for (const key of SLOT_KEYS) {
const slot = slots[key];
if (key === 'hans' || key === 'hant' || key === 'en') {
slot.mode = modes[key];
}
const file = `${key}.ttf`;
if (available.includes(file)) {
const info = await readFontInfo(file);
slot.path = `${FONTS_DIR}/${file}`;
slot.fileName = info.name ?? file;
if (info.sizeText) slot.sizeText = info.sizeText;
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
}
if (slot.supportsMulti && slot.multiWeights) {
for (const w of MULTI_WEIGHTS) {
const mf = `multi-${key}-${w}.ttf`;
if (!available.includes(mf)) continue;
const info = await readFontInfo(mf);
const entry = slot.multiWeights[w];
entry.path = `${MULTI_DIR}/${key}/${w}.ttf`;
entry.fileName = info.name ?? `${w}.ttf`;
if (info.sizeText) entry.sizeText = info.sizeText;
}
}
}
await refreshEnSubset();
notifyFontsChanged();
renderSlots();
}
+167 -3
View File
@@ -125,14 +125,18 @@ md-filled-card.slot-card {
--md-filled-card-container-color: var(--md-sys-color-surface-container-low);
--md-filled-card-container-shape: var(--md-shape-corner-large);
// 整卡可点击选择 (多字重卡片由内部各字重行触发)
cursor: pointer;
&.is-multi {
cursor: default;
}
// 已选择状态: tonal 高亮 (primary-container), M3 标准选中反馈
&.selected {
--md-filled-card-container-color: var(--md-sys-color-primary-container);
}
// 整卡可点击选择
cursor: pointer;
.slot-header {
display: flex;
justify-content: space-between;
@@ -154,6 +158,37 @@ md-filled-card.slot-card {
color: var(--md-sys-color-on-surface);
}
// 可变字体 / 多字重 分段切换胶囊
.slot-mode-toggle {
display: inline-flex;
align-items: center;
flex-shrink: 0;
padding: 2px;
border-radius: var(--md-shape-corner-full);
background-color: var(--md-sys-color-surface-container-highest);
gap: 2px;
.slot-mode-btn {
border: none;
background: transparent;
padding: 4px 10px;
border-radius: var(--md-shape-corner-full);
font-family: inherit;
font-size: var(--md-sys-typescale-label-small-size);
font-weight: 500;
color: var(--md-sys-color-on-surface-variant);
cursor: pointer;
transition:
background-color var(--md-duration-standard) var(--md-easing-standard),
color var(--md-duration-standard) var(--md-easing-standard);
&.active {
background-color: var(--md-sys-color-primary);
color: var(--md-sys-color-on-primary);
}
}
}
// 右侧导航箭头
.slot-arrow {
flex-shrink: 0;
@@ -169,6 +204,12 @@ md-filled-card.slot-card {
gap: 4px;
min-width: 0;
.slot-arrow--inline {
flex-shrink: 0;
color: var(--md-sys-color-on-surface-variant);
font-size: 22px;
}
// 清除按钮位于字体名称左侧
.slot-clear {
flex-shrink: 0;
@@ -222,6 +263,129 @@ md-filled-card.slot-card {
background-color: var(--md-sys-color-primary);
color: var(--md-sys-color-on-primary);
}
// 子集化徽标: 与可变字体徽标同级的实色提示 (仅英文字体被裁切时出现)
&.slot-meta-badge--subset {
background-color: var(--md-sys-color-tertiary);
color: var(--md-sys-color-on-tertiary);
}
}
}
}
}
// 多字重提示与 9 档列表
.slot-multi-summary {
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
margin-bottom: 10px;
&.required {
font-weight: 600;
color: var(--md-sys-color-tertiary);
}
}
.slot-weight-list {
display: flex;
flex-direction: column;
border-top: 1px solid var(--md-sys-color-outline-variant);
.slot-weight-row {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 4px;
min-height: 44px;
cursor: pointer;
border-bottom: 1px solid
color-mix(in srgb, var(--md-sys-color-outline-variant) 55%, transparent);
&:last-child {
border-bottom: none;
padding-bottom: 2px;
}
&:active {
opacity: 0.72;
}
.slot-weight-tag {
display: flex;
flex-direction: column;
width: 44px;
flex-shrink: 0;
.slot-weight-num {
font-size: var(--md-sys-typescale-label-large-size);
font-weight: 600;
font-variant-numeric: tabular-nums;
color: var(--md-sys-color-primary);
line-height: 1.1;
}
.slot-weight-label {
font-size: 11px;
color: var(--md-sys-color-on-surface-variant);
line-height: 1.2;
}
}
.slot-weight-info {
flex: 1;
min-width: 0;
.slot-weight-name {
font-size: var(--md-sys-typescale-body-medium-size);
font-weight: 500;
color: var(--md-sys-color-on-surface);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
&.placeholder {
font-weight: 400;
color: var(--md-sys-color-on-surface-variant);
opacity: 0.75;
}
}
.slot-meta {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 2px;
.slot-meta-badge {
display: inline-block;
padding: 1px 8px;
border-radius: var(--md-shape-corner-full);
background-color: var(--md-sys-color-surface-container-highest);
font-size: 11px;
color: var(--md-sys-color-on-surface-variant);
&.slot-meta-badge--subset {
background-color: var(--md-sys-color-tertiary);
color: var(--md-sys-color-on-tertiary);
}
}
}
}
.slot-weight-arrow {
flex-shrink: 0;
font-size: 20px;
color: var(--md-sys-color-on-surface-variant);
}
.slot-weight-clear {
flex-shrink: 0;
width: 32px;
height: 32px;
--md-icon-button-state-layer-size: 32px;
md-icon {
font-size: 18px;
}
}
}
+110 -49
View File
@@ -1,82 +1,141 @@
import { slots } from './slots';
import { getSelectedMultiWeights, isSlotConfigured, slots } from './slots';
import { listFontsDir } from './fontFiles';
import type { FontSlot } from './types';
import { MULTI_WEIGHTS } from './constants';
import { nearestWeight } from './fontsXml';
import type { FontSlot, MultiSlotKey, WeightLevel } from './types';
const testStatusText = document.getElementById('test-status-text')!;
const testContent = document.getElementById('test-content')!;
type TestSlot = 'hans' | 'hant' | 'en';
type TestSlot = MultiSlotKey;
const TEST_FONTS: { slot: TestSlot; file: string; family: string }[] = [
{ slot: 'hans', file: 'hans.ttf', family: 'FontMM-Hans' },
{ slot: 'hant', file: 'hant.ttf', family: 'FontMM-Hant' },
{ slot: 'en', file: 'en.ttf', family: 'FontMM-En' },
];
const TEST_FAMILIES: Record<TestSlot, string> = {
hans: 'FontMM-Hans',
hant: 'FontMM-Hant',
en: 'FontMM-En',
};
async function registerFont(family: string, file: string): Promise<boolean> {
// 记录已注册进 document.fonts 的 FontFace, 刷新时先清理避免旧字重描述符残留
const registeredFaces: FontFace[] = [];
function clearRegisteredFaces(): void {
for (const face of registeredFaces) {
document.fonts.delete(face);
}
registeredFaces.length = 0;
}
async function registerFont(
family: string,
file: string,
weightRange = '100 900',
): Promise<boolean> {
try {
// 声明完整字重范围: 否则 FontFace 默认只覆盖 weight 400,
// CSS font-weight 100-900 将无法匹配到该字体 (真机表现: 100-400 无变化)
const font = new FontFace(family, `url('fonts-test/${file}')`, { weight: '100 900' });
const font = new FontFace(family, `url('fonts-test/${file}')`, { weight: weightRange });
await font.load();
document.fonts.add(font);
registeredFaces.push(font);
return true;
} catch {
return false;
}
}
// 测试页字体只加载一次 (进入时), 应用新字体后重置, 避免每次进入重复加载
// 为多字重槽位按连续权重区间注册 FontFace (相同目标字体文件合并为一个区间, 只加载一次)
async function registerMultiSlotFonts(
family: string,
slotKey: TestSlot,
availWeights: WeightLevel[],
availableFiles: string[],
): Promise<boolean> {
const usable = availWeights.filter((w) => availableFiles.includes(`multi-${slotKey}-${w}.ttf`));
if (usable.length === 0) return false;
// 按最接近匹配将 100..900 归并到连续字重区间
const segments: { sourceW: WeightLevel; minW: number; maxW: number }[] = [];
for (const w of MULTI_WEIGHTS) {
const target = nearestWeight(usable, w) as WeightLevel;
const prev = segments[segments.length - 1];
if (prev && prev.sourceW === target) {
prev.maxW = w;
} else {
segments.push({ sourceW: target, minW: w, maxW: w });
}
}
let anyLoaded = false;
for (const seg of segments) {
const descriptor = seg.minW === seg.maxW ? String(seg.minW) : `${seg.minW} ${seg.maxW}`;
const ok = await registerFont(family, `multi-${slotKey}-${seg.sourceW}.ttf`, descriptor);
if (ok) anyLoaded = true;
}
return anyLoaded;
}
// 测试页字体只加载一次 (进入时), 槽位或模式变化后重置
let testLoaded = false;
// 字体已变化: 下次进入测试页时重新加载
export function invalidateTestFonts(): void {
testLoaded = false;
}
document.addEventListener('fonts-changed', () => invalidateTestFonts());
function describeSlot(key: TestSlot): string {
const slot = slots[key];
if (slot.mode === 'multi') {
const ws = getSelectedMultiWeights(slot);
if (ws.length === 0) return '';
const regName = slot.multiWeights?.[nearestWeight(ws, 400) as WeightLevel]?.fileName ?? '';
return regName ? `多字重 ${ws.length} 档 · ${regName}` : `多字重 ${ws.length} 档`;
}
return slot.path ? slot.fileName : '';
}
async function loadSlotFamily(key: TestSlot, availableFiles: string[]): Promise<boolean> {
const slot = slots[key];
const family = TEST_FAMILIES[key];
if (slot.mode === 'multi') {
const ws = getSelectedMultiWeights(slot);
return ws.length > 0 ? registerMultiSlotFonts(family, key, ws, availableFiles) : false;
}
const file = `${key}.ttf`;
return slot.path && availableFiles.includes(file) ? registerFont(family, file) : false;
}
export async function loadTestFonts(): Promise<void> {
if (testLoaded) return;
testContent.hidden = true;
testStatusText.textContent = '正在加载字体...';
// 字体已在 WebUI 打开时复制到 fonts-test, 此处直接读取
clearRegisteredFaces();
const available = await listFontsDir();
// 注册字体, 记录每个槽位是否加载成功
const loaded = new Map<TestSlot, boolean>();
for (const tf of TEST_FONTS) {
loaded.set(
tf.slot,
available.includes(tf.file) ? await registerFont(tf.family, tf.file) : false,
);
for (const key of ['hans', 'hant', 'en'] as const) {
loaded.set(key, await loadSlotFamily(key, available));
}
// fallback 逻辑: hant/en 缺失回退 hans
const hans = loaded.get('hans') ? 'FontMM-Hans' : 'sans-serif';
const hant = loaded.get('hant') ? 'FontMM-Hant' : hans;
const en = loaded.get('en') ? 'FontMM-En' : hans;
// fallback 逻辑: hant/en 当前模式未配置时回退 hans
const hans = loaded.get('hans') ? TEST_FAMILIES.hans : 'sans-serif';
const hant = loaded.get('hant') ? TEST_FAMILIES.hant : hans;
const en = loaded.get('en') ? TEST_FAMILIES.en : hans;
// 显示字体名称 (解析出的 family name; 未解析到时为文件名)
const slotLabel = (key: TestSlot): string => slots[key].fileName;
const hasFont = (key: TestSlot): boolean => available.includes(`${key}.ttf`);
const hansLabel = hasFont('hans') ? slotLabel('hans') : null;
const hansLabel = isSlotConfigured(slots.hans) ? describeSlot('hans') : null;
const hantLabel = isSlotConfigured(slots.hant) ? describeSlot('hant') : null;
const enLabel = isSlotConfigured(slots.en) ? describeSlot('en') : null;
const setTag = (id: string, text: string) => {
const el = document.getElementById(id);
if (el) el.textContent = text;
};
setTag('hans-tag', hasFont('hans') ? slotLabel('hans') : '未设置, 使用系统字体');
setTag(
'hant-tag',
hasFont('hant') ? slotLabel('hant') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体',
);
setTag(
'en-tag',
hasFont('en') ? slotLabel('en') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体',
);
setTag('hans-tag', hansLabel || '未设置, 使用系统字体');
setTag('hant-tag', hantLabel || (hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体'));
setTag('en-tag', enLabel || (hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体'));
setTag('weight-tag', `使用 ${hansLabel ?? '系统字体'}`);
// 可变字体提示: 若所选字体为可变字体, 显示 wght 轴范围
const varSlot: FontSlot | null = slots.hans.isVariable ? slots.hans : null;
const varSlot: FontSlot | null =
slots.hans.mode === 'single' && slots.hans.isVariable ? slots.hans : null;
setTag(
'var-tag',
`使用 ${hansLabel ?? '系统字体'}${varSlot?.wghtRange ? ` (可变字体 wght ${varSlot.wghtRange})` : ''}`,
@@ -89,8 +148,7 @@ export async function loadTestFonts(): Promise<void> {
setFamily('test-hans', hans, 'sans-serif');
setFamily('test-hant', hant, `'${hans}', sans-serif`);
setFamily('test-en', en, `'${hans}', sans-serif`);
// 字重 / 可变字体测试: 用完整 fallback 链渲染 (Hans → Hant → En 按用户选择顺序,
// 浏览器逐字形回退, 所见即所得地体现系统真实 fallback)
const fallbackChain = [...new Set([hans, hant, en])].map((f) => `'${f}'`).join(', ');
const fullChain = `${fallbackChain}, sans-serif`;
document.querySelectorAll<HTMLElement>('.test-w-text').forEach((el) => {
@@ -98,12 +156,12 @@ export async function loadTestFonts(): Promise<void> {
});
const vp = document.getElementById('test-var-preview');
if (vp) vp.style.fontFamily = fullChain;
applyWght(400); // 与滑条初始值保持一致
applyWght(400);
testStatusText.textContent =
available.length === 0
? '未找到已设置的字体 (FONTS 为空), 当前使用系统字体预览'
: '字体已加载, 下方为预览效果 (按 fallback 逻辑)';
const hasAny = available.length > 0 && isSlotConfigured(slots.hans);
testStatusText.textContent = hasAny
? '字体已加载, 下方为预览效果 (按实际模式与 fallback 逻辑)'
: '未找到已设置的字体 (FONTS 为空), 当前使用系统字体预览';
testContent.hidden = false;
testLoaded = true;
}
@@ -128,7 +186,9 @@ const varPreview = document.getElementById('test-var-preview') as HTMLElement |
let wghtTimer: number | undefined;
function applyWght(weight: number) {
if (varPreview) varPreview.style.fontVariationSettings = `'wght' ${weight}`;
if (!varPreview) return;
varPreview.style.fontVariationSettings = `'wght' ${weight}`;
varPreview.style.fontWeight = String(Math.round(weight / 100) * 100);
}
function updateVarPreview(weight: number) {
@@ -174,7 +234,8 @@ document.querySelectorAll<HTMLElement>('.test-card-editable').forEach((card) =>
const target = document.getElementById(targetId);
if (!target) return;
editTargetId = targetId;
editInput.value = target.textContent ?? '';
// trim: textContent 带着标签间的缩进与换行, 原样填入会在输入框里显示成空行 (issue #16)
editInput.value = (target.textContent ?? '').trim();
if (editDialog) editDialog.open = true;
});
});
+2 -4
View File
@@ -1,6 +1,6 @@
import '@material/web/button/filled-button.js';
import { exec, shellQuote } from './ksu';
import { FontFilePicker } from './fontPicker';
import { fontPicker } from './fontPicker';
import { renderPreview, type PreviewData } from './previewRenderer';
// ---------------- 工具框架 ----------------
@@ -377,7 +377,6 @@ class FontEditorPage {
private originalBytes: Uint8Array | null = null;
private fileName = '';
private hasNameChanges = false;
private picker: FontFilePicker | null = null;
private previewText = DEFAULT_PREVIEW_TEXT;
private editTimer: number | null = null;
@@ -502,10 +501,9 @@ class FontEditorPage {
void this.loadFont('demo-font.ttf', 'demo-font.ttf');
return;
}
this.picker ??= new FontFilePicker((path, name) => {
fontPicker.show('/storage/emulated/0/Download', (path, name) => {
void this.copyAndLoad(path, name);
});
this.picker.show('/storage/emulated/0/Download');
}
private async copyAndLoad(path: string, name: string): Promise<void> {
+24 -1
View File
@@ -1,6 +1,25 @@
export type SlotKey = 'hans' | 'hant' | 'en' | 'mono' | 'emoji';
export type MultiSlotKey = 'hans' | 'hant' | 'en';
export type SlotMode = 'single' | 'multi';
export type WeightLevel = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
export interface MultiWeightEntry {
weight: WeightLevel;
path: string | null;
fileName: string;
sizeText?: string;
/** 英文字体裁切后的子集大小 (如 "184 KB"), 仅 en 槽位子集有效时存在 */
subsetSizeText?: string;
}
export interface FontSlot {
key: 'hans' | 'hant' | 'en' | 'mono' | 'emoji';
key: SlotKey;
title: string;
/** 是否支持切换多字重模式 (仅 hans/hant/en) */
supportsMulti?: boolean;
/** 当前模式 ('single'=可变/单字体, 'multi'=多字重) */
mode: SlotMode;
/** 单字体模式选中文件路径 (与 multiWeights 各自保留, 切换模式不丢失) */
path: string | null;
fileName: string;
/** 字体大小展示文本 (如 "12.5 MB"), 异步获取 */
@@ -9,4 +28,8 @@ export interface FontSlot {
isVariable?: boolean;
/** wght 轴范围 (如 "100-900"), 可变字体时有 */
wghtRange?: string;
/** 英文字体裁切后的子集大小 (如 "218 KB"), 仅英文槽位且子集有效时存在 (issue #14) */
subsetSizeText?: string;
/** 多字重模式下各档位字体配置 */
multiWeights?: Record<WeightLevel, MultiWeightEntry>;
}
+1 -24
View File
@@ -1,7 +1,7 @@
import { exec, toast } from './ksu';
import { pickWghtRange, updateWghtModeDisabled } from './slots';
import { WEIGHTS, averagedAxis } from './fontsXml';
import { FONTS_DIR, WGHT_BIN } from './constants';
import { FONTS_DIR } from './constants';
export type WghtMode = 0 | 1 | 2 | 3;
@@ -64,29 +64,6 @@ async function readWghtMode(): Promise<WghtMode> {
return 0;
}
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (只改 fonts.xml, 再 -sync 到各派生配置)
export async function applyWghtOverride(mode: 1 | 2 | 3, min: number, max: number): Promise<void> {
const mapArg = mode === 3 ? ` -map '${FONTS_DIR}/wght-map.txt'` : '';
// 日志写到 FONTS/wght-apply.log 方便真机排查; 先 chmod +x 保证可执行
const logFile = `${FONTS_DIR}/wght-apply.log`;
const cmd = `chmod +x '${WGHT_BIN}' 2>/dev/null; '${WGHT_BIN}' -mode ${mode} -min ${min} -max ${max}${mapArg} -sync > '${logFile}' 2>&1`;
try {
const { errno } = await exec(cmd);
// 读取并回显执行日志 (同时 console 输出供排查)
const { stdout: log } = await exec(`cat '${logFile}' 2>/dev/null || true`);
console.log(`[wght-override] mode=${mode} min=${min} max=${max} errno=${errno}`);
if (log) console.log(`[wght-override] log:\n${log}`);
if (errno !== 0) {
console.warn('[wght-override] 执行失败:', log);
// 覆写失败不阻断应用主流程, 但把失败原因带出
throw new Error(log || `fontmm-wght 执行失败 (errno=${errno})`);
}
} catch (e) {
// 覆写失败不阻断应用主流程
console.warn('字重范围覆写失败:', e);
}
}
// 读取自定义字重映射 (FONTS/wght-map.txt: 每行 "weight axis")
async function readWghtMap(): Promise<Record<number, number>> {
const map: Record<number, number> = {};