Reduce Windows desktop format, opening and edit latency

This commit is contained in:
gloamxun committed 2026-12-03 00:02:37 +08:00
1 parent 4655f8a3c9
commit 830292b9b6
15 files changed
+1006 -167

No files matched your search

@@ -71,6 +71,52 @@ impl FormatImage {
self 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<Self, String> {
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::<Result<_, String>>()?;
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 /// 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, /// inputs still uses the original tree. Once any moved input is present,
/// every recorded input and alias in the moved tree must be available. /// every recorded input and alias in the moved tree must be available.
+6 -4
View File
@@ -29,8 +29,9 @@ Unicode 与 pdfLaTeX 兼容项目。
xeCJK 或 fontspec。线索不足时使用 pdfLaTeX,以保留常见旧模板的排版。 xeCJK 或 fontspec。线索不足时使用 pdfLaTeX,以保留常见旧模板的排版。
可以在「重新编译」旁按项目选择「自动」「Unicode」或「pdfLaTeX」。 可以在「重新编译」旁按项目选择「自动」「Unicode」或「pdfLaTeX」。
切换会保留当前编辑和上次成功预览。首次使用对应模式时会生成格式, 切换会保留当前编辑和上次成功预览。0.1.11 安装包预先生成两份格式。
后续重开时复用。若要在已打开的旧模板里添加中文,可以切到「Unicode」, 打开项目时加载所选格式,后续在同一程序中复用。要在现有模板里添加中文,
可以切到「Unicode」,
并在导言区加入 `\usepackage[UTF8,scheme=plain]{ctex}`。 并在导言区加入 `\usepackage[UTF8,scheme=plain]{ctex}`。
[CTeX 宏集手册](https://tug.ctan.org/language/chinese/ctex/ctex.pdf) [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、 zhnumber、fandol、xetex、ctex.doc、xecjk.doc、zhnumber.doc、
fandol.doc 的 `.tar.xz` 归档,放在同一下载目录。脚本用包索引校验 fandol.doc 的 `.tar.xz` 归档,放在同一下载目录。脚本用包索引校验
归档,再将 Unicode 资源和许可文件纳入安装包清单。使用已核验的 归档,再将 Unicode 资源和许可文件纳入安装包清单。使用已核验的
WSL 发布版作为基础 TeX 资源和 Web 界面的来源,在能访问该参考包 WSL 发布版作为基础 TeX 资源和 Web 界面的来源。准备脚本会运行同版
资源树的构建机运行。 Windows 内核,生成并校验安装包内的两份编译格式。构建机需能访问
参考资源并运行 Windows 程序,可以使用 Windows 或启用互操作的 WSL。
```sh ```sh
python3 desktop/build-windows-backend.py desktop/src-tauri/backend \ python3 desktop/build-windows-backend.py desktop/src-tauri/backend \
+29 -1
View File
@@ -5,9 +5,12 @@ import argparse
import hashlib import hashlib
import json import json
import lzma import lzma
import os
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
import shutil import shutil
import stat
import struct import struct
import subprocess
import tarfile import tarfile
import tempfile import tempfile
@@ -18,6 +21,7 @@ TOOLS = {
"bibtex.windows": ("bibtex.exe",), "bibtex.windows": ("bibtex.exe",),
"kpathsea.windows": ("kpsewhich.exe", "kpathsealibw64.dll", "msvcr100.dll"), "kpathsea.windows": ("kpsewhich.exe", "kpathsealibw64.dll", "msvcr100.dll"),
} }
FORMAT_MODES = ("pdflatex", "xelatex")
UNICODE_PACKAGES = ("ctex", "xecjk", "zhnumber", "fandol", "xetex") UNICODE_PACKAGES = ("ctex", "xecjk", "zhnumber", "fandol", "xetex")
UNICODE_NOTICES = { UNICODE_NOTICES = {
"ctex": {"doc/latex/ctex/README.md": "ctex-README.md"}, "ctex": {"doc/latex/ctex/README.md": "ctex-README.md"},
@@ -145,6 +149,28 @@ def copy_texmf(source, target, skip_generated):
shutil.copy2(path, staged) 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): def stage(args, output):
reference = json.loads((args.reference / "bundle.json").read_text()) reference = json.loads((args.reference / "bundle.json").read_text())
desktop = json.loads((args.reference / "desktop-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(":")) font_maps = Path(reference["environment"]["TEXFONTMAPS"].rstrip(":"))
(texmf / "fonts").mkdir() (texmf / "fonts").mkdir()
shutil.copy2(font_maps / "pdftex.map", texmf / "fonts") 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(): if not (texmf / "dist/tex/latex/tex-ini-files" / entry).is_file():
raise ValueError(f"Missing LaTeX initialization source: {entry}") raise ValueError(f"Missing LaTeX initialization source: {entry}")
@@ -189,6 +216,7 @@ def stage(args, output):
texmf / "overlay", licenses / "texlive", args.downloads, database texmf / "overlay", licenses / "texlive", args.downloads, database
) )
prepare_formats(output)
files = { files = {
path.relative_to(output).as_posix(): digest(path) path.relative_to(output).as_posix(): digest(path)
for path in sorted(output.rglob("*")) if path.is_file() for path in sorted(output.rglob("*")) if path.is_file()
+1 -1
View File
@@ -3237,7 +3237,7 @@ dependencies = [
[[package]] [[package]]
name = "texrra-desktop" name = "texrra-desktop"
version = "0.1.10" version = "0.1.11"
dependencies = [ dependencies = [
"serde_json", "serde_json",
"tauri", "tauri",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "texrra-desktop" name = "texrra-desktop"
version = "0.1.10" version = "0.1.11"
edition = "2024" edition = "2024"
rust-version = "1.92" rust-version = "1.92"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "Texrra", "productName": "Texrra",
"version": "0.1.10", "version": "0.1.11",
"identifier": "org.texrra.desktop", "identifier": "org.texrra.desktop",
"build": { "build": {
"frontendDist": "../startup" "frontendDist": "../startup"
+60 -8
View File
@@ -27,6 +27,9 @@ let activeFile;
let preparingProject = false; let preparingProject = false;
let compileMode; let compileMode;
let cachedPreviewRequest; let cachedPreviewRequest;
let openingPreviewRequest;
let openingPreviewFrame;
const openingStarted = performance.now();
let sequence = 0; let sequence = 0;
let publishedRevision = null; let publishedRevision = null;
let visibleRevision = null; let visibleRevision = null;
@@ -219,6 +222,7 @@ async function showCachedPreview() {
if (!canDisplay()) return; if (!canDisplay()) return;
for (const page of savedPages.slice(1)) frames.push(pageFrame(page)); for (const page of savedPages.slice(1)) frames.push(pageFrame(page));
pages.replaceChildren(...frames); pages.replaceChildren(...frames);
cachedPreviewStatus.textContent = "上次成功预览";
cachedPreviewStatus.hidden = false; cachedPreviewStatus.hidden = false;
} catch { } catch {
// Cache errors do not interrupt the live compile. // 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) { function requestPreviewText(revision) {
clearTimeout(textLayerTimer); clearTimeout(textLayerTimer);
textLayerRequest?.abort(); textLayerRequest?.abort();
@@ -349,7 +386,7 @@ async function requestHttpPreview(payload) {
return { status: response.status, body: await response.json() }; return { status: response.status, body: await response.json() };
} }
async function compile(edit, submitted, changes) { async function compile(edit, submitted, changes, usePrepared) {
const replacements = []; const replacements = [];
let pendingDraft; let pendingDraft;
try { try {
@@ -360,6 +397,7 @@ async function compile(edit, submitted, changes) {
visible_revision: visibleRevision, visible_revision: visibleRevision,
files: changes, files: changes,
preview_draft: previewDraft, preview_draft: previewDraft,
use_prepared: usePrepared,
}; };
const socketReply = requestSocketPreview(payload); const socketReply = requestSocketPreview(payload);
let response; let response;
@@ -382,7 +420,11 @@ async function compile(edit, submitted, changes) {
throw new Error("预览版本与当前页面不一致"); throw new Error("预览版本与当前页面不一致");
} }
for (const page of update.pages) replacements.push(pageFrame(page)); 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) { if (edit !== sequence) {
revokeDetached(replacements); revokeDetached(replacements);
return; return;
@@ -416,12 +458,15 @@ async function compile(edit, submitted, changes) {
reusedSuffixSteps: result.reused_suffix_steps, reusedSuffixSteps: result.reused_suffix_steps,
discardedSuffixAttemptSteps: result.discarded_suffix_attempt_steps, discardedSuffixAttemptSteps: result.discarded_suffix_attempt_steps,
executedSteps: result.executed_steps, executedSteps: result.executed_steps,
reusedPrepared: result.reused_prepared === true,
reusedFrontier: result.reused_frontier, reusedFrontier: result.reused_frontier,
replayedCalls: result.replayed_calls, replayedCalls: result.replayed_calls,
pendingPublication: result.pending_publication === true, pendingPublication: result.pending_publication === true,
deferredStateFingerprint: result.deferred_state_fingerprint === true, deferredStateFingerprint: result.deferred_state_fingerprint === true,
}; };
const visibleStatus = sample.count + " 页 · " + Math.round(sample.visibleMs) + " 毫秒";
if (edit === sequence) { if (edit === sequence) {
status.textContent = pendingDraft ? visibleStatus + " · 正在生成 PDF" : visibleStatus;
window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample })); window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample }));
} }
if (pendingDraft) { if (pendingDraft) {
@@ -437,9 +482,7 @@ async function compile(edit, submitted, changes) {
}, },
})); }));
} }
if (edit === sequence) { if (pendingDraft && edit === sequence) status.textContent = visibleStatus;
status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`;
}
} catch (failure) { } catch (failure) {
revokeDetached(replacements); revokeDetached(replacements);
if (edit === sequence) { if (edit === sequence) {
@@ -456,7 +499,7 @@ function invalidatePreview() {
promptCompilePending = false; promptCompilePending = false;
} }
function queueCompile(immediate = false) { function queueCompile(immediate = false, usePrepared = false) {
if (preparingProject) return; if (preparingProject) return;
const submitted = performance.now(); const submitted = performance.now();
// Edits arriving before the first dispatch share its prompt submission. // Edits arriving before the first dispatch share its prompt submission.
@@ -470,12 +513,13 @@ function queueCompile(immediate = false) {
if (edit !== sequence || composing) return; if (edit !== sequence || composing) return;
compileTimer = undefined; compileTimer = undefined;
promptCompilePending = false; promptCompilePending = false;
compile(edit, submitted, Object.fromEntries(edits)); compile(edit, submitted, Object.fromEntries(edits), usePrepared);
}, prompt ? 0 : EDIT_IDLE_MS); }, prompt ? 0 : EDIT_IDLE_MS);
} }
function manualCompile() { function manualCompile() {
if (recompile.disabled || composing) return; if (recompile.disabled || composing) return;
openingPreviewRequest?.abort();
recordEdit(true); recordEdit(true);
} }
@@ -596,7 +640,7 @@ async function finishProjectOpening(project) {
save.disabled = false; save.disabled = false;
recompile.disabled = false; recompile.disabled = false;
advertisePreviewSocket(project.preview_socket); advertisePreviewSocket(project.preview_socket);
queueCompile(true); queueCompile(true, true);
} }
async function switchCompileMode() { async function switchCompileMode() {
@@ -620,6 +664,13 @@ async function switchCompileMode() {
// full update. Old revision identifiers belong to the previous session. // full update. Old revision identifiers belong to the previous session.
restorePublishedPages(); restorePublishedPages();
cachedPreviewRequest?.abort(); cachedPreviewRequest?.abort();
openingPreviewRequest?.abort();
if (openingPreviewFrame) {
openingPreviewFrame.remove();
revokeDetached([openingPreviewFrame]);
openingPreviewFrame = undefined;
}
cachedPreviewStatus.textContent = "上次成功预览";
clearTimeout(textLayerTimer); clearTimeout(textLayerTimer);
textLayerRequest?.abort(); textLayerRequest?.abort();
textLayerRevision = undefined; textLayerRevision = undefined;
@@ -739,6 +790,7 @@ async function openProject() {
indentSource(); indentSource();
}); });
if (project.cached_preview === true) void showCachedPreview(); if (project.cached_preview === true) void showCachedPreview();
else if (project.preparing === true && previewDraft) void showOpeningPreview();
await finishProjectOpening(project); await finishProjectOpening(project);
} catch (failure) { } catch (failure) {
showError(failure.message); showError(failure.message);
+31 -18
View File
@@ -25,8 +25,8 @@ pub(super) struct EditorFormat {
} }
struct FormatPreparation { struct FormatPreparation {
lock: Mutex<()>, ready: Mutex<bool>,
build: Box<dyn Fn() -> Result<(), String> + Send + Sync>, prepare: Box<dyn Fn() -> Result<(), String> + Send + Sync>,
} }
impl EditorFormat { impl EditorFormat {
@@ -41,23 +41,36 @@ impl EditorFormat {
profile: InputProfile, profile: InputProfile,
build: impl Fn() -> Result<(), String> + Send + Sync + 'static, build: impl Fn() -> Result<(), String> + Send + Sync + 'static,
) -> Self { ) -> Self {
Self { let output = image.clone();
image, Self::prepare_on_open(image, manifest, profile, move || {
manifest, if !output.is_file() {
profile, build()?;
compiler: NativeCompiler::default(), }
preparation: Some(Arc::new(FormatPreparation { Ok(())
lock: Mutex::new(()), })
build: Box::new(build), }
})),
} #[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> { pub(super) fn ensure(&self) -> Result<(), String> {
if let Some(preparation) = &self.preparation { if let Some(preparation) = &self.preparation {
let _lock = preparation.lock.lock().unwrap(); let mut ready = preparation.ready.lock().unwrap();
if !self.image.is_file() { if !*ready || !self.image.is_file() {
(preparation.build)()?; (preparation.prepare)()?;
*ready = true;
} }
} }
Ok(()) Ok(())
@@ -100,10 +113,10 @@ impl Library {
} }
pub(super) fn prewarm_format(&self) { pub(super) fn prewarm_format(&self) {
// Decode ready formats in the background. A first launch can show // Decode caller-supplied formats in the background. Windows bundles
// the library while the selected project's missing format is built. // defer verification and decoding until a project selects a profile.
for format in std::iter::once(&self.primary).chain(self.unicode.iter()) { 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; continue;
} }
let compiler = format.compiler.clone(); let compiler = format.compiler.clone();
+286 -66
View File
@@ -16,13 +16,14 @@ use std::{
}; };
use texrra_engine::native::{ use texrra_engine::native::{
CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage,
CompiledDocument,
DraftPreview, Entry, DraftPreview, Entry,
EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot, EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot,
job_time, job_time,
}; };
use texrra_tex_core::{ use texrra_tex_core::{
execution::InputProfile, execution::InputProfile,
resources::{FileModificationTime, InputPolicy, ResourceKind, SearchPath, WorldConfig}, resources::{FileModificationTime, FileWorld, InputPolicy, ResourceKind, SearchPath, WorldConfig},
}; };
use thread_usage::ThreadUsage; use thread_usage::ThreadUsage;
use tiny_http::{Header, Method, Request, Response, Server}; use tiny_http::{Header, Method, Request, Response, Server};
@@ -55,6 +56,8 @@ struct Edit {
files: BTreeMap<String, Option<String>>, files: BTreeMap<String, Option<String>>,
#[serde(default)] #[serde(default)]
preview_draft: bool, preview_draft: bool,
#[serde(default)]
use_prepared: bool,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -98,15 +101,22 @@ impl PreviewReply {
struct Work { struct Work {
cache: Option<preview_cache::PreviewCache>, cache: Option<preview_cache::PreviewCache>,
respond_to: PreviewReply, respond_to: PreviewReply,
job: CompileJob, input: PreviewInput,
bibliography_pass: Option<CompileJob>,
compile: CompileRequest,
sequence: u64, sequence: u64,
visible_revision: Option<u64>, visible_revision: Option<u64>,
received: Instant, received: Instant,
preview_draft: bool, preview_draft: bool,
} }
enum PreviewInput {
Compile {
job: CompileJob,
bibliography_pass: Option<CompileJob>,
request: CompileRequest,
},
Prepared(Arc<CompiledDocument>),
}
#[derive(Clone, Copy, Default)] #[derive(Clone, Copy, Default)]
struct StageTiming { struct StageTiming {
wall_ms: f64, wall_ms: f64,
@@ -287,6 +297,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
} }
let mut args = std::env::args_os().skip(1).peekable(); let mut args = std::env::args_os().skip(1).peekable();
#[cfg(windows)] #[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() { if args.next_if(|arg| arg == "--windows-desktop").is_some() {
return windows_format::run(args).map_err(|error| { return windows_format::run(args).map_err(|error| {
let detail = error.to_string().replace(['\r', '\n'], " "); let detail = error.to_string().replace(['\r', '\n'], " ");
@@ -364,7 +378,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
root, &source, &format, &manifest, &run, &additional, input_profile, root, &source, &format, &manifest, &run, &additional, input_profile,
)?; )?;
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); 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))) (port, Some(EditorSession::new(run, editor, compiler, None)))
}; };
serve(web, library, port, session) serve(web, library, port, session)
@@ -528,6 +542,20 @@ fn serve(
}); });
continue; 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)) => { ("ready", Some(opening)) => {
let ready = opening.ready.clone(); let ready = opening.ready.clone();
std::thread::spawn(move || match ready.wait() { std::thread::spawn(move || match ready.wait() {
@@ -773,12 +801,21 @@ fn read_port(value: Option<PathBuf>) -> Result<u16, std::num::ParseIntError> {
} }
type ReadyEditor = Result<Arc<Mutex<EditorSession>>, String>; type ReadyEditor = Result<Arc<Mutex<EditorSession>>, String>;
type OpeningPreview = OnceLock<Option<Arc<CompiledDocument>>>;
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 { struct OpeningEditor {
id: String, id: String,
cache: Option<preview_cache::PreviewCache>, cache: Option<preview_cache::PreviewCache>,
sources: Value, sources: Value,
ready: Arc<OnceLock<ReadyEditor>>, ready: Arc<OnceLock<ReadyEditor>>,
preview: Arc<OpeningPreview>,
compiler: NativeCompiler, compiler: NativeCompiler,
superseded: Arc<AtomicBool>, superseded: Arc<AtomicBool>,
} }
@@ -813,11 +850,13 @@ impl OpeningEditor {
cache, cache,
sources, sources,
ready: Arc::new(OnceLock::new()), ready: Arc::new(OnceLock::new()),
preview: Arc::new(OnceLock::new()),
compiler, compiler,
superseded: Arc::new(AtomicBool::new(false)), superseded: Arc::new(AtomicBool::new(false)),
}; };
let id = opening.id.clone(); let id = opening.id.clone();
let ready = opening.ready.clone(); let ready = opening.ready.clone();
let preview = opening.preview.clone();
let compiler = opening.compiler.clone(); let compiler = opening.compiler.clone();
let superseded = opening.superseded.clone(); let superseded = opening.superseded.clone();
let cache = opening.cache.clone(); let cache = opening.cache.clone();
@@ -830,13 +869,16 @@ impl OpeningEditor {
let cache = cache.or_else(|| { let cache = cache.or_else(|| {
cacheable.then(|| initial_preview_cache(&id, &run, &staged, &format)).flatten() cacheable.then(|| initial_preview_cache(&id, &run, &staged, &format)).flatten()
}); });
let editor = finish_prepare(staged, &run, &compiler, Some(&superseded), Some(&id)) let editor = finish_prepare(
.map_err(|error| error.to_string())?; staged, &run, &compiler, Some(&superseded), Some(&id), Some(&preview),
).map_err(|error| error.to_string())?;
let mut session = EditorSession::new(run, editor, compiler, cache); let mut session = EditorSession::new(run, editor, compiler, cache);
session.id = Some(id); session.id = Some(id);
session.mode_choice = mode_choice; session.mode_choice = mode_choice;
Ok(Arc::new(Mutex::new(session))) Ok(Arc::new(Mutex::new(session)))
})(); })();
// Wake a provisional preview request even if preparation failed.
preview.get_or_init(|| None);
let _ = ready.set(result); let _ = ready.set(result);
})?; })?;
Ok(opening) Ok(opening)
@@ -895,6 +937,7 @@ struct EditorSession {
run: PathBuf, run: PathBuf,
compiler: NativeCompiler, compiler: NativeCompiler,
first_preview_revision: u64, first_preview_revision: u64,
prepared_preview: Option<Arc<CompiledDocument>>,
bibliography_compiler: Option<NativeCompiler>, bibliography_compiler: Option<NativeCompiler>,
queue: Arc<Queue>, queue: Arc<Queue>,
save_number: u64, save_number: u64,
@@ -904,12 +947,12 @@ struct EditorSession {
impl EditorSession { impl EditorSession {
fn new( fn new(
run: PathBuf, run: PathBuf,
editor: EditorProject, mut editor: EditorProject,
compiler: NativeCompiler, compiler: NativeCompiler,
cache: Option<preview_cache::PreviewCache>, cache: Option<preview_cache::PreviewCache>,
) -> Self { ) -> Self {
// Resource discovery warms the compiler's caches. Only preview jobs let prepared_preview = editor.prepared_preview.take();
// may expose a revision to the editor. // 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 first_preview_revision = compiler.latest().map_or(1, |document| document.revision() + 1);
let queue = Arc::new(Queue { let queue = Arc::new(Queue {
current: AtomicU64::new(editor.project.version().revision), current: AtomicU64::new(editor.project.version().revision),
@@ -934,6 +977,7 @@ impl EditorSession {
run, run,
compiler, compiler,
first_preview_revision, first_preview_revision,
prepared_preview,
bibliography_compiler, bibliography_compiler,
queue, queue,
save_number: 0, save_number: 0,
@@ -980,23 +1024,31 @@ impl EditorSession {
} }
project.with_file_changes(edit.sequence, updates) project.with_file_changes(edit.sequence, updates)
}); });
*project = match next { let next = match next {
Ok(project) => project, Ok(project) => project,
Err(error) => { Err(error) => {
respond_to.send(422, json!({ "error": error })); respond_to.send(422, json!({ "error": error }));
return; return;
} }
}; };
let compile = options.clone().with_project(project.clone()); let unchanged = project.version().sha256 == next.version().sha256;
let job = self.compiler.start(); *project = next;
let bibliography_pass = self.bibliography_compiler.as_ref().map(NativeCompiler::start); 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); self.queue.current.store(edit.sequence, Ordering::Release);
let replaced = self.queue.next.lock().unwrap().replace(Work { let replaced = self.queue.next.lock().unwrap().replace(Work {
cache: self.cache.as_ref().filter(|cache| cache.matches_saved_sources(project)).cloned(), cache: self.cache.as_ref().filter(|cache| cache.matches_saved_sources(project)).cloned(),
respond_to, respond_to,
job, input,
bibliography_pass,
compile,
sequence: edit.sequence, sequence: edit.sequence,
visible_revision: edit.visible_revision, visible_revision: edit.visible_revision,
received, received,
@@ -1045,6 +1097,7 @@ struct EditorProject {
declared: BTreeSet<PathBuf>, declared: BTreeSet<PathBuf>,
options: CompileRequest, options: CompileRequest,
bibliography: Option<bibliography::Plan>, bibliography: Option<bibliography::Plan>,
prepared_preview: Option<Arc<CompiledDocument>>,
} }
fn copy_with_date( fn copy_with_date(
@@ -1201,6 +1254,7 @@ fn finish_prepare(
compiler: &NativeCompiler, compiler: &NativeCompiler,
superseded: Option<&AtomicBool>, superseded: Option<&AtomicBool>,
project_id: Option<&str>, project_id: Option<&str>,
preview: Option<&OpeningPreview>,
) -> Result<EditorProject, Box<dyn std::error::Error>> { ) -> Result<EditorProject, Box<dyn std::error::Error>> {
let StagedProject { let StagedProject {
world, world,
@@ -1263,6 +1317,11 @@ fn finish_prepare(
Ok(result) Ok(result)
}; };
let mut seed = compile_seed(1)?; 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; let mut bibliography = None;
if let Ok(initial) = &seed { if let Ok(initial) = &seed {
let cached_bbl = project_id let cached_bbl = project_id
@@ -1366,6 +1425,7 @@ fn finish_prepare(
generated_roots: BTreeSet::from([run.to_owned()]), generated_roots: BTreeSet::from([run.to_owned()]),
generated, generated,
}, dates)?; }, dates)?;
let prepared_preview = seed.ok().filter(|document| stable_opening_seed(document, &project));
Ok(EditorProject { Ok(EditorProject {
project, project,
entry, entry,
@@ -1373,6 +1433,60 @@ fn finish_prepare(
declared, declared,
options: request, options: request,
bibliography, 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<ProjectSnapshot>) -> 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 { let Some(Work {
cache, cache,
respond_to, respond_to,
job, input,
bibliography_pass,
mut compile,
sequence, sequence,
visible_revision, visible_revision,
received, received,
@@ -1416,45 +1528,52 @@ fn worker(
received, received,
preview_draft, preview_draft,
}); });
let revision = job.revision(); let reused_prepared = matches!(&input, PreviewInput::Prepared(_));
let mut project = compile let (revision, result) = match input {
.project PreviewInput::Prepared(document) => (document.revision(), Ok(document)),
.clone() PreviewInput::Compile { job, bibliography_pass, mut request } => {
.expect("the editor submits a project snapshot"); let revision = job.revision();
project = resources let mut project = request
.apply(&project) .project
.expect("captured resources retain their original roots"); .clone()
let settle = (|| { .expect("the editor submits a project snapshot");
if let Some((path, settled)) = &mut settled_bibliography project = resources
&& let Some(current) = project.file(path).map(|file| file.data.clone()) .apply(&project)
&& !Arc::ptr_eq(settled, &current) .expect("captured resources retain their original roots");
&& settled.as_ref() != current.as_ref() let settle = (|| {
&& let Some(pass) = bibliography_pass if let Some((path, settled)) = &mut settled_bibliography
{ && let Some(current) = project.file(path).map(|file| file.data.clone())
// The new BBL writes the updated labels at the end of a pass. && !Arc::ptr_eq(settled, &current)
// A private compiler settles those AUX files before the editor && settled.as_ref() != current.as_ref()
// exposes any draft or PDF for this revision. && let Some(pass) = bibliography_pass
pass.compile_expanding_project(compile.clone().with_project(project.clone()), |failure| { {
if !observer.is_current() { // The new BBL writes the updated labels at the end of a pass.
return None; // 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)?; Ok(())
Some(project.clone()) })();
}).map_err(|failure| failure.error)?; request.observer = Some(observer.clone());
*settled = current; 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 compile_ms = observer.elapsed_ms();
let respond_to = observer.respond_to.lock().unwrap().take(); let respond_to = observer.respond_to.lock().unwrap().take();
let Some(respond_to) = respond_to else { let Some(respond_to) = respond_to else {
@@ -1498,15 +1617,14 @@ fn worker(
} }
match preview { match preview {
Ok(update) => { Ok(update) => {
respond_to.send( let steps = document.execution.execution.steps;
200, let adoption = EntryCheckpointWork { reused_steps: steps, ..EntryCheckpointWork::default() };
observer.preview_payload( let work = if reused_prepared { &adoption } else { &document.entry_checkpoint_work };
update, let mut payload = observer.preview_payload(update, steps, work, Some(compile_ms));
document.execution.execution.steps, if reused_prepared {
&document.entry_checkpoint_work, payload["reused_prepared"] = Value::Bool(true);
Some(compile_ms), }
), respond_to.send(200, payload);
);
if let Some(cache) = cache { if let Some(cache) = cache {
cache.refresh(document); cache.refresh(document);
} }
@@ -1534,3 +1652,105 @@ fn respond(request: Request, status: u16, content_type: &str, bytes: Vec<u8>) {
eprintln!("Editor response: {error}"); 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<String>,
) -> 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);
}
}
+161 -42
View File
@@ -1,8 +1,13 @@
//! Bootstrap the installed Windows editor from the packaged TeX resources. //! 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 serde::Deserialize;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::{ use std::{
collections::BTreeMap,
env, env,
ffi::{OsStr, OsString}, ffi::{OsStr, OsString},
fs::{self, File, OpenOptions}, fs::{self, File, OpenOptions},
@@ -10,7 +15,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
time::Instant, 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::{ use texrra_tex_core::{
execution::{Cancellation, InputProfile}, execution::{Cancellation, InputProfile},
resources::WorldConfig, resources::WorldConfig,
@@ -22,6 +27,41 @@ type LaunchResult<T> = Result<T, Box<dyn std::error::Error>>;
struct Bundle { struct Bundle {
schema: u32, schema: u32,
resources_sha256: String, resources_sha256: String,
#[serde(default)]
sha256: BTreeMap<String, String>,
}
const MODES: [(InputProfile, &str); 2] = [
(InputProfile::TeX8Bit, "pdflatex"),
(InputProfile::XeTeX, "xelatex"),
];
pub(super) fn prepare_bundle(mut arguments: impl Iterator<Item = OsString>) -> 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<Item = OsString>) -> LaunchResult<()> { pub(super) fn run(mut arguments: impl Iterator<Item = OsString>) -> LaunchResult<()> {
@@ -41,13 +81,7 @@ pub(super) fn run(mut arguments: impl Iterator<Item = OsString>) -> LaunchResult
let receipt = fs::read(backend.join("windows-bundle.json"))?; let receipt = fs::read(backend.join("windows-bundle.json"))?;
let bundle: Bundle = serde_json::from_slice(&receipt)?; let bundle: Bundle = serde_json::from_slice(&receipt)?;
if bundle.schema != 1 if bundle.schema != 1 || !valid_digest(&bundle.resources_sha256) {
|| bundle.resources_sha256.len() != 64
|| !bundle
.resources_sha256
.bytes()
.all(|byte| byte.is_ascii_hexdigit())
{
return Err("Invalid Windows desktop bundle receipt".into()); return Err("Invalid Windows desktop bundle receipt".into());
} }
let mut key = Sha256::new(); let mut key = Sha256::new();
@@ -58,20 +92,7 @@ pub(super) fn run(mut arguments: impl Iterator<Item = OsString>) -> LaunchResult
fs::create_dir_all(&runtime)?; fs::create_dir_all(&runtime)?;
let runtime = runtime.canonicalize()?; let runtime = runtime.canonicalize()?;
let texmf = backend.join("texmf"); let (roots, font_maps) = bundle_resources(&backend)?;
let roots = ["overlay", "dist", "var"]
.map(|directory| texmf.join(directory).canonicalize())
.into_iter()
.collect::<io::Result<Vec<_>>>()?;
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 state = home.join("state"); let state = home.join("state");
fs::create_dir_all(&state)?; fs::create_dir_all(&state)?;
configure_environment(&backend, &state, &font_maps)?; configure_environment(&backend, &state, &font_maps)?;
@@ -83,13 +104,39 @@ pub(super) fn run(mut arguments: impl Iterator<Item = OsString>) -> LaunchResult
fs::write(&manifest, manifest_bytes)?; fs::write(&manifest, manifest_bytes)?;
} }
let manifest = manifest.canonicalize()?; let manifest = manifest.canonicalize()?;
let primary = desktop_format(&runtime, &manifest, &roots, InputProfile::TeX8Bit, "pdflatex")?; let [primary, unicode] = MODES.map(|(profile, name)| {
let unicode = desktop_format(&runtime, &manifest, &roots, InputProfile::XeTeX, "xelatex")?; desktop_format(
&backend, &bundle, &runtime, &manifest, &roots, profile, name,
)
});
let web = WebAssets::load(&backend.join("web"))?; 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) serve(Some(web), Some(library), 0, None)
} }
fn bundle_resources(backend: &Path) -> LaunchResult<(Vec<PathBuf>, PathBuf)> {
let texmf = backend.join("texmf");
let roots = ["overlay", "dist", "var"]
.map(|directory| texmf.join(directory).canonicalize())
.into_iter()
.collect::<io::Result<Vec<_>>>()?;
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<File> { fn lock_backend(home: &Path) -> io::Result<File> {
let file = OpenOptions::new() let file = OpenOptions::new()
.read(true) .read(true)
@@ -160,34 +207,102 @@ fn start_lease() -> io::Result<()> {
Ok(()) 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<PathBuf> {
roots[1]
.join("tex/latex/tex-ini-files")
.join(format!("{name}.ini"))
.canonicalize()
}
fn desktop_format( fn desktop_format(
backend: &Path,
bundle: &Bundle,
runtime: &Path, runtime: &Path,
manifest: &Path, manifest: &Path,
roots: &[PathBuf], roots: &[PathBuf],
profile: InputProfile, profile: InputProfile,
name: &'static str, name: &'static str,
) -> LaunchResult<EditorFormat> { ) -> LaunchResult<EditorFormat> {
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); let directory = runtime.join(name);
fs::create_dir_all(&directory)?; fs::create_dir_all(&directory)?;
let output = directory.canonicalize()?.join("latex.tfx"); let output = directory.canonicalize()?.join("latex.tfx");
let roots = roots.to_vec(); let roots = roots.to_vec();
Ok(EditorFormat::lazy(output.clone(), manifest.to_owned(), profile, move || { Ok(EditorFormat::lazy(
let started = Instant::now(); output.clone(),
let result = build_format(&ini, &output, &roots, profile).map_err(|error| error.to_string()); manifest.to_owned(),
if env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE").is_some_and(|value| value == "1") { profile,
eprintln!("Texrra editor preparation {}", serde_json::json!({ move || {
"stage": "build-format", let started = Instant::now();
"mode": name, let result = build_format(&ini, &output, &roots, profile, None)
"ms": started.elapsed().as_secs_f64() * 1000.0, .map_err(|error| error.to_string());
"ok": result.is_ok(), if env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE").is_some_and(|value| value == "1") {
})); eprintln!(
} "Texrra editor preparation {}",
result 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 directory = format.parent().expect("format has a directory");
let world = WorldConfig::from_environment(directory, roots.to_vec())?; let world = WorldConfig::from_environment(directory, roots.to_vec())?;
let mut request = CompileRequest::new(world, ini, format, job_time()?); 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.input_profile = profile;
request.etex = true; request.etex = true;
request.limits.steps = 600_000_000; 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(()) Ok(())
} }
+31 -4
View File
@@ -350,6 +350,10 @@ impl CompiledDocument {
|| Ok(()), || Ok(()),
) )
} }
/// Render page one without rendering the rest of a prepared document.
pub fn first_preview_page(&self) -> Result<Option<PreviewPage>, String> {
self.preview.first_page(&self.pages, self.pdf.as_ref())
}
pub fn has_show_diagnostic(&self) -> bool { pub fn has_show_diagnostic(&self) -> bool {
self.execution.execution.events.iter().any(|e| { self.execution.execution.events.iter().any(|e| {
matches!( matches!(
@@ -1694,22 +1698,41 @@ pub fn dump_format(
) -> Result<BuiltFormat, CompileError> { ) -> Result<BuiltFormat, CompileError> {
dump_format_detailed(request, cancellation).map_err(|failure| failure.error) 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<BuiltFormat, CompileError> {
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 /// A format build has no editor-session revision; revision zero identifies the
/// offline attempt. Its source versions and host effects are still actual. /// offline attempt. Its source versions and host effects are still actual.
pub fn dump_format_detailed( pub fn dump_format_detailed(
request: CompileRequest, request: CompileRequest,
cancellation: Cancellation, cancellation: Cancellation,
) -> Result<BuiltFormat, CompileFailure> {
dump_format_with_location(request, cancellation, None)
}
fn dump_format_with_location(
request: CompileRequest,
cancellation: Cancellation,
bundle: Option<&Path>,
) -> Result<BuiltFormat, CompileFailure> { ) -> Result<BuiltFormat, CompileFailure> {
let mut evidence = AttemptEvidence::new(0); let mut evidence = AttemptEvidence::new(0);
let summary = AttemptRequest::from(&request); let summary = AttemptRequest::from(&request);
evidence.phase = AttemptPhase::Preparing; 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()) .map_err(|error| evidence.failure(error, summary).persist_requested())
} }
fn dump_format_observed( fn dump_format_observed(
request: CompileRequest, request: CompileRequest,
cancellation: Cancellation, cancellation: Cancellation,
evidence: &mut AttemptEvidence, evidence: &mut AttemptEvidence,
bundle: Option<&Path>,
) -> Result<BuiltFormat, CompileError> { ) -> Result<BuiltFormat, CompileError> {
let PreparedJob { let PreparedJob {
executor, executor,
@@ -1755,9 +1778,13 @@ fn dump_format_observed(
let trace = files.resource_trace(); let trace = files.resource_trace();
// Keep the completed kernel result available if format validation/encoding // Keep the completed kernel result available if format validation/encoding
// fails. This extra offline copy is not part of interactive compilation. // fails. This extra offline copy is not part of interactive compilation.
let bytes = FormatImage::from_dump_with_trace(execution.execution.clone(), trace)? let image = FormatImage::from_dump_with_trace(execution.execution.clone(), trace)?;
.with_project_location(&output, trace) let image = if let Some(bundle) = bundle {
.encode()?; image.with_bundle_location(&output, bundle)?
} else {
image.with_project_location(&output, trace)
};
let bytes = image.encode()?;
evidence.phase = AttemptPhase::Finishing; evidence.phase = AttemptPhase::Finishing;
let finished = files.finish(); let finished = files.finish();
let reported = report(&files, &request); let reported = report(&files, &request);
+117 -13
View File
@@ -245,11 +245,21 @@ impl CaptureSchedule {
} }
} }
fn with_preamble_anchor(mut self, source: &[u8]) -> Self { fn with_preamble_anchor(mut self, source: &[u8], profile: InputProfile) -> Self {
if self.fixed_frontier.is_none() && self.stride >= MIN_PREAMBLE_INTERVAL_BYTES { 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 // The first grid interval can span both package loading and
// LaTeX's generated-input reads. Keep one boundary between them. // 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 self
} }
@@ -783,7 +793,7 @@ impl CheckpointCache {
Option<Arc<CheckpointSet>>, Option<Arc<CheckpointSet>>,
) { ) {
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None) 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 captures = CapturedEntries::new(request, files);
let mut recording = RecordingHost::new(files); let mut recording = RecordingHost::new(files);
let mut nested = NestedSchedule::default(); let mut nested = NestedSchedule::default();
@@ -1127,7 +1137,7 @@ impl SelectedCheckpoint {
source.data.len(), source.data.len(),
None, None,
changed.or(self.set.edit_frontier), 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. // A comment-only line can be consumed without an observation.
// Keep an earlier anchor for this editing boundary. // Keep an earlier anchor for this editing boundary.
schedule.pending_edit_fallback = schedule.pending_edit_fallback =
@@ -1434,16 +1444,18 @@ fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
) )
} }
fn preamble_frontier(bytes: &[u8], limit: usize) -> Option<usize> { fn document_start_line(bytes: &[u8], limit: usize) -> Option<(usize, usize)> {
let mut start = 0; let mut start = 0;
for line in bytes.split_inclusive(|&byte| matches!(byte, b'\r' | b'\n')) { for line in bytes.split_inclusive(|&byte| matches!(byte, b'\r' | b'\n')) {
if start >= limit { if start >= limit {
break; break;
} }
let end = start + line.len();
if line.trim_ascii() == br"\begin{document}" { 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 None
} }
@@ -2591,22 +2603,114 @@ fn large_automatic_schedule_keeps_a_preamble_anchor_once() {
let mut source = prefix.to_vec(); let mut source = prefix.to_vec();
source.extend_from_slice(b" \\begin{document}\r\n"); source.extend_from_slice(b" \\begin{document}\r\n");
source.resize(4 * MIN_PREAMBLE_INTERVAL_BYTES, b'x'); 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); assert!(schedule.select(1, 0).unwrap().early);
let anchor = schedule.select(prefix.len(), 0).unwrap(); let anchor = schedule.select(prefix.len(), 0).unwrap();
assert!(anchor.preamble && !anchor.early && !anchor.edit && !anchor.page); assert!(anchor.preamble && !anchor.early && !anchor.edit && !anchor.page);
assert!(schedule.select(prefix.len(), 0).is_none()); assert!(schedule.select(prefix.len(), 0).is_none());
let mut schedule = CaptureSchedule::new(source.len(), None, Some(prefix.len())) 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(); let combined = schedule.select(prefix.len(), 0).unwrap();
assert!(combined.preamble && combined.early && combined.edit); assert!(combined.preamble && combined.early && combined.edit);
assert!(schedule.select(prefix.len(), 0).is_none()); assert!(schedule.select(prefix.len(), 0).is_none());
assert!(CaptureSchedule::new(source.len(), Some(1), 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) assert!(CaptureSchedule::new(prefix.len(), None, None)
.with_preamble_anchor(prefix).pending_preamble.is_none()); .with_preamble_anchor(prefix, InputProfile::TeX8Bit).pending_preamble.is_none());
assert_eq!(preamble_frontier(prefix, prefix.len()), 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] #[test]
+137 -1
View File
@@ -186,13 +186,60 @@ impl HostPreparation {
} }
return candidates.any(|candidate| self.same_file(candidate, path)); 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; let mut candidates = candidates;
candidates.any(|candidate| self.same_file(candidate, path)) 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<Item = &'a Path> + 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<Item = &'a Path>,
) -> Option<bool> {
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<Option<PathBuf>> {
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. /// Compare two outputs with the same protected paths in one live scan.
pub(crate) fn either_aliases_any<'a>( pub(crate) fn either_aliases_any<'a>(
&mut self, &mut self,
@@ -338,3 +385,92 @@ impl HostPreparation {
result.map(|()| Some(data)) 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();
}
}
+25 -7
View File
@@ -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<Option<PreviewPage>, 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( pub(crate) fn render(
&self, &self,
revision: u64, revision: u64,
@@ -189,13 +213,7 @@ impl PreviewState {
visible: Option<u64>, visible: Option<u64>,
check: impl Fn() -> Result<(), String>, check: impl Fn() -> Result<(), String>,
) -> Result<PreviewUpdate, String> { ) -> Result<PreviewUpdate, String> {
let mut pdf = PdfPreview { let mut pdf = self.pdf_context(pages, pdf);
bytes: pdf,
fonts: &self.fonts,
defaults: pages.iter().any(DisplayList::has_pdf_default_colors),
document: OnceLock::new(),
dependencies: PdfDependencies::default(),
};
let mut rendered = Vec::new(); let mut rendered = Vec::new();
let base_revision = if visible == Some(revision) { let base_revision = if visible == Some(revision) {
visible visible
+74
View File
@@ -3766,6 +3766,80 @@ fn format_seed_reuse_restarts_execution_and_checks_live_dependencies() {
fs::remove_dir_all(p).unwrap(); 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] #[test]
fn relocated_format_checks_current_sources_and_consumed_stream_ranges() { fn relocated_format_checks_current_sources_and_consumed_stream_ranges() {
let root = directory("format-relocation").canonicalize().unwrap(); let root = directory("format-relocation").canonicalize().unwrap();