/*
 * xvgrab.c - image grabbing (from the display) functions for XV
 *
 *  Author:    John Bradley, University of Pennsylvania
 *                (bradley@cis.upenn.edu)
 *
 *  Contains:
 *     int Grab()             - handles the GRAB command
 *     int LoadGrab();        - 'loads' the pic from the last succesful Grab
 *            
 */

/*
 * Copyright 1989, 1990, 1991, 1992 by John Bradley and
 *                       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.
 *
 * The author may be contacted via:
 *    US Mail:   John Bradley
 *               GRASP Lab, Room 301C
 *               3401 Walnut St.  
 *               Philadelphia, PA  19104
 *
 *    Phone:     (215) 898-8813
 *    EMail:     bradley@cis.upenn.edu       
 */


#include "xv.h"

static byte *grabPic = (byte *) NULL;
static int  gbits;                              /* either '8' or '24' */
static byte grabmapR[256], grabmapG[256], grabmapB[256];  /* colormap */
static int  gWIDE,gHIGH;


/* local function definitions */
#ifdef __STDC__
static void flashrect(int, int, int, int, int);
static void startflash();
static void endflash();
static int grabImage(int, int, int, int);
static int convertImage(XImage *, XColor *, int, XWindowAttributes *);
static int lowbit(unsigned long);
static int getxcolors(XWindowAttributes *, XColor **);
static Window xmuClientWindow(Display *, Window);
#else
static void flashrect(), startflash(), endflash();
static int grabImage(), convertImage(), lowbit(), getxcolors();
static Window xmuClientWindow();
#endif


/***********************************/
int Grab()
{
  /* does UI part of Grab command.  returns '1' on success */

  int i,j,x,y,x1,y1,x2,y2, ix, iy, iw, ih;
  Window       rW,cW;
  int          rx,ry;
  unsigned int mask;

  /* throw away previous 'grabbed' pic, if there is one */
  if (grabPic) {  free(grabPic);  grabPic = (byte *) NULL; }


  {
    XColor fc, bc;
    fc.red = fc.green = fc.blue = 0xffff;
    bc.red = bc.green = bc.blue = 0x0000;
    
    XRecolorCursor(theDisp, tcross, &fc, &bc);
  }

  i = XGrabPointer(theDisp, rootW, False, 0L, GrabModeAsync, GrabModeSync,
		   None, tcross, CurrentTime);

  XBell(theDisp, 0);    /* beep once at start of grab */
  if (DEBUG>1) fprintf(stderr,"pointer grabbed\n");


  /* wait for a button press */
  while (1) {
    if (XQueryPointer(theDisp,rootW,&rW,&cW,&rx,&ry,&x1,&y1,&mask)) {
      if (mask & (Button1Mask | Button2Mask | Button3Mask)) break;
    }
  }

  if (mask & Button3Mask || rW!=rootW) {  /* cancel grab */
    XUngrabPointer(theDisp, CurrentTime);
    XBell(theDisp, 0);
    XBell(theDisp, 0);
  
    return 0;
  }

  if (DEBUG>1) fprintf(stderr,"got button click\n");

  if (mask & Button2Mask) {  /* grab clicked on window (and frame, if any) */
    /* figure out window coordinates, setup ix,iy,iw,ih as the rectangle
       to snarf from the screen */
    
    if (!cW || cW == rootW) {   /* grab entire screen */
      if (DEBUG) fprintf(stderr,"Grab: clicked middle on root window.\n");
      ix = iy = 0;  iw = dispWIDE;  ih = dispHIGH;
    }
    else {
      int xr, yr;
      unsigned int wr, hr, bwr, dr;
      if (XGetGeometry(theDisp, cW, &rW, &xr, &yr, &wr, &hr, &bwr, &dr)) {
	ix = xr;  iy = yr;  iw = wr;  ih = hr;
      }
      else {
	ix = iy = 0;  iw = dispWIDE;  ih = dispHIGH;
	if (DEBUG) fprintf(stderr,"XGetGeometry failed? (using root win)\n");
      }
    }

    /* range checking:  keep rectangle fully on-screen */
    if (ix<0) { iw += ix;  ix = 0; }
    if (iy<0) { ih += iy;  iy = 0; }
    if (ix+iw>dispWIDE) iw = dispWIDE-ix;
    if (iy+ih>dispHIGH) ih = dispHIGH-iy;


    if (DEBUG) fprintf(stderr,"using %d,%d (%dx%d)\n", ix, iy, iw, ih);

    /* flash the rectangle a bit... */
    startflash();
    for (i=0; i<5; i++) {
      flashrect(ix, iy, iw, ih, 1);
      XFlush(theDisp);  Timer(100);
      flashrect(ix, iy, iw, ih, 0);
      XFlush(theDisp);  Timer(100);
    }
    endflash();
  }

  else {                     /* button 1 handling:  track a flashing rect */
    x2 = x1;  y2 = y1;
    ix = x1;  iy = y1;  iw = ih = 0;

    startflash();

    /* Wait for button release while tracking rectangle on screen */
    while (1) {
      if (XQueryPointer(theDisp,rootW,&rW,&cW,&rx,&ry,&x,&y,&mask)) {
	if (!(mask & Button1Mask)) break;
      }

      flashrect(ix, iy, iw, ih, 0);    /* turn off rect */

      if (x!=x2 || y!=y2) {            /* move rectangle */
	ix = (x1<x) ? x1 : x;
	iy = (y1<y) ? y1 : y;
	iw = abs(x - x1);  ih = abs(y - y1);
	x2 = x;  y2 = y;
      }
      
      if (iw>1 && ih>1)
	flashrect(ix, iy, iw, ih, 1);  /* turn on rect */
    }
  
    if (DEBUG>1) fprintf(stderr,"got button release\n");
    flashrect(ix, iy, iw, ih, 0);      /* turn off rect */

    endflash();
  }

  if (DEBUG>1) 
    fprintf(stderr,"grabbing %dx%d region, at %d,%d\n", iw, ih, ix, iy);

  /* note: grabImage Ungrabs the pointer once it's grabbed the image
     (or earlier, if an error occurs) */

  i = grabImage(ix, iy, iw, ih);

  return i;
}


