From 830292b9b6fe390373da2161efd370a27511d56a Mon Sep 17 00:00:00 2001 From: GloamXun Date: Thu, 3 Dec 2026 00:02:37 +0800 Subject: [PATCH] Reduce Windows desktop format, opening and edit latency --- .../src/execution/format_image/location.rs | 46 +++ desktop/README.md | 10 +- desktop/build-windows-backend.py | 30 +- desktop/src-tauri/Cargo.lock | 2 +- desktop/src-tauri/Cargo.toml | 2 +- desktop/src-tauri/tauri.conf.json | 2 +- examples/native_editor/app.js | 68 +++- examples/native_editor/library.rs | 49 ++- examples/native_editor/main.rs | 352 ++++++++++++++---- examples/native_editor/windows_format.rs | 203 +++++++--- src/native.rs | 35 +- src/native_checkpoint_guard.rs | 130 ++++++- src/native_host.rs | 138 ++++++- src/native_preview.rs | 32 +- tests/native_pipeline.rs | 74 ++++ 15 files changed, 1006 insertions(+), 167 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/format_image/location.rs b/crates/texrra-tex-core/src/execution/format_image/location.rs index 85dcf6b..61cacc7 100644 --- a/crates/texrra-tex-core/src/execution/format_image/location.rs +++ b/crates/texrra-tex-core/src/execution/format_image/location.rs @@ -71,6 +71,52 @@ impl FormatImage { self } + /// Bind a generated release format to the bundle that contains all its inputs. + pub fn with_bundle_location(mut self, output: &Path, bundle: &Path) -> Result { + let format_directory = output + .parent() + .and_then(|parent| parent.strip_prefix(bundle).ok()) + .ok_or("native release format output must be inside its bundle")?; + if self + .file_dates + .iter() + .any(|date| Path::new(&date.name).is_absolute()) + { + return Err("native release format observed an absolute file date".into()); + } + let checked = self.build_input_checks(); + let inputs = checked + .keys() + .map(PathBuf::as_path) + .chain(self.file_dates.iter().map(|date| Path::new(&date.from))) + .chain( + self.pdf_images + .iter() + .filter(|image| image.kind.reads_at_load()) + .map(|image| image.path()), + ) + .map(|path| { + let relative = path.strip_prefix(bundle).map_err(|_| { + format!( + "native release format input outside its bundle: {}", + path.display() + ) + })?; + Ok((path.to_owned(), BTreeSet::from([relative.to_owned()]))) + }) + .collect::>()?; + let location = FormatLocation { + cwd: bundle.to_owned(), + format_directory: format_directory.to_owned(), + inputs, + }; + if !location.is_valid() { + return Err("invalid native release format location".into()); + } + self.location = Some(location); + Ok(self) + } + /// Resolve a moved tree as a group. A format copied without its relative /// inputs still uses the original tree. Once any moved input is present, /// every recorded input and alias in the moved tree must be available. diff --git a/desktop/README.md b/desktop/README.md index 1f2fe94..4bf4272 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -29,8 +29,9 @@ Unicode 与 pdfLaTeX 兼容项目。 xeCJK 或 fontspec。线索不足时使用 pdfLaTeX,以保留常见旧模板的排版。 可以在「重新编译」旁按项目选择「自动」「Unicode」或「pdfLaTeX」。 -切换会保留当前编辑和上次成功预览。首次使用对应模式时会生成格式, -后续重开时复用。若要在已打开的旧模板里添加中文,可以切到「Unicode」, +切换会保留当前编辑和上次成功预览。0.1.11 安装包预先生成两份格式。 +打开项目时加载所选格式,后续在同一程序中复用。要在现有模板里添加中文, +可以切到「Unicode」, 并在导言区加入 `\usepackage[UTF8,scheme=plain]{ctex}`。 [CTeX 宏集手册](https://tug.ctan.org/language/chinese/ctex/ctex.pdf) @@ -50,8 +51,9 @@ cargo build --locked --release --target x86_64-pc-windows-msvc --example native_ zhnumber、fandol、xetex、ctex.doc、xecjk.doc、zhnumber.doc、 fandol.doc 的 `.tar.xz` 归档,放在同一下载目录。脚本用包索引校验 归档,再将 Unicode 资源和许可文件纳入安装包清单。使用已核验的 -WSL 发布版作为基础 TeX 资源和 Web 界面的来源,在能访问该参考包 -资源树的构建机运行。 +WSL 发布版作为基础 TeX 资源和 Web 界面的来源。准备脚本会运行同版 +Windows 内核,生成并校验安装包内的两份编译格式。构建机需能访问 +参考资源并运行 Windows 程序,可以使用 Windows 或启用互操作的 WSL。 ```sh python3 desktop/build-windows-backend.py desktop/src-tauri/backend \ diff --git a/desktop/build-windows-backend.py b/desktop/build-windows-backend.py index 7a12f3e..4e52eb5 100644 --- a/desktop/build-windows-backend.py +++ b/desktop/build-windows-backend.py @@ -5,9 +5,12 @@ import argparse import hashlib import json import lzma +import os from pathlib import Path, PurePosixPath import shutil +import stat import struct +import subprocess import tarfile import tempfile @@ -18,6 +21,7 @@ TOOLS = { "bibtex.windows": ("bibtex.exe",), "kpathsea.windows": ("kpsewhich.exe", "kpathsealibw64.dll", "msvcr100.dll"), } +FORMAT_MODES = ("pdflatex", "xelatex") UNICODE_PACKAGES = ("ctex", "xecjk", "zhnumber", "fandol", "xetex") UNICODE_NOTICES = { "ctex": {"doc/latex/ctex/README.md": "ctex-README.md"}, @@ -145,6 +149,28 @@ def copy_texmf(source, target, skip_generated): shutil.copy2(path, staged) +def prepare_formats(output): + output = output.resolve(strict=True) + editor = output / "bin/native_editor.exe" + if os.name == "nt": + backend = str(output) + else: + backend = subprocess.check_output(["wslpath", "-w", str(output)], text=True).strip() + editor.chmod(editor.stat().st_mode | stat.S_IXUSR) + subprocess.run( + [str(editor), "--prepare-windows-formats", backend], + stdin=subprocess.DEVNULL, + check=True, + ) + for name in FORMAT_MODES: + directory = output / "formats" / name + for filename in ("latex.tfx", "texsys.aux"): + path = directory / filename + if not path.is_file() or not path.stat().st_size: + raise ValueError(f"Missing generated {name} format input: {filename}") + (directory / "latex.log").unlink(missing_ok=True) + + def stage(args, output): reference = json.loads((args.reference / "bundle.json").read_text()) desktop = json.loads((args.reference / "desktop-bundle.json").read_text()) @@ -158,7 +184,8 @@ def stage(args, output): font_maps = Path(reference["environment"]["TEXFONTMAPS"].rstrip(":")) (texmf / "fonts").mkdir() shutil.copy2(font_maps / "pdftex.map", texmf / "fonts") - for entry in ("pdflatex.ini", "xelatex.ini"): + for mode in FORMAT_MODES: + entry = f"{mode}.ini" if not (texmf / "dist/tex/latex/tex-ini-files" / entry).is_file(): raise ValueError(f"Missing LaTeX initialization source: {entry}") @@ -189,6 +216,7 @@ def stage(args, output): texmf / "overlay", licenses / "texlive", args.downloads, database ) + prepare_formats(output) files = { path.relative_to(output).as_posix(): digest(path) for path in sorted(output.rglob("*")) if path.is_file() diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 1ab39aa..be2cb69 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -3237,7 +3237,7 @@ dependencies = [ [[package]] name = "texrra-desktop" -version = "0.1.10" +version = "0.1.11" dependencies = [ "serde_json", "tauri", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index e1b6c88..ee5c374 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "texrra-desktop" -version = "0.1.10" +version = "0.1.11" edition = "2024" rust-version = "1.92" license = "MIT OR Apache-2.0" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 3f44b47..259bc9f 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Texrra", - "version": "0.1.10", + "version": "0.1.11", "identifier": "org.texrra.desktop", "build": { "frontendDist": "../startup" diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index ecb6e60..0b31bf1 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -27,6 +27,9 @@ let activeFile; let preparingProject = false; let compileMode; let cachedPreviewRequest; +let openingPreviewRequest; +let openingPreviewFrame; +const openingStarted = performance.now(); let sequence = 0; let publishedRevision = null; let visibleRevision = null; @@ -219,6 +222,7 @@ async function showCachedPreview() { if (!canDisplay()) return; for (const page of savedPages.slice(1)) frames.push(pageFrame(page)); pages.replaceChildren(...frames); + cachedPreviewStatus.textContent = "上次成功预览"; cachedPreviewStatus.hidden = false; } catch { // Cache errors do not interrupt the live compile. @@ -228,6 +232,39 @@ async function showCachedPreview() { } } +async function showOpeningPreview() { + const request = new AbortController(); + openingPreviewRequest = request; + const canDisplay = () => !request.signal.aborted && !composing && edits.size === 0 + && visibleRevision === null && pages.childElementCount === 0; + let frame; + try { + const response = await fetch(projectPrefix + "/opening-preview", { signal: request.signal }); + if (!response.ok || !canDisplay()) return; + const page = await response.json(); + if (!canDisplay() || page?.index !== 0 || typeof page.svg !== "string") return; + frame = pageFrame(page); + await frame.querySelector("img").decode(); + if (!canDisplay()) return; + openingPreviewFrame = frame; + pages.append(frame); + cachedPreviewStatus.textContent = "初次排版预览"; + cachedPreviewStatus.hidden = false; + await new Promise(requestAnimationFrame); + await new Promise(requestAnimationFrame); + if (frame.isConnected && visibleRevision === null) { + window.dispatchEvent(new CustomEvent("texrra-opening-preview-painted", { + detail: { visibleMs: performance.now() - openingStarted }, + })); + } + } catch { + // The completed preview still follows the normal compilation path. + } finally { + if (openingPreviewRequest === request) openingPreviewRequest = undefined; + if (frame) revokeDetached([frame]); + } +} + function requestPreviewText(revision) { clearTimeout(textLayerTimer); textLayerRequest?.abort(); @@ -349,7 +386,7 @@ async function requestHttpPreview(payload) { return { status: response.status, body: await response.json() }; } -async function compile(edit, submitted, changes) { +async function compile(edit, submitted, changes, usePrepared) { const replacements = []; let pendingDraft; try { @@ -360,6 +397,7 @@ async function compile(edit, submitted, changes) { visible_revision: visibleRevision, files: changes, preview_draft: previewDraft, + use_prepared: usePrepared, }; const socketReply = requestSocketPreview(payload); let response; @@ -382,7 +420,11 @@ async function compile(edit, submitted, changes) { throw new Error("预览版本与当前页面不一致"); } for (const page of update.pages) replacements.push(pageFrame(page)); - await Promise.all(replacements.map((frame) => frame.querySelector("img").decode())); + // On a blank preview, paint page one as soon as it is decoded. On edits + // keep the existing pages in place until all replacements are ready. + const firstLivePage = pages.childElementCount === 0 || pages.firstElementChild === openingPreviewFrame; + const toDecode = firstLivePage ? replacements.slice(0, 1) : replacements; + await Promise.all(toDecode.map((frame) => frame.querySelector("img").decode())); if (edit !== sequence) { revokeDetached(replacements); return; @@ -416,12 +458,15 @@ async function compile(edit, submitted, changes) { reusedSuffixSteps: result.reused_suffix_steps, discardedSuffixAttemptSteps: result.discarded_suffix_attempt_steps, executedSteps: result.executed_steps, + reusedPrepared: result.reused_prepared === true, reusedFrontier: result.reused_frontier, replayedCalls: result.replayed_calls, pendingPublication: result.pending_publication === true, deferredStateFingerprint: result.deferred_state_fingerprint === true, }; + const visibleStatus = sample.count + " 页 · " + Math.round(sample.visibleMs) + " 毫秒"; if (edit === sequence) { + status.textContent = pendingDraft ? visibleStatus + " · 正在生成 PDF" : visibleStatus; window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample })); } if (pendingDraft) { @@ -437,9 +482,7 @@ async function compile(edit, submitted, changes) { }, })); } - if (edit === sequence) { - status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`; - } + if (pendingDraft && edit === sequence) status.textContent = visibleStatus; } catch (failure) { revokeDetached(replacements); if (edit === sequence) { @@ -456,7 +499,7 @@ function invalidatePreview() { promptCompilePending = false; } -function queueCompile(immediate = false) { +function queueCompile(immediate = false, usePrepared = false) { if (preparingProject) return; const submitted = performance.now(); // Edits arriving before the first dispatch share its prompt submission. @@ -470,12 +513,13 @@ function queueCompile(immediate = false) { if (edit !== sequence || composing) return; compileTimer = undefined; promptCompilePending = false; - compile(edit, submitted, Object.fromEntries(edits)); + compile(edit, submitted, Object.fromEntries(edits), usePrepared); }, prompt ? 0 : EDIT_IDLE_MS); } function manualCompile() { if (recompile.disabled || composing) return; + openingPreviewRequest?.abort(); recordEdit(true); } @@ -596,7 +640,7 @@ async function finishProjectOpening(project) { save.disabled = false; recompile.disabled = false; advertisePreviewSocket(project.preview_socket); - queueCompile(true); + queueCompile(true, true); } async function switchCompileMode() { @@ -620,6 +664,13 @@ async function switchCompileMode() { // full update. Old revision identifiers belong to the previous session. restorePublishedPages(); cachedPreviewRequest?.abort(); + openingPreviewRequest?.abort(); + if (openingPreviewFrame) { + openingPreviewFrame.remove(); + revokeDetached([openingPreviewFrame]); + openingPreviewFrame = undefined; + } + cachedPreviewStatus.textContent = "上次成功预览"; clearTimeout(textLayerTimer); textLayerRequest?.abort(); textLayerRevision = undefined; @@ -739,6 +790,7 @@ async function openProject() { indentSource(); }); if (project.cached_preview === true) void showCachedPreview(); + else if (project.preparing === true && previewDraft) void showOpeningPreview(); await finishProjectOpening(project); } catch (failure) { showError(failure.message); diff --git a/examples/native_editor/library.rs b/examples/native_editor/library.rs index 8f70e9a..cfe26a5 100644 --- a/examples/native_editor/library.rs +++ b/examples/native_editor/library.rs @@ -25,8 +25,8 @@ pub(super) struct EditorFormat { } struct FormatPreparation { - lock: Mutex<()>, - build: Box Result<(), String> + Send + Sync>, + ready: Mutex, + prepare: Box Result<(), String> + Send + Sync>, } impl EditorFormat { @@ -41,23 +41,36 @@ impl EditorFormat { profile: InputProfile, build: impl Fn() -> Result<(), String> + Send + Sync + 'static, ) -> Self { - Self { - image, - manifest, - profile, - compiler: NativeCompiler::default(), - preparation: Some(Arc::new(FormatPreparation { - lock: Mutex::new(()), - build: Box::new(build), - })), - } + let output = image.clone(); + Self::prepare_on_open(image, manifest, profile, move || { + if !output.is_file() { + build()?; + } + Ok(()) + }) + } + + #[cfg(windows)] + pub(super) fn prepare_on_open( + image: PathBuf, + manifest: PathBuf, + profile: InputProfile, + prepare: impl Fn() -> Result<(), String> + Send + Sync + 'static, + ) -> Self { + let mut format = Self::prepared(image, manifest, profile); + format.preparation = Some(Arc::new(FormatPreparation { + ready: Mutex::new(false), + prepare: Box::new(prepare), + })); + format } pub(super) fn ensure(&self) -> Result<(), String> { if let Some(preparation) = &self.preparation { - let _lock = preparation.lock.lock().unwrap(); - if !self.image.is_file() { - (preparation.build)()?; + let mut ready = preparation.ready.lock().unwrap(); + if !*ready || !self.image.is_file() { + (preparation.prepare)()?; + *ready = true; } } Ok(()) @@ -100,10 +113,10 @@ impl Library { } pub(super) fn prewarm_format(&self) { - // Decode ready formats in the background. A first launch can show - // the library while the selected project's missing format is built. + // Decode caller-supplied formats in the background. Windows bundles + // defer verification and decoding until a project selects a profile. for format in std::iter::once(&self.primary).chain(self.unicode.iter()) { - if !format.image.is_file() { + if format.preparation.is_some() || !format.image.is_file() { continue; } let compiler = format.compiler.clone(); diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 3fb3904..3bfa10d 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -16,13 +16,14 @@ use std::{ }; use texrra_engine::native::{ CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, + CompiledDocument, DraftPreview, Entry, EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot, job_time, }; use texrra_tex_core::{ execution::InputProfile, - resources::{FileModificationTime, InputPolicy, ResourceKind, SearchPath, WorldConfig}, + resources::{FileModificationTime, FileWorld, InputPolicy, ResourceKind, SearchPath, WorldConfig}, }; use thread_usage::ThreadUsage; use tiny_http::{Header, Method, Request, Response, Server}; @@ -55,6 +56,8 @@ struct Edit { files: BTreeMap>, #[serde(default)] preview_draft: bool, + #[serde(default)] + use_prepared: bool, } #[derive(Deserialize)] @@ -98,15 +101,22 @@ impl PreviewReply { struct Work { cache: Option, respond_to: PreviewReply, - job: CompileJob, - bibliography_pass: Option, - compile: CompileRequest, + input: PreviewInput, sequence: u64, visible_revision: Option, received: Instant, preview_draft: bool, } +enum PreviewInput { + Compile { + job: CompileJob, + bibliography_pass: Option, + request: CompileRequest, + }, + Prepared(Arc), +} + #[derive(Clone, Copy, Default)] struct StageTiming { wall_ms: f64, @@ -287,6 +297,10 @@ fn main() -> Result<(), Box> { } let mut args = std::env::args_os().skip(1).peekable(); #[cfg(windows)] + if args.next_if(|arg| arg == "--prepare-windows-formats").is_some() { + return windows_format::prepare_bundle(args); + } + #[cfg(windows)] if args.next_if(|arg| arg == "--windows-desktop").is_some() { return windows_format::run(args).map_err(|error| { let detail = error.to_string().replace(['\r', '\n'], " "); @@ -364,7 +378,7 @@ fn main() -> Result<(), Box> { root, &source, &format, &manifest, &run, &additional, input_profile, )?; let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); - let editor = finish_prepare(staged, &run, &compiler, None, None)?; + let editor = finish_prepare(staged, &run, &compiler, None, None, None)?; (port, Some(EditorSession::new(run, editor, compiler, None))) }; serve(web, library, port, session) @@ -528,6 +542,20 @@ fn serve( }); continue; } + ("opening-preview", Some(opening)) => { + let preview = opening.preview.clone(); + std::thread::spawn(move || reply_opening_preview(request, preview.wait().as_deref())); + continue; + } + ("opening-preview", None) if project_open => { + let session = session.as_ref().unwrap().lock().unwrap(); + let document = session.compiler.latest().filter(|document| { + session.queue.current.load(Ordering::Acquire) == 1 + && document.revision() < session.first_preview_revision + }); + std::thread::spawn(move || reply_opening_preview(request, document.as_deref())); + continue; + } ("ready", Some(opening)) => { let ready = opening.ready.clone(); std::thread::spawn(move || match ready.wait() { @@ -773,12 +801,21 @@ fn read_port(value: Option) -> Result { } type ReadyEditor = Result>, String>; +type OpeningPreview = OnceLock>>; + +fn reply_opening_preview(request: Request, document: Option<&CompiledDocument>) { + match document.and_then(|document| document.first_preview_page().ok().flatten()) { + Some(page) => reply(request, 200, json!(page)), + None => reply(request, 404, json!({ "error": "No initial preview" })), + } +} struct OpeningEditor { id: String, cache: Option, sources: Value, ready: Arc>, + preview: Arc, compiler: NativeCompiler, superseded: Arc, } @@ -813,11 +850,13 @@ impl OpeningEditor { cache, sources, ready: Arc::new(OnceLock::new()), + preview: Arc::new(OnceLock::new()), compiler, superseded: Arc::new(AtomicBool::new(false)), }; let id = opening.id.clone(); let ready = opening.ready.clone(); + let preview = opening.preview.clone(); let compiler = opening.compiler.clone(); let superseded = opening.superseded.clone(); let cache = opening.cache.clone(); @@ -830,13 +869,16 @@ impl OpeningEditor { let cache = cache.or_else(|| { cacheable.then(|| initial_preview_cache(&id, &run, &staged, &format)).flatten() }); - let editor = finish_prepare(staged, &run, &compiler, Some(&superseded), Some(&id)) - .map_err(|error| error.to_string())?; + let editor = finish_prepare( + staged, &run, &compiler, Some(&superseded), Some(&id), Some(&preview), + ).map_err(|error| error.to_string())?; let mut session = EditorSession::new(run, editor, compiler, cache); session.id = Some(id); session.mode_choice = mode_choice; Ok(Arc::new(Mutex::new(session))) })(); + // Wake a provisional preview request even if preparation failed. + preview.get_or_init(|| None); let _ = ready.set(result); })?; Ok(opening) @@ -895,6 +937,7 @@ struct EditorSession { run: PathBuf, compiler: NativeCompiler, first_preview_revision: u64, + prepared_preview: Option>, bibliography_compiler: Option, queue: Arc, save_number: u64, @@ -904,12 +947,12 @@ struct EditorSession { impl EditorSession { fn new( run: PathBuf, - editor: EditorProject, + mut editor: EditorProject, compiler: NativeCompiler, cache: Option, ) -> Self { - // Resource discovery warms the compiler's caches. Only preview jobs - // may expose a revision to the editor. + let prepared_preview = editor.prepared_preview.take(); + // The seed remains private until an unchanged opening request adopts it. let first_preview_revision = compiler.latest().map_or(1, |document| document.revision() + 1); let queue = Arc::new(Queue { current: AtomicU64::new(editor.project.version().revision), @@ -934,6 +977,7 @@ impl EditorSession { run, compiler, first_preview_revision, + prepared_preview, bibliography_compiler, queue, save_number: 0, @@ -980,23 +1024,31 @@ impl EditorSession { } project.with_file_changes(edit.sequence, updates) }); - *project = match next { + let next = match next { Ok(project) => project, Err(error) => { respond_to.send(422, json!({ "error": error })); return; } }; - let compile = options.clone().with_project(project.clone()); - let job = self.compiler.start(); - let bibliography_pass = self.bibliography_compiler.as_ref().map(NativeCompiler::start); + let unchanged = project.version().sha256 == next.version().sha256; + *project = next; + let input = match self.prepared_preview.take().filter(|_| edit.use_prepared && unchanged) { + Some(document) => { + self.first_preview_revision = document.revision(); + PreviewInput::Prepared(document) + } + None => PreviewInput::Compile { + job: self.compiler.start(), + bibliography_pass: self.bibliography_compiler.as_ref().map(NativeCompiler::start), + request: options.clone().with_project(project.clone()), + }, + }; self.queue.current.store(edit.sequence, Ordering::Release); let replaced = self.queue.next.lock().unwrap().replace(Work { cache: self.cache.as_ref().filter(|cache| cache.matches_saved_sources(project)).cloned(), respond_to, - job, - bibliography_pass, - compile, + input, sequence: edit.sequence, visible_revision: edit.visible_revision, received, @@ -1045,6 +1097,7 @@ struct EditorProject { declared: BTreeSet, options: CompileRequest, bibliography: Option, + prepared_preview: Option>, } fn copy_with_date( @@ -1201,6 +1254,7 @@ fn finish_prepare( compiler: &NativeCompiler, superseded: Option<&AtomicBool>, project_id: Option<&str>, + preview: Option<&OpeningPreview>, ) -> Result> { let StagedProject { world, @@ -1263,6 +1317,11 @@ fn finish_prepare( Ok(result) }; let mut seed = compile_seed(1)?; + check_current()?; + if let Some(preview) = preview { + let document = seed.as_ref().ok().filter(|document| !document.pages.is_empty()); + let _ = preview.set(document.cloned()); + } let mut bibliography = None; if let Ok(initial) = &seed { let cached_bbl = project_id @@ -1366,6 +1425,7 @@ fn finish_prepare( generated_roots: BTreeSet::from([run.to_owned()]), generated, }, dates)?; + let prepared_preview = seed.ok().filter(|document| stable_opening_seed(document, &project)); Ok(EditorProject { project, entry, @@ -1373,6 +1433,60 @@ fn finish_prepare( declared, options: request, bibliography, + prepared_preview, + }) +} + +// A second run may see an AUX file that the seed just created or updated. +// Keep that settling pass, along with the atomic editor's input restrictions. +fn stable_opening_seed(document: &CompiledDocument, project: &Arc) -> bool { + let resources = &document.resources; + let trace = &resources.trace; + let Some(initial) = &resources.generated_initial else { return false }; + if resources.generated_artifacts.writes.iter().any(|write| write.before != write.after) + || document.inputs.configuration() != project.configuration() + || !document.inputs.replay_gaps().is_empty() + || !trace.read_errors.is_empty() + || !trace.namespace_capture_failures.is_empty() + || !trace.directory_absences.is_empty() + { + return false; + } + let version = |path: &Path| { + project.file(path).map(|file| &file.version) + .or_else(|| initial.files().get(path).and_then(Option::as_ref)) + }; + if trace.reads.iter().any(|read| version(&read.path) != Some(read)) + || trace.stream_reads.iter().any(|read| { + if let Some(file) = project.file(&read.path) { + document.inputs.file(&read.path).is_none_or(|seen| seen.version != file.version) + } else { + version(&read.path).is_none() + } + }) + || trace.file_modifications.iter().any(|observation| { + !observation.result.as_ref().is_ok_and(|date| { + project.modification_time(&observation.path) == date.as_ref().map(|date| date.time) + }) + }) + { + return false; + } + let Ok(mut world) = FileWorld::from_project(project.clone()) else { return false }; + for path in initial.files().keys() { + if world.mark_generated_initial(path).is_err() { + return false; + } + } + // A trace does not distinguish the TeX input scanner from raw file + // queries. Require both suffix policies to agree for a TeX lookup. + trace.lookups.iter().all(|lookup| { + lookup.error.is_none() + && world.resolve(lookup.kind, &lookup.name, &lookup.from) + .is_ok_and(|resolved| resolved == lookup.resolved) + && (lookup.kind != ResourceKind::Tex + || world.resolve_tex_input(&lookup.name, &lookup.from) + .is_ok_and(|resolved| resolved == lookup.resolved)) }) } @@ -1393,9 +1507,7 @@ fn worker( let Some(Work { cache, respond_to, - job, - bibliography_pass, - mut compile, + input, sequence, visible_revision, received, @@ -1416,45 +1528,52 @@ fn worker( received, preview_draft, }); - let revision = job.revision(); - let mut project = compile - .project - .clone() - .expect("the editor submits a project snapshot"); - project = resources - .apply(&project) - .expect("captured resources retain their original roots"); - let settle = (|| { - if let Some((path, settled)) = &mut settled_bibliography - && let Some(current) = project.file(path).map(|file| file.data.clone()) - && !Arc::ptr_eq(settled, ¤t) - && settled.as_ref() != current.as_ref() - && let Some(pass) = bibliography_pass - { - // The new BBL writes the updated labels at the end of a pass. - // A private compiler settles those AUX files before the editor - // exposes any draft or PDF for this revision. - pass.compile_expanding_project(compile.clone().with_project(project.clone()), |failure| { - if !observer.is_current() { - return None; + let reused_prepared = matches!(&input, PreviewInput::Prepared(_)); + let (revision, result) = match input { + PreviewInput::Prepared(document) => (document.revision(), Ok(document)), + PreviewInput::Compile { job, bibliography_pass, mut request } => { + let revision = job.revision(); + let mut project = request + .project + .clone() + .expect("the editor submits a project snapshot"); + project = resources + .apply(&project) + .expect("captured resources retain their original roots"); + let settle = (|| { + if let Some((path, settled)) = &mut settled_bibliography + && let Some(current) = project.file(path).map(|file| file.data.clone()) + && !Arc::ptr_eq(settled, ¤t) + && settled.as_ref() != current.as_ref() + && let Some(pass) = bibliography_pass + { + // The new BBL writes the updated labels at the end of a pass. + // A private compiler settles those AUX files before the editor + // exposes any draft or PDF for this revision. + pass.compile_expanding_project(request.clone().with_project(project.clone()), |failure| { + if !observer.is_current() { + return None; + } + project = resources.expand(&project, failure)?; + Some(project.clone()) + }).map_err(|failure| failure.error)?; + *settled = current; } - project = resources.expand(&project, failure)?; - Some(project.clone()) - }).map_err(|failure| failure.error)?; - *settled = current; + Ok(()) + })(); + request.observer = Some(observer.clone()); + let result = settle.and_then(|()| { + job.compile_expanding_project(request.with_project(project.clone()), |failure| { + if observer.respond_to.lock().unwrap().is_none() || !observer.is_current() { + return None; + } + project = resources.expand(&project, failure)?; + Some(project.clone()) + }).map_err(|failure| failure.error) + }); + (revision, result) } - Ok(()) - })(); - compile.observer = Some(observer.clone()); - let result = settle.and_then(|()| { - job.compile_expanding_project(compile.with_project(project.clone()), |failure| { - if observer.respond_to.lock().unwrap().is_none() || !observer.is_current() { - return None; - } - project = resources.expand(&project, failure)?; - Some(project.clone()) - }).map_err(|failure| failure.error) - }); + }; let compile_ms = observer.elapsed_ms(); let respond_to = observer.respond_to.lock().unwrap().take(); let Some(respond_to) = respond_to else { @@ -1498,15 +1617,14 @@ fn worker( } match preview { Ok(update) => { - respond_to.send( - 200, - observer.preview_payload( - update, - document.execution.execution.steps, - &document.entry_checkpoint_work, - Some(compile_ms), - ), - ); + let steps = document.execution.execution.steps; + let adoption = EntryCheckpointWork { reused_steps: steps, ..EntryCheckpointWork::default() }; + let work = if reused_prepared { &adoption } else { &document.entry_checkpoint_work }; + let mut payload = observer.preview_payload(update, steps, work, Some(compile_ms)); + if reused_prepared { + payload["reused_prepared"] = Value::Bool(true); + } + respond_to.send(200, payload); if let Some(cache) = cache { cache.refresh(document); } @@ -1534,3 +1652,105 @@ fn respond(request: Request, status: u16, content_type: &str, bytes: Vec) { eprintln!("Editor response: {error}"); } } + + +#[cfg(test)] +mod opening_tests { + use super::*; + use std::time::Duration; + use texrra_tex_core::execution::JobTime; + + const HEADER: &str = r"\catcode123=1 \catcode125=2 \pdfoutput=1 "; + const RULE: &str = r"\shipout\vbox{\hrule width12pt height20pt depth0pt}\end"; + + fn prepare( + label: &str, + before_page: &str, + ) -> (PathBuf, EditorProject, NativeCompiler, OpeningPreview) { + let run = std::env::temp_dir().join(format!("texrra-editor-opening-{}-{label}", std::process::id())); + fs::create_dir(&run).unwrap(); + let run = run.canonicalize().unwrap(); + let entry = run.join("main.tex"); + let source = format!("{HEADER}{before_page}{RULE}\n"); + fs::write(&entry, &source).unwrap(); + let mut world = WorldConfig::new(&run); + world.input_policy = InputPolicy::Tex; + let mut options = CompileRequest::new( + world.clone(), &entry, run.join("job.pdf"), + JobTime::new(2026, 11, 12, 0).unwrap().with_pdf_clock(0, 0).unwrap(), + ).observe_generated_initial(); + options.entry = Entry::Initex; + options.etex = true; + let staged = StagedProject { + world, + entry: entry.clone(), + editable: BTreeMap::from([("main.tex".into(), entry.clone())]), + declared: BTreeSet::from([entry.clone()]), + files: BTreeMap::from([(entry, Arc::from(source.into_bytes()))]), + directories: BTreeSet::from([run.clone()]), + dates: BTreeMap::new(), + options, + }; + let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); + let provisional = OpeningPreview::new(); + let editor = finish_prepare(staged, &run, &compiler, None, None, Some(&provisional)).unwrap(); + (run, editor, compiler, provisional) + } + + fn submit( + session: &mut EditorSession, + source: Option, + ) -> Value { + let (send, receive) = mpsc::channel(); + session.submit_edit(Edit { + sequence: 2, visible_revision: None, source, files: BTreeMap::new(), + preview_draft: false, use_prepared: true, + }, Instant::now(), PreviewReply::Socket(send)); + let (status, body) = receive.recv_timeout(Duration::from_secs(10)).unwrap(); + assert_eq!(status, 200, "{body}"); + body + } + + #[test] + fn unchanged_opening_can_adopt_stable_render_and_keep_revision() { + let (run, editor, compiler, provisional) = prepare("stable", ""); + let seed = editor.prepared_preview.as_ref().unwrap().clone(); + let full = NativeCompiler::default().compile(editor.options.clone().with_project(editor.project.clone())).unwrap(); + assert_eq!(seed.pdf, full.pdf); + assert_eq!(seed.source_map, full.source_map); + assert_eq!(provisional.get().unwrap().as_ref().unwrap().first_preview_page().unwrap(), + full.preview_since(None).unwrap().pages.first().cloned()); + let mut session = EditorSession::new(run, editor, compiler, None); + let response = submit(&mut session, None); + assert_eq!(response["reused_prepared"], true); + assert_eq!(response["executed_steps"], 0); + assert_eq!(response["update"]["revision"], seed.revision()); + assert_eq!(session.first_preview_revision, seed.revision()); + } + + #[test] + fn changing_generated_input_keeps_settling_pass() { + let (run, editor, compiler, provisional) = prepare( + "changed-aux", "\\immediate\\openout0=cross.aux\n\\immediate\\write0{Initial}\n\\immediate\\closeout0\n", + ); + assert!(editor.prepared_preview.is_none()); + assert!(provisional.get().unwrap().is_some()); + let mut session = EditorSession::new(run, editor, compiler, None); + let response = submit(&mut session, None); + assert!(response.get("reused_prepared").is_none()); + assert_eq!(response["update"]["revision"], 2); + } + + #[test] + fn edit_queued_during_opening_compiles_current_source() { + let (run, editor, compiler, _) = prepare("edited", ""); + let seed = editor.prepared_preview.as_ref().unwrap(); + let old_pdf = seed.pdf.clone(); + let mut session = EditorSession::new(run, editor, compiler, None); + let source = format!("{HEADER}{}\n", RULE.replace("12pt", "32pt")); + let response = submit(&mut session, Some(source)); + assert!(response.get("reused_prepared").is_none()); + assert_eq!(response["update"]["revision"], 2); + assert_ne!(session.compiler.latest().unwrap().pdf, old_pdf); + } +} diff --git a/examples/native_editor/windows_format.rs b/examples/native_editor/windows_format.rs index c092526..c7e6ff1 100644 --- a/examples/native_editor/windows_format.rs +++ b/examples/native_editor/windows_format.rs @@ -1,8 +1,13 @@ //! Bootstrap the installed Windows editor from the packaged TeX resources. -use crate::{WebAssets, library::{EditorFormat, Library}, serve}; +use crate::{ + WebAssets, + library::{EditorFormat, Library}, + serve, +}; use serde::Deserialize; use sha2::{Digest, Sha256}; use std::{ + collections::BTreeMap, env, ffi::{OsStr, OsString}, fs::{self, File, OpenOptions}, @@ -10,7 +15,7 @@ use std::{ path::{Path, PathBuf}, time::Instant, }; -use texrra_engine::native::{CompileRequest, Entry, dump_format, job_time}; +use texrra_engine::native::{CompileRequest, Entry, dump_bundled_format, dump_format, job_time}; use texrra_tex_core::{ execution::{Cancellation, InputProfile}, resources::WorldConfig, @@ -22,6 +27,41 @@ type LaunchResult = Result>; struct Bundle { schema: u32, resources_sha256: String, + #[serde(default)] + sha256: BTreeMap, +} + +const MODES: [(InputProfile, &str); 2] = [ + (InputProfile::TeX8Bit, "pdflatex"), + (InputProfile::XeTeX, "xelatex"), +]; + +pub(super) fn prepare_bundle(mut arguments: impl Iterator) -> LaunchResult<()> { + let usage = "native_editor --prepare-windows-formats BACKEND_DIRECTORY"; + let backend = PathBuf::from(arguments.next().ok_or(usage)?); + if arguments.next().is_some() || !backend.is_absolute() { + return Err(usage.into()); + } + let backend = backend.canonicalize()?; + let (roots, font_maps) = bundle_resources(&backend)?; + let formats = backend.join("formats"); + fs::create_dir(&formats)?; + configure_environment(&backend, &formats, &font_maps)?; + for (profile, name) in MODES { + let directory = formats.join(name); + fs::create_dir(&directory)?; + let format = directory.join("latex.tfx"); + let started = Instant::now(); + build_format( + &initialization_source(&roots, name)?, + &format, + &roots, + profile, + Some(&backend), + )?; + println!("Prepared {name} in {:.2}s", started.elapsed().as_secs_f64()); + } + Ok(()) } pub(super) fn run(mut arguments: impl Iterator) -> LaunchResult<()> { @@ -41,13 +81,7 @@ pub(super) fn run(mut arguments: impl Iterator) -> LaunchResult let receipt = fs::read(backend.join("windows-bundle.json"))?; let bundle: Bundle = serde_json::from_slice(&receipt)?; - if bundle.schema != 1 - || bundle.resources_sha256.len() != 64 - || !bundle - .resources_sha256 - .bytes() - .all(|byte| byte.is_ascii_hexdigit()) - { + if bundle.schema != 1 || !valid_digest(&bundle.resources_sha256) { return Err("Invalid Windows desktop bundle receipt".into()); } let mut key = Sha256::new(); @@ -58,20 +92,7 @@ pub(super) fn run(mut arguments: impl Iterator) -> LaunchResult fs::create_dir_all(&runtime)?; let runtime = runtime.canonicalize()?; - let texmf = backend.join("texmf"); - let roots = ["overlay", "dist", "var"] - .map(|directory| texmf.join(directory).canonicalize()) - .into_iter() - .collect::>>()?; - let font_maps = texmf.join("fonts").canonicalize()?; - if roots - .iter() - .chain([&font_maps]) - .any(|root| !root.is_dir() || !root.starts_with(&backend)) - || !font_maps.join("pdftex.map").is_file() - { - return Err("The Windows desktop TeX resources are incomplete".into()); - } + let (roots, font_maps) = bundle_resources(&backend)?; let state = home.join("state"); fs::create_dir_all(&state)?; configure_environment(&backend, &state, &font_maps)?; @@ -83,13 +104,39 @@ pub(super) fn run(mut arguments: impl Iterator) -> LaunchResult fs::write(&manifest, manifest_bytes)?; } let manifest = manifest.canonicalize()?; - let primary = desktop_format(&runtime, &manifest, &roots, InputProfile::TeX8Bit, "pdflatex")?; - let unicode = desktop_format(&runtime, &manifest, &roots, InputProfile::XeTeX, "xelatex")?; + let [primary, unicode] = MODES.map(|(profile, name)| { + desktop_format( + &backend, &bundle, &runtime, &manifest, &roots, profile, name, + ) + }); let web = WebAssets::load(&backend.join("web"))?; - let library = Library::new(home.join("projects"), runtime.join("web-runs"), primary, Some(unicode))?; + let library = Library::new( + home.join("projects"), + runtime.join("web-runs"), + primary?, + Some(unicode?), + )?; serve(Some(web), Some(library), 0, None) } +fn bundle_resources(backend: &Path) -> LaunchResult<(Vec, PathBuf)> { + let texmf = backend.join("texmf"); + let roots = ["overlay", "dist", "var"] + .map(|directory| texmf.join(directory).canonicalize()) + .into_iter() + .collect::>>()?; + let font_maps = texmf.join("fonts").canonicalize()?; + if roots + .iter() + .chain([&font_maps]) + .any(|root| !root.is_dir() || !root.starts_with(backend)) + || !font_maps.join("pdftex.map").is_file() + { + return Err("The Windows desktop TeX resources are incomplete".into()); + } + Ok((roots, font_maps)) +} + fn lock_backend(home: &Path) -> io::Result { let file = OpenOptions::new() .read(true) @@ -160,34 +207,102 @@ fn start_lease() -> io::Result<()> { Ok(()) } +fn valid_digest(digest: &str) -> bool { + digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn verify_bundled_input(backend: &Path, input: &Path, expected: &str) -> LaunchResult<()> { + let canonical = input.canonicalize()?; + if canonical != input || !canonical.starts_with(backend) { + return Err(format!("Invalid bundled format path: {}", input.display()).into()); + } + let mut file = File::open(canonical)?; + let mut digest = Sha256::new(); + io::copy(&mut file, &mut digest)?; + if !format!("{:x}", digest.finalize()).eq_ignore_ascii_case(expected) { + return Err(format!("Bundled format checksum differs: {}", input.display()).into()); + } + Ok(()) +} + +fn initialization_source(roots: &[PathBuf], name: &str) -> io::Result { + roots[1] + .join("tex/latex/tex-ini-files") + .join(format!("{name}.ini")) + .canonicalize() +} + fn desktop_format( + backend: &Path, + bundle: &Bundle, runtime: &Path, manifest: &Path, roots: &[PathBuf], profile: InputProfile, name: &'static str, ) -> LaunchResult { - let ini = roots[1].join("tex/latex/tex-ini-files").join(format!("{name}.ini")).canonicalize()?; + let format_key = format!("formats/{name}/latex.tfx"); + let aux_key = format!("formats/{name}/texsys.aux"); + match (bundle.sha256.get(&format_key), bundle.sha256.get(&aux_key)) { + (Some(format_sha), Some(aux_sha)) if valid_digest(format_sha) && valid_digest(aux_sha) => { + let format = backend.join("formats").join(name).join("latex.tfx"); + let aux = format.with_file_name("texsys.aux"); + let image = format.clone(); + let backend = backend.to_owned(); + let format_sha = format_sha.clone(); + let aux_sha = aux_sha.clone(); + return Ok(EditorFormat::prepare_on_open( + image, + manifest.to_owned(), + profile, + move || { + verify_bundled_input(&backend, &aux, &aux_sha) + .and_then(|()| verify_bundled_input(&backend, &format, &format_sha)) + .map_err(|error| format!("Bundled {name} format: {error}")) + }, + )); + } + (None, None) => {} + _ => return Err(format!("Invalid bundled {name} format receipt").into()), + } + + // Earlier bundles supplied the initialization sources only. + let ini = initialization_source(roots, name)?; let directory = runtime.join(name); fs::create_dir_all(&directory)?; let output = directory.canonicalize()?.join("latex.tfx"); let roots = roots.to_vec(); - Ok(EditorFormat::lazy(output.clone(), manifest.to_owned(), profile, move || { - let started = Instant::now(); - let result = build_format(&ini, &output, &roots, profile).map_err(|error| error.to_string()); - if env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE").is_some_and(|value| value == "1") { - eprintln!("Texrra editor preparation {}", serde_json::json!({ - "stage": "build-format", - "mode": name, - "ms": started.elapsed().as_secs_f64() * 1000.0, - "ok": result.is_ok(), - })); - } - result - })) + Ok(EditorFormat::lazy( + output.clone(), + manifest.to_owned(), + profile, + move || { + let started = Instant::now(); + let result = build_format(&ini, &output, &roots, profile, None) + .map_err(|error| error.to_string()); + if env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE").is_some_and(|value| value == "1") { + eprintln!( + "Texrra editor preparation {}", + serde_json::json!({ + "stage": "build-format", + "mode": name, + "ms": started.elapsed().as_secs_f64() * 1000.0, + "ok": result.is_ok(), + }) + ); + } + result + }, + )) } -fn build_format(ini: &Path, format: &Path, roots: &[PathBuf], profile: InputProfile) -> LaunchResult<()> { +fn build_format( + ini: &Path, + format: &Path, + roots: &[PathBuf], + profile: InputProfile, + bundle: Option<&Path>, +) -> LaunchResult<()> { let directory = format.parent().expect("format has a directory"); let world = WorldConfig::from_environment(directory, roots.to_vec())?; let mut request = CompileRequest::new(world, ini, format, job_time()?); @@ -195,6 +310,10 @@ fn build_format(ini: &Path, format: &Path, roots: &[PathBuf], profile: InputProf request.input_profile = profile; request.etex = true; request.limits.steps = 600_000_000; - dump_format(request, Cancellation::default())?; + if let Some(bundle) = bundle { + dump_bundled_format(request, Cancellation::default(), bundle)?; + } else { + dump_format(request, Cancellation::default())?; + } Ok(()) } diff --git a/src/native.rs b/src/native.rs index 6a8cc53..ea941e5 100644 --- a/src/native.rs +++ b/src/native.rs @@ -350,6 +350,10 @@ impl CompiledDocument { || Ok(()), ) } + /// Render page one without rendering the rest of a prepared document. + pub fn first_preview_page(&self) -> Result, String> { + self.preview.first_page(&self.pages, self.pdf.as_ref()) + } pub fn has_show_diagnostic(&self) -> bool { self.execution.execution.events.iter().any(|e| { matches!( @@ -1694,22 +1698,41 @@ pub fn dump_format( ) -> Result { dump_format_detailed(request, cancellation).map_err(|failure| failure.error) } +/// Prepare a versioned release format whose captured inputs move with its bundle. +pub fn dump_bundled_format( + request: CompileRequest, + cancellation: Cancellation, + bundle: &Path, +) -> Result { + dump_format_with_location(request, cancellation, Some(bundle)).map_err(|failure| failure.error) +} + /// A format build has no editor-session revision; revision zero identifies the /// offline attempt. Its source versions and host effects are still actual. pub fn dump_format_detailed( request: CompileRequest, cancellation: Cancellation, +) -> Result { + dump_format_with_location(request, cancellation, None) +} + +fn dump_format_with_location( + request: CompileRequest, + cancellation: Cancellation, + bundle: Option<&Path>, ) -> Result { let mut evidence = AttemptEvidence::new(0); let summary = AttemptRequest::from(&request); evidence.phase = AttemptPhase::Preparing; - dump_format_observed(request, cancellation, &mut evidence) + dump_format_observed(request, cancellation, &mut evidence, bundle) .map_err(|error| evidence.failure(error, summary).persist_requested()) } + fn dump_format_observed( request: CompileRequest, cancellation: Cancellation, evidence: &mut AttemptEvidence, + bundle: Option<&Path>, ) -> Result { let PreparedJob { executor, @@ -1755,9 +1778,13 @@ fn dump_format_observed( let trace = files.resource_trace(); // Keep the completed kernel result available if format validation/encoding // fails. This extra offline copy is not part of interactive compilation. - let bytes = FormatImage::from_dump_with_trace(execution.execution.clone(), trace)? - .with_project_location(&output, trace) - .encode()?; + let image = FormatImage::from_dump_with_trace(execution.execution.clone(), trace)?; + let image = if let Some(bundle) = bundle { + image.with_bundle_location(&output, bundle)? + } else { + image.with_project_location(&output, trace) + }; + let bytes = image.encode()?; evidence.phase = AttemptPhase::Finishing; let finished = files.finish(); let reported = report(&files, &request); diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index afd6341..329703e 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -245,11 +245,21 @@ impl CaptureSchedule { } } - fn with_preamble_anchor(mut self, source: &[u8]) -> Self { - if self.fixed_frontier.is_none() && self.stride >= MIN_PREAMBLE_INTERVAL_BYTES { + fn with_preamble_anchor(mut self, source: &[u8], profile: InputProfile) -> Self { + if self.fixed_frontier.is_some() { + return self; + } + if self.stride >= MIN_PREAMBLE_INTERVAL_BYTES { // The first grid interval can span both package loading and // LaTeX's generated-input reads. Keep one boundary between them. - self.pending_preamble = preamble_frontier(source, self.stride); + self.pending_preamble = document_start_line(source, self.stride) + .and_then(|(start, _)| (start > 0).then_some(start)); + } else if profile == InputProfile::XeTeX { + // On a short source, package loading and the next line can + // occupy the same grid interval. Keep the first continuation + // with the begin-document line loaded and the body still unread. + self.pending_preamble = document_start_line(source, MIN_PREAMBLE_INTERVAL_BYTES) + .and_then(|(start, end)| (start > 0 && end < source.len()).then_some(end)); } self } @@ -783,7 +793,7 @@ impl CheckpointCache { Option>, ) { let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None) - .with_preamble_anchor(&source.data); + .with_preamble_anchor(&source.data, request.input_profile); let mut captures = CapturedEntries::new(request, files); let mut recording = RecordingHost::new(files); let mut nested = NestedSchedule::default(); @@ -1127,7 +1137,7 @@ impl SelectedCheckpoint { source.data.len(), None, changed.or(self.set.edit_frontier), - ).with_preamble_anchor(&source.data); + ).with_preamble_anchor(&source.data, request.input_profile); // A comment-only line can be consumed without an observation. // Keep an earlier anchor for this editing boundary. schedule.pending_edit_fallback = @@ -1434,16 +1444,18 @@ fn changed_line_start(previous: &[u8], current: &[u8]) -> Option { ) } -fn preamble_frontier(bytes: &[u8], limit: usize) -> Option { +fn document_start_line(bytes: &[u8], limit: usize) -> Option<(usize, usize)> { let mut start = 0; for line in bytes.split_inclusive(|&byte| matches!(byte, b'\r' | b'\n')) { if start >= limit { break; } + let end = start + line.len(); if line.trim_ascii() == br"\begin{document}" { - return (start > 0).then_some(start); + let crlf = line.ends_with(b"\r") && bytes.get(end) == Some(&b'\n'); + return Some((start, end + usize::from(crlf))); } - start += line.len(); + start = end; } None } @@ -2591,22 +2603,114 @@ fn large_automatic_schedule_keeps_a_preamble_anchor_once() { let mut source = prefix.to_vec(); source.extend_from_slice(b" \\begin{document}\r\n"); source.resize(4 * MIN_PREAMBLE_INTERVAL_BYTES, b'x'); - let mut schedule = CaptureSchedule::new(source.len(), None, None).with_preamble_anchor(&source); + let mut schedule = CaptureSchedule::new(source.len(), None, None).with_preamble_anchor(&source, InputProfile::TeX8Bit); assert!(schedule.select(1, 0).unwrap().early); let anchor = schedule.select(prefix.len(), 0).unwrap(); assert!(anchor.preamble && !anchor.early && !anchor.edit && !anchor.page); assert!(schedule.select(prefix.len(), 0).is_none()); let mut schedule = CaptureSchedule::new(source.len(), None, Some(prefix.len())) - .with_preamble_anchor(&source); + .with_preamble_anchor(&source, InputProfile::TeX8Bit); let combined = schedule.select(prefix.len(), 0).unwrap(); assert!(combined.preamble && combined.early && combined.edit); assert!(schedule.select(prefix.len(), 0).is_none()); assert!(CaptureSchedule::new(source.len(), Some(1), None) - .with_preamble_anchor(&source).pending_preamble.is_none()); + .with_preamble_anchor(&source, InputProfile::TeX8Bit).pending_preamble.is_none()); assert!(CaptureSchedule::new(prefix.len(), None, None) - .with_preamble_anchor(prefix).pending_preamble.is_none()); - assert_eq!(preamble_frontier(prefix, prefix.len()), None); + .with_preamble_anchor(prefix, InputProfile::TeX8Bit).pending_preamble.is_none()); + assert_eq!(document_start_line(prefix, prefix.len()), None); +} + +#[test] +fn short_xetex_schedule_keeps_a_boundary_before_body_bytes() { + for newline in ["\n", "\r\n", "\r"] { + let prefix = format!("\\documentclass{{article}}{newline}\\usepackage[UTF8,scheme=plain,fontset=fandol]{{ctex}}{newline}"); + let begin = format!("{prefix}\\begin{{document}}{newline}"); + let source = format!("{begin}你好,世界。Hello, world.{newline}\\end{{document}}{newline}"); + let bytes = source.as_bytes(); + let mut schedule = CaptureSchedule::new(bytes.len(), None, None) + .with_preamble_anchor(bytes, InputProfile::XeTeX); + assert_eq!((prefix.len() - 1) / schedule.stride, (begin.len() - 1) / schedule.stride); + assert!(schedule.select(prefix.len(), 0).unwrap().early); + let anchor = schedule.select(begin.len(), 0).unwrap(); + assert!(anchor.preamble && !anchor.early && !anchor.edit && !anchor.page); + assert!(schedule.select(begin.len(), 0).is_none()); + } +} + +#[test] +fn short_xetex_body_edit_reuses_the_preamble_and_rejects_a_changed_input() { + let cwd = std::env::temp_dir().join(format!("texrra-xetex-preamble-{}", std::process::id())); + fs::create_dir(&cwd).unwrap(); + let cwd = cwd.canonicalize().unwrap(); + let entry = cwd.join("main.tex"); + let package = cwd.join("preamble.tex"); + let prefix = "\\relax \\input preamble.tex % an input on the same grid interval as the next line\n"; + let begin = format!("{prefix}\\begin{{document}}\n"); + let document = |height| format!("{begin}\\shipout\\hbox{{\\vrule width\\rulewidth height{height}pt}}\\end\n"); + let preamble = |width| { + format!( + "\\catcode123=1 \\catcode125=2 \\catcode35=6\n\\def\\begin#1{{\\relax}}\n\\def\\rulewidth{{{width}pt}}\n{}", + "\\advance\\count0by1\n".repeat(64), + ) + }; + let original = document(1); + let mut world = WorldConfig::new(&cwd); + world.input_policy = InputPolicy::Tex; + let project = ProjectSnapshot::new(ProjectDefinition { + configuration: world.clone(), + revision: 1, + roots: BTreeSet::from([cwd.clone()]), + files: BTreeMap::from([ + (entry.clone(), Arc::from(original.as_bytes())), + (package.clone(), Arc::from(preamble(10).into_bytes())), + ]), + directories: BTreeSet::new(), + aliases: BTreeMap::new(), + generated_roots: BTreeSet::from([cwd.clone()]), + generated: BTreeSet::new(), + }) + .unwrap(); + let mut request = CompileRequest::new( + world, + "main.tex", + "main.pdf", + JobTime::new(2026, 11, 18, 1000).unwrap().with_pdf_clock(0, 0).unwrap(), + ).with_project(project.clone()).observe_generated_initial(); + request.entry = Entry::Initex; + request.input_profile = InputProfile::XeTeX; + + let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); + let before = compiler.compile(request.clone()).unwrap(); + let mut project = project; + let cases = [ + (entry, Arc::from(document(2).into_bytes()), true), + (package, Arc::from(preamble(15).into_bytes()), false), + ]; + let mut last = before; + for (index, (path, contents, anchored)) in cases.into_iter().enumerate() { + project = project.with_file_edits(index as u64 + 2, BTreeMap::from([(path, contents)])).unwrap(); + let request = request.clone().with_project(project.clone()); + let actual = compiler.compile(request.clone()).unwrap(); + let full = NativeCompiler::default().compile(request).unwrap(); + let work = &actual.entry_checkpoint_work; + if anchored { + assert_eq!(work.reused_frontier, Some(begin.len()), "{work:?}"); + assert!(work.reused_steps >= 64 && work.replayed_calls > 0, "{work:?}"); + } else { + assert!(work.reused_frontier.is_none_or(|frontier| frontier < begin.len()), "{work:?}"); + assert!(work.reused_steps < 64, "{work:?}"); + } + assert_ne!(last.pdf, actual.pdf); + assert_eq!(actual.pdf, full.pdf); + assert_eq!(actual.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + assert_eq!(actual.source_map.pages, full.source_map.pages); + assert_eq!(actual.source_map.sources, full.source_map.sources); + assert_eq!(actual.execution.execution, full.execution.execution); + assert_eq!(actual.resources.trace.lookups, full.resources.trace.lookups); + last = actual; + } + fs::remove_dir_all(cwd).unwrap(); } #[test] diff --git a/src/native_host.rs b/src/native_host.rs index e333f7a..aaf75fc 100644 --- a/src/native_host.rs +++ b/src/native_host.rs @@ -186,13 +186,60 @@ impl HostPreparation { } return candidates.any(|candidate| self.same_file(candidate, path)); } - #[cfg(not(unix))] + #[cfg(windows)] + { + self.aliases_any_windows(path, candidates) + } + #[cfg(not(any(unix, windows)))] { let mut candidates = candidates; candidates.any(|candidate| self.same_file(candidate, path)) } } + #[cfg(any(windows, test))] + fn aliases_any_windows<'a>( + &mut self, + path: &Path, + mut candidates: impl Iterator + Clone, + ) -> bool { + self.scan_canonical_aliases(path, candidates.clone()) + .unwrap_or_else(|| candidates.any(|candidate| self.same_file(candidate, path))) + } + + #[cfg(any(windows, test))] + fn scan_canonical_aliases<'a>( + &mut self, + path: &Path, + candidates: impl Iterator, + ) -> Option { + let mut candidates = candidates.peekable(); + let Some(first) = candidates.peek().copied() else { return Some(false); }; + if first == path { + return Some(self.record_alias(first, path, true)); + } + let target = self.canonical_alias_target(path).ok()?; + for candidate in candidates { + let same = candidate == path + || (target.is_some() && self.canonical_alias_target(candidate).ok()? == target); + if self.record_alias(candidate, path, same) { + return Some(true); + } + } + // Retry with live pairwise checks if the fixed path changed during + // a negative scan, including when a previously missing file appeared. + (self.canonical_alias_target(path).ok()? == target).then_some(false) + } + + #[cfg(any(windows, test))] + fn canonical_alias_target(&mut self, path: &Path) -> io::Result> { + match self.canonicalize(path) { + Ok(path) => Ok(Some(path)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } + } + /// Compare two outputs with the same protected paths in one live scan. pub(crate) fn either_aliases_any<'a>( &mut self, @@ -338,3 +385,92 @@ impl HostPreparation { result.map(|()| Some(data)) } } + +#[cfg(test)] +mod canonical_alias_tests { + use super::*; + + fn directory(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texrra-canonical-alias-{name}-{}", std::process::id())); + fs::create_dir(&dir).unwrap(); + dir + } + + fn canonicalization_paths(host: &HostPreparation) -> Vec<&Path> { + host.observations.iter().filter_map(|observation| match observation { + HostObservation::Canonicalize { path, .. } => Some(path.as_path()), + _ => None, + }).collect() + } + + #[test] + fn windows_alias_scan_reuses_the_fixed_target_probe() { + let dir = directory("stable"); + let first = dir.join("first"); + let second = dir.join("second"); + let fixed = dir.join("fixed"); + for path in [&first, &second] { + fs::write(path, b"input").unwrap(); + } + + let mut host = HostPreparation::default(); + assert!(!host.aliases_any_windows(&fixed, [first.as_path(), second.as_path()].into_iter())); + assert_eq!(canonicalization_paths(&host), [&fixed, &fixed]); + assert!(matches!(host.observations[1], HostObservation::Alias { same: false, .. })); + assert!(matches!(host.observations[2], HostObservation::Alias { same: false, .. })); + + let mut host = HostPreparation::default(); + assert!(host.aliases_any_windows(&fixed, [fixed.as_path()].into_iter())); + assert!(canonicalization_paths(&host).is_empty()); + + fs::write(&fixed, b"output").unwrap(); + let mut host = HostPreparation::default(); + assert!(!host.aliases_any_windows(&fixed, [first.as_path(), second.as_path()].into_iter())); + assert_eq!(canonicalization_paths(&host), [&fixed, &first, &second, &fixed]); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + #[cfg(unix)] + fn windows_alias_scan_falls_back_when_the_fixed_target_appears_or_a_probe_fails() { + use std::{cell::Cell, os::unix::fs::symlink}; + + let dir = directory("fallback"); + let first = dir.join("first"); + let second = dir.join("second"); + let fixed = dir.join("fixed"); + let loop_path = dir.join("path-loop"); + fs::write(&first, b"first").unwrap(); + fs::write(&second, b"second").unwrap(); + symlink(&loop_path, &loop_path).unwrap(); + + let added = Cell::new(false); + let candidates = [first.as_path(), second.as_path()].into_iter().inspect(|&path| { + if path == second && !added.replace(true) { + symlink(&first, &fixed).unwrap(); + } + }); + let mut host = HostPreparation::default(); + assert!(host.aliases_any_windows(&fixed, candidates)); + assert!(host.observations.iter().any(|observation| matches!(observation, + HostObservation::Alias { left, right, same: false } if left == &first && right == &fixed + ))); + assert!(host.observations.iter().any(|observation| matches!(observation, + HostObservation::Alias { left, right, same: true } if left == &first && right == &fixed + ))); + + let mut host = HostPreparation::default(); + assert!(host.aliases_any_windows(&fixed, [first.as_path()].into_iter())); + assert_eq!(canonicalization_paths(&host), [&fixed, &first]); + + let mut host = HostPreparation::default(); + assert!(host.aliases_any_windows(&fixed, [loop_path.as_path(), first.as_path()].into_iter())); + assert!(host.observations.iter().any(|observation| matches!(observation, + HostObservation::Canonicalize { path, result: Err(_) } if path == &loop_path + ))); + assert!(host.observations.iter().any(|observation| matches!(observation, + HostObservation::Alias { left, right, same: true } if left == &first && right == &fixed + ))); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/native_preview.rs b/src/native_preview.rs index 30d9be5..6763722 100644 --- a/src/native_preview.rs +++ b/src/native_preview.rs @@ -181,6 +181,30 @@ impl PreviewState { } } + fn pdf_context<'a>( + &'a self, + pages: &[DisplayList], + pdf: Option<&'a Arc<[u8]>>, + ) -> PdfPreview<'a> { + PdfPreview { + bytes: pdf, + fonts: &self.fonts, + defaults: pages.iter().any(DisplayList::has_pdf_default_colors), + document: OnceLock::new(), + dependencies: PdfDependencies::default(), + } + } + + pub(crate) fn first_page( + &self, + pages: &[DisplayList], + pdf: Option<&Arc<[u8]>>, + ) -> Result, String> { + let Some(page) = pages.first() else { return Ok(None) }; + let svg = self.render_page(0, page, &mut self.pdf_context(pages, pdf))?.svg.clone(); + Ok(Some(PreviewPage { index: 0, svg })) + } + pub(crate) fn render( &self, revision: u64, @@ -189,13 +213,7 @@ impl PreviewState { visible: Option, check: impl Fn() -> Result<(), String>, ) -> Result { - let mut pdf = PdfPreview { - bytes: pdf, - fonts: &self.fonts, - defaults: pages.iter().any(DisplayList::has_pdf_default_colors), - document: OnceLock::new(), - dependencies: PdfDependencies::default(), - }; + let mut pdf = self.pdf_context(pages, pdf); let mut rendered = Vec::new(); let base_revision = if visible == Some(revision) { visible diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 9303938..55640d5 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -3766,6 +3766,80 @@ fn format_seed_reuse_restarts_execution_and_checks_live_dependencies() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn bundled_format_rebinds_captured_tex_and_stream_data_after_move() { + let root = directory("bundled-format").canonicalize().unwrap(); + let staging = root.join("staging"); + let installed = root.join("installed"); + let project = root.join("project"); + let mode = staging.join("formats/pdflatex"); + let texmf = staging.join("texmf"); + for directory in [&mode, &texmf, &project] { + fs::create_dir_all(directory).unwrap(); + } + let seed = texmf.join("seed.tex"); + fs::write( + &seed, + br"\catcode123=1 \catcode125=2 \pdfoutput=1 +\input layout.tex +\openin3=texsys.aux \read3 to\storedwidth \closein3 +\dump +", + ) + .unwrap(); + fs::write( + texmf.join("layout.tex"), + br"\def\savedrule{\vrule width\storedwidth height4pt depth0pt}", + ) + .unwrap(); + fs::write(mode.join("texsys.aux"), b"8pt\nunread before move\n").unwrap(); + let mut build = request(&mode); + build.world = WorldConfig::new(&mode); + build.world.paths.insert( + ResourceKind::Tex, + vec![ + SearchPath::directory(&mode, false), + SearchPath::directory(&texmf, false), + ], + ); + build.input = seed; + build.output = mode.join("latex.tfx"); + let dumped = dump_bundled_format(build, Cancellation::default(), &staging).unwrap(); + assert!(dumped.resources.trace.stream_reads.iter().any(|range| { + range.path == mode.join("texsys.aux") && range.offset == 0 && range.bytes == 4 + })); + + fs::write(project.join("main.tex"), br"\shipout\hbox{\savedrule}\end").unwrap(); + let result = |bundle: &Path| { + let mut job = request(&project); + job.entry = Entry::Format(bundle.join("formats/pdflatex/latex.tfx")); + NativeCompiler::default().compile(job) + }; + let reference = result(&staging).unwrap(); + fs::rename(&staging, &installed).unwrap(); + assert!(!staging.exists()); + + let scratch = installed.join("formats/pdflatex/texsys.aux"); + fs::write(&scratch, b"8pt\nunread after move\n").unwrap(); + let moved = result(&installed).unwrap(); + assert_eq!(moved.pdf, reference.pdf); + assert!(moved.resources.trace.reads.iter().any(|resource| { + resource.path == installed.join("texmf/layout.tex") + })); + + fs::write(&scratch, b"9pt\nunread after move\n").unwrap(); + let error = result(&installed).err().unwrap(); + let message = error.to_string(); + assert!( + message.contains("native format source changed") && message.contains(scratch.to_str().unwrap()), + "{message}" + ); + fs::remove_file(scratch).unwrap(); + let error = result(&installed).err().unwrap(); + assert!(error.to_string().contains("native format relocated input not found"), "{error}"); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn relocated_format_checks_current_sources_and_consumed_stream_ranges() { let root = directory("format-relocation").canonicalize().unwrap();