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