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