]> www.fi.muni.cz Git - evince.git/blob - pdf/xpdf/pdf-document.cc
5a7304c6162afe6d5b73fea8b138a40cb822dcc7
[evince.git] / pdf / xpdf / pdf-document.cc
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; c-indent-level: 8 -*- */
2 /* pdfdocument.h: Implementation of EvDocument for PDF
3  * Copyright (C) 2004, Red Hat, Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #include <glib/gi18n.h>
21
22 #include "gpdf-g-switch.h"
23 #include "pdf-document.h"
24 #include "ev-ps-exporter.h"
25 #include "ev-document-find.h"
26 #include "gpdf-g-switch.h"
27 #include "ev-document-links.h"
28 #include "ev-document-misc.h"
29 #include "ev-document-security.h"
30 #include "ev-document-thumbnails.h"
31
32 #include "GlobalParams.h"
33 #include "GDKSplashOutputDev.h"
34 #include "SplashBitmap.h"
35 #include "PDFDoc.h"
36 #include "Outline.h"
37 #include "ErrorCodes.h"
38 #include "UnicodeMap.h"
39 #include "GlobalParams.h"
40 #include "GfxState.h"
41 #include "Thumb.h"
42 #include "goo/GList.h"
43 #include "PSOutputDev.h"
44
45 enum {
46         PROP_0,
47         PROP_TITLE
48 };
49
50 typedef struct
51 {
52         PdfDocument *document;
53         gunichar *ucs4;
54         glong ucs4_len;
55         guint idle;
56         /* full results are only possible for the rendered current page */
57         int current_page;
58         GArray *current_page_results;
59         int *other_page_flags; /* length n_pages + 1, first element ignored */
60         int start_page;   /* skip this one as we iterate, since we did it first */
61         int search_page;  /* the page we're searching now */
62         TextOutputDev *output_dev;
63 } PdfDocumentSearch;
64
65 typedef struct _PdfDocumentClass PdfDocumentClass;
66
67 #define PDF_DOCUMENT_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), PDF_TYPE_DOCUMENT, PdfDocumentClass))
68 #define PDF_IS_DOCUMENT_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), PDF_TYPE_DOCUMENT))
69 #define PDF_DOCUMENT_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), PDF_TYPE_DOCUMENT, PdfDocumentClass))
70
71 struct _PdfDocumentClass
72 {
73         GObjectClass parent_class;
74 };
75
76 struct _PdfDocument
77 {
78         GObject parent_instance;
79
80         int page;
81         int page_x_offset;
82         int page_y_offset;
83         double scale;
84         GdkDrawable *target;
85
86         GDKSplashOutputDev *out;
87         PSOutputDev *ps_out;
88         PDFDoc *doc;
89         Links *links;
90         UnicodeMap *umap;
91
92         gchar *password;
93         gboolean page_valid;
94
95         PdfDocumentSearch *search;
96 };
97
98 static void pdf_document_document_links_iface_init      (EvDocumentLinksIface      *iface);
99 static void pdf_document_document_thumbnails_iface_init (EvDocumentThumbnailsIface *iface);
100 static void pdf_document_document_iface_init            (EvDocumentIface           *iface);
101 static void pdf_document_ps_exporter_iface_init         (EvPSExporterIface         *iface);
102 static void pdf_document_find_iface_init                (EvDocumentFindIface       *iface);
103 static void pdf_document_security_iface_init            (EvDocumentSecurityIface   *iface);
104 static void pdf_document_search_free                    (PdfDocumentSearch         *search);
105 static void pdf_document_search_page_changed            (PdfDocumentSearch         *search);
106
107
108 G_DEFINE_TYPE_WITH_CODE (PdfDocument, pdf_document, G_TYPE_OBJECT,
109                          {
110                                  G_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT,
111                                                         pdf_document_document_iface_init);
112                                  G_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_LINKS,
113                                                         pdf_document_document_links_iface_init);
114                                  G_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_THUMBNAILS,
115                                                         pdf_document_document_thumbnails_iface_init);
116                                  G_IMPLEMENT_INTERFACE (EV_TYPE_PS_EXPORTER,
117                                                         pdf_document_ps_exporter_iface_init);
118                                  G_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_FIND,
119                                                         pdf_document_find_iface_init);
120                                  G_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_SECURITY,
121                                                         pdf_document_security_iface_init);
122                          });
123
124 static void
125 document_init_links (PdfDocument *pdf_document)
126 {
127         Page *page;
128         Object obj;
129
130         if (pdf_document->links) {
131                 delete pdf_document->links;
132         }
133         page = pdf_document->doc->getCatalog ()->getPage (pdf_document->page);
134         pdf_document->links = new Links (page->getAnnots (&obj),
135                                          pdf_document->doc->getCatalog ()->getBaseURI ());
136         obj.free ();
137 }
138
139 static gboolean
140 document_validate_page (PdfDocument *pdf_document)
141 {
142         if (!pdf_document->page_valid) {
143                 pdf_document->doc->displayPage (pdf_document->out, pdf_document->page,
144                                                 72 * pdf_document->scale,
145                                                 72 * pdf_document->scale,
146                                                 0, gTrue, gTrue);
147
148                 document_init_links (pdf_document);
149
150                 pdf_document->page_valid = TRUE;
151
152                 ev_document_changed (EV_DOCUMENT (pdf_document));
153
154                 /* Update the search results available to the app since
155                  * we only provide full results on the current page
156                  */
157                 if (pdf_document->search)
158                         pdf_document_search_page_changed (pdf_document->search);
159         }
160
161         return pdf_document->page_valid;
162 }
163
164 static gboolean
165 pdf_document_load (EvDocument  *document,
166                    const char  *uri,
167                    GError     **error)
168 {
169         PdfDocument *pdf_document = PDF_DOCUMENT (document);
170         PDFDoc *newDoc;
171         int err;
172         char *filename;
173         GString *filename_g;
174         GString *enc;
175
176         if (!globalParams) {
177                 globalParams = new GlobalParams("/etc/xpdfrc");
178                 globalParams->setupBaseFontsFc(NULL);
179         }
180
181         if (! pdf_document->umap) {
182                 enc = new GString("UTF-8");
183                 pdf_document->umap = globalParams->getUnicodeMap(enc);
184                 pdf_document->umap->incRefCnt ();
185                 delete enc;
186         }
187
188         filename = g_filename_from_uri (uri, NULL, error);
189         if (!filename)
190                 return FALSE;
191
192         filename_g = new GString (filename);
193         g_free (filename);
194
195         // open the PDF file, assumes ownership of filename_g
196         GString *password = NULL;
197         if (pdf_document->password)
198                 password = new GString (pdf_document->password);
199         newDoc = new PDFDoc(filename_g, password, password);
200         if (password)
201                 delete password;
202
203         if (!newDoc->isOk()) {
204                 err = newDoc->getErrorCode();
205                 delete newDoc;
206                 if (err == errEncrypted) {
207                         g_set_error (error, EV_DOCUMENT_ERROR,
208                                      EV_DOCUMENT_ERROR_ENCRYPTED,
209                                      "Document is encrypted.");
210                 } else {
211                         g_set_error (error, G_FILE_ERROR,
212                                      G_FILE_ERROR_FAILED,
213                                      "Failed to load document (error %d) '%s'\n",
214                                      err,
215                                      uri);
216                 }
217
218                 return FALSE;
219         }
220
221         if (pdf_document->doc)
222                 delete pdf_document->doc;
223         pdf_document->doc = newDoc;
224
225         pdf_document->page = 1;
226
227         if (pdf_document->out)
228                 pdf_document->out->startDoc(pdf_document->doc->getXRef());
229
230         pdf_document->page_valid = FALSE;
231
232         g_object_notify (G_OBJECT (pdf_document), "title");
233
234         return TRUE;
235 }
236
237 static gboolean
238 pdf_document_save (EvDocument  *document,
239                    const char  *uri,
240                    GError     **error)
241 {
242         PdfDocument *pdf_document = PDF_DOCUMENT (document);
243         char *filename;
244         gboolean retval = FALSE;
245
246         filename = g_filename_from_uri (uri, NULL, error);
247         if (filename != NULL) {
248                 GString *fname = new GString (filename);
249
250                 retval = pdf_document->doc->saveAs (fname);
251         }
252
253         return retval;
254 }
255
256 static int
257 pdf_document_get_n_pages (EvDocument  *document)
258 {
259         PdfDocument *pdf_document = PDF_DOCUMENT (document);
260
261         if (pdf_document->doc)
262                 return pdf_document->doc->getNumPages();
263         else
264                 return 1;
265 }
266
267 static void
268 pdf_document_set_page (EvDocument  *document,
269                        int          page)
270 {
271         PdfDocument *pdf_document = PDF_DOCUMENT (document);
272
273         page = CLAMP (page, 1, ev_document_get_n_pages (document));
274
275         if (page != pdf_document->page) {
276                 pdf_document->page = page;
277                 pdf_document->page_valid = FALSE;
278         }
279 }
280
281 static int
282 pdf_document_get_page (EvDocument  *document)
283 {
284         PdfDocument *pdf_document = PDF_DOCUMENT (document);
285
286         return pdf_document->page;
287 }
288
289 static void
290 redraw_callback (void *data)
291 {
292         /* Need to hook up through a EvDocument callback? */
293 }
294
295 static void
296 pdf_document_set_target (EvDocument  *document,
297                          GdkDrawable *target)
298 {
299         PdfDocument *pdf_document = PDF_DOCUMENT (document);
300
301         if (pdf_document->target != target) {
302                 if (pdf_document->target)
303                         g_object_unref (pdf_document->target);
304
305                 pdf_document->target = target;
306
307                 if (pdf_document->target)
308                         g_object_ref (pdf_document->target);
309
310                 if (pdf_document->out) {
311                         delete pdf_document->out;
312                         pdf_document->out = NULL;
313                 }
314
315                 if (pdf_document->target) {
316                         pdf_document->out = new GDKSplashOutputDev (gdk_drawable_get_screen (pdf_document->target),
317                                                          redraw_callback, (void*) document);
318
319                         if (pdf_document->doc)
320                                 pdf_document->out->startDoc(pdf_document->doc->getXRef());
321
322                 }
323
324                 pdf_document->page_valid = FALSE;
325         }
326 }
327
328 static void
329 pdf_document_set_scale (EvDocument  *document,
330                         double       scale)
331 {
332         PdfDocument *pdf_document = PDF_DOCUMENT (document);
333
334         if (pdf_document->scale != scale) {
335                 pdf_document->scale = scale;
336                 pdf_document->page_valid = FALSE;
337         }
338 }
339
340 static void
341 pdf_document_set_page_offset (EvDocument  *document,
342                               int          x,
343                               int          y)
344 {
345         PdfDocument *pdf_document = PDF_DOCUMENT (document);
346
347         pdf_document->page_x_offset = x;
348         pdf_document->page_y_offset = y;
349 }
350
351 static void
352 pdf_document_get_page_size (EvDocument   *document,
353                             int          *width,
354                             int          *height)
355 {
356         PdfDocument *pdf_document = PDF_DOCUMENT (document);
357
358         if (document_validate_page (pdf_document)) {
359                 if (width)
360                         *width = pdf_document->out->getBitmapWidth();
361                 if (height)
362                         *height = pdf_document->out->getBitmapHeight();
363         } else {
364                 if (width)
365                         *width = 1;
366                 if (height)
367                         *height = 1;
368         }
369 }
370
371 static void
372 pdf_document_render (EvDocument  *document,
373                      int          clip_x,
374                      int          clip_y,
375                      int          clip_width,
376                      int          clip_height)
377 {
378         PdfDocument *pdf_document = PDF_DOCUMENT (document);
379         GdkRectangle page;
380         GdkRectangle draw;
381
382         if (!document_validate_page (pdf_document) || !pdf_document->target)
383                 return;
384
385         page.x = pdf_document->page_x_offset;
386         page.y = pdf_document->page_y_offset;
387         page.width = pdf_document->out->getBitmapWidth();
388         page.height = pdf_document->out->getBitmapHeight();
389
390         draw.x = clip_x;
391         draw.y = clip_y;
392         draw.width = clip_width;
393         draw.height = clip_height;
394
395         if (gdk_rectangle_intersect (&page, &draw, &draw))
396                 pdf_document->out->redraw (draw.x - page.x, draw.y - page.y,
397                                            pdf_document->target,
398                                            draw.x, draw.y,
399                                            draw.width, draw.height);
400 }
401
402 int
403 pdf_document_find_page_has_results (EvDocumentFind *document_find,
404                                     int             page)
405 {
406         PdfDocumentSearch *search = PDF_DOCUMENT (document_find)->search;
407
408         g_return_val_if_fail (search != NULL, FALSE);
409
410         return search->other_page_flags[page];
411 }
412
413 int
414 pdf_document_find_get_n_results (EvDocumentFind *document_find)
415 {
416         PdfDocumentSearch *search = PDF_DOCUMENT (document_find)->search;
417
418         if (search) {
419                 return search->current_page_results->len;
420         } else {
421                 return 0;
422         }
423 }
424
425 gboolean
426 pdf_document_find_get_result (EvDocumentFind *document_find,
427                               int             n_result,
428                               GdkRectangle   *rectangle)
429 {
430         PdfDocumentSearch *search = PDF_DOCUMENT (document_find)->search;
431         GdkRectangle r;
432
433         if (search != NULL) {
434                 r = g_array_index (search->current_page_results,
435                                    GdkRectangle, n_result);
436
437                 rectangle->x = r.x;
438                 rectangle->y = r.y;
439                 rectangle->width = r.width;
440                 rectangle->height = r.height;
441
442                 return TRUE;
443         } else {
444                 return FALSE;
445         }
446 }
447
448 static void
449 pdf_document_search_page_changed (PdfDocumentSearch   *search)
450 {
451         PdfDocument *pdf_document = search->document;
452         int current_page;
453         GdkRectangle result;
454         int xMin, yMin, xMax, yMax;
455
456         current_page = pdf_document->page;
457
458         if (!pdf_document->page_valid) {
459                 /* we can't do anything until displayPage() */
460                 search->current_page = -1;
461                 return;
462         }
463
464         if (search->current_page == current_page)
465                 return;
466
467         /* We need to create current_page_results for the new current page */
468         g_array_set_size (search->current_page_results, 0);
469
470         if (pdf_document->out->findText (search->ucs4, search->ucs4_len,
471                                          gTrue, gTrue, // startAtTop, stopAtBottom
472                                          gFalse, gFalse, // startAtLast, stopAtLast
473                                          &xMin, &yMin, &xMax, &yMax)) {
474                 result.x = xMin;
475                 result.y = yMin;
476                 result.width = xMax - xMin;
477                 result.height = yMax - yMin;
478
479                 g_array_append_val (search->current_page_results, result);
480                 /* Now find further results */
481
482                 while (pdf_document->out->findText (search->ucs4, search->ucs4_len,
483                                                     gFalse, gTrue,
484                                                     gTrue, gFalse,
485                                                     &xMin, &yMin, &xMax, &yMax)) {
486                         result.x = xMin;
487                         result.y = yMin;
488                         result.width = xMax - xMin;
489                         result.height = yMax - yMin;
490
491                         g_array_append_val (search->current_page_results, result);
492                 }
493         }
494 }
495
496 static gboolean
497 pdf_document_search_idle_callback (void *data)
498 {
499         PdfDocumentSearch *search = (PdfDocumentSearch*) data;
500         PdfDocument *pdf_document = search->document;
501         int n_pages;
502         double xMin, yMin, xMax, yMax;
503
504         /* Note that PDF page count is 1 through n_pages INCLUSIVE
505          * like a real book. We are looking to add one result for each
506          * page with a match, because the coordinates are meaningless
507          * with TextOutputDev, so we just want to flag matching pages
508          * and then when the user switches to the current page, we
509          * will emit "found" again with the real results.
510          */
511         n_pages = ev_document_get_n_pages (EV_DOCUMENT (search->document));
512
513         if (search->output_dev == 0) {
514                 /* First time through here... */
515                 search->output_dev = new TextOutputDev (NULL, gTrue, gFalse, gFalse);
516                 if (!search->output_dev->isOk()) {
517                         goto end_search;
518                 }
519         }
520
521         pdf_document->doc->displayPage (search->output_dev,
522                                         search->search_page,
523                                         72, 72, 0, gTrue, gFalse);
524
525         if (search->output_dev->findText (search->ucs4,
526                                           search->ucs4_len,
527                                           gTrue, gTrue, // startAtTop, stopAtBottom
528                                           gFalse, gFalse, // startAtLast, stopAtLast
529                                           &xMin, &yMin, &xMax, &yMax)) {
530                 /* This page has results */
531                 search->other_page_flags[search->search_page] = 1;
532         } else {
533                 search->other_page_flags[search->search_page] = 0;
534         }
535
536         if (search->search_page != search->start_page) {
537                 ev_document_find_changed (EV_DOCUMENT_FIND (pdf_document),
538                                           search->search_page);
539                 return TRUE;
540         }
541
542         search->search_page += 1;
543         if (search->search_page > n_pages) {
544                 /* wrap around */
545                 search->search_page = 1;
546         }
547
548 end_search:
549         /* We're done. */
550         search->idle = 0; /* will return FALSE to remove */
551         return FALSE;
552 }
553
554 static void
555 pdf_document_find_begin (EvDocumentFind   *document,
556                          const char       *search_string,
557                          gboolean          case_sensitive)
558 {
559         PdfDocument *pdf_document = PDF_DOCUMENT (document);
560         PdfDocumentSearch *search;
561         int n_pages, i;
562         gunichar *ucs4;
563         glong ucs4_len;
564
565         /* FIXME handle case_sensitive (right now XPDF
566          * code is always case insensitive for ASCII
567          * and case sensitive for all other languaages)
568          */
569
570         g_assert (sizeof (gunichar) == sizeof (Unicode));
571         ucs4 = g_utf8_to_ucs4_fast (search_string, -1,
572                                     &ucs4_len);
573
574         if (pdf_document->search &&
575             pdf_document->search->ucs4_len == ucs4_len &&
576             memcmp (pdf_document->search->ucs4,
577                     ucs4,
578                     sizeof (gunichar) * ucs4_len) == 0) {
579                 /* Search is unchanged */
580                 g_free (ucs4);
581                 return;
582         }
583
584         if (pdf_document->search) {
585                 pdf_document_search_free (pdf_document->search);
586                 pdf_document->search = NULL;
587         }
588
589         search = g_new0 (PdfDocumentSearch, 1);
590
591         search->ucs4 = ucs4;
592         search->ucs4_len = ucs4_len;
593
594         search->current_page_results = g_array_new (FALSE,
595                                                     FALSE,
596                                                     sizeof (GdkRectangle));
597         n_pages = ev_document_get_n_pages (EV_DOCUMENT (document));
598
599         search->other_page_flags = g_new0 (int, n_pages + 1);
600         for (i = 0; i <= n_pages; i++) {
601                 search->other_page_flags[i] = -1;
602         }
603
604         search->document = pdf_document;
605
606         /* We add at low priority so the progress bar repaints */
607         search->idle = g_idle_add_full (G_PRIORITY_LOW,
608                                         pdf_document_search_idle_callback,
609                                         search,
610                                         NULL);
611
612         search->output_dev = 0;
613
614         search->start_page = pdf_document->page;
615         search->search_page = search->start_page;
616
617         search->current_page = -1;
618
619         pdf_document->search = search;
620
621         /* Update for the current page right away */
622         pdf_document_search_page_changed (search);
623 }
624
625 static void
626 pdf_document_find_cancel (EvDocumentFind   *document)
627 {
628         PdfDocument *pdf_document = PDF_DOCUMENT (document);
629
630         if (pdf_document->search) {
631                 pdf_document_search_free (pdf_document->search);
632                 pdf_document->search = NULL;
633         }
634 }
635
636 static void
637 pdf_document_search_free (PdfDocumentSearch   *search)
638 {
639         if (search->idle != 0)
640                 g_source_remove (search->idle);
641
642         if (search->output_dev)
643                 delete search->output_dev;
644
645         g_array_free (search->current_page_results, TRUE);
646         g_free (search->other_page_flags);
647
648         g_free (search->ucs4);
649         g_free (search);
650 }
651
652 static gboolean
653 pdf_document_has_document_security (EvDocumentSecurity *document_security)
654 {
655         /* FIXME: do we really need to have this? */
656         return FALSE;
657 }
658
659 static void
660 pdf_document_set_password (EvDocumentSecurity *document_security,
661                            const char         *password)
662 {
663         PdfDocument *document = PDF_DOCUMENT (document_security);
664
665         if (document->password)
666                 g_free (document->password);
667
668         document->password = g_strdup (password);
669 }
670
671 static void
672 pdf_document_ps_export_begin (EvPSExporter *exporter, const char *filename)
673 {
674         PdfDocument *document = PDF_DOCUMENT (exporter);
675
676         if (document->ps_out)
677                 delete document->ps_out;
678
679         document->ps_out = new PSOutputDev ((char *)filename, document->doc->getXRef(),
680                                             document->doc->getCatalog(), 1,
681                                             ev_document_get_n_pages (EV_DOCUMENT (document)),
682                                             psModePS);
683 }
684
685 static void
686 pdf_document_ps_export_do_page (EvPSExporter *exporter, int page)
687 {
688         PdfDocument *document = PDF_DOCUMENT (exporter);
689
690         document->doc->displayPage (document->ps_out, page,
691                                     72.0, 72.0, 0, gTrue, gFalse);
692 }
693
694 static void
695 pdf_document_ps_export_end (EvPSExporter *exporter)
696 {
697         PdfDocument *document = PDF_DOCUMENT (exporter);
698
699         delete document->ps_out;
700         document->ps_out = NULL;
701 }
702
703
704 /* EvDocumentLinks Implementation */
705 typedef struct
706 {
707         /* goo GList, not glib */
708         GList *items;
709         int index;
710         int level;
711 } LinksIter;
712
713 static gchar *
714 unicode_to_char (OutlineItem *outline_item,
715                  UnicodeMap *uMap)
716 {
717         GString gstr;
718         gchar buf[8]; /* 8 is enough for mapping an unicode char to a string */
719         int i, n;
720
721         for (i = 0; i < outline_item->getTitleLength(); ++i) {
722                 n = uMap->mapUnicode(outline_item->getTitle()[i], buf, sizeof(buf));
723                 gstr.append(buf, n);
724         }
725
726         return g_strdup (gstr.getCString ());
727 }
728
729
730 static gboolean
731 pdf_document_links_has_document_links (EvDocumentLinks *document_links)
732 {
733         PdfDocument *pdf_document = PDF_DOCUMENT (document_links);
734         Outline *outline;
735
736         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);
737
738         outline = pdf_document->doc->getOutline();
739         if (outline->getItems() != NULL &&
740             outline->getItems()->getLength() > 0)
741                 return TRUE;
742
743         return FALSE;
744 }
745
746 static EvDocumentLinksIter *
747 pdf_document_links_begin_read (EvDocumentLinks *document_links)
748 {
749         PdfDocument *pdf_document = PDF_DOCUMENT (document_links);
750         Outline *outline;
751         LinksIter *iter;
752         GList *items;
753
754         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), NULL);
755
756         outline = pdf_document->doc->getOutline();
757         items = outline->getItems();
758         if (! items)
759                 return NULL;
760
761         iter = g_new0 (LinksIter, 1);
762         iter->items = items;
763         iter->index = 0;
764         iter->level = 0;
765
766         return (EvDocumentLinksIter *) iter;
767 }
768
769 static EvLink *
770 build_link_from_action (PdfDocument *pdf_document,
771                         LinkAction  *link_action,
772                         const char  *title)
773 {
774         EvLink *link = NULL;
775
776         if (link_action == NULL) {
777                 link = ev_link_new_title (title);
778         } else if (link_action->getKind () == actionGoTo) {
779                 LinkDest *link_dest;
780                 LinkGoTo *link_goto;
781                 Ref page_ref;
782                 gint page_num = 0;
783                 GString *named_dest;
784
785                 link_goto = dynamic_cast <LinkGoTo *> (link_action);
786                 link_dest = link_goto->getDest ();
787                 named_dest = link_goto->getNamedDest ();
788
789                 /* Wow!  This seems excessively slow on large
790                  * documents. I need to investigate more... -jrb */
791                 if (link_dest != NULL) {
792                         link_dest = link_dest->copy ();
793                 } else if (named_dest != NULL) {
794                         named_dest = named_dest->copy ();
795                         link_dest = pdf_document->doc->findDest (named_dest);
796                         delete named_dest;
797                 }
798                 if (link_dest != NULL) {
799                         if (link_dest->isPageRef ()) {
800                                 page_ref = link_dest->getPageRef ();
801                                 page_num = pdf_document->doc->findPage (page_ref.num, page_ref.gen);
802                         } else {
803                                 page_num = link_dest->getPageNum ();
804                         }
805                         delete link_dest;
806                 }
807
808                 link = ev_link_new_page (title, page_num);
809         } else if (link_action->getKind () == actionURI) {
810                 LinkURI *link_uri;
811
812                 link_uri = dynamic_cast <LinkURI *> (link_action);
813                 link = ev_link_new_external
814                         (title, link_uri->getURI()->getCString());
815         } else if (link_action->getKind () == actionNamed) {
816                         /*Skip, for now */
817         }
818
819         return link;
820 }
821
822 /* FIXME This returns a new object every time, probably we should cache it
823    in the iter */
824 static EvLink *
825 pdf_document_links_get_link (EvDocumentLinks      *document_links,
826                              EvDocumentLinksIter  *links_iter)
827 {
828         PdfDocument *pdf_document = PDF_DOCUMENT (document_links);
829         LinksIter *iter = (LinksIter *)links_iter;
830         OutlineItem *anItem;
831         LinkAction *link_action;
832         Unicode *link_title;
833         const char *title;
834
835         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);
836         g_return_val_if_fail (iter != NULL, FALSE);
837
838         anItem = (OutlineItem *)iter->items->get(iter->index);
839         link_action = anItem->getAction ();
840         link_title = anItem->getTitle ();
841         title = unicode_to_char (anItem, pdf_document->umap);
842
843         return build_link_from_action (pdf_document, link_action, title);
844 }
845
846 static EvDocumentLinksIter *
847 pdf_document_links_get_child (EvDocumentLinks     *document_links,
848                               EvDocumentLinksIter *links_iter)
849 {
850         LinksIter *iter = (LinksIter *)links_iter;
851         LinksIter *child_iter;
852         OutlineItem *anItem;
853
854         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);
855
856         anItem = (OutlineItem *)iter->items->get(iter->index);
857         anItem->open ();
858         if (! (anItem->hasKids() && anItem->getKids()) )
859                 return NULL;
860
861         child_iter = g_new0 (LinksIter, 1);
862         child_iter->index = 0;
863         child_iter->level = iter->level + 1;
864         child_iter->items = anItem->getKids ();
865         g_assert (child_iter->items);
866
867         return (EvDocumentLinksIter *) child_iter;
868 }
869
870 static gboolean
871 pdf_document_links_next (EvDocumentLinks     *document_links,
872                          EvDocumentLinksIter *links_iter)
873 {
874         LinksIter *iter = (LinksIter *) links_iter;
875
876         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);
877
878         iter->index++;
879         if (iter->index >= iter->items->getLength())
880                 return FALSE;
881
882         return TRUE;
883 }
884
885 static void
886 pdf_document_links_free_iter (EvDocumentLinks     *document_links,
887                               EvDocumentLinksIter *iter)
888 {
889         g_return_if_fail (PDF_IS_DOCUMENT (document_links));
890         g_return_if_fail (iter != NULL);
891
892         /* FIXME: Should I close all the nodes?? Free them? */
893         g_free (iter);
894 }
895
896 static void
897 pdf_document_finalize (GObject *object)
898 {
899         PdfDocument *pdf_document = PDF_DOCUMENT (object);
900
901         if (pdf_document->links) {
902                 delete pdf_document->links;
903         }
904
905         if (pdf_document->umap) {
906                 pdf_document->umap->decRefCnt ();
907                 pdf_document->umap = NULL;
908         }
909
910         if (pdf_document->search)
911                 pdf_document_search_free (pdf_document->search);
912
913         if (pdf_document->target)
914                 g_object_unref (pdf_document->target);
915
916         if (pdf_document->out)
917                 delete pdf_document->out;
918         if (pdf_document->ps_out)
919                 delete pdf_document->ps_out;
920         if (pdf_document->doc)
921                 delete pdf_document->doc;
922
923 }
924
925 static void
926 pdf_document_set_property (GObject *object,
927                            guint prop_id,
928                            const GValue *value,
929                            GParamSpec *pspec)
930 {
931         switch (prop_id)
932
933         {
934                 case PROP_TITLE:
935                         /* read only */
936                         break;
937         }
938 }
939
940 static gboolean
941 has_unicode_marker (GString *string)
942 {
943         return ((string->getChar (0) & 0xff) == 0xfe &&
944                 (string->getChar (1) & 0xff) == 0xff);
945 }
946
947 static gchar *
948 pdf_info_dict_get_string (Dict *info_dict, const gchar *key) {
949         Object obj;
950         GString *value;
951         gchar *result;
952
953         g_return_val_if_fail (info_dict != NULL, NULL);
954         g_return_val_if_fail (key != NULL, NULL);
955
956         if (!info_dict->lookup ((gchar *)key, &obj)->isString ()) {
957                 obj.free ();
958                 return NULL;
959         }
960
961         value = obj.getString ();
962
963         if (has_unicode_marker (value)) {
964                 result = g_convert (value->getCString () + 2,
965                                     value->getLength () - 2,
966                                     "UTF-8", "UTF-16BE", NULL, NULL, NULL);
967         } else {
968                 result = g_strndup (value->getCString (), value->getLength ());
969         }
970
971         obj.free ();
972
973         return result;
974 }
975
976 static char *
977 pdf_document_get_title (PdfDocument *pdf_document)
978 {
979         char *title = NULL;
980         Object info;
981
982         if (pdf_document->doc == NULL)
983                 return NULL;
984         pdf_document->doc->getDocInfo (&info);
985
986         if (info.isDict ()) {
987                 title = pdf_info_dict_get_string (info.getDict(), "Title");
988         }
989
990         return title;
991 }
992
993 static char *
994 pdf_document_get_text (EvDocument *document, GdkRectangle *rect)
995 {
996         PdfDocument *pdf_document = PDF_DOCUMENT (document);
997         GString *sel_text = new GString;
998         const char *text;
999         int x1, y1, x2, y2;
1000
1001         x1 = rect->x + pdf_document->page_x_offset;
1002         y1 = rect->y + pdf_document->page_y_offset;
1003         x2 = x1 + rect->width + pdf_document->page_x_offset;
1004         y2 = y1 + rect->height + pdf_document->page_y_offset;
1005
1006         sel_text = pdf_document->out->getText (x1, y1, x2, y2);
1007         text = sel_text->getCString ();
1008
1009         return text ? g_strdup (text) : NULL;
1010 }
1011
1012 static EvLink *
1013 pdf_document_get_link (EvDocument *document, int x, int y)
1014 {
1015         PdfDocument *pdf_document = PDF_DOCUMENT (document);
1016         LinkAction *action;
1017         double link_x, link_y;
1018
1019         if (pdf_document->links == NULL) {
1020                 return NULL;
1021         }
1022
1023         /* Offset */
1024         link_x = x - pdf_document->page_x_offset;
1025         link_y = y - pdf_document->page_y_offset;
1026
1027         /* Inverse y */
1028         link_y = pdf_document->out->getBitmapHeight() - link_y;
1029
1030         /* Zoom */
1031         link_x = link_x / pdf_document->scale;
1032         link_y = link_y / pdf_document->scale;
1033
1034         action = pdf_document->links->find (link_x, link_y);
1035         
1036         if (action) {
1037                 return build_link_from_action (pdf_document, action, "");
1038         } else {
1039                 return NULL;
1040         }
1041 }
1042
1043 static void
1044 pdf_document_get_property (GObject *object,
1045                            guint prop_id,
1046                            GValue *value,
1047                            GParamSpec *pspec)
1048 {
1049         PdfDocument *pdf_document = PDF_DOCUMENT (object);
1050         char *title;
1051
1052         switch (prop_id)
1053         {
1054                 case PROP_TITLE:
1055                         title = pdf_document_get_title (pdf_document);
1056                         g_value_set_string (value, title);
1057                         g_free (title);
1058                         break;
1059         }
1060 }
1061
1062 static void
1063 pdf_document_class_init (PdfDocumentClass *klass)
1064 {
1065         GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1066
1067         gobject_class->finalize = pdf_document_finalize;
1068         gobject_class->get_property = pdf_document_get_property;
1069         gobject_class->set_property = pdf_document_set_property;
1070
1071         g_object_class_override_property (gobject_class, PROP_TITLE, "title");
1072 }
1073
1074 static void
1075 pdf_document_document_iface_init (EvDocumentIface *iface)
1076 {
1077         iface->load = pdf_document_load;
1078         iface->save = pdf_document_save;
1079         iface->get_text = pdf_document_get_text;
1080         iface->get_link = pdf_document_get_link;
1081         iface->get_n_pages = pdf_document_get_n_pages;
1082         iface->set_page = pdf_document_set_page;
1083         iface->get_page = pdf_document_get_page;
1084         iface->set_scale = pdf_document_set_scale;
1085         iface->set_target = pdf_document_set_target;
1086         iface->set_page_offset = pdf_document_set_page_offset;
1087         iface->get_page_size = pdf_document_get_page_size;
1088         iface->render = pdf_document_render;
1089 }
1090
1091 static void
1092 pdf_document_ps_exporter_iface_init (EvPSExporterIface *iface)
1093 {
1094         iface->begin = pdf_document_ps_export_begin;
1095         iface->do_page = pdf_document_ps_export_do_page;
1096         iface->end = pdf_document_ps_export_end;
1097 }
1098
1099
1100 static void
1101 pdf_document_find_iface_init (EvDocumentFindIface *iface)
1102 {
1103         iface->begin = pdf_document_find_begin;
1104         iface->get_n_results = pdf_document_find_get_n_results;
1105         iface->get_result = pdf_document_find_get_result;
1106         iface->page_has_results = pdf_document_find_page_has_results;
1107         iface->cancel = pdf_document_find_cancel;
1108 }
1109
1110 static void
1111 pdf_document_security_iface_init (EvDocumentSecurityIface *iface)
1112 {
1113         iface->has_document_security = pdf_document_has_document_security;
1114         iface->set_password = pdf_document_set_password;
1115 }
1116
1117 static void
1118 pdf_document_document_links_iface_init (EvDocumentLinksIface *iface)
1119 {
1120         iface->has_document_links = pdf_document_links_has_document_links;
1121         iface->begin_read = pdf_document_links_begin_read;
1122         iface->get_link = pdf_document_links_get_link;
1123         iface->get_child = pdf_document_links_get_child;
1124         iface->next = pdf_document_links_next;
1125         iface->free_iter = pdf_document_links_free_iter;
1126 }
1127
1128 /* Thumbnails */
1129
1130 static GdkPixbuf *
1131 bitmap_to_pixbuf (SplashBitmap *bitmap,
1132                   GdkPixbuf    *target,
1133                   gint          x_offset,
1134                   gint          y_offset)
1135 {
1136         gint width;
1137         gint height;
1138         SplashColorPtr dataPtr;
1139         int x, y;
1140
1141         gboolean target_has_alpha;
1142         gint target_rowstride;
1143         guchar *target_data;
1144
1145         width = bitmap->getWidth ();
1146         height = bitmap->getHeight ();
1147
1148         if (width + x_offset > gdk_pixbuf_get_width (target))
1149                 width = gdk_pixbuf_get_width (target) - x_offset;
1150         if (height + y_offset > gdk_pixbuf_get_height (target))
1151                 height = gdk_pixbuf_get_height (target) - x_offset;
1152
1153         target_has_alpha = gdk_pixbuf_get_has_alpha (target);
1154         target_rowstride = gdk_pixbuf_get_rowstride (target);
1155         target_data = gdk_pixbuf_get_pixels (target);
1156
1157         dataPtr = bitmap->getDataPtr ();
1158
1159         for (y = 0; y < height; y++) {
1160                 SplashRGB8 *p;
1161                 SplashRGB8 rgb;
1162                 guchar *q;
1163
1164                 p = dataPtr.rgb8 + y * width;
1165                 q = target_data + ((y + y_offset) * target_rowstride + 
1166                                    x_offset * (target_has_alpha?4:3));
1167                 for (x = 0; x < width; x++) {
1168                         rgb = *p++;
1169
1170                         *q++ = splashRGB8R (rgb);
1171                         *q++ = splashRGB8G (rgb);
1172                         *q++ = splashRGB8B (rgb);
1173
1174                         if (target_has_alpha)
1175                                 q++;
1176                 }
1177         }
1178
1179         return target;
1180 }
1181
1182
1183 static GdkPixbuf *
1184 pdf_document_thumbnails_get_page_pixbuf (PdfDocument *pdf_document,
1185                                          gdouble      scale_factor,
1186                                          gint         page_num,
1187                                          gint         width,
1188                                          gint         height)
1189 {
1190         SplashOutputDev *output;
1191         GdkPixbuf *pixbuf;
1192         SplashColor color;
1193
1194         color.rgb8 = splashMakeRGB8 (255, 255, 255);
1195
1196         output = new SplashOutputDev (splashModeRGB8, gFalse, color);
1197         output->startDoc (pdf_document->doc->getXRef());
1198         pdf_document->doc->displayPage (output,
1199                                         page_num + 1,
1200                                         72*scale_factor,
1201                                         72*scale_factor,
1202                                         0, gTrue, gFalse);
1203
1204         pixbuf = ev_document_misc_get_thumbnail_frame (output->getBitmap()->getWidth(),
1205                                                        output->getBitmap()->getHeight(),
1206                                                        NULL);
1207         bitmap_to_pixbuf (output->getBitmap(), pixbuf, 1, 1);
1208         delete output;
1209
1210         return pixbuf;
1211 }
1212
1213 static void
1214 pdf_document_thumbnails_get_dimensions (EvDocumentThumbnails *document_thumbnails,
1215                                         gint                  page,
1216                                         gint                  suggested_width,
1217                                         gint                 *width,
1218                                         gint                 *height)
1219 {
1220         PdfDocument *pdf_document = PDF_DOCUMENT (document_thumbnails);
1221         Page *the_page;
1222         Object the_thumb;
1223         Thumb *thumb = NULL;
1224         gdouble page_ratio;
1225
1226         /* getPage seems to want page + 1 for some reason; */
1227         the_page = pdf_document->doc->getCatalog ()->getPage (page + 1);
1228         the_page->getThumb (&the_thumb);
1229
1230         if (!(the_thumb.isNull () || the_thumb.isNone())) {
1231                 /* Build the thumbnail object */
1232                 thumb = new Thumb(pdf_document->doc->getXRef (),
1233                                   &the_thumb);
1234
1235                 *width = thumb->getWidth ();
1236                 *height = thumb->getHeight ();
1237         } else {
1238                 page_ratio = the_page->getHeight () / the_page->getWidth ();
1239                 *width = suggested_width;
1240                 *height = (gint) (suggested_width * page_ratio);
1241         }
1242 }
1243
1244 static GdkPixbuf *
1245 pdf_document_thumbnails_get_thumbnail (EvDocumentThumbnails *document_thumbnails,
1246                                        gint                  page,
1247                                        gint                  width)
1248 {
1249         PdfDocument *pdf_document = PDF_DOCUMENT (document_thumbnails);
1250         GdkPixbuf *thumbnail;
1251         Page *the_page;
1252         Object the_thumb;
1253         Thumb *thumb = NULL;
1254         gboolean have_ethumbs = FALSE;
1255         gdouble page_ratio;
1256         gint dest_height;
1257
1258         /* getPage seems to want page + 1 for some reason; */
1259         the_page = pdf_document->doc->getCatalog ()->getPage (page + 1);
1260         the_page->getThumb(&the_thumb);
1261
1262         page_ratio = the_page->getHeight () / the_page->getWidth ();
1263         dest_height = (gint) (width * page_ratio);
1264
1265
1266         if (!(the_thumb.isNull () || the_thumb.isNone())) {
1267                 /* Build the thumbnail object */
1268                 thumb = new Thumb(pdf_document->doc->getXRef (),
1269                                   &the_thumb);
1270
1271                 have_ethumbs = thumb->ok();
1272         }
1273
1274         if (have_ethumbs) {
1275                 guchar *data;
1276                 GdkPixbuf *tmp_pixbuf;
1277
1278                 data = thumb->getPixbufData();
1279                 tmp_pixbuf = gdk_pixbuf_new_from_data (data,
1280                                                        GDK_COLORSPACE_RGB,
1281                                                        FALSE,
1282                                                        8,
1283                                                        thumb->getWidth (),
1284                                                        thumb->getHeight (),
1285                                                        thumb->getWidth () * 3,
1286                                                        NULL, NULL);
1287                 /* FIXME: do we want to check that the thumb's size isn't ridiculous?? */
1288                 thumbnail = ev_document_misc_get_thumbnail_frame (-1, -1, tmp_pixbuf);
1289                 g_object_unref (tmp_pixbuf);
1290         } else {
1291                 gdouble scale_factor;
1292
1293                 scale_factor = (gdouble)width / the_page->getWidth ();
1294
1295                 thumbnail = pdf_document_thumbnails_get_page_pixbuf (pdf_document,
1296                                                                      scale_factor,
1297                                                                      page,
1298                                                                      width,
1299                                                                      dest_height);
1300         }
1301
1302         return thumbnail;
1303 }
1304 static void
1305 pdf_document_document_thumbnails_iface_init (EvDocumentThumbnailsIface *iface)
1306 {
1307         iface->get_thumbnail = pdf_document_thumbnails_get_thumbnail;
1308         iface->get_dimensions = pdf_document_thumbnails_get_dimensions;
1309 }
1310
1311
1312 static void
1313 pdf_document_init (PdfDocument *pdf_document)
1314 {
1315         pdf_document->page = 1;
1316         pdf_document->page_x_offset = 0;
1317         pdf_document->page_y_offset = 0;
1318         pdf_document->scale = 1.;
1319
1320         pdf_document->page_valid = FALSE;
1321         pdf_document->password = NULL;
1322 }
1323