Fix coding style.
[dana/urxvt.git] / src / background.C
1 /*----------------------------------------------------------------------*
2  * File:        background.C - former xpm.C
3  *----------------------------------------------------------------------*
4  *
5  * All portions of code are copyright by their respective author/s.
6  * Copyright (c) 2005-2008 Marc Lehmann <pcg@goof.com>
7  * Copyright (c) 2007      Sasha Vasko <sasha@aftercode.net>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  *---------------------------------------------------------------------*/
23
24 #include "../config.h"          /* NECESSARY */
25 #include "rxvt.h"               /* NECESSARY */
26
27 #define DO_TIMING_TEST 0
28
29 #if DO_TIMING_TEST
30 # include <sys/time.h>
31 #define TIMING_TEST_START(id) \
32         struct timeval timing_test_##id##_stv;\
33   gettimeofday (&timing_test_##id##_stv, NULL);
34
35 #define TIMING_TEST_PRINT_RESULT(id) \
36   do{ struct timeval tv;gettimeofday (&tv, NULL); tv.tv_sec -= (timing_test_##id##_stv).tv_sec;\
37       fprintf (stderr, "%s: %s: %d: elapsed  %ld usec\n", #id, __FILE__, __LINE__,\
38                tv.tv_sec * 1000000 + tv.tv_usec - (timing_test_##id##_stv).tv_usec);}while (0)
39
40 #else
41 #define TIMING_TEST_START(id) do{}while (0)
42 #define TIMING_TEST_PRINT_RESULT(id) do{}while (0)
43 #endif
44
45 /*
46  * Pixmap geometry string interpretation :
47  * Each geometry string contains zero or one scale/position
48  * adjustment and may optionally be followed by a colon and one or more
49  * colon-delimited pixmap operations.
50  * The following table shows the valid geometry strings and their
51  * affects on the background image :
52  *
53  * WxH+X+Y      Set scaling to W% by H%, and position to X% by Y%.
54  *            W and H are percentages of the terminal window size.
55  *            X and Y are also percentages; e.g., +50+50 centers
56  *            the image in the window.
57  * WxH+X            Assumes Y == X
58  * WxH        Assumes Y == X == 50 (centers the image)
59  * W+X+Y            Assumes H == W
60  * W+X        Assumes H == W and Y == X
61  * W            Assumes H == W and Y == X == 50
62  *
63  * Adjusting position only :
64  * =+X+Y            Set position to X% by Y% (absolute).
65  * =+X        Set position to X% by X%.
66  * +X+Y             Adjust position horizontally X% and vertically Y%
67  *            from current position (relative).
68  * +X               Adjust position horizontally X% and vertically X%
69  *            from current position.
70  *
71  * Adjusting scale only :
72  * Wx0        Multiply horizontal scaling factor by W%
73  * 0xH        Multiply vertical scaling factor by H%
74  * 0x0        No scaling (show image at normal size).
75  *
76  * Pixmap Operations : (should be prepended by a colon)
77  * tile             Tile image. Scaling/position modifiers above will affect
78  *            the tile size and origin.
79  * propscale    When scaling, scale proportionally. That is, maintain the
80  *            proper aspect ratio for the image. Any portion of the
81  *            background not covered by the image is filled with the
82  *            current background color.
83  * hscale     Scale horizontally, tile vertically ?
84  * vscale     Tile horizontally, scale vertically ?
85  * scale      Scale both up and down
86  * auto       Same as 100x100+50+50
87  */
88
89 #ifdef HAVE_BG_PIXMAP
90 bgPixmap_t::bgPixmap_t ()
91 {
92   // this is basically redundant as bgPixmap_t is only used in
93   // zero_initialised-derived structs
94 #ifdef HAVE_AFTERIMAGE
95   original_asim = NULL;
96 #endif
97 #ifdef BG_IMAGE_FROM_FILE
98   h_scale = v_scale = 0;
99   h_align = v_align = 0;
100 #endif
101   flags = 0;
102   pixmap = None;
103   valid_since = invalid_since = 0;
104   target = 0;
105 }
106
107 void
108 bgPixmap_t::destroy ()
109 {
110 #ifdef HAVE_AFTERIMAGE
111   if (original_asim)
112     safe_asimage_destroy (original_asim);
113 #endif
114
115   if (pixmap && target)
116     XFreePixmap (target->dpy, pixmap);
117 }
118
119 bool
120 bgPixmap_t::window_size_sensitive ()
121 {
122 # ifdef ENABLE_TRANSPARENCY
123   if (flags & isTransparent)
124     return true;
125 # endif
126
127 # ifdef BG_IMAGE_FROM_FILE
128 #  ifdef HAVE_AFTERIMAGE
129   if (original_asim)
130 #  endif
131     {
132       if (h_scale != 0 || v_scale != 0
133           || h_align != 0 || v_align != 0)
134         return true;
135     }
136 # endif
137
138   return false;
139 }
140
141 bool 
142 bgPixmap_t::window_position_sensitive () 
143 {
144 # ifdef ENABLE_TRANSPARENCY
145   if (flags & isTransparent)
146     return true;
147 # endif
148
149 # ifdef BG_IMAGE_FROM_FILE
150 #  ifdef HAVE_AFTERIMAGE
151   if (original_asim)
152 #  endif
153     {
154       if (h_align == rootAlign || v_align == rootAlign)
155         return true;
156     }
157 # endif
158
159   return false;
160 };
161
162 bool bgPixmap_t::need_client_side_rendering ()
163 {
164 # ifdef HAVE_AFTERIMAGE
165   if (original_asim)
166     return true;
167 # endif
168 # ifdef ENABLE_TRANSPARENCY
169   if (flags & isTransparent)
170     {
171 #  ifdef HAVE_AFTERIMAGE                // can't blur without libAI anyways
172       if ((flags & blurNeeded) && !(flags & blurServerSide))
173         return true;
174 #  endif
175       if ((flags & tintNeeded) && !(flags & tintServerSide))
176         return true;
177     }
178 # endif
179   return false;
180 }
181
182 # ifdef BG_IMAGE_FROM_FILE
183 static inline bool
184 check_set_scale_value (int geom_flags, int flag, unsigned int &scale, unsigned int new_value)
185 {
186   if (geom_flags & flag)
187     {
188       if (new_value > 1000)
189         new_value = 1000;
190       if (new_value != scale)
191         {
192           scale = new_value;
193           return true;
194         }
195     }
196   return false;
197 }
198
199 static inline bool
200 check_set_align_value (int geom_flags, int flag, int &align, int new_value)
201 {
202   if (geom_flags & flag)
203     {
204       if (new_value != bgPixmap_t::rootAlign)
205         {
206           if (new_value < -100)
207             new_value = -100;
208           else if (new_value > 200)
209             new_value = 200;
210         }
211       if (new_value != align)
212         {
213           align = new_value;
214           return true;
215         }
216     }
217   return false;
218 }
219
220 static inline int
221 make_align_position (int align, int window_size, int image_size)
222 {
223   int diff = window_size - image_size;
224   int smaller = MIN (image_size,window_size);
225
226   if (align >= 0 && align <= 50)
227     return diff * align / 100;
228   else if (align > 50 && align <= 100)
229     return window_size - image_size - diff * (100 - align) / 100;
230   else if (align > 100 && align <= 200 )
231     return ((align - 100) * smaller / 100) + window_size - smaller;
232   else if (align > -100 && align < 0)
233     return ((align + 100) * smaller / 100) - image_size;
234   return 0;
235 }
236
237 static inline int
238 make_clip_rectangle (int pos, int size, int target_size, int &dst_pos, int &dst_size)
239 {
240   int src_pos = 0;
241   dst_pos = 0;
242   dst_size = size;
243   if (pos < 0 && size > target_size)
244     {
245       src_pos = -pos;
246       dst_size += pos;
247     }
248   else if (pos > 0)
249     dst_pos = pos;
250
251   if (dst_pos + dst_size > target_size)
252     dst_size = target_size - dst_pos;
253   return src_pos;
254 }
255
256 bool
257 bgPixmap_t::set_geometry (const char *geom)
258 {
259   int geom_flags = 0, changed = 0;
260   int x = 0, y = 0;
261   unsigned int w = 0, h = 0;
262   unsigned int n;
263   unsigned long new_flags = (flags & (~geometryFlags));
264   const char *p;
265 #  define MAXLEN_GEOM           256 /* could be longer than regular geometry string */
266
267   if (geom == NULL)
268     return false;
269
270   char str[MAXLEN_GEOM];
271
272   while (isspace(*geom)) ++geom;
273   if ((p = strchr (geom, ';')) == NULL)
274     p = strchr (geom, '\0');
275
276   n = (p - geom);
277   if (n < MAXLEN_GEOM)
278     {
279       char *ops;
280       new_flags |= geometrySet;
281
282       memcpy (str, geom, n);
283       str[n] = '\0';
284       if (str[0] == ':')
285         ops = &str[0];
286       else if (str[0] != 'x' && str[0] != 'X' && isalpha(str[0]))
287         ops = &str[0];
288       else
289         {
290           char *tmp;
291           ops = strchr (str, ':');
292           if (ops != NULL)
293             {
294               for (tmp = ops-1; tmp >= str && isspace(*tmp); --tmp);
295               *(++tmp) = '\0';
296               if (ops == tmp) ++ops;
297             }
298         }
299
300       if (ops > str || ops == NULL)
301         {
302           /* we have geometry string - let's handle it prior to applying ops */
303           geom_flags = XParseGeometry (str, &x, &y, &w, &h);
304
305           if ((geom_flags & XValue) && !(geom_flags & YValue))
306             {
307               y = x;
308               geom_flags |= YValue;
309             }
310
311           if (flags & geometrySet)
312             {
313               /* new geometry is an adjustment to the old one ! */
314               if ((geom_flags & WidthValue) && (geom_flags & HeightValue))
315                 {
316                   if (w == 0 && h != 0)
317                     {
318                       w = h_scale;
319                       h = (v_scale * h) / 100;
320                     }
321                   else if (h == 0 && w != 0)
322                     {
323                       w = (h_scale * w) / 100;
324                       h = v_scale;
325                     }
326                 }
327               if (geom_flags & XValue)
328                 {
329                   if (str[0] != '=')
330                     {
331                       y += v_align;
332                       x += h_align;
333                     }
334                 }
335             }
336           else /* setting up geometry from scratch */
337             {
338               if (!(geom_flags & XValue))
339                 {
340                   /* use default geometry - centered */
341                   x = y = defaultAlign;
342                 }
343               else if (!(geom_flags & YValue))
344                 y = x;
345
346               if ((geom_flags & (WidthValue|HeightValue)) == 0)
347                 {
348                   /* use default geometry - scaled */
349                   w = h = defaultScale;
350                 }
351               else if (geom_flags & WidthValue)
352                 {
353                   if (!(geom_flags & HeightValue))
354                     h = w;
355                 }
356               else
357                 w = h;
358             }
359         } /* done parsing geometry string */
360       else if (!(flags & geometrySet))
361         {
362           /* default geometry - scaled and centered */
363           x = y = defaultAlign;
364           w = h = defaultScale;
365         }
366
367       if (!(flags & geometrySet))
368         geom_flags |= WidthValue|HeightValue|XValue|YValue;
369
370       if (ops)
371         {
372           while (*ops)
373             {
374               while (*ops == ':' || isspace(*ops)) ++ops;
375
376 #  define CHECK_GEOM_OPS(op_str)  (strncasecmp (ops, (op_str), sizeof (op_str) - 1) == 0)
377               if (CHECK_GEOM_OPS ("tile"))
378                 {
379                   w = h = noScale;
380                   geom_flags |= WidthValue|HeightValue;
381                 }
382               else if (CHECK_GEOM_OPS ("propscale"))
383                 {
384                   if (w == 0 && h == 0)
385                     {
386                       w = windowScale;
387                       geom_flags |= WidthValue;
388                     }
389                   new_flags |= propScale;
390                 }
391               else if (CHECK_GEOM_OPS ("hscale"))
392                 {
393                   if (w == 0) w = windowScale;
394
395                   h = noScale;
396                   geom_flags |= WidthValue|HeightValue;
397                 }
398               else if (CHECK_GEOM_OPS ("vscale"))
399                 {
400                   if (h == 0) h = windowScale;
401
402                   w = noScale;
403                   geom_flags |= WidthValue|HeightValue;
404                 }
405               else if (CHECK_GEOM_OPS ("scale"))
406                 {
407                   if (h == 0) h = windowScale;
408                   if (w == 0) w = windowScale;
409
410                   geom_flags |= WidthValue|HeightValue;
411                 }
412               else if (CHECK_GEOM_OPS ("auto"))
413                 {
414                   w = h = windowScale;
415                   x = y = centerAlign;
416                   geom_flags |= WidthValue|HeightValue|XValue|YValue;
417                 }
418               else if (CHECK_GEOM_OPS ("root"))
419                 {
420                   w = h = noScale;
421                   x = y = rootAlign;
422                   geom_flags |= WidthValue|HeightValue|XValue|YValue;
423                 }
424 #  undef CHECK_GEOM_OPS
425
426               while (*ops != ':' && *ops != '\0') ++ops;
427             } /* done parsing ops */
428         }
429
430       if (check_set_scale_value (geom_flags, WidthValue, h_scale, w))  ++changed;
431       if (check_set_scale_value (geom_flags, HeightValue, v_scale, h)) ++changed;
432       if (check_set_align_value (geom_flags, XValue, h_align, x))      ++changed;
433       if (check_set_align_value (geom_flags, YValue, v_align, y))      ++changed;
434     }
435
436   if (new_flags != flags)
437     {
438       flags = new_flags;
439       changed++;
440     }
441
442 //fprintf (stderr, "flags = %lX, scale = %ux%u, align=%+d%+d\n",
443 //         flags, h_scale, v_scale, h_align, v_align);
444   return (changed > 0);
445 }
446
447 #  ifdef HAVE_AFTERIMAGE
448 bool
449 bgPixmap_t::render_asim (ASImage *background, ARGB32 background_tint)
450 {
451   if (target == NULL)
452     return false;
453
454   target->init_asv ();
455
456   ASImage *result = 0;
457
458   int target_width    = target->szHint.width;
459   int target_height   = target->szHint.height;
460   int new_pmap_width  = target_width;
461   int new_pmap_height = target_height;
462
463   int x = 0;
464   int y = 0;
465   int w = h_scale * target_width / 100;
466   int h = v_scale * target_height / 100;
467
468   TIMING_TEST_START (asim);
469
470   if (original_asim)
471     {
472       if (h_align == rootAlign || v_align == rootAlign)
473         {
474           target->get_window_origin(x, y);
475           x = -x;
476           y = -y;
477         }
478
479       if (h_align != rootAlign)
480         x = make_align_position (h_align, target_width, w > 0 ? w : (int)original_asim->width);
481
482       if (v_align != rootAlign)
483         y = make_align_position (v_align, target_height, h > 0 ? h : (int)original_asim->height);
484     }
485
486   if (!original_asim
487       || x >= target_width
488       || y >= target_height
489       || (w > 0 && x + w <= 0)
490       || (h > 0 && y + h <= 0))
491     {
492       if (background)
493         {
494           new_pmap_width = background->width;
495           new_pmap_height = background->height;
496           result = background;
497
498           if (background_tint != TINT_LEAVE_SAME)
499             {
500               ASImage *tmp = tile_asimage (target->asv, background, 0, 0,
501                                            target_width, target_height, background_tint,
502                                            ASA_XImage, 100, ASIMAGE_QUALITY_DEFAULT);
503               if (tmp)
504                 result = tmp;
505             }
506         }
507       else
508         new_pmap_width = new_pmap_height = 0;
509     }
510   else
511     {
512       result = original_asim;
513
514       if ((w > 0 && w != original_asim->width)
515           || (h > 0 && h != original_asim->height))
516         {
517           result = scale_asimage (target->asv, original_asim,
518                                   w > 0 ? w : original_asim->width,
519                                   h > 0 ? h : original_asim->height,
520                                   background ? ASA_ASImage : ASA_XImage,
521                                   100, ASIMAGE_QUALITY_DEFAULT);
522         }
523
524       if (background == NULL)
525         {
526           /* if tiling - pixmap has to be sized exactly as the image,
527              but there is no need to make it bigger than the window! */
528           if (h_scale == 0)
529             new_pmap_width = min (result->width, target_width);
530           if (v_scale == 0)
531             new_pmap_height = min (result->height, target_height);
532           /* we also need to tile our image in one or both directions */
533           if (h_scale == 0 || v_scale == 0)
534             {
535               ASImage *tmp = tile_asimage (target->asv, result,
536                                            (h_scale > 0) ? 0 : (int)result->width - x,
537                                            (v_scale > 0) ? 0 : (int)result->height - y,
538                                            new_pmap_width, 
539                                            new_pmap_height,
540                                            TINT_LEAVE_SAME, ASA_XImage,
541                                            100, ASIMAGE_QUALITY_DEFAULT);
542               if (tmp)
543                 {
544                   if (result != original_asim)
545                     destroy_asimage (&result);
546
547                   result = tmp;
548                 }
549             }
550         }
551       else
552         {
553           /* if blending background and image - pixmap has to be sized same as target window */
554           ASImageLayer *layers = create_image_layers (2);
555           ASImage *merged_im = NULL;
556
557           layers[0].im = background;
558           layers[0].clip_width = target_width;
559           layers[0].clip_height = target_height;
560           layers[0].tint = background_tint;
561           layers[1].im = result;
562
563           if (w <= 0)
564             {
565               /* tile horizontally */
566               while (x > 0) x -= (int)result->width;
567               layers[1].dst_x = x;
568               layers[1].clip_width = result->width+target_width;
569             }
570           else
571             {
572               /* clip horizontally */
573               layers[1].dst_x = x;
574               layers[1].clip_width = result->width;
575             }
576
577           if (h <= 0)
578             {
579               while (y > 0) y -= (int)result->height;
580               layers[1].dst_y = y;
581               layers[1].clip_height = result->height + target_height;
582             }
583           else
584             {
585               layers[1].dst_y = y;
586               layers[1].clip_height = result->height;
587             }
588
589           if (target->rs[Rs_blendtype])
590             {
591               layers[1].merge_scanlines = blend_scanlines_name2func (target->rs[Rs_blendtype]);
592               if (layers[1].merge_scanlines == NULL)
593                 layers[1].merge_scanlines = alphablend_scanlines;
594             }
595
596           ASImage *tmp = merge_layers (target->asv, layers, 2, target_width, target_height,
597                                        ASA_XImage, 0, ASIMAGE_QUALITY_DEFAULT);
598
599           if (tmp)
600             {
601               if (result != original_asim)
602                 destroy_asimage (&result);
603
604               result = tmp;
605             }
606
607           free (layers);
608         }
609     }
610   TIMING_TEST_PRINT_RESULT (asim);
611
612   if (pixmap)
613     {
614       if (result == NULL
615           || pmap_width != new_pmap_width
616           || pmap_height != new_pmap_height
617           || pmap_depth != target->depth)
618         {
619           XFreePixmap (target->dpy, pixmap);
620           pixmap = None;
621         }
622     }
623
624   if (result)
625     {
626       XGCValues gcv;
627       GC gc;
628
629       /* create Pixmap */
630       if (pixmap == None)
631         {
632           pixmap = XCreatePixmap (target->dpy, target->vt, new_pmap_width, new_pmap_height, target->depth);
633           pmap_width = new_pmap_width;
634           pmap_height = new_pmap_height;
635           pmap_depth = target->depth;
636         }
637       /* fill with background color ( if result's not completely overlapping it)*/
638       gcv.foreground = target->pix_colors[Color_bg];
639       gc = XCreateGC (target->dpy, target->vt, GCForeground, &gcv);
640
641       int src_x = 0, src_y = 0, dst_x = 0, dst_y = 0;
642       int dst_width = result->width, dst_height = result->height;
643       if (background == NULL)
644         {
645           if (h_scale > 0) src_x = make_clip_rectangle (x, result->width , new_pmap_width , dst_x, dst_width );
646           if (v_scale > 0) src_y = make_clip_rectangle (y, result->height, new_pmap_height, dst_y, dst_height);
647
648           if (dst_x > 0 || dst_y > 0
649               || dst_x + dst_width < new_pmap_width
650               || dst_y + dst_height < new_pmap_height)
651             XFillRectangle (target->dpy, pixmap, gc, 0, 0, new_pmap_width, new_pmap_height);
652         }
653
654       /* put result on pixmap */
655       if (dst_x < new_pmap_width && dst_y < new_pmap_height)
656         asimage2drawable (target->asv, pixmap, result, gc, src_x, src_y, dst_x, dst_y, dst_width, dst_height, True);
657
658       if (result != background && result != original_asim)
659         destroy_asimage (&result);
660
661       XFreeGC (target->dpy, gc);
662       TIMING_TEST_PRINT_RESULT (asim);
663     }
664
665   return true;
666 }
667 #  endif /* HAVE_AFTERIMAGE */
668
669 bool
670 bgPixmap_t::set_file (const char *file)
671 {
672   assert (file);
673
674   if (*file)
675     {
676 #  ifdef HAVE_AFTERIMAGE
677       if (!target->asimman)
678         target->asimman = create_generic_imageman (target->rs[Rs_path]);
679
680       if (const char *p = strchr (file, ';'))
681         {
682           size_t len = p - file;
683           char *f = (char *)malloc (len + 1);
684           memcpy (f, file, len);
685           f[len] = '\0';
686           original_asim = get_asimage (target->asimman, f, 0xFFFFFFFF, 100);
687           free (f);
688         }
689       else
690         original_asim = get_asimage (target->asimman, file, 0xFFFFFFFF, 100);
691
692       return original_asim;
693 #  endif
694     }
695
696   return false;
697 }
698
699 # endif /* BG_IMAGE_FROM_FILE */
700
701 # ifdef ENABLE_TRANSPARENCY
702 bool
703 bgPixmap_t::set_transparent ()
704 {
705   if (!(flags & isTransparent))
706     {
707       flags |= isTransparent;
708       return true;
709     }
710
711   return false;
712 }
713
714 bool
715 bgPixmap_t::set_blur_radius (const char *geom)
716 {
717   int changed = 0;
718   unsigned int hr, vr;
719   int junk;
720   int geom_flags = XParseGeometry (geom, &junk, &junk, &hr, &vr);
721
722   if (!(geom_flags&WidthValue))
723     hr = 1;
724   if (!(geom_flags&HeightValue))
725     vr = hr;
726
727   if (h_blurRadius != hr)
728     {
729       ++changed;
730       h_blurRadius = hr;
731     }
732
733   if (v_blurRadius != vr)
734     {
735       ++changed;
736       v_blurRadius = vr;
737     }
738
739   if (v_blurRadius == 0 && h_blurRadius == 0)
740     flags &= ~blurNeeded;
741   else
742     flags |= blurNeeded;
743
744   return (changed>0);
745 }
746
747 static inline unsigned long
748 compute_tint_shade_flags (rxvt_color *tint, int shade)
749 {
750   unsigned long flags = 0;
751   rgba c (rgba::MAX_CC,rgba::MAX_CC,rgba::MAX_CC);
752   bool has_shade = (shade > 0 && shade < 100) || (shade > 100 && shade < 200);
753
754   if (tint)
755     {
756       tint->get (c);
757 #  define IS_COMPONENT_WHOLESOME(cmp)  ((cmp) <= 0x000700 || (cmp) >= 0x00f700)
758       if (!has_shade && IS_COMPONENT_WHOLESOME (c.r)
759           && IS_COMPONENT_WHOLESOME (c.g)
760           && IS_COMPONENT_WHOLESOME (c.b))
761         flags |= bgPixmap_t::tintWholesome;
762 #  undef  IS_COMPONENT_WHOLESOME
763     }
764
765   if (has_shade)
766     flags |= bgPixmap_t::tintNeeded;
767   else if (tint)
768     {
769       if ((c.r > 0x000700 || c.g > 0x000700 || c.b > 0x000700)
770           && (c.r < 0x00f700 || c.g < 0x00f700 || c.b < 0x00f700))
771       {
772         flags |= bgPixmap_t::tintNeeded;
773       }
774     }
775
776   if (flags & bgPixmap_t::tintNeeded)
777     {
778       if (flags & bgPixmap_t::tintWholesome)
779         flags |= bgPixmap_t::tintServerSide;
780       else
781         {
782 #if XFT
783           flags |= bgPixmap_t::tintServerSide;
784 #endif
785         }
786     }
787
788   return flags;
789 }
790
791 bool
792 bgPixmap_t::set_tint (rxvt_color &new_tint)
793 {
794   if (tint != new_tint)
795     {
796       unsigned long new_flags = compute_tint_shade_flags (&new_tint, shade);
797       tint = new_tint;
798       flags = (flags & ~tintFlags) | new_flags | tintSet;
799       return true;
800     }
801
802   return false;
803 }
804
805 bool
806 bgPixmap_t::unset_tint ()
807 {
808   unsigned long new_flags = compute_tint_shade_flags (NULL, shade);
809
810   if (new_flags != (flags & tintFlags))
811     {
812      flags = (flags&~tintFlags)|new_flags;
813      return true;
814     }
815
816   return false;
817 }
818
819 bool
820 bgPixmap_t::set_shade (const char *shade_str)
821 {
822   int new_shade = (shade_str) ? atoi (shade_str) : 0;
823
824   if (new_shade < 0 && new_shade > -100)
825     new_shade = 200 - (100 + new_shade);
826   else if (new_shade == 100)
827     new_shade = 0;
828
829   if (new_shade != shade)
830     {
831       unsigned long new_flags = compute_tint_shade_flags ((flags & tintSet) ? &tint : NULL, new_shade);
832       shade = new_shade;
833       flags = (flags & (~tintFlags | tintSet)) | new_flags;
834       return true;
835     }
836
837   return false;
838 }
839
840 /* make_transparency_pixmap()
841  * Builds a pixmap sized the same as terminal window, with depth same as the root window
842  * that pixmap contains tiled portion of the root pixmap that is supposed to be covered by
843  * our window.
844  */
845 unsigned long
846 bgPixmap_t::make_transparency_pixmap ()
847 {
848   unsigned long result = 0;
849
850   if (target == NULL)
851     return 0;
852
853   /* root dimentions may change from call to call - but Display structure should
854    * be always up-to-date, so let's use it :
855    */
856   Window root = target->display->root;
857   int screen = target->display->screen;
858   Display *dpy = target->dpy;
859   int root_width = DisplayWidth (dpy, screen);
860   int root_height = DisplayHeight (dpy, screen);
861   unsigned int root_pmap_width, root_pmap_height;
862   int window_width = target->szHint.width;
863   int window_height = target->szHint.height;
864   int sx, sy;
865   XGCValues gcv;
866
867   TIMING_TEST_START (tp);
868   target->get_window_origin (sx, sy);
869
870   /* check if we are outside of the visible part of the virtual screen : */
871   if (sx + window_width <= 0 || sy + window_height <= 0
872       || sx >= root_width || sy >= root_height)
873     return 0;
874
875   if (root_pixmap != None)
876     {
877       /* we want to validate the pixmap and get it's size at the same time : */
878       int junk;
879       unsigned int ujunk;
880       /* root pixmap may be bad - allow a error */
881       target->allowedxerror = -1;
882
883       if (!XGetGeometry (dpy, root_pixmap, &root, &junk, &junk, &root_pmap_width, &root_pmap_height, &ujunk, &ujunk))
884         root_pixmap = None;
885
886       target->allowedxerror = 0;
887     }
888
889   Pixmap tiled_root_pmap = XCreatePixmap (dpy, root, window_width, window_height, root_depth);
890   GC gc = NULL;
891
892   if (tiled_root_pmap == None) /* something really bad happened - abort */
893     return 0;
894
895   if (root_pixmap == None)
896     {
897       /* use tricks to obtain the root background image :*/
898       /* we want to create Overrideredirect window overlapping out window
899          with background type of Parent Relative and then grab it */
900       XSetWindowAttributes attr;
901       Window src;
902       bool success = false;
903
904       attr.background_pixmap = ParentRelative;
905       attr.backing_store = Always;
906       attr.event_mask = ExposureMask;
907       attr.override_redirect = True;
908           src = XCreateWindow (dpy, root, sx, sy, window_width, window_height, 0,
909                            CopyFromParent, CopyFromParent, CopyFromParent,
910                            CWBackPixmap|CWBackingStore|CWOverrideRedirect|CWEventMask,
911                            &attr);
912
913       if (src != None)
914         {
915           XEvent event;
916           int ev_count = 0;
917           XGrabServer (dpy);
918           XMapRaised (dpy, src);
919           XSync (dpy, False);
920
921           /* XSync should get window where it's properly exposed,
922            * but to be on the safe side - let's check for the actual event to arrive : */
923           while (XCheckWindowEvent (dpy, src, ExposureMask, &event))
924             ++ev_count;
925
926           if (ev_count > 0);
927             {
928               /* hooray! - we can grab the image! */
929               gc = XCreateGC (dpy, root, 0, NULL);
930               if (gc)
931                 {
932                   XCopyArea (dpy, src, tiled_root_pmap, gc, 0, 0, window_width, window_height, 0, 0);
933                   success = true;
934                 }
935             }
936
937           XDestroyWindow (dpy, src);
938           XUngrabServer (dpy);
939           //fprintf (stderr, "%s:%d: ev_count = %d\n", __FUNCTION__, __LINE__, ev_count);
940         }
941
942         if (!success)
943           {
944             XFreePixmap (dpy, tiled_root_pmap);
945             tiled_root_pmap = None;
946           }
947         else
948           result |= transpPmapTiled;
949     }
950   else
951     {
952       /* strightforward pixmap copy */
953       gcv.tile = root_pixmap;
954       gcv.fill_style = FillTiled;
955
956       while (sx < 0) sx += (int)root_width;
957       while (sy < 0) sy += (int)root_height;
958
959       gcv.ts_x_origin = -sx;
960       gcv.ts_y_origin = -sy;
961       gc = XCreateGC (dpy, root, GCFillStyle | GCTile | GCTileStipXOrigin | GCTileStipYOrigin, &gcv);
962
963       if (gc)
964         {
965           XFillRectangle (dpy, tiled_root_pmap, gc, 0, 0, window_width, window_height);
966           result |= transpPmapTiled;
967         }
968     }
969   TIMING_TEST_PRINT_RESULT (tp);
970
971   if (tiled_root_pmap != None)
972     {
973       if (!need_client_side_rendering ())
974         {
975           if ((flags & tintNeeded))
976             {
977               if (flags & tintWholesome)
978                 {
979                   /* In this case we can tint image server-side getting significant
980                    * performance improvements, as we eliminate XImage transfer
981                    */
982                   gcv.foreground = Pixel (tint);
983                   gcv.function = GXand;
984                   gcv.fill_style = FillSolid;
985                   if (gc)
986                     XChangeGC (dpy, gc, GCFillStyle | GCForeground | GCFunction, &gcv);
987                   else
988                     gc = XCreateGC (dpy, root, GCFillStyle | GCForeground | GCFunction, &gcv);
989                   if (gc)
990                     {
991                       XFillRectangle (dpy, tiled_root_pmap, gc, 0, 0, window_width, window_height);
992                       result |= transpPmapTinted;
993                     }
994                 }
995               else
996                 {
997 #  if XFT
998                   Picture back_pic = 0;
999                   rgba c (rgba::MAX_CC,rgba::MAX_CC,rgba::MAX_CC);
1000
1001                   if (flags & tintSet)
1002                     tint.get (c);
1003
1004                   if (shade > 0 && shade < 100)
1005                     {
1006                       c.r = (c.r * shade) / 100;
1007                       c.g = (c.g * shade) / 100;
1008                       c.b = (c.b * shade) / 100;
1009                     }
1010                   else if (shade > 100 && shade < 200)
1011                     {
1012                       c.r = (c.r * (200 - shade)) / 100;
1013                       c.g = (c.g * (200 - shade)) / 100;
1014                       c.b = (c.b * (200 - shade)) / 100;
1015                     }
1016
1017                   XRenderPictFormat pf;
1018                   pf.type = PictTypeDirect;
1019                   pf.depth = 32;
1020                   pf.direct.redMask = 0xff;
1021                   pf.direct.greenMask = 0xff;
1022                   pf.direct.blueMask = 0xff;
1023                   pf.direct.alphaMask = 0xff;
1024
1025                   XRenderPictFormat *solid_format = XRenderFindFormat (dpy,
1026                                                                        (PictFormatType|
1027                                                                         PictFormatDepth|
1028                                                                         PictFormatRedMask|
1029                                                                         PictFormatGreenMask|
1030                                                                         PictFormatBlueMask|
1031                                                                         PictFormatAlphaMask),
1032                                                                        &pf,
1033                                                                        0);
1034                   XRenderPictFormat *root_format = XRenderFindVisualFormat (dpy, DefaultVisualOfScreen (ScreenOfDisplay (dpy, target->display->screen)));
1035                   XRenderPictureAttributes pa ;
1036
1037                   back_pic = XRenderCreatePicture (dpy, tiled_root_pmap, root_format, 0, &pa);
1038
1039                   pa.repeat = True;
1040
1041                   Pixmap overlay_pmap = XCreatePixmap (dpy, root, 1, 1, 32);
1042                   Picture overlay_pic = XRenderCreatePicture (dpy, overlay_pmap, solid_format, CPRepeat, &pa);
1043                   XFreePixmap (dpy, overlay_pmap);
1044
1045                   pa.component_alpha = True;
1046                   Pixmap mask_pmap = XCreatePixmap (dpy, root, 1, 1, 32);
1047                   Picture mask_pic = XRenderCreatePicture (dpy, mask_pmap, solid_format, CPRepeat|CPComponentAlpha, &pa);
1048                   XFreePixmap (dpy, mask_pmap);
1049
1050                   if (mask_pic && overlay_pic && back_pic)
1051                     {
1052                       XRenderColor mask_c;
1053
1054                       memset (&mask_c, (shade > 100) ? 0xFF : 0x0, sizeof (mask_c));
1055                       mask_c.alpha = 0xffff;
1056                       XRenderFillRectangle (dpy, PictOpSrc, overlay_pic, &mask_c, 0, 0, 1, 1);
1057
1058                       mask_c.alpha = 0;
1059                       mask_c.red = 0xffff - c.r;
1060                       mask_c.green = 0xffff - c.g;
1061                       mask_c.blue = 0xffff - c.b;
1062                       XRenderFillRectangle (dpy, PictOpSrc, mask_pic, &mask_c, 0, 0, 1, 1);
1063                       XRenderComposite (dpy, PictOpOver, overlay_pic, mask_pic, back_pic, 0, 0, 0, 0, 0, 0, window_width, window_height);
1064                       result |= transpPmapTinted;
1065                     }
1066
1067                   XRenderFreePicture (dpy, mask_pic);
1068                   XRenderFreePicture (dpy, overlay_pic);
1069                   XRenderFreePicture (dpy, back_pic);
1070 #   if DO_TIMING_TEST
1071                   XSync (dpy, False);
1072 #   endif
1073 #  endif
1074                 }
1075              }
1076         } /* server side rendering completed */
1077
1078       if (pixmap)
1079         XFreePixmap (dpy, pixmap);
1080
1081       pixmap = tiled_root_pmap;
1082       pmap_width = window_width;
1083       pmap_height = window_height;
1084       pmap_depth = root_depth;
1085     }
1086
1087   if (gc)
1088     XFreeGC (dpy, gc);
1089
1090   TIMING_TEST_PRINT_RESULT (tp);
1091
1092   return result;
1093 }
1094
1095 bool
1096 bgPixmap_t::set_root_pixmap ()
1097 {
1098   Pixmap new_root_pixmap = target->get_pixmap_property (XA_XROOTPMAP_ID);
1099   if (new_root_pixmap == None)
1100     new_root_pixmap = target->get_pixmap_property (XA_ESETROOT_PMAP_ID);
1101
1102   if (new_root_pixmap != root_pixmap)
1103     {
1104       root_pixmap = new_root_pixmap;
1105       return true;
1106     }
1107
1108   return false;
1109 }
1110 # endif /* ENABLE_TRANSPARENCY */
1111
1112 # ifndef HAVE_AFTERIMAGE
1113 static void ShadeXImage(rxvt_term *term, XImage *srcImage, int shade, int rm, int gm, int bm);
1114 # endif
1115
1116 bool
1117 bgPixmap_t::render ()
1118 {
1119   unsigned long background_flags = 0;
1120
1121   if (target == NULL)
1122     return false;
1123
1124   TIMING_TEST_START (tp);
1125
1126   invalidate ();
1127 # ifdef ENABLE_TRANSPARENCY
1128   if (flags & isTransparent)
1129     {
1130       /*  we need to re-generate transparency pixmap in that case ! */
1131       background_flags = make_transparency_pixmap ();
1132       if (background_flags == 0)
1133         return false;
1134       else if ((background_flags & transpTransformations) == (flags & transpTransformations)
1135                 && pmap_depth == target->depth)
1136         flags = flags & ~isInvalid;
1137     }
1138 # endif
1139
1140   XImage *result = NULL;
1141 # ifdef HAVE_AFTERIMAGE
1142   if (original_asim
1143       || (background_flags & transpTransformations) != (flags & transpTransformations))
1144     {
1145       target->init_asv ();
1146
1147       ASImage *background = NULL;
1148       ARGB32 as_tint = TINT_LEAVE_SAME;
1149       if (background_flags)
1150         background = pixmap2ximage (target->asv, pixmap, 0, 0, pmap_width, pmap_height, AllPlanes, 100);
1151
1152 #  ifdef ENABLE_TRANSPARENCY
1153       if (!(background_flags & transpPmapTinted) && (flags & tintNeeded))
1154         {
1155           ShadingInfo as_shade;
1156           as_shade.shading = (shade == 0) ? 100 : shade;
1157
1158           rgba c (rgba::MAX_CC,rgba::MAX_CC,rgba::MAX_CC);
1159           if (flags & tintSet)
1160             tint.get (c);
1161           as_shade.tintColor.red = c.r;
1162           as_shade.tintColor.green = c.g;
1163           as_shade.tintColor.blue = c.b;
1164
1165           as_tint = shading2tint32 (&as_shade);
1166         }
1167
1168       if (!(background_flags & transpPmapBlured) && (flags & blurNeeded) && background != NULL)
1169         {
1170           ASImage *tmp = blur_asimage_gauss (target->asv, background, h_blurRadius, v_blurRadius, 0xFFFFFFFF,
1171                                              (original_asim == NULL || tint == TINT_LEAVE_SAME)?ASA_XImage:ASA_ASImage,
1172                                              100, ASIMAGE_QUALITY_DEFAULT);
1173           if (tmp)
1174             {
1175               destroy_asimage (&background);
1176               background = tmp;
1177             }
1178         }
1179 #  endif
1180
1181       if (render_asim (background, as_tint))
1182         flags = flags & ~isInvalid;
1183       if (background)
1184         destroy_asimage (&background);
1185     }
1186   else if (background_flags && pmap_depth != target->depth)
1187     result = XGetImage (target->dpy, pixmap, 0, 0, pmap_width, pmap_height, AllPlanes, ZPixmap);
1188
1189 # elif !XFT /* our own client-side tinting */
1190
1191   /* ATTENTION: We ASSUME that XFT will let us do all the tinting neccessary server-side.
1192      This may need to be changed in need_client_side_rendering() logic is altered !!! */
1193
1194   if (background_flags && (flags & isInvalid))
1195     {
1196       result = XGetImage (target->dpy, pixmap, 0, 0, pmap_width, pmap_height, AllPlanes, ZPixmap);
1197
1198       if (result != NULL && !(background_flags & transpPmapTinted) && (flags & tintNeeded))
1199         {
1200           rgba c (rgba::MAX_CC,rgba::MAX_CC,rgba::MAX_CC);
1201           if (flags & tintSet)
1202             tint.get (c);
1203           ShadeXImage (target, result, shade, c.r, c.g, c.b);
1204         }
1205     }
1206 # endif /* HAVE_AFTERIMAGE */
1207
1208   if (result)
1209     {
1210       GC gc = XCreateGC (target->dpy, target->vt, 0UL, NULL);
1211
1212       if (gc)
1213         {
1214           if (/*pmap_depth != target->depth &&*/ pixmap != None)
1215             {
1216               XFreePixmap (target->dpy, pixmap);
1217               pixmap = None;
1218             }
1219
1220           if (pixmap == None)
1221             {
1222               pixmap = XCreatePixmap (target->dpy, target->vt, result->width, result->height, target->depth);
1223               pmap_width  = result->width;
1224               pmap_height = result->height;
1225               pmap_depth  = target->depth;
1226             }
1227
1228           if (pmap_depth != result->depth)
1229             {
1230               /* Bad Match error will ensue ! stupid X !!!! */
1231               if (result->depth == 24 && pmap_depth == 32)
1232                 result->depth = 32;
1233               else if (result->depth == 32 && pmap_depth == 24)
1234                 result->depth = 24;
1235               else
1236                 {
1237                   /* TODO: implement image recoding */
1238                 }
1239             }
1240
1241           if (pmap_depth == result->depth)
1242             XPutImage (target->dpy, pixmap, gc, result, 0, 0, 0, 0, result->width, result->height);
1243
1244           XFreeGC (target->dpy, gc);
1245           flags = flags & ~isInvalid;
1246         }
1247
1248         XDestroyImage (result);
1249     }
1250
1251   if (flags & isInvalid)
1252     {
1253       if (pixmap != None)
1254         {
1255           XFreePixmap (target->dpy, pixmap);
1256           pixmap = None;
1257         }
1258     }
1259
1260   apply ();
1261
1262   XSync (target->dpy, False);
1263   valid_since = ev::now ();
1264
1265   TIMING_TEST_PRINT_RESULT (tp);
1266
1267   return true;
1268 }
1269
1270 bool
1271 bgPixmap_t::set_target (rxvt_term *new_target)
1272 {
1273   if (new_target)
1274     if (target != new_target)
1275       {
1276         target = new_target;
1277 # ifdef ENABLE_TRANSPARENCY
1278         root_depth = DefaultDepthOfScreen (ScreenOfDisplay (target->dpy, target->display->screen));
1279 # endif
1280         return true;
1281       }
1282
1283   return false;
1284 }
1285
1286 void
1287 bgPixmap_t::apply ()
1288 {
1289   if (target)
1290     {
1291       flags &= ~isVtOrigin;
1292
1293       if (pixmap != None)
1294         {
1295           /* set target's background to pixmap */
1296 # ifdef ENABLE_TRANSPARENCY
1297           if (flags & isTransparent)
1298             {
1299               XSetWindowBackgroundPixmap (target->dpy, target->parent[0], pixmap);
1300               XSetWindowBackgroundPixmap (target->dpy, target->vt, ParentRelative);
1301
1302               if (target->scrollBar.win)
1303                 XSetWindowBackgroundPixmap (target->dpy, target->scrollBar.win, ParentRelative);
1304             }
1305           else
1306 # endif
1307             {
1308               flags |= isVtOrigin;
1309               /* force old pixmap dereference in case it was transparent before :*/
1310               XSetWindowBackground (target->dpy, target->parent[0], target->pix_colors[Color_border]);
1311               XSetWindowBackgroundPixmap (target->dpy, target->vt, pixmap);
1312               /* do we also need to set scrollbar's background here ? */
1313
1314               if (target->scrollBar.win)
1315                 XSetWindowBackground (target->dpy, target->scrollBar.win, target->pix_colors[Color_border]);
1316             }
1317         }
1318       else
1319         {
1320           /* set target background to a pixel */
1321           XSetWindowBackground (target->dpy, target->parent[0], target->pix_colors[Color_border]);
1322           XSetWindowBackground (target->dpy, target->vt, target->pix_colors[Color_bg]);
1323           /* do we also need to set scrollbar's background here ? */
1324           if (target->scrollBar.win)
1325             XSetWindowBackground (target->dpy, target->scrollBar.win, target->pix_colors[Color_border]);
1326         }
1327
1328       /* don't want Expose on the parent or vt. It is better to use
1329          scr_touch or we get a great deal of flicker otherwise: */
1330       XClearWindow (target->dpy, target->parent[0]);
1331
1332       if (target->scrollBar.state && target->scrollBar.win)
1333         {
1334           target->scrollBar.state = STATE_IDLE;
1335           target->scrollBar.show (0);
1336         }
1337
1338       target->want_refresh = 1;
1339       flags |= hasChanged;
1340     }
1341 }
1342
1343 #endif /* HAVE_BG_PIXMAP */
1344
1345 #if defined(ENABLE_TRANSPARENCY) && !defined(HAVE_AFTERIMAGE) && !XFT
1346 /* taken from aterm-0.4.2 */
1347
1348 typedef uint32_t RUINT32T;
1349
1350 static void
1351 ShadeXImage(rxvt_term *term, XImage *srcImage, int shade, int rm, int gm, int bm)
1352 {
1353   int sh_r, sh_g, sh_b;
1354   RUINT32T mask_r, mask_g, mask_b;
1355   RUINT32T *lookup, *lookup_r, *lookup_g, *lookup_b;
1356   unsigned int lower_lim_r, lower_lim_g, lower_lim_b;
1357   unsigned int upper_lim_r, upper_lim_g, upper_lim_b;
1358   int i;
1359
1360   Visual *visual = term->visual;
1361
1362   if (visual->c_class != TrueColor || srcImage->format != ZPixmap) return ;
1363
1364   if (shade == 0)
1365     shade = 100;
1366
1367   /* for convenience */
1368   mask_r = visual->red_mask;
1369   mask_g = visual->green_mask;
1370   mask_b = visual->blue_mask;
1371
1372   /* boring lookup table pre-initialization */
1373   switch (srcImage->bits_per_pixel) {
1374     case 15:
1375       if ((mask_r != 0x7c00) ||
1376           (mask_g != 0x03e0) ||
1377           (mask_b != 0x001f))
1378         return;
1379         lookup = (RUINT32T *) malloc (sizeof (RUINT32T)*(32+32+32));
1380         lookup_r = lookup;
1381         lookup_g = lookup+32;
1382         lookup_b = lookup+32+32;
1383         sh_r = 10;
1384         sh_g = 5;
1385         sh_b = 0;
1386       break;
1387     case 16:
1388       if ((mask_r != 0xf800) ||
1389           (mask_g != 0x07e0) ||
1390           (mask_b != 0x001f))
1391         return;
1392         lookup = (RUINT32T *) malloc (sizeof (RUINT32T)*(32+64+32));
1393         lookup_r = lookup;
1394         lookup_g = lookup+32;
1395         lookup_b = lookup+32+64;
1396         sh_r = 11;
1397         sh_g = 5;
1398         sh_b = 0;
1399       break;
1400     case 24:
1401       if ((mask_r != 0xff0000) ||
1402           (mask_g != 0x00ff00) ||
1403           (mask_b != 0x0000ff))
1404         return;
1405         lookup = (RUINT32T *) malloc (sizeof (RUINT32T)*(256+256+256));
1406         lookup_r = lookup;
1407         lookup_g = lookup+256;
1408         lookup_b = lookup+256+256;
1409         sh_r = 16;
1410         sh_g = 8;
1411         sh_b = 0;
1412       break;
1413     case 32:
1414       if ((mask_r != 0xff0000) ||
1415           (mask_g != 0x00ff00) ||
1416           (mask_b != 0x0000ff))
1417         return;
1418         lookup = (RUINT32T *) malloc (sizeof (RUINT32T)*(256+256+256));
1419         lookup_r = lookup;
1420         lookup_g = lookup+256;
1421         lookup_b = lookup+256+256;
1422         sh_r = 16;
1423         sh_g = 8;
1424         sh_b = 0;
1425       break;
1426     default:
1427       return; /* we do not support this color depth */
1428   }
1429
1430   /* prepare limits for color transformation (each channel is handled separately) */
1431   if (shade < 0) {
1432     shade = -shade;
1433     if (shade < 0) shade = 0;
1434     if (shade > 100) shade = 100;
1435
1436     lower_lim_r = 65535-rm;
1437     lower_lim_g = 65535-gm;
1438     lower_lim_b = 65535-bm;
1439
1440     lower_lim_r = 65535-(unsigned int)(((RUINT32T)lower_lim_r)*((RUINT32T)shade)/100);
1441     lower_lim_g = 65535-(unsigned int)(((RUINT32T)lower_lim_g)*((RUINT32T)shade)/100);
1442     lower_lim_b = 65535-(unsigned int)(((RUINT32T)lower_lim_b)*((RUINT32T)shade)/100);
1443
1444     upper_lim_r = upper_lim_g = upper_lim_b = 65535;
1445   } else {
1446     if (shade < 0) shade = 0;
1447     if (shade > 100) shade = 100;
1448
1449     lower_lim_r = lower_lim_g = lower_lim_b = 0;
1450
1451     upper_lim_r = (unsigned int)((((RUINT32T)rm)*((RUINT32T)shade))/100);
1452     upper_lim_g = (unsigned int)((((RUINT32T)gm)*((RUINT32T)shade))/100);
1453     upper_lim_b = (unsigned int)((((RUINT32T)bm)*((RUINT32T)shade))/100);
1454   }
1455
1456   /* switch red and blue bytes if necessary, we need it for some weird XServers like XFree86 3.3.3.1 */
1457   if ((srcImage->bits_per_pixel == 24) && (mask_r >= 0xFF0000 ))
1458   {
1459     unsigned int tmp;
1460
1461     tmp = lower_lim_r;
1462     lower_lim_r = lower_lim_b;
1463     lower_lim_b = tmp;
1464
1465     tmp = upper_lim_r;
1466     upper_lim_r = upper_lim_b;
1467     upper_lim_b = tmp;
1468   }
1469
1470   /* fill our lookup tables */
1471   for (i = 0; i <= mask_r>>sh_r; i++)
1472   {
1473     RUINT32T tmp;
1474     tmp = ((RUINT32T)i)*((RUINT32T)(upper_lim_r-lower_lim_r));
1475     tmp += ((RUINT32T)(mask_r>>sh_r))*((RUINT32T)lower_lim_r);
1476     lookup_r[i] = (tmp/65535)<<sh_r;
1477   }
1478   for (i = 0; i <= mask_g>>sh_g; i++)
1479   {
1480     RUINT32T tmp;
1481     tmp = ((RUINT32T)i)*((RUINT32T)(upper_lim_g-lower_lim_g));
1482     tmp += ((RUINT32T)(mask_g>>sh_g))*((RUINT32T)lower_lim_g);
1483     lookup_g[i] = (tmp/65535)<<sh_g;
1484   }
1485   for (i = 0; i <= mask_b>>sh_b; i++)
1486   {
1487     RUINT32T tmp;
1488     tmp = ((RUINT32T)i)*((RUINT32T)(upper_lim_b-lower_lim_b));
1489     tmp += ((RUINT32T)(mask_b>>sh_b))*((RUINT32T)lower_lim_b);
1490     lookup_b[i] = (tmp/65535)<<sh_b;
1491   }
1492
1493   /* apply table to input image (replacing colors by newly calculated ones) */
1494   switch (srcImage->bits_per_pixel)
1495   {
1496     case 15:
1497     {
1498       unsigned short *p1, *pf, *p, *pl;
1499       p1 = (unsigned short *) srcImage->data;
1500       pf = (unsigned short *) (srcImage->data + srcImage->height * srcImage->bytes_per_line);
1501       while (p1 < pf)
1502       {
1503         p = p1;
1504         pl = p1 + srcImage->width;
1505         for (; p < pl; p++)
1506         {
1507           *p = lookup_r[(*p & 0x7c00)>>10] |
1508                lookup_g[(*p & 0x03e0)>> 5] |
1509                lookup_b[(*p & 0x001f)];
1510         }
1511         p1 = (unsigned short *) ((char *) p1 + srcImage->bytes_per_line);
1512       }
1513       break;
1514     }
1515     case 16:
1516     {
1517       unsigned short *p1, *pf, *p, *pl;
1518       p1 = (unsigned short *) srcImage->data;
1519       pf = (unsigned short *) (srcImage->data + srcImage->height * srcImage->bytes_per_line);
1520       while (p1 < pf)
1521       {
1522         p = p1;
1523         pl = p1 + srcImage->width;
1524         for (; p < pl; p++)
1525         {
1526           *p = lookup_r[(*p & 0xf800)>>11] |
1527                lookup_g[(*p & 0x07e0)>> 5] |
1528                lookup_b[(*p & 0x001f)];
1529         }
1530         p1 = (unsigned short *) ((char *) p1 + srcImage->bytes_per_line);
1531       }
1532       break;
1533     }
1534     case 24:
1535     {
1536       unsigned char *p1, *pf, *p, *pl;
1537       p1 = (unsigned char *) srcImage->data;
1538       pf = (unsigned char *) (srcImage->data + srcImage->height * srcImage->bytes_per_line);
1539       while (p1 < pf)
1540       {
1541         p = p1;
1542         pl = p1 + srcImage->width * 3;
1543         for (; p < pl; p += 3)
1544         {
1545           p[0] = lookup_r[(p[0] & 0xff0000)>>16];
1546           p[1] = lookup_r[(p[1] & 0x00ff00)>> 8];
1547           p[2] = lookup_r[(p[2] & 0x0000ff)];
1548         }
1549         p1 = (unsigned char *) ((char *) p1 + srcImage->bytes_per_line);
1550       }
1551       break;
1552     }
1553     case 32:
1554     {
1555       RUINT32T *p1, *pf, *p, *pl;
1556       p1 = (RUINT32T *) srcImage->data;
1557       pf = (RUINT32T *) (srcImage->data + srcImage->height * srcImage->bytes_per_line);
1558
1559       while (p1 < pf)
1560       {
1561         p = p1;
1562         pl = p1 + srcImage->width;
1563         for (; p < pl; p++)
1564         {
1565           *p = lookup_r[(*p & 0xff0000)>>16] |
1566                lookup_g[(*p & 0x00ff00)>> 8] |
1567                lookup_b[(*p & 0x0000ff)] |
1568                (*p & ~0xffffff);
1569         }
1570         p1 = (RUINT32T *) ((char *) p1 + srcImage->bytes_per_line);
1571       }
1572       break;
1573     }
1574   }
1575
1576   free (lookup);
1577 }
1578 #endif /* defined(ENABLE_TRANSPARENCY) && !defined(HAVE_AFTERIMAGE) */