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