/* 
 * tkImgPixmap.c --
 *
 *	This procedure implements images of type "pixmap" for Tk.
 *
 * <BASED ON tkImgBmap.c from TK 4.0, which has the following notice>
 * Copyright (c) 1994 The Regents of the University of California.
 * All rights reserved.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and its documentation for any purpose, provided that the
 * above copyright notice and the following two paragraphs appear in
 * all copies of this software.
 * 
 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */

static char sccsid[] = "@(#) tkImgPixmap.c 1.3 94/08/16 09:54:42";

#include "tkInt.h"
#include "tkPort.h"

/*
 * The following data structure is the colormap used in pixmap files
 * that map from one (or more) characters to a full color name.
 */
typedef struct PixmapCmap {
    char *key;			/* Identifies the color in the data */
    char *color;		/* Full color string */
} PixmapCmap;

/*
 * The following data structure represents the master for a pixmap
 * image:
 */

typedef struct PixmapMaster {
    Tk_ImageMaster tkMaster;	/* Tk's token for image master. */
    Tcl_Interp *interp;		/* Interpreter for application that is
				 * using image. */
    Tk_Uid imageName;		/* Name of image (and of image command
				 * for image).  Used to delete command
				 * when image goes away. */
    int width, height;		/* Dimensions of pixmap */
    char *dataString;		/* String representation of pixmap (suitable for
				 * input to CreatePixmapFromString).   May
				 * be NULL if no data.  Malloc'ed. */
    int ncolors;		/* Number of colors in the colormap */
    int cpp;			/* Number of characters-per-pixel in the
				 * string representation of the pixmap. */
    PixmapCmap *colormap;	/* Map from color index to color value */
    char *data;			/* Binary representation of pixmap, with one
				 * byte per pixel.  This limits the pixmap
				 * to 256 or less colors. */
    char *maskData;		/* Data for pixmap's mask (suitable for
				 * input to XBitmapPixmapFromData).
				 * Malloc'ed. */
    char *fileString;		/* Value of -file option (malloc'ed). */
    char *maskFileString;	/* Value of -maskfile option (malloc'ed). */
    char *maskDataString;	/* Value of -maskdata option (malloc'ed). */
    struct PixmapInstance *instancePtr;
				/* First in list of all instances associated
				 * with this master. */
} PixmapMaster;

/*
 * The following data structure represents all of the instances of an
 * image that lie within a particular window:
 */

typedef struct PixmapInstance {
    int refCount;		/* Number of instances that share this
				 * data structure. */
    PixmapMaster *masterPtr;	/* Pointer to master for image. */
    Tk_Window tkwin;		/* Window in which the instances will be
				 * displayed. */
    Pixmap pixmap;		/* The pixmap to display. */
    Pixmap mask;		/* Mask: only display pixmap pixels where
				 * there are 1's here. */
    XColor **colors;		/* Array of colors used by the pixmap */
    GC gc;			/* Graphics context for displaying pixmap.
				 * None means there was an error while
				 * setting up the instance, so it cannot
				 * be displayed. */
    struct PixmapInstance *nextPtr;
				/* Next in list of all instance structures
				 * associated with masterPtr (NULL means
				 * end of list). */
} PixmapInstance;

/*
 * The type record for pixmap images:
 */

static int		ImgPixmapCreate _ANSI_ARGS_((Tcl_Interp *interp,
			    char *name, int argc, char **argv,
			    Tk_ImageType *typePtr, Tk_ImageMaster master,
			    ClientData *clientDataPtr));
static ClientData	ImgPixmapGet _ANSI_ARGS_((Tk_Window tkwin,
			    ClientData clientData));
static void		ImgPixmapDisplay _ANSI_ARGS_((ClientData clientData,
			    Display *display, Drawable drawable, 
			    int imageX, int imageY, unsigned int width,
			    unsigned int height, int drawableX,
			    int drawableY));
static void		ImgPixmapFree _ANSI_ARGS_((ClientData clientData,
			    Display *display));
static void		ImgPixmapDelete _ANSI_ARGS_((ClientData clientData));

Tk_ImageType tkPixmapImageType = {
    "pixmap",			/* name */
    ImgPixmapCreate,		/* createProc */
    ImgPixmapGet,			/* getProc */
    ImgPixmapDisplay,		/* displayProc */
    ImgPixmapFree,		/* freeProc */
    ImgPixmapDelete,		/* deleteProc */
    (Tk_ImageType *) NULL	/* nextPtr */
};

/*
 * Information used for parsing configuration specs:
 */

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_STRING, "-data", (char *) NULL, (char *) NULL,
	(char *) NULL, Tk_Offset(PixmapMaster, dataString), TK_CONFIG_NULL_OK},
    {TK_CONFIG_STRING, "-file", (char *) NULL, (char *) NULL,
	(char *) NULL, Tk_Offset(PixmapMaster, fileString), TK_CONFIG_NULL_OK},
    {TK_CONFIG_STRING, "-maskdata", (char *) NULL, (char *) NULL,
	(char *) NULL, Tk_Offset(PixmapMaster, maskDataString),
	TK_CONFIG_NULL_OK},
    {TK_CONFIG_STRING, "-maskfile", (char *) NULL, (char *) NULL,
	(char *) NULL, Tk_Offset(PixmapMaster, maskFileString),
	TK_CONFIG_NULL_OK},
    {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
	(char *) NULL, 0, 0}
};

/*
 * The following data structure is used to describe the state of
 * parsing a pixmap file or string.  It is used for communication
 * between GetPixmapData and NextBitmapWord.
 */

