/*
 * xpixmap.c --
 *
 * Copyright (c) 1994 Software Research Associates, Inc.
 *
 * 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, and that the name of Software Research Associates not be
 * used in advertising or publicity pertaining to distribution of the
 * software without specific, written prior permission.  Software Research
 * Associates makes no representations about the suitability of this software
 * for any purpose.  It is provided "as is" without express or implied
 * warranty.
 */
 
#include "xlibInt.h" 

extern HDC GetDrawableDC( Drawable );
extern void ReleaseDrawableDC(HWND , HDC);
static char *ReadBitmapFile (const char *filename, unsigned int *width,
    unsigned int *height, int *x_hot, int *y_hot);


#define BMP_PLANES 1
#define BMP_PIXELS 1

static unsigned char
swap(unsigned char byte)
{
    register int i;
    register unsigned char bit = 0x80;
    register unsigned char result = 0;

    byte = ~byte;
    for (i = 0; i < 8; i++) {
   	if (byte & 0x01) {
   	    result |= bit;
   	}
   	byte >>= 1;
   	bit >>= 1;
    }
    return result;
}     	

static void
AddPixmap(Display *display, Pixmap pixmap)
{
    PixElem *pixElem;

    pixElem = (PixElem *) malloc(sizeof(PixElem));
    pixElem->next = display->pixmapList;
    pixElem->pixmap = pixmap;
    display->pixmapList = pixElem;
}

static void
RemovePixmap(Display *display, Pixmap pixmap)
{
    PixElem *prev, *curr, *next;

    for (prev = NULL, curr = display->pixmapList; curr != NULL;
	 prev = curr, curr = next)
    {
	next = curr->next;
	if (curr->pixmap == pixmap) {
	    if (prev != NULL) {
		prev->next = curr->next;
	    } else {
		display->pixmapList = curr->next;
	    }
	    free((char *) curr);
	}
    }
}

int
IsPixmap(Drawable drawable)
{
    PixElem *curr;
    Display *display;

    display = XOpenDisplay(NULL);
    for (curr = display->pixmapList; curr != NULL; curr = curr->next) {
	if (curr->pixmap == drawable) {
	    return TRUE;
	}
    }
    return FALSE;
}

unsigned char
_GetPixmapAttributes(Pixmap pixmap, XWindowChanges *attrs_return)
{
    HDC hdc;
    BITMAPINFO bmi;

    hdc = GetDrawableDC(pixmap);

    GetDIBits(hdc, pixmap, 0, 0, NULL, &bmi, DIB_PAL_COLORS);
    attrs_return->width = bmi.bmiHeader.biWidth;
    attrs_return->height = bmi.bmiHeader.biHeight;
    attrs_return->border_width = 0;
    ReleaseDrawableDC(hdc, pixmap);
    return Success;
}

Pixmap
XCreateBitmapFromData(Display *display, Drawable dummy2, const char *data,
	unsigned int width, unsigned int height)
{
    int byteWidth, dataWidth;
    int i, j, adjust = 0;
    BYTE *bPtr;
    HBITMAP hbmp;

    display->request++;

    byteWidth = dataWidth = (width + 7) / 8;

    if (dataWidth % 2) {
	byteWidth += 1;
    	adjust = 1;
    }

    bPtr = (BYTE *) malloc(byteWidth * height);
    for (i = 0; (unsigned)i < height; i++) {
        for (j = 0; j < byteWidth; j++) {
	    if (j == (byteWidth - 1) && adjust) {
	    	bPtr[i * byteWidth + j] = '\0';
	    } else {
		bPtr[i * byteWidth + j] = swap((BYTE)data[i * dataWidth + j]); 
	    }
    	}
    }
    hbmp = CreateBitmap(width, height, BMP_PLANES, BMP_PIXELS, bPtr);
    free(bPtr);

    AddPixmap(display, hbmp);
    return hbmp ;
}

