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