Use a Unicode default with project-level LaTeX compatibility

This commit is contained in:
gloamxun committed 2026-12-02 21:43:38 +08:00
1 parent 38a2a4a958
commit 81ac3ae321
11 files changed
+741 -126

No files matched your search

+155 -42
View File
@@ -1,33 +1,88 @@
use super::{
InputProfile, NativeCompiler, OpeningEditor, fs, json, projects::ProjectStore, reply,
stage_sources,
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},
time::Instant,
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 {
lock: Mutex<()>,
build: 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 {
Self {
image,
manifest,
profile,
compiler: NativeCompiler::default(),
preparation: Some(Arc::new(FormatPreparation {
lock: Mutex::new(()),
build: Box::new(build),
})),
}
}
pub(super) fn ensure(&self) -> Result<(), String> {
if let Some(preparation) = &self.preparation {
let _lock = preparation.lock.lock().unwrap();
if !self.image.is_file() {
(preparation.build)()?;
}
}
Ok(())
}
}
#[derive(Clone, Copy, serde::Serialize)]
pub(super) struct ModeChoice {
preference: CompileMode,
effective: CompileMode,
}
pub(super) struct Library {
store: ProjectStore,
format: PathBuf,
manifest: PathBuf,
primary: EditorFormat,
unicode: Option<EditorFormat>,
runs: PathBuf,
profile: InputProfile,
compiler: NativeCompiler,
}
impl Library {
pub(super) fn new(
store: PathBuf,
format: PathBuf,
manifest: PathBuf,
runs: PathBuf,
profile: InputProfile,
primary: EditorFormat,
unicode: Option<EditorFormat>,
) -> Result<Self, Box<dyn std::error::Error>> {
fs::create_dir_all(&store)?;
let store = store.canonicalize()?;
@@ -38,35 +93,40 @@ impl Library {
}
Ok(Self {
store: ProjectStore::new(store)?,
format,
manifest,
primary,
unicode,
runs,
profile,
compiler: NativeCompiler::default(),
})
}
pub(super) fn prewarm_format(&self) {
let compiler = self.compiler.clone();
let format = self.format.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(&format);
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}");
}
});
// Decode ready formats in the background. A first launch can show
// the library while the selected project's missing format is built.
for format in std::iter::once(&self.primary).chain(self.unicode.iter()) {
if !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) {
@@ -127,13 +187,41 @@ impl Library {
return;
}
};
match self.store.create_empty(&project.name) {
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());
@@ -149,16 +237,41 @@ impl Library {
.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 staged = stage_sources(
&root, &source, &self.format, &self.manifest, &run, &files, self.profile,
let mut staged = stage_sources(
&root, &source, &format.image, &format.manifest, &run, &files, format.profile,
)?;
let cache = super::preview_cache::PreviewCache::for_project(
&self.runs, &info.id, &run, &staged, &self.format, &self.manifest,
);
let compiler = self.compiler.new_session_sharing_format()
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, cache, compiler)
OpeningEditor::start(info.id, run, staged, format.clone(), choice, unchanged, compiler)
}
}