/* context.c - X context management
 * 
 *  Raster graphics library
 * 
 *  Copyright (c) 1997 Alfredo K. Kojima
 * 
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *  
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *  
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */


#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <stdlib.h>

#include "wraster.h"

static XColor*
allocatePseudoColor(RContext *ctx, int cpc)
{
    XColor *colors;
    XColor avcolors[256];
    int avncolors;
    int i, ncolors, r, g, b;
    int retries;

    ncolors = cpc * cpc * cpc;
    colors = malloc(sizeof(XColor)*ncolors);
    if (!colors) {
	sprintf(RErrorString, "out of memory");
	return False;
    }
    i=0;
    for (r=0; r<cpc; r++) {
	for (g=0; g<cpc; g++) {
	    for (b=0; b<cpc; b++) {
		colors[i].red=(r*0xffff) / (cpc-1);
		colors[i].green=(g*0xffff) / (cpc-1);
		colors[i].blue=(b*0xffff) / (cpc-1);
		colors[i].flags = DoRed|DoGreen|DoBlue;
		i++;
	    }
	}
    }
    /* try to allocate the colors */
    for (i=0; i<ncolors; i++) {
	if (!XAllocColor(ctx->dpy, ctx->cmap, &(colors[i]))) {
	    colors[i].flags = 0; /* failed */
	} else {
	    colors[i].flags = DoRed|DoGreen|DoBlue;	    
	}
    }
    /* try to allocate close values for the colors that couldn't 
     * be allocated before */
    avncolors = (1<<ctx->depth>256 ? 256 : 1<<ctx->depth);
    for (i=0; i<avncolors; i++) avcolors[i].pixel = i;

    XQueryColors(ctx->dpy, ctx->cmap, avcolors, avncolors);

    for (i=0; i<ncolors; i++) {
	if (colors[i].flags==0) {
	    int j;
	    unsigned long cdiff=0xffffffff, diff;
	    unsigned long closest=0;
	    
	    retries = 2;
	    
	    while (retries--) {
		/* find closest color */
		for (j=0; j<avncolors; j++) {
		    r = (colors[i].red - avcolors[i].red)>>8;
		    g = (colors[i].green - avcolors[i].green)>>8;
		    b = (colors[i].blue - avcolors[i].blue)>>8;
		    diff = r*r + g*g + b*b;
		    if (diff<cdiff) {
			cdiff = diff;
			closest = j;
		    }
		}
		/* allocate closest color found */
		colors[i].red = avcolors[closest].red;
		colors[i].green = avcolors[closest].green;
		colors[i].blue = avcolors[closest].blue;
		if (XAllocColor(ctx->dpy, ctx->cmap, &colors[i])) {
		    colors[i].flags = DoRed|DoGreen|DoBlue;
		    break; /* succeeded, don't need to retry */
		}
#ifdef DEBUG
		printf("close color allocation failed. Retrying...\n");
#endif
	    }
	}
    }
    return colors;
}


static XColor*
allocateGrayScale(RContext *ctx, int cpc)
{
    XColor *colors;
    XColor avcolors[256];
    int avncolors;
    int i, ncolors, r, g, b;
    int retries;

    ncolors = cpc * cpc * cpc;
    colors = malloc(sizeof(XColor)*ncolors);
    if (!colors) {
	sprintf(RErrorString, "out of memory");
	return False;
    }
    for (i=0; i<cpc*cpc*cpc; i++) {
	colors[i].red=(i*0xffff) / (cpc-1);
	colors[i].green=(i*0xffff) / (cpc-1);
	colors[i].blue=(i*0xffff) / (cpc-1);
	colors[i].flags = DoRed|DoGreen|DoBlue;
    }
    /* try to allocate the colors */
    for (i=0; i<ncolors; i++) {
	if (!XAllocColor(ctx->dpy, ctx->cmap, &(colors[i]))) {
	    colors[i].flags = 0; /* failed */
	} else {
	    colors[i].flags = DoRed|DoGreen|DoBlue;	    
	}
    }
    /* try to allocate close values for the colors that couldn't 
     * be allocated before */
    avncolors = (1<<ctx->depth>256 ? 256 : 1<<ctx->depth);
    for (i=0; i<avncolors; i++) avcolors[i].pixel = i;

    XQueryColors(ctx->dpy, ctx->cmap, avcolors, avncolors);

    for (i=0; i<ncolors; i++) {
	if (colors[i].flags==0) {
	    int j;
	    unsigned long cdiff=0xffffffff, diff;
	    unsigned long closest=0;
	    
	    retries = 2;
	    
	    while (retries--) {
		/* find closest color */
		for (j=0; j<avncolors; j++) {
		    r = (colors[i].red - avcolors[i].red)>>8;
		    g = (colors[i].green - avcolors[i].green)>>8;
		    b = (colors[i].blue - avcolors[i].blue)>>8;
		    diff = r*r + g*g + b*b;
		    if (diff<cdiff) {
			cdiff = diff;
			closest = j;
		    }
		}
		/* allocate closest color found */
		colors[i].red = avcolors[closest].red;
		colors[i].green = avcolors[closest].green;
		colors[i].blue = avcolors[closest].blue;
		if (XAllocColor(ctx->dpy, ctx->cmap, &colors[i])) {
		    colors[i].flags = DoRed|DoGreen|DoBlue;
		    break; /* succeeded, don't need to retry */
		}
#ifdef DEBUG
		printf("close color allocation failed. Retrying...\n");
#endif
	    }
	}
    }
    return colors;
}



RContext*
RCreateContext(Display *dpy, XVisualInfo *vinfo, int screen_number, int mode,
	       int cpc)
{
    RContext *context;
    XGCValues gcv;

    RErrorString[0]=0;
    context = malloc(sizeof(RContext));
    if (!context) {
	sprintf(RErrorString, "out of memory");
	return NULL;
    }
    context->dpy = dpy;
    if (!vinfo) {
	context->visual = DefaultVisual(dpy, screen_number);
	context->depth = DefaultDepth(dpy, screen_number);
	context->cmap = DefaultColormap(dpy, screen_number);
	context->drawable = RootWindow(dpy, screen_number);
	context->class = context->visual->class; 
    } else {
	sprintf(RErrorString, "visual != default not supported yet");
	return NULL;
	context->drawable =
	  XCreateSimpleWindow(dpy, RootWindow(dpy, screen_number),
			      -1, -1, 1, 1, 0, 0, 0);
    }
    context->mode = mode;
    gcv.function = GXcopy;
    context->copy_gc = XCreateGC(dpy, context->drawable, GCFunction, &gcv);
    
    
    context->cpc = cpc;
    if (context->class == PseudoColor) {
	context->colors = allocatePseudoColor(context, cpc);
	if (!context->colors) {
	    return NULL;
	}
    } else if (context->class == GrayScale) {
	context->colors = allocateGrayScale(context, cpc);
	if (!context->colors) {
	    return NULL;
	}
    }
    return context;
}

