[comp.sources.x] v09i078: XV -- successor to XGIF, Part01/01

bradley@grip.cis.upenn.edu (John Bradley) (10/11/90)

Submitted-by: bradley@grip.cis.upenn.edu (John Bradley)
Posting-number: Volume 9, Issue 78
Archive-name: xv/part01


-----------------------(cut here)------------------
#!/bin/sh
# to extract, remove the header and type "sh filename"
if `test ! -s ./xvdir.c`
then
echo "writting ./xvdir.c"
cat > ./xvdir.c << '\BARFOO\'
/* 
 * xvdir.c - Directory changin', file i/o dialog box
 *
 * callable functions:
 *
 *   CreateDirW(geom,bwidth)-  creates the dirW window.  Doesn't map it.
 *   DirBox(vis)            -  random processing based on value of 'vis'
 *                             maps/unmaps window, etc.
 *   RedrawDirW(x,y,w,h)    -  called by 'expose' events
 *   ClickDirW()            -  handles mouse clicks in DirW
 *   LoadCurrentDirectory() -  loads up current dir information for dirW
 *   DoSave()               -  calls appropriate save routines
 */

/*
 * Copyright 1989, 1990 by the University of Pennsylvania
 *
 * Permission to use, copy, and distribute for non-commercial purposes,
 * is hereby granted without fee, providing that the above copyright
 * notice appear in all copies and that both the copyright notice and this
 * permission notice appear in supporting documentation.
 *
 * The software may be modified for your own purposes, but modified versions
 * may not be distributed.
 *
 * This software is provided "as is" without any express or implied warranty.
 */


#define NEEDSDIR
#include "xv.h"


#define NLINES 9                   /* # of lines in list control (keep odd) */
#define LISTW  200

#define BUTTW   60
#define BUTTH   19
#define DDWIDE  LISTW-80+15

#define MAXDEEP 30    /* maximum number of directories in cwd path */
#define MAXFNLEN 40   /* max length of filename being entered */

#define DEFFILENAME ""   /* default filename filled in when program starts */

#ifdef __STDC__
static void RedrawDList(void);
static int  dnamcmp(char **, char **);
#else
static void RedrawDList();
static int  dnamcmp();
#endif

static int    listh;
static char  *dirnames[MAXNAMES];
static int    numdirnames = 0, ndirs = 0;
static char   path[MAXPATHLEN+1];
static char  *dirs[MAXDEEP];            /* list of directory names */
static char  *lastdir;                  /* name of the directory we're in */
static char   filename[MAXFNLEN];       /* filename being entered */
static RBUTT *formatRB, *colorRB, *sizeRB;


/***************************************************/
void CreateDirW(geom)
char *geom;
{
  int y;

  strcpy(filename,DEFFILENAME);
  listh = LINEHIGH * NLINES;

  dirW = CreateWindow("xv save dialog",geom,DIRWIDE, DIRHIGH, infofg, infobg);
  if (!dirW) FatalError("couldn't create 'save' window!");

  /* create doo-wah's */
  ddirW = XCreateSimpleWindow(theDisp, dirW, 40, 5, DDWIDE, LINEHIGH,
			      2, infofg, infobg);
  if (!ddirW) FatalError("can't create path window");
  XSelectInput(theDisp, ddirW, ExposureMask | ButtonPressMask);

  dnamW = XCreateSimpleWindow(theDisp, dirW, 80, listh+75-ASCENT-4, 
			      200, LINEHIGH+4, 1, infofg, infobg);
  if (!dnamW) FatalError("can't create name window");
  XSelectInput(theDisp, dnamW, ExposureMask);


  LSCreate(&dList, dirW, 10, 14+LINEHIGH, LISTW, listh, NLINES,
	   dirnames, numdirnames,
	   infofg, infobg, RedrawDList, 1, 0);

  BTCreate(&dbut[S_BOPEN], dirW, 233, dList.y-9+listh/5, 60, BUTTH, 
	   "Open", infofg, infobg);
  BTCreate(&dbut[S_BSAVE], dirW, 233, dList.y-9+(listh*2)/5, 60, BUTTH, 
	   "Save", infofg, infobg);
  BTCreate(&dbut[S_BCANC], dirW, 233, dList.y-9+(listh*3)/5, 60, BUTTH, 
	   "Cancel", infofg, infobg);
  BTCreate(&dbut[S_BQUIT], dirW, 233, dList.y-9+(listh*4)/5, 60, BUTTH, 
	   "Quit", infofg, infobg);

  y = listh + 110;
  formatRB = RBCreate(NULL, dirW, 26, y, "GIF", infofg, infobg);
  RBCreate(formatRB, dirW, 26, y+18, "PM", infofg, infobg);
  RBCreate(formatRB, dirW, 26, y+36, "PBM (raw)", infofg, infobg);
  RBCreate(formatRB, dirW, 26, y+54, "PBM (ascii)", infofg, infobg);
  RBCreate(formatRB, dirW, 26, y+72, "X11 Bitmap", infofg, infobg);

  colorRB = RBCreate(NULL, dirW, DIRWIDE/2, y, "Full Color", infofg, infobg);
  RBCreate(colorRB, dirW, DIRWIDE/2, y+18, "Greyscale", infofg, infobg);
  RBCreate(colorRB, dirW, DIRWIDE/2, y+36, "B/W Dithered", infofg, infobg);

  y = y + 115;
  sizeRB = RBCreate(NULL, dirW, 26, y, "Normal Size", infofg, infobg);
  RBCreate(sizeRB, dirW, 26, y+18, "At Current Expansion", infofg, infobg);

  if (!strlen(filename)) BTSetActive(&dbut[S_BSAVE],0);

  LoadCurrentDirectory();

  XMapSubwindows(theDisp, dirW);
}
  

/***************************************************/
void DirBox(vis)
int vis;
{
  if (vis) XMapRaised(theDisp, dirW);
  else     XUnmapWindow(theDisp, dirW);

  BTSetActive(&but[BSAVE], !vis);

  dirUp = vis;
}


/***************************************************/
void RedrawDirW(x,y,w,h)
int x,y,w,h;
{
  int  i,ypos;
  char foo[30];
  XRectangle xr;

  xr.x = x;  xr.y = y;  xr.width = w;  xr.height = h;
  XSetClipRectangles(theDisp, theGC, 0,0, &xr, 1, Unsorted);

  if (dList.nstr==1) strcpy(foo,"1 file");
                else sprintf(foo,"%d files",dList.nstr);

  ypos = dList.y + dList.h + 5 + ASCENT;
  XSetForeground(theDisp, theGC, infobg);
  XFillRectangle(theDisp, dirW, theGC, 10, ypos-ASCENT, DIRWIDE, CHIGH);
  XSetForeground(theDisp, theGC, infofg);
  XDrawString(theDisp, dirW, theGC, 10, ypos, foo, strlen(foo));

  XDrawString(theDisp, dirW, theGC, 10, dList.h+75, "File name:",10);

  for (i=0; i<S_NBUTTS; i++) BTRedraw(&dbut[i]);

  RBRedraw(formatRB, -1);
  RBRedraw(colorRB, -1);
  RBRedraw(sizeRB, -1);

  ULineString(dirW, "Format", formatRB->x-16, formatRB->y-3-DESCENT);
  ULineString(dirW, "Colors", colorRB->x-16,  colorRB->y-3-DESCENT);
  ULineString(dirW, "Size",   sizeRB->x-16,   sizeRB->y-3-DESCENT);

  XSetClipMask(theDisp, theGC, None);
}


/***************************************************/
void RedrawDDirW()
{
  XSetForeground(theDisp, theGC, infofg);
  XSetBackground(theDisp, theGC, infobg);

  XClearWindow(theDisp, ddirW);
  XDrawString(theDisp, ddirW, theGC, 3, ASCENT + 1,
              lastdir, strlen(lastdir));
}


/***************************************************/
int ClickDirW(x,y)
int x,y;
{
  BUTT  *bp;
  int    bnum;


  /* check the RBUTTS first, since they don't DO anything */
  if ( (bnum=RBClick(formatRB, x,y)) >= 0) { 
    RBTrack(formatRB, bnum);
    if (RBWhich(formatRB)==4) {  /* turn off FULLCOLOR + GRAYSCALE */
      RBSetActive(colorRB,0,0);
      RBSetActive(colorRB,1,0);
      RBSelect(colorRB,2);
    }
    else {                       /* turn on FULLCOLOR + GRAYSCALE */
      RBSetActive(colorRB,0,1);
      RBSetActive(colorRB,1,1);
    }
    return -1;
  }

  if ( (bnum=RBClick(colorRB, x,y)) >= 0) 
    { RBTrack(colorRB, bnum);  return -1; }

  if ( (bnum=RBClick(sizeRB, x,y)) >= 0) 
    { RBTrack(sizeRB, bnum);  return -1; }

  for (bnum=0; bnum<S_NBUTTS; bnum++) {
    bp = &dbut[bnum];
    if (PTINRECT(x, y, bp->x, bp->y, bp->w, bp->h)) break;
  }

  if (bnum<S_NBUTTS) {   /* found one */
    if (BTTrack(bp)) return (bnum);
  }

  return -1;
}


