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