Run cancellable pdfTeX matching in native frontends

This commit is contained in:
gloamxun committed 2026-11-20 16:43:48 +08:00
1 parent 091458d329
commit 6e573dc1ce
21 files changed
+665 -9

No files matched your search

+2
View File
@@ -9,5 +9,7 @@ mod native_generated;
mod native_host;
mod native_job;
mod native_preview;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod native_regex;
mod native_stream;
pub mod rust_typeset;
+3
View File
@@ -17,6 +17,9 @@ mod route_d;
use texrra_engine::rust_typeset;
fn main() {
if let Some(status) = texrra_engine::native::dispatch_pdf_regex_worker() {
std::process::exit(status);
}
if let Err(error) = run() {
eprintln!("error: {error}");
process::exit(1);
+10
View File
@@ -73,6 +73,16 @@ pub struct CompileRequest {
pub terminal: bool,
pub observer: Option<Arc<dyn CompileObserver>>,
}
/// Register this executable as the isolated pdfTeX matcher and handle its
/// internal worker invocation. Call before parsing application arguments, and
/// exit with the returned status when the invocation was handled.
pub fn dispatch_pdf_regex_worker() -> Option<i32> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
return crate::native_regex::dispatch();
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
None
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompileStage {
Prepared,
+11
View File
@@ -87,6 +87,17 @@ macro_rules! call {
}
impl SourceProvider for RecordingHost<'_> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
// GNU matching consumes only kernel-supplied bytes and is pinned to
// this executable on registered frontends. Its result is kernel state.
self.files.match_pdf_regex(request, cancellation)
}
fn execution_resource_trace(&self) -> Option<&ResourceTrace> {
self.files.execution_resource_trace()
}
+23
View File
@@ -151,6 +151,8 @@ struct DraftLedger {
pub struct Files {
world: FileWorld,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: Option<crate::native_regex::Worker>,
cwd: PathBuf,
inputs: BTreeMap<u8, Input>,
outputs: BTreeMap<u8, Output>,
@@ -547,6 +549,8 @@ impl Files {
preparation.phase = HostPreparationPhase::Ready;
Ok(Self {
world: stored_world.take().unwrap(),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: None,
cwd,
inputs: BTreeMap::new(),
outputs: BTreeMap::new(),
@@ -1404,6 +1408,25 @@ pub(crate) fn absolute_output(cwd: &Path, path: &Path) -> Result<PathBuf, String
}
impl SourceProvider for Files {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
use crate::native_regex::{self, Worker};
if !native_regex::enabled() {
return texrra_tex_core::execution::match_pdf_regex(request);
}
if self.regex_worker.is_none() {
self.regex_worker = Some(Worker::start()?);
}
self.regex_worker
.as_mut()
.expect("native matcher was started")
.request(request, cancellation)
}
fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> {
Some(self.world.trace())
}
+143
View File
@@ -0,0 +1,143 @@
use std::{
ffi::OsStr,
io::{self, BufRead, BufReader, Write},
process::{Child, Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, Receiver, Sender},
},
thread::{self, JoinHandle},
time::Duration,
};
use texrra_tex_core::execution::{Cancellation, RegexOutcome, RegexRequest, match_pdf_regex};
const WORKER_ARGUMENT: &str = "--internal-pdf-regex-worker";
static WORKER_ENABLED: AtomicBool = AtomicBool::new(false);
pub(crate) fn dispatch() -> Option<i32> {
let mut args = std::env::args_os().skip(1);
if args.next().as_deref() != Some(OsStr::new(WORKER_ARGUMENT)) {
WORKER_ENABLED.store(true, Ordering::Relaxed);
return None;
}
Some(match serve() {
Ok(()) => 0,
Err(error) => {
eprintln!("pdfTeX regex worker: {error}");
1
}
})
}
pub(crate) fn enabled() -> bool {
WORKER_ENABLED.load(Ordering::Relaxed)
}
fn serve() -> Result<(), Box<dyn std::error::Error>> {
let mut input = io::stdin().lock();
let mut output = io::stdout().lock();
let mut request = Vec::new();
loop {
request.clear();
if input.read_until(b'\n', &mut request)? == 0 {
return Ok(());
}
let request: RegexRequest = serde_json::from_slice(&request)?;
serde_json::to_writer(&mut output, &match_pdf_regex(&request))?;
output.write_all(b"\n")?;
output.flush()?;
}
}
pub(crate) struct Worker {
child: Child,
requests: Option<Sender<Vec<u8>>>,
answers: Receiver<Result<RegexOutcome, String>>,
pipe: Option<JoinHandle<()>>,
}
impl Worker {
pub(crate) fn start() -> Result<Self, String> {
// Re-execute the current image, even if an installer has replaced its
// original path since the process opened the project.
let mut child = Command::new("/proc/self/exe")
.arg(WORKER_ARGUMENT)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(|e| format!("pdfTeX regex worker launch: {e}"))?;
let mut input = child.stdin.take().expect("worker stdin is piped");
let mut output = BufReader::new(child.stdout.take().expect("worker stdout is piped"));
let (requests, waiting) = mpsc::channel::<Vec<u8>>();
let (answer, answers) = mpsc::sync_channel(1);
let pipe = thread::spawn(move || {
let mut response = Vec::new();
for request in waiting {
let result = (|| {
input.write_all(&request).map_err(|e| e.to_string())?;
input.write_all(b"\n").map_err(|e| e.to_string())?;
response.clear();
if output
.read_until(b'\n', &mut response)
.map_err(|e| e.to_string())?
== 0
{
return Err("pdfTeX regex worker closed its response pipe".into());
}
serde_json::from_slice::<Result<RegexOutcome, String>>(&response)
.map_err(|e| format!("pdfTeX regex response: {e}"))?
})();
if answer.send(result).is_err() {
break;
}
}
});
Ok(Self {
child,
requests: Some(requests),
answers,
pipe: Some(pipe),
})
}
pub(crate) fn request(
&mut self,
request: &RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
let payload = serde_json::to_vec(request).map_err(|e| e.to_string())?;
self.requests
.as_ref()
.ok_or("pdfTeX regex worker has stopped")?
.send(payload)
.map_err(|_| "pdfTeX regex worker has stopped")?;
loop {
if cancellation.is_some_and(Cancellation::is_cancelled) {
self.stop();
return Err("native compilation cancelled".into());
}
match self.answers.recv_timeout(Duration::from_millis(2)) {
Ok(result) => return result,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("pdfTeX regex worker lost its response pipe".into());
}
}
}
}
fn stop(&mut self) {
self.requests.take();
if let Some(pipe) = self.pipe.take() {
let _ = self.child.kill();
let _ = self.child.wait();
let _ = pipe.join();
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.stop();
}
}