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