Files
texrra-engine/examples/native_editor/windows_format.rs
T

201 lines
7.2 KiB
Rust

//! Bootstrap the installed Windows editor from the packaged TeX resources.
use crate::{WebAssets, library::{EditorFormat, Library}, serve};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::{
env,
ffi::{OsStr, OsString},
fs::{self, File, OpenOptions},
io::{self, Read},
path::{Path, PathBuf},
time::Instant,
};
use texrra_engine::native::{CompileRequest, Entry, dump_format, job_time};
use texrra_tex_core::{
execution::{Cancellation, InputProfile},
resources::WorldConfig,
};
type LaunchResult<T> = Result<T, Box<dyn std::error::Error>>;
#[derive(Deserialize)]
struct Bundle {
schema: u32,
resources_sha256: String,
}
pub(super) fn run(mut arguments: impl Iterator<Item = OsString>) -> LaunchResult<()> {
let usage = "native_editor --windows-desktop BACKEND_DIRECTORY DATA_DIRECTORY";
let backend = PathBuf::from(arguments.next().ok_or(usage)?);
let home = PathBuf::from(arguments.next().ok_or(usage)?);
if arguments.next().is_some() || !backend.is_absolute() || !home.is_absolute() {
return Err(usage.into());
}
let backend = backend.canonicalize()?;
fs::create_dir_all(&home)?;
let home = home.canonicalize()?;
if home.starts_with(&backend) || backend.starts_with(&home) {
return Err("Packaged resources and desktop data must be separate".into());
}
let _lock = lock_backend(&home)?;
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())
{
return Err("Invalid Windows desktop bundle receipt".into());
}
let mut key = Sha256::new();
key.update(b"texrra Windows LaTeX format 1");
key.update(Sha256::digest(&receipt));
key.update(backend.as_os_str().as_encoded_bytes());
let runtime = home.join("runtime").join(format!("{:x}", key.finalize()));
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 state = home.join("state");
fs::create_dir_all(&state)?;
configure_environment(&backend, &state, &font_maps)?;
start_lease()?;
let manifest = runtime.join("format-resources.json");
let manifest_bytes = serde_json::to_vec(&serde_json::json!({"texmf_roots": roots}))?;
if fs::read(&manifest).ok().as_deref() != Some(&manifest_bytes) {
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 web = WebAssets::load(&backend.join("web"))?;
let library = Library::new(home.join("projects"), runtime.join("web-runs"), primary, Some(unicode))?;
serve(Some(web), Some(library), 0, None)
}
fn lock_backend(home: &Path) -> io::Result<File> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(home.join("backend.lock"))?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(std::fs::TryLockError::WouldBlock) => Err(io::Error::other(
"The Texrra desktop is already running for this Windows data directory",
)),
Err(std::fs::TryLockError::Error(error)) => Err(error),
}
}
fn configure_environment(backend: &Path, state: &Path, font_maps: &Path) -> LaunchResult<()> {
let search = env::join_paths([font_maps.as_os_str(), OsStr::new("")])?;
// These changes happen during Windows startup before any worker is started.
// The Windows environment is also thread-safe for Rust's environment API.
unsafe {
for variable in [
"TEXRRA_TEXMF",
"TEXINPUTS",
"TFMFONTS",
"VFFONTS",
"T1FONTS",
"OPENTYPEFONTS",
"TTFONTS",
"PKFONTS",
"ENCFONTS",
"TEXFORMATS",
"TEXMFCNF",
"MISCFONTS",
"SFDFONTS",
"CMAPFONTS",
"texmf_casefold_search",
"FONTCONFIG_FILE",
"FONTCONFIG_PATH",
] {
env::remove_var(variable);
}
env::set_var("TEXFONTMAPS", search);
env::set_var("TEXRRA_WINDOWS_BACKEND", backend);
env::set_var("TEXRRA_STATE_DIR", state);
env::set_var("SOURCE_DATE_EPOCH", "1783900800");
env::set_var("FORCE_SOURCE_DATE", "1");
}
Ok(())
}
fn start_lease() -> io::Result<()> {
std::thread::Builder::new()
.name("texrra-desktop-lease".into())
.spawn(|| {
let mut stdin = io::stdin().lock();
let mut buffer = [0; 32];
loop {
match stdin.read(&mut buffer) {
Ok(0) => break,
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(_) => break,
}
}
std::process::exit(0);
})?;
Ok(())
}
fn desktop_format(
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 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
}))
}
fn build_format(ini: &Path, format: &Path, roots: &[PathBuf], profile: InputProfile) -> 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()?);
request.entry = Entry::Initex;
request.input_profile = profile;
request.etex = true;
request.limits.steps = 600_000_000;
dump_format(request, Cancellation::default())?;
Ok(())
}