/*
 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 ************* */