void 
XScrollWindow(Display *display, Drawable w, GC gc, 
	int src_x, int src_y, unsigned int width, unsigned int height, 
	int dest_x, int dest_y)
{
    HDC hdc;
    HRGN hrgn;
    RECT rect;

    hdc = GetDrawableDC(w);
    hrgn = CreateRectRgn(0, 0, 0, 0);
    GetWindowRect(w, &rect);

    rect.left = dest_x;
    rect.right = dest_x + width;
    if (dest_y < src_y) {
	rect.top = dest_y;
	rect.bottom = src_y + height;
    } else {
	rect.top = src_y;
	rect.bottom = dest_y + height;
    }
    
    ScrollWindow(w, 0, dest_y - src_y, NULL, &rect);
}

void 
XCopyArea(Display *display, Drawable src, Drawable dest, GC gc, 
	int src_x, int src_y, unsigned int width, unsigned int height, 
	int dest_x, int dest_y)
{
    HDC hsrc, hdest;

    display->request++;

    hdest = GetDrawableDC(dest);
    hsrc = (dest == src) ? hdest : GetDrawableDC(src);

    BitBlt( hdest, dest_x, dest_y, width, height,
	   hsrc,  src_x,  src_y, SRCCOPY );

    if (dest != src) {
	ReleaseDrawableDC(src, hsrc);
    }
    ReleaseDrawableDC(dest, hdest);
}

void
XCopyPlane(Display *display, Drawable src, Drawable dest, GC gc,
	int src_x, int src_y, unsigned int width, unsigned int height, 
	int dest_x, int dest_y, unsigned long dummy)
{
    HDC hsrc, hdest;
    HBRUSH fgBrush, bgBrush, hPrevBrush;

    display->request++;

    hdest = GetDrawableDC(dest);
    hsrc = (dest == src) ? hdest : GetDrawableDC(src);

    bgBrush = CreateSolidBrush(gc->background);
    fgBrush = CreateSolidBrush(gc->foreground);

    SelectObject(hdest, bgBrush);
    BitBlt(hdest, dest_x, dest_y, width, height, hsrc, src_x, src_y,
	   0xF00021);

    hPrevBrush = SelectObject(hdest, fgBrush);
    BitBlt(hdest, dest_x, dest_y, width, height, hsrc, src_x, src_y,
	   0xB8074A);

    SelectObject(hdest, hPrevBrush);

    DeleteObject(fgBrush);
    DeleteObject(bgBrush);


    if (dest != src) {
	ReleaseDrawableDC(src, hsrc);
    }
    ReleaseDrawableDC(dest, hdest);
}

Pixmap
XCreatePixmap(Display *display, Drawable dummy2, 
	unsigned int width, unsigned int height, unsigned int dummy3)
{
    BITMAPINFOHEADER bmih;
    HBITMAP hBitmap;
    HDC hdc;

    display->request++;

    bmih.biSize = sizeof(BITMAPINFOHEADER);
    bmih.biWidth = (DWORD) width;
    bmih.biHeight = (DWORD) height;
    bmih.biPlanes = 1;
    bmih.biBitCount = 8;
    bmih.biCompression = 0;
    bmih.biSizeImage = 0;
    bmih.biXPelsPerMeter = 0;
    bmih.biYPelsPerMeter = 0;
    bmih.biClrUsed = 0;
    bmih.biClrImportant = 0;
    hdc = GetDC(NULL);
    hBitmap = CreateDIBitmap(hdc, &bmih, 0L, NULL, NULL, 0);
    ReleaseDC(NULL, hdc);
    AddPixmap(display, hBitmap);
    return (Pixmap) hBitmap;
}

void
XFreePixmap(Display *display, Pixmap pixmap)
{
    display->request++;

    if (pixmap != NULL) {
	DeleteObject(pixmap);
	RemovePixmap(display, pixmap);
    }
}


