/** * seewo-kit 核心库 * * 希沃白板 5 的 MCP 没有动画 / 跨课件复制 / 文本改写 / 课件自检能力, * 但课件缓存都是明文(索引 JSON + 每页 XML + SQLite 缓存库), * 所以这里直接操作缓存文件,并通过希沃自己的 MCP 负责「关课件 / 开课件 / 同步」。 * * 约定: * · 所有写操作前,如果目标课件正开着,先关闭(syncBeforeClose=false) * · 关闭前检查「内存里的页数/大小」和磁盘索引是否一致,防止丢掉未同步的新页 * · 写完后更新索引 JSON(FileHash/FileSize/Revision)和 CoursewareCacheData.db * · 默认重新打开课件;sync=true 时再触发一次云同步 */ import { readFileSync, writeFileSync, readdirSync, statSync, existsSync, mkdirSync, copyFileSync, rmSync, renameSync, } from 'node:fs'; import { createHash, randomUUID, randomBytes } from 'node:crypto'; import path from 'node:path'; import os from 'node:os'; import { DatabaseSync } from 'node:sqlite'; // ---------------------------------------------------------------- 常量 const MCP_PORT = process.env.SEEWO_MCP_PORT || '7916'; const APP_DATA = path.join(os.homedir(), 'AppData', 'Roaming', 'Seewo', 'EasiNote5', 'Data'); const BACKUP_ROOT = path.join(os.tmpdir(), 'opencode', 'seewo-kit-backups'); const MAX_BACKUPS = 10; const SLIDE_RE = /^Slides[\\/]Slide_\d+\.xml$/i; const TMP = path.join(os.tmpdir(), 'opencode'); mkdirSync(BACKUP_ROOT, { recursive: true }); const sleep = ms => new Promise(r => setTimeout(r, ms)); const md5 = buf => createHash('md5').update(buf).digest('hex'); const md5File = f => md5(readFileSync(f)); const rand = n => { const cs = 'abcdefghijkmnopqrstuvwxyz0123456789'; let s = ''; for (let i = 0; i < n; i++) s += cs[Math.floor(Math.random() * cs.length)]; return s; }; const stamp = () => { const d = new Date(); const p = n => String(n).padStart(2, '0'); return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`; }; const isSlidePath = p => SLIDE_RE.test(String(p || '').replace(/\//g, '\\')); // ---------------------------------------------------------------- 希沃 MCP 客户端 let sessionId = null; let rpcId = 100; let initialized = false; async function post(body, timeoutMs = 30000) { const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }; if (sessionId) headers['Mcp-Session-Id'] = sessionId; const res = await fetch(`http://127.0.0.1:${MCP_PORT}/mcp`, { method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs), }); const sid = res.headers.get('mcp-session-id'); if (sid) sessionId = sid; const text = await res.text(); if (text.includes('data:')) { const data = text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join(''); try { return JSON.parse(data); } catch { return { raw: data }; } } try { return JSON.parse(text); } catch { return { raw: text }; } } async function rpc(name, args = {}, { timeoutMs } = {}) { const r = await post({ jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }, timeoutMs); if (r.error) throw new Error(`${name}: ${JSON.stringify(r.error)}`); const txt = (r.result?.content ?? []).filter(c => c.type === 'text').map(c => c.text).join('\n'); if (r.result?.isError) throw new Error(`${name}: ${txt}`); return { text: txt, data: r.result?.structuredContent }; } async function ensureInit() { if (initialized) return; await post({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-kit', version: '1.0' } }, }); await post({ jsonrpc: '2.0', method: 'notifications/initialized' }); initialized = true; } async function mcp(name, args = {}, { timeoutMs } = {}) { await ensureInit(); try { return await rpc(name, args, { timeoutMs }); } catch (e) { // 会话过期时重新握手一次 if (/session|会话|ShellId/i.test(String(e.message))) { sessionId = null; initialized = false; await ensureInit(); return await rpc(name, args, { timeoutMs }); } throw e; } } const shells = () => mcp('en_find_shells', { searchingMode: 'All' }) .then(r => r.data?.shells ?? []) .catch(() => []); // ---------------------------------------------------------------- 课件定位 export function listCoursewares() { const out = []; if (!existsSync(APP_DATA)) return out; for (const user of readdirSync(APP_DATA)) { const root = path.join(APP_DATA, user, 'Courseware'); if (!existsSync(root)) continue; for (const id of readdirSync(root)) { const dir = path.join(root, id); if (!statSync(dir).isDirectory()) continue; const jsonPath = path.join(dir, `${id}.json`); if (!existsSync(jsonPath)) continue; try { const json = JSON.parse(readFileSync(jsonPath, 'utf8').replace(/^\uFEFF/, '')); if (!json.Courseware) continue; out.push({ dir, jsonPath, json, userDir: path.dirname(root), name: json.Courseware.Name ?? '', localId: id, mtime: statSync(jsonPath).mtimeMs, }); } catch { /* 跳过坏索引 */ } } } return out.sort((a, b) => b.mtime - a.mtime); } export function duplicatesOf(coursewares, target) { const name = String(target.name || '').trim(); return coursewares.filter( c => c.localId !== target.localId && String(c.name || '').trim() === name, ); } /** 同名多份时直接报错,避免按 mtime 静默选错课件 */ export function resolveCourseware(query) { const all = listCoursewares(); if (!all.length) throw new Error('找不到本地课件缓存(希沃是否安装并登录过?)'); if (!query) return assertUniqueLocalName(all[0], all); const q = String(query).trim(); const byId = all.find(c => c.localId === q); if (byId) return byId; const hits = all.filter(c => c.name.includes(q)); if (!hits.length) { throw new Error(`没有名字含「${q}」的课件。可选:${all.slice(0, 8).map(c => c.name).join(' / ')}`); } const groups = new Map(); for (const c of hits) { const n = String(c.name).trim(); if (!groups.has(n)) groups.set(n, []); groups.get(n).push(c); } const dupes = [...groups.entries()].filter(([, v]) => v.length > 1); if (dupes.length) { const lines = dupes.flatMap(([n, v]) => v.map(c => ` · ${n} localId=${c.localId} remoteId=${c.json.Courseware.RemoteId || '(无)'} rev=${c.json.Courseware.Revision}`)); throw new Error(`匹配到重名课件,无法确定要操作哪一份:\n${lines.join('\n')}\n` + '请改用 localId 指定,或先调用 remove_local_courseware 清理重复。'); } return hits[0]; } function assertUniqueLocalName(cw, all = listCoursewares()) { const dupes = duplicatesOf(all, cw); if (dupes.length) { throw new Error(`课件「${cw.name}」还有 ${dupes.length} 份同名本地副本:` + dupes.map(c => `${c.localId}(remoteId=${c.json.Courseware.RemoteId || '无'})`).join('、') + '。为避免开错/覆盖错课件,请先用 localId 指定,或调用 remove_local_courseware 清理重复。'); } return cw; } // ---------------------------------------------------------------- 文件 / XML const readText = f => readFileSync(f, 'utf8'); const readJson = f => JSON.parse(readFileSync(f, 'utf8').replace(/^\uFEFF/, '')); const readLines = f => { const raw = readText(f); return { lines: raw.split(/\r?\n/), eol: raw.includes('\r\n') ? '\r\n' : '\n' }; }; const writeLines = (f, lines, eol) => writeFileSync(f, lines.join(eol), 'utf8'); function writeJson(cw) { writeFileSync(cw.jsonPath, '\uFEFF' + JSON.stringify(cw.json, null, 2), 'utf8'); } export function slideRecords(cw) { return cw.json.CoursewareFiles.filter(f => isSlidePath(f.RelativePath)); } function boardRecord(cw) { const rec = cw.json.CoursewareFiles.find(f => String(f.RelativePath).replace(/\//g, '\\') === 'Board.xml'); if (!rec) throw new Error(`课件「${cw.name}」没有 Board.xml 记录`); return rec; } export function readBoard(cw) { const rec = boardRecord(cw); const xml = readText(path.join(cw.dir, rec.FileName)); const block = xml.match(/([\s\S]*?)<\/Slides>/)?.[1] ?? ''; const ids = [...block.matchAll(/([0-9a-fA-F]{32})<\/Item>/g)].map(m => m[1]); return { rec, file: path.join(cw.dir, rec.FileName), xml, ids }; } const slideXmlId = xml => xml.match(/\s*([0-9a-fA-F]{32})<\/Id>/)?.[1] ?? null; /** 按 Board.xml 的页序返回 [{page, id, rec, file, xml}] */ export function slidesInBoardOrder(cw) { const { ids } = readBoard(cw); const byId = new Map(); for (const rec of slideRecords(cw)) { const file = path.join(cw.dir, rec.FileName); if (!existsSync(file)) continue; const xml = readText(file); const id = slideXmlId(xml); if (id) byId.set(id.toLowerCase(), { rec, file, xml }); } const out = []; const missing = []; ids.forEach((id, i) => { const hit = byId.get(id.toLowerCase()); if (!hit) missing.push({ page: i + 1, id }); else out.push({ page: i + 1, id, ...hit }); }); if (missing.length) { throw new Error(`页序表里有 ${missing.length} 页在索引中找不到对应 XML:${JSON.stringify(missing.slice(0, 5))}`); } return out; } export function slideAt(cw, page) { const list = slidesInBoardOrder(cw); if (!Number.isInteger(page) || page < 1 || page > list.length) { throw new Error(`页码 ${page} 超出范围(1-${list.length})`); } return list[page - 1]; } const blockRange = (lines, elementId) => { const idIdx = lines.findIndex(l => l.trim() === `${elementId}`); if (idIdx < 0) return null; let start = idIdx; while (start >= 0 && !/^ {4}<[A-Za-z]+>\s*$/.test(lines[start])) start--; if (start < 0) return null; const tag = lines[start].trim().replace(/[<>]/g, ''); let end = idIdx; while (end < lines.length && lines[end].trim() !== ``) end++; if (end >= lines.length) return null; return { start, end, tag }; }; const unesc = s => String(s).replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); const esc = s => String(s).replace(/&/g, '&').replace(//g, '>'); const elementText = body => { const cands = [...body.matchAll(/([^<]*)<\/Text>/g)].map(m => unesc(m[1])).filter(t => t.trim()); cands.sort((a, b) => b.length - a.length); return cands[0] ?? ''; }; /** 把 #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); } 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); 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), 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)}`), 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) => { if (!/^ {4}<[A-Za-z]+>\s*$/.test(l)) return; const tag = l.trim().replace(/[<>]/g, ''); let k = i + 1; while (k < lines.length && lines[k].trim() !== ``) k++; const body = lines.slice(i + 1, k).join('\n'); const id = body.match(/([0-9a-fA-F]{32})<\/Id>/)?.[1]; if (!id) return; 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(''), }); }); return out; } /** 给文本块写「固定框宽 + 单行折行」,避免只改 后按旧折行渲染 */ function collapseLines(block, text, width) { if (width != null) { const wi = block.findIndex(l => /^\s*[^<]*<\/Width>$/.test(l)); if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}${width}`; const sc = block.findIndex(l => //.test(l)); if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*Manual<'); } const ls = block.findIndex(l => l.trim() === ''); const n = [...text].length; if (ls >= 0) { let le = ls; while (le < block.length && block[le].trim() !== '') le++; block.splice(ls + 1, le - ls - 1, ' ', ' 0', ` ${n}`, ' '); return; } for (let i = 0; i < block.length; i++) { const m = block[i].match(/^(\s*)\d+<\/Length>$/); if (m) { block[i] = `${m[1]}${n}`; break; } } } // ---------------------------------------------------------------- 动画 const animNode = (id, o) => [ ' ', ' ', ` ${o.type}`, ` ${id}`, ' 1', ' Appearance', ` ${o.trigger}`, ' ', ` ${Math.round(o.duration * 10000000)}`, ` ${Math.round(o.delay * 10000000)}`, ' 1', ' 0', ' 1', ' 0', ' 1', ' ', ' ', ]; const ANIM_TYPES = ['FadeIn', 'FadeOut', 'WipeIn', 'WipeOut', 'ZoomIn', 'ZoomOut', 'FlyIn', 'FloatIn', 'Appear']; const TRIGGERS = ['Click', 'WithPrevious', 'AfterPrevious']; function stripAnimations(lines) { const out = []; for (let i = 0; i < lines.length; i++) { const t = lines[i].trim(); if (t === '' || t === '') { const close = t.replace('<', ':先删旧的,再按元素在页面里的先后重新排 */ function rebuildOrders(lines) { const oStart = lines.findIndex(l => l.trim() === ''); if (oStart >= 0) { let oEnd = oStart; while (oEnd < lines.length && lines[oEnd].trim() !== '') oEnd++; lines.splice(oStart, oEnd - oStart + 1); } const ids = []; for (const el of listElements(lines)) { const m = el.body.match(/[\s\S]*?([0-9a-fA-F]{32})<\/Id>/); if (m) ids.push(m[1]); } if (!ids.length) return ids; const closeIdx = lines.map(l => l.trim()).lastIndexOf(''); lines.splice(closeIdx, 0, ' ', ...ids.map(x => ` ${x}`), ' '); return ids; } function addAnimationToElement(lines, elementId, o) { const r = blockRange(lines, elementId); if (!r) return null; const block = lines.slice(r.start, r.end + 1); let replaced = 0; const a = block.findIndex(l => l.trim() === ''); if (a >= 0) { let b = a; while (b < block.length && block[b].trim() !== '') b++; replaced = 1; block.splice(a, b - a + 1); } const animId = randomBytes(16).toString('hex'); let at = block.findIndex(l => l.trim() === ''); if (at < 0) at = block.findIndex(l => l.trim() === ''); if (at < 0) at = block.length - 1; block.splice(at, 0, ...animNode(animId, o)); lines.splice(r.start, r.end - r.start + 1, ...block); return { animId, replaced }; } function parseAnimations(body) { const out = []; for (const block of body.matchAll(/([\s\S]*?)<\/Animations>/g)) { for (const a of block[1].matchAll(/([\s\S]*?)<\/Animation>/g)) { const g = t => a[1].match(new RegExp(`<${t}>([^<]*)`))?.[1]; out.push({ id: g('Id'), type: g('Type'), trigger: g('Trigger'), duration: Number(g('Duration') || 0) / 1e7, delay: Number(g('Delay') || 0) / 1e7, }); } } return out; } function parseOrders(lines) { const start = lines.findIndex(l => l.trim() === ''); if (start < 0) return []; let end = start; while (end < lines.length && lines[end].trim() !== '') end++; return lines.slice(start + 1, end) .map(l => l.match(/([0-9a-fA-F]{32})<\/Item>/)?.[1]) .filter(Boolean); } function resolveTargets(lines, { elementIds = [], textMatches = [], matchAll = false }) { const els = listElements(lines).filter(e => e.type === 'Text' || e.type === 'Picture' || e.type === 'Shape'); const byId = new Map(els.map(e => [e.id, e])); const picked = []; const missing = []; for (const id of elementIds) { if (byId.has(id)) picked.push(byId.get(id)); else missing.push({ elementId: id, reason: '元素不存在' }); } for (const needle of textMatches) { const hits = els.filter(e => e.text && e.text.includes(needle)); if (!hits.length) missing.push({ text: needle, reason: '没有文本含这段文字' }); else if (hits.length > 1 && !matchAll) { throw new Error(`「${needle}」匹配到 ${hits.length} 个元素,请改用 elementIds:` + hits.map(h => `${h.id}(${h.text.slice(0, 20)})`).join(' | ')); } else picked.push(...hits); } return { targets: [...new Map(picked.map(e => [e.id, e])).values()], missing }; } function applyCustomOrder(lines, elementOrder = []) { if (!elementOrder.length) return; const els = listElements(lines); const animOf = new Map(); for (const el of els) { const m = el.body.match(/[\s\S]*?([0-9a-fA-F]{32})<\/Id>/); if (m) animOf.set(el.id, m[1]); } const current = parseOrders(lines); const desired = elementOrder.map(id => animOf.get(id)).filter(Boolean); const rest = current.filter(x => !desired.includes(x)); const next = [...desired, ...rest]; const start = lines.findIndex(l => l.trim() === ''); if (start < 0) return; let end = start; while (end < lines.length && lines[end].trim() !== '') end++; lines.splice(start, end - start + 1, ' ', ...next.map(x => ` ${x}`), ' '); } // ---------------------------------------------------------------- 数据库 const dbPathOf = cw => path.join(cw.userDir, 'Courseware', 'CoursewareCacheData.db'); function withDb(cw, fn, { write = false } = {}) { const p = dbPathOf(cw); if (!existsSync(p)) return null; let db; try { db = new DatabaseSync(p, { readOnly: !write }); return fn(db); } finally { try { db?.close(); } catch { /* ignore */ } } } export function readDbRow(cw) { return withDb(cw, db => db.prepare( 'select LocalId,RemoteId,Name,UpdateTime,Size,LocalRevision,SyncedRevision,Hash,Files from Courseware where LocalId=?', ).get(cw.localId) ?? null); } function writeDb(cw) { return withDb(cw, db => { const j = cw.json; const localId = cw.localId; db.exec('BEGIN'); try { db.prepare('delete from CoursewareFile where FileRelativePath like ?').run(localId + '\\%'); const ins = db.prepare( 'insert into CoursewareFile (FileId,FileHash,FileName,FileSize,FileRelativePath,DocumentRelativePath,FileIntValueOne) values (?,?,?,?,?,?,0)', ); for (const f of j.CoursewareFiles) { ins.run(f.FileId, f.FileHash, f.FileName, f.FileSize, localId + '\\' + f.FileName, f.RelativePath); } db.prepare('update Courseware set Name=?,RemoteId=?,UpdateTime=?,Size=?,LocalRevision=?,SyncedRevision=?,Files=? where LocalId=?') .run(j.Courseware.Name, j.Courseware.RemoteId, j.Courseware.UpdateTime, j.Courseware.Size, j.Courseware.Revision, j.Courseware.SyncedRevision, j.Courseware.Files, localId); db.exec('COMMIT'); } catch (e) { db.exec('ROLLBACK'); throw e; } return true; }, { write: true }); } /** 写回索引 + DB:重算 Size/Files,Revision 取 JSON 与 DB 的较大值再 +1 */ function finalize(cw) { const j = cw.json; j.CoursewareFiles = j.CoursewareFiles.filter(f => f && f.FileId && f.FileName); j.Courseware.Files = j.CoursewareFiles.map(f => f.FileId).join(';') + ';'; j.Courseware.Size = j.CoursewareFiles.reduce((a, f) => a + (f.FileSize || 0), 0); const dbRow = readDbRow(cw); const base = Math.max(j.Courseware.Revision ?? 0, dbRow?.LocalRevision ?? 0); j.Courseware.Revision = base + 1; j.Courseware.SyncedRevision = Math.min( j.Courseware.Revision - 1, Math.max(j.Courseware.SyncedRevision ?? 0, dbRow?.SyncedRevision ?? 0), ); j.Courseware.UpdateTime = Date.now(); writeJson(cw); writeDb(cw); } const saveSlideRecord = (cw, rec, file) => { const buf = readFileSync(file); rec.FileHash = md5(buf); rec.FileSize = buf.length; }; // ---------------------------------------------------------------- 备份 function backupManifestPath(dir) { return path.join(dir, 'manifest.json'); } export function backupCourseware({ courseware, note = '' } = {}) { const cw = resolveCourseware(courseware); const id = `${cw.localId}-${stamp()}`; const dir = path.join(BACKUP_ROOT, id); mkdirSync(dir, { recursive: true }); const warnings = []; for (const f of cw.json.CoursewareFiles) { const src = path.join(cw.dir, f.FileName); if (!existsSync(src)) { warnings.push(`缺文件:${f.FileName}`); continue; } copyFileSync(src, path.join(dir, f.FileName)); } copyFileSync(cw.jsonPath, path.join(dir, 'index.json')); const manifest = { id, createdAt: new Date().toISOString(), note, localId: cw.localId, remoteId: cw.json.Courseware.RemoteId, name: cw.name, revision: cw.json.Courseware.Revision, syncedRevision: cw.json.Courseware.SyncedRevision, size: cw.json.Courseware.Size, dbRow: readDbRow(cw), files: cw.json.CoursewareFiles.map(f => ({ FileId: f.FileId, FileName: f.FileName, FileHash: f.FileHash, FileSize: f.FileSize, RelativePath: f.RelativePath, })), warnings, }; writeFileSync(backupManifestPath(dir), JSON.stringify(manifest, null, 2), 'utf8'); // 只保留最近 N 份 const siblings = readdirSync(BACKUP_ROOT) .filter(n => n.startsWith(cw.localId + '-')) .sort(); for (const old of siblings.slice(0, Math.max(0, siblings.length - MAX_BACKUPS))) { rmSync(path.join(BACKUP_ROOT, old), { recursive: true, force: true }); } return { backupId: id, dir, files: manifest.files.length, warnings }; } function resolveBackup(backupId) { const raw = String(backupId || '').trim(); if (!raw) throw new Error('缺少 backupId'); let dir = raw; if (!path.isAbsolute(raw)) dir = path.join(BACKUP_ROOT, raw); if (!existsSync(dir)) throw new Error(`找不到备份:${raw}`); const mf = backupManifestPath(dir); if (!existsSync(mf)) throw new Error(`备份缺少 manifest.json:${dir}`); return { dir, manifest: readJson(mf) }; } /** 列出备份快照,可按课件过滤;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(); return n === cw.name.trim(); } /** * 找出属于这份课件的 shell。 * 如果本地存在同名副本,仅靠名字会匹配错,这时再用 remoteId 逐个核对。 */ async function shellsForCourseware(cw) { const list = await shells(); const sameName = list.filter(s => sameCourseware(s, cw)); if (!sameName.length) return []; if (!duplicatesOf(listCoursewares(), cw).length) return sameName; const want = String(cw.json?.Courseware?.RemoteId ?? '').toLowerCase(); if (!want) { throw new Error( `课件「${cw.name}」存在同名副本,且目标课件没有 RemoteId,无法判断该操作哪个窗口。` + '请手动关闭课件后重试,或先清理重复副本。', ); } const out = []; for (const s of sameName) { const info = await mcp('get_current_courseware_info', { shellId: s.id }, { timeoutMs: 12000 }).catch(() => null); const rid = String(info?.data?.remoteId ?? '').toLowerCase(); if (rid === want) out.push(s); } return out; } /** * 等课件真正加载完:希沃刚打开云端课件时,get_current_courseware_info 会先返回 1 页, * 直接拿它和磁盘比较会被误判成「有未同步改动」。这里轮询到页数与磁盘一致, * 或页数连续稳定且不少于磁盘页数(用户本地新增了页)为止。 */ async function waitCoursewareLoaded(shellId, expectedPages, { timeoutMs = 25000 } = {}) { const deadline = Date.now() + timeoutMs; let last = null; let stable = 0; while (Date.now() < deadline) { let info = null; try { info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 12000 }); } catch { // 单次查询超时 / 界面暂时无响应:继续等,别把它当成 0 页 await sleep(800); continue; } const d = info?.data ?? {}; if (typeof d.slideCount === 'number') { if (d.slideCount === expectedPages) return { loaded: true, info: d }; if (last && d.slideCount === last.slideCount) stable++; else stable = 0; last = d; if (stable >= 2 && d.slideCount > expectedPages) return { loaded: true, info: d }; } await sleep(500); } return { loaded: false, info: last ?? {} }; } async function closeForWrite(cw, force) { await ensureInit(); const open = await shellsForCourseware(cw); if (!open.length) return { wasOpen: false, closed: 0 }; const diskPages = slideRecords(cw).length; const diskSize = cw.json.Courseware.Size; for (const s of open) { // 先切回备课界面:授课模式下页面列表可能还没就绪,get_current_courseware_info 会卡住或返回 0 页 await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {}); await sleep(600); let { loaded, info: d } = await waitCoursewareLoaded(s.id, diskPages); if (!loaded) { // 再给一次机会:重新切界面后再等 await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {}); await sleep(1000); ({ loaded, info: d } = await waitCoursewareLoaded(s.id, diskPages)); } if (!loaded && (d.slideCount ?? 0) <= 1 && diskPages > 1) { throw new Error( `课件「${cw.name}」还没加载完成(当前只看到 ${d.slideCount ?? 0} 页 / 磁盘 ${diskPages} 页)。` + '请等希沃界面显示完整后再试,或传 force=true 忽略检查。', ); } const bad = []; if (typeof d.slideCount === 'number' && d.slideCount !== diskPages) { bad.push(`内存 ${d.slideCount} 页 / 磁盘 ${diskPages} 页`); } if (typeof d.size === 'number' && d.size !== diskSize) { bad.push(`内存 ${d.size} 字节 / 磁盘 ${diskSize} 字节`); } if (bad.length && !force) { throw new Error( `课件「${cw.name}」有未同步的内存改动(${bad.join(';')})。` + '请先用 seewo 的 sync_current_courseware 同步,或传 force=true 丢弃这些改动。', ); } } for (const s of open) { await mcp('close_current_courseware', { shellId: s.id, syncBeforeClose: false }).catch(() => {}); } let stillOpen = true; for (let i = 0; i < 20; i++) { await sleep(500); stillOpen = (await shellsForCourseware(cw)).length > 0; if (!stillOpen) break; } if (stillOpen) { throw new Error( `课件「${cw.name}」关闭失败(希沃界面可能卡住),已中止写操作以免内存内容覆盖磁盘。` + '请手动关闭课件或重启希沃后重试。', ); } return { wasOpen: true, closed: open.length }; } async function openCourseware(cwOrName, expectedPages = null) { await ensureInit(); const cw = typeof cwOrName === 'string' ? resolveCourseware(cwOrName) : cwOrName; const name = cw.name; let s = (await shells()).find(x => String(x.coursewareName || '').trim() === name.trim()); for (let attempt = 0; attempt < 2 && !s; attempt++) { await mcp('open_cloud_courseware', { coursewareName: name }).catch(() => {}); for (let i = 0; i < 20; i++) { await sleep(700); s = (await shells()).find(x => String(x.coursewareName || '').trim() === name.trim()); if (s) break; } } if (!s) return null; // 同名副本时用 remoteId 核对,防止打开/同步到另一份 const want = String(cw.json?.Courseware?.RemoteId ?? '').toLowerCase(); if (want) { const info = await mcp('get_current_courseware_info', { shellId: s.id }, { timeoutMs: 12000 }).catch(() => null); const got = String(info?.data?.remoteId ?? '').toLowerCase(); if (got && got !== want) { await mcp('close_current_courseware', { shellId: s.id, syncBeforeClose: false }).catch(() => {}); throw new Error( `打开到的是另一份同名课件(云端 ${got},期望 ${want})。` + '请先在希沃里删除多余副本,或改用正确的 localId。', ); } } if (expectedPages != null) await waitCoursewareLoaded(s.id, expectedPages); await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {}); return s.id; } /** 做一次无害改动,让希沃认为课件「未同步」,否则 sync 只会下载 */ async function touch(shellId) { const info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 15000 }).catch(() => null); const count = info?.data?.slideCount ?? 0; if (!count) return; const add = await mcp('add_slide', { shellId, slideNumber: count }).catch(() => null); const added = add?.data?.slideNumber; if (added) { await mcp('delete_slide', { shellId, slideNumber: added }).catch(() => {}); } } /** 轮询到备课(Edit)界面。刚打开的课件常常还停留在 Display。 */ async function ensureEditMode(shellId, { timeoutMs = 20000 } = {}) { const deadline = Date.now() + timeoutMs; let mode = null; let tries = 0; while (Date.now() < deadline) { const info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 12000 }).catch(() => null); mode = info?.data?.shellContext?.workingMode ?? mode; if (mode === 'Edit') return true; if (tries % 2 === 0) await mcp('en_goto_app_ui', { ui: 'Edit', shellId }).catch(() => {}); tries++; await sleep(700); } return mode === 'Edit'; } async function syncShell(shellId) { const opts = { timeoutMs: 180000 }; const push = () => mcp('sync_current_courseware', { shellId, waitUntilSynced: true, waitSeconds: 120 }, opts) .catch(e => ({ text: 'ERR ' + e.message })); await ensureEditMode(shellId); await touch(shellId); let r = await push(); // 刚打开的课件偶尔还没真正进入备课界面,重试几轮 for (let i = 0; i < 3 && /备课界面|Edit|必须/.test(String(r.text)); i++) { await ensureEditMode(shellId); await sleep(800); await touch(shellId); r = await push(); } if (String(r.text).includes('下载')) { await touch(shellId); r = await push(); } return r.text; } // 串行化写操作,避免两个工具同时开/关课件 let chain = Promise.resolve(); function serial(fn) { const p = chain.then(fn, fn); chain = p.catch(() => {}); return p; } async function runEdit(cw, opts, action) { return serial(async () => { const { wasOpen, closed } = await closeForWrite(cw, opts.force); const backup = opts.backup === false ? null : backupCourseware({ courseware: cw.localId, note: 'auto-before-write' }); let result; try { result = await action(cw); finalize(cw); } catch (e) { e.message += backup ? `\n(改动前备份:${backup.backupId})` : ''; throw e; } let shellId = null; let syncText = null; if (opts.reopen !== false) { shellId = await openCourseware(cw, slideRecords(cw).length); if (opts.sync && shellId) syncText = await syncShell(shellId); } return { ...result, backupId: backup?.backupId ?? null, wasOpen, closed, reopened: !!shellId, shellId, sync: syncText, }; }); } // ---------------------------------------------------------------- 工具:动画 export async function setAnimations({ courseware, page, elementIds = [], textMatches = [], matchAll = false, type = 'FadeIn', trigger = 'Click', duration = 0.3, delay = 0, order = [], reopen = true, sync = false, force = false, backup = true, } = {}) { const cw = resolveCourseware(courseware); if (!ANIM_TYPES.includes(type)) throw new Error(`type 只能是:${ANIM_TYPES.join(' / ')}`); if (!TRIGGERS.includes(trigger)) throw new Error(`trigger 只能是:${TRIGGERS.join(' / ')}`); const o = { type, trigger, duration: Number(duration), delay: Number(delay) }; return runEdit(cw, { reopen, sync, force, backup }, async c => { const { file, rec } = slideAt(c, page); const { lines, eol } = readLines(file); const { targets, missing } = resolveTargets(lines, { elementIds, textMatches, matchAll }); if (!targets.length) throw new Error('没有匹配到任何元素' + (missing.length ? `:${JSON.stringify(missing)}` : '')); let replaced = 0; const added = []; for (const t of targets) { const r = addAnimationToElement(lines, t.id, o); if (r) { replaced += r.replaced; added.push({ elementId: t.id, animationId: r.animId, text: t.text.slice(0, 30) }); } else missing.push({ elementId: t.id, reason: '写动画失败' }); } rebuildOrders(lines); applyCustomOrder(lines, order); writeLines(file, lines, eol); saveSlideRecord(c, rec, file); return { courseware: c.name, page, added, replaced, missing, order: parseOrders(lines), options: o }; }); } export function getAnimations({ courseware, page } = {}) { const cw = resolveCourseware(courseware); const { lines } = readLines(slideAt(cw, page).file); const orders = parseOrders(lines); const orderIndex = new Map(orders.map((id, i) => [id.toLowerCase(), i + 1])); const elements = []; const known = new Set(); for (const el of listElements(lines)) { const anims = parseAnimations(el.body); if (!anims.length) continue; for (const a of anims) { if (a.id) known.add(a.id.toLowerCase()); elements.push({ elementId: el.id, elementType: el.type, text: el.text.slice(0, 60), x: el.x, y: el.y, ...a, order: orderIndex.get(String(a.id).toLowerCase()) ?? null, }); } } const issues = []; for (const e of elements) if (e.order == null) issues.push(`动画 ${e.id} 不在 AnimationOrders 里,不会播放`); for (const id of orders) if (!known.has(id.toLowerCase())) issues.push(`AnimationOrders 里的 ${id} 找不到对应动画`); return { courseware: cw.name, page, count: elements.length, order: orders, elements, issues }; } export async function clearAnimations({ courseware, page, allPages = false, elementIds = [], reopen = true, sync = false, force = false, backup = true, } = {}) { const cw = resolveCourseware(courseware); if (!allPages && !Number.isInteger(Number(page))) throw new Error('需要 page,或传 allPages=true'); return runEdit(cw, { reopen, sync, force, backup }, async c => { const pages = allPages ? slidesInBoardOrder(c).map(s => s.page) : [Number(page)]; const report = []; for (const n of pages) { const { file, rec } = slideAt(c, n); const { lines, eol } = readLines(file); const before = (lines.join('\n').match(//g) ?? []).length; let out; if (!elementIds.length) { out = stripAnimations(lines); } else { out = lines; for (const id of elementIds) { const r = blockRange(out, id); if (!r) continue; const block = out.slice(r.start, r.end + 1); const a = block.findIndex(l => l.trim() === ''); if (a >= 0) { let b = a; while (b < block.length && block[b].trim() !== '') b++; block.splice(a, b - a + 1); out.splice(r.start, r.end - r.start + 1, ...block); } } } const orders = rebuildOrders(out); writeLines(file, out, eol); saveSlideRecord(c, rec, file); report.push({ page: n, before, after: orders.length, cleared: Math.max(0, before - orders.length) }); } return { courseware: c.name, pages: report }; }); } // ---------------------------------------------------------------- 工具:改文字 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, 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 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 = []; 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(', ')); } else picked.push(...(matchAll ? hits : [hits[0]])); } } 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 = 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 (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(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 function verifyCourseware({ courseware, hashes = true, deep = true } = {}) { const cw = resolveCourseware(courseware); const issues = []; const add = (level, code, message, extra = {}) => issues.push({ level, code, message, ...extra }); const j = cw.json; let board = null; try { board = readBoard(cw); } catch (e) { add('error', 'board-missing', e.message); } const slides = slideRecords(cw); const ids = []; const seenSlideIds = new Map(); const elementOwner = new Map(); const animCounts = new Map(); for (const rec of slides) { const file = path.join(cw.dir, rec.FileName); if (!existsSync(file)) { add('error', 'slide-file-missing', `索引里的页面文件不存在:${rec.FileName}`, { relativePath: rec.RelativePath }); continue; } const buf = readFileSync(file); if (hashes) { if (buf.length !== rec.FileSize) add('error', 'slide-size-mismatch', `${rec.RelativePath} 大小不符:索引 ${rec.FileSize} / 实际 ${buf.length}`); const h = md5(buf); if (h !== rec.FileHash) add('error', 'slide-hash-mismatch', `${rec.RelativePath} MD5 不符`, { expected: rec.FileHash, actual: h }); } const xml = buf.toString('utf8'); animCounts.set(rec.FileName, (xml.match(//g) || []).length); const id = slideXmlId(xml); if (!id) { add('error', 'slide-id-missing', `${rec.RelativePath} 没有 `); continue; } ids.push({ rec, id }); if (seenSlideIds.has(id)) add('error', 'duplicate-slide-id', `页面 Id 重复:${id}`); else seenSlideIds.set(id, rec.RelativePath); if (deep) { for (const m of xml.matchAll(/([0-9a-fA-F]{32})<\/Id>/g)) { const eid = m[1].toLowerCase(); if (eid === id.toLowerCase()) continue; if (elementOwner.has(eid)) { add('warn', 'duplicate-element-id', `元素 Id ${eid} 同时出现在 ${elementOwner.get(eid)} 和 ${rec.RelativePath}`); } else elementOwner.set(eid, rec.RelativePath); } } } if (board) { const idToRec = new Map(ids.map(x => [x.id.toLowerCase(), x.rec])); if (board.ids.length !== slides.length) { add('error', 'page-count-mismatch', `Board.xml 有 ${board.ids.length} 页,索引有 ${slides.length} 页`); } board.ids.forEach((id, i) => { const rec = idToRec.get(id.toLowerCase()); if (!rec) { add('error', 'board-page-missing', `Board.xml 第 ${i + 1} 页的 Id ${id} 在索引里找不到`); return; } const expect = `Slides\\Slide_${i}.xml`; if (String(rec.RelativePath).replace(/\//g, '\\').toLowerCase() !== expect.toLowerCase()) { add('warn', 'page-order-mismatch', `第 ${i + 1} 页在索引里是 ${rec.RelativePath},与页序不一致`); } }); const inBoard = new Set(board.ids.map(x => x.toLowerCase())); for (const x of ids) if (!inBoard.has(x.id.toLowerCase())) add('error', 'page-not-in-board', `${x.rec.RelativePath} 不在 Board.xml 的页序里(会显示不出来)`); } // 索引 / 资源 / 孤儿文件 const byName = new Map(); for (const f of j.CoursewareFiles) { const file = path.join(cw.dir, f.FileName); if (!existsSync(file)) { add('error', 'file-missing', `索引文件不存在:${f.FileName}`); continue; } const size = statSync(file).size; if (size !== f.FileSize) add('error', 'file-size-mismatch', `${f.FileName} 大小不符(索引 ${f.FileSize} / 实际 ${size})`); if (hashes && f.FileHash) { const h = md5File(file); if (h !== f.FileHash) add('error', 'file-hash-mismatch', `${f.FileName} MD5 不符`); } byName.set(f.FileName, f); } const sum = j.CoursewareFiles.reduce((a, f) => a + (f.FileSize || 0), 0); if (sum !== j.Courseware.Size) add('warn', 'size-sum-mismatch', `Courseware.Size=${j.Courseware.Size},文件合计=${sum}`); const refRec = j.CoursewareFiles.find( f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === 'reference.xml', ); let refIds = null; if (refRec) { const rf = path.join(cw.dir, refRec.FileName); if (existsSync(rf)) { refIds = new Set([...readText(rf).matchAll(/([0-9a-fA-F]{32})<\/Id>/g)].map(m => m[1].toLowerCase())); } } for (const slide of slides) { const file = path.join(cw.dir, slide.FileName); if (!existsSync(file)) continue; const xml = readText(file); for (const m of xml.matchAll(/id:\/\/([0-9a-fA-F]{32})/g)) { const rid = m[1].toLowerCase(); const rec = j.CoursewareFiles.find(f => { const n = f.FileName.toLowerCase(); return n === rid || n.startsWith(rid + '.'); }); if (!rec) add('error', 'resource-missing', `${slide.RelativePath} 引用的资源 ${rid} 不在索引里`); else if (!existsSync(path.join(cw.dir, rec.FileName))) add('error', 'resource-file-missing', `${slide.RelativePath} 引用的资源文件不存在:${rec.FileName}`); if (refIds && !refIds.has(rid)) { add('error', 'resource-not-referenced', `${slide.RelativePath} 的资源 ${rid} 没有登记在 Reference.xml(会显示成占位图)`); } } } const referenced = new Set(j.CoursewareFiles.map(f => f.FileName)); const metaFiles = new Set([`${cw.localId}.json`, 'CoursewareSourceTrace.json']); const orphans = readdirSync(cw.dir).filter(n => { const p = path.join(cw.dir, n); return statSync(p).isFile() && !referenced.has(n) && !metaFiles.has(n) && !/\.db$/i.test(n); }); if (orphans.length) add('info', 'orphan-files', `目录里有 ${orphans.length} 个未被索引引用的文件(多为旧版页面残留,可忽略)`, { examples: orphans.slice(0, 5) }); const filesField = j.Courseware.Files || ''; const fileIds = new Set(j.CoursewareFiles.map(f => f.FileId)); const listed = filesField.split(';').filter(Boolean); if (listed.length !== fileIds.size || listed.some(x => !fileIds.has(x))) { add('warn', 'files-field-mismatch', 'Courseware.Files 与 CoursewareFiles 不一致'); } let dbRow = null; try { dbRow = readDbRow(cw); if (!dbRow) add('error', 'db-row-missing', 'CoursewareCacheData.db 里没有这份课件'); else { if (dbRow.LocalRevision !== j.Courseware.Revision) add('warn', 'db-revision-mismatch', `DB LocalRevision=${dbRow.LocalRevision},JSON Revision=${j.Courseware.Revision}`); if (dbRow.SyncedRevision !== j.Courseware.SyncedRevision) add('warn', 'db-synced-mismatch', `DB SyncedRevision=${dbRow.SyncedRevision},JSON SyncedRevision=${j.Courseware.SyncedRevision}`); if (dbRow.Size !== j.Courseware.Size) add('warn', 'db-size-mismatch', `DB Size=${dbRow.Size},JSON Size=${j.Courseware.Size}`); const n = withDb(cw, db => db.prepare('select count(*) c from CoursewareFile where FileRelativePath like ?').get(cw.localId + '\\%').c); if (n !== j.CoursewareFiles.length) add('warn', 'db-file-count-mismatch', `DB 文件行 ${n} 条,索引 ${j.CoursewareFiles.length} 条`); } } catch (e) { add('warn', 'db-unreadable', `读 DB 失败:${e.message}`); } // 每页动画数(按 Board 页序),方便一次调用做回归核对 const animByFile = new Map(ids.map(x => [x.rec.FileName, animCounts.get(x.rec.FileName) ?? 0])); const animations = {}; if (board) { board.ids.forEach((id, i) => { const hit = ids.find(x => x.id.toLowerCase() === id.toLowerCase()); animations[i + 1] = hit ? (animByFile.get(hit.rec.FileName) ?? 0) : 0; }); } else { slides.forEach((rec, i) => { animations[i + 1] = animByFile.get(rec.FileName) ?? 0; }); } const animationTotal = Object.values(animations).reduce((a, b) => a + b, 0); return { ok: !issues.some(x => x.level === 'error'), courseware: cw.name, localId: cw.localId, pages: board?.ids.length ?? slides.length, revision: j.Courseware.Revision, syncedRevision: j.Courseware.SyncedRevision, size: j.Courseware.Size, animations, animationTotal, db: dbRow && { localRevision: dbRow.LocalRevision, syncedRevision: dbRow.SyncedRevision, size: dbRow.Size }, counts: { errors: issues.filter(x => x.level === 'error').length, warnings: issues.filter(x => x.level === 'warn').length, infos: issues.filter(x => x.level === 'info').length }, issues, }; } // ---------------------------------------------------------------- 工具:恢复 export async function restoreCourseware({ backupId, courseware, confirm = false, reopen = true, sync = false, force = false, keepIdentity = true, } = {}) { if (!confirm) throw new Error('恢复会覆盖当前课件,请传 confirm=true'); const { dir, manifest } = resolveBackup(backupId); const cw = resolveCourseware(courseware ?? manifest.localId); return serial(async () => { // 备份里的 index.json 带的是备份时的身份(Name/RemoteId),恢复内容时不能把身份也带回去, // 否则会把本地指针指到另一份云端副本。 const before = { name: cw.json.Courseware.Name, remoteId: cw.json.Courseware.RemoteId, syncedRevision: cw.json.Courseware.SyncedRevision, }; const { wasOpen } = await closeForWrite(cw, force); for (const f of manifest.files) { const src = path.join(dir, f.FileName); if (existsSync(src)) copyFileSync(src, path.join(cw.dir, f.FileName)); } const idx = path.join(dir, 'index.json'); if (!existsSync(idx)) throw new Error('备份缺少 index.json'); writeFileSync(cw.jsonPath, readFileSync(idx)); cw.json = readJson(cw.jsonPath); if (keepIdentity) { if (before.name) cw.json.Courseware.Name = before.name; if (before.remoteId) cw.json.Courseware.RemoteId = before.remoteId; } cw.name = cw.json.Courseware.Name ?? cw.name; const dbRow = readDbRow(cw); const base = Math.max(cw.json.Courseware.Revision ?? 0, dbRow?.LocalRevision ?? 0); const synced = keepIdentity ? (before.syncedRevision ?? dbRow?.SyncedRevision ?? 0) : (manifest.syncedRevision ?? cw.json.Courseware.SyncedRevision ?? 0); cw.json.Courseware.Revision = Math.max(base + 1, synced + 1); cw.json.Courseware.SyncedRevision = synced; cw.json.Courseware.UpdateTime = Date.now(); writeJson(cw); writeDb(cw); let shellId = null; let syncText = null; if (reopen) { shellId = await openCourseware(cw, slideRecords(cw).length); if (sync && shellId) syncText = await syncShell(shellId); } return { restored: manifest.id, courseware: cw.name, revision: cw.json.Courseware.Revision, syncedRevision: cw.json.Courseware.SyncedRevision, keepIdentity, wasOpen, reopened: !!shellId, shellId, sync: syncText, }; }); } // ---------------------------------------------------------------- 工具:跨课件复制 function regenerateIds(xml) { const map = new Map(); const get = id => { const k = id.toLowerCase(); if (!map.has(k)) map.set(k, randomBytes(16).toString('hex')); return map.get(k); }; let out = xml.replace(/([0-9a-fA-F]{32})<\/Id>/g, (m, id) => `${get(id)}`); out = out.replace(/([0-9a-fA-F]{32})<\/Item>/g, (m, id) => `${get(id)}`); return out; } function resourceRefs(xml) { return [...new Set([...xml.matchAll(/id:\/\/([0-9a-fA-F]{32})/g)].map(m => m[1].toLowerCase()))]; } /** * 希沃真正解析 id://<32hex> 用的是 Reference.xml 里的关系表, * 只把资源文件 + 索引/DB 记录复制过来,页面上的图片仍会显示成占位图, * 保存时希沃还会把这条资源记录当成孤儿删掉。复制页面时必须同步合并关系表。 */ function referenceRecord(cw) { const rec = cw.json.CoursewareFiles.find( f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === 'reference.xml', ); if (!rec) return null; const file = path.join(cw.dir, rec.FileName); if (!existsSync(file)) return null; return { rec, file }; } function ensureReferenceDoc(cw) { const existing = referenceRecord(cw); if (existing) return existing; const fileName = `Reference_S${String(Date.now()).slice(-6)}.${rand(11)}.${rand(3)}.xml`; const file = path.join(cw.dir, fileName); writeFileSync(file, '\n \n \n\n', 'utf8'); const buf = readFileSync(file); const rec = { FileId: randomUUID(), FileName: fileName, FileHash: md5(buf), FileSize: buf.length, FilePath: `${cw.localId}\\${fileName}`, RelativePath: 'Reference.xml', FilePartialState: 0, }; cw.json.CoursewareFiles.push(rec); return { rec, file }; } function mergeReferences(cw, items) { const ref = ensureReferenceDoc(cw); let xml = readText(ref.file); const have = new Set([...xml.matchAll(/([0-9a-fA-F]{32})<\/Id>/g)].map(m => m[1].toLowerCase())); const add = []; for (const it of items) { const id = String(it.id).toLowerCase(); if (have.has(id)) continue; have.add(id); add.push(it); } if (!add.length) return { added: 0 }; const block = add.map(it => [ ' ', ` ${it.id}`, ` ${it.target}`, ` ${it.hash}`, ' ', ].join('\n')).join('\n'); if (!xml.includes(' ')) return { added: 0, warning: 'Reference.xml 结构异常,未写入资源关系' }; xml = xml.replace(' ', `${block}\n `); writeFileSync(ref.file, xml, 'utf8'); saveSlideRecord(cw, ref.rec, ref.file); return { added: add.length }; } export async function copySlides({ source, target, pages = [], position = null, reopen = true, sync = false, force = false, backup = true, } = {}) { if (!source || !target) throw new Error('需要 source 和 target'); if (!Array.isArray(pages) || !pages.length) throw new Error('pages 不能为空'); const src = resolveCourseware(source); const dst = resolveCourseware(target); return runEdit(dst, { reopen, sync, force, backup }, async c => { const srcSlides = slidesInBoardOrder(src); const dstSlides = slidesInBoardOrder(c); const picked = pages.map(n => { const s = srcSlides[n - 1]; if (!s) throw new Error(`源课件没有第 ${n} 页(共 ${srcSlides.length} 页)`); return s; }); const at = position == null ? dstSlides.length : Math.max(0, Math.min(dstSlides.length, Number(position))); const ts = String(Date.now()).slice(-4); const copied = []; const warnings = []; const refItems = []; for (const s of picked) { let xml = regenerateIds(s.xml); const newFile = `Slide_${dstSlides.length + copied.length}_S${ts}.${rand(11)}.${rand(3)}.xml`; writeFileSync(path.join(c.dir, newFile), xml, 'utf8'); const buf = readFileSync(path.join(c.dir, newFile)); const newId = slideXmlId(xml); copied.push({ id: newId, rec: { FileId: randomUUID(), FileName: newFile, FileHash: md5(buf), FileSize: buf.length, FilePath: `${c.localId}\\${newFile}`, RelativePath: '', FilePartialState: 0, }, }); // 复制这一页引用的图片/音频资源,并登记到 Reference.xml for (const rid of resourceRefs(xml)) { const srec = src.json.CoursewareFiles.find(f => { const n = f.FileName.toLowerCase(); return n === rid || n.startsWith(rid + '.'); }); if (!srec) { warnings.push(`第 ${s.page} 页引用的资源 ${rid} 在源课件索引里找不到`); continue; } const relPath = String(srec.RelativePath).replace(/\//g, '\\'); refItems.push({ id: rid, target: relPath, hash: srec.FileHash }); const exists = c.json.CoursewareFiles.some( f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === relPath.toLowerCase(), ); const srcFile = path.join(src.dir, srec.FileName); const dstFile = path.join(c.dir, srec.FileName); if (!existsSync(srcFile)) { warnings.push(`资源文件不存在:${srec.FileName}`); continue; } if (!existsSync(dstFile) || statSync(dstFile).size !== srec.FileSize) copyFileSync(srcFile, dstFile); if (exists) continue; c.json.CoursewareFiles.push({ FileId: randomUUID(), FileName: srec.FileName, FileHash: srec.FileHash, FileSize: srec.FileSize, FilePath: `${c.localId}\\${srec.FileName}`, RelativePath: srec.RelativePath, FilePartialState: 0, }); } } // 重排页序:目标原页 + 插入页 const merged = [...dstSlides.slice(0, at), ...copied, ...dstSlides.slice(at)]; const nonSlides = c.json.CoursewareFiles.filter(f => !isSlidePath(f.RelativePath)); merged.forEach((s, i) => { s.rec.RelativePath = `Slides\\Slide_${i}.xml`; s.rec.FilePath = `${c.localId}\\${s.rec.FileName}`; }); c.json.CoursewareFiles = [...nonSlides, ...merged.map(s => s.rec)]; // 更新 Board.xml 页序 const board = readBoard(c); const newBoardXml = board.xml.replace(/[\s\S]*?<\/Slides>/, '\n' + merged.map(s => ` ${s.id}`).join('\n') + '\n '); writeFileSync(board.file, newBoardXml, 'utf8'); saveSlideRecord(c, board.rec, board.file); const refResult = mergeReferences(c, refItems); if (refResult.warning) warnings.push(refResult.warning); return { courseware: c.name, source: src.name, insertedAt: at, pages: picked.map(s => s.page), newPages: merged.map((s, i) => ({ page: i + 1, slideId: s.id })).filter((x, i) => i >= at && i < at + copied.length), referencesAdded: refResult.added, warnings, }; }); } // ---------------------------------------------------------------- 工具:删页 / 排序 export async function 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); return serial(async () => { await ensureInit(); let shell = (await shells()).find(s => sameCourseware(s, cw)); let opened = false; if (!shell) { const id = await openCourseware(cw, slideRecords(cw).length); if (!id) throw new Error(`打开课件「${cw.name}」失败`); shell = { id }; opened = true; } const text = await syncShell(shell.id); const info = await mcp('get_current_courseware_info', { shellId: shell.id }, { timeoutMs: 15000 }) .then(r => r.data ?? null).catch(() => null); return { courseware: cw.name, shellId: shell.id, opened, sync: text, isSynced: info?.isSynced ?? null, slideCount: info?.slideCount ?? null, }; }); } // ---------------------------------------------------------------- 工具:清理孤儿文件 const ORPHAN_ROOT = path.join(TMP, 'seewo-kit-orphans'); const TRASH_ROOT = path.join(TMP, 'seewo-kit-trash'); /** 磁盘上存在、但索引里没引用的文件(旧版页面残留等) */ function orphanFilesOf(cw) { const referenced = new Set(cw.json.CoursewareFiles.map(f => f.FileName)); const metaFiles = new Set([`${cw.localId}.json`, 'CoursewareSourceTrace.json']); return readdirSync(cw.dir).filter(n => { let st; try { st = statSync(path.join(cw.dir, n)); } catch { return false; } return st.isFile() && !referenced.has(n) && !metaFiles.has(n) && !/\.db$/i.test(n); }); } export async function pruneOrphanFiles({ courseware, dryRun = true, confirm = false, force = false, backup = true, reopen = true, } = {}) { const cw = resolveCourseware(courseware); return serial(async () => { const orphans = orphanFilesOf(cw); const bytes = orphans.reduce((a, n) => { try { return a + statSync(path.join(cw.dir, n)).size; } catch { return a; } }, 0); const preview = { courseware: cw.name, localId: cw.localId, count: orphans.length, bytes, files: orphans.slice(0, 100), }; if (dryRun) return { ...preview, dryRun: true, removed: 0, trashDir: null, backupId: null }; if (!confirm) { throw new Error(`将移走 ${orphans.length} 个未被索引引用的文件(${bytes} 字节),请传 confirm=true;` + '可先传 dryRun=true 预览。'); } if (!orphans.length) { return { ...preview, dryRun: false, removed: 0, trashDir: null, backupId: null, wasOpen: false }; } const { wasOpen } = await closeForWrite(cw, force); const backupId = backup ? backupCourseware({ courseware: cw.localId, note: 'auto-before-prune' }).backupId : null; mkdirSync(ORPHAN_ROOT, { recursive: true }); const trashDir = path.join(ORPHAN_ROOT, `${cw.localId}-${stamp()}`); mkdirSync(trashDir, { recursive: true }); const moved = []; for (const n of orphans) { try { renameSync(path.join(cw.dir, n), path.join(trashDir, n)); moved.push(n); } catch { /* 跳过被占用的文件 */ } } let shellId = null; if (wasOpen && reopen !== false) shellId = await openCourseware(cw, slideRecords(cw).length); return { ...preview, dryRun: false, removed: moved.length, trashDir, backupId, wasOpen, reopened: !!shellId, shellId, }; }); } // ---------------------------------------------------------------- 工具:移除本地重复课件 export async function removeLocalCourseware({ courseware, confirm = false, force = false, trash = true, } = {}) { if (!confirm) throw new Error('会移走课件缓存并删除 DB 记录,请传 confirm=true'); const cw = resolveCourseware(courseware); return serial(async () => { await ensureInit(); const { wasOpen, closed } = await closeForWrite(cw, force); let trashDir = null; try { if (trash) { mkdirSync(TRASH_ROOT, { recursive: true }); trashDir = path.join(TRASH_ROOT, `${cw.localId}-${stamp()}`); renameSync(cw.dir, trashDir); } else { rmSync(cw.dir, { recursive: true, force: true }); } const removed = withDb(cw, db => { db.exec('BEGIN'); try { const files = db.prepare('delete from CoursewareFile where FileRelativePath like ?') .run(cw.localId + '\\%'); const row = db.prepare('delete from Courseware where LocalId=?').run(cw.localId); db.exec('COMMIT'); return { files: files.changes, courseware: row.changes }; } catch (e) { db.exec('ROLLBACK'); throw e; } }, { write: true }); return { removed: cw.name, localId: cw.localId, remoteId: cw.json.Courseware.RemoteId ?? null, wasOpen, closed, trashDir, db: removed, }; } catch (e) { // DB 删除失败时把目录挪回来,避免文件没了但记录还在 if (trashDir && existsSync(trashDir) && !existsSync(cw.dir)) { try { renameSync(trashDir, cw.dir); } catch { /* ignore */ } } throw e; } }); } // ---------------------------------------------------------------- 工具:课件对比 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 }), }; }); }