From 32b0e74e9d87e43c47c2a00fb0ad70a68388bd69 Mon Sep 17 00:00:00 2001 From: wangfar Date: Fri, 13 Nov 2026 08:12:27 +0800 Subject: [PATCH] =?UTF-8?q?seewo-kit:=20=E6=96=B0=E5=A2=9E=E5=AE=A1?= =?UTF-8?q?=E8=AE=A1/=E6=94=B9=E6=A0=B7=E5=BC=8F/=E5=88=A0=E9=A1=B5?= =?UTF-8?q?=E6=8E=92=E5=BA=8F/=E5=A4=87=E4=BB=BD=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - inspect_courseware:按页序审计文字、字号、颜色、位置、动画与点击顺序,支持全课件搜索 - set_text_style:批量改字号/加粗/颜色/对齐/框宽,只改 TextRun,保护默认属性与项目符号 - replace_text:支持 pages/allPages、matchAll、dryRun 预览 - delete_slides / move_slides:重写 Board 页序与索引映射,删页默认进回收目录 - list_backups:列出快照,供 restore_courseware 取 backupId - README 更新到 17 个工具 --- README.md | 11 +- kit/README.md | 84 +++++- kit/core.mjs | 675 +++++++++++++++++++++++++++++++++++++++++++++---- kit/server.mjs | 121 ++++++++- 4 files changed, 824 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 5f821c5..4950b89 100644 --- a/README.md +++ b/README.md @@ -140,10 +140,17 @@ node seewo-anim.mjs fix --slide 5 --minY 90 # 只改正文行(默认 ## 相关:seewo-kit(MCP 版) `kit/` 下是把本工具能力接进 MCP 的版本,另外补了课件自检、备份/恢复、跨课件复制页面、 -批量改文字、清理重复课件与孤儿文件。注册后可直接在 OpenCode 里调用 `seewokit_*` 工具,无需命令行。 +批量改文字、批量改样式、删页/排序、清理重复课件与孤儿文件。目前 17 个工具,注册后可直接在 OpenCode 里调用 +`seewokit_*`,无需命令行。 -两个特别有用的只读/维护工具: +几个特别有用的工具: +- `inspect_courseware`:按页序看每页文字、字号、加粗、颜色、位置、动画和点击顺序,也能全课件搜文字; + 和 `verify_courseware` 互补 —— 前者看内容,后者看结构。 +- `set_text_style`:按元素 Id / 文字批量改字号、加粗、颜色、对齐和文本框宽度,支持 `dryRun` 预览。 +- `replace_text`:支持 `pages` / `allPages` 多页改字,`matchAll` 处理同页多处命中,`dryRun` 先看改动。 +- `delete_slides` / `move_slides`:补上希沃 `move_slide` 不可用的缺口;删页默认移入回收目录,至少保留 1 页。 +- `list_backups`:列出快照,`restore_courseware` 的 `backupId` 直接从这里取。 - `verify_courseware`:一次返回页数、MD5、重复 Id、DB 一致性,以及每页动画数 (`animations: { 页码: 动画数 }`、`animationTotal`),适合改完后做回归核对。 - `prune_orphan_files`:默认 `dryRun` 只预览「磁盘上有、索引里没引用」的旧文件, diff --git a/kit/README.md b/kit/README.md index aedfb60..c397ebc 100644 --- a/kit/README.md +++ b/kit/README.md @@ -1,10 +1,10 @@ # seewo-kit · 希沃白板 MCP 增强工具 -希沃自带的 MCP 只有「建页 / 加元素 / 开关课件 / 同步」,缺动画、跨课件复制、改文字、自检这些能力。 +希沃自带的 MCP 只有「建页 / 加元素 / 开关课件 / 同步」,缺动画、跨课件复制、改文字、改样式、删页排序、自检这些能力。 `seewo-kit` 是一个独立的 stdio MCP server,直接读写希沃的本地课件缓存,同时复用希沃 MCP 完成 -「关课件 / 开课件 / 云同步」。 +「关课件 / 开课件 / 云同步」。目前提供 17 个工具。 -它是 `seewo-anim.mjs`(CLI)的 MCP 化版本,参数语义一致,另外补了 verify / backup / restore / copy / replace。 +它是 `seewo-anim.mjs`(CLI)的 MCP 化版本,参数语义一致,另外补了 verify / backup / inspect / style / replace / delete / move。 ``` kit/ @@ -37,7 +37,12 @@ kit/ | `set_animations` | 给元素加动画(默认 FadeIn / Click / 0.3 秒) | 是 | | `get_animations` | 读某页动画、点击顺序、`AnimationOrders` 一致性 | 否 | | `clear_animations` | 清整页 / 指定元素 / 全部页的动画 | 是 | -| `replace_text` | 批量改文本(整段或子串),可顺手规范折行 | 是 | +| `inspect_courseware` | 按页序审计内容:文字、字号、加粗、颜色、位置、动画、点击顺序、超宽提示;可全课件搜文字 | 否 | +| `replace_text` | 批量改文本(整段或子串),支持多页 / `dryRun` | 是 | +| `set_text_style` | 批量改文本样式:字号、加粗、颜色、对齐、文本框宽度 | 是 | +| `list_backups` | 列出本地备份快照,供 `restore_courseware` 取 `backupId` | 否 | +| `delete_slides` | 按页删除(默认移入回收目录,至少保留 1 页) | 是 | +| `move_slides` | 调整页序(`from`+`to`,或完整 `order`) | 是 | | `verify_courseware` | 课件自检:页数、页序、MD5、重复 Id、资源引用、DB 一致性、每页动画数 | 否 | | `backup_courseware` | 全量快照到临时目录,返回 `backupId` | 否 | | `restore_courseware` | 从快照恢复(需 `confirm=true`;默认保留当前身份) | 是 | @@ -52,7 +57,8 @@ kit/ | 参数 | 说明 | | --- | --- | | `courseware` | 课件名片段或 LocalId;不传取最近修改的课件 | -| `page` | 页码,1-based,按 `Board.xml` 页序 | +| `page` / `pages` / `allPages` | 单页 / 多页 / 全部页,1-based,按 `Board.xml` 页序 | +| `dryRun` | 只预览改动,不关课件、不写文件(`replace_text` / `set_text_style`) | | `reopen` | 改完是否重新打开课件,默认 `true` | | `sync` | 重开后是否云同步,默认 `false` | | `force` | 跳过「未同步改动」检查,默认 `false` | @@ -96,8 +102,59 @@ kit/ - `text`:整段替换,要求该元素只有一个不同的文本片段。 - `find` + `replace`:子串替换,必须命中,否则记进 `missing`。 - `width`:传了就同时把文本块规范成「固定框宽 + 单行折行」,避免重开后按旧折行渲染。 +- `page` 单页,或 `pages: [1,2]`,或 `allPages: true`。 +- 同一页 `find` 命中多个元素时会报错;加 `matchAll: true` 可全部替换。 +- `dryRun: true` 只返回「哪页哪个元素会从什么改成什么」,不关课件、不写文件。 +- 多页模式下 `missing` 会去噪:某一页没有这段文字、但别的页命中的,不算失败。 - 这是补希沃 `edit_text_element` 不能改文字内容的缺口。 +### inspect_courseware + +只读审计,不关课件。和 `verify_courseware` 的分工: + +- `verify_courseware` 查「结构有没有坏」; +- `inspect_courseware` 查「内容长什么样」。 + +- `page` 单页;`pages` 多页;不传看全部(多页默认只给每页摘要,单页/双页展开元素)。 +- `query` 全课件搜索文字,返回页码 + 元素 Id + 字号。 +- `format: "text"` 返回人读清单,便于直接看排版。 +- 每页返回 `fontSizes`、`clickOrder`、`warnings`(按字数估算可能超宽的行)。 +- 字号只统计真正显示的 `TextRun`,会忽略 `DefaultRunProperty` 和 `TextMarkerStyle`(否则会出现 0/16 之类的假字号)。 + +### set_text_style + +- 选择器:`elementIds` 或 `textMatches`(多命中加 `matchAll: true`);都不传 = 所选页的全部文本。 +- 可改 `fontSize` / `bold` / `color` / `align` / `width`。 +- 颜色支持 `#RRGGBB` 或 `#AARRGGBB`,内部统一成希沃的 `#AARRGGBB`。 +- **只改真正渲染的 `TextRun`**,不会动 `DefaultRunProperty`(默认属性)和 + `TextMarkerStyle`(项目符号字号 0),避免把项目符号或空文本的默认样式改坏。 +- 改字号/宽度后自动重建 `` 折行缓存。 +- 建议先 `dryRun: true`,确认 `after` 和 `overflow` 后再写。 + +### list_backups + +- 列出 `%TEMP%\opencode\seewo-kit-backups` 下的快照:`backupId`、时间、备注、页数、Revision、大小。 +- `courseware` 可按课件名片段或 LocalId 过滤;`limit` 默认 50。 +- `restore_courseware` 需要的 `backupId` 直接从这里取。 + +### delete_slides / move_slides + +`delete_slides`: + +- `pages` 是当前页序的页码数组;不能删光,至少保留 1 页。 +- 页面文件默认移到 `%TEMP%\opencode\seewo-kit-trash\-<时间>`,不是硬删除; + `trash: false` 才直接删。 +- 重写 `Board.xml` 页序、索引里的 `Slides\Slide_N.xml` 映射和 DB;被删页引用的资源留给 + `prune_orphan_files` 收尾。 + +`move_slides`: + +- `from` + `to`:把第 `from` 页移到第 `to` 个位置。 +- 或 `order: [3,1,2]`:传完整新页序(当前页码的全排列,不能重复/缺页)。 +- 只重写页序和索引映射,不改页面内容。 +- 返回的 `order` 是「新页序下每一页原来的页码」,`pages[].oldPage` 也是同样信息,便于核对。 +- 原地移动(`from === to`)返回 `changed: false`,不会走写流程。 + ### copy_slides - `pages` 是源课件页码数组;`position` 是插入到目标第几页之后(0 = 最前,不传 = 末尾)。 @@ -244,6 +301,23 @@ MCP 没有「删除云课件」的工具,云端多余副本只能在希沃 App MCP 加的元素在 Display 模式下不会被保存;写操作前后尽量让课件处于 Edit(备课)模式。 `kit` 的写操作走的是关闭后改文件,不依赖界面模式,但同步前建议 `en_goto_app_ui({ ui: 'Edit' })`(`syncShell` 已内置)。 +### 9. 改样式不能无脑替换整个元素 + +希沃文本元素的 XML 里,`` / `` / `` 会出现多次: + +- `TextRuns/TextRun`:真正显示的文本属性; +- `DefaultRunProperty/TextRun`:空文本的默认属性; +- `TextMarkerStyle`:项目符号,`0`。 + +如果整块正则替换,会把项目符号字号从 0 改成 28,或把默认前景色一起改掉。 +`set_text_style` 会先屏蔽后两种区域,只改 `TextRun`;`inspect_courseware` 的字号也只看 `TextRun`。 + +### 10. 删页/排序后文件名不会跟着改 + +`delete_slides` / `move_slides` 只重写 `Board.xml` 页序和索引里的 `RelativePath`(`Slides\Slide_N.xml`), +物理文件名仍是旧的 `Slide_3_Sxxxx.xml`。这是希沃自己的映射方式,`verify_courseware` 也按 +`RelativePath` 检查页序,所以不需要重命名文件;重命名反而容易和 DB 的 `FileName` 对不上。 + ## 排错 ```bash diff --git a/kit/core.mjs b/kit/core.mjs index 9ab0bf9..ddd727d 100644 --- a/kit/core.mjs +++ b/kit/core.mjs @@ -264,6 +264,235 @@ const elementText = body => { return cands[0] ?? ''; }; +/** 把 #RGB / #RRGGBB / #AARRGGBB 统一成希沃用的 #AARRGGBB */ +function normalizeColor(value) { + if (value == null || value === '') return null; + let s = String(value).trim(); + if (!s.startsWith('#')) s = '#' + s; + s = s.toUpperCase(); + if (/^#[0-9A-F]{3}$/.test(s)) s = '#' + [...s.slice(1)].map(ch => ch + ch).join(''); + if (/^#[0-9A-F]{6}$/.test(s)) return '#FF' + s.slice(1); + if (/^#[0-9A-F]{8}$/.test(s)) return s; + throw new Error(`颜色格式不支持:${value}(用 #RRGGBB 或 #AARRGGBB)`); +} + +/** 粗略估算一行文字的像素宽度:中文按 1em,英文/数字按 0.55em */ +function estimateTextWidth(text, fontSize) { + let units = 0; + for (const ch of String(text)) { + const code = ch.codePointAt(0); + if (ch === ' ') units += 0.5; + else if (code >= 0x2E80) units += 1; + else if (/[A-Za-z0-9]/.test(ch)) units += 0.55; + else units += 0.6; + } + return units * (Number(fontSize) || 28); +} + +const textStyleOf = el => ({ + fontSize: el?.fontSizes?.[0] ?? null, + bold: !!el?.bold, + color: el?.color ?? null, + align: el?.body?.match(/([^<]*)<\/TextAlignment>/)?.[1] ?? null, + width: el?.w ?? null, +}); + +/** page / pages / allPages 三种写法统一成页码数组 */ +function selectedPagesFor(cw, { page, pages, allPages = false } = {}) { + const all = slidesInBoardOrder(cw); + if (allPages) return all.map(s => s.page); + if (Array.isArray(pages) && pages.length) { + const out = [...new Set(pages.map(Number))]; + for (const n of out) { + if (!Number.isInteger(n) || n < 1 || n > all.length) { + throw new Error(`页码 ${n} 超出范围(1-${all.length})`); + } + } + return out; + } + if (page == null) throw new Error('需要 page,或传 pages / allPages=true'); + const n = Number(page); + if (!Number.isInteger(n) || n < 1 || n > all.length) { + throw new Error(`页码 ${n} 超出范围(1-${all.length})`); + } + return [n]; +} + +/** 按新页序重写索引里的 Slides\Slide_N.xml 映射;被删页的记录直接丢弃 */ +function reindexSlides(cw, ordered) { + const nonSlides = cw.json.CoursewareFiles.filter(f => !isSlidePath(f.RelativePath)); + ordered.forEach((s, i) => { + s.rec.RelativePath = `Slides\\Slide_${i}.xml`; + s.rec.FilePath = `${cw.localId}\\${s.rec.FileName}`; + }); + cw.json.CoursewareFiles = [...nonSlides, ...ordered.map(s => s.rec)]; +} + +/** 按新页序重写 Board.xml 的 列表 */ +function writeBoardOrder(cw, ordered) { + const board = readBoard(cw); + const xml = board.xml.replace(/[\s\S]*?<\/Slides>/, + '\n' + ordered.map(s => ` ${s.id}`).join('\n') + '\n '); + writeFileSync(board.file, xml, 'utf8'); + saveSlideRecord(cw, board.rec, board.file); +} + +function inspectSlide(slide, { includeAnimations = true } = {}) { + const { lines } = readLines(slide.file); + const orders = parseOrders(lines); + const orderIndex = new Map(orders.map((id, i) => [id.toLowerCase(), i + 1])); + const elements = listElements(lines).map(el => { + const anims = includeAnimations + ? parseAnimations(el.body).map(a => ({ ...a, order: orderIndex.get(String(a.id).toLowerCase()) ?? null })) + : []; + const fontSize = el.fontSizes[0] ?? null; + const overflow = !!(fontSize && el.text && el.w > 0 + && estimateTextWidth(el.text, fontSize) > el.w * 1.05); + return { + id: el.id, type: el.type, text: el.text, + fontSize, fontSizes: el.fontSizes, bold: el.bold, color: el.color, + x: el.x, y: el.y, w: el.w, h: el.h, + blank: /_{3,}/.test(el.text), + animated: el.animated, + animations: anims, + overflow, + }; + }); + const textElements = elements.filter(e => e.type === 'Text' && e.text); + return { + page: slide.page, slideId: slide.id, file: path.basename(slide.file), + elementCount: elements.length, + textCount: textElements.length, + animationCount: elements.reduce((a, e) => a + e.animations.length, 0), + 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)}`), + elements, + }; +} + +function renderInspectText(result) { + const out = []; + if (result.matches?.length) { + out.push(`匹配「${result.query}」共 ${result.matches.length} 处:`); + for (const m of result.matches) { + out.push(` 第 ${m.page} 页 ${m.fontSize ?? '-'}px ${m.elementId} ${m.text.slice(0, 80)}`); + } + out.push(''); + } + for (const p of result.items) { + out.push(`第 ${p.page} 页 ${p.file} 元素 ${p.elementCount} 文本 ${p.textCount} 动画 ${p.animationCount} 字号 ${p.fontSizes.join('/') || '-'}`); + for (const e of p.elements) { + if (!e.text && !e.animated) continue; + const flag = e.animated ? '[动画]' : '[ ]'; + const size = e.fontSize == null ? ' - ' : String(e.fontSize).padStart(3) + 'px'; + const body = e.text + ? ` ${e.text.replace(/\s+/g, ' ').slice(0, 90)}` + : ` <${e.type}> x=${e.x} y=${e.y} w=${e.w} h=${e.h}`; + out.push(` ${flag} ${size} ${body}${e.overflow ? ' ⚠可能超宽' : ''}`); + } + } + return out.join('\n'); +} + +/** 重新导出给 inspect_courseware 使用 */ +export function inspectCourseware({ + courseware, page, pages, query, includeElements, includeAnimations = true, format = 'json', +} = {}) { + const cw = resolveCourseware(courseware); + const all = slidesInBoardOrder(cw); + let selected; + if (Array.isArray(pages) && pages.length) { + const nums = [...new Set(pages.map(Number))]; + for (const n of nums) { + if (!Number.isInteger(n) || n < 1 || n > all.length) throw new Error(`页码 ${n} 超出范围(1-${all.length})`); + } + selected = nums.map(n => all[n - 1]); + } else if (page != null) { + const n = Number(page); + if (!Number.isInteger(n) || n < 1 || n > all.length) throw new Error(`页码 ${page} 超出范围(1-${all.length})`); + selected = [all[n - 1]]; + } else { + selected = all; + } + const showElements = includeElements ?? selected.length <= 2; + const items = selected.map(s => { + const item = inspectSlide(s, { includeAnimations }); + if (!showElements) { + item.elements = item.elements.map(e => ({ + id: e.id, type: e.type, text: e.text.slice(0, 120), + fontSize: e.fontSize, animated: e.animated, overflow: e.overflow, + })); + } + return item; + }); + const hasQuery = query != null && String(query) !== ''; + const matches = []; + if (hasQuery) { + const needle = String(query); + for (const s of all) { + const { lines } = readLines(s.file); + for (const el of listElements(lines)) { + if (el.text && el.text.includes(needle)) { + matches.push({ + page: s.page, elementId: el.id, type: el.type, text: el.text, + fontSize: el.fontSizes[0] ?? null, x: el.x, y: el.y, + animated: el.animated, + }); + } + } + } + } + const result = { + courseware: cw.name, localId: cw.localId, pages: all.length, + revision: cw.json.Courseware.Revision, syncedRevision: cw.json.Courseware.SyncedRevision, + inspectedPages: selected.map(s => s.page), items, + }; + if (hasQuery) { result.query = String(query); result.matches = matches; } + if (format === 'text') { + return { + courseware: result.courseware, localId: result.localId, pages: result.pages, + revision: result.revision, syncedRevision: result.syncedRevision, + inspectedPages: result.inspectedPages, query: result.query, + matchCount: matches.length, text: renderInspectText(result), + }; + } + return result; +} + +/** 去掉默认文本属性 / 项目符号属性,只留真正渲染文本的 TextRun 属性 */ +function textRunsBody(body) { + return String(body) + .replace(/[\s\S]*?<\/DefaultRunProperty>/g, '') + .replace(/[\s\S]*?<\/TextMarkerStyle>/g, ''); +} + +/** 在元素 XML 上改样式;DefaultRunProperty / TextMarkerStyle 原样保留 */ +function applyStyleToXml(xml, opts) { + const keep = []; + const masked = xml.replace(/<(DefaultRunProperty|TextMarkerStyle)>[\s\S]*?<\/\1>/g, m => { + keep.push(m); + return `\u0000KEEP${keep.length - 1}\u0000`; + }); + let out = masked; + if (opts.fontSize != null) { + out = out.replace(/[^<]*<\/FontSize>/g, `${opts.fontSize}`); + } + if (opts.bold != null) { + out = out.replace(/[^<]*<\/FontWeight>/g, `${opts.bold ? 'Bold' : 'Normal'}`); + } + if (opts.color) { + out = out.replace(/(\s*)[^<]*(<\/ColorBrush>)/g, `$1${opts.color}$2`); + } + if (opts.align) { + out = out.replace(/[^<]*<\/TextAlignment>/g, `${opts.align}`); + } + if (opts.width != null) { + out = out.replace(/[^<]*<\/Width>/, `${opts.width}`); + } + return out.replace(/\u0000KEEP(\d+)\u0000/g, (m, i) => keep[Number(i)]); +} + export function listElements(lines) { const out = []; lines.forEach((l, i) => { @@ -274,11 +503,19 @@ export function listElements(lines) { const body = lines.slice(i + 1, k).join('\n'); const id = body.match(/([0-9a-fA-F]{32})<\/Id>/)?.[1]; if (!id) return; + const styleBody = textRunsBody(body); out.push({ id, type: tag, body, x: Number(body.match(/([^<]*)<\/X>/)?.[1]), y: Number(body.match(/([^<]*)<\/Y>/)?.[1]), w: Number(body.match(/([^<]*)<\/Width>/)?.[1]), + h: Number(body.match(/([^<]*)<\/Height>/)?.[1]), + fontSizes: [...new Set( + [...styleBody.matchAll(/([\d.]+)<\/FontSize>/g)] + .map(m => Number(m[1])).filter(n => Number.isFinite(n) && n > 0), + )], + bold: /Bold<\/FontWeight>/.test(styleBody), + color: styleBody.match(/\s*(#[0-9A-Fa-f]{6,8})<\/ColorBrush>/)?.[1] ?? null, text: elementText(body), animated: body.includes(''), }); @@ -576,6 +813,36 @@ function resolveBackup(backupId) { return { dir, manifest: readJson(mf) }; } +/** 列出备份快照,可按课件过滤;restore_courseware 的 backupId 就从这里取 */ +export function listBackups({ courseware, limit = 50 } = {}) { + const localId = courseware ? resolveCourseware(courseware).localId : null; + let names = []; + try { names = readdirSync(BACKUP_ROOT); } catch { names = []; } + const items = []; + for (const name of names) { + if (localId && !name.startsWith(localId + '-')) continue; + const dir = path.join(BACKUP_ROOT, name); + const mf = backupManifestPath(dir); + if (!existsSync(mf)) continue; + try { + const m = readJson(mf); + items.push({ + backupId: name, dir, + createdAt: m.createdAt, note: m.note, + name: m.name, localId: m.localId, remoteId: m.remoteId, + revision: m.revision, syncedRevision: m.syncedRevision, size: m.size, + files: Array.isArray(m.files) ? m.files.length : null, + pages: Array.isArray(m.files) ? m.files.filter(f => isSlidePath(f.RelativePath)).length : null, + warnings: m.warnings ?? [], + }); + } catch { /* 跳过坏 manifest */ } + } + items.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)) + || String(b.backupId).localeCompare(String(a.backupId))); + const n = Math.max(1, Number(limit) || 50); + return { count: items.length, backups: items.slice(0, n) }; +} + // ---------------------------------------------------------------- 关/开/同步 function sameCourseware(shell, cw) { const n = String(shell.coursewareName || '').trim(); @@ -911,77 +1178,262 @@ export async function clearAnimations({ } // ---------------------------------------------------------------- 工具:改文字 +function replaceOneElement(lines, el, spec) { + if (spec.text == null && spec.find == null) { + return { missing: { elementId: el.id, reason: '需要 text 或 find' } }; + } + const r = blockRange(lines, el.id); + if (!r) return { missing: { elementId: el.id, reason: '元素块定位失败' } }; + const block = lines.slice(r.start, r.end + 1); + const before = elementText(block.join('\n')); + let after; + + if (spec.text != null) { + after = String(spec.text); + const nonEmpty = new Set([...block.join('\n').matchAll(/([^<]*)<\/Text>/g)] + .map(m => unesc(m[1])).filter(Boolean)); + if (nonEmpty.size > 1) { + throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`); + } + const oldTag = `${esc(before)}`; + for (let i = 0; i < block.length; i++) { + if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`${esc(after)}`); + } + } else { + const find = String(spec.find); + const rep = String(spec.replace ?? ''); + if (!before.includes(find)) return { missing: { elementId: el.id, reason: `文本里没有「${find}」` } }; + after = before.split(find).join(rep); + for (let i = 0; i < block.length; i++) { + block[i] = block[i].replace(/([^<]*)<\/Text>/g, (m, t) => { + const plain = unesc(t); + return plain.includes(find) ? `${esc(plain.split(find).join(rep))}` : m; + }); + } + } + + if (spec.width != null) collapseLines(block, after, Number(spec.width)); + else collapseLines(block, after); + lines.splice(r.start, r.end - r.start + 1, ...block); + return { change: { elementId: el.id, before, after, find: spec.find ?? null } }; +} + +function applyReplacements(lines, replacements, { matchAll = false } = {}) { + const changes = []; + const missing = []; + for (const spec of replacements) { + if (spec.elementId) { + const el = listElements(lines).find(e => e.id === spec.elementId); + if (!el) { missing.push({ elementId: spec.elementId, reason: '元素不存在' }); continue; } + const r = replaceOneElement(lines, el, spec); + if (r.change) changes.push(r.change); else missing.push(r.missing); + continue; + } + if (spec.find) { + const hits = listElements(lines).filter(e => e.type === 'Text' && e.text.includes(spec.find)); + if (!hits.length) { missing.push({ find: spec.find, reason: '没有文本含这段文字' }); continue; } + if (hits.length > 1 && !matchAll) { + throw new Error(`「${spec.find}」匹配到 ${hits.length} 个元素,请加 elementId 或 matchAll=true:` + + hits.map(h => h.id).join(', ')); + } + for (const el of (matchAll ? hits : [hits[0]])) { + const r = replaceOneElement(lines, el, spec); + if (r.change) changes.push(r.change); else missing.push(r.missing); + } + continue; + } + missing.push({ reason: '需要 elementId 或 find' }); + } + return { changes, missing }; +} + +/** 多页时把「这一页没找到」的噪音去掉;真正一次都没命中的才保留 */ +function pruneMissing(missing, changes) { + const foundIds = new Set(changes.map(c => c.elementId)); + const foundFinds = new Set(changes.map(c => c.find).filter(Boolean)); + const seen = new Set(); + return missing.filter(m => { + if (m.elementId && foundIds.has(m.elementId)) return false; + if (m.find && foundFinds.has(m.find)) return false; + const key = m.elementId ? `id:${m.elementId}` : m.find ? `find:${m.find}` : `reason:${m.reason}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + export async function replaceText({ - courseware, page, replacements = [], + courseware, page, pages, allPages = false, replacements = [], matchAll = false, dryRun = false, reopen = true, sync = false, force = false, backup = true, } = {}) { const cw = resolveCourseware(courseware); if (!Array.isArray(replacements) || !replacements.length) throw new Error('replacements 不能为空'); + const pageNumbers = selectedPagesFor(cw, { page, pages, allPages }); + + if (dryRun) { + const allChanges = []; + const allMissing = []; + const reports = []; + for (const n of pageNumbers) { + const { lines } = readLines(slideAt(cw, n).file); + const { changes, missing } = applyReplacements(lines, replacements, { matchAll }); + 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 { file, rec } = slideAt(c, page); - const { lines, eol } = readLines(file); - const changes = []; + 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 } = applyReplacements(lines, replacements, { matchAll }); + if (changes.length) { + writeLines(file, lines, eol); + saveSlideRecord(c, rec, file); + } + reports.push({ page: n, changes, missing }); + allChanges.push(...changes.map(x => ({ page: n, ...x }))); + allMissing.push(...missing.map(x => ({ page: n, ...x }))); + } + return { + courseware: c.name, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + changes: allChanges, + missing: pruneMissing(allMissing, allChanges), + ...(pageNumbers.length === 1 ? {} : { reports }), + }; + }); +} + +// ---------------------------------------------------------------- 工具:改样式 +export async function setTextStyle({ + courseware, page, pages, allPages = false, + elementIds = [], textMatches = [], matchAll = false, + fontSize, bold, color, align, width, dryRun = false, + reopen = true, sync = false, force = false, backup = true, +} = {}) { + const cw = resolveCourseware(courseware); + const pageNumbers = selectedPagesFor(cw, { page, pages, allPages }); + const opts = { + elementIds, textMatches, matchAll, + fontSize: fontSize == null ? null : Number(fontSize), + bold: bold == null ? null : !!bold, + color: color == null || color === '' ? null : normalizeColor(color), + align: align == null || align === '' ? null : String(align), + width: width == null ? null : Number(width), + }; + if (opts.fontSize != null && (!Number.isFinite(opts.fontSize) || opts.fontSize <= 0)) { + throw new Error('fontSize 必须是正数'); + } + if (opts.width != null && (!Number.isFinite(opts.width) || opts.width <= 0)) { + throw new Error('width 必须是正数'); + } + if (opts.align && !['Left', 'Center', 'Right'].includes(opts.align)) { + throw new Error('align 只能是:Left / Center / Right'); + } + if (opts.fontSize == null && opts.bold == null && opts.color == null && opts.align == null && opts.width == null) { + throw new Error('至少要传一个样式参数:fontSize / bold / color / align / width'); + } + + const applyPage = lines => { + const els = listElements(lines).filter(e => e.type === 'Text'); + const picked = []; const missing = []; - - for (const spec of replacements) { - let el = null; - if (spec.elementId) { - el = listElements(lines).find(e => e.id === spec.elementId); - if (!el) { missing.push({ elementId: spec.elementId, reason: '元素不存在' }); continue; } - } else if (spec.find) { - const hits = listElements(lines).filter(e => e.type === 'Text' && e.text.includes(spec.find)); - if (!hits.length) { missing.push({ find: spec.find, reason: '没有文本含这段文字' }); continue; } - if (hits.length > 1) { - throw new Error(`「${spec.find}」匹配到 ${hits.length} 个元素,请加 elementId:` + if (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 (textMatches.length) { + for (const needle of textMatches) { + const hits = els.filter(e => e.text.includes(needle)); + if (!hits.length) missing.push({ text: needle, reason: '没有文本含这段文字' }); + else if (hits.length > 1 && !matchAll) { + throw new Error(`「${needle}」匹配到 ${hits.length} 个元素,请加 elementId 或 matchAll=true:` + hits.map(h => h.id).join(', ')); - } - el = hits[0]; - } else { - missing.push({ reason: '需要 elementId 或 find' }); - continue; + } else picked.push(...(matchAll ? hits : [hits[0]])); } - if (spec.text == null && spec.find == null) { missing.push({ elementId: el.id, reason: '需要 text 或 find' }); continue; } + } + if (!elementIds.length && !textMatches.length) picked.push(...els); + 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 before = elementText(block.join('\n')); - let after; + const before = textStyleOf(el); + const nextBlock = applyStyleToXml(block.join('\n'), opts).split('\n'); + collapseLines(nextBlock, el.text, opts.width ?? undefined); + lines.splice(r.start, r.end - r.start + 1, ...nextBlock); + const updated = listElements(lines).find(e => e.id === el.id) ?? el; + const after = textStyleOf(updated); + const textWidth = estimateTextWidth(el.text, after.fontSize ?? before.fontSize ?? 28); + changes.push({ + elementId: el.id, text: el.text.slice(0, 60), before, after, + estimatedWidth: Math.round(textWidth), + overflow: after.width != null && textWidth > after.width * 1.05, + }); + } + return { changes, missing }; + }; - if (spec.text != null) { - after = String(spec.text); - const nonEmpty = new Set([...block.join('\n').matchAll(/([^<]*)<\/Text>/g)] - .map(m => unesc(m[1])).filter(Boolean)); - if (nonEmpty.size > 1) { - throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`); - } - const oldTag = `${esc(before)}`; - for (let i = 0; i < block.length; i++) { - if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`${esc(after)}`); - } - } else { - const find = String(spec.find); - const rep = String(spec.replace ?? ''); - if (!before.includes(find)) { missing.push({ elementId: el.id, reason: `文本里没有「${find}」` }); continue; } - after = before.split(find).join(rep); - for (let i = 0; i < block.length; i++) { - block[i] = block[i].replace(/([^<]*)<\/Text>/g, (m, t) => { - const plain = unesc(t); - return plain.includes(find) ? `${esc(plain.split(find).join(rep))}` : m; - }); - } + if (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); } - - if (spec.width != null) collapseLines(block, after, Number(spec.width)); - else collapseLines(block, after); - lines.splice(r.start, r.end - r.start + 1, ...block); - changes.push({ elementId: el.id, before, after }); + reports.push({ page: n, changes, missing }); + allChanges.push(...changes.map(x => ({ page: n, ...x }))); + allMissing.push(...missing.map(x => ({ page: n, ...x }))); } - - if (changes.length) { - writeLines(file, lines, eol); - saveSlideRecord(c, rec, file); - } - return { courseware: c.name, page, changes, missing }; + return { + courseware: c.name, + ...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }), + changes: allChanges, + missing: pruneMissing(allMissing, allChanges), + ...(pageNumbers.length === 1 ? {} : { reports }), + }; }); } @@ -1376,6 +1828,117 @@ export async function copySlides({ }); } +// ---------------------------------------------------------------- 工具:删页 / 排序 +export async function deleteSlides({ + courseware, pages = [], trash = true, + reopen = true, sync = false, force = false, backup = true, +} = {}) { + if (!Array.isArray(pages) || !pages.length) throw new Error('pages 不能为空'); + const cw = resolveCourseware(courseware); + const initial = slidesInBoardOrder(cw); + const nums = [...new Set(pages.map(Number))]; + for (const n of nums) { + if (!Number.isInteger(n) || n < 1 || n > initial.length) { + throw new Error(`页码 ${n} 超出范围(1-${initial.length})`); + } + } + if (nums.length >= initial.length) throw new Error('不能删除全部页面,至少保留 1 页'); + + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const all = slidesInBoardOrder(c); + const del = new Set(nums); + const kept = all.filter(s => !del.has(s.page)); + const removed = all.filter(s => del.has(s.page)); + if (!kept.length) throw new Error('不能删除全部页面,至少保留 1 页'); + + let trashDir = null; + if (trash) { + trashDir = path.join(TMP, 'seewo-kit-trash', `${c.localId}-${stamp()}`); + mkdirSync(trashDir, { recursive: true }); + } + const deleted = []; + for (const s of removed) { + const name = path.basename(s.file); + if (trash) { + const dst = path.join(trashDir, name); + try { renameSync(s.file, dst); } catch { + copyFileSync(s.file, dst); + rmSync(s.file, { force: true }); + } + } else { + rmSync(s.file, { force: true }); + } + deleted.push({ page: s.page, slideId: s.id, file: name }); + } + + reindexSlides(c, kept); + writeBoardOrder(c, kept); + return { + courseware: c.name, + deleted, remaining: kept.length, trashDir, + pages: kept.map((s, i) => ({ page: i + 1, slideId: s.id })), + }; + }); +} + +export async function moveSlides({ + courseware, from, to, order, + reopen = true, sync = false, force = false, backup = true, +} = {}) { + const cw = resolveCourseware(courseware); + const initial = slidesInBoardOrder(cw); + if (!(Array.isArray(order) && order.length) && (from == null || to == null)) { + throw new Error('需要 order(完整页序),或 from + to(把 from 页移到 to 位置)'); + } + + const resolveOrder = (all, list) => { + if (list.length !== all.length) throw new Error(`order 必须包含全部 ${all.length} 页`); + const seen = new Set(); + return list.map(value => { + const p = Number(value); + if (!Number.isInteger(p) || p < 1 || p > all.length) { + throw new Error(`order 里的页码 ${value} 超出范围(1-${all.length})`); + } + if (seen.has(p)) throw new Error(`order 里的页码 ${p} 重复`); + seen.add(p); + return all[p - 1]; + }); + }; + const resolveMove = (all, f, t) => { + if (!Number.isInteger(f) || f < 1 || f > all.length) throw new Error(`from 页码 ${f} 超出范围(1-${all.length})`); + if (!Number.isInteger(t) || t < 1 || t > all.length) throw new Error(`to 页码 ${t} 超出范围(1-${all.length})`); + const next = [...all]; + const [moved] = next.splice(f - 1, 1); + next.splice(t - 1, 0, moved); + return next; + }; + + const preview = Array.isArray(order) && order.length + ? resolveOrder(initial, order) + : resolveMove(initial, Number(from), Number(to)); + const oldOrder = initial.map(s => s.page).join(','); + const newOrder = preview.map(s => s.page).join(','); + if (oldOrder === newOrder) { + return { courseware: cw.name, changed: false, order: preview.map(s => s.page) }; + } + + return runEdit(cw, { reopen, sync, force, backup }, async c => { + const all = slidesInBoardOrder(c); + const next = Array.isArray(order) && order.length + ? resolveOrder(all, order) + : resolveMove(all, Number(from), Number(to)); + reindexSlides(c, next); + writeBoardOrder(c, next); + return { + courseware: c.name, changed: true, + from: from == null ? null : Number(from), + to: to == null ? null : Number(to), + order: next.map(s => s.page), + pages: next.map((s, i) => ({ page: i + 1, slideId: s.id, oldPage: s.page })), + }; + }); +} + // ---------------------------------------------------------------- 工具:单独同步 export async function syncCourseware({ courseware } = {}) { const cw = resolveCourseware(courseware); diff --git a/kit/server.mjs b/kit/server.mjs index c0322cf..e0b9919 100644 --- a/kit/server.mjs +++ b/kit/server.mjs @@ -16,6 +16,7 @@ import { setAnimations, getAnimations, clearAnimations, replaceText, verifyCourseware, backupCourseware, restoreCourseware, copySlides, listCoursewares, syncCourseware, pruneOrphanFiles, removeLocalCourseware, + inspectCourseware, setTextStyle, listBackups, deleteSlides, moveSlides, } from './core.mjs'; const log = (...a) => console.error('[seewo-kit]', ...a); @@ -87,17 +88,20 @@ const TOOLS = [ { name: 'replace_text', description: - '批量修改某页文本内容(希沃自带 edit_text_element 不能改文字)。\n' + '批量修改文本内容(希沃自带 edit_text_element 不能改文字)。\n' + 'replacements 每项:{ elementId 或 find, text 或 (find+replace), width? }\n' + '· text:整段替换(要求该元素只有一个不同文本片段)\n' - + '· find+replace:子串替换,必须命中\n' + + '· find+replace:子串替换;同一页命中多个时加 elementId 或 matchAll=true\n' + '· width:可选,传了就按「固定框宽 + 单行折行」重排(适合正文 1160)\n' - + '会更新 折行缓存,避免重开后按旧折行显示。写操作流程同 set_animations。', + + 'page 单页,或 pages 多页,或 allPages=true 全部页。\n' + + 'dryRun=true 只预览改动,不关课件、不写文件。写操作流程同 set_animations。', inputSchema: { type: 'object', properties: { courseware: { type: 'string' }, page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 }, description: '多页模式:页码数组' }, + allPages: { type: 'boolean', default: false, description: '全部页面' }, replacements: { type: 'array', items: { @@ -111,12 +115,116 @@ const TOOLS = [ }, }, }, + matchAll: { type: 'boolean', default: false, description: 'find 命中多个时全部替换' }, + dryRun: { type: 'boolean', default: false, description: '只预览,不写文件、不关/开课件' }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + required: ['replacements'], + }, + }, + { + name: 'inspect_courseware', + description: + '按 Board 页序检查课件内容(只读):每页元素 Id、文字、字号、加粗、颜色、位置、是否带动画、点击顺序,' + + '以及可能的超宽行。\n' + + 'page 单页;pages 多页;不传则全部页(多页默认只给摘要,不展开每页元素)。\n' + + 'query 可全课件搜索文字,返回匹配的页码/元素 Id;format="text" 返回人读清单。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 } }, + query: { type: 'string', description: '按文字包含搜索(全课件)' }, + includeElements: { type: 'boolean', description: '是否展开每页元素;默认单页/双页展开,多页只给摘要' }, + includeAnimations: { type: 'boolean', default: true }, + format: { type: 'string', enum: ['json', 'text'], default: 'json' }, + }, + }, + }, + { + name: 'set_text_style', + description: + '批量改文本样式(不换文字):字号、加粗、颜色、对齐、文本框宽度。\n' + + '用 elementIds / textMatches 选元素;都不传则改所选页的全部文本(建议先 dryRun 预览)。\n' + + 'page 单页,或 pages 多页,或 allPages=true 全部页。\n' + + '颜色用 #RRGGBB 或 #AARRGGBB;改字号后会自动更新折行缓存。', + 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 }, + fontSize: { type: 'number', minimum: 1 }, + bold: { type: 'boolean' }, + color: { type: 'string', description: '#RRGGBB 或 #AARRGGBB' }, + align: { type: 'string', enum: ['Left', 'Center', 'Right'] }, + width: { type: 'number', minimum: 1, description: '文本块宽度,可选' }, + dryRun: { type: 'boolean', default: false, description: '只预览,不写文件、不关/开课件' }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + }, + }, + { + name: 'list_backups', + description: + '列出本地备份快照(backupId / 时间 / 备注 / 页数 / Revision),可按课件过滤。' + + 'restore_courseware 需要的 backupId 就从这个列表取。只读。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string', description: '课件名片段或 LocalId;不传列全部' }, + limit: { type: 'integer', minimum: 1, default: 50 }, + }, + }, + }, + { + name: 'delete_slides', + description: + '按页删除页面:重写 Board.xml 页序、索引 Slides\\Slide_N 映射和 DB。\n' + + '页面文件默认移到 %TEMP%\\opencode\\seewo-kit-trash,不会硬删除;至少保留 1 页。\n' + + '删除后可用 prune_orphan_files 清理不再被索引引用的资源文件。写操作流程同 set_animations。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + pages: { type: 'array', items: { type: 'integer', minimum: 1 }, description: '要删除的页码(按当前页序)' }, + trash: { type: 'boolean', default: true, description: 'true=移到回收目录,false=直接删除' }, + reopen: { type: 'boolean', default: true }, + sync: { type: 'boolean', default: false }, + force: { type: 'boolean', default: false }, + backup: { type: 'boolean', default: true }, + }, + required: ['pages'], + }, + }, + { + name: 'move_slides', + description: + '调整页面顺序:from+to 把第 from 页移到第 to 个位置;或用 order 传完整新页序(当前页码数组)。\n' + + '只重写 Board.xml 和索引映射,不改页面内容。写操作流程同 set_animations。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string' }, + from: { type: 'integer', minimum: 1, description: '当前页码' }, + to: { type: 'integer', minimum: 1, description: '移动后的新位置' }, + order: { type: 'array', items: { type: 'integer', minimum: 1 }, description: '完整新页序(当前页码),如 [3,1,2]' }, reopen: { type: 'boolean', default: true }, sync: { type: 'boolean', default: false }, force: { type: 'boolean', default: false }, backup: { type: 'boolean', default: true }, }, - required: ['page', 'replacements'], }, }, { @@ -245,6 +353,11 @@ const HANDLERS = { get_animations: getAnimations, clear_animations: clearAnimations, replace_text: replaceText, + inspect_courseware: inspectCourseware, + set_text_style: setTextStyle, + list_backups: listBackups, + delete_slides: deleteSlides, + move_slides: moveSlides, verify_courseware: verifyCourseware, backup_courseware: backupCourseware, restore_courseware: restoreCourseware,