XImage *
XGetImage(Display *display, Drawable d, int x, int y, unsigned int width,
	  unsigned int height, unsigned long plm, int format)
{
    XImage *ret_image;
    unsigned char *smallBitData;
    HDC hdc, hdcMem;
    unsigned char *bigBitData,*smallBitBase;
    RECT clientRect;
    HBITMAP hbmp, hbmpPrev;
    BITMAPINFO bmInfo;
    int i;

    display->request++;

    if (format != ZPixmap) {
	/* XXX: Don't handle XYPixmap and XYBitmap for now */
	return NULL;
    }

    ret_image = (XImage *) malloc(sizeof(XImage));
    if (ret_image == NULL) {
	return NULL;
    }

    hdc = GetDrawableDC(d);

    /* Need to do a Blt operation to copy into a new bitmap */
    hbmp = CreateCompatibleBitmap(hdc, width, height);
    hbmpPrev = SelectObject(hdcMem, hbmp);
    hdcMem = CreateCompatibleDC(hdc);
    BitBlt(hdcMem, 0, 0, width, height, hdc, x, y, SRCCOPY);
    SelectObject(hdcMem, hbmpPrev);

    GetDIBits(hdcMem, hbmp, 0, 0, NULL, &bmInfo, DIB_RGB_COLORS);
    ret_image->width = width;
    ret_image->height = height;
    ret_image->xoffset = 0;
    ret_image->format = ZPixmap;

#if 0

    if (!(ret_image->data = malloc(width*height*2)))
    {
	printf("Failed to allocate data area for XImage.\n");
	return NULL;
    }
    if (!(smallBitData = smallBitBase = malloc(width*height*3)))
    {
	printf("Failed to allocate data area for 24 Bit image.\n");
	return NULL;
    }


    ret_image->byte_order = LSBFirst;
    ret_image->bitmap_unit = 8;
    ret_image->bitmap_bit_order = MSBFirst;
    ret_image->bitmap_pad = 0;
    ret_image->depth = 8;
    ret_image->bytes_per_line = width;
    ret_image->bits_per_pixel = 8;
    ret_image->f.destroy_image = NT_XDestroyImage;

    /* Get the BITMAP info into the Image. */
    GetDIBits(hdcCompatible,hbmBitmap,0,height,smallBitData,&bmInfo,DIB_RGB_COLORS);
       
    /* Copy the 24 Bit Pixmap to a 32-Bit one. */
    bigBitData = ret_image->data;
    for (i = 0 ; i< width*height;i++)
    {
	*bigBitData++ = *smallBitData++;
	*bigBitData++ = *smallBitData++;
	*bigBitData++ = *smallBitData++;
	*bigBitData++ = 0;
    }
	  
	  
    /* Free the Device contexts, and the Bitmap */
    free(smallBitBase);
    DeleteDC(hdcCompatible);
    DeleteObject(hbmBitmap);
    cachedImageWindow = w;
    return ret_image;
#else
    return NULL;
#endif
}


int 
XReadBitmapFile(Display *display, Drawable dummy2, const char *filename,
	unsigned int *width, unsigned int *height, Pixmap *bitmap,
	int *x_hot, int *y_hot)
{
    struct _stat st;
    char *buffer;
    FILE *fp;
    char *bits;
    HBITMAP hbm;
    BITMAPFILEHEADER *bmfh;
    BITMAPINFOHEADER *bmih;
    BITMAPINFO *bmi;
    HDC hdc;
    int result;

    /* First, check if it is a Windows bitmap file */
    if (_stat(filename, &st) != 0)				   
 	return BitmapOpenFailed;				   
    if ((fp = fopen(filename, "rb")) == NULL)	   
 	return BitmapOpenFailed;
    if ((buffer = (char *)malloc((size_t)st.st_size)) == NULL) {
 	result = BitmapNoMemory;
	goto close_end;
    }
    if (fread(buffer, (size_t)st.st_size, 1, fp) != 1) {	
 	result = BitmapFileInvalid;
	goto  free_end;
    }
    bmfh = (BITMAPFILEHEADER *)buffer;
    bmih = (BITMAPINFOHEADER *)(buffer + sizeof(BITMAPFILEHEADER));
    bmi = (BITMAPINFO *)bmih;
    bits = buffer + bmfh->bfOffBits;		

    if (strncmp((char *)&bmfh->bfType, "BM", 2) != 0) {	 
 	result = BitmapFileInvalid;
	goto free_end;
    }
    hdc = GetDC(NULL);
    hbm = CreateDIBitmap(hdc, bmih,	CBM_INIT, bits, bmi, DIB_RGB_COLORS);	 
    ReleaseDC(NULL, hdc);
    if (hbm == NULL) {
 	result =  BitmapFileInvalid;
	goto free_end;
    }
    *bitmap = hbm;
    *width = (unsigned int)bmih->biWidth;
    *height = (unsigned int)bmih->biHeight;
    *x_hot = 0;
    *y_hot = 0;		
    result = BitmapSuccess;

free_end:
    free(buffer);
    if (result == BitmapFileInvalid) {
	/* Now go to phase two: it may just be an ASCII file.  Try to read it
	 * as an X bitmap file
	 */
	bits = ReadBitmapFile(filename, width, height, x_hot, y_hot);
	if (bits != NULL) {
	    *bitmap = CreateBitmap(*width, *height, BMP_PLANES, BMP_PIXELS, bits);
	    if (*bitmap != NULL) {
		result = BitmapSuccess;
	    }
	    free(bits);
	}
    }

close_end:
    if (result == BitmapSuccess) {
	AddPixmap(display, *bitmap);
    }
    fclose(fp);
    return result;
}	