/***********************************/
static void flashrect(x,y,w,h,show)
     int x,y,w,h,show;
{
  static int isvis  = 0;
  static int maskno = 0;

  static unsigned long masks[8] = { 0x01010101,
				    0x02020203,
				    0x04040405,
				    0x08080809,
				    0x10101011,
				    0x20202021,
				    0x40404041,
				    0x80808081 };

  XSetPlaneMask(theDisp, theGC, masks[maskno]);

  if (!show) {     /* turn off rectangle */
    if (isvis) XDrawRectangle(theDisp, rootW, theGC, x, y, w-1, h-1);
    isvis = 0;
  }
  else {           /* show rectangle */
    if (!isvis && w>1 && h>1) {
      maskno = (maskno + 1) & 7;
      XSetPlaneMask(theDisp, theGC, masks[maskno]);
      XDrawRectangle(theDisp, rootW, theGC, x, y, w-1, h-1);
      isvis = 1;
    }
  }
}


/***********************************/
static void startflash()
{  
  /* set up for drawing a flashing rectangle */
  XSetFunction(theDisp, theGC, GXinvert);
  XSetSubwindowMode(theDisp, theGC, IncludeInferiors);
}

/***********************************/
static void endflash()
{  
  XSetFunction(theDisp, theGC, GXcopy);
  XSetSubwindowMode(theDisp, theGC, ClipByChildren);
  XSetPlaneMask(theDisp, theGC, AllPlanes);
}




/***********************************/
static int grabImage(x, y, w, h)
{
  /* attempts to grab the specified rectangle of the root window
     returns '1' on success */

  XImage *image;
  XWindowAttributes xwa;
  XColor *colors;
  int ncolors, i;
  char str[256];
  static char *foo[] = {"\nThat Sucks!"};

  /* range checking */
  if (x<0) { w += x;  x = 0; }
  if (y<0) { h += y;  y = 0; }
  if (x+w>dispWIDE) w = dispWIDE-x;
  if (y+h>dispHIGH) h = dispHIGH-y;

  if (w==0 || h==0) {  /* selected nothing */
    XUngrabPointer(theDisp, CurrentTime);
    return 0;
  }

  if (!XGetWindowAttributes(theDisp, rootW, &xwa)) {
    sprintf(str,"Unable to get window attributes for root window\n");
    XUngrabPointer(theDisp, CurrentTime);
    PopUp(str, foo, 1);
    return 0;
  }

  image = XGetImage(theDisp, rootW, x, y, w, h, AllPlanes, ZPixmap);
  if (!image || !image->data) {
    sprintf(str, "Unable to get image (%d,%d %dx%d) from display", x,y,w,h);
    XUngrabPointer(theDisp, CurrentTime);
    PopUp(str, foo, 1);
    return 0;
  }

  ncolors = getxcolors(&xwa, &colors);

  if (ncolors && DEBUG>1) {
    fprintf(stderr, "Colormap:\n");
    for (i=0; i<ncolors; i++)
      fprintf(stderr,"%02x%02x%02x  ",colors[i].red>>8, colors[i].green>>8,
	      colors[i].blue>>8);
    fprintf(stderr,"\n");
  }


  XBell(theDisp, 0);    /* beep twice at end of grab */
  XBell(theDisp, 0);

  XUngrabPointer(theDisp, CurrentTime);

  i = convertImage(image, colors, ncolors, &xwa);

  xvDestroyImage(image);

  return i;
}






