File: gsinterf.c

package info (click to toggle)
bmv 1.2-19
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 404 kB
  • ctags: 464
  • sloc: ansic: 3,432; makefile: 53
file content (567 lines) | stat: -rw-r--r-- 17,645 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*
 This is displ.c, part of the source code for

 BMV version 1.1
 copyright by Jan Kybic, 26th July 1994

 Jan Kybic, Prosecka 681, Praha 9, Czech Republic, <kybic@earn.cvut.cz>

 BMV is a very simple viewer of images in the pbm(5)-raw format
     and front end for GhostScript		
     based on Svgalib library for Linux

 BMV is distributed under GNU GPL (General Public License),
   you can obtain a copy from many FTP sites if you are interested for details
*/

/* this file deals with the interaction between GS and BMV */
/* see "bmv.h" for details about some globals */

#include "bmv.h"
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/errno.h>

/* PSLINELEN is a maximum line length we expect */

#define PSLINELEN 257

#define length(a) (sizeof(a)-1) /* get string length at compile time */

#define iscomment(a,b) (strncmp(a,b,length(b))==0)
                         /* this is just to make things more clear */

/* file stream for PS source file and our end of a pipe to GS */
FILE *psfile=NULL;
int gsin = -1 ;

/* file handle for the temporary file we write output from GS to */
int gsoutdesc=-1 ;


const char *gsname=GSNAME ;	/* GS binary */
const char *gsres=GSRES ;	/* GS resolution set option string */
const char *gspaper=GSPAPER ;	/* GS paper size string */
const char *gsincdir=		/* GS font include directory option string */

#ifdef GSDIR
		"-I" GSDIR ":" GSDIR "/fonts" ;
#else
		" " ;
#endif

#define	GSPAPERLEN	80	/* max length of papersize option */

int gstimeout = GSTIMEOUT ;	/* timeout in seconds */

char tempname[PSLINELEN]="" ; /* temporary file name */

/* pagedesc contains location of PS source for pages in GS document */
pagedesc pages={-1,NULL} ;


int usedsc=0 ; /* default is not DSC conforming document */

pid_t gspid=-1,gswrite=-1 ; /* pids of GS and a write_to_GS processes */

int gspipein[2],gspipeout[2] ;
  /* input and output pipes we use to get data to/from GS */


/* some prototypes, for description see definitions */
static void sendsection(int to,int num) ;
void sigalrmhandler(int sig) ;


/* openpsfile opens a PS file and sets all the global data.
   It determines whether it is a DSC document and if so, it scans it for
   comments, but it actually looks just for %%Page */

