]> Pileus Git - ~andy/gtk/blob - gdk/x11/gdkcc-x11.c
Only query the colormap for GRAYSCALE and PSEUDOCOLOR visuals, and don't
[~andy/gtk] / gdk / x11 / gdkcc-x11.c
1 /* GDK - The GIMP Drawing Kit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the Free
16  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 /* Color Context module
20  * Copyright 1994,1995 John L. Cwikla
21  * Copyright (C) 1997 by Ripley Software Development
22  * Copyright (C) 1997 by Federico Mena (port to Gtk/Gdk)
23  */
24
25 /* Copyright 1994,1995 John L. Cwikla
26  *
27  * Permission to use, copy, modify, distribute, and sell this software
28  * and its documentation for any purpose is hereby granted without fee,
29  * provided that the above copyright notice appears in all copies and that
30  * both that copyright notice and this permission notice appear in
31  * supporting documentation, and that the name of John L. Cwikla or
32  * Wolfram Research, Inc not be used in advertising or publicity
33  * pertaining to distribution of the software without specific, written
34  * prior permission.  John L. Cwikla and Wolfram Research, Inc make no
35  * representations about the suitability of this software for any
36  * purpose.  It is provided "as is" without express or implied warranty.
37  *
38  * John L. Cwikla and Wolfram Research, Inc disclaim all warranties with
39  * regard to this software, including all implied warranties of
40  * merchantability and fitness, in no event shall John L. Cwikla or
41  * Wolfram Research, Inc be liable for any special, indirect or
42  * consequential damages or any damages whatsoever resulting from loss of
43  * use, data or profits, whether in an action of contract, negligence or
44  * other tortious action, arising out of or in connection with the use or
45  * performance of this software.
46  *
47  * Author:
48  *  John L. Cwikla
49  *  X Programmer
50  *  Wolfram Research Inc.
51  *
52  *  cwikla@wri.com
53  */
54
55
56 #include <X11/Xlib.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include "gdk.h"
60 #include "gdkprivate.h"
61 #include "gdkx.h"
62
63
64 #define MAX_IMAGE_COLORS 256
65
66
67 static guint
68 hash_color (gpointer key)
69 {
70   GdkColor *color = key;
71
72   return (color->red * 33023 + color->green * 30013 + color->blue * 27011);
73 }
74
75 static gint
76 compare_colors (gpointer a,
77                 gpointer b)
78 {
79   GdkColor *aa = a;
80   GdkColor *bb = b;
81
82   return ((aa->red == bb->red) && (aa->green == bb->green) && (aa->blue == bb->blue));
83 }
84
85 static void
86 free_hash_entry (gpointer key,
87                  gpointer value,
88                  gpointer user_data)
89 {
90   g_free (key); /* key and value are the same GdkColor */
91 }
92
93 static int
94 pixel_sort (const void *a, const void *b)
95 {
96   return ((GdkColor *) a)->pixel - ((GdkColor *) b)->pixel;
97 }
98
99 /* XXX: This function does an XQueryColors() the hard way, because there is
100  * no corresponding function in Gdk.
101  */
102
103 static void
104 my_x_query_colors (GdkColormap *colormap,
105                    GdkColor    *colors,
106                    gint         ncolors)
107 {
108   XColor *xcolors;
109   gint    i;
110
111   xcolors = g_new (XColor, ncolors);
112   for (i = 0; i < ncolors; i++)
113     xcolors[i].pixel = colors[i].pixel;
114
115   XQueryColors (gdk_display, GDK_COLORMAP_XCOLORMAP (colormap), xcolors, ncolors);
116
117   for (i = 0; i < ncolors; i++)
118     {
119       colors[i].red   = xcolors[i].red;
120       colors[i].green = xcolors[i].green;
121       colors[i].blue  = xcolors[i].blue;
122     }
123
124   g_free (xcolors);
125 }
126
127 static void
128 query_colors (GdkColorContext *cc)
129 {
130   gint i;
131   GdkColorContextPrivate *ccp = (GdkColorContextPrivate *) cc;
132   cc->cmap = g_new (GdkColor, cc->num_colors);
133
134   for (i = 0; i < cc->num_colors; i++)
135     cc->cmap[i].pixel = cc->clut ? cc->clut[i] : ccp->std_cmap.base_pixel + i;
136
137   my_x_query_colors (cc->colormap, cc->cmap, cc->num_colors);
138         
139   qsort (cc->cmap, cc->num_colors, sizeof (GdkColor), pixel_sort);
140 }
141
142 static void
143 init_bw (GdkColorContext *cc)
144 {
145   GdkColor color;
146
147   g_warning ("init_bw: failed to allocate colors, falling back to black and white");
148
149   cc->mode = GDK_CC_MODE_BW;
150
151   color.red = color.green = color.blue = 0;
152   
153   if (!gdk_color_alloc (cc->colormap, &color))
154     cc->black_pixel = 0;
155   else
156     cc->black_pixel = color.pixel;
157
158   color.red = color.green = color.blue = 0xffff;
159   
160   if (!gdk_color_alloc (cc->colormap, &color))
161     cc->white_pixel = cc->black_pixel ? 0 : 1;
162   else
163     cc->white_pixel = color.pixel;
164
165   cc->num_colors = 2;
166 }
167
168 static void
169 init_gray (GdkColorContext *cc)
170 {
171   GdkColorContextPrivate *ccp = (GdkColorContextPrivate *) cc;
172   GdkColor *clrs, *cstart;
173   gint i;
174   gdouble dinc;
175         
176   cc->num_colors = GDK_VISUAL_XVISUAL (cc->visual)->map_entries;
177
178   cc->clut = g_new (gulong, cc->num_colors);
179   cstart = g_new (GdkColor, cc->num_colors);
180
181 retrygray:
182
183   dinc = 65535.0 / (cc->num_colors - 1);
184
185   clrs = cstart;
186
187   for (i = 0; i < cc->num_colors; i++)
188     {
189       clrs->red = clrs->green = clrs->blue = dinc * i;
190
191       if (!gdk_color_alloc (cc->colormap, clrs))
192         {
193           gdk_colors_free (cc->colormap, cc->clut, i, 0);
194
195           cc->num_colors /= 2;
196
197           if (cc->num_colors > 1)
198             goto retrygray;
199           else
200             {
201               g_free (cc->clut);
202               cc->clut = NULL;
203               init_bw (cc);
204               g_free (cstart);
205               return;
206             }
207         }
208
209       cc->clut[i] = clrs++->pixel;
210     }
211
212   g_free (cstart);
213
214   /* XXX: is this the right thing to do? */
215   ccp->std_cmap.colormap = GDK_COLORMAP_XCOLORMAP (cc->colormap);
216   ccp->std_cmap.base_pixel = 0;
217   ccp->std_cmap.red_max = cc->num_colors - 1;
218   ccp->std_cmap.green_max = 0;
219   ccp->std_cmap.blue_max = 0;
220   ccp->std_cmap.red_mult = 1;
221   ccp->std_cmap.green_mult = 0;
222   ccp->std_cmap.blue_mult = 0;
223
224   cc->white_pixel = WhitePixel (ccp->xdisplay, gdk_screen);
225   cc->black_pixel = BlackPixel (ccp->xdisplay, gdk_screen);
226
227   query_colors (cc);
228
229   cc->mode = GDK_CC_MODE_MY_GRAY;
230 }
231
232 static void
233 init_color (GdkColorContext *cc)
234 {
235   GdkColorContextPrivate *ccp = (GdkColorContextPrivate *) cc;
236   gint cubeval;
237
238   cubeval = 1;
239   while ((cubeval * cubeval * cubeval) < GDK_VISUAL_XVISUAL (cc->visual)->map_entries)
240     cubeval++;
241   cubeval--;
242
243   cc->num_colors = cubeval * cubeval * cubeval;
244
245   ccp->std_cmap.red_max    = cubeval - 1;
246   ccp->std_cmap.green_max  = cubeval - 1;
247   ccp->std_cmap.blue_max   = cubeval - 1;
248   ccp->std_cmap.red_mult   = cubeval * cubeval;
249   ccp->std_cmap.green_mult = cubeval;
250   ccp->std_cmap.blue_mult  = 1;
251   ccp->std_cmap.base_pixel = 0;
252
253   cc->white_pixel = WhitePixel (ccp->xdisplay, gdk_screen);
254   cc->black_pixel = BlackPixel (ccp->xdisplay, gdk_screen);
255   cc->num_colors = DisplayCells (ccp->xdisplay, gdk_screen);
256
257   /* a CLUT for storing allocated pixel indices */
258
259   cc->max_colors = cc->num_colors;
260   cc->clut = g_new (gulong, cc->max_colors);
261
262   for (cubeval = 0; cubeval < cc->max_colors; cubeval++)
263     cc->clut[cubeval] = cubeval;
264
265   query_colors (cc);
266
267   cc->mode = GDK_CC_MODE_STD_CMAP;
268 }
269
270
271 static void
272 init_true_color (GdkColorContext *cc)
273 {
274   GdkColorContextPrivate *ccp = (GdkColorContextPrivate *) cc;
275   gulong rmask, gmask, bmask;
276
277   cc->mode = GDK_CC_MODE_TRUE;
278
279   /* Red */
280
281   rmask = cc->masks.red = cc->visual->red_mask;
282
283   cc->shifts.red = 0;
284   cc->bits.red = 0;
285
286   while (!(rmask & 1))
287     {
288       rmask >>= 1;
289       cc->shifts.red++;
290     }
291
292   while (rmask & 1)
293     {
294       rmask >>= 1;
295       cc->bits.red++;
296     }
297
298   /* Green */
299
300   gmask = cc->masks.green = cc->visual->green_mask;
301
302   cc->shifts.green = 0;
303   cc->bits.green = 0;
304
305   while (!(gmask & 1))
306     {
307       gmask >>= 1;
308       cc->shifts.green++;
309     }
310
311   while (gmask & 1)
312     {
313       gmask >>= 1;
314       cc->bits.green++;
315     }
316
317   /* Blue */
318
319   bmask = cc->masks.blue = cc->visual->blue_mask;
320
321   cc->shifts.blue = 0;
322   cc->bits.blue = 0;
323
324   while (!(bmask & 1))
325     {
326       bmask >>= 1;
327       cc->shifts.blue++;
328     }
329
330   while (bmask & 1)
331     {
332       bmask >>= 1;
333       cc->bits.blue++;
334     }
335
336   cc->num_colors = (cc->visual->red_mask | cc->visual->green_mask | cc->visual->blue_mask) + 1;
337   cc->white_pixel = WhitePixel (ccp->xdisplay, gdk_screen);
338   cc->black_pixel = BlackPixel (ccp->xdisplay, gdk_screen);
339 }
340
341 static void
342 init_direct_color (GdkColorContext *cc)
343 {
344   gint n, count;
345   GdkColor *clrs, *cstart;
346   gulong rval, gval, bval;
347   gulong *rtable;
348   gulong *gtable;
349   gulong *btable;
350   gdouble dinc;
351
352   init_true_color (cc); /* for shift stuff */
353
354   rval = cc->visual->red_mask >> cc->shifts.red;
355   gval = cc->visual->green_mask >> cc->shifts.green;
356   bval = cc->visual->blue_mask >> cc->shifts.blue;
357
358   rtable = g_new (gulong, rval + 1);
359   gtable = g_new (gulong, gval + 1);
360   btable = g_new (gulong, bval + 1);
361
362   cc->max_entry = MAX (rval, gval);
363   cc->max_entry = MAX (cc->max_entry, bval);
364
365   cstart = g_new (GdkColor, cc->max_entry + 1);
366   cc->clut = g_new (gulong, cc->max_entry + 1);
367
368 retrydirect:
369
370   for (n = 0; n < rval; n++)
371     rtable[n] = rval ? (65535.0 / rval * n) : 0;
372
373   for (n = 0; n < gval; n++)
374     gtable[n] = gval ? (65535.0 / gval * n) : 0;
375
376   for (n = 0; n < bval; n++)
377     btable[n] = bval ? (65535.0 / bval * n) : 0;
378
379   cc->max_entry = MAX (rval, gval);
380   cc->max_entry = MAX (cc->max_entry, bval);
381
382   count = 0;
383   clrs = cstart;
384   cc->num_colors = (rval + 1) * (gval + 1) * (bval + 1);
385
386   for (n = 0; n < cc->max_entry; n++)
387     {
388       dinc = (double) n / cc->max_entry;
389
390       clrs->red   = rtable[(int) (dinc * rval)];
391       clrs->green = gtable[(int) (dinc * gval)];
392       clrs->blue  = btable[(int) (dinc * bval)];
393
394       if (gdk_color_alloc (cc->colormap, clrs))
395         {
396           cc->clut[count++] = clrs->pixel;
397           clrs++;
398         }
399       else
400         {
401           gdk_colors_free (cc->colormap, cc->clut, count, 0);
402
403           rval >>= 1;
404           gval >>= 1;
405           bval >>= 1;
406
407           cc->masks.red   = (cc->masks.red >> 1) & cc->visual->red_mask;
408           cc->masks.green = (cc->masks.green >> 1) & cc->visual->green_mask;
409           cc->masks.blue  = (cc->masks.blue >> 1) & cc->visual->blue_mask;
410
411           cc->shifts.red++;
412           cc->shifts.green++;
413           cc->shifts.blue++;
414
415           cc->bits.red--;
416           cc->bits.green--;
417           cc->bits.blue--;
418
419           cc->num_colors = (rval + 1) * (gval + 1) * (bval + 1);
420
421           if (cc->num_colors >1)
422             goto retrydirect;
423           else
424             {
425               g_free (cc->clut);
426               cc->clut = NULL;
427               init_bw (cc);
428               break;
429             }
430         }
431     }
432
433   /* Update allocated color count; original num_colors is max_entry, which
434    * is not necessarily the same as the really allocated number of colors.
435    */
436
437   cc->num_colors = count;
438
439   g_free (rtable);
440   g_free (gtable);
441   g_free (btable);
442   g_free (cstart);
443 }
444
445 static void
446 init_palette (GdkColorContext *cc)
447 {
448   /* restore correct mode for this cc */
449         
450   switch (cc->visual->type)
451     {
452     case GDK_VISUAL_STATIC_GRAY:
453     case GDK_VISUAL_GRAYSCALE:
454       if (GDK_VISUAL_XVISUAL (cc->visual)->map_entries == 2)
455         cc->mode = GDK_CC_MODE_BW;
456       else
457         cc->mode = GDK_CC_MODE_MY_GRAY;
458       break;
459
460     case GDK_VISUAL_TRUE_COLOR:
461     case GDK_VISUAL_DIRECT_COLOR:
462       cc->mode = GDK_CC_MODE_TRUE;
463       break;
464
465     case GDK_VISUAL_STATIC_COLOR:
466     case GDK_VISUAL_PSEUDO_COLOR:
467       cc->mode = GDK_CC_MODE_STD_CMAP;
468       break;
469
470     default:
471       cc->mode = GDK_CC_MODE_UNDEFINED;
472       break;
473     }
474
475   /* previous palette */
476
477   if (cc->num_palette)
478     g_free (cc->palette);
479
480   if (cc->fast_dither)
481     g_free (cc->fast_dither);
482
483   /* clear hash table if present */
484
485   if (cc->color_hash)
486     {
487       /* XXX: quick-and-dirty way to remove everything */
488
489       g_hash_table_destroy (cc->color_hash);
490       cc->color_hash = g_hash_table_new (hash_color, compare_colors);
491     }
492
493   cc->palette = NULL;
494   cc->num_palette = 0;
495   cc->fast_dither = NULL;
496 }
497
498 GdkColorContext *
499 gdk_color_context_new (GdkVisual   *visual,
500                        GdkColormap *colormap)
501 {
502   GdkColorContextPrivate *ccp;
503   gint use_private_colormap = FALSE; /* XXX: maybe restore full functionality later? */
504   GdkColorContext *cc;
505   gint retry_count;
506   GdkColormap *default_colormap;
507
508   g_assert (visual != NULL);
509   g_assert (colormap != NULL);
510
511   ccp = g_new (GdkColorContextPrivate, 1);
512   cc = (GdkColorContext *) ccp;
513   ccp->xdisplay = gdk_display;
514   cc->visual = visual;
515   cc->colormap = colormap;
516   cc->clut = NULL;
517   cc->cmap = NULL;
518   cc->mode = GDK_CC_MODE_UNDEFINED;
519   cc->need_to_free_colormap = FALSE;
520
521   cc->color_hash = NULL;
522   cc->palette = NULL;
523   cc->num_palette = 0;
524   cc->fast_dither = NULL;
525
526   default_colormap = gdk_colormap_get_system ();
527
528   retry_count = 0;
529
530   while (retry_count < 2)
531     {
532       /* Only create a private colormap if the visual found isn't equal
533        * to the default visual and we don't have a private colormap,
534        * -or- if we are instructed to create a private colormap (which
535        * never is the case for XmHTML).
536        */
537
538       if (use_private_colormap
539           || ((cc->visual != gdk_visual_get_system ()) /* default visual? */
540               && (GDK_COLORMAP_XCOLORMAP (colormap) == GDK_COLORMAP_XCOLORMAP (default_colormap))))
541         {
542           g_warning ("gdk_color_context_new: non-default visual detected, "
543                      "using private colormap");
544
545           cc->colormap = gdk_colormap_new (cc->visual, FALSE);
546
547           cc->need_to_free_colormap = (GDK_COLORMAP_XCOLORMAP (colormap)
548                                        != GDK_COLORMAP_XCOLORMAP (default_colormap));
549         }
550
551       switch (visual->type)
552         {
553         case GDK_VISUAL_STATIC_GRAY:
554         case GDK_VISUAL_GRAYSCALE:
555           if (gdk_debug_level >= 1)
556             g_print ("gdk_color_context_new: visual class is %s",
557                      (visual->type == GDK_VISUAL_STATIC_GRAY) ?
558                      "GDK_VISUAL_STATIC_GRAY" :
559                      "GDK_VISUAL_GRAYSCALE");
560
561           if (GDK_VISUAL_XVISUAL (cc->visual)->map_entries == 2)
562             init_bw (cc);
563           else
564             init_gray (cc);
565
566           break;
567
568         case GDK_VISUAL_TRUE_COLOR: /* shifts */
569           if (gdk_debug_level >= 1)
570             g_print ("gdk_color_context_new: visual class is "
571                      "GDK_VISUAL_TRUE_COLOR");
572
573           init_true_color (cc);
574           break;
575
576         case GDK_VISUAL_DIRECT_COLOR: /* shifts and fake CLUT */
577           if (gdk_debug_level >= 1)
578             g_print ("gdk_color_context_new: visual class is "
579                      "GDK_VISUAL_DIRECT_COLOR");
580
581           init_direct_color (cc);
582           break;
583
584         case GDK_VISUAL_STATIC_COLOR:
585         case GDK_VISUAL_PSEUDO_COLOR:
586           if (gdk_debug_level >= 1)
587             g_print ("gdk_color_context_new: visual class is %s",
588                      (visual->type == GDK_VISUAL_STATIC_COLOR) ?
589                      "GDK_VISUAL_STATIC_COLOR" :
590                      "GDK_VISUAL_PSEUDO_COLOR");
591
592           init_color (cc);
593           break;
594
595         default:
596           g_assert_not_reached ();
597         }
598
599       if ((cc->mode == GDK_CC_MODE_BW) && (cc->visual->depth > 1))
600         {
601           use_private_colormap = TRUE;
602           retry_count++;
603         }
604       else
605         break;
606     }
607
608   /* no. of colors allocated yet */
609
610   cc->num_allocated = 0;
611
612   if (gdk_debug_level >= 1)
613     g_print ("gdk_color_context_new: screen depth is %i, no. of colors is %i",
614              cc->visual->depth, cc->num_colors);
615
616   /* check if we need to initialize a hash table */
617
618   if ((cc->mode == GDK_CC_MODE_STD_CMAP) || (cc->mode == GDK_CC_MODE_UNDEFINED))
619     cc->color_hash = g_hash_table_new (hash_color, compare_colors);
620
621   return (GdkColorContext *) cc;
622 }
623
624 GdkColorContext *
625 gdk_color_context_new_mono (GdkVisual   *visual,
626                             GdkColormap *colormap)
627 {
628   GdkColorContextPrivate *ccp;
629   GdkColorContext *cc;
630
631   g_assert (visual != NULL);
632   g_assert (colormap != NULL);
633
634   cc = g_new (GdkColorContext, 1);
635   ccp = (GdkColorContextPrivate *) cc;
636   ccp->xdisplay = gdk_display;
637   cc->visual = visual;
638   cc->colormap = colormap;
639   cc->clut = NULL;
640   cc->cmap = NULL;
641   cc->mode = GDK_CC_MODE_UNDEFINED;
642   cc->need_to_free_colormap = FALSE;
643
644   init_bw (cc);
645
646   return (GdkColorContext *) cc;
647 }
648
649 /* This doesn't currently free black/white, hmm... */
650
651 void
652 gdk_color_context_free (GdkColorContext *cc)
653 {
654   g_assert (cc != NULL);
655
656   if ((cc->visual->type == GDK_VISUAL_STATIC_COLOR)
657       || (cc->visual->type == GDK_VISUAL_PSEUDO_COLOR))
658     {
659       gdk_colors_free (cc->colormap, cc->clut, cc->num_allocated, 0);
660       g_free (cc->clut);
661     }
662   else if (cc->clut != NULL)
663     {
664       gdk_colors_free (cc->colormap, cc->clut, cc->num_colors, 0);
665       g_free (cc->clut);
666     }
667
668   if (cc->cmap != NULL)
669     g_free (cc->cmap);
670
671   if (cc->need_to_free_colormap)
672     gdk_colormap_unref (cc->colormap);
673
674   /* free any palette that has been associated with this GdkColorContext */
675
676   init_palette (cc);
677
678   if (cc->color_hash)
679     {
680       g_hash_table_foreach (cc->color_hash,
681                             free_hash_entry,
682                             NULL);
683       g_hash_table_destroy (cc->color_hash);
684     }
685
686   g_free (cc);
687 }
688
689 gulong
690 gdk_color_context_get_pixel (GdkColorContext *cc,
691                              gushort          red,
692                              gushort          green,
693                              gushort          blue,
694                              gint            *failed)
695 {
696   GdkColorContextPrivate *ccp = (GdkColorContextPrivate *) cc;
697   g_assert (cc != NULL);
698   g_assert (failed != NULL);
699
700   *failed = FALSE;
701
702   switch (cc->mode)
703     {
704     case GDK_CC_MODE_BW:
705       {
706         gdouble value;
707
708         value = (red / 65535.0 * 0.30
709                  + green / 65535.0 * 0.59
710                  + blue / 65535.0 * 0.11);
711
712         if (value > 0.5)
713           return cc->white_pixel;
714
715         return cc->black_pixel;
716       }
717
718     case GDK_CC_MODE_MY_GRAY:
719       {
720         gulong ired, igreen, iblue;
721
722         red   = red * 0.30 + green * 0.59 + blue * 0.11;
723         green = 0;
724         blue  = 0;
725
726         if ((ired = red * (ccp->std_cmap.red_max + 1) / 0xffff) > ccp->std_cmap.red_max)
727           ired = ccp->std_cmap.red_max;
728
729         ired *= ccp->std_cmap.red_mult;
730
731         if ((igreen = green * (ccp->std_cmap.green_max + 1) / 0xffff) > ccp->std_cmap.green_max)
732           igreen = ccp->std_cmap.green_max;
733
734         igreen *= ccp->std_cmap.green_mult;
735
736         if ((iblue = blue * (ccp->std_cmap.blue_max + 1) / 0xffff) > ccp->std_cmap.blue_max)
737           iblue = ccp->std_cmap.blue_max;
738
739         iblue *= ccp->std_cmap.blue_mult;
740
741         if (cc->clut != NULL)
742           return cc->clut[ccp->std_cmap.base_pixel + ired + igreen + iblue];
743
744         return ccp->std_cmap.base_pixel + ired + igreen + iblue;
745       }
746
747     case GDK_CC_MODE_TRUE:
748       {
749         gulong ired, igreen, iblue;
750
751         if (cc->clut == NULL)
752           {
753             red   >>= 16 - cc->bits.red;
754             green >>= 16 - cc->bits.green;
755             blue  >>= 16 - cc->bits.blue;
756
757             ired   = (red << cc->shifts.red) & cc->masks.red;
758             igreen = (green << cc->shifts.green) & cc->masks.green;
759             iblue  = (blue << cc->shifts.blue) & cc->masks.blue;
760
761             return ired | igreen | iblue;
762           }
763
764         ired   = cc->clut[red * cc->max_entry / 65535] & cc->masks.red;
765         igreen = cc->clut[green * cc->max_entry / 65535] & cc->masks.green;
766         iblue  = cc->clut[blue * cc->max_entry / 65535] & cc->masks.blue;
767
768         return ired | igreen | iblue;
769       }
770
771     case GDK_CC_MODE_PALETTE:
772       return gdk_color_context_get_pixel_from_palette (cc, &red, &green, &blue, failed);
773
774     case GDK_CC_MODE_STD_CMAP:
775     default:
776       {
777         GdkColor color;
778         GdkColor *result;
779
780         color.red   = red;
781         color.green = green;
782         color.blue  = blue;
783
784         result = g_hash_table_lookup (cc->color_hash, &color);
785
786         if (!result)
787           {
788             color.red   = red;
789             color.green = green;
790             color.blue  = blue;
791             color.pixel = 0;
792
793             if (!gdk_color_alloc (cc->colormap, &color))
794               *failed = TRUE;
795             else
796               {
797                 GdkColor *cnew;
798                                         
799                 /* XXX: the following comment comes directly from
800                  * XCC.c.  I don't know if it is relevant for
801                  * gdk_color_alloc() as it is for XAllocColor()
802                  * - Federico
803                  */
804                 /*
805                  * I can't figure this out entirely, but it *is* possible
806                  * that XAllocColor succeeds, even if the number of
807                  * allocations we've made exceeds the number of available
808                  * colors in the current colormap. And therefore it
809                  * might be necessary for us to resize the CLUT.
810                  */
811
812                 if (cc->num_allocated == cc->max_colors)
813                   {
814                     cc->max_colors *= 2;
815
816                     if (gdk_debug_level >= 1)
817                       g_print ("gdk_color_context_get_pixel: "
818                                "resizing CLUT to %i entries",
819                                cc->max_colors);
820
821                     cc->clut = g_realloc (cc->clut,
822                                           cc->max_colors * sizeof (gulong));
823                   }
824
825                 /* Key and value are the same color structure */
826
827                 cnew = g_new (GdkColor, 1);
828                 *cnew = color;
829                 g_hash_table_insert (cc->color_hash, cnew, cnew);
830
831                 cc->clut[cc->num_allocated] = color.pixel;
832                 cc->num_allocated++;
833                 return color.pixel;
834               }
835           }
836                         
837         return result->pixel;
838       }
839     }
840 }
841
842 void
843 gdk_color_context_get_pixels (GdkColorContext *cc,
844                               gushort         *reds,
845                               gushort         *greens,
846                               gushort         *blues,
847                               gint             ncolors,
848                               gulong          *colors,
849                               gint            *nallocated)
850 {
851   gint i, k, idx;
852   gint cmapsize, ncols = 0, nopen = 0, counter = 0;
853   gint bad_alloc = FALSE;
854   gint failed[MAX_IMAGE_COLORS], allocated[MAX_IMAGE_COLORS];
855   GdkColor defs[MAX_IMAGE_COLORS], cmap[MAX_IMAGE_COLORS];
856   gint exact_col = 0, subst_col = 0, close_col = 0, black_col = 0;
857
858   g_assert (cc != NULL);
859   g_assert (reds != NULL);
860   g_assert (greens != NULL);
861   g_assert (blues != NULL);
862   g_assert (colors != NULL);
863   g_assert (nallocated != NULL);
864
865   memset (defs, 0, MAX_IMAGE_COLORS * sizeof (GdkColor));
866   memset (failed, 0, MAX_IMAGE_COLORS * sizeof (gint));
867   memset (allocated, 0, MAX_IMAGE_COLORS * sizeof (gint));
868
869   /* Will only have a value if used by the progressive image loader */
870
871   ncols = *nallocated;
872
873   *nallocated = 0;
874
875   /* First allocate all pixels */
876
877   for (i = 0; i < ncolors; i++)
878     {
879       /* colors[i] is only zero if the pixel at that location hasn't
880        * been allocated yet.  This is a sanity check required for proper
881        * color allocation by the progressive image loader
882        */
883
884       if (colors[i] == 0)
885         {
886           defs[i].red   = reds[i];
887           defs[i].green = greens[i];
888           defs[i].blue  = blues[i];
889
890           colors[i] = gdk_color_context_get_pixel (cc, reds[i], greens[i], blues[i],
891                                                    &bad_alloc);
892
893           /* successfully allocated, store it */
894
895           if (!bad_alloc)
896             {
897               defs[i].pixel = colors[i];
898               allocated[ncols++] = colors[i];
899             }
900           else
901             failed[nopen++] = i;
902         }
903     }
904
905   *nallocated = ncols;
906
907   /* all colors available, all done */
908
909   if ((ncols == ncolors) || (nopen == 0))
910     {
911       if (gdk_debug_level >= 1)
912         g_print ("gdk_color_context_get_pixels: got all %i colors; "
913                  "(%i colors allocated so far", ncolors, cc->num_allocated);
914
915       return;
916     }
917
918   /* The fun part.  We now try to allocate the colors we couldn't allocate
919    * directly.  The first step will map a color onto its nearest color
920    * that has been allocated (either by us or someone else).  If any colors
921    * remain unallocated, we map these onto the colors that we have allocated
922    * ourselves.
923    */
924
925   /* read up to MAX_IMAGE_COLORS colors of the current colormap */
926
927   cmapsize = MIN (cc->num_colors, MAX_IMAGE_COLORS);
928
929   /* see if the colormap has any colors to read */
930
931   if (cmapsize < 0)
932     {
933       g_warning ("gdk_color_context_get_pixels: oops!  no colors available, "
934                  "your images will look *really* ugly.");
935
936       return;
937     }
938
939 #ifdef DEBUG
940   exact_col = ncols;
941 #endif
942
943   /* initialize pixels */
944
945   for (i = 0; i < cmapsize; i++)
946     {
947       cmap[i].pixel = i;
948       cmap[i].red = cmap[i].green = cmap[i].blue = 0;
949     }
950
951   /* read the colormap */
952
953   my_x_query_colors (cc->colormap, cmap, cmapsize);
954
955   /* get a close match for any unallocated colors */
956
957   counter = nopen;
958   nopen = 0;
959   idx = 0;
960
961   do
962     {
963       gint d, j, mdist, close, ri, gi, bi;
964       gint rd, gd, bd;
965
966       i = failed[idx];
967
968       mdist = 0x1000000;
969       close = -1;
970
971       /* Store these vals.  Small performance increase as this skips three
972        * indexing operations in the loop code.
973        */
974
975       ri = reds[i];
976       gi = greens[i];
977       bi = blues[i];
978
979       /* Walk all colors in the colormap and see which one is the
980        * closest.  Uses plain least squares.
981        */
982
983       for (j = 0; (j < cmapsize) && (mdist != 0); j++)
984         {
985           /* Don't replace these by shifts; the sign may get clobbered */
986
987           rd = (ri - cmap[j].red) / 256;
988           gd = (gi - cmap[j].green) / 256;
989           bd = (bi - cmap[j].blue) / 256;
990
991           d = rd * rd + gd * gd + bd * bd;
992
993           if (d < mdist)
994             {
995               close = j;
996               mdist = d;
997             }
998         }
999
1000       if (close != -1)
1001         {
1002           rd = cmap[close].red;
1003           gd = cmap[close].green;
1004           bd = cmap[close].blue;
1005
1006           /* allocate */
1007
1008           colors[i] = gdk_color_context_get_pixel (cc, rd, gd, bd, &bad_alloc);
1009
1010           /* store */
1011
1012           if (!bad_alloc)
1013             {
1014               defs[i] = cmap[close];
1015               defs[i].pixel = colors[i];
1016               allocated[ncols++] = colors[i];
1017 #ifdef DEBUG
1018               close_col++;
1019 #endif
1020             } else
1021               failed[nopen++] = i;
1022         } else
1023           failed[nopen++] = i;
1024       /* deal with in next stage if allocation failed */
1025     }
1026   while (++idx < counter);
1027
1028   *nallocated = ncols;
1029
1030   /* This is the maximum no. of allocated colors.  See also the nopen == 0
1031    * note above.
1032    */
1033
1034   if ((ncols == ncolors) || (nopen == 0))
1035     {
1036       if (gdk_debug_level >= 1)
1037         g_print ("gdk_color_context_get_pixels: got %i colors, %i exact and "
1038                  "%i close (%i colors allocated so far)",
1039                  ncolors, exact_col, close_col, cc->num_allocated);
1040
1041       return;
1042     }
1043
1044   /* Now map any remaining unallocated pixels into the colors we did get */
1045
1046   idx = 0;
1047
1048   do
1049     {
1050       gint d, mdist, close, ri, gi, bi;
1051       gint j, rd, gd, bd;
1052
1053       i = failed[idx];
1054
1055       mdist = 0x1000000;
1056       close = -1;
1057
1058       /* store */
1059
1060       ri = reds[i];
1061       gi = greens[i];
1062       bi = blues[i];
1063
1064       /* search allocated colors */
1065
1066       for (j = 0; (j < ncols) && (mdist != 0); j++)
1067         {
1068           k = allocated[j];
1069
1070           /* Don't replace these by shifts; the sign may get clobbered */
1071
1072           rd = (ri - defs[k].red) / 256;
1073           gd = (gi - defs[k].green) / 256;
1074           bd = (bi - defs[k].blue) / 256;
1075
1076           d = rd * rd + gd * gd + bd * bd;
1077
1078           if (d < mdist)
1079             {
1080               close = k;
1081               mdist = d;
1082             }
1083         }
1084
1085       if (close < 0)
1086         {
1087           /* too bad, map to black */
1088
1089           defs[i].pixel = cc->black_pixel;
1090           defs[i].red = defs[i].green = defs[i].blue = 0;
1091 #ifdef DEBUG
1092           black_col++;
1093 #endif
1094         }
1095       else
1096         {
1097           defs[i] = defs[close];
1098 #ifdef DEBUG
1099           subst_col++;
1100 #endif
1101         }
1102
1103       colors[i] = defs[i].pixel;
1104     }
1105   while (++idx < nopen);
1106
1107   if (gdk_debug_level >= 1)
1108     g_print ("gdk_color_context_get_pixels: got %i colors, %i exact, %i close, "
1109              "%i substituted, %i to black (%i colors allocated so far)",
1110              ncolors, exact_col, close_col, subst_col, black_col, cc->num_allocated);
1111 }
1112
1113 void
1114 gdk_color_context_get_pixels_incremental (GdkColorContext *cc,
1115                                           gushort         *reds,
1116                                           gushort         *greens,
1117                                           gushort         *blues,
1118                                           gint             ncolors,
1119                                           gint            *used,
1120                                           gulong          *colors,
1121                                           gint            *nallocated)
1122 {
1123   gint i, k, idx;
1124   gint cmapsize, ncols = 0, nopen = 0, counter = 0;
1125   gint bad_alloc = FALSE;
1126   gint failed[MAX_IMAGE_COLORS], allocated[MAX_IMAGE_COLORS];
1127   GdkColor defs[MAX_IMAGE_COLORS], cmap[MAX_IMAGE_COLORS];
1128   gint exact_col = 0, subst_col = 0, close_col = 0, black_col = 0;
1129
1130   g_assert (cc != NULL);
1131   g_assert (reds != NULL);
1132   g_assert (greens != NULL);
1133   g_assert (blues != NULL);
1134   g_assert (used != NULL);
1135   g_assert (colors != NULL);
1136   g_assert (nallocated != NULL);
1137
1138   memset (defs, 0, MAX_IMAGE_COLORS * sizeof (GdkColor));
1139   memset (failed, 0, MAX_IMAGE_COLORS * sizeof (gint));
1140   memset (allocated, 0, MAX_IMAGE_COLORS * sizeof (gint));
1141
1142   /* Will only have a value if used by the progressive image loader */
1143
1144   ncols = *nallocated;
1145
1146   *nallocated = 0;
1147
1148   /* First allocate all pixels */
1149
1150   for (i = 0; i < ncolors; i++)
1151     {
1152       /* used[i] is only -1 if the pixel at that location hasn't
1153        * been allocated yet.  This is a sanity check required for proper
1154        * color allocation by the progressive image loader.
1155        * When colors[i] == 0 it indicates the slot is available for
1156        * allocation.
1157        */
1158
1159       if (used[i] != FALSE)
1160         {
1161           if (colors[i] == 0)
1162             {
1163               defs[i].red   = reds[i];
1164               defs[i].green = greens[i];
1165               defs[i].blue  = blues[i];
1166
1167               colors[i] = gdk_color_context_get_pixel (cc, reds[i], greens[i], blues[i], &bad_alloc);
1168
1169               /* successfully allocated, store it */
1170
1171               if (!bad_alloc)
1172                 {
1173                   defs[i].pixel = colors[i];
1174                   allocated[ncols++] = colors[i];
1175                 }
1176               else
1177                 failed[nopen++] = i;
1178             }
1179 #ifdef DEBUG
1180           else
1181             if (gdk_debug_level >= 1)
1182               g_print ("gdk_color_context_get_pixels_incremental: "
1183                        "pixel at slot %i already allocated, skipping", i);
1184 #endif
1185         }
1186     }
1187
1188   *nallocated = ncols;
1189
1190   if ((ncols == ncolors) || (nopen == 0))
1191     {
1192       if (gdk_debug_level >= 1)
1193         g_print ("gdk_color_context_get_pixels_incremental: got all %i colors "
1194                  "(%i colors allocated so far)",
1195                  ncolors, cc->num_allocated);
1196
1197       return;
1198     }
1199
1200   cmapsize = MIN (cc->num_colors, MAX_IMAGE_COLORS);
1201
1202   if (cmapsize < 0)
1203     {
1204       g_warning ("gdk_color_context_get_pixels_incremental: oops!  "
1205                  "No colors available images will look *really* ugly.");
1206       return;
1207     }
1208
1209 #ifdef DEBUG
1210   exact_col = ncols;
1211 #endif
1212
1213   /* initialize pixels */
1214
1215   for (i = 0; i < cmapsize; i++)
1216     {
1217       cmap[i].pixel = i;
1218       cmap[i].red = cmap[i].green = cmap[i].blue = 0;
1219     }
1220
1221   /* read */
1222
1223   my_x_query_colors (cc->colormap, cmap, cmapsize);
1224
1225   /* now match any unallocated colors */
1226
1227   counter = nopen;
1228   nopen = 0;
1229   idx = 0;
1230
1231   do
1232     {
1233       gint d, j, mdist, close, ri, gi, bi;
1234       gint rd, gd, bd;
1235
1236       i = failed[idx];
1237
1238       mdist = 0x1000000;
1239       close = -1;
1240
1241       /* store */
1242
1243       ri = reds[i];
1244       gi = greens[i];
1245       bi = blues[i];
1246
1247       for (j = 0; (j < cmapsize) && (mdist != 0); j++)
1248         {
1249           /* Don't replace these by shifts; the sign may get clobbered */
1250
1251           rd = (ri - cmap[j].red) / 256;
1252           gd = (gi - cmap[j].green) / 256;
1253           bd = (bi - cmap[j].blue) / 256;
1254
1255           d = rd * rd + gd * gd + bd * bd;
1256
1257           if (d < mdist)
1258             {
1259               close = j;
1260               mdist = d;
1261             }
1262         }
1263
1264       if (close != -1)
1265         {
1266           rd = cmap[close].red;
1267           gd = cmap[close].green;
1268           bd = cmap[close].blue;
1269
1270           /* allocate */
1271
1272           colors[i] = gdk_color_context_get_pixel (cc, rd, gd, bd, &bad_alloc);
1273
1274           /* store */
1275
1276           if (!bad_alloc)
1277             {
1278               defs[i] = cmap[close];
1279               defs[i].pixel = colors[i];
1280               allocated[ncols++] = colors[i];
1281 #ifdef DEBUG
1282               close_col++;
1283 #endif
1284             }
1285           else
1286             failed[nopen++] = i;
1287         }
1288       else
1289         failed[nopen++] = i;
1290       /* deal with in next stage if allocation failed */
1291     }
1292   while (++idx < counter);
1293
1294   *nallocated = ncols;
1295
1296   if ((ncols == ncolors) || (nopen == 0))
1297     {
1298       if (gdk_debug_level >= 1)
1299         g_print ("gdk_color_context_get_pixels_incremental: "
1300                  "got %i colors, %i exact and %i close "
1301                  "(%i colors allocated so far)",
1302                  ncolors, exact_col, close_col, cc->num_allocated);
1303
1304       return;
1305     }
1306
1307   /* map remaining unallocated pixels into colors we did get */
1308
1309   idx = 0;
1310
1311   do
1312     {
1313       gint d, mdist, close, ri, gi, bi;
1314       gint j, rd, gd, bd;
1315
1316       i = failed[idx];
1317
1318       mdist = 0x1000000;
1319       close = -1;
1320
1321       ri = reds[i];
1322       gi = greens[i];
1323       bi = blues[i];
1324
1325       /* search allocated colors */
1326
1327       for (j = 0; (j < ncols) && (mdist != 0); j++)
1328         {
1329           k = allocated[j];
1330
1331           /* downscale */
1332           /* Don't replace these by shifts; the sign may get clobbered */
1333
1334           rd = (ri - defs[k].red) / 256;
1335           gd = (gi - defs[k].green) / 256;
1336           bd = (bi - defs[k].blue) / 256;
1337
1338           d = rd * rd + gd * gd + bd * bd;
1339
1340           if (d < mdist)
1341             {
1342               close = k;
1343               mdist = d;
1344             }
1345         }
1346
1347       if (close < 0)
1348         {
1349           /* too bad, map to black */
1350
1351           defs[i].pixel = cc->black_pixel;
1352           defs[i].red = defs[i].green = defs[i].blue = 0;
1353 #ifdef DEBUG
1354           black_col++;
1355 #endif
1356         }
1357       else
1358         {
1359           defs[i] = defs[close];
1360 #ifdef DEBUG
1361           subst_col++;
1362 #endif
1363         }
1364
1365       colors[i] = defs[i].pixel;
1366     }
1367   while (++idx < nopen);
1368
1369   if (gdk_debug_level >= 1)
1370     g_print ("gdk_color_context_get_pixels_incremental: "
1371              "got %i colors, %i exact, %i close, %i substituted, %i to black "
1372              "(%i colors allocated so far)",
1373              ncolors, exact_col, close_col, subst_col, black_col, cc->num_allocated);
1374 }
1375
1376 gint
1377 gdk_color_context_query_color (GdkColorContext *cc,
1378                                GdkColor        *color)
1379 {
1380   return gdk_color_context_query_colors (cc, color, 1);
1381 }
1382
1383 gint
1384 gdk_color_context_query_colors (GdkColorContext *cc,
1385                                 GdkColor        *colors,
1386                                 gint             num_colors)
1387 {
1388   gint i;
1389   GdkColor *tc;
1390         
1391   g_assert (cc != NULL);
1392   g_assert (colors != NULL);
1393
1394   switch (cc->mode)
1395     {
1396     case GDK_CC_MODE_BW:
1397       for (i = 0, tc = colors; i < num_colors; i++, tc++)
1398         {
1399           if (tc->pixel == cc->white_pixel)
1400             tc->red = tc->green = tc->blue = 65535;
1401           else
1402             tc->red = tc->green = tc->blue = 0;
1403         }
1404       break;
1405
1406     case GDK_CC_MODE_TRUE:
1407       if (cc->clut == NULL)
1408         for (i = 0, tc = colors; i < num_colors; i++, tc++)
1409           {
1410             tc->red   = (tc->pixel & cc->masks.red) * 65535 / cc->masks.red;
1411             tc->green = (tc->pixel & cc->masks.green) * 65535 / cc->masks.green;
1412             tc->blue  = (tc->pixel & cc->masks.blue) * 65535 / cc->masks.blue;
1413           }
1414       else
1415         {
1416           my_x_query_colors (cc->colormap, colors, num_colors);
1417           return 1;
1418         }
1419       break;
1420
1421     case GDK_CC_MODE_STD_CMAP:
1422     default:
1423       if (cc->cmap == NULL)
1424         {
1425           my_x_query_colors (cc->colormap, colors, num_colors);
1426           return 1;
1427         }
1428       else
1429         {
1430           gint first, last, half;
1431           gulong half_pixel;
1432
1433           for (i = 0, tc = colors; i < num_colors; i++)
1434             {
1435               first = 0;
1436               last = cc->num_colors - 1;
1437
1438               while (first <= last)
1439                 {
1440                   half = (first + last) / 2;
1441                   half_pixel = cc->cmap[half].pixel;
1442
1443                   if (tc->pixel == half_pixel)
1444                     {
1445                       tc->red   = cc->cmap[half].red;
1446                       tc->green = cc->cmap[half].green;
1447                       tc->blue  = cc->cmap[half].blue;
1448                       first = last + 1; /* false break */
1449                     }
1450                   else
1451                     {
1452                       if (tc->pixel > half_pixel)
1453                         first = half + 1;
1454                       else
1455                         last = half - 1;
1456                     }
1457                 }
1458             }
1459           return 1;
1460         }
1461       break;
1462     }
1463   return 1;
1464 }
1465
1466 gint
1467 gdk_color_context_add_palette (GdkColorContext *cc,
1468                                GdkColor        *palette,
1469                                gint             num_palette)
1470 {
1471   gint i, j, erg;
1472   gushort r, g, b;
1473   gulong pixel[1];
1474
1475   g_assert (cc != NULL);
1476
1477   /* initialize this palette (will also erase previous palette as well) */
1478
1479   init_palette (cc);
1480
1481   /* restore previous mode if we aren't adding a new palette */
1482
1483   if (num_palette == 0)
1484     {
1485       /* GDK_CC_MODE_STD_CMAP uses a hash table, so we'd better initialize one */
1486
1487       /* XXX: here, the hash table is already initialized */
1488
1489       return 0;
1490     }
1491
1492   /* Initialize a hash table for this palette (we need one for allocating
1493    * the pixels in the palette using the current settings)
1494    */
1495
1496   if (cc->color_hash == NULL)
1497     cc->color_hash = g_hash_table_new (hash_color, compare_colors);
1498
1499   /* copy incoming palette */
1500
1501   cc->palette = g_new0(GdkColor, num_palette);
1502
1503   j = 0;
1504
1505   for (i = 0; i < num_palette; i++)
1506     {
1507       erg = 0;
1508       pixel[0] = 0;
1509
1510       /* try to allocate this color */
1511
1512       r = palette[i].red;
1513       g = palette[i].green;
1514       b = palette[i].blue;
1515
1516       gdk_color_context_get_pixels (cc, &r, &g, &b, 1, pixel, &erg);
1517
1518       /* only store if we succeed */
1519
1520       if (erg)
1521         {
1522           /* store in palette */
1523
1524           cc->palette[j].red   = r;
1525           cc->palette[j].green = g;
1526           cc->palette[j].blue  = b;
1527           cc->palette[j].pixel = pixel[0];
1528
1529           /* move to next slot */
1530
1531           j++;
1532         }
1533     }
1534
1535   /* resize to fit */
1536
1537   if (j != num_palette)
1538     cc->palette = g_realloc (cc->palette, j * sizeof (GdkColor));
1539
1540   /* clear the hash table, we don't use it when dithering */
1541
1542   if (cc->color_hash)
1543     {
1544       g_hash_table_destroy (cc->color_hash);
1545       cc->color_hash = NULL;
1546     }
1547
1548   /* store real palette size */
1549
1550   cc->num_palette = j;
1551
1552   /* switch to palette mode */
1553
1554   cc->mode = GDK_CC_MODE_PALETTE;
1555
1556   /* sort palette */
1557
1558   qsort (cc->palette, cc->num_palette, sizeof (GdkColor), pixel_sort);
1559
1560   cc->fast_dither = NULL;
1561
1562   return j;
1563 }
1564
1565 void
1566 gdk_color_context_init_dither (GdkColorContext *cc)
1567 {
1568   gint rr, gg, bb, err, erg, erb;
1569   gint success = FALSE;
1570
1571   g_assert (cc != NULL);
1572
1573   /* now we can initialize the fast dither matrix */
1574
1575   if (cc->fast_dither == NULL)
1576     cc->fast_dither = g_new (GdkColorContextDither, 1);
1577
1578   /* Fill it.  We ignore unsuccessful allocations, they are just mapped
1579    * to black instead */
1580
1581   for (rr = 0; rr < 32; rr++)
1582     for (gg = 0; gg < 32; gg++)
1583       for (bb = 0; bb < 32; bb++)
1584         {
1585           err = (rr << 3) | (rr >> 2);
1586           erg = (gg << 3) | (gg >> 2);
1587           erb = (bb << 3) | (bb >> 2);
1588
1589           cc->fast_dither->fast_rgb[rr][gg][bb] =
1590             gdk_color_context_get_index_from_palette (cc, &err, &erg, &erb, &success);
1591           cc->fast_dither->fast_err[rr][gg][bb] = err;
1592           cc->fast_dither->fast_erg[rr][gg][bb] = erg;
1593           cc->fast_dither->fast_erb[rr][gg][bb] = erb;
1594         }
1595 }
1596
1597 void
1598 gdk_color_context_free_dither (GdkColorContext *cc)
1599 {
1600   g_assert (cc != NULL);
1601
1602   if (cc->fast_dither)
1603     g_free (cc->fast_dither);
1604
1605   cc->fast_dither = NULL;
1606 }
1607
1608 gulong
1609 gdk_color_context_get_pixel_from_palette (GdkColorContext *cc,
1610                                           gushort         *red,
1611                                           gushort         *green,
1612                                           gushort         *blue,
1613                                           gint            *failed)
1614 {
1615   gulong pixel = 0;
1616   gint dif, dr, dg, db, j = -1;
1617   gint mindif = 0x7fffffff;
1618   gint err = 0, erg = 0, erb = 0;
1619   gint i;
1620
1621   g_assert (cc != NULL);
1622   g_assert (red != NULL);
1623   g_assert (green != NULL);
1624   g_assert (blue != NULL);
1625   g_assert (failed != NULL);
1626
1627   *failed = FALSE;
1628
1629   for (i = 0; i < cc->num_palette; i++)
1630     {
1631       dr = *red - cc->palette[i].red;
1632       dg = *green - cc->palette[i].green;
1633       db = *blue - cc->palette[i].blue;
1634
1635       dif = dr * dr + dg * dg + db * db;
1636                 
1637       if (dif < mindif)
1638         {
1639           mindif = dif;
1640           j = i;
1641           pixel = cc->palette[i].pixel;
1642           err = dr;
1643           erg = dg;
1644           erb = db;
1645
1646           if (mindif == 0)
1647             break;
1648         }
1649     }
1650
1651   /* we failed to map onto a color */
1652
1653   if (j == -1)
1654     *failed = TRUE;
1655   else
1656     {
1657       *red   = ABS (err);
1658       *green = ABS (erg);
1659       *blue  = ABS (erb);
1660     }
1661
1662   return pixel;
1663 }
1664
1665 guchar
1666 gdk_color_context_get_index_from_palette (GdkColorContext *cc,
1667                                           gint            *red,
1668                                           gint            *green,
1669                                           gint            *blue,
1670                                           gint            *failed)
1671 {
1672   gint dif, dr, dg, db, j = -1;
1673   gint mindif = 0x7fffffff;
1674   gint err = 0, erg = 0, erb = 0;
1675   gint i;
1676
1677   g_assert (cc != NULL);
1678   g_assert (red != NULL);
1679   g_assert (green != NULL);
1680   g_assert (blue != NULL);
1681   g_assert (failed != NULL);
1682
1683   *failed = FALSE;
1684
1685   for (i = 0; i < cc->num_palette; i++)
1686     {
1687       dr = *red - cc->palette[i].red;
1688       dg = *green - cc->palette[i].green;
1689       db = *blue - cc->palette[i].blue;
1690
1691       dif = dr * dr + dg * dg + db * db;
1692
1693       if (dif < mindif)
1694         {
1695           mindif = dif;
1696           j = i;
1697           err = dr;
1698           erg = dg;
1699           erb = db;
1700
1701           if (mindif == 0)
1702             break;
1703         }
1704     }
1705
1706   /* we failed to map onto a color */
1707
1708   if (j == -1)
1709     {
1710       *failed = TRUE;
1711       j = 0;
1712     }
1713   else
1714     {
1715       /* return error fractions */
1716
1717       *red   = err;
1718       *green = erg;
1719       *blue  = erb;
1720     }
1721
1722   return j;
1723 }