union swapun {
  unsigned long l;
  unsigned short s;
  byte b[4];
};


/**************************************/
static int convertImage(image, colors, ncolors, xwap)
     XImage *image;
     XColor *colors;
     int     ncolors;
     XWindowAttributes *xwap;
{
  /* attempts to conver the image from whatever weird-ass format it might
     be in into something E-Z to deal with (either an 8-bit colormapped
     image, or a 24-bit image).  Returns '1' on success. */

  /* this code owes a lot to 'xwdtopnm.c', part of the pbmplus package,
     written by Jef Poskanzer */

  int             i, j;
  byte           *bptr, tmpbyte;
  unsigned short *sptr, sval;
  unsigned long  *lptr, lval;
  byte           *pic24, *pptr, *lineptr;
  int            bits_used, bits_per_item, bit_shift, bit_order;
  int            bits_per_pixel, byte_order;
  unsigned long  pixvalue, pixmask, rmask, gmask, bmask;
  unsigned int   rshift, gshift, bshift, r8shift, g8shift, b8shift;
  unsigned int   rval, gval, bval;
  union swapun   sw;
  int            isLsbMachine, flipBytes;
  Visual         *visual;

  char errstr[256];
  static char *foo[] = { "\nThat Sucks!" };

  /* determine byte order of the machine we're running on */
  sw.l = 0x10000000;
  isLsbMachine = (sw.b[3]) ? 1 : 0;

  if (xwap && xwap->visual) visual = xwap->visual;
                       else visual = theVisual;

  if (DEBUG) {
    fprintf(stderr,"convertImage:\n");
    fprintf(stderr,"  %dx%d (offset %d), %s\n",
	    image->width, image->height, image->xoffset, 
	    (image->format == XYBitmap || image->format == XYPixmap) 
	    ? "XYPixmap" : "ZPixmap");

    fprintf(stderr,"byte_order = %s, bitmap_bit_order = %s, unit=%d, pad=%d\n",
	    (image->byte_order == LSBFirst) ? "LSBFirst" : "MSBFirst",
	    (image->bitmap_bit_order == LSBFirst) ? "LSBFirst" : "MSBFirst",
	    image->bitmap_unit, image->bitmap_pad);

    fprintf(stderr,"depth = %d, bperline = %d, bits_per_pixel = %d\n",
	    image->depth, image->bytes_per_line, image->bits_per_pixel);

    fprintf(stderr,"masks:  red %lx  green %lx  blue %lx\n",
	    image->red_mask, image->green_mask, image->blue_mask);

    sw.l = 0x10000000;
    if (isLsbMachine) fprintf(stderr,"This looks like an lsbfirst machine\n");
                 else fprintf(stderr,"This looks like an msbfirst machine\n");
  }


  if (image->bitmap_unit != 8 && image->bitmap_unit != 16 &&
      image->bitmap_unit != 32) {
    sprintf(errstr, "%s\nReturned image bitmap_unit (%d) non-standard.",
	    "Can't deal with this display.", image->bitmap_unit);
    PopUp(errstr, foo, 1);
    return 0;
  }

  if (!ncolors && visual->class != TrueColor) {
    sprintf(errstr, "%s\nOnly TrueColor displays can have no colormap.",
	    "Can't deal with this display.");
    PopUp(errstr, foo, 1);
    return 0;
  }


  /* build the 'global' grabPic stuff */
  gWIDE = image->width;  gHIGH = image->height;

  if (visual->class == TrueColor || visual->class == DirectColor ||
      ncolors > 256) {
    grabPic = (byte *) malloc(gWIDE * gHIGH * 3);
    gbits = 24;
  }
  else {
    grabPic = (byte *) malloc(gWIDE * gHIGH);
    gbits = 8;

    /* load up the colormap */
    for (i=0; i<ncolors; i++) {
      grabmapR[i] = colors[i].red   >> 8;
      grabmapG[i] = colors[i].green >> 8;
      grabmapB[i] = colors[i].blue  >> 8;
    }
  }
  
  if (!grabPic) FatalError("unable to malloc grabPic in convertImage()");
  pptr = grabPic;


  if (visual->class == TrueColor || visual->class == DirectColor) {
    unsigned long tmp;

    /* compute various shifty constants we'll need */
    rmask = image->red_mask;
    gmask = image->green_mask;
    bmask = image->blue_mask;

    rshift = lowbit(rmask);
    gshift = lowbit(gmask);
    bshift = lowbit(bmask);

    r8shift = 0;  tmp = rmask >> rshift;
    while (tmp >= 256) { tmp >>= 1;  r8shift -= 1; }
    while (tmp < 128)  { tmp <<= 1;  r8shift += 1; }

    g8shift = 0;  tmp = gmask >> gshift;
    while (tmp >= 256) { tmp >>= 1;  g8shift -= 1; }
    while (tmp < 128)  { tmp <<= 1;  g8shift += 1; }

    b8shift = 0;  tmp = bmask >> bshift;
    while (tmp >= 256) { tmp >>= 1;  b8shift -= 1; }
    while (tmp < 128)  { tmp <<= 1;  b8shift += 1; }

    if (DEBUG)
      fprintf(stderr,"True/DirectColor: shifts=%d,%d,%d  8shifts=%d,%d,%d\n",
	      rshift, gshift, bshift, r8shift, g8shift, b8shift);
  }


  bits_per_item = image->bitmap_unit;
  bits_used = bits_per_item;
  bits_per_pixel = image->bits_per_pixel;

  if (bits_per_pixel == 32) pixmask = 0xffffffff;
  else pixmask = (((unsigned long) 1) << bits_per_pixel) - 1;

  bit_order = image->bitmap_bit_order;
  byte_order = image->byte_order;

  /* if we're on an lsbfirst machine, or the image came from an lsbfirst
     machine, we should flip the bytes around.  NOTE:  if we're on an
     lsbfirst machine *and* the image came from an lsbfirst machine, 
     *don't* flip bytes, as it should work out */

  /* pity we don't have a logical exclusive-or */
  flipBytes = ( isLsbMachine && byte_order != LSBFirst) ||
              (!isLsbMachine && byte_order == LSBFirst);

  for (i=0; i<image->height; i++) {
    lineptr = (byte *) image->data + (i * image->bytes_per_line);
    bptr = ((byte *)           lineptr) - 1;
    sptr = ((unsigned short *) lineptr) - 1;
    lptr = ((unsigned long *)  lineptr) - 1;
    bits_used = bits_per_item;

    for (j=0; j<image->width; j++) {
      
      /* get the next pixel value from the image data */

      if (bits_used == bits_per_item) {  /* time to move on to next b/s/l */
	switch (bits_per_item) {
	case 8:  bptr++;  break;
	case 16: sptr++;  sval = *sptr;
	         if (flipBytes) {   /* swap short */
		   sw.s = sval;
		   tmpbyte = sw.b[0];
		   sw.b[0] = sw.b[1];
		   sw.b[1] = tmpbyte;
		   sval = sw.s;
		 }
	         break;
	case 32: lptr++;  lval = *lptr;
	         if (flipBytes) {   /* swap long */
		   sw.l = lval;
		   tmpbyte = sw.b[0];
		   sw.b[0] = sw.b[3];
		   sw.b[3] = tmpbyte;
		   tmpbyte = sw.b[1];
		   sw.b[1] = sw.b[2];
		   sw.b[2] = tmpbyte;
		   lval = sw.l;
		 }
	         break;
	}
		   
	bits_used = 0;
	if (bit_order == MSBFirst) bit_shift = bits_per_item - bits_per_pixel;
	                      else bit_shift = 0;
      }

      switch (bits_per_item) {
      case 8:  pixvalue = (*bptr >> bit_shift) & pixmask;  break;
      case 16: pixvalue = ( sval >> bit_shift) & pixmask;  break;
      case 32: pixvalue = ( lval >> bit_shift) & pixmask;  break;
      }

      if (bit_order == MSBFirst) bit_shift -= bits_per_pixel;
                            else bit_shift += bits_per_pixel;
      bits_used += bits_per_pixel;

      
      /* okay, we've got the next pixel value in 'pixvalue' */
      
      if (visual->class == TrueColor || visual->class == DirectColor) {
	/* in either case, we have to take the pixvalue and 
	   break it out into individual r,g,b components */
	rval = (pixvalue & rmask) >> rshift;
	gval = (pixvalue & gmask) >> gshift;
	bval = (pixvalue & bmask) >> bshift;

	if (visual->class == DirectColor) {
	  /* use rval, gval, bval as indicies into colors array */

	  *pptr++ = (rval < ncolors) ? (colors[rval].red   >> 8) : 0;
	  *pptr++ = (gval < ncolors) ? (colors[gval].green >> 8) : 0;
	  *pptr++ = (bval < ncolors) ? (colors[bval].blue  >> 8) : 0;
	}

	else {   /* TrueColor */
	  /* have to map rval,gval,bval into 0-255 range */
	  *pptr++ = (r8shift >= 0) ? (rval << r8shift) : (rval >> (-r8shift));
	  *pptr++ = (g8shift >= 0) ? (gval << g8shift) : (gval >> (-g8shift));
	  *pptr++ = (b8shift >= 0) ? (bval << b8shift) : (bval >> (-b8shift));
	}
      }

      else { /* all others: StaticGray, StaticColor, GrayScale, PseudoColor */
	/* use pixel value as an index into colors array */

	if (pixvalue >= ncolors) {
	  FatalError("convertImage(): pixvalue >= ncolors");
	}

	if (gbits == 24) {   /* too many colors for 8-bit colormap */
	  *pptr++ = (colors[pixvalue].red)   >> 8;
	  *pptr++ = (colors[pixvalue].green) >> 8;
	  *pptr++ = (colors[pixvalue].blue)  >> 8;
	}
	else *pptr++ = pixvalue & 0xff;

      }
    }
  }

  return 1;
}



