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

325 lines
11 KiB
Rust

use super::{
InputProfile, NativeCompiler, OpeningEditor, copy_with_date, fs, json,
projects::{CompileMode, ProjectStore, resolve_compile_mode},
reply, stage_sources,
};
use std::{
collections::BTreeMap,
io::{ErrorKind, Read},
path::{Path, PathBuf},
sync::{Arc, Mutex},
time::{Instant, SystemTime},
};
use tiny_http::Request;
pub(super) const SCRIPT: &str = include_str!("library.js");
const MAX_ZIP_UPLOAD: u64 = 64 * 1024 * 1024;
#[derive(Clone)]
pub(super) struct EditorFormat {
pub(super) image: PathBuf,
pub(super) manifest: PathBuf,
pub(super) profile: InputProfile,
preparation: Option<Arc<FormatPreparation>>,
compiler: NativeCompiler,
}
struct FormatPreparation {
ready: Mutex<bool>,
prepare: Box<dyn Fn() -> Result<(), String> + Send + Sync>,
}
impl EditorFormat {
pub(super) fn prepared(image: PathBuf, manifest: PathBuf, profile: InputProfile) -> Self {
Self { image, manifest, profile, preparation: None, compiler: NativeCompiler::default() }
}
#[cfg(windows)]
pub(super) fn lazy(
image: PathBuf,
manifest: PathBuf,
profile: InputProfile,
build: impl Fn() -> Result<(), String> + Send + Sync + 'static,
) -> Self {
let output = image.clone();
Self::prepare_on_open(image, manifest, profile, move || {
if !output.is_file() {
build()?;
}
Ok(())
})
}
#[cfg(windows)]
pub(super) fn prepare_on_open(
image: PathBuf,
manifest: PathBuf,
profile: InputProfile,
prepare: impl Fn() -> Result<(), String> + Send + Sync + 'static,
) -> Self {
let mut format = Self::prepared(image, manifest, profile);
format.preparation = Some(Arc::new(FormatPreparation {
ready: Mutex::new(false),
prepare: Box::new(prepare),
}));
format
}
pub(super) fn ensure(&self) -> Result<(), String> {
if let Some(preparation) = &self.preparation {
let mut ready = preparation.ready.lock().unwrap();
if !*ready || !self.image.is_file() {
(preparation.prepare)()?;
*ready = true;
}
}
Ok(())
}
}
#[derive(Clone, Copy, serde::Serialize)]
pub(super) struct ModeChoice {
preference: CompileMode,
effective: CompileMode,
}
pub(super) struct Library {
store: ProjectStore,
primary: EditorFormat,
unicode: Option<EditorFormat>,
runs: PathBuf,
}
impl Library {
pub(super) fn new(
store: PathBuf,
runs: PathBuf,
primary: EditorFormat,
unicode: Option<EditorFormat>,
) -> Result<Self, Box<dyn std::error::Error>> {
fs::create_dir_all(&store)?;
let store = store.canonicalize()?;
fs::create_dir_all(&runs)?;
let runs = runs.canonicalize()?;
if runs.starts_with(&store) || store.starts_with(&runs) {
return Err("Project and compilation directories must be separate".into());
}
Ok(Self {
store: ProjectStore::new(store)?,
primary,
unicode,
runs,
})
}
pub(super) fn prewarm_format(&self) {
// Decode caller-supplied formats in the background. Windows bundles
// defer verification and decoding until a project selects a profile.
for format in std::iter::once(&self.primary).chain(self.unicode.iter()) {
if format.preparation.is_some() || !format.image.is_file() {
continue;
}
let compiler = format.compiler.clone();
let image = format.image.clone();
let _ = std::thread::Builder::new()
.name("texrra-prewarm-format".into())
.spawn(move || {
let trace = std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE")
.is_some_and(|value| value == "1");
let started = Instant::now();
let result = compiler.prewarm_format(&image);
if trace {
eprintln!("Texrra editor preparation {}", json!({
"stage": "prewarm-format",
"ms": started.elapsed().as_secs_f64() * 1000.0,
"ok": result.is_ok(),
}));
}
if let Err(error) = result {
eprintln!("Editor format prewarm: {error}");
}
});
}
}
pub(super) fn list(&self, request: Request) {
match self.store.list() {
Ok(projects) => reply(request, 200, json!({"projects": projects})),
Err(error) => reply(request, 500, json!({"error": error})),
}
}
pub(super) fn import(&self, mut request: Request) {
if !request.headers().iter().any(|header| {
header.field.equiv("Content-Type")
&& header.value.as_str().split(';').next() == Some("application/zip")
}) {
reply(request, 415, json!({"error": "Expected a ZIP archive"}));
return;
}
let name = project_name(&request);
let mut bytes = Vec::new();
if let Err(error) = request
.as_reader()
.take(MAX_ZIP_UPLOAD + 1)
.read_to_end(&mut bytes)
{
reply(request, 400, json!({"error": error.to_string()}));
return;
}
if bytes.len() as u64 > MAX_ZIP_UPLOAD {
reply(request, 413, json!({"error": "ZIP upload exceeds 64 MB"}));
return;
}
match self.store.create_from_zip(&name, &bytes) {
Ok(project) => reply(request, 201, json!(project)),
Err(error) => reply(request, 422, json!({"error": error})),
}
}
pub(super) fn create(&self, mut request: Request) {
#[derive(serde::Deserialize)]
struct NewProject {
name: String,
}
if !request.headers().iter().any(|header| {
header.field.equiv("Content-Type")
&& header.value.as_str().split(';').next() == Some("application/json")
}) {
reply(
request,
415,
json!({"error": "Expected JSON project details"}),
);
return;
}
let project: NewProject = match super::read_json(&mut request) {
Ok(value) => value,
Err(error) => {
reply(request, 400, json!({"error": error}));
return;
}
};
let created = if self.unicode.is_some() {
self.store.create_empty_with_mode(&project.name, CompileMode::Unicode)
} else {
self.store.create_empty(&project.name)
};
match created {
Ok(project) => reply(request, 201, json!(project)),
Err(error) => reply(request, 422, json!({"error": error})),
}
}
pub(super) fn open(&self, id: &str) -> Result<OpeningEditor, Box<dyn std::error::Error>> {
self.open_with_sources(id, None, BTreeMap::new())
}
pub(super) fn change_mode(
&self,
id: &str,
mode: CompileMode,
edits: BTreeMap<String, String>,
) -> Result<OpeningEditor, Box<dyn std::error::Error>> {
if self.unicode.is_none() {
return Err("This installation has a single compilation mode".into());
}
let opened = self.open_with_sources(id, Some(mode), edits)?;
self.store.set_compile_mode(id, mode)?;
Ok(opened)
}
fn open_with_sources(
&self,
id: &str,
preference: Option<CompileMode>,
edits: BTreeMap<String, String>,
) -> Result<OpeningEditor, Box<dyn std::error::Error>> {
let root = self.store.project_dir(id)?;
if fs::symlink_metadata(&root)?.file_type().is_symlink() {
return Err("The project directory must be a local working copy".into());
}
let info = self.store.info(id)?;
if info.main_file.is_empty() {
return Err("The project does not contain a TeX entry file".into());
}
let source = self.store.file_path(id, &info.main_file)?.canonicalize()?;
let files = info
.files
.iter()
.filter(|file| file.path != info.main_file)
.map(|file| PathBuf::from(&file.path))
.collect::<Vec<_>>();
let mut format = &self.primary;
let mut choice = None;
if let Some(unicode) = &self.unicode {
let preference = preference.unwrap_or(info.compile_mode);
let effective = match preference {
CompileMode::Auto => match edits.get(&info.main_file) {
Some(source) => resolve_compile_mode(source),
None => resolve_compile_mode(&fs::read_to_string(&source)?),
},
selected => selected,
};
if effective == CompileMode::Unicode {
format = unicode;
}
choice = Some(ModeChoice { preference, effective });
}
let run = fresh_run(&self.runs, id)?;
let mut staged = stage_sources(
&root, &source, &format.image, &format.manifest, &run, &files, format.profile,
)?;
let unchanged = edits.iter().all(|(name, value)| {
staged.editable.get(name).and_then(|path| staged.files.get(path))
.is_some_and(|bytes| bytes.as_ref() == value.as_bytes())
});
for (name, value) in edits {
let path = staged.editable.get(&name).ok_or("Unknown source file")?;
if staged.files.get(path).is_some_and(|bytes| bytes.as_ref() == value.as_bytes()) {
continue;
}
copy_with_date(path, value.as_bytes(), Some(SystemTime::now()), &mut staged.dates)?;
staged.files.insert(path.clone(), Arc::from(value.into_bytes()));
}
let compiler = format.compiler.new_session_sharing_format()
.with_automatic_entry_checkpoints();
OpeningEditor::start(info.id, run, staged, format.clone(), choice, unchanged, compiler)
}
}
fn fresh_run(parent: &Path, id: &str) -> std::io::Result<PathBuf> {
for index in 1.. {
let candidate = parent.join(format!("{id}-{}-{index}", std::process::id()));
match fs::create_dir(&candidate) {
Ok(()) => return Ok(candidate),
Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
unreachable!()
}
fn project_name(request: &Request) -> String {
let name = request
.url()
.split_once('?')
.and_then(|(_, query)| query.split('&').find_map(|pair| pair.strip_prefix("name=")))
.unwrap_or("Project");
let mut bytes = Vec::with_capacity(name.len());
let mut input = name.as_bytes().iter().copied();
while let Some(byte) = input.next() {
match byte {
b'%' => {
let hex = |byte: u8| char::from(byte).to_digit(16);
if let Some(value) = input.next().and_then(hex).zip(input.next().and_then(hex)) {
bytes.push((value.0 * 16 + value.1) as u8);
}
}
b'+' => bytes.push(b' '),
_ => bytes.push(byte),
}
}
String::from_utf8_lossy(&bytes).into_owned()
}