91ee80731ec58f84494b32189cdc12821870c4f6
[dana/xcompmgr.git] / xcompmgr.c
1 /*
2  * $Id$
3  *
4  * Copyright © 2003 Keith Packard
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of Keith Packard not be used in
11  * advertising or publicity pertaining to distribution of the software without
12  * specific, written prior permission.  Keith Packard makes no
13  * representations about the suitability of this software for any purpose.  It
14  * is provided "as is" without express or implied warranty.
15  *
16  * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
17  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
18  * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
19  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
20  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
21  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22  * PERFORMANCE OF THIS SOFTWARE.
23  */
24
25
26 /* Modified by Matthew Hawn. I don't know what to say here so follow what it 
27    says above. Not that I can really do anything about it
28 */
29
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <math.h>
35 #include <sys/poll.h>
36 #include <sys/time.h>
37 #include <time.h>
38 #include <unistd.h>
39 #include <getopt.h>
40 #include <X11/Xlib.h>
41 #include <X11/Xutil.h>
42 #include <X11/Xatom.h>
43 #include <X11/extensions/Xcomposite.h>
44 #include <X11/extensions/Xdamage.h>
45 #include <X11/extensions/Xrender.h>
46
47 #if COMPOSITE_MAJOR > 0 || COMPOSITE_MINOR >= 2
48 #define HAS_NAME_WINDOW_PIXMAP 1
49 #endif
50
51 #define CAN_DO_USABLE 0
52
53 typedef enum {
54     WINTYPE_DESKTOP,
55     WINTYPE_DOCK,
56     WINTYPE_TOOLBAR,
57     WINTYPE_MENU,
58     WINTYPE_UTILITY,
59     WINTYPE_SPLASH,
60     WINTYPE_DIALOG,
61     WINTYPE_NORMAL,
62     WINTYPE_DROPDOWN_MENU,
63     WINTYPE_POPUP_MENU,
64     WINTYPE_TOOLTIP,
65     WINTYPE_NOTIFY,
66     WINTYPE_COMBO,
67     WINTYPE_DND,
68     NUM_WINTYPES
69 } wintype;
70
71 typedef struct _ignore {
72     struct _ignore      *next;
73     unsigned long       sequence;
74 } ignore;
75
76 typedef struct _win {
77     struct _win         *next;
78     Window              id;
79 #if HAS_NAME_WINDOW_PIXMAP
80     Pixmap              pixmap;
81 #endif
82     XWindowAttributes   a;
83 #if CAN_DO_USABLE
84     Bool                usable;             /* mapped and all damaged at one point */
85     XRectangle          damage_bounds;      /* bounds of damage */
86 #endif
87     int                 mode;
88     int                 damaged;
89     Damage              damage;
90     Picture             picture;
91     Picture             alphaPict;
92     Picture             shadowPict;
93     XserverRegion       borderSize;
94     XserverRegion       extents;
95     Picture             shadow;
96     int                 shadow_dx;
97     int                 shadow_dy;
98     int                 shadow_width;
99     int                 shadow_height;
100     unsigned int        opacity;
101     wintype             windowType;
102     unsigned long       damage_sequence;    /* sequence when damage was created */
103     Bool                destroyed;
104
105     Bool                need_configure;
106     XConfigureEvent     queue_configure;
107
108     /* for drawing translucent windows */
109     XserverRegion       borderClip;
110     struct _win         *prev_trans;
111 } win;
112
113 typedef struct _conv {
114     int     size;
115     double  *data;
116 } conv;
117
118 typedef struct _fade {
119     struct _fade        *next;
120     win                 *w;
121     double              cur;
122     double              finish;
123     double              step;
124     void                (*callback) (Display *dpy, win *w);
125     Display             *dpy;
126 } fade;
127
128 win             *list;
129 fade            *fades;
130 Display         *dpy;
131 int             scr;
132 Window          root;
133 Picture         rootPicture;
134 Picture         rootBuffer;
135 Picture         blackPicture;
136 Picture         transBlackPicture;
137 Picture         rootTile;
138 XserverRegion   allDamage;
139 Bool            clipChanged;
140 #if HAS_NAME_WINDOW_PIXMAP
141 Bool            hasNamePixmap;
142 #endif
143 int             root_height, root_width;
144 ignore          *ignore_head, **ignore_tail = &ignore_head;
145 int             xfixes_event, xfixes_error;
146 int             damage_event, damage_error;
147 int             composite_event, composite_error;
148 int             render_event, render_error;
149 Bool            synchronize;
150 int             composite_opcode;
151
152 /* find these once and be done with it */
153 Atom            opacityAtom;
154 Atom            winTypeAtom;
155 Atom            winType[NUM_WINTYPES];
156 double          winTypeOpacity[NUM_WINTYPES];
157 Bool            winTypeShadow[NUM_WINTYPES];
158 Bool            winTypeFade[NUM_WINTYPES];
159
160 /* opacity property name; sometime soon I'll write up an EWMH spec for it */
161 #define OPACITY_PROP    "_NET_WM_WINDOW_OPACITY"
162 #define REGISTER_PROP   "_NET_WM_CM_S"
163
164 #define TRANSLUCENT     0xe0000000
165 #define OPAQUE          0xffffffff
166
167 conv            *gaussianMap;
168
169 #define WINDOW_SOLID    0
170 #define WINDOW_TRANS    1
171 #define WINDOW_ARGB     2
172
173 #define TRANS_OPACITY   0.75
174
175 #define DEBUG_REPAINT 0
176 #define DEBUG_EVENTS 0
177 #define MONITOR_REPAINT 0
178
179 #define SHADOWS         1
180 #define SHARP_SHADOW    0
181
182 typedef enum _compMode {
183     CompSimple,         /* looks like a regular X server */
184     CompServerShadows,  /* use window alpha for shadow; sharp, but precise */
185     CompClientShadows,  /* use window extents for shadow, blurred */
186 } CompMode;
187
188 static void
189 determine_mode(Display *dpy, win *w);
190     
191 static double
192 get_opacity_percent(Display *dpy, win *w);
193
194 static XserverRegion
195 win_extents (Display *dpy, win *w);
196
197 CompMode    compMode = CompSimple;
198
199 int         shadowRadius = 12;
200 int         shadowOffsetX = -15;
201 int         shadowOffsetY = -15;
202 double      shadowOpacity = .75;
203
204 double  fade_in_step =  0.028;
205 double  fade_out_step = 0.03;
206 int     fade_delta =    10;
207 int     fade_time =     0;
208 Bool    fadeTrans = False;
209
210 Bool    autoRedirect = False;
211
212 /* For shadow precomputation */
213 int            Gsize = -1;
214 unsigned char *shadowCorner = NULL;
215 unsigned char *shadowTop = NULL;
216
217 int
218 get_time_in_milliseconds ()
219 {
220     struct timeval  tv;
221
222     gettimeofday (&tv, NULL);
223     return tv.tv_sec * 1000 + tv.tv_usec / 1000;
224 }
225
226 fade *
227 find_fade (win *w)
228 {
229     fade    *f;
230     
231     for (f = fades; f; f = f->next)
232     {
233         if (f->w == w)
234             return f;
235     }
236     return 0;
237 }
238
239 void
240 dequeue_fade (Display *dpy, fade *f)
241 {
242     fade    **prev;
243
244     for (prev = &fades; *prev; prev = &(*prev)->next)
245         if (*prev == f)
246         {
247             *prev = f->next;
248             if (f->callback)
249                 (*f->callback) (dpy, f->w);
250             free (f);
251             break;
252         }
253 }
254
255 void
256 cleanup_fade (Display *dpy, win *w)
257 {
258     fade *f = find_fade (w);
259     if (f)
260         dequeue_fade (dpy, f);
261 }
262
263 void
264 enqueue_fade (Display *dpy, fade *f)
265 {
266     if (!fades)
267         fade_time = get_time_in_milliseconds () + fade_delta;
268     f->next = fades;
269     fades = f;
270 }
271
272 static void
273 set_fade (Display *dpy, win *w, double start, double finish, double step,
274           void (*callback) (Display *dpy, win *w),
275           Bool exec_callback, Bool override)
276 {
277     fade    *f;
278
279     f = find_fade (w);
280     if (!f)
281     {
282         f = malloc (sizeof (fade));
283         f->next = 0;
284         f->w = w;
285         f->cur = start;
286         enqueue_fade (dpy, f);
287     }
288     else if(!override)
289         return;
290     else
291     {
292         if (exec_callback)
293             if (f->callback)
294                 (*f->callback)(dpy, f->w);
295     }
296
297     if (finish < 0)
298         finish = 0;
299     if (finish > 1)
300         finish = 1;
301     f->finish = finish;
302     if (f->cur < finish)
303         f->step = step;
304     else if (f->cur > finish)
305         f->step = -step;
306     f->callback = callback;
307     w->opacity = f->cur * OPAQUE;
308 #if 0
309     printf ("set_fade start %g step %g\n", f->cur, f->step);
310 #endif
311     determine_mode (dpy, w);
312     if (w->shadow)
313     {
314         XRenderFreePicture (dpy, w->shadow);
315         w->shadow = None;
316
317         if (w->extents != None)
318             XFixesDestroyRegion (dpy, w->extents);
319
320         /* rebuild the shadow */
321         w->extents = win_extents (dpy, w);
322     }
323
324     /* fading windows need to be drawn, mark them as damaged.
325        when a window maps, if it tries to fade in but it already at the right
326        opacity (map/unmap/map fast) then it will never get drawn without this
327        until it repaints */
328     w->damaged = 1;
329 }
330
331 int
332 fade_timeout (void)
333 {
334     int now;
335     int delta;
336     if (!fades)
337         return -1;
338     now = get_time_in_milliseconds();
339     delta = fade_time - now;
340     if (delta < 0)
341         delta = 0;
342 /*    printf ("timeout %d\n", delta); */
343     return delta;
344 }
345
346 void
347 run_fades (Display *dpy)
348 {
349     int     now = get_time_in_milliseconds();
350     fade    *next = fades;
351     int     steps;
352     Bool    need_dequeue;
353
354 #if 0
355     printf ("run fades\n");
356 #endif
357     if (fade_time - now > 0)
358         return;
359     steps = 1 + (now - fade_time) / fade_delta;
360
361     while (next)
362     {
363         fade *f = next;
364         win *w = f->w;
365         next = f->next;
366         f->cur += f->step * steps;
367         if (f->cur >= 1)
368             f->cur = 1;
369         else if (f->cur < 0)
370             f->cur = 0;
371 #if 0
372         printf ("opacity now %g\n", f->cur);
373 #endif
374         w->opacity = f->cur * OPAQUE;
375         need_dequeue = False;
376         if (f->step > 0)
377         {
378             if (f->cur >= f->finish)
379             {
380                 w->opacity = f->finish*OPAQUE;
381                 need_dequeue = True;
382             }
383         }
384         else
385         {
386             if (f->cur <= f->finish)
387             {
388                 w->opacity = f->finish*OPAQUE;
389                 need_dequeue = True;
390             }
391         }
392         determine_mode (dpy, w);
393         if (w->shadow)
394         {
395             XRenderFreePicture (dpy, w->shadow);
396             w->shadow = None;
397
398             if (w->extents != None)
399                 XFixesDestroyRegion (dpy, w->extents);
400
401             /* rebuild the shadow */
402             w->extents = win_extents(dpy, w);
403         }
404         /* Must do this last as it might destroy f->w in callbacks */
405         if (need_dequeue)
406                 dequeue_fade (dpy, f);
407     }
408     fade_time = now + fade_delta;
409 }
410
411 static double
412 gaussian (double r, double x, double y)
413 {
414     return ((1 / (sqrt (2 * M_PI * r))) *
415             exp ((- (x * x + y * y)) / (2 * r * r)));
416 }
417
418
419 static conv *
420 make_gaussian_map (Display *dpy, double r)
421 {
422     conv            *c;
423     int             size = ((int) ceil ((r * 3)) + 1) & ~1;
424     int             center = size / 2;
425     int             x, y;
426     double          t;
427     double          g;
428     
429     c = malloc (sizeof (conv) + size * size * sizeof (double));
430     c->size = size;
431     c->data = (double *) (c + 1);
432     t = 0.0;
433     for (y = 0; y < size; y++)
434         for (x = 0; x < size; x++)
435         {
436             g = gaussian (r, (double) (x - center), (double) (y - center));
437             t += g;
438             c->data[y * size + x] = g;
439         }
440 /*    printf ("gaussian total %f\n", t); */
441     for (y = 0; y < size; y++)
442         for (x = 0; x < size; x++)
443         {
444             c->data[y*size + x] /= t;
445         }
446     return c;
447 }
448
449 /*
450  * A picture will help
451  *
452  *      -center   0                width  width+center
453  *  -center +-----+-------------------+-----+
454  *          |     |                   |     |
455  *          |     |                   |     |
456  *        0 +-----+-------------------+-----+
457  *          |     |                   |     |
458  *          |     |                   |     |
459  *          |     |                   |     |
460  *   height +-----+-------------------+-----+
461  *          |     |                   |     |
462  * height+  |     |                   |     |
463  *  center  +-----+-------------------+-----+
464  */
465  
466 static unsigned char
467 sum_gaussian (conv *map, double opacity, int x, int y, int width, int height)
468 {
469     int     fx, fy;
470     double  *g_data;
471     double  *g_line = map->data;
472     int     g_size = map->size;
473     int     center = g_size / 2;
474     int     fx_start, fx_end;
475     int     fy_start, fy_end;
476     double  v;
477     
478     /*
479      * Compute set of filter values which are "in range",
480      * that's the set with:
481      *  0 <= x + (fx-center) && x + (fx-center) < width &&
482      *  0 <= y + (fy-center) && y + (fy-center) < height
483      *
484      *  0 <= x + (fx - center)  x + fx - center < width
485      *  center - x <= fx        fx < width + center - x
486      */
487
488     fx_start = center - x;
489     if (fx_start < 0)
490         fx_start = 0;
491     fx_end = width + center - x;
492     if (fx_end > g_size)
493         fx_end = g_size;
494
495     fy_start = center - y;
496     if (fy_start < 0)
497         fy_start = 0;
498     fy_end = height + center - y;
499     if (fy_end > g_size)
500         fy_end = g_size;
501
502     g_line = g_line + fy_start * g_size + fx_start;
503     
504     v = 0;
505     for (fy = fy_start; fy < fy_end; fy++)
506     {
507         g_data = g_line;
508         g_line += g_size;
509         
510         for (fx = fx_start; fx < fx_end; fx++)
511             v += *g_data++;
512     }
513     if (v > 1)
514         v = 1;
515     
516     return ((unsigned char) (v * opacity * 255.0));
517 }
518
519 /* precompute shadow corners and sides to save time for large windows */
520 static void
521 presum_gaussian (conv *map)
522 {
523     int center = map->size/2;
524     int opacity, x, y;
525
526     Gsize = map->size;
527
528     if (shadowCorner)
529         free ((void *)shadowCorner);
530     if (shadowTop)
531         free ((void *)shadowTop);
532
533     shadowCorner = (unsigned char *)(malloc ((Gsize + 1) * (Gsize + 1) * 26));
534     shadowTop = (unsigned char *)(malloc ((Gsize + 1) * 26));
535     
536     for (x = 0; x <= Gsize; x++)
537     {
538         shadowTop[25 * (Gsize + 1) + x] = sum_gaussian (map, 1, x - center, center, Gsize * 2, Gsize * 2);
539         for(opacity = 0; opacity < 25; opacity++)
540             shadowTop[opacity * (Gsize + 1) + x] = shadowTop[25 * (Gsize + 1) + x] * opacity / 25;
541         for(y = 0; y <= x; y++)
542         {
543             shadowCorner[25 * (Gsize + 1) * (Gsize + 1) + y * (Gsize + 1) + x]
544                 = sum_gaussian (map, 1, x - center, y - center, Gsize * 2, Gsize * 2);
545             shadowCorner[25 * (Gsize + 1) * (Gsize + 1) + x * (Gsize + 1) + y]
546                 = shadowCorner[25 * (Gsize + 1) * (Gsize + 1) + y * (Gsize + 1) + x];
547             for(opacity = 0; opacity < 25; opacity++)
548                 shadowCorner[opacity * (Gsize + 1) * (Gsize + 1) + y * (Gsize + 1) + x]
549                     = shadowCorner[opacity * (Gsize + 1) * (Gsize + 1) + x * (Gsize + 1) + y]
550                     = shadowCorner[25 * (Gsize + 1) * (Gsize + 1) + y * (Gsize + 1) + x] * opacity / 25;
551         }
552     }
553 }
554
555 static XImage *
556 make_shadow (Display *dpy, double opacity, int width, int height)
557 {
558     XImage          *ximage;
559     unsigned char   *data;
560     int             gsize = gaussianMap->size;
561     int             ylimit, xlimit;
562     int             swidth = width + gsize;
563     int             sheight = height + gsize;
564     int             center = gsize / 2;
565     int             x, y;
566     unsigned char   d;
567     int             x_diff;
568     int             opacity_int = (int)(opacity * 25);
569     data = malloc (swidth * sheight * sizeof (unsigned char));
570     if (!data)
571         return 0;
572     ximage = XCreateImage (dpy,
573                            DefaultVisual(dpy, DefaultScreen(dpy)),
574                            8,
575                            ZPixmap,
576                            0,
577                            (char *) data,
578                            swidth, sheight, 8, swidth * sizeof (unsigned char));
579     if (!ximage)
580     {
581         free (data);
582         return 0;
583     }
584     /*
585      * Build the gaussian in sections
586      */
587
588     /*
589      * center (fill the complete data array)
590      */
591     if (Gsize > 0)
592         d = shadowTop[opacity_int * (Gsize + 1) + Gsize];
593     else
594         d = sum_gaussian (gaussianMap, opacity, center, center, width, height);
595     memset(data, d, sheight * swidth);
596     
597     /*
598      * corners
599      */
600     ylimit = gsize;
601     if (ylimit > sheight / 2)
602         ylimit = (sheight + 1) / 2;
603     xlimit = gsize;
604     if (xlimit > swidth / 2)
605         xlimit = (swidth + 1) / 2;
606
607     for (y = 0; y < ylimit; y++)
608         for (x = 0; x < xlimit; x++)
609         {
610             if (xlimit == Gsize && ylimit == Gsize)
611                 d = shadowCorner[opacity_int * (Gsize + 1) * (Gsize + 1) + y * (Gsize + 1) + x];
612             else
613                 d = sum_gaussian (gaussianMap, opacity, x - center, y - center, width, height);
614             data[y * swidth + x] = d;
615             data[(sheight - y - 1) * swidth + x] = d;
616             data[(sheight - y - 1) * swidth + (swidth - x - 1)] = d;
617             data[y * swidth + (swidth - x - 1)] = d;
618         }
619
620     /*
621      * top/bottom
622      */
623     x_diff = swidth - (gsize * 2);
624     if (x_diff > 0 && ylimit > 0)
625     {
626         for (y = 0; y < ylimit; y++)
627         {
628             if (ylimit == Gsize)
629                 d = shadowTop[opacity_int * (Gsize + 1) + y];
630             else
631                 d = sum_gaussian (gaussianMap, opacity, center, y - center, width, height);
632             memset (&data[y * swidth + gsize], d, x_diff);
633             memset (&data[(sheight - y - 1) * swidth + gsize], d, x_diff);
634         }
635     }
636
637     /*
638      * sides
639      */
640     
641     for (x = 0; x < xlimit; x++)
642     {
643         if (xlimit == Gsize)
644             d = shadowTop[opacity_int * (Gsize + 1) + x];
645         else
646             d = sum_gaussian (gaussianMap, opacity, x - center, center, width, height);
647         for (y = gsize; y < sheight - gsize; y++)
648         {
649             data[y * swidth + x] = d;
650             data[y * swidth + (swidth - x - 1)] = d;
651         }
652     }
653
654     return ximage;
655 }
656
657 static Picture
658 shadow_picture (Display *dpy, double opacity, Picture alpha_pict, int width, int height, int *wp, int *hp)
659 {
660     XImage  *shadowImage;
661     Pixmap  shadowPixmap;
662     Picture shadowPicture;
663     GC      gc;
664     
665     shadowImage = make_shadow (dpy, opacity, width, height);
666     if (!shadowImage)
667         return None;
668     shadowPixmap = XCreatePixmap (dpy, root, 
669                                   shadowImage->width,
670                                   shadowImage->height,
671                                   8);
672     if (!shadowPixmap)
673     {
674         XDestroyImage (shadowImage);
675         return None;
676     }
677
678     shadowPicture = XRenderCreatePicture (dpy, shadowPixmap,
679                                           XRenderFindStandardFormat (dpy, PictStandardA8),
680                                           0, 0);
681     if (!shadowPicture)
682     {
683         XDestroyImage (shadowImage);
684         XFreePixmap (dpy, shadowPixmap);
685         return None;
686     }
687
688     gc = XCreateGC (dpy, shadowPixmap, 0, 0);
689     if (!gc)
690     {
691         XDestroyImage (shadowImage);
692         XFreePixmap (dpy, shadowPixmap);
693         XRenderFreePicture (dpy, shadowPicture);
694         return None;
695     }
696     
697     XPutImage (dpy, shadowPixmap, gc, shadowImage, 0, 0, 0, 0, 
698                shadowImage->width,
699                shadowImage->height);
700     *wp = shadowImage->width;
701     *hp = shadowImage->height;
702     XFreeGC (dpy, gc);
703     XDestroyImage (shadowImage);
704     XFreePixmap (dpy, shadowPixmap);
705     return shadowPicture;
706 }
707
708 Picture
709 solid_picture (Display *dpy, Bool argb, double a, double r, double g, double b)
710 {
711     Pixmap                      pixmap;
712     Picture                     picture;
713     XRenderPictureAttributes    pa;
714     XRenderColor                c;
715
716     pixmap = XCreatePixmap (dpy, root, 1, 1, argb ? 32 : 8);
717     if (!pixmap)
718         return None;
719
720     pa.repeat = True;
721     picture = XRenderCreatePicture (dpy, pixmap,
722                                     XRenderFindStandardFormat (dpy, argb ? PictStandardARGB32 : PictStandardA8),
723                                     CPRepeat,
724                                     &pa);
725     if (!picture)
726     {
727         XFreePixmap (dpy, pixmap);
728         return None;
729     }
730
731     c.alpha = a * 0xffff;
732     c.red = r * 0xffff;
733     c.green = g * 0xffff;
734     c.blue = b * 0xffff;
735     XRenderFillRectangle (dpy, PictOpSrc, picture, &c, 0, 0, 1, 1);
736     XFreePixmap (dpy, pixmap);
737     return picture;
738 }
739
740 void
741 discard_ignore (Display *dpy, unsigned long sequence)
742 {
743     while (ignore_head)
744     {
745         if ((long) (sequence - ignore_head->sequence) > 0)
746         {
747             ignore  *next = ignore_head->next;
748             free (ignore_head);
749             ignore_head = next;
750             if (!ignore_head)
751                 ignore_tail = &ignore_head;
752         }
753         else
754             break;
755     }
756 }
757
758 void
759 set_ignore (Display *dpy, unsigned long sequence)
760 {
761     ignore  *i = malloc (sizeof (ignore));
762     if (!i)
763         return;
764     i->sequence = sequence;
765     i->next = 0;
766     *ignore_tail = i;
767     ignore_tail = &i->next;
768 }
769
770 int
771 should_ignore (Display *dpy, unsigned long sequence)
772 {
773     discard_ignore (dpy, sequence);
774     return ignore_head && ignore_head->sequence == sequence;
775 }
776
777 static win *
778 find_win (Display *dpy, Window id)
779 {
780     win *w;
781
782     for (w = list; w; w = w->next)
783         if (w->id == id && !w->destroyed)
784             return w;
785     return 0;
786 }
787
788 static const char *backgroundProps[] = {
789     "_XROOTPMAP_ID",
790     "_XSETROOT_ID",
791     0,
792 };
793     
794 static Picture
795 root_tile (Display *dpy)
796 {
797     Picture         picture;
798     Atom            actual_type;
799     Pixmap          pixmap;
800     int             actual_format;
801     unsigned long   nitems;
802     unsigned long   bytes_after;
803     unsigned char   *prop;
804     Bool            fill;
805     XRenderPictureAttributes    pa;
806     int             p;
807
808     pixmap = None;
809     for (p = 0; backgroundProps[p]; p++)
810     {
811         if (XGetWindowProperty (dpy, root, XInternAtom (dpy, backgroundProps[p], False),
812                                 0, 4, False, AnyPropertyType,
813                                 &actual_type, &actual_format, &nitems, &bytes_after, &prop) == Success &&
814             actual_type == XInternAtom (dpy, "PIXMAP", False) && actual_format == 32 && nitems == 1)
815         {
816             memcpy (&pixmap, prop, 4);
817             XFree (prop);
818             fill = False;
819             break;
820         }
821     }
822     if (!pixmap)
823     {
824         pixmap = XCreatePixmap (dpy, root, 1, 1, DefaultDepth (dpy, scr));
825         fill = True;
826     }
827     pa.repeat = True;
828     picture = XRenderCreatePicture (dpy, pixmap,
829                                     XRenderFindVisualFormat (dpy,
830                                                              DefaultVisual (dpy, scr)),
831                                     CPRepeat, &pa);
832     if (fill)
833     {
834         XRenderColor    c;
835         
836         c.red = c.green = c.blue = 0x8080;
837         c.alpha = 0xffff;
838         XRenderFillRectangle (dpy, PictOpSrc, picture, &c, 
839                               0, 0, 1, 1);
840     }
841     return picture;
842 }
843
844 static void
845 paint_root (Display *dpy)
846 {
847     if (!rootTile)
848         rootTile = root_tile (dpy);
849     
850     XRenderComposite (dpy, PictOpSrc,
851                       rootTile, None, rootBuffer,
852                       0, 0, 0, 0, 0, 0, root_width, root_height);
853 }
854
855 static XserverRegion
856 win_extents (Display *dpy, win *w)
857 {
858     XRectangle      r;
859     
860     r.x = w->a.x;
861     r.y = w->a.y;
862     r.width = w->a.width + w->a.border_width * 2;
863     r.height = w->a.height + w->a.border_width * 2;
864     if (winTypeShadow[w->windowType])
865     {
866         if (compMode == CompServerShadows || w->mode != WINDOW_ARGB)
867         {
868             XRectangle  sr;
869
870             if (compMode == CompServerShadows)
871             {
872                 w->shadow_dx = 2;
873                 w->shadow_dy = 7;
874                 w->shadow_width = w->a.width;
875                 w->shadow_height = w->a.height;
876             }
877             else
878             {
879                 w->shadow_dx = shadowOffsetX;
880                 w->shadow_dy = shadowOffsetY;
881                 if (!w->shadow)
882                 {
883                     double      opacity = shadowOpacity;
884                     if (w->mode == WINDOW_TRANS)
885                         opacity = opacity * ((double)w->opacity)/((double)OPAQUE);
886                     w->shadow = shadow_picture (dpy, opacity, w->alphaPict,
887                                                 w->a.width + w->a.border_width * 2,
888                                                 w->a.height + w->a.border_width * 2,
889                                                 &w->shadow_width, &w->shadow_height);
890                 }
891             }
892             sr.x = w->a.x + w->shadow_dx;
893             sr.y = w->a.y + w->shadow_dy;
894             sr.width = w->shadow_width;
895             sr.height = w->shadow_height;
896             if (sr.x < r.x)
897             {
898                 r.width = (r.x + r.width) - sr.x;
899                 r.x = sr.x;
900             }
901             if (sr.y < r.y)
902             {
903                 r.height = (r.y + r.height) - sr.y;
904                 r.y = sr.y;
905             }
906             if (sr.x + sr.width > r.x + r.width)
907                 r.width = sr.x + sr.width - r.x;
908             if (sr.y + sr.height > r.y + r.height)
909                 r.height = sr.y + sr.height - r.y;
910         }
911     }
912     return XFixesCreateRegion (dpy, &r, 1);
913 }
914
915 static XserverRegion
916 border_size (Display *dpy, win *w)
917 {
918     XserverRegion   border;
919     /*
920      * if window doesn't exist anymore,  this will generate an error
921      * as well as not generate a region.  Perhaps a better XFixes
922      * architecture would be to have a request that copies instead
923      * of creates, that way you'd just end up with an empty region
924      * instead of an invalid XID.
925      */
926     set_ignore (dpy, NextRequest (dpy));
927     border = XFixesCreateRegionFromWindow (dpy, w->id, WindowRegionBounding);
928     /* translate this */
929     set_ignore (dpy, NextRequest (dpy));
930     XFixesTranslateRegion (dpy, border,
931                            w->a.x + w->a.border_width,
932                            w->a.y + w->a.border_width);
933     return border;
934 }
935
936 static void
937 paint_all (Display *dpy, XserverRegion region)
938 {
939     win *w;
940     win *t = 0;
941     
942     if (!region)
943     {
944         XRectangle  r;
945         r.x = 0;
946         r.y = 0;
947         r.width = root_width;
948         r.height = root_height;
949         region = XFixesCreateRegion (dpy, &r, 1);
950     }
951 #if MONITOR_REPAINT
952     rootBuffer = rootPicture;
953 #else
954     if (!rootBuffer)
955     {
956         Pixmap  rootPixmap = XCreatePixmap (dpy, root, root_width, root_height,
957                                             DefaultDepth (dpy, scr));
958         rootBuffer = XRenderCreatePicture (dpy, rootPixmap,
959                                            XRenderFindVisualFormat (dpy,
960                                                                     DefaultVisual (dpy, scr)),
961                                            0, 0);
962         XFreePixmap (dpy, rootPixmap);
963     }
964 #endif
965     XFixesSetPictureClipRegion (dpy, rootPicture, 0, 0, region);
966 #if MONITOR_REPAINT
967     XRenderComposite (dpy, PictOpSrc, blackPicture, None, rootPicture,
968                       0, 0, 0, 0, 0, 0, root_width, root_height);
969 #endif
970 #if DEBUG_REPAINT
971     printf ("paint:");
972 #endif
973     for (w = list; w; w = w->next)
974     {
975 #if CAN_DO_USABLE
976         if (!w->usable)
977             continue;
978 #endif
979         /* never painted, ignore it */
980         if (!w->damaged)
981             continue;
982         /* if invisible, ignore it */
983         if (w->a.x + w->a.width < 1 || w->a.y + w->a.height < 1
984             || w->a.x >= root_width || w->a.y >= root_height)
985             continue;
986         if (!w->picture)
987         {
988             XRenderPictureAttributes    pa;
989             XRenderPictFormat           *format;
990             Drawable                    draw = w->id;
991             
992 #if HAS_NAME_WINDOW_PIXMAP
993             if (hasNamePixmap && !w->pixmap) {
994                 set_ignore (dpy, NextRequest (dpy));
995                 w->pixmap = XCompositeNameWindowPixmap (dpy, w->id);
996             }
997             if (w->pixmap)
998                 draw = w->pixmap;
999 #endif
1000             format = XRenderFindVisualFormat (dpy, w->a.visual);
1001             pa.subwindow_mode = IncludeInferiors;
1002             w->picture = XRenderCreatePicture (dpy, draw,
1003                                                format,
1004                                                CPSubwindowMode,
1005                                                &pa);
1006         }
1007 #if DEBUG_REPAINT
1008         printf (" 0x%x", w->id);
1009 #endif
1010         if (clipChanged)
1011         {
1012             if (w->borderSize)
1013             {
1014                 set_ignore (dpy, NextRequest (dpy));
1015                 XFixesDestroyRegion (dpy, w->borderSize);
1016                 w->borderSize = None;
1017             }
1018             if (w->extents)
1019             {
1020                 XFixesDestroyRegion (dpy, w->extents);
1021                 w->extents = None;
1022             }
1023             if (w->borderClip)
1024             {
1025                 XFixesDestroyRegion (dpy, w->borderClip);
1026                 w->borderClip = None;
1027             }
1028         }
1029         if (!w->borderSize)
1030             w->borderSize = border_size (dpy, w);
1031         if (!w->extents)
1032             w->extents = win_extents (dpy, w);
1033         if (w->mode == WINDOW_SOLID)
1034         {
1035             int x, y, wid, hei;
1036 #if HAS_NAME_WINDOW_PIXMAP
1037             x = w->a.x;
1038             y = w->a.y;
1039             wid = w->a.width + w->a.border_width * 2;
1040             hei = w->a.height + w->a.border_width * 2;
1041 #else
1042             x = w->a.x + w->a.border_width;
1043             y = w->a.y + w->a.border_width;
1044             wid = w->a.width;
1045             hei = w->a.height;
1046 #endif
1047             XFixesSetPictureClipRegion (dpy, rootBuffer, 0, 0, region);
1048             set_ignore (dpy, NextRequest (dpy));
1049             XFixesSubtractRegion (dpy, region, region, w->borderSize);
1050             set_ignore (dpy, NextRequest (dpy));
1051             XRenderComposite (dpy, PictOpSrc, w->picture, None, rootBuffer,
1052                               0, 0, 0, 0, 
1053                               x, y, wid, hei);
1054         }
1055         if (!w->borderClip)
1056         {
1057             w->borderClip = XFixesCreateRegion (dpy, 0, 0);
1058             XFixesCopyRegion (dpy, w->borderClip, region);
1059         }
1060         w->prev_trans = t;
1061         t = w;
1062     }
1063 #if DEBUG_REPAINT
1064     printf ("\n");
1065     fflush (stdout);
1066 #endif
1067     XFixesSetPictureClipRegion (dpy, rootBuffer, 0, 0, region);
1068     paint_root (dpy);
1069     for (w = t; w; w = w->prev_trans)
1070     {
1071         XFixesSetPictureClipRegion (dpy, rootBuffer, 0, 0, w->borderClip);
1072         if (winTypeShadow[w->windowType]) {
1073             switch (compMode) {
1074             case CompSimple:
1075                 break;
1076             case CompServerShadows:
1077                 set_ignore (dpy, NextRequest (dpy));
1078                 if (w->opacity != OPAQUE && !w->shadowPict)
1079                     w->shadowPict = solid_picture (dpy, True,
1080                                                    (double) w->opacity / OPAQUE * 0.3,
1081                                                    0, 0, 0);
1082                 XRenderComposite (dpy, PictOpOver,
1083                                   w->shadowPict ? w->shadowPict : transBlackPicture,
1084                                   w->picture, rootBuffer,
1085                                   0, 0, 0, 0,
1086                                   w->a.x + w->shadow_dx,
1087                                   w->a.y + w->shadow_dy,
1088                                   w->shadow_width, w->shadow_height);
1089                 break;
1090             case CompClientShadows:
1091                 XRenderComposite (dpy, PictOpOver, blackPicture, w->shadow, rootBuffer,
1092                                   0, 0, 0, 0,
1093                                   w->a.x + w->shadow_dx,
1094                                   w->a.y + w->shadow_dy,
1095                                   w->shadow_width, w->shadow_height);
1096                 break;
1097             }
1098         }
1099         if (w->opacity != OPAQUE && !w->alphaPict)
1100             w->alphaPict = solid_picture (dpy, False, 
1101                                           (double) w->opacity / OPAQUE, 0, 0, 0);
1102         if (w->mode == WINDOW_TRANS)
1103         {
1104             int x, y, wid, hei;
1105 #if HAS_NAME_WINDOW_PIXMAP
1106             x = w->a.x;
1107             y = w->a.y;
1108             wid = w->a.width + w->a.border_width * 2;
1109             hei = w->a.height + w->a.border_width * 2;
1110 #else
1111             x = w->a.x + w->a.border_width;
1112             y = w->a.y + w->a.border_width;
1113             wid = w->a.width;
1114             hei = w->a.height;
1115 #endif
1116             set_ignore (dpy, NextRequest (dpy));
1117             XRenderComposite (dpy, PictOpOver, w->picture, w->alphaPict, rootBuffer,
1118                               0, 0, 0, 0, 
1119                               x, y, wid, hei);
1120         }
1121         else if (w->mode == WINDOW_ARGB)
1122         {
1123             int x, y, wid, hei;
1124 #if HAS_NAME_WINDOW_PIXMAP
1125             x = w->a.x;
1126             y = w->a.y;
1127             wid = w->a.width + w->a.border_width * 2;
1128             hei = w->a.height + w->a.border_width * 2;
1129 #else
1130             x = w->a.x + w->a.border_width;
1131             y = w->a.y + w->a.border_width;
1132             wid = w->a.width;
1133             hei = w->a.height;
1134 #endif
1135             set_ignore (dpy, NextRequest (dpy));
1136             XRenderComposite (dpy, PictOpOver, w->picture, w->alphaPict, rootBuffer,
1137                               0, 0, 0, 0, 
1138                               x, y, wid, hei);
1139         }
1140         XFixesDestroyRegion (dpy, w->borderClip);
1141         w->borderClip = None;
1142     }
1143     XFixesDestroyRegion (dpy, region);
1144     if (rootBuffer != rootPicture)
1145     {
1146         XFixesSetPictureClipRegion (dpy, rootBuffer, 0, 0, None);
1147         XRenderComposite (dpy, PictOpSrc, rootBuffer, None, rootPicture,
1148                           0, 0, 0, 0, 0, 0, root_width, root_height);
1149     }
1150 }
1151
1152 static void
1153 add_damage (Display *dpy, XserverRegion damage)
1154 {
1155     if (allDamage)
1156     {
1157         XFixesUnionRegion (dpy, allDamage, allDamage, damage);
1158         XFixesDestroyRegion (dpy, damage);
1159     }
1160     else
1161         allDamage = damage;
1162 }
1163
1164 static void
1165 repair_win (Display *dpy, win *w)
1166 {
1167     XserverRegion   parts;
1168
1169     if (!w->damaged)
1170     {
1171         parts = win_extents (dpy, w);
1172         set_ignore (dpy, NextRequest (dpy));
1173         XDamageSubtract (dpy, w->damage, None, None);
1174     }
1175     else
1176     {
1177         XserverRegion   o;
1178         parts = XFixesCreateRegion (dpy, 0, 0);
1179         set_ignore (dpy, NextRequest (dpy));
1180         XDamageSubtract (dpy, w->damage, None, parts);
1181         XFixesTranslateRegion (dpy, parts,
1182                                w->a.x + w->a.border_width,
1183                                w->a.y + w->a.border_width);
1184         if (compMode == CompServerShadows)
1185         {
1186             o = XFixesCreateRegion (dpy, 0, 0);
1187             XFixesCopyRegion (dpy, o, parts);
1188             XFixesTranslateRegion (dpy, o, w->shadow_dx, w->shadow_dy);
1189             XFixesUnionRegion (dpy, parts, parts, o);
1190             XFixesDestroyRegion (dpy, o);
1191         }
1192     }
1193     add_damage (dpy, parts);
1194     w->damaged = 1;
1195 }
1196
1197 static const char*
1198 wintype_name(wintype type)
1199 {
1200     const char *t;
1201     switch (type) {
1202     case WINTYPE_DESKTOP: t = "desktop"; break;
1203     case WINTYPE_DOCK:    t = "dock"; break;
1204     case WINTYPE_TOOLBAR: t = "toolbar"; break;
1205     case WINTYPE_MENU:    t = "menu"; break;
1206     case WINTYPE_UTILITY: t = "utility"; break;
1207     case WINTYPE_SPLASH:  t = "slash"; break;
1208     case WINTYPE_DIALOG:  t = "dialog"; break;
1209     case WINTYPE_NORMAL:  t = "normal"; break;
1210     case WINTYPE_DROPDOWN_MENU: t = "dropdown"; break;
1211     case WINTYPE_POPUP_MENU: t = "popup"; break;
1212     case WINTYPE_TOOLTIP: t = "tooltip"; break;
1213     case WINTYPE_NOTIFY:  t = "notification"; break;
1214     case WINTYPE_COMBO:   t = "combo"; break;
1215     case WINTYPE_DND:     t = "dnd"; break;
1216     default:              t = "unknown"; break;
1217     }
1218     return t;
1219 }
1220
1221 static wintype
1222 get_wintype_prop(Display * dpy, Window w)
1223 {
1224     Atom actual;
1225     wintype ret;
1226     int format;
1227     unsigned long n, left, off;
1228     unsigned char *data;
1229
1230     ret = (wintype)-1;
1231     off = 0;
1232
1233     do {
1234         set_ignore (dpy, NextRequest (dpy));
1235         int result = XGetWindowProperty (dpy, w, winTypeAtom, off, 1L, False,
1236                                          XA_ATOM, &actual, &format,
1237                                          &n, &left, &data);
1238
1239         if (result != Success)
1240             break;
1241         if (data != None)
1242         {
1243             int i;
1244
1245             for (i = 0; i < NUM_WINTYPES; ++i) {
1246                 Atom a;
1247                 memcpy (&a, data, sizeof (Atom));
1248                 if (a == winType[i]) {
1249                     /* known type */
1250                     ret = i;
1251                     break;
1252                 }
1253             }
1254
1255             XFree ( (void *) data);
1256         }
1257
1258         ++off;
1259     } while (left >= 4 && ret == (wintype)-1);
1260
1261     return ret;
1262 }
1263
1264 static wintype
1265 determine_wintype (Display *dpy, Window w, Window top)
1266 {
1267     Window       root_return, parent_return;
1268     Window      *children = NULL;
1269     unsigned int nchildren, i;
1270     wintype      type;
1271
1272     type = get_wintype_prop (dpy, w);
1273     if (type != (wintype)-1)
1274         return type;
1275
1276     set_ignore (dpy, NextRequest (dpy));
1277     if (!XQueryTree (dpy, w, &root_return, &parent_return, &children,
1278                             &nchildren))
1279     {
1280         /* XQueryTree failed. */
1281         if (children)
1282             XFree ((void *)children);
1283         return (wintype)-1;
1284     }
1285
1286     for (i = 0;i < nchildren;i++)
1287     {
1288         type = determine_wintype (dpy, children[i], top);
1289         if (type != (wintype)-1)
1290             return type;
1291     }
1292
1293     if (children)
1294         XFree ((void *)children);
1295
1296     if (w != top)
1297         return (wintype)-1;
1298     else
1299         return WINTYPE_NORMAL;
1300 }
1301
1302 static unsigned int
1303 get_opacity_prop (Display *dpy, win *w, unsigned int def);
1304
1305 static void
1306 configure_win (Display *dpy, XConfigureEvent *ce);
1307
1308 static void
1309 map_win (Display *dpy, Window id, unsigned long sequence, Bool fade)
1310 {
1311     win         *w = find_win (dpy, id);
1312
1313     if (!w)
1314         return;
1315
1316     w->a.map_state = IsViewable;
1317
1318     w->windowType = determine_wintype (dpy, w->id, w->id);
1319 #if 0
1320     printf("window 0x%x type %s\n", w->id, wintype_name(w->windowType));
1321 #endif
1322
1323     /* select before reading the property so that no property changes are lost */
1324     XSelectInput (dpy, id, PropertyChangeMask);
1325     w->opacity = get_opacity_prop (dpy, w, OPAQUE);
1326
1327     determine_mode (dpy, w);
1328
1329 #if CAN_DO_USABLE
1330     w->damage_bounds.x = w->damage_bounds.y = 0;
1331     w->damage_bounds.width = w->damage_bounds.height = 0;
1332 #endif
1333     w->damaged = 0;
1334
1335     if (fade && winTypeFade[w->windowType])
1336         set_fade (dpy, w, 0, get_opacity_percent (dpy, w), fade_in_step, 0, True, True);
1337
1338     /* if any configure events happened while the window was unmapped, then
1339        configure the window to its correct place */
1340     if (w->need_configure)
1341         configure_win (dpy, &w->queue_configure);
1342 }
1343
1344 static void
1345 finish_unmap_win (Display *dpy, win *w)
1346 {
1347     w->damaged = 0;
1348 #if CAN_DO_USABLE
1349     w->usable = False;
1350 #endif
1351     if (w->extents != None)
1352     {
1353         add_damage (dpy, w->extents);    /* destroys region */
1354         w->extents = None;
1355     }
1356     
1357 #if HAS_NAME_WINDOW_PIXMAP
1358     if (w->pixmap)
1359     {
1360         XFreePixmap (dpy, w->pixmap);
1361         w->pixmap = None;
1362     }
1363 #endif
1364
1365     if (w->picture)
1366     {
1367         set_ignore (dpy, NextRequest (dpy));
1368         XRenderFreePicture (dpy, w->picture);
1369         w->picture = None;
1370     }
1371
1372     if (w->borderSize)
1373     {
1374         set_ignore (dpy, NextRequest (dpy));
1375         XFixesDestroyRegion (dpy, w->borderSize);
1376         w->borderSize = None;
1377     }
1378     if (w->shadow)
1379     {
1380         XRenderFreePicture (dpy, w->shadow);
1381         w->shadow = None;
1382     }
1383     if (w->borderClip)
1384     {
1385         XFixesDestroyRegion (dpy, w->borderClip);
1386         w->borderClip = None;
1387     }
1388
1389     clipChanged = True;
1390 }
1391
1392 #if HAS_NAME_WINDOW_PIXMAP
1393 static void
1394 unmap_callback (Display *dpy, win *w)
1395 {
1396     finish_unmap_win (dpy, w);
1397 }
1398 #endif
1399
1400 static void
1401 unmap_win (Display *dpy, Window id, Bool fade)
1402 {
1403     win *w = find_win (dpy, id);
1404     if (!w)
1405         return;
1406     w->a.map_state = IsUnmapped;
1407
1408     /* don't care about properties anymore */
1409     set_ignore (dpy, NextRequest (dpy));
1410     XSelectInput(dpy, w->id, 0);
1411
1412 #if HAS_NAME_WINDOW_PIXMAP
1413     if (w->pixmap && fade && winTypeFade[w->windowType])
1414         set_fade (dpy, w, w->opacity*1.0/OPAQUE, 0.0, fade_out_step, unmap_callback, False, True);
1415     else
1416 #endif
1417         finish_unmap_win (dpy, w);
1418 }
1419
1420 /* Get the opacity prop from window
1421    not found: default
1422    otherwise the value
1423  */
1424 static unsigned int
1425 get_opacity_prop(Display *dpy, win *w, unsigned int def)
1426 {
1427     Atom actual;
1428     int format;
1429     unsigned long n, left;
1430
1431     unsigned char *data;
1432     int result = XGetWindowProperty(dpy, w->id, opacityAtom, 0L, 1L, False, 
1433                        XA_CARDINAL, &actual, &format, 
1434                                     &n, &left, &data);
1435     if (result == Success && data != NULL)
1436     {
1437         unsigned int i;
1438         memcpy (&i, data, sizeof (unsigned int));
1439         XFree( (void *) data);
1440         return i;
1441     }
1442     return def;
1443 }
1444
1445 /* Get the opacity property from the window in a percent format
1446    not found: default
1447    otherwise: the value
1448 */
1449 static double
1450 get_opacity_percent(Display *dpy, win *w)
1451 {
1452     double def = winTypeOpacity[w->windowType];
1453     unsigned int opacity = get_opacity_prop (dpy, w, (unsigned int)(OPAQUE*def));
1454
1455     return opacity*1.0/OPAQUE;
1456 }
1457
1458 static void
1459 determine_mode(Display *dpy, win *w)
1460 {
1461     int mode;
1462     XRenderPictFormat *format;
1463
1464     /* if trans prop == -1 fall back on  previous tests*/
1465
1466     if (w->alphaPict)
1467     {
1468         XRenderFreePicture (dpy, w->alphaPict);
1469         w->alphaPict = None;
1470     }
1471     if (w->shadowPict)
1472     {
1473         XRenderFreePicture (dpy, w->shadowPict);
1474         w->shadowPict = None;
1475     }
1476
1477     if (w->a.class == InputOnly)
1478     {
1479         format = 0;
1480     }
1481     else
1482     {
1483         format = XRenderFindVisualFormat (dpy, w->a.visual);
1484     }
1485
1486     if (format && format->type == PictTypeDirect && format->direct.alphaMask)
1487     {
1488         mode = WINDOW_ARGB;
1489     }
1490     else if (w->opacity != OPAQUE)
1491     {
1492         mode = WINDOW_TRANS;
1493     }
1494     else
1495     {
1496         mode = WINDOW_SOLID;
1497     }
1498     w->mode = mode;
1499     if (w->extents)
1500     {
1501         XserverRegion damage;
1502         damage = XFixesCreateRegion (dpy, 0, 0);
1503         XFixesCopyRegion (dpy, damage, w->extents);
1504         add_damage (dpy, damage);
1505     }
1506 }
1507
1508 static void
1509 add_win (Display *dpy, Window id, Window prev)
1510 {
1511     win                         *new = malloc (sizeof (win));
1512     win                         **p;
1513     
1514     if (!new)
1515         return;
1516     if (prev)
1517     {
1518         for (p = &list; *p; p = &(*p)->next)
1519             if ((*p)->id == prev && !(*p)->destroyed)
1520                 break;
1521     }
1522     else
1523         p = &list;
1524     new->id = id;
1525     set_ignore (dpy, NextRequest (dpy));
1526     if (!XGetWindowAttributes (dpy, id, &new->a))
1527     {
1528         free (new);
1529         return;
1530     }
1531     new->damaged = 0;
1532 #if CAN_DO_USABLE
1533     new->usable = False;
1534 #endif
1535 #if HAS_NAME_WINDOW_PIXMAP
1536     new->pixmap = None;
1537 #endif
1538     new->picture = None;
1539     if (new->a.class == InputOnly)
1540     {
1541         new->damage_sequence = 0;
1542         new->damage = None;
1543     }
1544     else
1545     {
1546         new->damage_sequence = NextRequest (dpy);
1547         set_ignore (dpy, NextRequest (dpy));
1548         new->damage = XDamageCreate (dpy, id, XDamageReportNonEmpty);
1549     }
1550     new->alphaPict = None;
1551     new->shadowPict = None;
1552     new->borderSize = None;
1553     new->extents = None;
1554     new->shadow = None;
1555     new->shadow_dx = 0;
1556     new->shadow_dy = 0;
1557     new->shadow_width = 0;
1558     new->shadow_height = 0;
1559     new->opacity = OPAQUE;
1560     new->destroyed = False;
1561     new->need_configure = False;
1562
1563     new->borderClip = None;
1564     new->prev_trans = 0;
1565
1566     new->next = *p;
1567     *p = new;
1568     if (new->a.map_state == IsViewable)
1569         map_win (dpy, id, new->damage_sequence - 1, True);
1570 }
1571
1572 void
1573 restack_win (Display *dpy, win *w, Window new_above)
1574 {
1575     Window  old_above;
1576     
1577     if (w->next)
1578         old_above = w->next->id;
1579     else
1580         old_above = None;
1581     if (old_above != new_above)
1582     {
1583         win **prev;
1584
1585         /* unhook */
1586         for (prev = &list; *prev; prev = &(*prev)->next)
1587             if ((*prev) == w)
1588                 break;
1589         *prev = w->next;
1590         
1591         /* rehook */
1592         for (prev = &list; *prev; prev = &(*prev)->next)
1593         {
1594             if ((*prev)->id == new_above && !(*prev)->destroyed)
1595                 break;
1596         }
1597         w->next = *prev;
1598         *prev = w;
1599     }
1600 }
1601
1602 static void
1603 configure_win (Display *dpy, XConfigureEvent *ce)
1604 {
1605     win             *w = find_win (dpy, ce->window);
1606     XserverRegion   damage = None;
1607     
1608     if (!w)
1609     {
1610         if (ce->window == root)
1611         {
1612             if (rootBuffer)
1613             {
1614                 XRenderFreePicture (dpy, rootBuffer);
1615                 rootBuffer = None;
1616             }
1617             root_width = ce->width;
1618             root_height = ce->height;
1619         }
1620         return;
1621     }
1622
1623     if (w->a.map_state == IsUnmapped) {
1624         /* save the configure event for when the window maps */
1625         w->need_configure = True;
1626         w->queue_configure = *ce;
1627     }
1628     else {
1629         w->need_configure = False;
1630
1631 #if CAN_DO_USABLE
1632         if (w->usable)
1633 #endif
1634         {
1635             damage = XFixesCreateRegion (dpy, 0, 0);
1636             if (w->extents != None)
1637                 XFixesCopyRegion (dpy, damage, w->extents);
1638         }
1639
1640         w->a.x = ce->x;
1641         w->a.y = ce->y;
1642         if (w->a.width != ce->width || w->a.height != ce->height)
1643         {
1644 #if HAS_NAME_WINDOW_PIXMAP
1645             if (w->pixmap)
1646             {
1647                 XFreePixmap (dpy, w->pixmap);
1648                 w->pixmap = None;
1649                 if (w->picture)
1650                 {
1651                     XRenderFreePicture (dpy, w->picture);
1652                     w->picture = None;
1653                 }
1654             }
1655 #endif
1656             if (w->shadow)
1657             {
1658                 XRenderFreePicture (dpy, w->shadow);
1659                 w->shadow = None;
1660             }
1661         }
1662         w->a.width = ce->width;
1663         w->a.height = ce->height;
1664         w->a.border_width = ce->border_width;
1665         if (w->a.map_state != IsUnmapped && damage)
1666         {
1667             XserverRegion       extents = win_extents (dpy, w);
1668             XFixesUnionRegion (dpy, damage, damage, extents);
1669             XFixesDestroyRegion (dpy, extents);
1670             add_damage (dpy, damage);
1671         }
1672
1673         clipChanged = True;
1674     }
1675
1676     w->a.override_redirect = ce->override_redirect;
1677     restack_win (dpy, w, ce->above);
1678 }
1679
1680 static void
1681 circulate_win (Display *dpy, XCirculateEvent *ce)
1682 {
1683     win     *w = find_win (dpy, ce->window);
1684     Window  new_above;
1685
1686     if (!w)
1687         return;
1688
1689     if (ce->place == PlaceOnTop)
1690         new_above = list->id;
1691     else
1692         new_above = None;
1693     restack_win (dpy, w, new_above);
1694     clipChanged = True;
1695 }
1696
1697 static void
1698 finish_destroy_win (Display *dpy, Window id)
1699 {
1700     win **prev, *w;
1701
1702     for (prev = &list; (w = *prev); prev = &w->next)
1703         if (w->id == id && w->destroyed)
1704         {
1705             finish_unmap_win (dpy, w);
1706             *prev = w->next;
1707             if (w->alphaPict)
1708             {
1709                 XRenderFreePicture (dpy, w->alphaPict);
1710                 w->alphaPict = None;
1711             }
1712             if (w->shadowPict)
1713             {
1714                 XRenderFreePicture (dpy, w->shadowPict);
1715                 w->shadowPict = None;
1716             }
1717             if (w->damage != None)
1718             {
1719                 set_ignore (dpy, NextRequest (dpy));
1720                 XDamageDestroy (dpy, w->damage);
1721                 w->damage = None;
1722             }
1723
1724             cleanup_fade (dpy, w);
1725             free (w);
1726             break;
1727         }
1728 }
1729
1730 #if HAS_NAME_WINDOW_PIXMAP
1731 static void
1732 destroy_callback (Display *dpy, win *w)
1733 {
1734     finish_destroy_win (dpy, w->id);
1735 }
1736 #endif
1737
1738 static void
1739 destroy_win (Display *dpy, Window id, Bool fade)
1740 {
1741     win *w = find_win (dpy, id);
1742
1743     if (w) w->destroyed = True;
1744
1745 #if HAS_NAME_WINDOW_PIXMAP
1746     if (w && w->pixmap && fade && winTypeFade[w->windowType])
1747         set_fade (dpy, w, w->opacity*1.0/OPAQUE, 0.0, fade_out_step,
1748                   destroy_callback, False, True);
1749     else
1750 #endif
1751     {
1752         finish_destroy_win (dpy, id);
1753     }
1754 }
1755
1756 /*
1757 static void
1758 dump_win (win *w)
1759 {
1760     printf ("\t%08lx: %d x %d + %d + %d (%d)\n", w->id,
1761             w->a.width, w->a.height, w->a.x, w->a.y, w->a.border_width);
1762 }
1763
1764
1765 static void
1766 dump_wins (void)
1767 {
1768     win *w;
1769
1770     printf ("windows:\n");
1771     for (w = list; w; w = w->next)
1772         dump_win (w);
1773 }
1774 */
1775
1776 static void
1777 damage_win (Display *dpy, XDamageNotifyEvent *de)
1778 {
1779     win *w = find_win (dpy, de->drawable);
1780
1781     if (!w)
1782         return;
1783 #if CAN_DO_USABLE
1784     if (!w->usable)
1785     {
1786         if (w->damage_bounds.width == 0 || w->damage_bounds.height == 0)
1787         {
1788             w->damage_bounds = de->area;
1789         }
1790         else
1791         {
1792             if (de->area.x < w->damage_bounds.x)
1793             {
1794                 w->damage_bounds.width += (w->damage_bounds.x - de->area.x);
1795                 w->damage_bounds.x = de->area.x;
1796             }
1797             if (de->area.y < w->damage_bounds.y)
1798             {
1799                 w->damage_bounds.height += (w->damage_bounds.y - de->area.y);
1800                 w->damage_bounds.y = de->area.y;
1801             }
1802             if (de->area.x + de->area.width > w->damage_bounds.x + w->damage_bounds.width)
1803                 w->damage_bounds.width = de->area.x + de->area.width - w->damage_bounds.x;
1804             if (de->area.y + de->area.height > w->damage_bounds.y + w->damage_bounds.height)
1805                 w->damage_bounds.height = de->area.y + de->area.height - w->damage_bounds.y;
1806         }
1807 #if 0
1808         printf ("unusable damage %d, %d: %d x %d bounds %d, %d: %d x %d\n",
1809                 de->area.x,
1810                 de->area.y,
1811                 de->area.width,
1812                 de->area.height,
1813                 w->damage_bounds.x,
1814                 w->damage_bounds.y,
1815                 w->damage_bounds.width,
1816                 w->damage_bounds.height);
1817 #endif
1818         if (w->damage_bounds.x <= 0 && 
1819             w->damage_bounds.y <= 0 &&
1820             w->a.width <= w->damage_bounds.x + w->damage_bounds.width &&
1821             w->a.height <= w->damage_bounds.y + w->damage_bounds.height)
1822         {
1823             clipChanged = True;
1824             if (winTypeFade[w->windowType])
1825                 set_fade (dpy, w, 0, get_opacity_percent (dpy, w), fade_in_step, 0, True, True);
1826             w->usable = True;
1827         }
1828     }
1829     if (w->usable)
1830 #endif
1831         repair_win (dpy, w);
1832 }
1833
1834 static int
1835 error (Display *dpy, XErrorEvent *ev)
1836 {
1837     int     o;
1838     const char    *name = 0;
1839     
1840     if (should_ignore (dpy, ev->serial))
1841         return 0;
1842     
1843     if (ev->request_code == composite_opcode &&
1844         ev->minor_code == X_CompositeRedirectSubwindows)
1845     {
1846         fprintf (stderr, "Another composite manager is already running\n");
1847         exit (1);
1848     }
1849     
1850     o = ev->error_code - xfixes_error;
1851     switch (o) {
1852     case BadRegion: name = "BadRegion"; break;
1853     default: break;
1854     }
1855     o = ev->error_code - damage_error;
1856     switch (o) {
1857     case BadDamage: name = "BadDamage"; break;
1858     default: break;
1859     }
1860     o = ev->error_code - render_error;
1861     switch (o) {
1862     case BadPictFormat: name ="BadPictFormat"; break;
1863     case BadPicture: name ="BadPicture"; break;
1864     case BadPictOp: name ="BadPictOp"; break;
1865     case BadGlyphSet: name ="BadGlyphSet"; break;
1866     case BadGlyph: name ="BadGlyph"; break;
1867     default: break;
1868     }
1869         
1870     printf ("error %d request %d minor %d serial %lu\n",
1871             ev->error_code, ev->request_code, ev->minor_code, ev->serial);
1872
1873 /*    abort ();     this is just annoying to most people */
1874     return 0;
1875 }
1876
1877 static void
1878 expose_root (Display *dpy, Window root, XRectangle *rects, int nrects)
1879 {
1880     XserverRegion  region = XFixesCreateRegion (dpy, rects, nrects);
1881     
1882     add_damage (dpy, region);
1883 }
1884
1885 #if DEBUG_EVENTS
1886 static int
1887 ev_serial (XEvent *ev)
1888 {
1889     if (ev->type & 0x7f != KeymapNotify)
1890         return ev->xany.serial;
1891     return NextRequest (ev->xany.display);
1892 }
1893
1894 static char *
1895 ev_name (XEvent *ev)
1896 {
1897     static char buf[128];
1898     switch (ev->type & 0x7f) {
1899     case Expose:
1900         return "Expose";
1901     case MapNotify:
1902         return "Map";
1903     case UnmapNotify:
1904         return "Unmap";
1905     case ReparentNotify:
1906         return "Reparent";
1907     case CirculateNotify:
1908         return "Circulate";
1909     default:
1910         if (ev->type == damage_event + XDamageNotify)
1911             return "Damage";
1912         sprintf (buf, "Event %d", ev->type);
1913         return buf;
1914     }
1915 }
1916
1917 static Window
1918 ev_window (XEvent *ev)
1919 {
1920     switch (ev->type) {
1921     case Expose:
1922         return ev->xexpose.window;
1923     case MapNotify:
1924         return ev->xmap.window;
1925     case UnmapNotify:
1926         return ev->xunmap.window;
1927     case ReparentNotify:
1928         return ev->xreparent.window;
1929     case CirculateNotify:
1930         return ev->xcirculate.window;
1931     default:
1932         if (ev->type == damage_event + XDamageNotify)
1933             return ((XDamageNotifyEvent *) ev)->drawable;
1934         return 0;
1935     }
1936 }
1937 #endif
1938
1939 void
1940 usage (char *program)
1941 {
1942     fprintf (stderr, "%s v1.1.3\n", program);
1943     fprintf (stderr, "usage: %s [options]\n", program);
1944     fprintf (stderr, "Options\n");
1945     fprintf (stderr, "   -d display\n      Specifies which display should be managed.\n");
1946     fprintf (stderr, "   -r radius\n      Specifies the blur radius for client-side shadows. (default 12)\n");
1947     fprintf (stderr, "   -o opacity\n      Specifies the translucency for client-side shadows. (default .75)\n");
1948     fprintf (stderr, "   -l left-offset\n      Specifies the left offset for client-side shadows. (default -15)\n");
1949     fprintf (stderr, "   -t top-offset\n      Specifies the top offset for clinet-side shadows. (default -15)\n");
1950     fprintf (stderr, "   -I fade-in-step\n      Specifies the opacity change between steps while fading in. (default 0.028)\n");
1951     fprintf (stderr, "   -O fade-out-step\n      Specifies the opacity change between steps while fading out. (default 0.03)\n");
1952     fprintf (stderr, "   -D fade-delta-time\n      Specifies the time between steps in a fade in milliseconds. (default 10)\n");
1953     fprintf (stderr, "   -m opacity\n      Specifies the opacity for menus. (default 1.0)\n");
1954     fprintf (stderr, "   -a\n      Use automatic server-side compositing. Faster, but no special effects.\n");
1955     fprintf (stderr, "   -c\n      Draw client-side shadows with fuzzy edges.\n");
1956     fprintf (stderr, "   -C\n      Avoid drawing shadows on dock/panel windows.\n");
1957     fprintf (stderr, "   -f\n      Fade windows in/out when opening/closing.\n");
1958     fprintf (stderr, "   -F\n      Fade windows during opacity changes.\n");
1959     fprintf (stderr, "   -n\n      Normal client-side compositing with transparency support\n");
1960     fprintf (stderr, "   -s\n      Draw server-side shadows with sharp edges.\n");
1961     fprintf (stderr, "   -S\n      Enable synchronous operation (for debugging).\n");
1962     exit (1);
1963 }
1964
1965 static void
1966 register_cm (int scr)
1967 {
1968     Window w;
1969     Atom a;
1970     char *buf;
1971     int len, s;
1972
1973     if (scr < 0) return;
1974
1975     w = XCreateSimpleWindow (dpy, RootWindow (dpy, 0), 0, 0, 1, 1, 0, None,
1976                              None);
1977
1978     Xutf8SetWMProperties (dpy, w, "xcompmgr", "xcompmgr", NULL, 0, NULL, NULL,
1979                           NULL);
1980
1981     len = strlen(REGISTER_PROP) + 2;
1982     s = scr;
1983     while (s >= 10) {
1984         ++len;
1985         s /= 10;
1986     }
1987     buf = malloc(len);
1988     snprintf(buf, len, REGISTER_PROP"%d", scr);
1989
1990     a = XInternAtom (dpy, buf, False);
1991     free(buf);
1992
1993     XSetSelectionOwner (dpy, a, w, 0);
1994 }
1995
1996 int
1997 main (int argc, char **argv)
1998 {
1999     XEvent          ev;
2000     Window          root_return, parent_return;
2001     Window          *children;
2002     unsigned int    nchildren;
2003     int             i;
2004     XRenderPictureAttributes    pa;
2005     XRectangle      *expose_rects = 0;
2006     int             size_expose = 0;
2007     int             n_expose = 0;
2008     struct pollfd   ufd;
2009     int             p;
2010     int             composite_major, composite_minor;
2011     char            *display = 0;
2012     int             o;
2013     Bool            noDockShadow = False;
2014
2015     for (i = 0; i < NUM_WINTYPES; ++i) {
2016         winTypeFade[i] = False;
2017         winTypeShadow[i] = False;
2018         winTypeOpacity[i] = 1.0;
2019     }
2020
2021     /* don't bother to draw a shadow for the desktop */
2022     winTypeShadow[WINTYPE_DESKTOP] = False;
2023
2024     while ((o = getopt (argc, argv, "D:I:O:d:r:o:m:l:t:scnfFCaS")) != -1)
2025     {
2026         switch (o) {
2027         case 'd':
2028             display = optarg;
2029             break;
2030         case 'D':
2031             fade_delta = atoi (optarg);
2032             if (fade_delta < 1)
2033                 fade_delta = 10;
2034             break;
2035         case 'I':
2036             fade_in_step = atof (optarg);
2037             if (fade_in_step <= 0)
2038                 fade_in_step = 0.01;
2039             break;
2040         case 'O':
2041             fade_out_step = atof (optarg);
2042             if (fade_out_step <= 0)
2043                 fade_out_step = 0.01;
2044             break;
2045         case 's':
2046             compMode = CompServerShadows;
2047             for (i = 0; i < NUM_WINTYPES; ++i)
2048                 winTypeShadow[i] = True;
2049             break;
2050         case 'c':
2051             compMode = CompClientShadows;
2052             for (i = 0; i < NUM_WINTYPES; ++i)
2053                 winTypeShadow[i] = True;
2054             break;
2055         case 'C':
2056             noDockShadow = True;
2057             break;
2058         case 'n':
2059             compMode = CompSimple;
2060             for (i = 0; i < NUM_WINTYPES; ++i)
2061                 winTypeShadow[i] = False;
2062             break;
2063         case 'm':
2064             winTypeOpacity[WINTYPE_DROPDOWN_MENU] = atof (optarg);
2065             winTypeOpacity[WINTYPE_POPUP_MENU] = atof (optarg);
2066             break;
2067         case 'f':
2068             for (i = 0; i < NUM_WINTYPES; ++i)
2069                 winTypeFade[i] = True;
2070             break;
2071         case 'F':
2072             fadeTrans = True;
2073             break;
2074         case 'a':
2075             autoRedirect = True;
2076             break;
2077         case 'S':
2078             synchronize = True;
2079             break;
2080         case 'r':
2081             shadowRadius = atoi (optarg);
2082             break;
2083         case 'o':
2084             shadowOpacity = atof (optarg);
2085             break;
2086         case 'l':
2087             shadowOffsetX = atoi (optarg);
2088             break;
2089         case 't':
2090             shadowOffsetY = atoi (optarg);
2091             break;
2092         default:
2093             usage (argv[0]);
2094             break;
2095         }
2096     }
2097
2098     if (noDockShadow)
2099         winTypeShadow[WINTYPE_DOCK] = False;
2100     
2101     dpy = XOpenDisplay (display);
2102     if (!dpy)
2103     {
2104         fprintf (stderr, "Can't open display\n");
2105         exit (1);
2106     }
2107     XSetErrorHandler (error);
2108     if (synchronize)
2109         XSynchronize (dpy, 1);
2110     scr = DefaultScreen (dpy);
2111     root = RootWindow (dpy, scr);
2112
2113     if (!XRenderQueryExtension (dpy, &render_event, &render_error))
2114     {
2115         fprintf (stderr, "No render extension\n");
2116         exit (1);
2117     }
2118     if (!XQueryExtension (dpy, COMPOSITE_NAME, &composite_opcode,
2119                           &composite_event, &composite_error))
2120     {
2121         fprintf (stderr, "No composite extension\n");
2122         exit (1);
2123     }
2124     XCompositeQueryVersion (dpy, &composite_major, &composite_minor);
2125 #if HAS_NAME_WINDOW_PIXMAP
2126     if (composite_major > 0 || composite_minor >= 2)
2127         hasNamePixmap = True;
2128 #endif
2129
2130     if (!XDamageQueryExtension (dpy, &damage_event, &damage_error))
2131     {
2132         fprintf (stderr, "No damage extension\n");
2133         exit (1);
2134     }
2135     if (!XFixesQueryExtension (dpy, &xfixes_event, &xfixes_error))
2136     {
2137         fprintf (stderr, "No XFixes extension\n");
2138         exit (1);
2139     }
2140
2141     register_cm(scr);
2142
2143     /* get atoms */
2144     opacityAtom = XInternAtom (dpy, OPACITY_PROP, False);
2145     winTypeAtom = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE", False);
2146     winType[WINTYPE_DESKTOP] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
2147     winType[WINTYPE_DOCK] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DOCK", False);
2148     winType[WINTYPE_TOOLBAR] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_TOOLBAR", False);
2149     winType[WINTYPE_MENU] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_MENU", False);
2150     winType[WINTYPE_UTILITY] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_UTILITY", False);
2151     winType[WINTYPE_SPLASH] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_SPLASH", False);
2152     winType[WINTYPE_DIALOG] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
2153     winType[WINTYPE_NORMAL] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_NORMAL", False);
2154     winType[WINTYPE_DROPDOWN_MENU] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", False);
2155     winType[WINTYPE_POPUP_MENU] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
2156     winType[WINTYPE_TOOLTIP] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_TOOLTIP", False);
2157     winType[WINTYPE_NOTIFY] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_NOTIFICATION", False);
2158     winType[WINTYPE_COMBO] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_COMBO", False);
2159     winType[WINTYPE_DND] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DND", False);
2160
2161     pa.subwindow_mode = IncludeInferiors;
2162
2163     if (compMode == CompClientShadows)
2164     {
2165         gaussianMap = make_gaussian_map(dpy, shadowRadius);
2166         presum_gaussian (gaussianMap);
2167     }
2168
2169     root_width = DisplayWidth (dpy, scr);
2170     root_height = DisplayHeight (dpy, scr);
2171
2172     rootPicture = XRenderCreatePicture (dpy, root, 
2173                                         XRenderFindVisualFormat (dpy,
2174                                                                  DefaultVisual (dpy, scr)),
2175                                         CPSubwindowMode,
2176                                         &pa);
2177     blackPicture = solid_picture (dpy, True, 1, 0, 0, 0);
2178     if (compMode == CompServerShadows)
2179         transBlackPicture = solid_picture (dpy, True, 0.3, 0, 0, 0);
2180     allDamage = None;
2181     clipChanged = True;
2182     XGrabServer (dpy);
2183     if (autoRedirect)
2184         XCompositeRedirectSubwindows (dpy, root, CompositeRedirectAutomatic);
2185     else
2186     {
2187         XCompositeRedirectSubwindows (dpy, root, CompositeRedirectManual);
2188         XSelectInput (dpy, root, 
2189                       SubstructureNotifyMask|
2190                       ExposureMask|
2191                       StructureNotifyMask|
2192                       PropertyChangeMask);
2193         XQueryTree (dpy, root, &root_return, &parent_return, &children, &nchildren);
2194         for (i = 0; i < nchildren; i++)
2195             add_win (dpy, children[i], i ? children[i-1] : None);
2196         XFree (children);
2197     }
2198     XUngrabServer (dpy);
2199     ufd.fd = ConnectionNumber (dpy);
2200     ufd.events = POLLIN;
2201     if (!autoRedirect)
2202         paint_all (dpy, None);
2203     for (;;)
2204     {
2205         /*      dump_wins (); */
2206         do {
2207             if (autoRedirect)
2208                 XFlush (dpy);
2209             if (!QLength (dpy))
2210             {
2211                  if (poll (&ufd, 1, fade_timeout()) == 0)
2212                  {
2213                     run_fades (dpy);
2214                     break;
2215                  }
2216             }
2217
2218             XNextEvent (dpy, &ev);
2219             if ((ev.type & 0x7f) != KeymapNotify)
2220                 discard_ignore (dpy, ev.xany.serial);
2221 #if DEBUG_EVENTS
2222             printf ("event %10.10s serial 0x%08x window 0x%08x\n",
2223                     ev_name(&ev), ev_serial (&ev), ev_window (&ev));
2224 #endif
2225             if (!autoRedirect) switch (ev.type) {
2226             case CreateNotify:
2227                 add_win (dpy, ev.xcreatewindow.window, 0);
2228                 break;
2229             case ConfigureNotify:
2230                 configure_win (dpy, &ev.xconfigure);
2231                 break;
2232             case DestroyNotify:
2233                 destroy_win (dpy, ev.xdestroywindow.window, True);
2234                 break;
2235             case MapNotify:
2236                 map_win (dpy, ev.xmap.window, ev.xmap.serial, True);
2237                 break;
2238             case UnmapNotify:
2239                 unmap_win (dpy, ev.xunmap.window, True);
2240                 break;
2241             case ReparentNotify:
2242                 if (ev.xreparent.parent == root)
2243                     add_win (dpy, ev.xreparent.window, 0);
2244                 else
2245                     destroy_win (dpy, ev.xreparent.window, True);
2246                 break;
2247             case CirculateNotify:
2248                 circulate_win (dpy, &ev.xcirculate);
2249                 break;
2250             case Expose:
2251                 if (ev.xexpose.window == root)
2252                 {
2253                     int more = ev.xexpose.count + 1;
2254                     if (n_expose == size_expose)
2255                     {
2256                         if (expose_rects)
2257                         {
2258                             expose_rects = realloc (expose_rects, 
2259                                                     (size_expose + more) * 
2260                                                     sizeof (XRectangle));
2261                             size_expose += more;
2262                         }
2263                         else
2264                         {
2265                             expose_rects = malloc (more * sizeof (XRectangle));
2266                             size_expose = more;
2267                         }
2268                     }
2269                     expose_rects[n_expose].x = ev.xexpose.x;
2270                     expose_rects[n_expose].y = ev.xexpose.y;
2271                     expose_rects[n_expose].width = ev.xexpose.width;
2272                     expose_rects[n_expose].height = ev.xexpose.height;
2273                     n_expose++;
2274                     if (ev.xexpose.count == 0)
2275                     {
2276                         expose_root (dpy, root, expose_rects, n_expose);
2277                         n_expose = 0;
2278                     }
2279                 }
2280                 break;
2281             case PropertyNotify:
2282                 for (p = 0; backgroundProps[p]; p++)
2283                 {
2284                     if (ev.xproperty.atom == XInternAtom (dpy, backgroundProps[p], False))
2285                     {
2286                         if (rootTile)
2287                         {
2288                             XClearArea (dpy, root, 0, 0, 0, 0, True);
2289                             XRenderFreePicture (dpy, rootTile);
2290                             rootTile = None;
2291                             break;
2292                         }
2293                     }
2294                 }
2295                 /* check if Trans property was changed */
2296                 if (ev.xproperty.atom == opacityAtom)
2297                 {
2298                     /* reset mode and redraw window */
2299                     win * w = find_win(dpy, ev.xproperty.window);
2300                     if (w)
2301                     {
2302                         if (fadeTrans)
2303                             set_fade (dpy, w, w->opacity*1.0/OPAQUE, get_opacity_percent (dpy, w),
2304                                       fade_out_step, 0, True, False);
2305                         else
2306                         {
2307                             w->opacity = get_opacity_prop(dpy, w, OPAQUE);
2308                             determine_mode(dpy, w);
2309                             if (w->shadow)
2310                             {
2311                                 XRenderFreePicture (dpy, w->shadow);
2312                                 w->shadow = None;
2313
2314                                 if (w->extents != None)
2315                                     XFixesDestroyRegion (dpy, w->extents);
2316
2317                                 /* rebuild the shadow */
2318                                 w->extents = win_extents (dpy, w);
2319                             }
2320                         }
2321                     }
2322                 }
2323                 break;
2324             default:
2325                 if (ev.type == damage_event + XDamageNotify)
2326                     damage_win (dpy, (XDamageNotifyEvent *) &ev);
2327                 break;
2328             }
2329         } while (QLength (dpy));
2330         if (allDamage && !autoRedirect)
2331         {
2332             static int  paint;
2333             paint_all (dpy, allDamage);
2334             paint++;
2335             XSync (dpy, False);
2336             allDamage = None;
2337             clipChanged = False;
2338         }
2339     }
2340 }