/**************************************/
static int lowbit(ul)
unsigned long ul;
{
  /* returns position of lowest set bit in 'ul' as an integer (0-31),
   or -1 if none */

  int i;
  for (i=0; ((ul&1) == 0) && i<32;  i++, ul>>=1);
  if (i==32) i = -1;
  return i;
}



/**************************************/
/* following code snarfed from 'xwd.c' */
/**************************************/

#define lowbit(x) ((x) & (~(x) + 1))


static int getxcolors(win_info, colors)
     XWindowAttributes *win_info;
     XColor **colors;
{
  int i, ncolors;
  Colormap cmap;

  if (win_info->visual->class == TrueColor) {
    if (DEBUG) fprintf(stderr,"TrueColor visual:  no colormap needed\n");
    return 0;
  }

  else if (!win_info->colormap) {
    if (DEBUG) fprintf(stderr,"no colormap associated with window\n");
    return 0;
  }

  ncolors = win_info->visual->map_entries;
  if (DEBUG) fprintf(stderr,"%d entries in colormap\n", ncolors);

  if (!(*colors = (XColor *) malloc (sizeof(XColor) * ncolors))) {
    XUngrabPointer(theDisp, CurrentTime);
    FatalError("malloc failed in getxcolors()");
  }

  if (win_info->visual->class == DirectColor) {
    Pixel red, green, blue, red1, green1, blue1;

    if (DEBUG) fprintf(stderr,"DirectColor visual\n");

    red = green = blue = 0;
    red1   = lowbit(win_info->visual->red_mask);
    green1 = lowbit(win_info->visual->green_mask);
    blue1  = lowbit(win_info->visual->blue_mask);
    for (i=0; i<ncolors; i++) {
      (*colors)[i].pixel = red|green|blue;
      (*colors)[i].pad = 0;
      red += red1;
      if (red > win_info->visual->red_mask)     red = 0;
      green += green1;
      if (green > win_info->visual->green_mask) green = 0;
      blue += blue1;
      if (blue > win_info->visual->blue_mask)   blue = 0;
    }
  }
  else {
    for (i=0; i<ncolors; i++) {
      (*colors)[i].pixel = i;
      (*colors)[i].pad = 0;
    }
  }

  if (cmapinstalled)           cmap = LocalCmap;
  else if (win_info->colormap) cmap = win_info->colormap;
  else                         cmap = theCmap;

  XQueryColors(theDisp, cmap, *colors, ncolors);

  return(ncolors);
}
    




/***********************************/
int LoadGrab()
{
  /* loads up (into XV structures) last image successfully grabbed */

  int i;

  if (!grabPic) return 0;   /* no image to use */

  SetISTR(ISTR_FORMAT,"<internal>");
  sprintf(formatStr, "%dx%d internal image.",gWIDE, gHIGH);

  if (gbits == 24) {
    i = Conv24to8(grabPic, gWIDE, gHIGH, (ncols>0) ? ncols : 256);
    free(grabPic);  grabPic = (byte *) NULL;
    return i;
  }

  else {
    pWIDE = gWIDE;  pHIGH = gHIGH;
    for (i=0; i<256; i++) {
      r[i] = grabmapR[i];
      g[i] = grabmapG[i];
      b[i] = grabmapB[i];
    }

    pic = grabPic;  
    grabPic = (byte *) NULL;
  }

  return 1;
}


