use crate::djvu_document::{DjVuDocument, DjVuPage, DocError};
use crate::djvu_render::{self, RenderError, RenderOptions};
use crate::pixmap::Pixmap;
#[derive(Debug)]
pub(crate) enum ForeignError {
Parse(String),
Decode(String),
OutOfRange(String),
}
impl ForeignError {
pub(crate) fn code(&self) -> i32 {
match self {
ForeignError::Parse(_) => 1,
ForeignError::Decode(_) => 2,
ForeignError::OutOfRange(_) => 3,
}
}
fn from_page_lookup(e: DocError) -> Self {
match e {
DocError::PageOutOfRange { .. } => ForeignError::OutOfRange(e.to_string()),
other => ForeignError::Decode(other.to_string()),
}
}
}
impl core::fmt::Display for ForeignError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ForeignError::Parse(m) | ForeignError::Decode(m) | ForeignError::OutOfRange(m) => {
f.write_str(m)
}
}
}
}
pub(crate) fn open(data: &[u8]) -> Result<DjVuDocument, ForeignError> {
DjVuDocument::parse(data).map_err(|e| ForeignError::Parse(e.to_string()))
}
pub(crate) fn page(doc: &DjVuDocument, index: usize) -> Result<&DjVuPage, ForeignError> {
doc.page(index).map_err(ForeignError::from_page_lookup)
}
pub(crate) fn page_width(doc: &DjVuDocument, index: usize) -> Result<u32, ForeignError> {
Ok(page(doc, index)?.width() as u32)
}
pub(crate) fn page_height(doc: &DjVuDocument, index: usize) -> Result<u32, ForeignError> {
Ok(page(doc, index)?.height() as u32)
}
pub(crate) fn page_dpi(doc: &DjVuDocument, index: usize) -> Result<u32, ForeignError> {
Ok(page(doc, index)?.dpi() as u32)
}
pub(crate) fn text(doc: &DjVuDocument, index: usize) -> Result<Option<String>, ForeignError> {
page(doc, index)?
.text()
.map_err(|e| ForeignError::Decode(e.to_string()))
}
pub(crate) fn render_opts_for_dpi(page: &DjVuPage, target_dpi: f32) -> RenderOptions {
let (width, height) = crate::export_common::size_at_dpi(page, target_dpi);
RenderOptions {
width,
height,
permissive: true,
..RenderOptions::default()
}
}
pub(crate) fn render_at_dpi(
doc: &DjVuDocument,
index: usize,
target_dpi: f32,
) -> Result<Pixmap, ForeignError> {
let page = page(doc, index)?;
let opts = render_opts_for_dpi(page, target_dpi);
djvu_render::render_pixmap(page, &opts).map_err(map_render_err)
}
pub(crate) fn map_render_err(e: RenderError) -> ForeignError {
ForeignError::Decode(e.to_string())
}