#define MAX_WORD_LENGTH 100
typedef struct ParseInfo {
    char *string;		/* Next character of string data for pixmap,
				 * or NULL if pixmap is being read from
				 * file. */
    FILE *f;			/* File containing pixmap data, or NULL
				 * if no file. */
    char word[MAX_WORD_LENGTH+1];
				/* Current word of pixmap data, NULL
				 * terminated. */
    int wordLength;		/* Number of non-NULL bytes in word. */
} ParseInfo;

#define NextCharacter(piPtr) \
    (((piPtr)->string == NULL) ? getc((piPtr)->f) : *(piPtr)->string++)

/*
 * Prototypes for procedures used only locally in this file:
 */

static char *		GetPixmapString _ANSI_ARGS_((Tcl_Interp *interp,
			    char *fileName));
static char *		GetBitmapData _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, char *fileName,
			    unsigned int *widthPtr,
			    unsigned int *heightPtr));
static int		GetPixmapData _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, char *fileName,
			    PixmapMaster *masterPtr));
static Pixmap		CreatePixmapFromData _ANSI_ARGS_((Tcl_Interp *interp,
			    PixmapInstance *instancePtr,
			    PixmapMaster *masterPtr));
static int		ImgPixmapCmd _ANSI_ARGS_((ClientData clientData,
			    Tcl_Interp *interp, int argc, char **argv));
static void		ImgPixmapConfigureInstance _ANSI_ARGS_((
			    PixmapInstance *instancePtr));
static int		ImgPixmapConfigureMaster _ANSI_ARGS_((
			    PixmapMaster *masterPtr, int argc, char **argv,
			    int flags));
static int		NextBitmapWord _ANSI_ARGS_((ParseInfo *parseInfoPtr));

/*
 *----------------------------------------------------------------------
 *
 * ImgPixmapCreate --
 *
 *	This procedure is called by the Tk image code to create "pixmap"
 *	images.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	The data structure for a new image is allocated.
 *
 *----------------------------------------------------------------------
 */

	/* ARGSUSED */