/* #ifdef TCL_MSDOS_PORT */
/* The code below is slightly modified from the X11R5 Xlib source file
 * XRdBitF.c
 */
/* $XFree86: mit/lib/X/XRdBitF.c,v 1.4 1993/03/27 09:14:21 dawes Exp $ */
/* $XConsortium: XRdBitF.c,v 1.15 91/02/01 16:34:46 gildea Exp $ */
/* Copyright, 1987, Massachusetts Institute of Technology */

/* TkWin version 0.1 -- Tk for Windows
 * Copyright (C) 1994 K. K. Kubota
 * Mathematical Sciences Computing Facility, University of Kentucky,
 * Lexington, KY 40506, USA (e-mail: ken@ms.uky.edu)

/*
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of M.I.T. not be used in advertising or
publicity pertaining to distribution of the software without specific,
written prior permission.  M.I.T. makes no representations about the
suitability of this software for any purpose.  It is provided "as is"
without express or implied warranty.
*/

#define MAX_SIZE 255

/* shared data for the image read/parse logic */
static short hexTable[256];		/* conversion value */
static Bool Xinitialized = False;	/* easier to fill in at run time */


/*
 *	Table index for the hex values. Initialized once, first time.
 *	Used for translation value or delimiter significance lookup.
 */
static void initHexTable()
{
    hexTable['0'] = 0;	hexTable['1'] = 1;
    hexTable['2'] = 2;	hexTable['3'] = 3;
    hexTable['4'] = 4;	hexTable['5'] = 5;
    hexTable['6'] = 6;	hexTable['7'] = 7;
    hexTable['8'] = 8;	hexTable['9'] = 9;
    hexTable['A'] = 10;	hexTable['B'] = 11;
    hexTable['C'] = 12;	hexTable['D'] = 13;
    hexTable['E'] = 14;	hexTable['F'] = 15;
    hexTable['a'] = 10;	hexTable['b'] = 11;
    hexTable['c'] = 12;	hexTable['d'] = 13;
    hexTable['e'] = 14;	hexTable['f'] = 15;

    /* delimiters of significance are flagged w/ negative value */
    hexTable[' '] = -1;	hexTable[','] = -1;
    hexTable['}'] = -1;	hexTable['\n'] = -1;
    hexTable['\t'] = -1;
	
    Xinitialized = True;
}

/*
 *	read next hex value in the input stream, return -1 if EOF
 */
static long NextInt (fstream)
    FILE *fstream;
{
    int	ch;
    long value = 0;
    int gotone = 0;
    int done = 0;
    
    /* loop, accumulate hex value until find delimiter  */
    /* skip any initial delimiters found in read stream */

    while (!done) {
	ch = getc(fstream);
	if (ch == EOF) {
	    value	= -1L;
	    done++;
	} else {
	    /* trim high bits, check type and accumulate */
	    ch &= 0xff;
	    if (isascii(ch) && isxdigit(ch)) {
		value = (value << 4) + hexTable[ch];
		gotone++;
	    } else if ((hexTable[ch]) < 0 && gotone)
	      done++;
	}
    }
    return value;
}

/* $XConsortium: Xlib.h,v 11.215 91/07/22 15:42:38 rws Exp $ */
/* 
 * Copyright 1985, 1986, 1987, 1991 by the Massachusetts Institute of Technology
 *
 * 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, and that the name of M.I.T. not be used in advertising
 * or publicity pertaining to distribution of the software without specific, 
 * written prior permission. M.I.T. makes no representations about the 
 * suitability of this software for any purpose.  It is provided "as is"
 * without express or implied warranty.
 *
 * X Window System is a Trademark of MIT.
 *
 */

