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

+161 -42
View File
@@ -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<T> = Result<T, Box<dyn std::error::Error>>;
struct Bundle {
schema: u32,
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<()> {
@@ -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 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<Item = OsString>) -> 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::<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 (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<Item = OsString>) -> 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>, 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> {
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<PathBuf> {
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<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);
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(())
}