Edit multiple project buffers in the native preview

This commit is contained in:
gloamxun committed 2026-11-19 17:39:01 +08:00
1 parent b5e87a8706
commit f6c493e462
4 files changed
+150 -22

No files matched your search

+23
View File
@@ -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 为 `target/p4-cancel-obsolete-svg/directed-2.log` 的 SHA-256 为
`8ee6161e103c8bc3bf1d41f2b4345533c77b1aed88a029cd223b8697427e8ee3`。取消延迟的独立预算还需实际测试。 `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 与主线兼容性 ### schema27 与主线兼容性
合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。 合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。
+27 -6
View File
@@ -3,6 +3,11 @@ const pages = document.querySelector("#pages");
const status = document.querySelector("#status"); const status = document.querySelector("#status");
const error = document.querySelector("#error"); const error = document.querySelector("#error");
const pdf = document.querySelector("#pdf"); 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 sequence = 0;
let publishedRevision = null; let publishedRevision = null;
let draft = null; let draft = null;
@@ -75,7 +80,7 @@ async function publicationStatus(edit, revision) {
return null; return null;
} }
async function compile(edit, submitted) { async function compile(edit, submitted, changes) {
const replacements = []; const replacements = [];
try { try {
const response = await fetch("/preview", { const response = await fetch("/preview", {
@@ -84,7 +89,7 @@ async function compile(edit, submitted) {
body: JSON.stringify({ body: JSON.stringify({
sequence: edit, sequence: edit,
visible_revision: publishedRevision, visible_revision: publishedRevision,
source: source.value, files: changes,
preview_draft: previewDraft, preview_draft: previewDraft,
}), }),
}); });
@@ -159,7 +164,8 @@ function queueCompile() {
cancelAnimationFrame(frame); cancelAnimationFrame(frame);
restorePublishedPages(); restorePublishedPages();
status.textContent = "正在编译"; status.textContent = "正在编译";
frame = requestAnimationFrame(() => compile(edit, submitted)); const changes = Object.fromEntries(edits);
frame = requestAnimationFrame(() => compile(edit, submitted, changes));
} }
async function openProject() { async function openProject() {
@@ -167,11 +173,26 @@ async function openProject() {
const response = await fetch("/project"); const response = await fetch("/project");
if (!response.ok) throw new Error("无法打开源文件"); if (!response.ok) throw new Error("无法打开源文件");
const project = await response.json(); const project = await response.json();
document.querySelector("#name").textContent = project.name; files = new Map(Object.entries(project.files));
source.value = project.source; activeFile = project.name;
name.textContent = activeFile;
source.value = files.get(activeFile);
source.disabled = false; source.disabled = false;
sequence = project.sequence; 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(); queueCompile();
} catch (failure) { } catch (failure) {
showError(failure.message); showError(failure.message);
+4 -1
View File
@@ -42,7 +42,10 @@
</header> </header>
<main> <main>
<section class="edit" aria-label="源文件"> <section class="edit" aria-label="源文件">
<label class="file" for="source" id="name">源文件</label> <div class="file">
<label for="source" id="name">源文件</label>
<select id="project-files" aria-label="选择源文件" hidden></select>
</div>
<textarea id="source" spellcheck="false" disabled></textarea> <textarea id="source" spellcheck="false" disabled></textarea>
</section> </section>
<section class="preview" aria-label="页面预览"> <section class="preview" aria-label="页面预览">
+96 -15
View File
@@ -5,7 +5,7 @@ use std::{
collections::{BTreeMap, BTreeSet}, collections::{BTreeMap, BTreeSet},
fs, fs,
io::Read, io::Read,
path::{Path, PathBuf}, path::{Component, Path, PathBuf},
sync::{ sync::{
Arc, Condvar, Mutex, Arc, Condvar, Mutex,
atomic::{AtomicU64, Ordering}, atomic::{AtomicU64, Ordering},
@@ -28,7 +28,9 @@ const SCRIPT: &str = include_str!("app.js");
struct Edit { struct Edit {
sequence: u64, sequence: u64,
visible_revision: Option<u64>, visible_revision: Option<u64>,
source: String, source: Option<String>,
#[serde(default)]
files: BTreeMap<String, String>,
#[serde(default)] #[serde(default)]
preview_draft: bool, preview_draft: bool,
} }
@@ -168,7 +170,7 @@ struct Queue {
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args_os().skip(1).map(PathBuf::from); 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 source = args.next().ok_or(usage)?.canonicalize()?;
let format = args.next().ok_or(usage)?.canonicalize()?; let format = args.next().ok_or(usage)?.canonicalize()?;
let manifest = args.next().ok_or(usage)?; let manifest = args.next().ok_or(usage)?;
@@ -178,12 +180,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.map(|s| s.to_string_lossy().parse()) .map(|s| s.to_string_lossy().parse())
.transpose()? .transpose()?
.unwrap_or(0u16); .unwrap_or(0u16);
if args.next().is_some() { let additional = args.collect::<Vec<_>>();
return Err(usage.into());
}
fs::create_dir(&run)?; fs::create_dir(&run)?;
let run = run.canonicalize()?; 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 compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?; let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
let queue = Arc::new(Queue { let queue = Arc::new(Queue {
@@ -207,12 +212,22 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
), ),
(&Method::Get, "/project") => { (&Method::Get, "/project") => {
let file = project.file(&entry).expect("the editor owns its entry"); 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::<Result<BTreeMap<_, _>, std::str::Utf8Error>>()?;
reply( reply(
request, request,
200, 200,
json!({ json!({
"name": entry.file_name().unwrap().to_string_lossy(), "name": entry.file_name().unwrap().to_string_lossy(),
"source": std::str::from_utf8(&file.data)?, "source": std::str::from_utf8(&file.data)?,
"files": files,
"sequence": queue.current.load(Ordering::Acquire), "sequence": queue.current.load(Ordering::Acquire),
}), }),
); );
@@ -235,10 +250,26 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
); );
continue; continue;
} }
let next = project.with_file_edits( let updates = edit
edit.sequence, .files
BTreeMap::from([(entry.clone(), Arc::from(edit.source.into_bytes()))]), .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::<Result<BTreeMap<_, _>, 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 { project = match next {
Ok(project) => project, Ok(project) => project,
Err(error) => { Err(error) => {
@@ -339,20 +370,66 @@ fn read_edit(request: &mut Request) -> Result<Edit, String> {
serde_json::from_slice(&body).map_err(|e| e.to_string()) serde_json::from_slice(&body).map_err(|e| e.to_string())
} }
struct EditorProject {
project: Arc<ProjectSnapshot>,
entry: PathBuf,
editable: BTreeMap<String, PathBuf>,
options: CompileRequest,
}
fn prepare( fn prepare(
source: &Path, source: &Path,
format: &Path, format: &Path,
manifest: &Path, manifest: &Path,
run: &Path, run: &Path,
) -> Result<(Arc<ProjectSnapshot>, PathBuf, CompileRequest), Box<dyn std::error::Error>> { additional: &[PathBuf],
) -> Result<EditorProject, Box<dyn std::error::Error>> {
let format_resources: Value = serde_json::from_slice(&fs::read(manifest)?)?; let format_resources: Value = serde_json::from_slice(&fs::read(manifest)?)?;
let roots: Vec<PathBuf> = serde_json::from_value(format_resources["texmf_roots"].clone())?; let roots: Vec<PathBuf> = serde_json::from_value(format_resources["texmf_roots"].clone())?;
let mut world = WorldConfig::from_environment(run, roots.clone())?; let mut world = WorldConfig::from_environment(run, roots.clone())?;
world.input_policy = InputPolicy::Tex; 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)?; let original = fs::read(source)?;
std::str::from_utf8(&original)?; std::str::from_utf8(&original)?;
fs::write(&entry, &original)?; fs::write(&entry, &original)?;
let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]);
let mut files = BTreeMap::<PathBuf, Arc<[u8]>>::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( let mut request = CompileRequest::new(
world.clone(), world.clone(),
&entry, &entry,
@@ -366,7 +443,6 @@ fn prepare(
// Provision the finite, immutable resource bundle used by this trial. // Provision the finite, immutable resource bundle used by this trial.
// The seed uses the same native compiler and actual package bytes. // The seed uses the same native compiler and actual package bytes.
let seed = NativeCompiler::default().compile(request.clone())?; let seed = NativeCompiler::default().compile(request.clone())?;
let mut files = BTreeMap::from([(entry.clone(), Arc::from(original))]);
for (path, captured) in seed.inputs.files() { for (path, captured) in seed.inputs.files() {
if !path.starts_with(run) { if !path.starts_with(run) {
files.insert(path.to_owned(), captured?.data.clone()); files.insert(path.to_owned(), captured?.data.clone());
@@ -404,7 +480,12 @@ fn prepare(
generated_roots: BTreeSet::from([run.to_owned()]), generated_roots: BTreeSet::from([run.to_owned()]),
generated, generated,
})?; })?;
Ok((project, entry, request)) Ok(EditorProject {
project,
entry,
editable,
options: request,
})
} }
fn worker(queue: &Arc<Queue>) { fn worker(queue: &Arc<Queue>) {