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