Backup: seewo-kit MCP tools and courseware anim scripts
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,145 @@
|
||||
# seewo-anim · 希沃白板「点击淡入」动画工具
|
||||
|
||||
希沃白板 5 的 MCP 接口里**没有任何动画能力**,但动画数据本身是明文存在课件的本地缓存文件里的。
|
||||
本工具直接改这些文件,于是可以批量做「一开始不显示 → 点一下淡入一个答案」这类效果。
|
||||
|
||||
## 原理
|
||||
|
||||
课件缓存目录(Windows):
|
||||
|
||||
```
|
||||
%APPDATA%\Seewo\EasiNote5\Data\<账号>\Courseware\<课件Id>\
|
||||
├─ <课件Id>.json ← 索引:每页对应哪个 XML 文件、MD5、文件大小、Revision
|
||||
└─ Slide_<页序>_<时间戳>.<随机>.xml ← 每页的完整内容(页序从 0 开始)
|
||||
```
|
||||
|
||||
动画写在两个地方:
|
||||
|
||||
```xml
|
||||
<!-- 1. 元素节点内部(<HasMask> 前面) -->
|
||||
<Animations>
|
||||
<Animation>
|
||||
<Type>FadeIn</Type>
|
||||
<Id>32位hex</Id>
|
||||
<Number>1</Number>
|
||||
<Category>Appearance</Category>
|
||||
<Trigger>Click</Trigger> <!-- 点一下才播 -->
|
||||
<Duration>3000000</Duration> <!-- 单位 100ns,3000000 = 0.3 秒 -->
|
||||
...
|
||||
</Animation>
|
||||
</Animations>
|
||||
|
||||
<!-- 2. 页面末尾(决定点击顺序) -->
|
||||
<AnimationOrders>
|
||||
<Item>32位hex</Item>
|
||||
<Item>32位hex</Item>
|
||||
</AnimationOrders>
|
||||
```
|
||||
|
||||
**关键前提:必须关掉课件再改文件。** 课件开着时希沃把内容放在内存里,关闭时会把内存写回文件,直接改会被覆盖。
|
||||
所以工具的流程固定是:
|
||||
|
||||
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 <id1>,<id2>
|
||||
|
||||
# 换个动画/时长
|
||||
node seewo-anim.mjs set --slide 2 --ids <id> --type WipeIn --duration 0.5 --delay 0.2
|
||||
|
||||
# 清掉整页动画,或只清指定元素
|
||||
node seewo-anim.mjs clear --slide 2 --all
|
||||
node seewo-anim.mjs clear --slide 2 --ids <id>
|
||||
|
||||
# 把 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`,而且会把**当前的折行结果**写进 `<Lines>`。之后如果只改 `<Text>` 内容(比如加宽空位),重开课件时仍按旧折行位置渲染,看起来就像文字串行。
|
||||
|
||||
`fix` 把指定的正文文本块统一改成:
|
||||
|
||||
- `<Width>` = `--width`(默认 1160,与手做页面一致)
|
||||
- `SizeToContent` = `Manual`
|
||||
- `<Lines>` 只留一条 `LineProperty(StartOffset=0, Length=字数)`
|
||||
|
||||
```bash
|
||||
node seewo-anim.mjs fix --slide 5 --width 1160
|
||||
node seewo-anim.mjs fix --slide 5 --ids <id1>,<id2> # 只改指定元素
|
||||
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 文件(文件名带新时间戳、`<Length>` 之类可能被规范化),动画数据本身会保留 —— 已实测多轮往返不丢。
|
||||
|
||||
## 相关:seewo-kit(MCP 版)
|
||||
|
||||
`kit/` 下是把本工具能力接进 MCP 的版本,另外补了课件自检、备份/恢复、跨课件复制页面、
|
||||
批量改文字。注册后可直接在 OpenCode 里调用 `seewokit_*` 工具,无需命令行。
|
||||
详见 [`kit/README.md`](kit/README.md)。
|
||||
|
||||
+232
@@ -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 数组可指定点击顺序;不传按元素在页面中的先后。
|
||||
- 每次都会重建 `<AnimationOrders>`,并校验动画 Id 与顺序表是否一一对应。
|
||||
- 动画时长单位是 100ns:`<Duration>3000000</Duration>` = 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\<localId>-<时间>`。
|
||||
- `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
|
||||
<Reference>
|
||||
<Relationships>
|
||||
<Relationship>
|
||||
<Id>b77212ebd37d398fa47bab8eeefccd1c</Id>
|
||||
<Target>Resources\b77212ebd37d398fa47bab8eeefccd1c.png</Target>
|
||||
<Hash>a460c7aa4832e85b33b7e65ae4a6d2d1</Hash>
|
||||
</Relationship>
|
||||
</Relationships>
|
||||
</Reference>
|
||||
```
|
||||
|
||||
只复制资源文件 + 索引/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`
|
||||
+1271
File diff suppressed because it is too large
Load Diff
+289
@@ -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'
|
||||
+ '会更新 <Lines> 折行缓存,避免重开后按旧折行显示。写操作流程同 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');
|
||||
+20
@@ -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)"
|
||||
+590
@@ -0,0 +1,590 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* seewo-anim —— 给希沃白板 5 课件加「点击淡入」动画(逆向版)
|
||||
*
|
||||
* 原理:希沃 MCP 没有动画接口,但动画数据就写在本地保存文件里:
|
||||
* <Data>\<账号>\Courseware\<课件Id>\Slide_<n>_<...>.xml
|
||||
* · 元素内:<Animations><Animation><Type>FadeIn</Type><Trigger>Click</Trigger>…</Animation></Animations>
|
||||
* · 页面末:<AnimationOrders><Item>动画Id</Item>…</AnimationOrders>
|
||||
* 所以:关课件 → 改 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() === `<Id>${elementId}</Id>`);
|
||||
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() !== `</${tag}>`) end++;
|
||||
return { start, end, tag };
|
||||
};
|
||||
|
||||
const elementText = (body) => {
|
||||
const cands = [...body.matchAll(/<Text>([^<]*)<\/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() !== `</${tag}>`) k++;
|
||||
const body = lines.slice(i + 1, k).join('\n');
|
||||
const id = body.match(/<Id>([0-9a-f]{32})<\/Id>/)?.[1];
|
||||
if (!id) return;
|
||||
out.push({
|
||||
id, type: tag, body,
|
||||
x: Number(body.match(/<X>([^<]*)<\/X>/)?.[1]),
|
||||
y: Number(body.match(/<Y>([^<]*)<\/Y>/)?.[1]),
|
||||
w: Number(body.match(/<Width>([^<]*)<\/Width>/)?.[1]),
|
||||
text: elementText(body),
|
||||
animated: body.includes('<Animations>'),
|
||||
});
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
const animNode = (id, o) => [
|
||||
' <Animations>',
|
||||
' <Animation>',
|
||||
` <Type>${o.type}</Type>`,
|
||||
` <Id>${id}</Id>`,
|
||||
' <Number>1</Number>',
|
||||
' <Category>Appearance</Category>',
|
||||
` <Trigger>${o.trigger}</Trigger>`,
|
||||
' <TriggerSource></TriggerSource>',
|
||||
` <Duration>${Math.round(o.duration * 10000000)}</Duration>`,
|
||||
` <Delay>${Math.round(o.delay * 10000000)}</Delay>`,
|
||||
' <AccelerationRatio>1</AccelerationRatio>',
|
||||
' <DecelerationRatio>0</DecelerationRatio>',
|
||||
' <RepeatBehavior>1</RepeatBehavior>',
|
||||
' <Start>0</Start>',
|
||||
' <End>1</End>',
|
||||
' </Animation>',
|
||||
' </Animations>',
|
||||
];
|
||||
|
||||
/**
|
||||
* 把文本块的排版信息改写成「固定框宽 + 单行折行」:
|
||||
* MCP 新建的文本会把折行结果写进 <Lines>,且 SizeToContent=Height;
|
||||
* 只改 <Text> 而不动这里,重开课件仍按旧折行位置渲染,看着像文字串行。
|
||||
*/
|
||||
function collapseLines(block, text) {
|
||||
const n = [...text].length;
|
||||
const sc = block.findIndex(l => /<SizeToContent>/.test(l));
|
||||
if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*</, '>Manual<');
|
||||
const ls = block.findIndex(l => l.trim() === '<Lines>');
|
||||
if (ls >= 0) {
|
||||
let le = ls;
|
||||
while (le < block.length && block[le].trim() !== '</Lines>') le++;
|
||||
block.splice(ls + 1, le - ls - 1,
|
||||
' <LineProperty>',
|
||||
' <StartOffset>0</StartOffset>',
|
||||
` <Length>${n}</Length>`,
|
||||
' </LineProperty>');
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < block.length; i++) {
|
||||
const m = block[i].match(/^(\s*)<Length>\d+<\/Length>$/);
|
||||
if (m) { block[i] = `${m[1]}<Length>${n}</Length>`; break; }
|
||||
}
|
||||
}
|
||||
|
||||
function stripAnimations(lines) {
|
||||
const out = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const t = lines[i].trim();
|
||||
if (t === '<Animations>' || t === '<AnimationOrders>') {
|
||||
const close = t.replace('<', '</');
|
||||
while (i < lines.length && lines[i].trim() !== close) i++;
|
||||
continue;
|
||||
}
|
||||
out.push(lines[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 重建 <AnimationOrders>:先删旧的,再按元素在页面里的先后重新排 */
|
||||
function rebuildOrders(lines) {
|
||||
const oStart = lines.findIndex(l => l.trim() === '<AnimationOrders>');
|
||||
if (oStart >= 0) {
|
||||
let oEnd = oStart;
|
||||
while (oEnd < lines.length && lines[oEnd].trim() !== '</AnimationOrders>') oEnd++;
|
||||
lines.splice(oStart, oEnd - oStart + 1);
|
||||
}
|
||||
const ids = [];
|
||||
for (const el of listElements(lines)) {
|
||||
const m = el.body.match(/<Animations>[\s\S]*?<Id>([0-9a-f]{32})<\/Id>/);
|
||||
if (m) ids.push(m[1]);
|
||||
}
|
||||
if (!ids.length) return ids;
|
||||
const closeIdx = lines.map(l => l.trim()).lastIndexOf('</Slide>');
|
||||
lines.splice(closeIdx, 0, ' <AnimationOrders>', ...ids.map(x => ` <Item>${x}</Item>`), ' </AnimationOrders>');
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** 给一个元素写动画:先删它自己原有的 <Animations>,再插新的。返回 {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() === '<Animations>');
|
||||
if (a >= 0) {
|
||||
let b = a;
|
||||
while (b < block.length && block[b].trim() !== '</Animations>') b++;
|
||||
replaced = 1;
|
||||
block.splice(a, b - a + 1);
|
||||
}
|
||||
const animId = randomBytes(16).toString('hex');
|
||||
let at = block.findIndex(l => l.trim() === '<HasMask>');
|
||||
if (at < 0) at = block.findIndex(l => l.trim() === '<RotateOrigin>');
|
||||
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(/<Animations>/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() === '<Animations>');
|
||||
if (a >= 0) {
|
||||
let b = a;
|
||||
while (b < block.length && block[b].trim() !== '</Animations>') 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>[^<]*<\/Width>$/.test(l));
|
||||
if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}<Width>${WIDTH}</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 = `<Text>${L.text}</Text>`;
|
||||
const newTag = `<Text>${r._finalText}</Text>`;
|
||||
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(/<Id>[0-9a-f]{32}<\/Id>/, `<Id>${randomBytes(16).toString('hex')}</Id>`)
|
||||
.replace(/<X>[^<]*<\/X>/, `<X>${x}</X>`)
|
||||
.replace(/<Y>[^<]*<\/Y>/, `<Y>${L.y}</Y>`)
|
||||
.replace(/<Width>[^<]*<\/Width>/, `<Width>${Math.round((ansW + 20) * 100) / 100}</Width>`)
|
||||
.replace(/<Length>\d+<\/Length>/, `<Length>${[...r.answers[i]].length}</Length>`)
|
||||
.replace(/#FF000000/g, '#FF' + COLOR.replace('#', ''))
|
||||
.replace(/<FontWeight>Normal<\/FontWeight>/g, '<FontWeight>Bold</FontWeight>')
|
||||
.replace(/<Text>[^<]*<\/Text>/g, `<Text>${r.answers[i]}</Text>`));
|
||||
const at = block.findIndex(l => l.trim() === '<HasMask>');
|
||||
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('</Elements>');
|
||||
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); });
|
||||
Reference in New Issue
Block a user