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