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