//! 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::{ collections::BTreeMap, env, ffi::{OsStr, OsString}, fs::{self, File, OpenOptions}, io::{self, Read}, path::{Path, PathBuf}, time::Instant, }; use texrra_engine::native::{CompileRequest, Entry, dump_bundled_format, dump_format, job_time}; use texrra_tex_core::{ execution::{Cancellation, InputProfile}, resources::WorldConfig, }; type LaunchResult = Result>; #[derive(Deserialize)] struct Bundle { schema: u32, resources_sha256: String, #[serde(default)] sha256: BTreeMap, } const MODES: [(InputProfile, &str); 2] = [ (InputProfile::TeX8Bit, "pdflatex"), (InputProfile::XeTeX, "xelatex"), ]; pub(super) fn prepare_bundle(mut arguments: impl Iterator) -> LaunchResult<()> { let usage = "native_editor --prepare-windows-formats BACKEND_DIRECTORY"; let backend = PathBuf::from(arguments.next().ok_or(usage)?); if arguments.next().is_some() || !backend.is_absolute() { return Err(usage.into()); } let backend = backend.canonicalize()?; let (roots, font_maps) = bundle_resources(&backend)?; let formats = backend.join("formats"); fs::create_dir(&formats)?; configure_environment(&backend, &formats, &font_maps)?; for (profile, name) in MODES { let directory = formats.join(name); fs::create_dir(&directory)?; let format = directory.join("latex.tfx"); let started = Instant::now(); build_format( &initialization_source(&roots, name)?, &format, &roots, profile, Some(&backend), )?; println!("Prepared {name} in {:.2}s", started.elapsed().as_secs_f64()); } Ok(()) } pub(super) fn run(mut arguments: impl Iterator) -> LaunchResult<()> { 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 || !valid_digest(&bundle.resources_sha256) { 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 (roots, font_maps) = bundle_resources(&backend)?; 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, 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?), )?; serve(Some(web), Some(library), 0, None) } fn bundle_resources(backend: &Path) -> LaunchResult<(Vec, PathBuf)> { let texmf = backend.join("texmf"); let roots = ["overlay", "dist", "var"] .map(|directory| texmf.join(directory).canonicalize()) .into_iter() .collect::>>()?; let font_maps = texmf.join("fonts").canonicalize()?; if roots .iter() .chain([&font_maps]) .any(|root| !root.is_dir() || !root.starts_with(backend)) || !font_maps.join("pdftex.map").is_file() { return Err("The Windows desktop TeX resources are incomplete".into()); } Ok((roots, font_maps)) } fn lock_backend(home: &Path) -> io::Result { let file = OpenOptions::new() .read(true) .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 valid_digest(digest: &str) -> bool { digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) } fn verify_bundled_input(backend: &Path, input: &Path, expected: &str) -> LaunchResult<()> { let canonical = input.canonicalize()?; if canonical != input || !canonical.starts_with(backend) { return Err(format!("Invalid bundled format path: {}", input.display()).into()); } let mut file = File::open(canonical)?; let mut digest = Sha256::new(); io::copy(&mut file, &mut digest)?; if !format!("{:x}", digest.finalize()).eq_ignore_ascii_case(expected) { return Err(format!("Bundled format checksum differs: {}", input.display()).into()); } Ok(()) } fn initialization_source(roots: &[PathBuf], name: &str) -> io::Result { roots[1] .join("tex/latex/tex-ini-files") .join(format!("{name}.ini")) .canonicalize() } fn desktop_format( backend: &Path, bundle: &Bundle, runtime: &Path, manifest: &Path, roots: &[PathBuf], profile: InputProfile, name: &'static str, ) -> LaunchResult { let 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, 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, 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()?); request.entry = Entry::Initex; request.input_profile = profile; request.etex = true; request.limits.steps = 600_000_000; if let Some(bundle) = bundle { dump_bundled_format(request, Cancellation::default(), bundle)?; } else { dump_format(request, Cancellation::default())?; } Ok(()) }