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