+ // get the allocated values from the X server (only the first 256 XXX why!?)
+ XColor icolors[256];
+ int incolors = (((1 << depth) > 256) ? 256 : (1 << depth));
+ for (int i = 0; i < incolors; i++)
+ icolors[i].pixel = i;
+ XQueryColors(**display, info->colormap(), icolors, incolors);
+
+ // try match unallocated ones
+ for (int i = 0; i < _ncolors; i++) {
+ if (!_colors[i].flags) { // if it wasn't allocated...
+ unsigned long closest = 0xffffffff, close = 0;
+ for (int ii = 0; ii < incolors; ii++) {
+ // find deviations
+ int r = (_colors[i].red - icolors[ii].red) & 0xff;
+ int g = (_colors[i].green - icolors[ii].green) & 0xff;
+ int b = (_colors[i].blue - icolors[ii].blue) & 0xff;
+ // find a weighted absolute deviation
+ unsigned long dev = (r * r) + (g * g) + (b * b);
+
+ if (dev < closest) {
+ closest = dev;
+ close = ii;
+ }
+ }
+
+ _colors[i].red = icolors[close].red;
+ _colors[i].green = icolors[close].green;
+ _colors[i].blue = icolors[close].blue;
+ _colors[i].pixel = icolors[close].pixel;
+
+ // try alloc this closest color, it had better succeed!
+ if (XAllocColor(**display, info->colormap(), &_colors[i]))
+ _colors[i].flags = DoRed|DoGreen|DoBlue; // mark as alloced
+ else
+ assert(false); // wtf has gone wrong, its already alloced for chissake!
+ }
+ }