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