]> www.fi.muni.cz Git - evince.git/blob - ps/ps-document.c
20d55c44d08a456d3d6da9f5ece148b2f060075b
[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
601         argv[argc++] = "-dNOPAUSE";
602         argv[argc++] = "-dQUIET";
603         argv[argc++] = "-dSAFER";
604
605         /* set up the pipes */
606         if (gs->send_filename_to_gs) {
607                 argv[argc++] = PS_DOCUMENT_GET_PS_FILE (gs);
608                 argv[argc++] = "-c";
609                 argv[argc++] = "quit";
610         } else {
611                 argv[argc++] = "-";
612         }
613
614         argv[argc++] = NULL;
615
616         if (!gs->reading_from_pipe && !gs->send_filename_to_gs) {
617                 if (pipe (std_in) == -1) {
618                         g_critical ("Unable to open pipe to Ghostscript.");
619                         return -1;
620                 }
621         }
622
623         if (pipe (std_out) == -1) {
624                 close_pipe (std_in);
625                 return -1;
626         }
627
628         if (pipe(std_err) == -1) {
629                 close_pipe (std_in);
630                 close_pipe (std_out);
631                 return -1;
632         }
633
634         gv_env = g_strdup_printf ("GHOSTVIEW=%ld %ld",
635                                   gdk_x11_drawable_get_xid (gs->pstarget),
636                                   gdk_x11_drawable_get_xid (gs->bpixmap));
637         LOG ("Launching ghostview with env %s", gv_env);
638
639         gs->busy = TRUE;
640         gs->interpreter_pid = fork ();
641         switch (gs->interpreter_pid) {
642                 case -1:                     /* error */
643                         close_pipe (std_in);
644                         close_pipe (std_out);
645                         close_pipe (std_err);
646                         return -2;
647                         break;
648                 case 0:                      /* child */
649                         close (std_out[0]);
650                         dup2 (std_out[1], 1);
651                         close (std_out[1]);
652
653                         close (std_err[0]);
654                         dup2 (std_err[1], 2);
655                         close (std_err[1]);
656
657                         if (!gs->reading_from_pipe) {
658                                 if (gs->send_filename_to_gs) {
659                                         int stdinfd;
660                                         /* just in case gs tries to read from stdin */
661                                         stdinfd = open("/dev/null", O_RDONLY);
662                                         if (stdinfd != 0) {
663                                                 dup2(stdinfd, 0);
664                                                 close(stdinfd);
665                                         }
666                                 } else {
667                                         close (std_in[1]);
668                                         dup2 (std_in[0], 0);
669                                         close (std_in[0]);
670                                 }
671                         }
672
673                         putenv(gv_env);
674
675                         /* change to directory where the input file is. This helps
676                          * with postscript-files which include other files using
677                          * a relative path */
678                         dir = g_path_get_dirname (gs->gs_filename);
679                         chdir (dir);
680                         g_free (dir);
681
682                         execvp (argv[0], argv);
683
684                         /* Notify error */
685                         g_critical ("Unable to execute [%s]\n", argv[0]);
686                         g_strfreev (gs_args);
687                         g_free (gv_env);
688                         g_strfreev (alpha_args);
689                         _exit (1);
690                         break;
691                 default:                     /* parent */
692                         if (!gs->send_filename_to_gs && !gs->reading_from_pipe) {
693                                 int result;
694                                 close (std_in[0]);
695                                 /* use non-blocking IO for pipe to ghostscript */
696                                 result = fcntl (std_in[1], F_GETFL, 0);
697                                 fcntl (std_in[1], F_SETFL, result | O_NONBLOCK);
698                                 gs->interpreter_input = std_in[1];
699                         } else {
700                                 gs->interpreter_input = -1;
701                         }
702                         close (std_out[1]);
703
704                         gs->interpreter_output = std_out[0];
705                         close (std_err[1]);
706                         gs->interpreter_err = std_err[0];
707                         gs->interpreter_output_id =
708                                 gdk_input_add (std_out[0], GDK_INPUT_READ, output, gs);
709                         gs->interpreter_error_id =
710                                 gdk_input_add (std_err[0], GDK_INPUT_READ, output, gs);
711                         break;
712         }
713
714         return TRUE;
715 }
716
717 static void
718 stop_interpreter(PSDocument * gs)
719 {
720   if(gs->interpreter_pid > 0) {
721     int status = 0;
722     LOG ("Stop the interpreter");
723     kill(gs->interpreter_pid, SIGTERM);
724     while((wait(&status) == -1) && (errno == EINTR)) ;
725     gs->interpreter_pid = -1;
726     if(status == 1) {
727       ps_document_cleanup(gs);
728       gs->gs_status = _("Interpreter failed.");
729     }
730   }
731
732   if(gs->interpreter_input >= 0) {
733     close(gs->interpreter_input);
734     gs->interpreter_input = -1;
735     if(gs->interpreter_input_id != 0) {
736       gdk_input_remove(gs->interpreter_input_id);
737       gs->interpreter_input_id = 0;
738     }
739     while(gs->ps_input) {
740       struct record_list *ps_old = gs->ps_input;
741       gs->ps_input = gs->ps_input->next;
742       if(ps_old->close && NULL != ps_old->fp)
743         fclose(ps_old->fp);
744       g_free((char *) ps_old);
745     }
746   }
747
748   if(gs->interpreter_output >= 0) {
749     close(gs->interpreter_output);
750     gs->interpreter_output = -1;
751     if(gs->interpreter_output_id) {
752       gdk_input_remove(gs->interpreter_output_id);
753       gs->interpreter_output_id = 0;
754     }
755   }
756
757   if(gs->interpreter_err >= 0) {
758     close(gs->interpreter_err);
759     gs->interpreter_err = -1;
760     if(gs->interpreter_error_id) {
761       gdk_input_remove(gs->interpreter_error_id);
762       gs->interpreter_error_id = 0;
763     }
764   }
765
766   gs->busy = FALSE;
767 }
768
769 /* If file exists and is a regular file then return its length, else -1 */
770 static gint
771 file_length(const gchar * filename)
772 {
773   struct stat stat_rec;
774
775   if(filename && (stat(filename, &stat_rec) == 0)
776      && S_ISREG(stat_rec.st_mode))
777     return stat_rec.st_size;
778   else
779     return -1;
780 }
781
782 /* Test if file exists, is a regular file and its length is > 0 */
783 static gboolean
784 file_readable(const char *filename)
785 {
786   return (file_length(filename) > 0);
787 }
788
789 /*
790  * Decompress gs->gs_filename if necessary
791  * Set gs->filename_unc to the name of the uncompressed file or NULL.
792  * Error reporting via signal 'interpreter_message'
793  * Return name of input file to use or NULL on error..
794  */
795 static gchar *
796 check_filecompressed(PSDocument * gs)
797 {
798   FILE *file;
799   gchar buf[1024];
800   gchar *filename, *filename_unc, *filename_err, *cmdline;
801   const gchar *cmd;
802   int fd;
803
804   cmd = NULL;
805
806   if((file = fopen(gs->gs_filename, "r"))
807      && (fread(buf, sizeof(gchar), 3, file) == 3)) {
808     if((buf[0] == '\037') && ((buf[1] == '\235') || (buf[1] == '\213'))) {
809       /* file is gzipped or compressed */
810       cmd = gtk_gs_defaults_get_ungzip_cmd();
811     }
812     else if(strncmp(buf, "BZh", 3) == 0) {
813       /* file is compressed with bzip2 */
814       cmd = gtk_gs_defaults_get_unbzip2_cmd();
815     }
816   }
817   if(NULL != file)
818     fclose(file);
819
820   if(!cmd)
821     return gs->gs_filename;
822
823   /* do the decompression */
824   filename = g_shell_quote(gs->gs_filename);
825   filename_unc = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL);
826   if((fd = mkstemp(filename_unc)) < 0) {
827     g_free(filename_unc);
828     g_free(filename);
829     return NULL;
830   }
831   close(fd);
832   filename_err = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL);
833   if((fd = mkstemp(filename_err)) < 0) {
834     g_free(filename_err);
835     g_free(filename_unc);
836     g_free(filename);
837     return NULL;
838   }
839   close(fd);
840   cmdline = g_strdup_printf("%s %s >%s 2>%s", cmd,
841                             filename, filename_unc, filename_err);
842   if((system(cmdline) == 0)
843      && file_readable(filename_unc)
844      && (file_length(filename_err) == 0)) {
845     /* sucessfully uncompressed file */
846     gs->gs_filename_unc = filename_unc;
847   }
848   else {
849     /* report error */
850     g_snprintf(buf, 1024, _("Error while decompressing file %s:\n"),
851                gs->gs_filename);
852     interpreter_failed (gs, buf);
853     unlink(filename_unc);
854     g_free(filename_unc);
855     filename_unc = NULL;
856   }
857   unlink(filename_err);
858   g_free(filename_err);
859   g_free(cmdline);
860   g_free(filename);
861   return filename_unc;
862 }
863
864 static void
865 compute_dimensions (PSDocument *gs, int page)
866 {
867         GtkGSPaperSize *paper_sizes = gtk_gs_defaults_get_paper_sizes ();
868         int urx, ury, llx, lly;
869         int width, height;
870         int orientation;
871
872         g_return_if_fail (PS_IS_DOCUMENT (gs));
873         g_return_if_fail (gs->doc != NULL);
874         g_return_if_fail (page >= 0);
875         g_return_if_fail (gs->doc->numpages > page);
876
877         orientation = GTK_GS_ORIENTATION_NONE;
878         if (gs->structured_doc) {
879                 orientation = gs->doc->pages[gs->current_page].orientation;
880         }
881         if (orientation == GTK_GS_ORIENTATION_NONE) {
882                 orientation = GTK_GS_ORIENTATION_PORTRAIT;
883         }
884
885         if (gs->doc->pages && gs->doc->pages[page].size) {
886                 int page_size;
887
888                 page_size = gs->doc->pages[page].size - gs->doc->size;
889                 llx = lly = 0;
890                 urx = gs->doc->size[page_size].width;
891                 ury = gs->doc->size[page_size].height;
892         } else if (gs->doc->pages &&
893                    (gs->doc->pages[page].boundingbox[URX] >
894                     gs->doc->pages[page].boundingbox[LLX]) &&
895                    (gs->doc->pages[page].boundingbox[URY] >
896                     gs->doc->pages[page].boundingbox[LLY])) {
897                 llx = gs->doc->pages[page].boundingbox[LLX];
898                 lly = gs->doc->pages[page].boundingbox[LLY];
899                 urx = gs->doc->pages[page].boundingbox[URX];
900                 ury = gs->doc->pages[page].boundingbox[URY];
901         } else if ((gs->doc->boundingbox[URX] > gs->doc->boundingbox[LLX]) &&
902                    (gs->doc->boundingbox[URY] > gs->doc->boundingbox[LLY])) {
903                 llx = gs->doc->boundingbox[LLX];
904                 lly = gs->doc->boundingbox[LLY];
905                 urx = gs->doc->boundingbox[URX];
906                 ury = gs->doc->boundingbox[URY];
907         } else {
908                 /* Fallback to A4 */
909                 llx = lly = 0;
910                 urx = paper_sizes[12].width;
911                 ury = paper_sizes[12].height;
912         }
913
914         switch (orientation) {
915                 case GTK_GS_ORIENTATION_PORTRAIT:
916                 case GTK_GS_ORIENTATION_UPSIDEDOWN:
917                         width = (urx - llx) / 72.0 * get_xdpi (gs) + 0.5;
918                         height = (ury - lly) / 72.0 * get_ydpi (gs) + 0.5;
919                         break;
920                 case GTK_GS_ORIENTATION_LANDSCAPE:
921                 case GTK_GS_ORIENTATION_SEASCAPE:
922                         width = (ury - lly) / 72.0 * get_xdpi (gs) + 0.5;
923                         height = (urx - llx) / 72.0 * get_ydpi (gs) + 0.5;
924                         break;
925                 default:
926                         width = height = 0;
927                         g_assert_not_reached ();
928                         break;
929         }
930
931         width = width * gs->zoom_factor;
932         height = height * gs->zoom_factor;
933
934         if (llx != gs->llx || lly != gs->lly ||
935             urx != gs->urx || ury != gs->ury ||
936             gs->width != width || gs->height != height ||
937             orientation != gs->orientation) {
938                 gs->llx = llx;
939                 gs->lly = lly;
940                 gs->urx = urx;
941                 gs->ury = ury;
942                 gs->width = width;
943                 gs->height = height;
944                 gs->orientation = orientation;
945                 gs->changed = TRUE;
946         }
947 }
948
949 static gint
950 ps_document_enable_interpreter(PSDocument * gs)
951 {
952   g_return_val_if_fail(gs != NULL, FALSE);
953   g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
954
955   if(!gs->gs_filename)
956     return 0;
957
958   return start_interpreter(gs);
959 }
960
961 /* publicly accessible functions */
962
963 GType
964 ps_document_get_type(void)
965 {
966   static GType gs_type = 0;
967   if(!gs_type) {
968     GTypeInfo gs_info = {
969       sizeof(PSDocumentClass),
970       (GBaseInitFunc) NULL,
971       (GBaseFinalizeFunc) NULL,
972       (GClassInitFunc) ps_document_class_init,
973       (GClassFinalizeFunc) NULL,
974       NULL,                     /* class_data */
975       sizeof(PSDocument),
976       0,                        /* n_preallocs */
977       (GInstanceInitFunc) ps_document_init
978     };
979
980     static const GInterfaceInfo document_info =
981     {
982         (GInterfaceInitFunc) ps_document_document_iface_init,
983         NULL,
984         NULL
985     };
986
987     gs_type = g_type_register_static(G_TYPE_OBJECT,
988                                      "PSDocument", &gs_info, 0);
989
990     g_type_add_interface_static (gs_type,
991                                  EV_TYPE_DOCUMENT,
992                                  &document_info);
993   }
994   return gs_type;
995
996
997 }
998
999 static gboolean
1000 document_load(PSDocument * gs, const gchar * fname)
1001 {
1002   g_return_val_if_fail(gs != NULL, FALSE);
1003   g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
1004
1005   LOG ("Load the document");
1006
1007   /* clean up previous document */
1008   ps_document_cleanup(gs);
1009
1010   if(fname == NULL) {
1011     gs->gs_status = "";
1012     return FALSE;
1013   }
1014
1015   /* prepare this document */
1016   gs->structured_doc = FALSE;
1017   gs->send_filename_to_gs = TRUE;
1018   gs->current_page = 0;
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       ps_document_cleanup(gs);
1054       return FALSE;
1055     }
1056
1057     /* we grab the vital statistics!!! */
1058     gs->doc = psscan(gs->gs_psfile, TRUE, filename);
1059
1060     g_object_notify (G_OBJECT (gs), "title");
1061
1062     if(gs->doc == NULL) {
1063       /* File does not seem to be a Postscript one */
1064       gchar buf[1024];
1065       g_snprintf(buf, 1024, _("Error while scanning file %s\n"), fname);
1066       interpreter_failed (gs, buf);
1067       ps_document_cleanup(gs);
1068       gs->gs_status = _("The file is not a PostScript document.");
1069       return FALSE;
1070     }
1071
1072     if((!gs->doc->epsf && gs->doc->numpages > 0) ||
1073        (gs->doc->epsf && gs->doc->numpages > 1)) {
1074       gs->structured_doc = TRUE;
1075       gs->send_filename_to_gs = FALSE;
1076     }
1077   }
1078   gs->loaded = TRUE;
1079   compute_dimensions (gs, gs->current_page);
1080
1081   gs->gs_status = _("Document loaded.");
1082
1083   return gs->loaded;
1084 }
1085
1086
1087 static gboolean
1088 ps_document_next_page (PSDocument *gs)
1089 {
1090         XEvent event;
1091
1092         LOG ("Make ghostscript render next page");
1093
1094         g_return_val_if_fail (PS_IS_DOCUMENT(gs), FALSE);
1095         g_return_val_if_fail (gs->interpreter_pid != 0, FALSE);
1096         g_return_val_if_fail (gs->busy != TRUE, FALSE);
1097
1098         gs->busy = TRUE;
1099
1100         event.xclient.type = ClientMessage;
1101         event.xclient.display = gdk_display;
1102         event.xclient.window = gs->message_window;
1103         event.xclient.message_type = gdk_x11_atom_to_xatom(gs_class->next_atom);
1104         event.xclient.format = 32;
1105
1106         gdk_error_trap_push ();
1107         XSendEvent (gdk_display, gs->message_window, FALSE, 0, &event);
1108         gdk_flush ();
1109         gdk_error_trap_pop ();
1110
1111         return TRUE;
1112 }
1113
1114 static gboolean
1115 render_page (PSDocument *gs, int page)
1116 {
1117         g_return_val_if_fail(gs != NULL, FALSE);
1118         g_return_val_if_fail(PS_IS_DOCUMENT(gs), FALSE);
1119
1120         if(!gs->gs_filename) {
1121                 return FALSE;
1122         }
1123
1124         if (gs->structured_doc && gs->doc) {
1125                 LOG ("It's a structured document, let's send one page to gs");
1126
1127                 if (is_interpreter_ready (gs)) {
1128                         ps_document_next_page (gs);
1129                 } else {
1130                         ps_document_enable_interpreter (gs);
1131                         send_ps (gs, gs->doc->beginprolog, gs->doc->lenprolog, FALSE);
1132                         send_ps (gs, gs->doc->beginsetup, gs->doc->lensetup, FALSE);
1133                 }
1134
1135                 send_ps (gs, gs->doc->pages[page].begin,
1136                          gs->doc->pages[page].len, FALSE);
1137         } else {
1138                 /* Unstructured document
1139                  *
1140                  * In the case of non structured documents,
1141                  * GS read the PS from the  actual file (via command
1142                  * line. Hence, ggv only send a signal next page.
1143                  * If ghostview is not running it is usually because
1144                  * the last page of the file was displayed. In that
1145                  * case, ggv restarts GS again and the first page is displayed.
1146                  */
1147
1148                 LOG ("It's an unstructured document, gs will just read the file");
1149
1150                 if (!is_interpreter_ready (gs)) {
1151                         ps_document_enable_interpreter(gs);
1152                 }
1153                 ps_document_next_page(gs);
1154         }
1155
1156         return TRUE;
1157 }
1158
1159 static gboolean
1160 ps_document_load (EvDocument  *document,
1161                   const char  *uri,
1162                   GError     **error)
1163 {
1164         gboolean result;
1165         char *filename;
1166
1167         filename = g_filename_from_uri (uri, NULL, error);
1168         if (!filename)
1169                 return FALSE;
1170
1171         result = document_load (PS_DOCUMENT (document), filename);
1172         if (!result) {
1173                 g_set_error (error, G_FILE_ERROR,
1174                              G_FILE_ERROR_FAILED,
1175                              "Failed to load document '%s'\n",
1176                              uri);
1177         }
1178
1179         g_free (filename);
1180
1181         return result;
1182 }
1183
1184 static gboolean
1185 ps_document_save (EvDocument  *document,
1186                   const char  *uri,
1187                   GError     **error)
1188 {
1189         g_warning ("ps_document_save not implemented"); /* FIXME */
1190         return TRUE;
1191 }
1192
1193 static int
1194 ps_document_get_n_pages (EvDocument  *document)
1195 {
1196         PSDocument *ps = PS_DOCUMENT (document);
1197
1198         g_return_val_if_fail (ps != NULL, -1);
1199
1200         if (!ps->gs_filename || !ps->doc) {
1201                 return -1;
1202         }
1203
1204         return ps->structured_doc ? ps->doc->numpages : 1;
1205 }
1206
1207 static void
1208 ps_document_get_page_size (EvDocument   *document,
1209                            int           page,
1210                            double       *width,
1211                            double       *height)
1212 {
1213         /* Post script documents never vary in size */
1214
1215         PSDocument *gs = PS_DOCUMENT (document);
1216
1217         compute_dimensions (gs, page);
1218
1219         if (width) {
1220                 *width = gs->width;
1221         }
1222
1223         if (height) {
1224                 *height = gs->height;
1225         }
1226 }
1227
1228 static char *
1229 ps_document_get_text (EvDocument *document, int page, EvRectangle *rect)
1230 {
1231         g_warning ("ps_document_get_text not implemented"); /* FIXME ? */
1232         return NULL;
1233 }
1234
1235 static gboolean
1236 render_pixbuf_idle (PSRenderJob *job)
1237 {
1238         PSDocument *gs = job->document;
1239
1240         if (gs->pstarget == NULL) {
1241                 GtkWidget *widget;
1242
1243                 widget = gtk_window_new (GTK_WINDOW_POPUP);
1244                 gtk_widget_realize (widget);
1245                 gs->pstarget = widget->window;
1246
1247                 g_assert (gs->pstarget != NULL);
1248
1249                 g_signal_connect (widget, "event",
1250                                   G_CALLBACK (ps_document_widget_event),
1251                                   gs);
1252         }
1253
1254         if (gs->changed) {
1255                 stop_interpreter (gs);
1256                 setup_pixmap (gs);
1257                 setup_page (gs, job->scale);
1258                 gs->changed = FALSE;
1259         }
1260
1261         render_page (gs, job->page);
1262
1263         return FALSE;
1264 }
1265
1266 static GdkPixbuf *
1267 ps_document_render_pixbuf (EvDocument *document, int page, double scale)
1268 {
1269         GdkPixbuf *pixbuf;
1270         PSRenderJob job;
1271
1272         job.page = page;
1273         job.scale = scale;
1274         job.document = PS_DOCUMENT (document);
1275         g_idle_add ((GSourceFunc)render_pixbuf_idle, &job);
1276
1277         g_mutex_lock (pixbuf_mutex);
1278         while (!current_pixbuf)
1279                 g_cond_wait (pixbuf_cond, pixbuf_mutex);
1280         pixbuf = current_pixbuf;
1281         current_pixbuf = NULL;
1282         g_mutex_unlock (pixbuf_mutex);
1283
1284         LOG ("Pixbuf rendered %p\n", pixbuf);
1285
1286         return pixbuf;
1287 }
1288
1289 static void
1290 ps_document_document_iface_init (EvDocumentIface *iface)
1291 {
1292         iface->load = ps_document_load;
1293         iface->save = ps_document_save;
1294         iface->get_text = ps_document_get_text;
1295         iface->get_n_pages = ps_document_get_n_pages;
1296         iface->get_page_size = ps_document_get_page_size;
1297         iface->render_pixbuf = ps_document_render_pixbuf;
1298 }