From ba8d43271b761bbec77267d9166d0ec4b52dcf22 Mon Sep 17 00:00:00 2001 From: wangfar Date: Fri, 13 Nov 2026 09:45:35 +0800 Subject: [PATCH] seewo-kit: add diff/preflight/undo/batch/layout/transition/export/rich-text (27 tools) --- README.md | 12 +- kit/README.md | 163 +++++++- kit/core.mjs | 1017 ++++++++++++++++++++++++++++++++++++++++++++++++ kit/server.mjs | 274 +++++++++++++ 4 files changed, 1460 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4950b89..92a0147 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,8 @@ node seewo-anim.mjs fix --slide 5 --minY 90 # 只改正文行(默认 ## 相关:seewo-kit(MCP 版) `kit/` 下是把本工具能力接进 MCP 的版本,另外补了课件自检、备份/恢复、跨课件复制页面、 -批量改文字、批量改样式、删页/排序、清理重复课件与孤儿文件。目前 17 个工具,注册后可直接在 OpenCode 里调用 +批量改文字、批量改样式、删页/排序、清理重复课件与孤儿文件、课件对比、课前自检、 +跨课件批量、元素排版、页面切换、PNG 导出和段内富文本。目前 27 个工具,注册后可直接在 OpenCode 里调用 `seewokit_*`,无需命令行。 几个特别有用的工具: @@ -156,6 +157,15 @@ node seewo-anim.mjs fix --slide 5 --minY 90 # 只改正文行(默认 - `prune_orphan_files`:默认 `dryRun` 只预览「磁盘上有、索引里没引用」的旧文件, 确认后移进回收目录(清理前自动备份)。 - `remove_local_courseware`:清理同名重复课件,目录进回收站并删 DB 行(不动云端)。 +- `diff_courseware`:对比两份课件,或「某次备份 vs 当前课件」,看文字/样式/动画/切换/位置改了什么。 +- `preflight_courseware`:上课前跑一遍,检查字号、超宽、挖空答案是否可见、动画顺序、页面切换和未同步状态。 +- `undo_last_edit`:一条命令恢复最近一次 kit 写操作前的自动备份(需 `confirm=true`)。 +- `batch_replace_text` / `batch_set_text_style` / `batch_inspect`:跨多份课件批量改字、改样式、检查; + 每份课件各自备份,默认不反复开关课件。 +- `layout_elements`:对齐、等距分布、批量缩放/改尺寸、批量移动,默认跳过锁定元素。 +- `set_slide_transition`:设置/清除页面切换和时长,支持友好别名或原始 `TransitionKey`。 +- `export_slides`:把页面批量导出成 PNG(复用希沃截图);首次截图慢或超时会明确报错,不会留下 0 字节文件。 +- `style_text_range`:段内富文本,只给匹配的一小段文字改字号/加粗/颜色,其余文字样式不变。 详见 [`kit/README.md`](kit/README.md)。 diff --git a/kit/README.md b/kit/README.md index c397ebc..93c4cca 100644 --- a/kit/README.md +++ b/kit/README.md @@ -2,9 +2,9 @@ 希沃自带的 MCP 只有「建页 / 加元素 / 开关课件 / 同步」,缺动画、跨课件复制、改文字、改样式、删页排序、自检这些能力。 `seewo-kit` 是一个独立的 stdio MCP server,直接读写希沃的本地课件缓存,同时复用希沃 MCP 完成 -「关课件 / 开课件 / 云同步」。目前提供 17 个工具。 +「关课件 / 开课件 / 云同步」。目前提供 27 个工具。 -它是 `seewo-anim.mjs`(CLI)的 MCP 化版本,参数语义一致,另外补了 verify / backup / inspect / style / replace / delete / move。 +它是 `seewo-anim.mjs`(CLI)的 MCP 化版本,参数语义一致,另外补了 verify / backup / inspect / style / replace / delete / move / diff / preflight / batch / layout / transition / export / rich-text。 ``` kit/ @@ -51,6 +51,16 @@ kit/ | `prune_orphan_files` | 清理未被索引引用的旧文件(默认只预览,可恢复) | 是 | | `remove_local_courseware` | 移除本地重复课件(目录进回收站 + 删 DB 行) | 是 | | `list_coursewares` | 列出本地缓存课件 | 否 | +| `diff_courseware` | 对比两份课件,或「备份 vs 当前课件」;文字/样式/动画/切换/位置 | 否 | +| `preflight_courseware` | 课前自检:结构 + 字号/超宽/挖空可见/动画顺序/切换/未同步 | 否 | +| `undo_last_edit` | 恢复最近一次 kit 写操作前的自动备份 | 是 | +| `batch_replace_text` | 跨课件批量改文字(每份各自备份) | 是 | +| `batch_set_text_style` | 跨课件批量改样式 | 是 | +| `batch_inspect` | 跨课件批量检查 | 否 | +| `layout_elements` | 对齐 / 等距分布 / 批量缩放 / 批量移动 | 是 | +| `set_slide_transition` | 设置/清除页面切换(含时长) | 是 | +| `export_slides` | 把页面导出成 PNG(复用希沃截图接口) | 否 | +| `style_text_range` | 段内富文本:只改匹配片段的字号/加粗/颜色 | 是 | 公共参数: @@ -58,11 +68,12 @@ kit/ | --- | --- | | `courseware` | 课件名片段或 LocalId;不传取最近修改的课件 | | `page` / `pages` / `allPages` | 单页 / 多页 / 全部页,1-based,按 `Board.xml` 页序 | -| `dryRun` | 只预览改动,不关课件、不写文件(`replace_text` / `set_text_style`) | -| `reopen` | 改完是否重新打开课件,默认 `true` | +| `dryRun` | 只预览改动,不关课件、不写文件(`replace_text` / `set_text_style` / `layout_elements` / `set_slide_transition` / `style_text_range` / 批量文字/样式) | +| `reopen` | 改完是否重新打开课件,默认 `true`;批量工具默认 `false` | | `sync` | 重开后是否云同步,默认 `false` | | `force` | 跳过「未同步改动」检查,默认 `false` | -| `backup` | 改动前是否自动备份,默认 `true` | +| `backup` | 改动前是否自动备份,默认 `true`;`undo_last_edit` 依赖这个自动备份 | +| `timeoutSec` | `export_slides` 单页截图超时,默认 180 秒 | ## 写操作的固定流程 @@ -131,6 +142,107 @@ kit/ - 改字号/宽度后自动重建 `` 折行缓存。 - 建议先 `dryRun: true`,确认 `after` 和 `overflow` 后再写。 +### style_text_range + +只给元素里匹配 `find` 的那一段文字上样式,其余文字保持原样: + +```json +{ "page": 3, "elementIds": ["32位hex"], "find": "中央集权", "bold": true, "color": "#C0392B" } +``` + +- 可选 `fontSize` / `bold` / `color`,至少传一个;`find` 不能为空。 +- 只处理匹配**完整落在单个 `TextRun` 内**的情况。命中后会把这个 Run 拆成「前 / 匹配段 / 后」最多 3 个 Run; + 跨 Run 的匹配会进 `missing` 并说明原因(希沃的富文本没有字符级样式,硬拆容易破坏折行)。 +- 只扫描 `` 里的真实 Run,不会动 `DefaultRunProperty` / `TextMarkerStyle`。 +- 用 `elementIds` / `textMatches` 选元素;都不传则在该页所有文本里找 `find`。 +- 支持 `dryRun`,返回 `runs`(拆出的 Run 数)和 `occurrences`(匹配次数)。 + +### layout_elements + +一个工具覆盖四类排版动作: + +| `action` | 必填 | 说明 | +| --- | --- | --- | +| `align` | `align` | `left` / `hcenter`(`center`) / `right` / `top` / `vcenter`(`middle`) / `bottom` | +| `distribute` | `distribute` | 至少 3 个元素;`horizontal` / `vertical`,按当前包围盒等距分布 | +| `resize` | `scale` 或 `width`/`height` | `anchor: "center"` 时围绕中心缩放,默认左上角不动 | +| `move` | `x`/`y` 或 `dx`/`dy` | 绝对位置和相对偏移可同时用,先绝对后偏移 | + +- 选择器:`elementIds` / `textMatches`(多命中加 `matchAll`)/ `allElements: true`。 +- `relativeTo`:`slide`(页面边缘,可加 `margin`,默认 0)/ `selection`(选中元素的包围盒)/ + `element`(配合 `referenceElementId`)。 +- 默认 `skipLocked: true`,锁定元素会进 `skipped`;返回每项的 `before` / `after`。 +- 只改顶级元素自己的 `X/Y/Width/Height`(6 个空格缩进),不会动 Group 内部子元素。 +- 支持 `page` / `pages` / `allPages` 和 `dryRun`。 + +### set_slide_transition + +- `transition` 支持友好别名:`none` / `dissolve` / `fade` / `slide-left` / `circle-out` / `random-lines`, + 也可以直接传希沃的原始 `TransitionKey`(如 `CircleOut`、`RandomizedLinesHorizontal`)。 +- `duration` 单位秒;不传则保留原时长。底层写 `` 后的 `` + ``(100ns)。 +- `transition: "none"` 只删 ``,不动 ``;要同时改时长就一起传。 +- `inspect_courseware` 每页现在会返回 `transition: { key, duration }`。 +- `page` / `pages` / `allPages`,支持 `dryRun`。 + +### diff_courseware + +两种用法: + +```json +{ "a": "旧版课件", "b": "新版课件" } +{ "backupId": "42578...-20261113-101500", "courseware": "当前课件" } +``` + +- 按 Board 页序逐页比:`texts`(文字)、`styles`(字号/加粗/颜色)、`animations`、`transition`、 + `addedElements` / `removedElements`。 +- 默认不比位置;`includeGeometry: true` 才比 `X/Y/Width/Height`。 +- 默认只返回有变化的页;`includeUnchanged: true` 连没变化的页一起返回。 +- `pages` 可只比指定页码;`maxPages` 默认 300。 +- 返回 `summary`(各类变化计数)和 `same`。备份模式下 A 是备份、B 是当前课件。 + +### preflight_courseware + +课前自检 = `verify_courseware` 的结构检查 + 教学设计检查: + +- 字号是否统一(`expectedFontSize` 默认 28;只查 `y >= bodyMinY` 的正文,默认 90,跳过顶部标题/页眉;传 0 跳过字号检查); +- 文本是否可能超宽(沿用字数估算); +- 挖空答案(`____`)是否没有动画、一开始就能看到;如果正文空位上方有带 FadeIn 的答案文本框覆盖, + 会视为「答案已用独立元素隐藏」,不再误报; +- 动画是否漏进 `AnimationOrders`(会不播放); +- 空页、页面切换覆盖情况(`transitions` / `noTransitionPages`); +- 本地 Revision 是否还没同步。 + +返回 `{ ok, ready, counts, issues[] }`:`ok` 只看 error,`ready` 还要求没有 warning。 +问题按 error → warn → info 排序,适合上课前跑一遍。 + +### undo_last_edit + +- 找到该课件最新一份 `note="auto-before-write"` 的备份并恢复,必须传 `confirm=true`。 +- 只恢复内容,保留当前 `Name` / `RemoteId`(内部走 `restore_courseware(keepIdentity=true)`)。 +- 如果最近一次写操作没有自动备份(`backup: false`),会报错并提示用 `list_backups` 手动选快照。 +- 恢复后 `Revision` 会继续递增;需要上传时再传 `sync=true`。 + +### 批量工具(batch_replace_text / batch_set_text_style / batch_inspect) + +- `coursewares: ["课件A", "课件B"]`,或 `allCoursewares: true` + `filter`(名字/LocalId 片段)。 +- 逐个串行执行,返回 `requested / processed / succeeded / failed / results[]`; + 单项失败默认继续,`stopOnError: true` 才中断。 +- 文字/样式批量默认 `reopen: false`,避免反复开关课件;每份课件各自备份。 +- `dryRun: true` 只读预览,不关课件、不写文件。 +- `batch_inspect` 是只读的 `inspect_courseware` 批量版,适合先看再改。 + +### export_slides + +- 默认导出全部页,或 `page` / `pages` 指定;输出到 + `%TEMP%\opencode\seewo-kit-export\-<时间>`,也可传 `outDir`(绝对路径或相对目录名)。 +- `fileNamePattern` 支持 `{page}`(原页码)和 `{index}`(补零),默认 `slide-01.png`。 +- 直接调用希沃原生 `get_slide_screenshot({ slideNumber, expectedPngImageFilePath })`,不额外调用 + `goto_slide`(少一次渲染等待,也少一个卡死点)。 +- 每页截图前会删掉 0 字节残留;成功标准是文件 ≥ `minBytes`(默认 2048)。 +- `timeoutSec` 默认 180 秒。超时会**停止后续页面**并返回 `ok: false`,同时提示确认希沃窗口在前台、 + 课件已完整加载,必要时重启希沃;不会像以前那样反复重试把界面越拖越死。 +- `retries` 只用于非超时错误(默认 2)。只读,不改课件;导出后课件保持打开。 + ### list_backups - 列出 `%TEMP%\opencode\seewo-kit-backups` 下的快照:`backupId`、时间、备注、页数、Revision、大小。 @@ -318,6 +430,47 @@ MCP 加的元素在 Display 模式下不会被保存;写操作前后尽量让 物理文件名仍是旧的 `Slide_3_Sxxxx.xml`。这是希沃自己的映射方式,`verify_courseware` 也按 `RelativePath` 检查页序,所以不需要重命名文件;重命名反而容易和 DB 的 `FileName` 对不上。 +### 11. 富文本没有字符级样式:只能拆 TextRun + +希沃的一段文字由多个 `` 组成,每个 Run 有自己的字号/加粗/颜色。没有「给第 3 到第 6 个字单独变色」 +这种字符级属性,所以 `style_text_range` 只能: + +1. 找到包含 `find` 的那个 Run; +2. 把 Run 拆成「前 / 匹配 / 后」最多 3 个 Run; +3. 只给中间的 Run 上样式。 + +匹配跨两个 Run 时无法安全拆分(可能破坏折行和项目符号),工具会把它记进 `missing` 并说明原因。 +遇到这种情况,先用 `replace_text` 把那段文字并回一个 Run,或整段改样式。 + +### 12. 截图第一次调用可能很慢,超时后希沃会卡住 + +`get_slide_screenshot` 在刚打开课件、渲染冷启动时可能超过 2 分钟。**超时后不要连续重试**: +希沃的渲染线程可能已经卡住,后续连 `get_current_courseware_info` 都会无响应。实测重启希沃后, +同一页截图约 9 秒完成(12 页、83 个动画的课件)。 + +因此 `export_slides`: + +- 不再调 `goto_slide`,直接让截图接口按 `slideNumber` 取页; +- 超时默认直接停止后续页面,返回 `ok: false` 和明确提示; +- 不把 0 字节文件当成功,会先删掉再重试; +- 可用 `timeoutSec` 调大(例如 300),但建议先确认希沃窗口在前台、课件已完整加载。 + +如果已经卡死:结束 `EasiNote.exe` 再启动即可,磁盘缓存不会损坏(写操作前都关课件,且课件已同步)。 + +### 13. 排版只改顶级元素,锁定元素默认跳过 + +`layout_elements` 用 6 个空格缩进定位元素自己的 `X/Y/Width/Height`。Group 内部的子元素是更深缩进, +不会被误改;移动/缩放 Group 时改的是 Group 的整体包围盒。 + +默认 `skipLocked: true`:带 `True` 的元素(以及内部有锁定子元素的 Group)会进 +`skipped`。要强制排版就传 `skipLocked: false`,但希沃界面里锁定元素通常本来就不该被批量移动。 + +### 14. 对比课件按页序号对齐,不猜内容对应关系 + +`diff_courseware` 按 Board 页序逐页对比;如果中间插页/删页,后面的页会整体错位,报告会显示成大量变化。 +需要精确对比时先用 `pages` 限定范围,或先让两份课件的页序一致。元素按 32 位 Id 对应; +复制页面时 `copy_slides` 会重新生成 Id,所以「复制出来的页」在 diff 里会显示为整页元素新增,这是正常的。 + ## 排错 ```bash diff --git a/kit/core.mjs b/kit/core.mjs index ddd727d..779c3aa 100644 --- a/kit/core.mjs +++ b/kit/core.mjs @@ -337,6 +337,60 @@ function writeBoardOrder(cw, ordered) { saveSlideRecord(cw, board.rec, board.file); } +const TRANSITION_ALIASES = new Map([ + ['none', null], ['无', null], ['clear', null], ['off', null], + ['dissolve', 'Dissolve'], ['溶解', 'Dissolve'], + ['fade', 'Fade'], ['淡入淡出', 'Fade'], + ['slide-left', 'SlideToLeft'], ['slideleft', 'SlideToLeft'], ['向左', 'SlideToLeft'], + ['circle-out', 'CircleOut'], ['circle', 'CircleOut'], ['圆形', 'CircleOut'], + ['random-lines', 'RandomizedLinesHorizontal'], + ['randomized-lines-horizontal', 'RandomizedLinesHorizontal'], + ['randomized-lines', 'RandomizedLinesHorizontal'], +]); + +function resolveTransitionKey(value) { + if (value == null || value === '') return null; + const raw = String(value).trim(); + const lower = raw.toLowerCase(); + if (TRANSITION_ALIASES.has(lower)) return TRANSITION_ALIASES.get(lower); + if (/^[A-Za-z][A-Za-z0-9]*$/.test(raw)) return raw; + throw new Error(`不认识的页面切换:${value}(可传 none / dissolve / fade / slide-left / circle-out / random-lines,或原始 TransitionKey)`); +} + +function slideTransitionOf(lines) { + const key = lines.find(l => /^ [^<]*<\/TransitionKey>$/.test(l)) + ?.match(/([^<]*)<\/TransitionKey>/)?.[1] ?? null; + const raw = lines.find(l => /^ [^<]*<\/Duration>$/.test(l)) + ?.match(/([^<]*)<\/Duration>/)?.[1]; + const ticks = Number(raw); + return { key, duration: Number.isFinite(ticks) ? ticks / 1e7 : null }; +} + +function setSlideTransitionLines(lines, key, durationSec) { + const before = slideTransitionOf(lines); + for (let i = lines.length - 1; i >= 0; i--) { + if (/^ [^<]*<\/TransitionKey>$/.test(lines[i])) lines.splice(i, 1); + } + if (key) { + const e = lines.findIndex(l => l.trim() === ''); + if (e < 0) throw new Error('页面缺少 ,无法写入切换'); + lines.splice(e + 1, 0, ` ${key}`); + } + if (durationSec != null) { + const ticks = Math.round(Number(durationSec) * 1e7); + if (!Number.isFinite(ticks) || ticks < 0) throw new Error('duration 必须是非负数秒'); + const d = lines.findIndex(l => /^ [^<]*<\/Duration>$/.test(l)); + if (d >= 0) lines[d] = ` ${ticks}`; + else { + const t = lines.findIndex(l => /^ /.test(l)); + const at = t >= 0 ? t + 1 : lines.findIndex(l => l.trim() === '') + 1; + if (at <= 0) throw new Error('页面缺少 ,无法写入切换时长'); + lines.splice(at, 0, ` ${ticks}`); + } + } + return { before, after: slideTransitionOf(lines) }; +} + function inspectSlide(slide, { includeAnimations = true } = {}) { const { lines } = readLines(slide.file); const orders = parseOrders(lines); @@ -364,6 +418,7 @@ function inspectSlide(slide, { includeAnimations = true } = {}) { elementCount: elements.length, textCount: textElements.length, animationCount: elements.reduce((a, e) => a + e.animations.length, 0), + transition: slideTransitionOf(lines), fontSizes: [...new Set(textElements.map(e => e.fontSize).filter(Boolean))].sort((a, b) => a - b), clickOrder: orders, warnings: elements.filter(e => e.overflow).map(e => `${e.id} 可能超宽:${e.text.slice(0, 40)}`), @@ -2072,3 +2127,965 @@ export async function removeLocalCourseware({ } }); } + +// ---------------------------------------------------------------- 工具:课件对比 +function coursewarePages(cw) { + return { + label: { + name: cw.name, localId: cw.localId, + pages: slidesInBoardOrder(cw).length, + revision: cw.json.Courseware.Revision, + syncedRevision: cw.json.Courseware.SyncedRevision, + }, + pages: slidesInBoardOrder(cw).map(s => ({ + page: s.page, slideId: s.id, xml: readText(s.file), + })), + }; +} + +function backupPages(backupId) { + const { dir, manifest } = resolveBackup(backupId); + const files = manifest.files + .filter(f => isSlidePath(f.RelativePath)) + .map(f => ({ + ...f, + no: Number(String(f.RelativePath).match(/Slide_(\d+)\.xml$/i)?.[1] ?? 0), + })) + .sort((a, b) => a.no - b.no); + return { + label: { + backupId: manifest.id, name: manifest.name, localId: manifest.localId, + pages: files.length, revision: manifest.revision, + syncedRevision: manifest.syncedRevision, createdAt: manifest.createdAt, + }, + pages: files.map((f, i) => { + const p = path.join(dir, f.FileName); + const xml = existsSync(p) ? readText(p) : ''; + return { page: i + 1, slideId: slideXmlId(xml), xml }; + }), + }; +} + +const numEq = (a, b) => (Number.isFinite(a) && Number.isFinite(b) + ? Math.abs(a - b) < 1e-6 + : a === b); + +function elementSnapshotOf(el) { + return { + elementId: el.id, type: el.type, text: el.text, + fontSize: el.fontSizes[0] ?? null, + bold: el.bold, color: el.color, + x: el.x, y: el.y, w: el.w, h: el.h, + animations: parseAnimations(el.body).map(a => ({ + type: a.type, trigger: a.trigger, duration: a.duration, delay: a.delay, + })), + }; +} + +function diffPage(beforeXml, afterXml, { includeGeometry = false } = {}) { + const a = new Map(listElements(beforeXml.split(/\r?\n/)).map(e => [e.id.toLowerCase(), elementSnapshotOf(e)])); + const b = new Map(listElements(afterXml.split(/\r?\n/)).map(e => [e.id.toLowerCase(), elementSnapshotOf(e)])); + const texts = []; + const styles = []; + const geometry = []; + const animations = []; + for (const [id, x] of a) { + const y = b.get(id); + if (!y) continue; + if (x.text !== y.text) texts.push({ elementId: x.elementId, type: x.type, before: x.text, after: y.text }); + for (const field of ['fontSize', 'bold', 'color']) { + if (x[field] !== y[field]) { + styles.push({ elementId: x.elementId, text: y.text.slice(0, 60), field, before: x[field], after: y[field] }); + } + } + if (includeGeometry) { + for (const field of ['x', 'y', 'w', 'h']) { + if (!numEq(x[field], y[field])) { + geometry.push({ elementId: x.elementId, text: y.text.slice(0, 60), field, before: x[field], after: y[field] }); + } + } + } + const sig = list => list.map(v => `${v.type}/${v.trigger}/${v.duration}/${v.delay}`).join('|'); + if (sig(x.animations) !== sig(y.animations)) { + animations.push({ elementId: x.elementId, text: y.text.slice(0, 60), before: x.animations, after: y.animations }); + } + } + const addedElements = [...b.values()].filter(e => !a.has(e.elementId.toLowerCase())) + .map(e => ({ elementId: e.elementId, type: e.type, text: e.text.slice(0, 80) })); + const removedElements = [...a.values()].filter(e => !b.has(e.elementId.toLowerCase())) + .map(e => ({ elementId: e.elementId, type: e.type, text: e.text.slice(0, 80) })); + const tA = slideTransitionOf(beforeXml.split(/\r?\n/)); + const tB = slideTransitionOf(afterXml.split(/\r?\n/)); + const transition = tA.key !== tB.key || !numEq(tA.duration, tB.duration) ? { before: tA, after: tB } : null; + const changed = !!(texts.length || styles.length || geometry.length || animations.length + || addedElements.length || removedElements.length || transition); + return { + changed, texts, styles, geometry, animations, + addedElements, removedElements, + textCounts: { before: a.size, after: b.size }, + transition, + }; +} + +/** + * 对比两份课件,或「某份备份 vs 当前课件」。 + * pages 可选,只对比指定页码(1-based);默认只返回有变化的页。 + */ +export function diffCourseware({ + a, b, backupId, courseware, pages, maxPages = 300, + includeGeometry = false, includeUnchanged = false, +} = {}) { + let A; + let B; + if (backupId) { + A = backupPages(backupId); + const cw = resolveCourseware(courseware ?? A.label.localId); + B = coursewarePages(cw); + } else { + if (!a || !b) throw new Error('需要 a + b 两份课件,或 backupId(备份 vs 当前课件)'); + A = coursewarePages(resolveCourseware(a)); + B = coursewarePages(resolveCourseware(b)); + } + const only = Array.isArray(pages) && pages.length ? new Set(pages.map(Number)) : null; + const total = Math.min(Math.max(A.pages.length, B.pages.length), Math.max(1, Number(maxPages) || 300)); + const items = []; + const summary = { + comparedPages: total, changedPages: 0, addedPages: 0, removedPages: 0, + textChanges: 0, styleChanges: 0, geometryChanges: 0, + animationChanges: 0, transitionChanges: 0, + addedElements: 0, removedElements: 0, + }; + for (let i = 1; i <= total; i++) { + if (only && !only.has(i)) continue; + const x = A.pages[i - 1]; + const y = B.pages[i - 1]; + if (!x || !y) { + const added = !x && !!y; + if (added) summary.addedPages++; else summary.removedPages++; + items.push({ + page: i, status: added ? 'added' : 'removed', + slideId: { before: x?.slideId ?? null, after: y?.slideId ?? null }, + elementCount: { before: x ? listElements(x.xml.split(/\r?\n/)).length : 0, + after: y ? listElements(y.xml.split(/\r?\n/)).length : 0 }, + firstText: { before: x ? (elementText(x.xml) ?? '').slice(0, 80) : null, + after: y ? (elementText(y.xml) ?? '').slice(0, 80) : null }, + }); + continue; + } + const d = diffPage(x.xml, y.xml, { includeGeometry }); + if (!d.changed && !includeUnchanged) continue; + if (d.changed) summary.changedPages++; + summary.textChanges += d.texts.length; + summary.styleChanges += d.styles.length; + summary.geometryChanges += d.geometry.length; + summary.animationChanges += d.animations.length; + summary.transitionChanges += d.transition ? 1 : 0; + summary.addedElements += d.addedElements.length; + summary.removedElements += d.removedElements.length; + items.push({ + page: i, status: d.changed ? 'changed' : 'same', + slideId: { before: x.slideId, after: y.slideId }, + ...d, + }); + } + const same = !summary.changedPages && !summary.addedPages && !summary.removedPages; + return { + a: A.label, b: B.label, same, pageCountDelta: B.pages.length - A.pages.length, + summary, pages: items, + }; +} + +// ---------------------------------------------------------------- 工具:课前自检 +/** + * 课前自检:在 verify_courseware 的基础上,额外检查 + * 字号是否统一、文本是否超宽、挖空答案是否初始可见、点击动画是否缺顺序、页面切换。 + */ +export function preflightCourseware({ + courseware, expectedFontSize = 28, bodyMinY = 90, hashes = true, deep = true, +} = {}) { + const cw = resolveCourseware(courseware); + const verify = verifyCourseware({ courseware: cw.localId, hashes, deep }); + const issues = verify.issues.map(x => ({ ...x, code: `verify:${x.code}`, source: 'verify' })); + const push = (level, code, message, extra = {}) => issues.push({ level, code, message, source: 'preflight', ...extra }); + + const slides = slidesInBoardOrder(cw); + const transitions = []; + const noTransitionPages = []; + let animationTotal = 0; + + for (const s of slides) { + const info = inspectSlide(s, { includeAnimations: true }); + animationTotal += info.animationCount; + if (info.transition?.key) transitions.push({ page: info.page, key: info.transition.key, duration: info.transition.duration }); + else noTransitionPages.push(info.page); + + if (!info.elementCount) push('warn', 'empty-page', `第 ${info.page} 页没有元素`, { page: info.page }); + + // 挖空页常见做法:正文保留空格,答案用另一个带 FadeIn 的文本框精确盖在空位上。 + // 所以“这一行有空格但自己没动画”不能直接判成答案可见,要看有没有动画元素盖在它上面。 + const animated = info.elements.filter(e => e.animated && e.type === 'Text' + && [e.x, e.y, e.w, e.h].every(Number.isFinite)); + const covers = (a, b) => a.x < b.x + b.w + 12 && a.x + a.w + 12 > b.x + && a.y < b.y + b.h + 12 && a.y + a.h + 12 > b.y; + + for (const el of info.elements) { + if (el.type !== 'Text' || !el.text) continue; + if (expectedFontSize && el.y >= bodyMinY) { + const sizes = (el.fontSizes?.length ? el.fontSizes : [el.fontSize]) + .filter(n => Number.isFinite(n) && n > 1); + const bad = sizes.filter(n => Math.abs(n - Number(expectedFontSize)) > 0.01); + if (bad.length) { + push('warn', 'font-size', `第 ${info.page} 页正文字号不统一:${bad.join('/')}px(期望 ${expectedFontSize}px)`, { + page: info.page, elementId: el.id, text: el.text.slice(0, 60), fontSizes: sizes, + }); + } + } + if (el.overflow) { + push('warn', 'text-overflow', `第 ${info.page} 页文本可能超宽:${el.text.slice(0, 50)}`, { + page: info.page, elementId: el.id, width: el.w, + }); + } + if (el.blank && !el.animated) { + const covered = animated.some(a => a.id !== el.id && covers(a, el)); + if (!covered) { + push('warn', 'blank-visible', `第 ${info.page} 页挖空答案没有动画,可能一开始就能看到:${el.text.slice(0, 50)}`, { + page: info.page, elementId: el.id, + }); + } + } + const noOrder = (el.animations ?? []).filter(x => x.order == null); + if (noOrder.length) { + push('warn', 'animation-order', `第 ${info.page} 页有 ${noOrder.length} 个动画没进 AnimationOrders,不会播放`, { + page: info.page, elementId: el.id, animations: noOrder.map(x => x.id), + }); + } + } + } + + const revision = cw.json.Courseware.Revision; + const syncedRevision = cw.json.Courseware.SyncedRevision; + if (revision !== syncedRevision) { + push('info', 'unsynced', `本地 Revision=${revision},云端 SyncedRevision=${syncedRevision}(本地改动还没上传)`); + } + if (!slides.length) push('error', 'no-pages', '课件没有页面'); + + const 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, + }; + const order = { error: 0, warn: 1, info: 2 }; + issues.sort((x, y) => order[x.level] - order[y.level]); + return { + courseware: cw.name, localId: cw.localId, + ok: counts.errors === 0, + ready: counts.errors === 0 && counts.warnings === 0, + pages: slides.length, revision, syncedRevision, + expectedFontSize: expectedFontSize || null, + bodyMinY, + animationTotal, + transitions, + noTransitionPages, + counts, + issues, + }; +} + +// ---------------------------------------------------------------- 工具:撤销上一次写操作 +export async function undoLastEdit({ + courseware, confirm = false, reopen = true, sync = false, force = false, +} = {}) { + if (!confirm) throw new Error('撤销会覆盖当前课件,请传 confirm=true'); + const cw = resolveCourseware(courseware); + const { backups } = listBackups({ courseware: cw.localId, limit: 500 }); + const hit = backups.find(b => String(b.note || '').startsWith('auto-before-write')); + if (!hit) { + throw new Error(`「${cw.name}」没有找到自动备份(auto-before-write);可用 list_backups 查看现有快照`); + } + const result = await restoreCourseware({ + backupId: hit.backupId, courseware: cw.localId, confirm: true, + reopen, sync, force, keepIdentity: true, + }); + return { + ...result, + undoneBackupId: hit.backupId, + undoneCreatedAt: hit.createdAt, + undoneNote: hit.note, + }; +} + +// ---------------------------------------------------------------- 工具:跨课件批量 +function resolveBatchTargets({ coursewares, allCoursewares = false, filter } = {}) { + let picked; + if (Array.isArray(coursewares) && coursewares.length) { + picked = coursewares.map(q => resolveCourseware(q)); + } else if (allCoursewares || filter) { + const all = listCoursewares(); + const needle = filter == null ? null : String(filter); + picked = needle + ? all.filter(cw => cw.name.includes(needle) || cw.localId.includes(needle)) + : all; + } else { + throw new Error('需要 coursewares 数组,或 allCoursewares=true(可加 filter 名字片段)'); + } + const map = new Map(); + for (const cw of picked) map.set(cw.localId, cw); + return [...map.values()]; +} + +async function runBatch(spec, fn) { + const targets = resolveBatchTargets(spec); + if (!targets.length) throw new Error('没有匹配到任何课件'); + const results = []; + for (const cw of targets) { + try { + const result = await fn(cw); + results.push({ localId: cw.localId, name: cw.name, ok: true, result }); + } catch (e) { + results.push({ localId: cw.localId, name: cw.name, ok: false, error: e.message }); + if (spec.stopOnError) break; + } + } + return { + requested: targets.length, + processed: results.length, + succeeded: results.filter(x => x.ok).length, + failed: results.filter(x => !x.ok).length, + results, + }; +} + +export async function batchReplaceText({ + coursewares, allCoursewares = false, filter, + page, pages, allPages = false, replacements = [], matchAll = false, + dryRun = false, stopOnError = false, + reopen = false, sync = false, force = false, backup = true, +} = {}) { + if (!Array.isArray(replacements) || !replacements.length) throw new Error('replacements 不能为空'); + return runBatch({ coursewares, allCoursewares, filter, stopOnError }, cw => replaceText({ + courseware: cw.localId, page, pages, allPages, replacements, matchAll, + dryRun, reopen, sync, force, backup, + })); +} + +export async function batchSetTextStyle({ + coursewares, allCoursewares = false, filter, + page, pages, allPages = false, + elementIds = [], textMatches = [], matchAll = false, + fontSize, bold, color, align, width, + dryRun = false, stopOnError = false, + reopen = false, sync = false, force = false, backup = true, +} = {}) { + return runBatch({ coursewares, allCoursewares, filter, stopOnError }, cw => setTextStyle({ + courseware: cw.localId, page, pages, allPages, + elementIds, textMatches, matchAll, + fontSize, bold, color, align, width, + dryRun, reopen, sync, force, backup, + })); +} + +export async function batchInspect({ + coursewares, allCoursewares = false, filter, + page, pages, query, includeElements, includeAnimations = true, format = 'json', + stopOnError = false, +} = {}) { + return runBatch({ coursewares, allCoursewares, filter, stopOnError }, cw => inspectCourseware({ + courseware: cw.localId, page, pages, query, includeElements, includeAnimations, format, + })); +} + +// ---------------------------------------------------------------- 工具:对齐 / 分布 / 缩放 +const round4 = n => Math.round(Number(n) * 10000) / 10000; + +function slideSizeOf(lines) { + const w = Number(lines.find(l => /^ {2}[^<]*<\/Width>$/.test(l)) + ?.match(/([^<]*)<\/Width>/)?.[1]); + const h = Number(lines.find(l => /^ {2}[^<]*<\/Height>$/.test(l)) + ?.match(/([^<]*)<\/Height>/)?.[1]); + return { + width: Number.isFinite(w) && w > 0 ? w : 1280, + height: Number.isFinite(h) && h > 0 ? h : 720, + }; +} + +/** 只改顶级元素自己的 X/Y/Width/Height(6 个空格缩进),不碰 Group 内部子元素 */ +function setElementBox(lines, elementId, box) { + const r = blockRange(lines, elementId); + if (!r) return false; + const block = lines.slice(r.start, r.end + 1); + for (const tag of ['X', 'Y', 'Width', 'Height']) { + const value = box[tag === 'Width' ? 'w' : tag === 'Height' ? 'h' : tag.toLowerCase()]; + if (value == null) continue; + const re = new RegExp(`^ {6}<${tag}>[^<]*$`); + const i = block.findIndex(l => re.test(l)); + if (i < 0) continue; + block[i] = ` <${tag}>${round4(value)}`; + } + lines.splice(r.start, r.end - r.start + 1, ...block); + return true; +} + +function layoutPage(lines, { + action, align, distribute, width, height, scale, x, y, dx, dy, + elementIds, textMatches, matchAll, allElements, referenceElementId, + relativeTo = 'slide', margin = 0, anchor = 'topleft', skipLocked = true, +}) { + const els = listElements(lines); + const picked = []; + const missing = []; + if (Array.isArray(elementIds) && elementIds.length) { + const byId = new Map(els.map(e => [e.id, e])); + for (const id of elementIds) { + const el = byId.get(id); + if (el) picked.push(el); else missing.push({ elementId: id, reason: '元素不存在' }); + } + } + if (Array.isArray(textMatches) && textMatches.length) { + for (const needle of textMatches) { + const hits = els.filter(e => e.type === '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 或 matchAll=true:` + + hits.map(h => h.id).join(', ')); + } else picked.push(...(matchAll ? hits : [hits[0]])); + } + } + if (allElements || (!picked.length && !missing.length && !elementIds?.length && !textMatches?.length)) { + picked.push(...els); + } + if (!picked.length && !missing.length) throw new Error('没有选中任何元素:请传 elementIds / textMatches,或 allElements=true'); + + const targets = []; + const skipped = []; + for (const el of [...new Map(picked.map(e => [e.id, e])).values()]) { + const locked = /True<\/IsLocked>/.test(el.body); + if (skipLocked && locked) { skipped.push({ elementId: el.id, reason: '已锁定' }); continue; } + if (![el.x, el.y, el.w, el.h].every(Number.isFinite)) { + skipped.push({ elementId: el.id, reason: '缺少位置/尺寸' }); + continue; + } + targets.push(el); + } + if (!targets.length) return { changes: [], missing, skipped }; + + const slide = slideSizeOf(lines); + const boxes = new Map(targets.map(el => [el.id, { x: el.x, y: el.y, w: el.w, h: el.h }])); + const reference = (() => { + if (relativeTo === 'element') { + const rel = els.find(e => e.id === referenceElementId); + if (!rel) throw new Error(`参考元素不存在:${referenceElementId}`); + return { x: rel.x, y: rel.y, w: rel.w, h: rel.h }; + } + if (relativeTo === 'selection') { + const minX = Math.min(...targets.map(e => e.x)); + const minY = Math.min(...targets.map(e => e.y)); + const maxX = Math.max(...targets.map(e => e.x + e.w)); + const maxY = Math.max(...targets.map(e => e.y + e.h)); + return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; + } + return { x: margin, y: margin, w: slide.width - margin * 2, h: slide.height - margin * 2 }; + })(); + + if (action === 'align') { + const mode = align === 'center' ? 'hcenter' : align === 'middle' ? 'vcenter' : align; + if (!['left', 'hcenter', 'right', 'top', 'vcenter', 'bottom'].includes(mode)) { + throw new Error('align 只能是:left / hcenter(center) / right / top / vcenter(middle) / bottom'); + } + for (const [id, box] of boxes) { + if (mode === 'left') box.x = reference.x; + else if (mode === 'right') box.x = reference.x + reference.w - box.w; + else if (mode === 'hcenter') box.x = reference.x + (reference.w - box.w) / 2; + else if (mode === 'top') box.y = reference.y; + else if (mode === 'bottom') box.y = reference.y + reference.h - box.h; + else if (mode === 'vcenter') box.y = reference.y + (reference.h - box.h) / 2; + boxes.set(id, box); + } + } else if (action === 'distribute') { + const axis = distribute === 'vertical' ? 'vertical' : 'horizontal'; + if (targets.length < 3) throw new Error('distribute 至少需要 3 个元素'); + const list = [...targets].sort((p, q) => (axis === 'horizontal' ? p.x - q.x : p.y - q.y)); + const first = boxes.get(list[0].id); + const last = boxes.get(list[list.length - 1].id); + const start = axis === 'horizontal' ? first.x : first.y; + const end = axis === 'horizontal' ? last.x + last.w : last.y + last.h; + const total = axis === 'horizontal' ? list.reduce((a, e) => a + e.w, 0) : list.reduce((a, e) => a + e.h, 0); + const gap = (end - start - total) / (list.length - 1); + let cursor = start; + for (const el of list) { + const box = boxes.get(el.id); + if (axis === 'horizontal') { box.x = cursor; cursor += box.w + gap; } else { box.y = cursor; cursor += box.h + gap; } + boxes.set(el.id, box); + } + } else if (action === 'resize') { + if (scale == null && width == null && height == null) { + throw new Error('resize 需要 scale,或 width / height'); + } + const factor = Number(scale); + for (const [, box] of boxes) { + const oldW = box.w; + const oldH = box.h; + let nextW = box.w; + let nextH = box.h; + if (scale != null) { + if (!Number.isFinite(factor) || factor <= 0) throw new Error('scale 必须是正数'); + nextW = box.w * factor; + nextH = box.h * factor; + } + if (width != null) nextW = Number(width); + if (height != null) nextH = Number(height); + if (!(nextW > 0) || !(nextH > 0)) throw new Error('width / height 必须是正数'); + box.w = nextW; + box.h = nextH; + if (anchor === 'center') { + box.x = box.x + (oldW - nextW) / 2; + box.y = box.y + (oldH - nextH) / 2; + } + } + } else if (action === 'move') { + if (x == null && y == null && dx == null && dy == null) { + throw new Error('move 需要 x / y(绝对位置)或 dx / dy(偏移)'); + } + for (const [, box] of boxes) { + if (x != null) box.x = Number(x); + if (y != null) box.y = Number(y); + if (dx != null) box.x += Number(dx); + if (dy != null) box.y += Number(dy); + } + } else { + throw new Error(`action 只能是:align / distribute / resize / move`); + } + + const changes = []; + for (const el of targets) { + const box = boxes.get(el.id); + const before = { x: el.x, y: el.y, w: el.w, h: el.h }; + const after = { x: round4(box.x), y: round4(box.y), w: round4(box.w), h: round4(box.h) }; + if (before.x === after.x && before.y === after.y && before.w === after.w && before.h === after.h) continue; + if (!setElementBox(lines, el.id, after)) { missing.push({ elementId: el.id, reason: '元素块定位失败' }); continue; } + changes.push({ + elementId: el.id, type: el.type, text: el.text.slice(0, 40), + before, after, + }); + } + return { changes, missing, skipped }; +} + +export async function layoutElements({ + courseware, page, pages, allPages = false, + action = 'align', align, distribute, width, height, scale, x, y, dx, dy, + elementIds = [], textMatches = [], matchAll = false, allElements = false, + referenceElementId, relativeTo = 'slide', margin = 0, anchor = 'topleft', + skipLocked = true, dryRun = false, + reopen = true, sync = false, force = false, backup = true, +} = {}) { + const cw = resolveCourseware(courseware); + const pageNumbers = selectedPagesFor(cw, { page, pages, allPages }); + const opts = { + action, align, distribute, + width: width == null ? null : Number(width), + height: height == null ? null : Number(height), + scale: scale == null ? null : Number(scale), + x: x == null ? null : Number(x), y: y == null ? null : Number(y), + dx: dx == null ? null : Number(dx), dy: dy == null ? null : Number(dy), + elementIds, textMatches, matchAll, allElements, + referenceElementId, relativeTo, margin: Number(margin) || 0, anchor, skipLocked, + }; + + const collect = lines => { + const { changes, missing, skipped } = layoutPage(lines, opts); + return { changes, missing, skipped }; + }; + + if (dryRun) { + const allChanges = []; + const allMissing = []; + const allSkipped = []; + const reports = []; + for (const n of pageNumbers) { + const { lines } = readLines(slideAt(cw, n).file); + const { changes, missing, skipped } = collect(lines); + reports.push({ page: n, changes, missing, skipped }); + allChanges.push(...changes.map(c => ({ page: n, ...c }))); + allMissing.push(...missing.map(m => ({ page: n, ...m }))); + allSkipped.push(...skipped.map(m => ({ page: n, ...m }))); + } + return { + courseware: cw.name, dryRun: true, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + action, changes: allChanges, missing: allMissing, skipped: allSkipped, + ...(pageNumbers.length === 1 ? {} : { reports }), + }; + } + + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const allChanges = []; + const allMissing = []; + const allSkipped = []; + const reports = []; + for (const n of pageNumbers) { + const { file, rec } = slideAt(c, n); + const { lines, eol } = readLines(file); + const { changes, missing, skipped } = collect(lines); + if (changes.length) { + writeLines(file, lines, eol); + saveSlideRecord(c, rec, file); + } + reports.push({ page: n, changes, missing, skipped }); + allChanges.push(...changes.map(v => ({ page: n, ...v }))); + allMissing.push(...missing.map(v => ({ page: n, ...v }))); + allSkipped.push(...skipped.map(v => ({ page: n, ...v }))); + } + return { + courseware: c.name, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + action, changes: allChanges, missing: allMissing, skipped: allSkipped, + ...(pageNumbers.length === 1 ? {} : { reports }), + }; + }); +} + +// ---------------------------------------------------------------- 工具:页面切换 +export async function setSlideTransition({ + courseware, page, pages, allPages = false, transition = 'fade', duration, + dryRun = false, reopen = true, sync = false, force = false, backup = true, +} = {}) { + const cw = resolveCourseware(courseware); + const pageNumbers = selectedPagesFor(cw, { page, pages, allPages }); + const key = resolveTransitionKey(transition); + const dur = duration == null || duration === '' ? null : Number(duration); + if (dur != null && (!Number.isFinite(dur) || dur < 0)) throw new Error('duration 必须是非负数秒'); + + const applyPage = lines => { + const before = slideTransitionOf(lines); + const { after } = setSlideTransitionLines(lines, key, dur); + return { + changed: before.key !== after.key || !numEq(before.duration, after.duration), + before, after, + }; + }; + + if (dryRun) { + const changes = []; + for (const n of pageNumbers) { + const { lines } = readLines(slideAt(cw, n).file); + const r = applyPage(lines); + if (r.changed) changes.push({ page: n, ...r }); + } + return { + courseware: cw.name, dryRun: true, transition: key, duration: dur, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + changes, + }; + } + + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const changes = []; + for (const n of pageNumbers) { + const { file, rec } = slideAt(c, n); + const { lines, eol } = readLines(file); + const r = applyPage(lines); + if (r.changed) { + writeLines(file, lines, eol); + saveSlideRecord(c, rec, file); + } + changes.push({ page: n, changed: r.changed, before: r.before, after: r.after }); + } + return { + courseware: c.name, transition: key, duration: dur, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + changes, + }; + }); +} + +// ---------------------------------------------------------------- 工具:导出页面 PNG +export async function exportSlides({ + courseware, page, pages, allPages, + outDir, prefix = 'slide', fileNamePattern, + openIfNeeded = true, retries = 2, minBytes = 2048, + timeoutSec = 180, stopOnError = true, settleMs = 600, +} = {}) { + const cw = resolveCourseware(courseware); + const wantAll = allPages === true || (page == null && !(Array.isArray(pages) && pages.length)); + const nums = selectedPagesFor(cw, { page, pages, allPages: wantAll }); + await ensureInit(); + let shell = (await shells()).find(s => sameCourseware(s, cw)); + let opened = false; + if (!shell) { + if (!openIfNeeded) throw new Error(`课件「${cw.name}」没打开;传 openIfNeeded=true 让 kit 打开它`); + const id = await openCourseware(cw, slideRecords(cw).length); + if (!id) throw new Error(`打开课件「${cw.name}」失败`); + shell = { id }; + opened = true; + } + await ensureEditMode(shell.id); + + const dir = outDir + ? (path.isAbsolute(outDir) ? outDir : path.join(TMP, 'seewo-kit-export', outDir)) + : path.join(TMP, 'seewo-kit-export', `${cw.localId}-${stamp()}`); + mkdirSync(dir, { recursive: true }); + const pad = Math.max(2, String(Math.max(...nums)).length); + const timeoutMs = Math.max(30, Number(timeoutSec) || 180) * 1000; + const files = []; + for (const n of nums) { + const name = fileNamePattern + ? String(fileNamePattern).replace(/\{page\}/g, String(n)).replace(/\{index\}/g, String(n).padStart(pad, '0')) + : `${prefix}-${String(n).padStart(pad, '0')}.png`; + const file = path.join(dir, name); + let bytes = 0; + let lastError = null; + let timedOut = false; + let attempts = 0; + for (let attempt = 0; attempt < Math.max(1, Number(retries) || 1); attempt++) { + attempts = attempt + 1; + // 上一次可能留下 0 字节文件;先删掉,避免把空文件当成成功 + if (existsSync(file) && statSync(file).size === 0) rmSync(file, { force: true }); + try { + const r = await mcp( + 'get_slide_screenshot', + { slideNumber: n, expectedPngImageFilePath: file, shellId: shell.id }, + { timeoutMs }, + ); + if (existsSync(file)) { + bytes = statSync(file).size; + if (bytes >= minBytes) break; + } + lastError = `截图接口返回了,但文件只有 ${bytes} 字节(${r.text.slice(0, 120)})`; + } catch (e) { + lastError = e.message; + timedOut = /abort|timeout|超时/i.test(String(e.message)); + } + await sleep(Math.max(0, Number(settleMs) || 0)); + // 超时通常意味着希沃渲染线程卡住;继续重试只会把界面越拖越死 + if (timedOut) break; + } + if (existsSync(file) && statSync(file).size < minBytes) rmSync(file, { force: true }); + const ok = bytes >= minBytes; + files.push({ + page: n, path: file, bytes, attempts, + ...(ok ? {} : { + error: timedOut + ? `截图超时(${timeoutSec} 秒)。请确认希沃窗口在前台、课件已完整加载;必要时重启希沃后重试,或调大 timeoutSec。` + : (lastError ?? '没有生成截图文件'), + timedOut, + }), + }); + if (!ok && stopOnError) break; + } + const succeeded = files.filter(f => f.bytes >= minBytes).length; + const failed = files.length - succeeded; + return { + ok: failed === 0 && files.length === nums.length, + courseware: cw.name, localId: cw.localId, + shellId: shell.id, opened, outDir: dir, + count: files.length, requested: nums.length, + succeeded, failed, skipped: nums.length - files.length, + timeoutSec, files, + }; +} + +// ---------------------------------------------------------------- 工具:段内富文本 +function textRunsRegion(block) { + const start = block.findIndex(l => l.trim() === ''); + if (start < 0) return null; + let depth = 0; + for (let i = start; i < block.length; i++) { + if (block[i].trim() === '') depth++; + else if (block[i].trim() === '') { + depth--; + if (depth === 0) return { start, end: i }; + } + } + return null; +} + +function textRunRanges(block) { + const out = []; + for (let i = 0; i < block.length; i++) { + if (block[i].trim() !== '') continue; + let j = i + 1; + while (j < block.length && block[j].trim() !== '') j++; + if (j >= block.length) break; + out.push({ start: i, end: j }); + i = j; + } + return out; +} + +function styleRunLines(runLines, text, style) { + const lines = [...runLines]; + const ti = lines.findIndex(l => /^\s*[\s\S]*<\/Text>$/.test(l)); + if (ti < 0) return null; + lines[ti] = lines[ti].replace(/[\s\S]*<\/Text>/, `${esc(text)}`); + if (style.fontSize != null) { + const i = lines.findIndex(l => /^\s*[^<]*<\/FontSize>$/.test(l)); + if (i >= 0) lines[i] = lines[i].replace(/[^<]*<\/FontSize>/, `${style.fontSize}`); + } + if (style.bold != null) { + const i = lines.findIndex(l => /^\s*[^<]*<\/FontWeight>$/.test(l)); + if (i >= 0) lines[i] = lines[i].replace(/[^<]*<\/FontWeight>/, `${style.bold ? 'Bold' : 'Normal'}`); + } + if (style.color) { + const fg = lines.findIndex(l => l.trim() === ''); + const brush = fg >= 0 ? lines.findIndex((l, i) => i > fg && /[^<]*<\/ColorBrush>/.test(l)) : -1; + if (brush >= 0) lines[brush] = lines[brush].replace(/[^<]*<\/ColorBrush>/, `${style.color}`); + } + return lines; +} + +function buildStyledRuns(runLines, find, style) { + const ti = runLines.findIndex(l => /^\s*[\s\S]*<\/Text>$/.test(l)); + if (ti < 0) return null; + const m = runLines[ti].match(/^(\s*)([\s\S]*)<\/Text>$/); + if (!m) return null; + const raw = unesc(m[2]); + if (!raw.includes(find)) return null; + const out = []; + let pos = 0; + let idx = 0; + let count = 0; + while ((idx = raw.indexOf(find, idx)) >= 0) { + if (idx > pos) out.push(styleRunLines(runLines, raw.slice(pos, idx), { ...style, fontSize: undefined, bold: undefined, color: undefined })); + out.push(styleRunLines(runLines, find, style)); + pos = idx + find.length; + idx += find.length; + count++; + } + if (pos < raw.length) { + out.push(styleRunLines(runLines, raw.slice(pos), { ...style, fontSize: undefined, bold: undefined, color: undefined })); + } + return count ? { runs: out, count } : null; +} + +export async function styleTextRange({ + courseware, page, pages, allPages = false, + elementIds = [], textMatches = [], matchAll = false, + find, fontSize, bold, color, dryRun = false, + reopen = true, sync = false, force = false, backup = true, +} = {}) { + const needle = find == null ? '' : String(find); + if (!needle) throw new Error('find 不能为空'); + const style = { + fontSize: fontSize == null ? null : Number(fontSize), + bold: bold == null ? null : !!bold, + color: color == null || color === '' ? null : normalizeColor(color), + }; + if (style.fontSize != null && (!Number.isFinite(style.fontSize) || style.fontSize <= 0)) { + throw new Error('fontSize 必须是正数'); + } + if (style.fontSize == null && style.bold == null && style.color == null) { + throw new Error('至少要传一个样式参数:fontSize / bold / color'); + } + const cw = resolveCourseware(courseware); + const pageNumbers = selectedPagesFor(cw, { page, pages, allPages }); + + const applyPage = lines => { + const els = listElements(lines).filter(e => e.type === 'Text' && e.text); + const picked = []; + const missing = []; + if (elementIds.length || textMatches.length) { + const byId = new Map(els.map(e => [e.id, e])); + for (const id of elementIds) { + const el = byId.get(id); + if (el) picked.push(el); else missing.push({ elementId: id, reason: '元素不存在' }); + } + for (const t of textMatches) { + const hits = els.filter(e => e.text.includes(t)); + if (!hits.length) { missing.push({ text: t, reason: '没有文本含这段文字' }); continue; } + if (hits.length > 1 && !matchAll) { + throw new Error(`「${t}」匹配到 ${hits.length} 个元素,请加 elementIds 或 matchAll=true:` + + hits.map(h => h.id).join(', ')); + } + picked.push(...(matchAll ? hits : [hits[0]])); + } + } else { + picked.push(...els.filter(e => e.text.includes(needle))); + } + const targets = [...new Map(picked.map(e => [e.id, e])).values()]; + + const changes = []; + for (const el of targets) { + const r = blockRange(lines, el.id); + if (!r) { missing.push({ elementId: el.id, reason: '元素块定位失败' }); continue; } + const block = lines.slice(r.start, r.end + 1); + const region = textRunsRegion(block); + if (!region) { missing.push({ elementId: el.id, reason: '没有 TextRuns' }); continue; } + const ranges = textRunRanges(block); + const replacement = []; + let cursor = region.start + 1; + let changedRuns = 0; + let occurrences = 0; + for (const rb of ranges) { + replacement.push(...block.slice(cursor, rb.start)); + const runLines = block.slice(rb.start, rb.end + 1); + const styled = buildStyledRuns(runLines, needle, style); + if (styled) { + replacement.push(...styled.runs.flat()); + changedRuns++; + occurrences += styled.count; + } else { + replacement.push(...runLines); + } + cursor = rb.end + 1; + } + replacement.push(...block.slice(cursor, region.end)); + if (!changedRuns) { + const reason = el.text.includes(needle) + ? `「${needle}」跨多个 TextRun,无法只给其中一段上样式` + : `文本里没有「${needle}」`; + missing.push({ elementId: el.id, reason }); + continue; + } + block.splice(region.start + 1, region.end - region.start - 1, ...replacement); + lines.splice(r.start, r.end - r.start + 1, ...block); + changes.push({ + elementId: el.id, text: el.text.slice(0, 80), find: needle, + runs: changedRuns, occurrences, style, + }); + } + return { changes, missing }; + }; + + if (dryRun) { + const allChanges = []; + const allMissing = []; + const reports = []; + for (const n of pageNumbers) { + const { lines } = readLines(slideAt(cw, n).file); + const { changes, missing } = applyPage(lines); + reports.push({ page: n, changes, missing }); + allChanges.push(...changes.map(c => ({ page: n, ...c }))); + allMissing.push(...missing.map(m => ({ page: n, ...m }))); + } + return { + courseware: cw.name, dryRun: true, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + changes: allChanges, missing: pruneMissing(allMissing, allChanges), + ...(pageNumbers.length === 1 ? {} : { reports }), + }; + } + + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const allChanges = []; + const allMissing = []; + const reports = []; + for (const n of pageNumbers) { + const { file, rec } = slideAt(c, n); + const { lines, eol } = readLines(file); + const { changes, missing } = applyPage(lines); + if (changes.length) { + writeLines(file, lines, eol); + saveSlideRecord(c, rec, file); + } + reports.push({ page: n, changes, missing }); + allChanges.push(...changes.map(v => ({ page: n, ...v }))); + allMissing.push(...missing.map(v => ({ page: n, ...v }))); + } + return { + courseware: c.name, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + changes: allChanges, missing: pruneMissing(allMissing, allChanges), + ...(pageNumbers.length === 1 ? {} : { reports }), + }; + }); +} diff --git a/kit/server.mjs b/kit/server.mjs index e0b9919..8b28993 100644 --- a/kit/server.mjs +++ b/kit/server.mjs @@ -17,6 +17,9 @@ import { replaceText, verifyCourseware, backupCourseware, restoreCourseware, copySlides, listCoursewares, syncCourseware, pruneOrphanFiles, removeLocalCourseware, inspectCourseware, setTextStyle, listBackups, deleteSlides, moveSlides, + diffCourseware, preflightCourseware, undoLastEdit, + batchReplaceText, batchSetTextStyle, batchInspect, + layoutElements, setSlideTransition, exportSlides, styleTextRange, } from './core.mjs'; const log = (...a) => console.error('[seewo-kit]', ...a); @@ -346,6 +349,267 @@ const TOOLS = [ }, }, }, + { + name: 'diff_courseware', + description: + '对比两份课件,或「某次备份 vs 当前课件」。按 Board 页序逐页比较文字、字号/加粗/颜色、动画、页面切换;' + + '可选比较位置尺寸。默认只返回有变化的页。pages 可只看指定页码。只读。', + inputSchema: { + type: 'object', + properties: { + a: { type: 'string', description: '课件 A:名称片段或 LocalId' }, + b: { type: 'string', description: '课件 B:名称片段或 LocalId' }, + backupId: { type: 'string', description: '传了就对比「备份(A)vs 当前课件(B)」' }, + courseware: { type: 'string', description: 'backupId 模式下对比的当前课件;默认用备份里的 LocalId' }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 }, description: '只对比这些页码' }, + maxPages: { type: 'integer', minimum: 1, default: 300, description: '最多对比多少页' }, + includeGeometry: { type: 'boolean', default: false, description: '是否比较 X/Y/宽/高' }, + includeUnchanged: { type: 'boolean', default: false, description: '是否连没变化的页一起返回' }, + }, + }, + }, + { + name: 'preflight_courseware', + description: + '课前自检(只读):在 verify_courseware 基础上检查字号是否统一、文本是否超宽、挖空答案是否一开始就可见、' + + '动画是否漏进 AnimationOrders、页面切换覆盖情况,以及本地是否还没同步。' + + '返回 { ok, ready, counts, issues, transitions };ready=false 时建议先处理 warnings。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + expectedFontSize: { type: 'number', default: 28, description: '期望正文字号;传 0 可跳过字号检查' }, + bodyMinY: { type: 'number', default: 90, description: '只检查 Y ≥ 该值的正文,跳过顶部标题/页眉' }, + hashes: { type: 'boolean', default: true, description: '是否逐文件校验 MD5' }, + deep: { type: 'boolean', default: true, description: '是否跨页检查重复元素 Id' }, + }, + }, + }, + { + name: 'undo_last_edit', + description: + '撤销最近一次 kit 写操作:找到该课件最新一份 note=auto-before-write 的自动备份并恢复。' + + '必须传 confirm=true。只恢复内容,保留当前 Name/RemoteId。', + inputSchema: { + type: 'object', + properties: { + 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: ['confirm'], + }, + }, + { + name: 'batch_replace_text', + description: + '跨课件批量改文字:对 coursewares 里的每份课件执行 replace_text。\n' + + '每份课件各自自动备份(backup=true);默认改完不重新打开(reopen=false),避免批量时反复开关。\n' + + 'dryRun=true 只读预览。返回每份课件的成功/失败明细。', + inputSchema: { + type: 'object', + properties: { + coursewares: { type: 'array', items: { type: 'string' }, description: '课件名片段或 LocalId 列表' }, + allCoursewares: { type: 'boolean', default: false, description: '对本地全部课件批量操作' }, + filter: { type: 'string', description: '与 allCoursewares 搭配:只处理名字/LocalId 含这段文字的课件' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + allPages: { type: 'boolean', default: false }, + replacements: { + type: 'array', + items: { + type: 'object', + properties: { + elementId: { type: 'string' }, find: { type: 'string' }, + replace: { type: 'string' }, text: { type: 'string' }, width: { type: 'number' }, + }, + }, + }, + matchAll: { type: 'boolean', default: false }, + dryRun: { type: 'boolean', default: false }, + stopOnError: { type: 'boolean', default: false }, + reopen: { type: 'boolean', default: false }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + required: ['replacements'], + }, + }, + { + name: 'batch_set_text_style', + description: + '跨课件批量改文本样式:对 coursewares 里的每份课件执行 set_text_style(字号/加粗/颜色/对齐/宽度)。\n' + + '默认每份各自备份、改完不重开;dryRun=true 只读预览。', + inputSchema: { + type: 'object', + properties: { + coursewares: { type: 'array', items: { type: 'string' } }, + allCoursewares: { type: 'boolean', default: false }, + filter: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + allPages: { type: 'boolean', default: false }, + elementIds: { type: 'array', items: { type: 'string' } }, + textMatches: { type: 'array', items: { type: 'string' } }, + matchAll: { type: 'boolean', default: false }, + fontSize: { type: 'number', minimum: 1 }, + bold: { type: 'boolean' }, + color: { type: 'string' }, + align: { type: 'string', enum: ['Left', 'Center', 'Right'] }, + width: { type: 'number', minimum: 1 }, + dryRun: { type: 'boolean', default: false }, + stopOnError: { type: 'boolean', default: false }, + reopen: { type: 'boolean', default: false }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + }, + }, + { + name: 'batch_inspect', + description: + '跨课件批量检查:对每份课件执行 inspect_courseware,返回各自结果。常与 batch_replace_text 的 dryRun 配合做批量核对。只读。', + inputSchema: { + type: 'object', + properties: { + coursewares: { type: 'array', items: { type: 'string' } }, + allCoursewares: { type: 'boolean', default: false }, + filter: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + query: { type: 'string' }, + includeElements: { type: 'boolean' }, + includeAnimations: { type: 'boolean', default: true }, + format: { type: 'string', enum: ['json', 'text'], default: 'json' }, + stopOnError: { type: 'boolean', default: false }, + }, + }, + }, + { + name: 'layout_elements', + description: + '页面元素排版:对齐(left/hcenter/right/top/vcenter/bottom)、等距分布、批量缩放/改尺寸、批量移动。\n' + + '用 elementIds / textMatches 选元素,或 allElements=true;默认跳过锁定元素。\n' + + 'relativeTo=slide(相对页面,可加 margin)/ selection(相对选中元素包围盒)/ element(配合 referenceElementId)。\n' + + 'action=distribute 至少 3 个元素;resize 用 scale 或 width/height;move 用 x/y 或 dx/dy。\n' + + 'dryRun=true 只预览 before/after,不写文件。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + allPages: { type: 'boolean', default: false }, + action: { type: 'string', enum: ['align', 'distribute', 'resize', 'move'], default: 'align' }, + align: { type: 'string', enum: ['left', 'hcenter', 'center', 'right', 'top', 'vcenter', 'middle', 'bottom'] }, + distribute: { type: 'string', enum: ['horizontal', 'vertical'], default: 'horizontal' }, + width: { type: 'number', minimum: 1 }, + height: { type: 'number', minimum: 1 }, + scale: { type: 'number', minimum: 0.01 }, + x: { type: 'number' }, + y: { type: 'number' }, + dx: { type: 'number' }, + dy: { type: 'number' }, + elementIds: { type: 'array', items: { type: 'string' } }, + textMatches: { type: 'array', items: { type: 'string' } }, + matchAll: { type: 'boolean', default: false }, + allElements: { type: 'boolean', default: false }, + referenceElementId: { type: 'string', description: 'relativeTo=element 时的参考元素 Id' }, + relativeTo: { type: 'string', enum: ['slide', 'selection', 'element'], default: 'slide' }, + margin: { type: 'number', default: 0, description: 'relativeTo=slide 时距边缘的距离' }, + anchor: { type: 'string', enum: ['topleft', 'center'], default: 'topleft', description: 'resize 时以左上角还是中心为基准' }, + skipLocked: { type: 'boolean', default: true }, + dryRun: { type: 'boolean', default: false }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + }, + }, + { + name: 'set_slide_transition', + description: + '设置页面切换:transition 可用 none / dissolve / fade / slide-left / circle-out / random-lines,' + + '也可直接传希沃的原始 TransitionKey;duration 单位秒。\n' + + 'page 单页,或 pages 多页,或 allPages=true。dryRun=true 只预览。写操作流程同 set_animations。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + allPages: { type: 'boolean', default: false }, + transition: { type: 'string', default: 'fade', description: '别名或原始 TransitionKey;none=清除切换' }, + duration: { type: 'number', minimum: 0, description: '秒;不传则保留原时长' }, + dryRun: { type: 'boolean', default: false }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + }, + }, + { + name: 'export_slides', + description: + '把页面导成 PNG:打开课件(没开会自动打开),逐页调用希沃原生截图接口。\n' + + '默认导出全部页;outDir 不传则写到 %TEMP%\\opencode\\seewo-kit-export\\-<时间>。\n' + + 'fileNamePattern 支持 {page} 和 {index}(补零)。\n' + + '注意:首次截图可能很慢(渲染冷启动)。默认 180 秒超时,超时会停止后续页面并提示重启希沃;' + + '确认希沃窗口在前台、课件完整加载后可调大 timeoutSec 重试。只读不改课件。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + allPages: { type: 'boolean', description: '默认 true;也可用 page/pages 指定' }, + outDir: { type: 'string', description: '绝对路径,或相对 %TEMP%\\opencode\\seewo-kit-export 的目录名' }, + prefix: { type: 'string', default: 'slide' }, + fileNamePattern: { type: 'string', description: '如 page-{index}.png' }, + openIfNeeded: { type: 'boolean', default: true }, + retries: { type: 'integer', minimum: 1, default: 2, description: '非超时错误的重试次数' }, + timeoutSec: { type: 'integer', minimum: 30, default: 180, description: '单页截图超时(秒)' }, + minBytes: { type: 'integer', minimum: 0, default: 2048, description: '小于这个字节数视为失败并删除空文件' }, + stopOnError: { type: 'boolean', default: true, description: '失败后是否停止后续页面(推荐 true)' }, + settleMs: { type: 'integer', minimum: 0, default: 600 }, + }, + }, + }, + { + name: 'style_text_range', + description: + '段内富文本:只给元素里匹配 find 的那一段文字改字号/加粗/颜色,其余文字样式不变。\n' + + '只处理匹配完整落在单个 TextRun 内的情况;跨 TextRun 会报 missing 并说明原因。\n' + + '用 elementIds / textMatches 选元素;都不传则在该页所有文本里找 find。支持 dryRun。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + allPages: { type: 'boolean', default: false }, + elementIds: { type: 'array', items: { type: 'string' } }, + textMatches: { type: 'array', items: { type: 'string' } }, + matchAll: { type: 'boolean', default: false }, + find: { type: 'string', description: '要单独上样式的那段文字' }, + fontSize: { type: 'number', minimum: 1 }, + bold: { type: 'boolean' }, + color: { type: 'string', description: '#RRGGBB 或 #AARRGGBB' }, + dryRun: { type: 'boolean', default: false }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + required: ['find'], + }, + }, ]; const HANDLERS = { @@ -365,6 +629,16 @@ const HANDLERS = { sync_courseware: syncCourseware, prune_orphan_files: pruneOrphanFiles, remove_local_courseware: removeLocalCourseware, + diff_courseware: diffCourseware, + preflight_courseware: preflightCourseware, + undo_last_edit: undoLastEdit, + batch_replace_text: batchReplaceText, + batch_set_text_style: batchSetTextStyle, + batch_inspect: batchInspect, + layout_elements: layoutElements, + set_slide_transition: setSlideTransition, + export_slides: exportSlides, + style_text_range: styleTextRange, list_coursewares: () => { const all = listCoursewares(); let dbCountHint = null;