]> www.fi.muni.cz Git - evince.git/blob - pdf/xpdf/pdf-document.cc
49da9e90b37308c862c040ec31ddff2bee66c3d7
[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->getKind () == actionGoToR) {
817                 g_warning ("actionGoToR links not implemented");
818         } else if (link_action->getKind () == actionLaunch) {
819                 g_warning ("actionLaunch links not implemented");
820         } else if (link_action->getKind () == actionNamed) {
821                 g_warning ("actionNamed links not implemented");
822         } else if (link_action->getKind () == actionMovie) {
823                 g_warning ("actionMovie links not implemented");
824         } else if (link_action->getKind () == actionGoTo) {
825                 LinkDest *link_dest;
826                 LinkGoTo *link_goto;
827                 Ref page_ref;
828                 gint page_num = 0;
829                 GString *named_dest;
830
831                 link_goto = dynamic_cast <LinkGoTo *> (link_action);
832                 link_dest = link_goto->getDest ();
833                 named_dest = link_goto->getNamedDest ();
834
835                 /* Wow!  This seems excessively slow on large
836                  * documents. I need to investigate more... -jrb */
837                 if (link_dest != NULL) {
838                         link_dest = link_dest->copy ();
839                 } else if (named_dest != NULL) {
840                         named_dest = named_dest->copy ();
841                         link_dest = pdf_document->doc->findDest (named_dest);
842                         delete named_dest;
843                 }
844                 if (link_dest != NULL) {
845                         if (link_dest->isPageRef ()) {
846                                 page_ref = link_dest->getPageRef ();
847                                 page_num = pdf_document->doc->findPage (page_ref.num, page_ref.gen);
848                         } else {
849                                 page_num = link_dest->getPageNum ();
850                         }
851                         delete link_dest;
852                 }
853
854                 link = ev_link_new_page (title, page_num);
855         } else if (link_action->getKind () == actionURI) {
856                 LinkURI *link_uri;
857
858                 link_uri = dynamic_cast <LinkURI *> (link_action);
859                 link = ev_link_new_external
860                         (title, link_uri->getURI()->getCString());
861         } else if (link_action->getKind () == actionUnknown) {
862                 LinkUnknown *link_unknown;
863
864                 link_unknown = dynamic_cast <LinkUnknown *> (link_action);
865
866                 g_warning ("Unknown link type %s",
867                            link_unknown->getAction()->getCString());
868         }
869
870         if (link == NULL) {
871                 link = ev_link_new_title (title);
872         }
873
874         return link;
875 }
876
877 /* FIXME This returns a new object every time, probably we should cache it
878    in the iter */
879 static EvLink *
880 pdf_document_links_get_link (EvDocumentLinks      *document_links,
881                              EvDocumentLinksIter  *links_iter)
882 {
883         PdfDocument *pdf_document = PDF_DOCUMENT (document_links);
884         LinksIter *iter = (LinksIter *)links_iter;
885         OutlineItem *anItem;
886         LinkAction *link_action;
887         Unicode *link_title;
888         const char *title;
889
890         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);
891         g_return_val_if_fail (iter != NULL, FALSE);
892
893         anItem = (OutlineItem *)iter->items->get(iter->index);
894         link_action = anItem->getAction ();
895         link_title = anItem->getTitle ();
896         title = unicode_to_char (anItem, pdf_document->umap);
897
898         return build_link_from_action (pdf_document, link_action, title);
899 }
900
901 static EvDocumentLinksIter *
902 pdf_document_links_get_child (EvDocumentLinks     *document_links,
903                               EvDocumentLinksIter *links_iter)
904 {
905         LinksIter *iter = (LinksIter *)links_iter;
906         LinksIter *child_iter;
907         OutlineItem *anItem;
908
909         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);
910
911         anItem = (OutlineItem *)iter->items->get(iter->index);
912         anItem->open ();
913         if (! (anItem->hasKids() && anItem->getKids()) )
914                 return NULL;
915
916         child_iter = g_new0 (LinksIter, 1);
917         child_iter->index = 0;
918         child_iter->level = iter->level + 1;
919         child_iter->items = anItem->getKids ();
920         g_assert (child_iter->items);
921
922         return (EvDocumentLinksIter *) child_iter;
923 }
924
925 static gboolean
926 pdf_document_links_next (EvDocumentLinks     *document_links,
927                          EvDocumentLinksIter *links_iter)
928 {
929         LinksIter *iter = (LinksIter *) links_iter;
930
931         g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);
932
933         iter->index++;
934         if (iter->index >= iter->items->getLength())
935                 return FALSE;
936
937         return TRUE;
938 }
939
940 static void
941 pdf_document_links_free_iter (EvDocumentLinks     *document_links,
942                               EvDocumentLinksIter *iter)
943 {
944         g_return_if_fail (PDF_IS_DOCUMENT (document_links));
945         g_return_if_fail (iter != NULL);
946
947         /* FIXME: Should I close all the nodes?? Free them? */
948         g_free (iter);
949 }
950
951 static void
952 pdf_document_finalize (GObject *object)
953 {
954         PdfDocument *pdf_document = PDF_DOCUMENT (object);
955
956         if (pdf_document->links) {
957                 delete pdf_document->links;
958         }
959
960         if (pdf_document->umap) {
961                 pdf_document->umap->decRefCnt ();
962                 pdf_document->umap = NULL;
963         }
964
965         if (pdf_document->search)
966                 pdf_document_search_free (pdf_document->search);
967
968         if (pdf_document->target)
969                 g_object_unref (pdf_document->target);
970
971         if (pdf_document->out)
972                 delete pdf_document->out;
973         if (pdf_document->ps_out)
974                 delete pdf_document->ps_out;
975         if (pdf_document->doc)
976                 delete pdf_document->doc;
977
978 }
979
980 static void
981 pdf_document_set_property (GObject *object,
982                            guint prop_id,
983                            const GValue *value,
984                            GParamSpec *pspec)
985 {
986         switch (prop_id)
987
988         {
989                 case PROP_TITLE:
990                         /* read only */
991                         break;
992         }
993 }
994
995 static gboolean
996 has_unicode_marker (GString *string)
997 {
998         return ((string->getChar (0) & 0xff) == 0xfe &&
999                 (string->getChar (1) & 0xff) == 0xff);
1000 }
1001
1002 static gchar *
1003 pdf_info_dict_get_string (Dict *info_dict, const gchar *key) {
1004         Object obj;
1005         GString *value;
1006         gchar *result;
1007
1008         g_return_val_if_fail (info_dict != NULL, NULL);
1009         g_return_val_if_fail (key != NULL, NULL);
1010
1011         if (!info_dict->lookup ((gchar *)key, &obj)->isString ()) {
1012                 obj.free ();
1013                 return NULL;
1014         }
1015
1016         value = obj.getString ();
1017
1018         if (has_unicode_marker (value)) {
1019                 result = g_convert (value->getCString () + 2,
1020                                     value->getLength () - 2,
1021                                     "UTF-8", "UTF-16BE", NULL, NULL, NULL);
1022         } else {
1023                 result = g_strndup (value->getCString (), value->getLength ());
1024         }
1025
1026         obj.free ();
1027
1028         return result;
1029 }
1030
1031 static char *
1032 pdf_document_get_title (PdfDocument *pdf_document)
1033 {
1034         char *title = NULL;
1035         Object info;
1036
1037         if (pdf_document->doc == NULL)
1038                 return NULL;
1039         pdf_document->doc->getDocInfo (&info);
1040
1041         if (info.isDict ()) {
1042                 title = pdf_info_dict_get_string (info.getDict(), "Title");
1043         }
1044
1045         return title;
1046 }
1047
1048 static char *
1049 pdf_document_get_text (EvDocument *document, GdkRectangle *rect)
1050 {
1051         PdfDocument *pdf_document = PDF_DOCUMENT (document);
1052         GString *sel_text = new GString;
1053         const char *text;
1054         int x1, y1, x2, y2;
1055
1056         x1 = rect->x - pdf_document->page_x_offset;
1057         y1 = rect->y - pdf_document->page_y_offset;
1058         x2 = x1 + rect->width;
1059         y2 = y1 + rect->height;
1060
1061         sel_text = pdf_document->out->getText (x1, y1, x2, y2);
1062         text = sel_text->getCString ();
1063
1064         return text ? g_strdup (text) : NULL;
1065 }
1066
1067 static EvLink *
1068 pdf_document_get_link (EvDocument *document, int x, int y)
1069 {
1070         PdfDocument *pdf_document = PDF_DOCUMENT (document);
1071         LinkAction *action;
1072         double link_x, link_y;
1073
1074         if (pdf_document->links == NULL) {
1075                 return NULL;
1076         }
1077
1078         /* Offset */
1079         link_x = x - pdf_document->page_x_offset;
1080         link_y = y - pdf_document->page_y_offset;
1081
1082         /* Inverse y */
1083         link_y = pdf_document->out->getBitmapHeight() - link_y;
1084
1085         /* Zoom */
1086         link_x = link_x / pdf_document->scale;
1087         link_y = link_y / pdf_document->scale;
1088
1089         action = pdf_document->links->find (link_x, link_y);
1090         
1091         if (action) {
1092                 return build_link_from_action (pdf_document, action, "");
1093         } else {
1094                 return NULL;
1095         }
1096 }
1097
1098 static void
1099 pdf_document_get_property (GObject *object,
1100                            guint prop_id,
1101                            GValue *value,
1102                            GParamSpec *pspec)
1103 {
1104         PdfDocument *pdf_document = PDF_DOCUMENT (object);
1105         char *title;
1106
1107         switch (prop_id)
1108         {
1109                 case PROP_TITLE:
1110                         title = pdf_document_get_title (pdf_document);
1111                         g_value_set_string (value, title);
1112                         g_free (title);
1113                         break;
1114         }
1115 }
1116
1117 static void
1118 pdf_document_class_init (PdfDocumentClass *klass)
1119 {
1120         GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1121
1122         gobject_class->finalize = pdf_document_finalize;
1123         gobject_class->get_property = pdf_document_get_property;
1124         gobject_class->set_property = pdf_document_set_property;
1125
1126         g_object_class_override_property (gobject_class, PROP_TITLE, "title");
1127 }
1128
1129 static void
1130 pdf_document_document_iface_init (EvDocumentIface *iface)
1131 {
1132         iface->load = pdf_document_load;
1133         iface->save = pdf_document_save;
1134         iface->get_text = pdf_document_get_text;
1135         iface->get_link = pdf_document_get_link;
1136         iface->get_n_pages = pdf_document_get_n_pages;
1137         iface->set_page = pdf_document_set_page;
1138         iface->get_page = pdf_document_get_page;
1139         iface->set_scale = pdf_document_set_scale;
1140         iface->set_target = pdf_document_set_target;
1141         iface->set_page_offset = pdf_document_set_page_offset;
1142         iface->get_page_size = pdf_document_get_page_size;
1143         iface->render = pdf_document_render;
1144 }
1145
1146 static void
1147 pdf_document_ps_exporter_iface_init (EvPSExporterIface *iface)
1148 {
1149         iface->begin = pdf_document_ps_export_begin;
1150         iface->do_page = pdf_document_ps_export_do_page;
1151         iface->end = pdf_document_ps_export_end;
1152 }
1153
1154
1155 static void
1156 pdf_document_find_iface_init (EvDocumentFindIface *iface)
1157 {
1158         iface->begin = pdf_document_find_begin;
1159         iface->get_n_results = pdf_document_find_get_n_results;
1160         iface->get_result = pdf_document_find_get_result;
1161         iface->page_has_results = pdf_document_find_page_has_results;
1162         iface->get_progress = pdf_document_find_get_progress;
1163         iface->cancel = pdf_document_find_cancel;
1164 }
1165
1166 static void
1167 pdf_document_security_iface_init (EvDocumentSecurityIface *iface)
1168 {
1169         iface->has_document_security = pdf_document_has_document_security;
1170         iface->set_password = pdf_document_set_password;
1171 }
1172
1173 static void
1174 pdf_document_document_links_iface_init (EvDocumentLinksIface *iface)
1175 {
1176         iface->has_document_links = pdf_document_links_has_document_links;
1177         iface->begin_read = pdf_document_links_begin_read;
1178         iface->get_link = pdf_document_links_get_link;
1179         iface->get_child = pdf_document_links_get_child;
1180         iface->next = pdf_document_links_next;
1181         iface->free_iter = pdf_document_links_free_iter;
1182 }
1183
1184 /* Thumbnails */
1185
1186 static GdkPixbuf *
1187 bitmap_to_pixbuf (SplashBitmap *bitmap,
1188                   GdkPixbuf    *target,
1189                   gint          x_offset,
1190                   gint          y_offset)
1191 {
1192         gint width;
1193         gint height;
1194         SplashColorPtr dataPtr;
1195         int x, y;
1196
1197         gboolean target_has_alpha;
1198         gint target_rowstride;
1199         guchar *target_data;
1200
1201         width = bitmap->getWidth ();
1202         height = bitmap->getHeight ();
1203
1204         if (width + x_offset > gdk_pixbuf_get_width (target))
1205                 width = gdk_pixbuf_get_width (target) - x_offset;
1206         if (height + y_offset > gdk_pixbuf_get_height (target))
1207                 height = gdk_pixbuf_get_height (target) - x_offset;
1208
1209         target_has_alpha = gdk_pixbuf_get_has_alpha (target);
1210         target_rowstride = gdk_pixbuf_get_rowstride (target);
1211         target_data = gdk_pixbuf_get_pixels (target);
1212
1213         dataPtr = bitmap->getDataPtr ();
1214
1215         for (y = 0; y < height; y++) {
1216                 SplashRGB8 *p;
1217                 SplashRGB8 rgb;
1218                 guchar *q;
1219
1220                 p = dataPtr.rgb8 + y * width;
1221                 q = target_data + ((y + y_offset) * target_rowstride + 
1222                                    x_offset * (target_has_alpha?4:3));
1223                 for (x = 0; x < width; x++) {
1224                         rgb = *p++;
1225
1226                         *q++ = splashRGB8R (rgb);
1227                         *q++ = splashRGB8G (rgb);
1228                         *q++ = splashRGB8B (rgb);
1229
1230                         if (target_has_alpha)
1231                                 q++;
1232                 }
1233         }
1234
1235         return target;
1236 }
1237
1238
1239 static GdkPixbuf *
1240 pdf_document_thumbnails_get_page_pixbuf (PdfDocument *pdf_document,
1241                                          gdouble      scale_factor,
1242                                          gint         page_num,
1243                                          gint         width,
1244                                          gint         height)
1245 {
1246         SplashOutputDev *output;
1247         GdkPixbuf *pixbuf;
1248         SplashColor color;
1249
1250         color.rgb8 = splashMakeRGB8 (255, 255, 255);
1251
1252         output = new SplashOutputDev (splashModeRGB8, gFalse, color);
1253         output->startDoc (pdf_document->doc->getXRef());
1254         pdf_document->doc->displayPage (output,
1255                                         page_num + 1,
1256                                         72*scale_factor,
1257                                         72*scale_factor,
1258                                         0, gTrue, gFalse);
1259
1260         pixbuf = ev_document_misc_get_thumbnail_frame (output->getBitmap()->getWidth(),
1261                                                        output->getBitmap()->getHeight(),
1262                                                        NULL);
1263         bitmap_to_pixbuf (output->getBitmap(), pixbuf, 1, 1);
1264         delete output;
1265
1266         return pixbuf;
1267 }
1268
1269 static void
1270 pdf_document_thumbnails_get_dimensions (EvDocumentThumbnails *document_thumbnails,
1271                                         gint                  page,
1272                                         gint                  suggested_width,
1273                                         gint                 *width,
1274                                         gint                 *height)
1275 {
1276         PdfDocument *pdf_document = PDF_DOCUMENT (document_thumbnails);
1277         Page *the_page;
1278         Object the_thumb;
1279         Thumb *thumb = NULL;
1280         gdouble page_ratio;
1281
1282         the_page = pdf_document->doc->getCatalog ()->getPage (page);
1283         the_page->getThumb (&the_thumb);
1284
1285         if (!(the_thumb.isNull () || the_thumb.isNone())) {
1286                 /* Build the thumbnail object */
1287                 thumb = new Thumb(pdf_document->doc->getXRef (),
1288                                   &the_thumb);
1289
1290                 *width = thumb->getWidth ();
1291                 *height = thumb->getHeight ();
1292         } else {
1293                 page_ratio = the_page->getHeight () / the_page->getWidth ();
1294                 *width = suggested_width;
1295                 *height = (gint) (suggested_width * page_ratio);
1296         }
1297 }
1298
1299 static GdkPixbuf *
1300 pdf_document_thumbnails_get_thumbnail (EvDocumentThumbnails *document_thumbnails,
1301                                        gint                  page,
1302                                        gint                  width)
1303 {
1304         PdfDocument *pdf_document = PDF_DOCUMENT (document_thumbnails);
1305         GdkPixbuf *thumbnail;
1306         Page *the_page;
1307         Object the_thumb;
1308         Thumb *thumb = NULL;
1309         gboolean have_ethumbs = FALSE;
1310         gdouble page_ratio;
1311         gint dest_height;
1312
1313         /* getPage seems to want page + 1 for some reason; */
1314         the_page = pdf_document->doc->getCatalog ()->getPage (page + 1);
1315         the_page->getThumb(&the_thumb);
1316
1317         page_ratio = the_page->getHeight () / the_page->getWidth ();
1318         dest_height = (gint) (width * page_ratio);
1319
1320
1321         if (!(the_thumb.isNull () || the_thumb.isNone())) {
1322                 /* Build the thumbnail object */
1323                 thumb = new Thumb(pdf_document->doc->getXRef (),
1324                                   &the_thumb);
1325
1326                 have_ethumbs = thumb->ok();
1327         }
1328
1329         if (have_ethumbs) {
1330                 guchar *data;
1331                 GdkPixbuf *tmp_pixbuf;
1332
1333                 data = thumb->getPixbufData();
1334                 tmp_pixbuf = gdk_pixbuf_new_from_data (data,
1335                                                        GDK_COLORSPACE_RGB,
1336                                                        FALSE,
1337                                                        8,
1338                                                        thumb->getWidth (),
1339                                                        thumb->getHeight (),
1340                                                        thumb->getWidth () * 3,
1341                                                        NULL, NULL);
1342                 /* FIXME: do we want to check that the thumb's size isn't ridiculous?? */
1343                 thumbnail = ev_document_misc_get_thumbnail_frame (-1, -1, tmp_pixbuf);
1344                 g_object_unref (tmp_pixbuf);
1345         } else {
1346                 gdouble scale_factor;
1347
1348                 scale_factor = (gdouble)width / the_page->getWidth ();
1349
1350                 thumbnail = pdf_document_thumbnails_get_page_pixbuf (pdf_document,
1351                                                                      scale_factor,
1352                                                                      page,
1353                                                                      width,
1354                                                                      dest_height);
1355         }
1356
1357         return thumbnail;
1358 }
1359 static void
1360 pdf_document_document_thumbnails_iface_init (EvDocumentThumbnailsIface *iface)
1361 {
1362         iface->get_thumbnail = pdf_document_thumbnails_get_thumbnail;
1363         iface->get_dimensions = pdf_document_thumbnails_get_dimensions;
1364 }
1365
1366
1367 static void
1368 pdf_document_init (PdfDocument *pdf_document)
1369 {
1370         pdf_document->page = 1;
1371         pdf_document->page_x_offset = 0;
1372         pdf_document->page_y_offset = 0;
1373         pdf_document->scale = 1.;
1374
1375         pdf_document->password = NULL;
1376 }
1377