void openpsfile(const char *filename)
{
  char buf[PSLINELEN] ; /* buffer for a single line */
  long pos ;  /* position in the file before current line */
  int p ;     /* contains serial number of page */
  int trailer ;	/* are we in trailer already? */
  char *s ;	/* used to scan buf */

  printf("Opening PostScript file %s for reading...\n",filename) ;

  if ((psfile=fopen(filename,"r"))==0)
    leave(1,"Cannot open PS file for reading",strerror(errno),NULL) ;

#ifdef BMV_BUFSIZ
  if (setvbuf(psfile, NULL, _IOFBF, BMV_BUFSIZ))
    printf("Could not increase %s buffer to %d\n", filename, BMV_BUFSIZ);
#endif

  /* read a first line */
  if (fgets(buf,PSLINELEN,psfile)==NULL)
    leave(1,"Cannot read from PS file",NULL) ;

  /* check if it is DSC */
  if (iscomment(buf,"%!PS-Adobe-")) usedsc=1 ;

  trailer = 0;

  if (usedsc)
  /* for DSC documents - scan for %%Pages comment */
  for(;;) {
    /* read line */
    if (fgets(buf,PSLINELEN,psfile)==NULL)
      /* if there is no %%Pages comment it is probably EPSF file
         we shall just pretend it is a plain PS */
      { usedsc=0 ; break ; }

    if (buf[0] != '%' && buf[0] != '\0' && !trailer && !isspace(buf[0]&0xFF)) {
      usedsc = 0 ; break ;
    }
    if (iscomment(buf,"%%Pages:")) {
      /* %%Pages comment found, read number of pages */
      s = buf + length("%%Pages:");
      while (*s == ' ') s++;
      if (sscanf(s, "%d", &pages.numpages) == 1) {
        printf("This document should contain %d pages.\n",pages.numpages) ;
        break ;
      }
      if (*s != '(') {
        leave(1,"Incorrect format of the 'Pages' comment",NULL) ;
      }
      if (!trailer) {
	trailer = 1;
	fseek(psfile, -(2L * PSLINELEN), SEEK_END);
      }
    }
  }

  /* for non DSC documents, pretend there is just a single page */
  if (!usedsc)
         { puts("This document does not conform to DSC") ;
           pages.numpages=1 ; }

  /* allocate memory for page information */
  if ((pages.pagepos=malloc((pages.numpages+1)*sizeof(long)))==NULL)
    leave(1,"Cannot allocate memory for page information",NULL) ;

  /* restart if we skipped to the end */
  if (trailer) {
    trailer = 0;
    fseek(psfile, 0L, SEEK_SET);
  }

  if (!usedsc)
  /* if it is not DSC, all is considered one page */
               { pages.pagepos[0]=0 ;
                 pages.pagepos[1]=LONG_MAX ; }
   else
     /* otherwise scan the file for %%Page comments */
     { for(p=0;p<pages.numpages+1;)
         {
           /* get current position */
           pos=ftell(psfile) ;

	   /* if we reach EOF, that's it */ 	
           if (fgets(buf,PSLINELEN,psfile)==NULL) break ;

           /* if we find %%Page, record current file position */
           if (iscomment(buf,"%%Page:")) {
#if 0
	     /* don't bother validating the page number */
	     /* we don't need it, so don't leave if it is invalid */
             if (sscanf(buf+length("%%Page:"), " %d",&i)!=1)
                 leave(1,"Incorrect format of the 'Page' comment",NULL) ;
#endif
             pages.pagepos[p++]=pos ;
	   }

           /* if we find %%Trailer or %%EOF it means we are done */
           /* ignore %%EOF because EPS included in our PS file may contain it */
           if (iscomment(buf,"%%Trailer") /* || iscomment(buf,"%%EOF") */)
              { pages.pagepos[p]=pos ; trailer=1 ;
                break ; }
         }


       /* just fill in the last entry if there was no trailer
          if there were more pages than announced, ignore the rest */
       if (p>pages.numpages)
               { puts("The file contains more pages than expected.") ;
                 puts("You will not be able to see them all.") ; }

         else if (!trailer) pages.pagepos[p]=LONG_MAX ;

     }

  puts("File processed succesfully") ;

  /* get temporary file name */
  tmpnam(tempname) ;
}


/* closepsfile performs clean up functions for this module, it closes files,
   removes temporary file, kills children and deallocates memory */

void closepsfile()
{
  /* we do not worry about errors here as we cannot do much about it */
  if (pages.pagepos!=NULL) free(pages.pagepos) ;
  if (psfile!=NULL) fclose(psfile) ;
  if (gsin!=-1) close(gsin) ;
  if (gsoutdesc!=-1) close(gsoutdesc) ;
  if (tempname) unlink(tempname) ;
  if (gspid>0 && waitpid(gspid,NULL,WNOHANG)==0) kill(gspid,SIGTERM) ;
  if (gswrite>0 && waitpid(gswrite,NULL,WNOHANG)==0) kill(gswrite,SIGTERM) ;
}



/* sendsection sends page number 'num' to file 'to'. If num=0 it means to send
   a header, and if num>pages.numpages it sends a trailer. It starts an
   alarm before writing every line out, so that in case of timeout a SIGALRM
   handler takes charge and we exit gracefully. LONG_MAX here stands for the
   end of the file
*/

