
#include "color.h"

int get_color (Display *display, int screen_num, char *name, unsigned long *color)
{
    int      default_depth;
    Visual   *default_visual;
    XColor   exact_def;
    Colormap default_cmap;
    int      i = 5;

    XVisualInfo visual_info;

    /*
     * Try to allocate colors for PseudoColor, TrueColor,
     * DirectColor, and StaticColor; use black and white
     * for StaticGray and GrayScale
     */
    default_depth  = DefaultDepth(display, screen_num);
    default_visual = DefaultVisual(display, screen_num);
    default_cmap   = DefaultColormap(display, screen_num);
    if (default_depth == 1) {
        /* Must be StaticGray, use black and white */
        *color = WhitePixel(display, screen_num);
        return(0);
    }

    while (!XMatchVisualInfo(display, screen_num, default_depth,
         /* visual class */i--, &visual_info))
        ;

    //printf("found a %s class visual at default depth.\n",
    //      visual_class[++i]);

    /* Color visual classes are 2 to 5 */
    if (i < StaticColor) {
        /*
         * No color visual available at default depth;
         * some applications might call XMatchVisualInfo
         * here to try for a GrayScale visual if they
         * can use gray to advantage, before giving up
         * and using black and white
         */
        *color = WhitePixel(display, screen_num);
        return(0);
    }

    /* Otherwise, got a color visual at default depth */
   
    /*
     * The visual we found is not necessarily the default
     * visual, and therefore it is not necessarily the one
     * we used to create our window; however, we now know
     * for sure that color is supported, so the following
     * code will work (or fail in a controlled way)
     */

    /* Let's check just out of curiosity: */
    if (visual_info.visual != default_visual) {
        //printf("%s class visual at default depth\n", visual_class[i]);
        //printf("is not default visual! Continuing anyway...\n");
    }

    //printf("allocating %s\n", name);
    if (!XParseColor (display, default_cmap, name, &exact_def)) {
        fprintf(stderr, "color name %s not in database", name);
        return(-1);
    }

    /*
    printf("The RGB values from the database are %d, %d, %d\n",
            exact_def.red, exact_def.green, exact_def.blue);
     */
    if (!XAllocColor(display, default_cmap, &exact_def)) {
        fprintf(stderr, "can't allocate color:\n");
        fprintf(stderr, "All colorcells allocated and\n");
        fprintf(stderr, "no matching cell found.\n");
        return(-1);
    }

    //printf("The RGB values actually allocated are %d, %d, %d\n",
    //      exact_def.red, exact_def.green,
    //      exact_def.blue);
    *color = exact_def.pixel;
    return(0);
}
