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

+31 -4
View File
@@ -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<Option<PreviewPage>, 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<BuiltFormat, CompileError> {
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
/// offline attempt. Its source versions and host effects are still actual.
pub fn dump_format_detailed(
request: CompileRequest,
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> {
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<BuiltFormat, CompileError> {
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);
+117 -13
View File
@@ -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<Arc<CheckpointSet>>,
) {
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<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;
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]
+137 -1
View File
@@ -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<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.
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();
}
}
+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(
&self,
revision: u64,
@@ -189,13 +213,7 @@ impl PreviewState {
visible: Option<u64>,
check: impl Fn() -> Result<(), String>,
) -> Result<PreviewUpdate, String> {
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