Build a standalone Windows desktop with opt-in project removal

This commit is contained in:
gloamxun committed 2026-12-02 18:20:38 +08:00
1 parent 2c5b9b5f10
commit 2c99cade7d
24 files changed
+1404 -168

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
//! Bootstrap the installed Windows editor from the packaged TeX resources.
use crate::{WebAssets, library::Library, serve};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::{
env,
ffi::{OsStr, OsString},
fs::{self, File, OpenOptions},
io::{self, Read, Write},
path::{Path, PathBuf},
};
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 format = runtime.join("latex.tfx");
if !format.is_file() {
let ini = roots[1].join("tex/latex/tex-ini-files/pdflatex.ini");
build_format(&ini, &runtime, &format, &roots)?;
}
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 web = WebAssets::load(&backend.join("web"))?;
let library = Library::new(
home.join("projects"),
format.canonicalize()?,
manifest.canonicalize()?,
runtime.join("web-runs"),
InputProfile::TeX8Bit,
)?;
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 build_format(ini: &Path, runtime: &Path, format: &Path, roots: &[PathBuf]) -> LaunchResult<()> {
let ini = ini.canonicalize()?;
let world = WorldConfig::from_environment(runtime, roots.to_vec())?;
let mut request = CompileRequest::new(world, ini, format, job_time()?);
request.entry = Entry::Initex;
request.etex = true;
request.limits.steps = 600_000_000;
println!("Texrra desktop preparing format");
io::stdout().flush()?;
dump_format(request, Cancellation::default())?;
Ok(())
}