]> www.fi.muni.cz Git - evince.git/blob - ps/ps-document.c
3ce591f9efaf10db08cc214e5f8c3456da273ea2
[evince.git] / ps / ps-document.c
1 /* Ghostscript widget for GTK/GNOME
2  * 
3  * Copyright (C) 1998 - 2005 the Free Software Foundation
4  * 
5  * Authors: Jonathan Blandford, Jaka Mocnik
6  * 
7  * Based on code by: Federico Mena (Quartic), Szekeres Istvan (Pista)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24  
25 #include "config.h"
26 #include <string.h>
27 #include <stdlib.h>
28 #include <signal.h>
29 #include <gtk/gtk.h>
30 #include <gtk/gtkobject.h>
31 #include <gdk/gdkprivate.h>
32 #include <gdk/gdkx.h>
33 #include <gdk/gdk.h>
34 #include <glib/gi18n.h>
35 #include <X11/Intrinsic.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <stdlib.h>
39 #include <errno.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/wait.h>
43 #include <stdio.h>
44 #include <math.h>
45
46 #include "ps-document.h"
47 #include "ev-debug.h"
48 #include "gsdefaults.h"
49 #include "ev-ps-exporter.h"
50 #include "ev-async-renderer.h"
51
52 #define MAX_BUFSIZE 1024
53
54 #define PS_DOCUMENT_IS_COMPRESSED(gs) (PS_DOCUMENT(gs)->gs_filename_unc != NULL)
55 #define PS_DOCUMENT_GET_PS_FILE(gs)   (PS_DOCUMENT_IS_COMPRESSED(gs) ? \
56                                        PS_DOCUMENT(gs)->gs_filename_unc : \
57                                        PS_DOCUMENT(gs)->gs_filename)
58
59 /* structure to describe section of file to send to ghostscript */
60 struct record_list
61 {
62         FILE *fp;
63         long begin;
64         guint len;
65         gboolean seek_needed;
66         gboolean close;
67         struct record_list *next;
68 };
69
70 static gboolean broken_pipe = FALSE;
71
72 /* Forward declarations */
73 static void     ps_document_init                        (PSDocument           *gs);
74 static void     ps_document_class_init                  (PSDocumentClass      *klass);
75 static void     send_ps                                 (PSDocument           *gs,
76                                                          long                  begin,
77                                                          unsigned int          len,
78                                                          gboolean              close);
79 static void     output                                  (gpointer              data,
80                                                          gint                  source,
81                                                          GdkInputCondition     condition);
82 static void     input                                   (gpointer              data,
83                                                          gint                  source,
84                                                          GdkInputCondition     condition);
85 static void     stop_interpreter                        (PSDocument           *gs);
86 static gint     start_interpreter                       (PSDocument           *gs);
87 static void     ps_document_document_iface_init         (EvDocumentIface      *iface);
88 static void     ps_document_ps_exporter_iface_init      (EvPSExporterIface    *iface);
89 static void     ps_async_renderer_iface_init            (EvAsyncRendererIface *iface);
90
91 G_DEFINE_TYPE_WITH_CODE (PSDocument, ps_document, G_TYPE_OBJECT,
92                          {
93                                  G_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT,
94                                                         ps_document_document_iface_init);
95                                  G_IMPLEMENT_INTERFACE (EV_TYPE_PS_EXPORTER,
96                                                         ps_document_ps_exporter_iface_init);
97                                  G_IMPLEMENT_INTERFACE (EV_TYPE_ASYNC_RENDERER,
98                                                         ps_async_renderer_iface_init);
99                          });
100
101 static GObjectClass *parent_class = NULL;
102 static PSDocumentClass *gs_class = NULL;
103
104 static void
105 ps_document_init (PSDocument *gs)
106 {
107         gs->bpixmap = NULL;
108
109         gs->interpreter_pid = -1;
110
111         gs->busy = FALSE;
112         gs->gs_filename = 0;
113         gs->gs_filename_unc = 0;
114
115         broken_pipe = FALSE;
116
117         gs->structured_doc = FALSE;
118         gs->reading_from_pipe = FALSE;
119         gs->send_filename_to_gs = FALSE;
120
121         gs->doc = NULL;
122
123         gs->interpreter_input = -1;
124         gs->interpreter_output = -1;
125         gs->interpreter_err = -1;
126         gs->interpreter_input_id = 0;
127         gs->interpreter_output_id = 0;
128         gs->interpreter_error_id = 0;
129
130         gs->ps_input = NULL;
131         gs->input_buffer = NULL;
132         gs->input_buffer_ptr = NULL;
133         gs->bytes_left = 0;
134         gs->buffer_bytes_left = 0;
135
136         gs->gs_status = _("No document loaded.");
137
138         gs->ps_export_pagelist = NULL;
139         gs->ps_export_filename = NULL;
140 }
141
142 static void
143 ps_document_dispose (GObject *object)
144 {
145         PSDocument *gs = PS_DOCUMENT (object);
146
147         g_return_if_fail (gs != NULL);
148
149         if (gs->gs_psfile) {
150                 fclose (gs->gs_psfile);
151                 gs->gs_psfile = NULL;
152         }
153
154         if (gs->gs_filename) {
155                 g_free (gs->gs_filename);
156                 gs->gs_filename = NULL;
157         }
158
159         if (gs->doc) {
160                 psfree (gs->doc);
161                 gs->doc = NULL;
162         }
163
164         if (gs->gs_filename_unc) {
165                 unlink(gs->gs_filename_unc);
166                 g_free(gs->gs_filename_unc);
167                 gs->gs_filename_unc = NULL;
168         }
169
170         if (gs->bpixmap) {
171                 gdk_drawable_unref (gs->bpixmap);
172         }
173
174         if(gs->input_buffer) {
175                 g_free(gs->input_buffer);
176                 gs->input_buffer = NULL;
177         }
178
179         if (gs->target_window) {
180                 gtk_widget_destroy (gs->target_window);
181                 gs->target_window = NULL;
182                 gs->pstarget = NULL;
183         }
184
185         stop_interpreter (gs);
186
187         G_OBJECT_CLASS (parent_class)->dispose (object);
188 }
189
190 static void
191 ps_document_class_init(PSDocumentClass *klass)
192 {
193         GObjectClass *object_class;
194
195         object_class = (GObjectClass *) klass;
196         parent_class = g_type_class_peek_parent (klass);
197         gs_class = klass;
198
199         object_class->dispose = ps_document_dispose;    
200
201         klass->gs_atom = gdk_atom_intern ("GHOSTVIEW", FALSE);
202         klass->next_atom = gdk_atom_intern ("NEXT", FALSE);
203         klass->page_atom = gdk_atom_intern ("PAGE", FALSE);
204         klass->string_atom = gdk_atom_intern ("STRING", FALSE);
205 }
206
207 static void
208 push_pixbuf (PSDocument *gs)
209 {
210         GdkColormap *cmap;
211         GdkPixbuf *pixbuf;
212         int width, height;
213
214         cmap = gdk_window_get_colormap (gs->pstarget);
215         gdk_drawable_get_size (gs->bpixmap, &width, &height);
216         LOG ("Get from drawable\n");
217         pixbuf =  gdk_pixbuf_get_from_drawable (NULL, gs->bpixmap, cmap,
218                                                 0, 0, 0, 0,
219                                                 width, height);
220         LOG ("Get from drawable done\n");
221         g_signal_emit_by_name (gs, "render_finished", pixbuf);
222         g_object_unref (pixbuf);
223 }
224
225 static void
226 interpreter_failed (PSDocument *gs, char *msg)
227 {
228         LOG ("Interpreter failed %s", msg);
229
230         push_pixbuf (gs);
231
232         stop_interpreter (gs);
233 }
234
235 static gboolean
236 ps_document_widget_event (GtkWidget *widget, GdkEvent *event, gpointer data)
237 {
238         PSDocument *gs = (PSDocument *) data;
239
240         if(event->type != GDK_CLIENT_EVENT)
241                 return FALSE;
242
243         gs->message_window = event->client.data.l[0];
244
245         if (event->client.message_type == gs_class->page_atom) {
246                 LOG ("GS rendered the document");
247                 gs->busy = FALSE;
248
249                 push_pixbuf (gs);
250                 LOG ("Pixbuf pushed");
251         }
252
253         return TRUE;
254 }
255
256 static void
257 send_ps (PSDocument *gs, long begin, unsigned int len, gboolean close)
258 {
259         struct record_list *ps_new;
260
261         if (gs->interpreter_input < 0) {
262                 g_critical("No pipe to gs: error in send_ps().");
263                 return;
264         }
265
266         ps_new = g_new0 (struct record_list, 1);
267         ps_new->fp = gs->gs_psfile;
268         ps_new->begin = begin;
269         ps_new->len = len;
270         ps_new->seek_needed = TRUE;
271         ps_new->close = close;
272         ps_new->next = NULL;
273
274         if (gs->input_buffer == NULL) {
275                 gs->input_buffer = g_malloc(MAX_BUFSIZE);
276         }
277
278         if (gs->ps_input == NULL) {
279                 gs->input_buffer_ptr = gs->input_buffer;
280                 gs->bytes_left = len;
281                 gs->buffer_bytes_left = 0;
282                 gs->ps_input = ps_new;
283                 gs->interpreter_input_id = gdk_input_add
284                         (gs->interpreter_input, GDK_INPUT_WRITE, input, gs);
285         } else {
286                 struct record_list *p = gs->ps_input;
287                 while (p->next != NULL) {
288                         p = p->next;
289                 }
290                 p->next = ps_new;
291         }
292 }
293
294 static float
295 get_xdpi (PSDocument *gs)
296 {
297         return 25.4 * gdk_screen_width() / gdk_screen_width_mm();
298 }
299
300 static float
301 get_ydpi (PSDocument *gs)
302 {
303         return 25.4 * gdk_screen_height() / gdk_screen_height_mm();
304 }
305
306 static void
307 setup_pixmap (PSDocument *gs, int page, double scale, int rotation)
308 {
309         GdkGC *fill;
310         GdkColor white = { 0, 0xFFFF, 0xFFFF, 0xFFFF };   /* pixel, r, g, b */
311         GdkColormap *colormap;
312         double width, height;
313         int pixmap_width, pixmap_height;
314
315         ev_document_get_page_size (EV_DOCUMENT (gs), page, &width, &height);
316
317         if (rotation == 90 || rotation == 270) {
318                 pixmap_height = width * scale + 0.5;
319                 pixmap_width = height * scale + 0.5;
320         } else {
321                 pixmap_width = width * scale + 0.5;
322                 pixmap_height = height * scale + 0.5;
323         }
324
325         if(gs->bpixmap) {
326                 int w, h;
327
328                 gdk_drawable_get_size (gs->bpixmap, &w, &h);
329
330                 if (pixmap_width != w || h != pixmap_height) {
331                         gdk_drawable_unref (gs->bpixmap);
332                         gs->bpixmap = NULL;
333                         stop_interpreter (gs);
334                 }
335         }
336
337         if (!gs->bpixmap) {
338                 LOG ("Create pixmap");
339
340                 fill = gdk_gc_new (gs->pstarget);
341                 colormap = gdk_drawable_get_colormap (gs->pstarget);
342                 gdk_color_alloc (colormap, &white);
343                 gdk_gc_set_foreground (fill, &white);
344                 gs->bpixmap = gdk_pixmap_new (gs->pstarget, pixmap_width,
345                                               pixmap_height, -1);
346                 gdk_draw_rectangle (gs->bpixmap, fill, TRUE,
347                                     0, 0, pixmap_width, pixmap_height);
348         }
349 }
350
351 #define DEFAULT_PAGE_SIZE 1
352
353 static void
354 get_page_box (PSDocument *gs, int page, int *urx, int *ury, int *llx, int *lly)
355 {
356         gint new_llx = 0;
357         gint new_lly = 0;
358         gint new_urx = 0;
359         gint new_ury = 0;
360         GtkGSPaperSize *papersizes = gtk_gs_defaults_get_paper_sizes ();
361         int new_pagesize = -1;
362
363         g_return_if_fail (PS_IS_DOCUMENT (gs));
364
365         if (new_pagesize == -1) {
366                 new_pagesize = DEFAULT_PAGE_SIZE;
367                 if (gs->doc) {
368                 /* If we have a document:
369                  * We use -- the page size (if specified)
370                  * or the doc. size (if specified)
371                  * or the page bbox (if specified)
372                  * or the bounding box
373                  */
374                         if ((page >= 0) && (gs->doc->numpages > page) &&
375                             (gs->doc->pages) && (gs->doc->pages[page].size)) {
376                                 new_pagesize = gs->doc->pages[page].size - gs->doc->size;
377                         } else if (gs->doc->default_page_size != NULL) {
378                                 new_pagesize = gs->doc->default_page_size - gs->doc->size;
379                         } else if ((page >= 0) &&
380                                    (gs->doc->numpages > page) &&
381                                    (gs->doc->pages) &&
382                                    (gs->doc->pages[page].boundingbox[URX] >
383                                     gs->doc->pages[page].boundingbox[LLX]) &&
384                                    (gs->doc->pages[page].boundingbox[URY] >
385                                     gs->doc->pages[page].boundingbox[LLY])) {
386                                 new_pagesize = -1;
387                         } else if ((gs->doc->boundingbox[URX] > gs->doc->boundingbox[LLX]) &&
388                                    (gs->doc->boundingbox[URY] > gs->doc->boundingbox[LLY])) {
389                                 new_pagesize = -1;
390                         }
391                 }
392         }
393
394         /* Compute bounding box */
395         if (gs->doc && (gs->doc->epsf || new_pagesize == -1)) {    /* epsf or bbox */
396                 if ((page >= 0) &&
397                     (gs->doc->pages) &&
398                     (gs->doc->pages[page].boundingbox[URX] >
399                      gs->doc->pages[page].boundingbox[LLX]) &&
400                     (gs->doc->pages[page].boundingbox[URY] >
401                      gs->doc->pages[page].boundingbox[LLY])) {
402                         /* use page bbox */
403                         new_llx = gs->doc->pages[page].boundingbox[LLX];
404                         new_lly = gs->doc->pages[page].boundingbox[LLY];
405                         new_urx = gs->doc->pages[page].boundingbox[URX];
406                         new_ury = gs->doc->pages[page].boundingbox[URY];
407                 } else if ((gs->doc->boundingbox[URX] > gs->doc->boundingbox[LLX]) &&
408                            (gs->doc->boundingbox[URY] > gs->doc->boundingbox[LLY])) {
409                         /* use doc bbox */
410                         new_llx = gs->doc->boundingbox[LLX];
411                         new_lly = gs->doc->boundingbox[LLY];
412                         new_urx = gs->doc->boundingbox[URX];
413                         new_ury = gs->doc->boundingbox[URY];
414                 }
415         } else {
416                 if (new_pagesize < 0)
417                         new_pagesize = DEFAULT_PAGE_SIZE;
418                 new_llx = new_lly = 0;
419                 if (gs->doc && gs->doc->size &&
420                     (new_pagesize < gs->doc->numsizes)) {
421                         new_urx = gs->doc->size[new_pagesize].width;
422                         new_ury = gs->doc->size[new_pagesize].height;
423                 } else {
424                         new_urx = papersizes[new_pagesize].width;
425                         new_ury = papersizes[new_pagesize].height;
426                 }
427         }
428
429         if (new_urx <= new_llx)
430                 new_urx = papersizes[12].width;
431         if (new_ury <= new_lly)
432                 new_ury = papersizes[12].height;
433
434         *urx = new_urx;
435         *ury = new_ury;
436         *llx = new_llx;
437         *lly = new_lly;
438 }
439
440 static void
441 setup_page (PSDocument *gs, int page, double scale, int rotation)
442 {
443         gchar *buf;
444         char scaled_xdpi[G_ASCII_DTOSTR_BUF_SIZE];      
445         char scaled_ydpi[G_ASCII_DTOSTR_BUF_SIZE];
446         int urx, ury, llx, lly;
447
448         LOG ("Setup the page");
449
450         get_page_box (gs, page, &urx, &ury, &llx, &lly);
451         g_ascii_dtostr (scaled_xdpi, G_ASCII_DTOSTR_BUF_SIZE, get_xdpi (gs) * scale);
452         g_ascii_dtostr (scaled_ydpi, G_ASCII_DTOSTR_BUF_SIZE, get_ydpi (gs) * scale);
453
454         buf = g_strdup_printf ("%ld %d %d %d %d %d %s %s %d %d %d %d",
455                                0L, rotation, llx, lly, urx, ury,
456                                scaled_xdpi, scaled_ydpi,
457                                0, 0, 0, 0);
458         LOG ("GS property %s", buf);
459
460         gdk_property_change (gs->pstarget, gs_class->gs_atom, gs_class->string_atom,
461                              8, GDK_PROP_MODE_REPLACE, (guchar *)buf, strlen(buf));
462         g_free (buf);
463         
464         gdk_flush ();
465 }
466
467 static void
468 close_pipe (int p[2])
469 {
470         if (p[0] != -1) {
471                 close (p[0]);
472         }
473         if (p[1] != -1) {
474                 close (p[1]);
475         }
476 }
477
478 static gboolean
479 is_interpreter_ready (PSDocument *gs)
480 {
481         return (gs->interpreter_pid != -1 && !gs->busy && gs->ps_input == NULL);
482 }
483
484 static void
485 output (gpointer data, gint source, GdkInputCondition condition)
486 {
487         char buf[MAX_BUFSIZE + 1];
488         guint bytes = 0;
489         PSDocument *gs = PS_DOCUMENT(data);
490
491         if (source == gs->interpreter_output) {
492                 bytes = read(gs->interpreter_output, buf, MAX_BUFSIZE);
493                 if (bytes == 0) {            /* EOF occurred */
494                         close (gs->interpreter_output);
495                         gs->interpreter_output = -1;
496                         gdk_input_remove (gs->interpreter_output_id);
497                         return;
498                 } else if (bytes == -1) {
499                         /* trouble... */
500                         interpreter_failed (gs, NULL);
501                         return;
502                 }
503                 if (gs->interpreter_err == -1) {
504                         interpreter_failed (gs, NULL);
505                 }
506         } else if (source == gs->interpreter_err) {
507                 bytes = read (gs->interpreter_err, buf, MAX_BUFSIZE);
508                 if (bytes == 0) {            /* EOF occurred */
509                         close (gs->interpreter_err);
510                         gs->interpreter_err = -1;
511                         gdk_input_remove (gs->interpreter_error_id);
512                         return;
513                 } else if (bytes == -1) {
514                         /* trouble... */
515                         interpreter_failed (gs, NULL);
516                         return;
517                 }
518                 if (gs->interpreter_output == -1) {
519                         interpreter_failed(gs, NULL);
520                 }
521         }
522
523         if (bytes > 0) {
524                 buf[bytes] = '\0';
525                 printf ("%s", buf);
526         }
527 }
528
529 static void
530 catchPipe (int i)
531 {
532         broken_pipe = True;
533 }
534
535 static void
536 input(gpointer data, gint source, GdkInputCondition condition)
537 {
538         PSDocument *gs = PS_DOCUMENT(data);
539         int bytes_written;
540         void (*oldsig) (int);
541         oldsig = signal(SIGPIPE, catchPipe);
542
543         LOG ("Input");
544
545         do {
546                 if (gs->buffer_bytes_left == 0) {
547                         /* Get a new section if required */
548                         if (gs->ps_input && gs->bytes_left == 0) {
549                                 struct record_list *ps_old = gs->ps_input;
550                                 gs->ps_input = ps_old->next;
551                                 if (ps_old->close && NULL != ps_old->fp)
552                                         fclose (ps_old->fp);
553                                 g_free (ps_old);
554                         }
555
556                         /* Have to seek at the beginning of each section */
557                         if (gs->ps_input && gs->ps_input->seek_needed) {
558                                 fseek (gs->ps_input->fp, gs->ps_input->begin, SEEK_SET);
559                                 gs->ps_input->seek_needed = FALSE;
560                                 gs->bytes_left = gs->ps_input->len;
561                         }
562
563                         if (gs->bytes_left > MAX_BUFSIZE) {
564                                 gs->buffer_bytes_left = fread (gs->input_buffer, sizeof(char),
565                                                                MAX_BUFSIZE, gs->ps_input->fp);
566                         } else if (gs->bytes_left > 0) {
567                                 gs->buffer_bytes_left = fread (gs->input_buffer, sizeof(char),
568                                                                gs->bytes_left, gs->ps_input->fp);
569                         } else {
570                                 gs->buffer_bytes_left = 0;
571                         }
572                         if (gs->bytes_left > 0 && gs->buffer_bytes_left == 0) {
573                                 interpreter_failed (gs, NULL); /* Error occurred */
574                         }
575                         gs->input_buffer_ptr = gs->input_buffer;
576                         gs->bytes_left -= gs->buffer_bytes_left;
577                 }
578
579                 if (gs->buffer_bytes_left > 0) {
580                         bytes_written = write (gs->interpreter_input,
581                                                gs->input_buffer_ptr, gs->buffer_bytes_left);
582
583                         if (broken_pipe) {
584                                 interpreter_failed (gs, g_strdup(_("Broken pipe.")));
585                                 broken_pipe = FALSE;
586                                 interpreter_failed (gs, NULL);
587                         } else if (bytes_written == -1) {
588                                 if ((errno != EWOULDBLOCK) && (errno != EAGAIN)) {
589                                         interpreter_failed (gs, NULL);   /* Something bad happened */
590                                 }
591                                 } else {
592                                 gs->buffer_bytes_left -= bytes_written;
593                                 gs->input_buffer_ptr += bytes_written;
594                         }
595                 }
596         } while (gs->ps_input && gs->buffer_bytes_left == 0);
597
598         signal (SIGPIPE, oldsig);
599
600         if (gs->ps_input == NULL && gs->buffer_bytes_left == 0) {
601                 if (gs->interpreter_input_id != 0) {
602                         gdk_input_remove (gs->interpreter_input_id);
603                         gs->interpreter_input_id = 0;
604                 }
605         }
606 }
607
608 static int
609 start_interpreter (PSDocument *gs)
610 {
611         int std_in[2] = { -1, -1 };   /* pipe to interp stdin */
612         int std_out[2];               /* pipe from interp stdout */
613         int std_err[2];               /* pipe from interp stderr */
614
615 #define NUM_ARGS    100
616 #define NUM_GS_ARGS (NUM_ARGS - 20)
617 #define NUM_ALPHA_ARGS 10
618
619         char *argv[NUM_ARGS], *dir, *gv_env;
620         char **gs_args, **alpha_args = NULL;
621         int argc = 0, i;
622
623         LOG ("Start the interpreter");
624
625         if(!gs->gs_filename)
626                 return 0;
627
628         stop_interpreter(gs);
629
630         /* set up the args... */
631         gs_args = g_strsplit (gtk_gs_defaults_get_interpreter_cmd (), " ", NUM_GS_ARGS);
632         for(i = 0; i < NUM_GS_ARGS && gs_args[i]; i++, argc++) {
633                 argv[argc] = gs_args[i];
634         }
635
636         alpha_args = g_strsplit (ALPHA_PARAMS, " ", NUM_ALPHA_ARGS);
637         for(i = 0; i < NUM_ALPHA_ARGS && alpha_args[i]; i++, argc++) {
638                 argv[argc] = alpha_args[i];
639         }
640
641         argv[argc++] = "-dNOPAUSE";
642         argv[argc++] = "-dQUIET";
643         argv[argc++] = "-dSAFER";
644
645         /* set up the pipes */
646         if (gs->send_filename_to_gs) {
647                 argv[argc++] = PS_DOCUMENT_GET_PS_FILE (gs);
648                 argv[argc++] = "-c";
649                 argv[argc++] = "quit";
650         } else {
651                 argv[argc++] = "-";
652         }
653
654         argv[argc++] = NULL;
655
656         if (!gs->reading_from_pipe && !gs->send_filename_to_gs) {
657                 if (pipe (std_in) == -1) {
658                         g_critical ("Unable to open pipe to Ghostscript.");
659                         return -1;
660                 }
661         }
662
663         if (pipe (std_out) == -1) {
664                 close_pipe (std_in);
665                 return -1;
666         }
667
668         if (pipe(std_err) == -1) {
669                 close_pipe (std_in);
670                 close_pipe (std_out);
671                 return -1;
672         }
673
674         gv_env = g_strdup_printf ("GHOSTVIEW=%ld %ld",
675                                   gdk_x11_drawable_get_xid (gs->pstarget),
676                                   gdk_x11_drawable_get_xid (gs->bpixmap));
677         LOG ("Launching ghostview with env %s", gv_env);
678
679         gs->interpreter_pid = fork ();
680         switch (gs->interpreter_pid) {
681                 case -1:                     /* error */
682                         close_pipe (std_in);
683                         close_pipe (std_out);
684                         close_pipe (std_err);
685                         return -2;
686                         break;
687                 case 0:                      /* child */
688                         close (std_out[0]);
689                         dup2 (std_out[1], 1);
690                         close (std_out[1]);
691
692                         close (std_err[0]);
693                         dup2 (std_err[1], 2);
694                         close (std_err[1]);
695
696                         if (!gs->reading_from_pipe) {
697                                 if (gs->send_filename_to_gs) {
698                                         int stdinfd;
699                                         /* just in case gs tries to read from stdin */
700                                         stdinfd = open("/dev/null", O_RDONLY);
701                                         if (stdinfd != 0) {
702                                                 dup2(stdinfd, 0);
703                                                 close(stdinfd);
704                                         }
705                                 } else {
706                                         close (std_in[1]);
707                                         dup2 (std_in[0], 0);
708                                         close (std_in[0]);
709                                 }
710                         }
711
712                         putenv(gv_env);
713
714                         /* change to directory where the input file is. This helps
715                          * with postscript-files which include other files using
716                          * a relative path */
717                         dir = g_path_get_dirname (gs->gs_filename);
718                         chdir (dir);
719                         g_free (dir);
720
721                         execvp (argv[0], argv);
722
723                         /* Notify error */
724                         g_critical ("Unable to execute [%s]\n", argv[0]);
725                         g_strfreev (gs_args);
726                         g_free (gv_env);
727                         g_strfreev (alpha_args);
728                         _exit (1);
729                         break;
730                 default:                     /* parent */
731                         if (!gs->send_filename_to_gs && !gs->reading_from_pipe) {
732                                 int result;
733                                 close (std_in[0]);
734                                 /* use non-blocking IO for pipe to ghostscript */
735                                 result = fcntl (std_in[1], F_GETFL, 0);
736                                 fcntl (std_in[1], F_SETFL, result | O_NONBLOCK);
737                                 gs->interpreter_input = std_in[1];
738                         } else {
739                                 gs->interpreter_input = -1;
740                         }
741                         close (std_out[1]);
742
743                         gs->interpreter_output = std_out[0];
744                         close (std_err[1]);
745                         gs->interpreter_err = std_err[0];
746                         gs->interpreter_output_id =
747                                 gdk_input_add (std_out[0], GDK_INPUT_READ, output, gs);
748                         gs->interpreter_error_id =
749                                 gdk_input_add (std_err[0], GDK_INPUT_READ, output, gs);
750                         break;
751         }
752
753         return TRUE;
754 }
755
756 static void
757 stop_interpreter(PSDocument * gs)
758 {
759         if (gs->interpreter_pid > 0) {
760                 int status = 0;
761                 LOG ("Stop the interpreter");
762                 kill (gs->interpreter_pid, SIGTERM);
763                 while ((wait(&status) == -1) && (errno == EINTR));
764                 gs->interpreter_pid = -1;
765                 if (status == 1) {
766                         gs->gs_status = _("Interpreter failed.");
767                 }
768         }
769
770         if (gs->interpreter_input >= 0) {
771                 close (gs->interpreter_input);
772                 gs->interpreter_input = -1;
773                 if (gs->interpreter_input_id != 0) {
774                         gdk_input_remove(gs->interpreter_input_id);
775                         gs->interpreter_input_id = 0;
776                 }
777                 while (gs->ps_input) {
778                         struct record_list *ps_old = gs->ps_input;
779                         gs->ps_input = gs->ps_input->next;
780                         if (ps_old->close && NULL != ps_old->fp)
781                                 fclose (ps_old->fp);
782                         g_free (ps_old);
783                 }
784         }
785
786         if (gs->interpreter_output >= 0) {
787                 close (gs->interpreter_output);
788                 gs->interpreter_output = -1;
789                 if (gs->interpreter_output_id) {
790                         gdk_input_remove (gs->interpreter_output_id);
791                         gs->interpreter_output_id = 0;
792                 }
793         }
794
795         if (gs->interpreter_err >= 0) {
796                 close (gs->interpreter_err);
797                 gs->interpreter_err = -1;
798                 if (gs->interpreter_error_id) {
799                         gdk_input_remove (gs->interpreter_error_id);
800                         gs->interpreter_error_id = 0;
801                 }
802         }
803
804         gs->busy = FALSE;
805 }
806
807 /* If file exists and is a regular file then return its length, else -1 */
808 static gint
809 file_length (const gchar * filename)
810 {
811         struct stat stat_rec;
812
813         if (filename && (stat (filename, &stat_rec) == 0) && S_ISREG (stat_rec.st_mode))
814                 return stat_rec.st_size;
815         else
816                 return -1;
817 }
818
819 /* Test if file exists, is a regular file and its length is > 0 */
820 static gboolean
821 file_readable(const char *filename)
822 {
823         return (file_length (filename) > 0);
824 }
825
826 /*
827  * Decompress gs->gs_filename if necessary
828  * Set gs->filename_unc to the name of the uncompressed file or NULL.
829  * Error reporting via signal 'interpreter_message'
830  * Return name of input file to use or NULL on error..
831  */
832 static gchar *
833 check_filecompressed (PSDocument * gs)
834 {
835         FILE *file;
836         gchar buf[1024];
837         gchar *filename, *filename_unc, *filename_err, *cmdline;
838         const gchar *cmd;
839         int fd;
840
841         cmd = NULL;
842
843         if ((file = fopen(gs->gs_filename, "r")) &&
844             (fread (buf, sizeof(gchar), 3, file) == 3)) {
845                 if ((buf[0] == '\037') && ((buf[1] == '\235') || (buf[1] == '\213'))) {
846                         /* file is gzipped or compressed */
847                         cmd = gtk_gs_defaults_get_ungzip_cmd ();
848                 } else if (strncmp (buf, "BZh", 3) == 0) {
849                         /* file is compressed with bzip2 */
850                         cmd = gtk_gs_defaults_get_unbzip2_cmd ();
851                 }
852         }
853
854         if (NULL != file)
855                 fclose(file);
856
857         if (!cmd)
858                 return gs->gs_filename;
859
860         /* do the decompression */
861         filename = g_shell_quote (gs->gs_filename);
862         filename_unc = g_strconcat (g_get_tmp_dir (), "/evinceXXXXXX", NULL);
863         if ((fd = mkstemp (filename_unc)) < 0) {
864                 g_free (filename_unc);
865                 g_free (filename);
866                 return NULL;
867         }
868         close (fd);
869
870         filename_err = g_strconcat (g_get_tmp_dir (), "/evinceXXXXXX", NULL);
871         if ((fd = mkstemp(filename_err)) < 0) {
872                 g_free (filename_err);
873                 g_free (filename_unc);
874                 g_free (filename);
875                 return NULL;
876         }
877         close (fd);
878
879         cmdline = g_strdup_printf ("%s %s >%s 2>%s", cmd,
880                                    filename, filename_unc, filename_err);
881         if (system (cmdline) == 0 &&
882             file_readable (filename_unc) &&
883             file_length (filename_err) == 0) {
884                 /* sucessfully uncompressed file */
885                 gs->gs_filename_unc = filename_unc;
886         } else {
887                 gchar *filename_dsp;
888                 gchar *msg;
889
890                 /* report error */
891                 filename_dsp = g_filename_display_name (gs->gs_filename);
892                 msg = g_strdup_printf (_("Error while decompressing file %s:\n"), filename_dsp);
893                 g_free (filename_dsp);
894                 
895                 interpreter_failed (gs, msg);
896                 g_free (msg);
897                 unlink (filename_unc);
898                 g_free (filename_unc);
899                 filename_unc = NULL;
900         }
901
902         unlink (filename_err);
903         g_free (filename_err);
904         g_free (cmdline);
905         g_free (filename);
906
907         return filename_unc;
908 }
909
910 static gint
911 ps_document_enable_interpreter(PSDocument *gs)
912 {
913         g_return_val_if_fail (PS_IS_DOCUMENT (gs), FALSE);
914
915         if (!gs->gs_filename)
916                 return 0;
917
918         return start_interpreter (gs);
919 }
920
921 static gboolean
922 document_load (PSDocument *gs, const gchar *fname)
923 {
924         g_return_val_if_fail (PS_IS_DOCUMENT(gs), FALSE);
925
926         LOG ("Load the document");
927
928         if (fname == NULL) {
929                 gs->gs_status = "";
930                 return FALSE;
931         }
932
933         /* prepare this document */
934         gs->structured_doc = FALSE;
935         gs->send_filename_to_gs = TRUE;
936         gs->gs_filename = g_strdup (fname);
937
938         if ((gs->reading_from_pipe = (strcmp (fname, "-") == 0))) {
939                 gs->send_filename_to_gs = FALSE;
940         } else {
941                 /*
942                  * We need to make sure that the file is loadable/exists!
943                  * otherwise we want to exit without loading new stuff...
944                  */
945                 gchar *filename = NULL;
946
947                 if (!file_readable(fname)) {
948                         gchar *filename_dsp;
949                         gchar *msg;
950
951                         filename_dsp = g_filename_display_name (fname);
952                         msg = g_strdup_printf (_("Cannot open file %s.\n"), filename_dsp);
953                         g_free (filename_dsp);
954                         
955                         interpreter_failed (gs, msg);
956                         g_free (msg);
957                         gs->gs_status = _("File is not readable.");
958                 } else {
959                         filename = check_filecompressed(gs);
960                 }
961
962                 if (!filename || (gs->gs_psfile = fopen(filename, "r")) == NULL) {
963                         interpreter_failed (gs, NULL);
964                         return FALSE;
965                 }
966
967                 /* we grab the vital statistics!!! */
968                 gs->doc = psscan(gs->gs_psfile, TRUE, filename);
969
970                 if ((!gs->doc->epsf && gs->doc->numpages > 0) ||
971                     (gs->doc->epsf && gs->doc->numpages > 1)) {
972                         gs->structured_doc = TRUE;
973                         gs->send_filename_to_gs = FALSE;
974                 }
975         }
976
977         gs->gs_status = _("Document loaded.");
978
979         return TRUE;
980 }
981
982 static gboolean
983 ps_document_next_page (PSDocument *gs)
984 {
985         XEvent event;
986
987         LOG ("Make ghostscript render next page");
988
989         g_return_val_if_fail (PS_IS_DOCUMENT(gs), FALSE);
990         g_return_val_if_fail (gs->interpreter_pid != 0, FALSE);
991         g_return_val_if_fail (gs->busy != TRUE, FALSE);
992
993         gs->busy = TRUE;
994
995         event.xclient.type = ClientMessage;
996         event.xclient.display = gdk_display;
997         event.xclient.window = gs->message_window;
998         event.xclient.message_type = gdk_x11_atom_to_xatom(gs_class->next_atom);
999         event.xclient.format = 32;
1000
1001         gdk_error_trap_push ();
1002         XSendEvent (gdk_display, gs->message_window, FALSE, 0, &event);
1003         gdk_flush ();
1004         gdk_error_trap_pop ();
1005
1006         return TRUE;
1007 }
1008
1009 static gboolean
1010 render_page (PSDocument *gs, int page)
1011 {
1012         g_return_val_if_fail(gs != NULL, FALSE);
1013         g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
1014
1015         if(!gs->gs_filename) {
1016                 return FALSE;
1017         }
1018
1019         if (gs->structured_doc && gs->doc) {
1020                 LOG ("It's a structured document, let's send one page to gs");
1021
1022                 if (is_interpreter_ready (gs)) {
1023                         ps_document_next_page (gs);
1024                 } else {
1025                         ps_document_enable_interpreter (gs);
1026                         send_ps (gs, gs->doc->beginprolog, gs->doc->lenprolog, FALSE);
1027                         send_ps (gs, gs->doc->beginsetup, gs->doc->lensetup, FALSE);
1028                 }
1029
1030                 send_ps (gs, gs->doc->pages[page].begin,
1031                          gs->doc->pages[page].len, FALSE);
1032         } else {
1033                 /* Unstructured document
1034                  *
1035                  * In the case of non structured documents,
1036                  * GS read the PS from the  actual file (via command
1037                  * line. Hence, ggv only send a signal next page.
1038                  * If ghostview is not running it is usually because
1039                  * the last page of the file was displayed. In that
1040                  * case, ggv restarts GS again and the first page is displayed.
1041                  */
1042
1043                 LOG ("It's an unstructured document, gs will just read the file");
1044
1045                 if (!is_interpreter_ready (gs)) {
1046                         ps_document_enable_interpreter(gs);
1047                 }
1048                 ps_document_next_page(gs);
1049         }
1050
1051         return TRUE;
1052 }
1053
1054 static gboolean
1055 ps_document_load (EvDocument  *document,
1056                   const char  *uri,
1057                   GError     **error)
1058 {
1059         gboolean result;
1060         char *filename;
1061
1062         filename = g_filename_from_uri (uri, NULL, error);
1063         if (!filename)
1064                 return FALSE;
1065
1066         result = document_load (PS_DOCUMENT (document), filename);
1067         if (!result) {
1068                 gchar *filename_dsp;
1069
1070                 filename_dsp = g_filename_display_name (filename);
1071
1072                 g_set_error (error, G_FILE_ERROR,
1073                              G_FILE_ERROR_FAILED,
1074                              _("Failed to load document '%s'"),
1075                              filename_dsp);
1076
1077                 g_free (filename_dsp);
1078         }
1079
1080         g_free (filename);
1081
1082         return result;
1083 }
1084
1085 static gboolean
1086 save_document (PSDocument *document, const char *filename)
1087 {
1088         gboolean result = TRUE;
1089         GtkGSDocSink *sink = gtk_gs_doc_sink_new ();
1090         FILE *f, *src_file;
1091         gchar *buf;
1092
1093         src_file = fopen (PS_DOCUMENT_GET_PS_FILE(document), "r");
1094         if (src_file) {
1095                 struct stat stat_rec;
1096
1097                 if (stat (PS_DOCUMENT_GET_PS_FILE(document), &stat_rec) == 0) {
1098                         pscopy (src_file, sink, 0, stat_rec.st_size - 1);
1099                 }
1100
1101                 fclose (src_file);
1102         }
1103         
1104         buf = gtk_gs_doc_sink_get_buffer (sink);
1105         if (buf == NULL) {
1106                 return FALSE;
1107         }
1108         
1109         f = fopen (filename, "w");
1110         if (f) {
1111                 fputs (buf, f);
1112                 fclose (f);
1113         } else {
1114                 result = FALSE;
1115         }
1116
1117         g_free (buf);
1118         gtk_gs_doc_sink_free (sink);
1119         g_free (sink);
1120
1121         return result;
1122 }
1123
1124 static gboolean
1125 save_page_list (PSDocument *document, int *page_list, const char *filename)
1126 {
1127         gboolean result = TRUE;
1128         GtkGSDocSink *sink = gtk_gs_doc_sink_new ();
1129         FILE *f;
1130         gchar *buf;
1131
1132         pscopydoc (sink, PS_DOCUMENT_GET_PS_FILE(document), 
1133                    document->doc, page_list);
1134         
1135         buf = gtk_gs_doc_sink_get_buffer (sink);
1136         
1137         f = fopen (filename, "w");
1138         if (f) {
1139                 fputs (buf, f);
1140                 fclose (f);
1141         } else {
1142                 result = FALSE;
1143         }
1144
1145         g_free (buf);
1146         gtk_gs_doc_sink_free (sink);
1147         g_free (sink);
1148
1149         return result;
1150 }
1151
1152 static gboolean
1153 ps_document_save (EvDocument  *document,
1154                   const char  *uri,
1155                   GError     **error)
1156 {
1157         PSDocument *ps = PS_DOCUMENT (document);
1158         gboolean result;
1159         char *filename;
1160
1161         filename = g_filename_from_uri (uri, NULL, error);
1162         if (!filename)
1163                 return FALSE;
1164
1165         result = save_document (ps, filename);
1166
1167         g_free (filename);
1168
1169         return result;
1170 }
1171
1172 static int
1173 ps_document_get_n_pages (EvDocument  *document)
1174 {
1175         PSDocument *ps = PS_DOCUMENT (document);
1176
1177         g_return_val_if_fail (ps != NULL, -1);
1178
1179         if (!ps->gs_filename || !ps->doc) {
1180                 return -1;
1181         }
1182
1183         return ps->structured_doc ? ps->doc->numpages : 1;
1184 }
1185
1186 static void
1187 ps_document_get_page_size (EvDocument   *document,
1188                            int           page,
1189                            double       *width,
1190                            double       *height)
1191 {
1192         PSDocument *gs = PS_DOCUMENT (document);
1193         int urx, ury, llx, lly;
1194
1195         get_page_box (PS_DOCUMENT (document), page, &urx, &ury, &llx, &lly);
1196
1197         if (width) {
1198                 *width = (urx - llx) / 72.0 * get_xdpi (gs) + 0.5;
1199         }
1200
1201         if (height) {
1202                 *height = (ury - lly) / 72.0 * get_ydpi (gs) + 0.5;
1203         }
1204 }
1205
1206 static gboolean
1207 ps_document_can_get_text (EvDocument *document)
1208 {
1209         return FALSE;
1210 }
1211
1212 static void
1213 ps_async_renderer_render_pixbuf (EvAsyncRenderer *renderer, int page, double scale, int rotation)
1214 {
1215         PSDocument *gs = PS_DOCUMENT (renderer);
1216
1217         if (gs->pstarget == NULL) {
1218                 gs->target_window = gtk_window_new (GTK_WINDOW_POPUP);
1219                 gtk_widget_realize (gs->target_window);
1220                 gs->pstarget = gs->target_window->window;
1221
1222                 g_assert (gs->pstarget != NULL);
1223
1224                 g_signal_connect (gs->target_window, "event",
1225                                   G_CALLBACK (ps_document_widget_event),
1226                                   gs);
1227         }
1228
1229         setup_pixmap (gs, page, scale, rotation);
1230         setup_page (gs, page, scale, rotation);
1231
1232         render_page (gs, page);
1233 }
1234
1235 static EvDocumentInfo *
1236 ps_document_get_info (EvDocument *document)
1237 {
1238         EvDocumentInfo *info;
1239         PSDocument *ps = PS_DOCUMENT (document);
1240
1241         info = g_new0 (EvDocumentInfo, 1);
1242         info->fields_mask = EV_DOCUMENT_INFO_TITLE |
1243                             EV_DOCUMENT_INFO_FORMAT |
1244                             EV_DOCUMENT_INFO_CREATOR |
1245                             EV_DOCUMENT_INFO_N_PAGES;
1246         info->title = g_strdup (ps->doc->title);
1247         info->format = ps->doc->epsf ? g_strdup (_("Encapsulated PostScript"))
1248                                      : g_strdup (_("PostScript"));
1249         info->creator = g_strdup (ps->doc->creator);
1250         info->n_pages = ev_document_get_n_pages (document);
1251
1252         return info;
1253 }
1254
1255 static void
1256 ps_document_document_iface_init (EvDocumentIface *iface)
1257 {
1258         iface->load = ps_document_load;
1259         iface->save = ps_document_save;
1260         iface->can_get_text = ps_document_can_get_text;
1261         iface->get_n_pages = ps_document_get_n_pages;
1262         iface->get_page_size = ps_document_get_page_size;
1263         iface->get_info = ps_document_get_info;
1264 }
1265
1266 static void
1267 ps_async_renderer_iface_init (EvAsyncRendererIface *iface)
1268 {
1269         iface->render_pixbuf = ps_async_renderer_render_pixbuf;
1270 }
1271
1272 static void
1273 ps_document_ps_export_begin (EvPSExporter *exporter, const char *filename,
1274                              int first_page, int last_page,
1275                              double width, double height, gboolean duplex)
1276 {
1277         PSDocument *document = PS_DOCUMENT (exporter);
1278
1279         if (document->structured_doc) {
1280                 g_free (document->ps_export_pagelist);
1281         
1282                 document->ps_export_pagelist = g_new0 (int, document->doc->numpages);
1283         }
1284
1285         document->ps_export_filename = g_strdup (filename);
1286 }
1287
1288 static void
1289 ps_document_ps_export_do_page (EvPSExporter *exporter, EvRenderContext *rc)
1290 {
1291         PSDocument *document = PS_DOCUMENT (exporter);
1292         
1293         if (document->structured_doc) {
1294                 document->ps_export_pagelist[rc->page] = 1;
1295         }
1296 }
1297
1298 static void
1299 ps_document_ps_export_end (EvPSExporter *exporter)
1300 {
1301         PSDocument *document = PS_DOCUMENT (exporter);
1302
1303         if (!document->structured_doc) {
1304                 save_document (document, document->ps_export_filename);
1305         } else {
1306                 save_page_list (document, document->ps_export_pagelist,
1307                                 document->ps_export_filename);
1308                 g_free (document->ps_export_pagelist);
1309                 g_free (document->ps_export_filename);  
1310                 document->ps_export_pagelist = NULL;
1311                 document->ps_export_filename = NULL;
1312         }
1313 }
1314
1315 static void
1316 ps_document_ps_exporter_iface_init (EvPSExporterIface *iface)
1317 {
1318         iface->begin = ps_document_ps_export_begin;
1319         iface->do_page = ps_document_ps_export_do_page;
1320         iface->end = ps_document_ps_export_end;
1321 }