1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
//! This is kind of the entry-point of the type-safe PDF functionality.
use std::fs;
use std::marker::PhantomData;
use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use std::path::Path;

use crate as pdf;
use crate::error::*;
use crate::object::*;
use crate::primitive::{Primitive, Dictionary, PdfString};
use crate::backend::Backend;
use crate::any::{Any};
use crate::parser::Lexer;
use crate::parser::{parse_indirect_object, parse};
use crate::xref::{XRef, XRefTable};
use crate::crypt::Decoder;
use crate::crypt::CryptDict;

pub struct PromisedRef<T> {
    inner:      PlainRef,
    _marker:    PhantomData<T>
}
impl<'a, T> Into<PlainRef> for &'a PromisedRef<T> {
    fn into(self) -> PlainRef {
        self.inner
    }
}
impl<'a, T> Into<Ref<T>> for &'a PromisedRef<T> {
    fn into(self) -> Ref<T> {
        Ref::new(self.into())
    }
}

pub struct Storage<B: Backend> {
    // objects identical to those in the backend
    cache: RefCell<HashMap<PlainRef, Any>>,

    // objects that differ from the backend
    changes:    HashMap<ObjNr, Primitive>,

    refs:       XRefTable,

    decoder:    Option<Decoder>,

    backend: B,

    /// Position of the PDF header in the file.
    start_offset: usize,
}
impl<B: Backend> Storage<B> {
    pub fn new(backend: B, refs: XRefTable, start_offset: usize) -> Storage<B> {
        Storage {
            backend,
            refs,
            start_offset,
            cache: RefCell::new(HashMap::new()),
            changes: HashMap::new(),
            decoder: None,
        }
    }
}
impl<B: Backend> Resolve for Storage<B> {
    fn resolve(&self, r: PlainRef) -> Result<Primitive> {
        match self.changes.get(&r.id) {
            Some(ref p) => Ok((*p).clone()),
            None => match t!(self.refs.get(r.id)) {
                XRef::Raw {pos, ..} => {
                    let mut lexer = Lexer::new(t!(self.backend.read(self.start_offset + pos ..)));
                    let p = t!(parse_indirect_object(&mut lexer, self, self.decoder.as_ref())).1;
                    Ok(p)
                }
                XRef::Stream {stream_id, index} => {
                    let obj_stream = t!(self.resolve(PlainRef {id: stream_id, gen: 0 /* TODO what gen nr? */}));
                    let obj_stream = t!(ObjectStream::from_primitive(obj_stream, self));
                    let slice = t!(obj_stream.get_object_slice(index));
                    parse(slice, self)
                }
                XRef::Free {..} => err!(PdfError::FreeObject {obj_nr: r.id}),
                XRef::Promised => unimplemented!(),
                XRef::Invalid => err!(PdfError::NullRef {obj_nr: r.id}),
            }
        }
    }
    fn get<T: Object>(&self, r: Ref<T>) -> Result<Rc<T>> {
        let key = r.get_inner();
        
        if let Some(any) = self.cache.borrow().get(&key) {
            return any.clone().downcast();
        }

        let primitive = t!(self.resolve(key));
        let obj = t!(T::from_primitive(primitive, self));
        let rc = Rc::new(obj);
        self.cache.borrow_mut().insert(key, Any::new(rc.clone()));
        
        Ok(rc)
    }
}

pub fn load_storage_and_trailer<B: Backend>(backend: B) -> Result<(Storage<B>, Dictionary)> {
    load_storage_and_trailer_password(backend, b"")
}

pub fn load_storage_and_trailer_password<B: Backend>(
    backend: B,
    password: &[u8],
) -> Result<(Storage<B>, Dictionary)> {
    let start_offset = t!(backend.locate_start_offset());
    let (refs, trailer) = t!(backend.read_xref_table_and_trailer(start_offset));
    let mut storage = Storage::new(backend, refs, start_offset);

    if let Some(crypt) = trailer.get("Encrypt") {
        let key = trailer
            .get("ID")
            .ok_or(PdfError::MissingEntry {
                typ: "Trailer",
                field: "ID".into(),
            })?
            .as_array()?[0]
            .as_string()?
            .as_bytes();
        let dict = CryptDict::from_primitive(crypt.clone(), &storage)?;
        storage.decoder = Some(t!(Decoder::from_password(&dict, key, password)));
        if let Primitive::Reference(reference) = crypt {
            storage.decoder.as_mut().unwrap().encrypt_indirect_object = Some(*reference);
        }
    }
    Ok((storage, trailer))
}

pub struct File<B: Backend> {
    storage:    Storage<B>,
    pub trailer:    Trailer,
}
impl<B: Backend> Resolve for File<B> {
    fn resolve(&self, r: PlainRef) -> Result<Primitive> {
        self.storage.resolve(r)
    }
    fn get<T: Object>(&self, r: Ref<T>) -> Result<Rc<T>> {
        self.storage.get(r)
    }
}
impl File<Vec<u8>> {
    /// Opens the file at `path` and uses Vec<u8> as backend.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        Self::from_data(fs::read(path)?)
    }

    /// Opens the file at `path`, with a password, and uses Vec<u8> as backend.
    pub fn open_password(path: impl AsRef<Path>, password: &[u8]) -> Result<Self> {
        Self::from_data_password(fs::read(path)?, password)
    }
}
impl<B: Backend> File<B> {
    pub fn from_data_password(backend: B, password: &[u8]) -> Result<Self> {
        Self::load_data(backend, password).map_err(|e| dbg!(e))
    }

