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