/*
 * ----------------------------------------------------------------------------
 * grTkDefineCursor:
 *
 *	Define a new set of cursors.  Use Tk-style cursors (portable)
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The given matrix is stored in the graphics display, and it can be
 *	used as the cursor by calling GrSetCursor.
 * ----------------------------------------------------------------------------
 */

Void
grTkDefineCursor(glyphs)
    GrGlyphs *glyphs;
{
    int glyphnum;
    Rect oldClip;
    int red, green, blue;
    bool isblack;

    if (glyphs->gr_num <= 0) return;

    if (glyphs->gr_num > MAX_CURSORS)
    {
	TxError("X only has room for %d cursors\n", MAX_CURSORS);
	return;
    }

    /* expand clipping amount for off-screen access on the X */
    GrLock(GR_LOCK_SCREEN, FALSE);
    oldClip = grCurClip;
    grCurClip = GrScreenRect;
    grCurClip.r_ytop += 16;
    
    /* what color should the cursor be?  The following makes it the
       opposite of what the background "mostly" is.
    */
    GrGetColor(GrStyleTable[STYLE_TRANSPARENT].color, &red, &green, &blue);
    isblack = (red + green + blue > 0x180);	/* (0x180 = 128 * 3) */

    /* enter the glyphs */
    for (glyphnum = 0; glyphnum < glyphs->gr_num; glyphnum++) {
	int *p;
	GrGlyph *g;
	int x, y;
	unsigned char *curs;

	g = glyphs->gr_glyph[glyphnum];
	if ((g->gr_xsize != 16) || (g->gr_ysize != 16)) {
	    TxError("Tk/OpenGL Cursors must be 16 X 16 pixels.\n");
	    return;
	}
	
	curs = (unsigned char *)mallocMagic(32 * sizeof(unsigned char));
	g->gr_cache = (ClientData)curs;
	g->gr_free = freeMagic;

	/* Perform transposition on the glyph matrix since X displays
	 * the least significant bit on the left hand side.
	 */
	p = &(g->gr_pixels[0]);
	for (y = 0; y < 32; y += 2) {
	    int i;

	    curs[i = 31 - y - 1] = 0;
	    for (x = 0; x < 8; x++) 
	    {
		if (GrStyleTable[*p].color != 0)
		{
		     curs[i] |= 1 << x; 
		}
		p++;
	    }
	    curs[i += 1] = 0;
	    for (x = 0; x < 8; x++) 
	    {
		if (GrStyleTable[*p].color != 0)
		{
		     curs[i] |= 1 << x; 
		}
		p++;
	    }
	}
	grCursors[glyphnum] = Tk_GetCursorFromData(magicinterp,
			Tk_MainWindow(magicinterp),
			(char *)curs, (char *)curs,
			16, 16, g->gr_origin.p_x, (15 - g->gr_origin.p_y),
			((isblack) ? "black" : "white"),
			((isblack) ? "white" : "black"));
    }

    /* Restore clipping */
    grCurClip = oldClip;
    GrUnlock(GR_LOCK_SCREEN);
}

