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