/***************************************************/
void SelectDir(n)
int n;
{
  int pend;

  /* called when entry #n in the dir list was selected/double-clicked */

  if (dList.str[n][0] == C_DIR || 
      dList.str[n][0] == C_LNK) {  /* it's cool, it's (possibly) a directory */
    pend = strlen(path);
    strcat(path,dList.str[n]+1);   /* add to pathname */
    if (chdir(path)) {
      fprintf(stderr,"unable to cd to '%s'\n",path);
      path[pend] = '\0';           /* undo path modification */
    }
    else 
      LoadCurrentDirectory();
  }

  else {  /* not a directory */
    XBell(theDisp,0);
  }
}


/***************************************************/
void TrackDDirW(x,y)
int x,y;
{
  Window        menuW, rW, cW;
  int           rx, ry, i,j, sel, lastsel;
  unsigned int  mask;

  XSetForeground(theDisp, theGC, infofg);
  XSetBackground(theDisp, theGC, infobg);

  menuW = XCreateSimpleWindow(theDisp, dirW, 40, 5, DDWIDE, ndirs*LINEHIGH,
			      2, infofg, infobg);
  if (!menuW) FatalError("can't create path window");

  XMapRaised(theDisp, menuW);

  for (i=ndirs-1, j=0; i>=0; i--,j++)
    XDrawString(theDisp, menuW, theGC, 3, j*LINEHIGH + ASCENT + 1,
		dirs[i], dirs[i+1]-dirs[i]);

  XFlush(theDisp);
  XSetFunction(theDisp, theGC, GXinvert);
  XSetPlaneMask(theDisp, theGC, infofg ^ infobg);
  lastsel = -1;  sel = 0;

  while (XQueryPointer(theDisp, menuW, &rW, &cW, &rx, &ry, &x, &y, &mask)) {
    if (!(mask & Button1Mask)) break;

    /* see if mouse has left window */

    sel = y / LINEHIGH;
    if (sel>=ndirs) sel = ndirs-1;
    if (sel<0) sel = 0;
    if (sel != lastsel) {
      XFillRectangle(theDisp,menuW,theGC,0,lastsel*LINEHIGH,DDWIDE,LINEHIGH);
      XFillRectangle(theDisp,menuW,theGC,0,sel*LINEHIGH,DDWIDE,LINEHIGH);
      lastsel = sel;
    }
  }

  XSetFunction(theDisp, theGC, GXcopy);
  XSetPlaneMask(theDisp, theGC, AllPlanes);
  XDestroyWindow(theDisp, menuW);

  if (sel!=0) { /* changed directories */
    /* end 'path' by changing trailing '/' (of dir name) to a '\0' */
    *(dirs[(ndirs-1)-sel + 1] - 1) = '\0';

    /* special case:  if cd to '/', fix path (it's currently "") */
    if (path[0] == '\0') strcpy(path,"/");

    if (chdir(path)) {
      fprintf(stderr,"unable to cd to '%s'\n",path);
    }
    else 
      LoadCurrentDirectory();   
  }
}


/***************************************************/
static void RedrawDList()
{
  LSRedraw(&dList);
}


/***************************************************/
void LoadCurrentDirectory()
{
  DIR           *dirp;
#ifdef DIRENT
  struct dirent *dp;
#else
  struct direct *dp;
#endif
  int            i, ftype;
  struct stat    st;
  char          *dbeg, *dend;

  /* get rid of previous file names */
  for (i=0; i<numdirnames; i++) free(dirnames[i]);

  numdirnames = 0;

  getwd(path);
  if (path[strlen(path)-1] != '/')
    strcat(path,"/");   /* tack on a trailing '/' to make path consistent */

  /* path will be something like: "/u3/bradley/src/weiner/whatever/" */
  /* parse path into individual directory names */
  dbeg = dend = path;
  for (i=0; i<MAXDEEP && dend; i++) {
    dend = strchr(dbeg,'/');  /* find next '/' char */
    dirs[i] = dbeg;
    dbeg = dend+1;
  }
  ndirs = i-1;

  lastdir = dirs[ndirs-1];
  RedrawDDirW();

  dirp = opendir(".");
  if (!dirp) {
    fprintf(stderr,"unable to open current directory");
    return;
  }

  i=0;
  while ( (dp = readdir(dirp)) != NULL) {
    if (strcmp(dp->d_name, ".")==0 || strcmp(dp->d_name, "..")==0) {
      /* skip over '.' and '..' */
    }
    else {
      dirnames[i] = (char *) malloc(dp->d_namlen + 2); /* +2=filetype + '\0'*/
      if (!dirnames[i]) FatalError("malloc error while reading directory");
      strcpy(dirnames[i]+1, dp->d_name);

      /* figure out what type of file the beastie is */
      dirnames[i][0] = C_REG;   /* default to normal file, if lstat fails */

      if (lstat(dirnames[i]+1, &st)==0) {
	ftype = st.st_mode & S_IFMT;   /* mask off uninteresting bits */
	if      (ftype == S_IFIFO)  dirnames[i][0] = C_FIFO;
	else if (ftype == S_IFCHR)  dirnames[i][0] = C_CHR;
	else if (ftype == S_IFDIR)  dirnames[i][0] = C_DIR;
	else if (ftype == S_IFBLK)  dirnames[i][0] = C_BLK;
	else if (ftype == S_IFLNK)  dirnames[i][0] = C_LNK;
	else if (ftype == S_IFSOCK) dirnames[i][0] = C_SOCK;
      }
      else {
	/* fprintf(stderr,"problems 'stat-ing' files\n");*/
	dirnames[i][0] = C_REG;
      }
      i++;
    }
  }

  closedir(dirp);

  numdirnames = i;

  qsort((char *) dirnames, numdirnames, sizeof(char *), dnamcmp);
  LSNewData(&dList, dirnames, numdirnames);
  DirOpenActive();
  RedrawDirW(0,0,DIRWIDE,DIRHIGH);
}


/***************************************************/
static int dnamcmp(s1,s2)
char **s1, **s2;
{
  /* sort so that directories are at beginning of list */

  /* if both dirs or both not dirs, sort on name */
  if ( (**s1 == C_DIR && **s2 == C_DIR) || (**s1 != C_DIR && **s2 != C_DIR))
    return (strcmp((*s1)+1, (*s2)+1));

  else if (**s1==C_DIR) return -1;  /* s1 is first */
  else return 1;                    /* s2 is first */
}





/***************************************************/
int DirKey(c)
int c;
{
  /* got keypress in dirW.  stick on end of filename */
  int len;

  len = strlen(filename);
  
  if (c>' ' && c<'\177') {              /* printable characters */
    if (c=='/') return(-1);             /* no directories in filename */
    if (len >= MAXFNLEN-1) return(-1);  /* max length of string */
    filename[len]=c;  filename[len+1]='\0';
  }

  else if (c=='\010' || c=='\177') {    /* BS or DEL */
    if (len==0) return(-1);             /* string already empty */
    filename[len-1]='\0';
  }

  else if (c=='\025' || c=='\013') {    /* ^U or ^K clear line */
    filename[0] = '\0';
  }

  else if (c=='\012' || c=='\015') {    /* CR or LF */
    FakeButtonPress(&dbut[S_BSAVE]);
  }

  else return(-1);                      /* unhandled character */

  XClearWindow(theDisp, dnamW);
  RedrawDNamW();

  BTSetActive(&dbut[S_BSAVE], strlen(filename)!=0 );
  return(0);
}


/***************************************************/
void RedrawDNamW()
{
  int width, len;

  len = strlen(filename);
  XSetForeground(theDisp, theGC, infofg);
  XDrawString(theDisp, dnamW, theGC, 3, ASCENT+3, filename, len);
  width = StringWidth(filename);
  XDrawLine(theDisp, dnamW, theGC, 3+width+1, 3, 3+width+1, 
	    3+CHIGH);
}


/***************************************************/
void DirOpenActive()
{
  if (dList.selected>=dList.nstr || dList.selected<0) 
    BTSetActive(&dbut[S_BOPEN],0);

  else if (dList.str[dList.selected][0] == C_DIR ||
      dList.str[dList.selected][0] == C_LNK) 
    BTSetActive(&dbut[S_BOPEN],1);

  else
    BTSetActive(&dbut[S_BOPEN],0);

  XFlush(theDisp);
}



