Prepare EPS graphics and BibTeX references for desktop previews

This commit is contained in:
gloamxun committed 2026-12-02 10:41:10 +08:00
1 parent 715ad81bcf
commit b38e39416e
8 files changed
+787 -7

No files matched your search

+11
View File
@@ -13,6 +13,13 @@ Texrra 桌面程序。在项目库导入包含主 .tex 文件的 ZIP,打开项
项目存放在该目录下的 texrra-desktop/projects。窗口关闭时,桌面端停止 项目存放在该目录下的 texrra-desktop/projects。窗口关闭时,桌面端停止
自己启动的后台引擎。 自己启动的后台引擎。
0.1.2 在私有工作副本中转换缺少配套 PDF 的 EPS 图。转换使用包内
Fedora Ghostscript 及 bubblewrap,随后由原生引擎读取生成的 PDF。
现有 EPS 和已提供的转换 PDF 保留。标准 BibTeX 模板打开时从 TeX
生成的辅助文件构建参考文献,改动已引用的数据库或样式文件时更新。
WSL 中需要已有的 TeX Live bibtex 和 kpsewhich。模板中新增的引文及
更换引用样式命令在重新打开保存的源项目时读取。
## 构建 ## 构建
在引擎仓库根目录使用已经完成定向回归的原生 release 构建回执,准备 在引擎仓库根目录使用已经完成定向回归的原生 release 构建回执,准备
@@ -25,6 +32,10 @@ python3 desktop/build-backend.py prepare desktop/src-tauri/backend \
--commit full-engine-git-commit --commit full-engine-git-commit
``` ```
包含 EPS 转换功能的安装包在上述准备命令中提供
--eps-tools path/to/eps-tools.tar。该归档是可相对路径解包的 Fedora 工具树,
包含 usr/bin/bwrap、usr/bin/gs、运行资源及许可证和上游源包清单。
在 Windows 上使用 Tauri 的 MSVC 工具链构建。在 Fedora WSL 上使用 在 Windows 上使用 Tauri 的 MSVC 工具链构建。在 Fedora WSL 上使用
cargo-xwin、Windows SDK、LLVM 和 NSIS。 cargo-xwin、Windows SDK、LLVM 和 NSIS。
+28 -3
View File
@@ -13,6 +13,7 @@ import shutil
import signal import signal
import subprocess import subprocess
import sys import sys
import tarfile
import tempfile import tempfile
@@ -21,6 +22,7 @@ WEB_FILES = ("index.html", "styles.css", "favicon.svg", "app.js")
NATIVE_FILES = ("latex.tfx", "format-resources.json") NATIVE_FILES = ("latex.tfx", "format-resources.json")
EDITOR = "bin/native_editor" EDITOR = "bin/native_editor"
RECEIPT = "desktop-bundle.json" RECEIPT = "desktop-bundle.json"
EPS_TOOLS = "eps-tools.tar"
PAYLOAD = ( PAYLOAD = (
EDITOR, *NATIVE_FILES, "bundle.json", "native-beta.py", "wsl-launch.py", EDITOR, *NATIVE_FILES, "bundle.json", "native-beta.py", "wsl-launch.py",
*(f"web/{name}" for name in WEB_FILES), *(f"web/{name}" for name in WEB_FILES),
@@ -54,7 +56,10 @@ def package_receipt(directory):
data = (directory / RECEIPT).read_bytes() data = (directory / RECEIPT).read_bytes()
receipt = json.loads(data) receipt = json.loads(data)
files = receipt.get("sha256", {}) files = receipt.get("sha256", {})
require(receipt.get("schema") == 1 and set(files) == set(PAYLOAD), "Invalid desktop bundle receipt") expected = set(PAYLOAD)
if EPS_TOOLS in files:
expected.add(EPS_TOOLS)
require(receipt.get("schema") == 1 and set(files) == expected, "Invalid desktop bundle receipt")
require(all(is_sha(value) for value in files.values()), "Invalid desktop bundle hashes") require(all(is_sha(value) for value in files.values()), "Invalid desktop bundle hashes")
return data, files return data, files
@@ -116,6 +121,9 @@ def prepare(args, repo):
write_json(bundle / "bundle.json", manifest) write_json(bundle / "bundle.json", manifest)
hashes = {EDITOR: editor_sha, **native_sha} hashes = {EDITOR: editor_sha, **native_sha}
hashes.update({name: digest(bundle / name) for name in PAYLOAD if name not in hashes}) hashes.update({name: digest(bundle / name) for name in PAYLOAD if name not in hashes})
if args.eps_tools:
shutil.copyfile(args.eps_tools.resolve(strict=True), bundle / EPS_TOOLS)
hashes[EPS_TOOLS] = digest(bundle / EPS_TOOLS)
write_json(bundle / RECEIPT, { write_json(bundle / RECEIPT, {
"schema": 1, "native_commit": args.commit, "web_commit": WEB_COMMIT, "sha256": hashes, "schema": 1, "native_commit": args.commit, "web_commit": WEB_COMMIT, "sha256": hashes,
}) })
@@ -151,12 +159,26 @@ def install(package, home):
shutil.copyfile(package / name, path) shutil.copyfile(package / name, path)
check_file(path, expected) check_file(path, expected)
(bundle / EDITOR).chmod(0o700) (bundle / EDITOR).chmod(0o700)
if EPS_TOOLS in files:
root = bundle / "eps-tools"
root.mkdir(mode=0o700)
with tarfile.open(bundle / EPS_TOOLS) as archive:
archive.extractall(root, filter="data")
eps_environment(root)
(bundle / RECEIPT).write_bytes(receipt) (bundle / RECEIPT).write_bytes(receipt)
(bundle / "state").symlink_to(home / "state", target_is_directory=True) (bundle / "state").symlink_to(home / "state", target_is_directory=True)
bundle.rename(destination) bundle.rename(destination)
return destination return destination
def eps_environment(root):
bubblewrap = root / "usr/bin/bwrap"
ghostscript = root / "usr/bin/gs"
require(all(tool.is_file() and os.access(tool, os.X_OK) for tool in (bubblewrap, ghostscript)),
"Desktop EPS converter is missing or incomplete")
return {"TEXRRA_EPS_BWRAP": str(bubblewrap), "TEXRRA_EPS_GS_ROOT": str(root)}
def launch_error(message): def launch_error(message):
detail = " ".join(str(message).splitlines()) detail = " ".join(str(message).splitlines())
print(f"Texrra desktop error {detail}", flush=True) print(f"Texrra desktop error {detail}", flush=True)
@@ -187,8 +209,10 @@ def launch(args):
sys.executable, bundle / "native-beta.py", "web", "--web-dir", bundle / "web", sys.executable, bundle / "native-beta.py", "web", "--web-dir", bundle / "web",
"--projects-dir", home / "projects", "--port", "0", "--projects-dir", home / "projects", "--port", "0",
] ]
with subprocess.Popen(command, stdin=subprocess.DEVNULL, env = dict(os.environ, **{INSTANCE_ENV: args.instance})
env=dict(os.environ, **{INSTANCE_ENV: args.instance})) as child: if (bundle / EPS_TOOLS).is_file():
env.update(eps_environment(bundle / "eps-tools"))
with subprocess.Popen(command, stdin=subprocess.DEVNULL, env=env) as child:
try: try:
print(f"Texrra desktop PID {child.pid}", flush=True) print(f"Texrra desktop PID {child.pid}", flush=True)
while child.poll() is None: while child.poll() is None:
@@ -238,6 +262,7 @@ def main():
stage.add_argument("output", type=Path) stage.add_argument("output", type=Path)
stage.add_argument("--artifact-dir", type=Path, required=True) stage.add_argument("--artifact-dir", type=Path, required=True)
stage.add_argument("--commit", required=True) stage.add_argument("--commit", required=True)
stage.add_argument("--eps-tools", type=Path, help="optional Fedora EPS converter tar archive")
stage.add_argument("--reference-bundle", type=Path, stage.add_argument("--reference-bundle", type=Path,
default=repo / "target/p4-a4-child-release/browser-bundle") default=repo / "target/p4-a4-child-release/browser-bundle")
stage.add_argument("--web-repo", type=Path, default=repo.parent / "texrra-web") stage.add_argument("--web-repo", type=Path, default=repo.parent / "texrra-web")
+1 -1
View File
@@ -3237,7 +3237,7 @@ dependencies = [
[[package]] [[package]]
name = "texrra-desktop" name = "texrra-desktop"
version = "0.1.1" version = "0.1.2"
dependencies = [ dependencies = [
"serde_json", "serde_json",
"tauri", "tauri",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "texrra-desktop" name = "texrra-desktop"
version = "0.1.1" version = "0.1.2"
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 -1
View File
@@ -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.1", "version": "0.1.2",
"identifier": "org.texrra.desktop", "identifier": "org.texrra.desktop",
"build": { "build": {
"frontendDist": "../startup" "frontendDist": "../startup"
+475
View File
@@ -0,0 +1,475 @@
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
io::{self, Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
thread,
time::{Duration, Instant},
};
use texrra_engine::native::{CompileRequest, GeneratedArtifacts, ProjectSnapshot};
use texrra_tex_core::resources::ResourceVersion;
const MAX_AUX_BYTES: u64 = 2 * 1024 * 1024;
const MAX_INPUT_BYTES: u64 = 32 * 1024 * 1024;
const MAX_BBL_BYTES: u64 = 4 * 1024 * 1024;
const JOB: &str = "texrra-bibliography";
pub(super) fn from_seed(
request: &CompileRequest,
artifacts: &GeneratedArtifacts,
files: &BTreeMap<PathBuf, Arc<[u8]>>,
) -> Result<Option<(Plan, Arc<[u8]>)>, String> {
let cwd = &request.world.cwd;
let Some(name) = request.input.file_stem() else {
return Ok(None);
};
let mut jobname = name.to_os_string();
jobname.push(".bbl");
let bbl = cwd.join(jobname);
if files.contains_key(&bbl) {
return Ok(None);
}
let mut jobname = name.to_os_string();
jobname.push(".aux");
let aux = cwd.join(jobname);
let versions = artifacts
.writes
.iter()
.filter_map(|write| {
write
.after
.as_ref()
.filter(|version| version.path == write.path)
.map(|version| (write.path.as_path(), version))
})
.collect::<BTreeMap<_, _>>();
if !versions.contains_key(aux.as_path()) {
return Ok(None);
}
let mut input = AuxRecords::default();
input.read(cwd, &aux, &versions, 0)?;
if input.databases.is_empty() || !input.has_citation {
return Ok(None);
}
if let Some(issue) = input.include_issue {
return Err(issue);
}
let staged_style = input.style.ok_or("BibTeX requires a bibliography style")?;
let style = project_style(cwd, &staged_style, files)?;
let mut plan = Plan {
cwd: cwd.clone(),
output: bbl,
records: input.records,
databases: input
.databases
.into_iter()
.map(|path| cwd.join(path))
.collect(),
style,
staged_style,
system_style: None,
};
let scratch = Scratch::new(cwd).map_err(bib_error)?;
if !files.contains_key(&plan.style) {
plan.system_style = Some(find_style(
&scratch.0,
&plan.staged_style,
&request.world.texmf_roots,
)?);
}
let data = plan.run(&scratch.0, |path| files.get(path).map(Arc::as_ref))?;
Ok(Some((plan, data)))
}
pub(super) struct Plan {
cwd: PathBuf,
output: PathBuf,
records: Vec<u8>,
databases: Vec<PathBuf>,
style: PathBuf,
staged_style: PathBuf,
system_style: Option<Arc<[u8]>>,
}
impl Plan {
pub(super) fn output(&self) -> &Path {
&self.output
}
pub(super) fn update(
&self,
project: &ProjectSnapshot,
edits: &BTreeMap<PathBuf, Option<Arc<[u8]>>>,
) -> Result<Option<Arc<[u8]>>, String> {
if !self
.databases
.iter()
.chain(std::iter::once(&self.style))
.any(|path| {
edits.get(path).is_some_and(|new| {
new.as_deref() != project.file(path).map(|file| file.data.as_ref())
})
})
{
return Ok(None);
}
let scratch = Scratch::new(&self.cwd).map_err(bib_error)?;
self.run(&scratch.0, |path| {
edits.get(path).map_or_else(
|| project.file(path).map(|file| file.data.as_ref()),
Option::as_deref,
)
})
.map(Some)
}
fn run<'a>(
&self,
scratch: &Path,
mut contents: impl FnMut(&Path) -> Option<&'a [u8]>,
) -> Result<Arc<[u8]>, String> {
let mut total = 0;
// Stage only named databases and a single style from trusted inputs.
for path in self.databases.iter().chain(std::iter::once(&self.style)) {
let relative = if path == &self.style {
&self.staged_style
} else {
path.strip_prefix(&self.cwd)
.expect("checked bibliography path")
};
let data = contents(path)
.or_else(|| {
(path == &self.style)
.then_some(self.system_style.as_deref())
.flatten()
})
.ok_or_else(|| {
format!("BibTeX input missing from project: {}", relative.display())
})?;
total += data.len() as u64;
if total > MAX_INPUT_BYTES {
return Err("BibTeX inputs exceed the size limit".into());
}
stage(scratch, relative, data).map_err(bib_error)?;
}
fs::write(scratch.join(format!("{JOB}.aux")), &self.records).map_err(bib_error)?;
run_bibtex(scratch).map(Into::into)
}
}
#[derive(Default)]
struct AuxRecords {
records: Vec<u8>,
databases: Vec<PathBuf>,
style: Option<PathBuf>,
has_citation: bool,
visited: BTreeSet<PathBuf>,
total: u64,
include_issue: Option<String>,
}
impl AuxRecords {
fn read(
&mut self,
cwd: &Path,
aux: &Path,
versions: &BTreeMap<&Path, &ResourceVersion>,
depth: usize,
) -> Result<(), String> {
if depth > 16 || !self.visited.insert(aux.to_owned()) {
return Err("BibTeX auxiliary files are nested too deeply or repeated".into());
}
let version = versions
.get(aux)
.ok_or("BibTeX auxiliary file was not produced by this job")?;
let data = read_limited(aux, MAX_AUX_BYTES).map_err(bib_error)?;
self.total += data.len() as u64;
if self.total > MAX_AUX_BYTES {
return Err("BibTeX auxiliary files exceed the size limit".into());
}
if data.len() as u64 != version.bytes
|| format!("{:x}", Sha256::digest(&data)) != version.sha256
{
return Err("BibTeX auxiliary file changed after compilation".into());
}
for line in data.split(|&byte| byte == b'\n') {
let line = line.trim_ascii();
if line.starts_with(br"\@input{") {
let included = field(line, br"\@input{")
.and_then(|file| relative_name(file.expect("matched auxiliary input"), ".aux"));
if let Err(error) =
included.and_then(|file| self.read(cwd, &cwd.join(file), versions, depth + 1))
{
self.include_issue.get_or_insert(error);
}
continue;
}
if let Some(value) = field(line, br"\bibdata{")? {
if !self.databases.is_empty() {
return Err("BibTeX bibliography databases were specified twice".into());
}
self.databases = value
.split(|&byte| byte == b',')
.map(|name| relative_name(name, ".bib"))
.collect::<Result<_, _>>()?;
} else if let Some(value) = field(line, br"\bibstyle{")? {
if self.style.replace(relative_name(value, ".bst")?).is_some() {
return Err("BibTeX bibliography style was specified twice".into());
}
} else if field(line, br"\citation{")?.is_some() {
self.has_citation = true;
} else {
continue;
}
self.records.extend_from_slice(line);
self.records.push(b'\n');
}
Ok(())
}
}
fn field<'a>(line: &'a [u8], prefix: &[u8]) -> Result<Option<&'a [u8]>, String> {
let Some(rest) = line.strip_prefix(prefix) else {
return Ok(None);
};
let value = rest
.strip_suffix(b"}")
.ok_or("Malformed BibTeX auxiliary record")?;
if value
.iter()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'{' | b'}' | b'\\'))
{
return Err("Malformed BibTeX auxiliary record".into());
}
Ok(Some(value))
}
fn relative_name(value: &[u8], extension: &str) -> Result<PathBuf, String> {
let name =
std::str::from_utf8(value.trim_ascii()).map_err(|_| "BibTeX filenames must be UTF-8")?;
if name.is_empty()
|| name.len() > 240
|| name.split('/').any(|part| {
!part
.as_bytes()
.first()
.is_some_and(u8::is_ascii_alphanumeric)
|| !part
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
|| part.ends_with('.')
})
{
return Err(format!("Unsafe BibTeX filename: {name}"));
}
if name.ends_with(extension) {
Ok(name.into())
} else {
Ok(format!("{name}{extension}").into())
}
}
fn read_limited(path: &Path, limit: u64) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
fs::File::open(path)?
.take(limit + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > limit {
return Err(io::Error::other("file exceeds the BibTeX size limit"));
}
Ok(bytes)
}
fn stage(root: &Path, relative: &Path, data: &[u8]) -> io::Result<()> {
let path = root.join(relative);
fs::create_dir_all(path.parent().expect("staged files have a parent"))?;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)?;
file.write_all(data)
}
fn bib_error(error: io::Error) -> String {
format!("BibTeX: {error}")
}
fn private_environment<'a>(command: &'a mut Command, scratch: &Path) -> &'a mut Command {
command
.current_dir(scratch)
.env_clear()
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.env("HOME", scratch)
.env("TEXMFHOME", scratch)
.env("TEXMFVAR", scratch)
.env("TEXMFCONFIG", scratch)
.env("openin_any", "p")
.env("openout_any", "p")
.env("shell_escape", "f")
.stdin(Stdio::null())
}
fn project_style(
cwd: &Path,
style: &Path,
files: &BTreeMap<PathBuf, Arc<[u8]>>,
) -> Result<PathBuf, String> {
let direct = cwd.join(style);
if files.contains_key(&direct) || style.components().count() != 1 {
return Ok(direct);
}
let mut matches = files
.keys()
.filter(|path| path.starts_with(cwd) && path.file_name() == style.file_name());
let found = matches.next().cloned().unwrap_or(direct);
if matches.next().is_some() {
return Err(format!(
"BibTeX style has more than one project match: {}",
style.display()
));
}
Ok(found)
}
fn find_style(scratch: &Path, style: &Path, roots: &[PathBuf]) -> Result<Arc<[u8]>, String> {
if style.components().count() != 1 {
return Err(format!(
"BibTeX style missing from project: {}",
style.display()
));
}
let result = private_environment(&mut Command::new("kpsewhich"), scratch)
.arg("--format=bst")
.arg(style)
.output()
.map_err(bib_error)?;
if !result.status.success() {
return Err(format!("BibTeX style missing: {}", style.display()));
}
let found = std::str::from_utf8(&result.stdout)
.map_err(|_| "BibTeX style path is not UTF-8")?
.trim_ascii();
let path = Path::new(found);
if !path.is_absolute() {
return Err("BibTeX style is outside the configured TeX resources".into());
}
let path = path.canonicalize().map_err(bib_error)?;
if !roots
.iter()
.filter_map(|root| root.canonicalize().ok())
.any(|root| path.starts_with(root))
{
return Err("BibTeX style is outside the configured TeX resources".into());
}
read_limited(&path, MAX_INPUT_BYTES)
.map(Into::into)
.map_err(bib_error)
}
fn run_bibtex(scratch: &Path) -> Result<Vec<u8>, String> {
#[cfg(target_os = "linux")]
let mut command = {
// Bound project-provided .bst programs on our Linux backend.
let mut command = Command::new("prlimit");
command.args([
"--fsize=4194304",
"--cpu=4",
"--as=134217728",
"--",
"bibtex",
]);
command
};
#[cfg(not(target_os = "linux"))]
let mut command = Command::new("bibtex");
let mut child = private_environment(&mut command, scratch)
.env("BIBINPUTS", ".")
.env("BSTINPUTS", ".")
.arg(JOB)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map_err(bib_error)?;
let deadline = Instant::now() + Duration::from_secs(5);
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() || status.code() == Some(1) => {
return read_limited(&scratch.join(format!("{JOB}.bbl")), MAX_BBL_BYTES)
.map_err(bib_error);
}
Ok(Some(status)) => return Err(format!("BibTeX failed ({status})")),
Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)),
result => {
let _ = child.kill();
let _ = child.wait();
return Err(result
.err()
.map_or_else(|| "BibTeX exceeded the time limit".into(), bib_error));
}
}
}
}
struct Scratch(PathBuf);
impl Scratch {
fn new(cwd: &Path) -> io::Result<Self> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let mut builder = fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
loop {
let index = NEXT.fetch_add(1, Ordering::Relaxed);
let path = cwd.join(format!(
".texrra-bibliography-{}-{index}",
std::process::id()
));
match builder.create(&path) {
Ok(()) => return Ok(Self(path)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bibliography_names_stay_inside_scratch_paths() {
assert_eq!(
relative_name(b"bib/references.v1", ".bib").unwrap(),
Path::new("bib/references.v1.bib")
);
for name in [
&b"../credentials"[..],
b"/home/private",
b"C:\\private",
b"folder/../private",
b"folder//private",
b"-option",
b"file\0",
] {
assert!(relative_name(name, ".bib").is_err());
}
assert!(field(br"\bibdata{ok}\@input{../private}", br"\bibdata{").is_err());
assert!(field(br"\citation{ok}", br"\citation{").unwrap().is_some());
}
}
+223
View File
@@ -0,0 +1,223 @@
use std::path::{Path, PathBuf};
pub(super) fn converted_relative_path(relative: &Path, bytes: &[u8]) -> Option<PathBuf> {
let extension = relative.extension()?.to_str()?;
if !extension.eq_ignore_ascii_case("eps")
|| !(bytes.starts_with(b"%!PS") || bytes.starts_with(&[0xc5, 0xd0, 0xd3, 0xc6]))
{
return None;
}
let mut filename = relative.file_stem()?.to_os_string();
filename.push("-eps-converted-to.pdf");
Some(relative.with_file_name(filename))
}
#[cfg(not(target_os = "linux"))]
pub(super) fn convert(_run: &Path, _source: &[u8]) -> std::io::Result<Option<Vec<u8>>> {
Ok(None)
}
#[cfg(target_os = "linux")]
pub(super) use linux::convert;
#[cfg(target_os = "linux")]
mod linux {
use std::{
env, fs,
io::{self, Read},
os::unix::{fs::DirBuilderExt, process::CommandExt},
path::{Path, PathBuf},
process::{Command, Stdio},
sync::atomic::{AtomicU64, Ordering},
thread,
time::{Duration, Instant},
};
const MAX_PDF_BYTES: u64 = 64 * 1024 * 1024;
const MAX_ADDRESS_SPACE: libc::rlim_t = 768 * 1024 * 1024;
const MAX_CPU_SECONDS: libc::rlim_t = 5;
const TIME_LIMIT: Duration = Duration::from_secs(8);
static NEXT_SCRATCH: AtomicU64 = AtomicU64::new(0);
struct Scratch(PathBuf);
impl Scratch {
fn new(run: &Path) -> io::Result<Self> {
loop {
let serial = NEXT_SCRATCH.fetch_add(1, Ordering::Relaxed);
let path = run.join(format!(".texrra-eps-{}-{serial}", std::process::id()));
match fs::DirBuilder::new().mode(0o700).create(&path) {
Ok(()) => return Ok(Self(path)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
pub(crate) fn convert(run: &Path, source: &[u8]) -> io::Result<Option<Vec<u8>>> {
let bwrap = env::var_os("TEXRRA_EPS_BWRAP");
let tool_root = env::var_os("TEXRRA_EPS_GS_ROOT");
let (bwrap, tool_root) = match (bwrap, tool_root) {
(None, None) => return Ok(None),
(Some(bwrap), Some(root)) => (PathBuf::from(bwrap), PathBuf::from(root)),
_ => {
return Err(io::Error::other(
"EPS conversion needs both TEXRRA_EPS_BWRAP and TEXRRA_EPS_GS_ROOT",
));
}
};
if !bwrap.is_absolute()
|| !tool_root.is_absolute()
|| !bwrap.is_file()
|| !tool_root.join("usr/bin/gs").is_file()
{
return Err(io::Error::other(
"EPS conversion needs an absolute bubblewrap executable and Ghostscript tool root",
));
}
let scratch = Scratch::new(run)?;
let input = scratch.0.join("input.eps");
let output = scratch.0.join("output.pdf");
fs::write(&input, source)?;
fs::File::create_new(&output)?;
let mut command = Command::new(bwrap);
command
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.args([
"--unshare-user",
"--unshare-pid",
"--unshare-net",
"--unshare-ipc",
"--unshare-uts",
"--disable-userns",
"--new-session",
"--die-with-parent",
"--clearenv",
"--ro-bind",
"/usr/lib64",
"/usr/lib64",
"--symlink",
"usr/lib64",
"/lib64",
"--dev",
"/dev",
"--size",
"67108864",
"--tmpfs",
"/tmp",
"--chdir",
"/tmp",
"--ro-bind",
])
.arg(&tool_root)
.args([
"/tool",
"--symlink",
"/tool/usr/share",
"/usr/share",
"--ro-bind",
])
.arg(&input)
.args(["/input.eps", "--bind"])
.arg(&output)
.args([
"/output.pdf",
"--setenv",
"LD_LIBRARY_PATH",
"/tool/usr/lib64",
"--setenv",
"HOME",
"/tmp",
"--setenv",
"TMPDIR",
"/tmp",
"--setenv",
"SOURCE_DATE_EPOCH",
"1783900800",
"--",
"/tool/usr/bin/gs",
"-q",
"-dSAFER",
"-dBATCH",
"-dNOPAUSE",
"-dEPSCrop",
"-dNOPLATFONTS",
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.5",
"-dAutoRotatePages=/None",
"-dOmitID",
"-dOmitInfoDate",
"-dOmitXMP",
"-sOutputFile=/output.pdf",
"-f",
"/input.eps",
]);
// These limits are inherited by bubblewrap and every process it launches.
unsafe {
command.pre_exec(|| {
for (resource, maximum) in [
(libc::RLIMIT_FSIZE, MAX_PDF_BYTES as libc::rlim_t),
(libc::RLIMIT_AS, MAX_ADDRESS_SPACE),
(libc::RLIMIT_CPU, MAX_CPU_SECONDS),
] {
let limit = libc::rlimit {
rlim_cur: maximum,
rlim_max: maximum,
};
if libc::setrlimit(resource, &limit) != 0 {
return Err(io::Error::last_os_error());
}
}
Ok(())
});
}
let mut child = command.spawn()?;
let deadline = Instant::now() + TIME_LIMIT;
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() => break,
Ok(Some(status)) => {
return Err(io::Error::other(format!(
"isolated EPS converter exited with {status}"
)));
}
Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)),
result => {
let _ = child.kill();
let _ = child.wait();
return Err(result.err().unwrap_or_else(|| {
io::Error::new(io::ErrorKind::TimedOut, "isolated EPS conversion timed out")
}));
}
}
}
let mut pdf = Vec::new();
fs::File::open(output)?
.take(MAX_PDF_BYTES + 1)
.read_to_end(&mut pdf)?;
if pdf.len() as u64 > MAX_PDF_BYTES
|| !pdf.starts_with(b"%PDF-")
|| !pdf.trim_ascii_end().ends_with(b"%%EOF")
{
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid converted EPS PDF",
));
}
Ok(Some(pdf))
}
}
+47 -1
View File
@@ -25,6 +25,8 @@ use texrra_tex_core::{
use thread_usage::ThreadUsage; use thread_usage::ThreadUsage;
use tiny_http::{Header, Method, Request, Response, Server}; use tiny_http::{Header, Method, Request, Response, Server};
mod bibliography;
mod figure_conversion;
mod library; mod library;
mod preview_socket; mod preview_socket;
#[path = "../../src/projects.rs"] #[path = "../../src/projects.rs"]
@@ -674,6 +676,7 @@ impl EditorSession {
entry, entry,
editable, editable,
options, options,
bibliography,
.. ..
} = &mut self.editor; } = &mut self.editor;
if edit.sequence <= self.queue.current.load(Ordering::Acquire) { if edit.sequence <= self.queue.current.load(Ordering::Acquire) {
@@ -699,6 +702,11 @@ impl EditorSession {
{ {
return Err("The entry file was edited twice".into()); return Err("The entry file was edited twice".into());
} }
if let Some(plan) = bibliography
&& let Some(contents) = plan.update(project, &updates)?
{
updates.insert(plan.output().to_owned(), Some(contents));
}
project.with_file_changes(edit.sequence, updates) project.with_file_changes(edit.sequence, updates)
}); });
*project = match next { *project = match next {
@@ -759,6 +767,7 @@ struct EditorProject {
editable: BTreeMap<String, PathBuf>, editable: BTreeMap<String, PathBuf>,
declared: BTreeSet<PathBuf>, declared: BTreeSet<PathBuf>,
options: CompileRequest, options: CompileRequest,
bibliography: Option<bibliography::Plan>,
} }
fn copy_with_date( fn copy_with_date(
@@ -869,6 +878,27 @@ fn prepare(
files.insert(logical, Arc::from(data)); files.insert(logical, Arc::from(data));
} }
} }
let figures = additional.iter().filter_map(|relative| {
let input = run.join(relative);
let data = files.get(&input)?;
let converted = run.join(figure_conversion::converted_relative_path(relative, data)?);
if files.contains_key(&converted) {
return None;
}
let date = dates.get(&input).and_then(|time| time.to_system_time());
Some((converted, data.clone(), date))
}).collect::<Vec<_>>();
for (path, source, date) in figures {
match figure_conversion::convert(run, &source) {
Ok(Some(pdf)) => {
let modified = date.unwrap_or_else(SystemTime::now);
copy_with_date(&path, &pdf, Some(modified), &mut dates)?;
files.insert(path, Arc::from(pdf));
}
Ok(None) => {}
Err(error) => eprintln!("Editor EPS conversion for {}: {error}", path.display()),
}
}
let mut output = entry.with_extension("pdf"); let mut output = entry.with_extension("pdf");
if declared.contains(&output) || declared.contains(&output.with_extension("log")) { if declared.contains(&output) || declared.contains(&output.with_extension("log")) {
let directory = run.join(".texrra-output"); let directory = run.join(".texrra-output");
@@ -884,7 +914,22 @@ fn prepare(
request = request.observe_generated_initial(); request = request.observe_generated_initial();
// Provision the finite, immutable resource bundle used by this trial. // Provision the finite, immutable resource bundle used by this trial.
// The seed uses the same native compiler and actual package bytes. // The seed uses the same native compiler and actual package bytes.
let seed = NativeCompiler::default().compile_detailed(request.clone()); let compiler = NativeCompiler::default();
let mut seed = compiler.compile_detailed(request.clone());
let mut bibliography = None;
if let Ok(initial) = &seed {
match bibliography::from_seed(&request, &initial.resources.generated_artifacts, &files) {
Ok(Some((plan, contents))) => {
let path = plan.output().to_owned();
copy_with_date(&path, &contents, Some(SystemTime::now()), &mut dates)?;
files.insert(path, contents);
bibliography = Some(plan);
seed = compiler.compile_detailed(request.clone());
}
Ok(None) => {}
Err(error) => eprintln!("Editor bibliography: {error}"),
}
}
let (inputs, trace, generated) = match &seed { let (inputs, trace, generated) = match &seed {
Ok(seed) => ( Ok(seed) => (
Some(seed.inputs.as_ref()), Some(seed.inputs.as_ref()),
@@ -969,6 +1014,7 @@ fn prepare(
editable, editable,
declared, declared,
options: request, options: request,
bibliography,
}) })
} }