    pub fn from_data(backend: B) -> Result<Self> {
        Self::from_data_password(backend, b"")
    }

    fn load_data(backend: B, password: &[u8]) -> Result<Self> {
        let (storage, trailer) = load_storage_and_trailer_password(backend, password)?;
        let trailer = t!(Trailer::from_primitive(
            Primitive::Dictionary(trailer),
            &storage,
        ));
        Ok(File { storage, trailer })
    }

    pub fn get_root(&self) -> &Catalog {
        &self.trailer.root
    }

    pub fn pages<'a>(&'a self) -> impl Iterator<Item=Result<PageRc>> + 'a {
        (0 .. self.num_pages()).map(move |n| self.get_page(n))
    }
    pub fn num_pages(&self) -> u32 {
        match *self.trailer.root.pages {
            PagesNode::Tree(ref tree) => tree.count,
            PagesNode::Leaf(_) => 1
        }
    }

    pub fn get_page(&self, n: u32) -> Result<PageRc> {
        match *self.trailer.root.pages {
            PagesNode::Tree(ref tree) => {
                tree.page(self, n)
            }
            PagesNode::Leaf(ref page) if n == 0 => Ok(page.clone()),
            _ => Err(PdfError::PageOutOfBounds {page_nr: n, max: 1})
        }
    }

    /*
    pub fn get_images(&self) -> Vec<ImageXObject> {
        let mut images = Vec::<ImageXObject>::new();
        scan_pages(&self.trailer.root.pages, 0, &mut |page| {
            println!("Found page!");
            match page.resources {
                Some(ref res) => {
                    match res.xobject {
                        Some(ref xobjects) => {
                            for (name, xobject) in xobjects {
                                match *xobject {
                                    XObject::Image (ref img_xobject) => {
                                        images.push(img_xobject.clone())
                                    }
                                    _ => {},
                                }
                            }
                        },
                        None => {},
                    }
                },
                None => {},
            }
        });
        images
    }
    
    // tail call to trick borrowck
    fn update_pages(&self, pages: &mut PageTree, mut offset: i32, page_nr: i32, page: Page) -> Result<()>  {
        for kid in &mut pages.kids.iter_mut() {
            // println!("{}/{} {:?}", offset, page_nr, kid);
            match *(self.get(kid)?) {
                PagesNode::Tree(ref mut t) => {
                    if offset + t.count < page_nr {
                        offset += t.count;
                    } else {
                        return self.update_pages(t, offset, page_nr, page);
                    }
                },
                PagesNode::Leaf(ref mut p) => {
                    if offset < page_nr {
                        offset += 1;
                    } else {
                        assert_eq!(offset, page_nr);
                        *p = page;
                        return Ok(());
                    }
                }
            }
            
        }
        Err(PdfError::PageNotFound {page_nr: page_nr})
    }
    
    pub fn update_page(&mut self, page_nr: i32, page: Page) -> Result<()> {
        self.update_pages(&mut self.trailer.root.pages, 0, page_nr, page)
    }
    
    pub fn update(&mut self, id: ObjNr, primitive: Primitive) {
        self.changes.insert(id, primitive);
    }
    
    pub fn promise<T: Object>(&mut self) -> PromisedRef<T> {
        let id = self.refs.len() as u64;
        
        self.refs.push(XRef::Promised);
        
        PromisedRef {
            inner: PlainRef {
                id:     id,
                gen:    0
            },
            _marker:    PhantomData
        }
    }
    
    pub fn fulfill<T>(&mut self, promise: PromisedRef<T>, obj: T) -> Ref<T>
    where T: Into<Primitive>
    {
        self.update(promise.inner.id, obj.into());
        
        Ref::new(promise.inner)
    }
    
    pub fn add<T>(&mut self, obj: T) -> Ref<T> where T: Into<Primitive> {
        let id = self.refs.len() as u64;
        self.refs.push(XRef::Promised);
        self.update(id, obj.into());
        
        Ref::from_id(id)
    }
    */
}

    
#[derive(Object)]
pub struct Trailer {
    #[pdf(key = "Size")]
    pub highest_id:         i32,

    #[pdf(key = "Prev")]
    pub prev_trailer_pos:   Option<i32>,

    #[pdf(key = "Root")]
    pub root:               Catalog,

    #[pdf(key = "Encrypt")]
    pub encrypt_dict:       Option<CryptDict>,

    #[pdf(key = "Info")]
    pub info_dict:          Option<Dictionary>,

    #[pdf(key = "ID")]
    pub id:                 Vec<PdfString>,
}

#[derive(Object, Debug)]
#[pdf(Type = "XRef")]
pub struct XRefInfo {
    // XRefStream fields
    #[pdf(key = "Size")]
    pub size: i32,

    //
    #[pdf(key = "Index", default = "vec![0, size]")]
    /// Array of pairs of integers for each subsection, (first object number, number of entries).
    /// Default value (assumed when None): `(0, self.size)`.
    pub index: Vec<i32>,

    #[pdf(key = "Prev")]
    prev: Option<i32>,

    #[pdf(key = "W")]
    pub w: Vec<i32>
}

/*
pub struct XRefStream {
    pub data: Vec<u8>,
    pub info: XRefInfo,
}

impl Object for XRefStream {
    fn serialize<W: io::Write>(&self, _out: &mut W) -> io::Result<()> {
        unimplemented!();
    }
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> {
        let stream = p.to_stream(resolve)?;
        let info = XRefInfo::from_primitive(Primitive::Dictionary (stream.info), resolve)?;
        let data = stream.data.clone();
        Ok(XRefStream {
            data: data,
            info: info,
        })
    }
}
*/