From e6d74ebb35e1d2ba22fee650150593de6b1361b5 Mon Sep 17 00:00:00 2001 From: wangfar Date: Mon, 9 Nov 2026 11:35:30 +0800 Subject: [PATCH] Backup: seewo-kit MCP tools and courseware anim scripts --- .gitignore | 4 + README.md | 145 ++++++ kit/README.md | 232 +++++++++ kit/core.mjs | 1271 ++++++++++++++++++++++++++++++++++++++++++++++++ kit/server.mjs | 289 +++++++++++ measure.ps1 | 20 + seewo-anim.mjs | 590 ++++++++++++++++++++++ 7 files changed, 2551 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 kit/README.md create mode 100644 kit/core.mjs create mode 100644 kit/server.mjs create mode 100644 measure.ps1 create mode 100644 seewo-anim.mjs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fc5c6be --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +*.log +.DS_Store +Thumbs.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..91f91b3 --- /dev/null +++ b/README.md @@ -0,0 +1,145 @@ +# seewo-anim · 希沃白板「点击淡入」动画工具 + +希沃白板 5 的 MCP 接口里**没有任何动画能力**,但动画数据本身是明文存在课件的本地缓存文件里的。 +本工具直接改这些文件,于是可以批量做「一开始不显示 → 点一下淡入一个答案」这类效果。 + +## 原理 + +课件缓存目录(Windows): + +``` +%APPDATA%\Seewo\EasiNote5\Data\<账号>\Courseware\<课件Id>\ + ├─ <课件Id>.json ← 索引:每页对应哪个 XML 文件、MD5、文件大小、Revision + └─ Slide_<页序>_<时间戳>.<随机>.xml ← 每页的完整内容(页序从 0 开始) +``` + +动画写在两个地方: + +```xml + + + + FadeIn + 32位hex + 1 + Appearance + Click + 3000000 + ... + + + + + + 32位hex + 32位hex + +``` + +**关键前提:必须关掉课件再改文件。** 课件开着时希沃把内容放在内存里,关闭时会把内存写回文件,直接改会被覆盖。 +所以工具的流程固定是: + +1. 通过 MCP 关掉当前打开的课件(`syncBeforeClose=false`,不保存内存改动) +2. 改 XML,同时更新索引里该页的 `FileHash`(文件 MD5)、`FileSize`,并把 `Revision` 加 1(让希沃认为本地比云端新,不会被云端的旧版本覆盖回去) +3. 重新打开课件 —— 此时动画已被读进内存;之后保存/同步都会原样带着动画上传 + +## 用法 + +```bash +# 看某页有哪些元素(拿 id 用) +node seewo-anim.mjs list --courseware "第8课" --slide 2 + +# 给已有元素加"点击淡入"(只动指定的这几个,其它元素的动画保留) +node seewo-anim.mjs set --courseware "第8课" --slide 2 --ids , + +# 换个动画/时长 +node seewo-anim.mjs set --slide 2 --ids --type WipeIn --duration 0.5 --delay 0.2 + +# 清掉整页动画,或只清指定元素 +node seewo-anim.mjs clear --slide 2 --all +node seewo-anim.mjs clear --slide 2 --ids + +# 把 MCP 新建页的正文文本块规范成「固定框宽 + 单行折行」 +node seewo-anim.mjs fix --slide 5 --width 1160 +node seewo-anim.mjs fix --slide 5,6 --width 1160 # 一次处理多页 + +# 一键做"挖空 + 答案逐个淡入"(见下) +node seewo-anim.mjs answers --plan plan.json +``` + +常用参数: + +| 参数 | 说明 | +| --- | --- | +| `--courseware <片段>` | 课件名的一部分,省略时取最近修改过的课件 | +| `--type` | `FadeIn`(默认)/ `FadeOut` / `WipeIn` / `WipeOut` / `ZoomIn` / `ZoomOut` / `FlyIn` / `FloatIn` / `Appear` | +| `--trigger` | `Click`(默认,点一下播一个)/ `WithPrevious` / `AfterPrevious` | +| `--duration` | 秒,默认 0.3 | +| `--delay` | 秒,默认 0 | +| `--sync` | 改完重开课件后顺手云同步(内部会先做一次无害改动,否则希沃只下载不上传) | +| `--no-reopen` | 只改文件不重开课件(调试用) | +| `--width` | `fix` 的正文框宽,默认 1160 | +| `--minY` | `fix` 只处理 Y 坐标 ≥ 该值的文本块,默认 90(即跳过标题/副标题) | + +## `fix`:规范 MCP 新建页的文本块 + +MCP 的 `add_text_element` 建出来的文本框是「按内容自适应」的:宽度等于当前文字宽度,`SizeToContent=Height`,而且会把**当前的折行结果**写进 ``。之后如果只改 `` 内容(比如加宽空位),重开课件时仍按旧折行位置渲染,看起来就像文字串行。 + +`fix` 把指定的正文文本块统一改成: + +- `` = `--width`(默认 1160,与手做页面一致) +- `SizeToContent` = `Manual` +- `` 只留一条 `LineProperty(StartOffset=0, Length=字数)` + +```bash +node seewo-anim.mjs fix --slide 5 --width 1160 +node seewo-anim.mjs fix --slide 5 --ids , # 只改指定元素 +node seewo-anim.mjs fix --slide 5 --minY 90 # 只改正文行(默认) +``` + +## `answers`:整页挖空答案 + +`plan.json`: + +```json +{ + "2": [ + { "line": "1b7017fcdef54caf8615181700058b97", "answers": ["打制"] }, + { "line": "d48ab3343b1b4048a7654e916024ae06", "answers": ["多元一体"] }, + { "line": "ed2be0ae9d654f62b2ae97e311b4a2a5", + "answers": ["商鞅变法", "356", "重农抑商"], + "base": "________(前________年):废井田、开阡陌,________,奖励军功,推行县制。" } + ] +} +``` + +- `line`:这一行的元素 Id(`list` 命令能查到) +- `answers`:按行内从左到右的顺序,对应行里的每个空位 +- 空位用 **4 个以上连续下划线** 表示(`________`) +- `base`(可选):强制改写这一行的文字,用于改措辞或重排空位;不写就沿用当前文字 + +工具会: + +1. 用 WPF `FormattedText` 量文字宽度(希沃本身也是 WPF,度量一致;实测误差 0) +2. **答案比空位宽时自动加宽该行空位**(多补下划线),保证红色答案不会压到相邻文字 +3. 生成答案文本框:颜色默认 `#C0392B`、加粗、字号与正文一致,精确叠在空位上(希沃文本实际渲染在 `x+10`,所以框宽 = 文字宽 + 20) +4. 每个答案框加一个 `Click` 触发的 `FadeIn`,顺序 = 页面里从左到右、从上到下 +5. 更新索引 → 重开课件 + +注意:`answers` 是**整页重建**,会先清掉这一页原有的全部动画再重排。适合"课前五分钟"这种自制页;不要拿它去处理原课件里有动画的页。 + +## 坑 + +- **改完必须重开课件**,否则界面里看不到;重开前若课件还开着,希沃关闭时会用内存内容覆盖你的修改。 +- **用 MCP 新建页后,必须先同步(上传)再做任何关课件/改 XML 的操作**。MCP 的 `add_slide` / `add_text_element` 只改内存,没同步前关闭课件会把新页全部丢掉(`close_current_courseware(syncBeforeClose=false)` 也不例外)。正确顺序:MCP 建页 → `sync_current_courseware`(上传)→ `fix` → `answers` → 再同步。 +- **同步要先"弄脏"**:本地只有 `Revision` 变大时,`sync` 只会"下载 19 → 19"。工具在 `--sync` 时会先 `add_slide` + `delete_slide` 做一次真实改动,希沃才会"上传"。 +- 元素 Id 必须用 `get_elements` / `list` 里的 32 位 hex;`get_element_properties` 用 GUID 会报"元素不存在"。元素 Id 会在每次重开/同步后变化,脚本里不要写死。 +- MCP 加的元素在**授课(Display)模式**下不会被保存;要么在备课界面操作,要么像本工具一样直接改文件。`edit_text_element` 在 Display 模式下会报"找不到元素可用的撤消恢复操作",`edit_element`(位置/尺寸)则可以。 +- 同步后希沃会重写 XML 文件(文件名带新时间戳、`` 之类可能被规范化),动画数据本身会保留 —— 已实测多轮往返不丢。 + +## 相关:seewo-kit(MCP 版) + +`kit/` 下是把本工具能力接进 MCP 的版本,另外补了课件自检、备份/恢复、跨课件复制页面、 +批量改文字。注册后可直接在 OpenCode 里调用 `seewokit_*` 工具,无需命令行。 +详见 [`kit/README.md`](kit/README.md)。 + diff --git a/kit/README.md b/kit/README.md new file mode 100644 index 0000000..0a6c039 --- /dev/null +++ b/kit/README.md @@ -0,0 +1,232 @@ +# seewo-kit · 希沃白板 MCP 增强工具 + +希沃自带的 MCP 只有「建页 / 加元素 / 开关课件 / 同步」,缺动画、跨课件复制、改文字、自检这些能力。 +`seewo-kit` 是一个独立的 stdio MCP server,直接读写希沃的本地课件缓存,同时复用希沃 MCP 完成 +「关课件 / 开课件 / 云同步」。 + +它是 `seewo-anim.mjs`(CLI)的 MCP 化版本,参数语义一致,另外补了 verify / backup / restore / copy / replace。 + +``` +kit/ +├─ core.mjs 核心实现(文件、XML、DB、MCP 客户端) +└─ server.mjs stdio MCP server,只负责协议和参数 schema +``` + +## 接入 OpenCode + +`C:\Users\Administrator\.config\opencode\opencode.json`: + +```json +{ + "mcp": { + "seewokit": { + "type": "local", + "enabled": true, + "command": ["node", "D:\\Documents\\Default Project\\seewo-anim\\kit\\server.mjs"] + } + } +} +``` + +改完重启 OpenCode,工具会以 `seewokit_*` 的名字出现。 + +## 工具一览 + +| 工具 | 作用 | 写操作 | +| --- | --- | --- | +| `set_animations` | 给元素加动画(默认 FadeIn / Click / 0.3 秒) | 是 | +| `get_animations` | 读某页动画、点击顺序、`AnimationOrders` 一致性 | 否 | +| `clear_animations` | 清整页 / 指定元素 / 全部页的动画 | 是 | +| `replace_text` | 批量改文本(整段或子串),可顺手规范折行 | 是 | +| `verify_courseware` | 课件自检:页数、页序、MD5、重复 Id、资源引用、DB 一致性 | 否 | +| `backup_courseware` | 全量快照到临时目录,返回 `backupId` | 否 | +| `restore_courseware` | 从快照恢复(需 `confirm=true`) | 是 | +| `copy_slides` | 跨课件复制页面(含图片/音频/动画/背景) | 是 | +| `sync_courseware` | 只做云同步,不改内容(用于清理 Revision 脏状态) | 是(同步) | +| `list_coursewares` | 列出本地缓存课件 | 否 | + +公共参数: + +| 参数 | 说明 | +| --- | --- | +| `courseware` | 课件名片段或 LocalId;不传取最近修改的课件 | +| `page` | 页码,1-based,按 `Board.xml` 页序 | +| `reopen` | 改完是否重新打开课件,默认 `true` | +| `sync` | 重开后是否云同步,默认 `false` | +| `force` | 跳过「未同步改动」检查,默认 `false` | +| `backup` | 改动前是否自动备份,默认 `true` | + +## 写操作的固定流程 + +所有写工具最终都走 `runEdit`: + +1. **检查**:如果目标课件正开着,先等它加载完(见下方「加载轮询」), + 比对内存页数/大小与磁盘索引;不一致且没传 `force` 就拒绝,避免丢掉未同步的新页。 +2. **关闭**:`close_current_courseware(syncBeforeClose=false)`,不保存内存改动。 +3. **备份**:自动快照到 `%TEMP%\opencode\seewo-kit-backups`,保留最近 10 份。 +4. **改文件**:改 XML,重算该文件 MD5/大小。 +5. **落盘**:更新索引 JSON 与 `CoursewareCacheData.db` 的 `Revision` / `SyncedRevision` / `Size` / 文件行。 +6. **重开**:`open_cloud_courseware`,等页面加载完成再返回。 +7. **可选同步**:`sync=true` 时先做一次「加页+删页」把课件弄脏,再上传。 + +## 各工具要点 + +### set_animations / clear_animations + +- 用 `elementIds` 精确指定,或 `textMatches` 按「文本包含」匹配;命中多个会报错,可加 `matchAll=true`。 +- `order` 传元素 Id 数组可指定点击顺序;不传按元素在页面中的先后。 +- 每次都会重建 ``,并校验动画 Id 与顺序表是否一一对应。 +- 动画时长单位是 100ns:`3000000` = 0.3 秒。 + +### replace_text + +`replacements` 每项: + +```json +{ "elementId": "32位hex", "text": "整段替换" } +{ "find": "客观:", "replace": "客观条件:" } +{ "elementId": "32位hex", "find": "旧", "replace": "新", "width": 1160 } +``` + +- `text`:整段替换,要求该元素只有一个不同的文本片段。 +- `find` + `replace`:子串替换,必须命中,否则记进 `missing`。 +- `width`:传了就同时把文本块规范成「固定框宽 + 单行折行」,避免重开后按旧折行渲染。 +- 这是补希沃 `edit_text_element` 不能改文字内容的缺口。 + +### copy_slides + +- `pages` 是源课件页码数组;`position` 是插入到目标第几页之后(0 = 最前,不传 = 末尾)。 +- 复制页的**页面 Id、元素 Id、动画 Id 全部重新生成**,避免与目标冲突。 +- 图片/音频资源会一起复制,并写入目标索引、DB 和 **`Reference.xml`**(关键,见坑)。 +- 重排 `Board.xml` 页序与索引里的 `Slides\Slide_N.xml` 映射。 + +### verify_courseware + +返回 `{ ok, issues[] }`,`level` 为 `error` / `warn` / `info`。重点检查: + +- `Board.xml` 页数 vs 索引页数、页序与 `Slide_N` 是否一致; +- 每个索引文件的 MD5 / 大小; +- 页面/元素 Id 重复; +- `id://` 资源是否存在、是否登记在 `Reference.xml`; +- JSON 与 `CoursewareCacheData.db` 的 Revision / Size / 文件行数是否一致。 + +### backup / restore + +- `backup_courseware` 返回 `backupId`,目录在 `%TEMP%\opencode\seewo-kit-backups\-<时间>`。 +- `restore_courseware` 必须传 `confirm=true`;会用快照覆盖当前缓存文件与索引/DB。 +- 恢复只改本地,`Revision` 会在当前值上再 +1;需要上传时传 `sync=true`。 + +### sync_courseware + +只同步、不改内容。课件没开会先打开,然后 `add_slide` + `delete_slide` 做一次无害改动再上传。 +适合清理测试留下的 Revision 脏状态。 + +> 不要用 `clear_animations(allPages=true)` 来「顺手触发同步」——它会真的删掉所有页面上的动画。 + +## 坑 + +### 1. 加载轮询:刚打开的课件只有 1 页 + +`open_cloud_courseware` 之后页面是异步加载的,立刻查 `get_current_courseware_info` 常常只返回 1 页。 +旧逻辑会把它当成「内存 1 页 / 磁盘 N 页 = 有未同步改动」而误报。 + +现在 `waitCoursewareLoaded` 会轮询到: + +- `slideCount` 与磁盘页数一致;或 +- 页数连续 3 次稳定且不少于磁盘页数(用户本地新增了页)。 + +只有确认加载完成后才做「未同步」判断;若超时仍只看到 1 页而磁盘有多页,会明确报「还没加载完成」,而不是误判。 + +另外: + +- 每次读写前都会先 `en_goto_app_ui({ ui: 'Edit' })`。授课(Display)模式下页面列表有时还没就绪, + `get_current_courseware_info` 会返回 0 页甚至一直无响应。 +- 所有 MCP 调用都带超时(普通 30 秒、同步 180 秒)。单次查询超时只会跳过这一轮轮询,不会被当成 0 页。 +- 关闭课件后会确认课件真的从 shell 列表里消失;关不掉就中止写操作,避免内存内容回头覆盖磁盘。 + 如果希沃界面彻底卡死(表现为 `get_current_courseware_info` / `close_current_courseware` 长时间无响应), + 只能结束对应的 `EasiNote.exe` 进程再继续;磁盘缓存不会因此损坏。 + +### 2. 「弄脏」课件:add_slide 返回的页码才是新页 + +`add_slide({ slideNumber: n })` 是在第 n 页之后插入,返回的新页号通常不是 n(例如 10 页课件返回 11)。 +`delete_slide` 必须用这个返回的页号;如果照着原来的页数删,会删掉最后一页真实内容。 + +### 3. 课件身份冲突:同名副本 / 自动改名 + +希沃检测到版本冲突时会把课件改名成 `名称(MM-dd HHmm 修改)`,并可能新建 `RemoteId`,本地也会出现 +两个同 `Name` 的缓存目录。此时 `resolveCourseware("名称片段")` 会按 mtime 命中其中一个,容易改错。 + +排查与修复: + +- 用 `list_coursewares` 看清每个 `localId` 的 `RemoteId` / 页数 / Revision; +- 用希沃的 `search_cloud_courseware` 确认云端有哪些同名副本; +- 以「有内容的那份」的 `RemoteId` 为准,把它的本地 JSON + DB 行保留;重复目录连同 + `Courseware` 行、`CoursewareFile` 行一起移除(先移出 `Courseware\` 而不是直接删); +- 恢复备份时注意:备份里的 `index.json` 带的是旧 `Name` / `RemoteId`,恢复后要把这两项改回目标云课件, + 再同步,否则会把本地指针指到另一份云端副本。 + +MCP 没有「删除云课件」的工具,云端多余副本只能在希沃 App 里手动删。 + +### 2. 图片占位图:`Reference.xml` 才是资源清单 + +希沃解析 `id://<32位hex>` **不是**只看索引 JSON,而是读课件里的 `Reference.xml`: + +```xml + + + + b77212ebd37d398fa47bab8eeefccd1c + Resources\b77212ebd37d398fa47bab8eeefccd1c.png + a460c7aa4832e85b33b7e65ae4a6d2d1 + + + +``` + +只复制资源文件 + 索引/DB 记录、不改 `Reference.xml`,图片会显示成 **EN 占位图**; +更糟的是希沃保存时会把这条「没人引用」的资源记录当作孤儿删掉。 + +`copy_slides` 现在会: + +1. 复制资源文件; +2. 写索引与 DB; +3. 合并 `Reference.xml`(没有就新建一个,并登记进索引/DB)。 + +`verify_courseware` 也加了 `resource-not-referenced` 检查,以后再漏会直接报错。 + +### 3. 同步要先「弄脏」 + +本地只有 `Revision` 变大时,希沃 `sync` 只会「下载」不会「上传」。 +`sync=true` 时工具会先 `add_slide` + `delete_slide` 做一次真实改动,再调 `sync_current_courseware`。 + +### 4. JSON 与 DB 必须一起改 + +只改索引 JSON 的 `Revision`、不改 `CoursewareCacheData.db`,重新打开云端课件时会被云端旧版本覆盖(已实测)。 +所有写操作都会在同一事务里更新: + +- `Courseware.Revision` / `SyncedRevision` / `Size` / `Files` +- `CoursewareFile` 的文件行 + +### 5. 别在课件开着时直接改文件 + +课件开着时内容在内存里,关闭会覆盖磁盘文件。必须走「关 → 改 → 开」。 + +### 6. 授课模式不保存 + +MCP 加的元素在 Display 模式下不会被保存;写操作前后尽量让课件处于 Edit(备课)模式。 +`kit` 的写操作走的是关闭后改文件,不依赖界面模式,但同步前建议 `en_goto_app_ui({ ui: 'Edit' })`(`syncShell` 已内置)。 + +## 排错 + +```bash +# 语法检查 +node --check core.mjs +node --check server.mjs + +# 手动列工具 / 调工具(stdio 客户端) +node %TEMP%\opencode\kit-test.mjs read +``` + +备份目录:`%TEMP%\opencode\seewo-kit-backups\` +账号缓存:`%APPDATA%\Seewo\EasiNote5\Data\<账号>\Courseware\<课件Id>\` +数据库:`%APPDATA%\Seewo\EasiNote5\Data\<账号>\Courseware\CoursewareCacheData.db` diff --git a/kit/core.mjs b/kit/core.mjs new file mode 100644 index 0000000..e6377d2 --- /dev/null +++ b/kit/core.mjs @@ -0,0 +1,1271 @@ +/** + * seewo-kit 核心库 + * + * 希沃白板 5 的 MCP 没有动画 / 跨课件复制 / 文本改写 / 课件自检能力, + * 但课件缓存都是明文(索引 JSON + 每页 XML + SQLite 缓存库), + * 所以这里直接操作缓存文件,并通过希沃自己的 MCP 负责「关课件 / 开课件 / 同步」。 + * + * 约定: + * · 所有写操作前,如果目标课件正开着,先关闭(syncBeforeClose=false) + * · 关闭前检查「内存里的页数/大小」和磁盘索引是否一致,防止丢掉未同步的新页 + * · 写完后更新索引 JSON(FileHash/FileSize/Revision)和 CoursewareCacheData.db + * · 默认重新打开课件;sync=true 时再触发一次云同步 + */ +import { + readFileSync, writeFileSync, readdirSync, statSync, existsSync, + mkdirSync, copyFileSync, rmSync, +} from 'node:fs'; +import { createHash, randomUUID, randomBytes } from 'node:crypto'; +import path from 'node:path'; +import os from 'node:os'; +import { DatabaseSync } from 'node:sqlite'; + +// ---------------------------------------------------------------- 常量 +const MCP_PORT = process.env.SEEWO_MCP_PORT || '7916'; +const APP_DATA = path.join(os.homedir(), 'AppData', 'Roaming', 'Seewo', 'EasiNote5', 'Data'); +const BACKUP_ROOT = path.join(os.tmpdir(), 'opencode', 'seewo-kit-backups'); +const MAX_BACKUPS = 10; +const SLIDE_RE = /^Slides[\\/]Slide_\d+\.xml$/i; +const TMP = path.join(os.tmpdir(), 'opencode'); + +mkdirSync(BACKUP_ROOT, { recursive: true }); + +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const md5 = buf => createHash('md5').update(buf).digest('hex'); +const md5File = f => md5(readFileSync(f)); +const rand = n => { + const cs = 'abcdefghijkmnopqrstuvwxyz0123456789'; + let s = ''; + for (let i = 0; i < n; i++) s += cs[Math.floor(Math.random() * cs.length)]; + return s; +}; +const stamp = () => { + const d = new Date(); + const p = n => String(n).padStart(2, '0'); + return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`; +}; +const isSlidePath = p => SLIDE_RE.test(String(p || '').replace(/\//g, '\\')); + +// ---------------------------------------------------------------- 希沃 MCP 客户端 +let sessionId = null; +let rpcId = 100; +let initialized = false; + +async function post(body, timeoutMs = 30000) { + const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }; + if (sessionId) headers['Mcp-Session-Id'] = sessionId; + const res = await fetch(`http://127.0.0.1:${MCP_PORT}/mcp`, { + method: 'POST', headers, body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + const sid = res.headers.get('mcp-session-id'); + if (sid) sessionId = sid; + const text = await res.text(); + if (text.includes('data:')) { + const data = text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join(''); + try { return JSON.parse(data); } catch { return { raw: data }; } + } + try { return JSON.parse(text); } catch { return { raw: text }; } +} + +async function rpc(name, args = {}, { timeoutMs } = {}) { + const r = await post({ jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }, timeoutMs); + if (r.error) throw new Error(`${name}: ${JSON.stringify(r.error)}`); + const txt = (r.result?.content ?? []).filter(c => c.type === 'text').map(c => c.text).join('\n'); + if (r.result?.isError) throw new Error(`${name}: ${txt}`); + return { text: txt, data: r.result?.structuredContent }; +} + +async function ensureInit() { + if (initialized) return; + await post({ + jsonrpc: '2.0', id: 1, method: 'initialize', + params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-kit', version: '1.0' } }, + }); + await post({ jsonrpc: '2.0', method: 'notifications/initialized' }); + initialized = true; +} + +async function mcp(name, args = {}, { timeoutMs } = {}) { + await ensureInit(); + try { + return await rpc(name, args, { timeoutMs }); + } catch (e) { + // 会话过期时重新握手一次 + if (/session|会话|ShellId/i.test(String(e.message))) { + sessionId = null; + initialized = false; + await ensureInit(); + return await rpc(name, args, { timeoutMs }); + } + throw e; + } +} + +const shells = () => mcp('en_find_shells', { searchingMode: 'All' }) + .then(r => r.data?.shells ?? []) + .catch(() => []); + +// ---------------------------------------------------------------- 课件定位 +export function listCoursewares() { + const out = []; + if (!existsSync(APP_DATA)) return out; + for (const user of readdirSync(APP_DATA)) { + const root = path.join(APP_DATA, user, 'Courseware'); + if (!existsSync(root)) continue; + for (const id of readdirSync(root)) { + const dir = path.join(root, id); + if (!statSync(dir).isDirectory()) continue; + const jsonPath = path.join(dir, `${id}.json`); + if (!existsSync(jsonPath)) continue; + try { + const json = JSON.parse(readFileSync(jsonPath, 'utf8').replace(/^\uFEFF/, '')); + if (!json.Courseware) continue; + out.push({ + dir, jsonPath, json, userDir: path.dirname(root), + name: json.Courseware.Name ?? '', localId: id, + mtime: statSync(jsonPath).mtimeMs, + }); + } catch { /* 跳过坏索引 */ } + } + } + return out.sort((a, b) => b.mtime - a.mtime); +} + +export function resolveCourseware(query) { + const all = listCoursewares(); + if (!all.length) throw new Error('找不到本地课件缓存(希沃是否安装并登录过?)'); + if (!query) return all[0]; + const q = String(query).trim(); + const byId = all.find(c => c.localId === q); + if (byId) return byId; + const hits = all.filter(c => c.name.includes(q)); + if (!hits.length) { + throw new Error(`没有名字含「${q}」的课件。可选:${all.slice(0, 8).map(c => c.name).join(' / ')}`); + } + return hits[0]; +} + +// ---------------------------------------------------------------- 文件 / XML +const readText = f => readFileSync(f, 'utf8'); +const readJson = f => JSON.parse(readFileSync(f, 'utf8').replace(/^\uFEFF/, '')); +const readLines = f => { + const raw = readText(f); + return { lines: raw.split(/\r?\n/), eol: raw.includes('\r\n') ? '\r\n' : '\n' }; +}; +const writeLines = (f, lines, eol) => writeFileSync(f, lines.join(eol), 'utf8'); + +function writeJson(cw) { + writeFileSync(cw.jsonPath, '\uFEFF' + JSON.stringify(cw.json, null, 2), 'utf8'); +} + +export function slideRecords(cw) { + return cw.json.CoursewareFiles.filter(f => isSlidePath(f.RelativePath)); +} + +function boardRecord(cw) { + const rec = cw.json.CoursewareFiles.find(f => String(f.RelativePath).replace(/\//g, '\\') === 'Board.xml'); + if (!rec) throw new Error(`课件「${cw.name}」没有 Board.xml 记录`); + return rec; +} + +export function readBoard(cw) { + const rec = boardRecord(cw); + const xml = readText(path.join(cw.dir, rec.FileName)); + const block = xml.match(/([\s\S]*?)<\/Slides>/)?.[1] ?? ''; + const ids = [...block.matchAll(/([0-9a-fA-F]{32})<\/Item>/g)].map(m => m[1]); + return { rec, file: path.join(cw.dir, rec.FileName), xml, ids }; +} + +const slideXmlId = xml => xml.match(/\s*([0-9a-fA-F]{32})<\/Id>/)?.[1] ?? null; + +/** 按 Board.xml 的页序返回 [{page, id, rec, file, xml}] */ +export function slidesInBoardOrder(cw) { + const { ids } = readBoard(cw); + const byId = new Map(); + for (const rec of slideRecords(cw)) { + const file = path.join(cw.dir, rec.FileName); + if (!existsSync(file)) continue; + const xml = readText(file); + const id = slideXmlId(xml); + if (id) byId.set(id.toLowerCase(), { rec, file, xml }); + } + const out = []; + const missing = []; + ids.forEach((id, i) => { + const hit = byId.get(id.toLowerCase()); + if (!hit) missing.push({ page: i + 1, id }); + else out.push({ page: i + 1, id, ...hit }); + }); + if (missing.length) { + throw new Error(`页序表里有 ${missing.length} 页在索引中找不到对应 XML:${JSON.stringify(missing.slice(0, 5))}`); + } + return out; +} + +export function slideAt(cw, page) { + const list = slidesInBoardOrder(cw); + if (!Number.isInteger(page) || page < 1 || page > list.length) { + throw new Error(`页码 ${page} 超出范围(1-${list.length})`); + } + return list[page - 1]; +} + +const blockRange = (lines, elementId) => { + const idIdx = lines.findIndex(l => l.trim() === `${elementId}`); + if (idIdx < 0) return null; + let start = idIdx; + while (start >= 0 && !/^ {4}<[A-Za-z]+>\s*$/.test(lines[start])) start--; + if (start < 0) return null; + const tag = lines[start].trim().replace(/[<>]/g, ''); + let end = idIdx; + while (end < lines.length && lines[end].trim() !== ``) end++; + if (end >= lines.length) return null; + return { start, end, tag }; +}; + +const unesc = s => String(s).replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); +const esc = s => String(s).replace(/&/g, '&').replace(//g, '>'); + +const elementText = body => { + const cands = [...body.matchAll(/([^<]*)<\/Text>/g)].map(m => unesc(m[1])).filter(t => t.trim()); + cands.sort((a, b) => b.length - a.length); + return cands[0] ?? ''; +}; + +export function listElements(lines) { + const out = []; + lines.forEach((l, i) => { + if (!/^ {4}<[A-Za-z]+>\s*$/.test(l)) return; + const tag = l.trim().replace(/[<>]/g, ''); + let k = i + 1; + while (k < lines.length && lines[k].trim() !== ``) k++; + const body = lines.slice(i + 1, k).join('\n'); + const id = body.match(/([0-9a-fA-F]{32})<\/Id>/)?.[1]; + if (!id) return; + out.push({ + id, type: tag, body, + x: Number(body.match(/([^<]*)<\/X>/)?.[1]), + y: Number(body.match(/([^<]*)<\/Y>/)?.[1]), + w: Number(body.match(/([^<]*)<\/Width>/)?.[1]), + text: elementText(body), + animated: body.includes(''), + }); + }); + return out; +} + +/** 给文本块写「固定框宽 + 单行折行」,避免只改 后按旧折行渲染 */ +function collapseLines(block, text, width) { + if (width != null) { + const wi = block.findIndex(l => /^\s*[^<]*<\/Width>$/.test(l)); + if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}${width}`; + const sc = block.findIndex(l => //.test(l)); + if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*Manual<'); + } + const ls = block.findIndex(l => l.trim() === ''); + const n = [...text].length; + if (ls >= 0) { + let le = ls; + while (le < block.length && block[le].trim() !== '') le++; + block.splice(ls + 1, le - ls - 1, + ' ', + ' 0', + ` ${n}`, + ' '); + return; + } + for (let i = 0; i < block.length; i++) { + const m = block[i].match(/^(\s*)\d+<\/Length>$/); + if (m) { block[i] = `${m[1]}${n}`; break; } + } +} + +// ---------------------------------------------------------------- 动画 +const animNode = (id, o) => [ + ' ', + ' ', + ` ${o.type}`, + ` ${id}`, + ' 1', + ' Appearance', + ` ${o.trigger}`, + ' ', + ` ${Math.round(o.duration * 10000000)}`, + ` ${Math.round(o.delay * 10000000)}`, + ' 1', + ' 0', + ' 1', + ' 0', + ' 1', + ' ', + ' ', +]; + +const ANIM_TYPES = ['FadeIn', 'FadeOut', 'WipeIn', 'WipeOut', 'ZoomIn', 'ZoomOut', 'FlyIn', 'FloatIn', 'Appear']; +const TRIGGERS = ['Click', 'WithPrevious', 'AfterPrevious']; + +function stripAnimations(lines) { + const out = []; + for (let i = 0; i < lines.length; i++) { + const t = lines[i].trim(); + if (t === '' || t === '') { + const close = t.replace('<', ':先删旧的,再按元素在页面里的先后重新排 */ +function rebuildOrders(lines) { + const oStart = lines.findIndex(l => l.trim() === ''); + if (oStart >= 0) { + let oEnd = oStart; + while (oEnd < lines.length && lines[oEnd].trim() !== '') oEnd++; + lines.splice(oStart, oEnd - oStart + 1); + } + const ids = []; + for (const el of listElements(lines)) { + const m = el.body.match(/[\s\S]*?([0-9a-fA-F]{32})<\/Id>/); + if (m) ids.push(m[1]); + } + if (!ids.length) return ids; + const closeIdx = lines.map(l => l.trim()).lastIndexOf(''); + lines.splice(closeIdx, 0, ' ', ...ids.map(x => ` ${x}`), ' '); + return ids; +} + +function addAnimationToElement(lines, elementId, o) { + const r = blockRange(lines, elementId); + if (!r) return null; + const block = lines.slice(r.start, r.end + 1); + let replaced = 0; + const a = block.findIndex(l => l.trim() === ''); + if (a >= 0) { + let b = a; + while (b < block.length && block[b].trim() !== '') b++; + replaced = 1; + block.splice(a, b - a + 1); + } + const animId = randomBytes(16).toString('hex'); + let at = block.findIndex(l => l.trim() === ''); + if (at < 0) at = block.findIndex(l => l.trim() === ''); + if (at < 0) at = block.length - 1; + block.splice(at, 0, ...animNode(animId, o)); + lines.splice(r.start, r.end - r.start + 1, ...block); + return { animId, replaced }; +} + +function parseAnimations(body) { + const out = []; + for (const block of body.matchAll(/([\s\S]*?)<\/Animations>/g)) { + for (const a of block[1].matchAll(/([\s\S]*?)<\/Animation>/g)) { + const g = t => a[1].match(new RegExp(`<${t}>([^<]*)`))?.[1]; + out.push({ + id: g('Id'), type: g('Type'), trigger: g('Trigger'), + duration: Number(g('Duration') || 0) / 1e7, + delay: Number(g('Delay') || 0) / 1e7, + }); + } + } + return out; +} + +function parseOrders(lines) { + const start = lines.findIndex(l => l.trim() === ''); + if (start < 0) return []; + let end = start; + while (end < lines.length && lines[end].trim() !== '') end++; + return lines.slice(start + 1, end) + .map(l => l.match(/([0-9a-fA-F]{32})<\/Item>/)?.[1]) + .filter(Boolean); +} + +function resolveTargets(lines, { elementIds = [], textMatches = [], matchAll = false }) { + const els = listElements(lines).filter(e => e.type === 'Text' || e.type === 'Picture' || e.type === 'Shape'); + const byId = new Map(els.map(e => [e.id, e])); + const picked = []; + const missing = []; + for (const id of elementIds) { + if (byId.has(id)) picked.push(byId.get(id)); + else missing.push({ elementId: id, reason: '元素不存在' }); + } + for (const needle of textMatches) { + const hits = els.filter(e => e.text && e.text.includes(needle)); + if (!hits.length) missing.push({ text: needle, reason: '没有文本含这段文字' }); + else if (hits.length > 1 && !matchAll) { + throw new Error(`「${needle}」匹配到 ${hits.length} 个元素,请改用 elementIds:` + + hits.map(h => `${h.id}(${h.text.slice(0, 20)})`).join(' | ')); + } else picked.push(...hits); + } + return { targets: [...new Map(picked.map(e => [e.id, e])).values()], missing }; +} + +function applyCustomOrder(lines, elementOrder = []) { + if (!elementOrder.length) return; + const els = listElements(lines); + const animOf = new Map(); + for (const el of els) { + const m = el.body.match(/[\s\S]*?([0-9a-fA-F]{32})<\/Id>/); + if (m) animOf.set(el.id, m[1]); + } + const current = parseOrders(lines); + const desired = elementOrder.map(id => animOf.get(id)).filter(Boolean); + const rest = current.filter(x => !desired.includes(x)); + const next = [...desired, ...rest]; + const start = lines.findIndex(l => l.trim() === ''); + if (start < 0) return; + let end = start; + while (end < lines.length && lines[end].trim() !== '') end++; + lines.splice(start, end - start + 1, ' ', ...next.map(x => ` ${x}`), ' '); +} + +// ---------------------------------------------------------------- 数据库 +const dbPathOf = cw => path.join(cw.userDir, 'Courseware', 'CoursewareCacheData.db'); + +function withDb(cw, fn, { write = false } = {}) { + const p = dbPathOf(cw); + if (!existsSync(p)) return null; + let db; + try { + db = new DatabaseSync(p, { readOnly: !write }); + return fn(db); + } finally { + try { db?.close(); } catch { /* ignore */ } + } +} + +export function readDbRow(cw) { + return withDb(cw, db => db.prepare( + 'select LocalId,RemoteId,Name,UpdateTime,Size,LocalRevision,SyncedRevision,Hash,Files from Courseware where LocalId=?', + ).get(cw.localId) ?? null); +} + +function writeDb(cw) { + return withDb(cw, db => { + const j = cw.json; + const localId = cw.localId; + db.exec('BEGIN'); + try { + db.prepare('delete from CoursewareFile where FileRelativePath like ?').run(localId + '\\%'); + const ins = db.prepare( + 'insert into CoursewareFile (FileId,FileHash,FileName,FileSize,FileRelativePath,DocumentRelativePath,FileIntValueOne) values (?,?,?,?,?,?,0)', + ); + for (const f of j.CoursewareFiles) { + ins.run(f.FileId, f.FileHash, f.FileName, f.FileSize, localId + '\\' + f.FileName, f.RelativePath); + } + db.prepare('update Courseware set UpdateTime=?, Size=?, LocalRevision=?, SyncedRevision=?, Files=? where LocalId=?') + .run(j.Courseware.UpdateTime, j.Courseware.Size, j.Courseware.Revision, j.Courseware.SyncedRevision, j.Courseware.Files, localId); + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + throw e; + } + return true; + }, { write: true }); +} + +/** 写回索引 + DB:重算 Size/Files,Revision 取 JSON 与 DB 的较大值再 +1 */ +function finalize(cw) { + const j = cw.json; + j.CoursewareFiles = j.CoursewareFiles.filter(f => f && f.FileId && f.FileName); + j.Courseware.Files = j.CoursewareFiles.map(f => f.FileId).join(';') + ';'; + j.Courseware.Size = j.CoursewareFiles.reduce((a, f) => a + (f.FileSize || 0), 0); + const dbRow = readDbRow(cw); + const base = Math.max(j.Courseware.Revision ?? 0, dbRow?.LocalRevision ?? 0); + j.Courseware.Revision = base + 1; + j.Courseware.SyncedRevision = Math.min( + j.Courseware.Revision - 1, + Math.max(j.Courseware.SyncedRevision ?? 0, dbRow?.SyncedRevision ?? 0), + ); + j.Courseware.UpdateTime = Date.now(); + writeJson(cw); + writeDb(cw); +} + +const saveSlideRecord = (cw, rec, file) => { + const buf = readFileSync(file); + rec.FileHash = md5(buf); + rec.FileSize = buf.length; +}; + +// ---------------------------------------------------------------- 备份 +function backupManifestPath(dir) { return path.join(dir, 'manifest.json'); } + +export function backupCourseware({ courseware, note = '' } = {}) { + const cw = resolveCourseware(courseware); + const id = `${cw.localId}-${stamp()}`; + const dir = path.join(BACKUP_ROOT, id); + mkdirSync(dir, { recursive: true }); + const warnings = []; + for (const f of cw.json.CoursewareFiles) { + const src = path.join(cw.dir, f.FileName); + if (!existsSync(src)) { warnings.push(`缺文件:${f.FileName}`); continue; } + copyFileSync(src, path.join(dir, f.FileName)); + } + copyFileSync(cw.jsonPath, path.join(dir, 'index.json')); + const manifest = { + id, createdAt: new Date().toISOString(), note, + localId: cw.localId, remoteId: cw.json.Courseware.RemoteId, + name: cw.name, + revision: cw.json.Courseware.Revision, + syncedRevision: cw.json.Courseware.SyncedRevision, + size: cw.json.Courseware.Size, + dbRow: readDbRow(cw), + files: cw.json.CoursewareFiles.map(f => ({ + FileId: f.FileId, FileName: f.FileName, FileHash: f.FileHash, + FileSize: f.FileSize, RelativePath: f.RelativePath, + })), + warnings, + }; + writeFileSync(backupManifestPath(dir), JSON.stringify(manifest, null, 2), 'utf8'); + + // 只保留最近 N 份 + const siblings = readdirSync(BACKUP_ROOT) + .filter(n => n.startsWith(cw.localId + '-')) + .sort(); + for (const old of siblings.slice(0, Math.max(0, siblings.length - MAX_BACKUPS))) { + rmSync(path.join(BACKUP_ROOT, old), { recursive: true, force: true }); + } + return { backupId: id, dir, files: manifest.files.length, warnings }; +} + +function resolveBackup(backupId) { + const raw = String(backupId || '').trim(); + if (!raw) throw new Error('缺少 backupId'); + let dir = raw; + if (!path.isAbsolute(raw)) dir = path.join(BACKUP_ROOT, raw); + if (!existsSync(dir)) throw new Error(`找不到备份:${raw}`); + const mf = backupManifestPath(dir); + if (!existsSync(mf)) throw new Error(`备份缺少 manifest.json:${dir}`); + return { dir, manifest: readJson(mf) }; +} + +// ---------------------------------------------------------------- 关/开/同步 +function sameCourseware(shell, cw) { + const n = String(shell.coursewareName || '').trim(); + return n === cw.name.trim(); +} + +/** + * 等课件真正加载完:希沃刚打开云端课件时,get_current_courseware_info 会先返回 1 页, + * 直接拿它和磁盘比较会被误判成「有未同步改动」。这里轮询到页数与磁盘一致, + * 或页数连续稳定且不少于磁盘页数(用户本地新增了页)为止。 + */ +async function waitCoursewareLoaded(shellId, expectedPages, { timeoutMs = 25000 } = {}) { + const deadline = Date.now() + timeoutMs; + let last = null; + let stable = 0; + while (Date.now() < deadline) { + let info = null; + try { + info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 12000 }); + } catch { + // 单次查询超时 / 界面暂时无响应:继续等,别把它当成 0 页 + await sleep(800); + continue; + } + const d = info?.data ?? {}; + if (typeof d.slideCount === 'number') { + if (d.slideCount === expectedPages) return { loaded: true, info: d }; + if (last && d.slideCount === last.slideCount) stable++; + else stable = 0; + last = d; + if (stable >= 2 && d.slideCount > expectedPages) return { loaded: true, info: d }; + } + await sleep(500); + } + return { loaded: false, info: last ?? {} }; +} + +async function closeForWrite(cw, force) { + await ensureInit(); + const open = (await shells()).filter(s => sameCourseware(s, cw)); + if (!open.length) return { wasOpen: false, closed: 0 }; + const diskPages = slideRecords(cw).length; + const diskSize = cw.json.Courseware.Size; + for (const s of open) { + // 先切回备课界面:授课模式下页面列表可能还没就绪,get_current_courseware_info 会卡住或返回 0 页 + await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {}); + await sleep(600); + let { loaded, info: d } = await waitCoursewareLoaded(s.id, diskPages); + if (!loaded) { + // 再给一次机会:重新切界面后再等 + await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {}); + await sleep(1000); + ({ loaded, info: d } = await waitCoursewareLoaded(s.id, diskPages)); + } + if (!loaded && (d.slideCount ?? 0) <= 1 && diskPages > 1) { + throw new Error( + `课件「${cw.name}」还没加载完成(当前只看到 ${d.slideCount ?? 0} 页 / 磁盘 ${diskPages} 页)。` + + '请等希沃界面显示完整后再试,或传 force=true 忽略检查。', + ); + } + const bad = []; + if (typeof d.slideCount === 'number' && d.slideCount !== diskPages) { + bad.push(`内存 ${d.slideCount} 页 / 磁盘 ${diskPages} 页`); + } + if (typeof d.size === 'number' && d.size !== diskSize) { + bad.push(`内存 ${d.size} 字节 / 磁盘 ${diskSize} 字节`); + } + if (bad.length && !force) { + throw new Error( + `课件「${cw.name}」有未同步的内存改动(${bad.join(';')})。` + + '请先用 seewo 的 sync_current_courseware 同步,或传 force=true 丢弃这些改动。', + ); + } + } + for (const s of open) { + await mcp('close_current_courseware', { shellId: s.id, syncBeforeClose: false }).catch(() => {}); + } + let stillOpen = true; + for (let i = 0; i < 20; i++) { + await sleep(500); + stillOpen = (await shells()).some(s => sameCourseware(s, cw)); + if (!stillOpen) break; + } + if (stillOpen) { + throw new Error( + `课件「${cw.name}」关闭失败(希沃界面可能卡住),已中止写操作以免内存内容覆盖磁盘。` + + '请手动关闭课件或重启希沃后重试。', + ); + } + return { wasOpen: true, closed: open.length }; +} + +async function openCourseware(cwName, expectedPages = null) { + await ensureInit(); + let s = (await shells()).find(x => String(x.coursewareName || '').trim() === cwName.trim()); + for (let attempt = 0; attempt < 2 && !s; attempt++) { + await mcp('open_cloud_courseware', { coursewareName: cwName }).catch(() => {}); + for (let i = 0; i < 20; i++) { + await sleep(700); + s = (await shells()).find(x => String(x.coursewareName || '').trim() === cwName.trim()); + if (s) break; + } + } + if (!s) return null; + if (expectedPages != null) await waitCoursewareLoaded(s.id, expectedPages); + await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {}); + return s.id; +} + +/** 做一次无害改动,让希沃认为课件「未同步」,否则 sync 只会下载 */ +async function touch(shellId) { + const info = await mcp('get_current_courseware_info', { shellId }); + const count = info.data?.slideCount ?? 0; + const add = await mcp('add_slide', { shellId, slideNumber: count }).catch(() => null); + if (add?.data?.slideNumber) { + await mcp('delete_slide', { shellId, slideNumber: add.data.slideNumber }).catch(() => {}); + } +} + +async function syncShell(shellId) { + await mcp('en_goto_app_ui', { ui: 'Edit', shellId }).catch(() => {}); + await sleep(1200); + await touch(shellId); + const opts = { timeoutMs: 180000 }; + let r = await mcp('sync_current_courseware', { shellId, waitUntilSynced: true, waitSeconds: 120 }, opts) + .catch(e => ({ text: 'ERR ' + e.message })); + if (String(r.text).includes('下载')) { + await touch(shellId); + r = await mcp('sync_current_courseware', { shellId, waitUntilSynced: true, waitSeconds: 120 }, opts) + .catch(e => ({ text: 'ERR ' + e.message })); + } + return r.text; +} + +// 串行化写操作,避免两个工具同时开/关课件 +let chain = Promise.resolve(); +function serial(fn) { + const p = chain.then(fn, fn); + chain = p.catch(() => {}); + return p; +} + +async function runEdit(cw, opts, action) { + return serial(async () => { + const { wasOpen, closed } = await closeForWrite(cw, opts.force); + const backup = opts.backup === false ? null : backupCourseware({ courseware: cw.localId, note: 'auto-before-write' }); + let result; + try { + result = await action(cw); + finalize(cw); + } catch (e) { + e.message += backup ? `\n(改动前备份:${backup.backupId})` : ''; + throw e; + } + let shellId = null; + let syncText = null; + if (opts.reopen !== false) { + shellId = await openCourseware(cw.name, slideRecords(cw).length); + if (opts.sync && shellId) syncText = await syncShell(shellId); + } + return { + ...result, + backupId: backup?.backupId ?? null, + wasOpen, closed, + reopened: !!shellId, + shellId, + sync: syncText, + }; + }); +} + +// ---------------------------------------------------------------- 工具:动画 +export async function setAnimations({ + courseware, page, elementIds = [], textMatches = [], matchAll = false, + type = 'FadeIn', trigger = 'Click', duration = 0.3, delay = 0, order = [], + reopen = true, sync = false, force = false, backup = true, +} = {}) { + const cw = resolveCourseware(courseware); + if (!ANIM_TYPES.includes(type)) throw new Error(`type 只能是:${ANIM_TYPES.join(' / ')}`); + if (!TRIGGERS.includes(trigger)) throw new Error(`trigger 只能是:${TRIGGERS.join(' / ')}`); + const o = { type, trigger, duration: Number(duration), delay: Number(delay) }; + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const { file, rec } = slideAt(c, page); + const { lines, eol } = readLines(file); + const { targets, missing } = resolveTargets(lines, { elementIds, textMatches, matchAll }); + if (!targets.length) throw new Error('没有匹配到任何元素' + (missing.length ? `:${JSON.stringify(missing)}` : '')); + let replaced = 0; + const added = []; + for (const t of targets) { + const r = addAnimationToElement(lines, t.id, o); + if (r) { replaced += r.replaced; added.push({ elementId: t.id, animationId: r.animId, text: t.text.slice(0, 30) }); } + else missing.push({ elementId: t.id, reason: '写动画失败' }); + } + rebuildOrders(lines); + applyCustomOrder(lines, order); + writeLines(file, lines, eol); + saveSlideRecord(c, rec, file); + return { courseware: c.name, page, added, replaced, missing, order: parseOrders(lines), options: o }; + }); +} + +export function getAnimations({ courseware, page } = {}) { + const cw = resolveCourseware(courseware); + const { lines } = readLines(slideAt(cw, page).file); + const orders = parseOrders(lines); + const orderIndex = new Map(orders.map((id, i) => [id.toLowerCase(), i + 1])); + const elements = []; + const known = new Set(); + for (const el of listElements(lines)) { + const anims = parseAnimations(el.body); + if (!anims.length) continue; + for (const a of anims) { + if (a.id) known.add(a.id.toLowerCase()); + elements.push({ + elementId: el.id, elementType: el.type, text: el.text.slice(0, 60), + x: el.x, y: el.y, + ...a, + order: orderIndex.get(String(a.id).toLowerCase()) ?? null, + }); + } + } + const issues = []; + for (const e of elements) if (e.order == null) issues.push(`动画 ${e.id} 不在 AnimationOrders 里,不会播放`); + for (const id of orders) if (!known.has(id.toLowerCase())) issues.push(`AnimationOrders 里的 ${id} 找不到对应动画`); + return { courseware: cw.name, page, count: elements.length, order: orders, elements, issues }; +} + +export async function clearAnimations({ + courseware, page, allPages = false, elementIds = [], + reopen = true, sync = false, force = false, backup = true, +} = {}) { + const cw = resolveCourseware(courseware); + if (!allPages && !Number.isInteger(Number(page))) throw new Error('需要 page,或传 allPages=true'); + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const pages = allPages ? slidesInBoardOrder(c).map(s => s.page) : [Number(page)]; + const report = []; + for (const n of pages) { + const { file, rec } = slideAt(c, n); + const { lines, eol } = readLines(file); + const before = (lines.join('\n').match(//g) ?? []).length; + let out; + if (!elementIds.length) { + out = stripAnimations(lines); + } else { + out = lines; + for (const id of elementIds) { + const r = blockRange(out, id); + if (!r) continue; + const block = out.slice(r.start, r.end + 1); + const a = block.findIndex(l => l.trim() === ''); + if (a >= 0) { + let b = a; + while (b < block.length && block[b].trim() !== '') b++; + block.splice(a, b - a + 1); + out.splice(r.start, r.end - r.start + 1, ...block); + } + } + } + const orders = rebuildOrders(out); + writeLines(file, out, eol); + saveSlideRecord(c, rec, file); + report.push({ page: n, before, after: orders.length, cleared: Math.max(0, before - orders.length) }); + } + return { courseware: c.name, pages: report }; + }); +} + +// ---------------------------------------------------------------- 工具:改文字 +export async function replaceText({ + courseware, page, replacements = [], + reopen = true, sync = false, force = false, backup = true, +} = {}) { + const cw = resolveCourseware(courseware); + if (!Array.isArray(replacements) || !replacements.length) throw new Error('replacements 不能为空'); + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const { file, rec } = slideAt(c, page); + const { lines, eol } = readLines(file); + const changes = []; + const missing = []; + + for (const spec of replacements) { + let el = null; + if (spec.elementId) { + el = listElements(lines).find(e => e.id === spec.elementId); + if (!el) { missing.push({ elementId: spec.elementId, reason: '元素不存在' }); continue; } + } else if (spec.find) { + const hits = listElements(lines).filter(e => e.type === 'Text' && e.text.includes(spec.find)); + if (!hits.length) { missing.push({ find: spec.find, reason: '没有文本含这段文字' }); continue; } + if (hits.length > 1) { + throw new Error(`「${spec.find}」匹配到 ${hits.length} 个元素,请加 elementId:` + + hits.map(h => h.id).join(', ')); + } + el = hits[0]; + } else { + missing.push({ reason: '需要 elementId 或 find' }); + continue; + } + if (spec.text == null && spec.find == null) { missing.push({ elementId: el.id, reason: '需要 text 或 find' }); continue; } + + const r = blockRange(lines, el.id); + const block = lines.slice(r.start, r.end + 1); + const before = elementText(block.join('\n')); + let after; + + if (spec.text != null) { + after = String(spec.text); + const nonEmpty = new Set([...block.join('\n').matchAll(/([^<]*)<\/Text>/g)] + .map(m => unesc(m[1])).filter(Boolean)); + if (nonEmpty.size > 1) { + throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`); + } + const oldTag = `${esc(before)}`; + for (let i = 0; i < block.length; i++) { + if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`${esc(after)}`); + } + } else { + const find = String(spec.find); + const rep = String(spec.replace ?? ''); + if (!before.includes(find)) { missing.push({ elementId: el.id, reason: `文本里没有「${find}」` }); continue; } + after = before.split(find).join(rep); + for (let i = 0; i < block.length; i++) { + block[i] = block[i].replace(/([^<]*)<\/Text>/g, (m, t) => { + const plain = unesc(t); + return plain.includes(find) ? `${esc(plain.split(find).join(rep))}` : m; + }); + } + } + + if (spec.width != null) collapseLines(block, after, Number(spec.width)); + else collapseLines(block, after); + lines.splice(r.start, r.end - r.start + 1, ...block); + changes.push({ elementId: el.id, before, after }); + } + + if (changes.length) { + writeLines(file, lines, eol); + saveSlideRecord(c, rec, file); + } + return { courseware: c.name, page, changes, missing }; + }); +} + +// ---------------------------------------------------------------- 工具:校验 +export function verifyCourseware({ courseware, hashes = true, deep = true } = {}) { + const cw = resolveCourseware(courseware); + const issues = []; + const add = (level, code, message, extra = {}) => issues.push({ level, code, message, ...extra }); + const j = cw.json; + + let board = null; + try { board = readBoard(cw); } catch (e) { add('error', 'board-missing', e.message); } + + const slides = slideRecords(cw); + const ids = []; + const seenSlideIds = new Map(); + const elementOwner = new Map(); + + for (const rec of slides) { + const file = path.join(cw.dir, rec.FileName); + if (!existsSync(file)) { add('error', 'slide-file-missing', `索引里的页面文件不存在:${rec.FileName}`, { relativePath: rec.RelativePath }); continue; } + const buf = readFileSync(file); + if (hashes) { + if (buf.length !== rec.FileSize) add('error', 'slide-size-mismatch', `${rec.RelativePath} 大小不符:索引 ${rec.FileSize} / 实际 ${buf.length}`); + const h = md5(buf); + if (h !== rec.FileHash) add('error', 'slide-hash-mismatch', `${rec.RelativePath} MD5 不符`, { expected: rec.FileHash, actual: h }); + } + const xml = buf.toString('utf8'); + const id = slideXmlId(xml); + if (!id) { add('error', 'slide-id-missing', `${rec.RelativePath} 没有 `); continue; } + ids.push({ rec, id }); + if (seenSlideIds.has(id)) add('error', 'duplicate-slide-id', `页面 Id 重复:${id}`); + else seenSlideIds.set(id, rec.RelativePath); + + if (deep) { + for (const m of xml.matchAll(/([0-9a-fA-F]{32})<\/Id>/g)) { + const eid = m[1].toLowerCase(); + if (eid === id.toLowerCase()) continue; + if (elementOwner.has(eid)) { + add('warn', 'duplicate-element-id', `元素 Id ${eid} 同时出现在 ${elementOwner.get(eid)} 和 ${rec.RelativePath}`); + } else elementOwner.set(eid, rec.RelativePath); + } + } + } + + if (board) { + const idToRec = new Map(ids.map(x => [x.id.toLowerCase(), x.rec])); + if (board.ids.length !== slides.length) { + add('error', 'page-count-mismatch', `Board.xml 有 ${board.ids.length} 页,索引有 ${slides.length} 页`); + } + board.ids.forEach((id, i) => { + const rec = idToRec.get(id.toLowerCase()); + if (!rec) { + add('error', 'board-page-missing', `Board.xml 第 ${i + 1} 页的 Id ${id} 在索引里找不到`); + return; + } + const expect = `Slides\\Slide_${i}.xml`; + if (String(rec.RelativePath).replace(/\//g, '\\').toLowerCase() !== expect.toLowerCase()) { + add('warn', 'page-order-mismatch', `第 ${i + 1} 页在索引里是 ${rec.RelativePath},与页序不一致`); + } + }); + const inBoard = new Set(board.ids.map(x => x.toLowerCase())); + for (const x of ids) if (!inBoard.has(x.id.toLowerCase())) add('error', 'page-not-in-board', `${x.rec.RelativePath} 不在 Board.xml 的页序里(会显示不出来)`); + } + + // 索引 / 资源 / 孤儿文件 + const byName = new Map(); + for (const f of j.CoursewareFiles) { + const file = path.join(cw.dir, f.FileName); + if (!existsSync(file)) { add('error', 'file-missing', `索引文件不存在:${f.FileName}`); continue; } + const size = statSync(file).size; + if (size !== f.FileSize) add('error', 'file-size-mismatch', `${f.FileName} 大小不符(索引 ${f.FileSize} / 实际 ${size})`); + if (hashes && f.FileHash) { + const h = md5File(file); + if (h !== f.FileHash) add('error', 'file-hash-mismatch', `${f.FileName} MD5 不符`); + } + byName.set(f.FileName, f); + } + const sum = j.CoursewareFiles.reduce((a, f) => a + (f.FileSize || 0), 0); + if (sum !== j.Courseware.Size) add('warn', 'size-sum-mismatch', `Courseware.Size=${j.Courseware.Size},文件合计=${sum}`); + + const refRec = j.CoursewareFiles.find( + f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === 'reference.xml', + ); + let refIds = null; + if (refRec) { + const rf = path.join(cw.dir, refRec.FileName); + if (existsSync(rf)) { + refIds = new Set([...readText(rf).matchAll(/([0-9a-fA-F]{32})<\/Id>/g)].map(m => m[1].toLowerCase())); + } + } + + for (const slide of slides) { + const file = path.join(cw.dir, slide.FileName); + if (!existsSync(file)) continue; + const xml = readText(file); + for (const m of xml.matchAll(/id:\/\/([0-9a-fA-F]{32})/g)) { + const rid = m[1].toLowerCase(); + const rec = j.CoursewareFiles.find(f => { + const n = f.FileName.toLowerCase(); + return n === rid || n.startsWith(rid + '.'); + }); + if (!rec) add('error', 'resource-missing', `${slide.RelativePath} 引用的资源 ${rid} 不在索引里`); + else if (!existsSync(path.join(cw.dir, rec.FileName))) add('error', 'resource-file-missing', `${slide.RelativePath} 引用的资源文件不存在:${rec.FileName}`); + if (refIds && !refIds.has(rid)) { + add('error', 'resource-not-referenced', `${slide.RelativePath} 的资源 ${rid} 没有登记在 Reference.xml(会显示成占位图)`); + } + } + } + + const referenced = new Set(j.CoursewareFiles.map(f => f.FileName)); + const metaFiles = new Set([`${cw.localId}.json`, 'CoursewareSourceTrace.json']); + const orphans = readdirSync(cw.dir).filter(n => { + const p = path.join(cw.dir, n); + return statSync(p).isFile() + && !referenced.has(n) + && !metaFiles.has(n) + && !/\.db$/i.test(n); + }); + if (orphans.length) add('info', 'orphan-files', `目录里有 ${orphans.length} 个未被索引引用的文件(多为旧版页面残留,可忽略)`, { examples: orphans.slice(0, 5) }); + + const filesField = j.Courseware.Files || ''; + const fileIds = new Set(j.CoursewareFiles.map(f => f.FileId)); + const listed = filesField.split(';').filter(Boolean); + if (listed.length !== fileIds.size || listed.some(x => !fileIds.has(x))) { + add('warn', 'files-field-mismatch', 'Courseware.Files 与 CoursewareFiles 不一致'); + } + + let dbRow = null; + try { + dbRow = readDbRow(cw); + if (!dbRow) add('error', 'db-row-missing', 'CoursewareCacheData.db 里没有这份课件'); + else { + if (dbRow.LocalRevision !== j.Courseware.Revision) add('warn', 'db-revision-mismatch', `DB LocalRevision=${dbRow.LocalRevision},JSON Revision=${j.Courseware.Revision}`); + if (dbRow.SyncedRevision !== j.Courseware.SyncedRevision) add('warn', 'db-synced-mismatch', `DB SyncedRevision=${dbRow.SyncedRevision},JSON SyncedRevision=${j.Courseware.SyncedRevision}`); + if (dbRow.Size !== j.Courseware.Size) add('warn', 'db-size-mismatch', `DB Size=${dbRow.Size},JSON Size=${j.Courseware.Size}`); + const n = withDb(cw, db => db.prepare('select count(*) c from CoursewareFile where FileRelativePath like ?').get(cw.localId + '\\%').c); + if (n !== j.CoursewareFiles.length) add('warn', 'db-file-count-mismatch', `DB 文件行 ${n} 条,索引 ${j.CoursewareFiles.length} 条`); + } + } catch (e) { + add('warn', 'db-unreadable', `读 DB 失败:${e.message}`); + } + + return { + ok: !issues.some(x => x.level === 'error'), + courseware: cw.name, + localId: cw.localId, + pages: board?.ids.length ?? slides.length, + revision: j.Courseware.Revision, + syncedRevision: j.Courseware.SyncedRevision, + size: j.Courseware.Size, + db: dbRow && { localRevision: dbRow.LocalRevision, syncedRevision: dbRow.SyncedRevision, size: dbRow.Size }, + counts: { errors: issues.filter(x => x.level === 'error').length, warnings: issues.filter(x => x.level === 'warn').length, infos: issues.filter(x => x.level === 'info').length }, + issues, + }; +} + +// ---------------------------------------------------------------- 工具:恢复 +export async function restoreCourseware({ + backupId, courseware, confirm = false, + reopen = true, sync = false, force = false, +} = {}) { + if (!confirm) throw new Error('恢复会覆盖当前课件,请传 confirm=true'); + const { dir, manifest } = resolveBackup(backupId); + const cw = resolveCourseware(courseware ?? manifest.localId); + return serial(async () => { + const { wasOpen } = await closeForWrite(cw, force); + for (const f of manifest.files) { + const src = path.join(dir, f.FileName); + if (existsSync(src)) copyFileSync(src, path.join(cw.dir, f.FileName)); + } + const idx = path.join(dir, 'index.json'); + if (!existsSync(idx)) throw new Error('备份缺少 index.json'); + writeFileSync(cw.jsonPath, readFileSync(idx)); + cw.json = readJson(cw.jsonPath); + + const dbRow = readDbRow(cw); + const base = Math.max(cw.json.Courseware.Revision ?? 0, dbRow?.LocalRevision ?? 0); + cw.json.Courseware.Revision = base + 1; + cw.json.Courseware.UpdateTime = Date.now(); + cw.json.Courseware.SyncedRevision = manifest.syncedRevision ?? cw.json.Courseware.SyncedRevision; + writeJson(cw); + writeDb(cw); + + let shellId = null; + let syncText = null; + if (reopen) { + shellId = await openCourseware(cw.name, slideRecords(cw).length); + if (sync && shellId) syncText = await syncShell(shellId); + } + return { + restored: manifest.id, courseware: cw.name, + revision: cw.json.Courseware.Revision, wasOpen, reopened: !!shellId, shellId, sync: syncText, + }; + }); +} + +// ---------------------------------------------------------------- 工具:跨课件复制 +function regenerateIds(xml) { + const map = new Map(); + const get = id => { + const k = id.toLowerCase(); + if (!map.has(k)) map.set(k, randomBytes(16).toString('hex')); + return map.get(k); + }; + let out = xml.replace(/([0-9a-fA-F]{32})<\/Id>/g, (m, id) => `${get(id)}`); + out = out.replace(/([0-9a-fA-F]{32})<\/Item>/g, (m, id) => `${get(id)}`); + return out; +} + +function resourceRefs(xml) { + return [...new Set([...xml.matchAll(/id:\/\/([0-9a-fA-F]{32})/g)].map(m => m[1].toLowerCase()))]; +} + +/** + * 希沃真正解析 id://<32hex> 用的是 Reference.xml 里的关系表, + * 只把资源文件 + 索引/DB 记录复制过来,页面上的图片仍会显示成占位图, + * 保存时希沃还会把这条资源记录当成孤儿删掉。复制页面时必须同步合并关系表。 + */ +function referenceRecord(cw) { + const rec = cw.json.CoursewareFiles.find( + f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === 'reference.xml', + ); + if (!rec) return null; + const file = path.join(cw.dir, rec.FileName); + if (!existsSync(file)) return null; + return { rec, file }; +} + +function ensureReferenceDoc(cw) { + const existing = referenceRecord(cw); + if (existing) return existing; + const fileName = `Reference_S${String(Date.now()).slice(-6)}.${rand(11)}.${rand(3)}.xml`; + const file = path.join(cw.dir, fileName); + writeFileSync(file, '\n \n \n\n', 'utf8'); + const buf = readFileSync(file); + const rec = { + FileId: randomUUID(), FileName: fileName, FileHash: md5(buf), FileSize: buf.length, + FilePath: `${cw.localId}\\${fileName}`, RelativePath: 'Reference.xml', FilePartialState: 0, + }; + cw.json.CoursewareFiles.push(rec); + return { rec, file }; +} + +function mergeReferences(cw, items) { + const ref = ensureReferenceDoc(cw); + let xml = readText(ref.file); + const have = new Set([...xml.matchAll(/([0-9a-fA-F]{32})<\/Id>/g)].map(m => m[1].toLowerCase())); + const add = []; + for (const it of items) { + const id = String(it.id).toLowerCase(); + if (have.has(id)) continue; + have.add(id); + add.push(it); + } + if (!add.length) return { added: 0 }; + const block = add.map(it => [ + ' ', + ` ${it.id}`, + ` ${it.target}`, + ` ${it.hash}`, + ' ', + ].join('\n')).join('\n'); + if (!xml.includes(' ')) return { added: 0, warning: 'Reference.xml 结构异常,未写入资源关系' }; + xml = xml.replace(' ', `${block}\n `); + writeFileSync(ref.file, xml, 'utf8'); + saveSlideRecord(cw, ref.rec, ref.file); + return { added: add.length }; +} + +export async function copySlides({ + source, target, pages = [], position = null, + reopen = true, sync = false, force = false, backup = true, +} = {}) { + if (!source || !target) throw new Error('需要 source 和 target'); + if (!Array.isArray(pages) || !pages.length) throw new Error('pages 不能为空'); + const src = resolveCourseware(source); + const dst = resolveCourseware(target); + return runEdit(dst, { reopen, sync, force, backup }, async c => { + const srcSlides = slidesInBoardOrder(src); + const dstSlides = slidesInBoardOrder(c); + const picked = pages.map(n => { + const s = srcSlides[n - 1]; + if (!s) throw new Error(`源课件没有第 ${n} 页(共 ${srcSlides.length} 页)`); + return s; + }); + + const at = position == null ? dstSlides.length : Math.max(0, Math.min(dstSlides.length, Number(position))); + const ts = String(Date.now()).slice(-4); + const copied = []; + const warnings = []; + const refItems = []; + + for (const s of picked) { + let xml = regenerateIds(s.xml); + const newFile = `Slide_${dstSlides.length + copied.length}_S${ts}.${rand(11)}.${rand(3)}.xml`; + writeFileSync(path.join(c.dir, newFile), xml, 'utf8'); + const buf = readFileSync(path.join(c.dir, newFile)); + const newId = slideXmlId(xml); + copied.push({ + id: newId, + rec: { + FileId: randomUUID(), FileName: newFile, FileHash: md5(buf), FileSize: buf.length, + FilePath: `${c.localId}\\${newFile}`, RelativePath: '', FilePartialState: 0, + }, + }); + + // 复制这一页引用的图片/音频资源,并登记到 Reference.xml + for (const rid of resourceRefs(xml)) { + const srec = src.json.CoursewareFiles.find(f => { + const n = f.FileName.toLowerCase(); + return n === rid || n.startsWith(rid + '.'); + }); + if (!srec) { warnings.push(`第 ${s.page} 页引用的资源 ${rid} 在源课件索引里找不到`); continue; } + const relPath = String(srec.RelativePath).replace(/\//g, '\\'); + refItems.push({ id: rid, target: relPath, hash: srec.FileHash }); + const exists = c.json.CoursewareFiles.some( + f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === relPath.toLowerCase(), + ); + const srcFile = path.join(src.dir, srec.FileName); + const dstFile = path.join(c.dir, srec.FileName); + if (!existsSync(srcFile)) { warnings.push(`资源文件不存在:${srec.FileName}`); continue; } + if (!existsSync(dstFile) || statSync(dstFile).size !== srec.FileSize) copyFileSync(srcFile, dstFile); + if (exists) continue; + c.json.CoursewareFiles.push({ + FileId: randomUUID(), FileName: srec.FileName, FileHash: srec.FileHash, FileSize: srec.FileSize, + FilePath: `${c.localId}\\${srec.FileName}`, RelativePath: srec.RelativePath, FilePartialState: 0, + }); + } + } + + // 重排页序:目标原页 + 插入页 + const merged = [...dstSlides.slice(0, at), ...copied, ...dstSlides.slice(at)]; + const nonSlides = c.json.CoursewareFiles.filter(f => !isSlidePath(f.RelativePath)); + merged.forEach((s, i) => { + s.rec.RelativePath = `Slides\\Slide_${i}.xml`; + s.rec.FilePath = `${c.localId}\\${s.rec.FileName}`; + }); + c.json.CoursewareFiles = [...nonSlides, ...merged.map(s => s.rec)]; + + // 更新 Board.xml 页序 + const board = readBoard(c); + const newBoardXml = board.xml.replace(/[\s\S]*?<\/Slides>/, + '\n' + merged.map(s => ` ${s.id}`).join('\n') + '\n '); + writeFileSync(board.file, newBoardXml, 'utf8'); + saveSlideRecord(c, board.rec, board.file); + + const refResult = mergeReferences(c, refItems); + if (refResult.warning) warnings.push(refResult.warning); + + return { + courseware: c.name, source: src.name, + insertedAt: at, pages: picked.map(s => s.page), + newPages: merged.map((s, i) => ({ page: i + 1, slideId: s.id })).filter((x, i) => i >= at && i < at + copied.length), + referencesAdded: refResult.added, + warnings, + }; + }); +} + +// ---------------------------------------------------------------- 工具:单独同步 +export async function syncCourseware({ courseware } = {}) { + const cw = resolveCourseware(courseware); + return serial(async () => { + await ensureInit(); + let shell = (await shells()).find(s => sameCourseware(s, cw)); + let opened = false; + if (!shell) { + const id = await openCourseware(cw.name, slideRecords(cw).length); + if (!id) throw new Error(`打开课件「${cw.name}」失败`); + shell = { id }; + opened = true; + } + const text = await syncShell(shell.id); + const info = await mcp('get_current_courseware_info', { shellId: shell.id }, { timeoutMs: 15000 }) + .then(r => r.data ?? null).catch(() => null); + return { + courseware: cw.name, + shellId: shell.id, + opened, + sync: text, + isSynced: info?.isSynced ?? null, + slideCount: info?.slideCount ?? null, + }; + }); +} diff --git a/kit/server.mjs b/kit/server.mjs new file mode 100644 index 0000000..1d3e10b --- /dev/null +++ b/kit/server.mjs @@ -0,0 +1,289 @@ +#!/usr/bin/env node +/** + * seewo-kit MCP server(stdio) + * + * 补希沃自带 MCP 的缺口: + * 动画三件套 · 课件自检 · 备份/恢复 · 跨课件复制页面 · 批量改文字 + * + * 启动方式(OpenCode 配置): + * "seewokit": { "type": "local", "command": ["node", "D:\\Documents\\Default Project\\seewo-anim\\kit\\server.mjs"] } + * + * 写操作内部会:关课件(不保存) → 自动备份 → 改缓存文件 → 更新索引/DB → 重新打开。 + * 前提:目标课件的未同步改动必须已经同步(内存页数/大小与磁盘不一致时会拒绝,除非 force=true)。 + */ +import { createInterface } from 'node:readline'; +import { + setAnimations, getAnimations, clearAnimations, + replaceText, verifyCourseware, backupCourseware, restoreCourseware, copySlides, + listCoursewares, syncCourseware, +} from './core.mjs'; + +const log = (...a) => console.error('[seewo-kit]', ...a); + +const TOOLS = [ + { + name: 'set_animations', + description: + '给页面元素加「点击淡入」等动画(FadeIn/Click 默认 0.3 秒)。只改指定元素,其它元素动画保留。\n' + + '写操作会先关闭目标课件(不保存内存改动)、自动备份、改缓存、重开课件。\n' + + '用 elementIds 或 textMatches 选元素;order 可指定点击顺序(元素 Id 数组)。\n' + + '注意:课件若有未同步的新页/改动会被拒绝,请先同步或传 force=true。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string', description: '课件名片段或 LocalId;不传取最近修改的课件' }, + page: { type: 'integer', minimum: 1, description: '页码(1-based,按 Board.xml 页序)' }, + elementIds: { type: 'array', items: { type: 'string' }, description: '元素 Id(32 位 hex)' }, + textMatches: { type: 'array', items: { type: 'string' }, description: '按文字包含匹配元素;多个命中会报错' }, + matchAll: { type: 'boolean', default: false, description: 'textMatches 命中多个时全部选中' }, + type: { + type: 'string', + enum: ['FadeIn', 'FadeOut', 'WipeIn', 'WipeOut', 'ZoomIn', 'ZoomOut', 'FlyIn', 'FloatIn', 'Appear'], + default: 'FadeIn', + }, + trigger: { type: 'string', enum: ['Click', 'WithPrevious', 'AfterPrevious'], default: 'Click' }, + duration: { type: 'number', default: 0.3, description: '秒' }, + delay: { type: 'number', default: 0, description: '秒' }, + order: { type: 'array', items: { type: 'string' }, description: '点击顺序(元素 Id 数组),可选' }, + reopen: { type: 'boolean', default: true, description: '改完重新打开课件' }, + sync: { type: 'boolean', default: false, description: '重开后立即云同步' }, + force: { type: 'boolean', default: false, description: '忽略未同步检查(会丢内存里未保存的改动)' }, + backup: { type: 'boolean', default: true, description: '改动前自动备份' }, + }, + required: ['page'], + }, + }, + { + name: 'get_animations', + description: '读取某页的动画:每个动画的类型/触发方式/时长/延迟/点击顺序,以及 AnimationOrders 的一致性问题。只读。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string', description: '课件名片段或 LocalId' }, + page: { type: 'integer', minimum: 1, description: '页码(1-based)' }, + }, + required: ['page'], + }, + }, + { + name: 'clear_animations', + description: + '清除动画:传 elementIds 只清这些元素;不传则清整页;allPages=true 清全部页面。\n' + + '会同步重建 AnimationOrders。写操作流程同 set_animations。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + allPages: { type: 'boolean', default: false }, + elementIds: { type: 'array', items: { type: 'string' } }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + }, + }, + { + name: 'replace_text', + description: + '批量修改某页文本内容(希沃自带 edit_text_element 不能改文字)。\n' + + 'replacements 每项:{ elementId 或 find, text 或 (find+replace), width? }\n' + + '· text:整段替换(要求该元素只有一个不同文本片段)\n' + + '· find+replace:子串替换,必须命中\n' + + '· width:可选,传了就按「固定框宽 + 单行折行」重排(适合正文 1160)\n' + + '会更新 折行缓存,避免重开后按旧折行显示。写操作流程同 set_animations。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + replacements: { + type: 'array', + items: { + type: 'object', + properties: { + elementId: { type: 'string' }, + find: { type: 'string' }, + replace: { type: 'string' }, + text: { type: 'string' }, + width: { type: 'number' }, + }, + }, + }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + required: ['page', 'replacements'], + }, + }, + { + name: 'verify_courseware', + description: + '课件自检(只读):页数、Board.xml 页序、索引与磁盘文件的 MD5/大小、重复 Id、图片资源引用、' + + 'DB 里的 Revision/行数是否一致、孤儿文件。返回 { ok, issues[] }。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + hashes: { type: 'boolean', default: true, description: '是否逐文件校验 MD5(大课件会慢一点)' }, + deep: { type: 'boolean', default: true, description: '是否跨页检查重复元素 Id' }, + }, + }, + }, + { + name: 'backup_courseware', + description: '把课件的全部缓存文件 + 索引 JSON + DB 行快照到临时目录,返回 backupId(可用于 restore_courseware)。只读不改课件。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + note: { type: 'string', description: '备注,写进 manifest' }, + }, + }, + }, + { + name: 'restore_courseware', + description: + '从 backup_courseware 的快照恢复(覆盖当前缓存文件与索引/DB)。必须传 confirm=true。\n' + + '恢复是本地操作:Revision 会比当前值再 +1,不会自动上传;需要时传 sync=true。', + inputSchema: { + type: 'object', + properties: { + backupId: { type: 'string', description: 'backup_courseware 返回的 backupId' }, + courseware: { type: 'string', description: '覆盖到哪份课件;默认用备份里的 LocalId' }, + confirm: { type: 'boolean', description: '必须为 true' }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + }, + required: ['backupId', 'confirm'], + }, + }, + { + name: 'copy_slides', + description: + '把源课件的指定页复制到目标课件(可跨课件),保留图片/音频等资源、动画和备注。\n' + + 'position:插入到目标第几页之后(0=最前面,不传=末尾)。\n' + + '会重建目标课件的 Board.xml 页序、索引和 DB;复制页的页面/元素/动画 Id 全部重新生成,避免冲突。\n' + + '写操作流程同 set_animations(自动备份 + 重开)。', + inputSchema: { + type: 'object', + properties: { + source: { type: 'string', description: '源课件名片段或 LocalId' }, + target: { type: 'string', description: '目标课件名片段或 LocalId' }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 }, description: '源课件页码(按页序)' }, + position: { type: 'integer', minimum: 0, description: '插入到目标第几页之后,0=最前,不传=末尾' }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + required: ['source', 'target', 'pages'], + }, + }, + { + name: 'list_coursewares', + description: '列出本地缓存里的课件(名称、LocalId、页数、Revision),排错时用。只读。', + inputSchema: { type: 'object', properties: {} }, + }, + { + name: 'sync_courseware', + description: + '只做云同步,不改内容:课件没开会先打开,然后做一次无害改动(加页+删页)让希沃认为「有更新」,再上传。\n' + + '用于把本地 Revision 脏状态清干净,或把本地改动推上云。返回同步结果与 isSynced。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string', description: '课件名片段或 LocalId' }, + }, + }, + }, +]; + +const HANDLERS = { + set_animations: setAnimations, + get_animations: getAnimations, + clear_animations: clearAnimations, + replace_text: replaceText, + verify_courseware: verifyCourseware, + backup_courseware: backupCourseware, + restore_courseware: restoreCourseware, + copy_slides: copySlides, + sync_courseware: syncCourseware, + list_coursewares: () => { + const all = listCoursewares(); + let dbCountHint = null; + return { + dbCountHint, + coursewares: all.slice(0, 50).map(c => ({ + name: c.name, + localId: c.localId, + pages: (c.json.CoursewareFiles || []).filter(f => /^Slides[\\/]Slide_\d+\.xml$/i.test(f.RelativePath)).length, + revision: c.json.Courseware.Revision, + syncedRevision: c.json.Courseware.SyncedRevision, + size: c.json.Courseware.Size, + modified: new Date(c.mtime).toISOString(), + })), + }; + }, +}; + +function send(msg) { + process.stdout.write(JSON.stringify(msg) + '\n'); +} + +async function handle(msg) { + const { id, method, params = {} } = msg; + if (method === 'initialize') { + return send({ + jsonrpc: '2.0', id, + result: { + protocolVersion: params.protocolVersion || '2025-06-18', + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: 'seewo-kit', version: '1.0.0' }, + }, + }); + } + if (method === 'notifications/initialized' || !('id' in msg)) return; + if (method === 'ping') return send({ jsonrpc: '2.0', id, result: {} }); + if (method === 'tools/list') return send({ jsonrpc: '2.0', id, result: { tools: TOOLS } }); + if (method === 'tool.call') { /* 有些客户端用这个别名 */ } + if (method === 'tools/call') { + const name = params.name; + const fn = HANDLERS[name]; + if (!fn) { + return send({ jsonrpc: '2.0', id, error: { code: -32602, message: `未知工具:${name}` } }); + } + try { + const out = await fn(params.arguments ?? {}); + return send({ + jsonrpc: '2.0', id, + result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] }, + }); + } catch (e) { + log(name, '失败:', e.stack || e.message); + return send({ + jsonrpc: '2.0', id, + result: { content: [{ type: 'text', text: '错误:' + (e.message || String(e)) }], isError: true }, + }); + } + } + send({ jsonrpc: '2.0', id, error: { code: -32601, message: `不支持的方法:${method}` } }); +} + +const rl = createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', line => { + const s = line.trim(); + if (!s) return; + let msg; + try { msg = JSON.parse(s); } catch (e) { log('坏消息:', s.slice(0, 200)); return; } + handle(msg).catch(e => { + log('处理失败:', e.stack || e.message); + if ('id' in msg) send({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: String(e.message || e) } }); + }); +}); +rl.on('close', () => process.exit(0)); +log('ready'); diff --git a/measure.ps1 b/measure.ps1 new file mode 100644 index 0000000..c618eed --- /dev/null +++ b/measure.ps1 @@ -0,0 +1,20 @@ +param([string]$InFile, [string]$OutFile, [double]$Size = 28, [string]$Font = "Microsoft YaHei") +# 用 WPF 的 FormattedText 量文字宽度(希沃白板也是 WPF,度量一致) +Add-Type -AssemblyName PresentationCore +Add-Type -AssemblyName WindowsBase +$tf = New-Object System.Windows.Media.Typeface($Font) +$items = Get-Content $InFile -Encoding UTF8 -Raw | ConvertFrom-Json +$res = @{} +foreach ($p in $items.PSObject.Properties) { + $ft = New-Object System.Windows.Media.FormattedText( + [string]$p.Value, + [System.Globalization.CultureInfo]::GetCultureInfo("zh-CN"), + [System.Windows.FlowDirection]::LeftToRight, + $tf, + $Size, + [System.Windows.Media.Brushes]::Black, + 1.0) + $res[$p.Name] = $ft.WidthIncludingTrailingWhitespace +} +$res | ConvertTo-Json -Depth 3 | Set-Content $OutFile -Encoding UTF8 +Write-Output "measured $($res.Count)" diff --git a/seewo-anim.mjs b/seewo-anim.mjs new file mode 100644 index 0000000..40f9f30 --- /dev/null +++ b/seewo-anim.mjs @@ -0,0 +1,590 @@ +#!/usr/bin/env node +/** + * seewo-anim —— 给希沃白板 5 课件加「点击淡入」动画(逆向版) + * + * 原理:希沃 MCP 没有动画接口,但动画数据就写在本地保存文件里: + * \<账号>\Courseware\<课件Id>\Slide__<...>.xml + * · 元素内:FadeInClick… + * · 页面末:动画Id… + * 所以:关课件 → 改 XML(顺便更新索引里的 MD5 / 文件大小)→ 重开课件。 + * 重开后希沃会把动画读进内存,保存/同步时也原样写回云端。 + * + * 命令: + * list --slide 2 列出某页的文本元素(id、位置、文字、是否已加动画) + * set --slide 2 --ids id1,id2 给已有元素加动画(只动这几个元素,其它动画保留) + * clear --slide 2 --all 清掉某页所有动画;或 --ids a,b 只清这几个 + * fix --slide 2 [--width 1160] 把 MCP 新建页的文本块规范成固定框宽 + 单行折行 + * answers --plan plan.json 重建空位宽度 + 生成答案框 + 逐个点击淡入 + * + * 通用参数: + * --courseware <名字片段> 不传则用最近改动的课件 + * --type FadeIn 动画类型(FadeIn/FadeOut/WipeIn/ZoomIn…) + * --trigger Click Click / WithPrevious / AfterPrevious + * --duration 0.3 秒 + * --delay 0 秒 + * --fontSize 28 答案字号(answers) + * --color #C0392B 答案文字颜色(answers) + * --width 1160 fix 的正文框宽(fix) + * --minY 90 fix 只处理 y ≥ 该值的文本块(fix,默认 90 即正文行) + * --sync 重开后触发云同步 + * --no-reopen 只改文件,不重开课件 + * + * plan.json 格式: + * { "2": [ { "line": "<32位元素Id>", "answers": ["打制"] }, + * { "line": "<32位元素Id>", "answers": ["商鞅变法","356","重农抑商"] } ] } + * · 行的文字里用 4 个以上下划线表示空位,答案按出现顺序对应 + * · 空位不够宽时会自动加宽(保证答案不压到别的字) + * · 可选 "base": "整行新文字" 强制替换该行原文(改措辞时用) + */ +import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from 'node:fs'; +import { createHash, randomBytes } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import path from 'node:path'; +import os from 'node:os'; +import { fileURLToPath } from 'node:url'; + +const SELF = path.dirname(fileURLToPath(import.meta.url)); +const MCP_PORT = process.env.SEEWO_MCP_PORT || '7916'; +const APP_DIR = path.join(os.homedir(), 'AppData', 'Roaming', 'Seewo', 'EasiNote5', 'Data'); +const TMP = path.join(os.tmpdir(), 'opencode'); +if (!existsSync(TMP)) throw new Error('临时目录不存在:' + TMP); + +// ---------------------------------------------------------------- 参数 +const argv = process.argv.slice(2); +const command = argv[0]; +const opt = {}; +for (let i = 1; i < argv.length; i++) { + const a = argv[i]; + if (!a.startsWith('--')) continue; + const k = a.slice(2); + const next = argv[i + 1]; + if (next && !next.startsWith('--')) { opt[k] = next; i++; } else opt[k] = true; +} +if (!command) { + console.log(readFileSync(new URL(import.meta.url), 'utf8').match(/\/\*\*([\s\S]*?)\*\//)[1].replace(/^ \* ?/gm, '').trim()); + process.exit(0); +} + +// ---------------------------------------------------------------- MCP +let sessionId = null; +async function post(body) { + const h = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }; + if (sessionId) h['Mcp-Session-Id'] = sessionId; + const res = await fetch(`http://127.0.0.1:${MCP_PORT}/mcp`, { method: 'POST', headers: h, body: JSON.stringify(body) }); + if (!sessionId) sessionId = res.headers.get('mcp-session-id'); + const text = await res.text(); + if (text.includes('data:')) { + const data = text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join(''); + try { return JSON.parse(data); } catch { return { raw: data }; } + } + try { return JSON.parse(text); } catch { return { raw: text }; } +} +let rpcId = 3; +async function mcp(name, args = {}) { + const r = await post({ jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }); + if (r.error) throw new Error(`${name}: ${JSON.stringify(r.error)}`); + const txt = (r.result?.content ?? []).filter(c => c.type === 'text').map(c => c.text).join('\n'); + if (r.result?.isError) throw new Error(`${name}: ${txt}`); + return { text: txt, data: r.result?.structuredContent }; +} +async function mcpInit() { + await post({ jsonrpc: '2.0', id: 0, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-anim', version: '1.0' } } }); + await post({ jsonrpc: '2.0', method: 'notifications/initialized' }); +} +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const shells = () => mcp('en_find_shells', { searchingMode: 'All' }).then(r => r.data?.shells ?? []).catch(() => []); + +async function closeCourseware() { + for (let i = 0; i < 20; i++) { + const s = await shells(); + if (!s.length) return true; + await mcp('close_current_courseware', { shellId: s[0].id, syncBeforeClose: false }).catch(() => {}); + await sleep(700); + } + return (await shells()).length === 0; +} + +async function openCourseware(name) { + await mcp('open_cloud_courseware', { coursewareName: name }); + for (let i = 0; i < 40; i++) { + await sleep(700); + const s = await shells(); + if (s.length) return s[0].id; + } + return null; +} + +/** 做一次无害改动,让希沃认为课件「未同步」,否则 sync 只会下载 */ +async function touch(shellId) { + const info = await mcp('get_current_courseware_info', { shellId }); + const count = info.data?.slideCount ?? 0; + const add = await mcp('add_slide', { shellId, slideNumber: count }).catch(() => null); + if (add?.data?.slideNumber) await mcp('delete_slide', { shellId, slideNumber: add.data.slideNumber }).catch(() => {}); +} + +// ---------------------------------------------------------------- 课件定位 +function findCoursewares() { + const out = []; + for (const user of existsSync(APP_DIR) ? readdirSync(APP_DIR) : []) { + const root = path.join(APP_DIR, user, 'Courseware'); + if (!existsSync(root)) continue; + for (const id of readdirSync(root)) { + const dir = path.join(root, id); + const jp = path.join(dir, `${id}.json`); + if (!existsSync(jp)) continue; + try { + const json = JSON.parse(readFileSync(jp, 'utf8').replace(/^\uFEFF/, '')); + out.push({ dir, jsonPath: jp, json, name: json.Courseware?.Name ?? '', mtime: statSync(jp).mtimeMs }); + } catch { /* skip */ } + } + } + return out.sort((a, b) => b.mtime - a.mtime); +} + +function pickCourseware() { + const all = findCoursewares(); + if (!all.length) throw new Error('找不到本地课件缓存'); + if (!opt.courseware) return all[0]; + const hit = all.find(c => c.name.includes(opt.courseware)); + if (!hit) throw new Error(`没有名字含「${opt.courseware}」的课件。可选:${all.map(c => c.name).join(' / ')}`); + return hit; +} + +function slideRecord(cw, n) { + const rec = cw.json.CoursewareFiles.find(f => f.RelativePath === `Slides\\Slide_${n - 1}.xml`); + if (!rec) throw new Error(`课件里没有第 ${n} 页`); + return { rec, file: path.join(cw.dir, rec.FileName) }; +} + +// ---------------------------------------------------------------- XML 工具 +const blockRange = (lines, elementId) => { + const idIdx = lines.findIndex(l => l.trim() === `${elementId}`); + if (idIdx < 0) return null; + let start = idIdx; + while (start >= 0 && !/^ {4}<[A-Za-z]+>\s*$/.test(lines[start])) start--; + if (start < 0) return null; + const tag = lines[start].trim().replace(/[<>]/g, ''); + let end = idIdx; + while (end < lines.length && lines[end].trim() !== ``) end++; + return { start, end, tag }; +}; + +const elementText = (body) => { + const cands = [...body.matchAll(/([^<]*)<\/Text>/g)].map(m => m[1]).filter(t => t.trim()); + cands.sort((a, b) => b.length - a.length); + return cands[0] ?? ''; +}; + +const listElements = (lines) => { + const out = []; + lines.forEach((l, i) => { + if (!/^ {4}<[A-Za-z]+>\s*$/.test(l)) return; + const tag = l.trim().replace(/[<>]/g, ''); + let k = i + 1; + while (k < lines.length && lines[k].trim() !== ``) k++; + const body = lines.slice(i + 1, k).join('\n'); + const id = body.match(/([0-9a-f]{32})<\/Id>/)?.[1]; + if (!id) return; + out.push({ + id, type: tag, body, + x: Number(body.match(/([^<]*)<\/X>/)?.[1]), + y: Number(body.match(/([^<]*)<\/Y>/)?.[1]), + w: Number(body.match(/([^<]*)<\/Width>/)?.[1]), + text: elementText(body), + animated: body.includes(''), + }); + }); + return out; +}; + +const animNode = (id, o) => [ + ' ', + ' ', + ` ${o.type}`, + ` ${id}`, + ' 1', + ' Appearance', + ` ${o.trigger}`, + ' ', + ` ${Math.round(o.duration * 10000000)}`, + ` ${Math.round(o.delay * 10000000)}`, + ' 1', + ' 0', + ' 1', + ' 0', + ' 1', + ' ', + ' ', +]; + +/** + * 把文本块的排版信息改写成「固定框宽 + 单行折行」: + * MCP 新建的文本会把折行结果写进 ,且 SizeToContent=Height; + * 只改 而不动这里,重开课件仍按旧折行位置渲染,看着像文字串行。 + */ +function collapseLines(block, text) { + const n = [...text].length; + const sc = block.findIndex(l => //.test(l)); + if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*Manual<'); + const ls = block.findIndex(l => l.trim() === ''); + if (ls >= 0) { + let le = ls; + while (le < block.length && block[le].trim() !== '') le++; + block.splice(ls + 1, le - ls - 1, + ' ', + ' 0', + ` ${n}`, + ' '); + return; + } + for (let i = 0; i < block.length; i++) { + const m = block[i].match(/^(\s*)\d+<\/Length>$/); + if (m) { block[i] = `${m[1]}${n}`; break; } + } +} + +function stripAnimations(lines) { + const out = []; + for (let i = 0; i < lines.length; i++) { + const t = lines[i].trim(); + if (t === '' || t === '') { + const close = t.replace('<', ':先删旧的,再按元素在页面里的先后重新排 */ +function rebuildOrders(lines) { + const oStart = lines.findIndex(l => l.trim() === ''); + if (oStart >= 0) { + let oEnd = oStart; + while (oEnd < lines.length && lines[oEnd].trim() !== '') oEnd++; + lines.splice(oStart, oEnd - oStart + 1); + } + const ids = []; + for (const el of listElements(lines)) { + const m = el.body.match(/[\s\S]*?([0-9a-f]{32})<\/Id>/); + if (m) ids.push(m[1]); + } + if (!ids.length) return ids; + const closeIdx = lines.map(l => l.trim()).lastIndexOf(''); + lines.splice(closeIdx, 0, ' ', ...ids.map(x => ` ${x}`), ' '); + return ids; +} + +/** 给一个元素写动画:先删它自己原有的 ,再插新的。返回 {animId, replaced} */ +function addAnimationToElement(lines, elementId, o) { + const r = blockRange(lines, elementId); + if (!r) return null; + const block = lines.slice(r.start, r.end + 1); + let replaced = 0; + const a = block.findIndex(l => l.trim() === ''); + if (a >= 0) { + let b = a; + while (b < block.length && block[b].trim() !== '') b++; + replaced = 1; + block.splice(a, b - a + 1); + } + const animId = randomBytes(16).toString('hex'); + let at = block.findIndex(l => l.trim() === ''); + if (at < 0) at = block.findIndex(l => l.trim() === ''); + if (at < 0) at = block.length - 1; + block.splice(at, 0, ...animNode(animId, o)); + lines.splice(r.start, r.end - r.start + 1, ...block); + return { animId, replaced }; +} + +// ---------------------------------------------------------------- 量字 +function measure(strings) { + const inFile = path.join(TMP, 'seewo_measure_in.json'); + const outFile = path.join(TMP, 'seewo_measure_out.json'); + const map = {}; + strings.forEach((s, i) => { map[`s${i}`] = s; }); + writeFileSync(inFile, JSON.stringify(map, null, 1), 'utf8'); + execFileSync('powershell', ['-ExecutionPolicy', 'Bypass', '-File', path.join(SELF, 'measure.ps1'), '-InFile', inFile, '-OutFile', outFile], { stdio: 'ignore' }); + const w = JSON.parse(readFileSync(outFile, 'utf8').replace(/^\uFEFF/, '')); + return strings.map((_, i) => w[`s${i}`]); +} + +// ---------------------------------------------------------------- 保存 +function saveSlide(cw, rec, file) { + rec.FileHash = createHash('md5').update(readFileSync(file)).digest('hex'); + rec.FileSize = statSync(file).size; +} +function bumpRevision(cw) { + cw.json.Courseware.Revision = (cw.json.Courseware.Revision ?? 0) + 1; + writeFileSync(cw.jsonPath, JSON.stringify(cw.json, null, 2), 'utf8'); +} + +// ---------------------------------------------------------------- 主流程 +const animOpts = () => ({ + type: opt.type ?? 'FadeIn', + trigger: ['Click', 'WithPrevious', 'AfterPrevious'].includes(opt.trigger) ? opt.trigger : 'Click', + duration: Number(opt.duration ?? 0.3), + delay: Number(opt.delay ?? 0), +}); + +async function main() { + const cw = pickCourseware(); + + if (command === 'list') { + const n = Number(opt.slide ?? 1); + const { file } = slideRecord(cw, n); + const els = listElements(readFileSync(file, 'utf8').split(/\r?\n/)).filter(e => e.type === 'Text'); + console.log(JSON.stringify({ courseware: cw.name, slide: n, elements: els.map(({ body, ...e }) => e) }, null, 2)); + return; + } + + if (command === 'set' || command === 'clear') { + const n = Number(opt.slide ?? 1); + const ids = String(opt.ids ?? '').split(',').map(s => s.trim()).filter(Boolean); + if (command === 'set' && !ids.length) throw new Error('set 需要 --ids id1,id2'); + if (command === 'clear' && !opt.all && !ids.length) throw new Error('clear 需要 --all 或 --ids'); + await mcpInit(); + await closeCourseware(); + const { rec, file } = slideRecord(cw, n); + const eol = readFileSync(file, 'utf8').includes('\r\n') ? '\r\n' : '\n'; + let lines = readFileSync(file, 'utf8').split(/\r?\n/); + + const before = [...readFileSync(file, 'utf8').matchAll(//g)].length; + let added = 0; + let replaced = 0; + const missing = []; + if (command === 'clear') { + // 只删指定元素(或不传 --ids 时删整页)的动画,其它元素不动 + if (opt.all) { + lines = stripAnimations(lines); + } else { + for (const id of ids) { + const r = blockRange(lines, id); + if (!r) { missing.push(id); continue; } + const block = lines.slice(r.start, r.end + 1); + const a = block.findIndex(l => l.trim() === ''); + if (a >= 0) { + let b = a; + while (b < block.length && block[b].trim() !== '') b++; + block.splice(a, b - a + 1); + lines.splice(r.start, r.end - r.start + 1, ...block); + } + } + } + } else { + for (const id of ids) { + const res = addAnimationToElement(lines, id, animOpts()); + if (res) { added++; replaced += res.replaced; } else missing.push(id); + } + } + const orders = rebuildOrders(lines); + writeFileSync(file, lines.join(eol), 'utf8'); + saveSlide(cw, rec, file); + bumpRevision(cw); + const report = { + courseware: cw.name, slide: n, + added, replaced, missing, + animations: `${before} → ${orders.length}`, + }; + if (!opt['no-reopen']) report.shellId = await openCourseware(cw.name); + if (opt.sync && report.shellId) { + await touch(report.shellId); + report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; + } + console.log(JSON.stringify(report, null, 2)); + return; + } + + if (command === 'fix') { + // 把 MCP 新建页的文本块从「按内容自适应」改成「固定框宽 + 单行折行」 + const pages = String(opt.slide ?? 1).split(',').map(s => Number(s.trim())).filter(Boolean); + const WIDTH = Number(opt.width ?? 1160); + const minY = Number(opt.minY ?? 90); + const only = String(opt.ids ?? '').split(',').map(s => s.trim()).filter(Boolean); + if (!opt['no-reopen']) { await mcpInit(); await closeCourseware(); } + const report = { courseware: cw.name, width: WIDTH, slides: {} }; + + for (const n of pages) { + const { rec, file } = slideRecord(cw, n); + const eol = readFileSync(file, 'utf8').includes('\r\n') ? '\r\n' : '\n'; + const lines = readFileSync(file, 'utf8').split(/\r?\n/); + + const targets = listElements(lines) + .filter(e => e.type === 'Text') + .filter(e => (only.length ? only.includes(e.id) : e.y >= minY)); + const missing = only.filter(id => !targets.some(e => e.id === id)); + let fixed = 0; + for (const el of targets) { + const r = blockRange(lines, el.id); + if (!r) { missing.push(el.id); continue; } + const block = lines.slice(r.start, r.end + 1); + const wi = block.findIndex(l => /^\s*[^<]*<\/Width>$/.test(l)); + if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}${WIDTH}`; + collapseLines(block, el.text); + lines.splice(r.start, r.end - r.start + 1, ...block); + fixed++; + } + writeFileSync(file, lines.join(eol), 'utf8'); + saveSlide(cw, rec, file); + report.slides[n] = { fixed, missing }; + } + bumpRevision(cw); + if (!opt['no-reopen']) report.shellId = await openCourseware(cw.name); + if (opt.sync && report.shellId) { + await touch(report.shellId); + report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; + } + console.log(JSON.stringify(report, null, 2)); + return; + } + + if (command === 'answers') { + const planFile = opt.plan; + if (!planFile) throw new Error('缺少 --plan plan.json'); + const plan = JSON.parse(readFileSync(planFile, 'utf8').replace(/^\uFEFF/, '')); + const FONT = Number(opt.fontSize ?? 28); + const COLOR = opt.color ?? '#C0392B'; + const BLANK_RE = /_{4,}/g; + + await mcpInit(); + await closeCourseware(); + + // 先读出每行原文 + const lineInfo = {}; // id -> {text,x,y,slide} + for (const n of Object.keys(plan)) { + const { file } = slideRecord(cw, Number(n)); + const lines = readFileSync(file, 'utf8').split(/\r?\n/); + for (const el of listElements(lines)) { + if (el.type !== 'Text') continue; + lineInfo[el.id] = { ...el, slide: Number(n) }; + } + } + + // 第一轮测量 + const need = []; + for (const [n, rows] of Object.entries(plan)) { + rows.forEach(r => { + const L = lineInfo[r.line]; + if (!L) throw new Error(`第${n}页找不到行 ${r.line}`); + r._base = r.base ?? L.text; + r._blanks = [...r._base.matchAll(BLANK_RE)].map(m => m[0]); + if (r._blanks.length !== r.answers.length) throw new Error(`第${n}页行 ${r.line.slice(0, 6)} 空位 ${r._blanks.length} 个,答案 ${r.answers.length} 个,数量不一致\n文字:${r._base}`); + r.answers.forEach(a => need.push(a)); + need.push(r._blanks[0]); + }); + } + const widths = measure(need); + let p = 0; + for (const [n, rows] of Object.entries(plan)) { + rows.forEach(r => { + r._ansW = r.answers.map(() => widths[p++]); + r._blankW = widths[p++]; + const maxAns = Math.max(...r._ansW); + const per = r._blankW / r._blanks[0].length; + r._nUnder = maxAns > r._blankW ? Math.ceil((maxAns + 16) / per) : r._blanks[0].length; + r._newBlank = '_'.repeat(r._nUnder); + r._finalText = r._base.replace(BLANK_RE, () => r._newBlank); + }); + } + // 第二轮:按最终文本量前缀 + const need2 = []; + for (const [n, rows] of Object.entries(plan)) { + rows.forEach(r => { + let from = 0; + r._prefixW = r.answers.map(() => 0); + r._prefixes = []; + for (let i = 0; i < r.answers.length; i++) { + const idx = r._finalText.indexOf(r._newBlank, from); + const pre = r._finalText.slice(0, idx); + r._prefixes.push(pre); + need2.push(pre); + from = idx + r._newBlank.length; + } + need2.push(r._newBlank); + }); + } + const w2 = measure(need2); + let q = 0; + for (const [n, rows] of Object.entries(plan)) { + rows.forEach(r => { + r._prefixW = r.answers.map(() => w2[q++]); + r._blankW2 = w2[q++]; + }); + } + + // 写入 + const log = []; + for (const [n, rows] of Object.entries(plan)) { + const { rec, file } = slideRecord(cw, Number(n)); + const orig = readFileSync(file, 'utf8'); + const eol = orig.includes('\r\n') ? '\r\n' : '\n'; + let lines = orig.split(/\r?\n/); + lines = stripAnimations(lines); + + // 1) 改写行文字(加宽空位) + for (const r of rows) { + const L = lineInfo[r.line]; + if (r._finalText === L.text) continue; + const rr = blockRange(lines, r.line); + if (!rr) { log.push(`!! 缺行 ${r.line}`); continue; } + const block = lines.slice(rr.start, rr.end + 1); + const oldTag = `${L.text}`; + const newTag = `${r._finalText}`; + for (let i = 0; i < block.length; i++) if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(newTag); + collapseLines(block, r._finalText); + lines.splice(rr.start, rr.end - rr.start + 1, ...block); + log.push(`第${n}页 行 ${r.line.slice(0, 6)} 空位加宽 ${r._blanks[0].length}→${r._nUnder} 个下划线`); + } + + // 2) 克隆答案元素 + let count = 0; + for (const r of rows) { + const L = lineInfo[r.line]; + const rr = blockRange(lines, r.line); + if (!rr) continue; + const tpl = lines.slice(rr.start, rr.end + 1); + for (let i = 0; i < r.answers.length; i++) { + const ansW = r._ansW[i]; + const x = Math.round((L.x + r._prefixW[i] + Math.max(0, (r._blankW2 - ansW) / 2)) * 10) / 10; + const block = tpl.map(l => l + .replace(/[0-9a-f]{32}<\/Id>/, `${randomBytes(16).toString('hex')}`) + .replace(/[^<]*<\/X>/, `${x}`) + .replace(/[^<]*<\/Y>/, `${L.y}`) + .replace(/[^<]*<\/Width>/, `${Math.round((ansW + 20) * 100) / 100}`) + .replace(/\d+<\/Length>/, `${[...r.answers[i]].length}`) + .replace(/#FF000000/g, '#FF' + COLOR.replace('#', '')) + .replace(/Normal<\/FontWeight>/g, 'Bold') + .replace(/[^<]*<\/Text>/g, `${r.answers[i]}`)); + const at = block.findIndex(l => l.trim() === ''); + const pos = at < 0 ? block.length - 1 : at; + block.splice(pos, 0, ...animNode(randomBytes(16).toString('hex'), animOpts())); + const endElements = lines.map(l => l.trim()).lastIndexOf(''); + lines.splice(endElements, 0, ...block); + count++; + } + } + const orders = rebuildOrders(lines); + writeFileSync(file, lines.join(eol), 'utf8'); + saveSlide(cw, rec, file); + log.push(`第${n}页 新增 ${count} 个答案框,页面动画 ${orders.length} 个`); + } + bumpRevision(cw); + const report = { courseware: cw.name, log }; + if (!opt['no-reopen']) report.shellId = await openCourseware(cw.name); + if (opt.sync && report.shellId) { + await touch(report.shellId); + report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; + if (String(report.sync).includes('下载')) { + await touch(report.shellId); + report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; + } + } + console.log(JSON.stringify(report, null, 2)); + return; + } + + throw new Error(`未知命令:${command}`); +} + +main().catch(e => { console.error(String(e?.message ?? e)); process.exit(1); });