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