/***************************************************/
int DoSave()
{
  FILE *fp;
  byte *thepic, *bwpic;
  int   w,h,rv,i;

  /* opens file, does appropriate color pre-processing, calls save routine
     based on chosen format.  Returns '0' if successful */

  bwpic = NULL;

  if (RBWhich(sizeRB)==1) { thepic = epic;  w = eWIDE;  h = eHIGH; }
                     else { thepic = cpic;  w = cWIDE;  h = cHIGH; }

  if (RBWhich(colorRB)==2) {
    /* generate a FSDithered 1-byte per pixel image */
    bwpic = (byte *) malloc(w*h);
    if (!bwpic) FatalError("unable to malloc dithered picture (DoSave)");
    FSDither(thepic, w, h, bwpic);
    thepic = bwpic;
  }

  /* open file */
  fp = fopen(filename, "w");
  if (!fp) {
    SetISTR(ISTR_INFO,"Can't create '%s' -  %s",filename,sys_errlist[errno]);
    Warning();
    if (bwpic) free(bwpic);
    return -1;
  }

  if ((mono || ncols==0) && RBWhich(colorRB)==0) {
    /* if we're saving color, but we're viewing B/W we have to NOT do
       the 'monofication' of the colormap ... */
    for (i=0; i<numcols; i++) {
      r[i] = rorg[i];  g[i] = gorg[i];  b[i] = borg[i];  /* original */
      
      if (revvideo) {
	r[i] = 255-r[i];  g[i] = 255-g[i];  b[i] = 255-b[i];
      }
   } 

    GammifyColors();
  }
      
      
  i = RBWhich(formatRB);
  switch (i) {
  case 0:  rv = WriteGIF(fp,thepic,w, h, r, g, b, numcols, RBWhich(colorRB));
           break;
  case 1:  rv = WritePM (fp,thepic,w, h, r, g, b, numcols, RBWhich(colorRB)); 
           break;
  case 2:  rv = WritePBM(fp,thepic,w, h, r, g, b, numcols, RBWhich(colorRB),1);
           break;
  case 3:  rv = WritePBM(fp,thepic,w, h, r, g, b, numcols, RBWhich(colorRB),0);
           break;
  case 4:  rv = WriteXBM(fp,thepic,w, h, filename);
           break;
  }

  fclose(fp);
  if (rv) unlink(filename);   /* couldn't properly write file:  delete it */

  if (!rv) {
    SetISTR(ISTR_INFO,"Successfully wrote '%s'",filename);
    LoadCurrentDirectory();   /* wrote file: rescan directory */
  }

  if (bwpic) free(bwpic);

  if ((mono || ncols==0) && RBWhich(colorRB)==0) {
    /* restore normal colormap */
    DoMonoAndRV();
    GammifyColors();
  }

  return rv;
}



\BARFOO\
else
  echo "will not over write ./xvdir.c"
fi
if `test ! -s ./xvfish.c`
then
echo "writting ./xvfish.c"
cat > ./xvfish.c << '\BARFOO\'
/*
 * xvfish.c  -  the required-by-law 'fish' portion of 'xv' 
 *
 * StartFish();
 * StopFish();
 */

/*
 * Copyright 1989, 1990 by the University of Pennsylvania
 *
 * Permission to use, copy, and distribute for non-commercial purposes,
 * is hereby granted without fee, providing that the above copyright
 * notice appear in all copies and that both the copyright notice and this
 * permission notice appear in supporting documentation.
 *
 * The software may be modified for your own purposes, but modified versions
 * may not be distributed.
 *
 * This software is provided "as is" without any express or implied warranty.
 */


#define DELAY 200000L   /* delay between fish increments, in microseconds */
#define NEEDSTIME

#include "xv.h"
     
/* size of fish */
#define fwide 32
#define fhigh 16
     

static char lfish_bits[] = {
   0x00, 0xc0, 0x07, 0x00, 0x00, 0xb0, 0x06, 0x00, 0x80, 0x7f, 0x03, 0xe0,
   0x60, 0x82, 0x03, 0xb0, 0x18, 0x00, 0x0c, 0x68, 0x64, 0x02, 0xf0, 0x37,
   0x62, 0x00, 0x00, 0x28, 0x01, 0xaa, 0xaa, 0x36, 0x46, 0x00, 0x00, 0x28,
   0x38, 0x03, 0xc0, 0x5f, 0xb0, 0x28, 0x30, 0xb0, 0xc0, 0x39, 0x0e, 0xe0,
   0x00, 0xee, 0x01, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00,
   0x00, 0xc0, 0x00, 0x00};
     
static char rfish_bits[] = {
   0x00, 0xe0, 0x03, 0x00, 0x00, 0x60, 0x0d, 0x00, 0x07, 0xc0, 0xfe, 0x01,
   0x0d, 0xc0, 0x41, 0x06, 0x12, 0x30, 0x00, 0x18, 0xec, 0x0f, 0x40, 0x26,
   0x14, 0x00, 0x00, 0x46, 0xac, 0xaa, 0x4a, 0x80, 0x14, 0x00, 0x00, 0x62,
   0xfa, 0x03, 0xc0, 0x1c, 0x0d, 0x0c, 0x14, 0x0d, 0x07, 0x70, 0x9c, 0x03,
   0x00, 0x80, 0x77, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x05, 0x00,
   0x00, 0x00, 0x03, 0x00};
     
     
typedef struct fishstr { short x,y,dx,dy; } FISH;
     

#define MAXFISH 100
FISH fishdat[MAXFISH];

Pixmap lfishP, rfishP;
int numfish=7;
int w,h;
static int firsttime=1;


static void dofish(), setfishtimer();

     
/**************/
StartFish()
/**************/
{
  int i;

  if (!fish) return;
  if (useroot || fishrunning || !mainW) return;
  w = eWIDE;  h = eHIGH;

  if (firsttime) {
    lfishP=XCreateBitmapFromData(theDisp,mainW,lfish_bits,fwide,fhigh);
    rfishP=XCreateBitmapFromData(theDisp,mainW,rfish_bits,fwide,fhigh);

    for (i=0; i<numfish; i++) {
      fishdat[i].x  = rand()%w;
      fishdat[i].y  = rand()%h;
      fishdat[i].dx = (abs(rand()%3)+4);
      
      if (rand()&0x10) fishdat[i].dx = -fishdat[i].dx;
     
      fishdat[i].dy=rand()%7-3;  if (fishdat[i].dy==0) fishdat[i].dy=1;
    }
    firsttime = 0;
  }

  fishrunning = 1;
  setfishtimer();
}   


/**************/
StopFish()
/**************/
{
  struct itimerval it;

  if (!fish) return;
  if (!fishrunning) return;
     
  sigblock(sigmask(SIGALRM));
  bzero(&it, sizeof(it));
  it.it_interval.tv_usec = 0L;
  it.it_value.tv_usec = 0L;

  setitimer(ITIMER_REAL, &it, (struct itimerval *)0);
  signal(SIGALRM,SIG_DFL);
  sigblock(0);
  fishrunning = 0;
}



/*******************************/
static void dofish()
{
  int i;
  FISH *fp;

  XSetForeground(theDisp, theGC, infofg);
  XSetBackground(theDisp, theGC, infobg);

  for (i=0; i<numfish; i++) {
    fp = &fishdat[i];    
    XClearArea(theDisp, mainW, fp->x, fp->y, fwide, fhigh, True);

    fp->x += fp->dx;
    fp->y += fp->dy;
    if (fp->x < -50)    fp->dx = abs(fp->dx);
    if (fp->x > (w+50)) fp->dx = -abs(fp->dx);

    if (fp->y < 10)     fp->dy = abs(fp->dy);
    if (fp->y > (h-20)) fp->dy = -abs(fp->dy);
     
    if (fp->dx<0)
      XCopyPlane(theDisp,lfishP,mainW,theGC,0,0,fwide,fhigh,fp->x,fp->y,1L);
    else
      XCopyPlane(theDisp,rfishP,mainW,theGC,0,0,fwide,fhigh,fp->x,fp->y,1L);
  }

  XFlush(theDisp);
  setfishtimer();
}
     

     
     
/*******/
static void setfishtimer()
/*******/
{
  struct itimerval it;
     
  bzero(&it, sizeof(it));
  it.it_value.tv_usec = DELAY;

  signal(SIGALRM,dofish);
  sigsetmask(0);
  setitimer(ITIMER_REAL, &it, (struct itimerval *)0);
}






\BARFOO\
else
  echo "will not over write ./xvfish.c"