#define	USE_FD	1

static void sendsection(int to, int num)
{
  char buf[INBUFSIZ] ; /* line buffer */
  /* last is the position after the last line we should copy */
  long last=num>pages.numpages ? LONG_MAX : pages.pagepos[num] ;
  long count;
#if USE_FD
  long pos;
  int psfd;
#endif

  /* if we are asked for a section begining at LONG_MAX, e.g. non-existend
     we return */
  if (num!=0 && pages.pagepos[num-1]==LONG_MAX) return ;

  /* otherwise set the initial position. Header (num=0) starts at position 0 */
#if USE_FD
  psfd = fileno(psfile);
  pos = (num==0 ? 0L : pages.pagepos[num-1]);
  if (lseek(psfd, pos, SEEK_SET) != pos)
      leave(1,"Failed to seek PS file",NULL) ;
#else
  if (fseek(psfile,num==0 ? 0L : pages.pagepos[num-1],SEEK_SET)!=0)
      leave(1,"Failed to seek PS file",NULL) ;
#endif


#if USE_FD
  while (pos < last)
#else
  for(;ftell(psfile)<last;)
#endif
  {
    /* read a line, use fread because the file may have nulls */
#if USE_FD
    count = last - pos;
    if (count > INBUFSIZ) count = INBUFSIZ;
    count = read(psfd, buf, count);
    pos += count;
#else
    count = last - ftell(psfile);
    if (count > INBUFSIZ) count = INBUFSIZ;
    count = fread(buf, 1, count, psfile);
#endif
    if (count <= 0) {
      /* we reached EOF. Is it OK? */
      if (last==LONG_MAX) break ;
        else leave(1,"Unexpected end of PS file "
                           "(while sending section to GhostScript)",NULL) ;
    }

    /* set timeout alarm end send line to GS */
    alarm(gstimeout) ;
    if (write(to, buf, count) < count)
      leave(1,"Failed to write to GhostScript",strerror(errno),NULL) ;
    /* switch the alarm off */
    alarm(0) ;
  }

  /* switch the alarm off */
  alarm(0) ;
}


/* displaypsfile is called from main to display a PS file
   It starts GhostScript in background, send a header to it and
   calls bkgdisplayfile that starts displaying and interaction with user
*/

