1564 lines
59 KiB
Rust
1564 lines
59 KiB
Rust
//! Shared strict Route-D compilation, resource closure and revision publication.
|
||
//! No process cwd changes, legacy frontend, or external TeX compilation.
|
||
#[path = "native_checkpoint_guard.rs"]
|
||
mod checkpoint_guard;
|
||
#[path = "native_checkpoint_probe.rs"]
|
||
mod checkpoint_probe;
|
||
|
||
pub use crate::native_generated::{GeneratedInitialState, GeneratedInputPolicy};
|
||
pub use crate::native_host::{
|
||
HostMetadata, HostObservation, HostPreparation, HostPreparationPhase, LedgerRead,
|
||
VersionExpectation,
|
||
};
|
||
pub use crate::native_job::job_time;
|
||
use crate::native_job::{
|
||
DraftSyncQueue, EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output,
|
||
file_modification_date,
|
||
};
|
||
use crate::native_preview::{PreviewFonts, PreviewState};
|
||
pub use crate::native_preview::{PreviewPage, PreviewUpdate};
|
||
pub use crate::native_stream::{
|
||
DescriptorIdentity, InputOpened, InputStorage, ReleaseCause, StreamEffect, StreamEvent,
|
||
StreamJournal, WriteAttempt, WriteOutcome,
|
||
};
|
||
use checkpoint_guard::CheckpointCache;
|
||
pub use checkpoint_guard::EntryCheckpointWork;
|
||
use std::{
|
||
collections::BTreeMap,
|
||
path::{Path, PathBuf},
|
||
sync::{Arc, Mutex},
|
||
};
|
||
pub use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot, ProjectVersion};
|
||
pub use texrra_tex_core::resources::{WorldFailure, WorldObservation};
|
||
use texrra_tex_core::{
|
||
execution::{
|
||
Cancellation, ExecutionFailure, Executor, FormatImage, InputProfile, JobTime, Limits,
|
||
NativeSession, Profile, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
|
||
SourceProvider, State, WriteDestination,
|
||
},
|
||
pdf_unicode::XdvGlyphNames,
|
||
render::{DisplayItem, DisplayList},
|
||
resources::{FileWorld, InputSnapshot, ResourceTrace, ResourceVersion, WorldConfig},
|
||
};
|
||
|
||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||
pub enum Entry {
|
||
Bootstrap,
|
||
Initex,
|
||
Format(PathBuf),
|
||
}
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||
pub enum Target {
|
||
Shipouts,
|
||
Paragraphs,
|
||
}
|
||
|
||
#[derive(Clone)]
|
||
pub struct CompileRequest {
|
||
pub world: WorldConfig,
|
||
pub inputs: Option<Arc<InputSnapshot>>,
|
||
pub project: Option<Arc<ProjectSnapshot>>,
|
||
pub generated_inputs: GeneratedInputPolicy,
|
||
pub input: PathBuf,
|
||
pub output: PathBuf,
|
||
pub entry: Entry,
|
||
pub target: Target,
|
||
pub etex: bool,
|
||
pub input_profile: InputProfile,
|
||
pub translation_file: Option<PathBuf>,
|
||
pub time: JobTime,
|
||
pub limits: Limits,
|
||
pub resource_manifest: Option<PathBuf>,
|
||
pub layout_manifest: Option<PathBuf>,
|
||
/// Failure reports only create new files; existing files are never replaced.
|
||
pub failure_manifest: Option<PathBuf>,
|
||
/// Whether the host sends TeX terminal diagnostics to stderr.
|
||
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,
|
||
Executed,
|
||
FontsResolved,
|
||
Exported,
|
||
ReadyToPublish,
|
||
}
|
||
/// Called outside the publication lock. An observer can request a new
|
||
/// revision or fail without publishing this result. Start/cancel are allowed;
|
||
/// schedule compilation after the callback returns, rather than recursing.
|
||
pub trait CompileObserver: Send + Sync {
|
||
fn stage(&self, revision: u64, stage: CompileStage) -> Result<(), String>;
|
||
|
||
/// Called for a completed native draft before its staged files are synced
|
||
/// and installed. The caller can display these pages provisionally. The
|
||
/// compile result determines whether this revision actually published.
|
||
fn draft_ready(&self, _draft: DraftPreview<'_>) -> Result<(), String> {
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
/// The same revision's native preview, available before artifact publication.
|
||
pub struct DraftPreview<'a> {
|
||
document: &'a CompiledDocument,
|
||
cancellation: &'a Cancellation,
|
||
}
|
||
|
||
impl DraftPreview<'_> {
|
||
pub fn preview_since(&self, visible_revision: Option<u64>) -> Result<PreviewUpdate, String> {
|
||
self.document.preview.render(
|
||
self.document.revision(),
|
||
&self.document.pages,
|
||
self.document.pdf.as_ref(),
|
||
visible_revision,
|
||
|| check(self.cancellation).map_err(|error| error.to_string()),
|
||
)
|
||
}
|
||
|
||
pub fn execution_steps(&self) -> usize {
|
||
self.document.execution.execution.steps
|
||
}
|
||
|
||
pub fn entry_checkpoint_work(&self) -> &EntryCheckpointWork {
|
||
&self.document.entry_checkpoint_work
|
||
}
|
||
}
|
||
fn notify(
|
||
request: &CompileRequest,
|
||
revision: u64,
|
||
stage: CompileStage,
|
||
cancellation: &Cancellation,
|
||
) -> Result<(), CompileError> {
|
||
check(cancellation)?;
|
||
if let Some(observer) = &request.observer {
|
||
let result = observer.stage(revision, stage);
|
||
check(cancellation)?;
|
||
result?;
|
||
}
|
||
Ok(())
|
||
}
|
||
impl CompileRequest {
|
||
pub fn new(
|
||
world: WorldConfig,
|
||
input: impl Into<PathBuf>,
|
||
output: impl Into<PathBuf>,
|
||
time: JobTime,
|
||
) -> Self {
|
||
Self {
|
||
world,
|
||
inputs: None,
|
||
project: None,
|
||
generated_inputs: GeneratedInputPolicy::Live,
|
||
input: input.into(),
|
||
output: output.into(),
|
||
entry: Entry::Bootstrap,
|
||
target: Target::Shipouts,
|
||
etex: false,
|
||
input_profile: InputProfile::TeX8Bit,
|
||
translation_file: None,
|
||
time,
|
||
limits: Limits::default(),
|
||
resource_manifest: None,
|
||
layout_manifest: None,
|
||
failure_manifest: None,
|
||
terminal: false,
|
||
observer: None,
|
||
}
|
||
}
|
||
pub fn with_inputs(mut self, inputs: Arc<InputSnapshot>) -> Self {
|
||
self.project = None;
|
||
self.world = inputs.configuration();
|
||
self.inputs = Some(inputs);
|
||
self
|
||
}
|
||
pub fn with_project(mut self, project: Arc<ProjectSnapshot>) -> Self {
|
||
self.world = project.configuration();
|
||
self.inputs = None;
|
||
self.project = Some(project);
|
||
self
|
||
}
|
||
pub fn with_generated_initial(mut self, state: GeneratedInitialState) -> Self {
|
||
self.generated_inputs = GeneratedInputPolicy::Expect(state);
|
||
self
|
||
}
|
||
pub fn observe_generated_initial(mut self) -> Self {
|
||
self.generated_inputs = GeneratedInputPolicy::Observe;
|
||
self
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||
pub struct GeneratedWrite {
|
||
/// Actual opened path even if both version inspections find it absent.
|
||
#[serde(default)]
|
||
pub path: PathBuf,
|
||
pub producer: PathBuf,
|
||
pub before: Option<ResourceVersion>,
|
||
pub after: Option<ResourceVersion>,
|
||
}
|
||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||
pub struct GeneratedArtifacts {
|
||
pub schema: u32,
|
||
pub ledger_path: PathBuf,
|
||
pub ledger_input: Option<ResourceVersion>,
|
||
/// Last version accepted or written by this host. A failed live check can
|
||
/// observe a different version; that actual result is in host_runtime.
|
||
pub ledger_current: Option<ResourceVersion>,
|
||
pub writes: Vec<GeneratedWrite>,
|
||
}
|
||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||
pub struct ResourceSnapshot {
|
||
#[serde(flatten)]
|
||
pub trace: ResourceTrace,
|
||
pub generated_artifacts: GeneratedArtifacts,
|
||
#[serde(default)]
|
||
pub generated_initial: Option<GeneratedInitialState>,
|
||
#[serde(default)]
|
||
pub stream_io: StreamJournal,
|
||
}
|
||
|
||
pub struct CompiledDocument {
|
||
pub execution: Arc<RevisionExecution>,
|
||
pub entry_checkpoint_work: EntryCheckpointWork,
|
||
pub format_preparation: Option<FormatPreparation>,
|
||
/// Actual paragraph search performed or reused in this revision.
|
||
pub line_break_work: texrra_tex_core::execution::LineBreakWork,
|
||
/// Work converting shipped boxes to local drawing lists before resolving PDF resources.
|
||
pub shipout_layout_work: ShipoutLayoutWork,
|
||
/// Type 1 glyph and PDF subset work in this revision.
|
||
pub type1_font_work: texrra_tex_core::native_font::Type1FontWork,
|
||
/// Original measurements with actual resolved font programs.
|
||
pub pages: Vec<DisplayList>,
|
||
/// Revision-local measured paint and source versions. `unmapped` explicitly
|
||
/// records uncollected legacy or diagnostic paint without guessing origins.
|
||
pub source_map: texrra_tex_core::source_map::SourceMap,
|
||
/// Includes resources read while embedding fonts, after execution.
|
||
pub resources: ResourceSnapshot,
|
||
pub inputs: Arc<InputSnapshot>,
|
||
pub host_preparation: HostPreparation,
|
||
pub host_runtime: Vec<HostObservation>,
|
||
pub export_diagnostics: Vec<String>,
|
||
/// Immutable bytes stay associated with this revision after another publish.
|
||
pub pdf: Option<Arc<[u8]>>,
|
||
/// The same revision’s bytes when TeX selected the DVI device.
|
||
pub dvi: Option<Arc<[u8]>>,
|
||
pub output: Option<ResourceVersion>,
|
||
preview: PreviewState,
|
||
shipout_layouts: Vec<Arc<DisplayList>>,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||
pub struct ShipoutLayoutWork {
|
||
pub lowered_pages: usize,
|
||
pub reused_pages: usize,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum FormatPreparation {
|
||
Decoded,
|
||
Reused,
|
||
}
|
||
impl CompiledDocument {
|
||
pub fn revision(&self) -> u64 {
|
||
self.execution.revision
|
||
}
|
||
/// Render updates for a preview of an earlier published revision in this
|
||
/// compiler session. An unknown revision gets a complete preview.
|
||
pub fn preview_since(&self, visible_revision: Option<u64>) -> Result<PreviewUpdate, String> {
|
||
self.preview.render(
|
||
self.revision(),
|
||
&self.pages,
|
||
self.pdf.as_ref(),
|
||
visible_revision,
|
||
|| Ok(()),
|
||
)
|
||
}
|
||
pub fn has_show_diagnostic(&self) -> bool {
|
||
self.execution.execution.events.iter().any(|e| {
|
||
matches!(
|
||
e,
|
||
texrra_tex_core::execution::Event::ShowBox(_)
|
||
| texrra_tex_core::execution::Event::Show(_)
|
||
)
|
||
})
|
||
}
|
||
}
|
||
pub struct BuiltFormat {
|
||
pub output: ResourceVersion,
|
||
pub resources: ResourceSnapshot,
|
||
pub inputs: Arc<InputSnapshot>,
|
||
pub host_preparation: HostPreparation,
|
||
pub host_runtime: Vec<HostObservation>,
|
||
pub execution: Arc<RevisionExecution>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||
pub enum CompileError {
|
||
Cancelled,
|
||
Execution(Box<texrra_tex_core::execution::Error>),
|
||
Host(String),
|
||
}
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||
pub enum AttemptPhase {
|
||
Queued,
|
||
Preparing,
|
||
Prepared,
|
||
Executing,
|
||
Layout,
|
||
Fonts,
|
||
Export,
|
||
Finishing,
|
||
ReadyToPublish,
|
||
Publishing,
|
||
}
|
||
#[derive(Debug, serde::Serialize)]
|
||
pub struct CompileFailure {
|
||
pub request: AttemptRequest,
|
||
pub revision: u64,
|
||
pub phase: AttemptPhase,
|
||
pub error: CompileError,
|
||
pub failed_execution: Option<ExecutionFailure>,
|
||
pub completed_execution: Option<Arc<RevisionExecution>>,
|
||
pub trace: Option<ResourceTrace>,
|
||
pub inputs: Option<Arc<InputSnapshot>>,
|
||
pub resources: Option<ResourceSnapshot>,
|
||
pub host_preparation: HostPreparation,
|
||
pub host_runtime: Vec<HostObservation>,
|
||
pub world_failure: Option<WorldFailure>,
|
||
/// Policy/stat/locking and partial finalization can be unavailable. These
|
||
/// records never authorize caching/reusing a failed computation.
|
||
pub evidence_gaps: Vec<String>,
|
||
pub export_diagnostics: Vec<String>,
|
||
}
|
||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||
pub struct AttemptRequest {
|
||
pub world: WorldConfig,
|
||
pub input: PathBuf,
|
||
pub output: PathBuf,
|
||
pub entry: Entry,
|
||
pub target: Target,
|
||
pub etex: bool,
|
||
pub input_profile: InputProfile,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub translation_file: Option<PathBuf>,
|
||
pub time: JobTime,
|
||
pub limits: Limits,
|
||
pub resource_manifest: Option<PathBuf>,
|
||
pub layout_manifest: Option<PathBuf>,
|
||
pub failure_manifest: Option<PathBuf>,
|
||
pub terminal: bool,
|
||
pub observer_attached: bool,
|
||
pub replay_requested: bool,
|
||
pub project_version: Option<ProjectVersion>,
|
||
#[serde(default)]
|
||
pub generated_inputs: GeneratedInputPolicy,
|
||
}
|
||
impl From<&CompileRequest> for AttemptRequest {
|
||
fn from(r: &CompileRequest) -> Self {
|
||
Self {
|
||
world: r.world.clone(),
|
||
input: r.input.clone(),
|
||
output: r.output.clone(),
|
||
entry: r.entry.clone(),
|
||
target: r.target,
|
||
etex: r.etex,
|
||
input_profile: r.input_profile,
|
||
translation_file: r.translation_file.clone(),
|
||
time: r.time,
|
||
limits: r.limits,
|
||
resource_manifest: r.resource_manifest.clone(),
|
||
layout_manifest: r.layout_manifest.clone(),
|
||
failure_manifest: r.failure_manifest.clone(),
|
||
terminal: r.terminal,
|
||
observer_attached: r.observer.is_some(),
|
||
replay_requested: r.inputs.is_some(),
|
||
generated_inputs: r.generated_inputs.clone(),
|
||
project_version: r.project.as_ref().map(|p| p.version().clone()).or_else(|| {
|
||
r.inputs
|
||
.as_ref()
|
||
.and_then(|s| s.project().map(|p| p.version().clone()))
|
||
}),
|
||
}
|
||
}
|
||
}
|
||
impl std::fmt::Display for CompileFailure {
|
||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
self.error.fmt(f)
|
||
}
|
||
}
|
||
impl std::error::Error for CompileFailure {}
|
||
impl CompileFailure {
|
||
/// Persist the actual typed failure, including captured bytes, in a new
|
||
/// file. This is evidence, not an executable checkpoint or lock lease.
|
||
pub fn write_manifest(&self, path: &std::path::Path) -> Result<(), String> {
|
||
let cwd = self
|
||
.trace
|
||
.as_ref()
|
||
.map(|t| t.cwd.as_path())
|
||
.unwrap_or(&self.request.world.cwd);
|
||
let destination = absolute_output(cwd, path)?;
|
||
if self
|
||
.inputs
|
||
.as_ref()
|
||
.and_then(|s| s.project())
|
||
.is_some_and(|p| p.protects_artifact(&destination))
|
||
{
|
||
return Err("failure report would overwrite an atomic project input or alias".into());
|
||
}
|
||
let mut reserved = vec![
|
||
self.request.input.clone(),
|
||
self.request.output.clone(),
|
||
self.request.output.with_extension("log"),
|
||
];
|
||
reserved.extend(self.request.layout_manifest.iter().cloned());
|
||
reserved.extend(self.request.resource_manifest.iter().cloned());
|
||
for path in reserved {
|
||
if absolute_output(cwd, &path).is_ok_and(|p| p == destination) {
|
||
return Err(
|
||
"native failure manifest must differ from job inputs, outputs and reports"
|
||
.into(),
|
||
);
|
||
}
|
||
}
|
||
if let Some(resources) = &self.resources {
|
||
if destination == resources.generated_artifacts.ledger_path
|
||
|| destination
|
||
== resources
|
||
.generated_artifacts
|
||
.ledger_path
|
||
.with_extension("lock")
|
||
|| resources.generated_artifacts.writes.iter().any(|w| {
|
||
w.path == destination
|
||
|| w.after
|
||
.as_ref()
|
||
.or(w.before.as_ref())
|
||
.is_some_and(|v| v.path == destination)
|
||
})
|
||
{
|
||
return Err(
|
||
"native failure manifest collides with generated artifacts or metadata".into(),
|
||
);
|
||
}
|
||
}
|
||
if self.host_preparation.ledger.as_ref().is_some_and(|l|destination==l.path||destination==l.path.with_extension("lock")) || self.host_preparation.observations.iter().any(|o|matches!(o,HostObservation::Operation {name,path,..} if (name=="open lock"||name=="acquire lock")&&(destination==*path||destination==path.with_extension("json")))) {
|
||
return Err("native failure manifest collides with host metadata".into());
|
||
}
|
||
if self.trace.as_ref().is_some_and(|t| {
|
||
t.reads.iter().any(|r| r.path == destination)
|
||
|| t.stream_reads.iter().any(|r| r.path == destination)
|
||
}) || self
|
||
.inputs
|
||
.as_ref()
|
||
.is_some_and(|s| s.files().any(|(p, _)| p == destination))
|
||
{
|
||
return Err("native failure manifest collides with a consumed input".into());
|
||
}
|
||
#[derive(serde::Serialize)]
|
||
struct Report<'a> {
|
||
schema: u32,
|
||
failure: &'a CompileFailure,
|
||
}
|
||
PreparedOutput::write_with(&destination, |file| {
|
||
use std::io::{BufWriter, Write};
|
||
let mut buffer = BufWriter::new(file);
|
||
serde_json::to_writer_pretty(
|
||
&mut buffer,
|
||
&Report {
|
||
schema: 1,
|
||
failure: self,
|
||
},
|
||
)
|
||
.map_err(|error| error.to_string())?;
|
||
buffer.flush().map_err(|error| error.to_string())
|
||
})?
|
||
.commit_new(&destination)
|
||
}
|
||
fn persist_requested(mut self) -> Self {
|
||
if let Some(path) = &self.request.failure_manifest {
|
||
if let Err(error) = self.write_manifest(path) {
|
||
self.evidence_gaps
|
||
.push(format!("native failure manifest: {error}"));
|
||
}
|
||
}
|
||
self
|
||
}
|
||
}
|
||
struct AttemptEvidence {
|
||
revision: u64,
|
||
phase: AttemptPhase,
|
||
failed_execution: Option<ExecutionFailure>,
|
||
completed_execution: Option<Arc<RevisionExecution>>,
|
||
trace: Option<ResourceTrace>,
|
||
inputs: Option<Arc<InputSnapshot>>,
|
||
resources: Option<ResourceSnapshot>,
|
||
host_preparation: HostPreparation,
|
||
host_runtime: Vec<HostObservation>,
|
||
world_failure: Option<WorldFailure>,
|
||
gaps: Vec<String>,
|
||
diagnostics: Vec<String>,
|
||
}
|
||
impl AttemptEvidence {
|
||
fn new(revision: u64) -> Self {
|
||
Self {
|
||
revision,
|
||
phase: AttemptPhase::Queued,
|
||
failed_execution: None,
|
||
completed_execution: None,
|
||
trace: None,
|
||
inputs: None,
|
||
resources: None,
|
||
host_preparation: HostPreparation::default(),
|
||
host_runtime: Vec::new(),
|
||
world_failure: None,
|
||
gaps: Vec::new(),
|
||
diagnostics: Vec::new(),
|
||
}
|
||
}
|
||
fn world(&mut self, world: &FileWorld) {
|
||
self.trace = Some(world.trace().clone());
|
||
self.inputs = Some(world.input_snapshot());
|
||
}
|
||
fn files(&mut self, files: &Files) {
|
||
self.host_preparation = files.preparation().clone();
|
||
self.trace = Some(files.resource_trace().clone());
|
||
self.inputs = Some(files.input_snapshot());
|
||
match files.snapshot() {
|
||
Ok(snapshot) => self.resources = Some(snapshot),
|
||
Err(e) => self.gaps.push(e),
|
||
}
|
||
self.host_runtime = files.runtime_observations();
|
||
}
|
||
fn failure(self, error: CompileError, request: AttemptRequest) -> CompileFailure {
|
||
CompileFailure {
|
||
request,
|
||
revision: self.revision,
|
||
phase: self.phase,
|
||
error,
|
||
failed_execution: self.failed_execution,
|
||
completed_execution: self.completed_execution,
|
||
trace: self.trace,
|
||
inputs: self.inputs,
|
||
resources: self.resources,
|
||
host_preparation: self.host_preparation,
|
||
host_runtime: self.host_runtime,
|
||
world_failure: self.world_failure,
|
||
evidence_gaps: self.gaps,
|
||
export_diagnostics: self.diagnostics,
|
||
}
|
||
}
|
||
}
|
||
impl std::fmt::Display for CompileError {
|
||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
match self {
|
||
Self::Cancelled => f.write_str("native compilation cancelled"),
|
||
Self::Execution(e) => e.fmt(f),
|
||
Self::Host(s) => f.write_str(s),
|
||
}
|
||
}
|
||
}
|
||
impl std::error::Error for CompileError {}
|
||
impl From<String> for CompileError {
|
||
fn from(s: String) -> Self {
|
||
Self::Host(s)
|
||
}
|
||
}
|
||
fn check(cancellation: &Cancellation) -> Result<(), CompileError> {
|
||
if cancellation.is_cancelled() {
|
||
Err(CompileError::Cancelled)
|
||
} else {
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
/// One editor/compiler session. Starting a job supersedes its previous job;
|
||
/// only a completely exported current revision can replace `latest()` or PDF.
|
||
#[derive(Clone, Default)]
|
||
pub struct NativeCompiler {
|
||
session: NativeSession,
|
||
latest: Arc<Mutex<Option<Arc<CompiledDocument>>>>,
|
||
jobs: Arc<Mutex<()>>,
|
||
draft_sync: Arc<DraftSyncQueue>,
|
||
format_cache: Arc<FormatCache>,
|
||
font_cache: Arc<texrra_tex_core::native_font::NativeFontCache>,
|
||
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
|
||
entry_checkpoints: Option<Arc<CheckpointCache>>,
|
||
}
|
||
|
||
#[derive(Default)]
|
||
struct FormatCache(Mutex<Option<CachedFormat>>);
|
||
|
||
#[derive(Clone)]
|
||
struct CachedFormat {
|
||
version: ResourceVersion,
|
||
image: Arc<FormatImage>,
|
||
bindings: Arc<BTreeMap<PathBuf, PathBuf>>,
|
||
}
|
||
|
||
impl FormatCache {
|
||
fn get(&self, version: &ResourceVersion) -> Option<CachedFormat> {
|
||
let cache = self.0.lock().expect("decoded native format cache poisoned");
|
||
cache
|
||
.as_ref()
|
||
.filter(|old| old.version == *version)
|
||
.cloned()
|
||
}
|
||
|
||
fn insert(&self, format: CachedFormat) {
|
||
*self.0.lock().expect("decoded native format cache poisoned") = Some(format);
|
||
}
|
||
}
|
||
pub struct CompileJob {
|
||
compiler: NativeCompiler,
|
||
job: RevisionJob,
|
||
}
|
||
impl NativeCompiler {
|
||
/// Enable entry-prefix reuse for atomic project shipout jobs. The byte
|
||
/// position is a lower bound for a physical command boundary to retain.
|
||
/// Invalidated prefixes use the same full compiler in the same revision.
|
||
pub fn with_entry_checkpoints(mut self, minimum_frontier: usize) -> Self {
|
||
self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(Some(minimum_frontier))));
|
||
self
|
||
}
|
||
|
||
/// Enable automatic prefix selection for a long-lived atomic project session.
|
||
pub fn with_automatic_entry_checkpoints(mut self) -> Self {
|
||
self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(None)));
|
||
self
|
||
}
|
||
|
||
pub fn start(&self) -> CompileJob {
|
||
CompileJob {
|
||
compiler: self.clone(),
|
||
job: self.session.start(),
|
||
}
|
||
}
|
||
pub fn cancel(&self, revision: u64) {
|
||
self.session.cancel(revision)
|
||
}
|
||
pub fn latest(&self) -> Option<Arc<CompiledDocument>> {
|
||
self.latest
|
||
.lock()
|
||
.expect("native completed result poisoned")
|
||
.clone()
|
||
}
|
||
pub fn compile(&self, request: CompileRequest) -> Result<Arc<CompiledDocument>, CompileError> {
|
||
self.start().compile(request)
|
||
}
|
||
pub fn compile_detailed(
|
||
&self,
|
||
request: CompileRequest,
|
||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||
self.start().compile_detailed(request)
|
||
}
|
||
}
|
||
|
||
struct PreparedJob {
|
||
executor: Option<Executor>,
|
||
format_preparation: Option<FormatPreparation>,
|
||
source: SourceFile,
|
||
files: Files,
|
||
output: PathBuf,
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||
enum KernelPreparation {
|
||
Fresh,
|
||
Resume,
|
||
}
|
||
|
||
fn prepare(
|
||
request: &CompileRequest,
|
||
dump: bool,
|
||
format_cache: Option<&FormatCache>,
|
||
cancellation: &Cancellation,
|
||
evidence: &mut AttemptEvidence,
|
||
) -> Result<PreparedJob, CompileError> {
|
||
prepare_checked(
|
||
request,
|
||
dump,
|
||
format_cache,
|
||
cancellation,
|
||
evidence,
|
||
None,
|
||
EffectMode::Live,
|
||
KernelPreparation::Fresh,
|
||
)
|
||
}
|
||
|
||
fn prepare_checked(
|
||
request: &CompileRequest,
|
||
dump: bool,
|
||
format_cache: Option<&FormatCache>,
|
||
cancellation: &Cancellation,
|
||
evidence: &mut AttemptEvidence,
|
||
check_inputs: Option<Box<PreparedInputsCheck<'_>>>,
|
||
effects: EffectMode,
|
||
kernel: KernelPreparation,
|
||
) -> Result<PreparedJob, CompileError> {
|
||
use texrra_tex_core::resources::ResourceKind;
|
||
check(cancellation)?;
|
||
if effects == EffectMode::Draft
|
||
&& (dump || request.layout_manifest.is_some() || request.resource_manifest.is_some())
|
||
{
|
||
return Err(CompileError::Host(
|
||
"draft effects require a document job without external reports".into(),
|
||
));
|
||
}
|
||
if request.layout_manifest.is_some() && (dump || request.target != Target::Shipouts) {
|
||
return Err(CompileError::Host(
|
||
"--layout-manifest requires a native document job".into(),
|
||
));
|
||
}
|
||
if dump && (!matches!(request.entry, Entry::Initex) || request.target != Target::Shipouts) {
|
||
return Err(CompileError::Host(
|
||
"format dump requires INITEX and actual shipouts".into(),
|
||
));
|
||
}
|
||
if dump && request.observer.is_some() {
|
||
return Err(CompileError::Host(
|
||
"format construction uses a cancellation token rather than revision observers".into(),
|
||
));
|
||
}
|
||
if request.inputs.is_some() && request.project.is_some() {
|
||
return Err(CompileError::Host(
|
||
"select an atomic project or captured inputs, not both".into(),
|
||
));
|
||
}
|
||
let mut world = if let Some(project) = &request.project {
|
||
if project.configuration() != request.world {
|
||
return Err(CompileError::Host(
|
||
"atomic project configuration differs from request".into(),
|
||
));
|
||
}
|
||
FileWorld::from_project(project.clone())?
|
||
} else if let Some(inputs) = &request.inputs {
|
||
evidence.inputs = Some(inputs.clone());
|
||
if request.world != inputs.configuration() {
|
||
return Err(CompileError::Host(
|
||
"native input snapshot configuration differs from request".into(),
|
||
));
|
||
}
|
||
FileWorld::from_snapshot(inputs.clone())?
|
||
} else {
|
||
let mut world = FileWorld::new_detailed(request.world.clone()).map_err(|failure| {
|
||
let error = failure.error.clone();
|
||
evidence.world_failure = Some(failure);
|
||
CompileError::Host(error)
|
||
})?;
|
||
world.capture_inputs();
|
||
world
|
||
};
|
||
if dump {
|
||
world.capture_lookup_paths();
|
||
}
|
||
let prepared = (|| -> Result<_, CompileError> {
|
||
evidence.host_preparation.phase = HostPreparationPhase::OutputPaths;
|
||
let output = evidence
|
||
.host_preparation
|
||
.output(&world.trace().cwd, &request.output)?;
|
||
world.check_artifact_output(&output)?;
|
||
let loaded = world.read(
|
||
ResourceKind::Tex,
|
||
&request.input.display().to_string(),
|
||
&request.input,
|
||
)?;
|
||
let path = loaded.version.path;
|
||
if output == path || output.canonicalize().ok().as_ref() == Some(&path) {
|
||
return Err(CompileError::Host(
|
||
"native PDF output must differ from the input source".into(),
|
||
));
|
||
}
|
||
let source = SourceFile {
|
||
name: path.display().to_string(),
|
||
data: loaded.data,
|
||
};
|
||
check(cancellation)?;
|
||
let translation = request.translation_file.as_ref().map(|name| {
|
||
if request.input_profile != InputProfile::TeX8Bit {
|
||
return Err("a TCX file requires the TeX 8-bit profile".to_owned());
|
||
}
|
||
let loaded = world.read_shared(ResourceKind::Tex, &name.to_string_lossy(), &path)?;
|
||
texrra_tex_core::execution::ByteTranslation::from_tcx(&loaded.data)
|
||
.map_err(|e| format!("TCX {}: {e}", loaded.version.path.display()))
|
||
}).transpose()?;
|
||
let (executor, format_preparation) = if let Entry::Format(name) = &request.entry {
|
||
let profile = if request.etex {
|
||
Profile::EtexBootstrap
|
||
} else {
|
||
Profile::Bootstrap
|
||
};
|
||
let loaded =
|
||
world.read_shared(ResourceKind::Tex, &name.display().to_string(), &path)?;
|
||
check(cancellation)?;
|
||
let read = |world: &mut FileWorld, resource: &std::path::Path| {
|
||
check(cancellation).map_err(|e| e.to_string())?;
|
||
world
|
||
.read_shared(ResourceKind::Tex, &resource.display().to_string(), &path)
|
||
.map(|r| r.data)
|
||
};
|
||
let date = |world: &mut FileWorld, name: &str, from: &str| {
|
||
check(cancellation).map_err(|e| e.to_string())?;
|
||
file_modification_date(world, name, from)
|
||
};
|
||
let bindings_for = |image: &FormatImage, world: &mut FileWorld| {
|
||
let bindings = image.input_bindings(&loaded.version.path, |candidate: &Path| {
|
||
check(cancellation).map_err(|e| e.to_string())?;
|
||
world.resolve(ResourceKind::Tex, &candidate.to_string_lossy(), &path)
|
||
})?;
|
||
world.record_format_input_bindings(&bindings);
|
||
Ok::<_, CompileError>(bindings)
|
||
};
|
||
match format_cache {
|
||
Some(cache) => {
|
||
let (cached, preparation) = if let Some(cached) = cache.get(&loaded.version) {
|
||
let bindings = bindings_for(&cached.image, &mut world)?;
|
||
if *cached.bindings == bindings {
|
||
(cached, FormatPreparation::Reused)
|
||
} else {
|
||
let mut image = FormatImage::decode(&loaded.data)?;
|
||
image.bind_inputs(&bindings);
|
||
(
|
||
CachedFormat {
|
||
version: loaded.version,
|
||
image: Arc::new(image),
|
||
bindings: Arc::new(bindings),
|
||
},
|
||
FormatPreparation::Decoded,
|
||
)
|
||
}
|
||
} else {
|
||
let mut image = FormatImage::decode(&loaded.data)?;
|
||
let bindings = bindings_for(&image, &mut world)?;
|
||
image.bind_inputs(&bindings);
|
||
(
|
||
CachedFormat {
|
||
version: loaded.version,
|
||
image: Arc::new(image),
|
||
bindings: Arc::new(bindings),
|
||
},
|
||
FormatPreparation::Decoded,
|
||
)
|
||
};
|
||
let image = &cached.image;
|
||
let executor = if kernel == KernelPreparation::Resume {
|
||
image.validate_shared_job_inputs(
|
||
profile,
|
||
request.input_profile,
|
||
&mut world,
|
||
read,
|
||
date,
|
||
)?;
|
||
None
|
||
} else {
|
||
Some(image.fork_job_with_file_dates(
|
||
profile,
|
||
request.input_profile,
|
||
request.time,
|
||
request.limits,
|
||
&mut world,
|
||
read,
|
||
date,
|
||
)?)
|
||
};
|
||
check(cancellation)?;
|
||
if preparation == FormatPreparation::Decoded {
|
||
cache.insert(cached);
|
||
}
|
||
(executor, Some(preparation))
|
||
}
|
||
None => {
|
||
let mut image = FormatImage::decode(&loaded.data)?;
|
||
let bindings = bindings_for(&image, &mut world)?;
|
||
image.bind_inputs(&bindings);
|
||
let executor = if kernel == KernelPreparation::Resume {
|
||
image.validate_shared_job_inputs(
|
||
profile,
|
||
request.input_profile,
|
||
&mut world,
|
||
read,
|
||
date,
|
||
)?;
|
||
None
|
||
} else {
|
||
Some(image.new_job_with_file_dates(
|
||
profile,
|
||
request.input_profile,
|
||
request.time,
|
||
request.limits,
|
||
&mut world,
|
||
read,
|
||
date,
|
||
)?)
|
||
};
|
||
(executor, Some(FormatPreparation::Decoded))
|
||
}
|
||
}
|
||
} else {
|
||
let executor = (kernel == KernelPreparation::Fresh).then(|| {
|
||
let state = if matches!(request.entry, Entry::Initex) {
|
||
State::initex()
|
||
} else {
|
||
State::default()
|
||
}
|
||
.with_job_time(request.time)
|
||
.with_input_profile(request.input_profile);
|
||
let state = if request.target == Target::Shipouts && !dump {
|
||
state.with_pdf_output()
|
||
} else {
|
||
state
|
||
};
|
||
let state = if request.etex {
|
||
state.with_etex()
|
||
} else {
|
||
state
|
||
};
|
||
Executor::new(state, request.limits)
|
||
});
|
||
(executor, None)
|
||
};
|
||
let executor = match (executor, translation) {
|
||
(Some(executor), Some(table)) => Some(executor.with_byte_translation(table)),
|
||
(executor, _) => executor,
|
||
};
|
||
check(cancellation)?;
|
||
Ok((path, source, executor, output, format_preparation))
|
||
})();
|
||
evidence.world(&world);
|
||
let (path, source, executor, output, format_preparation) = prepared?;
|
||
let files = Files::new_with_terminal(
|
||
&path,
|
||
&output,
|
||
world,
|
||
request.terminal,
|
||
&request.generated_inputs,
|
||
&mut evidence.host_preparation,
|
||
check_inputs,
|
||
effects,
|
||
)
|
||
.map_err(|failure| {
|
||
evidence.trace = Some(failure.trace);
|
||
evidence.inputs = Some(failure.inputs);
|
||
CompileError::Host(failure.error)
|
||
})?;
|
||
let executor = executor.map(|executor| {
|
||
if request.target == Target::Shipouts {
|
||
executor.with_native_pages()
|
||
} else {
|
||
executor
|
||
}
|
||
});
|
||
Ok(PreparedJob {
|
||
executor,
|
||
format_preparation,
|
||
source,
|
||
files,
|
||
output,
|
||
})
|
||
}
|
||
fn report(files: &Files, request: &CompileRequest) -> Result<(), CompileError> {
|
||
if let Some(path) = &request.resource_manifest {
|
||
files.write_resource_manifest(path)?;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
impl CompileJob {
|
||
pub fn revision(&self) -> u64 {
|
||
self.job.revision()
|
||
}
|
||
pub fn compile(self, request: CompileRequest) -> Result<Arc<CompiledDocument>, CompileError> {
|
||
self.compile_detailed(request)
|
||
.map_err(|failure| failure.error)
|
||
}
|
||
pub fn compile_detailed(
|
||
self,
|
||
mut request: CompileRequest,
|
||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||
if self.compiler.entry_checkpoints.is_some()
|
||
&& checkpoint_guard::can_stage(&request)
|
||
&& matches!(&request.generated_inputs, GeneratedInputPolicy::Live)
|
||
{
|
||
request.generated_inputs = GeneratedInputPolicy::Observe;
|
||
}
|
||
let mut evidence = AttemptEvidence::new(self.revision());
|
||
let summary = AttemptRequest::from(&request);
|
||
let mut suffix_failure = None;
|
||
let result = self.compile_observed(&request, &mut evidence, None, &mut suffix_failure);
|
||
let result = if let Some((error, discarded_steps)) = suffix_failure {
|
||
if self.job.cancellation().is_cancelled() {
|
||
Err(CompileError::Cancelled)
|
||
} else {
|
||
evidence = AttemptEvidence::new(self.revision());
|
||
self.compile_observed(&request, &mut evidence, Some((error, discarded_steps)), &mut None)
|
||
}
|
||
} else {
|
||
result
|
||
};
|
||
match result {
|
||
Ok(document) => Ok(document),
|
||
Err(error) => Err(evidence.failure(error, summary).persist_requested()),
|
||
}
|
||
}
|
||
fn compile_observed(
|
||
&self,
|
||
request: &CompileRequest,
|
||
evidence: &mut AttemptEvidence,
|
||
retry_suffix: Option<(String, usize)>,
|
||
suffix_failure: &mut Option<(String, usize)>,
|
||
) -> Result<Arc<CompiledDocument>, CompileError> {
|
||
let cancellation = self.job.cancellation();
|
||
check(&cancellation)?;
|
||
// Starting a revision stays nonblocking; actual same-session I/O waits
|
||
// for the cancelled predecessor to release its project handles.
|
||
let _job_guard = self
|
||
.compiler
|
||
.jobs
|
||
.lock()
|
||
.map_err(|_| CompileError::Host("native job queue poisoned".into()))?;
|
||
let revision = self.job.revision();
|
||
evidence.phase = AttemptPhase::Preparing;
|
||
let checkpoints = self
|
||
.compiler
|
||
.entry_checkpoints
|
||
.as_deref()
|
||
.filter(|_| checkpoint_guard::can_stage(&request));
|
||
let format_cache = &self.compiler.format_cache;
|
||
let mut entry_checkpoint_work = EntryCheckpointWork::default();
|
||
let allow_suffix = retry_suffix.is_none();
|
||
if let Some((error, discarded_steps)) = retry_suffix {
|
||
entry_checkpoint_work.rejection = Some(error);
|
||
entry_checkpoint_work.discarded_suffix_attempt_steps = discarded_steps;
|
||
}
|
||
let (active_checkpoint, prepared) =
|
||
if let Some(available) = checkpoints.and_then(CheckpointCache::current) {
|
||
match available.prepare(&request, format_cache, &cancellation, evidence) {
|
||
Ok((selected, prepared)) => (Some(selected), Some(prepared)),
|
||
Err(error) => {
|
||
check(&cancellation)?;
|
||
*evidence = AttemptEvidence::new(revision);
|
||
entry_checkpoint_work.rejection = Some(error.to_string());
|
||
(None, None)
|
||
}
|
||
}
|
||
} else {
|
||
(None, None)
|
||
};
|
||
let PreparedJob {
|
||
executor,
|
||
format_preparation,
|
||
source,
|
||
files,
|
||
output,
|
||
} = if let Some(prepared) = prepared {
|
||
prepared
|
||
} else {
|
||
prepare_checked(
|
||
&request,
|
||
false,
|
||
Some(format_cache),
|
||
&cancellation,
|
||
evidence,
|
||
None,
|
||
if checkpoints.is_some() {
|
||
EffectMode::Draft
|
||
} else {
|
||
EffectMode::Live
|
||
},
|
||
KernelPreparation::Fresh,
|
||
)
|
||
.map_err(|error| {
|
||
if cancellation.is_cancelled() {
|
||
CompileError::Cancelled
|
||
} else {
|
||
error
|
||
}
|
||
})?
|
||
};
|
||
let mut available_host = Some(files);
|
||
evidence.inputs = None;
|
||
evidence.trace = None;
|
||
let result = (|| -> Result<Arc<CompiledDocument>, CompileError> {
|
||
let files = available_host.as_mut().expect("prepared native host");
|
||
if let Some(path) = &request.layout_manifest {
|
||
files.check_layout_manifest_path(path, request.resource_manifest.as_deref())?;
|
||
}
|
||
evidence.phase = AttemptPhase::Prepared;
|
||
if allow_suffix {
|
||
notify(request, revision, CompileStage::Prepared, &cancellation)?;
|
||
}
|
||
evidence.phase = AttemptPhase::Executing;
|
||
let cache = &self.compiler.line_break_cache;
|
||
let before = cache.work();
|
||
let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
|
||
debug_assert!(executor.is_none());
|
||
let (executed, next) = current.resume(
|
||
&request,
|
||
&self.job,
|
||
source,
|
||
files,
|
||
cache.clone(),
|
||
&mut entry_checkpoint_work,
|
||
allow_suffix,
|
||
suffix_failure,
|
||
)?;
|
||
(executed, Some(next))
|
||
} else {
|
||
let executor = executor
|
||
.expect("fresh native job has an executor")
|
||
.with_line_break_cache(cache.clone());
|
||
if let Some(cache) = checkpoints {
|
||
let (executed, captured) =
|
||
cache.capture(request, &self.job, executor, source, files);
|
||
if let Some(snapshot) = &captured {
|
||
snapshot.report_capture(&mut entry_checkpoint_work);
|
||
}
|
||
(executed, captured)
|
||
} else {
|
||
(self.job.run_detailed(executor, source, files), None)
|
||
}
|
||
};
|
||
let execution = match executed {
|
||
Ok(execution) => {
|
||
evidence.completed_execution = Some(execution.clone());
|
||
report(files, &request)?;
|
||
execution
|
||
}
|
||
Err(failure) => {
|
||
evidence.failed_execution = failure.failed_execution;
|
||
evidence.completed_execution = failure.completed_execution;
|
||
if let Err(error) = report(files, &request) {
|
||
evidence.gaps.push(error.to_string());
|
||
}
|
||
return Err(match failure.error {
|
||
RevisionError::Cancelled => CompileError::Cancelled,
|
||
RevisionError::Execution(e) => CompileError::Execution(e),
|
||
});
|
||
}
|
||
};
|
||
let line_break_work = cache.work().since(before);
|
||
if execution.execution.format_dumped {
|
||
return Err(CompileError::Host(
|
||
"native format dump requires --dump-format".into(),
|
||
));
|
||
}
|
||
notify(&request, revision, CompileStage::Executed, &cancellation)?;
|
||
evidence.phase = AttemptPhase::Layout;
|
||
let e = &execution.execution;
|
||
let font_cache = &self.compiler.font_cache;
|
||
let type1_before = font_cache.type1_work();
|
||
let prior_layout = checkpoints.and_then(|_| self.compiler.latest());
|
||
let mut shipout_layout_work = ShipoutLayoutWork::default();
|
||
let mut shipout_layouts = Vec::new();
|
||
let (mut pages, paper_width, paper_height, origin) = if request.target
|
||
== Target::Shipouts
|
||
{
|
||
use texrra_tex_core::execution::Event;
|
||
let mut old = prior_layout.as_deref().into_iter().flat_map(|prior| {
|
||
prior.execution.execution.events.iter().filter_map(|event| {
|
||
if let Event::Shipout(page) = event { Some(page.as_ref()) } else { None }
|
||
}).zip(&prior.shipout_layouts)
|
||
});
|
||
let pages = e.shipout_display_lists_with(|page| {
|
||
if let Some((_, layout)) =
|
||
old.next().filter(|(prior, _)| page.shares_local_layout_with(prior))
|
||
{
|
||
shipout_layout_work.reused_pages += 1;
|
||
shipout_layouts.push(layout.clone());
|
||
return Ok((**layout).clone());
|
||
}
|
||
let layout = page.display_list()?;
|
||
shipout_layout_work.lowered_pages += 1;
|
||
if checkpoints.is_some() {
|
||
shipout_layouts.push(Arc::new(layout.clone()));
|
||
}
|
||
Ok(layout)
|
||
}).map_err(|e| e.to_string())?;
|
||
(pages, 0, 0, texrra_tex_core::pdf::PageOrigin::default())
|
||
} else {
|
||
let document = e.document().map_err(|e| e.to_string())?;
|
||
let engine = texrra_tex_core::Engine::layout_paged(&document)
|
||
.ok_or_else(|| CompileError::Host("unsupported native vertical list".into()))?;
|
||
(
|
||
engine.pages().iter().map(|p| p.display_list()).collect(),
|
||
document.paper_width,
|
||
document.paper_height,
|
||
texrra_tex_core::pdf::PageOrigin {
|
||
h_offset: document.h_offset,
|
||
v_offset: document.v_offset,
|
||
},
|
||
)
|
||
};
|
||
let dvi_mode = request.target == Target::Shipouts
|
||
&& pages.first().is_some_and(|page| page.pdf.is_none());
|
||
if dvi_mode
|
||
&& output.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("pdf"))
|
||
{
|
||
return Err(CompileError::Host(
|
||
"DVI mode requires a DVI output path, for example output.dvi".into(),
|
||
));
|
||
}
|
||
let draft_mode =
|
||
request.target == Target::Shipouts && !dvi_mode && e.state.pdf_draft_mode();
|
||
if let Some(path) = &request.layout_manifest {
|
||
let source_map = self.compiler.session.source_map(&execution, &pages)?;
|
||
files.write_layout_manifest(path, e, &pages, &source_map)?;
|
||
}
|
||
evidence.phase = AttemptPhase::Fonts;
|
||
let preview_fonts = if draft_mode {
|
||
PreviewFonts::default()
|
||
} else {
|
||
let mut forms = pages.first_mut().map(|first| std::mem::take(&mut first.forms))
|
||
.unwrap_or_default();
|
||
let actual_pages = pages.len();
|
||
pages.extend(forms.iter_mut().map(|form| std::mem::take(&mut form.list)));
|
||
let fonts = self.compiler.font_cache.resolve(&mut pages, files);
|
||
for (form, list) in forms.iter_mut().zip(pages.drain(actual_pages..)) {
|
||
form.list = list;
|
||
}
|
||
if let Some(first) = pages.first_mut() {
|
||
first.forms = forms;
|
||
}
|
||
let fonts = fonts.and_then(|_| PreviewFonts::resolve(
|
||
&pages, files, &self.compiler.font_cache,
|
||
));
|
||
let reported = report(files, &request);
|
||
match fonts {
|
||
Ok(preview) => {
|
||
reported?;
|
||
preview
|
||
}
|
||
Err(_) if dvi_mode => {
|
||
// A DVI driver resolves the requested outlines later.
|
||
// Unavailable preview fonts do not prevent DVI output.
|
||
reported?;
|
||
PreviewFonts::default()
|
||
}
|
||
Err(error) => {
|
||
if let Err(report) = reported {
|
||
evidence.gaps.push(report.to_string());
|
||
}
|
||
return Err(CompileError::Host(error));
|
||
}
|
||
}
|
||
};
|
||
let source_map = self.compiler.session.source_map(&execution, &pages)?;
|
||
notify(
|
||
&request,
|
||
revision,
|
||
CompileStage::FontsResolved,
|
||
&cancellation,
|
||
)?;
|
||
evidence.phase = AttemptPhase::Export;
|
||
let xdv_glyph_names = if request.target == Target::Shipouts
|
||
&& request.input_profile == InputProfile::XeTeX
|
||
&& pages.iter().any(|page| {
|
||
page.items.iter().any(|item| match item {
|
||
DisplayItem::OpenTypeGlyph { .. } => true,
|
||
DisplayItem::NativeGlyph { paint: Some(paint), .. } => matches!(
|
||
paint.program, texrra_tex_core::native_font::NativeFontProgram::Type1(_)
|
||
),
|
||
_ => false,
|
||
})
|
||
})
|
||
{
|
||
Some(XdvGlyphNames::load(files, &request.input.to_string_lossy())
|
||
.map_err(CompileError::Host)?)
|
||
} else {
|
||
None
|
||
};
|
||
let mut dvi = None;
|
||
let (pdf, export_diagnostics) = if pages.is_empty() {
|
||
(None, Vec::new())
|
||
} else if draft_mode {
|
||
(None, vec![r"\pdfdraftmode enabled, not changing output pdf".into()])
|
||
} else if dvi_mode {
|
||
let encoded = e.dvi_output(&cancellation);
|
||
check(&cancellation)?;
|
||
dvi = encoded?;
|
||
(None, Vec::new())
|
||
} else if request.target == Target::Shipouts {
|
||
let mut options = e.state.pdf_final_options();
|
||
options.xdv_glyph_names = xdv_glyph_names.as_ref();
|
||
options.font_cache = Some(font_cache);
|
||
let document = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document(
|
||
&pages,
|
||
options,
|
||
)?;
|
||
(Some(document.bytes), document.diagnostics)
|
||
} else {
|
||
(
|
||
Some(texrra_tex_core::pdf::display_lists_to_native_pdf(
|
||
&pages,
|
||
paper_width,
|
||
paper_height,
|
||
origin,
|
||
)?),
|
||
Vec::new(),
|
||
)
|
||
};
|
||
evidence.diagnostics = export_diagnostics.clone();
|
||
notify(&request, revision, CompileStage::Exported, &cancellation)?;
|
||
for warning in &export_diagnostics {
|
||
files.observe_diagnostic(
|
||
WriteDestination::TerminalAndLog,
|
||
&format!("native PDF warning: {warning}\n"),
|
||
)?;
|
||
}
|
||
evidence.phase = AttemptPhase::Finishing;
|
||
let finished = files.finish();
|
||
let reported = report(files, &request);
|
||
if let Err(error) = finished {
|
||
if let Err(report) = reported {
|
||
evidence.gaps.push(report.to_string());
|
||
}
|
||
return Err(CompileError::Host(error));
|
||
}
|
||
reported?;
|
||
let resources = files.snapshot()?;
|
||
let inputs = files.input_snapshot();
|
||
let prepared = pdf
|
||
.as_ref()
|
||
.or(dvi.as_ref())
|
||
.map(|bytes| {
|
||
if checkpoints.is_some() {
|
||
PreparedOutput::write_for_draft(&output, bytes)
|
||
} else {
|
||
PreparedOutput::write(&output, bytes)
|
||
}
|
||
})
|
||
.transpose()?;
|
||
let receipt = prepared.as_ref().map(|p| p.version(&output)).transpose()?;
|
||
let previous = self.compiler.latest();
|
||
// Identical PDF output allows direct reuse. When it differs,
|
||
// PDF previews validate the new page and its reachable objects.
|
||
let pdf_unchanged = pdf.is_some() && pages.iter().any(DisplayList::has_embedded_pdf)
|
||
&& previous
|
||
.as_deref()
|
||
.is_some_and(|document| document.pdf.as_deref() == pdf.as_deref());
|
||
let preview = PreviewState::new(
|
||
&pages,
|
||
previous.as_deref().map(|document| {
|
||
(
|
||
document.revision(),
|
||
document.pages.as_slice(),
|
||
&document.preview,
|
||
)
|
||
}),
|
||
pdf_unchanged,
|
||
preview_fonts,
|
||
);
|
||
let result = Arc::new(CompiledDocument {
|
||
format_preparation,
|
||
entry_checkpoint_work,
|
||
line_break_work,
|
||
shipout_layout_work,
|
||
type1_font_work: font_cache.type1_work().since(type1_before),
|
||
execution,
|
||
pages,
|
||
source_map,
|
||
resources,
|
||
inputs,
|
||
host_preparation: files.preparation().clone(),
|
||
host_runtime: files.runtime_observations(),
|
||
export_diagnostics,
|
||
pdf: pdf.map(Arc::from),
|
||
dvi: dvi.map(Arc::from),
|
||
output: receipt,
|
||
preview,
|
||
shipout_layouts,
|
||
});
|
||
evidence.phase = AttemptPhase::ReadyToPublish;
|
||
notify(
|
||
&request,
|
||
revision,
|
||
CompileStage::ReadyToPublish,
|
||
&cancellation,
|
||
)?;
|
||
if checkpoints.is_some()
|
||
&& let Some(observer) = &request.observer
|
||
{
|
||
let observed = observer.draft_ready(DraftPreview {
|
||
document: &result,
|
||
cancellation: &cancellation,
|
||
});
|
||
check(&cancellation)?;
|
||
observed?;
|
||
}
|
||
evidence.phase = AttemptPhase::Publishing;
|
||
let expose = || {
|
||
*self
|
||
.compiler
|
||
.latest
|
||
.lock()
|
||
.expect("native completed result poisoned") = Some(result.clone());
|
||
};
|
||
let published = if let Some(cache) = checkpoints {
|
||
let publication = available_host
|
||
.take()
|
||
.expect("prepared draft host")
|
||
.seal_draft(prepared, &self.compiler.draft_sync, &cancellation)
|
||
.and_then(|draft| {
|
||
let Some(draft) = draft else {
|
||
return Ok(None);
|
||
};
|
||
draft.publish_current(&self.compiler.session, result.revision(), || {
|
||
cache.set(next_checkpoint, &request);
|
||
expose();
|
||
})
|
||
});
|
||
if !matches!(publication, Ok(Some(()))) {
|
||
evidence.host_preparation = result.host_preparation.clone();
|
||
evidence.inputs = Some(result.inputs.clone());
|
||
evidence.trace = Some(result.resources.trace.clone());
|
||
evidence.resources = Some(result.resources.clone());
|
||
evidence.host_runtime = result.host_runtime.clone();
|
||
}
|
||
publication?
|
||
} else {
|
||
self.compiler
|
||
.session
|
||
.publish_current(result.revision(), || {
|
||
if let Some(prepared) = prepared {
|
||
prepared.commit(&output)?;
|
||
}
|
||
expose();
|
||
Ok::<_, String>(())
|
||
})?
|
||
};
|
||
if published.is_none() {
|
||
return Err(CompileError::Cancelled);
|
||
}
|
||
Ok(result)
|
||
})();
|
||
if result.is_err()
|
||
&& let Some(mut files) = available_host
|
||
{
|
||
evidence.gaps.extend(files.finish_failed());
|
||
if let Err(error) = report(&files, &request) {
|
||
evidence.gaps.push(error.to_string());
|
||
}
|
||
evidence.files(&files);
|
||
}
|
||
result
|
||
}
|
||
}
|
||
|
||
/// Offline format construction uses the same host and kernel. Its destination
|
||
/// must be new; cancellation never publishes a partially prepared format.
|
||
pub fn dump_format(
|
||
request: CompileRequest,
|
||
cancellation: Cancellation,
|
||
) -> Result<BuiltFormat, CompileError> {
|
||
dump_format_detailed(request, cancellation).map_err(|failure| failure.error)
|
||
}
|
||
/// A format build has no editor-session revision; revision zero identifies the
|
||
/// offline attempt. Its source versions and host effects are still actual.
|
||
pub fn dump_format_detailed(
|
||
request: CompileRequest,
|
||
cancellation: Cancellation,
|
||
) -> Result<BuiltFormat, CompileFailure> {
|
||
let mut evidence = AttemptEvidence::new(0);
|
||
let summary = AttemptRequest::from(&request);
|
||
evidence.phase = AttemptPhase::Preparing;
|
||
dump_format_observed(request, cancellation, &mut evidence)
|
||
.map_err(|error| evidence.failure(error, summary).persist_requested())
|
||
}
|
||
fn dump_format_observed(
|
||
request: CompileRequest,
|
||
cancellation: Cancellation,
|
||
evidence: &mut AttemptEvidence,
|
||
) -> Result<BuiltFormat, CompileError> {
|
||
let PreparedJob {
|
||
executor,
|
||
format_preparation: _,
|
||
source,
|
||
mut files,
|
||
output,
|
||
} = prepare(&request, true, None, &cancellation, evidence)?;
|
||
evidence.inputs = None;
|
||
evidence.trace = None;
|
||
let result = (|| -> Result<BuiltFormat, CompileError> {
|
||
evidence.phase = AttemptPhase::Executing;
|
||
let executed = executor
|
||
.expect("format dump has a fresh executor")
|
||
.with_cancellation(cancellation.clone())
|
||
.run_detailed(source, &mut files);
|
||
let execution = match executed {
|
||
Ok(execution) => {
|
||
let execution = Arc::new(RevisionExecution::from_execution(
|
||
0,
|
||
execution,
|
||
Some(files.resource_trace().clone()),
|
||
));
|
||
evidence.completed_execution = Some(execution.clone());
|
||
report(&files, &request)?;
|
||
check(&cancellation)?;
|
||
execution
|
||
}
|
||
Err(failure) => {
|
||
let error = if cancellation.is_cancelled() {
|
||
CompileError::Cancelled
|
||
} else {
|
||
CompileError::Execution(failure.error.clone())
|
||
};
|
||
evidence.failed_execution = Some(failure);
|
||
if let Err(report) = report(&files, &request) {
|
||
evidence.gaps.push(report.to_string());
|
||
}
|
||
return Err(error);
|
||
}
|
||
};
|
||
evidence.phase = AttemptPhase::Export;
|
||
let trace = files.resource_trace();
|
||
// Keep the completed kernel result available if format validation/encoding
|
||
// fails. This extra offline copy is not part of interactive compilation.
|
||
let bytes = FormatImage::from_dump_with_trace(execution.execution.clone(), trace)?
|
||
.with_project_location(&output, trace)
|
||
.encode()?;
|
||
evidence.phase = AttemptPhase::Finishing;
|
||
let finished = files.finish();
|
||
let reported = report(&files, &request);
|
||
if let Err(error) = finished {
|
||
if let Err(report) = reported {
|
||
evidence.gaps.push(report.to_string());
|
||
}
|
||
return Err(CompileError::Host(error));
|
||
}
|
||
reported?;
|
||
let resources = files.snapshot()?;
|
||
let inputs = files.input_snapshot();
|
||
let prepared = PreparedOutput::write(&output, &bytes)?;
|
||
let version = prepared.version(&output)?;
|
||
evidence.phase = AttemptPhase::ReadyToPublish;
|
||
check(&cancellation)?;
|
||
evidence.phase = AttemptPhase::Publishing;
|
||
prepared.commit_new(&output)?;
|
||
Ok(BuiltFormat {
|
||
output: version,
|
||
resources,
|
||
inputs,
|
||
host_preparation: files.preparation().clone(),
|
||
host_runtime: files.runtime_observations(),
|
||
execution,
|
||
})
|
||
})();
|
||
if result.is_err() {
|
||
evidence.gaps.extend(files.finish_failed());
|
||
if let Err(report) = report(&files, &request) {
|
||
evidence.gaps.push(report.to_string());
|
||
}
|
||
evidence.files(&files);
|
||
}
|
||
result
|
||
}
|