fi
if `test ! -s ./xvgam.c`
then
echo "writting ./xvgam.c"
cat > ./xvgam.c << '\BARFOO\'
/* 
 * xvgam.c - Gamma Correction box handling functions
 *
 * callable functions:
 *
 *   CreateGam(geom)        -  creates the ctrlW window.  Doesn't map it.
 *   GamBox(vis)            -  random processing based on value of 'vis'
 *                             maps/unmaps window, etc.
 *   RedrawGam(x,y,w,h)     -  called by 'expose' events
 *   RedrawGraph(x,y,w,h)   -  called by 'expose' events
 *   ClickGam(x,y)          -  called when B1 clicked in gamW 
 *   TrackGraph(x,y)        -  called when B1 clicked in graphW
 *   GenerateGamma()        -  called to generate/error-check 'ghand'
 *   GenerateFSGamma()      -  called to generate floyd steinberg correction
 *   GammifyColors()        -  does gamma correction of r[],g[],b[] arrays
 *   SetGPreset()           -  sets preset #n to supplied values
 */

/*
 * Copyright 1989, 1990 by the University of Pennsylvania
 *
 * Permission to use, copy, and distribute for non-commercial purposes,
 * is hereby granted without fee, providing that the above copyright
 * notice appear in all copies and that both the copyright notice and this
 * permission notice appear in supporting documentation.
 *
 * The software may be modified for your own purposes, but modified versions
 * may not be distributed.
 *
 * This software is provided "as is" without any express or implied warranty.
 */


#include "xv.h"

#define MAXUNDO 8

#define BUTTW   80
#define BUTTW2 100
#define BUTTH   19

#define LINESTR "Lines"
#define CURVSTR "Spline"
#define HSVSTR  "HSV Mode"
#define RGBSTR  "RGB Mode"


XPoint presets[4][NUMHANDS];
XPoint undo[MAXUNDO][NUMHANDS];
XPoint defgam[NUMHANDS];
static int firsttime=1;


#ifdef __STDC__
static void DrawGVals(void);
static void DoGamCommand(int);
static void DoGammaApply(int);
static void SaveUndoState(void);
static void HSVgamma(void);
static void spline(int *, int *, int, float *);
#else
static void DoGamCommand(), DoGammaApply(), HSVgamma(), spline();
static void DrawGVals(), SaveUndoState();
#endif


/***************************************************/
void CreateGam(geom)
char *geom;
{
  int i,ptop;

  gamW = CreateWindow("xv gamma", geom, GAMWIDE,GAMHIGH,infofg,infobg);
  if (!gamW) FatalError("can't create gamma window!");

  graphW = XCreateSimpleWindow(theDisp,gamW, 10,40, 256,256, 1, infofg,infobg);
  if (!graphW) FatalError("can't create graph window!");
  XSelectInput(theDisp, graphW, ExposureMask | ButtonPressMask);

  /* call CreateCtrl first to create grayTile */
  XSetWindowBackgroundPixmap(theDisp, gamW, grayTile);

  BTCreate(&gbut[G_BUP_BR], gamW, 276, 40,
	   BUTTW, BUTTH, "Brighter", infofg, infobg);
  BTCreate(&gbut[G_BDN_BR], gamW, 276, 40 + BUTTH + 4,
	   BUTTW, BUTTH, "Dimmer", infofg, infobg);
  BTCreate(&gbut[G_BUP_CN], gamW, 276, 40 + 2*BUTTH + 8 + 16,
	   BUTTW, BUTTH, "Sharper", infofg, infobg);
  BTCreate(&gbut[G_BDN_CN], gamW, 276, 40 + 3*BUTTH+12 + 16,
	   BUTTW, BUTTH, "Duller", infofg, infobg);

  BTCreate(&gbut[G_BHSVRGB], gamW, 276, 40 + 4*BUTTH+16+32,
	   BUTTW, BUTTH, HSVSTR, infofg, infobg);

  BTCreate(&gbut[G_B1], gamW, 276, 40 + 5*BUTTH+20+48,
	   17, BUTTH, "1", infofg, infobg);
  BTCreate(&gbut[G_B2], gamW, 276 + ((BUTTW-17)*1)/3, 40 + 5*BUTTH+20+48,
	   17, BUTTH, "2", infofg, infobg);
  BTCreate(&gbut[G_B3], gamW, 276 + ((BUTTW-17)*2)/3, 40 + 5*BUTTH+20+48,
	   17, BUTTH, "3", infofg, infobg);
  BTCreate(&gbut[G_B4], gamW, 276 + ((BUTTW-17)*3/3), 40 + 5*BUTTH+20+48,
	   17, BUTTH, "4", infofg, infobg);

  BTCreate(&gbut[G_BSET], gamW, 276, 40 + 6*BUTTH+24+48,
	   38, BUTTH, "Set", infofg, infobg);
  gbut[G_BSET].toggle = 1;

  BTCreate(&gbut[G_BUNDO], gamW, 276 + 42, 40 + 6*BUTTH+24+48,
	   38, BUTTH, "Undo", infofg, infobg);

  ptop = GAMHIGH - (2*BUTTH + 3*8);
  BTCreate(&gbut[G_BAPPLY], gamW, 10, ptop+8, BUTTW2, BUTTH, 
	   "Apply", infofg, infobg);
  BTCreate(&gbut[G_BNOGAM],  gamW, 10, ptop + BUTTH + 2*8, BUTTW2, BUTTH,
	   "No Gamma", infofg, infobg);

  BTCreate(&gbut[G_BRESET], gamW, 10+(GAMWIDE-20-BUTTW2)/2, ptop+8, 
	   BUTTW2, BUTTH, "Linear", infofg, infobg);
  BTCreate(&gbut[G_BDEF],  gamW, 10+(GAMWIDE-20-BUTTW2)/2, ptop + BUTTH + 2*8,
	   BUTTW2, BUTTH, "Default", infofg, infobg);

  BTCreate(&gbut[G_BGTYPE], gamW, 10+(2*(GAMWIDE-20-BUTTW2))/2, ptop+8, 
	   BUTTW2, BUTTH, CURVSTR, infofg, infobg);
  BTCreate(&gbut[G_BCLOSE],gamW, 10+(2*(GAMWIDE-20-BUTTW2))/2, ptop+BUTTH+2*8,
	   BUTTW2, BUTTH, "Close", infofg, infobg);

  XMapSubwindows(theDisp, gamW);

  /* fill up the undo stack */
  for (i=0; i<MAXUNDO; i++)
    memcpy(undo[i], ghand, sizeof(ghand));
}
  

/***************************************************/
void GamBox(vis)
int vis;
{
  if (vis) XMapRaised(theDisp, gamW);
  else     XUnmapWindow(theDisp, gamW);

  gamUp = vis;
}


/***************************************************/
void RedrawGam(x,y,w,h)
int x,y,w,h;
{
  int i;
  XRectangle xr;

  xr.x = x;  xr.y = y;  xr.width = w;  xr.height = h;
  XSetClipRectangles(theDisp, theGC, 0,0, &xr, 1, Unsorted);

  XSetBackground(theDisp, theGC, infobg);

  XSetForeground(theDisp, theGC, infobg);
  XFillRectangle(theDisp,gamW, theGC, 10+1,10+1,256,19);
  XSetForeground(theDisp,theGC,infofg);
  XDrawRectangle(theDisp,gamW, theGC, 10,10,257,20);
  DrawGVals();

  for (i=0; i<G_NBUTTS; i++)
    BTRedraw(&gbut[i]);

  XSetClipMask(theDisp, theGC, None);
}


/***************************************************/
static void DrawGVals()
{
  int  w;
  char foo[40];

  XSetForeground(theDisp, theGC, infofg);
  XSetBackground(theDisp, theGC, infobg);

  sprintf(foo,"%3d   %3d %3d   %3d %3d   %3d", ghand[0].y, ghand[1].x,
	  ghand[1].y, ghand[2].x, ghand[2].y, ghand[3].y);

  w = XTextWidth(monofinfo, foo, strlen(foo));
  XSetFont(theDisp, theGC, monofont);
  XDrawImageString(theDisp, gamW, theGC, 10 + (256-w)/2, 
	      11+(20-(monofinfo->ascent+monofinfo->descent))/2
	      + monofinfo->ascent, foo, strlen(foo));
  XSetFont(theDisp, theGC, mfont);
}

