1a942a1279c3a535e0b511aa4036b62f4d3960c5
[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     w->a.override_redirect = ce->override_redirect;
1674     restack_win (dpy, w, ce->above);
1675     clipChanged = True;
1676 }
1677
1678 static void
1679 circulate_win (Display *dpy, XCirculateEvent *ce)
1680 {
1681     win     *w = find_win (dpy, ce->window);
1682     Window  new_above;
1683
1684     if (!w)
1685         return;
1686
1687     if (ce->place == PlaceOnTop)
1688         new_above = list->id;
1689     else
1690         new_above = None;
1691     restack_win (dpy, w, new_above);
1692     clipChanged = True;
1693 }
1694
1695 static void
1696 finish_destroy_win (Display *dpy, Window id)
1697 {
1698     win **prev, *w;
1699
1700     for (prev = &list; (w = *prev); prev = &w->next)
1701         if (w->id == id && w->destroyed)
1702         {
1703             finish_unmap_win (dpy, w);
1704             *prev = w->next;
1705             if (w->alphaPict)
1706             {
1707                 XRenderFreePicture (dpy, w->alphaPict);
1708                 w->alphaPict = None;
1709             }
1710             if (w->shadowPict)
1711             {
1712                 XRenderFreePicture (dpy, w->shadowPict);
1713                 w->shadowPict = None;
1714             }
1715             if (w->damage != None)
1716             {
1717                 set_ignore (dpy, NextRequest (dpy));
1718                 XDamageDestroy (dpy, w->damage);
1719                 w->damage = None;
1720             }
1721
1722             cleanup_fade (dpy, w);
1723             free (w);
1724             break;
1725         }
1726 }
1727
1728 #if HAS_NAME_WINDOW_PIXMAP
1729 static void
1730 destroy_callback (Display *dpy, win *w)
1731 {
1732     finish_destroy_win (dpy, w->id);
1733 }
1734 #endif
1735
1736 static void
1737 destroy_win (Display *dpy, Window id, Bool fade)
1738 {
1739     win *w = find_win (dpy, id);
1740
1741     if (w) w->destroyed = True;
1742
1743 #if HAS_NAME_WINDOW_PIXMAP
1744     if (w && w->pixmap && fade && winTypeFade[w->windowType])
1745         set_fade (dpy, w, w->opacity*1.0/OPAQUE, 0.0, fade_out_step,
1746                   destroy_callback, False, (w->a.map_state != IsUnmapped));
1747     else
1748 #endif
1749     {
1750         finish_destroy_win (dpy, id);
1751     }
1752 }
1753
1754 /*
1755 static void
1756 dump_win (win *w)
1757 {
1758     printf ("\t%08lx: %d x %d + %d + %d (%d)\n", w->id,
1759             w->a.width, w->a.height, w->a.x, w->a.y, w->a.border_width);
1760 }
1761
1762
1763 static void
1764 dump_wins (void)
1765 {
1766     win *w;
1767
1768     printf ("windows:\n");
1769     for (w = list; w; w = w->next)
1770         dump_win (w);
1771 }
1772 */
1773
1774 static void
1775 damage_win (Display *dpy, XDamageNotifyEvent *de)
1776 {
1777     win *w = find_win (dpy, de->drawable);
1778
1779     if (!w)
1780         return;
1781 #if CAN_DO_USABLE
1782     if (!w->usable)
1783     {
1784         if (w->damage_bounds.width == 0 || w->damage_bounds.height == 0)
1785         {
1786             w->damage_bounds = de->area;
1787         }
1788         else
1789         {
1790             if (de->area.x < w->damage_bounds.x)
1791             {
1792                 w->damage_bounds.width += (w->damage_bounds.x - de->area.x);
1793                 w->damage_bounds.x = de->area.x;
1794             }
1795             if (de->area.y < w->damage_bounds.y)
1796             {
1797                 w->damage_bounds.height += (w->damage_bounds.y - de->area.y);
1798                 w->damage_bounds.y = de->area.y;
1799             }
1800             if (de->area.x + de->area.width > w->damage_bounds.x + w->damage_bounds.width)
1801                 w->damage_bounds.width = de->area.x + de->area.width - w->damage_bounds.x;
1802             if (de->area.y + de->area.height > w->damage_bounds.y + w->damage_bounds.height)
1803                 w->damage_bounds.height = de->area.y + de->area.height - w->damage_bounds.y;
1804         }
1805 #if 0
1806         printf ("unusable damage %d, %d: %d x %d bounds %d, %d: %d x %d\n",
1807                 de->area.x,
1808                 de->area.y,
1809                 de->area.width,
1810                 de->area.height,
1811                 w->damage_bounds.x,
1812                 w->damage_bounds.y,
1813                 w->damage_bounds.width,
1814                 w->damage_bounds.height);
1815 #endif
1816         if (w->damage_bounds.x <= 0 && 
1817             w->damage_bounds.y <= 0 &&
1818             w->a.width <= w->damage_bounds.x + w->damage_bounds.width &&
1819             w->a.height <= w->damage_bounds.y + w->damage_bounds.height)
1820         {
1821             clipChanged = True;
1822             if (winTypeFade[w->windowType])
1823                 set_fade (dpy, w, 0, get_opacity_percent (dpy, w), fade_in_step, 0, True, True);
1824             w->usable = True;
1825         }
1826     }
1827     if (w->usable)
1828 #endif
1829         repair_win (dpy, w);
1830 }
1831
1832 static int
1833 error (Display *dpy, XErrorEvent *ev)
1834 {
1835     int     o;
1836     const char    *name = 0;
1837     
1838     if (should_ignore (dpy, ev->serial))
1839         return 0;
1840     
1841     if (ev->request_code == composite_opcode &&
1842         ev->minor_code == X_CompositeRedirectSubwindows)
1843     {
1844         fprintf (stderr, "Another composite manager is already running\n");
1845         exit (1);
1846     }
1847     
1848     o = ev->error_code - xfixes_error;
1849     switch (o) {
1850     case BadRegion: name = "BadRegion"; break;
1851     default: break;
1852     }
1853     o = ev->error_code - damage_error;
1854     switch (o) {
1855     case BadDamage: name = "BadDamage"; break;
1856     default: break;
1857     }
1858     o = ev->error_code - render_error;
1859     switch (o) {
1860     case BadPictFormat: name ="BadPictFormat"; break;
1861     case BadPicture: name ="BadPicture"; break;
1862     case BadPictOp: name ="BadPictOp"; break;
1863     case BadGlyphSet: name ="BadGlyphSet"; break;
1864     case BadGlyph: name ="BadGlyph"; break;
1865     default: break;
1866     }
1867         
1868     printf ("error %d request %d minor %d serial %lu\n",
1869             ev->error_code, ev->request_code, ev->minor_code, ev->serial);
1870
1871 /*    abort ();     this is just annoying to most people */
1872     return 0;
1873 }
1874
1875 static void
1876 expose_root (Display *dpy, Window root, XRectangle *rects, int nrects)
1877 {
1878     XserverRegion  region = XFixesCreateRegion (dpy, rects, nrects);
1879     
1880     add_damage (dpy, region);
1881 }
1882
1883 #if DEBUG_EVENTS
1884 static int
1885 ev_serial (XEvent *ev)
1886 {
1887     if (ev->type & 0x7f != KeymapNotify)
1888         return ev->xany.serial;
1889     return NextRequest (ev->xany.display);
1890 }
1891
1892 static char *
1893 ev_name (XEvent *ev)
1894 {
1895     static char buf[128];
1896     switch (ev->type & 0x7f) {
1897     case Expose:
1898         return "Expose";
1899     case MapNotify:
1900         return "Map";
1901     case UnmapNotify:
1902         return "Unmap";
1903     case ReparentNotify:
1904         return "Reparent";
1905     case CirculateNotify:
1906         return "Circulate";
1907     default:
1908         if (ev->type == damage_event + XDamageNotify)
1909             return "Damage";
1910         sprintf (buf, "Event %d", ev->type);
1911         return buf;
1912     }
1913 }
1914
1915 static Window
1916 ev_window (XEvent *ev)
1917 {
1918     switch (ev->type) {
1919     case Expose:
1920         return ev->xexpose.window;
1921     case MapNotify:
1922         return ev->xmap.window;
1923     case UnmapNotify:
1924         return ev->xunmap.window;
1925     case ReparentNotify:
1926         return ev->xreparent.window;
1927     case CirculateNotify:
1928         return ev->xcirculate.window;
1929     default:
1930         if (ev->type == damage_event + XDamageNotify)
1931             return ((XDamageNotifyEvent *) ev)->drawable;
1932         return 0;
1933     }
1934 }
1935 #endif
1936
1937 void
1938 usage (char *program)
1939 {
1940     fprintf (stderr, "%s v1.1.3\n", program);
1941     fprintf (stderr, "usage: %s [options]\n", program);
1942     fprintf (stderr, "Options\n");
1943     fprintf (stderr, "   -d display\n      Specifies which display should be managed.\n");
1944     fprintf (stderr, "   -r radius\n      Specifies the blur radius for client-side shadows. (default 12)\n");
1945     fprintf (stderr, "   -o opacity\n      Specifies the translucency for client-side shadows. (default .75)\n");
1946     fprintf (stderr, "   -l left-offset\n      Specifies the left offset for client-side shadows. (default -15)\n");
1947     fprintf (stderr, "   -t top-offset\n      Specifies the top offset for clinet-side shadows. (default -15)\n");
1948     fprintf (stderr, "   -I fade-in-step\n      Specifies the opacity change between steps while fading in. (default 0.028)\n");
1949     fprintf (stderr, "   -O fade-out-step\n      Specifies the opacity change between steps while fading out. (default 0.03)\n");
1950     fprintf (stderr, "   -D fade-delta-time\n      Specifies the time between steps in a fade in milliseconds. (default 10)\n");
1951     fprintf (stderr, "   -m opacity\n      Specifies the opacity for menus. (default 1.0)\n");
1952     fprintf (stderr, "   -a\n      Use automatic server-side compositing. Faster, but no special effects.\n");
1953     fprintf (stderr, "   -c\n      Draw client-side shadows with fuzzy edges.\n");
1954     fprintf (stderr, "   -C\n      Avoid drawing shadows on dock/panel windows.\n");
1955     fprintf (stderr, "   -f\n      Fade windows in/out when opening/closing.\n");
1956     fprintf (stderr, "   -F\n      Fade windows during opacity changes.\n");
1957     fprintf (stderr, "   -n\n      Normal client-side compositing with transparency support\n");
1958     fprintf (stderr, "   -s\n      Draw server-side shadows with sharp edges.\n");
1959     fprintf (stderr, "   -S\n      Enable synchronous operation (for debugging).\n");
1960     exit (1);
1961 }
1962
1963 static void
1964 register_cm (int scr)
1965 {
1966     Window w;
1967     Atom a;
1968     char *buf;
1969     int len, s;
1970
1971     if (scr < 0) return;
1972
1973     w = XCreateSimpleWindow (dpy, RootWindow (dpy, 0), 0, 0, 1, 1, 0, None,
1974                              None);
1975
1976     Xutf8SetWMProperties (dpy, w, "xcompmgr", "xcompmgr", NULL, 0, NULL, NULL,
1977                           NULL);
1978
1979     len = strlen(REGISTER_PROP) + 2;
1980     s = scr;
1981     while (s >= 10) {
1982         ++len;
1983         s /= 10;
1984     }
1985     buf = malloc(len);
1986     snprintf(buf, len, REGISTER_PROP"%d", scr);
1987
1988     a = XInternAtom (dpy, buf, False);
1989     free(buf);
1990
1991     XSetSelectionOwner (dpy, a, w, 0);
1992 }
1993
1994 int
1995 main (int argc, char **argv)
1996 {
1997     XEvent          ev;
1998     Window          root_return, parent_return;
1999     Window          *children;
2000     unsigned int    nchildren;
2001     int             i;
2002     XRenderPictureAttributes    pa;
2003     XRectangle      *expose_rects = 0;
2004     int             size_expose = 0;
2005     int             n_expose = 0;
2006     struct pollfd   ufd;
2007     int             p;
2008     int             composite_major, composite_minor;
2009     char            *display = 0;
2010     int             o;
2011     Bool            noDockShadow = False;
2012
2013     for (i = 0; i < NUM_WINTYPES; ++i) {
2014         winTypeFade[i] = False;
2015         winTypeShadow[i] = False;
2016         winTypeOpacity[i] = 1.0;
2017     }
2018
2019     /* don't bother to draw a shadow for the desktop */
2020     winTypeShadow[WINTYPE_DESKTOP] = False;
2021
2022     while ((o = getopt (argc, argv, "D:I:O:d:r:o:m:l:t:scnfFCaS")) != -1)
2023     {
2024         switch (o) {
2025         case 'd':
2026             display = optarg;
2027             break;
2028         case 'D':
2029             fade_delta = atoi (optarg);
2030             if (fade_delta < 1)
2031                 fade_delta = 10;
2032             break;
2033         case 'I':
2034             fade_in_step = atof (optarg);
2035             if (fade_in_step <= 0)
2036                 fade_in_step = 0.01;
2037             break;
2038         case 'O':
2039             fade_out_step = atof (optarg);
2040             if (fade_out_step <= 0)
2041                 fade_out_step = 0.01;
2042             break;
2043         case 's':
2044             compMode = CompServerShadows;
2045             for (i = 0; i < NUM_WINTYPES; ++i)
2046                 winTypeShadow[i] = True;
2047             break;
2048         case 'c':
2049             compMode = CompClientShadows;
2050             for (i = 0; i < NUM_WINTYPES; ++i)
2051                 winTypeShadow[i] = True;
2052             break;
2053         case 'C':
2054             noDockShadow = True;
2055             break;
2056         case 'n':
2057             compMode = CompSimple;
2058             for (i = 0; i < NUM_WINTYPES; ++i)
2059                 winTypeShadow[i] = False;
2060             break;
2061         case 'm':
2062             winTypeOpacity[WINTYPE_DROPDOWN_MENU] = atof (optarg);
2063             winTypeOpacity[WINTYPE_POPUP_MENU] = atof (optarg);
2064             break;
2065         case 'f':
2066             for (i = 0; i < NUM_WINTYPES; ++i)
2067                 winTypeFade[i] = True;
2068             break;
2069         case 'F':
2070             fadeTrans = True;
2071             break;
2072         case 'a':
2073             autoRedirect = True;
2074             break;
2075         case 'S':
2076             synchronize = True;
2077             break;
2078         case 'r':
2079             shadowRadius = atoi (optarg);
2080             break;
2081         case 'o':
2082             shadowOpacity = atof (optarg);
2083             break;
2084         case 'l':
2085             shadowOffsetX = atoi (optarg);
2086             break;
2087         case 't':
2088             shadowOffsetY = atoi (optarg);
2089             break;
2090         default:
2091             usage (argv[0]);
2092             break;
2093         }
2094     }
2095
2096     if (noDockShadow)
2097         winTypeShadow[WINTYPE_DOCK] = False;
2098     
2099     dpy = XOpenDisplay (display);
2100     if (!dpy)
2101     {
2102         fprintf (stderr, "Can't open display\n");
2103         exit (1);
2104     }
2105     XSetErrorHandler (error);
2106     if (synchronize)
2107         XSynchronize (dpy, 1);
2108     scr = DefaultScreen (dpy);
2109     root = RootWindow (dpy, scr);
2110
2111     if (!XRenderQueryExtension (dpy, &render_event, &render_error))
2112     {
2113         fprintf (stderr, "No render extension\n");
2114         exit (1);
2115     }
2116     if (!XQueryExtension (dpy, COMPOSITE_NAME, &composite_opcode,
2117                           &composite_event, &composite_error))
2118     {
2119         fprintf (stderr, "No composite extension\n");
2120         exit (1);
2121     }
2122     XCompositeQueryVersion (dpy, &composite_major, &composite_minor);
2123 #if HAS_NAME_WINDOW_PIXMAP
2124     if (composite_major > 0 || composite_minor >= 2)
2125         hasNamePixmap = True;
2126 #endif
2127
2128     if (!XDamageQueryExtension (dpy, &damage_event, &damage_error))
2129     {
2130         fprintf (stderr, "No damage extension\n");
2131         exit (1);
2132     }
2133     if (!XFixesQueryExtension (dpy, &xfixes_event, &xfixes_error))
2134     {
2135         fprintf (stderr, "No XFixes extension\n");
2136         exit (1);
2137     }
2138
2139     register_cm(scr);
2140
2141     /* get atoms */
2142     opacityAtom = XInternAtom (dpy, OPACITY_PROP, False);
2143     winTypeAtom = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE", False);
2144     winType[WINTYPE_DESKTOP] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
2145     winType[WINTYPE_DOCK] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DOCK", False);
2146     winType[WINTYPE_TOOLBAR] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_TOOLBAR", False);
2147     winType[WINTYPE_MENU] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_MENU", False);
2148     winType[WINTYPE_UTILITY] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_UTILITY", False);
2149     winType[WINTYPE_SPLASH] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_SPLASH", False);
2150     winType[WINTYPE_DIALOG] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
2151     winType[WINTYPE_NORMAL] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_NORMAL", False);
2152     winType[WINTYPE_DROPDOWN_MENU] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", False);
2153     winType[WINTYPE_POPUP_MENU] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
2154     winType[WINTYPE_TOOLTIP] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_TOOLTIP", False);
2155     winType[WINTYPE_NOTIFY] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_NOTIFICATION", False);
2156     winType[WINTYPE_COMBO] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_COMBO", False);
2157     winType[WINTYPE_DND] = XInternAtom (dpy, "_NET_WM_WINDOW_TYPE_DND", False);
2158
2159     pa.subwindow_mode = IncludeInferiors;
2160
2161     if (compMode == CompClientShadows)
2162     {
2163         gaussianMap = make_gaussian_map(dpy, shadowRadius);
2164         presum_gaussian (gaussianMap);
2165     }
2166
2167     root_width = DisplayWidth (dpy, scr);
2168     root_height = DisplayHeight (dpy, scr);
2169
2170     rootPicture = XRenderCreatePicture (dpy, root, 
2171                                         XRenderFindVisualFormat (dpy,
2172                                                                  DefaultVisual (dpy, scr)),
2173                                         CPSubwindowMode,
2174                                         &pa);
2175     blackPicture = solid_picture (dpy, True, 1, 0, 0, 0);
2176     if (compMode == CompServerShadows)
2177         transBlackPicture = solid_picture (dpy, True, 0.3, 0, 0, 0);
2178     allDamage = None;
2179     clipChanged = True;
2180     XGrabServer (dpy);
2181     if (autoRedirect)
2182         XCompositeRedirectSubwindows (dpy, root, CompositeRedirectAutomatic);
2183     else
2184     {
2185         XCompositeRedirectSubwindows (dpy, root, CompositeRedirectManual);
2186         XSelectInput (dpy, root, 
2187                       SubstructureNotifyMask|
2188                       ExposureMask|
2189                       StructureNotifyMask|
2190                       PropertyChangeMask);
2191         XQueryTree (dpy, root, &root_return, &parent_return, &children, &nchildren);
2192         for (i = 0; i < nchildren; i++)
2193             add_win (dpy, children[i], i ? children[i-1] : None);
2194         XFree (children);
2195     }
2196     XUngrabServer (dpy);
2197     ufd.fd = ConnectionNumber (dpy);
2198     ufd.events = POLLIN;
2199     if (!autoRedirect)
2200         paint_all (dpy, None);
2201     for (;;)
2202     {
2203         /*      dump_wins (); */
2204         do {
2205             if (autoRedirect)
2206                 XFlush (dpy);
2207             if (!QLength (dpy))
2208             {
2209                  if (poll (&ufd, 1, fade_timeout()) == 0)
2210                  {
2211                     run_fades (dpy);
2212                     break;
2213                  }
2214             }
2215
2216             XNextEvent (dpy, &ev);
2217             if ((ev.type & 0x7f) != KeymapNotify)
2218                 discard_ignore (dpy, ev.xany.serial);
2219 #if DEBUG_EVENTS
2220             printf ("event %10.10s serial 0x%08x window 0x%08x\n",
2221                     ev_name(&ev), ev_serial (&ev), ev_window (&ev));
2222 #endif
2223             if (!autoRedirect) switch (ev.type) {
2224             case CreateNotify:
2225                 add_win (dpy, ev.xcreatewindow.window, 0);
2226                 break;
2227             case ConfigureNotify:
2228                 configure_win (dpy, &ev.xconfigure);
2229                 break;
2230             case DestroyNotify:
2231                 destroy_win (dpy, ev.xdestroywindow.window, True);
2232                 break;
2233             case MapNotify:
2234                 map_win (dpy, ev.xmap.window, ev.xmap.serial, True);
2235                 break;
2236             case UnmapNotify:
2237                 unmap_win (dpy, ev.xunmap.window, True);
2238                 break;
2239             case ReparentNotify:
2240                 if (ev.xreparent.parent == root)
2241                     add_win (dpy, ev.xreparent.window, 0);
2242                 else
2243                     destroy_win (dpy, ev.xreparent.window, True);
2244                 break;
2245             case CirculateNotify:
2246                 circulate_win (dpy, &ev.xcirculate);
2247                 break;
2248             case Expose:
2249                 if (ev.xexpose.window == root)
2250                 {
2251                     int more = ev.xexpose.count + 1;
2252                     if (n_expose == size_expose)
2253                     {
2254                         if (expose_rects)
2255                         {
2256                             expose_rects = realloc (expose_rects, 
2257                                                     (size_expose + more) * 
2258                                                     sizeof (XRectangle));
2259                             size_expose += more;
2260                         }
2261                         else
2262                         {
2263                             expose_rects = malloc (more * sizeof (XRectangle));
2264                             size_expose = more;
2265                         }
2266                     }
2267                     expose_rects[n_expose].x = ev.xexpose.x;
2268                     expose_rects[n_expose].y = ev.xexpose.y;
2269                     expose_rects[n_expose].width = ev.xexpose.width;
2270                     expose_rects[n_expose].height = ev.xexpose.height;
2271                     n_expose++;
2272                     if (ev.xexpose.count == 0)
2273                     {
2274                         expose_root (dpy, root, expose_rects, n_expose);
2275                         n_expose = 0;
2276                     }
2277                 }
2278                 break;
2279             case PropertyNotify:
2280                 for (p = 0; backgroundProps[p]; p++)
2281                 {
2282                     if (ev.xproperty.atom == XInternAtom (dpy, backgroundProps[p], False))
2283                     {
2284                         if (rootTile)
2285                         {
2286                             XClearArea (dpy, root, 0, 0, 0, 0, True);
2287                             XRenderFreePicture (dpy, rootTile);
2288                             rootTile = None;
2289                             break;
2290                         }
2291                     }
2292                 }
2293                 /* check if Trans property was changed */
2294                 if (ev.xproperty.atom == opacityAtom)
2295                 {
2296                     /* reset mode and redraw window */
2297                     win * w = find_win(dpy, ev.xproperty.window);
2298                     if (w)
2299                     {
2300                         if (fadeTrans)
2301                             set_fade (dpy, w, w->opacity*1.0/OPAQUE, get_opacity_percent (dpy, w),
2302                                       fade_out_step, 0, True, False);
2303                         else
2304                         {
2305                             w->opacity = get_opacity_prop(dpy, w, OPAQUE);
2306                             determine_mode(dpy, w);
2307                             if (w->shadow)
2308                             {
2309                                 XRenderFreePicture (dpy, w->shadow);
2310                                 w->shadow = None;
2311
2312                                 if (w->extents != None)
2313                                     XFixesDestroyRegion (dpy, w->extents);
2314
2315                                 /* rebuild the shadow */
2316                                 w->extents = win_extents (dpy, w);
2317                             }
2318                         }
2319                     }
2320                 }
2321                 break;
2322             default:
2323                 if (ev.type == damage_event + XDamageNotify)
2324                     damage_win (dpy, (XDamageNotifyEvent *) &ev);
2325                 break;
2326             }
2327         } while (QLength (dpy));
2328         if (allDamage && !autoRedirect)
2329         {
2330             static int  paint;
2331             paint_all (dpy, allDamage);
2332             paint++;
2333             XSync (dpy, False);
2334             allDamage = None;
2335             clipChanged = False;
2336         }
2337     }
2338 }