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