Files
seewo/kit/core.mjs
T
wangfar 3f5bffba8e seewo-kit: 云端代理探活 + shell 直连回退,修复写操作永久挂起
云端 MCP(7916) 对单个 shell 的转发会永久阻塞且不报超时:实测 130s 无响应,
期间云端没有向 shell 端口发起 TCP,shell 日志也没有请求记录;而该 shell 自己的
MCP 端口(从 Log\<时间>,<pid>\last_info.txt 读取)读写/截图均 10-130ms 正常。

- 新增 callShellTool/routeFor:每个 shell 首次调用做 4s 探活,云端超时即自动
  改走直连端口;单次调用中途超时也立刻降级,不再让调用方干等
- 路由按 shell 缓存,失败 15s 后重试;shell 重启导致端口变化时自动重新发现
- diagnose_courseware 输出 live.shells[].transport(cloud/direct/端口),
  新增 proxy-dead 警告;写操作与 export_slides 结果附带 transport
- 修正“渲染线程卡死”的误判文案
- README 增补坑 16
2026-11-23 10:48:13 +08:00

3579 lines
146 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 客户端
//
// 希沃有两层 MCP:
// · 云端(7916,Cloud MCP,宿主是主窗口进程)只有 11 个 en_* / 云课件工具,
// 其余 52 个「shell 工具」是它转发给某个课件窗口进程(shell)去执行的;
// · 每个 shell 进程自己也有一个完整的 MCP 服务,端口随机,启动时会写进日志。
//
// 云端那条转发链【没有超时】:某个 shell 的代理一旦失效,所有带 shellId 的调用都会永久挂住
// (实测 130 秒无响应,且 shell 侧收不到任何请求,连 TCP 都没连)。这会让写操作既写不进去,
// 又长时间不报错。所以这里对每个 shell 做一次探活:代理不通就自动改走该 shell 的直连端口。
// 直连端口从 %APPDATA%\Seewo\EasiNote5\Log\<时间>,<pid>\last_info.txt 里读取。
const LOG_ROOT = path.join(os.homedir(), 'AppData', 'Roaming', 'Seewo', 'EasiNote5', 'Log');
const PORT_RE = /Shell MCP server started on port:\s*(\d+)/g;
const LISTEN_RE = /Listening on http:\/\/(?:127\.0\.0\.1|\[::1\]):(\d+)\//;
/** 只有云端才有的工具;其余工具在 shell 直连端口上也有,可以走直连 */
const CLOUD_ONLY = new Set([
'en_find_shells', 'en_bind_shell', 'en_goto_app_ui',
'new_cloud_courseware', 'new_cloud_courseware_from_pptx', 'open_cloud_courseware',
'search_cloud_courseware', 'generate_video_from_pptx',
'ensys_open_file', 'switch_to_display_board_mode', 'recognition_document_and_goto_page',
]);
const PROBE_TIMEOUT_MS = 4000;
const DEFAULT_TIMEOUT_MS = 30000;
let rpcId = 100;
const sessions = new Map(); // port -> { sid, initialized, rpcId }
const routes = new Map(); // shellId -> { kind: 'cloud'|'direct'|'dead', port, reason, at }
const shellPorts = new Map(); // shellId -> { port, dir }
function sessionOf(port) {
let st = sessions.get(port);
if (!st) {
st = { sid: null, initialized: false };
sessions.set(port, st);
}
return st;
}
async function postTo(port, body, timeoutMs = DEFAULT_TIMEOUT_MS) {
const st = sessionOf(port);
const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' };
if (st.sid) headers['Mcp-Session-Id'] = st.sid;
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST', headers, body: JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
});
const sid = res.headers.get('mcp-session-id');
if (sid) st.sid = 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 ensureInitOn(port, timeoutMs = DEFAULT_TIMEOUT_MS) {
const st = sessionOf(port);
if (st.initialized) return;
await postTo(port, {
jsonrpc: '2.0', id: 1, method: 'initialize',
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-kit', version: '1.1' } },
}, timeoutMs);
await postTo(port, { jsonrpc: '2.0', method: 'notifications/initialized' }, timeoutMs);
st.initialized = true;
}
async function rpcOn(port, name, args = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
await ensureInitOn(port, timeoutMs);
const r = await postTo(port, {
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 };
}
const ensureInit = () => ensureInitOn(MCP_PORT);
const rpc = (name, args, { timeoutMs } = {}) => rpcOn(MCP_PORT, name, args, timeoutMs);
/** 超时 / 连不上,才算「这条链路坏了」;业务报错说明对面是通的 */
function isTransportError(e) {
const n = String(e?.name || '');
const m = String(e?.message || '');
return n === 'TimeoutError' || n === 'AbortError'
|| /aborted due to timeout|fetch failed|ECONNREFUSED|ECONNRESET|other side closed|socket/i.test(m);
}
/** 找 shell 进程的日志目录(目录名形如 20261123_102339,7568) */
function shellLogDirs(shellId) {
if (!existsSync(LOG_ROOT)) return [];
const want = String(shellId);
const out = [];
for (const name of readdirSync(LOG_ROOT)) {
const m = name.match(/(?:,|_)(\d+)$/);
if (!m || m[1] !== want) continue;
const dir = path.join(LOG_ROOT, name);
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
out.push({ name, dir });
}
// 目录名自带时间戳,倒序即最新在前
out.sort((a, b) => b.name.localeCompare(a.name));
return out;
}
/** 从日志里取这个 shell 的直连 MCP 端口 */
function discoverShellPort(shellId, { fresh = false } = {}) {
const id = String(shellId);
if (!fresh) {
const cached = shellPorts.get(id);
if (cached) return cached.port;
}
for (const { dir } of shellLogDirs(id)) {
for (const file of ['last_info.txt', 'all_info.txt']) {
const f = path.join(dir, file);
if (!existsSync(f)) continue;
const txt = readFileSync(f, 'utf8');
const hits = [...txt.matchAll(PORT_RE)];
const port = hits.length ? hits[hits.length - 1][1] : txt.match(LISTEN_RE)?.[1];
if (port) {
shellPorts.set(id, { port, dir });
return port;
}
}
}
shellPorts.delete(id);
return null;
}
/**
* 直连调用:shell 服务本来就是「当前课件」作用域,shellId 要脱掉
* (带上反而可能被判成 shellId 与绑定窗口不一致)。
*/
async function directRpc(port, name, args = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
const once = async (a) => {
try {
return await rpcOn(port, name, a, timeoutMs);
} catch (e) {
// 端口被复用时旧会话会失效,重握手一次
if (/session|会话/i.test(String(e.message))) {
const st = sessionOf(port);
st.sid = null;
st.initialized = false;
return await rpcOn(port, name, a, timeoutMs);
}
throw e;
}
};
const clean = { ...args };
const hadShell = Object.prototype.hasOwnProperty.call(clean, 'shellId');
delete clean.shellId;
try {
return await once(clean);
} catch (e) {
if (hadShell && /shellId|绑定|绑定的|Usage error|请先调用/i.test(String(e.message))) {
return await once(args);
}
throw e;
}
}
/** 判断这个 shell 该走云端还是直连;结果按 shell 缓存,避免每次都等超时 */
async function routeFor(shellId) {
const id = String(shellId);
const cached = routes.get(id);
if (cached && cached.kind !== 'dead') return cached;
// 已知彻底不通时不要每次调用都重等两轮探测,15 秒后再试
if (cached && cached.kind === 'dead' && Date.now() - (cached.at ?? 0) < 15000) return cached;
let cloudError = null;
try {
await rpcOn(MCP_PORT, 'get_current_courseware_info', { shellId: id }, PROBE_TIMEOUT_MS);
const r = { kind: 'cloud', port: discoverShellPort(id), at: Date.now() };
routes.set(id, r);
return r;
} catch (e) {
if (!isTransportError(e)) {
// 有业务返回,说明云端代理是通的
const r = { kind: 'cloud', port: discoverShellPort(id), at: Date.now() };
routes.set(id, r);
return r;
}
cloudError = e;
}
const port = discoverShellPort(id, { fresh: true });
if (port) {
try {
await rpcOn(port, 'get_current_courseware_info', {}, PROBE_TIMEOUT_MS);
const r = { kind: 'direct', port, reason: `云端代理无响应(${cloudError.message}),改走直连 ${port}`, at: Date.now() };
routes.set(id, r);
return r;
} catch (e) {
cloudError = new Error(`${cloudError.message};直连 ${port} 也失败:${e.message}`);
}
}
const r = { kind: 'dead', port, reason: String(cloudError?.message || '未知'), at: Date.now() };
routes.set(id, r);
return r;
}
/** 带 shellId 的工具调用:云端代理坏了就自动改直连 */
async function callShellTool(name, args = {}, { timeoutMs = DEFAULT_TIMEOUT_MS, shellId } = {}) {
const id = String(shellId);
const route = await routeFor(id);
if (route.kind === 'dead') {
throw new Error(
`云端 MCP 到 shell ${id} 的代理没有响应,也找不到可用的直连端口。`
+ `原因:${route.reason}。请重启希沃白板后重试。`,
);
}
if (route.kind === 'cloud') {
try {
return await rpcOn(MCP_PORT, name, args, timeoutMs);
} catch (e) {
if (!isTransportError(e)) throw e;
// 探活通过但这次仍超时:立即降级,别让调用方干等
const port = discoverShellPort(id, { fresh: true });
if (port) {
try {
const r = await directRpc(port, name, args, timeoutMs);
routes.set(id, { kind: 'direct', port, reason: `云端代理超时(${e.message}),改走直连 ${port}`, at: Date.now() });
return r;
} catch (e2) {
routes.set(id, { kind: 'dead', port, reason: `${e.message};直连失败:${e2.message}`, at: Date.now() });
throw e2;
}
}
routes.set(id, { kind: 'dead', port: null, reason: e.message, at: Date.now() });
throw e;
}
}
try {
return await directRpc(route.port, name, args, timeoutMs);
} catch (e) {
// shell 重启后端口会变,重新发现一次
const port = discoverShellPort(id, { fresh: true });
if (port && port !== route.port) {
const r = await directRpc(port, name, args, timeoutMs);
routes.set(id, { kind: 'direct', port, at: Date.now() });
return r;
}
throw e;
}
}
async function mcp(name, args = {}, { timeoutMs, direct = false } = {}) {
const shellId = args && args.shellId != null ? String(args.shellId) : null;
if (!direct && shellId && !CLOUD_ONLY.has(name)) {
return callShellTool(name, args, { timeoutMs: timeoutMs ?? DEFAULT_TIMEOUT_MS, shellId });
}
await ensureInit();
try {
return await rpc(name, args, { timeoutMs });
} catch (e) {
// 会话过期时重新握手一次
if (/session|会话/i.test(String(e.message))) {
const st = sessionOf(MCP_PORT);
st.sid = null;
st.initialized = false;
await ensureInit();
return await rpc(name, args, { timeoutMs });
}
throw e;
}
}
/** 给结果用:这个 shell 当前实际走的链路(cloud / direct) */
export function shellRouteOf(shellId) {
const r = routes.get(String(shellId));
if (!r) return null;
return { kind: r.kind, port: r.port ?? null, ...(r.reason ? { reason: r.reason } : {}) };
}
/** 给 diagnose 用:这个 shell 的云端代理 / 直连端口各自是否可用 */
export async function shellTransportOf(shellId) {
const id = String(shellId);
let cloud;
try {
const info = await rpcOn(MCP_PORT, 'get_current_courseware_info', { shellId: id }, PROBE_TIMEOUT_MS);
cloud = { ok: true, info };
} catch (e) {
cloud = { ok: false, error: e.message };
}
const port = discoverShellPort(id, { fresh: true });
let direct = { ok: false, port: port ?? null, ...(port ? {} : { error: '日志里没有找到该 shell 的 MCP 端口' }) };
if (port) {
try {
const info = await rpcOn(port, 'get_current_courseware_info', {}, PROBE_TIMEOUT_MS);
direct = { ok: true, port, info };
} catch (e) {
direct = { ok: false, port, error: e.message };
}
}
// 顺便把探活结果写进路由缓存,diagnose 之后的调用不用再等一次超时
if (cloud.ok) routes.set(id, { kind: 'cloud', port: direct.port ?? null, at: Date.now() });
else if (direct.ok) routes.set(id, { kind: 'direct', port, reason: `云端代理无响应(${cloud.error}),改走直连 ${port}`, at: Date.now() });
else routes.set(id, { kind: 'dead', port: direct.port ?? null, reason: String(cloud.error || direct.error || '未知'), at: Date.now() });
return { cloud, direct, route: routes.get(id) ?? null };
}
const shells = () => mcp('en_find_shells', { searchingMode: 'All' })
.then(r => r.data?.shells ?? [])
.catch(() => []);
/**
* 希沃有的工具只回文本 JSON、没有 structuredContent。
* 只读 data 会让「内存页数/大小」检查悄悄失效,所以这里统一兜底解析。
*/
function infoOf(r) {
if (!r) return null;
if (r.data && typeof r.data === 'object') return r.data;
try { return JSON.parse(String(r.text || '')); } catch { return null; }
}
// ---------------------------------------------------------------- 课件定位
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(/<Slides>([\s\S]*?)<\/Slides>/)?.[1] ?? '';
const ids = [...block.matchAll(/<Item>([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(/<Slide>\s*<Id>([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() === `<Id>${elementId}</Id>`);
if (idIdx < 0) return null;
let start = idIdx;
while (start >= 0 && !/^ {4}<[A-Za-z]+>\s*$/.test(lines[start])) start--;
if (start < 0) return null;
const tag = lines[start].trim().replace(/[<>]/g, '');
let end = idIdx;
while (end < lines.length && lines[end].trim() !== `</${tag}>`) end++;
if (end >= lines.length) return null;
return { start, end, tag };
};
const unesc = s => String(s).replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const elementText = body => {
const cands = [...body.matchAll(/<Text>([^<]*)<\/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>([^<]*)<\/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 的 <Slides> 列表 */
function writeBoardOrder(cw, ordered) {
const board = readBoard(cw);
const xml = board.xml.replace(/<Slides>[\s\S]*?<\/Slides>/,
'<Slides>\n' + ordered.map(s => ` <Item>${s.id}</Item>`).join('\n') + '\n </Slides>');
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>[^<]*<\/TransitionKey>$/.test(l))
?.match(/<TransitionKey>([^<]*)<\/TransitionKey>/)?.[1] ?? null;
const raw = lines.find(l => /^ <Duration>[^<]*<\/Duration>$/.test(l))
?.match(/<Duration>([^<]*)<\/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>[^<]*<\/TransitionKey>$/.test(lines[i])) lines.splice(i, 1);
}
if (key) {
const e = lines.findIndex(l => l.trim() === '</Elements>');
if (e < 0) throw new Error('页面缺少 </Elements>,无法写入切换');
lines.splice(e + 1, 0, ` <TransitionKey>${key}</TransitionKey>`);
}
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>[^<]*<\/Duration>$/.test(l));
if (d >= 0) lines[d] = ` <Duration>${ticks}</Duration>`;
else {
const t = lines.findIndex(l => /^ <TransitionKey>/.test(l));
const at = t >= 0 ? t + 1 : lines.findIndex(l => l.trim() === '</Elements>') + 1;
if (at <= 0) throw new Error('页面缺少 </Elements>,无法写入切换时长');
lines.splice(at, 0, ` <Duration>${ticks}</Duration>`);
}
}
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(/<DefaultRunProperty>[\s\S]*?<\/DefaultRunProperty>/g, '')
.replace(/<TextMarkerStyle>[\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>[^<]*<\/FontSize>/g, `<FontSize>${opts.fontSize}</FontSize>`);
}
if (opts.bold != null) {
out = out.replace(/<FontWeight>[^<]*<\/FontWeight>/g, `<FontWeight>${opts.bold ? 'Bold' : 'Normal'}</FontWeight>`);
}
if (opts.color) {
out = out.replace(/(<Foreground>\s*<ColorBrush>)[^<]*(<\/ColorBrush>)/g, `$1${opts.color}$2`);
}
if (opts.align) {
out = out.replace(/<TextAlignment>[^<]*<\/TextAlignment>/g, `<TextAlignment>${opts.align}</TextAlignment>`);
}
if (opts.width != null) {
out = out.replace(/<Width>[^<]*<\/Width>/, `<Width>${opts.width}</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() !== `</${tag}>`) k++;
const body = lines.slice(i + 1, k).join('\n');
const id = body.match(/<Id>([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>([^<]*)<\/X>/)?.[1]),
y: Number(body.match(/<Y>([^<]*)<\/Y>/)?.[1]),
w: Number(body.match(/<Width>([^<]*)<\/Width>/)?.[1]),
h: Number(body.match(/<Height>([^<]*)<\/Height>/)?.[1]),
fontSizes: [...new Set(
[...styleBody.matchAll(/<FontSize>([\d.]+)<\/FontSize>/g)]
.map(m => Number(m[1])).filter(n => Number.isFinite(n) && n > 0),
)],
bold: /<FontWeight>Bold<\/FontWeight>/.test(styleBody),
color: styleBody.match(/<Foreground>\s*<ColorBrush>(#[0-9A-Fa-f]{6,8})<\/ColorBrush>/)?.[1] ?? null,
text: elementText(body),
animated: body.includes('<Animations>'),
});
});
return out;
}
/** 给文本块写「固定框宽 + 单行折行」,避免只改 <Text> 后按旧折行渲染 */
function collapseLines(block, text, width) {
if (width != null) {
const wi = block.findIndex(l => /^\s*<Width>[^<]*<\/Width>$/.test(l));
if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}<Width>${width}</Width>`;
const sc = block.findIndex(l => /<SizeToContent>/.test(l));
if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*</, '>Manual<');
}
const ls = block.findIndex(l => l.trim() === '<Lines>');
const n = [...text].length;
if (ls >= 0) {
let le = ls;
while (le < block.length && block[le].trim() !== '</Lines>') le++;
block.splice(ls + 1, le - ls - 1,
' <LineProperty>',
' <StartOffset>0</StartOffset>',
` <Length>${n}</Length>`,
' </LineProperty>');
return;
}
for (let i = 0; i < block.length; i++) {
const m = block[i].match(/^(\s*)<Length>\d+<\/Length>$/);
if (m) { block[i] = `${m[1]}<Length>${n}</Length>`; break; }
}
}
// ---------------------------------------------------------------- 动画
const animNode = (id, o) => [
' <Animations>',
' <Animation>',
` <Type>${o.type}</Type>`,
` <Id>${id}</Id>`,
' <Number>1</Number>',
' <Category>Appearance</Category>',
` <Trigger>${o.trigger}</Trigger>`,
' <TriggerSource></TriggerSource>',
` <Duration>${Math.round(o.duration * 10000000)}</Duration>`,
` <Delay>${Math.round(o.delay * 10000000)}</Delay>`,
' <AccelerationRatio>1</AccelerationRatio>',
' <DecelerationRatio>0</DecelerationRatio>',
' <RepeatBehavior>1</RepeatBehavior>',
' <Start>0</Start>',
' <End>1</End>',
' </Animation>',
' </Animations>',
];
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 === '<Animations>' || t === '<AnimationOrders>') {
const close = t.replace('<', '</');
while (i < lines.length && lines[i].trim() !== close) i++;
continue;
}
out.push(lines[i]);
}
return out;
}
/** 重建 <AnimationOrders>:先删旧的,再按元素在页面里的先后重新排 */
function rebuildOrders(lines) {
const oStart = lines.findIndex(l => l.trim() === '<AnimationOrders>');
if (oStart >= 0) {
let oEnd = oStart;
while (oEnd < lines.length && lines[oEnd].trim() !== '</AnimationOrders>') oEnd++;
lines.splice(oStart, oEnd - oStart + 1);
}
const ids = [];
for (const el of listElements(lines)) {
const m = el.body.match(/<Animations>[\s\S]*?<Id>([0-9a-fA-F]{32})<\/Id>/);
if (m) ids.push(m[1]);
}
if (!ids.length) return ids;
const closeIdx = lines.map(l => l.trim()).lastIndexOf('</Slide>');
lines.splice(closeIdx, 0, ' <AnimationOrders>', ...ids.map(x => ` <Item>${x}</Item>`), ' </AnimationOrders>');
return ids;
}
function addAnimationToElement(lines, elementId, o) {
const r = blockRange(lines, elementId);
if (!r) return null;
const block = lines.slice(r.start, r.end + 1);
let replaced = 0;
const a = block.findIndex(l => l.trim() === '<Animations>');
if (a >= 0) {
let b = a;
while (b < block.length && block[b].trim() !== '</Animations>') b++;
replaced = 1;
block.splice(a, b - a + 1);
}
const animId = randomBytes(16).toString('hex');
let at = block.findIndex(l => l.trim() === '<HasMask>');
if (at < 0) at = block.findIndex(l => l.trim() === '<RotateOrigin>');
if (at < 0) at = block.length - 1;
block.splice(at, 0, ...animNode(animId, o));
lines.splice(r.start, r.end - r.start + 1, ...block);
return { animId, replaced };
}
function parseAnimations(body) {
const out = [];
for (const block of body.matchAll(/<Animations>([\s\S]*?)<\/Animations>/g)) {
for (const a of block[1].matchAll(/<Animation>([\s\S]*?)<\/Animation>/g)) {
const g = t => a[1].match(new RegExp(`<${t}>([^<]*)</${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() === '<AnimationOrders>');
if (start < 0) return [];
let end = start;
while (end < lines.length && lines[end].trim() !== '</AnimationOrders>') end++;
return lines.slice(start + 1, end)
.map(l => l.match(/<Item>([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(/<Animations>[\s\S]*?<Id>([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() === '<AnimationOrders>');
if (start < 0) return;
let end = start;
while (end < lines.length && lines[end].trim() !== '</AnimationOrders>') end++;
lines.splice(start, end - start + 1, ' <AnimationOrders>', ...next.map(x => ` <Item>${x}</Item>`), ' </AnimationOrders>');
}
// ---------------------------------------------------------------- 数据库
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(infoOf(info)?.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 = infoOf(info) ?? {};
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 };
// 多实例:每个窗口各存一份副本,后关闭的会覆盖先关闭的。
if (open.length > 1 && !force) {
throw new Error(
`课件「${cw.name}」同时打开了 ${open.length} 个窗口(shell ${open.map(s => s.id).join(' / ')})。`
+ '多个实例各自保存一份内容,写入后必然互相覆盖。'
+ '请先手动关掉多余窗口只留一个,或传 force=true 让 kit 全部关掉后再写。',
);
}
// 授课模式:切回备课会把该模式下新建/修改的内容丢掉,不能悄悄替用户决定。
const displayShells = open.filter(s => String(s.workingMode || 'Edit') !== 'Edit');
if (displayShells.length && !force) {
throw new Error(
`课件「${cw.name}」当前在授课(Display)界面(shell ${displayShells.map(s => s.id).join(' / ')})。`
+ '切回备课界面会丢弃在授课界面里新建/修改的页和元素,kit 不会替你做这个决定。'
+ '请先在希沃里回到备课界面;确认这些改动不要了,再传 force=true。',
);
}
const diskPages = slideRecords(cw).length;
const diskSize = cw.json.Courseware.Size;
for (const s of open) {
// 只有确实不在备课界面时才切:这个切换本身会丢掉授课模式下的改动
if (String(s.workingMode || 'Edit') !== 'Edit') {
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,
modes: open.map(s => String(s.workingMode || 'Edit')),
discardedDisplayEdits: displayShells.length > 0 && !!force,
};
}
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(infoOf(info)?.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 = infoOf(info)?.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) {
// 首选云端窗口列表里的 workingMode(直连端口的 get_current_courseware_info 不带 shellContext)
const cur = (await shells()).find(s => String(s.id) === String(shellId));
mode = cur?.workingMode ?? mode;
if (mode === 'Edit') return true;
const info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 12000 }).catch(() => null);
mode = infoOf(info)?.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, { force = false } = {}) {
// 授课模式下切到备课会丢掉该界面的改动,同步之前先拦住
if (!force) {
const cur = (await shells()).find(s => String(s.id) === String(shellId));
const mode = cur?.workingMode ?? null;
if (mode && mode !== 'Edit') {
throw new Error(
`课件当前停在「${mode}」界面,同步需要切回备课,而切换会丢弃在该界面里新建/修改的内容。`
+ '请先在希沃里回到备课界面;确认改动不要了再传 force=true。',
);
}
}
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;
}
/** 写前给所有页面文件做一次指纹,用来确认「工具说成功了,磁盘上真的变了」 */
function snapshotSlideFiles(cw) {
const map = new Map();
for (const rec of slideRecords(cw)) {
try { map.set(rec.FileName, md5File(path.join(cw.dir, rec.FileName))); } catch { /* 读不到就跳过 */ }
}
return map;
}
async function runEdit(cw, opts, action) {
return serial(async () => {
const before = snapshotSlideFiles(cw);
const { wasOpen, closed, modes = [], discardedDisplayEdits = false } = await closeForWrite(cw, opts.force);
const backup = opts.backup === false ? null : backupCourseware({ courseware: cw.localId, note: 'auto-before-write' });
let result;
let changedPages = 0;
try {
result = await action(cw);
finalize(cw);
const after = snapshotSlideFiles(cw);
changedPages = [...after.keys()].filter(k => before.get(k) !== after.get(k)).length;
} catch (e) {
e.message += backup ? `\n(改动前备份:${backup.backupId})` : '';
throw e;
}
const warnings = [];
if (!changedPages) warnings.push('工具返回成功,但磁盘上没有一页发生变化,请用 verify_courseware / inspect_courseware 确认改动是否真的落盘');
if (discardedDisplayEdits) warnings.push('写入前课件在授课界面,按 force=true 切回备课,授课界面里未保存的改动已被丢弃');
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, modes,
changedPages,
...(warnings.length ? { warnings } : {}),
reopened: !!shellId,
shellId,
...(shellId ? { transport: shellRouteOf(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(/<Animations>/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() === '<Animations>');
if (a >= 0) {
let b = a;
while (b < block.length && block[b].trim() !== '</Animations>') 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>([^<]*)<\/Text>/g)]
.map(m => unesc(m[1])).filter(Boolean));
if (nonEmpty.size > 1) {
throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`);
}
const oldTag = `<Text>${esc(before)}</Text>`;
for (let i = 0; i < block.length; i++) {
if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`<Text>${esc(after)}</Text>`);
}
} 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>([^<]*)<\/Text>/g, (m, t) => {
const plain = unesc(t);
return plain.includes(find) ? `<Text>${esc(plain.split(find).join(rep))}</Text>` : 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(/<Animation>/g) || []).length);
const id = slideXmlId(xml);
if (!id) { add('error', 'slide-id-missing', `${rec.RelativePath} 没有 <Id>`); 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(/<Id>([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(/<Id>([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(/<Id>([0-9a-fA-F]{32})<\/Id>/g, (m, id) => `<Id>${get(id)}</Id>`);
out = out.replace(/<Item>([0-9a-fA-F]{32})<\/Item>/g, (m, id) => `<Item>${get(id)}</Item>`);
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, '<Reference>\n <Relationships>\n </Relationships>\n</Reference>\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(/<Id>([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 => [
' <Relationship>',
` <Id>${it.id}</Id>`,
` <Target>${it.target}</Target>`,
` <Hash>${it.hash}</Hash>`,
' </Relationship>',
].join('\n')).join('\n');
if (!xml.includes(' </Relationships>')) return { added: 0, warning: 'Reference.xml 结构异常,未写入资源关系' };
xml = xml.replace(' </Relationships>', `${block}\n </Relationships>`);
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(/<Slides>[\s\S]*?<\/Slides>/,
'<Slides>\n' + merged.map(s => ` <Item>${s.id}</Item>`).join('\n') + '\n </Slides>');
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, force = false } = {}) {
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, { force });
const info = infoOf(await mcp('get_current_courseware_info', { shellId: shell.id }, { timeoutMs: 15000 })
.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 diagnoseCourseware({ courseware, checkRender = false, renderPage = 1, timeoutSec = 45 } = {}) {
const cw = resolveCourseware(courseware);
const issues = [];
const push = (level, code, message, extra = {}) => issues.push({ level, code, message, ...extra });
const slides = slidesInBoardOrder(cw);
const revision = cw.json.Courseware.Revision;
const syncedRevision = cw.json.Courseware.SyncedRevision;
if (revision !== syncedRevision) {
push('warn', 'unsynced', `本地 Revision=${revision},云端 SyncedRevision=${syncedRevision}(本地改动还没上传)`);
}
const verify = verifyCourseware({ courseware: cw.localId, hashes: true, deep: false });
for (const i of verify.issues) {
if (i.level === 'error') push('error', `verify:${i.code}`, i.message);
}
let live = { open: 0, shells: [] };
try {
await ensureInit();
const list = (await shells()).filter(s => sameCourseware(s, cw));
const details = [];
for (const s of list) {
const tr = await shellTransportOf(s.id);
const info = tr.cloud.ok ? tr.cloud.info : (tr.direct.ok ? tr.direct.info : null);
const d = infoOf(info) ?? {};
if (!tr.cloud.ok && tr.direct.ok) {
push('warn', 'proxy-dead',
`shell ${s.id} 的云端 MCP 代理无响应(${tr.cloud.error}),kit 已自动改走直连端口 ${tr.direct.port};`
+ '写操作仍可用,但云端代理要重启希沃才会恢复');
} else if (!tr.cloud.ok && !tr.direct.ok) {
push('error', 'shell-unreachable',
`shell ${s.id} 的云端代理和直连端口都不可用(云端:${tr.cloud.error};直连:${tr.direct.error ?? '无端口'});此时不要写课件`);
} else if (!info) {
push('warn', 'shell-unresponsive', `shell ${s.id} 12 秒内没有响应(可能正在渲染、切换界面或关闭),此时不要写课件`);
}
details.push({
shellId: String(s.id),
workingMode: s.workingMode ?? d.shellContext?.workingMode ?? null,
pages: typeof d.slideCount === 'number' ? d.slideCount : null,
size: typeof d.size === 'number' ? d.size : null,
remoteId: d.remoteId ?? null,
transport: {
cloud: tr.cloud.ok ? 'ok' : 'dead',
...(tr.cloud.ok ? {} : { cloudError: tr.cloud.error }),
direct: tr.direct.ok ? 'ok' : 'dead',
directPort: tr.direct.port ?? null,
...(tr.direct.ok ? {} : (tr.direct.error ? { directError: tr.direct.error } : {})),
},
});
}
live = { open: details.length, shells: details };
} catch (e) {
push('error', 'live', `查询希沃窗口失败:${e.message}`);
}
if (live.open > 1) {
push('error', 'multi-instance',
`同时打开了 ${live.open} 个窗口(shell ${live.shells.map(s => s.shellId).join(' / ')}),写操作会互相覆盖;先关掉多余的,只留一个`);
}
for (const s of live.shells) {
if (s.workingMode && s.workingMode !== 'Edit') {
push('warn', 'display-mode', `shell ${s.shellId} 停在「${s.workingMode}」界面,切回备课会丢弃在该界面里新建/修改的内容`);
}
if (s.pages != null && s.pages !== slides.length) {
push('warn', 'memory-pages', `shell ${s.shellId} 内存里 ${s.pages} 页,磁盘 ${slides.length} 页(未保存改动,或还在加载)`);
}
if (s.size != null && cw.json.Courseware.Size != null && s.size !== cw.json.Courseware.Size) {
push('info', 'memory-size', `shell ${s.shellId} 内存大小 ${s.size},磁盘 ${cw.json.Courseware.Size}(有未落盘的改动)`);
}
}
let render = null;
if (checkRender) {
const target = live.shells[0];
if (!target) {
render = { ok: false, error: '课件没有打开,无法测试截图接口' };
push('warn', 'render', render.error);
} else {
const file = path.join(TMP, `diag-${cw.localId}-p${renderPage}.png`);
const startedAt = Date.now();
try {
if (existsSync(file)) rmSync(file, { force: true });
await mcp('get_slide_screenshot',
{ slideNumber: renderPage, expectedPngImageFilePath: file, shellId: target.shellId },
{ timeoutMs: Math.max(10, Number(timeoutSec) || 45) * 1000 });
const bytes = existsSync(file) ? statSync(file).size : 0;
render = { ok: bytes > 2048, page: renderPage, bytes, ms: Date.now() - startedAt, path: file };
if (!render.ok) push('warn', 'render', `截图只拿到 ${bytes} 字节,渲染可能没起来`);
} catch (e) {
render = { ok: false, page: renderPage, ms: Date.now() - startedAt, error: e.message };
push('error', 'render', `截图 ${timeoutSec} 秒没返回(云端代理和 shell 直连都没成功);重启希沃后再继续`);
}
}
}
const { backups } = listBackups({ courseware: cw.localId, limit: 3 });
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,
safeToWrite: counts.errors === 0,
pages: slides.length,
revision,
syncedRevision,
live,
render,
latestBackups: backups.map(b => ({ backupId: b.backupId, note: b.note, createdAt: b.createdAt })),
counts,
issues,
tips: issues.length ? [
'multi-instance/display-mode 两种报错都不是让你忽略的:它们说明希沃里有多份内容,任何一方保存都会覆盖另一方。',
'proxy-dead 表示云端 MCP 到该窗口的转发链路坏了:kit 会自动走直连端口,写入不受影响,但重启希沃才会修好云端代理。',
'render 报错时不要反复重试截图,重启希沃最快。',
] : [],
};
}
// ---------------------------------------------------------------- 工具:撤销上一次写操作
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>[^<]*<\/Width>$/.test(l))
?.match(/<Width>([^<]*)<\/Width>/)?.[1]);
const h = Number(lines.find(l => /^ {2}<Height>[^<]*<\/Height>$/.test(l))
?.match(/<Height>([^<]*)<\/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}>[^<]*</${tag}>$`);
const i = block.findIndex(l => re.test(l));
if (i < 0) continue;
block[i] = ` <${tag}>${round4(value)}</${tag}>`;
}
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 = /<IsLocked>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;
}
// 授课界面也能截图;这时千万不要切回备课,否则会把该界面的改动丢掉
const modeNow = (await shells()).find(s => String(s.id) === String(shell.id))?.workingMode ?? null;
const keptDisplayMode = modeNow === 'Display';
if (!keptDisplayMode) 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 = [];
let consecutiveTimeouts = 0;
let aborted = false;
let abortedReason = null;
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 stale = false;
let attempts = 0;
for (let attempt = 0; attempt < Math.max(1, Number(retries) || 1); attempt++) {
attempts = attempt + 1;
// 每次截图前都删掉旧文件:同路径残留的上一张图会被误当成这次的成功结果
if (existsSync(file)) rmSync(file, { force: true });
let startedAt = Date.now();
try {
// 先切到目标页,否则希沃偶尔把上一页的旧帧当成这一页返回
await mcp('goto_slide', { slideNumber: n, shellId: shell.id }, { timeoutMs: 20000 }).catch(() => {});
await sleep(Math.min(400, Math.max(0, Number(settleMs) || 0)));
startedAt = Date.now();
const r = await mcp(
'get_slide_screenshot',
{ slideNumber: n, expectedPngImageFilePath: file, shellId: shell.id },
{ timeoutMs },
);
if (existsSync(file)) {
bytes = statSync(file).size;
const fresh = statSync(file).mtimeMs >= startedAt - 1000;
if (bytes >= minBytes && fresh) break;
if (bytes >= minBytes && !fresh) {
stale = true;
lastError = '截图接口返回的是本次调用之前生成的旧文件(可能是渲染线程卡住的旧帧)';
}
}
if (!lastError) 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 && !stale;
consecutiveTimeouts = ok ? 0 : (timedOut ? consecutiveTimeouts + 1 : 0);
files.push({
page: n, path: file, bytes, attempts,
...(ok ? {} : {
error: timedOut
? `截图超时(${timeoutSec} 秒):云端代理和 shell 直连都没有返回。请确认希沃窗口已完整加载,必要时重启希沃,或调大 timeoutSec。`
: (lastError ?? '没有生成截图文件'),
timedOut, ...(stale ? { stale: true } : {}),
}),
});
if (!ok && stopOnError) {
aborted = true;
break;
}
// 连续两页超时基本可以断定链路已死,继续只会更慢
if (consecutiveTimeouts >= 2) {
aborted = true;
abortedReason = `连续 ${consecutiveTimeouts} 页截图超时(云端代理与直连都不可用),请重启希沃后再导出`;
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,
workingMode: modeNow,
...(shellRouteOf(shell.id) ? { transport: shellRouteOf(shell.id) } : {}),
...(keptDisplayMode ? { note: '课件停在授课界面:为免丢内容没有切回备课,截图即当前授课画面。' } : {}),
count: files.length, requested: nums.length,
succeeded, failed, skipped: nums.length - files.length,
aborted,
...(aborted ? {
hint: abortedReason
?? '已中止剩余页面:截图一直超时(云端代理与直连都不可用)。重启希沃、让课件完整加载后再导出,比继续等更快。',
} : {}),
timeoutSec, files,
};
}
// ---------------------------------------------------------------- 工具:段内富文本
function textRunsRegion(block) {
const start = block.findIndex(l => l.trim() === '<TextRuns>');
if (start < 0) return null;
let depth = 0;
for (let i = start; i < block.length; i++) {
if (block[i].trim() === '<TextRuns>') depth++;
else if (block[i].trim() === '</TextRuns>') {
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() !== '<TextRun>') continue;
let j = i + 1;
while (j < block.length && block[j].trim() !== '</TextRun>') 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*<Text>[\s\S]*<\/Text>$/.test(l));
if (ti < 0) return null;
lines[ti] = lines[ti].replace(/<Text>[\s\S]*<\/Text>/, `<Text>${esc(text)}</Text>`);
if (style.fontSize != null) {
const i = lines.findIndex(l => /^\s*<FontSize>[^<]*<\/FontSize>$/.test(l));
if (i >= 0) lines[i] = lines[i].replace(/<FontSize>[^<]*<\/FontSize>/, `<FontSize>${style.fontSize}</FontSize>`);
}
if (style.bold != null) {
const i = lines.findIndex(l => /^\s*<FontWeight>[^<]*<\/FontWeight>$/.test(l));
if (i >= 0) lines[i] = lines[i].replace(/<FontWeight>[^<]*<\/FontWeight>/, `<FontWeight>${style.bold ? 'Bold' : 'Normal'}</FontWeight>`);
}
if (style.color) {
const fg = lines.findIndex(l => l.trim() === '<Foreground>');
const brush = fg >= 0 ? lines.findIndex((l, i) => i > fg && /<ColorBrush>[^<]*<\/ColorBrush>/.test(l)) : -1;
if (brush >= 0) lines[brush] = lines[brush].replace(/<ColorBrush>[^<]*<\/ColorBrush>/, `<ColorBrush>${style.color}</ColorBrush>`);
}
return lines;
}
function buildStyledRuns(runLines, find, style) {
const ti = runLines.findIndex(l => /^\s*<Text>[\s\S]*<\/Text>$/.test(l));
if (ti < 0) return null;
const m = runLines[ti].match(/^(\s*)<Text>([\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 }),
};
});
}