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