tikz-gallery-generator
Custum build of stapix for tikz.pablopie.xyz
| Name | Size | Mode |
| .. | ||
| src/mupdf.rs | 2K | -rw-r--r-- |
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111
//! Safe MuPDF wrappers use std::{ptr, slice, ops::Deref, ffi::CStr}; use mupdf_sys::*; #[derive(Debug)] pub struct Document { ctx: *mut fz_context, inner: *mut fz_document, page_count: usize, } #[derive(Debug)] pub struct Buffer<'doc> { doc: &'doc Document, inner: *mut fz_buffer, } impl Document { pub fn open_from_bytes(bytes: &[u8]) -> Result<Self, String> { let ctx = unsafe { fz_new_context(ptr::null(), ptr::null(), FZ_STORE_DEFAULT as usize) }; assert!(!ctx.is_null()); // SAFETY: this should really be wrapped with fz_try, but it can only // fail if ctx does not contain a document handler list (?) or // the list is already full. seems safe to assume // fz_new_documment will handle us a sane ctx unsafe { fz_register_document_handlers(ctx); } unsafe { fz_set_warning_callback(ctx, None, ptr::null_mut()); fz_set_error_callback(ctx, None, ptr::null_mut()); } let mut doc = ptr::null_mut(); let mut page_count = 0; let result = unsafe { mupdf_open_doc_from_bytes( ctx, bytes.as_ptr() as *mut _, bytes.len(), &mut doc, &mut page_count, ) }; if result.type_ != FZ_ERROR_NONE { return Err(unsafe { CStr::from_ptr(result.err_msg).to_string_lossy().to_string() }); } assert!(!doc.is_null()); let page_count = page_count as usize; Ok(Self { ctx, inner: doc, page_count, }) } pub fn render_page_to_svg( &self, page: usize, ) -> Result<Buffer<'_>, String> { assert!(page < self.page_count, "page {page} is out of bounds: document only has {} pages", self.page_count); let mut buf = ptr::null_mut(); let result = unsafe { mupdf_page_to_svg(self.ctx, self.inner, page, &mut buf) }; if result.type_ != FZ_ERROR_NONE { return Err(unsafe { CStr::from_ptr(result.err_msg).to_string_lossy().to_string() }); } assert!(!buf.is_null()); Ok(Buffer { doc: self, inner: buf, }) } } impl Drop for Document { fn drop(&mut self) { unsafe { fz_drop_document(self.ctx, self.inner); fz_drop_context(self.ctx); } } } impl<'doc> Deref for Buffer<'doc> { type Target = [u8]; fn deref(&self) -> &[u8] { unsafe { slice::from_raw_parts( (*self.inner).data as *const _, (*self.inner).len ) } } } impl<'doc> Drop for Buffer<'doc> { fn drop(&mut self) { unsafe { fz_drop_buffer(self.doc.ctx, self.inner); } } }