diff --git a/desktop/build-windows-backend.py b/desktop/build-windows-backend.py index 35b8c92..7a12f3e 100644 --- a/desktop/build-windows-backend.py +++ b/desktop/build-windows-backend.py @@ -5,7 +5,7 @@ import argparse import hashlib import json import lzma -from pathlib import Path +from pathlib import Path, PurePosixPath import shutil import struct import tarfile @@ -18,6 +18,16 @@ TOOLS = { "bibtex.windows": ("bibtex.exe",), "kpathsea.windows": ("kpsewhich.exe", "kpathsealibw64.dll", "msvcr100.dll"), } +UNICODE_PACKAGES = ("ctex", "xecjk", "zhnumber", "fandol", "xetex") +UNICODE_NOTICES = { + "ctex": {"doc/latex/ctex/README.md": "ctex-README.md"}, + "xecjk": {"doc/xelatex/xecjk/README.md": "xeCJK-README.md"}, + "zhnumber": {"doc/latex/zhnumber/README.md": "zhnumber-README.md"}, + "fandol": { + "doc/latex/fandol/COPYING": "Fandol-COPYING", + "doc/latex/fandol/README": "Fandol-README", + }, +} def digest(path, algorithm="sha256"): @@ -35,27 +45,51 @@ def require_amd64_pe(path): raise ValueError(f"Expected an x64 Windows executable: {path}") -def stage_bibtex(output, downloads): - output.mkdir(parents=True) +def read_texlive_database(downloads): with lzma.open(downloads / "texlive.tlpdb.xz", "rt") as stream: - db = stream.read() + records = stream.read().split("\n\n") + packages = {} + for record in records: + if not record.startswith("name "): + continue + fields = dict( + line.split(" ", 1) + for line in record.splitlines() + if line and not line[0].isspace() and " " in line + ) + packages[fields["name"]] = fields + return packages + + +def checked_texlive_archive(downloads, database, name): + package = name.removesuffix(".doc") + record = database[package] + field = "doccontainerchecksum" if name.endswith(".doc") else "containerchecksum" + checksum = record[field] + archive = downloads / f"{name}.tar.xz" + if digest(archive, "sha512") != checksum: + raise ValueError(f"TeX Live archive checksum differs for {name}") + return archive, {"revision": record["revision"], "sha512": checksum} + + +def copy_archive_file(archive, member, target): + if not member.isfile(): + raise ValueError(f"Expected a regular TeX Live file: {member.name}") + target.parent.mkdir(parents=True, exist_ok=True) + with archive.extractfile(member) as source, target.open("xb") as output: + shutil.copyfileobj(source, output) + + +def stage_bibtex(output, downloads, database): + output.mkdir(parents=True) receipts = {} for package, names in TOOLS.items(): - record = next(block for block in db.split("\n\n") if block.startswith(f"name {package}\n")) - fields = dict(line.split(" ", 1) for line in record.splitlines() if " " in line) - archive = downloads / f"{package}.tar.xz" - checksum = fields["containerchecksum"] - if digest(archive, "sha512") != checksum: - raise ValueError(f"TeX Live archive checksum differs for {package}") + archive, receipts[package] = checked_texlive_archive(downloads, database, package) with tarfile.open(archive, "r:xz") as bundle: for name in names: - member = bundle.getmember(f"bin/windows/{name}") - if not member.isfile(): - raise ValueError(f"Expected a regular TeX Live file: {name}") - with bundle.extractfile(member) as source, (output / name).open("wb") as target: - shutil.copyfileobj(source, target) - require_amd64_pe(output / name) - receipts[package] = {"revision": fields["revision"], "sha512": checksum} + target = output / name + copy_archive_file(bundle, bundle.getmember(f"bin/windows/{name}"), target) + require_amd64_pe(target) # Match TeX Live's width so a wrapped bibliography comment stays a comment. (output / "texmf.cnf").write_text( "BIBINPUTS = .\nBSTINPUTS = .\nopenin_any = p\nopenout_any = p\nshell_escape = f\n" @@ -65,6 +99,40 @@ def stage_bibtex(output, downloads): return receipts +def stage_unicode_resources(texmf, licenses, downloads, database): + receipts = {} + for package in UNICODE_PACKAGES: + archive, receipts[package] = checked_texlive_archive(downloads, database, package) + with tarfile.open(archive, "r:xz") as bundle: + for member in bundle: + if not member.isfile(): + continue + # TeX Live archives use either TDS paths or a texmf-dist prefix. + relative = PurePosixPath(member.name.removeprefix("texmf-dist/")) + if not relative.parts or relative.parts[0] not in ("tex", "fonts"): + continue + if ".." in relative.parts or any("\\" in part or ":" in part for part in relative.parts): + raise ValueError(f"Invalid TeX Live resource path: {member.name}") + copy_archive_file(bundle, member, texmf.joinpath(*relative.parts)) + + # CTeX loads this documented configuration before processing user options. + ctex_options = texmf / "tex/latex/ctex/config/ctexopts.cfg" + with ctex_options.open("a", encoding="utf-8", newline="\n") as options: + options.write( + "\n% Texrra bundles Fandol independently of the system's installed fonts.\n" + r"\sys_if_engine_xetex:T { \ctex_set:nn { option } { fontset = fandol } }" + "\n" + ) + + for package, notices in UNICODE_NOTICES.items(): + name = f"{package}.doc" + archive, receipts[name] = checked_texlive_archive(downloads, database, name) + with tarfile.open(archive, "r:xz") as bundle: + for member, filename in notices.items(): + copy_archive_file(bundle, bundle.getmember(member), licenses / filename) + return receipts + + def copy_texmf(source, target, skip_generated): target.mkdir(parents=True) for path in sorted(source.rglob("*")): @@ -90,8 +158,9 @@ def stage(args, output): font_maps = Path(reference["environment"]["TEXFONTMAPS"].rstrip(":")) (texmf / "fonts").mkdir() shutil.copy2(font_maps / "pdftex.map", texmf / "fonts") - if not (texmf / "dist/tex/latex/tex-ini-files/pdflatex.ini").is_file(): - raise ValueError("Missing pdfLaTeX initialization source") + for entry in ("pdflatex.ini", "xelatex.ini"): + if not (texmf / "dist/tex/latex/tex-ini-files" / entry).is_file(): + raise ValueError(f"Missing LaTeX initialization source: {entry}") web = output / "web" web.mkdir() @@ -100,7 +169,8 @@ def stage(args, output): if digest(source) != desktop["sha256"][f"web/{name}"]: raise ValueError(f"Reference Web asset has changed: {name}") shutil.copyfile(source, web / name) - tools = stage_bibtex(output / "tools/bibtex", args.downloads) + database = read_texlive_database(args.downloads) + tools = stage_bibtex(output / "tools/bibtex", args.downloads, database) (output / "bin").mkdir() require_amd64_pe(args.editor) shutil.copyfile(args.editor, output / "bin/native_editor.exe") @@ -108,11 +178,16 @@ def stage(args, output): "TeX Live resources and bundled BibTeX and Kpathsea binaries\n" "TeX Live licensing and sources: https://tug.org/texlive/copying.html\n" "TeX Live source archives: https://tug.org/texlive/svn/\n" + "CTeX, xeCJK, zhnumber and Fandol notices: licenses/texlive/\n" f"TeX Live binaries and package metadata: {MIRROR}\n", encoding="ascii", ) license_source = Path(__file__).resolve().with_name("licenses") - shutil.copytree(license_source, output / "licenses") + licenses = output / "licenses" + shutil.copytree(license_source, licenses) + unicode_resources = stage_unicode_resources( + texmf / "overlay", licenses / "texlive", args.downloads, database + ) files = { path.relative_to(output).as_posix(): digest(path) @@ -125,6 +200,7 @@ def stage(args, output): "web_commit": desktop["web_commit"], "resources_sha256": hashlib.sha256(fingerprints).hexdigest(), "texlive_tools": tools, + "texlive_unicode": unicode_resources, "sha256": files, }, indent=2, sort_keys=True) + "\n") @@ -134,7 +210,10 @@ def main(): parser.add_argument("output", type=Path) parser.add_argument("--editor", type=Path, required=True) parser.add_argument("--reference", type=Path, required=True) - parser.add_argument("--downloads", type=Path, required=True) + parser.add_argument( + "--downloads", type=Path, required=True, + help="TeX Live package archives and texlive.tlpdb.xz from the same mirror snapshot", + ) parser.add_argument("--commit", required=True) args = parser.parse_args() args.output.parent.mkdir(parents=True, exist_ok=True) diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index fd8113d..1ab39aa 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -3237,7 +3237,7 @@ dependencies = [ [[package]] name = "texrra-desktop" -version = "0.1.9" +version = "0.1.10" dependencies = [ "serde_json", "tauri", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 4fb436c..e1b6c88 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "texrra-desktop" -version = "0.1.9" +version = "0.1.10" edition = "2024" rust-version = "1.92" license = "MIT OR Apache-2.0" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 64b169c..3f44b47 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Texrra", - "version": "0.1.9", + "version": "0.1.10", "identifier": "org.texrra.desktop", "build": { "frontendDist": "../startup" diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index 451c5ed..ecb6e60 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -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; } } diff --git a/examples/native_editor/library.rs b/examples/native_editor/library.rs index fba02e3..8f70e9a 100644 --- a/examples/native_editor/library.rs +++ b/examples/native_editor/library.rs @@ -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>, + compiler: NativeCompiler, +} + +struct FormatPreparation { + lock: Mutex<()>, + build: Box 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, 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, ) -> Result> { 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> { + self.open_with_sources(id, None, BTreeMap::new()) + } + + pub(super) fn change_mode( + &self, + id: &str, + mode: CompileMode, + edits: BTreeMap, + ) -> Result> { + 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, + edits: BTreeMap, + ) -> Result> { 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::>(); + 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) } } diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 26f1e2d..3fb3904 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -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, } +#[derive(Deserialize)] +struct ChangeMode { + mode: CompileMode, + #[serde(default)] + files: BTreeMap, +} + enum PreviewReply { Http(Request), Socket(mpsc::Sender<(u16, Value)>), @@ -285,7 +294,7 @@ fn main() -> Result<(), Box> { 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> { 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, + format: EditorFormat, + mode_choice: Option, + cacheable: bool, compiler: NativeCompiler, ) -> Result> { + 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::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, + mode_choice: Option, cache: Option, run: PathBuf, compiler: NativeCompiler, @@ -845,6 +929,7 @@ impl EditorSession { }); Self { id: None, + mode_choice: None, cache, run, compiler, diff --git a/examples/native_editor/preview_cache.rs b/examples/native_editor/preview_cache.rs index 2157dae..48f1792 100644 --- a/examples/native_editor/preview_cache.rs +++ b/examples/native_editor/preview_cache.rs @@ -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, }))) diff --git a/examples/native_editor/preview_view.css b/examples/native_editor/preview_view.css index 4edbb36..dbb9d40 100644 --- a/examples/native_editor/preview_view.css +++ b/examples/native_editor/preview_view.css @@ -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; } diff --git a/examples/native_editor/windows_format.rs b/examples/native_editor/windows_format.rs index 27ecb36..c092526 100644 --- a/examples/native_editor/windows_format.rs +++ b/examples/native_editor/windows_format.rs @@ -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) -> 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 { + 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(()) } diff --git a/src/projects.rs b/src/projects.rs index a10854a..84c73ee 100644 --- a/src/projects.rs +++ b/src/projects.rs @@ -1,7 +1,8 @@ use std::{ fs, - io::{Read, Write}, + io::{self, Read, Write}, path::{Component, Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, time::{SystemTime, UNIX_EPOCH}, }; @@ -19,12 +20,32 @@ pub(super) struct ProjectFile { pub(super) size: u64, } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub(super) enum CompileMode { + #[default] + Auto, + Unicode, + PdfLatex, +} + +impl CompileMode { + fn as_str(self) -> &'static str { + match self { + Self::Auto => "auto", + Self::Unicode => "unicode", + Self::PdfLatex => "pdflatex", + } + } +} + #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] pub(super) struct ProjectInfo { pub(super) id: String, pub(super) name: String, pub(super) main_file: String, + pub(super) compile_mode: CompileMode, pub(super) created_at: u64, pub(super) updated_at: u64, pub(super) files: Vec, @@ -33,6 +54,7 @@ pub(super) struct ProjectInfo { struct Meta { name: String, main_file: String, + compile_mode: CompileMode, created_at: u64, updated_at: u64, } @@ -74,6 +96,7 @@ impl ProjectStore { let mut meta = self.load_meta(id).unwrap_or_else(|| Meta { name: id.to_string(), main_file: String::new(), + compile_mode: CompileMode::Auto, created_at: now_secs(), updated_at: now_secs(), }); @@ -82,6 +105,7 @@ impl ProjectStore { id: id.to_string(), name: meta.name, main_file: meta.main_file, + compile_mode: meta.compile_mode, created_at: meta.created_at, updated_at: meta.updated_at, files, @@ -89,12 +113,29 @@ impl ProjectStore { } pub(super) fn create_empty(&self, name: &str) -> Result { + self.create_empty_with_mode(name, CompileMode::Auto) + } + + pub(super) fn create_empty_with_mode( + &self, + name: &str, + compile_mode: CompileMode, + ) -> Result { let name = clean_name(name); let id = self.unique_id(&slug(&name)); let dir = self.root.join(&id); fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?; - let source = - "\\documentclass{article}\n\\begin{document}\nHello, world.\n\\end{document}\n"; + let source = if compile_mode == CompileMode::Unicode { + concat!( + "\\documentclass{article}\n", + "\\usepackage[UTF8,scheme=plain,fontset=fandol]{ctex}\n", + "\\begin{document}\n", + "你好,世界。Hello, world.\n", + "\\end{document}\n", + ) + } else { + "\\documentclass{article}\n\\begin{document}\nHello, world.\n\\end{document}\n" + }; fs::write(dir.join("main.tex"), source) .map_err(|error| format!("could not write main.tex: {error}"))?; self.save_meta( @@ -102,6 +143,7 @@ impl ProjectStore { &Meta { name, main_file: "main.tex".to_string(), + compile_mode, created_at: now_secs(), updated_at: now_secs(), }, @@ -173,6 +215,7 @@ impl ProjectStore { &Meta { name, main_file, + compile_mode: CompileMode::Auto, created_at: now_secs(), updated_at: now_secs(), }, @@ -180,6 +223,29 @@ impl ProjectStore { self.info(&id) } + pub(super) fn set_compile_mode( + &self, + id: &str, + mode: CompileMode, + ) -> Result { + let mut info = self.info(id)?; + if info.compile_mode != mode { + info.compile_mode = mode; + info.updated_at = now_secs(); + self.save_meta( + id, + &Meta { + name: info.name.clone(), + main_file: info.main_file.clone(), + compile_mode: mode, + created_at: info.created_at, + updated_at: info.updated_at, + }, + )?; + } + Ok(info) + } + pub(super) fn delete(&self, id: &str) -> Result<(), String> { let dir = self.project_dir(id)?; if !dir.is_dir() { @@ -322,6 +388,7 @@ impl ProjectStore { &Meta { name: stem.to_string(), main_file: file_name.to_string(), + compile_mode: CompileMode::Auto, created_at: now_secs(), updated_at: now_secs(), }, @@ -411,6 +478,7 @@ impl ProjectStore { let text = fs::read_to_string(self.meta_path(id)).ok()?; let mut name = String::new(); let mut main_file = String::new(); + let mut compile_mode = CompileMode::Auto; let mut created_at = 0; let mut updated_at = 0; for line in text.lines() { @@ -420,6 +488,13 @@ impl ProjectStore { match key { "name" => name = value.to_string(), "main" => main_file = value.to_string(), + "compile_mode" => { + compile_mode = match value { + "unicode" => CompileMode::Unicode, + "pdflatex" => CompileMode::PdfLatex, + _ => CompileMode::Auto, + }; + } "created" => created_at = value.parse().unwrap_or(0), "updated" => updated_at = value.parse().unwrap_or(0), _ => {} @@ -432,6 +507,7 @@ impl ProjectStore { name }, main_file, + compile_mode, created_at, updated_at, }) @@ -439,20 +515,48 @@ impl ProjectStore { fn save_meta(&self, id: &str, meta: &Meta) -> Result<(), String> { let text = format!( - "name={}\nmain={}\ncreated={}\nupdated={}\n", + "name={}\nmain={}\ncreated={}\nupdated={}\ncompile_mode={}\n", meta.name.replace(['\n', '\r'], " "), meta.main_file, meta.created_at, - meta.updated_at + meta.updated_at, + meta.compile_mode.as_str() ); - fs::write(self.meta_path(id), text) - .map_err(|error| format!("could not save project metadata: {error}")) + let path = self.meta_path(id); + let replace = (|| -> io::Result<()> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let (mut file, temporary) = loop { + let temporary = path.with_extension(format!( + "{}.{}.pending", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + match fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + { + Ok(file) => break (file, temporary), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + }; + let written = file.write_all(text.as_bytes()); + drop(file); + let result = written.and_then(|()| fs::rename(&temporary, path)); + if result.is_err() { + let _ = fs::remove_file(temporary); + } + result + })(); + replace.map_err(|error| format!("could not save project metadata: {error}")) } fn touch(&self, id: &str) -> Result<(), String> { let mut meta = self.load_meta(id).unwrap_or_else(|| Meta { name: id.to_string(), main_file: String::new(), + compile_mode: CompileMode::Auto, created_at: now_secs(), updated_at: now_secs(), }); @@ -566,6 +670,111 @@ fn entry_path(entry: &str) -> Option { Some(trimmed.to_string()) } +/// Detect the engine from editor directives and LaTeX package declarations. +/// Ambiguous documents retain the pdfLaTeX-compatible mode. +pub(super) fn resolve_compile_mode(source: &str) -> CompileMode { + let source = source.trim_start_matches('\u{feff}'); + for line in source.lines().map(str::trim) { + if line.is_empty() { + continue; + } + let Some(comment) = line.strip_prefix('%') else { + break; + }; + let Some((key, program)) = comment.split_once('=') else { + continue; + }; + let mut words = key.split_whitespace(); + if !words + .next() + .is_some_and(|word| word.eq_ignore_ascii_case("!tex")) + || !words.next().is_some_and(|word| { + word.eq_ignore_ascii_case("program") || word.eq_ignore_ascii_case("ts-program") + }) + || words.next().is_some() + { + continue; + } + match program.split_whitespace().next() { + Some(program) if program.eq_ignore_ascii_case("xelatex") => { + return CompileMode::Unicode; + } + Some(program) if program.eq_ignore_ascii_case("pdflatex") => { + return CompileMode::PdfLatex; + } + _ => {} + } + } + + let mut uncommented = String::new(); + for line in source.lines() { + let mut escaped = false; + let end = line + .char_indices() + .find_map(|(index, ch)| { + let comment = ch == '%' && !escaped; + escaped = ch == '\\' && !escaped; + comment.then_some(index) + }) + .unwrap_or(line.len()); + uncommented.push_str(&line[..end]); + uncommented.push('\n'); + } + let mut remaining = uncommented.as_str(); + while let Some((_, command)) = remaining.split_once('\\') { + let end = command + .find(|ch: char| !ch.is_ascii_alphabetic()) + .unwrap_or(command.len()); + let (name, after) = command.split_at(end); + if name.is_empty() { + let mut chars = after.chars(); + chars.next(); + remaining = chars.as_str(); + continue; + } + remaining = after; + let argument = match name { + "begin" + | "documentclass" + | "usepackage" + | "RequirePackage" + | "RequirePackageWithOptions" => tex_command_argument(after), + _ => None, + }; + let Some(argument) = argument else { + continue; + }; + match name { + "begin" if argument == "document" => break, + "documentclass" + if matches!(argument, "ctexart" | "ctexrep" | "ctexbook" | "ctexbeamer") => + { + return CompileMode::Unicode; + } + "usepackage" | "RequirePackage" | "RequirePackageWithOptions" + if argument.split(',').any(|package| { + matches!( + package.trim(), + "ctex" | "xeCJK" | "fontspec" | "unicode-math" + ) + }) => + { + return CompileMode::Unicode; + } + _ => {} + } + } + CompileMode::PdfLatex +} + +fn tex_command_argument(source: &str) -> Option<&str> { + let mut source = source.trim_start(); + if let Some(options) = source.strip_prefix('[') { + source = options.split_once(']')?.1.trim_start(); + } + Some(source.strip_prefix('{')?.split_once('}')?.0.trim()) +} + fn detect_main(directory: &Path, names: &[String]) -> Option { for candidate in ["main.tex", "document.tex", "paper.tex", "article.tex"] { if let Some(name) = names.iter().find(|name| name.as_str() == candidate) {