use crate::document::{DocumentError, DocumentSnapshot, PageIndex, ParseContext};
use crate::page_ir::{CompiledPage, FillRule, PageBounds, Rect};
pub mod dump;
mod interpret;
mod lower;
pub mod marked;
mod mesh;
pub mod semantic;
pub mod state;
pub mod tokenizer;
pub mod trace;
pub use marked::MarkedContentSpan;
pub use semantic::{
ActualTextSpan, ActualTextSpanId, SemColor, SemFont, SemImage, SemanticOp, SemanticPage,
TextElement, TextRun,
};
pub use state::GraphicsState;
pub use tokenizer::{ContentLexer, Lexeme, Operand};
pub use trace::{OpTrace, PageTrace, TraceFrame, TraceFrameKind};
#[derive(Debug, Clone)]
pub struct ContentLimits {
pub max_ops: u64,
pub max_invoke_depth: u32,
pub max_colorspace_depth: u32,
pub max_function_depth: u32,
pub max_content_depth: usize,
pub syntax: crate::syntax::SyntaxLimits,
}
impl Default for ContentLimits {
fn default() -> Self {
Self {
max_ops: 5_000_000,
max_invoke_depth: 16,
max_colorspace_depth: 8,
max_function_depth: 32,
max_content_depth: 8,
syntax: crate::syntax::SyntaxLimits::default(),
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ContentError {
#[error(transparent)]
Document(#[from] DocumentError),
#[error(transparent)]
Syntax(#[from] crate::syntax::SyntaxError),
#[error("operator budget exhausted after {0} operations")]
OperatorBudget(u64),
#[error("XObject/pattern recursion depth {0} exceeded")]
RecursionDepth(u32),
#[error("operand stack overflow ({0} operands)")]
OperandStackOverflow(usize),
#[error("operand nesting depth {0} exceeded")]
NestingDepth(usize),
#[error("malformed content stream: {0}")]
Malformed(String),
#[error("page compilation cancelled")]
Cancelled,
#[error("inline image framing failed: {0}")]
InlineImage(String),
#[error(transparent)]
Font(#[from] crate::font::FontError),
#[error(transparent)]
Image(#[from] crate::image::ImageError),
#[error(transparent)]
Color(#[from] crate::color::ColorError),
}
impl ContentError {
pub(crate) fn is_fatal(&self) -> bool {
matches!(
self,
ContentError::OperatorBudget(_)
| ContentError::RecursionDepth(_)
| ContentError::OperandStackOverflow(_)
| ContentError::NestingDepth(_)
| ContentError::Cancelled
)
}
}
#[derive(Debug, Clone)]
pub struct PageCompilation {
pub semantic: std::sync::Arc<SemanticPage>,
pub compiled: std::sync::Arc<CompiledPage>,
}
#[derive(Debug, Default)]
pub struct PageCompiler {
limits: ContentLimits,
system_fonts: Option<std::sync::Arc<dyn crate::font::SystemFontProvider>>,
annotations: bool,
}
impl PageCompiler {
pub fn new() -> Self {
Self::default()
}
pub fn with_limits(limits: ContentLimits) -> Self {
Self {
limits,
..Default::default()
}
}
pub fn with_system_fonts(
mut self,
provider: std::sync::Arc<dyn crate::font::SystemFontProvider>,
) -> Self {
self.system_fonts = Some(provider);
self
}
pub fn with_annotations(mut self, on: bool) -> Self {
self.annotations = on;
self
}
pub fn compile_semantic(
&self,
snapshot: &DocumentSnapshot,
page: PageIndex,
ctx: &mut ParseContext,
) -> Result<SemanticPage, ContentError> {
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let page_ref = snapshot.page(page)?.clone();
let [x0, y0, x1, y1] = page_ref.crop_box;
let bounds = PageBounds {
crop: Rect { x0, y0, x1, y1 }.normalized(),
rotate: page_ref.rotate,
};
let content =
interpret::gather_content(snapshot, page_ref.contents.as_ref(), ctx, &self.limits)?;
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);
let mut interp = interpret::Interpreter::new(
snapshot,
ctx,
&self.limits,
resources,
self.system_fonts.clone(),
);
interp.run(&content)?;
if self.annotations && !page_ref.annotations.is_empty() {
interp.run_annotations(&page_ref.annotations)?;
}
Ok(interp.finish(bounds))
}
pub fn marked_content_spans(
&self,
snapshot: &DocumentSnapshot,
page: PageIndex,
ctx: &mut ParseContext,
) -> Result<Vec<MarkedContentSpan>, ContentError> {
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let page_ref = snapshot.page(page)?.clone();
let content =
interpret::gather_content(snapshot, page_ref.contents.as_ref(), ctx, &self.limits)?;
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);
let mut interp = interpret::Interpreter::new(
snapshot,
ctx,
&self.limits,
resources,
self.system_fonts.clone(),
);
interp.set_record_marked();
interp.run(&content)?;
Ok(interp.take_marked_spans())
}
pub fn compile_semantic_traced(
&self,
snapshot: &DocumentSnapshot,
page: PageIndex,
ctx: &mut ParseContext,
) -> Result<(SemanticPage, PageTrace), ContentError> {
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let page_ref = snapshot.page(page)?.clone();
let [x0, y0, x1, y1] = page_ref.crop_box;
let bounds = PageBounds {
crop: Rect { x0, y0, x1, y1 }.normalized(),
rotate: page_ref.rotate,
};
let (content, segments) = interpret::gather_content_mapped(
snapshot,
page_ref.contents.as_ref(),
ctx,
&self.limits,
)?;
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);
let mut interp = interpret::Interpreter::new(
snapshot,
ctx,
&self.limits,
resources,
self.system_fonts.clone(),
);
interp.set_record_trace(segments);
interp.run(&content)?;
if self.annotations && !page_ref.annotations.is_empty() {
interp.run_annotations(&page_ref.annotations)?;
}
let trace = interp.take_trace();
Ok((interp.finish(bounds), trace))
}
pub fn compile_artifacts(
&self,
snapshot: &DocumentSnapshot,
page: PageIndex,
ctx: &mut ParseContext,
) -> Result<PageCompilation, ContentError> {
let semantic = std::sync::Arc::new(self.compile_semantic(snapshot, page, ctx)?);
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let compiled = std::sync::Arc::new(lower::lower(semantic.as_ref()));
if ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
Ok(PageCompilation { semantic, compiled })
}
pub fn compile(
&self,
snapshot: &DocumentSnapshot,
page: PageIndex,
ctx: &mut ParseContext,
) -> Result<CompiledPage, ContentError> {
let semantic = self.compile_semantic(snapshot, page, ctx)?;
Ok(lower::lower(&semantic))
}
#[cfg(feature = "profiling")]
pub fn compile_profiled(
&self,
snapshot: &DocumentSnapshot,
page: PageIndex,
ctx: &mut ParseContext,
) -> Result<(CompiledPage, crate::profiling::ProfileReport), ContentError> {
let all = std::time::Instant::now();
let page_start = std::time::Instant::now();
let page_ref = snapshot.page(page)?.clone();
let [x0, y0, x1, y1] = page_ref.crop_box;
let bounds = PageBounds {
crop: Rect { x0, y0, x1, y1 }.normalized(),
rotate: page_ref.rotate,
};
let mut profile = crate::profiling::ProfileReport::new();
profile.add_duration("compile.page_lookup", page_start.elapsed());
let content_start = std::time::Instant::now();
let content =
interpret::gather_content(snapshot, page_ref.contents.as_ref(), ctx, &self.limits)?;
profile.add_duration("compile.content_gather", content_start.elapsed());
profile.increment("compile.content_bytes", content.len() as u64);
let resources_start = std::time::Instant::now();
let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);
profile.add_duration("compile.resources", resources_start.elapsed());
let interpret_start = std::time::Instant::now();
let mut interp = interpret::Interpreter::new(
snapshot,
ctx,
&self.limits,
resources,
self.system_fonts.clone(),
);
interp.run(&content)?;
if self.annotations && !page_ref.annotations.is_empty() {
interp.run_annotations(&page_ref.annotations)?;
}
profile.add_duration("compile.interpret", interpret_start.elapsed());
let finish_start = std::time::Instant::now();
let semantic = interp.finish(bounds);
profile.add_duration("compile.semantic_finish", finish_start.elapsed());
let lower_start = std::time::Instant::now();
let compiled = lower::lower(&semantic);
profile.add_duration("compile.ir_lower", lower_start.elapsed());
profile.add_duration("compile.total", all.elapsed());
profile.increment("compile.operations", compiled.operations.len() as u64);
profile.increment("compile.objects_visited", ctx.objects_visited as u64);
profile.increment(
"compile.decoded_stream_bytes",
ctx.decoded_bytes_used as u64,
);
profile.increment("compile.recovery_events", ctx.recovery.len() as u64);
profile.increment("compile.object_cache_hits", ctx.object_cache_hits as u64);
profile.increment(
"compile.object_cache_misses",
ctx.object_cache_misses as u64,
);
profile.increment(
"compile.object_stream_cache_hits",
ctx.object_stream_cache_hits as u64,
);
profile.increment(
"compile.object_stream_inflates",
ctx.object_stream_inflates as u64,
);
Ok((compiled, profile))
}
pub fn map_fill_rule(even_odd: bool) -> FillRule {
if even_odd {
FillRule::EvenOdd
} else {
FillRule::NonZero
}
}
}
const fn _assert_send<T: Send>() {}
const _: () = _assert_send::<PageCompiler>();