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