74 Commits
110 changed files with 59391 additions and 216 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
template/*.zip filter=lfs diff=lfs merge=lfs -text
+48
View File
@@ -0,0 +1,48 @@
name: Build & Upload Artifacts
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 11
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
cache-dependency-path: web/pnpm-lock.yaml
- name: Install dependencies
run: pnpm -C web install --frozen-lockfile
- name: Build WebUI
run: pnpm -C web build
- name: Pack module (preplace / template)
run: bash dev/cd.sh
- name: Generate SHA256 checksums
run: |
for f in dist/*.zip; do
sha256sum "$f" > "$f.sha256"
done
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: fontmm-build
path: |
dist/*.zip
dist/*.zip.sha256
retention-days: 14
+39
View File
@@ -0,0 +1,39 @@
name: Go
on:
push:
paths:
- 'golang/**'
- 'dev/build-wght.sh'
pull_request:
paths:
- 'golang/**'
- 'dev/build-wght.sh'
workflow_dispatch:
jobs:
test-and-build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Vet
run: cd golang && go vet ./...
- name: Test
run: cd golang && go test ./...
- name: Cross-compile (android/arm64)
run: cd golang && GOOS=android GOARCH=arm64 CGO_ENABLED=0 go build -ldflags="-s -w" -o /tmp/fontmm-wght ./cmd/fontmm-wght
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: fontmm-wght
path: /tmp/fontmm-wght
-50
View File
@@ -1,50 +0,0 @@
name: Release Package & Attach
# 触发条件:当发布(published)一个 Release 时
on:
release:
types: [published]
jobs:
upload-assets:
runs-on: ubuntu-latest
# 授予写入 Release 内容的权限
permissions:
contents: write
steps:
# 1. 拉取代码并包含 LFS
- name: Checkout Code
uses: actions/checkout@v4
with:
lfs: true
- name: Pull LFS objects
run: git lfs pull
# 2. 准备打包环境并压缩
- name: Cleanup and Zip
id: pack
run: |
# 删除 .gitattributes
rm -f .gitattributes
# 获取当前 Release 的 Tag 名字 (比如 V1.1)
TAG_NAME="${{ github.event.release.tag_name }}"
# 按照你的要求命名:FontMM-[Tag]-release.zip
FILENAME="FontMM-${TAG_NAME}-release.zip"
# 执行最高压缩
zip -r -9 "$FILENAME" . -x "*.git*" ".github*"
# 存入环境变量供下一步引用
echo "ZIP_PATH=$FILENAME" >> $GITHUB_ENV
# 3. 将打包好的文件上传到当前的 Release 页面
- name: Upload Release Asset
uses: softprops/action-gh-release@v2
with:
# files 指向刚才生成的压缩包路径
files: ${{ env.ZIP_PATH }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+50
View File
@@ -0,0 +1,50 @@
name: Release
on:
release:
types: [published]
jobs:
build-and-release:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 11
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
cache-dependency-path: web/pnpm-lock.yaml
- name: Install dependencies
run: pnpm -C web install --frozen-lockfile
- name: Build WebUI
run: pnpm -C web build
- name: Pack module (preplace / template)
run: bash dev/cd.sh
- name: Generate SHA256 checksums
run: |
for f in dist/*.zip; do
sha256sum "$f" > "$f.sha256"
done
- name: Upload release assets
uses: softprops/action-gh-release@v2
with:
files: |
dist/*.zip
dist/*.zip.sha256
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+12
View File
@@ -0,0 +1,12 @@
node_modules/
web/node_modules/
dist/
src/webroot/
reasonix.toml
.reasonix/
.agent/
.ref/
src/tools/fontmm-wght
golang/bin/
src/SHA256SUMS
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["oxc.oxc-vscode"]
}
+17
View File
@@ -0,0 +1,17 @@
{
// 官方推荐: https://oxc.rs/docs/guide/usage/linter/editors.html
// https://oxc.rs/docs/guide/usage/formatter/editors.html
// 使用 Oxc 扩展 (oxlint --lsp / oxfmt --lsp), 需本地安装 oxlint 与 oxfmt
"editor.defaultFormatter": "oxc.oxc-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.oxc": "always"
},
// 显式指定 JavaScript/TypeScript 由 oxfmt 格式化
"[javascript]": {
"editor.defaultFormatter": "oxc.oxc-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "oxc.oxc-vscode"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Yule
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+284
View File
@@ -0,0 +1,284 @@
<h1 align="center">FontMM</h1>
<div align="center">
一个用于快速更换系统字体的 Magisk 模块,内置 WebUI 以及一些好用的功能
</div>
<div align="center">
<a href="#特性">特性</a> | <a href="#安装">安装</a> | <a href="#使用">使用</a> | <a href="#技术细节">开发</a> | <a href="#致谢">致谢</a> | <a href="#许可">许可</a><br>
</div>
## 特性
- Material 风格的管理界面,在支持 WebUI 的 Root 管理器中直接打开
- 多槽位字体分别选择,满足你的个性化需求
- 可变字体 wght 范围与实际字重等级不符时可选择覆写配置,保证正确映射
- 内置字库补充字体,兜底 CJK 扩展区、Unicode 18.0 全覆盖
## 支持环境
| 项目 | 要求 |
| --------- | ----------------------- |
| 系统 | >= ColorOS 16.0 |
| Root 环境 | Magisk 20.4+ / KernelSU |
| 字体格式 | `.ttf` |
## 安装
> 安装完成后,请在系统设置中选择 Roboto 作为字体,这样才能得到正确的字重映射!
### 选择版本
每个 Release 提供两个压缩包,区别仅在于是否预置字体:
| 版本 | FONT 目录 | 适用场景 |
| ------------------ | ------------------------------- | --------------------------------------------------------------------------- |
| `..._preplace.zip` | 含预置简体字体 `FONTS/hans.ttf` | **全新安装**:刷入后立即可用默认字体,随后可再在 WebUI 更换 |
| `..._template.zip` | `FONTS/` 为空目录 | **更新已有模块**:`customize.sh` 会自动从旧模块继承已设置的字体,包体积更小 |
- **首次安装**:用 `_preplace` 版,开箱即用;如果用 `_template` 版,刷入前需先在 `FONT/` 至少放置简体字体 `hans.ttf`,否则 `apply.sh` 会报错并拒绝安装
- **更新已安装的模块**:用 `_template` 版——更新模式会从旧模块的 `FONTS/` 目录继承已设置的字体,无需重新设置字体
### KernelSU 及其分支版本
> KernelSU 的分支版本包括但不限于:SukiSU Ultra, KernelSU Next, ReSukiSU
#### 元模块
如果您的 Root 管理器支持元模块,则必须预先安装一个有效的元模块,这样本模块才能成功挂载并生效,参见:[什么是元模块](https://kernelsu.org/zh_CN/guide/metamodule.html)。
目前经过测试可以与本模块兼容的元模块有:
- [mountify](https://github.com/backslashxx/mountify/releases)
#### 管理器配置
一般而言,如果你**正确安装了 Fontloader**,可以无需关闭「默认卸载模块」以及「卸载模块(内核级)」功能,**但我们始终建议关闭**,因为关闭后模块才能做到尽可能的全场景覆盖。
若您选择不关闭「默认卸载模块」以及「卸载模块(内核级)」功能,则被卸载的应用可能会出现字体不生效的情况,此时您可以通过 App Profile 功能单独关闭该应用的「卸载模块」选项,并重启应用。
### Magisk 及其分支版本
#### WebUI 支持
由于 Magisk 默认是不支持 WebUI 的,这意味着你需要安装一个外置的 WebUI 支持 App,比如:
- [WebUI X Portable](https://github.com/MMRLApp/WebUI-X-Portable)
- [KsuWebUI Standalone](https://github.com/5ec1cff/KsuWebUIStandalone)
### 通用依赖
#### Zygisk
因为 Fontloader 依赖于 Zygisk 进行运行,所以你需要安装一个可用的 Zygisk 实现,例如:
- [Zygisk Next](https://github.com/Dr-TSNG/ZygiskNext/releases)
**如果您选择使用 Zygisk Next,则还需要到其 WebUI 页面中将「排除列表策略」选项更改为「仅还原挂载」**。
#### Fontloader
**我们建议您在安装本模块前预先安装 Fontloader,否则可能出现应用闪退、开机卡第二屏、字体显示错误等严重错误**。
从 Android 12 起,系统加载字体的方式变为了在 App 启动时按需加载,这会导致被管理器卸载模块的 App 找不到字体文件,从而崩溃,**包括 Android 系统 App**。Fontloader 就是用来解决这个问题的,它会在 App 尚未失去字体访问权限时为 App 预加载字体。
由于 `RikkaW/FontLoader` 已经停更,推荐使用:
- [aviraxp/fontloader](https://github.com/KernelSU-Modules-Repo/fontloader/releases)
---
## 使用方法
### 通过 WebUI 更换字体(推荐)
#### 基础配置
1. 打开 KernelSU 或 WebUI 管理器,进入 FontMM 模块的 WebUI 界面,切换至「配置」页面
2. 在槽位中分别选择字体:
- **中文简体**:**必选**
- **中文繁体**:可选,未选择时自动使用简体
- **英文 & 数字**:可选,未选择时自动使用简体
- **等宽字体**:可选,未选择时不覆盖系统等宽字体
- **Emoji 表情**:可选,未选择时使用系统默认 Emoji
3. 点击「应用字体」,重启设备后生效
#### 高级配置
##### 字重覆写
当所选字体为可变字体时,可在配置页「字重覆写模式」选择字重映射的处理方式:
- **不处理**:默认,超出范围的字重由系统处理
- **裁切粗细等级**:删除范围外的字重条目
- **平均分配字重**:保留 9 档完整粗细,400 字重不变,两端按范围平均插值
- **自定义映射**:可以自定义 1-1000 字重的映射关系
### 手动放置字体
> 字体的 Fallback 逻辑同上
1. 把字体放入 `/data/adb/modules/FontMM/FONTS/`,命名规则:
- `hans.ttf`:中文简体(必选)
- `hant.ttf`:中文繁体(可选)
- `en.ttf`:英文与数字(可选)
- `mono.ttf`:等宽字体(可选)
- `emoji.ttf`:Emoji 表情(可选)
2. 执行 `sh /data/adb/modules/FontMM/apply.sh`
3. 重启设备
### 校验模块完整性
每个模块包都附带可执行文件的 SHA256 校验(`SHA256SUMS`),可在一键校验模块内脚本/二进制是否被篡改或损坏:
```sh
sh /data/adb/modules/FontMM/tools/verify-sha256.sh
```
GitHub Release 的 zip 附件旁均提供 `.sha256` 校验文件,可用 `sha256sum -c` 在本地验证下载完整性。
---
## 技术细节
### 字体挂载
模块把 5 个用户字体槽位挂载到系统字体文件:
| 槽位 | 用户文件 | 挂载的系统字体文件 | 回退逻辑(字体缺失时) |
| ----------- | ----------- | :--------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |
| 中文简体 | `hans.ttf` | `SysSans-Hans-Regular.ttf`、`SysFont-Static-Regular.ttf`、`SysFont-Myanmar.ttf`、`SysFont-Hans-Regular.ttf` | 拒绝安装和应用 |
| 中文繁体 | `hant.ttf` | `SysSans-Hant-Regular.ttf`、`SysFont-Hant-Regular.ttf` | 使用中文简体字体 `hans.ttf` |
| 英文 & 数字 | `en.ttf` | `SysSans-En-Regular.ttf`、`SysFont-Regular.ttf` | 使用中文简体字体 `hans.ttf` |
| 等宽字体 | `mono.ttf` | `DroidSansMono.ttf` | 不挂载 |
| Emoji 表情 | `emoji.ttf` | `NotoColorEmoji.ttf` | 不挂载 |
> 注:`SysFont-Regular.ttf` 是 `fonts.xml` 中 `sans-serif` 家族默认字体,由英文槽位填充(未设置时回退简体)。西文字体在配置中排在最前,中文字体自带的西文字形仅作兜底,避免中文完全覆盖西文(issue #6)。
### 补充字库
模块内置一组 OFL-1.1 / MIT 许可的补充字体,作为 `fonts.xml` 末尾的全局 fallback,兜底用户字体与系统字体未覆盖的字形(CJK 扩展区生僻字、最新 Unicode 字符、小篆等):
| 字体 | 说明 |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PlangothicP1/P2.ttf` | CJK 扩展区覆盖(Ext-B、G/H、**I、J** 等生僻字与新汉字) |
| `PlanschriftSeal-Regular.ttf` | **Seal(小篆)区块 11328 字符全覆盖**(Unicode 18 新增,子集化 34M;MIT/OFL 双许可,源自 [Planschrift_Project](https://github.com/Fitzgerald-Porthmouth-Koenigsegg/Planschrift_Project)) |
| `NotoSansPro.otf` | 多 Noto 家族合并,覆盖广泛语言字形 |
| `Unicode16/17/18-new.ttf` | Unicode 最新版本已定义字符覆盖 |
| `ZUno-Number.ttf` | 保留符号 / 私用区未定义符号显示编码信息 |
补充字库不参与用户槽位替换,仅在缺字形时按顺序兜底。字体来源与许可详见模块内 `system/fonts/LICENSE-*` 及 [MakeFontsGreatAgain](https://github.com/Numbersf/MakeFontsGreatAgain) 的 LICENSES。
## 工作原理
```
┌─────────────────────────────────────────────────────────┐
│ KernelSU 管理器 │
│ ┌──────────────────────────────┐ │
│ │ WebUI (web/ 构建产物) │ ksu.exec / toast │
│ └──────────────┬───────────────┘ │
└───────────────────┼─────────────────────────────────────┘
│ sh /data/adb/modules/FontMM/apply.sh
▼
┌───────────────────────┐ cp -f ┌──────────────────────┐
│ FONTS/ 用户字体 │ ──────────► │ system/fonts/ │
│ hans.ttf │ │ SysFont/SysSans 等 │
│ hant.ttf (可选) │ └──────────────────────┘
│ en.ttf (可选) │
└───────────────────────┘
```
1. **安装阶段**(`customize.sh`):系统检查(ColorOS 版本、KernelSU 元模块、FontLoader)→ 更新模式检测与旧字体继承 → 扫描设备系统 XML 生成派生字体配置 → 调用 `apply.sh` 完成首次字体安装
2. **换字体阶段**(WebUI):选择文件 → 复制到 `FONTS/` → 调用同一个 `apply.sh`,两条路径行为一致
3. **`apply.sh` 核心逻辑**:按字体映射表把 `FONTS/` 中的字体复制到 `system/fonts/` 的对应文件,缺繁体/英文时回退简体
4. **字体生效**:ColorOS 通过 `/system/etc/fonts.xml` 等配置引用 `SysFont*` / `SysSans*` 字体族,模块只内置 `fonts.xml` 主配置,各派生配置(`fonts_base.xml` / `fonts_ule.xml` / `font_fallback.xml`)由安装时扫描设备系统 XML 生成(缺失时回退内置),字重覆写时 `fontmm-wght -sync` 统一同步,提升跨 ColorOS 版本兼容性
## 开发指南
### 环境要求
- Node.js ≥ 18 + [pnpm](https://pnpm.io/)
- `zip` / `unzip`
- `shellcheck` + `shfmt`(仅 CI 检查需要)
- `Python 3` + `fontTools`(Unicode 覆盖测试)
- `Golang`
- 任意可运行 `ash` 的环境(验证 shell 脚本)
### 安装依赖
```bash
pnpm install && cd web && pnpm install
```
### 本地预览 WebUI
```bash
pnpm dev
```
`dev` 模式下 `ksu.ts` 使用内置 mock 文件系统,文件选择、槽位切换、应用字体全流程可脱离真机调试。
### 构建与打包
完整构建:
```bash
pnpm build
```
单独构建 WebUI 产物(调试用):
```bash
pnpm build:only-web # 产出 dist/webroot.zip
```
### 代码检查
> 前端 lint/format 由 [oxlint](https://oxc.rs/) 与 [oxfmt](https://oxc.rs/) 提供
```bash
pnpm lint # 前端 oxlint 检查
pnpm fmt # 前端 oxfmt 格式化
pnpm fmt:check # 前端 oxfmt 格式检查
bash dev/ci.sh # src/ 下所有 .sh 的 shellcheck + shfmt 检查
```
### Unicode 覆盖测试
> 本地模拟 `fonts.xml` 的 fallback 链,对照 Unicode Blocks.txt 统计每个区块覆盖率,首次运行会自动下载 Blocks.txt 缓存到 `dev/`
```bash
python3 dev/check-unicode-coverage.py # 全部区块
python3 dev/check-unicode-coverage.py "Archaic" "Seal" # 只测指定区块
```
### 占位字体机制
`src/system/fonts/` 下的 `SysFont*` / `SysSans*` 是 **0 字节占位文件**,避免把大字体文件提交进仓库;安装或应用字体时由 `apply.sh` 用 `FONTS/` 里的真实字体覆盖。
- 开发时可用 `dev/empty_font.sh` 重新生成这些占位文件
- `src/FONTS/hans.ttf` 是内置默认简体字体(仅 preplace 版打包)
## 常见问题
**Q:装完模块后字体没变?**
A:确认系统是 ColorOS 16+,并完成 [安装前的配置](#安装),记得重启
**Q:更新模块会丢失我设置好的字体吗?**
A:不会,检测到已安装的 FontMM 时会进入更新模式,从旧模块的 `FONTS/` 目录继承字体
## 致谢
- 字体映射与配置文件参考 ColorOS 16 系统字体体系
- 补充字库与 `fonts.xml` fallback 结构参考 [MakeFontsGreatAgain](https://github.com/Numbersf/MakeFontsGreatAgain)
- WebUI 基于 [Material Web](https://github.com/material-components/material-web)(Material Design 3)与 [kernelsu](https://www.npmjs.com/package/kernelsu) 构建
## 许可
[MIT License](./LICENSE)
-12
View File
@@ -1,12 +0,0 @@
1. 修改 module.prop
2. 在 ttf 里面放入你的字体
ch.ttf -- 中文(简体)
tc.ttf -- 中文(繁体)
en.ttf -- 英文
你也可以只放入一个 ch.ttf
这样的话,中文(繁体)和英文都会使用 ch.ttf
3. 运行 打包.sh
+53
View File
@@ -0,0 +1,53 @@
# Changelog
## v26.8.0-beta.5
- **修复中文字体完全覆盖西文字体**(issue #6):`SysFont-Regular.ttf` 改为英文槽位填充(未设置英文时仍回退简体),不再被中文字体占用,西文字形可正常显示
- **字重覆写覆盖全部生效家族**(issue #7):不再只改 `sans-serif`,同时覆写 `sys-sans-en` / `zh-Hans` / `zh-Hant` 家族,保证中英文一致映射
- **字重覆写只改一份配置**(issue #7):`fontmm-wght` 只修改 `fonts.xml` 主配置,再 `-sync` 同步到各派生配置;派生配置不再打包进模块,改由刷入脚本(`customize.sh`)扫描设备系统 XML 生成,提升跨 ColorOS 版本兼容性
- **SHA256 完整性校验**(issue #8):新增 `dev/gen-sha256.sh` 生成可执行文件校验(随模块打包),设备端 `tools/verify-sha256.sh` 一键校验;GitHub Release/CI 产物附带 `*.sha256` 校验文件
## v26.8.0-beta.4
- **字重范围覆写**(可变字体映射引擎,Go 方案):可变字体 wght 轴范围与实际字重等级不符时,可视化覆写 `sans-serif` 配置
- 支持三种模式:**裁切粗细等级** / **平均分配字重**(9 档线性插值)/ **自定义映射**
- 字重映射编辑器:实时预览、新增/删除映射、滑块拖拽(按住并水平滑动才触发,防误触)、轴值对比标注(+25 / -100)
- 工具栏:撤销(30 步历史)、导出/导入(base64 JSON,跨设备备份恢复)、重置
- 内置 Go 程序 `fontmm-wght` 本地覆写全部 6 个字体配置 XML,无命令长度限制;修复嵌套 family 深度配对,杜绝段被切掉导致无法开机的严重问题
- **新增「字体编辑」工具**(实验性,Pyodide + fontTools):打开 `.ttf` 编辑字体信息与字形
- 17 个 name 字段编辑;字形缩放 50-150% / 水平垂直偏移 / 字间距 / 行间距(Canvas 实时预览)
- 性能重构:lazy 解析 + 快照-重置 + numpy 批量矩阵变换,大字体导出提速 62s → 11.5s
- 编辑结果 base64 分块导出到 `Download/FontMM/`;Pyodide 全部本地化(零外部依赖),移入 Web Worker 不阻塞 UI
- **工具页重构**:ToolHost 注册表框架,每个工具独立页面(template/mount/unmount),为创意工坊等扩展铺路
- **安装体验**:非 ColorOS / 版本过低不再拒绝安装,改为音量键确认风险后继续(音量上继续 / 音量下中止)
- **WebUI 架构重构**:`main.ts`(1039 行)按职责拆分为 slots / wght / apply / home / navigation 等模块;修复动态 shell 参数未加引号的安全问题
- **文档完善**:README 重写(支持环境、KernelSU/Magisk 分支、元模块、Fontloader 配置说明)
## v26.8.0-beta.3
- **新增「工具」页**(底部导航第 4 个 tab):下载国际版小米主题字体 v1.0.0
- 搜索小米主题商店字体(跨域走 root shell 解决)、缩略图预览、分页浏览
- 下载 mtz 并自动解压提取 `fonts/` 目录字体,日志实时展示(后台运行 + 轮询,避免阻塞 WebUI)
- **等宽/Emoji 修复**:`mono.ttf` 与 `emoji.ttf` 改回**直接替换系统字体**(`DroidSansMono.ttf` / `NotoColorEmoji.ttf`,overlay 生效),不再使用自创独立字体文件(`FontMM-Mono` / `FontMM-Emoji` 不生效)
- **Emoji 槽位完善**:清除 emoji 槽位时从模块 `backup/` 恢复内嵌补充字库 Emoji(安装时自动备份);旧包更新继承列表补全 `emoji.ttf`
## v26.8.0-beta.2
- **补充字库**:内置 OFL-1.1 / MIT 许可字体,在 `fonts.xml` 末尾作为全局 fallback:
- PlangothicP1/P2——CJK 扩展区覆盖(Ext-B、G/H、**I、J** 等生僻字与新汉字)
- PlanschriftSeal——**Seal(小篆)区块 11328 字符 100% 覆盖**(Unicode 18 新增,子集化 34M,MIT/OFL 双许可)
- ArchaicCuneiformNumerals、NotoUnicode、NotoColorEmoji、UnicodiaFunky、Unknown-symbol 等
- **等宽字体修复**:改为独立文件 `FontMM-Mono.ttf`(monospace 家族优先引用),不再覆盖系统 `DroidSansMono`,解决设置等宽字体后不生效的问题
- **单一源字体配置**:`fonts.xml` 为唯一源,`dev/sync-fonts-xml.sh` 自动生成 `fonts_base.xml` / `fonts_ule.xml` / `font_fallback.xml`
- **Unicode 覆盖测试**:新增 `dev/check-unicode-coverage.py`,本地模拟 fallback 链统计各区块覆盖率
- 致谢补充字库来源 [MakeFontsGreatAgain](https://github.com/Numbersf/MakeFontsGreatAgain)
## v26.8.0-beta.1
全新 v26 架构重构:
- **WebUI 重写**(Material Design 3 + 底部导航):字体槽位选择/应用、字体测试(字重 100–900、可变字体滑条、字号调节)、关于页、深色模式跟随系统、edge-to-edge 延伸至小白条
- **字体名称解析**:打开 WebUI 时用 opentype.js 读取 FONT/ 内字体的真实名称并显示在卡片(如 OPPO Sans 4.0)
- **双版本打包**:`_preplace`(含预置字体)与 `_template`(FONT 空目录)两版;新增 `build:only-web` 快速调试产物
- **开发工具链**:oxlint / oxfmt / type-check / shellcheck 脚本化
- 新增 MIT LICENSE
+391
View File
@@ -0,0 +1,391 @@
# Blocks-18.0.0.txt
# Date: 2026-02-03
# © 2026 Unicode®, Inc.
# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries.
# For terms of use and license, see https://www.unicode.org/terms_of_use.html
#
# Unicode Character Database
# For documentation, see https://www.unicode.org/reports/tr44/
#
# Format:
# Start Code..End Code; Block Name
# ================================================
# Note: When comparing block names, casing, whitespace, hyphens,
# and underbars are ignored.
# For example, "Latin Extended-A" and "latin extended a" are equivalent.
# For more information on the comparison of property values,
# see UAX #44: https://www.unicode.org/reports/tr44/
#
# All block ranges start with a value where (cp MOD 16) = 0,
# and end with a value where (cp MOD 16) = 15. In other words,
# the last hexadecimal digit of the start of range is ...0
# and the last hexadecimal digit of the end of range is ...F.
# This constraint on block ranges guarantees that allocations
# are done in terms of whole columns, and that code chart display
# never involves splitting columns in the charts.
#
# All code points not explicitly listed for Block
# have the value No_Block.
# Property: Block
#
# @missing: 0000..10FFFF; No_Block
0000..007F; Basic Latin
0080..00FF; Latin-1 Supplement
0100..017F; Latin Extended-A
0180..024F; Latin Extended-B
0250..02AF; IPA Extensions
02B0..02FF; Spacing Modifier Letters
0300..036F; Combining Diacritical Marks
0370..03FF; Greek and Coptic
0400..04FF; Cyrillic
0500..052F; Cyrillic Supplement
0530..058F; Armenian
0590..05FF; Hebrew
0600..06FF; Arabic
0700..074F; Syriac
0750..077F; Arabic Supplement
0780..07BF; Thaana
07C0..07FF; NKo
0800..083F; Samaritan
0840..085F; Mandaic
0860..086F; Syriac Supplement
0870..089F; Arabic Extended-B
08A0..08FF; Arabic Extended-A
0900..097F; Devanagari
0980..09FF; Bengali
0A00..0A7F; Gurmukhi
0A80..0AFF; Gujarati
0B00..0B7F; Oriya
0B80..0BFF; Tamil
0C00..0C7F; Telugu
0C80..0CFF; Kannada
0D00..0D7F; Malayalam
0D80..0DFF; Sinhala
0E00..0E7F; Thai
0E80..0EFF; Lao
0F00..0FFF; Tibetan
1000..109F; Myanmar
10A0..10FF; Georgian
1100..11FF; Hangul Jamo
1200..137F; Ethiopic
1380..139F; Ethiopic Supplement
13A0..13FF; Cherokee
1400..167F; Unified Canadian Aboriginal Syllabics
1680..169F; Ogham
16A0..16FF; Runic
1700..171F; Tagalog
1720..173F; Hanunoo
1740..175F; Buhid
1760..177F; Tagbanwa
1780..17FF; Khmer
1800..18AF; Mongolian
18B0..18FF; Unified Canadian Aboriginal Syllabics Extended
1900..194F; Limbu
1950..197F; Tai Le
1980..19DF; New Tai Lue
19E0..19FF; Khmer Symbols
1A00..1A1F; Buginese
1A20..1AAF; Tai Tham
1AB0..1AFF; Combining Diacritical Marks Extended
1B00..1B7F; Balinese
1B80..1BBF; Sundanese
1BC0..1BFF; Batak
1C00..1C4F; Lepcha
1C50..1C7F; Ol Chiki
1C80..1C8F; Cyrillic Extended-C
1C90..1CBF; Georgian Extended
1CC0..1CCF; Sundanese Supplement
1CD0..1CFF; Vedic Extensions
1D00..1D7F; Phonetic Extensions
1D80..1DBF; Phonetic Extensions Supplement
1DC0..1DFF; Combining Diacritical Marks Supplement
1E00..1EFF; Latin Extended Additional
1F00..1FFF; Greek Extended
2000..206F; General Punctuation
2070..209F; Superscripts and Subscripts
20A0..20CF; Currency Symbols
20D0..20FF; Combining Diacritical Marks for Symbols
2100..214F; Letterlike Symbols
2150..218F; Number Forms
2190..21FF; Arrows
2200..22FF; Mathematical Operators
2300..23FF; Miscellaneous Technical
2400..243F; Control Pictures
2440..245F; Optical Character Recognition
2460..24FF; Enclosed Alphanumerics
2500..257F; Box Drawing
2580..259F; Block Elements
25A0..25FF; Geometric Shapes
2600..26FF; Miscellaneous Symbols
2700..27BF; Dingbats
27C0..27EF; Miscellaneous Mathematical Symbols-A
27F0..27FF; Supplemental Arrows-A
2800..28FF; Braille Patterns
2900..297F; Supplemental Arrows-B
2980..29FF; Miscellaneous Mathematical Symbols-B
2A00..2AFF; Supplemental Mathematical Operators
2B00..2BFF; Miscellaneous Symbols and Arrows
2C00..2C5F; Glagolitic
2C60..2C7F; Latin Extended-C
2C80..2CFF; Coptic
2D00..2D2F; Georgian Supplement
2D30..2D7F; Tifinagh
2D80..2DDF; Ethiopic Extended
2DE0..2DFF; Cyrillic Extended-A
2E00..2E7F; Supplemental Punctuation
2E80..2EFF; CJK Radicals Supplement
2F00..2FDF; Kangxi Radicals
2FF0..2FFF; Ideographic Description Characters
3000..303F; CJK Symbols and Punctuation
3040..309F; Hiragana
30A0..30FF; Katakana
3100..312F; Bopomofo
3130..318F; Hangul Compatibility Jamo
3190..319F; Kanbun
31A0..31BF; Bopomofo Extended
31C0..31EF; CJK Strokes
31F0..31FF; Katakana Phonetic Extensions
3200..32FF; Enclosed CJK Letters and Months
3300..33FF; CJK Compatibility
3400..4DBF; CJK Unified Ideographs Extension A
4DC0..4DFF; Yijing Hexagram Symbols
4E00..9FFF; CJK Unified Ideographs
A000..A48F; Yi Syllables
A490..A4CF; Yi Radicals
A4D0..A4FF; Lisu
A500..A63F; Vai
A640..A69F; Cyrillic Extended-B
A6A0..A6FF; Bamum
A700..A71F; Modifier Tone Letters
A720..A7FF; Latin Extended-D
A800..A82F; Syloti Nagri
A830..A83F; Common Indic Number Forms
A840..A87F; Phags-pa
A880..A8DF; Saurashtra
A8E0..A8FF; Devanagari Extended
A900..A92F; Kayah Li
A930..A95F; Rejang
A960..A97F; Hangul Jamo Extended-A
A980..A9DF; Javanese
A9E0..A9FF; Myanmar Extended-B
AA00..AA5F; Cham
AA60..AA7F; Myanmar Extended-A
AA80..AADF; Tai Viet
AAE0..AAFF; Meetei Mayek Extensions
AB00..AB2F; Ethiopic Extended-A
AB30..AB6F; Latin Extended-E
AB70..ABBF; Cherokee Supplement
ABC0..ABFF; Meetei Mayek
AC00..D7AF; Hangul Syllables
D7B0..D7FF; Hangul Jamo Extended-B
D800..DB7F; High Surrogates
DB80..DBFF; High Private Use Surrogates
DC00..DFFF; Low Surrogates
E000..F8FF; Private Use Area
F900..FAFF; CJK Compatibility Ideographs
FB00..FB4F; Alphabetic Presentation Forms
FB50..FDFF; Arabic Presentation Forms-A
FE00..FE0F; Variation Selectors
FE10..FE1F; Vertical Forms
FE20..FE2F; Combining Half Marks
FE30..FE4F; CJK Compatibility Forms
FE50..FE6F; Small Form Variants
FE70..FEFF; Arabic Presentation Forms-B
FF00..FFEF; Halfwidth and Fullwidth Forms
FFF0..FFFF; Specials
10000..1007F; Linear B Syllabary
10080..100FF; Linear B Ideograms
10100..1013F; Aegean Numbers
10140..1018F; Ancient Greek Numbers
10190..101CF; Ancient Symbols
101D0..101FF; Phaistos Disc
10280..1029F; Lycian
102A0..102DF; Carian
102E0..102FF; Coptic Epact Numbers
10300..1032F; Old Italic
10330..1034F; Gothic
10350..1037F; Old Permic
10380..1039F; Ugaritic
103A0..103DF; Old Persian
10400..1044F; Deseret
10450..1047F; Shavian
10480..104AF; Osmanya
104B0..104FF; Osage
10500..1052F; Elbasan
10530..1056F; Caucasian Albanian
10570..105BF; Vithkuqi
105C0..105FF; Todhri
10600..1077F; Linear A
10780..107BF; Latin Extended-F
10800..1083F; Cypriot Syllabary
10840..1085F; Imperial Aramaic
10860..1087F; Palmyrene
10880..108AF; Nabataean
108E0..108FF; Hatran
10900..1091F; Phoenician
10920..1093F; Lydian
10940..1095F; Sidetic
10980..1099F; Meroitic Hieroglyphs
109A0..109FF; Meroitic Cursive
10A00..10A5F; Kharoshthi
10A60..10A7F; Old South Arabian
10A80..10A9F; Old North Arabian
10AC0..10AFF; Manichaean
10B00..10B3F; Avestan
10B40..10B5F; Inscriptional Parthian
10B60..10B7F; Inscriptional Pahlavi
10B80..10BAF; Psalter Pahlavi
10C00..10C4F; Old Turkic
10C80..10CFF; Old Hungarian
10D00..10D3F; Hanifi Rohingya
10D40..10D8F; Garay
10E60..10E7F; Rumi Numeral Symbols
10E80..10EBF; Yezidi
10EC0..10EFF; Arabic Extended-C
10F00..10F2F; Old Sogdian
10F30..10F6F; Sogdian
10F70..10FAF; Old Uyghur
10FB0..10FDF; Chorasmian
10FE0..10FFF; Elymaic
11000..1107F; Brahmi
11080..110CF; Kaithi
110D0..110FF; Sora Sompeng
11100..1114F; Chakma
11150..1117F; Mahajani
11180..111DF; Sharada
111E0..111FF; Sinhala Archaic Numbers
11200..1124F; Khojki
11280..112AF; Multani
112B0..112FF; Khudawadi
11300..1137F; Grantha
11380..113FF; Tulu-Tigalari
11400..1147F; Newa
11480..114DF; Tirhuta
11580..115FF; Siddham
11600..1165F; Modi
11660..1167F; Mongolian Supplement
11680..116CF; Takri
116D0..116FF; Myanmar Extended-C
11700..1174F; Ahom
11800..1184F; Dogra
118A0..118FF; Warang Citi
11900..1195F; Dives Akuru
119A0..119FF; Nandinagari
11A00..11A4F; Zanabazar Square
11A50..11AAF; Soyombo
11AB0..11ABF; Unified Canadian Aboriginal Syllabics Extended-A
11AC0..11AFF; Pau Cin Hau
11B00..11B5F; Devanagari Extended-A
11B60..11B7F; Sharada Supplement
11BC0..11BFF; Sunuwar
11C00..11C6F; Bhaiksuki
11C70..11CBF; Marchen
11D00..11D5F; Masaram Gondi
11D60..11DAF; Gunjala Gondi
11DB0..11DEF; Tolong Siki
11DF0..11DFF; Bengali Supplement
11EE0..11EFF; Makasar
11F00..11F5F; Kawi
11FB0..11FBF; Lisu Supplement
11FC0..11FFF; Tamil Supplement
12000..123FF; Cuneiform
12400..1247F; Cuneiform Numbers and Punctuation
12480..1254F; Early Dynastic Cuneiform
12550..1268F; Archaic Cuneiform Numerals
12F90..12FFF; Cypro-Minoan
13000..1342F; Egyptian Hieroglyphs
13430..1345F; Egyptian Hieroglyph Format Controls
13460..143FF; Egyptian Hieroglyphs Extended-A
14400..1467F; Anatolian Hieroglyphs
16100..1613F; Gurung Khema
16800..16A3F; Bamum Supplement
16A40..16A6F; Mro
16A70..16ACF; Tangsa
16AD0..16AFF; Bassa Vah
16B00..16B8F; Pahawh Hmong
16D40..16D7F; Kirat Rai
16D80..16DAF; Chisoi
16E40..16E9F; Medefaidrin
16EA0..16EDF; Beria Erfe
16F00..16F9F; Miao
16FE0..16FFF; Ideographic Symbols and Punctuation
17000..187FF; Tangut
18800..18AFF; Tangut Components
18B00..18CFF; Khitan Small Script
18D00..18D7F; Tangut Supplement
18D80..18DFF; Tangut Components Supplement
18E00..1919F; Jurchen
191A0..191DF; Jurchen Radicals
1AFF0..1AFFF; Kana Extended-B
1B000..1B0FF; Kana Supplement
1B100..1B12F; Kana Extended-A
1B130..1B16F; Small Kana Extension
1B170..1B2FF; Nushu
1BC00..1BC9F; Duployan
1BCA0..1BCAF; Shorthand Format Controls
1CC00..1CEBF; Symbols for Legacy Computing Supplement
1CEC0..1CEFF; Miscellaneous Symbols Supplement
1CF00..1CFCF; Znamenny Musical Notation
1D000..1D0FF; Byzantine Musical Symbols
1D100..1D1FF; Musical Symbols
1D200..1D24F; Ancient Greek Musical Notation
1D250..1D28F; Musical Symbols Supplement
1D2C0..1D2DF; Kaktovik Numerals
1D2E0..1D2FF; Mayan Numerals
1D300..1D35F; Tai Xuan Jing Symbols
1D360..1D37F; Counting Rod Numerals
1D400..1D7FF; Mathematical Alphanumeric Symbols
1D800..1DAAF; Sutton SignWriting
1DB00..1DBFF; Miscellaneous Symbols and Arrows Extended
1DF00..1DFFF; Latin Extended-G
1E000..1E02F; Glagolitic Supplement
1E030..1E08F; Cyrillic Extended-D
1E100..1E14F; Nyiakeng Puachue Hmong
1E290..1E2BF; Toto
1E2C0..1E2FF; Wancho
1E4D0..1E4FF; Nag Mundari
1E5D0..1E5FF; Ol Onal
1E6C0..1E6FF; Tai Yo
1E7E0..1E7FF; Ethiopic Extended-B
1E800..1E8DF; Mende Kikakui
1E900..1E95F; Adlam
1EC70..1ECBF; Indic Siyaq Numbers
1ED00..1ED4F; Ottoman Siyaq Numbers
1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols
1F000..1F02F; Mahjong Tiles
1F030..1F09F; Domino Tiles
1F0A0..1F0FF; Playing Cards
1F100..1F1FF; Enclosed Alphanumeric Supplement
1F200..1F2FF; Enclosed Ideographic Supplement
1F300..1F5FF; Miscellaneous Symbols and Pictographs
1F600..1F64F; Emoticons
1F650..1F67F; Ornamental Dingbats
1F680..1F6FF; Transport and Map Symbols
1F700..1F77F; Alchemical Symbols
1F780..1F7FF; Geometric Shapes Extended
1F800..1F8FF; Supplemental Arrows-C
1F900..1F9FF; Supplemental Symbols and Pictographs
1FA00..1FA6F; Chess Symbols
1FA70..1FAFF; Symbols and Pictographs Extended-A
1FB00..1FBFF; Symbols for Legacy Computing
20000..2A6DF; CJK Unified Ideographs Extension B
2A700..2B73F; CJK Unified Ideographs Extension C
2B740..2B81F; CJK Unified Ideographs Extension D
2B820..2CEAF; CJK Unified Ideographs Extension E
2CEB0..2EBEF; CJK Unified Ideographs Extension F
2EBF0..2EE5F; CJK Unified Ideographs Extension I
2F800..2FA1F; CJK Compatibility Ideographs Supplement
30000..3134F; CJK Unified Ideographs Extension G
31350..323AF; CJK Unified Ideographs Extension H
323B0..3347F; CJK Unified Ideographs Extension J
3D000..3FC3F; Seal
E0000..E007F; Tags
E0100..E01EF; Variation Selectors Supplement
F0000..FFFFF; Supplementary Private Use Area-A
100000..10FFFF; Supplementary Private Use Area-B
# EOF
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# build-wght.sh - 交叉编译 fontmm-wght (Go -> android-arm64, 无需 NDK)
# 产物输出到 src/tools/fontmm-wght, 随模块 zip 打包 (与 mi-font-download.sh 等工具脚本同层)
set -e
cd "$(dirname "$0")/../golang"
echo "[*] 交叉编译 fontmm-wght (android/arm64)..."
GOOS=android GOARCH=arm64 CGO_ENABLED=0 go build -ldflags="-s -w" -o ../src/tools/fontmm-wght ./cmd/fontmm-wght
echo "[✓] 产物: src/tools/fontmm-wght ($(wc -c < ../src/tools/fontmm-wght) 字节)"
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env bash
set -euo pipefail
# dev/cd.sh — 打包 FontMM 模块 (preplace / template 两版)
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC_DIR="$ROOT_DIR/src"
DIST_DIR="$ROOT_DIR/dist"
PROP_FILE="$SRC_DIR/module.prop"
command -v zip >/dev/null 2>&1 || {
echo "[!] 未找到 zip 命令, 请先安装" >&2
exit 1
}
# 1. 从 module.prop 读版本号: version=26.8.0-beta.1(260800001)
VERSION="$(sed -n 's/^version=//p' "$PROP_FILE" 2>/dev/null | head -n 1 | tr -d '\r' || true)"
if [ -z "$VERSION" ]; then
echo "[!] 无法从 $PROP_FILE 读取 version 字段" >&2
exit 1
fi
# 文件名安全化: 括号 -> 点 (GitHub Release 网页上传会把括号改写为点, 导致 URL 不一致)
# 26.8.0-beta.1(260800001) -> 26.8.0-beta.1.260800001
FILE_VERSION="$(printf '%s' "$VERSION" | sed 's/(/./g; s/)//g')"
PRE_OUT="$DIST_DIR/FontMM_v${FILE_VERSION}_preplace.zip"
TPL_OUT="$DIST_DIR/FontMM_v${FILE_VERSION}_template.zip"
mkdir -p "$DIST_DIR"
rm -f "$PRE_OUT" "$TPL_OUT" # 先删旧的, 防止 zip 增量更新残留已删除的文件
# 0. 派生字体配置由 customize.sh 在设备上扫描生成 (issue #7), 打包时不再复制;
# 仅保留 fonts.xml 主配置。dev/sync-fonts-xml.sh 供开发期本地调试参考。
# 0.5 交叉编译 fontmm-wght (Go -> android-arm64, 字重范围覆写用)
bash "$ROOT_DIR/dev/build-wght.sh"
# 保证工具二进制可执行 (zip 权限位 -> Magisk 安装后保持)
chmod 755 "$SRC_DIR/tools/fontmm-wght"
# 0.6 生成模块可执行文件 SHA256 校验文件 (src/SHA256SUMS, 随 zip 打包)
bash "$ROOT_DIR/dev/gen-sha256.sh" --no-dist
# 派生配置路径 (从 zip 中排除, 避免与设备端生成冲突)
DERIVED_XML='system/etc/fonts_base.xml system/etc/fonts_ule.xml system/etc/font_fallback.xml system/system_ext/etc/fonts_base.xml system/system_ext/etc/fonts_ule.xml'
# 2. 打包函数: $1=输出路径, $2=额外排除模式 (可选)
# (zip 根 = 模块根, 不含 src 这层目录)
pack() {
local out="$1" extra="${2:-}"
local args=(-r -2 "$out" . -x '*.git*' -x '*.DS_Store' -x '*.swp' -x '*~' -x '*.bak')
local f=""
for f in $DERIVED_XML; do
args+=(-x "$f")
done
if [ -n "$extra" ]; then
args+=(-x "$extra")
fi
(
cd "$SRC_DIR"
zip "${args[@]}"
)
}
echo "[*] 打包 preplace 版 (含预置字体)..."
pack "$PRE_OUT"
echo "[*] 打包 template 版 (FONT 目录为空)..."
pack "$TPL_OUT" 'FONTS/*'
# -x 'FONTS/*' 会连目录条目一起排除, 这里补回空的 FONTS/ 目录
(
cd "$SRC_DIR"
zip -g "$TPL_OUT" 'FONTS/'
)
# 3. 产物校验: 必须含 module.prop, 防止打包错目录
# 注意: 不能用 grep -q, 它匹配后立即退出会使上游 unzip 收到 SIGPIPE (141),
# 在 pipefail 下整个管道被判失败, 产生"缺少 module.prop"的偶发误报
check() {
local out="$1"
if ! unzip -l "$out" | grep 'module\.prop' >/dev/null; then
echo "[!] 打包产物缺少 module.prop: $out" >&2
exit 1
fi
}
check "$PRE_OUT"
check "$TPL_OUT"
# 4. template 版校验: FONTS 目录必须不含字体文件 (保留空目录)
if unzip -l "$TPL_OUT" | grep 'FONTS/.*\.ttf' >/dev/null; then
echo "[!] template 版不应包含 FONTS 字体文件" >&2
exit 1
fi
# 5. 生成发布产物 sha256 (dist/*.zip.sha256)
bash "$ROOT_DIR/dev/gen-sha256.sh" || true
echo "[✓] 打包完成:"
echo " preplace: $PRE_OUT ($(du -h "$PRE_OUT" | cut -f1))"
echo " template: $TPL_OUT ($(du -h "$TPL_OUT" | cut -f1))"
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""check-unicode-coverage.py — 本地模拟 Android 字体 fallback 链, 统计 Unicode 区块覆盖率.
原理: 按 fonts.xml 中 family 的声明顺序构成 fallback 链, 逐字形检查覆盖;
用 fontTools 读取各字体 cmap, 对照 Unicode Blocks.txt 统计每个区块的覆盖率.
用法:
python3 dev/check-unicode-coverage.py # 全部区块 (自动获取 Blocks.txt 缓存到 dev/)
python3 dev/check-unicode-coverage.py --blocks-file Blocks.txt
python3 dev/check-unicode-coverage.py Hebrew "Archaic" # 只测匹配的区块名 (子串)
"""
import argparse
import os
import urllib.request
import xml.etree.ElementTree as ET
from fontTools.ttLib import TTFont
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FONTS_DIR = os.path.join(ROOT, 'src', 'system', 'fonts')
FONTS_XML = os.path.join(ROOT, 'src', 'system', 'etc', 'fonts.xml')
BLOCKS_URL = 'https://www.unicode.org/Public/draft/ucd/Blocks.txt'
def load_chain(xml_path):
"""按 fonts.xml 声明顺序提取 fallback 链 (全部 font 文件名, 去重)."""
root = ET.parse(xml_path).getroot()
chain, seen = [], set()
for family in root.iter('family'):
for font in family.iter('font'):
name = (font.text or '').strip()
if name and name not in seen:
seen.add(name)
chain.append(name)
return chain
def load_cmaps(fonts_dir, chain):
cmaps, missing = {}, []
for name in chain:
path = os.path.join(fonts_dir, name)
if not os.path.exists(path):
missing.append(name)
continue
try:
cmaps[name] = TTFont(path, lazy=True).getBestCmap()
except Exception as exc: # 解析失败 (如特殊字体) 跳过
missing.append(f'{name} ({exc})')
return cmaps, missing
def load_blocks(path):
blocks = []
with open(path, encoding='utf-8') as fh:
for line in fh:
line = line.strip()
if not line or line.startswith('#') or '..' not in line:
continue
rng, name = line.split(';')
start, end = (int(x, 16) for x in rng.strip().split('..'))
blocks.append((name.strip(), start, end))
return blocks
def fetch_blocks(dest):
print(f'[i] 获取 Blocks.txt: {BLOCKS_URL}')
urllib.request.urlretrieve(BLOCKS_URL, dest)
return dest
def main():
ap = argparse.ArgumentParser(description='本地 Unicode 覆盖测试 (模拟 fonts.xml fallback 链)')
ap.add_argument('blocks', nargs='*', help='只测试匹配的区块名 (子串, 如 Hebrew)')
ap.add_argument('--blocks-file', help='本地 Blocks.txt 路径 (默认自动下载缓存到 dev/Blocks.txt)')
args = ap.parse_args()
chain = load_chain(FONTS_XML)
print(f'[i] fallback 链: {len(chain)} 个字体 ({FONTS_XML})')
cmaps, missing = load_cmaps(FONTS_DIR, chain)
if missing:
print(f'[!] 缺失/无法解析的字体: {missing}')
if not cmaps:
print('[!] 无可用字体, 退出', file=os.sys.stderr)
return 1
# 合并全部 cmap 为并集, 快速判字形
union = set()
for cm in cmaps.values():
union.update(cm)
print(f'[i] 可用字体 {len(cmaps)} 个, 字形码位并集 {len(union):,}')
blocks_file = args.blocks_file
if not blocks_file:
blocks_file = os.path.join(ROOT, 'dev', 'Blocks.txt')
if not os.path.exists(blocks_file):
fetch_blocks(blocks_file)
blocks = load_blocks(blocks_file)
if args.blocks:
blocks = [b for b in blocks if any(k.lower() in b[0].lower() for k in args.blocks)]
print(f'\n{"Block":<42}{"Covered":>9}{"Total":>8}{"Pct":>9} Status')
print('-' * 76)
failed = []
for name, start, end in blocks:
total = end - start + 1
covered = sum(1 for cp in range(start, end + 1) if cp in union)
pct = covered / total * 100 if total else 0
status = 'PASS' if covered == total else ('FAIL' if pct < 95 else '')
if status == 'FAIL':
failed.append(name)
print(f'{name:<42}{covered:>9}{total:>8}{pct:>8.2f}% {status}')
print(f'\n[=] 共 {len(blocks)} 个区块, FAIL (<95%): {len(failed)} 个')
for name in failed:
print(f' - {name}')
return 1 if failed else 0
if __name__ == '__main__':
raise SystemExit(main())
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$SCRIPT_DIR"
# ---------- Termux 兼容 ----------
# Termux 的 shellcheck / shfmt 安装在 app 私有目录, 需手动加入 PATH 与 LD_LIBRARY_PATH;
# 其他环境 (Linux/macOS 等) 直接使用系统 PATH 中的工具
if [ -n "${PREFIX:-}" ] && [ -d "$PREFIX/bin" ]; then
export PATH="$PREFIX/bin:${PATH}"
export LD_LIBRARY_PATH="$PREFIX/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
elif [ -d /data/user/0/com.termux/files/usr/bin ]; then
export PATH="/data/user/0/com.termux/files/usr/bin:${PATH}"
export LD_LIBRARY_PATH="/data/user/0/com.termux/files/usr/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
fi
# 工具可用性检查
command -v shellcheck > /dev/null 2>&1 || {
echo "[!] 未找到 shellcheck, 请先安装" >&2
exit 1
}
command -v shfmt > /dev/null 2>&1 || {
echo "[!] 未找到 shfmt, 请先安装" >&2
exit 1
}
shopt -s nullglob globstar
files=("$SCRIPT_DIR/src"/**/*.sh)
for f in "${files[@]}"; do
echo "> Checking: $f"
shellcheck "$f" || exit 1
done
for f in "${files[@]}"; do
echo "> Formatting: $f"
shfmt -i 4 -w -d "$f"
done
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
FONT_DIR="$SCRIPT_DIR/src/system/fonts"
# 字体清单(记得和 customize.sh 保持一致)
all_fonts='SysSans-Hans-Regular.ttf
SysFont-Static-Regular.ttf
SysFont-Myanmar.ttf
SysFont-Hans-Regular.ttf
SysFont-Regular.ttf
SysSans-Hant-Regular.ttf
SysFont-Hant-Regular.ttf
SysSans-En-Regular.ttf'
mkdir -p "$FONT_DIR"
count=0
while IFS= read -r font; do
[ -z "$font" ] && continue
: > "$FONT_DIR/$font"
echo "[*] 已生成空字体: $font"
count=$((count + 1))
done <<< "$all_fonts"
echo "[✓] 完成,共 $count 个空字体 -> $FONT_DIR"
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -euo pipefail
# dev/gen-sha256.sh — 生成模块可执行文件的 SHA256 校验文件
# 1. src/SHA256SUMS: 记录模块内脚本/二进制的 sha256 (随 zip 打包, 供设备端 verify-sha256.sh 校验)
# 2. dist/*.sha256: 记录打包产物 zip 的 sha256 (发布时作为 release asset)
#
# 用法: bash dev/gen-sha256.sh [--no-dist]
# --no-dist: 只生成 src/SHA256SUMS, 跳过 dist 产物校验 (供 cd.sh 打包前调用)
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC_DIR="$ROOT_DIR/src"
DIST_DIR="$ROOT_DIR/dist"
NO_DIST=0
[ "${1:-}" = "--no-dist" ] && NO_DIST=1
command -v sha256sum >/dev/null 2>&1 || {
echo "[!] 未找到 sha256sum 命令" >&2
exit 1
}
# 生成 src/SHA256SUMS: 只收录可执行文件 (脚本/二进制), 路径相对模块根
# 注: SHA256SUMS 自身不收录 (自引用无意义)
gen_module_sum() {
local out="$SRC_DIR/SHA256SUMS"
local tmp
tmp="$(mktemp)"
local f=""
while IFS= read -r f; do
[ -z "$f" ] && continue
local rel="${f#"$SRC_DIR"/}"
sha256sum "$f" | awk -v r="$rel" '{ print $1 " " r }' >>"$tmp"
done < <(find "$SRC_DIR" -type f \
\( -name '*.sh' -o -name 'fontmm-wght' -o -name 'update-binary' -o -name 'updater-script' \) \
-not -path '*/webroot/*' | sort)
mv "$tmp" "$out"
echo "[✓] 已生成 $out ($(wc -l <"$out") 条可执行文件校验)"
}
# 生成 dist/*.sha256 (发布产物校验)
gen_dist_sum() {
[ "$NO_DIST" -eq 1 ] && return 0
[ -d "$DIST_DIR" ] || { echo "[-] 无 dist 目录, 跳过"; return 0; }
local z=""
while IFS= read -r z; do
[ -z "$z" ] && continue
sha256sum "$z" >"$z.sha256"
echo "[✓] 已生成 ${z}.sha256"
done < <(find "$DIST_DIR" -maxdepth 1 -name '*.zip' | sort)
}
gen_module_sum
gen_dist_sum
echo "[✓] SHA256 校验文件生成完成"
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
# dev/sync-fonts-xml.sh — 以 fonts.xml 为唯一源, 复制生成各派生字体配置 (仅开发期用)
# 注意: 该脚本仅用于开发期本地对照/调试; 模块打包 (dev/cd.sh) 不再包含派生配置,
# 由刷入脚本 (src/customize.sh) 在设备端扫描系统 XML 生成, 提升兼容性 (issue #7)
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC="$ROOT_DIR/src/system/etc/fonts.xml"
[ -f "$SRC" ] || {
echo "[!] 找不到源文件: $SRC" >&2
exit 1
}
DEST=(
"$ROOT_DIR/src/system/etc/fonts_base.xml"
"$ROOT_DIR/src/system/etc/fonts_ule.xml"
"$ROOT_DIR/src/system/etc/font_fallback.xml"
"$ROOT_DIR/src/system/system_ext/etc/fonts_base.xml"
"$ROOT_DIR/src/system/system_ext/etc/fonts_ule.xml"
)
for f in "${DEST[@]}"; do
cp -f "$SRC" "$f"
echo "[✓] 已同步: $f"
done
echo "[✓] 完成, 共 ${#DEST[@]} 个派生文件"
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
set -euo pipefail
# dev/webzip.sh — 仅把构建产物 src/webroot 压缩为 dist/webroot.zip (调试 WebUI 用)
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC="$ROOT_DIR/src/webroot"
OUT="$ROOT_DIR/dist/webroot.zip"
command -v zip >/dev/null 2>&1 || {
echo "[!] 未找到 zip 命令, 请先安装" >&2
exit 1
}
[ -d "$SRC" ] || {
echo "[!] $SRC 不存在, 请先执行 pnpm -C web build" >&2
exit 1
}
mkdir -p "$(dirname "$OUT")"
rm -f "$OUT"
# zip 根 = webroot 内容 (不含 webroot 这层目录)
(
cd "$SRC"
zip -r -9 "$OUT" . \
-x '*.git*' \
-x '*.DS_Store'
)
echo "[✓] 已打包: $OUT ($(du -h "$OUT" | cut -f1))"
+42
View File
@@ -0,0 +1,42 @@
// fontmm-wght: 覆写模块字体配置 XML 各生效 family 的字重范围
// 用法: fontmm-wght -mode 0|1|2|3 [-min N] [-max N] [-map <wght-map.txt>] [-xml-dir <模块根>] [-sync]
// 说明: 只修改主配置 system/etc/fonts.xml, 加 -sync 后复制到各派生配置 (issue #7)
package main
import (
"flag"
"fmt"
"os"
"fontmm/internal/wght"
)
func main() {
mode := flag.Int("mode", 0, "覆写模式: 0=不处理 1=裁切 2=平均分配 3=自定义映射")
min := flag.Int("min", 100, "裁切/平均最小字重")
max := flag.Int("max", 900, "裁切/平均最大字重")
mapPath := flag.String("map", "", "自定义映射文件 (mode 3): 每行 'weight axis'")
xmlDir := flag.String("xml-dir", "/data/adb/modules/FontMM", "模块根目录 (含 system/etc/fonts.xml)")
sync := flag.Bool("sync", false, "覆写后复制 fonts.xml 到各派生配置")
flag.Parse()
var customMap map[int]int
if *mode == 3 {
var err error
customMap, err = wght.ReadCustomMap(*mapPath)
if err != nil {
fmt.Printf("[x] 读取映射文件失败: %v\n", err)
os.Exit(1)
}
if len(customMap) == 0 {
fmt.Println("[-] 映射文件为空, 使用平均分配回退")
}
}
changed, err := wght.ApplyToDir(*xmlDir, *mode, *min, *max, customMap, *sync)
if err != nil {
fmt.Printf("[x] %v\n", err)
os.Exit(1)
}
fmt.Printf("[✓] 完成, 共处理 %d 个文件\n", changed)
}
+3
View File
@@ -0,0 +1,3 @@
module fontmm
go 1.24.4
+318
View File
@@ -0,0 +1,318 @@
// Package wght 提供字体配置 XML 的字重范围覆写逻辑
package wght
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
)
// 标准 9 档字重
var Weights = []int{100, 200, 300, 400, 500, 600, 700, 800, 900}
// axisStyle 描述家族内 <font> 条目的轴配置风格
type axisStyle int
const (
// axisFull: sans-serif 全轴 (ital/wdth/wght)
axisFull axisStyle = iota
// axisWghtOnly: sys-sans-en / zh-* 仅 wght 轴
axisWghtOnly
)
// familySpec 描述一个需要覆写字重的家族及其条目格式
type familySpec struct {
openTag string // 家族起始标签 (用于定位与生成)
fontFile string // 家族引用的字体文件
postScript string // postScriptName 属性 (无则为空)
serifFallback bool // 是否包含 fallbackFor="serif" 的 400 条目 (zh-Hans/zh-Hant)
axis axisStyle
}
// 所有生效家族: 英文 (sans-serif / sys-sans-en) 与中文 (zh-Hans / zh-Hant) 都要覆盖,
// 否则中文或英文单独使用时字重映射不生效 (issue #7)
var FamilySpecs = []familySpec{
{openTag: `<family name="sans-serif">`, fontFile: "SysFont-Regular.ttf", axis: axisFull},
{openTag: `<family name="sys-sans-en">`, fontFile: "SysSans-En-Regular.ttf", postScript: "OPlusSansEn", axis: axisWghtOnly},
{openTag: `<family lang="zh-Hans">`, fontFile: "SysSans-Hans-Regular.ttf", postScript: "OPPO_Sans_4.0_SC", serifFallback: true, axis: axisWghtOnly},
{openTag: `<family lang="zh-Hant,zh-Bopo">`, fontFile: "SysSans-Hant-Regular.ttf", postScript: "OPPO_Sans_4.0_TC", serifFallback: true, axis: axisWghtOnly},
}
// 主配置文件名 (唯一源)
const SourceXMLRel = "system/etc/fonts.xml"
// 派生配置 (与 fonts.xml 内容一致, 由 -sync 复制生成)
var DerivedXMLRel = []string{
"system/etc/fonts_base.xml",
"system/etc/fonts_ule.xml",
"system/etc/font_fallback.xml",
"system/system_ext/etc/fonts_base.xml",
"system/system_ext/etc/fonts_ule.xml",
}
// 平均分配: weight w 对应的 axis 值 (400 固定, 两端 floor 线性插值)
func AveragedAxis(min, max, w int) int {
if w == 400 {
return 400
}
if w < 400 {
return min + (400-min)*(w-100)/300
}
return 400 + (max-400)*(w-400)/500
}
// 生成 sans-serif 家族段 (mode 1/2/3), 使用标准 9 档字重
func GenerateFamily(min, max, mode int, customMap map[int]int) string {
return generateFamily(FamilySpecs[0], Weights, min, max, mode, customMap)
}
// 生成单条 <font> 条目 (按家族风格)
func fontEntryFor(spec familySpec, weight, axisWght int) string {
if spec.axis == axisFull {
return fmt.Sprintf(` <font weight="%d" style="normal">%s
<axis tag="ital" stylevalue="0" />
<axis tag="wdth" stylevalue="100" />
<axis tag="wght" stylevalue="%d" />
</font>`, weight, spec.fontFile, axisWght)
}
return fmt.Sprintf(` <font weight="%d" style="normal" postScriptName="%s" >%s
<axis tag="wght" stylevalue="%d"/>
</font>`, weight, spec.postScript, spec.fontFile, axisWght)
}
// 生成 zh-Hans/zh-Hant 家族的 fallbackFor="serif" 400 条目
func serifEntry(spec familySpec) string {
return fmt.Sprintf(` <font weight="400" style="normal" fallbackFor="serif"
postScriptName="%s">%s
</font>`, spec.postScript, spec.fontFile)
}
// 生成家族段 (mode 1=裁切 2=平均 3=自定义映射)
// weights 为声明字重集 (取自原家族, 保持设备 XML 一致性)
func generateFamily(spec familySpec, weights []int, min, max, mode int, customMap map[int]int) string {
ws := weights
if mode == 3 && len(customMap) > 0 {
ws = make([]int, 0, len(customMap))
for w := range customMap {
ws = append(ws, w)
}
sort.Ints(ws)
}
var lines []string
for _, w := range ws {
if mode == 1 && (w < min || w > max) {
continue
}
axis := w
if mode == 2 {
axis = AveragedAxis(min, max, w)
} else if mode == 3 {
if v, ok := customMap[w]; ok {
axis = v
} else {
axis = AveragedAxis(min, max, w)
}
}
lines = append(lines, fontEntryFor(spec, w, axis))
if spec.serifFallback && w == 400 {
lines = append(lines, serifEntry(spec))
}
}
return " " + spec.openTag + "\n" + strings.Join(lines, "\n") + "\n </family>"
}
// 在完整 XML 中覆写指定家族段; 家族不存在时原样返回
func replaceFamily(xml string, spec familySpec, mode, min, max int, customMap map[int]int) string {
start := findFamilyStart(xml, spec.openTag)
if start < 0 {
return xml
}
end := matchFamilyClose(xml, start+len(spec.openTag))
if end < 0 {
return xml
}
// 字重集选择: 裁切保留原家族声明字重 (兼容设备 XML), 平均分配固定 9 档完整粗细,
// 自定义映射由映射文件的键决定
weights := Weights
if mode == 1 {
if ex := extractWeights(xml[start:end]); len(ex) > 0 {
weights = ex
}
}
// 整行替换 (含行首缩进与闭合标签后的换行), 保持与原有段一致的缩进
lineStart := start
for lineStart > 0 && xml[lineStart-1] != '\n' {
lineStart--
}
lineEnd := end
for lineEnd < len(xml) && xml[lineEnd] != '\n' {
lineEnd++
}
if lineEnd < len(xml) {
lineEnd++ // 吃掉换行
}
return xml[:lineStart] + generateFamily(spec, weights, min, max, mode, customMap) + "\n" + xml[lineEnd:]
}
// 覆写全部生效家族 (mode 0 原样返回)
func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string {
if mode == 0 {
return xml
}
result := xml
for _, spec := range FamilySpecs {
result = replaceFamily(result, spec, mode, min, max, customMap)
}
return result
}
// 查找 startTag 的位置 (跳过 XML 注释, 避免误匹配注释内的文本)
func findFamilyStart(xml, startTag string) int {
searchFrom := 0
for {
i := strings.Index(xml[searchFrom:], startTag)
if i < 0 {
return -1
}
i += searchFrom
open := strings.LastIndex(xml[:i], "<!--")
if open < 0 {
return i
}
if rel := strings.Index(xml[open:], "-->"); rel < 0 || open+rel+3 > i {
// 命中位置在注释内, 继续向后找
searchFrom = i + 1
continue
}
return i
}
}
// 从紧随 <family ...> 之后的位置开始, 找到配对的 </family> (含嵌套),
// 返回其结束位置 (含标签); 未找到返回 -1
func matchFamilyClose(xml string, start int) int {
depth := 1
i := start
for i < len(xml) {
// 跳过注释
if strings.HasPrefix(xml[i:], "<!--") {
if rel := strings.Index(xml[i:], "-->"); rel >= 0 {
i += rel + len("-->")
continue
}
}
// 找下一个 '<'
lt := strings.IndexByte(xml[i:], '<')
if lt < 0 {
return -1
}
i += lt
if strings.HasPrefix(xml[i:], "</family>") {
depth--
if depth == 0 {
return i + len("</family>")
}
i += len("</family>")
continue
}
if strings.HasPrefix(xml[i:], "<family") {
gt := strings.IndexByte(xml[i:], '>')
if gt < 0 {
return -1
}
// 自闭合 <family .../> 不增加嵌套深度
if xml[i+gt-1] != '/' {
depth++
}
i += gt + 1
continue
}
// 其他标签: 跳到 '>' 之后
gt := strings.IndexByte(xml[i:], '>')
if gt < 0 {
return -1
}
i += gt + 1
}
return -1
}
var weightRe = regexp.MustCompile(`<font weight="(\d+)"`)
// 提取家族段内声明字重 (去重并升序), 保留设备 XML 的字重集
func extractWeights(block string) []int {
var ws []int
seen := map[int]bool{}
for _, m := range weightRe.FindAllStringSubmatch(block, -1) {
if n, err := strconv.Atoi(m[1]); err == nil && !seen[n] {
ws = append(ws, n)
seen[n] = true
}
}
sort.Ints(ws)
return ws
}
// 读取自定义映射文件 (每行 "weight axis")
func ReadCustomMap(path string) (map[int]int, error) {
m := map[int]int{}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Fields(line)
if len(parts) != 2 {
continue
}
w, err1 := strconv.Atoi(parts[0])
v, err2 := strconv.Atoi(parts[1])
if err1 == nil && err2 == nil {
m[w] = v
}
}
return m, nil
}
// ApplyToDir 覆写模块根目录下的主配置 fonts.xml; sync 为 true 时复制到各派生配置
// 返回覆写/同步的文件总数
func ApplyToDir(xmlDir string, mode, min, max int, customMap map[int]int, sync bool) (int, error) {
src := filepath.Join(xmlDir, SourceXMLRel)
data, err := os.ReadFile(src)
if err != nil {
return 0, fmt.Errorf("读取 %s 失败: %w", SourceXMLRel, err)
}
replaced := ApplyWghtMode(string(data), mode, min, max, customMap)
changed := 0
if replaced != string(data) {
if err := os.WriteFile(src, []byte(replaced), 0o644); err != nil {
return changed, fmt.Errorf("写入失败 %s: %w", SourceXMLRel, err)
}
changed++
fmt.Printf("[✓] 已覆写: %s\n", SourceXMLRel)
} else {
fmt.Printf("[-] 无变化: %s\n", SourceXMLRel)
}
if sync {
for _, rel := range DerivedXMLRel {
p := filepath.Join(xmlDir, rel)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return changed, fmt.Errorf("创建目录失败 %s: %w", filepath.Dir(p), err)
}
if err := os.WriteFile(p, []byte(replaced), 0o644); err != nil {
return changed, fmt.Errorf("同步失败 %s: %w", rel, err)
}
changed++
fmt.Printf("[✓] 已同步: %s\n", rel)
}
}
return changed, nil
}
+275
View File
@@ -0,0 +1,275 @@
package wght
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// 平均分配公式 (MiSansVF 150-700, 与用户示例一致)
func TestAveragedAxis(t *testing.T) {
want := map[int]int{100: 150, 200: 233, 300: 316, 400: 400, 500: 460, 600: 520, 700: 580, 800: 640, 900: 700}
for w, v := range want {
if got := AveragedAxis(150, 700, w); got != v {
t.Errorf("AveragedAxis(150,700,%d) = %d, want %d", w, got, v)
}
}
}
func extractAttrs(family string) ([]int, []int) {
var ws, axes []int
for _, line := range strings.Split(family, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "<font weight=") {
var w int
if _, err := fmt.Sscanf(line, "<font weight=\"%d\"", &w); err == nil {
ws = append(ws, w)
}
}
if strings.Contains(line, `<axis tag="wght" stylevalue="`) {
var v int
if _, err := fmt.Sscanf(line, "<axis tag=\"wght\" stylevalue=\"%d\"", &v); err == nil {
axes = append(axes, v)
}
}
}
return ws, axes
}
func TestGenerateFamilyTrim(t *testing.T) {
family := GenerateFamily(150, 700, 1, nil)
ws, axes := extractAttrs(family)
want := []int{200, 300, 400, 500, 600, 700}
if len(ws) != len(want) {
t.Fatalf("裁切 weight = %v, want %v", ws, want)
}
for i := range want {
if ws[i] != want[i] || axes[i] != want[i] {
t.Errorf("裁切第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], want[i], want[i])
}
}
}
func TestGenerateFamilyAvg(t *testing.T) {
family := GenerateFamily(150, 700, 2, nil)
ws, axes := extractAttrs(family)
wantW := []int{100, 200, 300, 400, 500, 600, 700, 800, 900}
wantA := []int{150, 233, 316, 400, 460, 520, 580, 640, 700}
if len(ws) != 9 {
t.Fatalf("平均 weight = %v", ws)
}
for i := range wantW {
if ws[i] != wantW[i] || axes[i] != wantA[i] {
t.Errorf("平均第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], wantW[i], wantA[i])
}
}
}
func TestGenerateFamilyCustom(t *testing.T) {
m := map[int]int{150: 180, 250: 300, 400: 400, 700: 650}
family := GenerateFamily(150, 700, 3, m)
ws, axes := extractAttrs(family)
wantW := []int{150, 250, 400, 700}
wantA := []int{180, 300, 400, 650}
for i := range wantW {
if ws[i] != wantW[i] || axes[i] != wantA[i] {
t.Errorf("自定义第 %d 项 weight=%d axis=%d, want %d/%d", i, ws[i], axes[i], wantW[i], wantA[i])
}
}
}
func TestApplyWghtMode(t *testing.T) {
xml := "<?xml version=\"1.0\"?>\n<familyset>\n <!-- #ifdef OPLUS_FEATURE_FONT_FLIP -->\n" +
" <family name=\"sans-serif\">\n <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n </font>\n </family>\n" +
" <!-- #endif -->\n</familyset>\n"
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
if !strings.Contains(replaced, "OPLUS_FEATURE_FONT_FLIP") {
t.Error("覆写后 #ifdef 注释丢失")
}
if !strings.Contains(replaced, `stylevalue="233"`) {
t.Error("覆写后缺少平均分配值 233")
}
if strings.Count(replaced, "<family name=\"sans-serif\">") != 1 {
t.Error("sans-serif family 数量异常")
}
// mode 0 原样
if ApplyWghtMode(xml, 0, 150, 700, nil) != xml {
t.Error("mode=0 应原样返回")
}
}
// 所有生效家族 (sans-serif / sys-sans-en / zh-Hans / zh-Hant) 都应被覆写,
// 保证中英文都有正确的字重映射 (issue #7)
func TestApplyWghtModeAllFamilies(t *testing.T) {
xml := "<?xml version=\"1.0\"?>\n<familyset version=\"23\">\n" +
" <family name=\"sans-serif\">\n <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n </font>\n </family>\n" +
" <family name=\"sys-sans-en\">\n <font weight=\"100\" style=\"normal\" postScriptName=\"OPlusSansEn\">SysSans-En-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n </family>\n" +
" <family lang=\"zh-Hans\">\n <font weight=\"100\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n <font weight=\"400\" style=\"normal\" fallbackFor=\"serif\"\n" +
" postScriptName=\"OPPO_Sans_4.0_SC\">SysSans-Hans-Regular.ttf\n </font>\n </family>\n" +
" <family lang=\"zh-Hant,zh-Bopo\">\n <font weight=\"100\" style=\"normal\" postScriptName=\"OPPO_Sans_4.0_TC\">SysSans-Hant-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\"/>\n </font>\n </family>\n" +
"</familyset>\n"
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
for _, tag := range []string{
`<family name="sans-serif">`,
`<family name="sys-sans-en">`,
`<family lang="zh-Hans">`,
`<family lang="zh-Hant,zh-Bopo">`,
} {
if strings.Count(replaced, tag) != 1 {
t.Errorf("覆写后应保留且只出现一次 %s", tag)
}
}
// zh-Hans 家族应保留 serif fallback 条目
if !strings.Contains(replaced, `fallbackFor="serif"`) {
t.Error("zh-Hans 家族丢失 fallbackFor=\"serif\" 条目")
}
// 各家族字号都应含平均分配后的 200 -> 233
if strings.Count(replaced, `stylevalue="233"`) != 4 {
t.Errorf("各家族应有 4 处 233 轴值, 实际 %d", strings.Count(replaced, `stylevalue="233"`))
}
}
// 段内有嵌套 family (如 sans-serif-black) 时, 必须配对正确的 </family>,
// 不能把嵌套段的闭合当成外层闭合导致尾部丢失 (曾导致无法开机)
func TestApplyWghtModeNestedFamily(t *testing.T) {
xml := "<?xml version=\"1.0\"?>\n<familyset>\n" +
" <!-- #ifdef OPLUS_FEATURE_FONT_FLIP -->\n" +
" <family name=\"sans-serif\">\n" +
" <family name=\"sans-serif-black\">\n" +
" <font weight=\"900\" style=\"normal\">Black.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"900\" />\n" +
" </font>\n" +
" </family>\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n" +
" </font>\n" +
" </family>\n" +
" <!-- #endif -->\n" +
" <family name=\"sans-serif-medium\">\n" +
" <font weight=\"500\" style=\"normal\">Medium.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"500\" />\n" +
" </font>\n" +
" </family>\n" +
"</familyset>\n"
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
// 后续的 sans-serif-medium 段必须完整保留 (嵌套闭合误配会导致其被切掉)
if !strings.Contains(replaced, `<family name="sans-serif-medium">`) {
t.Fatal("覆写后丢失了 sans-serif-medium 段")
}
if strings.Contains(replaced, `<family name="sans-serif-black">`) {
t.Error("sans-serif-black 嵌套段未随段替换被移除")
}
// 闭合标签数量应与开始标签数量一致 (结构完整)
open := strings.Count(replaced, "<family ")
closeN := strings.Count(replaced, "</family>")
if open != closeN {
t.Errorf("family 标签不平衡: open=%d close=%d\n%s", open, closeN, replaced)
}
if !strings.HasSuffix(replaced, "</familyset>\n") {
t.Errorf("文件末尾被破坏:\n%s", replaced)
}
}
// 段首不应被重复缩进 (原行缩进 + 生成段自带缩进)
func TestApplyWghtModeNoDoubleIndent(t *testing.T) {
xml := "<familyset>\n" +
" <family name=\"sans-serif\">\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n" +
" </font>\n" +
" </family>\n" +
"</familyset>\n"
replaced := ApplyWghtMode(xml, 1, 100, 900, nil)
if strings.Contains(replaced, " <family name=\"sans-serif\">") {
t.Errorf("段首出现重复缩进 (8 空格):\n%s", replaced)
}
if !strings.Contains(replaced, " <family name=\"sans-serif\">") {
t.Errorf("段首应为 4 空格缩进:\n%s", replaced)
}
}
// ApplyToDir 只覆写主配置 fonts.xml, sync 时复制到各派生配置 (issue #7)
func TestApplyToDirSync(t *testing.T) {
dir := t.TempDir()
mkfile := func(rel, content string) {
p := dir + "/" + rel
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
base := "<familyset>\n" +
" <family name=\"sans-serif\">\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n" +
" </font>\n" +
" </family>\n" +
"</familyset>\n"
mkfile(SourceXMLRel, base)
// 派生配置预置旧内容, 验证被覆盖
for _, rel := range DerivedXMLRel {
mkfile(rel, "<familyset>\n</familyset>\n")
}
changed, err := ApplyToDir(dir, 2, 150, 700, nil, true)
if err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
// 1 份主配置 + 5 份派生 = 6
if changed != 1+len(DerivedXMLRel) {
t.Fatalf("changed = %d, want %d", changed, 1+len(DerivedXMLRel))
}
src, err := os.ReadFile(dir + "/" + SourceXMLRel)
if err != nil {
t.Fatal(err)
}
for _, rel := range DerivedXMLRel {
data, err := os.ReadFile(dir + "/" + rel)
if err != nil {
t.Fatalf("派生配置缺失 %s: %v", rel, err)
}
if string(data) != string(src) {
t.Errorf("派生配置 %s 与 fonts.xml 不一致", rel)
}
}
if !strings.Contains(string(src), `stylevalue="233"`) {
t.Error("覆写后应含平均分配值 233")
}
}
// mode 0 + sync: 不改内容, 仅把 fonts.xml 复制到派生配置 (customize.sh 用)
func TestApplyToDirSyncMode0(t *testing.T) {
dir := t.TempDir()
base := "<familyset>\n</familyset>\n"
if err := os.MkdirAll(dir+"/system/etc", 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dir+"/"+SourceXMLRel, []byte(base), 0o644); err != nil {
t.Fatal(err)
}
changed, err := ApplyToDir(dir, 0, 100, 900, nil, true)
if err != nil {
t.Fatalf("ApplyToDir: %v", err)
}
if changed != len(DerivedXMLRel) {
t.Fatalf("mode0+sync changed = %d, want %d", changed, len(DerivedXMLRel))
}
for _, rel := range DerivedXMLRel {
data, err := os.ReadFile(dir + "/" + rel)
if err != nil {
t.Fatalf("派生配置缺失 %s: %v", rel, err)
}
if string(data) != base {
t.Errorf("派生配置 %s 内容不一致", rel)
}
}
}
-6
View File
@@ -1,6 +0,0 @@
id=MyFontModule
name=我的字体模块
version=1.0
versionCode=10
author=Yule
description=我的字体模块
+18
View File
@@ -0,0 +1,18 @@
{
"name": "fontmm",
"private": true,
"scripts": {
"dev": "pnpm -C web dev",
"build": "pnpm -C web build && bash dev/cd.sh",
"build:only-web": "pnpm -C web build && bash dev/webzip.sh",
"lint": "pnpm -C web lint",
"fmt": "pnpm -C web fmt",
"fmt:check": "pnpm -C web fmt:check",
"type-check": "pnpm -C web type-check",
"shellcheck": "find src -name '*.sh' -print0 | xargs -0 shellcheck",
"shfmt": "find src -name '*.sh' -print0 | xargs -0 shfmt -i 4 -w -d",
"go:test": "cd golang && go vet ./... && go test ./...",
"go:build": "bash dev/build-wght.sh",
"go:build:local": "cd golang && go build -o /tmp/fontmm-wght ./cmd/fontmm-wght"
}
}
+9
View File
@@ -0,0 +1,9 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.: {}
Binary file not shown.
@@ -0,0 +1,33 @@
#!/sbin/sh
#################
# Initialization
#################
umask 022
# echo before loading util_functions
ui_print() { echo "$1"; }
require_new_magisk() {
ui_print "*******************************"
ui_print " Please install Magisk v20.4+! "
ui_print "*******************************"
exit 1
}
#########################
# Load util_functions.sh
#########################
OUTFD=$2
ZIPFILE=$3
mount /data 2>/dev/null
[ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk
. /data/adb/magisk/util_functions.sh
[ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk
install_module
exit 0
@@ -0,0 +1 @@
#MAGISK
+87
View File
@@ -0,0 +1,87 @@
#!/system/bin/sh
# shellcheck shell=ash
# FontMM apply.sh — 应用字体: 把 FONTS/ 里的字体安装到 system/fonts
# 用法: apply.sh [模块目录] 默认 /data/adb/modules/FontMM
# 回退逻辑: hant/en 缺失时回退到 hans; mono/emoji 缺失时恢复系统原字体
MODDIR="${1:-/data/adb/modules/FontMM}"
FONTS_DIR="$MODDIR/FONTS"
SYS_FONT_DIR="$MODDIR/system/fonts"
# 注意: SysFont-Regular.ttf 是 fonts.xml 中 sans-serif 家族第一位的默认字体,
# 作为西文槽位处理 (中文字体自带西文字形, 若同时占用该槽位会覆盖西文字体, issue #6)
hans_fonts='SysSans-Hans-Regular.ttf
SysFont-Static-Regular.ttf
SysFont-Myanmar.ttf
SysFont-Hans-Regular.ttf'
hant_fonts='SysSans-Hant-Regular.ttf
SysFont-Hant-Regular.ttf'
en_fonts='SysSans-En-Regular.ttf
SysFont-Regular.ttf'
[ -f "$FONTS_DIR/hans.ttf" ] || {
echo "[✗] FONTS/hans.ttf 不存在, 请先在 WebUI 选择字体"
exit 1
}
mkdir -p "$SYS_FONT_DIR"
install_from() {
local src="$1" list="$2" line=""
while IFS= read -r line; do
cp -f "$src" "$SYS_FONT_DIR/$line" || {
echo "[✗] 复制 $line 失败"
exit 1
}
echo "[*] 安装: $line"
done <<EOF
$list
EOF
}
echo "[*] 安装简体字体..."
install_from "$FONTS_DIR/hans.ttf" "$hans_fonts"
echo "[*] 处理繁体字体..."
if [ -f "$FONTS_DIR/hant.ttf" ]; then
install_from "$FONTS_DIR/hant.ttf" "$hant_fonts"
else
echo "[-] 未设置繁体, 回退使用简体"
install_from "$FONTS_DIR/hans.ttf" "$hant_fonts"
fi
echo "[*] 处理英文&数字..."
if [ -f "$FONTS_DIR/en.ttf" ]; then
install_from "$FONTS_DIR/en.ttf" "$en_fonts"
else
echo "[-] 未设置英文, 回退使用简体"
# 未选西文时仍用简体覆盖英文槽位; 西文字体在 fonts.xml 中排最前,
# 简体仅在缺字形时兜底 (issue #6)
install_from "$FONTS_DIR/hans.ttf" "$en_fonts"
fi
echo "[*] 处理等宽字体..."
if [ -f "$FONTS_DIR/mono.ttf" ]; then
# 直接替换系统等宽字体 DroidSansMono.ttf (overlay 生效)
install_from "$FONTS_DIR/mono.ttf" 'DroidSansMono.ttf'
else
echo "[-] 未设置等宽字体, 恢复系统等宽字体"
rm -f "$SYS_FONT_DIR/DroidSansMono.ttf"
fi
echo "[*] 处理 Emoji 字体..."
if [ -f "$FONTS_DIR/emoji.ttf" ]; then
# 首次设置前备份模块内嵌的补充字库 NotoColorEmoji.ttf, 供清除时恢复
if [ -f "$SYS_FONT_DIR/NotoColorEmoji.ttf" ] && [ ! -f "$MODDIR/backup/NotoColorEmoji.ttf" ]; then
mkdir -p "$MODDIR/backup"
cp -f "$SYS_FONT_DIR/NotoColorEmoji.ttf" "$MODDIR/backup/NotoColorEmoji.ttf"
fi
# 直接替换系统 emoji 字体 NotoColorEmoji.ttf (overlay 生效)
install_from "$FONTS_DIR/emoji.ttf" 'NotoColorEmoji.ttf'
else
echo "[-] 未设置 Emoji 字体, 恢复默认"
if [ -f "$MODDIR/backup/NotoColorEmoji.ttf" ]; then
cp -f "$MODDIR/backup/NotoColorEmoji.ttf" "$SYS_FONT_DIR/NotoColorEmoji.ttf"
fi
fi
echo "[*] 全部完成, 重启后生效"
+287
View File
@@ -0,0 +1,287 @@
#!/system/bin/sh
# shellcheck shell=ash
# shellcheck disable=SC2034
# FontMM ColorOS 16 — 刷入脚本
# 字体安装统一交给 apply.sh (与 WebUI 共用同一套逻辑)
REPLACE=""
REMOVE=""
# ---------- 路径 ----------
if [ -z "${MODPATH+x}" ]; then
case "$0" in
*/*) MODPATH="${0%/*}" ;;
*) MODPATH="." ;;
esac
fi
MOD_WORK_PATH="$MODPATH/FONTS"
UPDATE_MODE=0
# ---------- 日志 ----------
log() {
local msg="$1"
echo "[-] $msg"
}
log_err() {
local msg="$1"
local code="${2:-1}"
if command -v abort >/dev/null 2>&1; then
abort "$msg"
fi
echo "[✗] $msg"
exit "$code"
}
log_succ() {
local msg="$1"
echo "[*] $msg"
}
log_warn() {
local msg="$1"
echo "[!] $msg"
}
# ---------- 更新模式 ----------
# 检测旧版 FontMM 是否已安装
DETECT_UPDATE_MODE() {
if [ -d /data/adb/modules/FontMM ]; then
UPDATE_MODE=1
log "检测到已安装的 FontMM, 进入更新模式"
else
log "全新安装"
fi
}
# 更新模式: 以旧包为主继承字体
IMPORT_OLD_FONTS() {
[ "$UPDATE_MODE" -eq 1 ] || return 0
local old_fonts="/data/adb/modules/FontMM/FONTS"
if [ ! -d "$old_fonts" ]; then
log "注意: 旧模块中没有 FONTS 目录, 将使用新包字体"
return 0
fi
mkdir -p "$MOD_WORK_PATH"
local f=""
for f in hans.ttf hant.ttf en.ttf mono.ttf emoji.ttf; do
if [ -f "$old_fonts/$f" ]; then
if cp -f "$old_fonts/$f" "$MOD_WORK_PATH/$f"; then
log_succ "已从旧模块继承字体: $f"
else
log_err "继承字体 $f 失败"
fi
else
log "旧包没有 $f, 使用新包字体"
fi
done
}
# ---------- 系统检查 ----------
# 不阻止安装: 非 ColorOS 16 时仅提示兼容性风险
CHECK_COLOROS() {
local oplus_api=""
oplus_api="$(getprop ro.build.version.oplus.api 2>/dev/null || true)"
if [ -z "$oplus_api" ]; then
log_warn "当前系统不是 ColorOS, 可能无法正常替换字体, 存在兼容性风险"
CONFIRM_RISK "当前系统不是 ColorOS" "字体替换可能无法生效, 且可能导致字体渲染异常"
return 0
fi
local oplus_display=""
oplus_display="$(getprop ro.build.version.oplusrom.display 2>/dev/null || true)"
local major="${oplus_display%%.*}"
if [ "${major:-0}" -lt 16 ] 2>/dev/null; then
log_warn "ColorOS 版本过低 (${oplus_display:-未知}), 建议 16.0 及以上, 低版本可能存在兼容性风险"
CONFIRM_RISK "ColorOS 版本过低 (${oplus_display:-未知})" "建议 16.0 及以上, 低版本可能存在兼容性风险"
return 0
fi
log_succ "ColorOS ${oplus_display}"
}
# ---------- 检查元模块 ----------
CHECK_META_MODULE() {
if [ ! -f /data/adb/ksud ]; then
log "非 KernelSU 环境, 跳过元模块检查"
return 0
fi
local ksud_version=""
ksud_version="$(/data/adb/ksud --version 2>/dev/null | tr -d '\r' || true)"
local ver_num
ver_num="$(printf '%s' "$ksud_version" |
grep -o '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*' |
head -n 1 || true)"
log_succ "KernelSU v${ver_num}"
local major="${ver_num%%.*}"
if [ "${major:-0}" -lt 3 ] 2>/dev/null; then
log "KernelSU 版本 ${ver_num:-未知} < 3.0.0, 无需元模块"
return 0
fi
if [ ! -f /data/adb/metamodule/module.prop ]; then
log "警告: KernelSU >= 3.0.0 需要元模块, 请先安装"
return 1
fi
local meta_name=""
meta_name="$(sed -n 's/^name=//p' /data/adb/metamodule/module.prop | head -n 1 || true)"
if [ -n "$meta_name" ]; then
log_succ "元模块已安装: $meta_name"
else
log "元模块已安装 (但读不到 name 字段)"
fi
return 0
}
# ---------- 音量键确认 ----------
# 音量上键确认继续, 音量下键中止安装
btn() {
while :; do
local c
c="$(getevent -qlc 1 2>/dev/null | awk '{ print $3 }')"
case "$c" in
KEY_VOLUMEUP)
echo "0"
return
;;
KEY_VOLUMEDOWN)
echo "1"
return
;;
esac
done
}
# 通用风险确认 (兼容性等场景)
CONFIRM_RISK() {
local reason="$1"
local detail="$2"
echo
log "警告: $reason"
[ -n "$detail" ] && log "$detail"
log "请按音量上键确认继续安装, 按音量下键取消安装。"
if [ "$(btn)" = "1" ]; then
log_err "用户取消安装"
fi
}
CONFIRM_FONTLOADER_RISK() {
local reason="$1"
echo
log "警告: $reason"
log "未安装或版本过低的 FontLoader 可能导致开机卡死、字体渲染错误或系统异常。"
log "请按音量上键确认继续安装, 按音量下键取消安装。"
if [ "$(btn)" = "1" ]; then
log_err "用户取消安装"
fi
}
# ---------- 判断 FontLoader ----------
CHECK_FONTLOADER() {
local fontloader_moddir="/data/adb/modules/fontloader"
local fontloader_github="https://github.com/KernelSU-Modules-Repo/fontloader/releases"
if [ ! -d "$fontloader_moddir" ]; then
log "注意: 你还没安装 FontLoader"
log "前往 $fontloader_github 安装 FontLoader"
CONFIRM_FONTLOADER_RISK "当前设备未安装 FontLoader。"
return 0
fi
local prop_file="$fontloader_moddir/module.prop"
local version_code=""
if [ -f "$prop_file" ]; then
version_code="$(sed -n 's/^versionCode=//p' "$prop_file")"
fi
version_code="$(printf '%s' "$version_code" | tr -cd '0-9')"
if [ -z "$version_code" ]; then
log "注意: 无法读取 FontLoader 版本号, 建议更新到最新版"
log "前往 $fontloader_github 更新 FontLoader"
CONFIRM_FONTLOADER_RISK "无法确认 FontLoader 版本。"
return 0
fi
if [ "$version_code" -lt 33 ] 2>/dev/null; then
log "注意: 你的 FontLoader 版本过低, 建议更新到 v1.2.3+"
log "前往 $fontloader_github 更新 FontLoader"
CONFIRM_FONTLOADER_RISK "当前 FontLoader 版本低于 v1.2.3。"
else
log_succ "FontLoader 版本正常"
fi
}
# ---------- 字体配置 XML: 扫描设备 + 同步派生配置 ----------
# 模块只内置 fonts.xml 一份主配置; 各派生配置 (fonts_base/ule/font_fallback) 按设备实际文件补齐,
# 设备缺失时回退内置 fonts.xml, 提升跨 ColorOS 版本的兼容性 (issue #7)
# 随后用模块内置 fontmm-wght -sync 把主配置同步到全部派生配置
SYNC_FONT_XMLS() {
local xml_src="$MODPATH/system/etc/fonts.xml"
# 派生配置在设备上的真实路径 (模块内 overlay 的对应位置)
local device_xmls="system/etc/fonts_base.xml
system/etc/fonts_ule.xml
system/etc/font_fallback.xml
system/system_ext/etc/fonts_base.xml
system/system_ext/etc/fonts_ule.xml"
local rel=""
for rel in $device_xmls; do
mkdir -p "$MODPATH/$(dirname "$rel")"
if [ -f "/system/$rel" ]; then
cp -f "/system/$rel" "$MODPATH/$rel"
log "已从设备复制配置: $rel"
else
cp -f "$xml_src" "$MODPATH/$rel"
log "设备无 $rel, 回退内置 fonts.xml"
fi
done
# 用 Go 程序把主配置同步到派生配置 (避免 shell 复制与主配置不一致)
if [ -x "$MODPATH/tools/fontmm-wght" ]; then
if "$MODPATH/tools/fontmm-wght" -mode 0 -sync -xml-dir "$MODPATH" >/dev/null 2>&1; then
log "已同步派生字体配置"
else
log "同步派生配置失败 (可忽略, 使用内置副本)"
fi
fi
}
# ---------- 主流程 ----------
MAIN() {
CHECK_COLOROS
if ! CHECK_META_MODULE; then
log_err "元模块检查不通过"
fi
CHECK_FONTLOADER
echo && log "开始准备字体..."
DETECT_UPDATE_MODE
IMPORT_OLD_FONTS
# 同步派生字体配置 (设备 XML 扫描 + fontmm-wght -sync)
SYNC_FONT_XMLS
# 备份模块内嵌的补充字库 Emoji 字体, 供用户清除 emoji 槽位时恢复
if [ -f "$MODPATH/system/fonts/NotoColorEmoji.ttf" ] && [ ! -f "$MODPATH/backup/NotoColorEmoji.ttf" ]; then
mkdir -p "$MODPATH/backup"
cp -f "$MODPATH/system/fonts/NotoColorEmoji.ttf" "$MODPATH/backup/NotoColorEmoji.ttf"
fi
echo && log "开始安装字体..."
if sh "$MODPATH/apply.sh" "$MODPATH"; then
echo && log_succ "所有字体安装成功, 重启设备后生效"
else
echo && log_err "字体安装出现问题, 请联系开发者"
fi
}
MAIN
+7
View File
@@ -0,0 +1,7 @@
id=FontMM
name=FontMM
version=26.8.0-beta.5
versionCode=26080005
author=Yule
description=ColorOS 16 字体模块模板
updateJson=https://raw.githubusercontent.com/YuleBest/FontMM/main/update.json
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2018–2022 Cyano Hao
Copyright (c) 2022 Shiroki Satsuki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Losketch
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+94
View File
@@ -0,0 +1,94 @@
Copyright 2025 The Noto Project Authors (https://github.com/notofonts)
Copyright 2025 Mercury13 (https://github.com/Mercury13/unicodia)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+91
View File
@@ -0,0 +1,91 @@
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File renamed without changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+61
View File
@@ -0,0 +1,61 @@
#!/system/bin/sh
# FontMM 工具: 下载国际版小米主题字体并解压提取 (v1.0.0)
# 用法: mi-font-download.sh "<标题>" "<主题ID>" "<URL编码标题>"
# 流程: 详情API取下载地址 -> 下载 .mtz -> 解压提取 fonts/ 目录字体
DOWN_DIR="/storage/emulated/0/Download/xttdown"
DETAILS_API="https://api.zhuti.intl.xiaomi.com/app/v9/uipages/theme/"
DL_BASE="https://f17.market.xiaomi.com/issue/"
TITLE="$1"
ID="$2"
ENCODED="$3"
[ -z "$TITLE" ] || [ -z "$ID" ] || [ -z "$ENCODED" ] && {
echo "[x] 参数不足: <标题> <主题ID> <URL编码标题>"
echo "__DONE__"
exit 1
}
# 文件名安全化
SAFE_TITLE=$(printf "%s" "$TITLE" | tr -c 'A-Za-z0-9._-' '_')
echo "[*] 获取「$TITLE」下载链接..."
DOWN_URL=$(curl -s "${DETAILS_API}${ID}" | sed -n 's/.*"downloadUrl":"\([^"]*\)".*/\1/p' | head -1)
[ -z "$DOWN_URL" ] && {
echo "[x] 获取下载链接失败"
echo "__DONE__"
exit 1
}
DL_URL="${DL_BASE}${DOWN_URL}/${ENCODED}.mtz"
SAVE="${DOWN_DIR}/${SAFE_TITLE}.mtz"
echo "[*] 下载: ${DL_URL}"
mkdir -p "$DOWN_DIR"
if ! curl -sL -o "$SAVE" "$DL_URL" || [ ! -s "$SAVE" ]; then
echo "[x] 下载失败"
echo "__DONE__"
exit 1
fi
echo "[✓] 下载完成: ${SAVE} ($(du -h "$SAVE" | cut -f1))"
EXTRACT_DIR="${DOWN_DIR}/extracted/${SAFE_TITLE}"
echo "[*] 解压 mtz 并提取字体..."
mkdir -p "$EXTRACT_DIR"
unzip -o -j "$SAVE" 'fonts/*' -d "$EXTRACT_DIR" >/dev/null 2>&1
# 收集提取出的字体文件 (ttf/otf)
FONTS=''
for f in "$EXTRACT_DIR"/*.ttf "$EXTRACT_DIR"/*.otf; do
[ -f "$f" ] && FONTS="${FONTS} $(basename "$f")"
done
if [ -n "$FONTS" ]; then
echo "[✓] 提取字体:"
for f in $FONTS; do
echo " ${EXTRACT_DIR}/${f}"
done
else
echo "[-] 未在 mtz 中找到字体文件, 原始包保留在 ${SAVE}"
fi
echo "__DONE__"
+49
View File
@@ -0,0 +1,49 @@
#!/system/bin/sh
# shellcheck shell=ash
# FontMM 一键校验: 校验模块内可执行文件的 SHA256 完整性
# 用法: sh verify-sha256.sh [模块目录] 默认 /data/adb/modules/FontMM
# 依赖: SHA256SUMS (随模块打包), sha256sum (toybox 自带)
MODDIR="${1:-/data/adb/modules/FontMM}"
SUMS="$MODDIR/SHA256SUMS"
[ -f "$SUMS" ] || {
echo "[✗] 未找到 $SUMS, 请确认模块已正确安装"
exit 1
}
command -v sha256sum >/dev/null 2>&1 || {
echo "[✗] 系统缺少 sha256sum 命令"
exit 1
}
cd "$MODDIR" || exit 1
echo "[*] 正在校验 $(wc -l <"$SUMS") 个文件..."
# 逐条校验, 便于指出具体是哪个文件不匹配
FAIL=0
while IFS= read -r line; do
[ -z "$line" ] && continue
expected="${line%% *}"
file="${line#* }"
[ -f "$file" ] || {
echo "[✗] 文件缺失: $file"
FAIL=1
continue
}
actual="$(sha256sum "$file" | awk '{ print $1 }')"
if [ "$actual" = "$expected" ]; then
echo "[✓] $file"
else
echo "[✗] 校验失败: $file"
FAIL=1
fi
done <"$SUMS"
if [ "$FAIL" -eq 0 ]; then
echo "[*] 全部文件校验通过"
else
echo "[✗] 存在校验失败的文件, 建议重新安装模块"
exit 1
fi
+90
View File
@@ -0,0 +1,90 @@
#!/bin/sh
# wght-range.sh - 读取可变字体 wght 轴范围,输出 "min max"
# 用法: sh wght-range.sh <字体.ttf>
font=$1
[ -n "$font" ] || {
echo "usage: sh $0 <font.ttf>" >&2
exit 1
}
[ -f "$font" ] || {
echo "error: file not found: $font" >&2
exit 1
}
# 读 1 字节
byte() {
od -An -tu1 -j "$1" -N1 "$font" 2>/dev/null | tr -d ' '
}
# 读 2 字节大端无符号整数
u16() {
b0=$(byte "$1") || return 1
b1=$(byte "$(($1 + 1))") || return 1
[ -n "$b0" ] && [ -n "$b1" ] || return 1
echo $(((b0 << 8) | b1))
}
# 读 4 字节大端无符号整数
u32() {
b0=$(byte "$1") || return 1
b1=$(byte "$(($1 + 1))") || return 1
b2=$(byte "$(($1 + 2))") || return 1
b3=$(byte "$(($1 + 3))") || return 1
[ -n "$b0" ] && [ -n "$b1" ] && [ -n "$b2" ] && [ -n "$b3" ] || return 1
echo $(((b0 << 24) | (b1 << 16) | (b2 << 8) | b3))
}
# 读 4 字节 ASCII tag
tag4() {
dd if="$font" bs=1 skip="$1" count=4 2>/dev/null
}
num_tables=$(u16 4) || {
echo "error: cannot read font: $font" >&2
exit 1
}
# 在 sfnt 表目录里找 fvar 表
# offset 12 起,每条 16 字节:tag/checksum/offset/length
i=0
fvar_off=
while [ "$i" -lt "$num_tables" ]; do
pos=$((12 + i * 16))
if [ "$(tag4 "$pos")" = "fvar" ]; then
fvar_off=$(u32 "$((pos + 8))")
break
fi
i=$((i + 1))
done
[ -n "$fvar_off" ] || {
echo "error: no fvar table (not a variable font?)" >&2
exit 1
}
axis_off=$((fvar_off + $(u16 "$((fvar_off + 4))")))
axis_count=$(u16 "$((fvar_off + 8))")
axis_size=$(u16 "$((fvar_off + 10))")
# 遍历轴找 wght
# min/max 是 Signed Fixed 16.16,整数部分 = 高 16 位
j=0
while [ "$j" -lt "$axis_count" ]; do
p=$((axis_off + j * axis_size))
if [ "$(tag4 "$p")" = "wght" ]; then
hi=$(u16 "$((p + 4))") # minValue 高 16 位
[ "$hi" -ge 32768 ] && hi=$((hi - 65536))
min=$hi
hi=$(u16 "$((p + 12))") # maxValue 高 16 位
[ "$hi" -ge 32768 ] && hi=$((hi - 65536))
max=$hi
echo "$min $max"
exit 0
fi
j=$((j + 1))
done
echo "error: no wght axis in font" >&2
exit 1
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f54da868866e46a56c39820d34f6f3c4f3d7b0922fe09d3ae938c9bd41e75f41
size 112703062
+6
View File
@@ -0,0 +1,6 @@
{
"versionCode": 26080005,
"version": "v26.8.0-beta.5",
"zipUrl": "https://github.com/YuleBest/FontMM/releases/download/v26.8.0-beta.5/FontMM_v26.8.0-beta.5_template.zip",
"changelog": "https://raw.githubusercontent.com/YuleBest/FontMM/main/changelog.md"
}
+5
View File
@@ -0,0 +1,5 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"singleQuote": true,
"ignorePatterns": []
}
+12
View File
@@ -0,0 +1,12 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["typescript", "unicorn", "oxc"],
"categories": {
"correctness": "error"
},
"rules": {},
"ignorePatterns": ["public/pyodide/**"],
"env": {
"builtin": true
}
}
+399
View File
@@ -0,0 +1,399 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover"
/>
<title>FontMM</title>
</head>
<body>
<!-- Top App Bar (滚动后标题固定在左侧, 右上角重启按钮) -->
<header class="top-app-bar">
<span class="top-app-bar__title" id="top-bar-title"></span>
<div class="top-app-bar__actions">
<md-icon-button id="reboot-btn" aria-label="重启设备">
<md-icon>autorenew</md-icon>
</md-icon-button>
</div>
</header>
<!-- 滑动视图轨道 (三页横排, 切换/手势滑动) -->
<div class="view-track" id="view-track">
<!-- 主页视图 -->
<main id="home-view" class="view view-home active">
<div class="home-title">FontMM</div>
<!-- 模块状态 -->
<md-elevated-card class="home-card home-status-card">
<div class="home-status-icon">
<md-icon>check</md-icon>
</div>
<div class="home-status-text">
<div class="home-status-title" id="home-status">已挂载字体</div>
<div class="home-status-sub">版本 <span id="home-version">-</span></div>
</div>
</md-elevated-card>
<!-- 请我喝咖啡 -->
<md-elevated-card class="home-card home-entry-card" id="donate-card">
<div class="home-entry-row" id="donate-entry">
<div class="home-entry-icon">
<md-icon>coffee</md-icon>
</div>
<div class="home-entry-text">
<div class="home-entry-title">请我喝咖啡</div>
<div class="home-entry-sub">FontMM 将保持免费开源</div>
</div>
<md-icon class="home-entry-arrow" id="donate-arrow">expand_more</md-icon>
</div>
<div class="home-entry-expand" id="donate-expand" hidden>
<div class="home-donate-note">感谢您的自愿捐献</div>
<div class="home-donate-row">
<button class="home-donate-item" id="donate-alipay">
<span class="home-donate-logo">支付宝</span>
</button>
<button class="home-donate-item" id="donate-ifdian">
<span class="home-donate-logo">爱发电</span>
</button>
</div>
</div>
</md-elevated-card>
<!-- 开发者 -->
<md-elevated-card class="home-card home-entry-card">
<div class="home-entry-row" id="dev-entry">
<div class="home-entry-icon">
<md-icon>code</md-icon>
</div>
<div class="home-entry-text">
<div class="home-entry-title">开发者</div>
<div class="home-entry-sub">Yule</div>
</div>
<md-icon class="home-entry-arrow">chevron_right</md-icon>
</div>
</md-elevated-card>
<!-- 设备信息 -->
<md-elevated-card class="home-card home-info-card">
<div class="home-info-title">设备信息</div>
<div class="home-info-row">
<div class="home-info-label">系统版本</div>
<div class="home-info-value" id="home-android-version">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">设备型号</div>
<div class="home-info-value" id="home-device-model">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">系统架构</div>
<div class="home-info-value" id="home-abi">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">已安装字体</div>
<div class="home-info-value" id="home-font-count">-</div>
</div>
<div class="home-info-row">
<div class="home-info-label">元模块</div>
<div class="home-info-value" id="home-metamodule">-</div>
</div>
</md-elevated-card>
</main>
<!-- 配置视图 -->
<main id="config-view" class="view view-config">
<div class="home-title">字体配置</div>
<div id="slots"></div>
<!-- 高级配置 (可折叠/展开) -->
<md-filled-card class="wght-advanced">
<div class="wght-advanced-header" id="wght-advanced-header">
<div class="wght-advanced-title">高级配置</div>
<md-icon class="wght-advanced-arrow">expand_more</md-icon>
</div>
<div class="wght-advanced-body">
<div class="wght-advanced-content">
<div class="wght-mode-row">
<div class="wght-mode-info">
<div class="wght-mode-title">字重覆写模式</div>
<div class="wght-mode-sub" id="wght-mode-sub">
可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置
</div>
</div>
<md-outlined-select id="wght-mode-select" label="覆写模式">
<md-select-option value="0" selected>不处理</md-select-option>
<md-select-option value="1">裁切粗细等级</md-select-option>
<md-select-option value="2">平均分配字重</md-select-option>
<md-select-option value="3">自定义映射</md-select-option>
</md-outlined-select>
</div>
<!-- 字重映射 (各模式实时预览, 修改即切为自定义) -->
<div class="wght-map" id="wght-map">
<div class="wght-map-inner">
<div class="wght-map-title">字重映射</div>
<div class="wght-map-sub">
各模式的实时映射结果 (字重等级 → wght 轴值),
修改任意值将自动切换为「自定义映射」
</div>
<div id="wght-map-rows"></div>
<div class="wght-map-footer">
<md-text-button id="wght-map-add" class="wght-map-add">
<md-icon slot="icon">add</md-icon>
新增映射
</md-text-button>
<div class="wght-map-toolbar">
<md-icon-button id="wght-map-undo" aria-label="撤销">
<md-icon>undo</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-export" aria-label="导出映射">
<md-icon>file_upload</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-import" aria-label="导入映射">
<md-icon>file_download</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-reset" aria-label="重置映射">
<md-icon>restart_alt</md-icon>
</md-icon-button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 新增字重映射对话框 -->
<md-dialog id="wght-map-add-dialog">
<div slot="headline">新增字重映射</div>
<div slot="content">
<input
type="number"
id="wght-map-add-weight"
class="wght-map-input wght-map-add-input"
min="1"
max="1000"
placeholder="字重等级 (1-1000)"
/>
</div>
<div slot="actions">
<md-text-button id="wght-map-add-cancel">取消</md-text-button>
<md-text-button id="wght-map-add-confirm">添加</md-text-button>
</div>
</md-dialog>
<!-- 映射导入/导出对话框 (base64 JSON 文本) -->
<md-dialog id="wght-map-transfer-dialog">
<div slot="headline" id="wght-map-transfer-title">导出映射</div>
<div slot="content">
<div class="wght-map-transfer-note" id="wght-map-transfer-note"></div>
<textarea
id="wght-map-transfer-input"
class="wght-map-transfer-input"
rows="4"
spellcheck="false"
></textarea>
</div>
<div slot="actions">
<md-text-button id="wght-map-transfer-cancel">取消</md-text-button>
<md-text-button id="wght-map-transfer-confirm">关闭</md-text-button>
</div>
</md-dialog>
</md-filled-card>
</main>
<!-- 字体测试视图 -->
<div id="test-view" class="view view-test">
<div class="home-title">字体测试</div>
<md-elevated-card class="test-status-card" id="test-status">
<div class="test-status-icon">
<md-icon>info</md-icon>
</div>
<div class="test-status-text" id="test-status-text">正在加载字体...</div>
</md-elevated-card>
<div id="test-content" class="test-content" hidden>
<md-elevated-card class="test-card test-card-editable" data-edit-target="test-hans">
<div class="test-section-title">
中文简体 <span class="test-tag" id="hans-tag"></span>
</div>
<div class="test-sample test-sample-hans" id="test-hans">
天地玄黄,宇宙洪荒。日月盈昃,辰宿列张。寒来暑往,秋收冬藏。ABCDE 12345
</div>
</md-elevated-card>
<md-elevated-card class="test-card test-card-editable" data-edit-target="test-hant">
<div class="test-section-title">
中文繁体 <span class="test-tag" id="hant-tag"></span>
</div>
<div class="test-sample" id="test-hant">
天地玄黃,宇宙洪荒。日月盈昃,辰宿列張。寒來暑往,秋收冬藏。ABCDE 12345
</div>
</md-elevated-card>
<md-elevated-card class="test-card test-card-editable" data-edit-target="test-en">
<div class="test-section-title">
英文 & 数字 <span class="test-tag" id="en-tag"></span>
</div>
<div class="test-sample" id="test-en">
The quick brown fox jumps over the lazy dog. 0123456789
</div>
</md-elevated-card>
<md-elevated-card class="test-card">
<div class="test-section-title">字重<span class="test-tag" id="weight-tag"></span></div>
<div class="test-var-note">
若各字重显示相同,说明字体为静态单字重或未包含对应字重。
</div>
<div class="test-w-row" style="font-weight: 100">
<span class="test-w-text">100 - 淡体 Thin</span>
</div>
<div class="test-w-row" style="font-weight: 200">
<span class="test-w-text">200 - 特细 ExtraLight</span>
</div>
<div class="test-w-row" style="font-weight: 300">
<span class="test-w-text">300 - 细体 Light</span>
</div>
<div class="test-w-row" style="font-weight: 400">
<span class="test-w-text">400 - 标准 Regular</span>
</div>
<div class="test-w-row" style="font-weight: 500">
<span class="test-w-text">500 - 适中 Medium</span>
</div>
<div class="test-w-row" style="font-weight: 600">
<span class="test-w-text">600 - 次粗 SemiBold</span>
</div>
<div class="test-w-row" style="font-weight: 700">
<span class="test-w-text">700 - 粗体 Bold</span>
</div>
<div class="test-w-row" style="font-weight: 800">
<span class="test-w-text">800 - 特粗 ExtraBold</span>
</div>
<div class="test-w-row" style="font-weight: 900">
<span class="test-w-text">900 - 浓体 Black</span>
</div>
</md-elevated-card>
<md-elevated-card class="test-card">
<div class="test-section-title">
可变字体<span class="test-tag" id="var-tag"></span>
</div>
<div class="test-var-note">
拖动滑条调整字重,停止滑动后应用;仅对可变字体 (VF) 生效,静态字体下无变化。
</div>
<div class="test-wght-row">
<span class="test-wght-label">字重</span>
<md-slider
id="wght-slider"
min="100"
max="900"
step="1"
value="400"
aria-label="字重滑条"
></md-slider>
<span class="test-wght-value" id="wght-value">400</span>
</div>
<div class="test-wght-row">
<span class="test-wght-label">字号</span>
<md-slider
id="size-slider"
min="12"
max="40"
step="1"
value="16"
aria-label="字号滑条"
></md-slider>
<span class="test-wght-value" id="size-value">16</span>
</div>
<div class="test-var-preview" id="test-var-preview">400 - 标准 Regular</div>
</md-elevated-card>
</div>
</div>
<!-- 工具视图 -->
<div id="tools-view" class="view view-tools">
<!-- 工具列表 (ToolHost 渲染卡片) -->
<div id="tools-list">
<div class="home-title">工具</div>
<div id="tools-grid"></div>
</div>
<!-- 工具页面挂载点 (打开工具时由 ToolHost 渲染) -->
<div id="tools-pages"></div>
</div>
</div>
<!-- 悬浮应用按钮 (仅配置页, 向下滚动时隐藏) -->
<button id="apply-btn" class="fab" disabled aria-label="应用字体">
<md-icon>check_circle</md-icon>
<span>应用</span>
</button>
<!-- 测试文本编辑对话框 -->
<md-dialog id="edit-text-dialog">
<div slot="headline">编辑测试文本</div>
<div slot="content">
<md-outlined-text-field
id="edit-text-input"
type="textarea"
rows="3"
label="测试文本"
style="width: 100%"
></md-outlined-text-field>
</div>
<div slot="actions">
<md-text-button id="edit-text-cancel">取消</md-text-button>
<md-text-button id="edit-text-save">保存</md-text-button>
</div>
</md-dialog>
<!-- 重启确认对话框 -->
<md-dialog id="reboot-dialog">
<div slot="headline">重启设备?</div>
<div slot="content">重启后字体才会生效,确定要立即重启设备吗?</div>
<div slot="actions">
<md-text-button id="reboot-cancel">取消</md-text-button>
<md-text-button id="reboot-confirm">重启</md-text-button>
</div>
</md-dialog>
<!-- 日志弹窗 -->
<md-dialog id="log-dialog">
<div slot="headline">应用日志</div>
<div slot="content">
<pre
id="log-content"
style="white-space: pre-wrap; font-family: monospace; font-size: 0.8rem"
></pre>
</div>
<div slot="actions">
<md-text-button id="log-close">关闭</md-text-button>
</div>
</md-dialog>
<!-- 底部导航栏 -->
<nav class="bottom-nav">
<md-navigation-bar id="nav-bar" active-index="0">
<md-navigation-tab label="主页">
<md-icon slot="active-icon">home</md-icon>
<md-icon slot="inactive-icon">home</md-icon>
</md-navigation-tab>
<md-navigation-tab label="配置">
<md-icon slot="active-icon">tune</md-icon>
<md-icon slot="inactive-icon">tune</md-icon>
</md-navigation-tab>
<md-navigation-tab label="字体测试">
<md-icon slot="active-icon">text_fields</md-icon>
<md-icon slot="inactive-icon">text_fields</md-icon>
</md-navigation-tab>
<md-navigation-tab label="工具">
<md-icon slot="active-icon">build</md-icon>
<md-icon slot="inactive-icon">build</md-icon>
</md-navigation-tab>
</md-navigation-bar>
</nav>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+30
View File
@@ -0,0 +1,30 @@
{
"name": "fontmm-webui",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "oxlint",
"fmt": "oxfmt",
"fmt:check": "oxfmt --check",
"type-check": "tsc --noEmit"
},
"dependencies": {
"@material/web": "^2.4.1",
"fast-xml-parser": "^5.10.1",
"kernelsu": "^3.0.2",
"material-symbols": "^0.28.0",
"opentype.js": "^2.0.0",
"pyodide": "^314.0.3"
},
"devDependencies": {
"oxfmt": "^0.61.0",
"oxlint": "^1.76.0",
"sass": "^1.86.0",
"typescript": "^5.8.0",
"vite": "^6.0.11"
}
}
+1494
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
allowBuilds:
'@parcel/watcher': true
esbuild: true
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.
+836
View File
@@ -0,0 +1,836 @@
'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
@@ -0,0 +1,801 @@
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.
+84
View File
@@ -0,0 +1,84 @@
import { exec, shellQuote, toast } from './ksu';
import { copyFont, pickWghtRange, renderSlots, setApplying, slots } from './slots';
import { applyWghtOverride, getSelectedWghtMode, writeWghtMode } from './wght';
import { invalidateTestFonts } from './testFonts';
import { applyBtn } from './dom';
import { FONTS_DIR } from './constants';
const logDialog = document.getElementById('log-dialog') as any;
const logContent = document.getElementById('log-content')!;
document.getElementById('log-close')?.addEventListener('click', () => {
logDialog.open = false;
});
async function apply() {
if (!slots.hans.path) return;
setApplying(true);
renderSlots();
try {
// 字重范围覆写: 用 UI 当前模式 (持久化到 FONTS/wght-mode.txt), 仅当存在可变字体且模式非 0 时处理
const wghtMode = getSelectedWghtMode();
await writeWghtMode(wghtMode);
const wghtPick = pickWghtRange();
if (wghtMode !== 0 && wghtPick) {
// Go 程序自行读取 wght-map.txt (mode 3)
await applyWghtOverride(wghtMode, wghtPick.min, wghtPick.max);
}
// 启动加载的字体 path 即 FONT/ 内的文件, 无需再复制
if (slots.hans.path !== `${FONTS_DIR}/hans.ttf`) {
await copyFont(slots.hans.path, `${FONTS_DIR}/hans.ttf`);
}
if (slots.hant.path) {
if (slots.hant.path !== `${FONTS_DIR}/hant.ttf`) {
await copyFont(slots.hant.path, `${FONTS_DIR}/hant.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/hant.ttf`)}`);
}
if (slots.en.path) {
if (slots.en.path !== `${FONTS_DIR}/en.ttf`) {
await copyFont(slots.en.path, `${FONTS_DIR}/en.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/en.ttf`)}`);
}
if (slots.mono.path) {
if (slots.mono.path !== `${FONTS_DIR}/mono.ttf`) {
await copyFont(slots.mono.path, `${FONTS_DIR}/mono.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/mono.ttf`)}`);
}
if (slots.emoji.path) {
if (slots.emoji.path !== `${FONTS_DIR}/emoji.ttf`) {
await copyFont(slots.emoji.path, `${FONTS_DIR}/emoji.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/emoji.ttf`)}`);
}
const { errno, stdout, stderr } = await exec('sh /data/adb/modules/FontMM/apply.sh');
if (errno !== 0) throw new Error(stderr || 'apply.sh 执行失败');
if (logContent && logDialog) {
logContent.textContent = stdout;
logDialog.open = true;
}
toast('字体已应用,重启后生效');
// 字体已变化: 下次进入测试页时重新加载
invalidateTestFonts();
} catch (e) {
toast(`应用失败: ${String(e)}`);
} finally {
setApplying(false);
renderSlots();
}
}
applyBtn?.addEventListener('click', apply);
+13
View File
@@ -0,0 +1,13 @@
// 全局路径与外部链接常量
export const FONTS_DIR = '/data/adb/modules/FontMM/FONTS';
export const WEBROOT_DIR = '/data/adb/modules/FontMM/webroot';
export const TEST_FONT_DIR = `${WEBROOT_DIR}/fonts-test`;
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制)
export const WGHT_BIN = '/data/adb/modules/FontMM/tools/fontmm-wght';
// 捐献 (支付宝/爱发电) 与开发者主页 (浏览器) 链接
export const DONATE_ALIPAY_URI =
'alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/2m615805eflrafv8ipc2p15';
export const ALIPAY_PKG = 'com.eg.android.AlipayGphone';
export const DONATE_IFDIAN_URL = 'https://www.ifdian.net/a/xiaoyule';
export const DEV_PROFILE_URL = 'https://github.com/YuleBest';
+3
View File
@@ -0,0 +1,3 @@
// 跨模块共享的 DOM 元素引用
export const applyBtn = document.getElementById('apply-btn') as HTMLButtonElement;
export const rebootBtn = document.getElementById('reboot-btn');
+36
View File
@@ -0,0 +1,36 @@
import { exec, shellQuote } from './ksu';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
// 复制 FONT/ 到 webroot/fonts-test, 供页面加载与名称解析
// (WebView 无法直接访问模块外部目录, 符号链接在真机也不可靠, 直接复制)
export async function ensureFontsCopy(): Promise<string[]> {
const copyCmd = [
`rm -rf '${TEST_FONT_DIR}'`,
`mkdir -p '${TEST_FONT_DIR}'`,
`cp -f '${FONTS_DIR}'/*.ttf '${TEST_FONT_DIR}'/ 2>/dev/null`,
].join('\n');
try {
const { errno } = await exec(copyCmd);
if (errno !== 0) return [];
} catch {
return [];
}
return listFontsDir();
}
// 列出 fonts-test/ 下的字体文件 (每行一个完整路径)
export async function listFontsDir(): Promise<string[]> {
try {
const { errno, stdout } = await exec(
`find ${shellQuote(TEST_FONT_DIR)} -maxdepth 1 -mindepth 1 -type f`,
);
if (errno !== 0) return [];
return stdout
.split('\n')
.map((s) => s.trim())
.filter(Boolean)
.map((p) => p.slice(p.lastIndexOf('/') + 1));
} catch {
return [];
}
}
+74
View File
@@ -0,0 +1,74 @@
import * as opentype from 'opentype.js';
export interface FontInfo {
name?: string;
sizeText?: string;
isVariable?: boolean;
wghtRange?: string;
}
// 从字体名称表提取 family name, 优先中文字体名
function extractFamilyName(font: any): string | null {
const pick = (table: any): string | null => {
if (!table) return null;
const family = table.fontFamily ?? table.fullName;
if (!family || typeof family !== 'object') return null;
for (const lang of ['zh-CN', 'zh-Hans', 'zh', 'zh-TW', 'zh-Hant', 'en', 'en-US']) {
if (typeof family[lang] === 'string' && family[lang]) return family[lang];
}
const first = Object.values(family).find((v) => typeof v === 'string' && v);
return first ? String(first) : null;
};
return pick(font.names?.windows) ?? pick(font.names?.macintosh);
}
// 可变字体时返回 wght 轴范围
function extractWghtRange(font: any): string | undefined {
const fvar = font?.tables?.fvar;
if (!fvar?.axes) return undefined;
const wght = fvar.axes.find((a: any) => a.tag === 'wght');
if (!wght) return undefined;
return `${Math.round(wght.minValue)}-${Math.round(wght.maxValue)}`;
}
// 读取 fonts-test/ 下字体文件的名称与大小 (WebView 仅能访问 webroot 内文件)
export async function readFontInfo(file: string): Promise<FontInfo> {
// dev 假数据: 模拟各槽位字体的名称/大小/可变标识
if (import.meta.env.DEV) {
const MOCK_FONT_INFO: Record<
string,
{ name: string; size: string; variable: boolean; wght?: string }
> = {
'hans.ttf': { name: 'HarmonyOS Sans SC', size: '13.5 MB', variable: true, wght: '100-900' },
'hant.ttf': { name: '源樣明體', size: '21.2 MB', variable: false },
'en.ttf': { name: 'Inter Variable', size: '0.8 MB', variable: true, wght: '200-700' },
'mono.ttf': { name: 'JetBrains Mono', size: '1.2 MB', variable: false },
'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,
}
: {};
}
try {
const res = await fetch(`fonts-test/${file}`);
if (!res.ok) return {};
const buf = await res.arrayBuffer();
const font = opentype.parse(buf);
const name = extractFamilyName(font);
const sizeText = `${(buf.byteLength / 1024 / 1024).toFixed(1)} MB`;
return {
name: name ?? undefined,
sizeText,
isVariable: Boolean(font.tables?.fvar),
wghtRange: extractWghtRange(font),
};
} catch {
return {};
}
}
+185
View File
@@ -0,0 +1,185 @@
import '@material/web/dialog/dialog.js';
import '@material/web/list/list.js';
import '@material/web/list/list-item.js';
import '@material/web/icon/icon.js';
import '@material/web/iconbutton/icon-button.js';
import '@material/web/button/text-button.js';
import { exec, shellQuote } from './ksu';
export interface FileItem {
name: string;
isDir: boolean;
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;
constructor(onSelect: (path: string, fileName: string) => void) {
this.onSelectCallback = onSelect;
this.initDialog();
}
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;
}
const dialogHTML = `
<md-dialog id="picker-dialog" class="font-picker-dialog">
<div slot="headline" class="picker-header">
<div class="picker-title-bar">
<md-icon-button id="picker-back-btn" class="picker-back" aria-label="返回上一级">
<md-icon>arrow_back</md-icon>
</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>
</div>
</div>
<div slot="content" class="picker-content">
<md-list id="picker-list" class="picker-list"></md-list>
</div>
<div slot="actions">
<md-text-button id="picker-cancel-btn">取消</md-text-button>
</div>
</md-dialog>
`;
document.body.insertAdjacentHTML('beforeend', dialogHTML);
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);
}
public hide(): void {
(this.dialogEl as any).open = false;
}
private navigateUp(): void {
if (this.currentPath === '/' || this.currentPath === '') return;
const parts = this.currentPath.split('/').filter(Boolean);
parts.pop();
this.currentPath = parts.length === 0 ? '/' : '/' + parts.join('/');
this.loadDirectory(this.currentPath);
}
private async loadDirectory(path: string): Promise<void> {
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>`;
return;
}
this.renderList(items);
} catch (e) {
this.listEl.innerHTML = `<div class="picker-error">读取目录异常: ${String(e)}</div>`;
}
}
// 用 find 列出目录与文件: -print0 以 NUL 分隔路径, 路径含空格/换行也安全
// (兼容 busybox 与 GNU find, 不解析 ls 的列输出)
private async readDir(path: string): Promise<{ items: FileItem[]; failed: boolean }> {
const [dirRes, fileRes] = await Promise.all([
exec(`find ${shellQuote(path)} -maxdepth 1 -mindepth 1 -type d -print0`),
exec(`find ${shellQuote(path)} -maxdepth 1 -mindepth 1 -type f -print0`),
]);
if (dirRes.errno !== 0 || fileRes.errno !== 0) {
return { items: [], failed: true };
}
const dirs = this.splitNul(dirRes.stdout).map((p) => this.basename(p));
const files = this.splitNul(fileRes.stdout)
.map((p) => this.basename(p))
// 仅显示扩展名为 .ttf 的文件
.filter((name) => name.toLowerCase().endsWith('.ttf'));
const items: FileItem[] = [
...dirs.map((name) => ({ name, isDir: true })),
...files.map((name) => ({ name, isDir: false })),
].sort((a, b) => {
if (a.isDir && !b.isDir) return -1;
if (!a.isDir && b.isDir) return 1;
return a.name.localeCompare(b.name);
});
return { items, failed: false };
}
// 按 NUL 分隔 find -print0 的输出 (路径内的换行/空格不受影响)
private splitNul(output: string): string[] {
return output.split('\0').filter(Boolean);
}
private basename(path: string): string {
return path.slice(path.lastIndexOf('/') + 1) || path;
}
private renderList(items: FileItem[]): void {
if (items.length === 0) {
this.listEl.innerHTML = `
<div class="picker-empty">
<md-icon>find_in_page</md-icon>
<span>此目录下没有 .ttf 字体文件</span>
</div>`;
return;
}
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}">
<md-icon slot="start" class="item-icon">
${item.isDir ? 'folder' : 'font_download'}
</md-icon>
<div slot="headline" class="item-name">${item.name}</div>
${
item.isDir
? `<md-icon slot="end" class="item-arrow">chevron_right</md-icon>`
: `<md-text-button slot="end" class="item-select-btn">选择</md-text-button>`
}
</md-list-item>
`,
)
.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();
}
});
});
}
}
+362
View File
@@ -0,0 +1,362 @@
// 字体编辑 Worker: Pyodide + fontTools 在独立线程运行, 避免大字体编辑阻塞 UI
// 主线程通过 postMessage 通信: init / analyze / edit
// 用 fontTools 解析字体: 名称 / 字形数 / unitsPerEm / 可变 + 全部可读 name 字段
const ANALYZE_PY = `
from fontTools.ttLib import TTFont
from io import BytesIO
def read_all_names(f):
out = {}
for nid in range(0, 26):
try:
v = f['name'].getDebugName(nid)
except Exception:
v = None
if v:
out[str(nid)] = v
return out
def analyze(data):
try:
f = TTFont(BytesIO(data), fontNumber=0)
name = f['name']
family = name.getDebugName(1) or name.getDebugName(16) or '(未命名)'
subfamily = name.getDebugName(2) or ''
glyphs = f['maxp'].numGlyphs
units = f['head'].unitsPerEm
variable = 'fvar' in f
wght_range = None
if variable:
for a in f['fvar'].axes:
if a.axisTag == 'wght':
wght_range = '%d-%d' % (round(a.minValue), round(a.maxValue))
break
return {'ok': True, 'family': family, 'subfamily': subfamily,
'glyphs': glyphs, 'units': units, 'variable': variable,
'wghtRange': wght_range, 'names': read_all_names(f)}
except Exception as e:
return {'ok': False, 'error': str(e)}
`;
// 编辑字体: 字形轮廓缩放 + 偏移, advance 随缩放; 丢弃可变字体表
const EDIT_PY = `
from fontTools.ttLib import TTFont
from fontTools.misc.transform import Transform
from fontTools.ttLib.tables._g_l_y_f import Glyph, GlyphComponent, GlyphCoordinates
from fontTools.ttLib.tables.ttProgram import Program
import numpy
from io import BytesIO
# 缓存: 原始字体对象 + 字形快照 (list 浅拷贝, 毫秒级; 避免 deepcopy 整个字体)
_FONT_CACHE = {}
_GLYPH_ORIG = {}
_HMTX_ORIG = {}
_LINEGAP_ORIG = {}
def _snapshot_glyph(g):
if g is None:
return None
if g.numberOfContours is not None and g.numberOfContours >= 0:
program = getattr(g, 'program', None)
bc = None
if program is not None and program.bytecode:
bc = list(program.bytecode)
return ('simple', g.numberOfContours,
list(g.coordinates) if hasattr(g, 'coordinates') else [],
list(g.flags) if hasattr(g, 'flags') else [],
list(g.endPtsOfContours) if hasattr(g, 'endPtsOfContours') else [],
bc)
comps = []
for c in g.components:
tr_raw = getattr(c, 'transform', None)
tr = None
if tr_raw is not None:
tr = (tr_raw[0][0], tr_raw[0][1], tr_raw[1][0], tr_raw[1][1])
comps.append((c.glyphName, c.x, c.y, tr, c.flags))
return ('composite', comps)
def _restore_glyph(snap):
if snap is None:
return None
g = Glyph()
if snap[0] == 'simple':
g.numberOfContours = snap[1]
if snap[2]:
g.coordinates = GlyphCoordinates(snap[2])
if snap[3]:
g.flags = snap[3]
if snap[4]:
g.endPtsOfContours = snap[4]
if snap[5]:
g.program = Program()
g.program.fromBytecode(bytes(snap[5]))
else:
g.program = Program()
else:
g.numberOfContours = -1
g.components = []
for name2, x, y, tr, flags in snap[1]:
c = GlyphComponent()
c.glyphName = name2
c.x = x
c.y = y
c.flags = flags
if tr is not None:
c.transform = [[tr[0], tr[1]], [tr[2], tr[3]]]
g.components.append(c)
g.program = Program()
return g
def _ensure_snapshot(data_key, data):
if data_key in _FONT_CACHE:
return
# lazy=True: glyf 字形按需解析, 大字体首次预览只解析用到的字形
f = TTFont(BytesIO(data), fontNumber=0, lazy=True)
_FONT_CACHE[data_key] = f
_GLYPH_ORIG[data_key] = {}
_HMTX_ORIG[data_key] = dict(f['hmtx'].metrics)
_LINEGAP_ORIG[data_key] = (
f['hhea'].lineGap if 'hhea' in f else 0,
f['OS/2'].sTypoLineGap if 'OS/2' in f else 0,
)
def _orig_glyph(data_key, name):
# 懒快照单个字形
snap = _GLYPH_ORIG[data_key].get(name, '?')
if snap == '?':
f = _FONT_CACHE[data_key]
g = f['glyf'][name] if name in f['glyf'] else None
snap = _snapshot_glyph(g)
_GLYPH_ORIG[data_key][name] = snap
return snap
# Glyph 无 transform 方法: numpy 批量变换简单字形点, 复合字形合并组件矩阵
def _apply_matrix(g, matrix):
if g is None:
return
nc = g.numberOfContours
if nc is not None and nc >= 0 and hasattr(g, 'coordinates'):
coords = g.coordinates
xx, xy, yx, yy, dx, dy = matrix
arr = numpy.array(coords, dtype=numpy.float64)
arr = arr @ numpy.array([[xx, xy], [yx, yy]], dtype=numpy.float64)
arr = arr + numpy.array([dx, dy], dtype=numpy.float64)
arr = numpy.rint(arr).astype(numpy.int32)
g.coordinates = GlyphCoordinates(arr.tolist())
elif nc == -1:
xx, xy, yx, yy, dx, dy = matrix
for c in g.components:
tr = getattr(c, 'transform', None)
if tr:
c.transform = [[xx * tr[0][0] + xy * tr[1][0], xx * tr[0][1] + xy * tr[1][1]],
[yx * tr[0][0] + yy * tr[1][0], yx * tr[0][1] + yy * tr[1][1]]]
px = c.x * xx + c.y * xy + dx
py = c.x * yx + c.y * yy + dy
c.x, c.y = round(px), round(py)
def _glyph_names_for_text(f, text):
cmap = f.getBestCmap()
names = set()
for ch in text:
cp = ord(ch)
if cp in cmap:
names.add(cmap[cp])
return names
def edit_font(data_key, data, scale, dx, dy, letter_spacing=0, line_spacing=0,
preview_chars=None):
try:
_ensure_snapshot(data_key, data)
f = _FONT_CACHE[data_key]
if 'glyf' not in f:
return {'ok': False, 'error': '仅支持 TrueType (.ttf) 字体'}
glyf = f['glyf']
matrix = Transform(scale, 0, 0, scale, dx, dy)
# 预览模式: 只重置+变换预览文本涉及的字形; 导出时全量
if preview_chars:
names = _glyph_names_for_text(f, preview_chars)
else:
names = set(f.getGlyphOrder())
for name in names:
snap = _orig_glyph(data_key, name)
if snap is not None:
glyf[name] = _restore_glyph(snap)
_apply_matrix(glyf[name], matrix)
# 度量: 从原始快照重算 (advance 全量调整)
hmtx = f['hmtx']
orig_hmtx = _HMTX_ORIG[data_key]
for name, (advance, lsb) in orig_hmtx.items():
if advance:
hmtx.metrics[name] = (max(1, round(advance * scale + letter_spacing)), lsb)
else:
hmtx.metrics[name] = (0, lsb)
if line_spacing:
orig_line_gap, orig_typo_gap = _LINEGAP_ORIG[data_key]
if 'hhea' in f:
f['hhea'].lineGap = max(0, round(orig_line_gap + line_spacing))
if 'OS/2' in f:
f['OS/2'].sTypoLineGap = max(0, round(orig_typo_gap + line_spacing))
# 编辑后可变轴已无意义, 丢弃
for t in ('fvar', 'gvar', 'avar', 'STAT', 'cvar'):
if t in f:
del f[t]
# 注: 预览模式不做 subset (subset 会污染缓存字体对象), 直接输出完整字体
out = BytesIO()
f.save(out)
return {'ok': True, 'data': out.getvalue()}
except Exception as e:
return {'ok': False, 'error': str(e)}
# 预览: 提取预览文本涉及字形的轮廓点 (不生成字体文件, 毫秒级)
# 返回 { glyphs: {unicode码点: {pts: [[x,y,on],...], end: [...], adv: advance}}, upem, lineGap }
def build_preview(data_key, data, text, scale, dx, dy, letter_spacing=0, line_spacing=0):
try:
_ensure_snapshot(data_key, data)
f = _FONT_CACHE[data_key]
if 'glyf' not in f:
return {'ok': False, 'error': '仅支持 TrueType (.ttf) 字体'}
cmap = f.getBestCmap()
glyf = f['glyf']
hmtx = f['hmtx']
matrix = Transform(scale, 0, 0, scale, dx, dy)
orig_glyphs = _GLYPH_ORIG[data_key]
glyphs = {}
for ch in text:
cp = ord(ch)
if cp in glyphs:
continue
name = cmap.get(cp)
if name is None:
continue
snap = _orig_glyph(data_key, name)
if snap is None:
continue
g = _restore_glyph(snap)
_apply_matrix(g, matrix)
# getCoordinates 自动展开复合字形
coords, endPts, flags = g.getCoordinates(glyf)
pts = []
for i, (x, y) in enumerate(coords):
on = 1 if flags[i] & 0x01 else 0
pts.append([round(x), round(y), on])
advance, _ = hmtx[name]
glyphs[str(cp)] = {'pts': pts, 'end': list(endPts), 'adv': max(1, round(advance * scale + letter_spacing))}
line_gap = _LINEGAP_ORIG[data_key][0] if line_spacing else 0
import json
# JSON 序列化传递 (避免 PyProxy 经 postMessage 克隆失败)
return {'ok': True, 'json': json.dumps({
'glyphs': glyphs,
'upem': f['head'].unitsPerEm,
'lineGap': max(0, round(line_gap + line_spacing)),
})}
except Exception as e:
return {'ok': False, 'error': str(e)}
# 修改 name 表字段 (Windows Unicode 平台, 写入或替换)
def update_names(data, names):
try:
f = TTFont(BytesIO(data), fontNumber=0)
for nid_str, value in names.items():
nid = int(nid_str)
if value is None or str(value).strip() == '':
continue
f['name'].setName(str(value), nid, 3, 1, 0x409)
out = BytesIO()
f.save(out)
return {'ok': True, 'data': out.getvalue()}
except Exception as e:
return {'ok': False, 'error': str(e)}
`;
let py: any = null;
self.onmessage = async (e: MessageEvent) => {
const { id, type, payload } = e.data;
try {
if (type === 'init') {
const { loadPyodide } = await import('pyodide');
py = await loadPyodide({ indexURL: payload.indexURL });
await py.loadPackage('fonttools');
await py.loadPackage('numpy');
await py.runPythonAsync(ANALYZE_PY + EDIT_PY);
self.postMessage({ id, ok: true });
} else if (type === 'analyze') {
const bytes = py.toPy(new Uint8Array(payload.data));
const r = py.globals
.get('analyze')(bytes)
.toJs({ dict_converter: Object.fromEntries, depth: 2 });
self.postMessage({
id,
ok: Boolean(r.ok),
family: r.family,
subfamily: r.subfamily,
glyphs: r.glyphs,
units: r.units,
variable: r.variable,
wghtRange: r.wghtRange,
names: r.names,
error: r.error,
});
} else if (type === 'preview') {
const r = py.globals
.get('build_preview')(
payload.dataKey,
py.toPy(new Uint8Array(payload.data)),
payload.text,
payload.scale,
payload.dx,
payload.dy,
payload.letterSpacing ?? 0,
payload.lineSpacing ?? 0,
)
.toJs({ dict_converter: Object.fromEntries });
if (r.ok) {
const parsed = JSON.parse(r.json);
self.postMessage({
id,
ok: true,
glyphs: parsed.glyphs,
upem: parsed.upem,
lineGap: parsed.lineGap,
});
} else {
self.postMessage({ id, ok: false, error: r.error });
}
} else if (type === 'edit') {
const bytes = py.toPy(new Uint8Array(payload.data));
const r = py.globals
.get('edit_font')(
payload.dataKey,
bytes,
payload.scale,
payload.dx,
payload.dy,
payload.letterSpacing ?? 0,
payload.lineSpacing ?? 0,
payload.previewChars ?? null,
)
.toJs({ dict_converter: Object.fromEntries });
if (r.ok) {
const data: Uint8Array = r.data;
self.postMessage({ id, ok: true, data }, { transfer: [data.buffer] });
} else {
self.postMessage({ id, ok: false, error: r.error });
}
} else if (type === 'updateNames') {
const bytes = py.toPy(new Uint8Array(payload.data));
const names = py.toPy(payload.names);
const r = py.globals
.get('update_names')(bytes, names)
.toJs({ dict_converter: Object.fromEntries });
if (r.ok) {
const data: Uint8Array = r.data;
self.postMessage({ id, ok: true, data }, { transfer: [data.buffer] });
} else {
self.postMessage({ id, ok: false, error: r.error });
}
}
} catch (err) {
self.postMessage({ id, ok: false, error: String(err) });
}
};
+11
View File
@@ -0,0 +1,11 @@
// fontsXml.ts — 字重覆写 UI 辅助 (生成逻辑已迁移至 Go 程序 fontmm-wght)
// 仅保留 UI 渲染滑块默认值所需的函数
export const WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900];
/** 平均分配: 计算 weight w 对应的 axis wght 值 (400 固定, 两端线性插值, 向下取整) */
export function averagedAxis(min: number, max: number, w: number): number {
if (w === 400) return 400;
if (w < 400) return Math.floor(min + ((400 - min) * (w - 100)) / 300);
return Math.floor(400 + ((max - 400) * (w - 400)) / 500);
}
+102
View File
@@ -0,0 +1,102 @@
import { amStart, exec, getSystemInfo, moduleInfo } from './ksu';
import { rebootBtn } from './dom';
import { ALIPAY_PKG, DEV_PROFILE_URL, DONATE_ALIPAY_URI, DONATE_IFDIAN_URL } from './constants';
interface ModuleProp {
[key: string]: string;
}
// 解析 module.prop 风格文本 (key=value 每行一个)
function parseProp(text: string): ModuleProp {
const out: ModuleProp = {};
for (const line of text.split('\n')) {
const idx = line.indexOf('=');
if (idx > 0) {
const key = line.slice(0, idx).trim();
if (key) out[key] = line.slice(idx + 1).trim();
}
}
return out;
}
// 渲染主页: 模块状态 + 设备信息
export async function loadHome(): Promise<void> {
// 模块信息 (module.prop)
let prop: ModuleProp = {};
try {
prop = { ...prop, ...parseProp(moduleInfo()) };
} catch {
// dev 或 API 不可用时忽略, 走下方兜底
}
try {
const { errno, stdout } = await exec('cat /data/adb/modules/FontMM/module.prop');
if (errno === 0) prop = { ...prop, ...parseProp(stdout) };
} catch {
// 忽略读取失败
}
// 挂载状态与设备信息
const sys = await getSystemInfo();
const mounted = sys.fontCount > 0;
const set = (id: string, value: string) => {
const el = document.getElementById(id);
if (el) el.textContent = value;
};
set('home-status', mounted ? '已挂载字体' : '未挂载字体');
set('home-version', prop.version || '未知');
set('home-android-version', sys.androidVersion || '未知');
set('home-device-model', sys.deviceModel || '未知');
set('home-abi', sys.abi || '未知');
set('home-font-count', `${sys.fontCount} 个`);
// 元模块: /data/adb/metamodule 是符号链接, cat 可直接读取其 module.prop 的 name
try {
const { errno, stdout } = await exec('cat /data/adb/metamodule/module.prop');
if (errno === 0 && stdout.trim()) {
set('home-metamodule', parseProp(stdout).name || '未知');
} else {
set('home-metamodule', '未安装');
}
} catch {
set('home-metamodule', '未安装');
}
}
// 支付宝捐献: 必须在 WebUI 外打开 (am start), 否则 alipays 协议无法唤起
let donateOpen = false;
const donateExpand = document.getElementById('donate-expand')!;
const donateArrow = document.getElementById('donate-arrow')!;
document.getElementById('donate-entry')?.addEventListener('click', () => {
donateOpen = !donateOpen;
donateExpand.hidden = !donateOpen;
donateArrow.classList.toggle('expanded', donateOpen);
});
document.getElementById('donate-alipay')?.addEventListener('click', () => {
void amStart(DONATE_ALIPAY_URI, ALIPAY_PKG);
});
// 爱发电: 用系统默认浏览器打开 (am start)
document.getElementById('donate-ifdian')?.addEventListener('click', () => {
void amStart(DONATE_IFDIAN_URL);
});
// 开发者主页: 用系统默认浏览器打开 (am start, 避免在 WebView 内打开)
document.getElementById('dev-entry')?.addEventListener('click', () => {
void amStart(DEV_PROFILE_URL);
});
// 重启设备 (二次确认): dev 模式由 mockExec 模拟输出; 真机立即重启
const rebootDialog = document.getElementById('reboot-dialog') as any;
rebootBtn?.addEventListener('click', () => {
if (rebootDialog) rebootDialog.open = true;
});
document.getElementById('reboot-cancel')?.addEventListener('click', () => {
if (rebootDialog) rebootDialog.open = false;
});
document.getElementById('reboot-confirm')?.addEventListener('click', () => {
if (rebootDialog) rebootDialog.open = false;
void exec('sync; reboot');
});
+289
View File
@@ -0,0 +1,289 @@
import { exec as ksuExec, toast as ksuToast, moduleInfo as ksuModuleInfo } from 'kernelsu';
export interface ExecResult {
errno: number;
stdout: string;
stderr: string;
}
/**
* Quote one argument for the POSIX shell used by KernelSU.exec.
* Prefer spawn() when the command can be expressed as argv; use this helper
* whenever exec() must receive a shell command containing external input.
*/
export function shellQuote(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`;
}
// dev 模式假文件系统 (用于文件选择器, 路径结构与 Android 一致)
const FAKE_FS: Record<string, { dirs: string[]; fonts: string[]; files: string[] }> = {
'/': { dirs: ['storage'], fonts: [], files: [] },
'/storage': { dirs: ['emulated'], fonts: [], files: [] },
'/storage/emulated': { dirs: ['0'], fonts: [], files: [] },
'/storage/emulated/0': {
dirs: ['Download', 'Fonts', 'Documents', '字体'],
fonts: [],
files: ['notes.txt'],
},
'/storage/emulated/0/Download': {
dirs: [],
fonts: ['HarmonyOS_Sans.ttf', 'MiSans-Bold.ttf', 'AlibabaPuHuiTi.otf'],
files: ['a.pdf'],
},
'/storage/emulated/0/Fonts': {
dirs: [],
fonts: ['OPPOSans.ttf', 'SourceHanSansCN.ttf', 'Inter-Variable.otf'],
files: [],
},
'/storage/emulated/0/Documents': { dirs: [], fonts: [], files: ['notes.txt'] },
'/storage/emulated/0/字体': { dirs: [], fonts: ['思源黑体.ttf', '霞鹜文楷.ttf'], files: [] },
};
async function mockExec(command: string): Promise<ExecResult> {
const fake = (stdout = ''): ExecResult => ({ errno: 0, stdout, stderr: '' });
const fail = (stderr: string): ExecResult => ({ errno: 1, stdout: '', stderr });
const slow = (stdout = '') =>
new Promise<ExecResult>((r) => setTimeout(() => r(fake(stdout)), 200));
const slowFail = (stderr: string) =>
new Promise<ExecResult>((r) => setTimeout(() => r(fail(stderr)), 200));
// find 命令: 解析路径与类型 (d/f), 返回假目录/文件, 以 NUL 分隔 (与 -print0 一致)
if (command.startsWith('find ')) {
const m = command.match(
/^find ['"]([^'"]*)['"] -maxdepth 1 -mindepth 1 -type ([df]) ?-print0$/,
);
if (!m) return slow(`(mock 未定义: ${command})`);
const dir = m[1];
const node = FAKE_FS[dir];
if (!node) return slowFail(`find: ${dir}: No such file or directory`);
const full = (name: string) => (dir === '/' ? `/${name}` : `${dir}/${name}`);
const lines = m[2] === 'd' ? node.dirs.map(full) : [...node.fonts, ...node.files].map(full);
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');
}
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[*] 全部完成, 重启后生效 (模拟)');
}
// 字重覆写模式: cat 返回已选 '1' (裁切), echo 写入模拟成功
if (command.includes('wght-mode.txt')) {
return command.includes('echo') ? fake('') : slow('1');
}
// 字重覆写: Go 程序 fontmm-wght (模拟成功日志)
if (command.includes('fontmm-wght')) {
return slow(
'[✓] 已覆写: system/etc/fonts.xml\n[✓] 已覆写: system/etc/fonts_base.xml\n[✓] 已覆写: system/etc/fonts_ule.xml\n[✓] 已覆写: system/etc/font_fallback.xml\n[✓] 已覆写: system/system_ext/etc/fonts_base.xml\n[✓] 已覆写: system/system_ext/etc/fonts_ule.xml\n[*] 完成, 共覆写 6 个文件',
);
}
// 覆写日志回显: cat wght-apply.log
if (command.includes('wght-apply.log')) {
return slow('[✓] 已覆写: system/etc/fonts.xml\n[✓] 完成, 共覆写 6 个文件');
}
// 自定义字重映射: cat 返回模拟映射, rm/echo 写入模拟成功
if (command.includes('wght-map.txt')) {
if (command.includes('rm -f') || command.includes('echo')) return fake('');
return slow('100 160\n200 250\n300 330\n400 400\n500 480\n600 560\n700 650\n800 680\n900 700');
}
// 覆写 fonts.xml: cp 模拟成功 (fetch work/fonts.xml 在 dev 下 404, 覆写被跳过, 不阻断应用)
if (command.includes('fonts.xml')) {
return slow('');
}
// 元模块 (KernelSU 3.0+ 需要): 模拟已安装
if (command.includes('metamodule')) {
return slow('name=KernelSU MetaModule\nversion=v1.0\nauthor=KernelSU');
}
// 小米主题字体工具: 搜索/详情/下载 (模拟)
if (command.includes('thm.market.intl.xiaomi.com')) {
return slow(
JSON.stringify({
apiData: {
cards: [
{
items: [
{
schema: {
clicks: [
{ title: 'MiSans Global (模拟)', link: 'mock-font-1' },
{ title: 'OPPO Sans (模拟)', link: 'mock-font-2' },
],
},
},
],
},
],
},
}),
);
}
if (command.includes('api.zhuti.intl.xiaomi.com')) {
return slow(
JSON.stringify({
apiData: { extraInfo: { themeDetail: { downloadUrl: 'mock/download/path' } } },
}),
);
}
// 下载: 后台启动脚本 (立即返回)
if (command.includes('nohup sh') && command.includes('mi-font-download.sh')) {
return fake('');
}
// 字体编辑导出: 复制/目录/分块 base64/mv 全部模拟成功
if (
command.includes('cp -f') ||
command.includes("mkdir -p '/storage/emulated/0/Download/FontMM'") ||
command.includes('base64 -d >>') ||
command.includes("mv '")
) {
return slow('');
}
// 下载: 轮询日志文件 (模拟完整日志 + 结束标记)
if (command.includes('mi-download.log')) {
return slow(
[
'[*] 获取「MiSans Global (模拟)」下载链接...',
'[*] 下载: https://f17.market.xiaomi.com/issue/mock/download/path/MiSans%20Global%20(模拟).mtz',
'[✓] 下载完成: /storage/emulated/0/Download/xttdown/MiSans_Global_模拟_.mtz (23.3M)',
'[*] 解压 mtz 并提取字体...',
'[✓] 提取字体:',
' /storage/emulated/0/Download/xttdown/extracted/MiSans_Global_模拟_/Roboto-Regular.ttf',
' /storage/emulated/0/Download/xttdown/extracted/MiSans_Global_模拟_/MiSans-DemiBold.ttf',
'__DONE__',
].join('\n'),
);
}
if (command.includes('ro.product.model')) return slow('Pixel 8 Pro (模拟设备)');
return slow(`(mock 未定义: ${command})`);
}
export async function exec(command: string): Promise<ExecResult> {
if (import.meta.env.DEV) return mockExec(command);
// KernelSU-Next 等分支的 ksu API 可能与 KernelSU 不一致, 缺失时优雅降级
if (typeof ksuExec !== 'function') {
return { errno: 1, stdout: '', stderr: 'kernelsu exec API 不可用' };
}
return ksuExec(command);
}
export function toast(msg: string): void {
if (import.meta.env.DEV) console.log('[toast]', msg);
else if (typeof ksuToast === 'function') ksuToast(msg);
}
// 模块信息 (module.prop 风格文本), dev 模式返回模拟数据
export function moduleInfo(): string {
if (import.meta.env.DEV) {
return [
'id=FontMM',
'name=FontMM',
'version=26.8.0-beta.1(260800001)',
'versionCode=26080001',
'author=Yule',
'description=ColorOS 16 字体模块模板',
].join('\n');
}
if (typeof ksuModuleInfo === 'function') return ksuModuleInfo();
return '';
}
// 全屏: 让 WebView 内容延伸到状态栏 / 底部导航栏(小白条) 下方
export function fullScreen(enabled: boolean): void {
if (import.meta.env.DEV) return;
// 直接调用全局 ksu (绕过 npm 包封装), KernelSU-Next 分支缺失/命名不同时忽略
try {
const ksuApi = (window as any).ksu as Record<string, unknown> | undefined;
if (ksuApi && typeof ksuApi.fullScreen === 'function') {
(ksuApi.fullScreen as (v: boolean) => void)(enabled);
}
} catch {
// 忽略
}
}
// edge-to-edge: 启用安全区 insets (配合 insets.css 的 --window-inset-* 变量)
export function enableEdgeToEdge(enabled: boolean): void {
if (import.meta.env.DEV) return;
// 关键: 不能检查 npm 包的 import 绑定 (它始终存在, 真正的 TypeError 在包内部
// 调用 ksu.enableEdgeToEdge 时抛出, 会中断整个脚本)。必须直接检查全局 ksu 对象。
// KernelSU: enableEdgeToEdge; KernelSU-Next: enableInsets (命名不同)
try {
const ksuApi = (window as any).ksu as Record<string, unknown> | undefined;
if (!ksuApi) return;
const fn = (ksuApi.enableEdgeToEdge ?? ksuApi.enableInsets) as
| ((v: boolean) => void)
| undefined;
if (typeof fn === 'function') fn(enabled);
} catch {
// 忽略
}
}
// ---------------- 主页: 设备 / 模块信息 ----------------
export interface SystemInfo {
/** ro.build.version.release, 如 "16.0" */
androidVersion: string;
/** ro.build.version.sdk, 如 "36" */
sdk: string;
/** ro.product.model, 如 "PHZ110" */
deviceModel: string;
/** ro.product.cpu.abi, 如 "arm64-v8a" */
abi: string;
/** FONTS/ 中实际存在的用户字体文件数 (0-4) */
fontCount: number;
}
// 模块 FONT 目录 (与 main.ts 的 FONTS_DIR 保持一致)
const MODULE_FONTS_DIR = '/data/adb/modules/FontMM/FONTS';
export async function getSystemInfo(): Promise<SystemInfo> {
if (import.meta.env.DEV) {
return {
androidVersion: '16.0',
sdk: '36',
deviceModel: 'Pixel 8 Pro (模拟设备)',
abi: 'arm64-v8a',
fontCount: 2,
};
}
const info: SystemInfo = { androidVersion: '', sdk: '', deviceModel: '', abi: '', fontCount: 0 };
try {
const props = [
'ro.build.version.release',
'ro.build.version.sdk',
'ro.product.model',
'ro.product.cpu.abi',
];
const { errno, stdout } = await exec(
`${props.map((p) => `getprop ${p}`).join('; ')}; ls -1 '${MODULE_FONTS_DIR}'/*.ttf 2>/dev/null`,
);
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;
}
} catch {
// 读取失败时保持空值, 由 UI 显示占位
}
return info;
}
// 用 am start 在 WebUI 之外打开链接/应用 (避免在 WebView 内打开)
export async function amStart(uri: string, pkg?: string): Promise<void> {
const cmd = `am start -a android.intent.action.VIEW -d '${uri}'${pkg ? ` -p ${pkg}` : ''}`;
if (import.meta.env.DEV) {
console.log('[am start]', cmd);
return;
}
await exec(cmd);
}
+20
View File
@@ -0,0 +1,20 @@
import './material';
// 各功能模块在导入时完成自身初始化 (绑定事件/加载数据)
import './slots';
import './wght';
import './apply';
import './testFonts';
import './home';
import './navigation';
import { enableEdgeToEdge } from './ksu';
import { FontEditorToolDef, MiFontToolDef, ToolHost } from './tools';
// edge-to-edge: 启用安全区 insets, 内容延伸至状态栏/底部小白条区域,
// insets.css 的 --window-inset-* 变量随之生效, 底栏据此避让
enableEdgeToEdge(true);
// ---------------- 工具 ----------------
const toolHost = new ToolHost();
toolHost.register(MiFontToolDef);
toolHost.register(FontEditorToolDef);
+19
View File
@@ -0,0 +1,19 @@
import '@material/web/button/outlined-button.js';
import '@material/web/button/text-button.js';
import '@material/web/button/filled-button.js';
import '@material/web/iconbutton/icon-button.js';
import '@material/web/icon/icon.js';
import '@material/web/textfield/outlined-text-field.js';
import '@material/web/dialog/dialog.js';
import '@material/web/slider/slider.js';
import '@material/web/select/outlined-select.js';
import '@material/web/select/select-option.js';
import '@material/web/progress/linear-progress.js';
import '@material/web/labs/card/elevated-card.js';
import '@material/web/labs/card/filled-card.js';
import '@material/web/labs/navigationbar/navigation-bar.js';
import '@material/web/labs/navigationtab/navigation-tab.js';
import 'material-symbols/outlined.css';
import './theme.scss';
import './style.scss';
+85
View File
@@ -0,0 +1,85 @@
import { slots } from './slots';
import { loadHome } from './home';
import { loadTestFonts } from './testFonts';
import { applyBtn, rebootBtn } from './dom';
// ---------------- 导航与视图切换 ----------------
const homeView = document.getElementById('home-view')!;
const configView = document.getElementById('config-view')!;
const testView = document.getElementById('test-view')!;
const toolsView = document.getElementById('tools-view')!;
const views = [homeView, configView, testView, toolsView];
const navBar = document.getElementById('nav-bar') as any;
// 悬浮应用按钮 (与配置页绑定, 仅配置页显示)
const applyFab = applyBtn;
// 滑动视图轨道
const viewTrack = document.getElementById('view-track')!;
let currentIndex = 0;
// 顶栏滚动标题: 各页标题元素与相对偏移 (标题中心移出视口顶部时固定在顶栏)
const topBarTitle = document.getElementById('top-bar-title')!;
const pageTitleEls = Array.from(document.querySelectorAll<HTMLElement>('.home-title'));
const titleOffsets = views.map((view, i) => {
const el = pageTitleEls[i];
if (!el) return 0;
return el.getBoundingClientRect().top - view.getBoundingClientRect().top + view.scrollTop;
});
// 视口 pager: 轨道高度 = 视口 - 顶栏 (显式计算, 避免依赖 vh/dvh/flex 解析)
function updateTrackHeight() {
const topBar = document.querySelector<HTMLElement>('.top-app-bar');
const h = window.innerHeight - (topBar?.offsetHeight ?? 64);
viewTrack.style.height = `${Math.max(0, h)}px`;
}
updateTrackHeight();
window.addEventListener('resize', updateTrackHeight);
window.addEventListener('orientationchange', () => setTimeout(updateTrackHeight, 100));
function showView(index: number) {
const target = Math.max(0, Math.min(views.length - 1, index));
currentIndex = target;
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';
// 重启按钮仅主页显示 (visibility 保持顶栏布局不跳动)
if (rebootBtn) rebootBtn.style.visibility = target === 0 ? 'visible' : 'hidden';
// 同步底部导航高亮
if (navBar) navBar.activeIndex = target;
// 每页独立滚动, 切换后回到该页顶部
views[target].scrollTop = 0;
// 顶栏标题: 切换页时更新文字, 并回到未滚动状态 (标题在内容区显示)
topBarTitle.textContent = pageTitleEls[target]?.textContent ?? '';
document.body.classList.remove('title-scrolled');
if (target === 0) loadHome();
if (target === 2) loadTestFonts();
}
// 悬浮按钮滚动隐藏: 向下滚动移出视口, 向上滚动出现 (每页独立滚动)
views.forEach((view, i) => {
let lastY = 0;
view.addEventListener(
'scroll',
() => {
const y = view.scrollTop;
if (y > lastY + 4) applyFab.classList.add('fab-hidden');
else if (y < lastY - 4) applyFab.classList.remove('fab-hidden');
lastY = y;
// 顶栏标题: 当前页标题中心移出视口顶部时固定在顶栏
if (view === views[currentIndex] && pageTitleEls[i]) {
const titleCenter = titleOffsets[i] + pageTitleEls[i].offsetHeight / 2;
document.body.classList.toggle('title-scrolled', y > titleCenter);
}
},
{ passive: true },
);
});
navBar?.addEventListener('navigation-bar-activated', (e: { detail: { activeIndex: number } }) => {
showView(e.detail.activeIndex);
});
// 初始加载主页
void loadHome();
+123
View File
@@ -0,0 +1,123 @@
// Canvas 字形预览渲染: 用 fontTools 提取的轮廓点直接绘制, 不依赖字体文件
export interface GlyphPreviewData {
pts: [number, number, number][]; // [x, y, onCurve]
end: number[];
adv: number;
}
export interface PreviewData {
glyphs: Record<string, GlyphPreviewData>; // key: unicode 码点
upem: number;
lineGap: number;
}
// 绘制单个轮廓段 (TrueType 二次贝塞尔规则, 含首尾 off-curve 处理)
function traceContour(ctx: CanvasRenderingContext2D, seg: [number, number, number][]): void {
const n = seg.length;
if (n < 2) return;
// 起点: 首点 on-curve -> 直接用; 否则用末点或首末中点
let i = 0;
let sx: number;
let sy: number;
if (seg[0][2] === 1) {
sx = seg[0][0];
sy = seg[0][1];
i = 1;
} else if (seg[n - 1][2] === 1) {
sx = seg[n - 1][0];
sy = seg[n - 1][1];
} else {
sx = (seg[0][0] + seg[n - 1][0]) / 2;
sy = (seg[0][1] + seg[n - 1][1]) / 2;
}
ctx.moveTo(sx, -sy);
let visited = 0;
const maxIter = n * 2 + 2;
while (visited < n && i < maxIter) {
const p = seg[i % n];
if (p[2] === 1) {
ctx.lineTo(p[0], -p[1]);
i++;
visited++;
} else {
const next = seg[(i + 1) % n];
if (next[2] === 1) {
ctx.quadraticCurveTo(p[0], -p[1], next[0], -next[1]);
i += 2;
visited += 2;
} else {
// 连续 off-curve: 中间隐含 on-curve 点为中点
ctx.quadraticCurveTo(p[0], -p[1], (p[0] + next[0]) / 2, -(p[1] + next[1]) / 2);
i++;
visited++;
}
}
}
ctx.closePath();
}
function traceGlyph(ctx: CanvasRenderingContext2D, g: GlyphPreviewData): void {
if (!g || g.pts.length === 0) return;
ctx.beginPath();
let start = 0;
for (const endIdx of g.end) {
traceContour(ctx, g.pts.slice(start, endIdx + 1));
start = endIdx + 1;
}
if (start < g.pts.length) traceContour(ctx, g.pts.slice(start));
}
export interface RenderOptions {
fontSize: number; // CSS 像素字号
color: string;
}
// 渲染预览文本到 canvas (自动适配宽高/折行)
export function renderPreview(
canvas: HTMLCanvasElement,
data: PreviewData,
text: string,
opts: RenderOptions,
): void {
const dpr = window.devicePixelRatio || 1;
const cssW = canvas.clientWidth || 320;
const cssH = canvas.clientHeight || 200;
canvas.width = Math.round(cssW * dpr);
canvas.height = Math.round(cssH * dpr);
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, cssW, cssH);
ctx.fillStyle = opts.color;
const pxPerUnit = opts.fontSize / data.upem;
const pad = 8;
const lineHeight = opts.fontSize + data.lineGap * pxPerUnit;
let x = pad;
let y = pad + opts.fontSize; // 基线
for (const ch of text) {
if (ch === '\n') {
x = pad;
y += lineHeight;
continue;
}
const g = data.glyphs[String(ch.codePointAt(0))];
if (g) {
ctx.save();
ctx.translate(x, y);
ctx.scale(pxPerUnit, pxPerUnit);
traceGlyph(ctx, g);
ctx.fill();
ctx.restore();
x += g.adv * pxPerUnit;
} else {
x += opts.fontSize * 0.5; // 缺失字形占位
}
if (x > cssW - pad) {
x = pad;
y += lineHeight;
}
}
}
+218
View File
@@ -0,0 +1,218 @@
import { FontFilePicker } from './fontPicker';
import { exec, shellQuote } from './ksu';
import { readFontInfo } from './fontInfo';
import { ensureFontsCopy } from './fontFiles';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
import { applyBtn } from './dom';
import type { FontSlot } from './types';
export const SLOT_KEYS = ['hans', 'hant', 'en', 'mono', 'emoji'] as const;
export type SlotKey = (typeof SLOT_KEYS)[number];
export const slots: Record<SlotKey, FontSlot> = {
hans: {
key: 'hans',
title: '中文简体',
path: null,
fileName: '',
},
hant: {
key: 'hant',
title: '中文繁体',
path: null,
fileName: '',
},
en: {
key: 'en',
title: '英文 & 数字',
path: null,
fileName: '',
},
mono: {
key: 'mono',
title: '等宽字体',
path: null,
fileName: '',
},
emoji: {
key: 'emoji',
title: 'Emoji 表情',
path: null,
fileName: '',
},
};
const slotsEl = document.getElementById('slots')!;
// 字重覆写模式选择 (声明提前: renderSlots 首轮调用会访问)
const wghtModeSelect = document.getElementById('wght-mode-select') as any;
const wghtModeSub = document.getElementById('wght-mode-sub');
let pickingKey: SlotKey = 'hans';
// 应用流程进行中: renderSlots 据此禁用/启用应用按钮
export let applying = false;
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);
});
// 未选择时的占位文案: 回退可视化 (WYSIWYG)
function slotPlaceholder(slot: FontSlot): string {
if (slot.path) return slot.fileName;
if (slot.key === 'hans') return '未选择字体文件';
if (slots.hans.path) {
if (slot.key === 'mono') return '未选择,保持系统等宽字体';
if (slot.key === 'emoji') return '未选择,保持系统 Emoji';
return `默认使用:${slots.hans.fileName}`;
}
return '未选择字体文件';
}
// 根据是否有可变字体决定是否禁用字重覆写 (emoji/mono 不计入)
export function updateWghtModeDisabled(): void {
const hasVar = ['hans', 'hant', 'en'].some((k) => slots[k as 'hans']?.isVariable);
if (wghtModeSelect) wghtModeSelect.disabled = !hasVar;
if (wghtModeSub) {
wghtModeSub.textContent = hasVar
? '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置'
: '当前未选择可变字体 (中文/繁体/英文), 此功能不可用';
}
}
export function renderSlots() {
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() : '';
return `
<md-filled-card class="slot-card ${slot.key === 'hans' ? 'slot-hans' : ''} ${slot.path ? 'selected' : ''}" data-key="${slot.key}">
<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>
</div>
</md-filled-card>
`;
})
.join('');
// 绑定事件: 整卡点击选择字体
slotsEl.querySelectorAll<HTMLElement>('.slot-card').forEach((card) => {
card.addEventListener('click', () => {
pickingKey = card.dataset.key as SlotKey;
picker.show();
});
});
slotsEl.querySelectorAll<HTMLElement>('.slot-clear').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation(); // 阻止冒泡触发卡片选择
const slot = slots[btn.dataset.key as SlotKey];
slot.path = null;
slot.fileName = '';
renderSlots();
});
});
if (applyBtn) {
// 未选择简体字体时直接隐藏按钮 (不做半透明禁用); 应用过程中禁用
applyBtn.style.display = !slots.hans.path ? 'none' : '';
applyBtn.disabled = applying;
}
updateWghtModeDisabled();
// 通知其他模块 (如字重映射预览) 槽位已变化
document.dispatchEvent(new CustomEvent('slots-rendered'));
}
export async function copyFont(src: string, dest: string) {
const { errno, stderr } = await exec(`cp -f ${shellQuote(src)} ${shellQuote(dest)}`);
if (errno !== 0) throw new Error(`复制失败: ${stderr}`);
}
// 选择用于覆写的 wght 范围: 从 hans/hant/en 收集 (emoji/mono 除外), 取跨度最小者; 无可变返回 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) {
const r = slots[key]?.wghtRange;
if (!r) continue;
const m = r.match(/^(\d+)-(\d+)$/);
if (!m) continue;
const min = Number(m[1]);
const max = Number(m[2]);
const span = max - min;
if (span < bestSpan) {
bestSpan = span;
best = { min, max };
}
}
return best;
}
// 选择新字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小
async function refreshSlotInfo(slot: FontSlot) {
if (!slot.path) return;
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();
} catch {
// 忽略解析失败, 保持选择器返回的文件名
}
}
// 打开 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;
}
renderSlots();
}
renderSlots();
void loadExistingFonts();
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more