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