From 29193c03bca38919bb20dbcb4e577b15f688ee57 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 29 Nov 2026 13:30:18 +0800 Subject: [PATCH] Save and reopen native Beta source snapshots --- docs/NATIVE_BETA.md | 18 +++++-- docs/P2_M1_PROGRESS.md | 23 +++++++++ examples/native_editor/app.js | 24 +++++++++ examples/native_editor/index.html | 8 ++- examples/native_editor/main.rs | 48 +++++++++++++++++- examples/native_editor/saved_project.rs | 66 +++++++++++++++++++++++++ scripts/native-beta.py | 22 +++++++-- 7 files changed, 198 insertions(+), 11 deletions(-) create mode 100644 examples/native_editor/saved_project.rs diff --git a/docs/NATIVE_BETA.md b/docs/NATIVE_BETA.md index b8223c5..1db4810 100644 --- a/docs/NATIVE_BETA.md +++ b/docs/NATIVE_BETA.md @@ -33,9 +33,21 @@ python3 target/local-beta/native-beta.py compile /path/to/main.tex /path/to/outp ``` `--file` 接收相对于主文件目录的路径,可列出子文件及实际使用的图像等资源。 -编辑器在试用目录中创建工作副本。当前编辑内容保存在会话内,可以下载 PDF。 -命令行按项目实际读写作业文件。需要 BibTeX 的项目可在辅助文件生成后 -运行 BibTeX,再继续 LaTeX 编译到引用收敛。 +编辑器在试用目录中创建工作副本。命令行按项目实际读写作业文件。 +需要 BibTeX 的项目可在辅助文件生成后运行 BibTeX,再继续 LaTeX 编译到引用收敛。 + +## 保存和重新打开 + +点击「保存源文件」将当前编辑与已声明的项目资源一起写入一个新目录。 +目录路径显示在编辑器中。里面的 sources 子目录包含可单独使用的项目文件, +预览的 PDF 可通过「下载 PDF」另行取得。使用原 Beta 包打开保存目录。 + +~~~sh +python3 target/local-beta/native-beta.py resume /path/to/texrra-sources-directory +~~~ + +有编译错误的草稿也可以保存。重开目前需要通过首次编译,若草稿仍有错误, +可先在保存目录的 sources 中修正源文件。每次保存都会得到独立的一份。 ## 已对照的项目 diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index a52d035..023a740 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,29 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 Beta 源码保存和恢复 + +编辑器保存时将当前浏览器缓冲与已声明的输入资源一并写入一个 +源码副本。先完成全部文件和恢复清单,再发布新目录。保存与编译 +各自处理,已有输出继续按编译版本发布。resume 读取保存目录的 +入口和实际相对路径,建立新的编译工作目录。 + +用原样 A4 主文件和子文件在 Edge 验证。在同一次操作中修改两个 +文件并保存,随后收到更新的预览。额外声明的嵌套 PDF 资源按实际 +字节保存。引入未知命令的草稿可另存,错误期间仍可下载上次 PDF。 +两次源码副本保持独立。已验证旧版本、未知文件和非 JSON 请求均被 +拒绝,未创建额外副本。 + +重新启动有效副本后,浏览器缓冲、PDF 及辅助文件与独立 CLI 两轮 +收敛作业一致。测试输入文件指纹保持。错误草稿当前重开仍受首次 +编译限制,失败和保存下来的源文件均保留。下一批从错误草稿可打开 +的资源准备路径及原样多页项目的启动耗时继续推进。 + +本机包在 target/native-beta-save/beta-pdftex/。证据目录 +target/native-beta-save/ 的 SHA256SUMS 指纹为 +46d0ba4d0fd0afe15a3dad8f19915a7ef3048c3964cae240611fc60b05053c4c。 +[Beta 使用指南](NATIVE_BETA.md#保存和重新打开) + ## 2026-11-29 本地 Beta 启动与五份原样模板 本地启动脚本准备同一构建的原生 CLI、编辑器、实际格式与资源配置。 diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index a523932..cfaaf17 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -3,6 +3,8 @@ const pages = document.querySelector("#pages"); const status = document.querySelector("#status"); const error = document.querySelector("#error"); const pdf = document.querySelector("#pdf"); +const save = document.querySelector("#save"); +const saved = document.querySelector("#saved"); const selector = document.querySelector("#project-files"); const name = document.querySelector("#name"); const edits = new Map(); @@ -171,6 +173,26 @@ function queueCompile() { frame = requestAnimationFrame(() => compile(edit, submitted, changes)); } +async function saveSources() { + save.disabled = true; + saved.hidden = false; + saved.textContent = "正在保存源文件"; + try { + const response = await fetch("/save", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sequence, files: Object.fromEntries(edits) }), + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error); + saved.textContent = "已保存源文件至 " + result.directory; + } catch (failure) { + saved.textContent = "保存失败:" + failure.message; + } finally { + save.disabled = false; + } +} + async function openProject() { try { const response = await fetch("/project"); @@ -182,6 +204,8 @@ async function openProject() { source.value = files.get(activeFile); source.disabled = false; sequence = project.sequence; + save.disabled = false; + save.addEventListener("click", saveSources); if (files.size > 1) { for (const filename of files.keys()) selector.add(new Option(filename, filename)); selector.value = activeFile; diff --git a/examples/native_editor/index.html b/examples/native_editor/index.html index c99e79f..91755be 100644 --- a/examples/native_editor/index.html +++ b/examples/native_editor/index.html @@ -18,6 +18,8 @@ } header strong { letter-spacing: .02em; } header a { color: #bde5ff; } + .actions { min-width: 0; display: flex; align-items: center; flex-wrap: wrap; gap: .6rem; } + .actions span { overflow-wrap: anywhere; } main { display: grid; grid-template-columns: minmax(270px, 5fr) minmax(300px, 7fr); min-height: 0; } .edit { min-height: 0; display: grid; grid-template-rows: auto 1fr; background: white; } .file { padding: .6rem 1rem; border-bottom: 1px solid #d9e0e6; font: 14px/1.5 ui-monospace, monospace; } @@ -38,7 +40,11 @@
Texrra 原生预览 正在打开文档 - +
+ + + +
diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 6d8783b..35ecd96 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -23,6 +23,8 @@ use texrra_tex_core::{ }; use tiny_http::{Header, Method, Request, Response, Server}; +mod saved_project; + const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024; const PAGE: &str = include_str!("index.html"); const SCRIPT: &str = include_str!("app.js"); @@ -38,6 +40,12 @@ struct Edit { preview_draft: bool, } +#[derive(Deserialize)] +struct Save { + sequence: u64, + files: BTreeMap, +} + struct Work { request: Request, job: CompileJob, @@ -208,6 +216,7 @@ fn main() -> Result<(), Box> { mut project, entry, editable, + declared, options, } = prepare(&source, &format, &manifest, &run, &additional, input_profile)?; let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); @@ -220,6 +229,7 @@ fn main() -> Result<(), Box> { let queue = queue.clone(); move || worker(&queue) }); + let mut save_number = 0; println!("Native editor http://{}", server.server_addr()); for request in server.incoming_requests() { let path = request.url().to_owned(); @@ -252,7 +262,7 @@ fn main() -> Result<(), Box> { (&Method::Post, "/preview") => { let received = Instant::now(); let mut request = request; - let edit = match read_edit(&mut request) { + let edit: Edit = match read_json(&mut request) { Ok(edit) => edit, Err(error) => { reply(request, 400, json!({ "error": error })); @@ -318,6 +328,38 @@ fn main() -> Result<(), Box> { ); } } + (&Method::Post, "/save") => { + let mut request = request; + if !request.headers().iter().any(|header| { + header.field.equiv("Content-Type") + && header.value.as_str().split(';').next() == Some("application/json") + }) { + reply(request, 415, json!({"error": "Expected JSON source edits"})); + continue; + } + let save: Save = match read_json(&mut request) { + Ok(save) => save, + Err(error) => { + reply(request, 400, json!({ "error": error })); + continue; + } + }; + if save.sequence < queue.current.load(Ordering::Acquire) { + reply(request, 409, json!({"error": "A newer edit is already queued"})); + continue; + } + let changes: Option> = save.files.iter() + .map(|(name, data)| editable.get(name).map(|path| (path.as_path(), data.as_bytes()))) + .collect(); + let Some(changes) = changes else { + reply(request, 422, json!({"error": "The save refers to an unknown source file"})); + continue; + }; + match saved_project::save(&run, &entry, &declared, &project, changes, &mut save_number) { + Ok(path) => reply(request, 200, json!({"directory": path})), + Err(error) => reply(request, 500, json!({"error": error.to_string()})), + } + } (&Method::Get, path) if path.starts_with("/publication?revision=") => { let revision = path["/publication?revision=".len()..].parse::().ok(); let result = queue @@ -377,7 +419,7 @@ fn main() -> Result<(), Box> { Ok(()) } -fn read_edit(request: &mut Request) -> Result { +fn read_json(request: &mut Request) -> Result { let mut body = Vec::new(); request .as_reader() @@ -394,6 +436,7 @@ struct EditorProject { project: Arc, entry: PathBuf, editable: BTreeMap, + declared: BTreeSet, options: CompileRequest, } @@ -545,6 +588,7 @@ fn prepare( project, entry, editable, + declared, options: request, }) } diff --git a/examples/native_editor/saved_project.rs b/examples/native_editor/saved_project.rs new file mode 100644 index 0000000..e9558a5 --- /dev/null +++ b/examples/native_editor/saved_project.rs @@ -0,0 +1,66 @@ +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, io, + path::{Path, PathBuf}, +}; +use texrra_engine::native::ProjectSnapshot; + +pub(super) fn save( + run: &Path, + entry: &Path, + declared: &BTreeSet, + project: &ProjectSnapshot, + edits: BTreeMap<&Path, &[u8]>, + next_number: &mut u64, +) -> io::Result { + let parent = run.parent().expect("the working directory has a parent"); + let (staging, destination) = loop { + *next_number += 1; + let name = format!("texrra-sources-{}-{next_number}", std::process::id()); + let destination = parent.join(&name); + if destination.symlink_metadata().is_ok() { + continue; + } + let staging = parent.join(format!(".{name}.pending")); + match fs::create_dir(&staging) { + Ok(()) => break (staging, destination), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + }; + let result = (|| { + let sources = staging.join("sources"); + fs::create_dir(&sources)?; + let mut files = Vec::new(); + for path in declared { + let relative = path.strip_prefix(run).expect("declared sources stay in the working copy"); + let name = relative.to_str().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "A project file needs a UTF-8 name") + })?; + let saved = sources.join(relative); + fs::create_dir_all(saved.parent().expect("a source file has a parent"))?; + if let Some(data) = edits + .get(path.as_path()) + .copied() + .or_else(|| project.file(path).map(|file| file.data.as_ref())) + { + fs::write(&saved, data)?; + } + if path != entry { + files.push(name); + } + } + let entry_name = entry.file_name().expect("the entry has a name").to_str().unwrap(); + let manifest = fs::File::create(staging.join("project.json"))?; + serde_json::to_writer_pretty(manifest, &serde_json::json!({ + "entry": entry_name, "files": files, + }))?; + // Publish the metadata and every source at once. + fs::rename(&staging, &destination) + })(); + if let Err(error) = result { + let _ = fs::remove_dir_all(&staging); + return Err(error); + } + Ok(destination) +} diff --git a/scripts/native-beta.py b/scripts/native-beta.py index c1c0b78..fdb227f 100644 --- a/scripts/native-beta.py +++ b/scripts/native-beta.py @@ -125,9 +125,18 @@ def launch(args): env.update(manifest["environment"]) env["TEXRRA_STATE_DIR"] = str(bundle / "state") profile = manifest["input_profile"] - if args.action == "open": - source = args.entry.resolve(strict=True) if args.entry else bundle / "a4-project/main.tex" - assets = args.file if args.entry else ["chapter.tex", *args.file] + if args.action in ("open", "resume"): + if args.action == "resume": + saved = args.snapshot.resolve(strict=True) + project = json.loads((saved / "project.json").read_text(encoding="utf-8")) + entry = Path(project["entry"]) + if len(entry.parts) != 1 or entry.name in ("", ".."): + raise ValueError("The saved project entry must be a filename") + source = (saved / "sources" / entry).resolve(strict=True) + assets = project["files"] + else: + source = args.entry.resolve(strict=True) if args.entry else bundle / "a4-project/main.tex" + assets = args.file if args.entry else ["chapter.tex", *args.file] runs = bundle / "runs" if args.run_dir: run = args.run_dir.resolve() @@ -162,8 +171,11 @@ def main(): editor = commands.add_parser("open", help="open a project or the bundled A4 sample") editor.add_argument("entry", type=Path, nargs="?") editor.add_argument("--file", action="append", default=[], help="path relative to the entry") - editor.add_argument("--run-dir", type=Path) - editor.add_argument("--port", type=int, default=0) + resume = commands.add_parser("resume", help="reopen a saved source snapshot") + resume.add_argument("snapshot", type=Path) + for command in (editor, resume): + command.add_argument("--run-dir", type=Path) + command.add_argument("--port", type=int, default=0) compiler = commands.add_parser("compile", help="produce a PDF with the bundle's native CLI") compiler.add_argument("entry", type=Path)