]> Pileus Git - ~andy/gtk/blob - gdk/x11/gdkcc-x11.c
fixed a bug for mode GDK_CC_MODE_TRUE, when on a 24-bit visual on a 32-bit
[~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           GDK_NOTE (COLOR_CONTEXT,
556             g_print ("gdk_color_context_new: visual class is %s\n",
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           GDK_NOTE (COLOR_CONTEXT,
570             g_print ("gdk_color_context_new: visual class is GDK_VISUAL_TRUE_COLOR\n"));
571
572           init_true_color (cc);
573           break;
574
575         case GDK_VISUAL_DIRECT_COLOR: /* shifts and fake CLUT */
576           GDK_NOTE (COLOR_CONTEXT,
577             g_print ("gdk_color_context_new: visual class is GDK_VISUAL_DIRECT_COLOR\n"));
578
579           init_direct_color (cc);
580           break;
581
582         case GDK_VISUAL_STATIC_COLOR:
583         case GDK_VISUAL_PSEUDO_COLOR:
584           GDK_NOTE (COLOR_CONTEXT,
585             g_print ("gdk_color_context_new: visual class is %s\n",
586                      (visual->type == GDK_VISUAL_STATIC_COLOR) ?
587                      "GDK_VISUAL_STATIC_COLOR" :
588                      "GDK_VISUAL_PSEUDO_COLOR"));
589
590           init_color (cc);
591           break;
592
593         default:
594           g_assert_not_reached ();
595         }
596
597       if ((cc->mode == GDK_CC_MODE_BW) && (cc->visual->depth > 1))
598         {
599           use_private_colormap = TRUE;
600           retry_count++;
601         }
602       else
603         break;
604     }
605
606   /* no. of colors allocated yet */
607
608   cc->num_allocated = 0;
609
610   GDK_NOTE (COLOR_CONTEXT,
611     g_print ("gdk_color_context_new: screen depth is %i, no. of colors is %i\n",
612              cc->visual->depth, cc->num_colors));
613
614   /* check if we need to initialize a hash table */
615
616   if ((cc->mode == GDK_CC_MODE_STD_CMAP) || (cc->mode == GDK_CC_MODE_UNDEFINED))
617     cc->color_hash = g_hash_table_new (hash_color, compare_colors);
618
619   return (GdkColorContext *) cc;
620 }
621
622 GdkColorContext *
623 gdk_color_context_new_mono (GdkVisual   *visual,
624                             GdkColormap *colormap)
625 {
626   GdkColorContextPrivate *ccp;
627   GdkColorContext *cc;
628
629   g_assert (visual != NULL);
630   g_assert (colormap != NULL);
631
632   cc = g_new (GdkColorContext, 1);
633   ccp = (GdkColorContextPrivate *) cc;
634   ccp->xdisplay = gdk_display;
635   cc->visual = visual;
636   cc->colormap = colormap;
637   cc->clut = NULL;
638   cc->cmap = NULL;
639   cc->mode = GDK_CC_MODE_UNDEFINED;
640   cc->need_to_free_colormap = FALSE;
641
642   init_bw (cc);
643
644   return (GdkColorContext *) cc;
645 }
646
647 /* This doesn't currently free black/white, hmm... */
648
649 void
650 gdk_color_context_free (GdkColorContext *cc)
651 {
652   g_assert (cc != NULL);
653
654   if ((cc->visual->type == GDK_VISUAL_STATIC_COLOR)
655       || (cc->visual->type == GDK_VISUAL_PSEUDO_COLOR))
656     {
657       gdk_colors_free (cc->colormap, cc->clut, cc->num_allocated, 0);
658       g_free (cc->clut);
659     }
660   else if (cc->clut != NULL)
661     {
662       gdk_colors_free (cc->colormap, cc->clut, cc->num_colors, 0);
663       g_free (cc->clut);
664     }
665
666   if (cc->cmap != NULL)
667     g_free (cc->cmap);
668
669   if (cc->need_to_free_colormap)
670     gdk_colormap_unref (cc->colormap);
671
672   /* free any palette that has been associated with this GdkColorContext */
673
674   init_palette (cc);
675
676   if (cc->color_hash)
677     {
678       g_hash_table_foreach (cc->color_hash,
679                             free_hash_entry,
680                             NULL);
681       g_hash_table_destroy (cc->color_hash);
682     }
683
684   g_free (cc);
685 }
686
687 gulong
688 gdk_color_context_get_pixel (GdkColorContext *cc,
689                              gushort          red,
690                              gushort          green,
691                              gushort          blue,
692                              gint            *failed)
693 {
694   GdkColorContextPrivate *ccp = (GdkColorContextPrivate *) cc;
695   g_assert (cc != NULL);
696   g_assert (failed != NULL);
697
698   *failed = FALSE;
699
700   switch (cc->mode)
701     {
702     case GDK_CC_MODE_BW:
703       {
704         gdouble value;
705
706         value = (red / 65535.0 * 0.30
707                  + green / 65535.0 * 0.59
708                  + blue / 65535.0 * 0.11);
709
710         if (value > 0.5)
711           return cc->white_pixel;
712
713         return cc->black_pixel;
714       }
715
716     case GDK_CC_MODE_MY_GRAY:
717       {
718         gulong ired, igreen, iblue;
719
720         red   = red * 0.30 + green * 0.59 + blue * 0.11;
721         green = 0;
722         blue  = 0;
723
724         if ((ired = red * (ccp->std_cmap.red_max + 1) / 0xffff) > ccp->std_cmap.red_max)
725           ired = ccp->std_cmap.red_max;
726
727         ired *= ccp->std_cmap.red_mult;
728
729         if ((igreen = green * (ccp->std_cmap.green_max + 1) / 0xffff) > ccp->std_cmap.green_max)
730           igreen = ccp->std_cmap.green_max;
731
732         igreen *= ccp->std_cmap.green_mult;
733
734         if ((iblue = blue * (ccp->std_cmap.blue_max + 1) / 0xffff) > ccp->std_cmap.blue_max)
735           iblue = ccp->std_cmap.blue_max;
736
737         iblue *= ccp->std_cmap.blue_mult;
738
739         if (cc->clut != NULL)
740           return cc->clut[ccp->std_cmap.base_pixel + ired + igreen + iblue];
741
742         return ccp->std_cmap.base_pixel + ired + igreen + iblue;
743       }
744
745     case GDK_CC_MODE_TRUE:
746       {
747         gulong ired, igreen, iblue;
748
749         if (cc->clut == NULL)
750           {
751             red   >>= 16 - cc->bits.red;
752             green >>= 16 - cc->bits.green;
753             blue  >>= 16 - cc->bits.blue;
754
755             ired   = (red << cc->shifts.red) & cc->masks.red;
756             igreen = (green << cc->shifts.green) & cc->masks.green;
757             iblue  = (blue << cc->shifts.blue) & cc->masks.blue;
758
759             return ired | igreen | iblue;
760           }
761
762         ired   = cc->clut[red * cc->max_entry / 65535] & cc->masks.red;
763         igreen = cc->clut[green * cc->max_entry / 65535] & cc->masks.green;
764         iblue  = cc->clut[blue * cc->max_entry / 65535] & cc->masks.blue;
765
766         return ired | igreen | iblue;
767       }
768
769     case GDK_CC_MODE_PALETTE:
770       return gdk_color_context_get_pixel_from_palette (cc, &red, &green, &blue, failed);
771
772     case GDK_CC_MODE_STD_CMAP:
773     default:
774       {
775         GdkColor color;
776         GdkColor *result;
777
778         color.red   = red;
779         color.green = green;
780         color.blue  = blue;
781
782         result = g_hash_table_lookup (cc->color_hash, &color);
783
784         if (!result)
785           {
786             color.red   = red;
787             color.green = green;
788             color.blue  = blue;
789             color.pixel = 0;
790
791             if (!gdk_color_alloc (cc->colormap, &color))
792               *failed = TRUE;
793             else
794               {
795                 GdkColor *cnew;
796                                         
797                 /* XXX: the following comment comes directly from
798                  * XCC.c.  I don't know if it is relevant for
799                  * gdk_color_alloc() as it is for XAllocColor()
800                  * - Federico
801                  */
802                 /*
803                  * I can't figure this out entirely, but it *is* possible
804                  * that XAllocColor succeeds, even if the number of
805                  * allocations we've made exceeds the number of available
806                  * colors in the current colormap. And therefore it
807                  * might be necessary for us to resize the CLUT.
808                  */
809
810                 if (cc->num_allocated == cc->max_colors)
811                   {
812                     cc->max_colors *= 2;
813
814                     GDK_NOTE (COLOR_CONTEXT,
815                       g_print ("gdk_color_context_get_pixel: "
816                                "resizing CLUT to %i entries\n",
817                                cc->max_colors));
818
819                     cc->clut = g_realloc (cc->clut,
820                                           cc->max_colors * sizeof (gulong));
821                   }
822
823                 /* Key and value are the same color structure */
824
825                 cnew = g_new (GdkColor, 1);
826                 *cnew = color;
827                 g_hash_table_insert (cc->color_hash, cnew, cnew);
828
829                 cc->clut[cc->num_allocated] = color.pixel;
830                 cc->num_allocated++;
831                 return color.pixel;
832               }
833           }
834                         
835         return result->pixel;
836       }
837     }
838 }
839
840 void
841 gdk_color_context_get_pixels (GdkColorContext *cc,
842                               gushort         *reds,
843                               gushort         *greens,
844                               gushort         *blues,
845                               gint             ncolors,
846                               gulong          *colors,
847                               gint            *nallocated)
848 {
849   gint i, k, idx;
850   gint cmapsize, ncols = 0, nopen = 0, counter = 0;
851   gint bad_alloc = FALSE;
852   gint failed[MAX_IMAGE_COLORS], allocated[MAX_IMAGE_COLORS];
853   GdkColor defs[MAX_IMAGE_COLORS], cmap[MAX_IMAGE_COLORS];
854   gint exact_col = 0, subst_col = 0, close_col = 0, black_col = 0;
855
856   g_assert (cc != NULL);
857   g_assert (reds != NULL);
858   g_assert (greens != NULL);
859   g_assert (blues != NULL);
860   g_assert (colors != NULL);
861   g_assert (nallocated != NULL);
862
863   memset (defs, 0, MAX_IMAGE_COLORS * sizeof (GdkColor));
864   memset (failed, 0, MAX_IMAGE_COLORS * sizeof (gint));
865   memset (allocated, 0, MAX_IMAGE_COLORS * sizeof (gint));
866
867   /* Will only have a value if used by the progressive image loader */
868
869   ncols = *nallocated;
870
871   *nallocated = 0;
872
873   /* First allocate all pixels */
874
875   for (i = 0; i < ncolors; i++)
876     {
877       /* colors[i] is only zero if the pixel at that location hasn't
878        * been allocated yet.  This is a sanity check required for proper
879        * color allocation by the progressive image loader
880        */
881
882       if (colors[i] == 0)
883         {
884           defs[i].red   = reds[i];
885           defs[i].green = greens[i];
886           defs[i].blue  = blues[i];
887
888           colors[i] = gdk_color_context_get_pixel (cc, reds[i], greens[i], blues[i],
889                                                    &bad_alloc);
890
891           /* successfully allocated, store it */
892
893           if (!bad_alloc)
894             {
895               defs[i].pixel = colors[i];
896               allocated[ncols++] = colors[i];
897             }
898           else
899             failed[nopen++] = i;
900         }
901     }
902
903   *nallocated = ncols;
904
905   /* all colors available, all done */
906
907   if ((ncols == ncolors) || (nopen == 0))
908     {
909       GDK_NOTE (COLOR_CONTEXT,
910         g_print ("gdk_color_context_get_pixels: got all %i colors; "
911                  "(%i colors allocated so far)\n", ncolors, cc->num_allocated));
912
913       return;
914     }
915
916   /* The fun part.  We now try to allocate the colors we couldn't allocate
917    * directly.  The first step will map a color onto its nearest color
918    * that has been allocated (either by us or someone else).  If any colors
919    * remain unallocated, we map these onto the colors that we have allocated
920    * ourselves.
921    */
922
923   /* read up to MAX_IMAGE_COLORS colors of the current colormap */
924
925   cmapsize = MIN (cc->num_colors, MAX_IMAGE_COLORS);
926
927   /* see if the colormap has any colors to read */
928
929   if (cmapsize < 0)
930     {
931       g_warning ("gdk_color_context_get_pixels: oops!  no colors available, "
932                  "your images will look *really* ugly.");
933
934       return;
935     }
936
937 #ifdef DEBUG
938   exact_col = ncols;
939 #endif
940
941   /* initialize pixels */
942
943   for (i = 0; i < cmapsize; i++)
944     {
945       cmap[i].pixel = i;
946       cmap[i].red = cmap[i].green = cmap[i].blue = 0;
947     }
948
949   /* read the colormap */
950
951   my_x_query_colors (cc->colormap, cmap, cmapsize);
952
953   /* get a close match for any unallocated colors */
954
955   counter = nopen;
956   nopen = 0;
957   idx = 0;
958
959   do
960     {
961       gint d, j, mdist, close, ri, gi, bi;
962       gint rd, gd, bd;
963
964       i = failed[idx];
965
966       mdist = 0x1000000;
967       close = -1;
968
969       /* Store these vals.  Small performance increase as this skips three
970        * indexing operations in the loop code.
971        */
972
973       ri = reds[i];
974       gi = greens[i];
975       bi = blues[i];
976
977       /* Walk all colors in the colormap and see which one is the
978        * closest.  Uses plain least squares.
979        */
980
981       for (j = 0; (j < cmapsize) && (mdist != 0); j++)
982         {
983           /* Don't replace these by shifts; the sign may get clobbered */
984
985           rd = (ri - cmap[j].red) / 256;
986           gd = (gi - cmap[j].green) / 256;
987           bd = (bi - cmap[j].blue) / 256;
988
989           d = rd * rd + gd * gd + bd * bd;
990
991           if (d < mdist)
992             {
993               close = j;
994               mdist = d;
995             }
996         }
997
998       if (close != -1)
999         {
1000           rd = cmap[close].red;
1001           gd = cmap[close].green;
1002           bd = cmap[close].blue;
1003
1004           /* allocate */
1005
1006           colors[i] = gdk_color_context_get_pixel (cc, rd, gd, bd, &bad_alloc);
1007
1008           /* store */
1009
1010           if (!bad_alloc)
1011             {
1012               defs[i] = cmap[close];
1013               defs[i].pixel = colors[i];
1014               allocated[ncols++] = colors[i];
1015 #ifdef DEBUG
1016               close_col++;
1017 #endif
1018             } else
1019               failed[nopen++] = i;
1020         } else
1021           failed[nopen++] = i;
1022       /* deal with in next stage if allocation failed */
1023     }
1024   while (++idx < counter);
1025
1026   *nallocated = ncols;
1027
1028   /* This is the maximum no. of allocated colors.  See also the nopen == 0
1029    * note above.
1030    */
1031
1032   if ((ncols == ncolors) || (nopen == 0))
1033     {
1034       GDK_NOTE (COLOR_CONTEXT,
1035         g_print ("gdk_color_context_get_pixels: got %i colors, %i exact and "
1036                  "%i close (%i colors allocated so far)\n",
1037                  ncolors, exact_col, close_col, cc->num_allocated));
1038
1039       return;
1040     }
1041
1042   /* Now map any remaining unallocated pixels into the colors we did get */
1043
1044   idx = 0;
1045
1046   do
1047     {
1048       gint d, mdist, close, ri, gi, bi;
1049       gint j, rd, gd, bd;
1050
1051       i = failed[idx];
1052
1053       mdist = 0x1000000;
1054       close = -1;
1055
1056       /* store */
1057
1058       ri = reds[i];
1059       gi = greens[i];
1060       bi = blues[i];
1061
1062       /* search allocated colors */
1063
1064       for (j = 0; (j < ncols) && (mdist != 0); j++)
1065         {
1066           k = allocated[j];
1067
1068           /* Don't replace these by shifts; the sign may get clobbered */
1069
1070           rd = (ri - defs[k].red) / 256;
1071           gd = (gi - defs[k].green) / 256;
1072           bd = (bi - defs[k].blue) / 256;
1073
1074           d = rd * rd + gd * gd + bd * bd;
1075
1076           if (d < mdist)
1077             {
1078               close = k;
1079               mdist = d;
1080             }
1081         }
1082
1083       if (close < 0)
1084         {
1085           /* too bad, map to black */
1086
1087           defs[i].pixel = cc->black_pixel;
1088           defs[i].red = defs[i].green = defs[i].blue = 0;
1089 #ifdef DEBUG
1090           black_col++;
1091 #endif
1092         }
1093       else
1094         {
1095           defs[i] = defs[close];
1096 #ifdef DEBUG
1097           subst_col++;
1098 #endif
1099         }
1100
1101       colors[i] = defs[i].pixel;
1102     }
1103   while (++idx < nopen);
1104
1105   GDK_NOTE (COLOR_CONTEXT,
1106     g_print ("gdk_color_context_get_pixels: got %i colors, %i exact, %i close, "
1107              "%i substituted, %i to black (%i colors allocated so far)\n",
1108              ncolors, exact_col, close_col, subst_col, black_col, cc->num_allocated));
1109 }
1110
1111 void
1112 gdk_color_context_get_pixels_incremental (GdkColorContext *cc,
1113                                           gushort         *reds,
1114                                           gushort         *greens,
1115                                           gushort         *blues,
1116                                           gint             ncolors,
1117                                           gint            *used,
1118                                           gulong          *colors,
1119                                           gint            *nallocated)
1120 {
1121   gint i, k, idx;
1122   gint cmapsize, ncols = 0, nopen = 0, counter = 0;
1123   gint bad_alloc = FALSE;
1124   gint failed[MAX_IMAGE_COLORS], allocated[MAX_IMAGE_COLORS];
1125   GdkColor defs[MAX_IMAGE_COLORS], cmap[MAX_IMAGE_COLORS];
1126   gint exact_col = 0, subst_col = 0, close_col = 0, black_col = 0;
1127
1128   g_assert (cc != NULL);
1129   g_assert (reds != NULL);
1130   g_assert (greens != NULL);
1131   g_assert (blues != NULL);
1132   g_assert (used != NULL);
1133   g_assert (colors != NULL);
1134   g_assert (nallocated != NULL);
1135
1136   memset (defs, 0, MAX_IMAGE_COLORS * sizeof (GdkColor));
1137   memset (failed, 0, MAX_IMAGE_COLORS * sizeof (gint));
1138   memset (allocated, 0, MAX_IMAGE_COLORS * sizeof (gint));
1139
1140   /* Will only have a value if used by the progressive image loader */
1141
1142   ncols = *nallocated;
1143
1144   *nallocated = 0;
1145
1146   /* First allocate all pixels */
1147
1148   for (i = 0; i < ncolors; i++)
1149     {
1150       /* used[i] is only -1 if the pixel at that location hasn't
1151        * been allocated yet.  This is a sanity check required for proper
1152        * color allocation by the progressive image loader.
1153        * When colors[i] == 0 it indicates the slot is available for
1154        * allocation.
1155        */
1156
1157       if (used[i] != FALSE)
1158         {
1159           if (colors[i] == 0)
1160             {
1161               defs[i].red   = reds[i];
1162               defs[i].green = greens[i];
1163               defs[i].blue  = blues[i];
1164
1165               colors[i] = gdk_color_context_get_pixel (cc, reds[i], greens[i], blues[i], &bad_alloc);
1166
1167               /* successfully allocated, store it */
1168
1169               if (!bad_alloc)
1170                 {
1171                   defs[i].pixel = colors[i];
1172                   allocated[ncols++] = colors[i];
1173                 }
1174               else
1175                 failed[nopen++] = i;
1176             }
1177 #ifdef DEBUG
1178           else
1179             GDK_NOTE (COLOR_CONTEXT,
1180               g_print ("gdk_color_context_get_pixels_incremental: "
1181                        "pixel at slot %i already allocated, skipping\n", i));
1182 #endif
1183         }
1184     }
1185
1186   *nallocated = ncols;
1187
1188   if ((ncols == ncolors) || (nopen == 0))
1189     {
1190       GDK_NOTE (COLOR_CONTEXT,
1191         g_print ("gdk_color_context_get_pixels_incremental: got all %i colors "
1192                  "(%i colors allocated so far)\n",
1193                  ncolors, cc->num_allocated));
1194
1195       return;
1196     }
1197
1198   cmapsize = MIN (cc->num_colors, MAX_IMAGE_COLORS);
1199
1200   if (cmapsize < 0)
1201     {
1202       g_warning ("gdk_color_context_get_pixels_incremental: oops!  "
1203                  "No colors available images will look *really* ugly.");
1204       return;
1205     }
1206
1207 #ifdef DEBUG
1208   exact_col = ncols;
1209 #endif
1210
1211   /* initialize pixels */
1212
1213   for (i = 0; i < cmapsize; i++)
1214     {
1215       cmap[i].pixel = i;
1216       cmap[i].red = cmap[i].green = cmap[i].blue = 0;
1217     }
1218
1219   /* read */
1220
1221   my_x_query_colors (cc->colormap, cmap, cmapsize);
1222
1223   /* now match any unallocated colors */
1224
1225   counter = nopen;
1226   nopen = 0;
1227   idx = 0;
1228
1229   do
1230     {
1231       gint d, j, mdist, close, ri, gi, bi;
1232       gint rd, gd, bd;
1233
1234       i = failed[idx];
1235
1236       mdist = 0x1000000;
1237       close = -1;
1238
1239       /* store */
1240
1241       ri = reds[i];
1242       gi = greens[i];
1243       bi = blues[i];
1244
1245       for (j = 0; (j < cmapsize) && (mdist != 0); j++)
1246         {
1247           /* Don't replace these by shifts; the sign may get clobbered */
1248
1249           rd = (ri - cmap[j].red) / 256;
1250           gd = (gi - cmap[j].green) / 256;
1251           bd = (bi - cmap[j].blue) / 256;
1252
1253           d = rd * rd + gd * gd + bd * bd;
1254
1255           if (d < mdist)
1256             {
1257               close = j;
1258               mdist = d;
1259             }
1260         }
1261
1262       if (close != -1)
1263         {
1264           rd = cmap[close].red;
1265           gd = cmap[close].green;
1266           bd = cmap[close].blue;
1267
1268           /* allocate */
1269
1270           colors[i] = gdk_color_context_get_pixel (cc, rd, gd, bd, &bad_alloc);
1271
1272           /* store */
1273
1274           if (!bad_alloc)
1275             {
1276               defs[i] = cmap[close];
1277               defs[i].pixel = colors[i];
1278               allocated[ncols++] = colors[i];
1279 #ifdef DEBUG
1280               close_col++;
1281 #endif
1282             }
1283           else
1284             failed[nopen++] = i;
1285         }
1286       else
1287         failed[nopen++] = i;
1288       /* deal with in next stage if allocation failed */
1289     }
1290   while (++idx < counter);
1291
1292   *nallocated = ncols;
1293
1294   if ((ncols == ncolors) || (nopen == 0))
1295     {
1296       GDK_NOTE (COLOR_CONTEXT,
1297         g_print ("gdk_color_context_get_pixels_incremental: "
1298                  "got %i colors, %i exact and %i close "
1299                  "(%i colors allocated so far)\n",
1300                  ncolors, exact_col, close_col, cc->num_allocated));
1301
1302       return;
1303     }
1304
1305   /* map remaining unallocated pixels into colors we did get */
1306
1307   idx = 0;
1308
1309   do
1310     {
1311       gint d, mdist, close, ri, gi, bi;
1312       gint j, rd, gd, bd;
1313
1314       i = failed[idx];
1315
1316       mdist = 0x1000000;
1317       close = -1;
1318
1319       ri = reds[i];
1320       gi = greens[i];
1321       bi = blues[i];
1322
1323       /* search allocated colors */
1324
1325       for (j = 0; (j < ncols) && (mdist != 0); j++)
1326         {
1327           k = allocated[j];
1328
1329           /* downscale */
1330           /* Don't replace these by shifts; the sign may get clobbered */
1331
1332           rd = (ri - defs[k].red) / 256;
1333           gd = (gi - defs[k].green) / 256;
1334           bd = (bi - defs[k].blue) / 256;
1335
1336           d = rd * rd + gd * gd + bd * bd;
1337
1338           if (d < mdist)
1339             {
1340               close = k;
1341               mdist = d;
1342             }
1343         }
1344
1345       if (close < 0)
1346         {
1347           /* too bad, map to black */
1348
1349           defs[i].pixel = cc->black_pixel;
1350           defs[i].red = defs[i].green = defs[i].blue = 0;
1351 #ifdef DEBUG
1352           black_col++;
1353 #endif
1354         }
1355       else
1356         {
1357           defs[i] = defs[close];
1358 #ifdef DEBUG
1359           subst_col++;
1360 #endif
1361         }
1362
1363       colors[i] = defs[i].pixel;
1364     }
1365   while (++idx < nopen);
1366
1367   GDK_NOTE (COLOR_CONTEXT,
1368     g_print ("gdk_color_context_get_pixels_incremental: "
1369              "got %i colors, %i exact, %i close, %i substituted, %i to black "
1370              "(%i colors allocated so far)\n",
1371              ncolors, exact_col, close_col, subst_col, black_col, cc->num_allocated));
1372 }
1373
1374 gint
1375 gdk_color_context_query_color (GdkColorContext *cc,
1376                                GdkColor        *color)
1377 {
1378   return gdk_color_context_query_colors (cc, color, 1);
1379 }
1380
1381 gint
1382 gdk_color_context_query_colors (GdkColorContext *cc,
1383                                 GdkColor        *colors,
1384                                 gint             num_colors)
1385 {
1386   gint i;
1387   GdkColor *tc;
1388         
1389   g_assert (cc != NULL);
1390   g_assert (colors != NULL);
1391
1392   switch (cc->mode)
1393     {
1394     case GDK_CC_MODE_BW:
1395       for (i = 0, tc = colors; i < num_colors; i++, tc++)
1396         {
1397           if (tc->pixel == cc->white_pixel)
1398             tc->red = tc->green = tc->blue = 65535;
1399           else
1400             tc->red = tc->green = tc->blue = 0;
1401         }
1402       break;
1403
1404     case GDK_CC_MODE_TRUE:
1405       if (cc->clut == NULL)
1406         for (i = 0, tc = colors; i < num_colors; i++, tc++)
1407           {
1408             tc->red   = ((tc->pixel & cc->masks.red) >> cc->shifts.red) << (16 - cc->bits.red);
1409             tc->green = ((tc->pixel & cc->masks.green) >> cc->shifts.green) << (16 - cc->bits.green);
1410             tc->blue  = ((tc->pixel & cc->masks.blue) >> cc->shifts.blue) << (16 - cc->bits.blue);
1411           }
1412       else
1413         {
1414           my_x_query_colors (cc->colormap, colors, num_colors);
1415           return 1;
1416         }
1417       break;
1418
1419     case GDK_CC_MODE_STD_CMAP:
1420     default:
1421       if (cc->cmap == NULL)
1422         {
1423           my_x_query_colors (cc->colormap, colors, num_colors);
1424           return 1;
1425         }
1426       else
1427         {
1428           gint first, last, half;
1429           gulong half_pixel;
1430
1431           for (i = 0, tc = colors; i < num_colors; i++)
1432             {
1433               first = 0;
1434               last = cc->num_colors - 1;
1435
1436               while (first <= last)
1437                 {
1438                   half = (first + last) / 2;
1439                   half_pixel = cc->cmap[half].pixel;
1440
1441                   if (tc->pixel == half_pixel)
1442                     {
1443                       tc->red   = cc->cmap[half].red;
1444                       tc->green = cc->cmap[half].green;
1445                       tc->blue  = cc->cmap[half].blue;
1446                       first = last + 1; /* false break */
1447                     }
1448                   else
1449                     {
1450                       if (tc->pixel > half_pixel)
1451                         first = half + 1;
1452                       else
1453                         last = half - 1;
1454                     }
1455                 }
1456             }
1457           return 1;
1458         }
1459       break;
1460     }
1461   return 1;
1462 }
1463
1464 gint
1465 gdk_color_context_add_palette (GdkColorContext *cc,
1466                                GdkColor        *palette,
1467                                gint             num_palette)
1468 {
1469   gint i, j, erg;
1470   gushort r, g, b;
1471   gulong pixel[1];
1472
1473   g_assert (cc != NULL);
1474
1475   /* initialize this palette (will also erase previous palette as well) */
1476
1477   init_palette (cc);
1478
1479   /* restore previous mode if we aren't adding a new palette */
1480
1481   if (num_palette == 0)
1482     {
1483       /* GDK_CC_MODE_STD_CMAP uses a hash table, so we'd better initialize one */
1484
1485       /* XXX: here, the hash table is already initialized */
1486
1487       return 0;
1488     }
1489
1490   /* Initialize a hash table for this palette (we need one for allocating
1491    * the pixels in the palette using the current settings)
1492    */
1493
1494   if (cc->color_hash == NULL)
1495     cc->color_hash = g_hash_table_new (hash_color, compare_colors);
1496
1497   /* copy incoming palette */
1498
1499   cc->palette = g_new0(GdkColor, num_palette);
1500
1501   j = 0;
1502
1503   for (i = 0; i < num_palette; i++)
1504     {
1505       erg = 0;
1506       pixel[0] = 0;
1507
1508       /* try to allocate this color */
1509
1510       r = palette[i].red;
1511       g = palette[i].green;
1512       b = palette[i].blue;
1513
1514       gdk_color_context_get_pixels (cc, &r, &g, &b, 1, pixel, &erg);
1515
1516       /* only store if we succeed */
1517
1518       if (erg)
1519         {
1520           /* store in palette */
1521
1522           cc->palette[j].red   = r;
1523           cc->palette[j].green = g;
1524           cc->palette[j].blue  = b;
1525           cc->palette[j].pixel = pixel[0];
1526
1527           /* move to next slot */
1528
1529           j++;
1530         }
1531     }
1532
1533   /* resize to fit */
1534
1535   if (j != num_palette)
1536     cc->palette = g_realloc (cc->palette, j * sizeof (GdkColor));
1537
1538   /* clear the hash table, we don't use it when dithering */
1539
1540   if (cc->color_hash)
1541     {
1542       g_hash_table_destroy (cc->color_hash);
1543       cc->color_hash = NULL;
1544     }
1545
1546   /* store real palette size */
1547
1548   cc->num_palette = j;
1549
1550   /* switch to palette mode */
1551
1552   cc->mode = GDK_CC_MODE_PALETTE;
1553
1554   /* sort palette */
1555
1556   qsort (cc->palette, cc->num_palette, sizeof (GdkColor), pixel_sort);
1557
1558   cc->fast_dither = NULL;
1559
1560   return j;
1561 }
1562
1563 void
1564 gdk_color_context_init_dither (GdkColorContext *cc)
1565 {
1566   gint rr, gg, bb, err, erg, erb;
1567   gint success = FALSE;
1568
1569   g_assert (cc != NULL);
1570
1571   /* now we can initialize the fast dither matrix */
1572
1573   if (cc->fast_dither == NULL)
1574     cc->fast_dither = g_new (GdkColorContextDither, 1);
1575
1576   /* Fill it.  We ignore unsuccessful allocations, they are just mapped
1577    * to black instead */
1578
1579   for (rr = 0; rr < 32; rr++)
1580     for (gg = 0; gg < 32; gg++)
1581       for (bb = 0; bb < 32; bb++)
1582         {
1583           err = (rr << 3) | (rr >> 2);
1584           erg = (gg << 3) | (gg >> 2);
1585           erb = (bb << 3) | (bb >> 2);
1586
1587           cc->fast_dither->fast_rgb[rr][gg][bb] =
1588             gdk_color_context_get_index_from_palette (cc, &err, &erg, &erb, &success);
1589           cc->fast_dither->fast_err[rr][gg][bb] = err;
1590           cc->fast_dither->fast_erg[rr][gg][bb] = erg;
1591           cc->fast_dither->fast_erb[rr][gg][bb] = erb;
1592         }
1593 }
1594
1595 void
1596 gdk_color_context_free_dither (GdkColorContext *cc)
1597 {
1598   g_assert (cc != NULL);
1599
1600   if (cc->fast_dither)
1601     g_free (cc->fast_dither);
1602
1603   cc->fast_dither = NULL;
1604 }
1605
1606 gulong
1607 gdk_color_context_get_pixel_from_palette (GdkColorContext *cc,
1608                                           gushort         *red,
1609                                           gushort         *green,
1610                                           gushort         *blue,
1611                                           gint            *failed)
1612 {
1613   gulong pixel = 0;
1614   gint dif, dr, dg, db, j = -1;
1615   gint mindif = 0x7fffffff;
1616   gint err = 0, erg = 0, erb = 0;
1617   gint i;
1618
1619   g_assert (cc != NULL);
1620   g_assert (red != NULL);
1621   g_assert (green != NULL);
1622   g_assert (blue != NULL);
1623   g_assert (failed != NULL);
1624
1625   *failed = FALSE;
1626
1627   for (i = 0; i < cc->num_palette; i++)
1628     {
1629       dr = *red - cc->palette[i].red;
1630       dg = *green - cc->palette[i].green;
1631       db = *blue - cc->palette[i].blue;
1632
1633       dif = dr * dr + dg * dg + db * db;
1634                 
1635       if (dif < mindif)
1636         {
1637           mindif = dif;
1638           j = i;
1639           pixel = cc->palette[i].pixel;
1640           err = dr;
1641           erg = dg;
1642           erb = db;
1643
1644           if (mindif == 0)
1645             break;
1646         }
1647     }
1648
1649   /* we failed to map onto a color */
1650
1651   if (j == -1)
1652     *failed = TRUE;
1653   else
1654     {
1655       *red   = ABS (err);
1656       *green = ABS (erg);
1657       *blue  = ABS (erb);
1658     }
1659
1660   return pixel;
1661 }
1662
1663 guchar
1664 gdk_color_context_get_index_from_palette (GdkColorContext *cc,
1665                                           gint            *red,
1666                                           gint            *green,
1667                                           gint            *blue,
1668                                           gint            *failed)
1669 {
1670   gint dif, dr, dg, db, j = -1;
1671   gint mindif = 0x7fffffff;
1672   gint err = 0, erg = 0, erb = 0;
1673   gint i;
1674
1675   g_assert (cc != NULL);
1676   g_assert (red != NULL);
1677   g_assert (green != NULL);
1678   g_assert (blue != NULL);
1679   g_assert (failed != NULL);
1680
1681   *failed = FALSE;
1682
1683   for (i = 0; i < cc->num_palette; i++)
1684     {
1685       dr = *red - cc->palette[i].red;
1686       dg = *green - cc->palette[i].green;
1687       db = *blue - cc->palette[i].blue;
1688
1689       dif = dr * dr + dg * dg + db * db;
1690
1691       if (dif < mindif)
1692         {
1693           mindif = dif;
1694           j = i;
1695           err = dr;
1696           erg = dg;
1697           erb = db;
1698
1699           if (mindif == 0)
1700             break;
1701         }
1702     }
1703
1704   /* we failed to map onto a color */
1705
1706   if (j == -1)
1707     {
1708       *failed = TRUE;
1709       j = 0;
1710     }
1711   else
1712     {
1713       /* return error fractions */
1714
1715       *red   = err;
1716       *green = erg;
1717       *blue  = erb;
1718     }
1719
1720   return j;
1721 }