]> www.fi.muni.cz Git - evince.git/blob - ps/ps-document.c
d7995f7688505d1b7c003dd5c16ef6e2e2d3e29b
[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         g_print ("%f %f %f %d %d\n", width, height, scale, pixmap_width, pixmap_height);
376
377         if(gs->bpixmap) {
378                 int w, h;
379
380                 gdk_drawable_get_size (gs->bpixmap, &w, &h);
381
382                 if (pixmap_width != w || h != pixmap_height) {
383                         gdk_drawable_unref (gs->bpixmap);
384                         gs->bpixmap = NULL;
385                         stop_interpreter (gs);
386                 }
387         }
388
389         if (!gs->bpixmap) {
390                 LOG ("Create pixmap");
391
392                 fill = gdk_gc_new (gs->pstarget);
393                 colormap = gdk_drawable_get_colormap (gs->pstarget);
394                 gdk_color_alloc (colormap, &white);
395                 gdk_gc_set_foreground (fill, &white);
396                 gs->bpixmap = gdk_pixmap_new (gs->pstarget, pixmap_width,
397                                               pixmap_height, -1);
398                 gdk_draw_rectangle (gs->bpixmap, fill, TRUE,
399                                     0, 0, pixmap_width, pixmap_height);
400         }
401 }
402
403 static void
404 get_page_box (PSDocument *gs, int page, int *urx, int *ury, int *llx, int *lly)
405 {
406         GtkGSPaperSize *paper_sizes = gtk_gs_defaults_get_paper_sizes ();
407
408         g_return_if_fail (PS_IS_DOCUMENT (gs));
409         g_return_if_fail (gs->doc != NULL);
410         g_return_if_fail (page >= 0);
411
412         if (gs->doc->pages && gs->doc->pages[page].size) {
413                 int page_size;
414
415                 page_size = gs->doc->pages[page].size - gs->doc->size;
416                 *llx = *lly = 0;
417                 *urx = gs->doc->size[page_size].width;
418                 *ury = gs->doc->size[page_size].height;
419         } else if (gs->doc->pages &&
420                    (gs->doc->pages[page].boundingbox[URX] >
421                     gs->doc->pages[page].boundingbox[LLX]) &&
422                    (gs->doc->pages[page].boundingbox[URY] >
423                     gs->doc->pages[page].boundingbox[LLY])) {
424                 *llx = gs->doc->pages[page].boundingbox[LLX];
425                 *lly = gs->doc->pages[page].boundingbox[LLY];
426                 *urx = gs->doc->pages[page].boundingbox[URX];
427                 *ury = gs->doc->pages[page].boundingbox[URY];
428         } else if ((gs->doc->boundingbox[URX] > gs->doc->boundingbox[LLX]) &&
429                    (gs->doc->boundingbox[URY] > gs->doc->boundingbox[LLY])) {
430                 *llx = gs->doc->boundingbox[LLX];
431                 *lly = gs->doc->boundingbox[LLY];
432                 *urx = gs->doc->boundingbox[URX];
433                 *ury = gs->doc->boundingbox[URY];
434         } else {
435                 /* Fallback to A4 */
436                 *llx = *lly = 0;
437                 *urx = paper_sizes[12].width;
438                 *ury = paper_sizes[12].height;
439         }
440 }
441
442 static int
443 get_page_orientation (PSDocument *gs, int page)
444 {
445         int orientation;
446
447         orientation = GTK_GS_ORIENTATION_NONE;
448
449         if (gs->structured_doc) {
450                 orientation = gs->doc->pages[page].orientation;
451         }
452         if (orientation == GTK_GS_ORIENTATION_NONE) {
453                 orientation = GTK_GS_ORIENTATION_PORTRAIT;
454         }
455
456         return orientation;
457 }
458
459 static void
460 setup_page (PSDocument *gs, int page, double scale)
461 {
462         char buf[1024];
463         int urx, ury, llx, lly, orientation;
464 #ifdef HAVE_LOCALE_H
465         char *savelocale;
466 #endif
467
468         LOG ("Setup the page");
469
470 #ifdef HAVE_LOCALE_H
471         /* gs needs floating point parameters with '.' as decimal point
472          * while some (european) locales use ',' instead, so we set the 
473          * locale for this snprintf to "C".
474          */
475         savelocale = setlocale (LC_NUMERIC, "C");
476 #endif
477         get_page_box (gs, page, &urx, &ury, &llx, &lly);
478         orientation = get_page_orientation (gs, page);
479
480         g_snprintf (buf, 1024, "%ld %d %d %d %d %d %f %f %d %d %d %d",
481                     0L, orientation * 90, llx, lly, urx, ury,
482                     get_xdpi (gs) * scale,
483                     get_ydpi (gs) * scale,
484                     0, 0, 0, 0);
485         LOG ("GS property %s", buf);
486
487 #ifdef HAVE_LOCALE_H
488         setlocale(LC_NUMERIC, savelocale);
489 #endif
490         gdk_property_change (gs->pstarget, gs_class->gs_atom, gs_class->string_atom,
491                              8, GDK_PROP_MODE_REPLACE, (guchar *)buf, strlen(buf));
492         gdk_flush ();
493 }
494
495 static void
496 close_pipe (int p[2])
497 {
498         if (p[0] != -1) {
499                 close (p[0]);
500         }
501         if (p[1] != -1) {
502                 close (p[1]);
503         }
504 }
505
506 static gboolean
507 is_interpreter_ready (PSDocument *gs)
508 {
509         return (gs->interpreter_pid != -1 && !gs->busy && gs->ps_input == NULL);
510 }
511
512 static void
513 output(gpointer data, gint source, GdkInputCondition condition)
514 {
515   char buf[MAX_BUFSIZE + 1], *msg;
516   guint bytes = 0;
517   PSDocument *gs = PS_DOCUMENT(data);
518
519   if(source == gs->interpreter_output) {
520     bytes = read(gs->interpreter_output, buf, MAX_BUFSIZE);
521     if(bytes == 0) {            /* EOF occurred */
522       close(gs->interpreter_output);
523       gs->interpreter_output = -1;
524       gdk_input_remove(gs->interpreter_output_id);
525       return;
526     }
527     else if(bytes == -1) {
528       /* trouble... */
529       interpreter_failed(gs, NULL);
530       return;
531     }
532     if(gs->interpreter_err == -1) {
533       interpreter_failed(gs, NULL);
534     }
535   }
536   else if(source == gs->interpreter_err) {
537     bytes = read(gs->interpreter_err, buf, MAX_BUFSIZE);
538     if(bytes == 0) {            /* EOF occurred */
539       close(gs->interpreter_err);
540       gs->interpreter_err = -1;
541       gdk_input_remove(gs->interpreter_error_id);
542       return;
543     }
544     else if(bytes == -1) {
545       /* trouble... */
546       interpreter_failed(gs, NULL);
547       return;
548     }
549     if(gs->interpreter_output == -1) {
550       interpreter_failed(gs, NULL);
551     }
552   }
553   if(bytes > 0) {
554     buf[bytes] = '\0';
555     msg = g_strdup(buf);
556     interpreter_failed (gs, msg);   
557   }
558 }
559
560 static void
561 catchPipe(int i)
562 {
563   broken_pipe = True;
564 }
565
566 static void
567 input(gpointer data, gint source, GdkInputCondition condition)
568 {
569   PSDocument *gs = PS_DOCUMENT(data);
570   int bytes_written;
571   void (*oldsig) (int);
572   oldsig = signal(SIGPIPE, catchPipe);
573
574   LOG ("Input");
575
576   do {
577     if(gs->buffer_bytes_left == 0) {
578       /* Get a new section if required */
579       if(gs->ps_input && gs->bytes_left == 0) {
580         struct record_list *ps_old = gs->ps_input;
581         gs->ps_input = ps_old->next;
582         if(ps_old->close && NULL != ps_old->fp)
583           fclose(ps_old->fp);
584         g_free((char *) ps_old);
585       }
586       /* Have to seek at the beginning of each section */
587       if(gs->ps_input && gs->ps_input->seek_needed) {
588         fseek(gs->ps_input->fp, gs->ps_input->begin, SEEK_SET);
589         gs->ps_input->seek_needed = FALSE;
590         gs->bytes_left = gs->ps_input->len;
591       }
592
593       if(gs->bytes_left > MAX_BUFSIZE) {
594         gs->buffer_bytes_left =
595           fread(gs->input_buffer, sizeof(char), MAX_BUFSIZE, gs->ps_input->fp);
596       }
597       else if(gs->bytes_left > 0) {
598         gs->buffer_bytes_left =
599           fread(gs->input_buffer,
600                 sizeof(char), gs->bytes_left, gs->ps_input->fp);
601       }
602       else {
603         gs->buffer_bytes_left = 0;
604       }
605       if(gs->bytes_left > 0 && gs->buffer_bytes_left == 0) {
606         interpreter_failed (gs, NULL); /* Error occurred */
607       }
608       gs->input_buffer_ptr = gs->input_buffer;
609       gs->bytes_left -= gs->buffer_bytes_left;
610     }
611
612     if(gs->buffer_bytes_left > 0) {
613       bytes_written = write(gs->interpreter_input,
614                             gs->input_buffer_ptr, gs->buffer_bytes_left);
615
616       if(broken_pipe) {
617         interpreter_failed (gs, g_strdup(_("Broken pipe.")));
618         broken_pipe = FALSE;
619         interpreter_failed (gs, NULL);
620       }
621       else if(bytes_written == -1) {
622         if((errno != EWOULDBLOCK) && (errno != EAGAIN)) {
623           interpreter_failed (gs, NULL);   /* Something bad happened */
624         }
625       }
626       else {
627         gs->buffer_bytes_left -= bytes_written;
628         gs->input_buffer_ptr += bytes_written;
629       }
630     }
631   }
632   while(gs->ps_input && gs->buffer_bytes_left == 0);
633
634   signal(SIGPIPE, oldsig);
635
636   if(gs->ps_input == NULL && gs->buffer_bytes_left == 0) {
637     if(gs->interpreter_input_id != 0) {
638       gdk_input_remove(gs->interpreter_input_id);
639       gs->interpreter_input_id = 0;
640     }
641   }
642 }
643
644 static int
645 start_interpreter (PSDocument *gs)
646 {
647         int std_in[2] = { -1, -1 };   /* pipe to interp stdin */
648         int std_out[2];               /* pipe from interp stdout */
649         int std_err[2];               /* pipe from interp stderr */
650
651 #define NUM_ARGS    100
652 #define NUM_GS_ARGS (NUM_ARGS - 20)
653 #define NUM_ALPHA_ARGS 10
654
655         char *argv[NUM_ARGS], *dir, *gv_env;
656         char **gs_args, **alpha_args = NULL;
657         int argc = 0, i;
658
659         LOG ("Start the interpreter");
660
661         if(!gs->gs_filename)
662                 return 0;
663
664         stop_interpreter(gs);
665
666         /* set up the args... */
667         gs_args = g_strsplit (gtk_gs_defaults_get_interpreter_cmd (), " ", NUM_GS_ARGS);
668         for(i = 0; i < NUM_GS_ARGS && gs_args[i]; i++, argc++) {
669                 argv[argc] = gs_args[i];
670         }
671
672         alpha_args = g_strsplit (ALPHA_PARAMS, " ", NUM_ALPHA_ARGS);
673         for(i = 0; i < NUM_ALPHA_ARGS && alpha_args[i]; i++, argc++) {
674                 argv[argc] = alpha_args[i];
675         }
676
677         argv[argc++] = "-dNOPAUSE";
678         argv[argc++] = "-dQUIET";
679         argv[argc++] = "-dSAFER";
680
681         /* set up the pipes */
682         if (gs->send_filename_to_gs) {
683                 argv[argc++] = PS_DOCUMENT_GET_PS_FILE (gs);
684                 argv[argc++] = "-c";
685                 argv[argc++] = "quit";
686         } else {
687                 argv[argc++] = "-";
688         }
689
690         argv[argc++] = NULL;
691
692         if (!gs->reading_from_pipe && !gs->send_filename_to_gs) {
693                 if (pipe (std_in) == -1) {
694                         g_critical ("Unable to open pipe to Ghostscript.");
695                         return -1;
696                 }
697         }
698
699         if (pipe (std_out) == -1) {
700                 close_pipe (std_in);
701                 return -1;
702         }
703
704         if (pipe(std_err) == -1) {
705                 close_pipe (std_in);
706                 close_pipe (std_out);
707                 return -1;
708         }
709
710         gv_env = g_strdup_printf ("GHOSTVIEW=%ld %ld",
711                                   gdk_x11_drawable_get_xid (gs->pstarget),
712                                   gdk_x11_drawable_get_xid (gs->bpixmap));
713         LOG ("Launching ghostview with env %s", gv_env);
714
715         gs->busy = TRUE;
716         gs->interpreter_pid = fork ();
717         switch (gs->interpreter_pid) {
718                 case -1:                     /* error */
719                         close_pipe (std_in);
720                         close_pipe (std_out);
721                         close_pipe (std_err);
722                         return -2;
723                         break;
724                 case 0:                      /* child */
725                         close (std_out[0]);
726                         dup2 (std_out[1], 1);
727                         close (std_out[1]);
728
729                         close (std_err[0]);
730                         dup2 (std_err[1], 2);
731                         close (std_err[1]);
732
733                         if (!gs->reading_from_pipe) {
734                                 if (gs->send_filename_to_gs) {
735                                         int stdinfd;
736                                         /* just in case gs tries to read from stdin */
737                                         stdinfd = open("/dev/null", O_RDONLY);
738                                         if (stdinfd != 0) {
739                                                 dup2(stdinfd, 0);
740                                                 close(stdinfd);
741                                         }
742                                 } else {
743                                         close (std_in[1]);
744                                         dup2 (std_in[0], 0);
745                                         close (std_in[0]);
746                                 }
747                         }
748
749                         putenv(gv_env);
750
751                         /* change to directory where the input file is. This helps
752                          * with postscript-files which include other files using
753                          * a relative path */
754                         dir = g_path_get_dirname (gs->gs_filename);
755                         chdir (dir);
756                         g_free (dir);
757
758                         execvp (argv[0], argv);
759
760                         /* Notify error */
761                         g_critical ("Unable to execute [%s]\n", argv[0]);
762                         g_strfreev (gs_args);
763                         g_free (gv_env);
764                         g_strfreev (alpha_args);
765                         _exit (1);
766                         break;
767                 default:                     /* parent */
768                         if (!gs->send_filename_to_gs && !gs->reading_from_pipe) {
769                                 int result;
770                                 close (std_in[0]);
771                                 /* use non-blocking IO for pipe to ghostscript */
772                                 result = fcntl (std_in[1], F_GETFL, 0);
773                                 fcntl (std_in[1], F_SETFL, result | O_NONBLOCK);
774                                 gs->interpreter_input = std_in[1];
775                         } else {
776                                 gs->interpreter_input = -1;
777                         }
778                         close (std_out[1]);
779
780                         gs->interpreter_output = std_out[0];
781                         close (std_err[1]);
782                         gs->interpreter_err = std_err[0];
783                         gs->interpreter_output_id =
784                                 gdk_input_add (std_out[0], GDK_INPUT_READ, output, gs);
785                         gs->interpreter_error_id =
786                                 gdk_input_add (std_err[0], GDK_INPUT_READ, output, gs);
787                         break;
788         }
789
790         return TRUE;
791 }
792
793 static void
794 stop_interpreter(PSDocument * gs)
795 {
796   if(gs->interpreter_pid > 0) {
797     int status = 0;
798     LOG ("Stop the interpreter");
799     kill(gs->interpreter_pid, SIGTERM);
800     while((wait(&status) == -1) && (errno == EINTR)) ;
801     gs->interpreter_pid = -1;
802     if(status == 1) {
803       ps_document_cleanup(gs);
804       gs->gs_status = _("Interpreter failed.");
805     }
806   }
807
808   if(gs->interpreter_input >= 0) {
809     close(gs->interpreter_input);
810     gs->interpreter_input = -1;
811     if(gs->interpreter_input_id != 0) {
812       gdk_input_remove(gs->interpreter_input_id);
813       gs->interpreter_input_id = 0;
814     }
815     while(gs->ps_input) {
816       struct record_list *ps_old = gs->ps_input;
817       gs->ps_input = gs->ps_input->next;
818       if(ps_old->close && NULL != ps_old->fp)
819         fclose(ps_old->fp);
820       g_free((char *) ps_old);
821     }
822   }
823
824   if(gs->interpreter_output >= 0) {
825     close(gs->interpreter_output);
826     gs->interpreter_output = -1;
827     if(gs->interpreter_output_id) {
828       gdk_input_remove(gs->interpreter_output_id);
829       gs->interpreter_output_id = 0;
830     }
831   }
832
833   if(gs->interpreter_err >= 0) {
834     close(gs->interpreter_err);
835     gs->interpreter_err = -1;
836     if(gs->interpreter_error_id) {
837       gdk_input_remove(gs->interpreter_error_id);
838       gs->interpreter_error_id = 0;
839     }
840   }
841
842   gs->busy = FALSE;
843 }
844
845 /* If file exists and is a regular file then return its length, else -1 */
846 static gint
847 file_length(const gchar * filename)
848 {
849   struct stat stat_rec;
850
851   if(filename && (stat(filename, &stat_rec) == 0)
852      && S_ISREG(stat_rec.st_mode))
853     return stat_rec.st_size;
854   else
855     return -1;
856 }
857
858 /* Test if file exists, is a regular file and its length is > 0 */
859 static gboolean
860 file_readable(const char *filename)
861 {
862   return (file_length(filename) > 0);
863 }
864
865 /*
866  * Decompress gs->gs_filename if necessary
867  * Set gs->filename_unc to the name of the uncompressed file or NULL.
868  * Error reporting via signal 'interpreter_message'
869  * Return name of input file to use or NULL on error..
870  */
871 static gchar *
872 check_filecompressed(PSDocument * gs)
873 {
874   FILE *file;
875   gchar buf[1024];
876   gchar *filename, *filename_unc, *filename_err, *cmdline;
877   const gchar *cmd;
878   int fd;
879
880   cmd = NULL;
881
882   if((file = fopen(gs->gs_filename, "r"))
883      && (fread(buf, sizeof(gchar), 3, file) == 3)) {
884     if((buf[0] == '\037') && ((buf[1] == '\235') || (buf[1] == '\213'))) {
885       /* file is gzipped or compressed */
886       cmd = gtk_gs_defaults_get_ungzip_cmd();
887     }
888     else if(strncmp(buf, "BZh", 3) == 0) {
889       /* file is compressed with bzip2 */
890       cmd = gtk_gs_defaults_get_unbzip2_cmd();
891     }
892   }
893   if(NULL != file)
894     fclose(file);
895
896   if(!cmd)
897     return gs->gs_filename;
898
899   /* do the decompression */
900   filename = g_shell_quote(gs->gs_filename);
901   filename_unc = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL);
902   if((fd = mkstemp(filename_unc)) < 0) {
903     g_free(filename_unc);
904     g_free(filename);
905     return NULL;
906   }
907   close(fd);
908   filename_err = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL);
909   if((fd = mkstemp(filename_err)) < 0) {
910     g_free(filename_err);
911     g_free(filename_unc);
912     g_free(filename);
913     return NULL;
914   }
915   close(fd);
916   cmdline = g_strdup_printf("%s %s >%s 2>%s", cmd,
917                             filename, filename_unc, filename_err);
918   if((system(cmdline) == 0)
919      && file_readable(filename_unc)
920      && (file_length(filename_err) == 0)) {
921     /* sucessfully uncompressed file */
922     gs->gs_filename_unc = filename_unc;
923   }
924   else {
925     /* report error */
926     g_snprintf(buf, 1024, _("Error while decompressing file %s:\n"),
927                gs->gs_filename);
928     interpreter_failed (gs, buf);
929     unlink(filename_unc);
930     g_free(filename_unc);
931     filename_unc = NULL;
932   }
933   unlink(filename_err);
934   g_free(filename_err);
935   g_free(cmdline);
936   g_free(filename);
937   return filename_unc;
938 }
939
940 static gint
941 ps_document_enable_interpreter(PSDocument * gs)
942 {
943   g_return_val_if_fail(gs != NULL, FALSE);
944   g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
945
946   if(!gs->gs_filename)
947     return 0;
948
949   return start_interpreter(gs);
950 }
951
952 /* publicly accessible functions */
953
954 GType
955 ps_document_get_type(void)
956 {
957   static GType gs_type = 0;
958   if(!gs_type) {
959     GTypeInfo gs_info = {
960       sizeof(PSDocumentClass),
961       (GBaseInitFunc) NULL,
962       (GBaseFinalizeFunc) NULL,
963       (GClassInitFunc) ps_document_class_init,
964       (GClassFinalizeFunc) NULL,
965       NULL,                     /* class_data */
966       sizeof(PSDocument),
967       0,                        /* n_preallocs */
968       (GInstanceInitFunc) ps_document_init
969     };
970
971     static const GInterfaceInfo document_info =
972     {
973         (GInterfaceInitFunc) ps_document_document_iface_init,
974         NULL,
975         NULL
976     };
977
978     gs_type = g_type_register_static(G_TYPE_OBJECT,
979                                      "PSDocument", &gs_info, 0);
980
981     g_type_add_interface_static (gs_type,
982                                  EV_TYPE_DOCUMENT,
983                                  &document_info);
984   }
985   return gs_type;
986
987
988 }
989
990 static gboolean
991 document_load(PSDocument * gs, const gchar * fname)
992 {
993   g_return_val_if_fail(gs != NULL, FALSE);
994   g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
995
996   LOG ("Load the document");
997
998   /* clean up previous document */
999   ps_document_cleanup(gs);
1000
1001   if(fname == NULL) {
1002     gs->gs_status = "";
1003     return FALSE;
1004   }
1005
1006   /* prepare this document */
1007   gs->structured_doc = FALSE;
1008   gs->send_filename_to_gs = TRUE;
1009   gs->loaded = FALSE;
1010   if(*fname == '/') {
1011     /* an absolute path */
1012     gs->gs_filename = g_strdup(fname);
1013   }
1014   else {
1015     /* path relative to our cwd: make it absolute */
1016     gchar *cwd = g_get_current_dir();
1017     gs->gs_filename = g_strconcat(cwd, "/", fname, NULL);
1018     g_free(cwd);
1019   }
1020
1021   if((gs->reading_from_pipe = (strcmp(fname, "-") == 0))) {
1022     gs->send_filename_to_gs = FALSE;
1023   }
1024   else {
1025     /*
1026      * We need to make sure that the file is loadable/exists!
1027      * otherwise we want to exit without loading new stuff...
1028      */
1029     gchar *filename = NULL;
1030
1031     if(!file_readable(fname)) {
1032       gchar buf[1024];
1033       g_snprintf(buf, 1024, _("Cannot open file %s.\n"), fname);
1034       interpreter_failed (gs, buf);
1035       gs->gs_status = _("File is not readable.");
1036     }
1037     else {
1038       filename = check_filecompressed(gs);
1039     }
1040
1041     if(!filename || (gs->gs_psfile = fopen(filename, "r")) == NULL) {
1042       interpreter_failed (gs, NULL);
1043       ps_document_cleanup(gs);
1044       return FALSE;
1045     }
1046
1047     /* we grab the vital statistics!!! */
1048     gs->doc = psscan(gs->gs_psfile, TRUE, filename);
1049
1050     g_object_notify (G_OBJECT (gs), "title");
1051
1052     if(gs->doc == NULL) {
1053       /* File does not seem to be a Postscript one */
1054       gchar buf[1024];
1055       g_snprintf(buf, 1024, _("Error while scanning file %s\n"), fname);
1056       interpreter_failed (gs, buf);
1057       ps_document_cleanup(gs);
1058       gs->gs_status = _("The file is not a PostScript document.");
1059       return FALSE;
1060     }
1061
1062     if((!gs->doc->epsf && gs->doc->numpages > 0) ||
1063        (gs->doc->epsf && gs->doc->numpages > 1)) {
1064       gs->structured_doc = TRUE;
1065       gs->send_filename_to_gs = FALSE;
1066     }
1067   }
1068   gs->loaded = TRUE;
1069
1070   gs->gs_status = _("Document loaded.");
1071
1072   return gs->loaded;
1073 }
1074
1075
1076 static gboolean
1077 ps_document_next_page (PSDocument *gs)
1078 {
1079         XEvent event;
1080
1081         LOG ("Make ghostscript render next page");
1082
1083         g_return_val_if_fail (PS_IS_DOCUMENT(gs), FALSE);
1084         g_return_val_if_fail (gs->interpreter_pid != 0, FALSE);
1085         g_return_val_if_fail (gs->busy != TRUE, FALSE);
1086
1087         gs->busy = TRUE;
1088
1089         event.xclient.type = ClientMessage;
1090         event.xclient.display = gdk_display;
1091         event.xclient.window = gs->message_window;
1092         event.xclient.message_type = gdk_x11_atom_to_xatom(gs_class->next_atom);
1093         event.xclient.format = 32;
1094
1095         gdk_error_trap_push ();
1096         XSendEvent (gdk_display, gs->message_window, FALSE, 0, &event);
1097         gdk_flush ();
1098         gdk_error_trap_pop ();
1099
1100         return TRUE;
1101 }
1102
1103 static gboolean
1104 render_page (PSDocument *gs, int page)
1105 {
1106         g_return_val_if_fail(gs != NULL, FALSE);
1107         g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
1108
1109         if(!gs->gs_filename) {
1110                 return FALSE;
1111         }
1112
1113         if (gs->structured_doc && gs->doc) {
1114                 LOG ("It's a structured document, let's send one page to gs");
1115
1116                 if (is_interpreter_ready (gs)) {
1117                         ps_document_next_page (gs);
1118                 } else {
1119                         ps_document_enable_interpreter (gs);
1120                         send_ps (gs, gs->doc->beginprolog, gs->doc->lenprolog, FALSE);
1121                         send_ps (gs, gs->doc->beginsetup, gs->doc->lensetup, FALSE);
1122                 }
1123
1124                 send_ps (gs, gs->doc->pages[page].begin,
1125                          gs->doc->pages[page].len, FALSE);
1126         } else {
1127                 /* Unstructured document
1128                  *
1129                  * In the case of non structured documents,
1130                  * GS read the PS from the  actual file (via command
1131                  * line. Hence, ggv only send a signal next page.
1132                  * If ghostview is not running it is usually because
1133                  * the last page of the file was displayed. In that
1134                  * case, ggv restarts GS again and the first page is displayed.
1135                  */
1136
1137                 LOG ("It's an unstructured document, gs will just read the file");
1138
1139                 if (!is_interpreter_ready (gs)) {
1140                         ps_document_enable_interpreter(gs);
1141                 }
1142                 ps_document_next_page(gs);
1143         }
1144
1145         return TRUE;
1146 }
1147
1148 static gboolean
1149 ps_document_load (EvDocument  *document,
1150                   const char  *uri,
1151                   GError     **error)
1152 {
1153         gboolean result;
1154         char *filename;
1155
1156         filename = g_filename_from_uri (uri, NULL, error);
1157         if (!filename)
1158                 return FALSE;
1159
1160         result = document_load (PS_DOCUMENT (document), filename);
1161         if (!result) {
1162                 g_set_error (error, G_FILE_ERROR,
1163                              G_FILE_ERROR_FAILED,
1164                              "Failed to load document '%s'\n",
1165                              uri);
1166         }
1167
1168         g_free (filename);
1169
1170         return result;
1171 }
1172
1173 static gboolean
1174 ps_document_save (EvDocument  *document,
1175                   const char  *uri,
1176                   GError     **error)
1177 {
1178         g_warning ("ps_document_save not implemented"); /* FIXME */
1179         return TRUE;
1180 }
1181
1182 static int
1183 ps_document_get_n_pages (EvDocument  *document)
1184 {
1185         PSDocument *ps = PS_DOCUMENT (document);
1186
1187         g_return_val_if_fail (ps != NULL, -1);
1188
1189         if (!ps->gs_filename || !ps->doc) {
1190                 return -1;
1191         }
1192
1193         return ps->structured_doc ? ps->doc->numpages : 1;
1194 }
1195
1196 static void
1197 ps_document_get_page_size (EvDocument   *document,
1198                            int           page,
1199                            double       *width,
1200                            double       *height)
1201 {
1202         PSDocument *gs = PS_DOCUMENT (document);
1203         int w, h;
1204         int urx, ury, llx, lly, orientation;
1205
1206         get_page_box (PS_DOCUMENT (document), page, &urx, &ury, &llx, &lly);
1207         orientation = get_page_orientation (PS_DOCUMENT (document), page);
1208
1209         switch (orientation) {
1210                 case GTK_GS_ORIENTATION_PORTRAIT:
1211                 case GTK_GS_ORIENTATION_UPSIDEDOWN:
1212                         w = (urx - llx) / 72.0 * get_xdpi (gs) + 0.5;
1213                         h = (ury - lly) / 72.0 * get_ydpi (gs) + 0.5;
1214                         break;
1215                 case GTK_GS_ORIENTATION_LANDSCAPE:
1216                 case GTK_GS_ORIENTATION_SEASCAPE:
1217                         w = (ury - lly) / 72.0 * get_xdpi (gs) + 0.5;
1218                         h = (urx - llx) / 72.0 * get_ydpi (gs) + 0.5;
1219                         break;
1220                 default:
1221                         w = h = 0;
1222                         g_assert_not_reached ();
1223                         break;
1224         }
1225
1226         if (width) {
1227                 *width = w;
1228         }
1229
1230         if (height) {
1231                 *height = h;
1232         }
1233 }
1234
1235 static char *
1236 ps_document_get_text (EvDocument *document, int page, EvRectangle *rect)
1237 {
1238         g_warning ("ps_document_get_text not implemented"); /* FIXME ? */
1239         return NULL;
1240 }
1241
1242 static gboolean
1243 render_pixbuf_idle (PSRenderJob *job)
1244 {
1245         PSDocument *gs = job->document;
1246
1247         if (gs->pstarget == NULL) {
1248                 GtkWidget *widget;
1249
1250                 widget = gtk_window_new (GTK_WINDOW_POPUP);
1251                 gtk_widget_realize (widget);
1252                 gs->pstarget = widget->window;
1253
1254                 g_assert (gs->pstarget != NULL);
1255
1256                 g_signal_connect (widget, "event",
1257                                   G_CALLBACK (ps_document_widget_event),
1258                                   gs);
1259         }
1260
1261         setup_pixmap (gs, job->page, job->scale);
1262         setup_page (gs, job->page, job->scale);
1263
1264         render_page (gs, job->page);
1265
1266         return FALSE;
1267 }
1268
1269 static GdkPixbuf *
1270 ps_document_render_pixbuf (EvDocument *document, int page, double scale)
1271 {
1272         GdkPixbuf *pixbuf;
1273         PSRenderJob job;
1274
1275         job.page = page;
1276         job.scale = scale;
1277         job.document = PS_DOCUMENT (document);
1278         g_idle_add ((GSourceFunc)render_pixbuf_idle, &job);
1279
1280         g_mutex_lock (pixbuf_mutex);
1281         while (!current_pixbuf)
1282                 g_cond_wait (pixbuf_cond, pixbuf_mutex);
1283         pixbuf = current_pixbuf;
1284         current_pixbuf = NULL;
1285         g_mutex_unlock (pixbuf_mutex);
1286
1287         LOG ("Pixbuf rendered %p\n", pixbuf);
1288
1289         return pixbuf;
1290 }
1291
1292 static void
1293 ps_document_document_iface_init (EvDocumentIface *iface)
1294 {
1295         iface->load = ps_document_load;
1296         iface->save = ps_document_save;
1297         iface->get_text = ps_document_get_text;
1298         iface->get_n_pages = ps_document_get_n_pages;
1299         iface->get_page_size = ps_document_get_page_size;
1300         iface->render_pixbuf = ps_document_render_pixbuf;
1301 }