/***************************************************/
void RedrawGraph(x,y,w,h)
int x,y,w,h;
{
  int i;
  XRectangle xr;
  XPoint  pts[256], *pt;

  xr.x = x;  xr.y = y;  xr.width = w;  xr.height = h;
  XSetClipRectangles(theDisp, theGC, 0,0, &xr, 1, Unsorted);

  XSetForeground(theDisp, theGC, infofg);
  XSetBackground(theDisp, theGC, infobg);

  XClearArea(theDisp, graphW, x,y,w,h, False);

  for (i=0, pt=pts; i<256; i++,pt++) {
    pt->x = i;  pt->y = 255-gamcr[i];
  }
  XDrawLines(theDisp, graphW, theGC, pts, 256, CoordModeOrigin);

  for (i=0; i<NUMHANDS; i++) {
    XSetForeground(theDisp, theGC, infobg);
    XFillRectangle(theDisp, graphW, theGC, 
		   ghand[i].x-2, 255-ghand[i].y-2,5,5);
    XSetForeground(theDisp,theGC,infofg);
    XDrawRectangle(theDisp, graphW, theGC,
		   ghand[i].x-3, 255-ghand[i].y-3,6,6);
    XDrawPoint(theDisp, graphW, theGC, ghand[i].x, 255-ghand[i].y);
  }

  XSetClipMask(theDisp, theGC, None);
}


/***************************************************/
void ClickGam(x,y)
int x,y;
{
  int i;
  BUTT *bp;

  for (i=0; i<G_NBUTTS; i++) {
    bp = &gbut[i];
    if (PTINRECT(x, y, bp->x, bp->y, bp->w, bp->h)) break;
  }

  /* if 'Set' is lit, and we didn't click 'set' or '1'..'4', turn it off */
  if (i!=G_BSET && i!=G_B1 && i!=G_B2 && i!=G_B3 && i!=G_B4 
      && gbut[G_BSET].lit) 
    { gbut[G_BSET].lit = 0;  BTRedraw(&gbut[G_BSET]); }

  if (i==G_NBUTTS) return;  /* didn't find one */

  if (BTTrack(bp)) DoGamCommand(i);
}



/**********************************************/
void TrackGraph(mx,my)
int mx,my;
{
  /* called when we've gotten a click inside graph window */

  Window       rW, cW;
  int          x, y, rx, ry, rval;
  unsigned int mask;
  int          h, vertonly, offx, offy;

  if (gbut[G_BSET].lit) 
    { gbut[G_BSET].lit = 0;  BTRedraw(&gbut[G_BSET]); }

  my = 255 - my;   /* flip y axis */

  /* see if x,y is within any of the handles */
  for (h=0; h<NUMHANDS; h++) {
    if (PTINRECT(mx, my, ghand[h].x-5, ghand[h].y-5, 11,11)) break;
  }
  if (h==NUMHANDS) return;   /* didn't find one */

  offx = ghand[h].x - mx;  offy = ghand[h].y - my;

  vertonly = (h==0 || h==(NUMHANDS-1));

  SaveUndoState();

  while (XQueryPointer(theDisp,graphW,&rW,&cW,&rx,&ry,&x,&y,&mask)) {
    if (!(mask & Button1Mask)) break;    /* button released */
    y = 255 - y;   /* flip y-axis */

    /* keep this handle between other handles (x-axis) if nec. */
    if (!vertonly) {
      if (x+offx <= ghand[h-1].x) x = (ghand[h-1].x+1)-offx;
      if (x+offx >= ghand[h+1].x) x = (ghand[h+1].x-1)-offx;
    }
    else x = mx;   /* if vert only, ignore sidewards motion */

    if (mx != x || my != y) {   /* this handle has moved... */
      ghand[h].x = x+offx;  ghand[h].y = y+offy;
      RANGE(ghand[h].y,0,255);
      GenerateGamma();
      RedrawGraph(0,0,256,256);  /* open to better ideas... */
    }
    mx = x;  my = y;
  }

  if ((rwcolor && rwthistime) || ncols==0) DoGammaApply(1);
}


/*********************/
void GenerateGamma()
{
  /* this function generates a gamma correction curve (gamcr)

     This function generates a 4 point spline curve to be used as a 
     non-linear grey 'colormap'.  Two of the points are nailed down at 0,0
     and 255,255, and can't be changed.  You specify the other two.  If
     you specify points on the line (0,0 - 255,255), you'll get the normal
     linear reponse curve.  If you specify points of 50,0 and 200,255, you'll
     get grey values of 0-50 to map to black (0), and grey values of 200-255
     to map to white (255) (roughly).  Values between 50 and 200 will cover
     the output range 0-255.  The reponse curve will be slightly 's' shaped. */

  int i,j,k;
  static int x[NUMHANDS], y[NUMHANDS];
  float yf[NUMHANDS];
  static float splint();

  /* do some idiot-proofing (x-coords must be monotonically increasing)  */

  for (i=0; i<4; i++) { 
    RANGE(ghand[i].x, 0, 255); 
    RANGE(ghand[i].y, 0, 255);
  }

  ghand[0].x = 0;  ghand[3].x = 255;
  if (ghand[1].x < 1)  ghand[1].x = 1;
  if (ghand[1].x >253) ghand[1].x = 253;
  if (ghand[2].x < ghand[1].x) ghand[2].x = ghand[1].x + 1;
  if (ghand[2].x >254) ghand[2].x = 254;

  if (firsttime) {   /* if this is the first 'generate' save as 'default' */
    memcpy(defgam, ghand, sizeof(ghand));
    firsttime=0;
  }

  DrawGVals();

  if (!strcmp(gbut[G_BGTYPE].str,LINESTR)) {
    /* do linear interpolation */
    for (i=0; i<NUMHANDS-1; i++) {
      for (j=ghand[i].x,k=0; j<=ghand[i+1].x; j++,k++) {
	gamcr[j] = ghand[i].y + (k * (ghand[i+1].y - ghand[i].y)) / 
	                        (ghand[i+1].x - ghand[i].x);
      }
    }
    return;
  }



  for (i=0; i<NUMHANDS; i++) { x[i] = ghand[i].x;  y[i] = ghand[i].y; }
  spline(x, y, NUMHANDS, yf);
  
  for (i=0; i<256; i++) {
    j = (int) splint(x, y, yf, NUMHANDS, (float) i);
    if (j<0) j=0;
    else if (j>255) j=255;
    gamcr[i] = j;
  }
}


/*********************/
void GenerateFSGamma()
{
  /* this function generates the Floyd-Steinberg gamma curve (fsgamcr)

     This function generates a 4 point spline curve to be used as a 
     non-linear grey 'colormap'.  Two of the points are nailed down at 0,0
     and 255,255, and can't be changed.  You specify the other two.  If
     you specify points on the line (0,0 - 255,255), you'll get the normal
     linear reponse curve.  If you specify points of 50,0 and 200,255, you'll
     get grey values of 0-50 to map to black (0), and grey values of 200-255
     to map to white (255) (roughly).  Values between 50 and 200 will cover
     the output range 0-255.  The reponse curve will be slightly 's' shaped. */

  int i,j,k;
  static int x[4] = {0,32,224,255};
  static int y[4] = {0, 0,255,255};
  float yf[4];
  static float splint();

  spline(x, y, 4, yf);
  
  for (i=0; i<256; i++) {
    j = (int) splint(x, y, yf, 4, (float) i);
    if (j<0) j=0;
    else if (j>255) j=255;
    fsgamcr[i] = j;
  }
}


/*********************/
static void spline(x,y,n,y2)
     int *x, *y, n;
     float *y2;
{
  /* given arrays of data points x[0..n-1] and y[0..n-1], computes the
     values of the second derivative at each of the data points
     y2[0..n-1] for use in the splint function */

  int i,k;
  float p,qn,sig,un,u[NUMHANDS];

  y2[0] = u[0] = 0.0;

  for (i=1; i<n-1; i++) {
    sig = ((float) x[i]-x[i-1]) / ((float) x[i+1] - x[i-1]);
    p = sig * y2[i-1] + 2.0;
    y2[i] = (sig-1.0) / p;
    u[i] = (((float) y[i+1]-y[i]) / (x[i+1]-x[i])) - 
           (((float) y[i]-y[i-1]) / (x[i]-x[i-1]));
    u[i] = (6.0 * u[i]/(x[i+1]-x[i-1]) - sig*u[i-1]) / p;
  }
  qn = un = 0.0;

  y2[n-1] = (un-qn*u[n-2]) / (qn*y2[n-2]+1.0);
  for (k=n-2; k>=0; k--)
    y2[k] = y2[k]*y2[k+1]+u[k];
}



/*********************/
static float splint(xa,ya,y2a,n,x)
float y2a[],x;
int n,xa[],ya[];
{
  int klo,khi,k;
  float h,b,a;

  klo = 0;
  khi = n-1;
  while (khi-klo > 1) {
    k = (khi+klo) >> 1;
    if (xa[k] > x) khi = k;
    else klo = k;
  }
  h = xa[khi] - xa[klo];
  if (h==0.0) FatalError("bad xvalues in splint\n");
  a = (xa[khi]-x)/h;
  b = (x-xa[klo])/h;
  return (a*ya[klo] + b*ya[khi] + ((a*a*a-a)*y2a[klo] +(b*b*b-b)*y2a[khi]) 
	  * (h*h) / 6.0);
}
    