static int
ImgPixmapCreate(interp, name, argc, argv, typePtr, master, clientDataPtr)
    Tcl_Interp *interp;		/* Interpreter for application containing
				 * image. */
    char *name;			/* Name to use for image. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings for options (doesn't
				 * include image name or type). */
    Tk_ImageType *typePtr;	/* Pointer to our type record (not used). */
    Tk_ImageMaster master;	/* Token for image, to be used by us in
				 * later callbacks. */
    ClientData *clientDataPtr;	/* Store manager's token for image here;
				 * it will be returned in later callbacks. */
{
    PixmapMaster *masterPtr;

    masterPtr = (PixmapMaster *) ckalloc(sizeof(PixmapMaster));
    masterPtr->tkMaster = master;
    masterPtr->interp = interp;
    masterPtr->imageName = ckalloc((unsigned) (strlen(name) + 1));
    strcpy(masterPtr->imageName, name);
    masterPtr->width = masterPtr->height = 0;
    masterPtr->dataString = NULL;
    masterPtr->ncolors = 0;
    masterPtr->cpp = 0;
    masterPtr->colormap = NULL;
    masterPtr->data = NULL;
    masterPtr->maskData = NULL;
    masterPtr->fileString = NULL;
    masterPtr->maskFileString = NULL;
    masterPtr->maskDataString = NULL;
    masterPtr->instancePtr = NULL;
    if (ImgPixmapConfigureMaster(masterPtr, argc, argv, 0) != TCL_OK) {
	ImgPixmapDelete((ClientData) masterPtr);
	return TCL_ERROR;
    }
    Tcl_CreateCommand(interp, name, ImgPixmapCmd, (ClientData) masterPtr,
	    (void (*)()) NULL);
    *clientDataPtr = (ClientData) masterPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ImgPixmapConfigureMaster --
 *
 *	This procedure is called when a pixmap image is created or
 *	reconfigured.  It process configuration options and resets
 *	any instances of the image.
 *
 * Results:
 *	A standard Tcl return value.  If TCL_ERROR is returned then
 *	an error message is left in masterPtr->interp->result.
 *
 * Side effects:
 *	Existing instances of the image will be redisplayed to match
 *	the new configuration options.
 *
 *----------------------------------------------------------------------
 */

static int
ImgPixmapConfigureMaster(masterPtr, argc, argv, flags)
    PixmapMaster *masterPtr;	/* Pointer to data structure describing
				 * overall pixmap image to (reconfigure). */
    int argc;			/* Number of entries in argv. */
    char **argv;		/* Pairs of configuration options for image. */
    int flags;			/* Flags to pass to Tk_ConfigureWidget,
				 * such as TK_CONFIG_ARGV_ONLY. */
{
    PixmapInstance *instancePtr;
    unsigned int maskWidth, maskHeight;

    if (Tk_ConfigureWidget(masterPtr->interp, Tk_MainWindow(masterPtr->interp),
	    configSpecs, argc, argv, (char *) masterPtr, flags)
	    != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Parse the pixmap and/or mask to create binary data.  Make sure that
     * the pixmap and mask have the same dimensions.
     */

    if ((masterPtr->fileString != NULL) ||
	(masterPtr->dataString != NULL)) {
	if (GetPixmapData(masterPtr->interp, masterPtr->dataString,
		masterPtr->fileString, masterPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
    }
    if ((masterPtr->maskFileString != NULL)
	    || (masterPtr->maskDataString != NULL)) {
	if (masterPtr->data == NULL) {
	    masterPtr->interp->result = "can't have mask without pixmap";
	    return TCL_ERROR;
	}
	if (masterPtr->maskData != NULL) {
	    ckfree(masterPtr->maskData);
	}
	masterPtr->maskData = GetBitmapData(masterPtr->interp,
		masterPtr->maskDataString, masterPtr->maskFileString,
		&maskWidth, &maskHeight);
	if (masterPtr->maskData == NULL) {
	    return TCL_ERROR;
	}
	if ((maskWidth != masterPtr->width)
		|| (maskHeight != masterPtr->height)) {
	    ckfree(masterPtr->maskData);
	    masterPtr->maskData = NULL;
	    masterPtr->interp->result = "pixmap and mask have different sizes";
	    return TCL_ERROR;
	}
    }

    /*
     * Cycle through all of the instances of this image, regenerating
     * the information for each instance.  Then force the image to be
     * redisplayed everywhere that it is used.
     */

    for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
	    instancePtr = instancePtr->nextPtr) {
	ImgPixmapConfigureInstance(instancePtr);
    }
    Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width,
	    masterPtr->height, masterPtr->width, masterPtr->height);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ImgPixmapConfigureInstance --
 *
 *	This procedure is called to create displaying information for
 *	a pixmap image instance based on the configuration information
 *	in the master.  It is invoked both when new instances are
 *	created and when the master is reconfigured.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Generates errors via Tk_BackgroundError if there are problems
 *	in setting up the instance.
 *
 *----------------------------------------------------------------------
 */

static void
ImgPixmapConfigureInstance(instancePtr)
    PixmapInstance *instancePtr;	/* Instance to reconfigure. */
{
    PixmapMaster *masterPtr = instancePtr->masterPtr;
    XColor *colorPtr;
    XGCValues gcValues;
    GC gc;
    int status;
    unsigned int mask;

    /*
     * For each of the options in masterPtr, translate the string
     * form into an internal form appropriate for instancePtr.
     */
    if (instancePtr->pixmap != None) {
	XFreePixmap(Tk_Display(instancePtr->tkwin), instancePtr->pixmap);
	instancePtr->pixmap = None;
    }
    if (masterPtr->data != NULL) {
	instancePtr->pixmap = CreatePixmapFromData(masterPtr->interp,
		instancePtr,
		masterPtr);
	if (instancePtr->pixmap == None) {
	    goto error;
	}
    }

    if (instancePtr->mask != None) {
	XFreePixmap(Tk_Display(instancePtr->tkwin), instancePtr->mask);
	instancePtr->mask = None;
    }
    if (masterPtr->maskData != NULL) {
	instancePtr->mask = XCreateBitmapFromData(
		Tk_Display(instancePtr->tkwin),
		RootWindowOfScreen(Tk_Screen(instancePtr->tkwin)),
		masterPtr->maskData, masterPtr->width, masterPtr->height);
    }

    if (masterPtr->data != NULL) {
	gcValues.graphics_exposures = False;
	mask = GCGraphicsExposures;
	if (instancePtr->mask != None) {
	    gcValues.clip_mask = instancePtr->mask;
	    mask |= GCClipMask;
	}
	gc = Tk_GetGC(instancePtr->tkwin, mask, &gcValues);
    } else {
	gc = None;
    }
    if (instancePtr->gc != None) {
	Tk_FreeGC(Tk_Display(instancePtr->tkwin), instancePtr->gc);
    }
    instancePtr->gc = gc;
    return;

    error:
    /*
     * An error occurred: clear the graphics context in the instance to
     * make it clear that this instance cannot be displayed.  Then report
     * the error.
     */

    if (instancePtr->gc != None) {
	Tk_FreeGC(Tk_Display(instancePtr->tkwin), instancePtr->gc);
    }
    instancePtr->gc = None;
    Tcl_AddErrorInfo(masterPtr->interp, "\n    (while configuring image \"");
    Tcl_AddErrorInfo(masterPtr->interp, masterPtr->imageName);
    Tcl_AddErrorInfo(masterPtr->interp, "\")");
    Tk_BackgroundError(masterPtr->interp);
}
#ifdef notdef

/*
 *----------------------------------------------------------------------
 *
 * GetPixmapString --
 *
 *	Given a file name, this procedure reads the
 *	file and returns the whole contents.  The pixmap string
 *	gets parsed later by the Xpm library routines.
 *
 * Results:
 *	If the file was read successfully then the
 *	return value is a malloc-ed array containing the pixmap string.
 *	If an error occurred, NULL is returned and an error message is
 *	left in interp->result.
 *
 * Side effects:
 *	A string is allocated.
 *
 *----------------------------------------------------------------------
 */

static char *
GetPixmapString(interp, fileName)
    Tcl_Interp *interp;			/* For reporting errors. */
    char *fileName;			/* Name of file containing pixmap
					 * description. */
{
    int fd;
    struct stat statb;
    char *string;
    int n;

    fd = open(fileName, O_RDONLY, 0);
    if (fd < 0) {
	Tcl_AppendResult(interp, "couldn't read pixmap file \"",
		    fileName, "\": ", Tcl_PosixError(interp), (char *) NULL);
	return NULL;
    }
    if (fstat(fd, &statb) < 0) {
	Tcl_AppendResult(interp, "couldn't fstat pixmap file \"",
		    fileName, "\": ", Tcl_PosixError(interp), (char *) NULL);
	return NULL;
    }
    if (! S_ISREG(statb.st_mode)) {
	Tcl_AppendResult(interp, "pixmap file \"",
		    fileName, "\" is not a regular file ",
		    (char *) NULL);
	return NULL;

    }
    n = statb.st_size;
    string = (char *)ckalloc(n+1);
    n = read(fd, string, n);
    if (n != statb.st_size) {
	Tcl_AppendResult(interp, "Failed to read pixmap file \"",
		    fileName, "\"", (char *) NULL);
	ckfree(string);
	return NULL;
    }
    close(fd);
    return string;
}
#endif

/*
 *----------------------------------------------------------------------
 *
 * GetBitmapData --
 *
 *	Given a file name or ASCII string, this procedure parses the
 *	file or string contents to produce binary data for a bitmap.
 *
 * Results:
 *	If the bitmap description was parsed successfully then the
 *	return value is a malloc-ed array containing the bitmap data.
 *	The dimensions of the data are stored in *widthPtr and *heightPtr.
 *	If an error occurred, NULL is returned and an error message is
 *	left in interp->result.
 *
 * Side effects:
 *	A pixmap is created.
 *
 *----------------------------------------------------------------------
 */

static char *
GetBitmapData(interp, string, fileName, widthPtr, heightPtr)
    Tcl_Interp *interp;			/* For reporting errors. */
    char *string;			/* String describing bitmap.  May
					 * be NULL. */
    char *fileName;			/* Name of file containing bitmap
					 * description.  Used only if string
					 * is NULL.  Must not be NULL if
					 * string is NULL. */
    unsigned int *widthPtr, *heightPtr;	/* Dimensions of bitmap get returned
					 * here. */
{
    int width, height, numBytes;
    char *p, *end;
    ParseInfo pi;
    char *data = NULL;

    pi.string = string;
    if (string == NULL) {
	pi.f = fopen(fileName, "r");
	if (pi.f == NULL) {
	    Tcl_AppendResult(interp, "couldn't read bitmap file \"",
		    fileName, "\": ", Tcl_PosixError(interp), (char *) NULL);
	    return NULL;
	}
    } else {
	pi.f = NULL;
    }

    /*
     * Parse the lines that define the dimensions of the bitmap,
     * plus the first line that defines the bitmap data (it declares
     * the name of a data variable but doesn't include any actual
     * data).  These lines look something like the following:
     *
     *		#define foo_width 16
     *		#define foo_height 16
     *		#define foo_x_hot 3
     *		#define foo_y_hot 3
     *		static char foo_bits[] = {
     *
     * The x_hot and y_hot lines may or may not be present.  It's
     * important to check for "char" in the last line, in order to
     * reject old X10-style bitmaps that used shorts.
     */

    width = 0;
    height = 0;
    while (1) {
	if (NextBitmapWord(&pi) != TCL_OK) {
	    goto error;
	}
	if ((pi.wordLength >= 6) && (pi.word[pi.wordLength-6] == '_')
		&& (strcmp(pi.word+pi.wordLength-6, "_width") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    width = strtol(pi.word, &end, 0);
	    if ((end == pi.word) || (*end != 0)) {
		goto error;
	    }
	} else if ((pi.wordLength >= 7) && (pi.word[pi.wordLength-7] == '_')
		&& (strcmp(pi.word+pi.wordLength-7, "_height") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    height = strtol(pi.word, &end, 0);
	    if ((end == pi.word) || (*end != 0)) {
		goto error;
	    }
	}
	if ((pi.word[0] == 's') && (strcmp(pi.word, "static") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    if (strcmp(pi.word, "unsigned") == 0) {
		if (NextBitmapWord(&pi) != TCL_OK) {
		    goto error;
		}
	    }
	    if (strcmp(pi.word, "char") != 0) {
		Tcl_AppendResult(interp, "format error in bitmap data; ",
			"looks like it's an obsolete X10 bitmap file",
			(char *) NULL);
		goto errorCleanup;
	    }
	    while (1) {
		if (NextBitmapWord(&pi) != TCL_OK) {
		    goto error;
		}
		if ((pi.word[0] == '{') && (pi.word[1] == 0)) {
		    goto getData;
		}
	    }
	}
    }

    /*
     * Now we've read everything but the data.  Allocate an array
     * and read in the data.
     */

    getData:
    if ((width <= 0) || (height <= 0)) {
	goto error;
    }
    numBytes = ((width+7)/8) * height;
    data = ckalloc((unsigned) numBytes);
    for (p = data; numBytes > 0; p++, numBytes--) {
	if (NextBitmapWord(&pi) != TCL_OK) {
	    goto error;
	}
	*p = strtol(pi.word, &end, 0);
	if (end == pi.word) {
	    goto error;
	}
    }

    /*
     * All done.  Clean up and return.
     */

    if (pi.f != NULL) {
	fclose(pi.f);
    }
    *widthPtr = width;
    *heightPtr = height;
    return data;

    error:
    interp->result = "format error in bitmap data";
    errorCleanup:
    if (data != NULL) {
	ckfree(data);
    }
    if (pi.f != NULL) {
	fclose(pi.f);
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * GetPixmapData --
 *
 *	Given a file name or ASCII string, this procedure parses the
 *	file or string contents to produce binary data and colormap
 *	information needed for a pixmap.
 *
 * Results:
 *	If the pixmap description was parsed successfully then the
 *	fields of masterPtr are filled in with data, dimensions,and
 *	color information, and TCL_OK is returned.  Otherwise
 *	TCL_ERROR is returned and an error message is
 *	left in interp->result.
 *
 * Side effects:
 *	A pixmap is created.
 *
 *----------------------------------------------------------------------
 */

static int
GetPixmapData(interp, string, fileName, masterPtr)
    Tcl_Interp *interp;			/* For reporting errors. */
    char *string;			/* String describing bitmap.  May
					 * be NULL. */
    char *fileName;			/* Name of file containing bitmap
					 * description.  Used only if string
					 * is NULL.  Must not be NULL if
					 * string is NULL. */
    PixmapMaster *masterPtr;		/* Main data structure */
{
    int width, height, numBytes;
    int ok, nc, ncolors, cpp, format;
    char *p, *end;
    ParseInfo pi;
    char *data = NULL;
    PixmapCmap *colormap = NULL;
    char key[8];
    char color[128];

    pi.string = string;
    if (string == NULL) {
	pi.f = fopen(fileName, "r");
	if (pi.f == NULL) {
	    Tcl_AppendResult(interp, "couldn't read bitmap file \"",
		    fileName, "\": ", Tcl_PosixError(interp), (char *) NULL);
	    return TCL_ERROR;
	}
    } else {
	pi.f = NULL;
    }

    /*
     * Parse the lines that define the dimensions of the bitmap,
     * plus the first line that defines the colormap data.
     * These lines look something like the following:
     *
     *		#define noname_format 1
     *		#define noname_width  64
     *		#define noname_height 64
     *		#define noname_x_hot 8
     *		#define noname_y_hot 8
     *		#define noname_ncolors 17
     *		#define noname_chars_per_pixel 1
     *		static char *noname_colors[] = {
     *			"`", "black",
     *			"a", "gray56",
     *		(and more like this)
     *		};
     *		static char *noname_pixels[] = {
     *	"bbbbbbbbbbbbbbbbbbbbegeeeeeggiiigggggebbbbbbbbbbbbbbbbbbbbbbbbbb",
     *		(and more like this)
     *		};
     *
     * The x_hot and y_hot lines may or may not be present.  It's
     * important to check for "char" in the last line, in order to
     * reject old X10-style bitmaps that used shorts.
     */

    width = 0;
    height = 0;
    format = 0;
    cpp = 0;
    ncolors = 0;
    ok = 0;
    while (1) {
	if (NextBitmapWord(&pi) != TCL_OK) {
	    goto error;
	}
	if ((pi.wordLength >= 6) && (pi.word[pi.wordLength-6] == '_')
		&& (strcmp(pi.word+pi.wordLength-6, "_width") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    width = strtol(pi.word, &end, 0);
	    if ((end == pi.word) || (*end != 0)) {
		goto error;
	    }
	} else if ((pi.wordLength >= 7) && (pi.word[pi.wordLength-7] == '_')
		&& (strcmp(pi.word+pi.wordLength-7, "_height") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    height = strtol(pi.word, &end, 0);
	    if ((end == pi.word) || (*end != 0)) {
		goto error;
	    }
	} else if ((pi.wordLength >= 7) && (pi.word[pi.wordLength-7] == '_')
		&& (strcmp(pi.word+pi.wordLength-7, "_format") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    format = strtol(pi.word, &end, 0);
	    if ((end == pi.word) || (*end != 0)) {
		goto error;
	    }
	} else if ((pi.wordLength >= 8) && (pi.word[pi.wordLength-8] == '_')
		&& (strcmp(pi.word+pi.wordLength-8, "_ncolors") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    ncolors = strtol(pi.word, &end, 0);
	    if ((end == pi.word) || (*end != 0)) {
		goto error;
	    }
	} else if ((pi.wordLength >= 16) && (pi.word[pi.wordLength-16] == '_')
		&& (strcmp(pi.word+pi.wordLength-16, "_chars_per_pixel") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    cpp = strtol(pi.word, &end, 0);
	    if ((end == pi.word) || (*end != 0)) {
		goto error;
	    }
	}
	if ((pi.word[0] == 's') && (strcmp(pi.word, "static") == 0)) {
	    if (NextBitmapWord(&pi) != TCL_OK) {
		goto error;
	    }
	    if (strcmp(pi.word, "unsigned") == 0) {
		if (NextBitmapWord(&pi) != TCL_OK) {
		    goto error;
		}
	    }
	    if (strcmp(pi.word, "char") != 0) {
		Tcl_AppendResult(interp, "format error in bitmap data; ",
			"looks like it's an obsolete X10 bitmap file",
			(char *) NULL);
		goto errorCleanup;
	    }
	    while (1) {
		if (NextBitmapWord(&pi) != TCL_OK) {
		    goto error;
		}
		if ((pi.wordLength >= 9) && (pi.word[pi.wordLength-9] == '_')
		    && (strcmp(pi.word+pi.wordLength-9, "_colors[]") == 0)) {
		    ok = 1;
		}
		if ((pi.word[0] == '{') && (pi.word[1] == 0)) {
		    if (!ok) {
			goto error;
		    } else {
			goto getColors;
		    }
		}
	    }
	}
    }

    /*
     * Read and save the colormap, which is a map from one (or more)
     * characters to a full color name.
     */
    getColors:
    if ((width <= 0) || (height <= 0) || (format != 1)) {
	goto error;
    }
    if (ncolors > 256) {
	Tcl_AppendResult(interp, "cannot support more than 256 colors per pixmap",
		(char *) NULL);
	goto error;
    }

    colormap = (PixmapCmap *)ckalloc(ncolors * sizeof(PixmapCmap));
    if (colormap == NULL) {
	goto error;
    }

    ok = 0;	/* Used as a binary state bit in the next loop */
    nc = 0;	/* Num Colors counter */
    while (1) {
	if (NextBitmapWord(&pi) != TCL_OK) {
	    goto error;
	}
	if ((pi.word[0] == '}') && (pi.word[1] == ';')) {
	    break;
	}
	/*
	 * Lines are like
	    "e", "#efefef",
	 * So we skip the double quotes.
	 */
	if (!ok) {	/* Getting the key */
	    if (nc > ncolors) {
		goto error;
	    }
	    strncpy(key, pi.word+1, pi.wordLength-2);
	    key[pi.wordLength-2] = '\0';
	    colormap[nc].key = Tk_GetUid(key);
	    ok = 1;
	} else {	/* Getting the value */
	    strncpy(color, pi.word+1, pi.wordLength-2);
	    color[pi.wordLength-2] = '\0';
	    colormap[nc].color = Tk_GetUid(color);
	    nc++;
	    ok = 0;
	}
    }
    /* 
     * Skip the line that defines the pixel array.
     */
    ok = 0;
    while (1) {
	if (NextBitmapWord(&pi) != TCL_OK) {
	    goto error;
	}
	if ((pi.wordLength >= 9) && (pi.word[pi.wordLength-9] == '_')
	    && (strcmp(pi.word+pi.wordLength-9, "_pixels[]") == 0)) {
	    ok = 1;
	}
	if ((pi.word[0] == '{') && (pi.word[1] == 0)) {
	    if (!ok) {
		goto error;
	    } else {
		break;
	    }
	}
    }
    /*
     * Now we've read everything but the data.  Allocate an array
     * and read in the data.  For simplicity, we use one byte per pixel,
     * although that limits the number of different colors we can support.
     */

    getData:
    numBytes = width * height;
    data = ckalloc((unsigned) numBytes);
    if (data == NULL) {
	goto error;
    }
    for (p = data; numBytes > 0; p++, numBytes--) {
	char c;
	char *cPtr = key;	/* To copy next pixel value from array */
	for (nc=0 ; nc<cpp ; ) {
	    c = NextCharacter(&pi);
	    if (c == '"' || c == ',' || c == '\n') {
		continue;
	    } else if (c == '}') {
		break;
	    }
	    *cPtr++ = c;
	    nc++;
	}
	*cPtr = '\0';
	/*
	 * Map from the pixel key to an index.
	 */
	for (nc=0 ; nc<ncolors ; nc++) {
	    if (strncmp(key, colormap[nc].key, cpp) == 0) {
		*p = nc;
		goto GotPixel;
	    }
	}
	goto error;
	GotPixel: ;
    }

    /*
     * All done.  Clean up and return.
     */

    if (pi.f != NULL) {
	fclose(pi.f);
    }
    masterPtr->width = width;
    masterPtr->height = height;
    if (masterPtr->colormap) {
	ckfree(masterPtr->colormap);
    }
    masterPtr->ncolors = ncolors;
    masterPtr->colormap = colormap;
    if (masterPtr->data != NULL) {
	ckfree(masterPtr->data);
    }
    masterPtr->data = data;
    return TCL_OK;

    error:
    interp->result = "format error in bitmap data";
    errorCleanup:
    if (data != NULL) {
	ckfree(data);
    }
    if (colormap != NULL) {
	ckfree(colormap);
    }
    if (pi.f != NULL) {
	fclose(pi.f);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * NextBitmapWord --
 *
 *	This procedure retrieves the next word of information (stuff
 *	between commas or white space) from a pixmap description.
 *
 * Results:
 *	Returns TCL_OK if all went well.  In this case the next word,
 *	and its length, will be availble in *parseInfoPtr.  If the end
 *	of the pixmap description was reached then TCL_ERROR is returned.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
NextBitmapWord(parseInfoPtr)
    ParseInfo *parseInfoPtr;		/* Describes what we're reading
					 * and where we are in it. */
{
    char *src, *dst;
    int c;

    parseInfoPtr->wordLength = 0;
    dst = parseInfoPtr->word;
    if (parseInfoPtr->string != NULL) {
	for (src = parseInfoPtr->string; isspace(*src) || (*src == ',');
		src++) {
	    if (*src == 0) {
		return TCL_ERROR;
	    }
	}
	for ( ; !isspace(*src) && (*src != ',') && (*src != 0); src++) {
	    *dst = *src;
	    dst++;
	    parseInfoPtr->wordLength++;
	    if (parseInfoPtr->wordLength > MAX_WORD_LENGTH) {
		return TCL_ERROR;
	    }
	}
	parseInfoPtr->string = src;
    } else {
	for (c = getc(parseInfoPtr->f); isspace(c) || (c == ',');
		c = getc(parseInfoPtr->f)) {
	    if (c == EOF) {
		return TCL_ERROR;
	    }
	}
	for ( ; !isspace(c) && (c != ',') && (c != EOF);
		c = getc(parseInfoPtr->f)) {
	    *dst = c;
	    dst++;
	    parseInfoPtr->wordLength++;
	    if (parseInfoPtr->wordLength > MAX_WORD_LENGTH) {
		return TCL_ERROR;
	    }
	}
    }
    if (parseInfoPtr->wordLength == 0) {
	return TCL_ERROR;
    }
    parseInfoPtr->word[parseInfoPtr->wordLength] = 0;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CreatePixmapFromData --
 *
 *	Create a pixmap from the master data, taking into account the
 *	visual requirements of the instance.
 *
 * Results:
 *	A pixmap is created and the instance is set to point to it.
 *
 * Side effects:
 *	A pixmap is created.
 *	Colors will be allocated.
 *
 *----------------------------------------------------------------------
 */

static Pixmap
CreatePixmapFromData(interp, instancePtr, masterPtr)
    Tcl_Interp *interp;			/* For reporting errors */
    PixmapInstance *instancePtr;	/* Instance for a window */
    PixmapMaster *masterPtr;		/* Main data structure */
{
    Display *display = Tk_Display(instancePtr->tkwin);
    Visual *visual = Tk_Visual(instancePtr->tkwin);
    Colormap colormap = Tk_Colormap(instancePtr->tkwin);
    unsigned int depth, width, height;
    XColor **colors = NULL;
    XImage *image;
    Pixmap pixmap;
    XGCValues gcValues;
    GC gc;
    int nc;
    int x, y;
    int pad, bytesPerLine;
    char *dataPtr;

    depth = Tk_Depth(instancePtr->tkwin);
    width = masterPtr->width;
    height = masterPtr->height;
    /*
     * Allocate colors for the pixmap.
     */
    colors = (XColor **)ckalloc(masterPtr->ncolors * sizeof(XColor *));
    for (nc = 0 ; nc<masterPtr->ncolors ; nc++) {
	colors[nc] = Tk_GetColor(interp, instancePtr->tkwin,
				    masterPtr->colormap[nc].color);
	if (colors[nc] == NULL) {
	    int j;
	    for (j=0 ; j<nc ; j++) {
		Tk_FreeColor(colors[j]);
	    }
	    ckfree(colors);
	    return None;
	}
    }
    /*
     * Set up an X image.
     */
    if (depth > 16) {
	pad = 32;
    } else if (depth > 8) {
	pad = 16;
    } else {
	pad = 8;
    }
    /*
     * Fill in the data structure and let Xlib calculate bytes_per_line
     */
    image = XCreateImage(display, visual, depth, ZPixmap, 0, 0,
			width, height, pad, 0);
    image->data = (char *)ckalloc(image->bytes_per_line * height);
    if (image->data == NULL) {
	Tcl_AppendResult(interp, "out of memory ", (char *) NULL);
	goto error;

    }
    /*
     * Fill in the image pixels.  Obviously this could be optimized.
     */
    dataPtr = masterPtr->data;
    for (y=0 ; y<height ; y++) {
	for (x=0 ; x<width ; x++) {
	    XPutPixel(image, x, y, colors[*dataPtr++]->pixel);
	}
    }
    /*
     * Create the (server resident) pixmap and copy the image there.
     */
    pixmap = XCreatePixmap(display, 
		RootWindowOfScreen(Tk_Screen(instancePtr->tkwin)),
		image->width,image->height, image->depth);
    gcValues.function = GXcopy;
    gc = Tk_GetGC(instancePtr->tkwin, GCFunction, &gcValues);

    XPutImage(display, pixmap, gc, image, 0, 0, 0, 0,
	      image->width, image->height);

    /*
     * Normal cleanup
     */
    XDestroyImage(image);
    Tk_FreeGC(display, gc);
    if (instancePtr->colors) {
	ckfree(colors);
    }
    instancePtr->colors = colors;
    return pixmap;
    /*
     * Error cleanup
     */
    error:
    for (nc=0 ; nc<masterPtr->ncolors ; nc++) {
	Tk_FreeColor(colors[nc]);
    }
    ckfree(colors);
    return None;
}

/*
 *--------------------------------------------------------------
 *
 * ImgPixmapCmd --
 *
 *	This procedure is invoked to process the Tcl command
 *	that corresponds to an image managed by this module.
 *	See the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

static int
ImgPixmapCmd(clientData, interp, argc, argv)
    ClientData clientData;	/* Information about button widget. */
    Tcl_Interp *interp;		/* Current interpreter. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings. */
{
    PixmapMaster *masterPtr = (PixmapMaster *) clientData;
    int c, length, code;

    if (argc < 2) {
	sprintf(interp->result,
		"wrong # args: should be \"%.50s option ?arg arg ...?\"",
		argv[0]);
	return TCL_ERROR;
    }
    c = argv[1][0];
    length = strlen(argv[1]);
    if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0)) {
	if (argc == 2) {
	    code = Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
		    configSpecs, (char *) masterPtr, (char *) NULL, 0);
	} else if (argc == 3) {
	    code = Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
		    configSpecs, (char *) masterPtr, argv[2], 0);
	} else {
	    code = ImgPixmapConfigureMaster(masterPtr, argc-2, argv+2,
		    TK_CONFIG_ARGV_ONLY);
	}
	return code;
    } else {
	Tcl_AppendResult(interp, "bad option \"", argv[1],
		"\": must be configure", (char *) NULL);
	return TCL_ERROR;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ImgPixmapGet --
 *
 *	This procedure is called for each use of a pixmap image in a
 *	widget.
 *
 * Results:
 *	The return value is a token for the instance, which is passed
 *	back to us in calls to ImgPixmapDisplay and ImgPixmapFree.
 *
 * Side effects:
 *	A data structure is set up for the instance (or, an existing
 *	instance is re-used for the new one).
 *
 *----------------------------------------------------------------------
 */

static ClientData
ImgPixmapGet(tkwin, masterData)
    Tk_Window tkwin;		/* Window in which the instance will be
				 * used. */
    ClientData masterData;	/* Pointer to our master structure for the
				 * image. */
{
    PixmapMaster *masterPtr = (PixmapMaster *) masterData;
    PixmapInstance *instancePtr;

    /*
     * See if there is already an instance for this window.  If so
     * then just re-use it.
     */

    for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
	    instancePtr = instancePtr->nextPtr) {
	if (instancePtr->tkwin == tkwin) {
	    instancePtr->refCount++;
	    return (ClientData) instancePtr;
	}
    }

    /*
     * The image isn't already in use in this window.  Make a new
     * instance of the image.
     */

    instancePtr = (PixmapInstance *) ckalloc(sizeof(PixmapInstance));
    instancePtr->refCount = 1;
    instancePtr->masterPtr = masterPtr;
    instancePtr->tkwin = tkwin;
    instancePtr->pixmap = None;
    instancePtr->colors = NULL;
    instancePtr->mask = None;
    instancePtr->gc = None;
    instancePtr->nextPtr = masterPtr->instancePtr;
    masterPtr->instancePtr = instancePtr;
    ImgPixmapConfigureInstance(instancePtr);

    /*
     * If this is the first instance, must set the size of the image.
     */

    if (instancePtr->nextPtr == NULL) {
	Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, masterPtr->width,
		masterPtr->height);
    }

    return (ClientData) instancePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * ImgPixmapDisplay --
 *
 *	This procedure is invoked to draw a pixmap image.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A portion of the image gets rendered in a pixmap or window.
 *
 *----------------------------------------------------------------------
 */

static void
ImgPixmapDisplay(clientData, display, drawable, imageX, imageY, width,
	height, drawableX, drawableY)
    ClientData clientData;	/* Pointer to PixmapInstance structure for
				 * for instance to be displayed. */
    Display *display;		/* Display on which to draw image. */
    Drawable drawable;		/* Pixmap or window in which to draw image. */
    int imageX, imageY;		/* Upper-left corner of region within image
				 * to draw. */
    unsigned int width, height;	/* Dimensions of region within image to draw. */
    int drawableX, drawableY;	/* Coordinates within drawable that
				 * correspond to imageX and imageY. */
{
    PixmapInstance *instancePtr = (PixmapInstance *) clientData;

    /*
     * If there's no graphics context, it means that an error occurred
     * while creating the image instance so it can't be displayed.
     */

    if (instancePtr->gc == None) {
	return;
    }

    /*
     * If masking is in effect, must modify the mask origin within
     * the graphics context to line up with the image's origin.
     * Then draw the image and reset the clip origin, if there's
     * a mask.
     */

    if (instancePtr->mask != None) {
	XSetClipOrigin(display, instancePtr->gc, drawableX - imageX,
		drawableY - imageY);
    }
    XCopyArea(display, instancePtr->pixmap, drawable, instancePtr->gc,
	    imageX, imageY, width, height, drawableX, drawableY);
    if (instancePtr->mask != None) {
	XSetClipOrigin(display, instancePtr->gc, 0, 0);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ImgPixmapFree --
 *
 *	This procedure is called when a widget ceases to use a
 *	particular instance of an image.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Internal data structures get cleaned up.
 *
 *----------------------------------------------------------------------
 */

static void
ImgPixmapFree(clientData, display)
    ClientData clientData;	/* Pointer to PixmapInstance structure for
				 * for instance to be displayed. */
    Display *display;		/* Display containing window that used image. */
{
    PixmapInstance *instancePtr = (PixmapInstance *) clientData;
    PixmapMaster *masterPtr = instancePtr->masterPtr;
    PixmapInstance *prevPtr;
    int nc;

    instancePtr->refCount--;
    if (instancePtr->refCount > 0) {
	return;
    }

    /*
     * There are no more uses of the image within this widget.  Free
     * the instance structure.
     */
    if (instancePtr->colors) {
	for (nc=0 ; nc<masterPtr->ncolors ; nc++) {
	    Tk_FreeColor(instancePtr->colors[nc]);
	}
	ckfree(instancePtr->colors);
    }
    if (instancePtr->pixmap != None) {
	XFreePixmap(display, instancePtr->pixmap);
    }
    if (instancePtr->mask != None) {
	XFreePixmap(display, instancePtr->mask);
    }
    if (instancePtr->gc != None) {
	Tk_FreeGC(display, instancePtr->gc);
    }
    if (instancePtr->masterPtr->instancePtr == instancePtr) {
	instancePtr->masterPtr->instancePtr = instancePtr->nextPtr;
    } else {
	for (prevPtr = instancePtr->masterPtr->instancePtr;
		prevPtr->nextPtr != instancePtr; prevPtr = prevPtr->nextPtr) {
	    /* Empty loop body */
	}
	prevPtr->nextPtr = instancePtr->nextPtr;
    }
    ckfree((char *) instancePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * ImgPixmapDelete --
 *
 *	This procedure is called by the image code to delete the
 *	master structure for an image.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Resources associated with the image get freed.
 *
 *----------------------------------------------------------------------
 */

static void
ImgPixmapDelete(masterData)
    ClientData masterData;	/* Pointer to PixmapMaster structure for
				 * image.  Must not have any more instances. */
{
    PixmapMaster *masterPtr = (PixmapMaster *) masterData;

    if (masterPtr->instancePtr != NULL) {
	panic("tried to delete pixmap image when instances still exist");
    }
    if (masterPtr->colormap != NULL) {
	ckfree(masterPtr->colormap);
    }
    ckfree(masterPtr->imageName);
    if (masterPtr->data != NULL) {
	ckfree(masterPtr->data);
    }
    if (masterPtr->maskData != NULL) {
	ckfree(masterPtr->maskData);
    }
    Tk_FreeOptions(configSpecs, (char *) masterPtr, (Display *) NULL, 0);
    ckfree((char *) masterPtr);
}
