Use a Unicode default with project-level LaTeX compatibility
This commit is contained in:
1 parent
38a2a4a958
commit
81ac3ae321
11 files changed
+722
-107
No files matched your search
@@ -5,7 +5,7 @@ import argparse
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import lzma
|
import lzma
|
||||||
from pathlib import Path
|
from pathlib import Path, PurePosixPath
|
||||||
import shutil
|
import shutil
|
||||||
import struct
|
import struct
|
||||||
import tarfile
|
import tarfile
|
||||||
@@ -18,6 +18,16 @@ TOOLS = {
|
|||||||
"bibtex.windows": ("bibtex.exe",),
|
"bibtex.windows": ("bibtex.exe",),
|
||||||
"kpathsea.windows": ("kpsewhich.exe", "kpathsealibw64.dll", "msvcr100.dll"),
|
"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"):
|
def digest(path, algorithm="sha256"):
|
||||||
@@ -35,27 +45,51 @@ def require_amd64_pe(path):
|
|||||||
raise ValueError(f"Expected an x64 Windows executable: {path}")
|
raise ValueError(f"Expected an x64 Windows executable: {path}")
|
||||||
|
|
||||||
|
|
||||||
def stage_bibtex(output, downloads):
|
def read_texlive_database(downloads):
|
||||||
output.mkdir(parents=True)
|
|
||||||
with lzma.open(downloads / "texlive.tlpdb.xz", "rt") as stream:
|
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 = {}
|
receipts = {}
|
||||||
for package, names in TOOLS.items():
|
for package, names in TOOLS.items():
|
||||||
record = next(block for block in db.split("\n\n") if block.startswith(f"name {package}\n"))
|
archive, receipts[package] = checked_texlive_archive(downloads, database, package)
|
||||||
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}")
|
|
||||||
with tarfile.open(archive, "r:xz") as bundle:
|
with tarfile.open(archive, "r:xz") as bundle:
|
||||||
for name in names:
|
for name in names:
|
||||||
member = bundle.getmember(f"bin/windows/{name}")
|
target = output / name
|
||||||
if not member.isfile():
|
copy_archive_file(bundle, bundle.getmember(f"bin/windows/{name}"), target)
|
||||||
raise ValueError(f"Expected a regular TeX Live file: {name}")
|
require_amd64_pe(target)
|
||||||
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}
|
|
||||||
# Match TeX Live's width so a wrapped bibliography comment stays a comment.
|
# Match TeX Live's width so a wrapped bibliography comment stays a comment.
|
||||||
(output / "texmf.cnf").write_text(
|
(output / "texmf.cnf").write_text(
|
||||||
"BIBINPUTS = .\nBSTINPUTS = .\nopenin_any = p\nopenout_any = p\nshell_escape = f\n"
|
"BIBINPUTS = .\nBSTINPUTS = .\nopenin_any = p\nopenout_any = p\nshell_escape = f\n"
|
||||||
@@ -65,6 +99,40 @@ def stage_bibtex(output, downloads):
|
|||||||
return receipts
|
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):
|
def copy_texmf(source, target, skip_generated):
|
||||||
target.mkdir(parents=True)
|
target.mkdir(parents=True)
|
||||||
for path in sorted(source.rglob("*")):
|
for path in sorted(source.rglob("*")):
|
||||||
@@ -90,8 +158,9 @@ def stage(args, output):
|
|||||||
font_maps = Path(reference["environment"]["TEXFONTMAPS"].rstrip(":"))
|
font_maps = Path(reference["environment"]["TEXFONTMAPS"].rstrip(":"))
|
||||||
(texmf / "fonts").mkdir()
|
(texmf / "fonts").mkdir()
|
||||||
shutil.copy2(font_maps / "pdftex.map", texmf / "fonts")
|
shutil.copy2(font_maps / "pdftex.map", texmf / "fonts")
|
||||||
if not (texmf / "dist/tex/latex/tex-ini-files/pdflatex.ini").is_file():
|
for entry in ("pdflatex.ini", "xelatex.ini"):
|
||||||
raise ValueError("Missing pdfLaTeX initialization source")
|
if not (texmf / "dist/tex/latex/tex-ini-files" / entry).is_file():
|
||||||
|
raise ValueError(f"Missing LaTeX initialization source: {entry}")
|
||||||
|
|
||||||
web = output / "web"
|
web = output / "web"
|
||||||
web.mkdir()
|
web.mkdir()
|
||||||
@@ -100,7 +169,8 @@ def stage(args, output):
|
|||||||
if digest(source) != desktop["sha256"][f"web/{name}"]:
|
if digest(source) != desktop["sha256"][f"web/{name}"]:
|
||||||
raise ValueError(f"Reference Web asset has changed: {name}")
|
raise ValueError(f"Reference Web asset has changed: {name}")
|
||||||
shutil.copyfile(source, web / 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()
|
(output / "bin").mkdir()
|
||||||
require_amd64_pe(args.editor)
|
require_amd64_pe(args.editor)
|
||||||
shutil.copyfile(args.editor, output / "bin/native_editor.exe")
|
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 resources and bundled BibTeX and Kpathsea binaries\n"
|
||||||
"TeX Live licensing and sources: https://tug.org/texlive/copying.html\n"
|
"TeX Live licensing and sources: https://tug.org/texlive/copying.html\n"
|
||||||
"TeX Live source archives: https://tug.org/texlive/svn/\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",
|
f"TeX Live binaries and package metadata: {MIRROR}\n",
|
||||||
encoding="ascii",
|
encoding="ascii",
|
||||||
)
|
)
|
||||||
license_source = Path(__file__).resolve().with_name("licenses")
|
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 = {
|
files = {
|
||||||
path.relative_to(output).as_posix(): digest(path)
|
path.relative_to(output).as_posix(): digest(path)
|
||||||
@@ -125,6 +200,7 @@ def stage(args, output):
|
|||||||
"web_commit": desktop["web_commit"],
|
"web_commit": desktop["web_commit"],
|
||||||
"resources_sha256": hashlib.sha256(fingerprints).hexdigest(),
|
"resources_sha256": hashlib.sha256(fingerprints).hexdigest(),
|
||||||
"texlive_tools": tools,
|
"texlive_tools": tools,
|
||||||
|
"texlive_unicode": unicode_resources,
|
||||||
"sha256": files,
|
"sha256": files,
|
||||||
}, indent=2, sort_keys=True) + "\n")
|
}, indent=2, sort_keys=True) + "\n")
|
||||||
|
|
||||||
@@ -134,7 +210,10 @@ def main():
|
|||||||
parser.add_argument("output", type=Path)
|
parser.add_argument("output", type=Path)
|
||||||
parser.add_argument("--editor", type=Path, required=True)
|
parser.add_argument("--editor", type=Path, required=True)
|
||||||
parser.add_argument("--reference", 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)
|
parser.add_argument("--commit", required=True)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|||||||
Generated
+1
-1
@@ -3237,7 +3237,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "texrra-desktop"
|
name = "texrra-desktop"
|
||||||
version = "0.1.9"
|
version = "0.1.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "texrra-desktop"
|
name = "texrra-desktop"
|
||||||
version = "0.1.9"
|
version = "0.1.10"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.92"
|
rust-version = "1.92"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Texrra",
|
"productName": "Texrra",
|
||||||
"version": "0.1.9",
|
"version": "0.1.10",
|
||||||
"identifier": "org.texrra.desktop",
|
"identifier": "org.texrra.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../startup"
|
"frontendDist": "../startup"
|
||||||
|
|||||||
+122
-17
@@ -20,10 +20,13 @@ const fileViews = new Map();
|
|||||||
const EDIT_IDLE_MS = 70;
|
const EDIT_IDLE_MS = 70;
|
||||||
const TEXT_LAYER_IDLE_MS = 180;
|
const TEXT_LAYER_IDLE_MS = 180;
|
||||||
const PREVIEW_SOCKET_RETRY_MS = 1000;
|
const PREVIEW_SOCKET_RETRY_MS = 1000;
|
||||||
|
const COMPILE_MODE_LABELS = { unicode: "Unicode", pdflatex: "pdfLaTeX" };
|
||||||
let files;
|
let files;
|
||||||
let projectFiles = [];
|
let projectFiles = [];
|
||||||
let activeFile;
|
let activeFile;
|
||||||
let preparingProject = false;
|
let preparingProject = false;
|
||||||
|
let compileMode;
|
||||||
|
let cachedPreviewRequest;
|
||||||
let sequence = 0;
|
let sequence = 0;
|
||||||
let publishedRevision = null;
|
let publishedRevision = null;
|
||||||
let visibleRevision = null;
|
let visibleRevision = null;
|
||||||
@@ -54,6 +57,16 @@ recompile.disabled = true;
|
|||||||
previewView.toolbar.prepend(recompile);
|
previewView.toolbar.prepend(recompile);
|
||||||
recompile.addEventListener("click", manualCompile);
|
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");
|
const cachedPreviewStatus = document.createElement("span");
|
||||||
cachedPreviewStatus.id = "cached-preview-status";
|
cachedPreviewStatus.id = "cached-preview-status";
|
||||||
cachedPreviewStatus.className = "texrra-preview-history";
|
cachedPreviewStatus.className = "texrra-preview-history";
|
||||||
@@ -188,25 +201,29 @@ function restorePublishedPages() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function showCachedPreview() {
|
async function showCachedPreview() {
|
||||||
|
const request = new AbortController();
|
||||||
|
cachedPreviewRequest = request;
|
||||||
|
const canDisplay = () => !request.signal.aborted && visibleRevision === null;
|
||||||
const frames = [];
|
const frames = [];
|
||||||
try {
|
try {
|
||||||
const response = await fetch(projectPrefix + "/cached-preview");
|
const response = await fetch(projectPrefix + "/cached-preview", { signal: request.signal });
|
||||||
if (!response.ok || visibleRevision !== null) return;
|
if (!response.ok || !canDisplay()) return;
|
||||||
const { page_count, pages: savedPages } = await response.json();
|
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) =>
|
|| savedPages.length !== page_count || savedPages.some((page, index) =>
|
||||||
page?.index !== index || typeof page.svg !== "string")) return;
|
page?.index !== index || typeof page.svg !== "string")) return;
|
||||||
const first = pageFrame(savedPages[0]);
|
const first = pageFrame(savedPages[0]);
|
||||||
frames.push(first);
|
frames.push(first);
|
||||||
// The rest of the saved document can decode after the first page is ready.
|
// The rest of the saved document can decode after the first page is ready.
|
||||||
await first.querySelector("img").decode();
|
await first.querySelector("img").decode();
|
||||||
if (visibleRevision !== null) return;
|
if (!canDisplay()) return;
|
||||||
for (const page of savedPages.slice(1)) frames.push(pageFrame(page));
|
for (const page of savedPages.slice(1)) frames.push(pageFrame(page));
|
||||||
pages.replaceChildren(...frames);
|
pages.replaceChildren(...frames);
|
||||||
cachedPreviewStatus.hidden = false;
|
cachedPreviewStatus.hidden = false;
|
||||||
} catch {
|
} catch {
|
||||||
// Cache errors do not interrupt the live compile.
|
// Cache errors do not interrupt the live compile.
|
||||||
} finally {
|
} finally {
|
||||||
|
if (cachedPreviewRequest === request) cachedPreviewRequest = undefined;
|
||||||
revokeDetached(frames);
|
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() {
|
async function openProject() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(projectPrefix + "/project");
|
const response = await fetch(projectPrefix + "/project");
|
||||||
@@ -580,6 +693,8 @@ async function openProject() {
|
|||||||
addFormulaButtons();
|
addFormulaButtons();
|
||||||
sequence = project.sequence;
|
sequence = project.sequence;
|
||||||
preparingProject = project.preparing === true;
|
preparingProject = project.preparing === true;
|
||||||
|
showCompileMode(project.compile_mode);
|
||||||
|
compileModeSelect.disabled = preparingProject;
|
||||||
recompile.title = "重新编译主文件 " + project.name + "(Ctrl/Cmd+Enter)";
|
recompile.title = "重新编译主文件 " + project.name + "(Ctrl/Cmd+Enter)";
|
||||||
save.addEventListener("click", saveSources);
|
save.addEventListener("click", saveSources);
|
||||||
document.addEventListener("keydown", (event) => {
|
document.addEventListener("keydown", (event) => {
|
||||||
@@ -624,21 +739,11 @@ async function openProject() {
|
|||||||
indentSource();
|
indentSource();
|
||||||
});
|
});
|
||||||
if (project.cached_preview === true) void showCachedPreview();
|
if (project.cached_preview === true) void showCachedPreview();
|
||||||
if (preparingProject) {
|
await finishProjectOpening(project);
|
||||||
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);
|
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
showError(failure.message);
|
showError(failure.message);
|
||||||
|
} finally {
|
||||||
|
compileModeSelect.disabled = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,33 +1,88 @@
|
|||||||
use super::{
|
use super::{
|
||||||
InputProfile, NativeCompiler, OpeningEditor, fs, json, projects::ProjectStore, reply,
|
InputProfile, NativeCompiler, OpeningEditor, copy_with_date, fs, json,
|
||||||
stage_sources,
|
projects::{CompileMode, ProjectStore, resolve_compile_mode},
|
||||||
|
reply, stage_sources,
|
||||||
};
|
};
|
||||||
use std::{
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
io::{ErrorKind, Read},
|
io::{ErrorKind, Read},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
time::Instant,
|
sync::{Arc, Mutex},
|
||||||
|
time::{Instant, SystemTime},
|
||||||
};
|
};
|
||||||
use tiny_http::Request;
|
use tiny_http::Request;
|
||||||
|
|
||||||
pub(super) const SCRIPT: &str = include_str!("library.js");
|
pub(super) const SCRIPT: &str = include_str!("library.js");
|
||||||
const MAX_ZIP_UPLOAD: u64 = 64 * 1024 * 1024;
|
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 {
|
pub(super) struct Library {
|
||||||
store: ProjectStore,
|
store: ProjectStore,
|
||||||
format: PathBuf,
|
primary: EditorFormat,
|
||||||
manifest: PathBuf,
|
unicode: Option<EditorFormat>,
|
||||||
runs: PathBuf,
|
runs: PathBuf,
|
||||||
profile: InputProfile,
|
|
||||||
compiler: NativeCompiler,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Library {
|
impl Library {
|
||||||
pub(super) fn new(
|
pub(super) fn new(
|
||||||
store: PathBuf,
|
store: PathBuf,
|
||||||
format: PathBuf,
|
|
||||||
manifest: PathBuf,
|
|
||||||
runs: PathBuf,
|
runs: PathBuf,
|
||||||
profile: InputProfile,
|
primary: EditorFormat,
|
||||||
|
unicode: Option<EditorFormat>,
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
fs::create_dir_all(&store)?;
|
fs::create_dir_all(&store)?;
|
||||||
let store = store.canonicalize()?;
|
let store = store.canonicalize()?;
|
||||||
@@ -38,24 +93,28 @@ impl Library {
|
|||||||
}
|
}
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
store: ProjectStore::new(store)?,
|
store: ProjectStore::new(store)?,
|
||||||
format,
|
primary,
|
||||||
manifest,
|
unicode,
|
||||||
runs,
|
runs,
|
||||||
profile,
|
|
||||||
compiler: NativeCompiler::default(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn prewarm_format(&self) {
|
pub(super) fn prewarm_format(&self) {
|
||||||
let compiler = self.compiler.clone();
|
// Decode ready formats in the background. A first launch can show
|
||||||
let format = self.format.clone();
|
// 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()
|
let _ = std::thread::Builder::new()
|
||||||
.name("texrra-prewarm-format".into())
|
.name("texrra-prewarm-format".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
let trace = std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE")
|
let trace = std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE")
|
||||||
.is_some_and(|value| value == "1");
|
.is_some_and(|value| value == "1");
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
let result = compiler.prewarm_format(&format);
|
let result = compiler.prewarm_format(&image);
|
||||||
if trace {
|
if trace {
|
||||||
eprintln!("Texrra editor preparation {}", json!({
|
eprintln!("Texrra editor preparation {}", json!({
|
||||||
"stage": "prewarm-format",
|
"stage": "prewarm-format",
|
||||||
@@ -68,6 +127,7 @@ impl Library {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn list(&self, request: Request) {
|
pub(super) fn list(&self, request: Request) {
|
||||||
match self.store.list() {
|
match self.store.list() {
|
||||||
@@ -127,13 +187,41 @@ impl Library {
|
|||||||
return;
|
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)),
|
Ok(project) => reply(request, 201, json!(project)),
|
||||||
Err(error) => reply(request, 422, json!({"error": error})),
|
Err(error) => reply(request, 422, json!({"error": error})),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn open(&self, id: &str) -> Result<OpeningEditor, Box<dyn std::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)?;
|
let root = self.store.project_dir(id)?;
|
||||||
if fs::symlink_metadata(&root)?.file_type().is_symlink() {
|
if fs::symlink_metadata(&root)?.file_type().is_symlink() {
|
||||||
return Err("The project directory must be a local working copy".into());
|
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)
|
.filter(|file| file.path != info.main_file)
|
||||||
.map(|file| PathBuf::from(&file.path))
|
.map(|file| PathBuf::from(&file.path))
|
||||||
.collect::<Vec<_>>();
|
.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 run = fresh_run(&self.runs, id)?;
|
||||||
let staged = stage_sources(
|
let mut staged = stage_sources(
|
||||||
&root, &source, &self.format, &self.manifest, &run, &files, self.profile,
|
&root, &source, &format.image, &format.manifest, &run, &files, format.profile,
|
||||||
)?;
|
)?;
|
||||||
let cache = super::preview_cache::PreviewCache::for_project(
|
let unchanged = edits.iter().all(|(name, value)| {
|
||||||
&self.runs, &info.id, &run, &staged, &self.format, &self.manifest,
|
staged.editable.get(name).and_then(|path| staged.files.get(path))
|
||||||
);
|
.is_some_and(|bytes| bytes.as_ref() == value.as_bytes())
|
||||||
let compiler = self.compiler.new_session_sharing_format()
|
});
|
||||||
|
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();
|
.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.
|
//! Loopback editor for comparing actual native page updates with full jobs.
|
||||||
|
use library::{EditorFormat, ModeChoice};
|
||||||
|
use projects::CompileMode;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use std::{
|
use std::{
|
||||||
@@ -61,6 +63,13 @@ struct Save {
|
|||||||
files: BTreeMap<String, String>,
|
files: BTreeMap<String, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ChangeMode {
|
||||||
|
mode: CompileMode,
|
||||||
|
#[serde(default)]
|
||||||
|
files: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
enum PreviewReply {
|
enum PreviewReply {
|
||||||
Http(Request),
|
Http(Request),
|
||||||
Socket(mpsc::Sender<(u16, Value)>),
|
Socket(mpsc::Sender<(u16, Value)>),
|
||||||
@@ -285,7 +294,7 @@ fn main() -> Result<(), Box<dyn std::error::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() {
|
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) {
|
match args.next().as_deref().and_then(std::ffi::OsStr::to_str) {
|
||||||
Some("tex8bit") => InputProfile::TeX8Bit,
|
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 format = args.next().ok_or(usage)?.canonicalize()?;
|
||||||
let manifest = args.next().ok_or(usage)?.canonicalize()?;
|
let manifest = args.next().ok_or(usage)?.canonicalize()?;
|
||||||
let runs = args.next().ok_or(usage)?;
|
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(
|
Some(library::Library::new(
|
||||||
store,
|
store,
|
||||||
format,
|
|
||||||
manifest,
|
|
||||||
runs,
|
runs,
|
||||||
input_profile,
|
EditorFormat::prepared(format, manifest, input_profile),
|
||||||
|
unicode,
|
||||||
)?)
|
)?)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -454,6 +474,37 @@ fn serve(
|
|||||||
);
|
);
|
||||||
continue;
|
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 {
|
if request.method() == &Method::Get {
|
||||||
match (rest, pending) {
|
match (rest, pending) {
|
||||||
("project", Some(opening)) => {
|
("project", Some(opening)) => {
|
||||||
@@ -529,6 +580,7 @@ fn serve(
|
|||||||
compiler,
|
compiler,
|
||||||
cache,
|
cache,
|
||||||
first_preview_revision,
|
first_preview_revision,
|
||||||
|
mode_choice,
|
||||||
queue,
|
queue,
|
||||||
save_number,
|
save_number,
|
||||||
editor,
|
editor,
|
||||||
@@ -559,6 +611,9 @@ fn serve(
|
|||||||
let mut payload = project_payload(
|
let mut payload = project_payload(
|
||||||
run, entry, declared, files, queue.current.load(Ordering::Acquire), id.as_deref(),
|
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) {
|
if cache.as_ref().is_some_and(preview_cache::PreviewCache::exists) {
|
||||||
payload["cached_preview"] = json!(true);
|
payload["cached_preview"] = json!(true);
|
||||||
}
|
}
|
||||||
@@ -733,14 +788,23 @@ impl OpeningEditor {
|
|||||||
id: String,
|
id: String,
|
||||||
run: PathBuf,
|
run: PathBuf,
|
||||||
staged: StagedProject,
|
staged: StagedProject,
|
||||||
cache: Option<preview_cache::PreviewCache>,
|
format: EditorFormat,
|
||||||
|
mode_choice: Option<ModeChoice>,
|
||||||
|
cacheable: bool,
|
||||||
compiler: NativeCompiler,
|
compiler: NativeCompiler,
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
) -> 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)| {
|
let files = staged.editable.iter().filter_map(|(name, path)| {
|
||||||
staged.files.get(path).map(|bytes| (name.as_str(), bytes.as_ref()))
|
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))?;
|
let mut sources = project_payload(&run, &staged.entry, &staged.declared, files, 1, Some(&id))?;
|
||||||
sources["preparing"] = json!(true);
|
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) {
|
if cache.as_ref().is_some_and(preview_cache::PreviewCache::exists) {
|
||||||
sources["cached_preview"] = json!(true);
|
sources["cached_preview"] = json!(true);
|
||||||
}
|
}
|
||||||
@@ -758,19 +822,38 @@ impl OpeningEditor {
|
|||||||
let superseded = opening.superseded.clone();
|
let superseded = opening.superseded.clone();
|
||||||
let cache = opening.cache.clone();
|
let cache = opening.cache.clone();
|
||||||
std::thread::Builder::new().name("texrra-open-project".into()).spawn(move || {
|
std::thread::Builder::new().name("texrra-open-project".into()).spawn(move || {
|
||||||
let result = finish_prepare(staged, &run, &compiler, Some(&superseded), Some(&id))
|
let result = (|| {
|
||||||
.map(|editor| {
|
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);
|
let mut session = EditorSession::new(run, editor, compiler, cache);
|
||||||
session.id = Some(id);
|
session.id = Some(id);
|
||||||
Arc::new(Mutex::new(session))
|
session.mode_choice = mode_choice;
|
||||||
})
|
Ok(Arc::new(Mutex::new(session)))
|
||||||
.map_err(|error| error.to_string());
|
})();
|
||||||
let _ = ready.set(result);
|
let _ = ready.set(result);
|
||||||
})?;
|
})?;
|
||||||
Ok(opening)
|
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 {
|
impl Drop for OpeningEditor {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if self.ready.get().is_none() {
|
if self.ready.get().is_none() {
|
||||||
@@ -807,6 +890,7 @@ fn project_payload<'a>(
|
|||||||
|
|
||||||
struct EditorSession {
|
struct EditorSession {
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
|
mode_choice: Option<ModeChoice>,
|
||||||
cache: Option<preview_cache::PreviewCache>,
|
cache: Option<preview_cache::PreviewCache>,
|
||||||
run: PathBuf,
|
run: PathBuf,
|
||||||
compiler: NativeCompiler,
|
compiler: NativeCompiler,
|
||||||
@@ -845,6 +929,7 @@ impl EditorSession {
|
|||||||
});
|
});
|
||||||
Self {
|
Self {
|
||||||
id: None,
|
id: None,
|
||||||
|
mode_choice: None,
|
||||||
cache,
|
cache,
|
||||||
run,
|
run,
|
||||||
compiler,
|
compiler,
|
||||||
|
|||||||
@@ -87,8 +87,13 @@ impl PreviewCache {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
.collect();
|
.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 {
|
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(),
|
key: key.finalize().into(),
|
||||||
originals,
|
originals,
|
||||||
})))
|
})))
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
margin-bottom: .65rem;
|
margin-bottom: .65rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.texrra-preview-controls button {
|
.texrra-preview-controls :is(button, select) {
|
||||||
min-width: 1.9rem;
|
min-width: 1.9rem;
|
||||||
min-height: 1.9rem;
|
min-height: 1.9rem;
|
||||||
padding: .15rem .45rem;
|
padding: .15rem .45rem;
|
||||||
@@ -41,12 +41,12 @@
|
|||||||
background: #eaf1f7;
|
background: #eaf1f7;
|
||||||
}
|
}
|
||||||
|
|
||||||
.texrra-preview-controls button:focus-visible {
|
.texrra-preview-controls :is(button, select):focus-visible {
|
||||||
outline: 2px solid #1972a4;
|
outline: 2px solid #1972a4;
|
||||||
outline-offset: 2px;
|
outline-offset: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.texrra-preview-controls button:disabled {
|
.texrra-preview-controls :is(button, select):disabled {
|
||||||
opacity: .48;
|
opacity: .48;
|
||||||
cursor: default;
|
cursor: default;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
//! Bootstrap the installed Windows editor from the packaged TeX resources.
|
//! 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 serde::Deserialize;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::{
|
use std::{
|
||||||
env,
|
env,
|
||||||
ffi::{OsStr, OsString},
|
ffi::{OsStr, OsString},
|
||||||
fs::{self, File, OpenOptions},
|
fs::{self, File, OpenOptions},
|
||||||
io::{self, Read, Write},
|
io::{self, Read},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
|
time::Instant,
|
||||||
};
|
};
|
||||||
use texrra_engine::native::{CompileRequest, Entry, dump_format, job_time};
|
use texrra_engine::native::{CompileRequest, Entry, dump_format, job_time};
|
||||||
use texrra_tex_core::{
|
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)?;
|
configure_environment(&backend, &state, &font_maps)?;
|
||||||
start_lease()?;
|
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 = runtime.join("format-resources.json");
|
||||||
let manifest_bytes = serde_json::to_vec(&serde_json::json!({"texmf_roots": roots}))?;
|
let manifest_bytes = serde_json::to_vec(&serde_json::json!({"texmf_roots": roots}))?;
|
||||||
if fs::read(&manifest).ok().as_deref() != Some(&manifest_bytes) {
|
if fs::read(&manifest).ok().as_deref() != Some(&manifest_bytes) {
|
||||||
fs::write(&manifest, 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 web = WebAssets::load(&backend.join("web"))?;
|
||||||
let library = Library::new(
|
let library = Library::new(home.join("projects"), runtime.join("web-runs"), primary, Some(unicode))?;
|
||||||
home.join("projects"),
|
|
||||||
format.canonicalize()?,
|
|
||||||
manifest.canonicalize()?,
|
|
||||||
runtime.join("web-runs"),
|
|
||||||
InputProfile::TeX8Bit,
|
|
||||||
)?;
|
|
||||||
serve(Some(web), Some(library), 0, None)
|
serve(Some(web), Some(library), 0, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,15 +160,41 @@ fn start_lease() -> io::Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_format(ini: &Path, runtime: &Path, format: &Path, roots: &[PathBuf]) -> LaunchResult<()> {
|
fn desktop_format(
|
||||||
let ini = ini.canonicalize()?;
|
runtime: &Path,
|
||||||
let world = WorldConfig::from_environment(runtime, roots.to_vec())?;
|
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()?);
|
let mut request = CompileRequest::new(world, ini, format, job_time()?);
|
||||||
request.entry = Entry::Initex;
|
request.entry = Entry::Initex;
|
||||||
|
request.input_profile = profile;
|
||||||
request.etex = true;
|
request.etex = true;
|
||||||
request.limits.steps = 600_000_000;
|
request.limits.steps = 600_000_000;
|
||||||
println!("Texrra desktop preparing format");
|
|
||||||
io::stdout().flush()?;
|
|
||||||
dump_format(request, Cancellation::default())?;
|
dump_format(request, Cancellation::default())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
+216
-7
@@ -1,7 +1,8 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs,
|
fs,
|
||||||
io::{Read, Write},
|
io::{self, Read, Write},
|
||||||
path::{Component, Path, PathBuf},
|
path::{Component, Path, PathBuf},
|
||||||
|
sync::atomic::{AtomicU64, Ordering},
|
||||||
time::{SystemTime, UNIX_EPOCH},
|
time::{SystemTime, UNIX_EPOCH},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -19,12 +20,32 @@ pub(super) struct ProjectFile {
|
|||||||
pub(super) size: u64,
|
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)]
|
#[derive(serde::Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub(super) struct ProjectInfo {
|
pub(super) struct ProjectInfo {
|
||||||
pub(super) id: String,
|
pub(super) id: String,
|
||||||
pub(super) name: String,
|
pub(super) name: String,
|
||||||
pub(super) main_file: String,
|
pub(super) main_file: String,
|
||||||
|
pub(super) compile_mode: CompileMode,
|
||||||
pub(super) created_at: u64,
|
pub(super) created_at: u64,
|
||||||
pub(super) updated_at: u64,
|
pub(super) updated_at: u64,
|
||||||
pub(super) files: Vec<ProjectFile>,
|
pub(super) files: Vec<ProjectFile>,
|
||||||
@@ -33,6 +54,7 @@ pub(super) struct ProjectInfo {
|
|||||||
struct Meta {
|
struct Meta {
|
||||||
name: String,
|
name: String,
|
||||||
main_file: String,
|
main_file: String,
|
||||||
|
compile_mode: CompileMode,
|
||||||
created_at: u64,
|
created_at: u64,
|
||||||
updated_at: u64,
|
updated_at: u64,
|
||||||
}
|
}
|
||||||
@@ -74,6 +96,7 @@ impl ProjectStore {
|
|||||||
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
|
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
|
||||||
name: id.to_string(),
|
name: id.to_string(),
|
||||||
main_file: String::new(),
|
main_file: String::new(),
|
||||||
|
compile_mode: CompileMode::Auto,
|
||||||
created_at: now_secs(),
|
created_at: now_secs(),
|
||||||
updated_at: now_secs(),
|
updated_at: now_secs(),
|
||||||
});
|
});
|
||||||
@@ -82,6 +105,7 @@ impl ProjectStore {
|
|||||||
id: id.to_string(),
|
id: id.to_string(),
|
||||||
name: meta.name,
|
name: meta.name,
|
||||||
main_file: meta.main_file,
|
main_file: meta.main_file,
|
||||||
|
compile_mode: meta.compile_mode,
|
||||||
created_at: meta.created_at,
|
created_at: meta.created_at,
|
||||||
updated_at: meta.updated_at,
|
updated_at: meta.updated_at,
|
||||||
files,
|
files,
|
||||||
@@ -89,12 +113,29 @@ impl ProjectStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn create_empty(&self, name: &str) -> Result<ProjectInfo, String> {
|
pub(super) fn create_empty(&self, name: &str) -> Result<ProjectInfo, String> {
|
||||||
|
self.create_empty_with_mode(name, CompileMode::Auto)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn create_empty_with_mode(
|
||||||
|
&self,
|
||||||
|
name: &str,
|
||||||
|
compile_mode: CompileMode,
|
||||||
|
) -> Result<ProjectInfo, String> {
|
||||||
let name = clean_name(name);
|
let name = clean_name(name);
|
||||||
let id = self.unique_id(&slug(&name));
|
let id = self.unique_id(&slug(&name));
|
||||||
let dir = self.root.join(&id);
|
let dir = self.root.join(&id);
|
||||||
fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?;
|
fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?;
|
||||||
let source =
|
let source = if compile_mode == CompileMode::Unicode {
|
||||||
"\\documentclass{article}\n\\begin{document}\nHello, world.\n\\end{document}\n";
|
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)
|
fs::write(dir.join("main.tex"), source)
|
||||||
.map_err(|error| format!("could not write main.tex: {error}"))?;
|
.map_err(|error| format!("could not write main.tex: {error}"))?;
|
||||||
self.save_meta(
|
self.save_meta(
|
||||||
@@ -102,6 +143,7 @@ impl ProjectStore {
|
|||||||
&Meta {
|
&Meta {
|
||||||
name,
|
name,
|
||||||
main_file: "main.tex".to_string(),
|
main_file: "main.tex".to_string(),
|
||||||
|
compile_mode,
|
||||||
created_at: now_secs(),
|
created_at: now_secs(),
|
||||||
updated_at: now_secs(),
|
updated_at: now_secs(),
|
||||||
},
|
},
|
||||||
@@ -173,6 +215,7 @@ impl ProjectStore {
|
|||||||
&Meta {
|
&Meta {
|
||||||
name,
|
name,
|
||||||
main_file,
|
main_file,
|
||||||
|
compile_mode: CompileMode::Auto,
|
||||||
created_at: now_secs(),
|
created_at: now_secs(),
|
||||||
updated_at: now_secs(),
|
updated_at: now_secs(),
|
||||||
},
|
},
|
||||||
@@ -180,6 +223,29 @@ impl ProjectStore {
|
|||||||
self.info(&id)
|
self.info(&id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn set_compile_mode(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
mode: CompileMode,
|
||||||
|
) -> Result<ProjectInfo, String> {
|
||||||
|
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> {
|
pub(super) fn delete(&self, id: &str) -> Result<(), String> {
|
||||||
let dir = self.project_dir(id)?;
|
let dir = self.project_dir(id)?;
|
||||||
if !dir.is_dir() {
|
if !dir.is_dir() {
|
||||||
@@ -322,6 +388,7 @@ impl ProjectStore {
|
|||||||
&Meta {
|
&Meta {
|
||||||
name: stem.to_string(),
|
name: stem.to_string(),
|
||||||
main_file: file_name.to_string(),
|
main_file: file_name.to_string(),
|
||||||
|
compile_mode: CompileMode::Auto,
|
||||||
created_at: now_secs(),
|
created_at: now_secs(),
|
||||||
updated_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 text = fs::read_to_string(self.meta_path(id)).ok()?;
|
||||||
let mut name = String::new();
|
let mut name = String::new();
|
||||||
let mut main_file = String::new();
|
let mut main_file = String::new();
|
||||||
|
let mut compile_mode = CompileMode::Auto;
|
||||||
let mut created_at = 0;
|
let mut created_at = 0;
|
||||||
let mut updated_at = 0;
|
let mut updated_at = 0;
|
||||||
for line in text.lines() {
|
for line in text.lines() {
|
||||||
@@ -420,6 +488,13 @@ impl ProjectStore {
|
|||||||
match key {
|
match key {
|
||||||
"name" => name = value.to_string(),
|
"name" => name = value.to_string(),
|
||||||
"main" => main_file = 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),
|
"created" => created_at = value.parse().unwrap_or(0),
|
||||||
"updated" => updated_at = value.parse().unwrap_or(0),
|
"updated" => updated_at = value.parse().unwrap_or(0),
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -432,6 +507,7 @@ impl ProjectStore {
|
|||||||
name
|
name
|
||||||
},
|
},
|
||||||
main_file,
|
main_file,
|
||||||
|
compile_mode,
|
||||||
created_at,
|
created_at,
|
||||||
updated_at,
|
updated_at,
|
||||||
})
|
})
|
||||||
@@ -439,20 +515,48 @@ impl ProjectStore {
|
|||||||
|
|
||||||
fn save_meta(&self, id: &str, meta: &Meta) -> Result<(), String> {
|
fn save_meta(&self, id: &str, meta: &Meta) -> Result<(), String> {
|
||||||
let text = format!(
|
let text = format!(
|
||||||
"name={}\nmain={}\ncreated={}\nupdated={}\n",
|
"name={}\nmain={}\ncreated={}\nupdated={}\ncompile_mode={}\n",
|
||||||
meta.name.replace(['\n', '\r'], " "),
|
meta.name.replace(['\n', '\r'], " "),
|
||||||
meta.main_file,
|
meta.main_file,
|
||||||
meta.created_at,
|
meta.created_at,
|
||||||
meta.updated_at
|
meta.updated_at,
|
||||||
|
meta.compile_mode.as_str()
|
||||||
);
|
);
|
||||||
fs::write(self.meta_path(id), text)
|
let path = self.meta_path(id);
|
||||||
.map_err(|error| format!("could not save project metadata: {error}"))
|
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> {
|
fn touch(&self, id: &str) -> Result<(), String> {
|
||||||
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
|
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
|
||||||
name: id.to_string(),
|
name: id.to_string(),
|
||||||
main_file: String::new(),
|
main_file: String::new(),
|
||||||
|
compile_mode: CompileMode::Auto,
|
||||||
created_at: now_secs(),
|
created_at: now_secs(),
|
||||||
updated_at: now_secs(),
|
updated_at: now_secs(),
|
||||||
});
|
});
|
||||||
@@ -566,6 +670,111 @@ fn entry_path(entry: &str) -> Option<String> {
|
|||||||
Some(trimmed.to_string())
|
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<String> {
|
fn detect_main(directory: &Path, names: &[String]) -> Option<String> {
|
||||||
for candidate in ["main.tex", "document.tex", "paper.tex", "article.tex"] {
|
for candidate in ["main.tex", "document.tex", "paper.tex", "article.tex"] {
|
||||||
if let Some(name) = names.iter().find(|name| name.as_str() == candidate) {
|
if let Some(name) = names.iter().find(|name| name.as_str() == candidate) {
|
||||||
|
|||||||
Reference in new issue
Block a user