/* read bitmap from X10 or X11 bitmap files and return
 * array of data bits in format appropriate for Microsoft Windows
 */
static char *ReadBitmapFile (filename, width, height, x_hot, y_hot)
    const char *filename;
    unsigned int *width, *height;       /* RETURNED */
    int *x_hot, *y_hot;                 /* RETURNED */
{
    FILE *fstream;			/* handle on file  */
    char *data = NULL;			/* working variable */
    char line[MAX_SIZE];		/* input line from file */
    int size;				/* number of bytes of data */
    char name_and_type[MAX_SIZE];	/* an input line */
    char *type;				/* for parsing */
    long value;				/* from an input line */
    int val;
    int version10p;			/* boolean, old format */
    int padding;			/* to handle alignment */
    int bytes_per_line;			/* per scanline of data */
    unsigned int ww = 0;		/* width */
    unsigned int hh = 0;		/* height */
    int hx = -1;			/* x hotspot */
    int hy = -1;			/* y hotspot */
    char *retval = NULL;

    /* first time initialization */
    if (Xinitialized == False) initHexTable();

    if ((fstream = fopen(filename, "rt")) == NULL) {
	return NULL;
    }

    while (fgets(line, MAX_SIZE, fstream)) {
	if (strlen(line) == MAX_SIZE-1) {
	    goto error;
	}
	if (sscanf(line,"#define %s %d",name_and_type,&val) == 2) {
	    if ((type = strrchr(name_and_type, '_')) == NULL) {
		type = name_and_type;
	    } else {
		type++;
	    }

	    if (!strcmp("width", type)) {
		ww = (unsigned int) val;
	    }
	    if (!strcmp("height", type)) {
		hh = (unsigned int) val;
	    }
	    if (!strcmp("hot", type)) {
		if (type-- == name_and_type || type-- == name_and_type)
		    continue;
		if (!strcmp("x_hot", type))
		    hx = val;
		if (!strcmp("y_hot", type))
		    hy = val;
	    }
	    continue;
	}
    
	if (sscanf(line, "static short %s = {", name_and_type) == 1)
	    version10p = 1;
	else if (sscanf(line,"static unsigned char %s = {",name_and_type) == 1)
	    version10p = 0;
	else if (sscanf(line, "static char %s = {", name_and_type) == 1)
	    version10p = 0;
	else
	    continue;

	if ((type = strrchr(name_and_type, '_')) == NULL)
	    type = name_and_type;
	else
	    type++;

	if (strcmp("bits[]", type))
	    continue;
    
	if (!ww || !hh) {
	    goto error;
	}

	if ((ww % 16) && ((ww % 16) < 9) && !version10p) {
	    padding = 1;
	} else {
	    padding = 0;
	}

	bytes_per_line = (ww+7)/8 + padding;

	size = bytes_per_line * hh;
/* xxxxxxxxxx added +hh */
	data = (char *) malloc ((unsigned int) (size + hh));
	if (!data) {
	    goto error;
	}

	if (version10p) {
	    unsigned char *ptr;
	    int bytes;

	    for (bytes=0, ptr=data; bytes<size; (bytes += 2)) {
		value = NextInt(fstream);
		if (value < 0) {
		    goto error;
		}
		*(ptr++) = swap((unsigned char) (value & 0xff));
		*(ptr++) = swap((unsigned char) ((value >> 8) & 0xff));
	    }
	} else {
	    unsigned char *ptr;
	    int bytes;

	    for (bytes=0, ptr=data; bytes<size; bytes++, ptr++) {
		value = NextInt(fstream);
		if (value < 0) {
		    goto error;
		}
		*ptr= swap((unsigned char) (value & 0xff));
		if (padding && ((bytes+2) % bytes_per_line) == 0) {
		    ptr++;
		    *ptr = (unsigned char) 0x00;
		    bytes++;
		}
	    }
	}
    }					/* end while */


    *width = ww;
    *height = hh;
    if (x_hot) *x_hot = hx;
    if (y_hot) *y_hot = hy;

    retval = data;

 error:
    if (data && retval != data) {
	free (data);
    }
    fclose (fstream);
    return retval;
}