/*********************/
static void DoGamCommand(cmd)
int cmd;
{
  int i,p, app;

  app = 1;

  switch (cmd) {
  case G_BAPPLY: DoGammaApply(1);  app = 0;  break;
  case G_BNOGAM: DoGammaApply(0);  app = 0;  break;

  case G_BRESET: SaveUndoState();
                 ghand[0].x =   0; ghand[0].y =   0;
                 ghand[1].x =  64; ghand[1].y =  64;
                 ghand[2].x = 192; ghand[2].y = 192;
                 ghand[3].x = 255; ghand[3].y = 255;

                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;



  case G_BDEF:   SaveUndoState();
                 memcpy(ghand, defgam, sizeof(ghand));

                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;

  case G_BGTYPE: if (!strcmp(gbut[G_BGTYPE].str, LINESTR))
                      gbut[G_BGTYPE].str = CURVSTR;
                 else gbut[G_BGTYPE].str = LINESTR;
                 BTRedraw(&gbut[G_BGTYPE]);
                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;

  case G_BCLOSE: GamBox(0);  app=0;  break;

  case G_BUP_BR: SaveUndoState();
                 for (i=0; i<NUMHANDS; i++) {
                   ghand[i].y += 10;
		   RANGE(ghand[i].y,0,255);
		 }
                 
                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;

  case G_BDN_BR: SaveUndoState();
                 for (i=0; i<NUMHANDS; i++) {
                   ghand[i].y -= 10;
		   RANGE(ghand[i].y,0,255);
		 }
                 
                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;

  case G_BUP_CN: SaveUndoState();
                 ghand[0].y -= 10;  
                 ghand[1].y -= 10;  ghand[1].x += 5;
                 ghand[2].y += 10;  ghand[2].x -= 5;
                 ghand[3].y += 10;
                 if (ghand[1].x > 127) ghand[1].x = 127;
                 if (ghand[2].x <= ghand[1].x) ghand[2].x = ghand[1].x+1;
                 for (i=0; i<NUMHANDS; i++) RANGE(ghand[i].y,0,255);
                 
                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;

  case G_BDN_CN: SaveUndoState();
                 if (abs(ghand[0].y - 127) < 10) ghand[0].y = 127;
                 else ghand[0].y += ((ghand[0].y>127) ? -10 : 10);

                 if (abs(ghand[1].y - 127) < 10) ghand[1].y = 127;
                 else ghand[1].y += ((ghand[1].y>127) ? -10 : 10);

                 if (abs(ghand[2].y - 127) < 10) ghand[2].y = 127;
                 else ghand[2].y += ((ghand[2].y>127) ? -10 : 10);

                 if (abs(ghand[3].y - 127) < 10) ghand[3].y = 127;
                 else ghand[3].y += ((ghand[3].y>127) ? -10 : 10);

                 for (i=0; i<NUMHANDS; i++) RANGE(ghand[i].y,0,255);
                 
                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;

  case G_BHSVRGB:if (!strcmp(gbut[G_BHSVRGB].str, HSVSTR))
                      gbut[G_BHSVRGB].str = RGBSTR;
                 else gbut[G_BHSVRGB].str = HSVSTR;
                 BTRedraw(&gbut[G_BHSVRGB]);
                 break;

  case G_B1:
  case G_B2:
  case G_B3:
  case G_B4:     if      (cmd==G_B1) p = 0;
                 else if (cmd==G_B2) p = 1;
                 else if (cmd==G_B3) p = 2;
                 else if (cmd==G_B4) p = 3;
                
                 if (gbut[G_BSET].lit) {
                   memcpy(presets[p], ghand, sizeof(ghand));
		   gbut[G_BSET].lit = 0;
		   BTRedraw(&gbut[G_BSET]);
		   app=0;
		 }
                 else {
                   SaveUndoState();
		   memcpy(ghand, presets[p], sizeof(ghand));
		   GenerateGamma();
                   RedrawGraph(0,0,256,256);
		 }
                 break;

  case G_BSET:   app=0;  break;

  case G_BUNDO:  bcopy(undo[0], ghand, sizeof(ghand));
                 bcopy(undo[1], undo[0], (MAXUNDO-1)*sizeof(ghand));
                 GenerateGamma();
                 RedrawGraph(0,0,256,256);
                 break;
  }
  
  if (app && rwcolor && rwthistime) DoGammaApply(1);
}


/*********************/
static void DoGammaApply(app)
int app;
{
  int i,j;

  DoMonoAndRV();

  if (app) GammifyColors();

  /* special case: if using R/W color, just modify the colors and leave */
  if (rwcolor && rwthistime) {
    XColor ctab[256];
    for (i=0; i<nfcols; i++) {
      j = fc2pcol[i];
      ctab[i].pixel = freecols[i];
      ctab[i].red   = r[j]<<8;
      ctab[i].green = g[j]<<8;
      ctab[i].blue  = b[j]<<8;
      ctab[i].flags = DoRed | DoGreen | DoBlue;
      XStoreColor(theDisp, LocalCmap ? LocalCmap : theCmap, &ctab[i]);
    }
    return;
  }
    

  if (useroot && (LocalCmap || nfcols)) {
    XSetWindowBackgroundPixmap(theDisp, rootW, None);
  }


  if (LocalCmap) {
    XClearWindow(theDisp,mainW);
    XFreeColormap(theDisp,LocalCmap);
    LocalCmap = 0;
  }

  else if (nfcols) {
    for (i=0; i<nfcols; i++)
      XFreeColors(theDisp, theCmap, &freecols[i], 1, 0L);

    XFlush(theDisp);  /* just to make sure they're all freed right now... */

    /* clear window if we're on a non-static display */
   if (theVisual->class & 1 && ncols>0) XClearWindow(theDisp,mainW);
  }

  AllocColors();
  CreateXImage();

  if (useroot) MakeRootPic();
          else DrawWindow(0,0,eWIDE,eHIGH);
  SetCursors(-1);
}


/*********************/
void GammifyColors()
{
  int i;

  if (!strcmp(gbut[G_BHSVRGB].str,RGBSTR)) {
    for (i=0; i<numcols; i++) {
      r[i] = gamcr[r[i]];
      g[i] = gamcr[g[i]];
      b[i] = gamcr[b[i]];
    }
  }
  else HSVgamma();
}


/*********************/
void SetGPreset(n,y0,x1,y1,x2,y2,y3)
int n,y0,x1,y1,x2,y2,y3;
{
  if (n<0 || n>3) return;
  
  presets[n][0].x = 0;     presets[n][0].y = y0;
  presets[n][1].x = x1;    presets[n][1].y = y1;
  presets[n][2].x = x2;    presets[n][2].y = y2;
  presets[n][3].x = 255;   presets[n][3].y = y3;
}

  
#define NOHUE -1

/*********************/
static void HSVgamma()
{
  int    i, vi, j;
  double rd, gd, bd, h, s, v, max, min, del, rc, gc, bc;
  double f, p, q, t;

  for (i=0; i<numcols; i++) {
    /* convert RGB to HSV */
    rd = r[i] / 255.0;            /* rd,gd,bd range 0-1 instead of 0-255 */
    gd = g[i] / 255.0;
    bd = b[i] / 255.0;

    /* compute maximum of rd,gd,bd */
    if (rd>=gd) { if (rd>=bd) max = rd;  else max = bd; }
           else { if (gd>=bd) max = gd;  else max = bd; }

    /* compute minimum of rd,gd,bd */
    if (rd<=gd) { if (rd<=bd) min = rd;  else min = bd; }
           else { if (gd<=bd) min = gd;  else min = bd; }

    del = max - min;
    v = max;
    if (max != 0.0) s = (del) / max;
               else s = 0.0;

    if (s == 0.0) h = NOHUE;
    else {
      rc = (max - rd) / del;
      gc = (max - gd) / del;
      bc = (max - bd) / del;

      if      (rd==max) h = bc - gc;
      else if (gd==max) h = 2 + rc - bc;
      else if (bd==max) h = 4 + gc - rc;

      h = h * 60;
      if (h<0) h += 360;
    }

    /* map near-black to black to avoid weird effects */
    if (v <= .0625) s = 0.0;

    /* apply gamcr[] function to 'v' (the intensity) */
    vi = (int) floor(v * 255);
    v = gamcr[vi] / 255.0;

    /* convert HSV back to RGB */
    if (s==0.0) { rd = v;  gd = v;  bd = v; }
    else {
      if (h==360.0) h = 0.0;
      h = h / 60.0;
      j = (int) floor(h);
      f = h - j;
      p = v * (1-s);
      q = v * (1 - (s*f));
      t = v * (1 - (s*(1 - f)));

      switch (j) {
      case 0:  rd = v;  gd = t;  bd = p;  break;
      case 1:  rd = q;  gd = v;  bd = p;  break;
      case 2:  rd = p;  gd = v;  bd = t;  break;
      case 3:  rd = p;  gd = q;  bd = v;  break;
      case 4:  rd = t;  gd = p;  bd = v;  break;
      case 5:  rd = v;  gd = p;  bd = q;  break;
      }
    }

    r[i] = (int) floor(rd * 255);
    g[i] = (int) floor(gd * 255);
    b[i] = (int) floor(bd * 255);
  }
}


  