void displaypsfile(const char *filename)
{
  int oldf ; /* used to store old file flags */
  char paper_option[ GSPAPERLEN ] ;	/* papersize option */

  /* Open and scan PS file */
  openpsfile(filename) ;

  /* Set up pipes */
  if (pipe(gspipein)!=0 || pipe(gspipeout)!=0)
    leave(1,"Cannot create pipe",strerror(errno),NULL) ;

  gsin = gspipein[1];

  /* Set output pipe as non blocking, so that we can read whatever GS
     sends us immediately */
  if ((oldf=fcntl(gspipeout[0],F_GETFL,0))==-1 ||
        fcntl(gspipeout[0],F_SETFL,oldf | O_NONBLOCK)==-1)
          leave(1,"Fcntl on GhostScript output failed",strerror(errno),NULL) ;

  /* Flush output buffers before forking */
  fflush(stdout); fflush(stderr);

  /* Create GhostScript process */
  gspid = fork();

  if (gspid < 0)
    leave(1,"Cannot fork",NULL) ;

  if (gspid==0) { /* Child - GS process */
           /* setup signal handlers */
           signal(SIGTERM,SIG_DFL) ;
           signal(SIGINT,siginthandler) ;

           /* display our intention */
           puts("Starting GhostScript...") ;

           /* redirect stdin, stdout to pipes */
           dup2(gspipein[0],STDIN_FILENO) ;
           dup2(gspipeout[1],STDOUT_FILENO) ;

           /* start GS - do not change the parameters unless you know
               what you are doing, it is not as simple as it may seem */

	   strcpy(paper_option, GSPAPER_PREFIX);
	   strncat(paper_option, gspaper, GSPAPERLEN - strlen(paper_option));
	   paper_option[ GSPAPERLEN - 1 ] = '\0';

           execl(gsname,	/* binary file name */
		  "gs",		/* gs own name again */
		  gsres,	/* resolution */
#ifdef GSDIR
		  gsincdir,	/* default dir */
#endif
#if 1
		  "-q",		/* quiet */
#endif
                  "-dNOPAUSE", /* disable prompting */
		  "-dNOGC",	/* disable garbage collection to run faster */
#if COLOUR
                  "-sDEVICE=ppmraw", /* output device */
#else
		  "-sDEVICE=pbmraw", /* output device */
#endif
		  paper_option,	/* set paper size */
                  "-sOutputFile=-", /* output to stdout please */
                  "-",     /* prevent GS from performing seeks on input */
                  NULL) ;

           /* If we fail to start GS, print out the reason and notify parent */
           printerr("Failed to start GhostScript") ;
           printerr(strerror(errno)) ;
           kill(getppid(),SIGTERM) ;
           exit(1) ;
                 }

  /* this is the parent process */

  /* set alarm handler for the purpose of timeout */
  signal(SIGALRM,sigalrmhandler) ;

  puts("Sending header to GhostScript") ;
  sendsection(gsin,0) ;

  /* call bkgdisplay file to do the interactive displaying */
  bkgdisplayfile(tempname) ;

  /* User wants us to quit, we try to tell it to GS gently.
     If he disobeys, we kill him in closepsfile */
  write(gsin," quit\n",6) ;

  /* We should perhaps also send a trailer to GS at some point
     but it did not seem necessary and it sometimes makes GS expect
     further input and we have to wait for timeout.
     But you can try:
     sendsection(gsin,pages.numpages+1) ; */

  /* we do not need alarm any more */
  signal(SIGALRM,SIG_IGN) ;

  /* do the cleanup and return */
  closepsfile() ;
}



/* makegsdisplay makes GS display page number 'num'. It catches GS output
   from pipe and filters out the initial rubbish ( unfortunately we cannot
   switch it off with -q, because then if GS wants to tell something, like
   'substituting with Ugly', it exits with a cryptic message (Try it))
   The filtering works well unless you deliberately fool it.
   The raw PBM image is written to a temp file and every once a while
   we check if the file is complete. If so, we are done.
   A child process is created to send data to GS. */

