Build a standalone Windows desktop with opt-in project removal
This commit is contained in:
1 parent
2c5b9b5f10
commit
2c99cade7d
24 files changed
+1404
-168
No files matched your search
@@ -16,6 +16,8 @@ use texrra_engine::native::{CompileRequest, GeneratedArtifacts, ProjectSnapshot}
|
||||
use texrra_tex_core::resources::ResourceVersion;
|
||||
|
||||
mod cache;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
const MAX_AUX_BYTES: u64 = 2 * 1024 * 1024;
|
||||
const MAX_INPUT_BYTES: u64 = 32 * 1024 * 1024;
|
||||
@@ -381,6 +383,10 @@ fn find_style(scratch: &Path, style: &Path, roots: &[PathBuf]) -> Result<Arc<[u8
|
||||
style.display()
|
||||
));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if windows::bundled_directory().is_some() {
|
||||
return windows::find_style(style, roots);
|
||||
}
|
||||
let result = private_environment(&mut Command::new("kpsewhich"), scratch)
|
||||
.arg("--format=bst")
|
||||
.arg(style)
|
||||
@@ -438,7 +444,12 @@ fn run_bibtex(scratch: &Path) -> Result<(Vec<u8>, bool), String> {
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let mut command = Command::new("bibtex");
|
||||
let mut child = private_environment(&mut command, scratch)
|
||||
private_environment(&mut command, scratch);
|
||||
#[cfg(windows)]
|
||||
if let Some(directory) = windows::bundled_directory() {
|
||||
command = windows::bundled_command(&directory, scratch)?;
|
||||
}
|
||||
let mut child = command
|
||||
.env("BIBINPUTS", ".")
|
||||
.env("BSTINPUTS", ".")
|
||||
.arg(JOB)
|
||||
|
||||
@@ -59,7 +59,15 @@ pub(super) fn write(path: &Path, key: &[u8; 32], output: &[u8]) -> io::Result<()
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu")))]
|
||||
#[cfg(windows)]
|
||||
pub(super) fn tool_identity(_scratch: &Path) -> Option<[u8; 32]> {
|
||||
super::windows::tool_identity()
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
windows,
|
||||
all(target_os = "linux", target_arch = "x86_64", target_env = "gnu")
|
||||
)))]
|
||||
pub(super) fn tool_identity(_scratch: &Path) -> Option<[u8; 32]> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
use super::{MAX_INPUT_BYTES, bib_error, private_environment, read_limited, stage};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
env, fs,
|
||||
os::windows::process::CommandExt,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
|
||||
pub(super) fn bundled_directory() -> Option<PathBuf> {
|
||||
let backend = PathBuf::from(env::var_os("TEXRRA_WINDOWS_BACKEND")?);
|
||||
if !backend.is_absolute()
|
||||
|| env::current_exe().ok()?.canonicalize().ok()? != backend.join("bin/native_editor.exe")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(backend.join("tools/bibtex"))
|
||||
}
|
||||
|
||||
pub(super) fn tool_identity() -> Option<[u8; 32]> {
|
||||
let directory = bundled_directory()?;
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(b"texrra Windows BibTeX 1");
|
||||
for name in [
|
||||
"bibtex.exe",
|
||||
"kpsewhich.exe",
|
||||
"kpathsealibw64.dll",
|
||||
"msvcr100.dll",
|
||||
"texmf.cnf",
|
||||
] {
|
||||
let file = directory.join(name);
|
||||
if !fs::symlink_metadata(&file).ok()?.is_file() {
|
||||
return None;
|
||||
}
|
||||
let bytes = read_limited(&file, 16 * 1024 * 1024).ok()?;
|
||||
super::cache::field(&mut hash, name.as_bytes());
|
||||
super::cache::field(&mut hash, &bytes);
|
||||
}
|
||||
Some(hash.finalize().into())
|
||||
}
|
||||
|
||||
pub(super) fn bundled_command(directory: &Path, scratch: &Path) -> Result<Command, String> {
|
||||
// Keep Kpathsea's search relative to its working directory. The tool
|
||||
// never needs to interpret a canonical Windows path or a user search list.
|
||||
let configuration = read_limited(&directory.join("texmf.cnf"), 64 * 1024).map_err(bib_error)?;
|
||||
stage(scratch, Path::new("texmf.cnf"), &configuration).map_err(bib_error)?;
|
||||
let executable = win32_path(&directory.join("bibtex.exe"))?;
|
||||
let working_directory = win32_path(scratch)?;
|
||||
let mut command = Command::new(executable);
|
||||
private_environment(&mut command, &working_directory)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.env_remove("PATH")
|
||||
.env("HOME", ".")
|
||||
.env("TEXMFHOME", ".")
|
||||
.env("TEXMFVAR", ".")
|
||||
.env("TEXMFCONFIG", ".")
|
||||
.env("TEXMFCNF", ".");
|
||||
if let Some(root) = env::var_os("SystemRoot") {
|
||||
command.env("SystemRoot", root);
|
||||
}
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
// The packaged Kpathsea rejects the verbatim prefix in the executable
|
||||
// spelling it receives from the Windows process launcher.
|
||||
fn win32_path(path: &Path) -> Result<PathBuf, String> {
|
||||
let value = path.to_str().ok_or("BibTeX needs Unicode Windows paths")?;
|
||||
if let Some(rest) = value.strip_prefix(r"\\?\UNC\") {
|
||||
return Ok(format!(r"\\{rest}").into());
|
||||
}
|
||||
Ok(value.strip_prefix(r"\\?\").unwrap_or(value).into())
|
||||
}
|
||||
|
||||
pub(super) fn find_style(style: &Path, roots: &[PathBuf]) -> Result<Arc<[u8]>, String> {
|
||||
for root in roots {
|
||||
let style_root = root.join("bibtex/bst");
|
||||
let mut directories = vec![style_root];
|
||||
while let Some(directory) = directories.pop() {
|
||||
let candidate = directory.join(style);
|
||||
if candidate.is_file() {
|
||||
let path = candidate.canonicalize().map_err(bib_error)?;
|
||||
if path.starts_with(root) {
|
||||
return read_limited(&path, MAX_INPUT_BYTES)
|
||||
.map(Into::into)
|
||||
.map_err(bib_error);
|
||||
}
|
||||
}
|
||||
// Bundled resources are ordinary files. Keep root priority and
|
||||
// a stable first match, without following directory links.
|
||||
if let Ok(entries) = fs::read_dir(directory) {
|
||||
let mut children = entries
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
|
||||
.map(|entry| entry.path())
|
||||
.collect::<Vec<_>>();
|
||||
children.sort_unstable();
|
||||
directories.extend(children.into_iter().rev());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(format!("BibTeX style missing: {}", style.display()))
|
||||
}
|
||||
@@ -37,6 +37,8 @@ mod resource_capture;
|
||||
mod saved_project;
|
||||
mod text_layer;
|
||||
mod thread_usage;
|
||||
#[cfg(windows)]
|
||||
mod windows_format;
|
||||
|
||||
const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024;
|
||||
const PAGE: &str = include_str!("index.html");
|
||||
@@ -275,6 +277,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
std::process::exit(status);
|
||||
}
|
||||
let mut args = std::env::args_os().skip(1).peekable();
|
||||
#[cfg(windows)]
|
||||
if args.next_if(|arg| arg == "--windows-desktop").is_some() {
|
||||
return windows_format::run(args).map_err(|error| {
|
||||
let detail = error.to_string().replace(['\r', '\n'], " ");
|
||||
println!("Texrra desktop error {detail}");
|
||||
error
|
||||
});
|
||||
}
|
||||
let usage = "native_editor [--input-profile PROFILE] [--web-dir DIR] [--source-root DIR] SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...] or native_editor [--input-profile PROFILE] --web-dir DIR --projects STORE FORMAT FORMAT_RESOURCES RUNS [PORT]";
|
||||
let input_profile = if args.next_if(|arg| arg == "--input-profile").is_some() {
|
||||
match args.next().as_deref().and_then(std::ffi::OsStr::to_str) {
|
||||
@@ -337,6 +347,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let editor = finish_prepare(staged, &run, &compiler, None, None)?;
|
||||
(port, Some(EditorSession::new(run, editor, compiler, None)))
|
||||
};
|
||||
serve(web, library, port, session)
|
||||
}
|
||||
|
||||
fn serve(
|
||||
web: Option<WebAssets>,
|
||||
library: Option<library::Library>,
|
||||
port: u16,
|
||||
session: Option<EditorSession>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut session = session.map(|session| Arc::new(Mutex::new(session)));
|
||||
let mut opening: Option<OpeningEditor> = None;
|
||||
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
Reference in new issue
Block a user