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