/*********************/
static void SaveUndoState()
{
  /* pushes the current 'ghand' values onto the undo stack */

  /* use bcopy 'cause it knows how to do overlapped copies */
  bcopy(undo[0], undo[1], (MAXUNDO-1) * sizeof(ghand));
  
  /* and put 'ghand' on the top of the stack */
  bcopy(ghand, undo[0], sizeof(ghand));
}
\BARFOO\
else
  echo "will not over write ./xvgam.c"
fi
if `test ! -s ./xvgif.c`
then
echo "writting ./xvgif.c"
cat > ./xvgif.c << '\BARFOO\'
/*
 * xvgif.c  -  GIF loading code for 'xv'.  Based strongly on...
 *
 * gif2ras.c - Converts from a Compuserve GIF (tm) image to a Sun Raster image.
 *
 * Copyright (c) 1988, 1989 by Patrick J. Naughton
 *
 * Author: Patrick J. Naughton
 * naughton@wind.sun.com
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and that
 * both that copyright notice and this permission notice appear in
 * supporting documentation.
 *
 * This file is provided AS IS with no warranties of any kind.  The author
 * shall have no liability with respect to the infringement of copyrights,
 * trade secrets or any patents by this file or any part thereof.  In no
 * event will the author be liable for any lost revenue or profits or
 * other special, indirect and consequential damages.
 *
 */

/*
 * Copyright 1989, 1990 by the University of Pennsylvania
 *
 * Permission to use, copy, and distribute for non-commercial purposes,
 * is hereby granted without fee, providing that the above copyright
 * notice appear in all copies and that both the copyright notice and this
 * permission notice appear in supporting documentation.
 *
 * The software may be modified for your own purposes, but modified versions
 * may not be distributed.
 *
 * This software is provided "as is" without any express or implied warranty.
 */

#include "xv.h"

typedef int boolean;

#define NEXTBYTE (*ptr++)
#define IMAGESEP 0x2c
#define EXTENSION 0x21
#define INTERLACEMASK 0x40
#define COLORMAPMASK 0x80

  

FILE *fp;

int BitOffset = 0,		/* Bit Offset of next code */
    XC = 0, YC = 0,		/* Output X and Y coords of current pixel */
    Pass = 0,			/* Used by output routine if interlaced pic */
    OutCount = 0,		/* Decompressor output 'stack count' */
    RWidth, RHeight,		/* screen dimensions */
    Width, Height,		/* image dimensions */
    LeftOfs, TopOfs,		/* image offset */
    BitsPerPixel,		/* Bits per pixel, read from GIF header */
    BytesPerScanline,		/* bytes per scanline in output raster */
    ColorMapSize,		/* number of colors */
    Background,			/* background color */
    CodeSize,			/* Code size, read from GIF header */
    InitCodeSize,		/* Starting code size, used during Clear */
    Code,			/* Value returned by ReadCode */
    MaxCode,			/* limiting value for current code size */
    ClearCode,			/* GIF clear code */
    EOFCode,			/* GIF end-of-information code */
    CurCode, OldCode, InCode,	/* Decompressor variables */
    FirstFree,			/* First free code, generated per GIF spec */
    FreeCode,			/* Decompressor,next free slot in hash table */
    FinChar,			/* Decompressor variable */
    BitMask,			/* AND mask for data size */
    ReadMask,			/* Code AND mask for current code size */
    Misc;                       /* miscellaneous bits (interlace, local cmap)*/


boolean Interlace, HasColormap;

byte *RawGIF;			/* The heap array to hold it, raw */
byte *Raster;			/* The raster data stream, unblocked */

    /* The hash table used by the decompressor */
int Prefix[4096];
int Suffix[4096];

    /* An output array used by the decompressor */
int OutCode[1025];

char *id = "GIF87a";

static int EGApalette[16][3] = {
  {0,0,0},       {0,0,128},     {0,128,0},     {0,128,128}, 
  {128,0,0},     {128,0,128},   {128,128,0},   {200,200,200},
  {100,100,100}, {100,100,255}, {100,255,100}, {100,255,255},
  {255,100,100}, {255,100,255}, {255,255,100}, {255,255,255} };
  

static int  ReadCode();
static void DoInterlace();
static int  GifError();

int filesize;

/*****************************/
int LoadGIF(fname,nc)
  char *fname;
  int   nc;
