#!/usr/bin/env node /** * seewo-anim —— 给希沃白板 5 课件加「点击淡入」动画(逆向版) * * 原理:希沃 MCP 没有动画接口,但动画数据就写在本地保存文件里: * \<账号>\Courseware\<课件Id>\Slide__<...>.xml * · 元素内:FadeInClick… * · 页面末:动画Id… * 所以:关课件 → 改 XML(顺便更新索引里的 MD5 / 文件大小)→ 重开课件。 * 重开后希沃会把动画读进内存,保存/同步时也原样写回云端。 * * 命令: * list --slide 2 列出某页的文本元素(id、位置、文字、是否已加动画) * set --slide 2 --ids id1,id2 给已有元素加动画(只动这几个元素,其它动画保留) * clear --slide 2 --all 清掉某页所有动画;或 --ids a,b 只清这几个 * fix --slide 2 [--width 1160] 把 MCP 新建页的文本块规范成固定框宽 + 单行折行 * answers --plan plan.json 重建空位宽度 + 生成答案框 + 逐个点击淡入 * * 通用参数: * --courseware <名字片段> 不传则用最近改动的课件 * --type FadeIn 动画类型(FadeIn/FadeOut/WipeIn/ZoomIn…) * --trigger Click Click / WithPrevious / AfterPrevious * --duration 0.3 秒 * --delay 0 秒 * --fontSize 28 答案字号(answers) * --color #C0392B 答案文字颜色(answers) * --width 1160 fix 的正文框宽(fix) * --minY 90 fix 只处理 y ≥ 该值的文本块(fix,默认 90 即正文行) * --sync 重开后触发云同步 * --no-reopen 只改文件,不重开课件 * * plan.json 格式: * { "2": [ { "line": "<32位元素Id>", "answers": ["打制"] }, * { "line": "<32位元素Id>", "answers": ["商鞅变法","356","重农抑商"] } ] } * · 行的文字里用 4 个以上下划线表示空位,答案按出现顺序对应 * · 空位不够宽时会自动加宽(保证答案不压到别的字) * · 可选 "base": "整行新文字" 强制替换该行原文(改措辞时用) */ import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from 'node:fs'; import { createHash, randomBytes } from 'node:crypto'; import { execFileSync } from 'node:child_process'; import path from 'node:path'; import os from 'node:os'; import { fileURLToPath } from 'node:url'; const SELF = path.dirname(fileURLToPath(import.meta.url)); const MCP_PORT = process.env.SEEWO_MCP_PORT || '7916'; const APP_DIR = path.join(os.homedir(), 'AppData', 'Roaming', 'Seewo', 'EasiNote5', 'Data'); const TMP = path.join(os.tmpdir(), 'opencode'); if (!existsSync(TMP)) throw new Error('临时目录不存在:' + TMP); // ---------------------------------------------------------------- 参数 const argv = process.argv.slice(2); const command = argv[0]; const opt = {}; for (let i = 1; i < argv.length; i++) { const a = argv[i]; if (!a.startsWith('--')) continue; const k = a.slice(2); const next = argv[i + 1]; if (next && !next.startsWith('--')) { opt[k] = next; i++; } else opt[k] = true; } if (!command) { console.log(readFileSync(new URL(import.meta.url), 'utf8').match(/\/\*\*([\s\S]*?)\*\//)[1].replace(/^ \* ?/gm, '').trim()); process.exit(0); } // ---------------------------------------------------------------- MCP let sessionId = null; async function post(body) { const h = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }; if (sessionId) h['Mcp-Session-Id'] = sessionId; const res = await fetch(`http://127.0.0.1:${MCP_PORT}/mcp`, { method: 'POST', headers: h, body: JSON.stringify(body) }); if (!sessionId) sessionId = res.headers.get('mcp-session-id'); const text = await res.text(); if (text.includes('data:')) { const data = text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join(''); try { return JSON.parse(data); } catch { return { raw: data }; } } try { return JSON.parse(text); } catch { return { raw: text }; } } let rpcId = 3; async function mcp(name, args = {}) { const r = await post({ jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }); if (r.error) throw new Error(`${name}: ${JSON.stringify(r.error)}`); const txt = (r.result?.content ?? []).filter(c => c.type === 'text').map(c => c.text).join('\n'); if (r.result?.isError) throw new Error(`${name}: ${txt}`); return { text: txt, data: r.result?.structuredContent }; } async function mcpInit() { await post({ jsonrpc: '2.0', id: 0, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-anim', version: '1.0' } } }); await post({ jsonrpc: '2.0', method: 'notifications/initialized' }); } const sleep = ms => new Promise(r => setTimeout(r, ms)); const shells = () => mcp('en_find_shells', { searchingMode: 'All' }).then(r => r.data?.shells ?? []).catch(() => []); async function closeCourseware() { for (let i = 0; i < 20; i++) { const s = await shells(); if (!s.length) return true; await mcp('close_current_courseware', { shellId: s[0].id, syncBeforeClose: false }).catch(() => {}); await sleep(700); } return (await shells()).length === 0; } async function openCourseware(name) { await mcp('open_cloud_courseware', { coursewareName: name }); for (let i = 0; i < 40; i++) { await sleep(700); const s = await shells(); if (s.length) return s[0].id; } return null; } /** 做一次无害改动,让希沃认为课件「未同步」,否则 sync 只会下载 */ async function touch(shellId) { const info = await mcp('get_current_courseware_info', { shellId }); const count = info.data?.slideCount ?? 0; const add = await mcp('add_slide', { shellId, slideNumber: count }).catch(() => null); if (add?.data?.slideNumber) await mcp('delete_slide', { shellId, slideNumber: add.data.slideNumber }).catch(() => {}); } // ---------------------------------------------------------------- 课件定位 function findCoursewares() { const out = []; for (const user of existsSync(APP_DIR) ? readdirSync(APP_DIR) : []) { const root = path.join(APP_DIR, user, 'Courseware'); if (!existsSync(root)) continue; for (const id of readdirSync(root)) { const dir = path.join(root, id); const jp = path.join(dir, `${id}.json`); if (!existsSync(jp)) continue; try { const json = JSON.parse(readFileSync(jp, 'utf8').replace(/^\uFEFF/, '')); out.push({ dir, jsonPath: jp, json, name: json.Courseware?.Name ?? '', mtime: statSync(jp).mtimeMs }); } catch { /* skip */ } } } return out.sort((a, b) => b.mtime - a.mtime); } function pickCourseware() { const all = findCoursewares(); if (!all.length) throw new Error('找不到本地课件缓存'); if (!opt.courseware) return all[0]; const hit = all.find(c => c.name.includes(opt.courseware)); if (!hit) throw new Error(`没有名字含「${opt.courseware}」的课件。可选:${all.map(c => c.name).join(' / ')}`); return hit; } function slideRecord(cw, n) { const rec = cw.json.CoursewareFiles.find(f => f.RelativePath === `Slides\\Slide_${n - 1}.xml`); if (!rec) throw new Error(`课件里没有第 ${n} 页`); return { rec, file: path.join(cw.dir, rec.FileName) }; } // ---------------------------------------------------------------- XML 工具 const blockRange = (lines, elementId) => { const idIdx = lines.findIndex(l => l.trim() === `${elementId}`); if (idIdx < 0) return null; let start = idIdx; while (start >= 0 && !/^ {4}<[A-Za-z]+>\s*$/.test(lines[start])) start--; if (start < 0) return null; const tag = lines[start].trim().replace(/[<>]/g, ''); let end = idIdx; while (end < lines.length && lines[end].trim() !== ``) end++; return { start, end, tag }; }; const elementText = (body) => { const cands = [...body.matchAll(/([^<]*)<\/Text>/g)].map(m => m[1]).filter(t => t.trim()); cands.sort((a, b) => b.length - a.length); return cands[0] ?? ''; }; const listElements = (lines) => { const out = []; lines.forEach((l, i) => { if (!/^ {4}<[A-Za-z]+>\s*$/.test(l)) return; const tag = l.trim().replace(/[<>]/g, ''); let k = i + 1; while (k < lines.length && lines[k].trim() !== ``) k++; const body = lines.slice(i + 1, k).join('\n'); const id = body.match(/([0-9a-f]{32})<\/Id>/)?.[1]; if (!id) return; out.push({ id, type: tag, body, x: Number(body.match(/([^<]*)<\/X>/)?.[1]), y: Number(body.match(/([^<]*)<\/Y>/)?.[1]), w: Number(body.match(/([^<]*)<\/Width>/)?.[1]), text: elementText(body), animated: body.includes(''), }); }); return out; }; const animNode = (id, o) => [ ' ', ' ', ` ${o.type}`, ` ${id}`, ' 1', ' Appearance', ` ${o.trigger}`, ' ', ` ${Math.round(o.duration * 10000000)}`, ` ${Math.round(o.delay * 10000000)}`, ' 1', ' 0', ' 1', ' 0', ' 1', ' ', ' ', ]; /** * 把文本块的排版信息改写成「固定框宽 + 单行折行」: * MCP 新建的文本会把折行结果写进 ,且 SizeToContent=Height; * 只改 而不动这里,重开课件仍按旧折行位置渲染,看着像文字串行。 */ function collapseLines(block, text) { const n = [...text].length; const sc = block.findIndex(l => //.test(l)); if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*Manual<'); const ls = block.findIndex(l => l.trim() === ''); if (ls >= 0) { let le = ls; while (le < block.length && block[le].trim() !== '') le++; block.splice(ls + 1, le - ls - 1, ' ', ' 0', ` ${n}`, ' '); return; } for (let i = 0; i < block.length; i++) { const m = block[i].match(/^(\s*)\d+<\/Length>$/); if (m) { block[i] = `${m[1]}${n}`; break; } } } function stripAnimations(lines) { const out = []; for (let i = 0; i < lines.length; i++) { const t = lines[i].trim(); if (t === '' || t === '') { const close = t.replace('<', ':先删旧的,再按元素在页面里的先后重新排 */ function rebuildOrders(lines) { const oStart = lines.findIndex(l => l.trim() === ''); if (oStart >= 0) { let oEnd = oStart; while (oEnd < lines.length && lines[oEnd].trim() !== '') oEnd++; lines.splice(oStart, oEnd - oStart + 1); } const ids = []; for (const el of listElements(lines)) { const m = el.body.match(/[\s\S]*?([0-9a-f]{32})<\/Id>/); if (m) ids.push(m[1]); } if (!ids.length) return ids; const closeIdx = lines.map(l => l.trim()).lastIndexOf(''); lines.splice(closeIdx, 0, ' ', ...ids.map(x => ` ${x}`), ' '); return ids; } /** 给一个元素写动画:先删它自己原有的 ,再插新的。返回 {animId, replaced} */ function addAnimationToElement(lines, elementId, o) { const r = blockRange(lines, elementId); if (!r) return null; const block = lines.slice(r.start, r.end + 1); let replaced = 0; const a = block.findIndex(l => l.trim() === ''); if (a >= 0) { let b = a; while (b < block.length && block[b].trim() !== '') b++; replaced = 1; block.splice(a, b - a + 1); } const animId = randomBytes(16).toString('hex'); let at = block.findIndex(l => l.trim() === ''); if (at < 0) at = block.findIndex(l => l.trim() === ''); if (at < 0) at = block.length - 1; block.splice(at, 0, ...animNode(animId, o)); lines.splice(r.start, r.end - r.start + 1, ...block); return { animId, replaced }; } // ---------------------------------------------------------------- 量字 function measure(strings) { const inFile = path.join(TMP, 'seewo_measure_in.json'); const outFile = path.join(TMP, 'seewo_measure_out.json'); const map = {}; strings.forEach((s, i) => { map[`s${i}`] = s; }); writeFileSync(inFile, JSON.stringify(map, null, 1), 'utf8'); execFileSync('powershell', ['-ExecutionPolicy', 'Bypass', '-File', path.join(SELF, 'measure.ps1'), '-InFile', inFile, '-OutFile', outFile], { stdio: 'ignore' }); const w = JSON.parse(readFileSync(outFile, 'utf8').replace(/^\uFEFF/, '')); return strings.map((_, i) => w[`s${i}`]); } // ---------------------------------------------------------------- 保存 function saveSlide(cw, rec, file) { rec.FileHash = createHash('md5').update(readFileSync(file)).digest('hex'); rec.FileSize = statSync(file).size; } function bumpRevision(cw) { cw.json.Courseware.Revision = (cw.json.Courseware.Revision ?? 0) + 1; writeFileSync(cw.jsonPath, JSON.stringify(cw.json, null, 2), 'utf8'); } // ---------------------------------------------------------------- 主流程 const animOpts = () => ({ type: opt.type ?? 'FadeIn', trigger: ['Click', 'WithPrevious', 'AfterPrevious'].includes(opt.trigger) ? opt.trigger : 'Click', duration: Number(opt.duration ?? 0.3), delay: Number(opt.delay ?? 0), }); async function main() { const cw = pickCourseware(); if (command === 'list') { const n = Number(opt.slide ?? 1); const { file } = slideRecord(cw, n); const els = listElements(readFileSync(file, 'utf8').split(/\r?\n/)).filter(e => e.type === 'Text'); console.log(JSON.stringify({ courseware: cw.name, slide: n, elements: els.map(({ body, ...e }) => e) }, null, 2)); return; } if (command === 'set' || command === 'clear') { const n = Number(opt.slide ?? 1); const ids = String(opt.ids ?? '').split(',').map(s => s.trim()).filter(Boolean); if (command === 'set' && !ids.length) throw new Error('set 需要 --ids id1,id2'); if (command === 'clear' && !opt.all && !ids.length) throw new Error('clear 需要 --all 或 --ids'); await mcpInit(); await closeCourseware(); const { rec, file } = slideRecord(cw, n); const eol = readFileSync(file, 'utf8').includes('\r\n') ? '\r\n' : '\n'; let lines = readFileSync(file, 'utf8').split(/\r?\n/); const before = [...readFileSync(file, 'utf8').matchAll(//g)].length; let added = 0; let replaced = 0; const missing = []; if (command === 'clear') { // 只删指定元素(或不传 --ids 时删整页)的动画,其它元素不动 if (opt.all) { lines = stripAnimations(lines); } else { for (const id of ids) { const r = blockRange(lines, id); if (!r) { missing.push(id); continue; } const block = lines.slice(r.start, r.end + 1); const a = block.findIndex(l => l.trim() === ''); if (a >= 0) { let b = a; while (b < block.length && block[b].trim() !== '') b++; block.splice(a, b - a + 1); lines.splice(r.start, r.end - r.start + 1, ...block); } } } } else { for (const id of ids) { const res = addAnimationToElement(lines, id, animOpts()); if (res) { added++; replaced += res.replaced; } else missing.push(id); } } const orders = rebuildOrders(lines); writeFileSync(file, lines.join(eol), 'utf8'); saveSlide(cw, rec, file); bumpRevision(cw); const report = { courseware: cw.name, slide: n, added, replaced, missing, animations: `${before} → ${orders.length}`, }; if (!opt['no-reopen']) report.shellId = await openCourseware(cw.name); if (opt.sync && report.shellId) { await touch(report.shellId); report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; } console.log(JSON.stringify(report, null, 2)); return; } if (command === 'fix') { // 把 MCP 新建页的文本块从「按内容自适应」改成「固定框宽 + 单行折行」 const pages = String(opt.slide ?? 1).split(',').map(s => Number(s.trim())).filter(Boolean); const WIDTH = Number(opt.width ?? 1160); const minY = Number(opt.minY ?? 90); const only = String(opt.ids ?? '').split(',').map(s => s.trim()).filter(Boolean); if (!opt['no-reopen']) { await mcpInit(); await closeCourseware(); } const report = { courseware: cw.name, width: WIDTH, slides: {} }; for (const n of pages) { const { rec, file } = slideRecord(cw, n); const eol = readFileSync(file, 'utf8').includes('\r\n') ? '\r\n' : '\n'; const lines = readFileSync(file, 'utf8').split(/\r?\n/); const targets = listElements(lines) .filter(e => e.type === 'Text') .filter(e => (only.length ? only.includes(e.id) : e.y >= minY)); const missing = only.filter(id => !targets.some(e => e.id === id)); let fixed = 0; for (const el of targets) { const r = blockRange(lines, el.id); if (!r) { missing.push(el.id); continue; } const block = lines.slice(r.start, r.end + 1); const wi = block.findIndex(l => /^\s*[^<]*<\/Width>$/.test(l)); if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}${WIDTH}`; collapseLines(block, el.text); lines.splice(r.start, r.end - r.start + 1, ...block); fixed++; } writeFileSync(file, lines.join(eol), 'utf8'); saveSlide(cw, rec, file); report.slides[n] = { fixed, missing }; } bumpRevision(cw); if (!opt['no-reopen']) report.shellId = await openCourseware(cw.name); if (opt.sync && report.shellId) { await touch(report.shellId); report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; } console.log(JSON.stringify(report, null, 2)); return; } if (command === 'answers') { const planFile = opt.plan; if (!planFile) throw new Error('缺少 --plan plan.json'); const plan = JSON.parse(readFileSync(planFile, 'utf8').replace(/^\uFEFF/, '')); const FONT = Number(opt.fontSize ?? 28); const COLOR = opt.color ?? '#C0392B'; const BLANK_RE = /_{4,}/g; await mcpInit(); await closeCourseware(); // 先读出每行原文 const lineInfo = {}; // id -> {text,x,y,slide} for (const n of Object.keys(plan)) { const { file } = slideRecord(cw, Number(n)); const lines = readFileSync(file, 'utf8').split(/\r?\n/); for (const el of listElements(lines)) { if (el.type !== 'Text') continue; lineInfo[el.id] = { ...el, slide: Number(n) }; } } // 第一轮测量 const need = []; for (const [n, rows] of Object.entries(plan)) { rows.forEach(r => { const L = lineInfo[r.line]; if (!L) throw new Error(`第${n}页找不到行 ${r.line}`); r._base = r.base ?? L.text; r._blanks = [...r._base.matchAll(BLANK_RE)].map(m => m[0]); if (r._blanks.length !== r.answers.length) throw new Error(`第${n}页行 ${r.line.slice(0, 6)} 空位 ${r._blanks.length} 个,答案 ${r.answers.length} 个,数量不一致\n文字:${r._base}`); r.answers.forEach(a => need.push(a)); need.push(r._blanks[0]); }); } const widths = measure(need); let p = 0; for (const [n, rows] of Object.entries(plan)) { rows.forEach(r => { r._ansW = r.answers.map(() => widths[p++]); r._blankW = widths[p++]; const maxAns = Math.max(...r._ansW); const per = r._blankW / r._blanks[0].length; r._nUnder = maxAns > r._blankW ? Math.ceil((maxAns + 16) / per) : r._blanks[0].length; r._newBlank = '_'.repeat(r._nUnder); r._finalText = r._base.replace(BLANK_RE, () => r._newBlank); }); } // 第二轮:按最终文本量前缀 const need2 = []; for (const [n, rows] of Object.entries(plan)) { rows.forEach(r => { let from = 0; r._prefixW = r.answers.map(() => 0); r._prefixes = []; for (let i = 0; i < r.answers.length; i++) { const idx = r._finalText.indexOf(r._newBlank, from); const pre = r._finalText.slice(0, idx); r._prefixes.push(pre); need2.push(pre); from = idx + r._newBlank.length; } need2.push(r._newBlank); }); } const w2 = measure(need2); let q = 0; for (const [n, rows] of Object.entries(plan)) { rows.forEach(r => { r._prefixW = r.answers.map(() => w2[q++]); r._blankW2 = w2[q++]; }); } // 写入 const log = []; for (const [n, rows] of Object.entries(plan)) { const { rec, file } = slideRecord(cw, Number(n)); const orig = readFileSync(file, 'utf8'); const eol = orig.includes('\r\n') ? '\r\n' : '\n'; let lines = orig.split(/\r?\n/); lines = stripAnimations(lines); // 1) 改写行文字(加宽空位) for (const r of rows) { const L = lineInfo[r.line]; if (r._finalText === L.text) continue; const rr = blockRange(lines, r.line); if (!rr) { log.push(`!! 缺行 ${r.line}`); continue; } const block = lines.slice(rr.start, rr.end + 1); const oldTag = `${L.text}`; const newTag = `${r._finalText}`; for (let i = 0; i < block.length; i++) if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(newTag); collapseLines(block, r._finalText); lines.splice(rr.start, rr.end - rr.start + 1, ...block); log.push(`第${n}页 行 ${r.line.slice(0, 6)} 空位加宽 ${r._blanks[0].length}→${r._nUnder} 个下划线`); } // 2) 克隆答案元素 let count = 0; for (const r of rows) { const L = lineInfo[r.line]; const rr = blockRange(lines, r.line); if (!rr) continue; const tpl = lines.slice(rr.start, rr.end + 1); for (let i = 0; i < r.answers.length; i++) { const ansW = r._ansW[i]; const x = Math.round((L.x + r._prefixW[i] + Math.max(0, (r._blankW2 - ansW) / 2)) * 10) / 10; const block = tpl.map(l => l .replace(/[0-9a-f]{32}<\/Id>/, `${randomBytes(16).toString('hex')}`) .replace(/[^<]*<\/X>/, `${x}`) .replace(/[^<]*<\/Y>/, `${L.y}`) .replace(/[^<]*<\/Width>/, `${Math.round((ansW + 20) * 100) / 100}`) .replace(/\d+<\/Length>/, `${[...r.answers[i]].length}`) .replace(/#FF000000/g, '#FF' + COLOR.replace('#', '')) .replace(/Normal<\/FontWeight>/g, 'Bold') .replace(/[^<]*<\/Text>/g, `${r.answers[i]}`)); const at = block.findIndex(l => l.trim() === ''); const pos = at < 0 ? block.length - 1 : at; block.splice(pos, 0, ...animNode(randomBytes(16).toString('hex'), animOpts())); const endElements = lines.map(l => l.trim()).lastIndexOf(''); lines.splice(endElements, 0, ...block); count++; } } const orders = rebuildOrders(lines); writeFileSync(file, lines.join(eol), 'utf8'); saveSlide(cw, rec, file); log.push(`第${n}页 新增 ${count} 个答案框,页面动画 ${orders.length} 个`); } bumpRevision(cw); const report = { courseware: cw.name, log }; if (!opt['no-reopen']) report.shellId = await openCourseware(cw.name); if (opt.sync && report.shellId) { await touch(report.shellId); report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; if (String(report.sync).includes('下载')) { await touch(report.shellId); report.sync = (await mcp('sync_current_courseware', { shellId: report.shellId, waitUntilSynced: true, waitSeconds: 120 }).catch(e => ({ text: 'ERR ' + e.message }))).text; } } console.log(JSON.stringify(report, null, 2)); return; } throw new Error(`未知命令:${command}`); } main().catch(e => { console.error(String(e?.message ?? e)); process.exit(1); });