void makegsdisplay(int num)
{ int status ;
  int ok;
  printf("Asking GhostScript to display page number %d\n",num) ;

  /* Flush output buffers before forking */
  fflush(stdout); fflush(stderr);

  /* remove temporary file from the last go */
  unlink(tempname) ;

  gswrite = fork();

  if (gswrite < 0)
     leave(1,"Cannot fork",NULL) ;

  if (gswrite)
       /* This is a parent */
     { fd_set f ; struct timeval t ; /* for select */
       char buf[INBUFSIZ+1],*ptr ; /* input buffer and pointer to it */
       size_t numb ; /* number of bytes read */
       int pbmstarted=0 ; /* has the graphics started already ? */

       /* read until the PBM file is complete */
       ok = 1;
       while (ok) {

         /* open temporary file for appending */
         if ((gsoutdesc=open(tempname,O_CREAT | O_WRONLY | O_APPEND,0600))==-1)
            leave(1,"Cannot open temporary file for writing",
                     strerror(errno),NULL) ;

         /* wait efficiently until GS sends something or timeout */
         FD_ZERO(&f) ; FD_SET(gspipeout[0],&f) ;
         t.tv_sec=gstimeout ;
         t.tv_usec=0 ;
         if (select(FD_SETSIZE,&f,NULL,NULL,(gstimeout>0?&t:NULL))==0)
           leave(1,"GhostScript did not respond within timeout",NULL) ;

         /* read as much as possible but at most INBUFSIZ */

         numb = read(gspipeout[0],buf,INBUFSIZ);

         if (numb == -1) {
          /* pipe is non blocking so EAGAIN can happen */
          if (errno==EAGAIN) continue ;
           else
             leave(1,"Failed to read from GhostScript",strerror(errno),NULL) ;
	 }

         /* If nothing was read for some reason, try again */
         if (numb==0) continue ;


         /* If graphics data has not started yet, skip the initial bit
            until P4\n, which is the proper magic ident of rawPBM */

         ptr=buf ;
         if (!pbmstarted)
           { /* we do strstr here, assuming that GS sends no NULLs */
             if (numb > INBUFSIZ) numb = INBUFSIZ;
             buf[ numb ] = '\0';
             for (ptr = buf; ptr[0] != '\0'; ptr++) {
	       if (ptr[0] == 'P' &&
	           (ptr[1] == PBMRAW_MAGIC || ptr[1] == PGMRAW_MAGIC ||
	            ptr[1] == PPMRAW_MAGIC) &&
	           ptr[2] == '\n') {
		 break;
	       }
	       if ((ptr[0] == 'E' || ptr[0] == 'e') &&
	           strncmp(ptr+1, "rror", 4) == 0) {
		 ptr = &buf[ numb ];	/* show all output in buffer */
		 ok = 0;
		 break;
	       }
	     }
             if (*ptr == '\0') {
               /* copy the message on stdout */
               printf("%.*s", (int) numb, buf) ;
               if (!ok)
		 leave(1, "PostScript errors", NULL) ;
               continue ;
	     }
              else
               /* copy message on stdout and set flag that PBM started */
               { printf("%.*s", (int)(ptr-buf), buf) ; pbmstarted=1 ; }
           }

         /* write to temporary file */
         if (write(gsoutdesc,ptr,numb)!=numb)
           leave(1,"Failed to write to temporary file",strerror(errno),NULL) ;

         /* close temporary file - Maybe it is not necessary, but it seemed
            that other processes could not determine the size reliably
            if I did not close it */

         close(gsoutdesc) ;

         /* Ask openpbm to check for us, if the file is complete */
         testpbm=1 ;
	 openpbm(tempname) ;
         if (testpbm)
           /* yes, the file is complete */
           { testpbm=0 ; break ; }
         } /* end of for loop */
     }
   else {

      /* This is a child - it sends the proper source text for desired
         page to GS */
      puts("Writing process started") ;

      /* set up signals, so we can be killed silently */
      signal(SIGTERM,SIG_DFL) ;
      signal(SIGINT,siginthandler) ;
      signal(SIGALRM,sigalrmhandler) ;

      /* send data */	
      sendsection(gsin,num) ;

      /* ask GS to flush its internal buffers
          - this is tricky, but I could not find any other way to do it
            and it works unless you do some evil PostScript spells */
            	
      write(gsin, "flush\n", 6) ;
      puts("Writing process finished") ;
      exit(0) ; }    /* end exit */


  /* we say Waiting... but we just check and kill the child if it is
     still alive */
  puts("Waiting for the writing process to finish.") ;
  if (waitpid(gswrite,&status,WNOHANG)!=gswrite) kill(gswrite,SIGTERM) ;
   else
     if (!WIFEXITED(status) || WEXITSTATUS(status)!=0)
       leave(1,"Writing process finished prematurely",NULL) ;
}


/* sigalrmhandler catches SIGALRM caused by timeout for GS */

void sigalrmhandler(int sig)
{ printerr("GhostScript did not respond within timeout") ;

  if (gswrite)
        /* if I am the parrent,leave straight away */
        leave(1,NULL) ;
   else /* if I am gswrite process - kill parent */
        kill(getppid(),SIGINT) ;
  pause() ;
}

/* ************* end of gsinterf.c ************* */