/*****************************/
{
  register byte  ch, ch1;
  register byte *ptr, *ptr1, *picptr;
  register int   i;
  int            npixels, maxpixels;

  /* initialize variables */
  BitOffset = XC = YC = Pass = OutCount = npixels = maxpixels = 0;
  RawGIF = Raster = pic = NULL;
  
  fp = fopen(fname,"r");
  if (!fp) {
    fprintf(stderr,"%s: LoadGIF() - unable to open file '%s'\n",cmd,fname);
    return 1;
  }
  
  /* find the size of the file */
  fseek(fp, 0L, 2);
  filesize = ftell(fp);
  fseek(fp, 0L, 0);
  
  /* the +256's are so we can read truncated GIF files without fear of 
     segmentation violation */
  if (!(ptr = RawGIF = (byte *) malloc(filesize+256)))
    return( GifError("not enough memory to read gif file") );
  
  if (!(Raster = (byte *) malloc(filesize+256)))    
    return( GifError("not enough memory to read gif file") );
  
  if (fread(ptr, filesize, 1, fp) != 1) 
    return( GifError("GIF data read failed") );
  
  if (strncmp(ptr, id, 6)) 
    return( GifError("not a GIF file"));
  
  ptr += 6;
  
  /* Get variables from the GIF screen descriptor */
  
  ch = NEXTBYTE;
  RWidth = ch + 0x100 * NEXTBYTE;	/* screen dimensions... not used. */
  ch = NEXTBYTE;
  RHeight = ch + 0x100 * NEXTBYTE;
  
  ch = NEXTBYTE;
  HasColormap = ((ch & COLORMAPMASK) ? True : False);
  
  BitsPerPixel = (ch & 7) + 1;
  numcols = ColorMapSize = 1 << BitsPerPixel;
  BitMask = ColorMapSize - 1;
  
  Background = NEXTBYTE;		/* background color... not used. */
  
  if (NEXTBYTE)		/* supposed to be NULL */
    return( GifError("corrupt GIF file (screen descriptor)") );
  
  
  /* Read in global colormap. */
  
  if (HasColormap)
    for (i=0; i<ColorMapSize; i++) {
      r[i] = NEXTBYTE;
      g[i] = NEXTBYTE;
      b[i] = NEXTBYTE;
    }
  else {  /* no colormap in GIF file */
    /* put std EGA palette (repeated 16 times) into colormap, for lack of
       anything better to do */

    for (i=0; i<256; i++) {
      r[i] = EGApalette[i&15][0];
      g[i] = EGApalette[i&15][1];
      b[i] = EGApalette[i&15][2];
    }
  }


  while ( (i=NEXTBYTE) == EXTENSION) {  /* parse extension blocks */
    int i, fn, blocksize, aspnum, aspden;

    /* read extension block */
    fn = NEXTBYTE;

    do {
      i = 0;  blocksize = NEXTBYTE;
      while (i<blocksize) {
	if (fn == 'R' && blocksize == 2) {   /* aspect ratio extension */
	  aspnum = NEXTBYTE;  i++;
	  aspden = NEXTBYTE;  i++;
	  if (aspden>0 && aspnum>0) 
	    normaspect = (float) aspnum / (float) aspden;
	  else { normaspect = 1.0;  aspnum = aspden = 1; }

          /* fprintf(stderr,"aspect extension: %d:%d = %f\n", 
		  aspnum, aspden,normaspect); */
	}
	else { NEXTBYTE;  i++; }
      }
    } while (blocksize);
  }


  /* Check for image seperator */
  if (i != IMAGESEP) 
    return( GifError("corrupt GIF file (no image separator)") );
  
  /* Now read in values from the image descriptor */
  
  ch = NEXTBYTE;
  LeftOfs = ch + 0x100 * NEXTBYTE;
  ch = NEXTBYTE;
  TopOfs = ch + 0x100 * NEXTBYTE;
  ch = NEXTBYTE;
  Width = ch + 0x100 * NEXTBYTE;
  ch = NEXTBYTE;
  Height = ch + 0x100 * NEXTBYTE;

  Misc = NEXTBYTE;
  Interlace = ((Misc & INTERLACEMASK) ? True : False);

  if (Misc & 0x80) {
    for (i=0; i< 1 << ((Misc&7)+1); i++) {
      r[i] = NEXTBYTE;
      g[i] = NEXTBYTE;
      b[i] = NEXTBYTE;
    }
  }


  if (!HasColormap && !(Misc&0x80)) {
    /* no global or local colormap */
    SetISTR(ISTR_WARNING,
	    "No colormap in this GIF file.  Assuming EGA colors.");
  }
    

  
  /* Start reading the raster data. First we get the intial code size
   * and compute decompressor constant values, based on this code size.
   */
  
  CodeSize = NEXTBYTE;
  ClearCode = (1 << CodeSize);
  EOFCode = ClearCode + 1;
  FreeCode = FirstFree = ClearCode + 2;
  
  /* The GIF spec has it that the code size is the code size used to
   * compute the above values is the code size given in the file, but the
   * code size used in compression/decompression is the code size given in
   * the file plus one. (thus the ++).
   */
  
  CodeSize++;
  InitCodeSize = CodeSize;
  MaxCode = (1 << CodeSize);
  ReadMask = MaxCode - 1;
  


  /* UNBLOCK:
   * Read the raster data.  Here we just transpose it from the GIF array
   * to the Raster array, turning it from a series of blocks into one long
   * data stream, which makes life much easier for ReadCode().
   */
  
  ptr1 = Raster;
  do {
    ch = ch1 = NEXTBYTE;
    while (ch--) { *ptr1 = NEXTBYTE; ptr1++; }
    if ((ptr - RawGIF) > filesize) {
      SetISTR(ISTR_WARNING,
	      "This GIF file seems to be truncated.  Winging it.");
      break;
    }
  } while(ch1);
  free(RawGIF);	 RawGIF = NULL; 	/* We're done with the raw data now */



  if (DEBUG) {
    fprintf(stderr,"xv: LoadGIF() - picture is %dx%d, %d bits, %sinterlaced\n",
	    Width, Height, BitsPerPixel, Interlace ? "" : "non-");
  }
  
  SetISTR(ISTR_FORMAT, "GIF, %d bits per pixel, %sinterlaced.  (%d bytes)",
	  BitsPerPixel, Interlace ? "" : "non-", filesize);



  /* Allocate the 'pic' */
  pWIDE = Width;  pHIGH = Height;
  maxpixels = Width*Height;
  picptr = pic = (byte *) malloc(maxpixels);
  if (!pic) 
    return( GifError("not enough memory for 'pic'") );

  
  /* Decompress the file, continuing until you see the GIF EOF code.
   * One obvious enhancement is to add checking for corrupt files here.
   */
  
  Code = ReadCode();
  while (Code != EOFCode) {
    /* Clear code sets everything back to its initial value, then reads the
     * immediately subsequent code as uncompressed data.
     */

    if (Code == ClearCode) {
      CodeSize = InitCodeSize;
      MaxCode = (1 << CodeSize);
      ReadMask = MaxCode - 1;
      FreeCode = FirstFree;
      Code = ReadCode();
      CurCode = OldCode = Code;
      FinChar = CurCode & BitMask;
      if (!Interlace) *picptr++ = FinChar;
         else DoInterlace(FinChar);
      npixels++;
    }
    else {
      /* If not a clear code, must be data: save same as CurCode and InCode */

      /* if we're at maxcode and didn't get a clear, stop loading */
      if (FreeCode>=4096) { /* printf("freecode blew up\n"); */
			    break; }

      CurCode = InCode = Code;
      
      /* If greater or equal to FreeCode, not in the hash table yet;
       * repeat the last character decoded
       */
      
      if (CurCode >= FreeCode) {
	CurCode = OldCode;
	if (OutCount > 1024) {  /* printf("outcount1 blew up\n"); */ break; }
	OutCode[OutCount++] = FinChar;
      }
      
      /* Unless this code is raw data, pursue the chain pointed to by CurCode
       * through the hash table to its end; each code in the chain puts its
       * associated output code on the output queue.
       */
      
      while (CurCode > BitMask) {
	if (OutCount > 1024) break;   /* corrupt file */
	OutCode[OutCount++] = Suffix[CurCode];
	CurCode = Prefix[CurCode];
      }
      
      if (OutCount > 1024) { /* printf("outcount blew up\n"); */ break; }
      
      /* The last code in the chain is treated as raw data. */
      
      FinChar = CurCode & BitMask;
      OutCode[OutCount++] = FinChar;
      
      /* Now we put the data out to the Output routine.
       * It's been stacked LIFO, so deal with it that way...
       */

      /* safety thing:  prevent exceeding range of 'pic' */
      if (npixels + OutCount > maxpixels) OutCount = maxpixels-npixels;
	
      npixels += OutCount;
      if (!Interlace) for (i=OutCount-1; i>=0; i--) *picptr++ = OutCode[i];
                else  for (i=OutCount-1; i>=0; i--) DoInterlace(OutCode[i]);
      OutCount = 0;

      /* Build the hash table on-the-fly. No table is stored in the file. */
      
      Prefix[FreeCode] = OldCode;
      Suffix[FreeCode] = FinChar;
      OldCode = InCode;
      
      /* Point to the next slot in the table.  If we exceed the current
       * MaxCode value, increment the code size unless it's already 12.  If it
       * is, do nothing: the next code decompressed better be CLEAR
       */
      
      FreeCode++;
      if (FreeCode >= MaxCode) {
	if (CodeSize < 12) {
	  CodeSize++;
	  MaxCode *= 2;
	  ReadMask = (1 << CodeSize) - 1;
	}
      }
    }
    Code = ReadCode();
    if (npixels >= maxpixels) break;
  }
  free(Raster);  Raster = NULL;
  
  if (npixels != maxpixels) {
    SetISTR(ISTR_WARNING,"This GIF file seems to be truncated.  Winging it.");
    memset(pic+npixels, 0, maxpixels-npixels);  /* clear to EOBuffer */
  }

  if (fp != stdin) fclose(fp);

  return 0;
}


/* Fetch the next code from the raster data stream.  The codes can be
 * any length from 3 to 12 bits, packed into 8-bit bytes, so we have to
 * maintain our location in the Raster array as a BIT Offset.  We compute
 * the byte Offset into the raster array by dividing this by 8, pick up
 * three bytes, compute the bit Offset into our 24-bit chunk, shift to
 * bring the desired code to the bottom, then mask it off and return it. 
 */

static int ReadCode()
{
  int RawCode, ByteOffset;
  
  ByteOffset = BitOffset / 8;
  RawCode = Raster[ByteOffset] + (Raster[ByteOffset + 1] << 8);
  if (CodeSize >= 8)
    RawCode += (Raster[ByteOffset + 2] << 16);
  RawCode >>= (BitOffset % 8);
  BitOffset += CodeSize;

  return(RawCode & ReadMask);
}


/***************************/
static void DoInterlace(Index)
     byte Index;
{
  static byte *ptr = NULL;
  static int   oldYC = -1;
  
  if (oldYC != YC) {  ptr = pic + YC * Width;  oldYC = YC; }
  
  if (YC<Height)
    *ptr++ = Index;
  
  /* Update the X-coordinate, and if it overflows, update the Y-coordinate */
  
  if (++XC == Width) {
    
    /* deal with the interlace as described in the GIF
     * spec.  Put the decoded scan line out to the screen if we haven't gone
     * past the bottom of it
     */
    
    XC = 0;
    
    switch (Pass) {
    case 0:
      YC += 8;
      if (YC >= Height) { Pass++; YC = 4; }
      break;
      
    case 1:
      YC += 8;
      if (YC >= Height) { Pass++; YC = 2; }
      break;
      
    case 2:
      YC += 4;
      if (YC >= Height) { Pass++; YC = 1; }
      break;
      
    case 3:
      YC += 2;  break;
      
    default:
      break;
    }
  }
}


      
/*****************************/
static int GifError(st)
     char *st;
{
  fprintf(stderr,"%s: LoadGIF() - %s\n",cmd,st);
  
  if (RawGIF != NULL) free(RawGIF);
  if (Raster != NULL) free(Raster);
  if (pic    != NULL) free(pic);
  
  return -1;
}

\BARFOO\
else
  echo "will not over write ./xvgif.c"
fi
echo "Finished archive 3 of 8"
exit



dan
----------------------------------------------------
O'Reilly && Associates   argv@sun.com / argv@ora.com
Opinions expressed reflect those of the author only.