Debian Codegraph @

src/compton.c

raw
1 /*
2 * Compton - a compositor for X11
3 *
4 * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
5 *
6 * Copyright (c) 2011-2013, Christopher Jeffrey
7 * See LICENSE for more information.
8 *
9 */
10
11 #include "compton.h"
12 #include <ctype.h>
13
14 // === Global constants ===
15
16 /// Name strings for window types.
17 const char * const WINTYPES[NUM_WINTYPES] = {
18 "unknown",
19 "desktop",
20 "dock",
21 "toolbar",
22 "menu",
23 "utility",
24 "splash",
25 "dialog",
26 "normal",
27 "dropdown_menu",
28 "popup_menu",
29 "tooltip",
30 "notify",
31 "combo",
32 "dnd",
33 };
34
35 /// Names of VSync modes.
36 const char * const VSYNC_STRS[NUM_VSYNC + 1] = {
37 "none", // VSYNC_NONE
38 "drm", // VSYNC_DRM
39 "opengl", // VSYNC_OPENGL
40 "opengl-oml", // VSYNC_OPENGL_OML
41 "opengl-swc", // VSYNC_OPENGL_SWC
42 "opengl-mswc", // VSYNC_OPENGL_MSWC
43 NULL
44 };
45
46 /// Names of backends.
47 const char * const BACKEND_STRS[NUM_BKEND + 1] = {
48 "xrender", // BKEND_XRENDER
49 "glx", // BKEND_GLX
50 "xr_glx_hybrid",// BKEND_XR_GLX_HYBRID
51 NULL
52 };
53
54 /// Function pointers to init VSync modes.
55 static bool (* const (VSYNC_FUNCS_INIT[NUM_VSYNC]))(session_t *ps) = {
56 [VSYNC_DRM ] = vsync_drm_init,
57 [VSYNC_OPENGL ] = vsync_opengl_init,
58 [VSYNC_OPENGL_OML ] = vsync_opengl_oml_init,
59 [VSYNC_OPENGL_SWC ] = vsync_opengl_swc_init,
60 [VSYNC_OPENGL_MSWC ] = vsync_opengl_mswc_init,
61 };
62
63 /// Function pointers to wait for VSync.
64 static int (* const (VSYNC_FUNCS_WAIT[NUM_VSYNC]))(session_t *ps) = {
65 #ifdef CONFIG_VSYNC_DRM
66 [VSYNC_DRM ] = vsync_drm_wait,
67 #endif
68 #ifdef CONFIG_VSYNC_OPENGL
69 [VSYNC_OPENGL ] = vsync_opengl_wait,
70 [VSYNC_OPENGL_OML ] = vsync_opengl_oml_wait,
71 #endif
72 };
73
74 /// Function pointers to deinitialize VSync.
75 static void (* const (VSYNC_FUNCS_DEINIT[NUM_VSYNC]))(session_t *ps) = {
76 #ifdef CONFIG_VSYNC_OPENGL
77 [VSYNC_OPENGL_SWC ] = vsync_opengl_swc_deinit,
78 [VSYNC_OPENGL_MSWC ] = vsync_opengl_mswc_deinit,
79 #endif
80 };
81
82 /// Names of root window properties that could point to a pixmap of
83 /// background.
84 const static char *background_props_str[] = {
85 "_XROOTPMAP_ID",
86 "_XSETROOT_ID",
87 0,
88 };
89
90 // === Global variables ===
91
92 /// Pointer to current session, as a global variable. Only used by
93 /// <code>error()</code> and <code>reset_enable()</code>, which could not
94 /// have a pointer to current session passed in.
95 session_t *ps_g = NULL;
96
97 // === Fading ===
98
99 /**
100 * Get the time left before next fading point.
101 *
102 * In milliseconds.
103 */
104 static int
105 fade_timeout(session_t *ps) {
106 int diff = ps->o.fade_delta - get_time_ms() + ps->fade_time;
107
108 diff = normalize_i_range(diff, 0, ps->o.fade_delta * 2);
109
110 return diff;
111 }
112
113 /**
114 * Run fading on a window.
115 *
116 * @param steps steps of fading
117 */
118 static void
119 run_fade(session_t *ps, win *w, unsigned steps) {
120 // If we have reached target opacity, return
121 if (w->opacity == w->opacity_tgt) {
122 return;
123 }
124
125 if (!w->fade)
126 w->opacity = w->opacity_tgt;
127 else if (steps) {
128 // Use double below because opacity_t will probably overflow during
129 // calculations
130 if (w->opacity < w->opacity_tgt)
131 w->opacity = normalize_d_range(
132 (double) w->opacity + (double) ps->o.fade_in_step * steps,
133 0.0, w->opacity_tgt);
134 else
135 w->opacity = normalize_d_range(
136 (double) w->opacity - (double) ps->o.fade_out_step * steps,
137 w->opacity_tgt, OPAQUE);
138 }
139
140 if (w->opacity != w->opacity_tgt) {
141 ps->idling = false;
142 }
143 }
144
145 /**
146 * Set fade callback of a window, and possibly execute the previous
147 * callback.
148 *
149 * @param exec_callback whether the previous callback is to be executed
150 */
151 static void
152 set_fade_callback(session_t *ps, win *w,
153 void (*callback) (session_t *ps, win *w), bool exec_callback) {
154 void (*old_callback) (session_t *ps, win *w) = w->fade_callback;
155
156 w->fade_callback = callback;
157 // Must be the last line as the callback could destroy w!
158 if (exec_callback && old_callback) {
159 old_callback(ps, w);
160 // Although currently no callback function affects window state on
161 // next paint, it could, in the future
162 ps->idling = false;
163 }
164 }
165
166 // === Shadows ===
167
168 static double __attribute__((const))
169 gaussian(double r, double x, double y) {
170 return ((1 / (sqrt(2 * M_PI * r))) *
171 exp((- (x * x + y * y)) / (2 * r * r)));
172 }
173
174 static conv *
175 make_gaussian_map(double r) {
176 conv *c;
177 int size = ((int) ceil((r * 3)) + 1) & ~1;
178 int center = size / 2;
179 int x, y;
180 double t;
181 double g;
182
183 c = malloc(sizeof(conv) + size * size * sizeof(double));
184 c->size = size;
185 c->data = (double *) (c + 1);
186 t = 0.0;
187
188 for (y = 0; y < size; y++) {
189 for (x = 0; x < size; x++) {
190 g = gaussian(r, x - center, y - center);
191 t += g;
192 c->data[y * size + x] = g;
193 }
194 }
195
196 for (y = 0; y < size; y++) {
197 for (x = 0; x < size; x++) {
198 c->data[y * size + x] /= t;
199 }
200 }
201
202 return c;
203 }
204
205 /*
206 * A picture will help
207 *
208 * -center 0 width width+center
209 * -center +-----+-------------------+-----+
210 * | | | |
211 * | | | |
212 * 0 +-----+-------------------+-----+
213 * | | | |
214 * | | | |
215 * | | | |
216 * height +-----+-------------------+-----+
217 * | | | |
218 * height+ | | | |
219 * center +-----+-------------------+-----+
220 */
221
222 static unsigned char
223 sum_gaussian(conv *map, double opacity,
224 int x, int y, int width, int height) {
225 int fx, fy;
226 double *g_data;
227 double *g_line = map->data;
228 int g_size = map->size;
229 int center = g_size / 2;
230 int fx_start, fx_end;
231 int fy_start, fy_end;
232 double v;
233
234 /*
235 * Compute set of filter values which are "in range",
236 * that's the set with:
237 * 0 <= x + (fx-center) && x + (fx-center) < width &&
238 * 0 <= y + (fy-center) && y + (fy-center) < height
239 *
240 * 0 <= x + (fx - center) x + fx - center < width
241 * center - x <= fx fx < width + center - x
242 */
243
244 fx_start = center - x;
245 if (fx_start < 0) fx_start = 0;
246 fx_end = width + center - x;
247 if (fx_end > g_size) fx_end = g_size;
248
249 fy_start = center - y;
250 if (fy_start < 0) fy_start = 0;
251 fy_end = height + center - y;
252 if (fy_end > g_size) fy_end = g_size;
253
254 g_line = g_line + fy_start * g_size + fx_start;
255
256 v = 0;
257
258 for (fy = fy_start; fy < fy_end; fy++) {
259 g_data = g_line;
260 g_line += g_size;
261
262 for (fx = fx_start; fx < fx_end; fx++) {
263 v += *g_data++;
264 }
265 }
266
267 if (v > 1) v = 1;
268
269 return ((unsigned char) (v * opacity * 255.0));
270 }
271
272 /* precompute shadow corners and sides
273 to save time for large windows */
274
275 static void
276 presum_gaussian(session_t *ps, conv *map) {
277 int center = map->size / 2;
278 int opacity, x, y;
279
280 ps->cgsize = map->size;
281
282 if (ps->shadow_corner)
283 free(ps->shadow_corner);
284 if (ps->shadow_top)
285 free(ps->shadow_top);
286
287 ps->shadow_corner = malloc((ps->cgsize + 1) * (ps->cgsize + 1) * 26);
288 ps->shadow_top = malloc((ps->cgsize + 1) * 26);
289
290 for (x = 0; x <= ps->cgsize; x++) {
291 ps->shadow_top[25 * (ps->cgsize + 1) + x] =
292 sum_gaussian(map, 1, x - center, center, ps->cgsize * 2, ps->cgsize * 2);
293
294 for (opacity = 0; opacity < 25; opacity++) {
295 ps->shadow_top[opacity * (ps->cgsize + 1) + x] =
296 ps->shadow_top[25 * (ps->cgsize + 1) + x] * opacity / 25;
297 }
298
299 for (y = 0; y <= x; y++) {
300 ps->shadow_corner[25 * (ps->cgsize + 1) * (ps->cgsize + 1) + y * (ps->cgsize + 1) + x]
301 = sum_gaussian(map, 1, x - center, y - center, ps->cgsize * 2, ps->cgsize * 2);
302 ps->shadow_corner[25 * (ps->cgsize + 1) * (ps->cgsize + 1) + x * (ps->cgsize + 1) + y]
303 = ps->shadow_corner[25 * (ps->cgsize + 1) * (ps->cgsize + 1) + y * (ps->cgsize + 1) + x];
304
305 for (opacity = 0; opacity < 25; opacity++) {
306 ps->shadow_corner[opacity * (ps->cgsize + 1) * (ps->cgsize + 1)
307 + y * (ps->cgsize + 1) + x]
308 = ps->shadow_corner[opacity * (ps->cgsize + 1) * (ps->cgsize + 1)
309 + x * (ps->cgsize + 1) + y]
310 = ps->shadow_corner[25 * (ps->cgsize + 1) * (ps->cgsize + 1)
311 + y * (ps->cgsize + 1) + x] * opacity / 25;
312 }
313 }
314 }
315 }
316
317 static XImage *
318 make_shadow(session_t *ps, double opacity,
319 int width, int height) {
320 XImage *ximage;
321 unsigned char *data;
322 int ylimit, xlimit;
323 int swidth = width + ps->cgsize;
324 int sheight = height + ps->cgsize;
325 int center = ps->cgsize / 2;
326 int x, y;
327 unsigned char d;
328 int x_diff;
329 int opacity_int = (int)(opacity * 25);
330
331 data = malloc(swidth * sheight * sizeof(unsigned char));
332 if (!data) return 0;
333
334 ximage = XCreateImage(ps->dpy, ps->vis, 8,
335 ZPixmap, 0, (char *) data, swidth, sheight, 8, swidth * sizeof(char));
336
337 if (!ximage) {
338 free(data);
339 return 0;
340 }
341
342 /*
343 * Build the gaussian in sections
344 */
345
346 /*
347 * center (fill the complete data array)
348 */
349
350 // If clear_shadow is enabled and the border & corner shadow (which
351 // later will be filled) could entirely cover the area of the shadow
352 // that will be displayed, do not bother filling other pixels. If it
353 // can't, we must fill the other pixels here.
354 /* if (!(clear_shadow && ps->o.shadow_offset_x <= 0 && ps->o.shadow_offset_x >= -ps->cgsize
355 && ps->o.shadow_offset_y <= 0 && ps->o.shadow_offset_y >= -ps->cgsize)) { */
356 if (ps->cgsize > 0) {
357 d = ps->shadow_top[opacity_int * (ps->cgsize + 1) + ps->cgsize];
358 } else {
359 d = sum_gaussian(ps->gaussian_map,
360 opacity, center, center, width, height);
361 }
362 memset(data, d, sheight * swidth);
363 // }
364
365 /*
366 * corners
367 */
368
369 ylimit = ps->cgsize;
370 if (ylimit > sheight / 2) ylimit = (sheight + 1) / 2;
371
372 xlimit = ps->cgsize;
373 if (xlimit > swidth / 2) xlimit = (swidth + 1) / 2;
374
375 for (y = 0; y < ylimit; y++) {
376 for (x = 0; x < xlimit; x++) {
377 if (xlimit == ps->cgsize && ylimit == ps->cgsize) {
378 d = ps->shadow_corner[opacity_int * (ps->cgsize + 1) * (ps->cgsize + 1)
379 + y * (ps->cgsize + 1) + x];
380 } else {
381 d = sum_gaussian(ps->gaussian_map,
382 opacity, x - center, y - center, width, height);
383 }
384 data[y * swidth + x] = d;
385 data[(sheight - y - 1) * swidth + x] = d;
386 data[(sheight - y - 1) * swidth + (swidth - x - 1)] = d;
387 data[y * swidth + (swidth - x - 1)] = d;
388 }
389 }
390
391 /*
392 * top/bottom
393 */
394
395 x_diff = swidth - (ps->cgsize * 2);
396 if (x_diff > 0 && ylimit > 0) {
397 for (y = 0; y < ylimit; y++) {
398 if (ylimit == ps->cgsize) {
399 d = ps->shadow_top[opacity_int * (ps->cgsize + 1) + y];
400 } else {
401 d = sum_gaussian(ps->gaussian_map,
402 opacity, center, y - center, width, height);
403 }
404 memset(&data[y * swidth + ps->cgsize], d, x_diff);
405 memset(&data[(sheight - y - 1) * swidth + ps->cgsize], d, x_diff);
406 }
407 }
408
409 /*
410 * sides
411 */
412
413 for (x = 0; x < xlimit; x++) {
414 if (xlimit == ps->cgsize) {
415 d = ps->shadow_top[opacity_int * (ps->cgsize + 1) + x];
416 } else {
417 d = sum_gaussian(ps->gaussian_map,
418 opacity, x - center, center, width, height);
419 }
420 for (y = ps->cgsize; y < sheight - ps->cgsize; y++) {
421 data[y * swidth + x] = d;
422 data[y * swidth + (swidth - x - 1)] = d;
423 }
424 }
425
426 /*
427 if (clear_shadow) {
428 // Clear the region in the shadow that the window would cover based
429 // on shadow_offset_{x,y} user provides
430 int xstart = normalize_i_range(- (int) ps->o.shadow_offset_x, 0, swidth);
431 int xrange = normalize_i_range(width - (int) ps->o.shadow_offset_x,
432 0, swidth) - xstart;
433 int ystart = normalize_i_range(- (int) ps->o.shadow_offset_y, 0, sheight);
434 int yend = normalize_i_range(height - (int) ps->o.shadow_offset_y,
435 0, sheight);
436 int y;
437
438 for (y = ystart; y < yend; y++) {
439 memset(&data[y * swidth + xstart], 0, xrange);
440 }
441 }
442 */
443
444 return ximage;
445 }
446
447 /**
448 * Generate shadow <code>Picture</code> for a window.
449 */
450 static bool
451 win_build_shadow(session_t *ps, win *w, double opacity) {
452 const int width = w->widthb;
453 const int height = w->heightb;
454
455 XImage *shadow_image = NULL;
456 Pixmap shadow_pixmap = None, shadow_pixmap_argb = None;
457 Picture shadow_picture = None, shadow_picture_argb = None;
458 GC gc = None;
459
460 shadow_image = make_shadow(ps, opacity, width, height);
461 if (!shadow_image)
462 return None;
463
464 shadow_pixmap = XCreatePixmap(ps->dpy, ps->root,
465 shadow_image->width, shadow_image->height, 8);
466 shadow_pixmap_argb = XCreatePixmap(ps->dpy, ps->root,
467 shadow_image->width, shadow_image->height, 32);
468
469 if (!shadow_pixmap || !shadow_pixmap_argb)
470 goto shadow_picture_err;
471
472 shadow_picture = XRenderCreatePicture(ps->dpy, shadow_pixmap,
473 XRenderFindStandardFormat(ps->dpy, PictStandardA8), 0, 0);
474 shadow_picture_argb = XRenderCreatePicture(ps->dpy, shadow_pixmap_argb,
475 XRenderFindStandardFormat(ps->dpy, PictStandardARGB32), 0, 0);
476 if (!shadow_picture || !shadow_picture_argb)
477 goto shadow_picture_err;
478
479 gc = XCreateGC(ps->dpy, shadow_pixmap, 0, 0);
480 if (!gc)
481 goto shadow_picture_err;
482
483 XPutImage(ps->dpy, shadow_pixmap, gc, shadow_image, 0, 0, 0, 0,
484 shadow_image->width, shadow_image->height);
485 XRenderComposite(ps->dpy, PictOpSrc, ps->cshadow_picture, shadow_picture,
486 shadow_picture_argb, 0, 0, 0, 0, 0, 0,
487 shadow_image->width, shadow_image->height);
488
489 assert(!w->shadow_paint.pixmap);
490 w->shadow_paint.pixmap = shadow_pixmap_argb;
491 assert(!w->shadow_paint.pict);
492 w->shadow_paint.pict = shadow_picture_argb;
493
494 // Sync it once and only once
495 xr_sync(ps, w->shadow_paint.pixmap, NULL);
496
497 XFreeGC(ps->dpy, gc);
498 XDestroyImage(shadow_image);
499 XFreePixmap(ps->dpy, shadow_pixmap);
500 XRenderFreePicture(ps->dpy, shadow_picture);
501
502 return true;
503
504 shadow_picture_err:
505 if (shadow_image)
506 XDestroyImage(shadow_image);
507 if (shadow_pixmap)
508 XFreePixmap(ps->dpy, shadow_pixmap);
509 if (shadow_pixmap_argb)
510 XFreePixmap(ps->dpy, shadow_pixmap_argb);
511 if (shadow_picture)
512 XRenderFreePicture(ps->dpy, shadow_picture);
513 if (shadow_picture_argb)
514 XRenderFreePicture(ps->dpy, shadow_picture_argb);
515 if (gc)
516 XFreeGC(ps->dpy, gc);
517
518 return false;
519 }
520
521 /**
522 * Generate a 1x1 <code>Picture</code> of a particular color.
523 */
524 static Picture
525 solid_picture(session_t *ps, bool argb, double a,
526 double r, double g, double b) {
527 Pixmap pixmap;
528 Picture picture;
529 XRenderPictureAttributes pa;
530 XRenderColor c;
531
532 pixmap = XCreatePixmap(ps->dpy, ps->root, 1, 1, argb ? 32 : 8);
533
534 if (!pixmap) return None;
535
536 pa.repeat = True;
537 picture = XRenderCreatePicture(ps->dpy, pixmap,
538 XRenderFindStandardFormat(ps->dpy, argb
539 ? PictStandardARGB32 : PictStandardA8),
540 CPRepeat,
541 &pa);
542
543 if (!picture) {
544 XFreePixmap(ps->dpy, pixmap);
545 return None;
546 }
547
548 c.alpha = a * 0xffff;
549 c.red = r * 0xffff;
550 c.green = g * 0xffff;
551 c.blue = b * 0xffff;
552
553 XRenderFillRectangle(ps->dpy, PictOpSrc, picture, &c, 0, 0, 1, 1);
554 XFreePixmap(ps->dpy, pixmap);
555
556 return picture;
557 }
558
559 // === Error handling ===
560
561 static void
562 discard_ignore(session_t *ps, unsigned long sequence) {
563 while (ps->ignore_head) {
564 if ((long) (sequence - ps->ignore_head->sequence) > 0) {
565 ignore_t *next = ps->ignore_head->next;
566 free(ps->ignore_head);
567 ps->ignore_head = next;
568 if (!ps->ignore_head) {
569 ps->ignore_tail = &ps->ignore_head;
570 }
571 } else {
572 break;
573 }
574 }
575 }
576
577 static void
578 set_ignore(session_t *ps, unsigned long sequence) {
579 if (ps->o.show_all_xerrors)
580 return;
581
582 ignore_t *i = malloc(sizeof(ignore_t));
583 if (!i) return;
584
585 i->sequence = sequence;
586 i->next = 0;
587 *ps->ignore_tail = i;
588 ps->ignore_tail = &i->next;
589 }
590
591 static int
592 should_ignore(session_t *ps, unsigned long sequence) {
593 discard_ignore(ps, sequence);
594 return ps->ignore_head && ps->ignore_head->sequence == sequence;
595 }
596
597 // === Windows ===
598
599 /**
600 * Get a specific attribute of a window.
601 *
602 * Returns a blank structure if the returned type and format does not
603 * match the requested type and format.
604 *
605 * @param ps current session
606 * @param w window
607 * @param atom atom of attribute to fetch
608 * @param length length to read
609 * @param rtype atom of the requested type
610 * @param rformat requested format
611 * @return a <code>winprop_t</code> structure containing the attribute
612 * and number of items. A blank one on failure.
613 */
614 winprop_t
615 wid_get_prop_adv(const session_t *ps, Window w, Atom atom, long offset,
616 long length, Atom rtype, int rformat) {
617 Atom type = None;
618 int format = 0;
619 unsigned long nitems = 0, after = 0;
620 unsigned char *data = NULL;
621
622 if (Success == XGetWindowProperty(ps->dpy, w, atom, offset, length,
623 False, rtype, &type, &format, &nitems, &after, &data)
624 && nitems && (AnyPropertyType == type || type == rtype)
625 && (!rformat || format == rformat)
626 && (8 == format || 16 == format || 32 == format)) {
627 return (winprop_t) {
628 .data.p8 = data,
629 .nitems = nitems,
630 .type = type,
631 .format = format,
632 };
633 }
634
635 cxfree(data);
636
637 return (winprop_t) {
638 .data.p8 = NULL,
639 .nitems = 0,
640 .type = AnyPropertyType,
641 .format = 0
642 };
643 }
644
645 /**
646 * Check if a window has rounded corners.
647 */
648 static void
649 win_rounded_corners(session_t *ps, win *w) {
650 w->rounded_corners = false;
651
652 if (!w->bounding_shaped)
653 return;
654
655 // Fetch its bounding region
656 if (!w->border_size)
657 w->border_size = border_size(ps, w, true);
658
659 // Quit if border_size() returns None
660 if (!w->border_size)
661 return;
662
663 // Determine the minimum width/height of a rectangle that could mark
664 // a window as having rounded corners
665 unsigned short minwidth = max_i(w->widthb * (1 - ROUNDED_PERCENT),
666 w->widthb - ROUNDED_PIXELS);
667 unsigned short minheight = max_i(w->heightb * (1 - ROUNDED_PERCENT),
668 w->heightb - ROUNDED_PIXELS);
669
670 // Get the rectangles in the bounding region
671 int nrects = 0, i;
672 XRectangle *rects = XFixesFetchRegion(ps->dpy, w->border_size, &nrects);
673 if (!rects)
674 return;
675
676 // Look for a rectangle large enough for this window be considered
677 // having rounded corners
678 for (i = 0; i < nrects; ++i)
679 if (rects[i].width >= minwidth && rects[i].height >= minheight) {
680 w->rounded_corners = true;
681 break;
682 }
683
684 cxfree(rects);
685 }
686
687 /**
688 * Add a pattern to a condition linked list.
689 */
690 static bool
691 condlst_add(session_t *ps, c2_lptr_t **pcondlst, const char *pattern) {
692 if (!pattern)
693 return false;
694
695 #ifdef CONFIG_C2
696 if (!c2_parse(ps, pcondlst, pattern))
697 exit(1);
698 #else
699 printf_errfq(1, "(): Condition support not compiled in.");
700 #endif
701
702 return true;
703 }
704
705 /**
706 * Determine the event mask for a window.
707 */
708 static long
709 determine_evmask(session_t *ps, Window wid, win_evmode_t mode) {
710 long evmask = NoEventMask;
711 win *w = NULL;
712
713 // Check if it's a mapped frame window
714 if (WIN_EVMODE_FRAME == mode
715 || ((w = find_win(ps, wid)) && IsViewable == w->a.map_state)) {
716 evmask |= PropertyChangeMask;
717 if (ps->o.track_focus && !ps->o.use_ewmh_active_win)
718 evmask |= FocusChangeMask;
719 }
720
721 // Check if it's a mapped client window
722 if (WIN_EVMODE_CLIENT == mode
723 || ((w = find_toplevel(ps, wid)) && IsViewable == w->a.map_state)) {
724 if (ps->o.frame_opacity || ps->o.track_wdata || ps->track_atom_lst
725 || ps->o.detect_client_opacity)
726 evmask |= PropertyChangeMask;
727 }
728
729 return evmask;
730 }
731
732 /**
733 * Find out the WM frame of a client window by querying X.
734 *
735 * @param ps current session
736 * @param wid window ID
737 * @return struct _win object of the found window, NULL if not found
738 */
739 static win *
740 find_toplevel2(session_t *ps, Window wid) {
741 win *w = NULL;
742
743 // We traverse through its ancestors to find out the frame
744 while (wid && wid != ps->root && !(w = find_win(ps, wid))) {
745 Window troot;
746 Window parent;
747 Window *tchildren;
748 unsigned tnchildren;
749
750 // XQueryTree probably fails if you run compton when X is somehow
751 // initializing (like add it in .xinitrc). In this case
752 // just leave it alone.
753 if (!XQueryTree(ps->dpy, wid, &troot, &parent, &tchildren,
754 &tnchildren)) {
755 parent = 0;
756 break;
757 }
758
759 cxfree(tchildren);
760
761 wid = parent;
762 }
763
764 return w;
765 }
766
767 /**
768 * Recheck currently focused window and set its <code>w->focused</code>
769 * to true.
770 *
771 * @param ps current session
772 * @return struct _win of currently focused window, NULL if not found
773 */
774 static win *
775 recheck_focus(session_t *ps) {
776 // Use EWMH _NET_ACTIVE_WINDOW if enabled
777 if (ps->o.use_ewmh_active_win) {
778 update_ewmh_active_win(ps);
779 return ps->active_win;
780 }
781
782 // Determine the currently focused window so we can apply appropriate
783 // opacity on it
784 Window wid = 0;
785 int revert_to;
786
787 XGetInputFocus(ps->dpy, &wid, &revert_to);
788
789 win *w = find_win_all(ps, wid);
790
791 #ifdef DEBUG_EVENTS
792 print_timestamp(ps);
793 printf_dbgf("(): %#010lx (%#010lx \"%s\") focused.\n", wid,
794 (w ? w->id: None), (w ? w->name: NULL));
795 #endif
796
797 // And we set the focus state here
798 if (w) {
799 win_set_focused(ps, w, true);
800 return w;
801 }
802
803 return NULL;
804 }
805
806 static bool
807 get_root_tile(session_t *ps) {
808 /*
809 if (ps->o.paint_on_overlay) {
810 return ps->root_picture;
811 } */
812
813 assert(!ps->root_tile_paint.pixmap);
814 ps->root_tile_fill = false;
815
816 bool fill = false;
817 Pixmap pixmap = None;
818
819 // Get the values of background attributes
820 for (int p = 0; background_props_str[p]; p++) {
821 winprop_t prop = wid_get_prop(ps, ps->root,
822 get_atom(ps, background_props_str[p]),
823 1L, XA_PIXMAP, 32);
824 if (prop.nitems) {
825 pixmap = *prop.data.p32;
826 fill = false;
827 free_winprop(&prop);
828 break;
829 }
830 free_winprop(&prop);
831 }
832
833 // Make sure the pixmap we got is valid
834 if (pixmap && !validate_pixmap(ps, pixmap))
835 pixmap = None;
836
837 // Create a pixmap if there isn't any
838 if (!pixmap) {
839 pixmap = XCreatePixmap(ps->dpy, ps->root, 1, 1, ps->depth);
840 fill = true;
841 }
842
843 // Create Picture
844 {
845 XRenderPictureAttributes pa = {
846 .repeat = True,
847 };
848 ps->root_tile_paint.pict = XRenderCreatePicture(
849 ps->dpy, pixmap, XRenderFindVisualFormat(ps->dpy, ps->vis),
850 CPRepeat, &pa);
851 }
852
853 // Fill pixmap if needed
854 if (fill) {
855 XRenderColor c;
856
857 c.red = c.green = c.blue = 0x8080;
858 c.alpha = 0xffff;
859 XRenderFillRectangle(ps->dpy, PictOpSrc, ps->root_tile_paint.pict, &c, 0, 0, 1, 1);
860 }
861
862 ps->root_tile_fill = fill;
863 ps->root_tile_paint.pixmap = pixmap;
864 #ifdef CONFIG_VSYNC_OPENGL
865 if (BKEND_GLX == ps->o.backend)
866 return glx_bind_pixmap(ps, &ps->root_tile_paint.ptex, ps->root_tile_paint.pixmap, 0, 0, 0);
867 #endif
868
869 return true;
870 }
871
872 /**
873 * Paint root window content.
874 */
875 static void
876 paint_root(session_t *ps, XserverRegion reg_paint) {
877 if (!ps->root_tile_paint.pixmap)
878 get_root_tile(ps);
879
880 win_render(ps, NULL, 0, 0, ps->root_width, ps->root_height, 1.0, reg_paint,
881 NULL, ps->root_tile_paint.pict);
882 }
883
884 /**
885 * Get a rectangular region a window occupies, excluding shadow.
886 */
887 static XserverRegion
888 win_get_region(session_t *ps, win *w, bool use_offset) {
889 XRectangle r;
890
891 r.x = (use_offset ? w->a.x: 0);
892 r.y = (use_offset ? w->a.y: 0);
893 r.width = w->widthb;
894 r.height = w->heightb;
895
896 return XFixesCreateRegion(ps->dpy, &r, 1);
897 }
898
899 /**
900 * Get a rectangular region a window occupies, excluding frame and shadow.
901 */
902 static XserverRegion
903 win_get_region_noframe(session_t *ps, win *w, bool use_offset) {
904 const margin_t extents = win_calc_frame_extents(ps, w);
905 XRectangle r;
906
907 r.x = (use_offset ? w->a.x: 0) + extents.left;
908 r.y = (use_offset ? w->a.y: 0) + extents.top;
909 r.width = max_i(w->a.width - extents.left - extents.right, 0);
910 r.height = max_i(w->a.height - extents.top - extents.bottom, 0);
911
912 if (r.width > 0 && r.height > 0)
913 return XFixesCreateRegion(ps->dpy, &r, 1);
914 else
915 return XFixesCreateRegion(ps->dpy, NULL, 0);
916 }
917
918 /**
919 * Get a rectangular region a window (and possibly its shadow) occupies.
920 *
921 * Note w->shadow and shadow geometry must be correct before calling this
922 * function.
923 */
924 static XserverRegion
925 win_extents(session_t *ps, win *w) {
926 XRectangle r;
927
928 r.x = w->a.x;
929 r.y = w->a.y;
930 r.width = w->widthb;
931 r.height = w->heightb;
932
933 if (w->shadow) {
934 XRectangle sr;
935
936 sr.x = w->a.x + w->shadow_dx;
937 sr.y = w->a.y + w->shadow_dy;
938 sr.width = w->shadow_width;
939 sr.height = w->shadow_height;
940
941 if (sr.x < r.x) {
942 r.width = (r.x + r.width) - sr.x;
943 r.x = sr.x;
944 }
945
946 if (sr.y < r.y) {
947 r.height = (r.y + r.height) - sr.y;
948 r.y = sr.y;
949 }
950
951 if (sr.x + sr.width > r.x + r.width) {
952 r.width = sr.x + sr.width - r.x;
953 }
954
955 if (sr.y + sr.height > r.y + r.height) {
956 r.height = sr.y + sr.height - r.y;
957 }
958 }
959
960 return XFixesCreateRegion(ps->dpy, &r, 1);
961 }
962
963 /**
964 * Retrieve the bounding shape of a window.
965 */
966 static XserverRegion
967 border_size(session_t *ps, win *w, bool use_offset) {
968 // Start with the window rectangular region
969 XserverRegion fin = win_get_region(ps, w, use_offset);
970
971 // Only request for a bounding region if the window is shaped
972 if (w->bounding_shaped) {
973 /*
974 * if window doesn't exist anymore, this will generate an error
975 * as well as not generate a region. Perhaps a better XFixes
976 * architecture would be to have a request that copies instead
977 * of creates, that way you'd just end up with an empty region
978 * instead of an invalid XID.
979 */
980
981 XserverRegion border = XFixesCreateRegionFromWindow(
982 ps->dpy, w->id, WindowRegionBounding);
983
984 if (!border)
985 return fin;
986
987 if (use_offset) {
988 // Translate the region to the correct place
989 XFixesTranslateRegion(ps->dpy, border,
990 w->a.x + w->a.border_width,
991 w->a.y + w->a.border_width);
992 }
993
994 // Intersect the bounding region we got with the window rectangle, to
995 // make sure the bounding region is not bigger than the window
996 // rectangle
997 XFixesIntersectRegion(ps->dpy, fin, fin, border);
998 XFixesDestroyRegion(ps->dpy, border);
999 }
1000
1001 return fin;
1002 }
1003
1004 /**
1005 * Look for the client window of a particular window.
1006 */
1007 static Window
1008 find_client_win(session_t *ps, Window w) {
1009 if (wid_has_prop(ps, w, ps->atom_client)) {
1010 return w;
1011 }
1012
1013 Window *children;
1014 unsigned int nchildren;
1015 unsigned int i;
1016 Window ret = 0;
1017
1018 if (!wid_get_children(ps, w, &children, &nchildren)) {
1019 return 0;
1020 }
1021
1022 for (i = 0; i < nchildren; ++i) {
1023 if ((ret = find_client_win(ps, children[i])))
1024 break;
1025 }
1026
1027 cxfree(children);
1028
1029 return ret;
1030 }
1031
1032 /**
1033 * Retrieve frame extents from a window.
1034 */
1035 static void
1036 get_frame_extents(session_t *ps, win *w, Window client) {
1037 cmemzero_one(&w->frame_extents);
1038
1039 winprop_t prop = wid_get_prop(ps, client, ps->atom_frame_extents,
1040 4L, XA_CARDINAL, 32);
1041
1042 if (4 == prop.nitems) {
1043 const long * const extents = prop.data.p32;
1044 w->frame_extents.left = extents[0];
1045 w->frame_extents.right = extents[1];
1046 w->frame_extents.top = extents[2];
1047 w->frame_extents.bottom = extents[3];
1048
1049 if (ps->o.frame_opacity)
1050 update_reg_ignore_expire(ps, w);
1051 }
1052
1053 #ifdef DEBUG_FRAME
1054 printf_dbgf("(%#010lx): %d, %d, %d, %d\n", w->id,
1055 w->frame_extents.left, w->frame_extents.right,
1056 w->frame_extents.top, w->frame_extents.bottom);
1057 #endif
1058
1059 free_winprop(&prop);
1060 }
1061
1062 /**
1063 * Get alpha <code>Picture</code> for an opacity in <code>double</code>.
1064 */
1065 static inline Picture
1066 get_alpha_pict_d(session_t *ps, double o) {
1067 assert((round(normalize_d(o) / ps->o.alpha_step)) <= round(1.0 / ps->o.alpha_step));
1068 return ps->alpha_picts[(int) (round(normalize_d(o)
1069 / ps->o.alpha_step))];
1070 }
1071
1072 /**
1073 * Get alpha <code>Picture</code> for an opacity in
1074 * <code>opacity_t</code>.
1075 */
1076 static inline Picture
1077 get_alpha_pict_o(session_t *ps, opacity_t o) {
1078 return get_alpha_pict_d(ps, (double) o / OPAQUE);
1079 }
1080
1081 static win *
1082 paint_preprocess(session_t *ps, win *list) {
1083 win *t = NULL, *next = NULL;
1084
1085 // Fading step calculation
1086 time_ms_t steps = 0L;
1087 if (ps->fade_time) {
1088 steps = ((get_time_ms() - ps->fade_time) + FADE_DELTA_TOLERANCE * ps->o.fade_delta) / ps->o.fade_delta;
1089 }
1090 // Reset fade_time if unset, or there appears to be a time disorder
1091 if (!ps->fade_time || steps < 0L) {
1092 ps->fade_time = get_time_ms();
1093 steps = 0L;
1094 }
1095 ps->fade_time += steps * ps->o.fade_delta;
1096
1097 XserverRegion last_reg_ignore = None;
1098
1099 bool unredir_possible = false;
1100 // Trace whether it's the highest window to paint
1101 bool is_highest = true;
1102 for (win *w = list; w; w = next) {
1103 bool to_paint = true;
1104 const winmode_t mode_old = w->mode;
1105
1106 // In case calling the fade callback function destroys this window
1107 next = w->next;
1108 opacity_t opacity_old = w->opacity;
1109
1110 // Data expiration
1111 {
1112 // Remove built shadow if needed
1113 if (w->flags & WFLAG_SIZE_CHANGE)
1114 free_paint(ps, &w->shadow_paint);
1115
1116 // Destroy reg_ignore on all windows if they should expire
1117 if (ps->reg_ignore_expire)
1118 free_region(ps, &w->reg_ignore);
1119 }
1120
1121 // Restore flags from last paint if the window is being faded out
1122 if (IsUnmapped == w->a.map_state) {
1123 win_set_shadow(ps, w, w->shadow_last);
1124 w->fade = w->fade_last;
1125 win_set_invert_color(ps, w, w->invert_color_last);
1126 win_set_blur_background(ps, w, w->blur_background_last);
1127 }
1128
1129 // Update window opacity target and dim state if asked
1130 if (WFLAG_OPCT_CHANGE & w->flags) {
1131 calc_opacity(ps, w);
1132 calc_dim(ps, w);
1133 }
1134
1135 // Run fading
1136 run_fade(ps, w, steps);
1137
1138 // Opacity will not change, from now on.
1139
1140 // Give up if it's not damaged or invisible, or it's unmapped and its
1141 // pixmap is gone (for example due to a ConfigureNotify), or when it's
1142 // excluded
1143 if (!w->damaged
1144 || w->a.x + w->a.width < 1 || w->a.y + w->a.height < 1
1145 || w->a.x >= ps->root_width || w->a.y >= ps->root_height
1146 || ((IsUnmapped == w->a.map_state || w->destroyed) && !w->paint.pixmap)
1147 || get_alpha_pict_o(ps, w->opacity) == ps->alpha_picts[0]
1148 || w->paint_excluded)
1149 to_paint = false;
1150
1151 // to_paint will never change afterward
1152
1153 // Determine mode as early as possible
1154 if (to_paint && (!w->to_paint || w->opacity != opacity_old))
1155 win_determine_mode(ps, w);
1156
1157 if (to_paint) {
1158 // Fetch bounding region
1159 if (!w->border_size)
1160 w->border_size = border_size(ps, w, true);
1161
1162 // Fetch window extents
1163 if (!w->extents)
1164 w->extents = win_extents(ps, w);
1165
1166 // Calculate frame_opacity
1167 {
1168 double frame_opacity_old = w->frame_opacity;
1169
1170 if (ps->o.frame_opacity && 1.0 != ps->o.frame_opacity
1171 && win_has_frame(w))
1172 w->frame_opacity = get_opacity_percent(w) *
1173 ps->o.frame_opacity;
1174 else
1175 w->frame_opacity = 0.0;
1176
1177 // Destroy all reg_ignore above when frame opaque state changes on
1178 // SOLID mode
1179 if (w->to_paint && WMODE_SOLID == mode_old
1180 && (0.0 == frame_opacity_old) != (0.0 == w->frame_opacity))
1181 ps->reg_ignore_expire = true;
1182 }
1183
1184 // Calculate shadow opacity
1185 if (w->frame_opacity)
1186 w->shadow_opacity = ps->o.shadow_opacity * w->frame_opacity;
1187 else
1188 w->shadow_opacity = ps->o.shadow_opacity * get_opacity_percent(w);
1189 }
1190
1191 // Add window to damaged area if its painting status changes
1192 // or opacity changes
1193 if (to_paint != w->to_paint || w->opacity != opacity_old)
1194 add_damage_win(ps, w);
1195
1196 // Destroy all reg_ignore above when window mode changes
1197 if ((to_paint && WMODE_SOLID == w->mode)
1198 != (w->to_paint && WMODE_SOLID == mode_old))
1199 ps->reg_ignore_expire = true;
1200
1201 if (to_paint) {
1202 // Generate ignore region for painting to reduce GPU load
1203 if (ps->reg_ignore_expire || !w->to_paint) {
1204 free_region(ps, &w->reg_ignore);
1205
1206 // If the window is solid, we add the window region to the
1207 // ignored region
1208 if (win_is_solid(ps, w)) {
1209 if (!w->frame_opacity) {
1210 if (w->border_size)
1211 w->reg_ignore = copy_region(ps, w->border_size);
1212 else
1213 w->reg_ignore = win_get_region(ps, w, true);
1214 }
1215 else {
1216 w->reg_ignore = win_get_region_noframe(ps, w, true);
1217 if (w->border_size)
1218 XFixesIntersectRegion(ps->dpy, w->reg_ignore, w->reg_ignore,
1219 w->border_size);
1220 }
1221
1222 if (last_reg_ignore)
1223 XFixesUnionRegion(ps->dpy, w->reg_ignore, w->reg_ignore,
1224 last_reg_ignore);
1225 }
1226 // Otherwise we copy the last region over
1227 else if (last_reg_ignore)
1228 w->reg_ignore = copy_region(ps, last_reg_ignore);
1229 else
1230 w->reg_ignore = None;
1231 }
1232
1233 last_reg_ignore = w->reg_ignore;
1234
1235 // (Un)redirect screen
1236 // We could definitely unredirect the screen when there's no window to
1237 // paint, but this is typically unnecessary, may cause flickering when
1238 // fading is enabled, and could create inconsistency when the wallpaper
1239 // is not correctly set.
1240 if (ps->o.unredir_if_possible && is_highest && to_paint) {
1241 is_highest = false;
1242 if (win_is_solid(ps, w)
1243 && (!w->frame_opacity || !win_has_frame(w))
1244 && win_is_fullscreen(ps, w)
1245 && !w->unredir_if_possible_excluded)
1246 unredir_possible = true;
1247 }
1248
1249 // Reset flags
1250 w->flags = 0;
1251 }
1252
1253 // Avoid setting w->to_paint if w is to be freed
1254 bool destroyed = (w->opacity_tgt == w->opacity && w->destroyed);
1255
1256 if (to_paint) {
1257 w->prev_trans = t;
1258 t = w;
1259 }
1260 else {
1261 assert(w->destroyed == (w->fade_callback == destroy_callback));
1262 check_fade_fin(ps, w);
1263 }
1264
1265 if (!destroyed) {
1266 w->to_paint = to_paint;
1267
1268 if (w->to_paint) {
1269 // Save flags
1270 w->shadow_last = w->shadow;
1271 w->fade_last = w->fade;
1272 w->invert_color_last = w->invert_color;
1273 w->blur_background_last = w->blur_background;
1274 }
1275 }
1276 }
1277
1278
1279 // If possible, unredirect all windows and stop painting
1280 if (UNSET != ps->o.redirected_force)
1281 unredir_possible = !ps->o.redirected_force;
1282
1283 // If there's no window to paint, and the screen isn't redirected,
1284 // don't redirect it.
1285 if (ps->o.unredir_if_possible && is_highest && !ps->redirected)
1286 unredir_possible = true;
1287 if (unredir_possible) {
1288 if (ps->redirected) {
1289 if (!ps->o.unredir_if_possible_delay || ps->tmout_unredir_hit)
1290 redir_stop(ps);
1291 else if (!ps->tmout_unredir->enabled) {
1292 timeout_reset(ps, ps->tmout_unredir);
1293 ps->tmout_unredir->enabled = true;
1294 }
1295 }
1296 }
1297 else {
1298 ps->tmout_unredir->enabled = false;
1299 redir_start(ps);
1300 }
1301
1302 return t;
1303 }
1304
1305 /**
1306 * Paint the shadow of a window.
1307 */
1308 static inline void
1309 win_paint_shadow(session_t *ps, win *w,
1310 XserverRegion reg_paint, const reg_data_t *pcache_reg) {
1311 // Bind shadow pixmap to GLX texture if needed
1312 paint_bind_tex(ps, &w->shadow_paint, 0, 0, 32, false);
1313
1314 if (!paint_isvalid(ps, &w->shadow_paint)) {
1315 printf_errf("(%#010lx): Missing painting data. This is a bad sign.", w->id);
1316 return;
1317 }
1318
1319 render(ps, 0, 0, w->a.x + w->shadow_dx, w->a.y + w->shadow_dy,
1320 w->shadow_width, w->shadow_height, w->shadow_opacity, true, false,
1321 w->shadow_paint.pict, w->shadow_paint.ptex, reg_paint, pcache_reg, NULL);
1322 }
1323
1324 /**
1325 * Create an picture.
1326 */
1327 static inline Picture
1328 xr_build_picture(session_t *ps, int wid, int hei,
1329 XRenderPictFormat *pictfmt) {
1330 if (!pictfmt)
1331 pictfmt = XRenderFindVisualFormat(ps->dpy, ps->vis);
1332
1333 int depth = pictfmt->depth;
1334
1335 Pixmap tmp_pixmap = XCreatePixmap(ps->dpy, ps->root, wid, hei, depth);
1336 if (!tmp_pixmap)
1337 return None;
1338
1339 Picture tmp_picture = XRenderCreatePicture(ps->dpy, tmp_pixmap,
1340 pictfmt, 0, 0);
1341 free_pixmap(ps, &tmp_pixmap);
1342
1343 return tmp_picture;
1344 }
1345
1346 /**
1347 * @brief Blur an area on a buffer.
1348 *
1349 * @param ps current session
1350 * @param tgt_buffer a buffer as both source and destination
1351 * @param x x pos
1352 * @param y y pos
1353 * @param wid width
1354 * @param hei height
1355 * @param blur_kerns blur kernels, ending with a NULL, guaranteed to have at
1356 * least one kernel
1357 * @param reg_clip a clipping region to be applied on intermediate buffers
1358 *
1359 * @return true if successful, false otherwise
1360 */
1361 static bool
1362 xr_blur_dst(session_t *ps, Picture tgt_buffer,
1363 int x, int y, int wid, int hei, XFixed **blur_kerns,
1364 XserverRegion reg_clip) {
1365 assert(blur_kerns[0]);
1366
1367 // Directly copying from tgt_buffer to it does not work, so we create a
1368 // Picture in the middle.
1369 Picture tmp_picture = xr_build_picture(ps, wid, hei, NULL);
1370
1371 if (!tmp_picture) {
1372 printf_errf("(): Failed to build intermediate Picture.");
1373 return false;
1374 }
1375
1376 if (reg_clip && tmp_picture)
1377 XFixesSetPictureClipRegion(ps->dpy, tmp_picture, reg_clip, 0, 0);
1378
1379 Picture src_pict = tgt_buffer, dst_pict = tmp_picture;
1380 for (int i = 0; blur_kerns[i]; ++i) {
1381 assert(i < MAX_BLUR_PASS - 1);
1382 XFixed *convolution_blur = blur_kerns[i];
1383 int kwid = XFixedToDouble(convolution_blur[0]),
1384 khei = XFixedToDouble(convolution_blur[1]);
1385 bool rd_from_tgt = (tgt_buffer == src_pict);
1386
1387 // Copy from source picture to destination. The filter must
1388 // be applied on source picture, to get the nearby pixels outside the
1389 // window.
1390 XRenderSetPictureFilter(ps->dpy, src_pict, XRFILTER_CONVOLUTION,
1391 convolution_blur, kwid * khei + 2);
1392 XRenderComposite(ps->dpy, PictOpSrc, src_pict, None, dst_pict,
1393 (rd_from_tgt ? x: 0), (rd_from_tgt ? y: 0), 0, 0,
1394 (rd_from_tgt ? 0: x), (rd_from_tgt ? 0: y), wid, hei);
1395 xrfilter_reset(ps, src_pict);
1396
1397 {
1398 XserverRegion tmp = src_pict;
1399 src_pict = dst_pict;
1400 dst_pict = tmp;
1401 }
1402 }
1403
1404 if (src_pict != tgt_buffer)
1405 XRenderComposite(ps->dpy, PictOpSrc, src_pict, None, tgt_buffer,
1406 0, 0, 0, 0, x, y, wid, hei);
1407
1408 free_picture(ps, &tmp_picture);
1409
1410 return true;
1411 }
1412
1413 /*
1414 * WORK-IN-PROGRESS!
1415 static void
1416 xr_take_screenshot(session_t *ps) {
1417 XImage *img = XGetImage(ps->dpy, get_tgt_window(ps), 0, 0,
1418 ps->root_width, ps->root_height, AllPlanes, XYPixmap);
1419 if (!img) {
1420 printf_errf("(): Failed to get XImage.");
1421 return NULL;
1422 }
1423 assert(0 == img->xoffset);
1424 }
1425 */
1426
1427 /**
1428 * Blur the background of a window.
1429 */
1430 static inline void
1431 win_blur_background(session_t *ps, win *w, Picture tgt_buffer,
1432 XserverRegion reg_paint, const reg_data_t *pcache_reg) {
1433 const int x = w->a.x;
1434 const int y = w->a.y;
1435 const int wid = w->widthb;
1436 const int hei = w->heightb;
1437
1438 double factor_center = 1.0;
1439 // Adjust blur strength according to window opacity, to make it appear
1440 // better during fading
1441 if (!ps->o.blur_background_fixed) {
1442 double pct = 1.0 - get_opacity_percent(w) * (1.0 - 1.0 / 9.0);
1443 factor_center = pct * 8.0 / (1.1 - pct);
1444 }
1445
1446 switch (ps->o.backend) {
1447 case BKEND_XRENDER:
1448 case BKEND_XR_GLX_HYBRID:
1449 {
1450 // Normalize blur kernels
1451 for (int i = 0; i < MAX_BLUR_PASS; ++i) {
1452 XFixed *kern_src = ps->o.blur_kerns[i];
1453 XFixed *kern_dst = ps->blur_kerns_cache[i];
1454 assert(i < MAX_BLUR_PASS);
1455 if (!kern_src) {
1456 assert(!kern_dst);
1457 break;
1458 }
1459
1460 assert(!kern_dst
1461 || (kern_src[0] == kern_dst[0] && kern_src[1] == kern_dst[1]));
1462
1463 // Skip for fixed factor_center if the cache exists already
1464 if (ps->o.blur_background_fixed && kern_dst) continue;
1465
1466 int kwid = XFixedToDouble(kern_src[0]),
1467 khei = XFixedToDouble(kern_src[1]);
1468
1469 // Allocate cache space if needed
1470 if (!kern_dst) {
1471 kern_dst = malloc((kwid * khei + 2) * sizeof(XFixed));
1472 if (!kern_dst) {
1473 printf_errf("(): Failed to allocate memory for blur kernel.");
1474 return;
1475 }
1476 ps->blur_kerns_cache[i] = kern_dst;
1477 }
1478
1479 // Modify the factor of the center pixel
1480 kern_src[2 + (khei / 2) * kwid + kwid / 2] =
1481 XDoubleToFixed(factor_center);
1482
1483 // Copy over
1484 memcpy(kern_dst, kern_src, (kwid * khei + 2) * sizeof(XFixed));
1485 normalize_conv_kern(kwid, khei, kern_dst + 2);
1486 }
1487
1488 // Minimize the region we try to blur, if the window itself is not
1489 // opaque, only the frame is.
1490 XserverRegion reg_noframe = None;
1491 if (win_is_solid(ps, w)) {
1492 XserverRegion reg_all = border_size(ps, w, false);
1493 reg_noframe = win_get_region_noframe(ps, w, false);
1494 XFixesSubtractRegion(ps->dpy, reg_noframe, reg_all, reg_noframe);
1495 free_region(ps, &reg_all);
1496 }
1497 xr_blur_dst(ps, tgt_buffer, x, y, wid, hei, ps->blur_kerns_cache,
1498 reg_noframe);
1499 free_region(ps, &reg_noframe);
1500 }
1501 break;
1502 #ifdef CONFIG_VSYNC_OPENGL_GLSL
1503 case BKEND_GLX:
1504 // TODO: Handle frame opacity
1505 glx_blur_dst(ps, x, y, wid, hei, ps->psglx->z - 0.5, factor_center,
1506 reg_paint, pcache_reg, &w->glx_blur_cache);
1507 break;
1508 #endif
1509 default:
1510 assert(0);
1511 }
1512 }
1513
1514 static void
1515 render_(session_t *ps, int x, int y, int dx, int dy, int wid, int hei,
1516 double opacity, bool argb, bool neg,
1517 Picture pict, glx_texture_t *ptex,
1518 XserverRegion reg_paint, const reg_data_t *pcache_reg
1519 #ifdef CONFIG_VSYNC_OPENGL_GLSL
1520 , const glx_prog_main_t *pprogram
1521 #endif
1522 ) {
1523 switch (ps->o.backend) {
1524 case BKEND_XRENDER:
1525 case BKEND_XR_GLX_HYBRID:
1526 {
1527 Picture alpha_pict = get_alpha_pict_d(ps, opacity);
1528 if (alpha_pict != ps->alpha_picts[0]) {
1529 int op = ((!argb && !alpha_pict) ? PictOpSrc: PictOpOver);
1530 XRenderComposite(ps->dpy, op, pict, alpha_pict,
1531 ps->tgt_buffer.pict, x, y, 0, 0, dx, dy, wid, hei);
1532 }
1533 break;
1534 }
1535 #ifdef CONFIG_VSYNC_OPENGL
1536 case BKEND_GLX:
1537 glx_render(ps, ptex, x, y, dx, dy, wid, hei,
1538 ps->psglx->z, opacity, argb, neg, reg_paint, pcache_reg, pprogram);
1539 ps->psglx->z += 1;
1540 break;
1541 #endif
1542 default:
1543 assert(0);
1544 }
1545 }
1546
1547 /**
1548 * Paint a window itself and dim it if asked.
1549 */
1550 static inline void
1551 win_paint_win(session_t *ps, win *w, XserverRegion reg_paint,
1552 const reg_data_t *pcache_reg) {
1553 glx_mark(ps, w->id, true);
1554
1555 // Fetch Pixmap
1556 if (!w->paint.pixmap && ps->has_name_pixmap) {
1557 set_ignore_next(ps);
1558 w->paint.pixmap = XCompositeNameWindowPixmap(ps->dpy, w->id);
1559 if (w->paint.pixmap)
1560 free_fence(ps, &w->fence);
1561 }
1562
1563 Drawable draw = w->paint.pixmap;
1564 if (!draw)
1565 draw = w->id;
1566
1567 // XRender: Build picture
1568 if (bkend_use_xrender(ps) && !w->paint.pict) {
1569 {
1570 XRenderPictureAttributes pa = {
1571 .subwindow_mode = IncludeInferiors,
1572 };
1573
1574 w->paint.pict = XRenderCreatePicture(ps->dpy, draw, w->pictfmt,
1575 CPSubwindowMode, &pa);
1576 }
1577 }
1578
1579 if (IsViewable == w->a.map_state)
1580 xr_sync(ps, draw, &w->fence);
1581
1582 // GLX: Build texture
1583 // Let glx_bind_pixmap() determine pixmap size, because if the user
1584 // is resizing windows, the width and height we get may not be up-to-date,
1585 // causing the jittering issue M4he reported in #7.
1586 if (!paint_bind_tex(ps, &w->paint, 0, 0, 0,
1587 (!ps->o.glx_no_rebind_pixmap && w->pixmap_damaged))) {
1588 printf_errf("(%#010lx): Failed to bind texture. Expect troubles.", w->id);
1589 }
1590 w->pixmap_damaged = false;
1591
1592 if (!paint_isvalid(ps, &w->paint)) {
1593 printf_errf("(%#010lx): Missing painting data. This is a bad sign.", w->id);
1594 return;
1595 }
1596
1597 const int x = w->a.x;
1598 const int y = w->a.y;
1599 const int wid = w->widthb;
1600 const int hei = w->heightb;
1601
1602 Picture pict = w->paint.pict;
1603
1604 // Invert window color, if required
1605 if (bkend_use_xrender(ps) && w->invert_color) {
1606 Picture newpict = xr_build_picture(ps, wid, hei, w->pictfmt);
1607 if (newpict) {
1608 // Apply clipping region to save some CPU
1609 if (reg_paint) {
1610 XserverRegion reg = copy_region(ps, reg_paint);
1611 XFixesTranslateRegion(ps->dpy, reg, -x, -y);
1612 XFixesSetPictureClipRegion(ps->dpy, newpict, 0, 0, reg);
1613 free_region(ps, &reg);
1614 }
1615
1616 XRenderComposite(ps->dpy, PictOpSrc, pict, None,
1617 newpict, 0, 0, 0, 0, 0, 0, wid, hei);
1618 XRenderComposite(ps->dpy, PictOpDifference, ps->white_picture, None,
1619 newpict, 0, 0, 0, 0, 0, 0, wid, hei);
1620 // We use an extra PictOpInReverse operation to get correct pixel
1621 // alpha. There could be a better solution.
1622 if (WMODE_ARGB == w->mode)
1623 XRenderComposite(ps->dpy, PictOpInReverse, pict, None,
1624 newpict, 0, 0, 0, 0, 0, 0, wid, hei);
1625 pict = newpict;
1626 }
1627 }
1628
1629 const double dopacity = get_opacity_percent(w);
1630
1631 if (!w->frame_opacity) {
1632 win_render(ps, w, 0, 0, wid, hei, dopacity, reg_paint, pcache_reg, pict);
1633 }
1634 else {
1635 // Painting parameters
1636 const margin_t extents = win_calc_frame_extents(ps, w);
1637 const int t = extents.top;
1638 const int l = extents.left;
1639 const int b = extents.bottom;
1640 const int r = extents.right;
1641
1642 #define COMP_BDR(cx, cy, cwid, chei) \
1643 win_render(ps, w, (cx), (cy), (cwid), (chei), w->frame_opacity, \
1644 reg_paint, pcache_reg, pict)
1645
1646 // The following complicated logic is required because some broken
1647 // window managers (I'm talking about you, Openbox!) that makes
1648 // top_width + bottom_width > height in some cases.
1649
1650 // top
1651 int phei = min_i(t, hei);
1652 if (phei > 0)
1653 COMP_BDR(0, 0, wid, phei);
1654
1655 if (hei > t) {
1656 phei = min_i(hei - t, b);
1657
1658 // bottom
1659 if (phei > 0)
1660 COMP_BDR(0, hei - phei, wid, phei);
1661
1662 phei = hei - t - phei;
1663 if (phei > 0) {
1664 int pwid = min_i(l, wid);
1665 // left
1666 if (pwid > 0)
1667 COMP_BDR(0, t, pwid, phei);
1668
1669 if (wid > l) {
1670 pwid = min_i(wid - l, r);
1671
1672 // right
1673 if (pwid > 0)
1674 COMP_BDR(wid - pwid, t, pwid, phei);
1675
1676 pwid = wid - l - pwid;
1677 if (pwid > 0) {
1678 // body
1679 win_render(ps, w, l, t, pwid, phei, dopacity, reg_paint, pcache_reg, pict);
1680 }
1681 }
1682 }
1683 }
1684 }
1685
1686 #undef COMP_BDR
1687
1688 if (pict != w->paint.pict)
1689 free_picture(ps, &pict);
1690
1691 // Dimming the window if needed
1692 if (w->dim) {
1693 double dim_opacity = ps->o.inactive_dim;
1694 if (!ps->o.inactive_dim_fixed)
1695 dim_opacity *= get_opacity_percent(w);
1696
1697 switch (ps->o.backend) {
1698 case BKEND_XRENDER:
1699 case BKEND_XR_GLX_HYBRID:
1700 {
1701 unsigned short cval = 0xffff * dim_opacity;
1702
1703 // Premultiply color
1704 XRenderColor color = {
1705 .red = 0, .green = 0, .blue = 0, .alpha = cval,
1706 };
1707
1708 XRectangle rect = {
1709 .x = x,
1710 .y = y,
1711 .width = wid,
1712 .height = hei,
1713 };
1714
1715 XRenderFillRectangles(ps->dpy, PictOpOver, ps->tgt_buffer.pict,
1716 &color, &rect, 1);
1717 }
1718 break;
1719 #ifdef CONFIG_VSYNC_OPENGL
1720 case BKEND_GLX:
1721 glx_dim_dst(ps, x, y, wid, hei, ps->psglx->z - 0.7, dim_opacity,
1722 reg_paint, pcache_reg);
1723 break;
1724 #endif
1725 default:
1726 assert(false);
1727 }
1728 }
1729
1730 glx_mark(ps, w->id, false);
1731 }
1732
1733 /**
1734 * Rebuild cached <code>screen_reg</code>.
1735 */
1736 static void
1737 rebuild_screen_reg(session_t *ps) {
1738 if (ps->screen_reg)
1739 XFixesDestroyRegion(ps->dpy, ps->screen_reg);
1740 ps->screen_reg = get_screen_region(ps);
1741 }
1742
1743 /**
1744 * Rebuild <code>shadow_exclude_reg</code>.
1745 */
1746 static void
1747 rebuild_shadow_exclude_reg(session_t *ps) {
1748 free_region(ps, &ps->shadow_exclude_reg);
1749 XRectangle rect = geom_to_rect(ps, &ps->o.shadow_exclude_reg_geom, NULL);
1750 ps->shadow_exclude_reg = rect_to_reg(ps, &rect);
1751 }
1752
1753 static void
1754 paint_all(session_t *ps, XserverRegion region, XserverRegion region_real, win *t) {
1755 if (!region_real)
1756 region_real = region;
1757
1758 #ifdef DEBUG_REPAINT
1759 static struct timespec last_paint = { 0 };
1760 #endif
1761 XserverRegion reg_paint = None, reg_tmp = None, reg_tmp2 = None;
1762
1763 #ifdef CONFIG_VSYNC_OPENGL
1764 if (bkend_use_glx(ps)) {
1765 glx_paint_pre(ps, &region);
1766 }
1767 #endif
1768
1769 if (!region) {
1770 region_real = region = get_screen_region(ps);
1771 }
1772 else {
1773 // Remove the damaged area out of screen
1774 XFixesIntersectRegion(ps->dpy, region, region, ps->screen_reg);
1775 }
1776
1777 #ifdef MONITOR_REPAINT
1778 // Note: MONITOR_REPAINT cannot work with DBE right now.
1779 // Picture old_tgt_buffer = ps->tgt_buffer.pict;
1780 ps->tgt_buffer.pict = ps->tgt_picture;
1781 #else
1782 if (!paint_isvalid(ps, &ps->tgt_buffer)) {
1783 // DBE painting mode: Directly paint to a Picture of the back buffer
1784 if (BKEND_XRENDER == ps->o.backend && ps->o.dbe) {
1785 ps->tgt_buffer.pict = XRenderCreatePicture(ps->dpy, ps->root_dbe,
1786 XRenderFindVisualFormat(ps->dpy, ps->vis),
1787 0, 0);
1788 }
1789 // No-DBE painting mode: Paint to an intermediate Picture then paint
1790 // the Picture to root window
1791 else {
1792 if (!ps->tgt_buffer.pixmap) {
1793 free_paint(ps, &ps->tgt_buffer);
1794 ps->tgt_buffer.pixmap = XCreatePixmap(ps->dpy, ps->root,
1795 ps->root_width, ps->root_height, ps->depth);
1796 }
1797
1798 if (BKEND_GLX != ps->o.backend)
1799 ps->tgt_buffer.pict = XRenderCreatePicture(ps->dpy,
1800 ps->tgt_buffer.pixmap, XRenderFindVisualFormat(ps->dpy, ps->vis),
1801 0, 0);
1802 }
1803 }
1804 #endif
1805
1806 if (BKEND_XRENDER == ps->o.backend)
1807 XFixesSetPictureClipRegion(ps->dpy, ps->tgt_picture, 0, 0, region_real);
1808
1809 #ifdef MONITOR_REPAINT
1810 switch (ps->o.backend) {
1811 case BKEND_XRENDER:
1812 XRenderComposite(ps->dpy, PictOpSrc, ps->black_picture, None,
1813 ps->tgt_picture, 0, 0, 0, 0, 0, 0,
1814 ps->root_width, ps->root_height);
1815 break;
1816 case BKEND_GLX:
1817 case BKEND_XR_GLX_HYBRID:
1818 glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
1819 glClear(GL_COLOR_BUFFER_BIT);
1820 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
1821 break;
1822 }
1823 #endif
1824
1825 if (t && t->reg_ignore) {
1826 // Calculate the region upon which the root window is to be painted
1827 // based on the ignore region of the lowest window, if available
1828 reg_paint = reg_tmp = XFixesCreateRegion(ps->dpy, NULL, 0);
1829 XFixesSubtractRegion(ps->dpy, reg_paint, region, t->reg_ignore);
1830 }
1831 else {
1832 reg_paint = region;
1833 }
1834
1835 set_tgt_clip(ps, reg_paint, NULL);
1836 paint_root(ps, reg_paint);
1837
1838 // Create temporary regions for use during painting
1839 if (!reg_tmp)
1840 reg_tmp = XFixesCreateRegion(ps->dpy, NULL, 0);
1841 reg_tmp2 = XFixesCreateRegion(ps->dpy, NULL, 0);
1842
1843 for (win *w = t; w; w = w->prev_trans) {
1844 // Painting shadow
1845 if (w->shadow) {
1846 // Lazy shadow building
1847 if (!w->shadow_paint.pixmap)
1848 win_build_shadow(ps, w, 1);
1849
1850 // Shadow is to be painted based on the ignore region of current
1851 // window
1852 if (w->reg_ignore) {
1853 if (w == t) {
1854 // If it's the first cycle and reg_tmp2 is not ready, calculate
1855 // the paint region here
1856 reg_paint = reg_tmp;
1857 XFixesSubtractRegion(ps->dpy, reg_paint, region, w->reg_ignore);
1858 }
1859 else {
1860 // Otherwise, used the cached region during last cycle
1861 reg_paint = reg_tmp2;
1862 }
1863 XFixesIntersectRegion(ps->dpy, reg_paint, reg_paint, w->extents);
1864 }
1865 else {
1866 reg_paint = reg_tmp;
1867 XFixesIntersectRegion(ps->dpy, reg_paint, region, w->extents);
1868 }
1869
1870 if (ps->shadow_exclude_reg)
1871 XFixesSubtractRegion(ps->dpy, reg_paint, reg_paint,
1872 ps->shadow_exclude_reg);
1873
1874 // Might be worthwhile to crop the region to shadow border
1875 {
1876 XRectangle rec_shadow_border = {
1877 .x = w->a.x + w->shadow_dx,
1878 .y = w->a.y + w->shadow_dy,
1879 .width = w->shadow_width,
1880 .height = w->shadow_height
1881 };
1882 XserverRegion reg_shadow = XFixesCreateRegion(ps->dpy,
1883 &rec_shadow_border, 1);
1884 XFixesIntersectRegion(ps->dpy, reg_paint, reg_paint, reg_shadow);
1885 free_region(ps, &reg_shadow);
1886 }
1887
1888 // Clear the shadow here instead of in make_shadow() for saving GPU
1889 // power and handling shaped windows
1890 if (ps->o.clear_shadow && w->border_size)
1891 XFixesSubtractRegion(ps->dpy, reg_paint, reg_paint, w->border_size);
1892
1893 #ifdef CONFIG_XINERAMA
1894 if (ps->o.xinerama_shadow_crop && w->xinerama_scr >= 0)
1895 XFixesIntersectRegion(ps->dpy, reg_paint, reg_paint,
1896 ps->xinerama_scr_regs[w->xinerama_scr]);
1897 #endif
1898
1899 // Detect if the region is empty before painting
1900 {
1901 reg_data_t cache_reg = REG_DATA_INIT;
1902 if (region == reg_paint
1903 || !is_region_empty(ps, reg_paint, &cache_reg)) {
1904 set_tgt_clip(ps, reg_paint, &cache_reg);
1905
1906 win_paint_shadow(ps, w, reg_paint, &cache_reg);
1907 }
1908 free_reg_data(&cache_reg);
1909 }
1910 }
1911
1912 // Calculate the region based on the reg_ignore of the next (higher)
1913 // window and the bounding region
1914 reg_paint = reg_tmp;
1915 if (w->prev_trans && w->prev_trans->reg_ignore) {
1916 XFixesSubtractRegion(ps->dpy, reg_paint, region,
1917 w->prev_trans->reg_ignore);
1918 // Copy the subtracted region to be used for shadow painting in next
1919 // cycle
1920 XFixesCopyRegion(ps->dpy, reg_tmp2, reg_paint);
1921
1922 if (w->border_size)
1923 XFixesIntersectRegion(ps->dpy, reg_paint, reg_paint, w->border_size);
1924 }
1925 else {
1926 if (w->border_size)
1927 XFixesIntersectRegion(ps->dpy, reg_paint, region, w->border_size);
1928 else
1929 reg_paint = region;
1930 }
1931
1932 {
1933 reg_data_t cache_reg = REG_DATA_INIT;
1934 if (!is_region_empty(ps, reg_paint, &cache_reg)) {
1935 set_tgt_clip(ps, reg_paint, &cache_reg);
1936 // Blur window background
1937 if (w->blur_background && (!win_is_solid(ps, w)
1938 || (ps->o.blur_background_frame && w->frame_opacity))) {
1939 win_blur_background(ps, w, ps->tgt_buffer.pict, reg_paint, &cache_reg);
1940 }
1941
1942 // Painting the window
1943 win_paint_win(ps, w, reg_paint, &cache_reg);
1944 }
1945 free_reg_data(&cache_reg);
1946 }
1947 }
1948
1949 // Free up all temporary regions
1950 XFixesDestroyRegion(ps->dpy, reg_tmp);
1951 XFixesDestroyRegion(ps->dpy, reg_tmp2);
1952
1953 // Do this as early as possible
1954 if (!ps->o.dbe)
1955 set_tgt_clip(ps, None, NULL);
1956
1957 if (ps->o.vsync) {
1958 // Make sure all previous requests are processed to achieve best
1959 // effect
1960 XSync(ps->dpy, False);
1961 #ifdef CONFIG_VSYNC_OPENGL
1962 if (glx_has_context(ps)) {
1963 if (ps->o.vsync_use_glfinish)
1964 glFinish();
1965 else
1966 glFlush();
1967 glXWaitX();
1968 }
1969 #endif
1970 }
1971
1972 // Wait for VBlank. We could do it aggressively (send the painting
1973 // request and XFlush() on VBlank) or conservatively (send the request
1974 // only on VBlank).
1975 if (!ps->o.vsync_aggressive)
1976 vsync_wait(ps);
1977
1978 switch (ps->o.backend) {
1979 case BKEND_XRENDER:
1980 // DBE painting mode, only need to swap the buffer
1981 if (ps->o.dbe) {
1982 XdbeSwapInfo swap_info = {
1983 .swap_window = get_tgt_window(ps),
1984 // Is it safe to use XdbeUndefined?
1985 .swap_action = XdbeCopied
1986 };
1987 XdbeSwapBuffers(ps->dpy, &swap_info, 1);
1988 }
1989 // No-DBE painting mode
1990 else if (ps->tgt_buffer.pict != ps->tgt_picture) {
1991 XRenderComposite(
1992 ps->dpy, PictOpSrc, ps->tgt_buffer.pict, None,
1993 ps->tgt_picture, 0, 0, 0, 0,
1994 0, 0, ps->root_width, ps->root_height);
1995 }
1996 break;
1997 #ifdef CONFIG_VSYNC_OPENGL
1998 case BKEND_XR_GLX_HYBRID:
1999 XSync(ps->dpy, False);
2000 if (ps->o.vsync_use_glfinish)
2001 glFinish();
2002 else
2003 glFlush();
2004 glXWaitX();
2005 assert(ps->tgt_buffer.pixmap);
2006 xr_sync(ps, ps->tgt_buffer.pixmap, &ps->tgt_buffer_fence);
2007 paint_bind_tex_real(ps, &ps->tgt_buffer,
2008 ps->root_width, ps->root_height, ps->depth,
2009 !ps->o.glx_no_rebind_pixmap);
2010 // See #163
2011 xr_sync(ps, ps->tgt_buffer.pixmap, &ps->tgt_buffer_fence);
2012 if (ps->o.vsync_use_glfinish)
2013 glFinish();
2014 else
2015 glFlush();
2016 glXWaitX();
2017 glx_render(ps, ps->tgt_buffer.ptex, 0, 0, 0, 0,
2018 ps->root_width, ps->root_height, 0, 1.0, false, false,
2019 region_real, NULL, NULL);
2020 // falls through
2021 case BKEND_GLX:
2022 if (ps->o.glx_use_copysubbuffermesa)
2023 glx_swap_copysubbuffermesa(ps, region_real);
2024 else
2025 glXSwapBuffers(ps->dpy, get_tgt_window(ps));
2026 break;
2027 #endif
2028 default:
2029 assert(0);
2030 }
2031 glx_mark_frame(ps);
2032
2033 if (ps->o.vsync_aggressive)
2034 vsync_wait(ps);
2035
2036 XFlush(ps->dpy);
2037
2038 #ifdef CONFIG_VSYNC_OPENGL
2039 if (glx_has_context(ps)) {
2040 glFlush();
2041 glXWaitX();
2042 }
2043 #endif
2044
2045 XFixesDestroyRegion(ps->dpy, region);
2046
2047 #ifdef DEBUG_REPAINT
2048 print_timestamp(ps);
2049 struct timespec now = get_time_timespec();
2050 struct timespec diff = { 0 };
2051 timespec_subtract(&diff, &now, &last_paint);
2052 printf("[ %5ld:%09ld ] ", diff.tv_sec, diff.tv_nsec);
2053 last_paint = now;
2054 printf("paint:");
2055 for (win *w = t; w; w = w->prev_trans)
2056 printf(" %#010lx", w->id);
2057 putchar('\n');
2058 fflush(stdout);
2059 #endif
2060
2061 // Check if fading is finished on all painted windows
2062 {
2063 win *pprev = NULL;
2064 for (win *w = t; w; w = pprev) {
2065 pprev = w->prev_trans;
2066 check_fade_fin(ps, w);
2067 }
2068 }
2069 }
2070
2071 static void
2072 add_damage(session_t *ps, XserverRegion damage) {
2073 // Ignore damage when screen isn't redirected
2074 if (!ps->redirected)
2075 free_region(ps, &damage);
2076
2077 if (!damage) return;
2078 if (ps->all_damage) {
2079 XFixesUnionRegion(ps->dpy, ps->all_damage, ps->all_damage, damage);
2080 XFixesDestroyRegion(ps->dpy, damage);
2081 } else {
2082 ps->all_damage = damage;
2083 }
2084 }
2085
2086 static void
2087 repair_win(session_t *ps, win *w) {
2088 if (IsViewable != w->a.map_state)
2089 return;
2090
2091 XserverRegion parts;
2092
2093 if (!w->damaged) {
2094 parts = win_extents(ps, w);
2095 set_ignore_next(ps);
2096 XDamageSubtract(ps->dpy, w->damage, None, None);
2097 } else {
2098 parts = XFixesCreateRegion(ps->dpy, 0, 0);
2099 set_ignore_next(ps);
2100 XDamageSubtract(ps->dpy, w->damage, None, parts);
2101 XFixesTranslateRegion(ps->dpy, parts,
2102 w->a.x + w->a.border_width,
2103 w->a.y + w->a.border_width);
2104 }
2105
2106 w->damaged = true;
2107 w->pixmap_damaged = true;
2108
2109 // Why care about damage when screen is unredirected?
2110 // We will force full-screen repaint on redirection.
2111 if (!ps->redirected) {
2112 free_region(ps, &parts);
2113 return;
2114 }
2115
2116 // Remove the part in the damage area that could be ignored
2117 if (!ps->reg_ignore_expire && w->prev_trans && w->prev_trans->reg_ignore)
2118 XFixesSubtractRegion(ps->dpy, parts, parts, w->prev_trans->reg_ignore);
2119
2120 add_damage(ps, parts);
2121 }
2122
2123 static wintype_t
2124 wid_get_prop_wintype(session_t *ps, Window wid) {
2125 set_ignore_next(ps);
2126 winprop_t prop = wid_get_prop(ps, wid, ps->atom_win_type, 32L, XA_ATOM, 32);
2127
2128 for (unsigned i = 0; i < prop.nitems; ++i) {
2129 for (wintype_t j = 1; j < NUM_WINTYPES; ++j) {
2130 if (ps->atoms_wintypes[j] == (Atom) prop.data.p32[i]) {
2131 free_winprop(&prop);
2132 return j;
2133 }
2134 }
2135 }
2136
2137 free_winprop(&prop);
2138
2139 return WINTYPE_UNKNOWN;
2140 }
2141
2142 static void
2143 map_win(session_t *ps, Window id) {
2144 // Unmap overlay window if it got mapped but we are currently not
2145 // in redirected state.
2146 if (ps->overlay && id == ps->overlay && !ps->redirected) {
2147 XUnmapWindow(ps->dpy, ps->overlay);
2148 XFlush(ps->dpy);
2149 }
2150
2151 win *w = find_win(ps, id);
2152
2153 #ifdef DEBUG_EVENTS
2154 printf_dbgf("(%#010lx \"%s\"): %p\n", id, (w ? w->name: NULL), w);
2155 #endif
2156
2157 // Don't care about window mapping if it's an InputOnly window
2158 // Try avoiding mapping a window twice
2159 if (!w || InputOnly == w->a.class
2160 || IsViewable == w->a.map_state)
2161 return;
2162
2163 assert(!win_is_focused_real(ps, w));
2164
2165 w->a.map_state = IsViewable;
2166
2167 cxinerama_win_upd_scr(ps, w);
2168
2169 // Call XSelectInput() before reading properties so that no property
2170 // changes are lost
2171 XSelectInput(ps->dpy, id, determine_evmask(ps, id, WIN_EVMODE_FRAME));
2172
2173 // Notify compton when the shape of a window changes
2174 if (ps->shape_exists) {
2175 XShapeSelectInput(ps->dpy, id, ShapeNotifyMask);
2176 }
2177
2178 // Make sure the XSelectInput() requests are sent
2179 XFlush(ps->dpy);
2180
2181 // Update window mode here to check for ARGB windows
2182 win_determine_mode(ps, w);
2183
2184 // Detect client window here instead of in add_win() as the client
2185 // window should have been prepared at this point
2186 if (!w->client_win) {
2187 win_recheck_client(ps, w);
2188 }
2189 else {
2190 // Re-mark client window here
2191 win_mark_client(ps, w, w->client_win);
2192 }
2193
2194 assert(w->client_win);
2195
2196 #ifdef DEBUG_WINTYPE
2197 printf_dbgf("(%#010lx): type %s\n", w->id, WINTYPES[w->window_type]);
2198 #endif
2199
2200 // Detect if the window is shaped or has rounded corners
2201 win_update_shape_raw(ps, w);
2202
2203 // FocusIn/Out may be ignored when the window is unmapped, so we must
2204 // recheck focus here
2205 if (ps->o.track_focus)
2206 recheck_focus(ps);
2207
2208 // Update window focus state
2209 win_update_focused(ps, w);
2210
2211 // Update opacity and dim state
2212 win_update_opacity_prop(ps, w);
2213 w->flags |= WFLAG_OPCT_CHANGE;
2214
2215 // Check for _COMPTON_SHADOW
2216 if (ps->o.respect_prop_shadow)
2217 win_update_prop_shadow_raw(ps, w);
2218
2219 // Many things above could affect shadow
2220 win_determine_shadow(ps, w);
2221
2222 // Set fading state
2223 w->in_openclose = true;
2224 set_fade_callback(ps, w, finish_map_win, true);
2225 win_determine_fade(ps, w);
2226
2227 win_determine_blur_background(ps, w);
2228
2229 w->damaged = false;
2230
2231 /* if any configure events happened while
2232 the window was unmapped, then configure
2233 the window to its correct place */
2234 if (w->need_configure) {
2235 configure_win(ps, &w->queue_configure);
2236 }
2237
2238 #ifdef CONFIG_DBUS
2239 // Send D-Bus signal
2240 if (ps->o.dbus) {
2241 cdbus_ev_win_mapped(ps, w);
2242 }
2243 #endif
2244 }
2245
2246 static void
2247 finish_map_win(session_t *ps, win *w) {
2248 w->in_openclose = false;
2249 if (ps->o.no_fading_openclose) {
2250 win_determine_fade(ps, w);
2251 }
2252 }
2253
2254 static void
2255 finish_unmap_win(session_t *ps, win *w) {
2256 w->damaged = false;
2257
2258 w->in_openclose = false;
2259
2260 update_reg_ignore_expire(ps, w);
2261
2262 if (w->extents != None) {
2263 /* destroys region */
2264 add_damage(ps, w->extents);
2265 w->extents = None;
2266 }
2267
2268 free_wpaint(ps, w);
2269 free_region(ps, &w->border_size);
2270 free_paint(ps, &w->shadow_paint);
2271 }
2272
2273 static void
2274 unmap_callback(session_t *ps, win *w) {
2275 finish_unmap_win(ps, w);
2276 }
2277
2278 static void
2279 unmap_win(session_t *ps, win *w) {
2280 if (!w || IsUnmapped == w->a.map_state) return;
2281
2282 if (w->destroyed) return;
2283
2284 // One last synchronization
2285 if (w->paint.pixmap)
2286 xr_sync(ps, w->paint.pixmap, &w->fence);
2287 free_fence(ps, &w->fence);
2288
2289 // Set focus out
2290 win_set_focused(ps, w, false);
2291
2292 w->a.map_state = IsUnmapped;
2293
2294 // Fading out
2295 w->flags |= WFLAG_OPCT_CHANGE;
2296 set_fade_callback(ps, w, unmap_callback, false);
2297 w->in_openclose = true;
2298 win_determine_fade(ps, w);
2299
2300 // Validate pixmap if we have to do fading
2301 if (w->fade)
2302 win_validate_pixmap(ps, w);
2303
2304 // don't care about properties anymore
2305 win_ev_stop(ps, w);
2306
2307 #ifdef CONFIG_DBUS
2308 // Send D-Bus signal
2309 if (ps->o.dbus) {
2310 cdbus_ev_win_unmapped(ps, w);
2311 }
2312 #endif
2313 }
2314
2315 static bool
2316 wid_get_opacity_prop(session_t *ps, Window wid, opacity_t def, opacity_t *out) {
2317 bool ret = false;
2318 *out = def;
2319
2320 winprop_t prop = wid_get_prop(ps, wid, ps->atom_opacity, 1L,
2321 XA_CARDINAL, 32);
2322
2323 if (prop.nitems) {
2324 *out = *prop.data.p32;
2325 ret = true;
2326 }
2327
2328 free_winprop(&prop);
2329
2330 return ret;
2331 }
2332
2333 static double
2334 get_opacity_percent(win *w) {
2335 return ((double) w->opacity) / OPAQUE;
2336 }
2337
2338 static void
2339 win_determine_mode(session_t *ps, win *w) {
2340 winmode_t mode = WMODE_SOLID;
2341
2342 if (w->pictfmt && w->pictfmt->type == PictTypeDirect
2343 && w->pictfmt->direct.alphaMask) {
2344 mode = WMODE_ARGB;
2345 } else if (w->opacity != OPAQUE) {
2346 mode = WMODE_TRANS;
2347 } else {
2348 mode = WMODE_SOLID;
2349 }
2350
2351 w->mode = mode;
2352 }
2353
2354 /**
2355 * Calculate and set the opacity of a window.
2356 *
2357 * If window is inactive and inactive_opacity_override is set, the
2358 * priority is: (Simulates the old behavior)
2359 *
2360 * inactive_opacity > _NET_WM_WINDOW_OPACITY (if not opaque)
2361 * > window type default opacity
2362 *
2363 * Otherwise:
2364 *
2365 * _NET_WM_WINDOW_OPACITY (if not opaque)
2366 * > window type default opacity (if not opaque)
2367 * > inactive_opacity
2368 *
2369 * @param ps current session
2370 * @param w struct _win object representing the window
2371 */
2372 static void
2373 calc_opacity(session_t *ps, win *w) {
2374 opacity_t opacity = OPAQUE;
2375
2376 if (w->destroyed || IsViewable != w->a.map_state)
2377 opacity = 0;
2378 else {
2379 // Try obeying opacity property and window type opacity firstly
2380 if(w->has_opacity_prop)
2381 opacity = w->opacity_prop;
2382 else if (!isnan(ps->o.wintype_opacity[w->window_type]))
2383 opacity = ps->o.wintype_opacity[w->window_type] * OPAQUE;
2384 else {
2385 // Respect active_opacity only when the window is physically focused
2386 if (win_is_focused_real(ps, w))
2387 opacity = ps->o.active_opacity;
2388 else if (false == w->focused)
2389 // Respect inactive_opacity in some cases
2390 opacity = ps->o.inactive_opacity;
2391 }
2392
2393 // respect inactive override
2394 if (ps->o.inactive_opacity_override && false == w->focused)
2395 opacity = ps->o.inactive_opacity;
2396 }
2397
2398 w->opacity_tgt = opacity;
2399 }
2400
2401 /**
2402 * Determine whether a window is to be dimmed.
2403 */
2404 static void
2405 calc_dim(session_t *ps, win *w) {
2406 bool dim;
2407
2408 // Make sure we do nothing if the window is unmapped / destroyed
2409 if (w->destroyed || IsViewable != w->a.map_state)
2410 return;
2411
2412 if (ps->o.inactive_dim && !(w->focused)) {
2413 dim = true;
2414 } else {
2415 dim = false;
2416 }
2417
2418 if (dim != w->dim) {
2419 w->dim = dim;
2420 add_damage_win(ps, w);
2421 }
2422 }
2423
2424 /**
2425 * Determine if a window should fade on opacity change.
2426 */
2427 static void
2428 win_determine_fade(session_t *ps, win *w) {
2429 // To prevent it from being overwritten by last-paint value if the window is
2430 // unmapped on next frame, write w->fade_last as well
2431 if (UNSET != w->fade_force)
2432 w->fade_last = w->fade = w->fade_force;
2433 else if (ps->o.no_fading_openclose && w->in_openclose)
2434 w->fade_last = w->fade = false;
2435 else if (ps->o.no_fading_destroyed_argb && w->destroyed
2436 && WMODE_ARGB == w->mode && w->client_win && w->client_win != w->id) {
2437 w->fade_last = w->fade = false;
2438 }
2439 // Ignore other possible causes of fading state changes after window
2440 // gets unmapped
2441 else if (IsViewable != w->a.map_state) {
2442 }
2443 else if (win_match(ps, w, ps->o.fade_blacklist, &w->cache_fblst))
2444 w->fade = false;
2445 else
2446 w->fade = ps->o.wintype_fade[w->window_type];
2447 }
2448
2449 /**
2450 * Update window-shape.
2451 */
2452 static void
2453 win_update_shape_raw(session_t *ps, win *w) {
2454 if (ps->shape_exists) {
2455 w->bounding_shaped = wid_bounding_shaped(ps, w->id);
2456 if (w->bounding_shaped && ps->o.detect_rounded_corners)
2457 win_rounded_corners(ps, w);
2458 }
2459 }
2460
2461 /**
2462 * Update window-shape related information.
2463 */
2464 static void
2465 win_update_shape(session_t *ps, win *w) {
2466 if (ps->shape_exists) {
2467 // bool bounding_shaped_old = w->bounding_shaped;
2468
2469 win_update_shape_raw(ps, w);
2470
2471 win_on_factor_change(ps, w);
2472
2473 /*
2474 // If clear_shadow state on the window possibly changed, destroy the old
2475 // shadow_pict
2476 if (ps->o.clear_shadow && w->bounding_shaped != bounding_shaped_old)
2477 free_paint(ps, &w->shadow_paint);
2478 */
2479 }
2480 }
2481
2482 /**
2483 * Reread _COMPTON_SHADOW property from a window.
2484 *
2485 * The property must be set on the outermost window, usually the WM frame.
2486 */
2487 static void
2488 win_update_prop_shadow_raw(session_t *ps, win *w) {
2489 winprop_t prop = wid_get_prop(ps, w->id, ps->atom_compton_shadow, 1,
2490 XA_CARDINAL, 32);
2491
2492 if (!prop.nitems) {
2493 w->prop_shadow = -1;
2494 }
2495 else {
2496 w->prop_shadow = *prop.data.p32;
2497 }
2498
2499 free_winprop(&prop);
2500 }
2501
2502 /**
2503 * Reread _COMPTON_SHADOW property from a window and update related
2504 * things.
2505 */
2506 static void
2507 win_update_prop_shadow(session_t *ps, win *w) {
2508 long attr_shadow_old = w->prop_shadow;
2509
2510 win_update_prop_shadow_raw(ps, w);
2511
2512 if (w->prop_shadow != attr_shadow_old)
2513 win_determine_shadow(ps, w);
2514 }
2515
2516 static void
2517 win_set_shadow(session_t *ps, win *w, bool shadow_new) {
2518 if (w->shadow == shadow_new) return;
2519
2520 w->shadow = shadow_new;
2521
2522 // Window extents need update on shadow state change
2523 // Shadow geometry currently doesn't change on shadow state change
2524 // calc_shadow_geometry(ps, w);
2525 if (w->extents) {
2526 // Mark the old extents as damaged if the shadow is removed
2527 if (!w->shadow)
2528 add_damage(ps, w->extents);
2529 else
2530 free_region(ps, &w->extents);
2531 w->extents = win_extents(ps, w);
2532 // Mark the new extents as damaged if the shadow is added
2533 if (w->shadow)
2534 add_damage_win(ps, w);
2535 }
2536 }
2537
2538 /**
2539 * Determine if a window should have shadow, and update things depending
2540 * on shadow state.
2541 */
2542 static void
2543 win_determine_shadow(session_t *ps, win *w) {
2544 bool shadow_new = w->shadow;
2545
2546 if (UNSET != w->shadow_force)
2547 shadow_new = w->shadow_force;
2548 else if (IsViewable == w->a.map_state)
2549 shadow_new = (ps->o.wintype_shadow[w->window_type]
2550 && !win_match(ps, w, ps->o.shadow_blacklist, &w->cache_sblst)
2551 && !(ps->o.shadow_ignore_shaped && w->bounding_shaped
2552 && !w->rounded_corners)
2553 && !(ps->o.respect_prop_shadow && 0 == w->prop_shadow));
2554
2555 win_set_shadow(ps, w, shadow_new);
2556 }
2557
2558 static void
2559 win_set_invert_color(session_t *ps, win *w, bool invert_color_new) {
2560 if (w->invert_color == invert_color_new) return;
2561
2562 w->invert_color = invert_color_new;
2563
2564 add_damage_win(ps, w);
2565 }
2566
2567 /**
2568 * Determine if a window should have color inverted.
2569 */
2570 static void
2571 win_determine_invert_color(session_t *ps, win *w) {
2572 bool invert_color_new = w->invert_color;
2573
2574 if (UNSET != w->invert_color_force)
2575 invert_color_new = w->invert_color_force;
2576 else if (IsViewable == w->a.map_state)
2577 invert_color_new = win_match(ps, w, ps->o.invert_color_list,
2578 &w->cache_ivclst);
2579
2580 win_set_invert_color(ps, w, invert_color_new);
2581 }
2582
2583 static void
2584 win_set_blur_background(session_t *ps, win *w, bool blur_background_new) {
2585 if (w->blur_background == blur_background_new) return;
2586
2587 w->blur_background = blur_background_new;
2588
2589 // Only consider window damaged if it's previously painted with background
2590 // blurred
2591 if (!win_is_solid(ps, w)
2592 || (ps->o.blur_background_frame && w->frame_opacity))
2593 add_damage_win(ps, w);
2594 }
2595
2596 /**
2597 * Determine if a window should have background blurred.
2598 */
2599 static void
2600 win_determine_blur_background(session_t *ps, win *w) {
2601 if (IsViewable != w->a.map_state)
2602 return;
2603
2604 bool blur_background_new = ps->o.blur_background
2605 && !win_match(ps, w, ps->o.blur_background_blacklist, &w->cache_bbblst);
2606
2607 win_set_blur_background(ps, w, blur_background_new);
2608 }
2609
2610 /**
2611 * Update window opacity according to opacity rules.
2612 */
2613 static void
2614 win_update_opacity_rule(session_t *ps, win *w) {
2615 if (IsViewable != w->a.map_state)
2616 return;
2617
2618 #ifdef CONFIG_C2
2619 opacity_t opacity = OPAQUE;
2620 bool is_set = false;
2621 void *val = NULL;
2622 if (c2_matchd(ps, w, ps->o.opacity_rules, &w->cache_oparule, &val)) {
2623 opacity = ((double) (long) val) / 100.0 * OPAQUE;
2624 is_set = true;
2625 }
2626
2627 if (is_set == w->opacity_is_set && opacity == w->opacity_set)
2628 return;
2629
2630 w->opacity_set = opacity;
2631 w->opacity_is_set = is_set;
2632 if (!is_set)
2633 wid_rm_opacity_prop(ps, w->id);
2634 else
2635 wid_set_opacity_prop(ps, w->id, opacity);
2636 #endif
2637 }
2638
2639 /**
2640 * Function to be called on window type changes.
2641 */
2642 static void
2643 win_on_wtype_change(session_t *ps, win *w) {
2644 win_determine_shadow(ps, w);
2645 win_determine_fade(ps, w);
2646 win_update_focused(ps, w);
2647 if (ps->o.invert_color_list)
2648 win_determine_invert_color(ps, w);
2649 if (ps->o.opacity_rules)
2650 win_update_opacity_rule(ps, w);
2651 }
2652
2653 /**
2654 * Function to be called on window data changes.
2655 */
2656 static void
2657 win_on_factor_change(session_t *ps, win *w) {
2658 if (ps->o.shadow_blacklist)
2659 win_determine_shadow(ps, w);
2660 if (ps->o.fade_blacklist)
2661 win_determine_fade(ps, w);
2662 if (ps->o.invert_color_list)
2663 win_determine_invert_color(ps, w);
2664 if (ps->o.focus_blacklist)
2665 win_update_focused(ps, w);
2666 if (ps->o.blur_background_blacklist)
2667 win_determine_blur_background(ps, w);
2668 if (ps->o.opacity_rules)
2669 win_update_opacity_rule(ps, w);
2670 if (IsViewable == w->a.map_state && ps->o.paint_blacklist)
2671 w->paint_excluded = win_match(ps, w, ps->o.paint_blacklist,
2672 &w->cache_pblst);
2673 if (IsViewable == w->a.map_state && ps->o.unredir_if_possible_blacklist)
2674 w->unredir_if_possible_excluded = win_match(ps, w,
2675 ps->o.unredir_if_possible_blacklist, &w->cache_uipblst);
2676 }
2677
2678 /**
2679 * Update cache data in struct _win that depends on window size.
2680 */
2681 static void
2682 calc_win_size(session_t *ps, win *w) {
2683 w->widthb = w->a.width + w->a.border_width * 2;
2684 w->heightb = w->a.height + w->a.border_width * 2;
2685 calc_shadow_geometry(ps, w);
2686 w->flags |= WFLAG_SIZE_CHANGE;
2687 }
2688
2689 /**
2690 * Calculate and update geometry of the shadow of a window.
2691 */
2692 static void
2693 calc_shadow_geometry(session_t *ps, win *w) {
2694 w->shadow_dx = ps->o.shadow_offset_x;
2695 w->shadow_dy = ps->o.shadow_offset_y;
2696 w->shadow_width = w->widthb + ps->gaussian_map->size;
2697 w->shadow_height = w->heightb + ps->gaussian_map->size;
2698 }
2699
2700 /**
2701 * Update window type.
2702 */
2703 static void
2704 win_upd_wintype(session_t *ps, win *w) {
2705 const wintype_t wtype_old = w->window_type;
2706
2707 // Detect window type here
2708 w->window_type = wid_get_prop_wintype(ps, w->client_win);
2709
2710 // Conform to EWMH standard, if _NET_WM_WINDOW_TYPE is not present, take
2711 // override-redirect windows or windows without WM_TRANSIENT_FOR as
2712 // _NET_WM_WINDOW_TYPE_NORMAL, otherwise as _NET_WM_WINDOW_TYPE_DIALOG.
2713 if (WINTYPE_UNKNOWN == w->window_type) {
2714 if (w->a.override_redirect
2715 || !wid_has_prop(ps, w->client_win, ps->atom_transient))
2716 w->window_type = WINTYPE_NORMAL;
2717 else
2718 w->window_type = WINTYPE_DIALOG;
2719 }
2720
2721 if (w->window_type != wtype_old)
2722 win_on_wtype_change(ps, w);
2723 }
2724
2725 /**
2726 * Mark a window as the client window of another.
2727 *
2728 * @param ps current session
2729 * @param w struct _win of the parent window
2730 * @param client window ID of the client window
2731 */
2732 static void
2733 win_mark_client(session_t *ps, win *w, Window client) {
2734 w->client_win = client;
2735
2736 // If the window isn't mapped yet, stop here, as the function will be
2737 // called in map_win()
2738 if (IsViewable != w->a.map_state)
2739 return;
2740
2741 XSelectInput(ps->dpy, client,
2742 determine_evmask(ps, client, WIN_EVMODE_CLIENT));
2743
2744 // Make sure the XSelectInput() requests are sent
2745 XFlush(ps->dpy);
2746
2747 win_upd_wintype(ps, w);
2748
2749 // Get frame widths. The window is in damaged area already.
2750 if (ps->o.frame_opacity)
2751 get_frame_extents(ps, w, client);
2752
2753 // Get window group
2754 if (ps->o.track_leader)
2755 win_update_leader(ps, w);
2756
2757 // Get window name and class if we are tracking them
2758 if (ps->o.track_wdata) {
2759 win_get_name(ps, w);
2760 win_get_class(ps, w);
2761 win_get_role(ps, w);
2762 }
2763
2764 // Update everything related to conditions
2765 win_on_factor_change(ps, w);
2766
2767 // Update window focus state
2768 win_update_focused(ps, w);
2769 }
2770
2771 /**
2772 * Unmark current client window of a window.
2773 *
2774 * @param ps current session
2775 * @param w struct _win of the parent window
2776 */
2777 static void
2778 win_unmark_client(session_t *ps, win *w) {
2779 Window client = w->client_win;
2780
2781 w->client_win = None;
2782
2783 // Recheck event mask
2784 XSelectInput(ps->dpy, client,
2785 determine_evmask(ps, client, WIN_EVMODE_UNKNOWN));
2786 }
2787
2788 /**
2789 * Recheck client window of a window.
2790 *
2791 * @param ps current session
2792 * @param w struct _win of the parent window
2793 */
2794 static void
2795 win_recheck_client(session_t *ps, win *w) {
2796 // Initialize wmwin to false
2797 w->wmwin = false;
2798
2799 // Look for the client window
2800
2801 // Always recursively look for a window with WM_STATE, as Fluxbox
2802 // sets override-redirect flags on all frame windows.
2803 Window cw = find_client_win(ps, w->id);
2804 #ifdef DEBUG_CLIENTWIN
2805 if (cw)
2806 printf_dbgf("(%#010lx): client %#010lx\n", w->id, cw);
2807 #endif
2808 // Set a window's client window to itself if we couldn't find a
2809 // client window
2810 if (!cw) {
2811 cw = w->id;
2812 w->wmwin = !w->a.override_redirect;
2813 #ifdef DEBUG_CLIENTWIN
2814 printf_dbgf("(%#010lx): client self (%s)\n", w->id,
2815 (w->wmwin ? "wmwin": "override-redirected"));
2816 #endif
2817 }
2818
2819 // Unmark the old one
2820 if (w->client_win && w->client_win != cw)
2821 win_unmark_client(ps, w);
2822
2823 // Mark the new one
2824 win_mark_client(ps, w, cw);
2825 }
2826
2827 static bool
2828 add_win(session_t *ps, Window id, Window prev) {
2829 const static win win_def = {
2830 .next = NULL,
2831 .prev_trans = NULL,
2832
2833 .id = None,
2834 .a = { },
2835 #ifdef CONFIG_XINERAMA
2836 .xinerama_scr = -1,
2837 #endif
2838 .pictfmt = NULL,
2839 .mode = WMODE_TRANS,
2840 .damaged = false,
2841 .damage = None,
2842 .pixmap_damaged = false,
2843 .paint = PAINT_INIT,
2844 .border_size = None,
2845 .extents = None,
2846 .flags = 0,
2847 .need_configure = false,
2848 .queue_configure = { },
2849 .reg_ignore = None,
2850 .widthb = 0,
2851 .heightb = 0,
2852 .destroyed = false,
2853 .bounding_shaped = false,
2854 .rounded_corners = false,
2855 .to_paint = false,
2856 .in_openclose = false,
2857
2858 .client_win = None,
2859 .window_type = WINTYPE_UNKNOWN,
2860 .wmwin = false,
2861 .leader = None,
2862 .cache_leader = None,
2863
2864 .focused = false,
2865 .focused_force = UNSET,
2866
2867 .name = NULL,
2868 .class_instance = NULL,
2869 .class_general = NULL,
2870 .role = NULL,
2871 .cache_sblst = NULL,
2872 .cache_fblst = NULL,
2873 .cache_fcblst = NULL,
2874 .cache_ivclst = NULL,
2875 .cache_bbblst = NULL,
2876 .cache_oparule = NULL,
2877
2878 .opacity = 0,
2879 .opacity_tgt = 0,
2880 .has_opacity_prop = false,
2881 .opacity_prop = OPAQUE,
2882 .opacity_is_set = false,
2883 .opacity_set = OPAQUE,
2884
2885 .fade = false,
2886 .fade_force = UNSET,
2887 .fade_callback = NULL,
2888
2889 .frame_opacity = 0.0,
2890 .frame_extents = MARGIN_INIT,
2891
2892 .shadow = false,
2893 .shadow_force = UNSET,
2894 .shadow_opacity = 0.0,
2895 .shadow_dx = 0,
2896 .shadow_dy = 0,
2897 .shadow_width = 0,
2898 .shadow_height = 0,
2899 .shadow_paint = PAINT_INIT,
2900 .prop_shadow = -1,
2901
2902 .dim = false,
2903
2904 .invert_color = false,
2905 .invert_color_force = UNSET,
2906
2907 .blur_background = false,
2908 };
2909
2910 // Reject overlay window and already added windows
2911 if (id == ps->overlay || find_win(ps, id)) {
2912 return false;
2913 }
2914
2915 // Allocate and initialize the new win structure
2916 win *new = malloc(sizeof(win));
2917
2918 #ifdef DEBUG_EVENTS
2919 printf_dbgf("(%#010lx): %p\n", id, new);
2920 #endif
2921
2922 if (!new) {
2923 printf_errf("(%#010lx): Failed to allocate memory for the new window.", id);
2924 return false;
2925 }
2926
2927 memcpy(new, &win_def, sizeof(win));
2928
2929 // Find window insertion point
2930 win **p = NULL;
2931 if (prev) {
2932 for (p = &ps->list; *p; p = &(*p)->next) {
2933 if ((*p)->id == prev && !(*p)->destroyed)
2934 break;
2935 }
2936 } else {
2937 p = &ps->list;
2938 }
2939
2940 // Fill structure
2941 new->id = id;
2942
2943 set_ignore_next(ps);
2944 if (!XGetWindowAttributes(ps->dpy, id, &new->a)
2945 || IsUnviewable == new->a.map_state) {
2946 // Failed to get window attributes probably means the window is gone
2947 // already. IsUnviewable means the window is already reparented
2948 // elsewhere.
2949 free(new);
2950 return false;
2951 }
2952
2953 // Delay window mapping
2954 int map_state = new->a.map_state;
2955 assert(IsViewable == map_state || IsUnmapped == map_state);
2956 new->a.map_state = IsUnmapped;
2957
2958 if (InputOutput == new->a.class) {
2959 // Get window picture format
2960 new->pictfmt = XRenderFindVisualFormat(ps->dpy, new->a.visual);
2961
2962 // Create Damage for window
2963 set_ignore_next(ps);
2964 new->damage = XDamageCreate(ps->dpy, id, XDamageReportNonEmpty);
2965 }
2966
2967 calc_win_size(ps, new);
2968
2969 new->next = *p;
2970 *p = new;
2971
2972 #ifdef CONFIG_DBUS
2973 // Send D-Bus signal
2974 if (ps->o.dbus) {
2975 cdbus_ev_win_added(ps, new);
2976 }
2977 #endif
2978
2979 if (IsViewable == map_state) {
2980 map_win(ps, id);
2981 }
2982
2983 return true;
2984 }
2985
2986 static void
2987 restack_win(session_t *ps, win *w, Window new_above) {
2988 Window old_above;
2989
2990 update_reg_ignore_expire(ps, w);
2991
2992 if (w->next) {
2993 old_above = w->next->id;
2994 } else {
2995 old_above = None;
2996 }
2997
2998 if (old_above != new_above) {
2999 win **prev = NULL, **prev_old = NULL;
3000
3001 // unhook
3002 for (prev = &ps->list; *prev; prev = &(*prev)->next) {
3003 if ((*prev) == w) break;
3004 }
3005
3006 prev_old = prev;
3007
3008 bool found = false;
3009
3010 // rehook
3011 for (prev = &ps->list; *prev; prev = &(*prev)->next) {
3012 if ((*prev)->id == new_above && !(*prev)->destroyed) {
3013 found = true;
3014 break;
3015 }
3016 }
3017
3018 if (new_above && !found) {
3019 printf_errf("(%#010lx, %#010lx): "
3020 "Failed to found new above window.", w->id, new_above);
3021 return;
3022 }
3023
3024 *prev_old = w->next;
3025
3026 w->next = *prev;
3027 *prev = w;
3028
3029 #ifdef DEBUG_RESTACK
3030 {
3031 const char *desc;
3032 char *window_name = NULL;
3033 bool to_free;
3034 win* c = ps->list;
3035
3036 printf_dbgf("(%#010lx, %#010lx): "
3037 "Window stack modified. Current stack:\n", w->id, new_above);
3038
3039 for (; c; c = c->next) {
3040 window_name = "(Failed to get title)";
3041
3042 to_free = ev_window_name(ps, c->id, &window_name);
3043
3044 desc = "";
3045 if (c->destroyed) desc = "(D) ";
3046 printf("%#010lx \"%s\" %s", c->id, window_name, desc);
3047 if (c->next)
3048 printf("-> ");
3049
3050 if (to_free) {
3051 cxfree(window_name);
3052 window_name = NULL;
3053 }
3054 }
3055 fputs("\n", stdout);
3056 }
3057 #endif
3058 }
3059 }
3060
3061 static bool
3062 init_filters(session_t *ps);
3063
3064 static void
3065 configure_win(session_t *ps, XConfigureEvent *ce) {
3066 // On root window changes
3067 if (ce->window == ps->root) {
3068 free_paint(ps, &ps->tgt_buffer);
3069
3070 ps->root_width = ce->width;
3071 ps->root_height = ce->height;
3072
3073 rebuild_screen_reg(ps);
3074 rebuild_shadow_exclude_reg(ps);
3075 free_all_damage_last(ps);
3076
3077 // Re-redirect screen if required
3078 if (ps->o.reredir_on_root_change && ps->redirected) {
3079 redir_stop(ps);
3080 redir_start(ps);
3081 }
3082
3083 #ifdef CONFIG_VSYNC_OPENGL
3084 // Reinitialize GLX on root change
3085 if (ps->o.glx_reinit_on_root_change && ps->psglx) {
3086 if (!glx_reinit(ps, bkend_use_glx(ps)))
3087 printf_errf("(): Failed to reinitialize GLX, troubles ahead.");
3088 if (BKEND_GLX == ps->o.backend && !init_filters(ps))
3089 printf_errf("(): Failed to initialize filters.");
3090 }
3091
3092 // GLX root change callback
3093 if (BKEND_GLX == ps->o.backend)
3094 glx_on_root_change(ps);
3095 #endif
3096
3097 force_repaint(ps);
3098
3099 return;
3100 }
3101
3102 // Other window changes
3103 win *w = find_win(ps, ce->window);
3104 XserverRegion damage = None;
3105
3106 if (!w)
3107 return;
3108
3109 if (w->a.map_state == IsUnmapped) {
3110 /* save the configure event for when the window maps */
3111 w->need_configure = true;
3112 w->queue_configure = *ce;
3113 restack_win(ps, w, ce->above);
3114 } else {
3115 if (!(w->need_configure)) {
3116 restack_win(ps, w, ce->above);
3117 }
3118
3119 bool factor_change = false;
3120
3121 // Windows restack (including window restacks happened when this
3122 // window is not mapped) could mess up all reg_ignore
3123 ps->reg_ignore_expire = true;
3124
3125 w->need_configure = false;
3126
3127 damage = XFixesCreateRegion(ps->dpy, 0, 0);
3128 if (w->extents != None) {
3129 XFixesCopyRegion(ps->dpy, damage, w->extents);
3130 }
3131
3132 // If window geometry did not change, don't free extents here
3133 if (w->a.x != ce->x || w->a.y != ce->y
3134 || w->a.width != ce->width || w->a.height != ce->height
3135 || w->a.border_width != ce->border_width) {
3136 factor_change = true;
3137 free_region(ps, &w->extents);
3138 free_region(ps, &w->border_size);
3139 }
3140
3141 w->a.x = ce->x;
3142 w->a.y = ce->y;
3143
3144 if (w->a.width != ce->width || w->a.height != ce->height
3145 || w->a.border_width != ce->border_width)
3146 free_wpaint(ps, w);
3147
3148 if (w->a.width != ce->width || w->a.height != ce->height
3149 || w->a.border_width != ce->border_width) {
3150 w->a.width = ce->width;
3151 w->a.height = ce->height;
3152 w->a.border_width = ce->border_width;
3153 calc_win_size(ps, w);
3154
3155 // Rounded corner detection is affected by window size
3156 if (ps->shape_exists && ps->o.shadow_ignore_shaped
3157 && ps->o.detect_rounded_corners && w->bounding_shaped)
3158 win_update_shape(ps, w);
3159 }
3160
3161 if (damage) {
3162 XserverRegion extents = win_extents(ps, w);
3163 XFixesUnionRegion(ps->dpy, damage, damage, extents);
3164 XFixesDestroyRegion(ps->dpy, extents);
3165 add_damage(ps, damage);
3166 }
3167
3168 if (factor_change) {
3169 cxinerama_win_upd_scr(ps, w);
3170 win_on_factor_change(ps, w);
3171 }
3172 }
3173
3174 // override_redirect flag cannot be changed after window creation, as far
3175 // as I know, so there's no point to re-match windows here.
3176 w->a.override_redirect = ce->override_redirect;
3177 }
3178
3179 static void
3180 circulate_win(session_t *ps, XCirculateEvent *ce) {
3181 win *w = find_win(ps, ce->window);
3182 Window new_above;
3183
3184 if (!w) return;
3185
3186 if (ce->place == PlaceOnTop) {
3187 new_above = ps->list->id;
3188 } else {
3189 new_above = None;
3190 }
3191
3192 restack_win(ps, w, new_above);
3193 }
3194
3195 static void
3196 finish_destroy_win(session_t *ps, win *w) {
3197 assert(w->destroyed);
3198 win **prev = NULL, *i = NULL;
3199
3200 #ifdef DEBUG_EVENTS
3201 printf_dbgf("(%#010lx): Starting...\n", w->id);
3202 #endif
3203
3204 for (prev = &ps->list; (i = *prev); prev = &i->next) {
3205 if (w == i) {
3206 #ifdef DEBUG_EVENTS
3207 printf_dbgf("(%#010lx \"%s\"): %p\n", w->id, w->name, w);
3208 #endif
3209
3210 finish_unmap_win(ps, w);
3211 *prev = w->next;
3212
3213 // Clear active_win if it's pointing to the destroyed window
3214 if (w == ps->active_win)
3215 ps->active_win = NULL;
3216
3217 free_win_res(ps, w);
3218
3219 // Drop w from all prev_trans to avoid accessing freed memory in
3220 // repair_win()
3221 for (win *w2 = ps->list; w2; w2 = w2->next)
3222 if (w == w2->prev_trans)
3223 w2->prev_trans = NULL;
3224
3225 free(w);
3226 break;
3227 }
3228 }
3229 }
3230
3231 static void
3232 destroy_callback(session_t *ps, win *w) {
3233 finish_destroy_win(ps, w);
3234 }
3235
3236 static void
3237 destroy_win(session_t *ps, Window id) {
3238 win *w = find_win(ps, id);
3239
3240 #ifdef DEBUG_EVENTS
3241 printf_dbgf("(%#010lx \"%s\"): %p\n", id, (w ? w->name: NULL), w);
3242 #endif
3243
3244 if (w) {
3245 unmap_win(ps, w);
3246
3247 w->destroyed = true;
3248
3249 if (ps->o.no_fading_destroyed_argb)
3250 win_determine_fade(ps, w);
3251
3252 // Set fading callback
3253 set_fade_callback(ps, w, destroy_callback, false);
3254
3255 #ifdef CONFIG_DBUS
3256 // Send D-Bus signal
3257 if (ps->o.dbus) {
3258 cdbus_ev_win_destroyed(ps, w);
3259 }
3260 #endif
3261 }
3262 }
3263
3264 static inline void
3265 root_damaged(session_t *ps) {
3266 if (ps->root_tile_paint.pixmap) {
3267 XClearArea(ps->dpy, ps->root, 0, 0, 0, 0, true);
3268 // if (ps->root_picture != ps->root_tile) {
3269 free_root_tile(ps);
3270 /* }
3271 if (root_damage) {
3272 XserverRegion parts = XFixesCreateRegion(ps->dpy, 0, 0);
3273 XDamageSubtract(ps->dpy, root_damage, None, parts);
3274 add_damage(ps, parts);
3275 } */
3276 }
3277
3278 // Mark screen damaged
3279 force_repaint(ps);
3280 }
3281
3282 static void
3283 damage_win(session_t *ps, XDamageNotifyEvent *de) {
3284 /*
3285 if (ps->root == de->drawable) {
3286 root_damaged();
3287 return;
3288 } */
3289
3290 win *w = find_win(ps, de->drawable);
3291
3292 if (!w) return;
3293
3294 repair_win(ps, w);
3295 }
3296
3297 /**
3298 * Xlib error handler function.
3299 */
3300 static int
3301 xerror(Display __attribute__((unused)) *dpy, XErrorEvent *ev) {
3302 session_t * const ps = ps_g;
3303
3304 int o = 0;
3305 const char *name = "Unknown";
3306
3307 if (should_ignore(ps, ev->serial)) {
3308 return 0;
3309 }
3310
3311 if (ev->request_code == ps->composite_opcode
3312 && ev->minor_code == X_CompositeRedirectSubwindows) {
3313 fprintf(stderr, "Another composite manager is already running "
3314 "(and does not handle _NET_WM_CM_Sn correctly)\n");
3315 exit(1);
3316 }
3317
3318 #define CASESTRRET2(s) case s: name = #s; break
3319
3320 o = ev->error_code - ps->xfixes_error;
3321 switch (o) {
3322 CASESTRRET2(BadRegion);
3323 }
3324
3325 o = ev->error_code - ps->damage_error;
3326 switch (o) {
3327 CASESTRRET2(BadDamage);
3328 }
3329
3330 o = ev->error_code - ps->render_error;
3331 switch (o) {
3332 CASESTRRET2(BadPictFormat);
3333 CASESTRRET2(BadPicture);
3334 CASESTRRET2(BadPictOp);
3335 CASESTRRET2(BadGlyphSet);
3336 CASESTRRET2(BadGlyph);
3337 }
3338
3339 #ifdef CONFIG_VSYNC_OPENGL
3340 if (ps->glx_exists) {
3341 o = ev->error_code - ps->glx_error;
3342 switch (o) {
3343 CASESTRRET2(GLX_BAD_SCREEN);
3344 CASESTRRET2(GLX_BAD_ATTRIBUTE);
3345 CASESTRRET2(GLX_NO_EXTENSION);
3346 CASESTRRET2(GLX_BAD_VISUAL);
3347 CASESTRRET2(GLX_BAD_CONTEXT);
3348 CASESTRRET2(GLX_BAD_VALUE);
3349 CASESTRRET2(GLX_BAD_ENUM);
3350 }
3351 }
3352 #endif
3353
3354 #ifdef CONFIG_XSYNC
3355 if (ps->xsync_exists) {
3356 o = ev->error_code - ps->xsync_error;
3357 switch (o) {
3358 CASESTRRET2(XSyncBadCounter);
3359 CASESTRRET2(XSyncBadAlarm);
3360 CASESTRRET2(XSyncBadFence);
3361 }
3362 }
3363 #endif
3364
3365 switch (ev->error_code) {
3366 CASESTRRET2(BadAccess);
3367 CASESTRRET2(BadAlloc);
3368 CASESTRRET2(BadAtom);
3369 CASESTRRET2(BadColor);
3370 CASESTRRET2(BadCursor);
3371 CASESTRRET2(BadDrawable);
3372 CASESTRRET2(BadFont);
3373 CASESTRRET2(BadGC);
3374 CASESTRRET2(BadIDChoice);
3375 CASESTRRET2(BadImplementation);
3376 CASESTRRET2(BadLength);
3377 CASESTRRET2(BadMatch);
3378 CASESTRRET2(BadName);
3379 CASESTRRET2(BadPixmap);
3380 CASESTRRET2(BadRequest);
3381 CASESTRRET2(BadValue);
3382 CASESTRRET2(BadWindow);
3383 }
3384
3385 #undef CASESTRRET2
3386
3387 print_timestamp(ps);
3388 {
3389 char buf[BUF_LEN] = "";
3390 XGetErrorText(ps->dpy, ev->error_code, buf, BUF_LEN);
3391 printf("error %4d %-12s request %4d minor %4d serial %6lu: \"%s\"\n",
3392 ev->error_code, name, ev->request_code,
3393 ev->minor_code, ev->serial, buf);
3394 }
3395
3396 // print_backtrace();
3397
3398 return 0;
3399 }
3400
3401 static void
3402 expose_root(session_t *ps, XRectangle *rects, int nrects) {
3403 free_all_damage_last(ps);
3404 XserverRegion region = XFixesCreateRegion(ps->dpy, rects, nrects);
3405 add_damage(ps, region);
3406 }
3407
3408 /**
3409 * Get the value of a type-<code>Window</code> property of a window.
3410 *
3411 * @return the value if successful, 0 otherwise
3412 */
3413 static Window
3414 wid_get_prop_window(session_t *ps, Window wid, Atom aprop) {
3415 // Get the attribute
3416 Window p = None;
3417 winprop_t prop = wid_get_prop(ps, wid, aprop, 1L, XA_WINDOW, 32);
3418
3419 // Return it
3420 if (prop.nitems) {
3421 p = *prop.data.p32;
3422 }
3423
3424 free_winprop(&prop);
3425
3426 return p;
3427 }
3428
3429 /**
3430 * Update focused state of a window.
3431 */
3432 static void
3433 win_update_focused(session_t *ps, win *w) {
3434 if (UNSET != w->focused_force) {
3435 w->focused = w->focused_force;
3436 }
3437 else {
3438 w->focused = win_is_focused_real(ps, w);
3439
3440 // Use wintype_focus, and treat WM windows and override-redirected
3441 // windows specially
3442 if (ps->o.wintype_focus[w->window_type]
3443 || (ps->o.mark_wmwin_focused && w->wmwin)
3444 || (ps->o.mark_ovredir_focused
3445 && w->id == w->client_win && !w->wmwin)
3446 || (IsViewable == w->a.map_state && win_match(ps, w, ps->o.focus_blacklist, &w->cache_fcblst)))
3447 w->focused = true;
3448
3449 // If window grouping detection is enabled, mark the window active if
3450 // its group is
3451 if (ps->o.track_leader && ps->active_leader
3452 && win_get_leader(ps, w) == ps->active_leader) {
3453 w->focused = true;
3454 }
3455 }
3456
3457 // Always recalculate the window target opacity, since some opacity-related
3458 // options depend on the output value of win_is_focused_real() instead of
3459 // w->focused
3460 w->flags |= WFLAG_OPCT_CHANGE;
3461 }
3462
3463 /**
3464 * Set real focused state of a window.
3465 */
3466 static void
3467 win_set_focused(session_t *ps, win *w, bool focused) {
3468 // Unmapped windows will have their focused state reset on map
3469 if (IsUnmapped == w->a.map_state)
3470 return;
3471
3472 if (win_is_focused_real(ps, w) == focused) return;
3473
3474 if (focused) {
3475 if (ps->active_win)
3476 win_set_focused(ps, ps->active_win, false);
3477 ps->active_win = w;
3478 }
3479 else if (w == ps->active_win)
3480 ps->active_win = NULL;
3481
3482 assert(win_is_focused_real(ps, w) == focused);
3483
3484 win_on_focus_change(ps, w);
3485 }
3486
3487 /**
3488 * Handle window focus change.
3489 */
3490 static void
3491 win_on_focus_change(session_t *ps, win *w) {
3492 // If window grouping detection is enabled
3493 if (ps->o.track_leader) {
3494 Window leader = win_get_leader(ps, w);
3495
3496 // If the window gets focused, replace the old active_leader
3497 if (win_is_focused_real(ps, w) && leader != ps->active_leader) {
3498 Window active_leader_old = ps->active_leader;
3499
3500 ps->active_leader = leader;
3501
3502 group_update_focused(ps, active_leader_old);
3503 group_update_focused(ps, leader);
3504 }
3505 // If the group get unfocused, remove it from active_leader
3506 else if (!win_is_focused_real(ps, w) && leader && leader == ps->active_leader
3507 && !group_is_focused(ps, leader)) {
3508 ps->active_leader = None;
3509 group_update_focused(ps, leader);
3510 }
3511
3512 // The window itself must be updated anyway
3513 win_update_focused(ps, w);
3514 }
3515 // Otherwise, only update the window itself
3516 else {
3517 win_update_focused(ps, w);
3518 }
3519
3520 // Update everything related to conditions
3521 win_on_factor_change(ps, w);
3522
3523 #ifdef CONFIG_DBUS
3524 // Send D-Bus signal
3525 if (ps->o.dbus) {
3526 if (win_is_focused_real(ps, w))
3527 cdbus_ev_win_focusin(ps, w);
3528 else
3529 cdbus_ev_win_focusout(ps, w);
3530 }
3531 #endif
3532 }
3533
3534 /**
3535 * Update leader of a window.
3536 */
3537 static void
3538 win_update_leader(session_t *ps, win *w) {
3539 Window leader = None;
3540
3541 // Read the leader properties
3542 if (ps->o.detect_transient && !leader)
3543 leader = wid_get_prop_window(ps, w->client_win, ps->atom_transient);
3544
3545 if (ps->o.detect_client_leader && !leader)
3546 leader = wid_get_prop_window(ps, w->client_win, ps->atom_client_leader);
3547
3548 win_set_leader(ps, w, leader);
3549
3550 #ifdef DEBUG_LEADER
3551 printf_dbgf("(%#010lx): client %#010lx, leader %#010lx, cache %#010lx\n", w->id, w->client_win, w->leader, win_get_leader(ps, w));
3552 #endif
3553 }
3554
3555 /**
3556 * Set leader of a window.
3557 */
3558 static void
3559 win_set_leader(session_t *ps, win *w, Window nleader) {
3560 // If the leader changes
3561 if (w->leader != nleader) {
3562 Window cache_leader_old = win_get_leader(ps, w);
3563
3564 w->leader = nleader;
3565
3566 // Forcefully do this to deal with the case when a child window
3567 // gets mapped before parent, or when the window is a waypoint
3568 clear_cache_win_leaders(ps);
3569
3570 // Update the old and new window group and active_leader if the window
3571 // could affect their state.
3572 Window cache_leader = win_get_leader(ps, w);
3573 if (win_is_focused_real(ps, w) && cache_leader_old != cache_leader) {
3574 ps->active_leader = cache_leader;
3575
3576 group_update_focused(ps, cache_leader_old);
3577 group_update_focused(ps, cache_leader);
3578 }
3579 // Otherwise, at most the window itself is affected
3580 else {
3581 win_update_focused(ps, w);
3582 }
3583
3584 // Update everything related to conditions
3585 win_on_factor_change(ps, w);
3586 }
3587 }
3588
3589 /**
3590 * Internal function of win_get_leader().
3591 */
3592 static Window
3593 win_get_leader_raw(session_t *ps, win *w, int recursions) {
3594 // Rebuild the cache if needed
3595 if (!w->cache_leader && (w->client_win || w->leader)) {
3596 // Leader defaults to client window
3597 if (!(w->cache_leader = w->leader))
3598 w->cache_leader = w->client_win;
3599
3600 // If the leader of this window isn't itself, look for its ancestors
3601 if (w->cache_leader && w->cache_leader != w->client_win) {
3602 win *wp = find_toplevel(ps, w->cache_leader);
3603 if (wp) {
3604 // Dead loop?
3605 if (recursions > WIN_GET_LEADER_MAX_RECURSION)
3606 return None;
3607
3608 w->cache_leader = win_get_leader_raw(ps, wp, recursions + 1);
3609 }
3610 }
3611 }
3612
3613 return w->cache_leader;
3614 }
3615
3616 /**
3617 * Get the value of a text property of a window.
3618 */
3619 bool
3620 wid_get_text_prop(session_t *ps, Window wid, Atom prop,
3621 char ***pstrlst, int *pnstr) {
3622 XTextProperty text_prop = { NULL, None, 0, 0 };
3623
3624 if (!(XGetTextProperty(ps->dpy, wid, &text_prop, prop) && text_prop.value))
3625 return false;
3626
3627 if (Success !=
3628 XmbTextPropertyToTextList(ps->dpy, &text_prop, pstrlst, pnstr)
3629 || !*pnstr) {
3630 *pnstr = 0;
3631 if (*pstrlst)
3632 XFreeStringList(*pstrlst);
3633 cxfree(text_prop.value);
3634 return false;
3635 }
3636
3637 cxfree(text_prop.value);
3638 return true;
3639 }
3640
3641 /**
3642 * Get the name of a window from window ID.
3643 */
3644 static bool
3645 wid_get_name(session_t *ps, Window wid, char **name) {
3646 XTextProperty text_prop = { NULL, None, 0, 0 };
3647 char **strlst = NULL;
3648 int nstr = 0;
3649
3650 if (!(wid_get_text_prop(ps, wid, ps->atom_name_ewmh, &strlst, &nstr))) {
3651 #ifdef DEBUG_WINDATA
3652 printf_dbgf("(%#010lx): _NET_WM_NAME unset, falling back to WM_NAME.\n", wid);
3653 #endif
3654
3655 if (!(XGetWMName(ps->dpy, wid, &text_prop) && text_prop.value)) {
3656 return false;
3657 }
3658 if (Success !=
3659 XmbTextPropertyToTextList(ps->dpy, &text_prop, &strlst, &nstr)
3660 || !nstr || !strlst) {
3661 if (strlst)
3662 XFreeStringList(strlst);
3663 cxfree(text_prop.value);
3664 return false;
3665 }
3666 cxfree(text_prop.value);
3667 }
3668
3669 *name = mstrcpy(strlst[0]);
3670
3671 XFreeStringList(strlst);
3672
3673 return true;
3674 }
3675
3676 /**
3677 * Get the role of a window from window ID.
3678 */
3679 static bool
3680 wid_get_role(session_t *ps, Window wid, char **role) {
3681 char **strlst = NULL;
3682 int nstr = 0;
3683
3684 if (!wid_get_text_prop(ps, wid, ps->atom_role, &strlst, &nstr)) {
3685 return false;
3686 }
3687
3688 *role = mstrcpy(strlst[0]);
3689
3690 XFreeStringList(strlst);
3691
3692 return true;
3693 }
3694
3695 /**
3696 * Retrieve a string property of a window and update its <code>win</code>
3697 * structure.
3698 */
3699 static int
3700 win_get_prop_str(session_t *ps, win *w, char **tgt,
3701 bool (*func_wid_get_prop_str)(session_t *ps, Window wid, char **tgt)) {
3702 int ret = -1;
3703 char *prop_old = *tgt;
3704
3705 // Can't do anything if there's no client window
3706 if (!w->client_win)
3707 return false;
3708
3709 // Get the property
3710 ret = func_wid_get_prop_str(ps, w->client_win, tgt);
3711
3712 // Return -1 if func_wid_get_prop_str() failed, 0 if the property
3713 // doesn't change, 1 if it changes
3714 if (!ret)
3715 ret = -1;
3716 else if (prop_old && !strcmp(*tgt, prop_old))
3717 ret = 0;
3718 else
3719 ret = 1;
3720
3721 // Keep the old property if there's no new one
3722 if (*tgt != prop_old)
3723 free(prop_old);
3724
3725 return ret;
3726 }
3727
3728 /**
3729 * Retrieve the <code>WM_CLASS</code> of a window and update its
3730 * <code>win</code> structure.
3731 */
3732 static bool
3733 win_get_class(session_t *ps, win *w) {
3734 char **strlst = NULL;
3735 int nstr = 0;
3736
3737 // Can't do anything if there's no client window
3738 if (!w->client_win)
3739 return false;
3740
3741 // Free and reset old strings
3742 free(w->class_instance);
3743 free(w->class_general);
3744 w->class_instance = NULL;
3745 w->class_general = NULL;
3746
3747 // Retrieve the property string list
3748 if (!wid_get_text_prop(ps, w->client_win, ps->atom_class, &strlst, &nstr))
3749 return false;
3750
3751 // Copy the strings if successful
3752 w->class_instance = mstrcpy(strlst[0]);
3753
3754 if (nstr > 1)
3755 w->class_general = mstrcpy(strlst[1]);
3756
3757 XFreeStringList(strlst);
3758
3759 #ifdef DEBUG_WINDATA
3760 printf_dbgf("(%#010lx): client = %#010lx, "
3761 "instance = \"%s\", general = \"%s\"\n",
3762 w->id, w->client_win, w->class_instance, w->class_general);
3763 #endif
3764
3765 return true;
3766 }
3767
3768 /**
3769 * Force a full-screen repaint.
3770 */
3771 void
3772 force_repaint(session_t *ps) {
3773 assert(ps->screen_reg);
3774 XserverRegion reg = None;
3775 if (ps->screen_reg && (reg = copy_region(ps, ps->screen_reg))) {
3776 ps->ev_received = true;
3777 add_damage(ps, reg);
3778 }
3779 }
3780
3781 #ifdef CONFIG_DBUS
3782 /** @name DBus hooks
3783 */
3784 ///@{
3785
3786 /**
3787 * Set w->shadow_force of a window.
3788 */
3789 void
3790 win_set_shadow_force(session_t *ps, win *w, switch_t val) {
3791 if (val != w->shadow_force) {
3792 w->shadow_force = val;
3793 win_determine_shadow(ps, w);
3794 ps->ev_received = true;
3795 }
3796 }
3797
3798 /**
3799 * Set w->fade_force of a window.
3800 */
3801 void
3802 win_set_fade_force(session_t *ps, win *w, switch_t val) {
3803 if (val != w->fade_force) {
3804 w->fade_force = val;
3805 win_determine_fade(ps, w);
3806 ps->ev_received = true;
3807 }
3808 }
3809
3810 /**
3811 * Set w->focused_force of a window.
3812 */
3813 void
3814 win_set_focused_force(session_t *ps, win *w, switch_t val) {
3815 if (val != w->focused_force) {
3816 w->focused_force = val;
3817 win_update_focused(ps, w);
3818 ps->ev_received = true;
3819 }
3820 }
3821
3822 /**
3823 * Set w->invert_color_force of a window.
3824 */
3825 void
3826 win_set_invert_color_force(session_t *ps, win *w, switch_t val) {
3827 if (val != w->invert_color_force) {
3828 w->invert_color_force = val;
3829 win_determine_invert_color(ps, w);
3830 ps->ev_received = true;
3831 }
3832 }
3833
3834 /**
3835 * Enable focus tracking.
3836 */
3837 void
3838 opts_init_track_focus(session_t *ps) {
3839 // Already tracking focus
3840 if (ps->o.track_focus)
3841 return;
3842
3843 ps->o.track_focus = true;
3844
3845 if (!ps->o.use_ewmh_active_win) {
3846 // Start listening to FocusChange events
3847 for (win *w = ps->list; w; w = w->next)
3848 if (IsViewable == w->a.map_state)
3849 XSelectInput(ps->dpy, w->id,
3850 determine_evmask(ps, w->id, WIN_EVMODE_FRAME));
3851 }
3852
3853 // Recheck focus
3854 recheck_focus(ps);
3855 }
3856
3857 /**
3858 * Set no_fading_openclose option.
3859 */
3860 void
3861 opts_set_no_fading_openclose(session_t *ps, bool newval) {
3862 if (newval != ps->o.no_fading_openclose) {
3863 ps->o.no_fading_openclose = newval;
3864 for (win *w = ps->list; w; w = w->next)
3865 win_determine_fade(ps, w);
3866 ps->ev_received = true;
3867 }
3868 }
3869
3870 //!@}
3871 #endif
3872
3873 #ifdef DEBUG_EVENTS
3874 static int
3875 ev_serial(XEvent *ev) {
3876 if ((ev->type & 0x7f) != KeymapNotify) {
3877 return ev->xany.serial;
3878 }
3879 return NextRequest(ev->xany.display);
3880 }
3881
3882 static const char *
3883 ev_name(session_t *ps, XEvent *ev) {
3884 static char buf[128];
3885 switch (ev->type & 0x7f) {
3886 CASESTRRET(FocusIn);
3887 CASESTRRET(FocusOut);
3888 CASESTRRET(CreateNotify);
3889 CASESTRRET(ConfigureNotify);
3890 CASESTRRET(DestroyNotify);
3891 CASESTRRET(MapNotify);
3892 CASESTRRET(UnmapNotify);
3893 CASESTRRET(ReparentNotify);
3894 CASESTRRET(CirculateNotify);
3895 CASESTRRET(Expose);
3896 CASESTRRET(PropertyNotify);
3897 CASESTRRET(ClientMessage);
3898 }
3899
3900 if (isdamagenotify(ps, ev))
3901 return "Damage";
3902
3903 if (ps->shape_exists && ev->type == ps->shape_event)
3904 return "ShapeNotify";
3905
3906 #ifdef CONFIG_XSYNC
3907 if (ps->xsync_exists) {
3908 int o = ev->type - ps->xsync_event;
3909 switch (o) {
3910 CASESTRRET(XSyncCounterNotify);
3911 CASESTRRET(XSyncAlarmNotify);
3912 }
3913 }
3914 #endif
3915
3916 sprintf(buf, "Event %d", ev->type);
3917
3918 return buf;
3919 }
3920
3921 static Window
3922 ev_window(session_t *ps, XEvent *ev) {
3923 switch (ev->type) {
3924 case FocusIn:
3925 case FocusOut:
3926 return ev->xfocus.window;
3927 case CreateNotify:
3928 return ev->xcreatewindow.window;
3929 case ConfigureNotify:
3930 return ev->xconfigure.window;
3931 case DestroyNotify:
3932 return ev->xdestroywindow.window;
3933 case MapNotify:
3934 return ev->xmap.window;
3935 case UnmapNotify:
3936 return ev->xunmap.window;
3937 case ReparentNotify:
3938 return ev->xreparent.window;
3939 case CirculateNotify:
3940 return ev->xcirculate.window;
3941 case Expose:
3942 return ev->xexpose.window;
3943 case PropertyNotify:
3944 return ev->xproperty.window;
3945 case ClientMessage:
3946 return ev->xclient.window;
3947 default:
3948 if (isdamagenotify(ps, ev)) {
3949 return ((XDamageNotifyEvent *)ev)->drawable;
3950 }
3951
3952 if (ps->shape_exists && ev->type == ps->shape_event) {
3953 return ((XShapeEvent *) ev)->window;
3954 }
3955
3956 return 0;
3957 }
3958 }
3959
3960 static inline const char *
3961 ev_focus_mode_name(XFocusChangeEvent* ev) {
3962 switch (ev->mode) {
3963 CASESTRRET(NotifyNormal);
3964 CASESTRRET(NotifyWhileGrabbed);
3965 CASESTRRET(NotifyGrab);
3966 CASESTRRET(NotifyUngrab);
3967 }
3968
3969 return "Unknown";
3970 }
3971
3972 static inline const char *
3973 ev_focus_detail_name(XFocusChangeEvent* ev) {
3974 switch (ev->detail) {
3975 CASESTRRET(NotifyAncestor);
3976 CASESTRRET(NotifyVirtual);
3977 CASESTRRET(NotifyInferior);
3978 CASESTRRET(NotifyNonlinear);
3979 CASESTRRET(NotifyNonlinearVirtual);
3980 CASESTRRET(NotifyPointer);
3981 CASESTRRET(NotifyPointerRoot);
3982 CASESTRRET(NotifyDetailNone);
3983 }
3984
3985 return "Unknown";
3986 }
3987
3988 static inline void
3989 ev_focus_report(XFocusChangeEvent* ev) {
3990 printf(" { mode: %s, detail: %s }\n", ev_focus_mode_name(ev),
3991 ev_focus_detail_name(ev));
3992 }
3993
3994 #endif
3995
3996 // === Events ===
3997
3998 /**
3999 * Determine whether we should respond to a <code>FocusIn/Out</code>
4000 * event.
4001 */
4002 /*
4003 inline static bool
4004 ev_focus_accept(XFocusChangeEvent *ev) {
4005 return NotifyNormal == ev->mode || NotifyUngrab == ev->mode;
4006 }
4007 */
4008
4009 static inline void
4010 ev_focus_in(session_t *ps, XFocusChangeEvent *ev) {
4011 #ifdef DEBUG_EVENTS
4012 ev_focus_report(ev);
4013 #endif
4014
4015 recheck_focus(ps);
4016 }
4017
4018 inline static void
4019 ev_focus_out(session_t *ps, XFocusChangeEvent *ev) {
4020 #ifdef DEBUG_EVENTS
4021 ev_focus_report(ev);
4022 #endif
4023
4024 recheck_focus(ps);
4025 }
4026
4027 inline static void
4028 ev_create_notify(session_t *ps, XCreateWindowEvent *ev) {
4029 assert(ev->parent == ps->root);
4030 add_win(ps, ev->window, 0);
4031 }
4032
4033 inline static void
4034 ev_configure_notify(session_t *ps, XConfigureEvent *ev) {
4035 #ifdef DEBUG_EVENTS
4036 printf(" { send_event: %d, "
4037 " above: %#010lx, "
4038 " override_redirect: %d }\n",
4039 ev->send_event, ev->above, ev->override_redirect);
4040 #endif
4041 configure_win(ps, ev);
4042 }
4043
4044 inline static void
4045 ev_destroy_notify(session_t *ps, XDestroyWindowEvent *ev) {
4046 destroy_win(ps, ev->window);
4047 }
4048
4049 inline static void
4050 ev_map_notify(session_t *ps, XMapEvent *ev) {
4051 map_win(ps, ev->window);
4052 }
4053
4054 inline static void
4055 ev_unmap_notify(session_t *ps, XUnmapEvent *ev) {
4056 win *w = find_win(ps, ev->window);
4057
4058 if (w)
4059 unmap_win(ps, w);
4060 }
4061
4062 inline static void
4063 ev_reparent_notify(session_t *ps, XReparentEvent *ev) {
4064 #ifdef DEBUG_EVENTS
4065 printf_dbg(" { new_parent: %#010lx, override_redirect: %d }\n",
4066 ev->parent, ev->override_redirect);
4067 #endif
4068
4069 if (ev->parent == ps->root) {
4070 add_win(ps, ev->window, 0);
4071 } else {
4072 destroy_win(ps, ev->window);
4073
4074 // Reset event mask in case something wrong happens
4075 XSelectInput(ps->dpy, ev->window,
4076 determine_evmask(ps, ev->window, WIN_EVMODE_UNKNOWN));
4077
4078 // Check if the window is an undetected client window
4079 // Firstly, check if it's a known client window
4080 if (!find_toplevel(ps, ev->window)) {
4081 // If not, look for its frame window
4082 win *w_top = find_toplevel2(ps, ev->parent);
4083 // If found, and the client window has not been determined, or its
4084 // frame may not have a correct client, continue
4085 if (w_top && (!w_top->client_win
4086 || w_top->client_win == w_top->id)) {
4087 // If it has WM_STATE, mark it the client window
4088 if (wid_has_prop(ps, ev->window, ps->atom_client)) {
4089 w_top->wmwin = false;
4090 win_unmark_client(ps, w_top);
4091 win_mark_client(ps, w_top, ev->window);
4092 }
4093 // Otherwise, watch for WM_STATE on it
4094 else {
4095 XSelectInput(ps->dpy, ev->window,
4096 determine_evmask(ps, ev->window, WIN_EVMODE_UNKNOWN)
4097 | PropertyChangeMask);
4098 }
4099 }
4100 }
4101 }
4102 }
4103
4104 inline static void
4105 ev_circulate_notify(session_t *ps, XCirculateEvent *ev) {
4106 circulate_win(ps, ev);
4107 }
4108
4109 inline static void
4110 ev_expose(session_t *ps, XExposeEvent *ev) {
4111 if (ev->window == ps->root || (ps->overlay && ev->window == ps->overlay)) {
4112 int more = ev->count + 1;
4113 if (ps->n_expose == ps->size_expose) {
4114 if (ps->expose_rects) {
4115 ps->expose_rects = realloc(ps->expose_rects,
4116 (ps->size_expose + more) * sizeof(XRectangle));
4117 ps->size_expose += more;
4118 } else {
4119 ps->expose_rects = malloc(more * sizeof(XRectangle));
4120 ps->size_expose = more;
4121 }
4122 }
4123
4124 ps->expose_rects[ps->n_expose].x = ev->x;
4125 ps->expose_rects[ps->n_expose].y = ev->y;
4126 ps->expose_rects[ps->n_expose].width = ev->width;
4127 ps->expose_rects[ps->n_expose].height = ev->height;
4128 ps->n_expose++;
4129
4130 if (ev->count == 0) {
4131 expose_root(ps, ps->expose_rects, ps->n_expose);
4132 ps->n_expose = 0;
4133 }
4134 }
4135 }
4136
4137 /**
4138 * Update current active window based on EWMH _NET_ACTIVE_WIN.
4139 *
4140 * Does not change anything if we fail to get the attribute or the window
4141 * returned could not be found.
4142 */
4143 static void
4144 update_ewmh_active_win(session_t *ps) {
4145 // Search for the window
4146 Window wid = wid_get_prop_window(ps, ps->root, ps->atom_ewmh_active_win);
4147 win *w = find_win_all(ps, wid);
4148
4149 // Mark the window focused. No need to unfocus the previous one.
4150 if (w) win_set_focused(ps, w, true);
4151 }
4152
4153 inline static void
4154 ev_property_notify(session_t *ps, XPropertyEvent *ev) {
4155 #ifdef DEBUG_EVENTS
4156 {
4157 // Print out changed atom
4158 char *name = XGetAtomName(ps->dpy, ev->atom);
4159 printf_dbg(" { atom = %s }\n", name);
4160 cxfree(name);
4161 }
4162 #endif
4163
4164 if (ps->root == ev->window) {
4165 if (ps->o.track_focus && ps->o.use_ewmh_active_win
4166 && ps->atom_ewmh_active_win == ev->atom) {
4167 update_ewmh_active_win(ps);
4168 }
4169 else {
4170 // Destroy the root "image" if the wallpaper probably changed
4171 for (int p = 0; background_props_str[p]; p++) {
4172 if (ev->atom == get_atom(ps, background_props_str[p])) {
4173 root_damaged(ps);
4174 break;
4175 }
4176 }
4177 }
4178
4179 // Unconcerned about any other proprties on root window
4180 return;
4181 }
4182
4183 // If WM_STATE changes
4184 if (ev->atom == ps->atom_client) {
4185 // Check whether it could be a client window
4186 if (!find_toplevel(ps, ev->window)) {
4187 // Reset event mask anyway
4188 XSelectInput(ps->dpy, ev->window,
4189 determine_evmask(ps, ev->window, WIN_EVMODE_UNKNOWN));
4190
4191 win *w_top = find_toplevel2(ps, ev->window);
4192 // Initialize client_win as early as possible
4193 if (w_top && (!w_top->client_win || w_top->client_win == w_top->id)
4194 && wid_has_prop(ps, ev->window, ps->atom_client)) {
4195 w_top->wmwin = false;
4196 win_unmark_client(ps, w_top);
4197 win_mark_client(ps, w_top, ev->window);
4198 }
4199 }
4200 }
4201
4202 // If _NET_WM_WINDOW_TYPE changes... God knows why this would happen, but
4203 // there are always some stupid applications. (#144)
4204 if (ev->atom == ps->atom_win_type) {
4205 win *w = NULL;
4206 if ((w = find_toplevel(ps, ev->window)))
4207 win_upd_wintype(ps, w);
4208 }
4209
4210 // If _NET_WM_OPACITY changes
4211 if (ev->atom == ps->atom_opacity) {
4212 win *w = find_win(ps, ev->window) ?: find_toplevel(ps, ev->window);
4213 if (w) {
4214 win_update_opacity_prop(ps, w);
4215 w->flags |= WFLAG_OPCT_CHANGE;
4216 }
4217 }
4218
4219 // If frame extents property changes
4220 if (ps->o.frame_opacity && ev->atom == ps->atom_frame_extents) {
4221 win *w = find_toplevel(ps, ev->window);
4222 if (w) {
4223 get_frame_extents(ps, w, ev->window);
4224 // If frame extents change, the window needs repaint
4225 add_damage_win(ps, w);
4226 }
4227 }
4228
4229 // If name changes
4230 if (ps->o.track_wdata
4231 && (ps->atom_name == ev->atom || ps->atom_name_ewmh == ev->atom)) {
4232 win *w = find_toplevel(ps, ev->window);
4233 if (w && 1 == win_get_name(ps, w)) {
4234 win_on_factor_change(ps, w);
4235 }
4236 }
4237
4238 // If class changes
4239 if (ps->o.track_wdata && ps->atom_class == ev->atom) {
4240 win *w = find_toplevel(ps, ev->window);
4241 if (w) {
4242 win_get_class(ps, w);
4243 win_on_factor_change(ps, w);
4244 }
4245 }
4246
4247 // If role changes
4248 if (ps->o.track_wdata && ps->atom_role == ev->atom) {
4249 win *w = find_toplevel(ps, ev->window);
4250 if (w && 1 == win_get_role(ps, w)) {
4251 win_on_factor_change(ps, w);
4252 }
4253 }
4254
4255 // If _COMPTON_SHADOW changes
4256 if (ps->o.respect_prop_shadow && ps->atom_compton_shadow == ev->atom) {
4257 win *w = find_win(ps, ev->window);
4258 if (w)
4259 win_update_prop_shadow(ps, w);
4260 }
4261
4262 // If a leader property changes
4263 if ((ps->o.detect_transient && ps->atom_transient == ev->atom)
4264 || (ps->o.detect_client_leader && ps->atom_client_leader == ev->atom)) {
4265 win *w = find_toplevel(ps, ev->window);
4266 if (w) {
4267 win_update_leader(ps, w);
4268 }
4269 }
4270
4271 // Check for other atoms we are tracking
4272 for (latom_t *platom = ps->track_atom_lst; platom; platom = platom->next) {
4273 if (platom->atom == ev->atom) {
4274 win *w = find_win(ps, ev->window);
4275 if (!w)
4276 w = find_toplevel(ps, ev->window);
4277 if (w)
4278 win_on_factor_change(ps, w);
4279 break;
4280 }
4281 }
4282 }
4283
4284 inline static void
4285 ev_damage_notify(session_t *ps, XDamageNotifyEvent *ev) {
4286 damage_win(ps, ev);
4287 }
4288
4289 inline static void
4290 ev_shape_notify(session_t *ps, XShapeEvent *ev) {
4291 win *w = find_win(ps, ev->window);
4292 if (!w || IsUnmapped == w->a.map_state) return;
4293
4294 /*
4295 * Empty border_size may indicated an
4296 * unmapped/destroyed window, in which case
4297 * seemingly BadRegion errors would be triggered
4298 * if we attempt to rebuild border_size
4299 */
4300 if (w->border_size) {
4301 // Mark the old border_size as damaged
4302 add_damage(ps, w->border_size);
4303
4304 w->border_size = border_size(ps, w, true);
4305
4306 // Mark the new border_size as damaged
4307 add_damage(ps, copy_region(ps, w->border_size));
4308 }
4309
4310 // Redo bounding shape detection and rounded corner detection
4311 win_update_shape(ps, w);
4312
4313 update_reg_ignore_expire(ps, w);
4314 }
4315
4316 /**
4317 * Handle ScreenChangeNotify events from X RandR extension.
4318 */
4319 static void
4320 ev_screen_change_notify(session_t *ps,
4321 XRRScreenChangeNotifyEvent __attribute__((unused)) *ev) {
4322 if (ps->o.xinerama_shadow_crop)
4323 cxinerama_upd_scrs(ps);
4324
4325 if (ps->o.sw_opti && !ps->o.refresh_rate) {
4326 update_refresh_rate(ps);
4327 if (!ps->refresh_rate) {
4328 fprintf(stderr, "ev_screen_change_notify(): Refresh rate detection "
4329 "failed, --sw-opti disabled.");
4330 ps->o.sw_opti = false;
4331 }
4332 }
4333 }
4334
4335 inline static void
4336 ev_selection_clear(session_t *ps,
4337 XSelectionClearEvent __attribute__((unused)) *ev) {
4338 // The only selection we own is the _NET_WM_CM_Sn selection.
4339 // If we lose that one, we should exit.
4340 fprintf(stderr, "Another composite manager started and "
4341 "took the _NET_WM_CM_Sn selection.\n");
4342 exit(1);
4343 }
4344
4345 #if defined(DEBUG_EVENTS) || defined(DEBUG_RESTACK)
4346 /**
4347 * Get a window's name from window ID.
4348 */
4349 static bool
4350 ev_window_name(session_t *ps, Window wid, char **name) {
4351 bool to_free = false;
4352
4353 *name = "";
4354 if (wid) {
4355 *name = "(Failed to get title)";
4356 if (ps->root == wid)
4357 *name = "(Root window)";
4358 else if (ps->overlay == wid)
4359 *name = "(Overlay)";
4360 else {
4361 win *w = find_win(ps, wid);
4362 if (!w)
4363 w = find_toplevel(ps, wid);
4364
4365 if (w && w->name)
4366 *name = w->name;
4367 else if (!(w && w->client_win
4368 && (to_free = wid_get_name(ps, w->client_win, name))))
4369 to_free = wid_get_name(ps, wid, name);
4370 }
4371 }
4372
4373 return to_free;
4374 }
4375 #endif
4376
4377 static void
4378 ev_handle(session_t *ps, XEvent *ev) {
4379 if ((ev->type & 0x7f) != KeymapNotify) {
4380 discard_ignore(ps, ev->xany.serial);
4381 }
4382
4383 #ifdef DEBUG_EVENTS
4384 if (!isdamagenotify(ps, ev)) {
4385 Window wid = ev_window(ps, ev);
4386 char *window_name = NULL;
4387 bool to_free = false;
4388
4389 to_free = ev_window_name(ps, wid, &window_name);
4390
4391 print_timestamp(ps);
4392 printf("event %10.10s serial %#010x window %#010lx \"%s\"\n",
4393 ev_name(ps, ev), ev_serial(ev), wid, window_name);
4394
4395 if (to_free) {
4396 cxfree(window_name);
4397 window_name = NULL;
4398 }
4399 }
4400
4401 #endif
4402
4403 switch (ev->type) {
4404 case FocusIn:
4405 ev_focus_in(ps, (XFocusChangeEvent *)ev);
4406 break;
4407 case FocusOut:
4408 ev_focus_out(ps, (XFocusChangeEvent *)ev);
4409 break;
4410 case CreateNotify:
4411 ev_create_notify(ps, (XCreateWindowEvent *)ev);
4412 break;
4413 case ConfigureNotify:
4414 ev_configure_notify(ps, (XConfigureEvent *)ev);
4415 break;
4416 case DestroyNotify:
4417 ev_destroy_notify(ps, (XDestroyWindowEvent *)ev);
4418 break;
4419 case MapNotify:
4420 ev_map_notify(ps, (XMapEvent *)ev);
4421 break;
4422 case UnmapNotify:
4423 ev_unmap_notify(ps, (XUnmapEvent *)ev);
4424 break;
4425 case ReparentNotify:
4426 ev_reparent_notify(ps, (XReparentEvent *)ev);
4427 break;
4428 case CirculateNotify:
4429 ev_circulate_notify(ps, (XCirculateEvent *)ev);
4430 break;
4431 case Expose:
4432 ev_expose(ps, (XExposeEvent *)ev);
4433 break;
4434 case PropertyNotify:
4435 ev_property_notify(ps, (XPropertyEvent *)ev);
4436 break;
4437 case SelectionClear:
4438 ev_selection_clear(ps, (XSelectionClearEvent *)ev);
4439 break;
4440 default:
4441 if (ps->shape_exists && ev->type == ps->shape_event) {
4442 ev_shape_notify(ps, (XShapeEvent *) ev);
4443 break;
4444 }
4445 if (ps->randr_exists && ev->type == (ps->randr_event + RRScreenChangeNotify)) {
4446 ev_screen_change_notify(ps, (XRRScreenChangeNotifyEvent *) ev);
4447 break;
4448 }
4449 if (isdamagenotify(ps, ev)) {
4450 ev_damage_notify(ps, (XDamageNotifyEvent *) ev);
4451 break;
4452 }
4453 }
4454 }
4455
4456 // === Main ===
4457
4458 /**
4459 * Print usage text and exit.
4460 */
4461 static void
4462 usage(int ret) {
4463 #define WARNING_DISABLED " (DISABLED AT COMPILE TIME)"
4464 #define WARNING
4465 const static char *usage_text =
4466 "compton (" COMPTON_VERSION ")\n"
4467 "This is the maintenance fork of compton, please report\n"
4468 "bugs to https://github.com/yshui/compton\n\n"
4469 "usage: compton [options]\n"
4470 "Options:\n"
4471 "\n"
4472 "-d display\n"
4473 " Which display should be managed.\n"
4474 "\n"
4475 "-r radius\n"
4476 " The blur radius for shadows. (default 12)\n"
4477 "\n"
4478 "-o opacity\n"
4479 " The translucency for shadows. (default .75)\n"
4480 "\n"
4481 "-l left-offset\n"
4482 " The left offset for shadows. (default -15)\n"
4483 "\n"
4484 "-t top-offset\n"
4485 " The top offset for shadows. (default -15)\n"
4486 "\n"
4487 "-I fade-in-step\n"
4488 " Opacity change between steps while fading in. (default 0.028)\n"
4489 "\n"
4490 "-O fade-out-step\n"
4491 " Opacity change between steps while fading out. (default 0.03)\n"
4492 "\n"
4493 "-D fade-delta-time\n"
4494 " The time between steps in a fade in milliseconds. (default 10)\n"
4495 "\n"
4496 "-m opacity\n"
4497 " The opacity for menus. (default 1.0)\n"
4498 "\n"
4499 "-c\n"
4500 " Enabled client-side shadows on windows.\n"
4501 "\n"
4502 "-C\n"
4503 " Avoid drawing shadows on dock/panel windows.\n"
4504 "\n"
4505 "-z\n"
4506 " Zero the part of the shadow's mask behind the window.\n"
4507 "\n"
4508 "-f\n"
4509 " Fade windows in/out when opening/closing and when opacity\n"
4510 " changes, unless --no-fading-openclose is used.\n"
4511 "\n"
4512 "-F\n"
4513 " Equals to -f. Deprecated.\n"
4514 "\n"
4515 "-i opacity\n"
4516 " Opacity of inactive windows. (0.1 - 1.0)\n"
4517 "\n"
4518 "-e opacity\n"
4519 " Opacity of window titlebars and borders. (0.1 - 1.0)\n"
4520 "\n"
4521 "-G\n"
4522 " Don't draw shadows on DND windows\n"
4523 "\n"
4524 "-b\n"
4525 " Daemonize process.\n"
4526 "\n"
4527 "-S\n"
4528 " Enable synchronous operation (for debugging).\n"
4529 "\n"
4530 "--show-all-xerrors\n"
4531 " Show all X errors (for debugging).\n"
4532 "\n"
4533 #undef WARNING
4534 #ifndef CONFIG_LIBCONFIG
4535 #define WARNING WARNING_DISABLED
4536 #else
4537 #define WARNING
4538 #endif
4539 "--config path\n"
4540 " Look for configuration file at the path. Use /dev/null to avoid\n"
4541 " loading configuration file." WARNING "\n"
4542 "\n"
4543 "--write-pid-path path\n"
4544 " Write process ID to a file.\n"
4545 "\n"
4546 "--shadow-red value\n"
4547 " Red color value of shadow (0.0 - 1.0, defaults to 0).\n"
4548 "\n"
4549 "--shadow-green value\n"
4550 " Green color value of shadow (0.0 - 1.0, defaults to 0).\n"
4551 "\n"
4552 "--shadow-blue value\n"
4553 " Blue color value of shadow (0.0 - 1.0, defaults to 0).\n"
4554 "\n"
4555 "--inactive-opacity-override\n"
4556 " Inactive opacity set by -i overrides value of _NET_WM_OPACITY.\n"
4557 "\n"
4558 "--inactive-dim value\n"
4559 " Dim inactive windows. (0.0 - 1.0, defaults to 0)\n"
4560 "\n"
4561 "--active-opacity opacity\n"
4562 " Default opacity for active windows. (0.0 - 1.0)\n"
4563 "\n"
4564 "--mark-wmwin-focused\n"
4565 " Try to detect WM windows and mark them as active.\n"
4566 "\n"
4567 "--shadow-exclude condition\n"
4568 " Exclude conditions for shadows.\n"
4569 "\n"
4570 "--fade-exclude condition\n"
4571 " Exclude conditions for fading.\n"
4572 "\n"
4573 "--mark-ovredir-focused\n"
4574 " Mark windows that have no WM frame as active.\n"
4575 "\n"
4576 "--no-fading-openclose\n"
4577 " Do not fade on window open/close.\n"
4578 "\n"
4579 "--no-fading-destroyed-argb\n"
4580 " Do not fade destroyed ARGB windows with WM frame. Workaround of bugs\n"
4581 " in Openbox, Fluxbox, etc.\n"
4582 "\n"
4583 "--shadow-ignore-shaped\n"
4584 " Do not paint shadows on shaped windows. (Deprecated, use\n"
4585 " --shadow-exclude \'bounding_shaped\' or\n"
4586 " --shadow-exclude \'bounding_shaped && !rounded_corners\' instead.)\n"
4587 "\n"
4588 "--detect-rounded-corners\n"
4589 " Try to detect windows with rounded corners and don't consider\n"
4590 " them shaped windows. Affects --shadow-ignore-shaped,\n"
4591 " --unredir-if-possible, and possibly others. You need to turn this\n"
4592 " on manually if you want to match against rounded_corners in\n"
4593 " conditions.\n"
4594 "\n"
4595 "--detect-client-opacity\n"
4596 " Detect _NET_WM_OPACITY on client windows, useful for window\n"
4597 " managers not passing _NET_WM_OPACITY of client windows to frame\n"
4598 " windows.\n"
4599 "\n"
4600 "--refresh-rate val\n"
4601 " Specify refresh rate of the screen. If not specified or 0, compton\n"
4602 " will try detecting this with X RandR extension.\n"
4603 "\n"
4604 "--vsync vsync-method\n"
4605 " Set VSync method. There are (up to) 5 VSync methods currently\n"
4606 " available:\n"
4607 " none = No VSync\n"
4608 #undef WARNING
4609 #ifndef CONFIG_VSYNC_DRM
4610 #define WARNING WARNING_DISABLED
4611 #else
4612 #define WARNING
4613 #endif
4614 " drm = VSync with DRM_IOCTL_WAIT_VBLANK. May only work on some\n"
4615 " (DRI-based) drivers." WARNING "\n"
4616 #undef WARNING
4617 #ifndef CONFIG_VSYNC_OPENGL
4618 #define WARNING WARNING_DISABLED
4619 #else
4620 #define WARNING
4621 #endif
4622 " opengl = Try to VSync with SGI_video_sync OpenGL extension. Only\n"
4623 " work on some drivers." WARNING"\n"
4624 " opengl-oml = Try to VSync with OML_sync_control OpenGL extension.\n"
4625 " Only work on some drivers." WARNING"\n"
4626 " opengl-swc = Try to VSync with SGI_swap_control OpenGL extension.\n"
4627 " Only work on some drivers. Works only with GLX backend." WARNING "\n"
4628 " opengl-mswc = Try to VSync with MESA_swap_control OpenGL\n"
4629 " extension. Basically the same as opengl-swc above, except the\n"
4630 " extension we use." WARNING "\n"
4631 "\n"
4632 "--vsync-aggressive\n"
4633 " Attempt to send painting request before VBlank and do XFlush()\n"
4634 " during VBlank. This switch may be lifted out at any moment.\n"
4635 "\n"
4636 "--alpha-step val\n"
4637 " X Render backend: Step for pregenerating alpha pictures. \n"
4638 " 0.01 - 1.0. Defaults to 0.03.\n"
4639 "\n"
4640 "--dbe\n"
4641 " Enable DBE painting mode, intended to use with VSync to\n"
4642 " (hopefully) eliminate tearing.\n"
4643 "\n"
4644 "--paint-on-overlay\n"
4645 " Painting on X Composite overlay window.\n"
4646 "\n"
4647 "--sw-opti\n"
4648 " Limit compton to repaint at most once every 1 / refresh_rate\n"
4649 " second to boost performance.\n"
4650 "\n"
4651 "--use-ewmh-active-win\n"
4652 " Use _NET_WM_ACTIVE_WINDOW on the root window to determine which\n"
4653 " window is focused instead of using FocusIn/Out events.\n"
4654 "\n"
4655 "--respect-prop-shadow\n"
4656 " Respect _COMPTON_SHADOW. This a prototype-level feature, which\n"
4657 " you must not rely on.\n"
4658 "\n"
4659 "--unredir-if-possible\n"
4660 " Unredirect all windows if a full-screen opaque window is\n"
4661 " detected, to maximize performance for full-screen windows.\n"
4662 "\n"
4663 "--unredir-if-possible-delay ms\n"
4664 " Delay before unredirecting the window, in milliseconds.\n"
4665 " Defaults to 0.\n"
4666 "\n"
4667 "--unredir-if-possible-exclude condition\n"
4668 " Conditions of windows that shouldn't be considered full-screen\n"
4669 " for unredirecting screen.\n"
4670 "\n"
4671 "--focus-exclude condition\n"
4672 " Specify a list of conditions of windows that should always be\n"
4673 " considered focused.\n"
4674 "\n"
4675 "--inactive-dim-fixed\n"
4676 " Use fixed inactive dim value.\n"
4677 "\n"
4678 "--detect-transient\n"
4679 " Use WM_TRANSIENT_FOR to group windows, and consider windows in\n"
4680 " the same group focused at the same time.\n"
4681 "\n"
4682 "--detect-client-leader\n"
4683 " Use WM_CLIENT_LEADER to group windows, and consider windows in\n"
4684 " the same group focused at the same time. WM_TRANSIENT_FOR has\n"
4685 " higher priority if --detect-transient is enabled, too.\n"
4686 "\n"
4687 "--blur-background\n"
4688 " Blur background of semi-transparent / ARGB windows. Bad in\n"
4689 " performance. The switch name may change without prior\n"
4690 " notifications.\n"
4691 "\n"
4692 "--blur-background-frame\n"
4693 " Blur background of windows when the window frame is not opaque.\n"
4694 " Implies --blur-background. Bad in performance. The switch name\n"
4695 " may change.\n"
4696 "\n"
4697 "--blur-background-fixed\n"
4698 " Use fixed blur strength instead of adjusting according to window\n"
4699 " opacity.\n"
4700 "\n"
4701 "--blur-kern matrix\n"
4702 " Specify the blur convolution kernel, with the following format:\n"
4703 " WIDTH,HEIGHT,ELE1,ELE2,ELE3,ELE4,ELE5...\n"
4704 " The element in the center must not be included, it will be forever\n"
4705 " 1.0 or changing based on opacity, depending on whether you have\n"
4706 " --blur-background-fixed.\n"
4707 " A 7x7 Gaussian blur kernel looks like:\n"
4708 " --blur-kern '7,7,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000102,0.003494,0.029143,0.059106,0.029143,0.003494,0.000102,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.001723,0.059106,0.493069,0.493069,0.059106,0.001723,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000102,0.003494,0.029143,0.059106,0.029143,0.003494,0.000102,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003'\n"
4709 " Up to 4 blur kernels may be specified, separated with semicolon, for\n"
4710 " multi-pass blur.\n"
4711 " May also be one the predefined kernels: 3x3box (default), 5x5box,\n"
4712 " 7x7box, 3x3gaussian, 5x5gaussian, 7x7gaussian, 9x9gaussian,\n"
4713 " 11x11gaussian.\n"
4714 "\n"
4715 "--blur-background-exclude condition\n"
4716 " Exclude conditions for background blur.\n"
4717 "\n"
4718 "--resize-damage integer\n"
4719 " Resize damaged region by a specific number of pixels. A positive\n"
4720 " value enlarges it while a negative one shrinks it. Useful for\n"
4721 " fixing the line corruption issues of blur. May or may not\n"
4722 " work with --glx-no-stencil. Shrinking doesn't function correctly.\n"
4723 "\n"
4724 "--invert-color-include condition\n"
4725 " Specify a list of conditions of windows that should be painted with\n"
4726 " inverted color. Resource-hogging, and is not well tested.\n"
4727 "\n"
4728 "--opacity-rule opacity:condition\n"
4729 " Specify a list of opacity rules, in the format \"PERCENT:PATTERN\",\n"
4730 " like \'50:name *= \"Firefox\"'. compton-trans is recommended over\n"
4731 " this. Note we do not distinguish 100% and unset, and we don't make\n"
4732 " any guarantee about possible conflicts with other programs that set\n"
4733 " _NET_WM_WINDOW_OPACITY on frame or client windows.\n"
4734 "\n"
4735 "--shadow-exclude-reg geometry\n"
4736 " Specify a X geometry that describes the region in which shadow\n"
4737 " should not be painted in, such as a dock window region.\n"
4738 " Use --shadow-exclude-reg \'x10+0-0\', for example, if the 10 pixels\n"
4739 " on the bottom of the screen should not have shadows painted on.\n"
4740 #undef WARNING
4741 #ifndef CONFIG_XINERAMA
4742 #define WARNING WARNING_DISABLED
4743 #else
4744 #define WARNING
4745 #endif
4746 "\n"
4747 "--xinerama-shadow-crop\n"
4748 " Crop shadow of a window fully on a particular Xinerama screen to the\n"
4749 " screen." WARNING "\n"
4750 "\n"
4751 #undef WARNING
4752 #ifndef CONFIG_VSYNC_OPENGL
4753 #define WARNING "(GLX BACKENDS DISABLED AT COMPILE TIME)"
4754 #else
4755 #define WARNING
4756 #endif
4757 "--backend backend\n"
4758 " Choose backend. Possible choices are xrender, glx, and\n"
4759 " xr_glx_hybrid" WARNING ".\n"
4760 "\n"
4761 "--glx-no-stencil\n"
4762 " GLX backend: Avoid using stencil buffer. Might cause issues\n"
4763 " when rendering transparent content. My tests show a 15% performance\n"
4764 " boost.\n"
4765 "\n"
4766 "--glx-copy-from-front\n"
4767 " GLX backend: Copy unmodified regions from front buffer instead of\n"
4768 " redrawing them all. My tests with nvidia-drivers show a 5% decrease\n"
4769 " in performance when the whole screen is modified, but a 30% increase\n"
4770 " when only 1/4 is. My tests on nouveau show terrible slowdown. Could\n"
4771 " work with --glx-swap-method but not --glx-use-copysubbuffermesa.\n"
4772 "\n"
4773 "--glx-use-copysubbuffermesa\n"
4774 " GLX backend: Use MESA_copy_sub_buffer to do partial screen update.\n"
4775 " My tests on nouveau shows a 200% performance boost when only 1/4 of\n"
4776 " the screen is updated. May break VSync and is not available on some\n"
4777 " drivers. Overrides --glx-copy-from-front.\n"
4778 "\n"
4779 "--glx-no-rebind-pixmap\n"
4780 " GLX backend: Avoid rebinding pixmap on window damage. Probably\n"
4781 " could improve performance on rapid window content changes, but is\n"
4782 " known to break things on some drivers (LLVMpipe, xf86-video-intel,\n"
4783 " etc.).\n"
4784 "\n"
4785 "--glx-swap-method undefined/copy/exchange/3/4/5/6/buffer-age\n"
4786 " GLX backend: GLX buffer swap method we assume. Could be\n"
4787 " undefined (0), copy (1), exchange (2), 3-6, or buffer-age (-1).\n"
4788 " \"undefined\" is the slowest and the safest, and the default value.\n"
4789 " 1 is fastest, but may fail on some drivers, 2-6 are gradually slower\n"
4790 " but safer (6 is still faster than 0). -1 means auto-detect using\n"
4791 " GLX_EXT_buffer_age, supported by some drivers. Useless with\n"
4792 " --glx-use-copysubbuffermesa.\n"
4793 "\n"
4794 "--glx-use-gpushader4\n"
4795 " GLX backend: Use GL_EXT_gpu_shader4 for some optimization on blur\n"
4796 " GLSL code. My tests on GTX 670 show no noticeable effect.\n"
4797 "\n"
4798 "--xrender-sync\n"
4799 " Attempt to synchronize client applications' draw calls with XSync(),\n"
4800 " used on GLX backend to ensure up-to-date window content is painted.\n"
4801 #undef WARNING
4802 #ifndef CONFIG_XSYNC
4803 #define WARNING WARNING_DISABLED
4804 #else
4805 #define WARNING
4806 #endif
4807 "\n"
4808 "--xrender-sync-fence\n"
4809 " Additionally use X Sync fence to sync clients' draw calls. Needed\n"
4810 " on nvidia-drivers with GLX backend for some users." WARNING "\n"
4811 "\n"
4812 "--glx-fshader-win shader\n"
4813 " GLX backend: Use specified GLSL fragment shader for rendering window\n"
4814 " contents.\n"
4815 "\n"
4816 "--force-win-blend\n"
4817 " Force all windows to be painted with blending. Useful if you have a\n"
4818 " --glx-fshader-win that could turn opaque pixels transparent.\n"
4819 "\n"
4820 #undef WARNING
4821 #ifndef CONFIG_DBUS
4822 #define WARNING WARNING_DISABLED
4823 #else
4824 #define WARNING
4825 #endif
4826 "--dbus\n"
4827 " Enable remote control via D-Bus. See the D-BUS API section in the\n"
4828 " man page for more details." WARNING "\n"
4829 "\n"
4830 "--benchmark cycles\n"
4831 " Benchmark mode. Repeatedly paint until reaching the specified cycles.\n"
4832 "\n"
4833 "--benchmark-wid window-id\n"
4834 " Specify window ID to repaint in benchmark mode. If omitted or is 0,\n"
4835 " the whole screen is repainted.\n"
4836 ;
4837 FILE *f = (ret ? stderr: stdout);
4838 fputs(usage_text, f);
4839 #undef WARNING
4840 #undef WARNING_DISABLED
4841
4842 exit(ret);
4843 }
4844
4845 /**
4846 * Register a window as symbol, and initialize GLX context if wanted.
4847 */
4848 static bool
4849 register_cm(session_t *ps) {
4850 assert(!ps->reg_win);
4851
4852 ps->reg_win = XCreateSimpleWindow(ps->dpy, ps->root, 0, 0, 1, 1, 0,
4853 None, None);
4854
4855 if (!ps->reg_win) {
4856 printf_errf("(): Failed to create window.");
4857 return false;
4858 }
4859
4860 // Unredirect the window if it's redirected, just in case
4861 if (ps->redirected)
4862 XCompositeUnredirectWindow(ps->dpy, ps->reg_win, CompositeRedirectManual);
4863
4864 {
4865 XClassHint *h = XAllocClassHint();
4866 if (h) {
4867 h->res_name = "compton";
4868 h->res_class = "xcompmgr";
4869 }
4870 Xutf8SetWMProperties(ps->dpy, ps->reg_win, "xcompmgr", "xcompmgr",
4871 NULL, 0, NULL, NULL, h);
4872 cxfree(h);
4873 }
4874
4875 // Set _NET_WM_PID
4876 {
4877 long pid = getpid();
4878 if (!XChangeProperty(ps->dpy, ps->reg_win,
4879 get_atom(ps, "_NET_WM_PID"), XA_CARDINAL, 32, PropModeReplace,
4880 (unsigned char *) &pid, 1)) {
4881 printf_errf("(): Failed to set _NET_WM_PID.");
4882 }
4883 }
4884
4885 // Set COMPTON_VERSION
4886 if (!wid_set_text_prop(ps, ps->reg_win, get_atom(ps, "COMPTON_VERSION"), COMPTON_VERSION)) {
4887 printf_errf("(): Failed to set COMPTON_VERSION.");
4888 }
4889
4890 // Acquire X Selection _NET_WM_CM_S?
4891 if (!ps->o.no_x_selection) {
4892 unsigned len = strlen(REGISTER_PROP) + 2;
4893 int s = ps->scr;
4894 Atom atom;
4895
4896 while (s >= 10) {
4897 ++len;
4898 s /= 10;
4899 }
4900
4901 char *buf = malloc(len);
4902 snprintf(buf, len, REGISTER_PROP "%d", ps->scr);
4903 buf[len - 1] = '\0';
4904 atom = get_atom(ps, buf);
4905
4906 if (XGetSelectionOwner(ps->dpy, atom) != None) {
4907 fprintf(stderr, "Another composite manager is already running\n");
4908 return false;
4909 }
4910 XSetSelectionOwner(ps->dpy, atom, ps->reg_win, 0);
4911 free(buf);
4912 }
4913
4914 return true;
4915 }
4916
4917 /**
4918 * Reopen streams for logging.
4919 */
4920 static bool
4921 ostream_reopen(session_t *ps, const char *path) {
4922 if (!path)
4923 path = ps->o.logpath;
4924 if (!path)
4925 path = "/dev/null";
4926
4927 bool success = freopen(path, "a", stdout);
4928 success = freopen(path, "a", stderr) && success;
4929 if (!success)
4930 printf_errfq(1, "(%s): freopen() failed.", path);
4931
4932 return success;
4933 }
4934
4935 /**
4936 * Fork program to background and disable all I/O streams.
4937 */
4938 static inline bool
4939 fork_after(session_t *ps) {
4940 if (getppid() == 1)
4941 return true;
4942
4943 #ifdef CONFIG_VSYNC_OPENGL
4944 // GLX context must be released and reattached on fork
4945 if (glx_has_context(ps) && !glXMakeCurrent(ps->dpy, None, NULL)) {
4946 printf_errf("(): Failed to detach GLx context.");
4947 return false;
4948 }
4949 #endif
4950
4951 int pid = fork();
4952
4953 if (-1 == pid) {
4954 printf_errf("(): fork() failed.");
4955 return false;
4956 }
4957
4958 if (pid > 0) _exit(0);
4959
4960 setsid();
4961
4962 #ifdef CONFIG_VSYNC_OPENGL
4963 if (glx_has_context(ps)
4964 && !glXMakeCurrent(ps->dpy, get_tgt_window(ps), ps->psglx->context)) {
4965 printf_errf("(): Failed to make GLX context current.");
4966 return false;
4967 }
4968 #endif
4969
4970 // Mainly to suppress the _FORTIFY_SOURCE warning
4971 bool success = freopen("/dev/null", "r", stdin);
4972 if (!success) {
4973 printf_errf("(): freopen() failed.");
4974 return false;
4975 }
4976
4977 return success;
4978 }
4979
4980 /**
4981 * Write PID to a file.
4982 */
4983 static inline bool
4984 write_pid(session_t *ps) {
4985 if (!ps->o.write_pid_path)
4986 return true;
4987
4988 FILE *f = fopen(ps->o.write_pid_path, "w");
4989 if (unlikely(!f)) {
4990 printf_errf("(): Failed to write PID to \"%s\".", ps->o.write_pid_path);
4991 return false;
4992 }
4993
4994 fprintf(f, "%ld\n", (long) getpid());
4995 fclose(f);
4996
4997 return true;
4998 }
4999
5000 /**
5001 * Parse a long number.
5002 */
5003 static inline bool
5004 parse_long(const char *s, long *dest) {
5005 const char *endptr = NULL;
5006 long val = strtol(s, (char **) &endptr, 0);
5007 if (!endptr || endptr == s) {
5008 printf_errf("(\"%s\"): Invalid number.", s);
5009 return false;
5010 }
5011 while (isspace(*endptr))
5012 ++endptr;
5013 if (*endptr) {
5014 printf_errf("(\"%s\"): Trailing characters.", s);
5015 return false;
5016 }
5017 *dest = val;
5018 return true;
5019 }
5020
5021 /**
5022 * Parse a floating-point number in matrix.
5023 */
5024 static inline const char *
5025 parse_matrix_readnum(const char *src, double *dest) {
5026 char *pc = NULL;
5027 double val = strtod(src, &pc);
5028 if (!pc || pc == src) {
5029 printf_errf("(\"%s\"): No number found.", src);
5030 return src;
5031 }
5032
5033 while (*pc && (isspace(*pc) || ',' == *pc))
5034 ++pc;
5035
5036 *dest = val;
5037
5038 return pc;
5039 }
5040
5041 /**
5042 * Parse a matrix.
5043 */
5044 static inline XFixed *
5045 parse_matrix(session_t *ps, const char *src, const char **endptr) {
5046 int wid = 0, hei = 0;
5047 const char *pc = NULL;
5048 XFixed *matrix = NULL;
5049
5050 // Get matrix width and height
5051 {
5052 double val = 0.0;
5053 if (src == (pc = parse_matrix_readnum(src, &val)))
5054 goto parse_matrix_err;
5055 src = pc;
5056 wid = val;
5057 if (src == (pc = parse_matrix_readnum(src, &val)))
5058 goto parse_matrix_err;
5059 src = pc;
5060 hei = val;
5061 }
5062
5063 // Validate matrix width and height
5064 if (wid <= 0 || hei <= 0) {
5065 printf_errf("(): Invalid matrix width/height.");
5066 goto parse_matrix_err;
5067 }
5068 if (!(wid % 2 && hei % 2)) {
5069 printf_errf("(): Width/height not odd.");
5070 goto parse_matrix_err;
5071 }
5072 if (wid > 16 || hei > 16)
5073 printf_errf("(): Matrix width/height too large, may slow down"
5074 "rendering, and/or consume lots of memory");
5075
5076 // Allocate memory
5077 matrix = calloc(wid * hei + 2, sizeof(XFixed));
5078 if (!matrix) {
5079 printf_errf("(): Failed to allocate memory for matrix.");
5080 goto parse_matrix_err;
5081 }
5082
5083 // Read elements
5084 {
5085 int skip = hei / 2 * wid + wid / 2;
5086 bool hasneg = false;
5087 for (int i = 0; i < wid * hei; ++i) {
5088 // Ignore the center element
5089 if (i == skip) {
5090 matrix[2 + i] = XDoubleToFixed(0);
5091 continue;
5092 }
5093 double val = 0;
5094 if (src == (pc = parse_matrix_readnum(src, &val)))
5095 goto parse_matrix_err;
5096 src = pc;
5097 if (val < 0) hasneg = true;
5098 matrix[2 + i] = XDoubleToFixed(val);
5099 }
5100 if (BKEND_XRENDER == ps->o.backend && hasneg)
5101 printf_errf("(): A convolution kernel with negative values "
5102 "may not work properly under X Render backend.");
5103 }
5104
5105 // Detect trailing characters
5106 for ( ;*pc && ';' != *pc; ++pc)
5107 if (!isspace(*pc) && ',' != *pc) {
5108 printf_errf("(): Trailing characters in matrix string.");
5109 goto parse_matrix_err;
5110 }
5111
5112 // Jump over spaces after ';'
5113 if (';' == *pc) {
5114 ++pc;
5115 while (*pc && isspace(*pc))
5116 ++pc;
5117 }
5118
5119 // Require an end of string if endptr is not provided, otherwise
5120 // copy end pointer to endptr
5121 if (endptr)
5122 *endptr = pc;
5123 else if (*pc) {
5124 printf_errf("(): Only one matrix expected.");
5125 goto parse_matrix_err;
5126 }
5127
5128 // Fill in width and height
5129 matrix[0] = XDoubleToFixed(wid);
5130 matrix[1] = XDoubleToFixed(hei);
5131
5132 return matrix;
5133
5134 parse_matrix_err:
5135 free(matrix);
5136 return NULL;
5137 }
5138
5139 /**
5140 * Parse a convolution kernel.
5141 */
5142 static inline XFixed *
5143 parse_conv_kern(session_t *ps, const char *src, const char **endptr) {
5144 return parse_matrix(ps, src, endptr);
5145 }
5146
5147 /**
5148 * Parse a list of convolution kernels.
5149 */
5150 static bool
5151 parse_conv_kern_lst(session_t *ps, const char *src, XFixed **dest, int max) {
5152 static const struct {
5153 const char *name;
5154 const char *kern_str;
5155 } CONV_KERN_PREDEF[] = {
5156 { "3x3box", "3,3,1,1,1,1,1,1,1,1," },
5157 { "5x5box", "5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1," },
5158 { "7x7box", "7,7,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1," },
5159 { "3x3gaussian", "3,3,0.243117,0.493069,0.243117,0.493069,0.493069,0.243117,0.493069,0.243117," },
5160 { "5x5gaussian", "5,5,0.003493,0.029143,0.059106,0.029143,0.003493,0.029143,0.243117,0.493069,0.243117,0.029143,0.059106,0.493069,0.493069,0.059106,0.029143,0.243117,0.493069,0.243117,0.029143,0.003493,0.029143,0.059106,0.029143,0.003493," },
5161 { "7x7gaussian", "7,7,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000102,0.003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.001723,0.059106,0.493069,0.493069,0.059106,0.001723,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000102,0.003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003," },
5162 { "9x9gaussian", "9,9,0.000000,0.000000,0.000001,0.000006,0.000012,0.000006,0.000001,0.000000,0.000000,0.000000,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000000,0.000001,0.000102,0.003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000001,0.000006,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000006,0.000012,0.001723,0.059106,0.493069,0.493069,0.059106,0.001723,0.000012,0.000006,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000006,0.000001,0.000102,0.003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000001,0.000000,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000000,0.000000,0.000000,0.000001,0.000006,0.000012,0.000006,0.000001,0.000000,0.000000," },
5163 { "11x11gaussian", "11,11,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000001,0.000006,0.000012,0.000006,0.000001,0.000000,0.000000,0.000000,0.000000,0.000000,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000000,0.000000,0.000000,0.000001,0.000102,0.003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000001,0.000000,0.000000,0.000006,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000006,0.000000,0.000000,0.000012,0.001723,0.059106,0.493069,0.493069,0.059106,0.001723,0.000012,0.000000,0.000000,0.000006,0.000849,0.029143,0.243117,0.493069,0.243117,0.029143,0.000849,0.000006,0.000000,0.000000,0.000001,0.000102,0.003493,0.029143,0.059106,0.029143,0.003493,0.000102,0.000001,0.000000,0.000000,0.000000,0.000003,0.000102,0.000849,0.001723,0.000849,0.000102,0.000003,0.000000,0.000000,0.000000,0.000000,0.000000,0.000001,0.000006,0.000012,0.000006,0.000001,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000," },
5164 };
5165 for (int i = 0;
5166 i < sizeof(CONV_KERN_PREDEF) / sizeof(CONV_KERN_PREDEF[0]); ++i)
5167 if (!strcmp(CONV_KERN_PREDEF[i].name, src))
5168 return parse_conv_kern_lst(ps, CONV_KERN_PREDEF[i].kern_str, dest, max);
5169
5170 int i = 0;
5171 const char *pc = src;
5172
5173 // Free old kernels
5174 for (i = 0; i < max; ++i) {
5175 free(dest[i]);
5176 dest[i] = NULL;
5177 }
5178
5179 // Continue parsing until the end of source string
5180 i = 0;
5181 while (pc && *pc && i < max - 1) {
5182 if (!(dest[i++] = parse_conv_kern(ps, pc, &pc)))
5183 return false;
5184 }
5185
5186 if (*pc) {
5187 printf_errf("(): Too many blur kernels!");
5188 return false;
5189 }
5190
5191 return true;
5192 }
5193
5194 /**
5195 * Parse a X geometry.
5196 */
5197 static inline bool
5198 parse_geometry(session_t *ps, const char *src, geometry_t *dest) {
5199 geometry_t geom = { .wid = -1, .hei = -1, .x = -1, .y = -1 };
5200 long val = 0L;
5201 char *endptr = NULL;
5202
5203 #define T_STRIPSPACE() do { \
5204 while (*src && isspace(*src)) ++src; \
5205 if (!*src) goto parse_geometry_end; \
5206 } while(0)
5207
5208 T_STRIPSPACE();
5209
5210 // Parse width
5211 // Must be base 10, because "0x0..." may appear
5212 if (!('+' == *src || '-' == *src)) {
5213 val = strtol(src, &endptr, 10);
5214 if (endptr && src != endptr) {
5215 geom.wid = val;
5216 assert(geom.wid >= 0);
5217 src = endptr;
5218 }
5219 T_STRIPSPACE();
5220 }
5221
5222 // Parse height
5223 if ('x' == *src) {
5224 ++src;
5225 val = strtol(src, &endptr, 10);
5226 if (endptr && src != endptr) {
5227 geom.hei = val;
5228 if (geom.hei < 0) {
5229 printf_errf("(\"%s\"): Invalid height.", src);
5230 return false;
5231 }
5232 src = endptr;
5233 }
5234 T_STRIPSPACE();
5235 }
5236
5237 // Parse x
5238 if ('+' == *src || '-' == *src) {
5239 val = strtol(src, &endptr, 10);
5240 if (endptr && src != endptr) {
5241 geom.x = val;
5242 if ('-' == *src && geom.x <= 0)
5243 geom.x -= 2;
5244 src = endptr;
5245 }
5246 T_STRIPSPACE();
5247 }
5248
5249 // Parse y
5250 if ('+' == *src || '-' == *src) {
5251 val = strtol(src, &endptr, 10);
5252 if (endptr && src != endptr) {
5253 geom.y = val;
5254 if ('-' == *src && geom.y <= 0)
5255 geom.y -= 2;
5256 src = endptr;
5257 }
5258 T_STRIPSPACE();
5259 }
5260
5261 if (*src) {
5262 printf_errf("(\"%s\"): Trailing characters.", src);
5263 return false;
5264 }
5265
5266 parse_geometry_end:
5267 *dest = geom;
5268 return true;
5269 }
5270
5271 /**
5272 * Parse a list of opacity rules.
5273 */
5274 static inline bool
5275 parse_rule_opacity(session_t *ps, const char *src) {
5276 #ifdef CONFIG_C2
5277 // Find opacity value
5278 char *endptr = NULL;
5279 long val = strtol(src, &endptr, 0);
5280 if (!endptr || endptr == src) {
5281 printf_errf("(\"%s\"): No opacity specified?", src);
5282 return false;
5283 }
5284 if (val > 100 || val < 0) {
5285 printf_errf("(\"%s\"): Opacity %ld invalid.", src, val);
5286 return false;
5287 }
5288
5289 // Skip over spaces
5290 while (*endptr && isspace(*endptr))
5291 ++endptr;
5292 if (':' != *endptr) {
5293 printf_errf("(\"%s\"): Opacity terminator not found.", src);
5294 return false;
5295 }
5296 ++endptr;
5297
5298 // Parse pattern
5299 // I hope 1-100 is acceptable for (void *)
5300 return c2_parsed(ps, &ps->o.opacity_rules, endptr, (void *) val);
5301 #else
5302 printf_errf("(\"%s\"): Condition support not compiled in.", src);
5303 return false;
5304 #endif
5305 }
5306
5307 #ifdef CONFIG_LIBCONFIG
5308 /**
5309 * Get a file stream of the configuration file to read.
5310 *
5311 * Follows the XDG specification to search for the configuration file.
5312 */
5313 static FILE *
5314 open_config_file(char *cpath, char **ppath) {
5315 const static char *config_filename = "/compton.conf";
5316 const static char *config_filename_legacy = "/.compton.conf";
5317 const static char *config_home_suffix = "/.config";
5318 const static char *config_system_dir = "/etc/xdg";
5319
5320 char *dir = NULL, *home = NULL;
5321 char *path = cpath;
5322 FILE *f = NULL;
5323
5324 if (path) {
5325 f = fopen(path, "r");
5326 if (f && ppath)
5327 *ppath = path;
5328 return f;
5329 }
5330
5331 // Check user configuration file in $XDG_CONFIG_HOME firstly
5332 if (!((dir = getenv("XDG_CONFIG_HOME")) && strlen(dir))) {
5333 if (!((home = getenv("HOME")) && strlen(home)))
5334 return NULL;
5335
5336 path = mstrjoin3(home, config_home_suffix, config_filename);
5337 }
5338 else
5339 path = mstrjoin(dir, config_filename);
5340
5341 f = fopen(path, "r");
5342
5343 if (f && ppath)
5344 *ppath = path;
5345 else
5346 free(path);
5347 if (f)
5348 return f;
5349
5350 // Then check user configuration file in $HOME
5351 if ((home = getenv("HOME")) && strlen(home)) {
5352 path = mstrjoin(home, config_filename_legacy);
5353 f = fopen(path, "r");
5354 if (f && ppath)
5355 *ppath = path;
5356 else
5357 free(path);
5358 if (f)
5359 return f;
5360 }
5361
5362 // Check system configuration file in $XDG_CONFIG_DIRS at last
5363 if ((dir = getenv("XDG_CONFIG_DIRS")) && strlen(dir)) {
5364 char *part = strtok(dir, ":");
5365 while (part) {
5366 path = mstrjoin(part, config_filename);
5367 f = fopen(path, "r");
5368 if (f && ppath)
5369 *ppath = path;
5370 else
5371 free(path);
5372 if (f)
5373 return f;
5374 part = strtok(NULL, ":");
5375 }
5376 }
5377 else {
5378 path = mstrjoin(config_system_dir, config_filename);
5379 f = fopen(path, "r");
5380 if (f && ppath)
5381 *ppath = path;
5382 else
5383 free(path);
5384 if (f)
5385 return f;
5386 }
5387
5388 return NULL;
5389 }
5390
5391 /**
5392 * Parse a condition list in configuration file.
5393 */
5394 static inline void
5395 parse_cfg_condlst(session_t *ps, const config_t *pcfg, c2_lptr_t **pcondlst,
5396 const char *name) {
5397 config_setting_t *setting = config_lookup(pcfg, name);
5398 if (setting) {
5399 // Parse an array of options
5400 if (config_setting_is_array(setting)) {
5401 int i = config_setting_length(setting);
5402 while (i--)
5403 condlst_add(ps, pcondlst, config_setting_get_string_elem(setting, i));
5404 }
5405 // Treat it as a single pattern if it's a string
5406 else if (CONFIG_TYPE_STRING == config_setting_type(setting)) {
5407 condlst_add(ps, pcondlst, config_setting_get_string(setting));
5408 }
5409 }
5410 }
5411
5412 /**
5413 * Parse an opacity rule list in configuration file.
5414 */
5415 static inline void
5416 parse_cfg_condlst_opct(session_t *ps, const config_t *pcfg, const char *name) {
5417 config_setting_t *setting = config_lookup(pcfg, name);
5418 if (setting) {
5419 // Parse an array of options
5420 if (config_setting_is_array(setting)) {
5421 int i = config_setting_length(setting);
5422 while (i--)
5423 if (!parse_rule_opacity(ps, config_setting_get_string_elem(setting,
5424 i)))
5425 exit(1);
5426 }
5427 // Treat it as a single pattern if it's a string
5428 else if (CONFIG_TYPE_STRING == config_setting_type(setting)) {
5429 parse_rule_opacity(ps, config_setting_get_string(setting));
5430 }
5431 }
5432 }
5433
5434 /**
5435 * Parse a configuration file from default location.
5436 */
5437 static void
5438 parse_config(session_t *ps, struct options_tmp *pcfgtmp) {
5439 char *path = NULL;
5440 FILE *f;
5441 config_t cfg;
5442 int ival = 0;
5443 double dval = 0.0;
5444 // libconfig manages string memory itself, so no need to manually free
5445 // anything
5446 const char *sval = NULL;
5447
5448 f = open_config_file(ps->o.config_file, &path);
5449 if (!f) {
5450 if (ps->o.config_file) {
5451 printf_errfq(1, "(): Failed to read configuration file \"%s\".",
5452 ps->o.config_file);
5453 free(ps->o.config_file);
5454 ps->o.config_file = NULL;
5455 }
5456 return;
5457 }
5458
5459 config_init(&cfg);
5460 #ifndef CONFIG_LIBCONFIG_LEGACY
5461 {
5462 // dirname() could modify the original string, thus we must pass a
5463 // copy
5464 char *path2 = mstrcpy(path);
5465 char *parent = dirname(path2);
5466
5467 if (parent)
5468 config_set_include_dir(&cfg, parent);
5469
5470 free(path2);
5471 }
5472 #endif
5473
5474 {
5475 int read_result = config_read(&cfg, f);
5476 fclose(f);
5477 f = NULL;
5478 if (CONFIG_FALSE == read_result) {
5479 printf("Error when reading configuration file \"%s\", line %d: %s\n",
5480 path, config_error_line(&cfg), config_error_text(&cfg));
5481 config_destroy(&cfg);
5482 free(path);
5483 return;
5484 }
5485 }
5486 config_set_auto_convert(&cfg, 1);
5487
5488 if (path != ps->o.config_file) {
5489 free(ps->o.config_file);
5490 ps->o.config_file = path;
5491 }
5492
5493 // Get options from the configuration file. We don't do range checking
5494 // right now. It will be done later
5495
5496 // -D (fade_delta)
5497 if (lcfg_lookup_int(&cfg, "fade-delta", &ival))
5498 ps->o.fade_delta = ival;
5499 // -I (fade_in_step)
5500 if (config_lookup_float(&cfg, "fade-in-step", &dval))
5501 ps->o.fade_in_step = normalize_d(dval) * OPAQUE;
5502 // -O (fade_out_step)
5503 if (config_lookup_float(&cfg, "fade-out-step", &dval))
5504 ps->o.fade_out_step = normalize_d(dval) * OPAQUE;
5505 // -r (shadow_radius)
5506 lcfg_lookup_int(&cfg, "shadow-radius", &ps->o.shadow_radius);
5507 // -o (shadow_opacity)
5508 config_lookup_float(&cfg, "shadow-opacity", &ps->o.shadow_opacity);
5509 // -l (shadow_offset_x)
5510 lcfg_lookup_int(&cfg, "shadow-offset-x", &ps->o.shadow_offset_x);
5511 // -t (shadow_offset_y)
5512 lcfg_lookup_int(&cfg, "shadow-offset-y", &ps->o.shadow_offset_y);
5513 // -i (inactive_opacity)
5514 if (config_lookup_float(&cfg, "inactive-opacity", &dval))
5515 ps->o.inactive_opacity = normalize_d(dval) * OPAQUE;
5516 // --active_opacity
5517 if (config_lookup_float(&cfg, "active-opacity", &dval))
5518 ps->o.active_opacity = normalize_d(dval) * OPAQUE;
5519 // -e (frame_opacity)
5520 config_lookup_float(&cfg, "frame-opacity", &ps->o.frame_opacity);
5521 // -z (clear_shadow)
5522 lcfg_lookup_bool(&cfg, "clear-shadow", &ps->o.clear_shadow);
5523 // -c (shadow_enable)
5524 if (config_lookup_bool(&cfg, "shadow", &ival) && ival)
5525 wintype_arr_enable(ps->o.wintype_shadow);
5526 // -C (no_dock_shadow)
5527 lcfg_lookup_bool(&cfg, "no-dock-shadow", &pcfgtmp->no_dock_shadow);
5528 // -G (no_dnd_shadow)
5529 lcfg_lookup_bool(&cfg, "no-dnd-shadow", &pcfgtmp->no_dnd_shadow);
5530 // -m (menu_opacity)
5531 config_lookup_float(&cfg, "menu-opacity", &pcfgtmp->menu_opacity);
5532 // -f (fading_enable)
5533 if (config_lookup_bool(&cfg, "fading", &ival) && ival)
5534 wintype_arr_enable(ps->o.wintype_fade);
5535 // --no-fading-open-close
5536 lcfg_lookup_bool(&cfg, "no-fading-openclose", &ps->o.no_fading_openclose);
5537 // --no-fading-destroyed-argb
5538 lcfg_lookup_bool(&cfg, "no-fading-destroyed-argb",
5539 &ps->o.no_fading_destroyed_argb);
5540 // --shadow-red
5541 config_lookup_float(&cfg, "shadow-red", &ps->o.shadow_red);
5542 // --shadow-green
5543 config_lookup_float(&cfg, "shadow-green", &ps->o.shadow_green);
5544 // --shadow-blue
5545 config_lookup_float(&cfg, "shadow-blue", &ps->o.shadow_blue);
5546 // --shadow-exclude-reg
5547 if (config_lookup_string(&cfg, "shadow-exclude-reg", &sval)
5548 && !parse_geometry(ps, sval, &ps->o.shadow_exclude_reg_geom))
5549 exit(1);
5550 // --inactive-opacity-override
5551 lcfg_lookup_bool(&cfg, "inactive-opacity-override",
5552 &ps->o.inactive_opacity_override);
5553 // --inactive-dim
5554 config_lookup_float(&cfg, "inactive-dim", &ps->o.inactive_dim);
5555 // --mark-wmwin-focused
5556 lcfg_lookup_bool(&cfg, "mark-wmwin-focused", &ps->o.mark_wmwin_focused);
5557 // --mark-ovredir-focused
5558 lcfg_lookup_bool(&cfg, "mark-ovredir-focused",
5559 &ps->o.mark_ovredir_focused);
5560 // --shadow-ignore-shaped
5561 lcfg_lookup_bool(&cfg, "shadow-ignore-shaped",
5562 &ps->o.shadow_ignore_shaped);
5563 // --detect-rounded-corners
5564 lcfg_lookup_bool(&cfg, "detect-rounded-corners",
5565 &ps->o.detect_rounded_corners);
5566 // --xinerama-shadow-crop
5567 lcfg_lookup_bool(&cfg, "xinerama-shadow-crop",
5568 &ps->o.xinerama_shadow_crop);
5569 // --detect-client-opacity
5570 lcfg_lookup_bool(&cfg, "detect-client-opacity",
5571 &ps->o.detect_client_opacity);
5572 // --refresh-rate
5573 lcfg_lookup_int(&cfg, "refresh-rate", &ps->o.refresh_rate);
5574 // --vsync
5575 if (config_lookup_string(&cfg, "vsync", &sval) && !parse_vsync(ps, sval))
5576 exit(1);
5577 // --backend
5578 if (config_lookup_string(&cfg, "backend", &sval) && !parse_backend(ps, sval))
5579 exit(1);
5580 // --alpha-step
5581 config_lookup_float(&cfg, "alpha-step", &ps->o.alpha_step);
5582 // --dbe
5583 lcfg_lookup_bool(&cfg, "dbe", &ps->o.dbe);
5584 // --paint-on-overlay
5585 lcfg_lookup_bool(&cfg, "paint-on-overlay", &ps->o.paint_on_overlay);
5586 // --sw-opti
5587 lcfg_lookup_bool(&cfg, "sw-opti", &ps->o.sw_opti);
5588 // --use-ewmh-active-win
5589 lcfg_lookup_bool(&cfg, "use-ewmh-active-win",
5590 &ps->o.use_ewmh_active_win);
5591 // --unredir-if-possible
5592 lcfg_lookup_bool(&cfg, "unredir-if-possible",
5593 &ps->o.unredir_if_possible);
5594 // --unredir-if-possible-delay
5595 if (lcfg_lookup_int(&cfg, "unredir-if-possible-delay", &ival))
5596 ps->o.unredir_if_possible_delay = ival;
5597 // --inactive-dim-fixed
5598 lcfg_lookup_bool(&cfg, "inactive-dim-fixed", &ps->o.inactive_dim_fixed);
5599 // --detect-transient
5600 lcfg_lookup_bool(&cfg, "detect-transient", &ps->o.detect_transient);
5601 // --detect-client-leader
5602 lcfg_lookup_bool(&cfg, "detect-client-leader",
5603 &ps->o.detect_client_leader);
5604 // --shadow-exclude
5605 parse_cfg_condlst(ps, &cfg, &ps->o.shadow_blacklist, "shadow-exclude");
5606 // --fade-exclude
5607 parse_cfg_condlst(ps, &cfg, &ps->o.fade_blacklist, "fade-exclude");
5608 // --focus-exclude
5609 parse_cfg_condlst(ps, &cfg, &ps->o.focus_blacklist, "focus-exclude");
5610 // --invert-color-include
5611 parse_cfg_condlst(ps, &cfg, &ps->o.invert_color_list, "invert-color-include");
5612 // --blur-background-exclude
5613 parse_cfg_condlst(ps, &cfg, &ps->o.blur_background_blacklist, "blur-background-exclude");
5614 // --opacity-rule
5615 parse_cfg_condlst_opct(ps, &cfg, "opacity-rule");
5616 // --unredir-if-possible-exclude
5617 parse_cfg_condlst(ps, &cfg, &ps->o.unredir_if_possible_blacklist, "unredir-if-possible-exclude");
5618 // --blur-background
5619 lcfg_lookup_bool(&cfg, "blur-background", &ps->o.blur_background);
5620 // --blur-background-frame
5621 lcfg_lookup_bool(&cfg, "blur-background-frame",
5622 &ps->o.blur_background_frame);
5623 // --blur-background-fixed
5624 lcfg_lookup_bool(&cfg, "blur-background-fixed",
5625 &ps->o.blur_background_fixed);
5626 // --blur-kern
5627 if (config_lookup_string(&cfg, "blur-kern", &sval)
5628 && !parse_conv_kern_lst(ps, sval, ps->o.blur_kerns, MAX_BLUR_PASS))
5629 exit(1);
5630 // --resize-damage
5631 lcfg_lookup_int(&cfg, "resize-damage", &ps->o.resize_damage);
5632 // --glx-no-stencil
5633 lcfg_lookup_bool(&cfg, "glx-no-stencil", &ps->o.glx_no_stencil);
5634 // --glx-copy-from-front
5635 lcfg_lookup_bool(&cfg, "glx-copy-from-front", &ps->o.glx_copy_from_front);
5636 // --glx-use-copysubbuffermesa
5637 lcfg_lookup_bool(&cfg, "glx-use-copysubbuffermesa", &ps->o.glx_use_copysubbuffermesa);
5638 // --glx-no-rebind-pixmap
5639 lcfg_lookup_bool(&cfg, "glx-no-rebind-pixmap", &ps->o.glx_no_rebind_pixmap);
5640 // --glx-swap-method
5641 if (config_lookup_string(&cfg, "glx-swap-method", &sval)
5642 && !parse_glx_swap_method(ps, sval))
5643 exit(1);
5644 // --glx-use-gpushader4
5645 lcfg_lookup_bool(&cfg, "glx-use-gpushader4", &ps->o.glx_use_gpushader4);
5646 // --xrender-sync
5647 lcfg_lookup_bool(&cfg, "xrender-sync", &ps->o.xrender_sync);
5648 // --xrender-sync-fence
5649 lcfg_lookup_bool(&cfg, "xrender-sync-fence", &ps->o.xrender_sync_fence);
5650 // Wintype settings
5651 {
5652 wintype_t i;
5653
5654 for (i = 0; i < NUM_WINTYPES; ++i) {
5655 char *str = mstrjoin("wintypes.", WINTYPES[i]);
5656 config_setting_t *setting = config_lookup(&cfg, str);
5657 free(str);
5658 if (setting) {
5659 if (config_setting_lookup_bool(setting, "shadow", &ival))
5660 ps->o.wintype_shadow[i] = (bool) ival;
5661 if (config_setting_lookup_bool(setting, "fade", &ival))
5662 ps->o.wintype_fade[i] = (bool) ival;
5663 if (config_setting_lookup_bool(setting, "focus", &ival))
5664 ps->o.wintype_focus[i] = (bool) ival;
5665
5666 double fval;
5667 if (config_setting_lookup_float(setting, "opacity", &fval))
5668 ps->o.wintype_opacity[i] = normalize_d(fval);
5669 }
5670 }
5671 }
5672
5673 config_destroy(&cfg);
5674 }
5675 #endif
5676
5677 /**
5678 * Process arguments and configuration files.
5679 */
5680 static void
5681 get_cfg(session_t *ps, int argc, char *const *argv, bool first_pass) {
5682 const static char *shortopts = "D:I:O:d:r:o:m:l:t:i:e:hscnfFCaSzGb";
5683 const static struct option longopts[] = {
5684 { "help", no_argument, NULL, 'h' },
5685 { "config", required_argument, NULL, 256 },
5686 { "shadow-radius", required_argument, NULL, 'r' },
5687 { "shadow-opacity", required_argument, NULL, 'o' },
5688 { "shadow-offset-x", required_argument, NULL, 'l' },
5689 { "shadow-offset-y", required_argument, NULL, 't' },
5690 { "fade-in-step", required_argument, NULL, 'I' },
5691 { "fade-out-step", required_argument, NULL, 'O' },
5692 { "fade-delta", required_argument, NULL, 'D' },
5693 { "menu-opacity", required_argument, NULL, 'm' },
5694 { "shadow", no_argument, NULL, 'c' },
5695 { "no-dock-shadow", no_argument, NULL, 'C' },
5696 { "clear-shadow", no_argument, NULL, 'z' },
5697 { "fading", no_argument, NULL, 'f' },
5698 { "inactive-opacity", required_argument, NULL, 'i' },
5699 { "frame-opacity", required_argument, NULL, 'e' },
5700 { "daemon", no_argument, NULL, 'b' },
5701 { "no-dnd-shadow", no_argument, NULL, 'G' },
5702 { "shadow-red", required_argument, NULL, 257 },
5703 { "shadow-green", required_argument, NULL, 258 },
5704 { "shadow-blue", required_argument, NULL, 259 },
5705 { "inactive-opacity-override", no_argument, NULL, 260 },
5706 { "inactive-dim", required_argument, NULL, 261 },
5707 { "mark-wmwin-focused", no_argument, NULL, 262 },
5708 { "shadow-exclude", required_argument, NULL, 263 },
5709 { "mark-ovredir-focused", no_argument, NULL, 264 },
5710 { "no-fading-openclose", no_argument, NULL, 265 },
5711 { "shadow-ignore-shaped", no_argument, NULL, 266 },
5712 { "detect-rounded-corners", no_argument, NULL, 267 },
5713 { "detect-client-opacity", no_argument, NULL, 268 },
5714 { "refresh-rate", required_argument, NULL, 269 },
5715 { "vsync", required_argument, NULL, 270 },
5716 { "alpha-step", required_argument, NULL, 271 },
5717 { "dbe", no_argument, NULL, 272 },
5718 { "paint-on-overlay", no_argument, NULL, 273 },
5719 { "sw-opti", no_argument, NULL, 274 },
5720 { "vsync-aggressive", no_argument, NULL, 275 },
5721 { "use-ewmh-active-win", no_argument, NULL, 276 },
5722 { "respect-prop-shadow", no_argument, NULL, 277 },
5723 { "unredir-if-possible", no_argument, NULL, 278 },
5724 { "focus-exclude", required_argument, NULL, 279 },
5725 { "inactive-dim-fixed", no_argument, NULL, 280 },
5726 { "detect-transient", no_argument, NULL, 281 },
5727 { "detect-client-leader", no_argument, NULL, 282 },
5728 { "blur-background", no_argument, NULL, 283 },
5729 { "blur-background-frame", no_argument, NULL, 284 },
5730 { "blur-background-fixed", no_argument, NULL, 285 },
5731 { "dbus", no_argument, NULL, 286 },
5732 { "logpath", required_argument, NULL, 287 },
5733 { "invert-color-include", required_argument, NULL, 288 },
5734 { "opengl", no_argument, NULL, 289 },
5735 { "backend", required_argument, NULL, 290 },
5736 { "glx-no-stencil", no_argument, NULL, 291 },
5737 { "glx-copy-from-front", no_argument, NULL, 292 },
5738 { "benchmark", required_argument, NULL, 293 },
5739 { "benchmark-wid", required_argument, NULL, 294 },
5740 { "glx-use-copysubbuffermesa", no_argument, NULL, 295 },
5741 { "blur-background-exclude", required_argument, NULL, 296 },
5742 { "active-opacity", required_argument, NULL, 297 },
5743 { "glx-no-rebind-pixmap", no_argument, NULL, 298 },
5744 { "glx-swap-method", required_argument, NULL, 299 },
5745 { "fade-exclude", required_argument, NULL, 300 },
5746 { "blur-kern", required_argument, NULL, 301 },
5747 { "resize-damage", required_argument, NULL, 302 },
5748 { "glx-use-gpushader4", no_argument, NULL, 303 },
5749 { "opacity-rule", required_argument, NULL, 304 },
5750 { "shadow-exclude-reg", required_argument, NULL, 305 },
5751 { "paint-exclude", required_argument, NULL, 306 },
5752 { "xinerama-shadow-crop", no_argument, NULL, 307 },
5753 { "unredir-if-possible-exclude", required_argument, NULL, 308 },
5754 { "unredir-if-possible-delay", required_argument, NULL, 309 },
5755 { "write-pid-path", required_argument, NULL, 310 },
5756 { "vsync-use-glfinish", no_argument, NULL, 311 },
5757 { "xrender-sync", no_argument, NULL, 312 },
5758 { "xrender-sync-fence", no_argument, NULL, 313 },
5759 { "show-all-xerrors", no_argument, NULL, 314 },
5760 { "no-fading-destroyed-argb", no_argument, NULL, 315 },
5761 { "force-win-blend", no_argument, NULL, 316 },
5762 { "glx-fshader-win", required_argument, NULL, 317 },
5763 { "version", no_argument, NULL, 318 },
5764 { "no-x-selection", no_argument, NULL, 319 },
5765 { "no-name-pixmap", no_argument, NULL, 320 },
5766 { "reredir-on-root-change", no_argument, NULL, 731 },
5767 { "glx-reinit-on-root-change", no_argument, NULL, 732 },
5768 // Must terminate with a NULL entry
5769 { NULL, 0, NULL, 0 },
5770 };
5771
5772 int o = 0, longopt_idx = -1, i = 0;
5773
5774 if (first_pass) {
5775 // Pre-parse the commandline arguments to check for --config and invalid
5776 // switches
5777 // Must reset optind to 0 here in case we reread the commandline
5778 // arguments
5779 optind = 1;
5780 while (-1 !=
5781 (o = getopt_long(argc, argv, shortopts, longopts, &longopt_idx))) {
5782 if (256 == o)
5783 ps->o.config_file = mstrcpy(optarg);
5784 else if ('d' == o)
5785 ps->o.display = mstrcpy(optarg);
5786 else if ('S' == o)
5787 ps->o.synchronize = true;
5788 else if (314 == o)
5789 ps->o.show_all_xerrors = true;
5790 else if (318 == o) {
5791 printf("%s\n", COMPTON_VERSION);
5792 exit(0);
5793 }
5794 else if (320 == o)
5795 ps->o.no_name_pixmap = true;
5796 else if ('?' == o || ':' == o)
5797 usage(1);
5798 }
5799
5800 // Check for abundant positional arguments
5801 if (optind < argc)
5802 printf_errfq(1, "(): compton doesn't accept positional arguments.");
5803
5804 return;
5805 }
5806
5807 struct options_tmp cfgtmp = {
5808 .no_dock_shadow = false,
5809 .no_dnd_shadow = false,
5810 .menu_opacity = NAN,
5811 };
5812 bool shadow_enable = false, fading_enable = false;
5813 char *lc_numeric_old = mstrcpy(setlocale(LC_NUMERIC, NULL));
5814
5815 for (i = 0; i < NUM_WINTYPES; ++i) {
5816 ps->o.wintype_fade[i] = false;
5817 ps->o.wintype_shadow[i] = false;
5818 ps->o.wintype_opacity[i] = NAN;
5819 }
5820
5821 // Enforce LC_NUMERIC locale "C" here to make sure dots are recognized
5822 // instead of commas in atof().
5823 setlocale(LC_NUMERIC, "C");
5824
5825 #ifdef CONFIG_LIBCONFIG
5826 parse_config(ps, &cfgtmp);
5827 #endif
5828
5829 // Parse commandline arguments. Range checking will be done later.
5830
5831 optind = 1;
5832 while (-1 !=
5833 (o = getopt_long(argc, argv, shortopts, longopts, &longopt_idx))) {
5834 long val = 0;
5835 switch (o) {
5836 #define P_CASEBOOL(idx, option) case idx: ps->o.option = true; break
5837 #define P_CASELONG(idx, option) \
5838 case idx: \
5839 if (!parse_long(optarg, &val)) exit(1); \
5840 ps->o.option = val; \
5841 break
5842
5843 // Short options
5844 case 'h':
5845 usage(0);
5846 break;
5847 case 'd':
5848 case 'S':
5849 case 314:
5850 case 318:
5851 case 320:
5852 break;
5853 P_CASELONG('D', fade_delta);
5854 case 'I':
5855 ps->o.fade_in_step = normalize_d(atof(optarg)) * OPAQUE;
5856 break;
5857 case 'O':
5858 ps->o.fade_out_step = normalize_d(atof(optarg)) * OPAQUE;
5859 break;
5860 case 'c':
5861 shadow_enable = true;
5862 break;
5863 case 'C':
5864 cfgtmp.no_dock_shadow = true;
5865 break;
5866 case 'G':
5867 cfgtmp.no_dnd_shadow = true;
5868 break;
5869 case 'm':
5870 cfgtmp.menu_opacity = atof(optarg);
5871 break;
5872 case 'f':
5873 case 'F':
5874 fading_enable = true;
5875 break;
5876 P_CASELONG('r', shadow_radius);
5877 case 'o':
5878 ps->o.shadow_opacity = atof(optarg);
5879 break;
5880 P_CASELONG('l', shadow_offset_x);
5881 P_CASELONG('t', shadow_offset_y);
5882 case 'i':
5883 ps->o.inactive_opacity = (normalize_d(atof(optarg)) * OPAQUE);
5884 break;
5885 case 'e':
5886 ps->o.frame_opacity = atof(optarg);
5887 break;
5888 P_CASEBOOL('z', clear_shadow);
5889 case 'n':
5890 case 'a':
5891 case 's':
5892 printf_errfq(1, "(): -n, -a, and -s have been removed.");
5893 break;
5894 P_CASEBOOL('b', fork_after_register);
5895 // Long options
5896 case 256:
5897 // --config
5898 break;
5899 case 257:
5900 // --shadow-red
5901 ps->o.shadow_red = atof(optarg);
5902 break;
5903 case 258:
5904 // --shadow-green
5905 ps->o.shadow_green = atof(optarg);
5906 break;
5907 case 259:
5908 // --shadow-blue
5909 ps->o.shadow_blue = atof(optarg);
5910 break;
5911 P_CASEBOOL(260, inactive_opacity_override);
5912 case 261:
5913 // --inactive-dim
5914 ps->o.inactive_dim = atof(optarg);
5915 break;
5916 P_CASEBOOL(262, mark_wmwin_focused);
5917 case 263:
5918 // --shadow-exclude
5919 condlst_add(ps, &ps->o.shadow_blacklist, optarg);
5920 break;
5921 P_CASEBOOL(264, mark_ovredir_focused);
5922 P_CASEBOOL(265, no_fading_openclose);
5923 P_CASEBOOL(266, shadow_ignore_shaped);
5924 P_CASEBOOL(267, detect_rounded_corners);
5925 P_CASEBOOL(268, detect_client_opacity);
5926 P_CASELONG(269, refresh_rate);
5927 case 270:
5928 // --vsync
5929 if (!parse_vsync(ps, optarg))
5930 exit(1);
5931 break;
5932 case 271:
5933 // --alpha-step
5934 ps->o.alpha_step = atof(optarg);
5935 break;
5936 P_CASEBOOL(272, dbe);
5937 P_CASEBOOL(273, paint_on_overlay);
5938 P_CASEBOOL(274, sw_opti);
5939 P_CASEBOOL(275, vsync_aggressive);
5940 P_CASEBOOL(276, use_ewmh_active_win);
5941 P_CASEBOOL(277, respect_prop_shadow);
5942 P_CASEBOOL(278, unredir_if_possible);
5943 case 279:
5944 // --focus-exclude
5945 condlst_add(ps, &ps->o.focus_blacklist, optarg);
5946 break;
5947 P_CASEBOOL(280, inactive_dim_fixed);
5948 P_CASEBOOL(281, detect_transient);
5949 P_CASEBOOL(282, detect_client_leader);
5950 P_CASEBOOL(283, blur_background);
5951 P_CASEBOOL(284, blur_background_frame);
5952 P_CASEBOOL(285, blur_background_fixed);
5953 P_CASEBOOL(286, dbus);
5954 case 287:
5955 // --logpath
5956 ps->o.logpath = mstrcpy(optarg);
5957 break;
5958 case 288:
5959 // --invert-color-include
5960 condlst_add(ps, &ps->o.invert_color_list, optarg);
5961 break;
5962 case 289:
5963 // --opengl
5964 ps->o.backend = BKEND_GLX;
5965 break;
5966 case 290:
5967 // --backend
5968 if (!parse_backend(ps, optarg))
5969 exit(1);
5970 break;
5971 P_CASEBOOL(291, glx_no_stencil);
5972 P_CASEBOOL(292, glx_copy_from_front);
5973 P_CASELONG(293, benchmark);
5974 case 294:
5975 // --benchmark-wid
5976 ps->o.benchmark_wid = strtol(optarg, NULL, 0);
5977 break;
5978 P_CASEBOOL(295, glx_use_copysubbuffermesa);
5979 case 296:
5980 // --blur-background-exclude
5981 condlst_add(ps, &ps->o.blur_background_blacklist, optarg);
5982 break;
5983 case 297:
5984 // --active-opacity
5985 ps->o.active_opacity = (normalize_d(atof(optarg)) * OPAQUE);
5986 break;
5987 P_CASEBOOL(298, glx_no_rebind_pixmap);
5988 case 299:
5989 // --glx-swap-method
5990 if (!parse_glx_swap_method(ps, optarg))
5991 exit(1);
5992 break;
5993 case 300:
5994 // --fade-exclude
5995 condlst_add(ps, &ps->o.fade_blacklist, optarg);
5996 break;
5997 case 301:
5998 // --blur-kern
5999 if (!parse_conv_kern_lst(ps, optarg, ps->o.blur_kerns, MAX_BLUR_PASS))
6000 exit(1);
6001 break;
6002 P_CASELONG(302, resize_damage);
6003 P_CASEBOOL(303, glx_use_gpushader4);
6004 case 304:
6005 // --opacity-rule
6006 if (!parse_rule_opacity(ps, optarg))
6007 exit(1);
6008 break;
6009 case 305:
6010 // --shadow-exclude-reg
6011 if (!parse_geometry(ps, optarg, &ps->o.shadow_exclude_reg_geom))
6012 exit(1);
6013 break;
6014 case 306:
6015 // --paint-exclude
6016 condlst_add(ps, &ps->o.paint_blacklist, optarg);
6017 break;
6018 P_CASEBOOL(307, xinerama_shadow_crop);
6019 case 308:
6020 // --unredir-if-possible-exclude
6021 condlst_add(ps, &ps->o.unredir_if_possible_blacklist, optarg);
6022 break;
6023 P_CASELONG(309, unredir_if_possible_delay);
6024 case 310:
6025 // --write-pid-path
6026 ps->o.write_pid_path = mstrcpy(optarg);
6027 break;
6028 P_CASEBOOL(311, vsync_use_glfinish);
6029 P_CASEBOOL(312, xrender_sync);
6030 P_CASEBOOL(313, xrender_sync_fence);
6031 P_CASEBOOL(315, no_fading_destroyed_argb);
6032 P_CASEBOOL(316, force_win_blend);
6033 case 317:
6034 ps->o.glx_fshader_win_str = mstrcpy(optarg);
6035 break;
6036 P_CASEBOOL(319, no_x_selection);
6037 P_CASEBOOL(731, reredir_on_root_change);
6038 P_CASEBOOL(732, glx_reinit_on_root_change);
6039 default:
6040 usage(1);
6041 break;
6042 #undef P_CASEBOOL
6043 }
6044 }
6045
6046 // Restore LC_NUMERIC
6047 setlocale(LC_NUMERIC, lc_numeric_old);
6048 free(lc_numeric_old);
6049
6050 // Range checking and option assignments
6051 ps->o.fade_delta = max_i(ps->o.fade_delta, 1);
6052 ps->o.shadow_radius = max_i(ps->o.shadow_radius, 1);
6053 ps->o.shadow_red = normalize_d(ps->o.shadow_red);
6054 ps->o.shadow_green = normalize_d(ps->o.shadow_green);
6055 ps->o.shadow_blue = normalize_d(ps->o.shadow_blue);
6056 ps->o.inactive_dim = normalize_d(ps->o.inactive_dim);
6057 ps->o.frame_opacity = normalize_d(ps->o.frame_opacity);
6058 ps->o.shadow_opacity = normalize_d(ps->o.shadow_opacity);
6059 cfgtmp.menu_opacity = normalize_d(cfgtmp.menu_opacity);
6060 ps->o.refresh_rate = normalize_i_range(ps->o.refresh_rate, 0, 300);
6061 ps->o.alpha_step = normalize_d_range(ps->o.alpha_step, 0.01, 1.0);
6062 if (shadow_enable)
6063 wintype_arr_enable(ps->o.wintype_shadow);
6064 ps->o.wintype_shadow[WINTYPE_DESKTOP] = false;
6065 if (cfgtmp.no_dock_shadow)
6066 ps->o.wintype_shadow[WINTYPE_DOCK] = false;
6067 if (cfgtmp.no_dnd_shadow)
6068 ps->o.wintype_shadow[WINTYPE_DND] = false;
6069 if (fading_enable)
6070 wintype_arr_enable(ps->o.wintype_fade);
6071 if (!isnan(cfgtmp.menu_opacity)) {
6072 ps->o.wintype_opacity[WINTYPE_DROPDOWN_MENU] = cfgtmp.menu_opacity;
6073 ps->o.wintype_opacity[WINTYPE_POPUP_MENU] = cfgtmp.menu_opacity;
6074 }
6075
6076 // --blur-background-frame implies --blur-background
6077 if (ps->o.blur_background_frame)
6078 ps->o.blur_background = true;
6079
6080 if (ps->o.xrender_sync_fence)
6081 ps->o.xrender_sync = true;
6082
6083 // Other variables determined by options
6084
6085 // Determine whether we need to track focus changes
6086 if (ps->o.inactive_opacity != ps->o.active_opacity ||
6087 ps->o.inactive_dim) {
6088 ps->o.track_focus = true;
6089 }
6090
6091 // Determine whether we track window grouping
6092 if (ps->o.detect_transient || ps->o.detect_client_leader) {
6093 ps->o.track_leader = true;
6094 }
6095
6096 // Fill default blur kernel
6097 if (ps->o.blur_background && !ps->o.blur_kerns[0]) {
6098 // Convolution filter parameter (box blur)
6099 // gaussian or binomial filters are definitely superior, yet looks
6100 // like they aren't supported as of xorg-server-1.13.0
6101 const static XFixed convolution_blur[] = {
6102 // Must convert to XFixed with XDoubleToFixed()
6103 // Matrix size
6104 XDoubleToFixed(3), XDoubleToFixed(3),
6105 // Matrix
6106 XDoubleToFixed(1), XDoubleToFixed(1), XDoubleToFixed(1),
6107 XDoubleToFixed(1), XDoubleToFixed(1), XDoubleToFixed(1),
6108 XDoubleToFixed(1), XDoubleToFixed(1), XDoubleToFixed(1),
6109 };
6110 ps->o.blur_kerns[0] = malloc(sizeof(convolution_blur));
6111 if (!ps->o.blur_kerns[0]) {
6112 printf_errf("(): Failed to allocate memory for convolution kernel.");
6113 exit(1);
6114 }
6115 memcpy(ps->o.blur_kerns[0], &convolution_blur, sizeof(convolution_blur));
6116 }
6117
6118 rebuild_shadow_exclude_reg(ps);
6119
6120 if (ps->o.resize_damage < 0)
6121 printf_errf("(): Negative --resize-damage does not work correctly.");
6122 }
6123
6124 /**
6125 * Fetch all required atoms and save them to a session.
6126 */
6127 static void
6128 init_atoms(session_t *ps) {
6129 ps->atom_opacity = get_atom(ps, "_NET_WM_WINDOW_OPACITY");
6130 ps->atom_frame_extents = get_atom(ps, "_NET_FRAME_EXTENTS");
6131 ps->atom_client = get_atom(ps, "WM_STATE");
6132 ps->atom_name = XA_WM_NAME;
6133 ps->atom_name_ewmh = get_atom(ps, "_NET_WM_NAME");
6134 ps->atom_class = XA_WM_CLASS;
6135 ps->atom_role = get_atom(ps, "WM_WINDOW_ROLE");
6136 ps->atom_transient = XA_WM_TRANSIENT_FOR;
6137 ps->atom_client_leader = get_atom(ps, "WM_CLIENT_LEADER");
6138 ps->atom_ewmh_active_win = get_atom(ps, "_NET_ACTIVE_WINDOW");
6139 ps->atom_compton_shadow = get_atom(ps, "_COMPTON_SHADOW");
6140
6141 ps->atom_win_type = get_atom(ps, "_NET_WM_WINDOW_TYPE");
6142 ps->atoms_wintypes[WINTYPE_UNKNOWN] = 0;
6143 ps->atoms_wintypes[WINTYPE_DESKTOP] = get_atom(ps,
6144 "_NET_WM_WINDOW_TYPE_DESKTOP");
6145 ps->atoms_wintypes[WINTYPE_DOCK] = get_atom(ps,
6146 "_NET_WM_WINDOW_TYPE_DOCK");
6147 ps->atoms_wintypes[WINTYPE_TOOLBAR] = get_atom(ps,
6148 "_NET_WM_WINDOW_TYPE_TOOLBAR");
6149 ps->atoms_wintypes[WINTYPE_MENU] = get_atom(ps,
6150 "_NET_WM_WINDOW_TYPE_MENU");
6151 ps->atoms_wintypes[WINTYPE_UTILITY] = get_atom(ps,
6152 "_NET_WM_WINDOW_TYPE_UTILITY");
6153 ps->atoms_wintypes[WINTYPE_SPLASH] = get_atom(ps,
6154 "_NET_WM_WINDOW_TYPE_SPLASH");
6155 ps->atoms_wintypes[WINTYPE_DIALOG] = get_atom(ps,
6156 "_NET_WM_WINDOW_TYPE_DIALOG");
6157 ps->atoms_wintypes[WINTYPE_NORMAL] = get_atom(ps,
6158 "_NET_WM_WINDOW_TYPE_NORMAL");
6159 ps->atoms_wintypes[WINTYPE_DROPDOWN_MENU] = get_atom(ps,
6160 "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU");
6161 ps->atoms_wintypes[WINTYPE_POPUP_MENU] = get_atom(ps,
6162 "_NET_WM_WINDOW_TYPE_POPUP_MENU");
6163 ps->atoms_wintypes[WINTYPE_TOOLTIP] = get_atom(ps,
6164 "_NET_WM_WINDOW_TYPE_TOOLTIP");
6165 ps->atoms_wintypes[WINTYPE_NOTIFY] = get_atom(ps,
6166 "_NET_WM_WINDOW_TYPE_NOTIFICATION");
6167 ps->atoms_wintypes[WINTYPE_COMBO] = get_atom(ps,
6168 "_NET_WM_WINDOW_TYPE_COMBO");
6169 ps->atoms_wintypes[WINTYPE_DND] = get_atom(ps,
6170 "_NET_WM_WINDOW_TYPE_DND");
6171 }
6172
6173 /**
6174 * Update refresh rate info with X Randr extension.
6175 */
6176 static void
6177 update_refresh_rate(session_t *ps) {
6178 XRRScreenConfiguration* randr_info;
6179
6180 if (!(randr_info = XRRGetScreenInfo(ps->dpy, ps->root)))
6181 return;
6182 ps->refresh_rate = XRRConfigCurrentRate(randr_info);
6183
6184 XRRFreeScreenConfigInfo(randr_info);
6185
6186 if (ps->refresh_rate)
6187 ps->refresh_intv = US_PER_SEC / ps->refresh_rate;
6188 else
6189 ps->refresh_intv = 0;
6190 }
6191
6192 /**
6193 * Initialize refresh-rated based software optimization.
6194 *
6195 * @return true for success, false otherwise
6196 */
6197 static bool
6198 swopti_init(session_t *ps) {
6199 // Prepare refresh rate
6200 // Check if user provides one
6201 ps->refresh_rate = ps->o.refresh_rate;
6202 if (ps->refresh_rate)
6203 ps->refresh_intv = US_PER_SEC / ps->refresh_rate;
6204
6205 // Auto-detect refresh rate otherwise
6206 if (!ps->refresh_rate && ps->randr_exists) {
6207 update_refresh_rate(ps);
6208 }
6209
6210 // Turn off vsync_sw if we can't get the refresh rate
6211 if (!ps->refresh_rate)
6212 return false;
6213
6214 return true;
6215 }
6216
6217 /**
6218 * Modify a struct timeval timeout value to render at a fixed pace.
6219 *
6220 * @param ps current session
6221 * @param[in,out] ptv pointer to the timeout
6222 */
6223 static void
6224 swopti_handle_timeout(session_t *ps, struct timeval *ptv) {
6225 if (!ptv)
6226 return;
6227
6228 // Get the microsecond offset of the time when the we reach the timeout
6229 // I don't think a 32-bit long could overflow here.
6230 long offset = (ptv->tv_usec + get_time_timeval().tv_usec - ps->paint_tm_offset) % ps->refresh_intv;
6231 if (offset < 0)
6232 offset += ps->refresh_intv;
6233
6234 assert(offset >= 0 && offset < ps->refresh_intv);
6235
6236 // If the target time is sufficiently close to a refresh time, don't add
6237 // an offset, to avoid certain blocking conditions.
6238 if (offset < SWOPTI_TOLERANCE
6239 || offset > ps->refresh_intv - SWOPTI_TOLERANCE)
6240 return;
6241
6242 // Add an offset so we wait until the next refresh after timeout
6243 ptv->tv_usec += ps->refresh_intv - offset;
6244 if (ptv->tv_usec > US_PER_SEC) {
6245 ptv->tv_usec -= US_PER_SEC;
6246 ++ptv->tv_sec;
6247 }
6248 }
6249
6250 /**
6251 * Initialize DRM VSync.
6252 *
6253 * @return true for success, false otherwise
6254 */
6255 static bool
6256 vsync_drm_init(session_t *ps) {
6257 #ifdef CONFIG_VSYNC_DRM
6258 // Should we always open card0?
6259 if (ps->drm_fd < 0 && (ps->drm_fd = open("/dev/dri/card0", O_RDWR)) < 0) {
6260 printf_errf("(): Failed to open device.");
6261 return false;
6262 }
6263
6264 if (vsync_drm_wait(ps))
6265 return false;
6266
6267 return true;
6268 #else
6269 printf_errf("(): Program not compiled with DRM VSync support.");
6270 return false;
6271 #endif
6272 }
6273
6274 #ifdef CONFIG_VSYNC_DRM
6275 /**
6276 * Wait for next VSync, DRM method.
6277 *
6278 * Stolen from: https://github.com/MythTV/mythtv/blob/master/mythtv/libs/libmythtv/vsync.cpp
6279 */
6280 static int
6281 vsync_drm_wait(session_t *ps) {
6282 int ret = -1;
6283 drm_wait_vblank_t vbl;
6284
6285 vbl.request.type = _DRM_VBLANK_RELATIVE,
6286 vbl.request.sequence = 1;
6287
6288 do {
6289 ret = ioctl(ps->drm_fd, DRM_IOCTL_WAIT_VBLANK, &vbl);
6290 vbl.request.type &= ~_DRM_VBLANK_RELATIVE;
6291 } while (ret && errno == EINTR);
6292
6293 if (ret)
6294 fprintf(stderr, "vsync_drm_wait(): VBlank ioctl did not work, "
6295 "unimplemented in this drmver?\n");
6296
6297 return ret;
6298
6299 }
6300 #endif
6301
6302 /**
6303 * Initialize OpenGL VSync.
6304 *
6305 * Stolen from: http://git.tuxfamily.org/?p=ccm/cairocompmgr.git;a=commitdiff;h=efa4ceb97da501e8630ca7f12c99b1dce853c73e
6306 * Possible original source: http://www.inb.uni-luebeck.de/~boehme/xvideo_sync.html
6307 *
6308 * @return true for success, false otherwise
6309 */
6310 static bool
6311 vsync_opengl_init(session_t *ps) {
6312 #ifdef CONFIG_VSYNC_OPENGL
6313 if (!ensure_glx_context(ps))
6314 return false;
6315
6316 // Get video sync functions
6317 if (!ps->psglx->glXGetVideoSyncSGI)
6318 ps->psglx->glXGetVideoSyncSGI = (f_GetVideoSync)
6319 glXGetProcAddress((const GLubyte *) "glXGetVideoSyncSGI");
6320 if (!ps->psglx->glXWaitVideoSyncSGI)
6321 ps->psglx->glXWaitVideoSyncSGI = (f_WaitVideoSync)
6322 glXGetProcAddress((const GLubyte *) "glXWaitVideoSyncSGI");
6323 if (!ps->psglx->glXWaitVideoSyncSGI || !ps->psglx->glXGetVideoSyncSGI) {
6324 printf_errf("(): Failed to get glXWait/GetVideoSyncSGI function.");
6325 return false;
6326 }
6327
6328 return true;
6329 #else
6330 printf_errf("(): Program not compiled with OpenGL VSync support.");
6331 return false;
6332 #endif
6333 }
6334
6335 static bool
6336 vsync_opengl_oml_init(session_t *ps) {
6337 #ifdef CONFIG_VSYNC_OPENGL
6338 if (!ensure_glx_context(ps))
6339 return false;
6340
6341 // Get video sync functions
6342 if (!ps->psglx->glXGetSyncValuesOML)
6343 ps->psglx->glXGetSyncValuesOML = (f_GetSyncValuesOML)
6344 glXGetProcAddress ((const GLubyte *) "glXGetSyncValuesOML");
6345 if (!ps->psglx->glXWaitForMscOML)
6346 ps->psglx->glXWaitForMscOML = (f_WaitForMscOML)
6347 glXGetProcAddress ((const GLubyte *) "glXWaitForMscOML");
6348 if (!ps->psglx->glXGetSyncValuesOML || !ps->psglx->glXWaitForMscOML) {
6349 printf_errf("(): Failed to get OML_sync_control functions.");
6350 return false;
6351 }
6352
6353 return true;
6354 #else
6355 printf_errf("(): Program not compiled with OpenGL VSync support.");
6356 return false;
6357 #endif
6358 }
6359
6360 static bool
6361 vsync_opengl_swc_init(session_t *ps) {
6362 #ifdef CONFIG_VSYNC_OPENGL
6363 if (!ensure_glx_context(ps))
6364 return false;
6365
6366 if (!bkend_use_glx(ps)) {
6367 printf_errf("(): I'm afraid glXSwapIntervalSGI wouldn't help if you are "
6368 "not using GLX backend. You could try, nonetheless.");
6369 }
6370
6371 // Get video sync functions
6372 if (!ps->psglx->glXSwapIntervalProc)
6373 ps->psglx->glXSwapIntervalProc = (f_SwapIntervalSGI)
6374 glXGetProcAddress ((const GLubyte *) "glXSwapIntervalSGI");
6375 if (!ps->psglx->glXSwapIntervalProc) {
6376 printf_errf("(): Failed to get SGI_swap_control function.");
6377 return false;
6378 }
6379 ps->psglx->glXSwapIntervalProc(1);
6380
6381 return true;
6382 #else
6383 printf_errf("(): Program not compiled with OpenGL VSync support.");
6384 return false;
6385 #endif
6386 }
6387
6388 static bool
6389 vsync_opengl_mswc_init(session_t *ps) {
6390 #ifdef CONFIG_VSYNC_OPENGL
6391 if (!ensure_glx_context(ps))
6392 return false;
6393
6394 if (!bkend_use_glx(ps)) {
6395 printf_errf("(): I'm afraid glXSwapIntervalMESA wouldn't help if you are "
6396 "not using GLX backend. You could try, nonetheless.");
6397 }
6398
6399 // Get video sync functions
6400 if (!ps->psglx->glXSwapIntervalMESAProc)
6401 ps->psglx->glXSwapIntervalMESAProc = (f_SwapIntervalMESA)
6402 glXGetProcAddress ((const GLubyte *) "glXSwapIntervalMESA");
6403 if (!ps->psglx->glXSwapIntervalMESAProc) {
6404 printf_errf("(): Failed to get MESA_swap_control function.");
6405 return false;
6406 }
6407 ps->psglx->glXSwapIntervalMESAProc(1);
6408
6409 return true;
6410 #else
6411 printf_errf("(): Program not compiled with OpenGL VSync support.");
6412 return false;
6413 #endif
6414 }
6415
6416 #ifdef CONFIG_VSYNC_OPENGL
6417 /**
6418 * Wait for next VSync, OpenGL method.
6419 */
6420 static int
6421 vsync_opengl_wait(session_t *ps) {
6422 unsigned vblank_count = 0;
6423
6424 ps->psglx->glXGetVideoSyncSGI(&vblank_count);
6425 ps->psglx->glXWaitVideoSyncSGI(2, (vblank_count + 1) % 2, &vblank_count);
6426 // I see some code calling glXSwapIntervalSGI(1) afterwards, is it required?
6427
6428 return 0;
6429 }
6430
6431 /**
6432 * Wait for next VSync, OpenGL OML method.
6433 *
6434 * https://mail.gnome.org/archives/clutter-list/2012-November/msg00031.html
6435 */
6436 static int
6437 vsync_opengl_oml_wait(session_t *ps) {
6438 int64_t ust = 0, msc = 0, sbc = 0;
6439
6440 ps->psglx->glXGetSyncValuesOML(ps->dpy, ps->reg_win, &ust, &msc, &sbc);
6441 ps->psglx->glXWaitForMscOML(ps->dpy, ps->reg_win, 0, 2, (msc + 1) % 2,
6442 &ust, &msc, &sbc);
6443
6444 return 0;
6445 }
6446
6447 static void
6448 vsync_opengl_swc_deinit(session_t *ps) {
6449 // The standard says it doesn't accept 0, but in fact it probably does
6450 if (glx_has_context(ps) && ps->psglx->glXSwapIntervalProc)
6451 ps->psglx->glXSwapIntervalProc(0);
6452 }
6453
6454 static void
6455 vsync_opengl_mswc_deinit(session_t *ps) {
6456 if (glx_has_context(ps) && ps->psglx->glXSwapIntervalMESAProc)
6457 ps->psglx->glXSwapIntervalMESAProc(0);
6458 }
6459 #endif
6460
6461 /**
6462 * Initialize current VSync method.
6463 */
6464 bool
6465 vsync_init(session_t *ps) {
6466 if (ps->o.vsync && VSYNC_FUNCS_INIT[ps->o.vsync]
6467 && !VSYNC_FUNCS_INIT[ps->o.vsync](ps)) {
6468 ps->o.vsync = VSYNC_NONE;
6469 return false;
6470 }
6471 else
6472 return true;
6473 }
6474
6475 /**
6476 * Wait for next VSync.
6477 */
6478 static void
6479 vsync_wait(session_t *ps) {
6480 if (!ps->o.vsync)
6481 return;
6482
6483 if (VSYNC_FUNCS_WAIT[ps->o.vsync])
6484 VSYNC_FUNCS_WAIT[ps->o.vsync](ps);
6485 }
6486
6487 /**
6488 * Deinitialize current VSync method.
6489 */
6490 void
6491 vsync_deinit(session_t *ps) {
6492 if (ps->o.vsync && VSYNC_FUNCS_DEINIT[ps->o.vsync])
6493 VSYNC_FUNCS_DEINIT[ps->o.vsync](ps);
6494 }
6495
6496 /**
6497 * Pregenerate alpha pictures.
6498 */
6499 static void
6500 init_alpha_picts(session_t *ps) {
6501 int i;
6502 int num = round(1.0 / ps->o.alpha_step) + 1;
6503
6504 ps->alpha_picts = malloc(sizeof(Picture) * num);
6505
6506 for (i = 0; i < num; ++i) {
6507 double o = i * ps->o.alpha_step;
6508 if ((1.0 - o) > ps->o.alpha_step)
6509 ps->alpha_picts[i] = solid_picture(ps, false, o, 0, 0, 0);
6510 else
6511 ps->alpha_picts[i] = None;
6512 }
6513 }
6514
6515 /**
6516 * Initialize double buffer.
6517 */
6518 static bool
6519 init_dbe(session_t *ps) {
6520 if (!(ps->root_dbe = XdbeAllocateBackBufferName(ps->dpy,
6521 (ps->o.paint_on_overlay ? ps->overlay: ps->root), XdbeCopied))) {
6522 printf_errf("(): Failed to create double buffer. Double buffering "
6523 "cannot work.");
6524 return false;
6525 }
6526
6527 return true;
6528 }
6529
6530 /**
6531 * Initialize X composite overlay window.
6532 */
6533 static bool
6534 init_overlay(session_t *ps) {
6535 ps->overlay = XCompositeGetOverlayWindow(ps->dpy, ps->root);
6536 if (ps->overlay) {
6537 // Set window region of the overlay window, code stolen from
6538 // compiz-0.8.8
6539 XserverRegion region = XFixesCreateRegion(ps->dpy, NULL, 0);
6540 XFixesSetWindowShapeRegion(ps->dpy, ps->overlay, ShapeBounding, 0, 0, 0);
6541 XFixesSetWindowShapeRegion(ps->dpy, ps->overlay, ShapeInput, 0, 0, region);
6542 XFixesDestroyRegion(ps->dpy, region);
6543
6544 // Listen to Expose events on the overlay
6545 XSelectInput(ps->dpy, ps->overlay, ExposureMask);
6546
6547 // Retrieve DamageNotify on root window if we are painting on an
6548 // overlay
6549 // root_damage = XDamageCreate(ps->dpy, root, XDamageReportNonEmpty);
6550
6551 // Unmap overlay, firstly. But this typically does not work because
6552 // the window isn't created yet.
6553 // XUnmapWindow(ps->dpy, ps->overlay);
6554 // XFlush(ps->dpy);
6555 }
6556 else {
6557 fprintf(stderr, "Cannot get X Composite overlay window. Falling "
6558 "back to painting on root window.\n");
6559 ps->o.paint_on_overlay = false;
6560 }
6561 #ifdef DEBUG_REDIR
6562 printf_dbgf("(): overlay = %#010lx\n", ps->overlay);
6563 #endif
6564
6565 return ps->overlay;
6566 }
6567
6568 /**
6569 * Query needed X Render / OpenGL filters to check for their existence.
6570 */
6571 static bool
6572 init_filters(session_t *ps) {
6573 // Blur filter
6574 if (ps->o.blur_background || ps->o.blur_background_frame) {
6575 switch (ps->o.backend) {
6576 case BKEND_XRENDER:
6577 case BKEND_XR_GLX_HYBRID:
6578 {
6579 // Query filters
6580 XFilters *pf = XRenderQueryFilters(ps->dpy, get_tgt_window(ps));
6581 if (pf) {
6582 for (int i = 0; i < pf->nfilter; ++i) {
6583 // Convolution filter
6584 if (!strcmp(pf->filter[i], XRFILTER_CONVOLUTION))
6585 ps->xrfilter_convolution_exists = true;
6586 }
6587 }
6588 cxfree(pf);
6589
6590 // Turn features off if any required filter is not present
6591 if (!ps->xrfilter_convolution_exists) {
6592 printf_errf("(): X Render convolution filter unsupported by your X server. Background blur is not possible.");
6593 return false;
6594 }
6595 break;
6596 }
6597 #ifdef CONFIG_VSYNC_OPENGL
6598 case BKEND_GLX:
6599 return glx_init_blur(ps);
6600 #endif
6601 default:
6602 assert(false);
6603 }
6604 }
6605
6606 return true;
6607 }
6608
6609 /**
6610 * Redirect all windows.
6611 */
6612 static void
6613 redir_start(session_t *ps) {
6614 if (!ps->redirected) {
6615 #ifdef DEBUG_REDIR
6616 print_timestamp(ps);
6617 printf_dbgf("(): Screen redirected.\n");
6618 #endif
6619
6620 // Map overlay window. Done firstly according to this:
6621 // https://bugzilla.gnome.org/show_bug.cgi?id=597014
6622 if (ps->overlay)
6623 XMapWindow(ps->dpy, ps->overlay);
6624
6625 XCompositeRedirectSubwindows(ps->dpy, ps->root, CompositeRedirectManual);
6626
6627 /*
6628 // Unredirect GL context window as this may have an effect on VSync:
6629 // < http://dri.freedesktop.org/wiki/CompositeSwap >
6630 XCompositeUnredirectWindow(ps->dpy, ps->reg_win, CompositeRedirectManual);
6631 if (ps->o.paint_on_overlay && ps->overlay) {
6632 XCompositeUnredirectWindow(ps->dpy, ps->overlay,
6633 CompositeRedirectManual);
6634 } */
6635
6636 // Must call XSync() here
6637 XSync(ps->dpy, False);
6638
6639 ps->redirected = true;
6640
6641 // Repaint the whole screen
6642 force_repaint(ps);
6643 }
6644 }
6645
6646 /**
6647 * Get the poll time.
6648 */
6649 static time_ms_t
6650 timeout_get_poll_time(session_t *ps) {
6651 const time_ms_t now = get_time_ms();
6652 time_ms_t wait = TIME_MS_MAX;
6653
6654 // Traverse throught the timeout linked list
6655 for (timeout_t *ptmout = ps->tmout_lst; ptmout; ptmout = ptmout->next) {
6656 if (ptmout->enabled) {
6657 time_ms_t newrun = timeout_get_newrun(ptmout);
6658 if (newrun <= now) {
6659 wait = 0;
6660 break;
6661 }
6662 else {
6663 time_ms_t newwait = newrun - now;
6664 if (newwait < wait)
6665 wait = newwait;
6666 }
6667 }
6668 }
6669
6670 return wait;
6671 }
6672
6673 /**
6674 * Insert a new timeout.
6675 */
6676 timeout_t *
6677 timeout_insert(session_t *ps, time_ms_t interval,
6678 bool (*callback)(session_t *ps, timeout_t *ptmout), void *data) {
6679 const static timeout_t tmout_def = {
6680 .enabled = true,
6681 .data = NULL,
6682 .callback = NULL,
6683 .firstrun = 0L,
6684 .lastrun = 0L,
6685 .interval = 0L,
6686 };
6687
6688 const time_ms_t now = get_time_ms();
6689 timeout_t *ptmout = malloc(sizeof(timeout_t));
6690 if (!ptmout)
6691 printf_errfq(1, "(): Failed to allocate memory for timeout.");
6692 memcpy(ptmout, &tmout_def, sizeof(timeout_t));
6693
6694 ptmout->interval = interval;
6695 ptmout->firstrun = now;
6696 ptmout->lastrun = now;
6697 ptmout->data = data;
6698 ptmout->callback = callback;
6699 ptmout->next = ps->tmout_lst;
6700 ps->tmout_lst = ptmout;
6701
6702 return ptmout;
6703 }
6704
6705 /**
6706 * Drop a timeout.
6707 *
6708 * @return true if we have found the timeout and removed it, false
6709 * otherwise
6710 */
6711 bool
6712 timeout_drop(session_t *ps, timeout_t *prm) {
6713 timeout_t **pplast = &ps->tmout_lst;
6714
6715 for (timeout_t *ptmout = ps->tmout_lst; ptmout;
6716 pplast = &ptmout->next, ptmout = ptmout->next) {
6717 if (prm == ptmout) {
6718 *pplast = ptmout->next;
6719 free(ptmout);
6720
6721 return true;
6722 }
6723 }
6724
6725 return false;
6726 }
6727
6728 /**
6729 * Clear all timeouts.
6730 */
6731 static void
6732 timeout_clear(session_t *ps) {
6733 timeout_t *ptmout = ps->tmout_lst;
6734 timeout_t *next = NULL;
6735 while (ptmout) {
6736 next = ptmout->next;
6737 free(ptmout);
6738 ptmout = next;
6739 }
6740 }
6741
6742 /**
6743 * Run timeouts.
6744 *
6745 * @return true if we have ran a timeout, false otherwise
6746 */
6747 static bool
6748 timeout_run(session_t *ps) {
6749 const time_ms_t now = get_time_ms();
6750 bool ret = false;
6751 timeout_t *pnext = NULL;
6752
6753 for (timeout_t *ptmout = ps->tmout_lst; ptmout; ptmout = pnext) {
6754 pnext = ptmout->next;
6755 if (ptmout->enabled) {
6756 const time_ms_t max = now +
6757 (time_ms_t) (ptmout->interval * TIMEOUT_RUN_TOLERANCE);
6758 time_ms_t newrun = timeout_get_newrun(ptmout);
6759 if (newrun <= max) {
6760 ret = true;
6761 timeout_invoke(ps, ptmout);
6762 }
6763 }
6764 }
6765
6766 return ret;
6767 }
6768
6769 /**
6770 * Invoke a timeout.
6771 */
6772 void
6773 timeout_invoke(session_t *ps, timeout_t *ptmout) {
6774 const time_ms_t now = get_time_ms();
6775 ptmout->lastrun = now;
6776 // Avoid modifying the timeout structure after running timeout, to
6777 // make it possible to remove timeout in callback
6778 if (ptmout->callback)
6779 ptmout->callback(ps, ptmout);
6780 }
6781
6782 /**
6783 * Reset a timeout to initial state.
6784 */
6785 void
6786 timeout_reset(session_t *ps, timeout_t *ptmout) {
6787 ptmout->firstrun = ptmout->lastrun = get_time_ms();
6788 }
6789
6790 /**
6791 * Unredirect all windows.
6792 */
6793 static void
6794 redir_stop(session_t *ps) {
6795 if (ps->redirected) {
6796 #ifdef DEBUG_REDIR
6797 print_timestamp(ps);
6798 printf_dbgf("(): Screen unredirected.\n");
6799 #endif
6800 // Destroy all Pictures as they expire once windows are unredirected
6801 // If we don't destroy them here, looks like the resources are just
6802 // kept inaccessible somehow
6803 for (win *w = ps->list; w; w = w->next)
6804 free_wpaint(ps, w);
6805
6806 XCompositeUnredirectSubwindows(ps->dpy, ps->root, CompositeRedirectManual);
6807 // Unmap overlay window
6808 if (ps->overlay)
6809 XUnmapWindow(ps->dpy, ps->overlay);
6810
6811 // Must call XSync() here
6812 XSync(ps->dpy, False);
6813
6814 ps->redirected = false;
6815 }
6816 }
6817
6818 /**
6819 * Unredirection timeout callback.
6820 */
6821 static bool
6822 tmout_unredir_callback(session_t *ps, timeout_t *tmout) {
6823 ps->tmout_unredir_hit = true;
6824 tmout->enabled = false;
6825
6826 return true;
6827 }
6828
6829 /**
6830 * Main loop.
6831 */
6832 static bool
6833 mainloop(session_t *ps) {
6834 // Don't miss timeouts even when we have a LOT of other events!
6835 timeout_run(ps);
6836
6837 // Process existing events
6838 // Sometimes poll() returns 1 but no events are actually read,
6839 // causing XNextEvent() to block, I have no idea what's wrong, so we
6840 // check for the number of events here.
6841 if (XEventsQueued(ps->dpy, QueuedAfterReading)) {
6842 XEvent ev = { };
6843
6844 XNextEvent(ps->dpy, &ev);
6845 ev_handle(ps, &ev);
6846 ps->ev_received = true;
6847
6848 return true;
6849 }
6850
6851 #ifdef CONFIG_DBUS
6852 if (ps->o.dbus) {
6853 cdbus_loop(ps);
6854 }
6855 #endif
6856
6857 if (ps->reset)
6858 return false;
6859
6860 // Calculate timeout
6861 struct timeval *ptv = NULL;
6862 {
6863 // Consider ev_received firstly
6864 if (ps->ev_received || ps->o.benchmark) {
6865 ptv = malloc(sizeof(struct timeval));
6866 ptv->tv_sec = 0L;
6867 ptv->tv_usec = 0L;
6868 }
6869 // Then consider fading timeout
6870 else if (!ps->idling) {
6871 ptv = malloc(sizeof(struct timeval));
6872 *ptv = ms_to_tv(fade_timeout(ps));
6873 }
6874
6875 // Software optimization is to be applied on timeouts that require
6876 // immediate painting only
6877 if (ptv && ps->o.sw_opti)
6878 swopti_handle_timeout(ps, ptv);
6879
6880 // Don't continue looping for 0 timeout
6881 if (ptv && timeval_isempty(ptv)) {
6882 free(ptv);
6883 return false;
6884 }
6885
6886 // Now consider the waiting time of other timeouts
6887 time_ms_t tmout_ms = timeout_get_poll_time(ps);
6888 if (tmout_ms < TIME_MS_MAX) {
6889 if (!ptv) {
6890 ptv = malloc(sizeof(struct timeval));
6891 *ptv = ms_to_tv(tmout_ms);
6892 }
6893 else if (timeval_ms_cmp(ptv, tmout_ms) > 0) {
6894 *ptv = ms_to_tv(tmout_ms);
6895 }
6896 }
6897
6898 // Don't continue looping for 0 timeout
6899 if (ptv && timeval_isempty(ptv)) {
6900 free(ptv);
6901 return false;
6902 }
6903 }
6904
6905 // Polling
6906 fds_poll(ps, ptv);
6907 free(ptv);
6908 ptv = NULL;
6909
6910 return true;
6911 }
6912
6913 static void
6914 cxinerama_upd_scrs(session_t *ps) {
6915 #ifdef CONFIG_XINERAMA
6916 free_xinerama_info(ps);
6917
6918 if (!ps->o.xinerama_shadow_crop || !ps->xinerama_exists) return;
6919
6920 if (!XineramaIsActive(ps->dpy)) return;
6921
6922 ps->xinerama_scrs = XineramaQueryScreens(ps->dpy, &ps->xinerama_nscrs);
6923
6924 // Just in case the shit hits the fan...
6925 if (!ps->xinerama_nscrs) {
6926 cxfree(ps->xinerama_scrs);
6927 ps->xinerama_scrs = NULL;
6928 return;
6929 }
6930
6931 ps->xinerama_scr_regs = allocchk(malloc(sizeof(XserverRegion *)
6932 * ps->xinerama_nscrs));
6933 for (int i = 0; i < ps->xinerama_nscrs; ++i) {
6934 const XineramaScreenInfo * const s = &ps->xinerama_scrs[i];
6935 XRectangle r = { .x = s->x_org, .y = s->y_org,
6936 .width = s->width, .height = s->height };
6937 ps->xinerama_scr_regs[i] = XFixesCreateRegion(ps->dpy, &r, 1);
6938 }
6939 #endif
6940 }
6941
6942 /**
6943 * Initialize a session.
6944 *
6945 * @param ps_old old session, from which the function will take the X
6946 * connection, then free it
6947 * @param argc number of commandline arguments
6948 * @param argv commandline arguments
6949 */
6950 static session_t *
6951 session_init(session_t *ps_old, int argc, char **argv) {
6952 const static session_t s_def = {
6953 .dpy = NULL,
6954 .scr = 0,
6955 .vis = NULL,
6956 .depth = 0,
6957 .root = None,
6958 .root_height = 0,
6959 .root_width = 0,
6960 // .root_damage = None,
6961 .overlay = None,
6962 .root_tile_fill = false,
6963 .root_tile_paint = PAINT_INIT,
6964 .screen_reg = None,
6965 .tgt_picture = None,
6966 .tgt_buffer = PAINT_INIT,
6967 .root_dbe = None,
6968 .reg_win = None,
6969 .o = {
6970 .config_file = NULL,
6971 .display = NULL,
6972 .backend = BKEND_XRENDER,
6973 .glx_no_stencil = false,
6974 .glx_copy_from_front = false,
6975 #ifdef CONFIG_VSYNC_OPENGL_GLSL
6976 .glx_prog_win = GLX_PROG_MAIN_INIT,
6977 #endif
6978 .mark_wmwin_focused = false,
6979 .mark_ovredir_focused = false,
6980 .fork_after_register = false,
6981 .synchronize = false,
6982 .detect_rounded_corners = false,
6983 .paint_on_overlay = false,
6984 .resize_damage = 0,
6985 .unredir_if_possible = false,
6986 .unredir_if_possible_blacklist = NULL,
6987 .unredir_if_possible_delay = 0,
6988 .redirected_force = UNSET,
6989 .stoppaint_force = UNSET,
6990 .dbus = false,
6991 .benchmark = 0,
6992 .benchmark_wid = None,
6993 .logpath = NULL,
6994
6995 .refresh_rate = 0,
6996 .sw_opti = false,
6997 .vsync = VSYNC_NONE,
6998 .dbe = false,
6999 .vsync_aggressive = false,
7000
7001 .wintype_shadow = { false },
7002 .shadow_red = 0.0,
7003 .shadow_green = 0.0,
7004 .shadow_blue = 0.0,
7005 .shadow_radius = 12,
7006 .shadow_offset_x = -15,
7007 .shadow_offset_y = -15,
7008 .shadow_opacity = .75,
7009 .clear_shadow = false,
7010 .shadow_blacklist = NULL,
7011 .shadow_ignore_shaped = false,
7012 .respect_prop_shadow = false,
7013 .xinerama_shadow_crop = false,
7014
7015 .wintype_fade = { false },
7016 .fade_in_step = 0.028 * OPAQUE,
7017 .fade_out_step = 0.03 * OPAQUE,
7018 .fade_delta = 10,
7019 .no_fading_openclose = false,
7020 .no_fading_destroyed_argb = false,
7021 .fade_blacklist = NULL,
7022
7023 .wintype_opacity = { NAN },
7024 .inactive_opacity = OPAQUE,
7025 .inactive_opacity_override = false,
7026 .active_opacity = OPAQUE,
7027 .frame_opacity = 0.0,
7028 .detect_client_opacity = false,
7029 .alpha_step = 0.03,
7030
7031 .blur_background = false,
7032 .blur_background_frame = false,
7033 .blur_background_fixed = false,
7034 .blur_background_blacklist = NULL,
7035 .blur_kerns = { NULL },
7036 .inactive_dim = 0.0,
7037 .inactive_dim_fixed = false,
7038 .invert_color_list = NULL,
7039 .opacity_rules = NULL,
7040
7041 .wintype_focus = { false },
7042 .use_ewmh_active_win = false,
7043 .focus_blacklist = NULL,
7044 .detect_transient = false,
7045 .detect_client_leader = false,
7046
7047 .track_focus = false,
7048 .track_wdata = false,
7049 .track_leader = false,
7050 },
7051
7052 .pfds_read = NULL,
7053 .pfds_write = NULL,
7054 .pfds_except = NULL,
7055 .nfds_max = 0,
7056 .tmout_lst = NULL,
7057
7058 .all_damage = None,
7059 .all_damage_last = { None },
7060 .time_start = { 0, 0 },
7061 .redirected = false,
7062 .alpha_picts = NULL,
7063 .reg_ignore_expire = false,
7064 .idling = false,
7065 .fade_time = 0L,
7066 .ignore_head = NULL,
7067 .ignore_tail = NULL,
7068 .reset = false,
7069
7070 .expose_rects = NULL,
7071 .size_expose = 0,
7072 .n_expose = 0,
7073
7074 .list = NULL,
7075 .active_win = NULL,
7076 .active_leader = None,
7077
7078 .black_picture = None,
7079 .cshadow_picture = None,
7080 .white_picture = None,
7081 .gaussian_map = NULL,
7082 .cgsize = 0,
7083 .shadow_corner = NULL,
7084 .shadow_top = NULL,
7085
7086 .refresh_rate = 0,
7087 .refresh_intv = 0UL,
7088 .paint_tm_offset = 0L,
7089
7090 #ifdef CONFIG_VSYNC_DRM
7091 .drm_fd = -1,
7092 #endif
7093
7094 .xfixes_event = 0,
7095 .xfixes_error = 0,
7096 .damage_event = 0,
7097 .damage_error = 0,
7098 .render_event = 0,
7099 .render_error = 0,
7100 .composite_event = 0,
7101 .composite_error = 0,
7102 .composite_opcode = 0,
7103 .has_name_pixmap = false,
7104 .shape_exists = false,
7105 .shape_event = 0,
7106 .shape_error = 0,
7107 .randr_exists = 0,
7108 .randr_event = 0,
7109 .randr_error = 0,
7110 #ifdef CONFIG_VSYNC_OPENGL
7111 .glx_exists = false,
7112 .glx_event = 0,
7113 .glx_error = 0,
7114 #endif
7115 .dbe_exists = false,
7116 .xrfilter_convolution_exists = false,
7117
7118 .atom_opacity = None,
7119 .atom_frame_extents = None,
7120 .atom_client = None,
7121 .atom_name = None,
7122 .atom_name_ewmh = None,
7123 .atom_class = None,
7124 .atom_role = None,
7125 .atom_transient = None,
7126 .atom_ewmh_active_win = None,
7127 .atom_compton_shadow = None,
7128 .atom_win_type = None,
7129 .atoms_wintypes = { 0 },
7130 .track_atom_lst = NULL,
7131
7132 #ifdef CONFIG_DBUS
7133 .dbus_conn = NULL,
7134 .dbus_service = NULL,
7135 #endif
7136 };
7137
7138 // Allocate a session and copy default values into it
7139 session_t *ps = malloc(sizeof(session_t));
7140 memcpy(ps, &s_def, sizeof(session_t));
7141 ps_g = ps;
7142 ps->ignore_tail = &ps->ignore_head;
7143 gettimeofday(&ps->time_start, NULL);
7144
7145 wintype_arr_enable(ps->o.wintype_focus);
7146 ps->o.wintype_focus[WINTYPE_UNKNOWN] = false;
7147 ps->o.wintype_focus[WINTYPE_NORMAL] = false;
7148 ps->o.wintype_focus[WINTYPE_UTILITY] = false;
7149
7150 // First pass
7151 get_cfg(ps, argc, argv, true);
7152
7153 // Inherit old Display if possible, primarily for resource leak checking
7154 if (ps_old && ps_old->dpy)
7155 ps->dpy = ps_old->dpy;
7156
7157 // Open Display
7158 if (!ps->dpy) {
7159 ps->dpy = XOpenDisplay(ps->o.display);
7160 if (!ps->dpy) {
7161 printf_errfq(1, "(): Can't open display.");
7162 }
7163 }
7164
7165 XSetErrorHandler(xerror);
7166 if (ps->o.synchronize) {
7167 XSynchronize(ps->dpy, 1);
7168 }
7169
7170 ps->scr = DefaultScreen(ps->dpy);
7171 ps->root = RootWindow(ps->dpy, ps->scr);
7172
7173 ps->vis = DefaultVisual(ps->dpy, ps->scr);
7174 ps->depth = DefaultDepth(ps->dpy, ps->scr);
7175
7176 // Start listening to events on root earlier to catch all possible
7177 // root geometry changes
7178 XSelectInput(ps->dpy, ps->root,
7179 SubstructureNotifyMask
7180 | ExposureMask
7181 | StructureNotifyMask
7182 | PropertyChangeMask);
7183 XFlush(ps->dpy);
7184
7185 ps->root_width = DisplayWidth(ps->dpy, ps->scr);
7186 ps->root_height = DisplayHeight(ps->dpy, ps->scr);
7187
7188 if (!XRenderQueryExtension(ps->dpy,
7189 &ps->render_event, &ps->render_error)) {
7190 fprintf(stderr, "No render extension\n");
7191 exit(1);
7192 }
7193
7194 if (!XQueryExtension(ps->dpy, COMPOSITE_NAME, &ps->composite_opcode,
7195 &ps->composite_event, &ps->composite_error)) {
7196 fprintf(stderr, "No composite extension\n");
7197 exit(1);
7198 }
7199
7200 {
7201 int composite_major = 0, composite_minor = 0;
7202
7203 XCompositeQueryVersion(ps->dpy, &composite_major, &composite_minor);
7204
7205 if (!ps->o.no_name_pixmap
7206 && (composite_major > 0 || composite_minor >= 2)) {
7207 ps->has_name_pixmap = true;
7208 }
7209 }
7210
7211 if (!XDamageQueryExtension(ps->dpy, &ps->damage_event, &ps->damage_error)) {
7212 fprintf(stderr, "No damage extension\n");
7213 exit(1);
7214 }
7215
7216 if (!XFixesQueryExtension(ps->dpy, &ps->xfixes_event, &ps->xfixes_error)) {
7217 fprintf(stderr, "No XFixes extension\n");
7218 exit(1);
7219 }
7220
7221 // Build a safe representation of display name
7222 {
7223 char *display_repr = DisplayString(ps->dpy);
7224 if (!display_repr)
7225 display_repr = "unknown";
7226 display_repr = mstrcpy(display_repr);
7227
7228 // Convert all special characters in display_repr name to underscore
7229 {
7230 char *pdisp = display_repr;
7231
7232 while (*pdisp) {
7233 if (!isalnum(*pdisp))
7234 *pdisp = '_';
7235 ++pdisp;
7236 }
7237 }
7238
7239 ps->o.display_repr = display_repr;
7240 }
7241
7242 // Second pass
7243 get_cfg(ps, argc, argv, false);
7244
7245 // Query X Shape
7246 if (XShapeQueryExtension(ps->dpy, &ps->shape_event, &ps->shape_error)) {
7247 ps->shape_exists = true;
7248 }
7249
7250 if (ps->o.xrender_sync_fence) {
7251 #ifdef CONFIG_XSYNC
7252 // Query X Sync
7253 if (XSyncQueryExtension(ps->dpy, &ps->xsync_event, &ps->xsync_error)) {
7254 // TODO: Fencing may require version >= 3.0?
7255 int major_version_return = 0, minor_version_return = 0;
7256 if (XSyncInitialize(ps->dpy, &major_version_return, &minor_version_return))
7257 ps->xsync_exists = true;
7258 }
7259 if (!ps->xsync_exists) {
7260 printf_errf("(): X Sync extension not found. No X Sync fence sync is "
7261 "possible.");
7262 exit(1);
7263 }
7264 #else
7265 printf_errf("(): X Sync support not compiled in. --xrender-sync-fence "
7266 "can't work.");
7267 exit(1);
7268 #endif
7269 }
7270
7271 // Query X RandR
7272 if ((ps->o.sw_opti && !ps->o.refresh_rate) || ps->o.xinerama_shadow_crop) {
7273 if (XRRQueryExtension(ps->dpy, &ps->randr_event, &ps->randr_error))
7274 ps->randr_exists = true;
7275 else
7276 printf_errf("(): No XRandR extension, automatic screen change "
7277 "detection impossible.");
7278 }
7279
7280 // Query X DBE extension
7281 if (ps->o.dbe) {
7282 int dbe_ver_major = 0, dbe_ver_minor = 0;
7283 if (XdbeQueryExtension(ps->dpy, &dbe_ver_major, &dbe_ver_minor))
7284 if (dbe_ver_major >= 1)
7285 ps->dbe_exists = true;
7286 else
7287 fprintf(stderr, "DBE extension version too low. Double buffering "
7288 "impossible.\n");
7289 else {
7290 fprintf(stderr, "No DBE extension. Double buffering impossible.\n");
7291 }
7292 if (!ps->dbe_exists)
7293 ps->o.dbe = false;
7294 }
7295
7296 // Query X Xinerama extension
7297 if (ps->o.xinerama_shadow_crop) {
7298 #ifdef CONFIG_XINERAMA
7299 int xinerama_event = 0, xinerama_error = 0;
7300 if (XineramaQueryExtension(ps->dpy, &xinerama_event, &xinerama_error))
7301 ps->xinerama_exists = true;
7302 #else
7303 printf_errf("(): Xinerama support not compiled in.");
7304 #endif
7305 }
7306
7307 rebuild_screen_reg(ps);
7308
7309 // Overlay must be initialized before double buffer, and before creation
7310 // of OpenGL context.
7311 if (ps->o.paint_on_overlay)
7312 init_overlay(ps);
7313
7314 // Initialize DBE
7315 if (ps->o.dbe && BKEND_XRENDER != ps->o.backend) {
7316 printf_errf("(): DBE couldn't be used on GLX backend.");
7317 ps->o.dbe = false;
7318 }
7319
7320 if (ps->o.dbe && !init_dbe(ps))
7321 exit(1);
7322
7323 // Initialize OpenGL as early as possible
7324 if (bkend_use_glx(ps)) {
7325 #ifdef CONFIG_VSYNC_OPENGL
7326 if (!glx_init(ps, true))
7327 exit(1);
7328 #else
7329 printf_errfq(1, "(): GLX backend support not compiled in.");
7330 #endif
7331 }
7332
7333 // Initialize window GL shader
7334 if (BKEND_GLX == ps->o.backend && ps->o.glx_fshader_win_str) {
7335 #ifdef CONFIG_VSYNC_OPENGL_GLSL
7336 if (!glx_load_prog_main(ps, NULL, ps->o.glx_fshader_win_str, &ps->o.glx_prog_win))
7337 exit(1);
7338 #else
7339 printf_errf("(): GLSL supported not compiled in, can't load shader.");
7340 exit(1);
7341 #endif
7342 }
7343
7344 // Initialize software optimization
7345 if (ps->o.sw_opti)
7346 ps->o.sw_opti = swopti_init(ps);
7347
7348 // Monitor screen changes if vsync_sw is enabled and we are using
7349 // an auto-detected refresh rate, or when Xinerama features are enabled
7350 if (ps->randr_exists && ((ps->o.sw_opti && !ps->o.refresh_rate)
7351 || ps->o.xinerama_shadow_crop))
7352 XRRSelectInput(ps->dpy, ps->root, RRScreenChangeNotifyMask);
7353
7354 // Initialize VSync
7355 if (!vsync_init(ps))
7356 exit(1);
7357
7358 cxinerama_upd_scrs(ps);
7359
7360 // Create registration window
7361 if (!ps->reg_win && !register_cm(ps))
7362 exit(1);
7363
7364 init_atoms(ps);
7365 init_alpha_picts(ps);
7366
7367 ps->gaussian_map = make_gaussian_map(ps->o.shadow_radius);
7368 presum_gaussian(ps, ps->gaussian_map);
7369
7370 {
7371 XRenderPictureAttributes pa;
7372 pa.subwindow_mode = IncludeInferiors;
7373
7374 ps->root_picture = XRenderCreatePicture(ps->dpy, ps->root,
7375 XRenderFindVisualFormat(ps->dpy, ps->vis),
7376 CPSubwindowMode, &pa);
7377 if (ps->o.paint_on_overlay) {
7378 ps->tgt_picture = XRenderCreatePicture(ps->dpy, ps->overlay,
7379 XRenderFindVisualFormat(ps->dpy, ps->vis),
7380 CPSubwindowMode, &pa);
7381 }
7382 else {
7383 ps->tgt_picture = ps->root_picture;
7384 }
7385 }
7386
7387 // Initialize filters, must be preceded by OpenGL context creation
7388 if (!init_filters(ps))
7389 exit(1);
7390
7391 ps->black_picture = solid_picture(ps, true, 1, 0, 0, 0);
7392 ps->white_picture = solid_picture(ps, true, 1, 1, 1, 1);
7393
7394 // Generates another Picture for shadows if the color is modified by
7395 // user
7396 if (!ps->o.shadow_red && !ps->o.shadow_green && !ps->o.shadow_blue) {
7397 ps->cshadow_picture = ps->black_picture;
7398 } else {
7399 ps->cshadow_picture = solid_picture(ps, true, 1,
7400 ps->o.shadow_red, ps->o.shadow_green, ps->o.shadow_blue);
7401 }
7402
7403 fds_insert(ps, ConnectionNumber(ps->dpy), POLLIN);
7404 ps->tmout_unredir = timeout_insert(ps, ps->o.unredir_if_possible_delay,
7405 tmout_unredir_callback, NULL);
7406 ps->tmout_unredir->enabled = false;
7407
7408 XGrabServer(ps->dpy);
7409
7410 {
7411 Window root_return, parent_return;
7412 Window *children;
7413 unsigned int nchildren;
7414
7415 XQueryTree(ps->dpy, ps->root, &root_return,
7416 &parent_return, &children, &nchildren);
7417
7418 for (unsigned i = 0; i < nchildren; i++) {
7419 add_win(ps, children[i], i ? children[i-1] : None);
7420 }
7421
7422 cxfree(children);
7423 }
7424
7425 if (ps->o.track_focus) {
7426 recheck_focus(ps);
7427 }
7428
7429 XUngrabServer(ps->dpy);
7430 // ALWAYS flush after XUngrabServer()!
7431 XFlush(ps->dpy);
7432
7433 // Initialize DBus
7434 if (ps->o.dbus) {
7435 #ifdef CONFIG_DBUS
7436 cdbus_init(ps);
7437 if (!ps->dbus_conn) {
7438 cdbus_destroy(ps);
7439 ps->o.dbus = false;
7440 }
7441 #else
7442 printf_errfq(1, "(): DBus support not compiled in!");
7443 #endif
7444 }
7445
7446 // Fork to background, if asked
7447 if (ps->o.fork_after_register) {
7448 if (!fork_after(ps)) {
7449 session_destroy(ps);
7450 return NULL;
7451 }
7452 }
7453
7454 // Redirect output stream
7455 if (ps->o.fork_after_register || ps->o.logpath)
7456 ostream_reopen(ps, NULL);
7457
7458 write_pid(ps);
7459
7460 // Free the old session
7461 if (ps_old)
7462 free(ps_old);
7463
7464 return ps;
7465 }
7466
7467 /**
7468 * Destroy a session.
7469 *
7470 * Does not close the X connection or free the <code>session_t</code>
7471 * structure, though.
7472 *
7473 * @param ps session to destroy
7474 */
7475 static void
7476 session_destroy(session_t *ps) {
7477 redir_stop(ps);
7478
7479 // Stop listening to events on root window
7480 XSelectInput(ps->dpy, ps->root, 0);
7481
7482 #ifdef CONFIG_DBUS
7483 // Kill DBus connection
7484 if (ps->o.dbus)
7485 cdbus_destroy(ps);
7486
7487 free(ps->dbus_service);
7488 #endif
7489
7490 // Free window linked list
7491 {
7492 win *next = NULL;
7493 for (win *w = ps->list; w; w = next) {
7494 // Must be put here to avoid segfault
7495 next = w->next;
7496
7497 if (IsViewable == w->a.map_state && !w->destroyed)
7498 win_ev_stop(ps, w);
7499
7500 free_win_res(ps, w);
7501 free(w);
7502 }
7503
7504 ps->list = NULL;
7505 }
7506
7507 // Free alpha_picts
7508 {
7509 const int max = round(1.0 / ps->o.alpha_step) + 1;
7510 for (int i = 0; i < max; ++i)
7511 free_picture(ps, &ps->alpha_picts[i]);
7512 free(ps->alpha_picts);
7513 ps->alpha_picts = NULL;
7514 }
7515
7516 #ifdef CONFIG_C2
7517 // Free blacklists
7518 free_wincondlst(&ps->o.shadow_blacklist);
7519 free_wincondlst(&ps->o.fade_blacklist);
7520 free_wincondlst(&ps->o.focus_blacklist);
7521 free_wincondlst(&ps->o.invert_color_list);
7522 free_wincondlst(&ps->o.blur_background_blacklist);
7523 free_wincondlst(&ps->o.opacity_rules);
7524 free_wincondlst(&ps->o.paint_blacklist);
7525 free_wincondlst(&ps->o.unredir_if_possible_blacklist);
7526 #endif
7527
7528 // Free tracked atom list
7529 {
7530 latom_t *next = NULL;
7531 for (latom_t *this = ps->track_atom_lst; this; this = next) {
7532 next = this->next;
7533 free(this);
7534 }
7535
7536 ps->track_atom_lst = NULL;
7537 }
7538
7539 // Free ignore linked list
7540 {
7541 ignore_t *next = NULL;
7542 for (ignore_t *ign = ps->ignore_head; ign; ign = next) {
7543 next = ign->next;
7544
7545 free(ign);
7546 }
7547
7548 // Reset head and tail
7549 ps->ignore_head = NULL;
7550 ps->ignore_tail = &ps->ignore_head;
7551 }
7552
7553 // Free cshadow_picture and black_picture
7554 if (ps->cshadow_picture == ps->black_picture)
7555 ps->cshadow_picture = None;
7556 else
7557 free_picture(ps, &ps->cshadow_picture);
7558
7559 free_picture(ps, &ps->black_picture);
7560 free_picture(ps, &ps->white_picture);
7561
7562 // Free tgt_{buffer,picture} and root_picture
7563 if (ps->tgt_buffer.pict == ps->tgt_picture)
7564 ps->tgt_buffer.pict = None;
7565
7566 if (ps->tgt_picture == ps->root_picture)
7567 ps->tgt_picture = None;
7568 else
7569 free_picture(ps, &ps->tgt_picture);
7570 free_fence(ps, &ps->tgt_buffer_fence);
7571
7572 free_picture(ps, &ps->root_picture);
7573 free_paint(ps, &ps->tgt_buffer);
7574
7575 // Free other X resources
7576 free_root_tile(ps);
7577 free_region(ps, &ps->screen_reg);
7578 free_region(ps, &ps->all_damage);
7579 for (int i = 0; i < CGLX_MAX_BUFFER_AGE; ++i)
7580 free_region(ps, &ps->all_damage_last[i]);
7581 free(ps->expose_rects);
7582 free(ps->shadow_corner);
7583 free(ps->shadow_top);
7584 free(ps->gaussian_map);
7585
7586 free(ps->o.config_file);
7587 free(ps->o.write_pid_path);
7588 free(ps->o.display);
7589 free(ps->o.display_repr);
7590 free(ps->o.logpath);
7591 for (int i = 0; i < MAX_BLUR_PASS; ++i) {
7592 free(ps->o.blur_kerns[i]);
7593 free(ps->blur_kerns_cache[i]);
7594 }
7595 free(ps->pfds_read);
7596 free(ps->pfds_write);
7597 free(ps->pfds_except);
7598 free(ps->o.glx_fshader_win_str);
7599 free_xinerama_info(ps);
7600
7601 #ifdef CONFIG_VSYNC_OPENGL
7602 glx_destroy(ps);
7603 #endif
7604
7605 // Free double buffer
7606 if (ps->root_dbe) {
7607 XdbeDeallocateBackBufferName(ps->dpy, ps->root_dbe);
7608 ps->root_dbe = None;
7609 }
7610
7611 #ifdef CONFIG_VSYNC_DRM
7612 // Close file opened for DRM VSync
7613 if (ps->drm_fd >= 0) {
7614 close(ps->drm_fd);
7615 ps->drm_fd = -1;
7616 }
7617 #endif
7618
7619 // Release overlay window
7620 if (ps->overlay) {
7621 XCompositeReleaseOverlayWindow(ps->dpy, ps->overlay);
7622 ps->overlay = None;
7623 }
7624
7625 // Free reg_win
7626 if (ps->reg_win) {
7627 XDestroyWindow(ps->dpy, ps->reg_win);
7628 ps->reg_win = None;
7629 }
7630
7631 // Flush all events
7632 XSync(ps->dpy, True);
7633
7634 #ifdef DEBUG_XRC
7635 // Report about resource leakage
7636 xrc_report_xid();
7637 #endif
7638
7639 // Free timeouts
7640 ps->tmout_unredir = NULL;
7641 timeout_clear(ps);
7642
7643 if (ps == ps_g)
7644 ps_g = NULL;
7645 }
7646
7647 /*
7648 static inline void
7649 dump_img(session_t *ps) {
7650 int len = 0;
7651 unsigned char *d = glx_take_screenshot(ps, &len);
7652 write_binary_data("/tmp/dump.raw", d, len);
7653 free(d);
7654 }
7655 */
7656
7657 /**
7658 * Do the actual work.
7659 *
7660 * @param ps current session
7661 */
7662 static void
7663 session_run(session_t *ps) {
7664 win *t;
7665
7666 if (ps->o.sw_opti)
7667 ps->paint_tm_offset = get_time_timeval().tv_usec;
7668
7669 ps->reg_ignore_expire = true;
7670
7671 t = paint_preprocess(ps, ps->list);
7672
7673 if (ps->redirected)
7674 paint_all(ps, None, None, t);
7675
7676 // Initialize idling
7677 ps->idling = false;
7678
7679 // Main loop
7680 while (!ps->reset) {
7681 ps->ev_received = false;
7682
7683 while (mainloop(ps))
7684 continue;
7685
7686 if (ps->o.benchmark) {
7687 if (ps->o.benchmark_wid) {
7688 win *w = find_win(ps, ps->o.benchmark_wid);
7689 if (!w) {
7690 printf_errf("(): Couldn't find specified benchmark window.");
7691 session_destroy(ps);
7692 exit(1);
7693 }
7694 add_damage_win(ps, w);
7695 }
7696 else {
7697 force_repaint(ps);
7698 }
7699 }
7700
7701 // idling will be turned off during paint_preprocess() if needed
7702 ps->idling = true;
7703
7704 t = paint_preprocess(ps, ps->list);
7705 ps->tmout_unredir_hit = false;
7706
7707 // If the screen is unredirected, free all_damage to stop painting
7708 if (!ps->redirected || ON == ps->o.stoppaint_force)
7709 free_region(ps, &ps->all_damage);
7710
7711 XserverRegion all_damage_orig = None;
7712 if (ps->o.resize_damage > 0)
7713 all_damage_orig = copy_region(ps, ps->all_damage);
7714 resize_region(ps, ps->all_damage, ps->o.resize_damage);
7715 if (ps->all_damage && !is_region_empty(ps, ps->all_damage, NULL)) {
7716 static int paint = 0;
7717 paint_all(ps, ps->all_damage, all_damage_orig, t);
7718 ps->reg_ignore_expire = false;
7719 paint++;
7720 if (ps->o.benchmark && paint >= ps->o.benchmark)
7721 exit(0);
7722 XSync(ps->dpy, False);
7723 ps->all_damage = None;
7724 }
7725 free_region(ps, &all_damage_orig);
7726
7727 if (ps->idling)
7728 ps->fade_time = 0L;
7729 }
7730 }
7731
7732 /**
7733 * Turn on the program reset flag.
7734 *
7735 * This will result in compton resetting itself after next paint.
7736 */
7737 static void
7738 reset_enable(int __attribute__((unused)) signum) {
7739 session_t * const ps = ps_g;
7740
7741 ps->reset = true;
7742 }
7743
7744 /**
7745 * The function that everybody knows.
7746 */
7747 int
7748 main(int argc, char **argv) {
7749 // Set locale so window names with special characters are interpreted
7750 // correctly
7751 setlocale(LC_ALL, "");
7752
7753 // Set up SIGUSR1 signal handler to reset program
7754 {
7755 sigset_t block_mask;
7756 sigemptyset(&block_mask);
7757 const struct sigaction action= {
7758 .sa_handler = reset_enable,
7759 .sa_mask = block_mask,
7760 .sa_flags = 0
7761 };
7762 sigaction(SIGUSR1, &action, NULL);
7763 }
7764
7765 // Main loop
7766 session_t *ps_old = ps_g;
7767 while (1) {
7768 ps_g = session_init(ps_old, argc, argv);
7769 if (!ps_g) {
7770 printf_errf("(): Failed to create new session.");
7771 return 1;
7772 }
7773 session_run(ps_g);
7774 ps_old = ps_g;
7775 session_destroy(ps_g);
7776 }
7777
7778 free(ps_g);
7779
7780 return 0;
7781 }
7782
7783 // vim: set et sw=2 :