use crate::char::Char;
use crate::document::Document;
use crate::error::Result;
use crate::geom::Matrix;
use crate::text::options::TextOptions;
use crate::word::{Word, WordOptions};
use std::sync::OnceLock;
pub struct Page<'doc> {
doc: &'doc Document,
index: usize,
chars_cache: OnceLock<Vec<Char>>,
metrics_cache: OnceLock<PageMetrics>,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct PageMetrics {
pub media_width: f32,
pub media_height: f32,
pub rotation: i16,
}
impl PageMetrics {
fn is_quarter_turn(&self) -> bool {
self.rotation == 90 || self.rotation == 270
}
pub(crate) fn display_width(&self) -> f32 {
if self.is_quarter_turn() {
self.media_height
} else {
self.media_width
}
}
pub(crate) fn display_height(&self) -> f32 {
if self.is_quarter_turn() {
self.media_width
} else {
self.media_height
}
}
pub(crate) fn rotation_matrix(&self) -> Matrix {
let (w, h) = (self.media_width, self.media_height);
match self.rotation {
90 => Matrix::new(0.0, -1.0, 1.0, 0.0, 0.0, w),
180 => Matrix::new(-1.0, 0.0, 0.0, -1.0, w, h),
270 => Matrix::new(0.0, 1.0, -1.0, 0.0, h, 0.0),
_ => Matrix::IDENTITY,
}
}
}
impl<'doc> Page<'doc> {
pub(crate) fn new(doc: &'doc Document, index: usize) -> Self {
Self {
doc,
index,
chars_cache: OnceLock::new(),
metrics_cache: OnceLock::new(),
}
}
pub fn index(&self) -> usize {
self.index
}
pub fn document(&self) -> &'doc Document {
self.doc
}
pub(crate) fn page_id(&self) -> lopdf::ObjectId {
self.doc.page_ids[self.index]
}
pub(crate) fn metrics(&self) -> &PageMetrics {
self.metrics_cache.get_or_init(|| {
crate::parser::lopdf_backend::page_metrics(&self.doc.inner, self.page_id(), self.index)
.unwrap_or(PageMetrics {
media_width: 612.0,
media_height: 792.0,
rotation: 0,
})
})
}
pub fn width(&self) -> f32 {
self.metrics().display_width()
}
pub fn height(&self) -> f32 {
self.metrics().display_height()
}
pub fn rotation(&self) -> i16 {
self.metrics().rotation
}
pub fn chars(&self) -> Result<&[Char]> {
if let Some(cached) = self.chars_cache.get() {
return Ok(cached.as_slice());
}
let parsed = crate::parser::lopdf_backend::extract_chars(self)?;
let _ = self.chars_cache.set(parsed);
Ok(self
.chars_cache
.get()
.expect("chars_cache populated by either set() above or a concurrent caller")
.as_slice())
}
pub fn words(&self, opts: &WordOptions) -> Result<Vec<Word>> {
let chars = self.chars()?;
Ok(crate::text::extractor::extract_words(chars, opts))
}
pub fn extract_text(&self) -> Result<String> {
let chars = self.chars()?;
Ok(crate::text::extractor::extract_text_simple(chars))
}
pub fn extract_text_layout(&self, opts: &TextOptions) -> Result<String> {
let chars = self.chars()?;
Ok(crate::text::extractor::extract_text_layout(chars, opts))
}
pub fn is_scanned(&self) -> Result<bool> {
crate::parser::scan_detect::is_scanned(self)
}
}