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