diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 5732789..27ded1b 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -330,6 +330,29 @@ p95 分别为105.9和119.7 ms。运行前后 I/O pressure avg10 为11.45%和39.9 `target/p4-cancel-obsolete-svg/directed-2.log` 的 SHA-256 为 `8ee6161e103c8bc3bf1d41f2b4345533c77b1aed88a029cd223b8697427e8ee3`。取消延迟的独立预算还需实际测试。 +### 多文件编辑器和原样 A4 + +测试编辑器可在现有端口参数之后接收相对入口目录的项目文件列表。选择主文件 +或子文件编辑时,尚未保存的缓冲区合并为同一个原子项目修订。原有主文件请求 +继续可用,未列为可编辑的文件拒绝进入修订。原始输入文件保持同字节。 + +用实际原样 A4 的 `main.tex` 和 `chapter.tex` 验证两份缓冲区在同一浏览器 +帧内修改后都进入同一修订,并逐次核对 `chapter.tex` 实际入读版本与字形 +来源。相同优化程序和真实 LaTeX 格式,每种交付方式各做30次主文件正文修改 +和30次子文件正文修改。页面、SVG、PDF、当前来源版本和映射、最终 aux +一致。57次提前绘制后仍直接观察到文件待发布。 + +| 编辑范围 | 文件发布后绘制 p50 / p95 | 文件写入期间绘制 p50 / p95 | +| --- | ---: | ---: | +| 主文件正文 | 888.9 / 1935.3 ms | 261.9 / 293.3 ms | +| 子文件正文 | 1028.8 / 2197.6 ms | 280.5 / 316.1 ms | + +服务端峰值 RSS 为629292和629900 KiB。主文件100 ms 和依赖250 ms 的可见 +预算仍待达到。独立全量使用同一优化程序、原样格式和最后两份未保存的实际 +缓冲区,零复用步骤,得到与热会话逐字节一致的 PDF、SVG、来源版本和映射、 +最终 aux。浏览器回执 `target/p4-multifile-editor/edge-a4/run-1/receipt.json` +SHA-256 为 `305fa4b8a1247f5c3683e2434d8b43b7a5b4dfd0256711a37ffd3a220a13ebb3`,独立全量回执 SHA-256 为 `47753c1293eb31fca88d1ac2357dfd50ada6156699b703b3dc1178d87082b4b4`。 + ### schema27 与主线兼容性 合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。 diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index e1a3dc9..8a1771c 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -3,6 +3,11 @@ const pages = document.querySelector("#pages"); const status = document.querySelector("#status"); const error = document.querySelector("#error"); const pdf = document.querySelector("#pdf"); +const selector = document.querySelector("#project-files"); +const name = document.querySelector("#name"); +const edits = new Map(); +let files; +let activeFile; let sequence = 0; let publishedRevision = null; let draft = null; @@ -75,7 +80,7 @@ async function publicationStatus(edit, revision) { return null; } -async function compile(edit, submitted) { +async function compile(edit, submitted, changes) { const replacements = []; try { const response = await fetch("/preview", { @@ -84,7 +89,7 @@ async function compile(edit, submitted) { body: JSON.stringify({ sequence: edit, visible_revision: publishedRevision, - source: source.value, + files: changes, preview_draft: previewDraft, }), }); @@ -159,7 +164,8 @@ function queueCompile() { cancelAnimationFrame(frame); restorePublishedPages(); status.textContent = "正在编译"; - frame = requestAnimationFrame(() => compile(edit, submitted)); + const changes = Object.fromEntries(edits); + frame = requestAnimationFrame(() => compile(edit, submitted, changes)); } async function openProject() { @@ -167,11 +173,26 @@ async function openProject() { const response = await fetch("/project"); if (!response.ok) throw new Error("无法打开源文件"); const project = await response.json(); - document.querySelector("#name").textContent = project.name; - source.value = project.source; + files = new Map(Object.entries(project.files)); + activeFile = project.name; + name.textContent = activeFile; + source.value = files.get(activeFile); source.disabled = false; sequence = project.sequence; - source.addEventListener("input", queueCompile); + if (files.size > 1) { + for (const filename of files.keys()) selector.add(new Option(filename, filename)); + selector.value = activeFile; + selector.hidden = false; + name.hidden = true; + selector.addEventListener("change", () => { + activeFile = selector.value; + source.value = edits.get(activeFile) ?? files.get(activeFile); + }); + } + source.addEventListener("input", () => { + edits.set(activeFile, source.value); + queueCompile(); + }); queueCompile(); } catch (failure) { showError(failure.message); diff --git a/examples/native_editor/index.html b/examples/native_editor/index.html index b1d503e..c99e79f 100644 --- a/examples/native_editor/index.html +++ b/examples/native_editor/index.html @@ -42,7 +42,10 @@
- +
+ + +
diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 5e1c7a9..629046b 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -5,7 +5,7 @@ use std::{ collections::{BTreeMap, BTreeSet}, fs, io::Read, - path::{Path, PathBuf}, + path::{Component, Path, PathBuf}, sync::{ Arc, Condvar, Mutex, atomic::{AtomicU64, Ordering}, @@ -28,7 +28,9 @@ const SCRIPT: &str = include_str!("app.js"); struct Edit { sequence: u64, visible_revision: Option, - source: String, + source: Option, + #[serde(default)] + files: BTreeMap, #[serde(default)] preview_draft: bool, } @@ -168,7 +170,7 @@ struct Queue { fn main() -> Result<(), Box> { let mut args = std::env::args_os().skip(1).map(PathBuf::from); - let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT]"; + let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...]"; let source = args.next().ok_or(usage)?.canonicalize()?; let format = args.next().ok_or(usage)?.canonicalize()?; let manifest = args.next().ok_or(usage)?; @@ -178,12 +180,15 @@ fn main() -> Result<(), Box> { .map(|s| s.to_string_lossy().parse()) .transpose()? .unwrap_or(0u16); - if args.next().is_some() { - return Err(usage.into()); - } + let additional = args.collect::>(); fs::create_dir(&run)?; let run = run.canonicalize()?; - let (mut project, entry, options) = prepare(&source, &format, &manifest, &run)?; + let EditorProject { + mut project, + entry, + editable, + options, + } = prepare(&source, &format, &manifest, &run, &additional)?; let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?; let queue = Arc::new(Queue { @@ -207,12 +212,22 @@ fn main() -> Result<(), Box> { ), (&Method::Get, "/project") => { let file = project.file(&entry).expect("the editor owns its entry"); + let files = editable + .iter() + .map(|(name, path)| { + let file = project + .file(path) + .expect("editable project files are immutable"); + Ok((name, std::str::from_utf8(&file.data)?)) + }) + .collect::, std::str::Utf8Error>>()?; reply( request, 200, json!({ "name": entry.file_name().unwrap().to_string_lossy(), "source": std::str::from_utf8(&file.data)?, + "files": files, "sequence": queue.current.load(Ordering::Acquire), }), ); @@ -235,10 +250,26 @@ fn main() -> Result<(), Box> { ); continue; } - let next = project.with_file_edits( - edit.sequence, - BTreeMap::from([(entry.clone(), Arc::from(edit.source.into_bytes()))]), - ); + let updates = edit + .files + .into_iter() + .map(|(name, value)| { + let path = editable + .get(&name) + .ok_or_else(|| format!("File is not editable: {name}"))?; + Ok((path.clone(), Arc::from(value.into_bytes()))) + }) + .collect::, String>>(); + let next = updates.and_then(|mut updates| { + if let Some(source) = edit.source + && updates + .insert(entry.clone(), Arc::from(source.into_bytes())) + .is_some() + { + return Err("The entry file was edited twice".into()); + } + project.with_file_edits(edit.sequence, updates) + }); project = match next { Ok(project) => project, Err(error) => { @@ -339,20 +370,66 @@ fn read_edit(request: &mut Request) -> Result { serde_json::from_slice(&body).map_err(|e| e.to_string()) } +struct EditorProject { + project: Arc, + entry: PathBuf, + editable: BTreeMap, + options: CompileRequest, +} + fn prepare( source: &Path, format: &Path, manifest: &Path, run: &Path, -) -> Result<(Arc, PathBuf, CompileRequest), Box> { + additional: &[PathBuf], +) -> Result> { let format_resources: Value = serde_json::from_slice(&fs::read(manifest)?)?; let roots: Vec = serde_json::from_value(format_resources["texmf_roots"].clone())?; let mut world = WorldConfig::from_environment(run, roots.clone())?; world.input_policy = InputPolicy::Tex; - let entry = run.join(source.file_name().ok_or("Source needs a filename")?); + let name = source + .file_name() + .and_then(|name| name.to_str()) + .ok_or("Source needs a UTF-8 filename")?; + let entry = run.join(name); let original = fs::read(source)?; std::str::from_utf8(&original)?; fs::write(&entry, &original)?; + let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]); + let mut files = BTreeMap::>::from([(entry.clone(), Arc::from(original))]); + let source_root = source.parent().expect("the entry has a parent"); + for relative in additional { + if relative.as_os_str().is_empty() + || relative + .components() + .any(|item| !matches!(item, Component::Normal(_))) + { + return Err(format!( + "Project file must be relative to the entry directory: {}", + relative.display() + ) + .into()); + } + let logical = run.join(relative); + let physical = source_root.join(relative).canonicalize()?; + if !physical.starts_with(source_root) || files.contains_key(&logical) { + return Err(format!( + "Project file is outside the entry directory or is listed twice: {}", + relative.display() + ) + .into()); + } + let data: Arc<[u8]> = Arc::from(fs::read(physical)?); + fs::create_dir_all(logical.parent().expect("project file has a parent"))?; + fs::write(&logical, &data)?; + if let Some(name) = relative.to_str() + && std::str::from_utf8(&data).is_ok() + { + editable.insert(name.into(), logical.clone()); + } + files.insert(logical, data); + } let mut request = CompileRequest::new( world.clone(), &entry, @@ -366,7 +443,6 @@ fn prepare( // Provision the finite, immutable resource bundle used by this trial. // The seed uses the same native compiler and actual package bytes. let seed = NativeCompiler::default().compile(request.clone())?; - let mut files = BTreeMap::from([(entry.clone(), Arc::from(original))]); for (path, captured) in seed.inputs.files() { if !path.starts_with(run) { files.insert(path.to_owned(), captured?.data.clone()); @@ -404,7 +480,12 @@ fn prepare( generated_roots: BTreeSet::from([run.to_owned()]), generated, })?; - Ok((project, entry, request)) + Ok(EditorProject { + project, + entry, + editable, + options: request, + }) } fn worker(queue: &Arc) {