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