]> www.fi.muni.cz Git - evince.git/blob - ps/ps-document.c
Runtime check for gs interpreter. Fix for the bug #320868. Thanks to
[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, *gs_path;
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_path = g_find_program_in_path ("gs");
632         gs_args = g_strsplit (gs_path, " ", NUM_GS_ARGS);
633         g_free (gs_path);
634         for(i = 0; i < NUM_GS_ARGS && gs_args[i]; i++, argc++) {
635                 argv[argc] = gs_args[i];
636         }
637
638         alpha_args = g_strsplit (ALPHA_PARAMS, " ", NUM_ALPHA_ARGS);
639         for(i = 0; i < NUM_ALPHA_ARGS && alpha_args[i]; i++, argc++) {
640                 argv[argc] = alpha_args[i];
641         }
642
643         argv[argc++] = "-dNOPAUSE";
644         argv[argc++] = "-dQUIET";
645         argv[argc++] = "-dSAFER";
646
647         /* set up the pipes */
648         if (gs->send_filename_to_gs) {
649                 argv[argc++] = PS_DOCUMENT_GET_PS_FILE (gs);
650                 argv[argc++] = "-c";
651                 argv[argc++] = "quit";
652         } else {
653                 argv[argc++] = "-";
654         }
655
656         argv[argc++] = NULL;
657
658         if (!gs->reading_from_pipe && !gs->send_filename_to_gs) {
659                 if (pipe (std_in) == -1) {
660                         g_critical ("Unable to open pipe to Ghostscript.");
661                         return -1;
662                 }
663         }
664
665         if (pipe (std_out) == -1) {
666                 close_pipe (std_in);
667                 return -1;
668         }
669
670         if (pipe(std_err) == -1) {
671                 close_pipe (std_in);
672                 close_pipe (std_out);
673                 return -1;
674         }
675
676         gv_env = g_strdup_printf ("GHOSTVIEW=%ld %ld",
677                                   gdk_x11_drawable_get_xid (gs->pstarget),
678                                   gdk_x11_drawable_get_xid (gs->bpixmap));
679         LOG ("Launching ghostview with env %s", gv_env);
680
681         gs->interpreter_pid = fork ();
682         switch (gs->interpreter_pid) {
683                 case -1:                     /* error */
684                         close_pipe (std_in);
685                         close_pipe (std_out);
686                         close_pipe (std_err);
687                         return -2;
688                         break;
689                 case 0:                      /* child */
690                         close (std_out[0]);
691                         dup2 (std_out[1], 1);
692                         close (std_out[1]);
693
694                         close (std_err[0]);
695                         dup2 (std_err[1], 2);
696                         close (std_err[1]);
697
698                         if (!gs->reading_from_pipe) {
699                                 if (gs->send_filename_to_gs) {
700                                         int stdinfd;
701                                         /* just in case gs tries to read from stdin */
702                                         stdinfd = open("/dev/null", O_RDONLY);
703                                         if (stdinfd != 0) {
704                                                 dup2(stdinfd, 0);
705                                                 close(stdinfd);
706                                         }
707                                 } else {
708                                         close (std_in[1]);
709                                         dup2 (std_in[0], 0);
710                                         close (std_in[0]);
711                                 }
712                         }
713
714                         putenv(gv_env);
715
716                         /* change to directory where the input file is. This helps
717                          * with postscript-files which include other files using
718                          * a relative path */
719                         dir = g_path_get_dirname (gs->gs_filename);
720                         chdir (dir);
721                         g_free (dir);
722
723                         execvp (argv[0], argv);
724
725                         /* Notify error */
726                         g_critical ("Unable to execute [%s]\n", argv[0]);
727                         g_strfreev (gs_args);
728                         g_free (gv_env);
729                         g_strfreev (alpha_args);
730                         _exit (1);
731                         break;
732                 default:                     /* parent */
733                         if (!gs->send_filename_to_gs && !gs->reading_from_pipe) {
734                                 int result;
735                                 close (std_in[0]);
736                                 /* use non-blocking IO for pipe to ghostscript */
737                                 result = fcntl (std_in[1], F_GETFL, 0);
738                                 fcntl (std_in[1], F_SETFL, result | O_NONBLOCK);
739                                 gs->interpreter_input = std_in[1];
740                         } else {
741                                 gs->interpreter_input = -1;
742                         }
743                         close (std_out[1]);
744
745                         gs->interpreter_output = std_out[0];
746                         close (std_err[1]);
747                         gs->interpreter_err = std_err[0];
748                         gs->interpreter_output_id =
749                                 gdk_input_add (std_out[0], GDK_INPUT_READ, output, gs);
750                         gs->interpreter_error_id =
751                                 gdk_input_add (std_err[0], GDK_INPUT_READ, output, gs);
752                         break;
753         }
754
755         return TRUE;
756 }
757
758 static void
759 stop_interpreter(PSDocument * gs)
760 {
761         if (gs->interpreter_pid > 0) {
762                 int status = 0;
763                 LOG ("Stop the interpreter");
764                 kill (gs->interpreter_pid, SIGTERM);
765                 while ((wait(&status) == -1) && (errno == EINTR));
766                 gs->interpreter_pid = -1;
767                 if (status == 1) {
768                         gs->gs_status = _("Interpreter failed.");
769                 }
770         }
771
772         if (gs->interpreter_input >= 0) {
773                 close (gs->interpreter_input);
774                 gs->interpreter_input = -1;
775                 if (gs->interpreter_input_id != 0) {
776                         gdk_input_remove(gs->interpreter_input_id);
777                         gs->interpreter_input_id = 0;
778                 }
779                 while (gs->ps_input) {
780                         struct record_list *ps_old = gs->ps_input;
781                         gs->ps_input = gs->ps_input->next;
782                         if (ps_old->close && NULL != ps_old->fp)
783                                 fclose (ps_old->fp);
784                         g_free (ps_old);
785                 }
786         }
787
788         if (gs->interpreter_output >= 0) {
789                 close (gs->interpreter_output);
790                 gs->interpreter_output = -1;
791                 if (gs->interpreter_output_id) {
792                         gdk_input_remove (gs->interpreter_output_id);
793                         gs->interpreter_output_id = 0;
794                 }
795         }
796
797         if (gs->interpreter_err >= 0) {
798                 close (gs->interpreter_err);
799                 gs->interpreter_err = -1;
800                 if (gs->interpreter_error_id) {
801                         gdk_input_remove (gs->interpreter_error_id);
802                         gs->interpreter_error_id = 0;
803                 }
804         }
805
806         gs->busy = FALSE;
807 }
808
809 /* If file exists and is a regular file then return its length, else -1 */
810 static gint
811 file_length (const gchar * filename)
812 {
813         struct stat stat_rec;
814
815         if (filename && (stat (filename, &stat_rec) == 0) && S_ISREG (stat_rec.st_mode))
816                 return stat_rec.st_size;
817         else
818                 return -1;
819 }
820
821 /* Test if file exists, is a regular file and its length is > 0 */
822 static gboolean
823 file_readable(const char *filename)
824 {
825         return (file_length (filename) > 0);
826 }
827
828 /*
829  * Decompress gs->gs_filename if necessary
830  * Set gs->filename_unc to the name of the uncompressed file or NULL.
831  * Error reporting via signal 'interpreter_message'
832  * Return name of input file to use or NULL on error..
833  */
834 static gchar *
835 check_filecompressed (PSDocument * gs)
836 {
837         FILE *file;
838         gchar buf[1024];
839         gchar *filename, *filename_unc, *filename_err, *cmdline;
840         const gchar *cmd;
841         int fd;
842
843         cmd = NULL;
844
845         if ((file = fopen(gs->gs_filename, "r")) &&
846             (fread (buf, sizeof(gchar), 3, file) == 3)) {
847                 if ((buf[0] == '\037') && ((buf[1] == '\235') || (buf[1] == '\213'))) {
848                         /* file is gzipped or compressed */
849                         cmd = gtk_gs_defaults_get_ungzip_cmd ();
850                 } else if (strncmp (buf, "BZh", 3) == 0) {
851                         /* file is compressed with bzip2 */
852                         cmd = gtk_gs_defaults_get_unbzip2_cmd ();
853                 }
854         }
855
856         if (NULL != file)
857                 fclose(file);
858
859         if (!cmd)
860                 return gs->gs_filename;
861
862         /* do the decompression */
863         filename = g_shell_quote (gs->gs_filename);
864         filename_unc = g_strconcat (g_get_tmp_dir (), "/evinceXXXXXX", NULL);
865         if ((fd = mkstemp (filename_unc)) < 0) {
866                 g_free (filename_unc);
867                 g_free (filename);
868                 return NULL;
869         }
870         close (fd);
871
872         filename_err = g_strconcat (g_get_tmp_dir (), "/evinceXXXXXX", NULL);
873         if ((fd = mkstemp(filename_err)) < 0) {
874                 g_free (filename_err);
875                 g_free (filename_unc);
876                 g_free (filename);
877                 return NULL;
878         }
879         close (fd);
880
881         cmdline = g_strdup_printf ("%s %s >%s 2>%s", cmd,
882                                    filename, filename_unc, filename_err);
883         if (system (cmdline) == 0 &&
884             file_readable (filename_unc) &&
885             file_length (filename_err) == 0) {
886                 /* sucessfully uncompressed file */
887                 gs->gs_filename_unc = filename_unc;
888         } else {
889                 gchar *filename_dsp;
890                 gchar *msg;
891
892                 /* report error */
893                 filename_dsp = g_filename_display_name (gs->gs_filename);
894                 msg = g_strdup_printf (_("Error while decompressing file %s:\n"), filename_dsp);
895                 g_free (filename_dsp);
896                 
897                 interpreter_failed (gs, msg);
898                 g_free (msg);
899                 unlink (filename_unc);
900                 g_free (filename_unc);
901                 filename_unc = NULL;
902         }
903
904         unlink (filename_err);
905         g_free (filename_err);
906         g_free (cmdline);
907         g_free (filename);
908
909         return filename_unc;
910 }
911
912 static gint
913 ps_document_enable_interpreter(PSDocument *gs)
914 {
915         g_return_val_if_fail (PS_IS_DOCUMENT (gs), FALSE);
916
917         if (!gs->gs_filename)
918                 return 0;
919
920         return start_interpreter (gs);
921 }
922
923 static gboolean
924 document_load (PSDocument *gs, const gchar *fname)
925 {
926         g_return_val_if_fail (PS_IS_DOCUMENT(gs), FALSE);
927
928         LOG ("Load the document");
929
930         if (fname == NULL) {
931                 gs->gs_status = "";
932                 return FALSE;
933         }
934
935         /* prepare this document */
936         gs->structured_doc = FALSE;
937         gs->send_filename_to_gs = TRUE;
938         gs->gs_filename = g_strdup (fname);
939
940         if ((gs->reading_from_pipe = (strcmp (fname, "-") == 0))) {
941                 gs->send_filename_to_gs = FALSE;
942         } else {
943                 /*
944                  * We need to make sure that the file is loadable/exists!
945                  * otherwise we want to exit without loading new stuff...
946                  */
947                 gchar *filename = NULL;
948
949                 if (!file_readable(fname)) {
950                         gchar *filename_dsp;
951                         gchar *msg;
952
953                         filename_dsp = g_filename_display_name (fname);
954                         msg = g_strdup_printf (_("Cannot open file %s.\n"), filename_dsp);
955                         g_free (filename_dsp);
956                         
957                         interpreter_failed (gs, msg);
958                         g_free (msg);
959                         gs->gs_status = _("File is not readable.");
960                 } else {
961                         filename = check_filecompressed(gs);
962                 }
963
964                 if (!filename || (gs->gs_psfile = fopen(filename, "r")) == NULL) {
965                         interpreter_failed (gs, NULL);
966                         return FALSE;
967                 }
968
969                 /* we grab the vital statistics!!! */
970                 gs->doc = psscan(gs->gs_psfile, TRUE, filename);
971
972                 if ((!gs->doc->epsf && gs->doc->numpages > 0) ||
973                     (gs->doc->epsf && gs->doc->numpages > 1)) {
974                         gs->structured_doc = TRUE;
975                         gs->send_filename_to_gs = FALSE;
976                 }
977         }
978
979         gs->gs_status = _("Document loaded.");
980
981         return TRUE;
982 }
983
984 static gboolean
985 ps_document_next_page (PSDocument *gs)
986 {
987         XEvent event;
988
989         LOG ("Make ghostscript render next page");
990
991         g_return_val_if_fail (PS_IS_DOCUMENT(gs), FALSE);
992         g_return_val_if_fail (gs->interpreter_pid != 0, FALSE);
993         g_return_val_if_fail (gs->busy != TRUE, FALSE);
994
995         gs->busy = TRUE;
996
997         event.xclient.type = ClientMessage;
998         event.xclient.display = gdk_display;
999         event.xclient.window = gs->message_window;
1000         event.xclient.message_type = gdk_x11_atom_to_xatom(gs_class->next_atom);
1001         event.xclient.format = 32;
1002
1003         gdk_error_trap_push ();
1004         XSendEvent (gdk_display, gs->message_window, FALSE, 0, &event);
1005         gdk_flush ();
1006         gdk_error_trap_pop ();
1007
1008         return TRUE;
1009 }
1010
1011 static gboolean
1012 render_page (PSDocument *gs, int page)
1013 {
1014         g_return_val_if_fail(gs != NULL, FALSE);
1015         g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
1016
1017         if(!gs->gs_filename) {
1018                 return FALSE;
1019         }
1020
1021         if (gs->structured_doc && gs->doc) {
1022                 LOG ("It's a structured document, let's send one page to gs");
1023
1024                 if (is_interpreter_ready (gs)) {
1025                         ps_document_next_page (gs);
1026                 } else {
1027                         ps_document_enable_interpreter (gs);
1028                         send_ps (gs, gs->doc->beginprolog, gs->doc->lenprolog, FALSE);
1029                         send_ps (gs, gs->doc->beginsetup, gs->doc->lensetup, FALSE);
1030                 }
1031
1032                 send_ps (gs, gs->doc->pages[page].begin,
1033                          gs->doc->pages[page].len, FALSE);
1034         } else {
1035                 /* Unstructured document
1036                  *
1037                  * In the case of non structured documents,
1038                  * GS read the PS from the  actual file (via command
1039                  * line. Hence, ggv only send a signal next page.
1040                  * If ghostview is not running it is usually because
1041                  * the last page of the file was displayed. In that
1042                  * case, ggv restarts GS again and the first page is displayed.
1043                  */
1044
1045                 LOG ("It's an unstructured document, gs will just read the file");
1046
1047                 if (!is_interpreter_ready (gs)) {
1048                         ps_document_enable_interpreter(gs);
1049                 }
1050                 ps_document_next_page(gs);
1051         }
1052
1053         return TRUE;
1054 }
1055
1056 static gboolean
1057 ps_document_load (EvDocument  *document,
1058                   const char  *uri,
1059                   GError     **error)
1060 {
1061         char *filename;
1062         char *gs_path;
1063         gboolean result;
1064
1065         filename = g_filename_from_uri (uri, NULL, error);
1066         if (!filename)
1067                 return FALSE;
1068
1069         gs_path = g_find_program_in_path ("gs");
1070         if (!gs_path) {
1071                     gchar *filename_dsp;
1072                     filename_dsp = g_filename_display_name (filename);
1073                     g_set_error(error,
1074                                 G_FILE_ERROR,
1075                                 G_FILE_ERROR_NOENT,
1076                                 _("Failed to load document '%s'. Ghostscript interpreter was not found in path"),
1077                                 filename);
1078                     g_free (filename_dsp);
1079                     result = FALSE;     
1080         } else {
1081                 result = document_load (PS_DOCUMENT (document), filename);
1082                 if (!result) {
1083                         gchar *filename_dsp;
1084                         filename_dsp = g_filename_display_name (filename);
1085                         
1086                         g_set_error (error, G_FILE_ERROR,
1087                                      G_FILE_ERROR_FAILED,
1088                                      _("Failed to load document '%s'"),
1089                                      filename_dsp);
1090                         g_free (filename_dsp);
1091                 }
1092                 g_free (gs_path);
1093         }
1094         g_free (filename);
1095
1096         return result;
1097 }
1098
1099 static gboolean
1100 save_document (PSDocument *document, const char *filename)
1101 {
1102         gboolean result = TRUE;
1103         GtkGSDocSink *sink = gtk_gs_doc_sink_new ();
1104         FILE *f, *src_file;
1105         gchar *buf;
1106
1107         src_file = fopen (PS_DOCUMENT_GET_PS_FILE(document), "r");
1108         if (src_file) {
1109                 struct stat stat_rec;
1110
1111                 if (stat (PS_DOCUMENT_GET_PS_FILE(document), &stat_rec) == 0) {
1112                         pscopy (src_file, sink, 0, stat_rec.st_size - 1);
1113                 }
1114
1115                 fclose (src_file);
1116         }
1117         
1118         buf = gtk_gs_doc_sink_get_buffer (sink);
1119         if (buf == NULL) {
1120                 return FALSE;
1121         }
1122         
1123         f = fopen (filename, "w");
1124         if (f) {
1125                 fputs (buf, f);
1126                 fclose (f);
1127         } else {
1128                 result = FALSE;
1129         }
1130
1131         g_free (buf);
1132         gtk_gs_doc_sink_free (sink);
1133         g_free (sink);
1134
1135         return result;
1136 }
1137
1138 static gboolean
1139 save_page_list (PSDocument *document, int *page_list, const char *filename)
1140 {
1141         gboolean result = TRUE;
1142         GtkGSDocSink *sink = gtk_gs_doc_sink_new ();
1143         FILE *f;
1144         gchar *buf;
1145
1146         pscopydoc (sink, PS_DOCUMENT_GET_PS_FILE(document), 
1147                    document->doc, page_list);
1148         
1149         buf = gtk_gs_doc_sink_get_buffer (sink);
1150         
1151         f = fopen (filename, "w");
1152         if (f) {
1153                 fputs (buf, f);
1154                 fclose (f);
1155         } else {
1156                 result = FALSE;
1157         }
1158
1159         g_free (buf);
1160         gtk_gs_doc_sink_free (sink);
1161         g_free (sink);
1162
1163         return result;
1164 }
1165
1166 static gboolean
1167 ps_document_save (EvDocument  *document,
1168                   const char  *uri,
1169                   GError     **error)
1170 {
1171         PSDocument *ps = PS_DOCUMENT (document);
1172         gboolean result;
1173         char *filename;
1174
1175         filename = g_filename_from_uri (uri, NULL, error);
1176         if (!filename)
1177                 return FALSE;
1178
1179         result = save_document (ps, filename);
1180
1181         g_free (filename);
1182
1183         return result;
1184 }
1185
1186 static int
1187 ps_document_get_n_pages (EvDocument  *document)
1188 {
1189         PSDocument *ps = PS_DOCUMENT (document);
1190
1191         g_return_val_if_fail (ps != NULL, -1);
1192
1193         if (!ps->gs_filename || !ps->doc) {
1194                 return -1;
1195         }
1196
1197         return ps->structured_doc ? ps->doc->numpages : 1;
1198 }
1199
1200 static void
1201 ps_document_get_page_size (EvDocument   *document,
1202                            int           page,
1203                            double       *width,
1204                            double       *height)
1205 {
1206         PSDocument *gs = PS_DOCUMENT (document);
1207         int urx, ury, llx, lly;
1208
1209         get_page_box (PS_DOCUMENT (document), page, &urx, &ury, &llx, &lly);
1210
1211         if (width) {
1212                 *width = (urx - llx) / 72.0 * get_xdpi (gs) + 0.5;
1213         }
1214
1215         if (height) {
1216                 *height = (ury - lly) / 72.0 * get_ydpi (gs) + 0.5;
1217         }
1218 }
1219
1220 static gboolean
1221 ps_document_can_get_text (EvDocument *document)
1222 {
1223         return FALSE;
1224 }
1225
1226 static void
1227 ps_async_renderer_render_pixbuf (EvAsyncRenderer *renderer, int page, double scale, int rotation)
1228 {
1229         PSDocument *gs = PS_DOCUMENT (renderer);
1230
1231         if (gs->pstarget == NULL) {
1232                 gs->target_window = gtk_window_new (GTK_WINDOW_POPUP);
1233                 gtk_widget_realize (gs->target_window);
1234                 gs->pstarget = gs->target_window->window;
1235
1236                 g_assert (gs->pstarget != NULL);
1237
1238                 g_signal_connect (gs->target_window, "event",
1239                                   G_CALLBACK (ps_document_widget_event),
1240                                   gs);
1241         }
1242
1243         setup_pixmap (gs, page, scale, rotation);
1244         setup_page (gs, page, scale, rotation);
1245
1246         render_page (gs, page);
1247 }
1248
1249 static EvDocumentInfo *
1250 ps_document_get_info (EvDocument *document)
1251 {
1252         EvDocumentInfo *info;
1253         PSDocument *ps = PS_DOCUMENT (document);
1254
1255         info = g_new0 (EvDocumentInfo, 1);
1256         info->fields_mask = EV_DOCUMENT_INFO_TITLE |
1257                             EV_DOCUMENT_INFO_FORMAT |
1258                             EV_DOCUMENT_INFO_CREATOR |
1259                             EV_DOCUMENT_INFO_N_PAGES;
1260         info->title = g_strdup (ps->doc->title);
1261         info->format = ps->doc->epsf ? g_strdup (_("Encapsulated PostScript"))
1262                                      : g_strdup (_("PostScript"));
1263         info->creator = g_strdup (ps->doc->creator);
1264         info->n_pages = ev_document_get_n_pages (document);
1265
1266         return info;
1267 }
1268
1269 static void
1270 ps_document_document_iface_init (EvDocumentIface *iface)
1271 {
1272         iface->load = ps_document_load;
1273         iface->save = ps_document_save;
1274         iface->can_get_text = ps_document_can_get_text;
1275         iface->get_n_pages = ps_document_get_n_pages;
1276         iface->get_page_size = ps_document_get_page_size;
1277         iface->get_info = ps_document_get_info;
1278 }
1279
1280 static void
1281 ps_async_renderer_iface_init (EvAsyncRendererIface *iface)
1282 {
1283         iface->render_pixbuf = ps_async_renderer_render_pixbuf;
1284 }
1285
1286 static void
1287 ps_document_ps_export_begin (EvPSExporter *exporter, const char *filename,
1288                              int first_page, int last_page,
1289                              double width, double height, gboolean duplex)
1290 {
1291         PSDocument *document = PS_DOCUMENT (exporter);
1292
1293         if (document->structured_doc) {
1294                 g_free (document->ps_export_pagelist);
1295         
1296                 document->ps_export_pagelist = g_new0 (int, document->doc->numpages);
1297         }
1298
1299         document->ps_export_filename = g_strdup (filename);
1300 }
1301
1302 static void
1303 ps_document_ps_export_do_page (EvPSExporter *exporter, EvRenderContext *rc)
1304 {
1305         PSDocument *document = PS_DOCUMENT (exporter);
1306         
1307         if (document->structured_doc) {
1308                 document->ps_export_pagelist[rc->page] = 1;
1309         }
1310 }
1311
1312 static void
1313 ps_document_ps_export_end (EvPSExporter *exporter)
1314 {
1315         PSDocument *document = PS_DOCUMENT (exporter);
1316
1317         if (!document->structured_doc) {
1318                 save_document (document, document->ps_export_filename);
1319         } else {
1320                 save_page_list (document, document->ps_export_pagelist,
1321                                 document->ps_export_filename);
1322                 g_free (document->ps_export_pagelist);
1323                 g_free (document->ps_export_filename);  
1324                 document->ps_export_pagelist = NULL;
1325                 document->ps_export_filename = NULL;
1326         }
1327 }
1328
1329 static void
1330 ps_document_ps_exporter_iface_init (EvPSExporterIface *iface)
1331 {
1332         iface->begin = ps_document_ps_export_begin;
1333         iface->do_page = ps_document_ps_export_do_page;
1334         iface->end = ps_document_ps_export_end;
1335 }