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