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