Use a Unicode default with project-level LaTeX compatibility
This commit is contained in:
1 parent
38a2a4a958
commit
81ac3ae321
11 files changed
+741
-126
No files matched your search
+122
-17
@@ -20,10 +20,13 @@ const fileViews = new Map();
|
||||
const EDIT_IDLE_MS = 70;
|
||||
const TEXT_LAYER_IDLE_MS = 180;
|
||||
const PREVIEW_SOCKET_RETRY_MS = 1000;
|
||||
const COMPILE_MODE_LABELS = { unicode: "Unicode", pdflatex: "pdfLaTeX" };
|
||||
let files;
|
||||
let projectFiles = [];
|
||||
let activeFile;
|
||||
let preparingProject = false;
|
||||
let compileMode;
|
||||
let cachedPreviewRequest;
|
||||
let sequence = 0;
|
||||
let publishedRevision = null;
|
||||
let visibleRevision = null;
|
||||
@@ -54,6 +57,16 @@ recompile.disabled = true;
|
||||
previewView.toolbar.prepend(recompile);
|
||||
recompile.addEventListener("click", manualCompile);
|
||||
|
||||
const compileModeSelect = document.createElement("select");
|
||||
compileModeSelect.id = "compile-mode";
|
||||
compileModeSelect.setAttribute("aria-label", "编译模式");
|
||||
compileModeSelect.hidden = true;
|
||||
for (const [mode, label] of Object.entries({ auto: "自动", ...COMPILE_MODE_LABELS })) {
|
||||
compileModeSelect.add(new Option(label, mode));
|
||||
}
|
||||
previewView.toolbar.prepend(compileModeSelect);
|
||||
compileModeSelect.addEventListener("change", switchCompileMode);
|
||||
|
||||
const cachedPreviewStatus = document.createElement("span");
|
||||
cachedPreviewStatus.id = "cached-preview-status";
|
||||
cachedPreviewStatus.className = "texrra-preview-history";
|
||||
@@ -188,25 +201,29 @@ function restorePublishedPages() {
|
||||
}
|
||||
|
||||
async function showCachedPreview() {
|
||||
const request = new AbortController();
|
||||
cachedPreviewRequest = request;
|
||||
const canDisplay = () => !request.signal.aborted && visibleRevision === null;
|
||||
const frames = [];
|
||||
try {
|
||||
const response = await fetch(projectPrefix + "/cached-preview");
|
||||
if (!response.ok || visibleRevision !== null) return;
|
||||
const response = await fetch(projectPrefix + "/cached-preview", { signal: request.signal });
|
||||
if (!response.ok || !canDisplay()) return;
|
||||
const { page_count, pages: savedPages } = await response.json();
|
||||
if (visibleRevision !== null || !Array.isArray(savedPages) || savedPages.length === 0
|
||||
if (!canDisplay() || !Array.isArray(savedPages) || savedPages.length === 0
|
||||
|| savedPages.length !== page_count || savedPages.some((page, index) =>
|
||||
page?.index !== index || typeof page.svg !== "string")) return;
|
||||
const first = pageFrame(savedPages[0]);
|
||||
frames.push(first);
|
||||
// The rest of the saved document can decode after the first page is ready.
|
||||
await first.querySelector("img").decode();
|
||||
if (visibleRevision !== null) return;
|
||||
if (!canDisplay()) return;
|
||||
for (const page of savedPages.slice(1)) frames.push(pageFrame(page));
|
||||
pages.replaceChildren(...frames);
|
||||
cachedPreviewStatus.hidden = false;
|
||||
} catch {
|
||||
// Cache errors do not interrupt the live compile.
|
||||
} finally {
|
||||
if (cachedPreviewRequest === request) cachedPreviewRequest = undefined;
|
||||
revokeDetached(frames);
|
||||
}
|
||||
}
|
||||
@@ -551,6 +568,102 @@ async function saveSources() {
|
||||
}
|
||||
}
|
||||
|
||||
function showCompileMode(mode) {
|
||||
if (!mode || !["auto", "unicode", "pdflatex"].includes(mode.preference)
|
||||
|| !Object.hasOwn(COMPILE_MODE_LABELS, mode.effective)) {
|
||||
compileMode = undefined;
|
||||
compileModeSelect.hidden = true;
|
||||
return;
|
||||
}
|
||||
compileMode = mode;
|
||||
compileModeSelect.options[0].textContent = "自动(" + COMPILE_MODE_LABELS[mode.effective] + ")";
|
||||
compileModeSelect.value = mode.preference;
|
||||
compileModeSelect.hidden = false;
|
||||
}
|
||||
|
||||
async function finishProjectOpening(project) {
|
||||
if (project.preparing === true) {
|
||||
status.textContent = project.building_format === true
|
||||
? "首次准备编译格式,可能需要几分钟"
|
||||
: "正在准备编译资源";
|
||||
const ready = await fetch(projectPrefix + "/ready");
|
||||
if (!ready.ok) {
|
||||
const failure = await ready.json();
|
||||
throw new Error(failure.error ?? "准备项目失败");
|
||||
}
|
||||
}
|
||||
preparingProject = false;
|
||||
save.disabled = false;
|
||||
recompile.disabled = false;
|
||||
advertisePreviewSocket(project.preview_socket);
|
||||
queueCompile(true);
|
||||
}
|
||||
|
||||
async function switchCompileMode() {
|
||||
const mode = compileModeSelect.value;
|
||||
const previousMode = compileMode;
|
||||
if (!previousMode || mode === previousMode.preference) return;
|
||||
|
||||
const wasPreparing = preparingProject;
|
||||
const previousSocketUrl = previewSocketUrl;
|
||||
preparingProject = true;
|
||||
recompile.disabled = true;
|
||||
compileModeSelect.disabled = true;
|
||||
invalidatePreview();
|
||||
if (composing) {
|
||||
source.blur();
|
||||
composing = false;
|
||||
}
|
||||
recordEdit();
|
||||
|
||||
// Keep the last committed pages on screen until this engine produces a
|
||||
// full update. Old revision identifiers belong to the previous session.
|
||||
restorePublishedPages();
|
||||
cachedPreviewRequest?.abort();
|
||||
clearTimeout(textLayerTimer);
|
||||
textLayerRequest?.abort();
|
||||
textLayerRevision = undefined;
|
||||
publishedRevision = null;
|
||||
visibleRevision = null;
|
||||
delete document.body.dataset.visibleRevision;
|
||||
cachedPreviewStatus.hidden = pages.childElementCount === 0;
|
||||
pdf.hidden = true;
|
||||
pdf.removeAttribute("href");
|
||||
previewSocketUrl = undefined;
|
||||
if (previewSocket) retirePreviewSocket(previewSocket);
|
||||
previewSocketRetryAt = 0;
|
||||
errorPanel.hidden = true;
|
||||
status.textContent = "正在切换编译模式";
|
||||
|
||||
let switched = false;
|
||||
try {
|
||||
const response = await fetch(projectPrefix + "/compile-mode", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ mode, files: Object.fromEntries(edits) }),
|
||||
});
|
||||
const project = await response.json();
|
||||
if (!response.ok) throw new Error(project.error ?? "无法切换编译模式");
|
||||
switched = true;
|
||||
// An old HTTP preview may still finish. Never reuse its sequence number
|
||||
// if the new session starts counting revisions from zero again.
|
||||
sequence = Math.max(sequence, project.sequence);
|
||||
showCompileMode(project.compile_mode);
|
||||
await finishProjectOpening(project);
|
||||
} catch (failure) {
|
||||
if (!switched) {
|
||||
showCompileMode(previousMode);
|
||||
preparingProject = wasPreparing;
|
||||
recompile.disabled = wasPreparing;
|
||||
previewSocketUrl = previousSocketUrl;
|
||||
connectPreviewSocket();
|
||||
}
|
||||
showError(failure.message);
|
||||
} finally {
|
||||
compileModeSelect.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openProject() {
|
||||
try {
|
||||
const response = await fetch(projectPrefix + "/project");
|
||||
@@ -580,6 +693,8 @@ async function openProject() {
|
||||
addFormulaButtons();
|
||||
sequence = project.sequence;
|
||||
preparingProject = project.preparing === true;
|
||||
showCompileMode(project.compile_mode);
|
||||
compileModeSelect.disabled = preparingProject;
|
||||
recompile.title = "重新编译主文件 " + project.name + "(Ctrl/Cmd+Enter)";
|
||||
save.addEventListener("click", saveSources);
|
||||
document.addEventListener("keydown", (event) => {
|
||||
@@ -624,21 +739,11 @@ async function openProject() {
|
||||
indentSource();
|
||||
});
|
||||
if (project.cached_preview === true) void showCachedPreview();
|
||||
if (preparingProject) {
|
||||
status.textContent = "正在准备编译资源";
|
||||
const ready = await fetch(projectPrefix + "/ready");
|
||||
if (!ready.ok) {
|
||||
const failure = await ready.json();
|
||||
throw new Error(failure.error ?? "准备项目失败");
|
||||
}
|
||||
preparingProject = false;
|
||||
}
|
||||
save.disabled = false;
|
||||
recompile.disabled = false;
|
||||
advertisePreviewSocket(project.preview_socket);
|
||||
queueCompile(true);
|
||||
await finishProjectOpening(project);
|
||||
} catch (failure) {
|
||||
showError(failure.message);
|
||||
} finally {
|
||||
compileModeSelect.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
//! Loopback editor for comparing actual native page updates with full jobs.
|
||||
use library::{EditorFormat, ModeChoice};
|
||||
use projects::CompileMode;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
@@ -61,6 +63,13 @@ struct Save {
|
||||
files: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ChangeMode {
|
||||
mode: CompileMode,
|
||||
#[serde(default)]
|
||||
files: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
enum PreviewReply {
|
||||
Http(Request),
|
||||
Socket(mpsc::Sender<(u16, Value)>),
|
||||
@@ -285,7 +294,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
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 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 [--unicode-format FORMAT FORMAT_RESOURCES] [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) {
|
||||
Some("tex8bit") => InputProfile::TeX8Bit,
|
||||
@@ -313,12 +322,23 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let manifest = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let runs = args.next().ok_or(usage)?;
|
||||
let unicode = if args.next_if(|arg| arg == Path::new("--unicode-format")).is_some() {
|
||||
if input_profile != InputProfile::TeX8Bit {
|
||||
return Err("The secondary Unicode format requires a pdfLaTeX primary format".into());
|
||||
}
|
||||
Some(EditorFormat::prepared(
|
||||
args.next().ok_or(usage)?.canonicalize()?,
|
||||
args.next().ok_or(usage)?.canonicalize()?,
|
||||
InputProfile::XeTeX,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(library::Library::new(
|
||||
store,
|
||||
format,
|
||||
manifest,
|
||||
runs,
|
||||
input_profile,
|
||||
EditorFormat::prepared(format, manifest, input_profile),
|
||||
unicode,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
@@ -454,6 +474,37 @@ fn serve(
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if rest == "compile-mode" && request.method() == &Method::Post {
|
||||
if !project_open && pending.is_none() {
|
||||
reply(request, 409, json!({"error": "The project is no longer open. Reload to reopen it."}));
|
||||
continue;
|
||||
}
|
||||
let mut request = request;
|
||||
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 compilation settings"}));
|
||||
continue;
|
||||
}
|
||||
let change: ChangeMode = match read_json(&mut request) {
|
||||
Ok(change) => change,
|
||||
Err(error) => {
|
||||
reply(request, 400, json!({"error": error}));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match library.change_mode(id, change.mode, change.files) {
|
||||
Ok(next) => {
|
||||
let payload = next.sources.clone();
|
||||
session = None;
|
||||
opening = Some(next);
|
||||
reply(request, 200, payload);
|
||||
}
|
||||
Err(error) => reply(request, 422, json!({"error": error.to_string()})),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if request.method() == &Method::Get {
|
||||
match (rest, pending) {
|
||||
("project", Some(opening)) => {
|
||||
@@ -529,6 +580,7 @@ fn serve(
|
||||
compiler,
|
||||
cache,
|
||||
first_preview_revision,
|
||||
mode_choice,
|
||||
queue,
|
||||
save_number,
|
||||
editor,
|
||||
@@ -559,6 +611,9 @@ fn serve(
|
||||
let mut payload = project_payload(
|
||||
run, entry, declared, files, queue.current.load(Ordering::Acquire), id.as_deref(),
|
||||
)?;
|
||||
if let Some(choice) = mode_choice {
|
||||
payload["compile_mode"] = json!(choice);
|
||||
}
|
||||
if cache.as_ref().is_some_and(preview_cache::PreviewCache::exists) {
|
||||
payload["cached_preview"] = json!(true);
|
||||
}
|
||||
@@ -733,14 +788,23 @@ impl OpeningEditor {
|
||||
id: String,
|
||||
run: PathBuf,
|
||||
staged: StagedProject,
|
||||
cache: Option<preview_cache::PreviewCache>,
|
||||
format: EditorFormat,
|
||||
mode_choice: Option<ModeChoice>,
|
||||
cacheable: bool,
|
||||
compiler: NativeCompiler,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let cache = cacheable.then(|| initial_preview_cache(&id, &run, &staged, &format)).flatten();
|
||||
let files = staged.editable.iter().filter_map(|(name, path)| {
|
||||
staged.files.get(path).map(|bytes| (name.as_str(), bytes.as_ref()))
|
||||
});
|
||||
let mut sources = project_payload(&run, &staged.entry, &staged.declared, files, 1, Some(&id))?;
|
||||
sources["preparing"] = json!(true);
|
||||
if !format.image.is_file() {
|
||||
sources["building_format"] = json!(true);
|
||||
}
|
||||
if let Some(choice) = mode_choice {
|
||||
sources["compile_mode"] = json!(choice);
|
||||
}
|
||||
if cache.as_ref().is_some_and(preview_cache::PreviewCache::exists) {
|
||||
sources["cached_preview"] = json!(true);
|
||||
}
|
||||
@@ -758,19 +822,38 @@ impl OpeningEditor {
|
||||
let superseded = opening.superseded.clone();
|
||||
let cache = opening.cache.clone();
|
||||
std::thread::Builder::new().name("texrra-open-project".into()).spawn(move || {
|
||||
let result = finish_prepare(staged, &run, &compiler, Some(&superseded), Some(&id))
|
||||
.map(|editor| {
|
||||
let mut session = EditorSession::new(run, editor, compiler, cache);
|
||||
session.id = Some(id);
|
||||
Arc::new(Mutex::new(session))
|
||||
})
|
||||
.map_err(|error| error.to_string());
|
||||
let result = (|| {
|
||||
format.ensure()?;
|
||||
if superseded.load(Ordering::Acquire) {
|
||||
return Err("The project has closed".to_owned());
|
||||
}
|
||||
let cache = cache.or_else(|| {
|
||||
cacheable.then(|| initial_preview_cache(&id, &run, &staged, &format)).flatten()
|
||||
});
|
||||
let editor = finish_prepare(staged, &run, &compiler, Some(&superseded), Some(&id))
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut session = EditorSession::new(run, editor, compiler, cache);
|
||||
session.id = Some(id);
|
||||
session.mode_choice = mode_choice;
|
||||
Ok(Arc::new(Mutex::new(session)))
|
||||
})();
|
||||
let _ = ready.set(result);
|
||||
})?;
|
||||
Ok(opening)
|
||||
}
|
||||
}
|
||||
|
||||
fn initial_preview_cache(
|
||||
id: &str,
|
||||
run: &Path,
|
||||
staged: &StagedProject,
|
||||
format: &EditorFormat,
|
||||
) -> Option<preview_cache::PreviewCache> {
|
||||
preview_cache::PreviewCache::for_project(
|
||||
run.parent()?, id, run, staged, &format.image, &format.manifest,
|
||||
)
|
||||
}
|
||||
|
||||
impl Drop for OpeningEditor {
|
||||
fn drop(&mut self) {
|
||||
if self.ready.get().is_none() {
|
||||
@@ -807,6 +890,7 @@ fn project_payload<'a>(
|
||||
|
||||
struct EditorSession {
|
||||
id: Option<String>,
|
||||
mode_choice: Option<ModeChoice>,
|
||||
cache: Option<preview_cache::PreviewCache>,
|
||||
run: PathBuf,
|
||||
compiler: NativeCompiler,
|
||||
@@ -845,6 +929,7 @@ impl EditorSession {
|
||||
});
|
||||
Self {
|
||||
id: None,
|
||||
mode_choice: None,
|
||||
cache,
|
||||
run,
|
||||
compiler,
|
||||
|
||||
@@ -87,8 +87,13 @@ impl PreviewCache {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let filename = match staged.options.input_profile {
|
||||
super::InputProfile::TeX8Bit => format!("{id}.preview"),
|
||||
super::InputProfile::UnicodeScalar => format!("{id}.unicode-scalar.preview"),
|
||||
super::InputProfile::XeTeX => format!("{id}.unicode.preview"),
|
||||
};
|
||||
Some(Self(Arc::new(CacheEntry {
|
||||
path: runs.join(".cached-previews").join(format!("{id}.preview")),
|
||||
path: runs.join(".cached-previews").join(filename),
|
||||
key: key.finalize().into(),
|
||||
originals,
|
||||
})))
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
margin-bottom: .65rem;
|
||||
}
|
||||
|
||||
.texrra-preview-controls button {
|
||||
.texrra-preview-controls :is(button, select) {
|
||||
min-width: 1.9rem;
|
||||
min-height: 1.9rem;
|
||||
padding: .15rem .45rem;
|
||||
@@ -41,12 +41,12 @@
|
||||
background: #eaf1f7;
|
||||
}
|
||||
|
||||
.texrra-preview-controls button:focus-visible {
|
||||
.texrra-preview-controls :is(button, select):focus-visible {
|
||||
outline: 2px solid #1972a4;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.texrra-preview-controls button:disabled {
|
||||
.texrra-preview-controls :is(button, select):disabled {
|
||||
opacity: .48;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! Bootstrap the installed Windows editor from the packaged TeX resources.
|
||||
use crate::{WebAssets, library::Library, serve};
|
||||
use crate::{WebAssets, library::{EditorFormat, Library}, serve};
|
||||
use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
env,
|
||||
ffi::{OsStr, OsString},
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{self, Read, Write},
|
||||
io::{self, Read},
|
||||
path::{Path, PathBuf},
|
||||
time::Instant,
|
||||
};
|
||||
use texrra_engine::native::{CompileRequest, Entry, dump_format, job_time};
|
||||
use texrra_tex_core::{
|
||||
@@ -76,24 +77,16 @@ pub(super) fn run(mut arguments: impl Iterator<Item = OsString>) -> LaunchResult
|
||||
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 manifest = manifest.canonicalize()?;
|
||||
let primary = desktop_format(&runtime, &manifest, &roots, InputProfile::TeX8Bit, "pdflatex")?;
|
||||
let unicode = desktop_format(&runtime, &manifest, &roots, InputProfile::XeTeX, "xelatex")?;
|
||||
let web = WebAssets::load(&backend.join("web"))?;
|
||||
let library = Library::new(
|
||||
home.join("projects"),
|
||||
format.canonicalize()?,
|
||||
manifest.canonicalize()?,
|
||||
runtime.join("web-runs"),
|
||||
InputProfile::TeX8Bit,
|
||||
)?;
|
||||
let library = Library::new(home.join("projects"), runtime.join("web-runs"), primary, Some(unicode))?;
|
||||
serve(Some(web), Some(library), 0, None)
|
||||
}
|
||||
|
||||
@@ -167,15 +160,41 @@ fn start_lease() -> io::Result<()> {
|
||||
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())?;
|
||||
fn desktop_format(
|
||||
runtime: &Path,
|
||||
manifest: &Path,
|
||||
roots: &[PathBuf],
|
||||
profile: InputProfile,
|
||||
name: &'static str,
|
||||
) -> LaunchResult<EditorFormat> {
|
||||
let ini = roots[1].join("tex/latex/tex-ini-files").join(format!("{name}.ini")).canonicalize()?;
|
||||
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).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) -> 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;
|
||||
println!("Texrra desktop preparing format");
|
||||
io::stdout().flush()?;
|
||||
dump_format(request, Cancellation::default())?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user