Debian Codegraph @

src/wm/win.c

raw symbols SCIP
1 // SPDX-License-Identifier: MIT
2 // Copyright (c) 2011-2013, Christopher Jeffrey
3 // Copyright (c) 2013 Richard Grenville <[email protected]>
4 // Copyright (c) 2018 Yuxuan Shui <[email protected]>
5
6 #include <X11/Xlib.h>
7 #include <X11/Xutil.h>
8 #include <inttypes.h>
9 #include <math.h>
10 #include <stdbool.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <xcb/composite.h>
14 #include <xcb/damage.h>
15 #include <xcb/render.h>
16 #include <xcb/xcb.h>
17 #include <xcb/xcb_renderutil.h>
18
19 #include <picom/types.h>
20
21 #include "atom.h"
22 #include "c2.h"
23 #include "common.h"
24 #include "compiler.h"
25 #include "config.h"
26 #include "dbus.h"
27 #include "inspect.h"
28 #include "log.h"
29 #include "picom.h"
30 #include "region.h"
31 #include "utils/console.h"
32 #include "utils/misc.h"
33 #include "x.h"
34
35 #include "defs.h"
36 #include "wm.h"
37
38 #include "win.h"
39
40 #define OPAQUE (0xffffffff)
41 static const int ROUNDED_PIXELS = 1;
42 static const double ROUNDED_PERCENT = 0.05;
43
44 // TODO(yshui)
45 //
46 // Right now, how window properties/states/information (let's just call them states)
47 // are calculated is a huge mess.
48 //
49 // We can divide a window's states (i.e. fields in struct managed_win) in to two groups:
50 // one is "raw" window states, those come directly from the X server; the other is
51 // computed window states, which is calculated based on the raw properties, and user
52 // configurations like rules etc.
53 //
54 // Right now what we do is when some raw states are updated, we set some flags to
55 // recalculate relevant computed states. This is really hard to get right, because it's
56 // tedious to figure out the influence a raw window state has. And it is also imprecise,
57 // just look at our `win_on_factor_changed` - it is so difficult to get the recalculation
58 // right, so we basically use "factor change" as a catch-all, basically any changes to raw
59 // states will cause it to be called. And we recalculate everything there, kind of
60 // destroying the whole point.
61 //
62 // A better way is doing this the other way around, we shouldn't need to do anything when
63 // updating a raw state. Instead, the computed states should declare which raw states they
64 // depend on, so we can go through the computed states, only recalculate the ones whose
65 // dependencies have changed. The c2 rules are kind of already calculated this way, we
66 // should unify the rest of the computed states. This would simplify the code as well.
67
68 static void
69 win_update_prop_shadow_raw(struct x_connection *c, struct atom *atoms, struct win *w);
70 static bool win_update_prop_shadow(struct x_connection *c, struct atom *atoms, struct win *w);
71 /**
72 * Update leader of a window.
73 */
74 static xcb_window_t
75 win_get_leader_property(struct x_connection *c, struct atom *atoms, xcb_window_t wid,
76 bool detect_transient, bool detect_client_leader);
77
78 /// Generate a "no corners" region function, from a function that returns the
79 /// region via a region_t pointer argument. Corners of the window will be removed from
80 /// the returned region.
81 /// Function signature has to be (win *, region_t *)
82 #define gen_without_corners(fun) \
83 void fun##_without_corners(const struct win *w, region_t *res) { \
84 fun(w, res); \
85 win_region_remove_corners_local(w, res); \
86 }
87
88 /// Generate a "return by value" function, from a function that returns the
89 /// region via a region_t pointer argument.
90 /// Function signature has to be (win *)
91 #define gen_by_val(fun) \
92 region_t fun##_by_val(const struct win *w) { \
93 region_t ret; \
94 pixman_region32_init(&ret); \
95 fun(w, &ret); \
96 return ret; \
97 }
98
99 /**
100 * Update focused state of a window.
101 */
102 static bool win_is_focused(session_t *ps, struct win *w) {
103 bool is_wmwin = win_is_wmwin(w);
104 if (w->a.map_state == XCB_MAP_STATE_VIEWABLE && (w->is_focused || w->is_group_focused)) {
105 return true;
106 }
107 // Use wintype_focus, and treat WM windows and override-redirected
108 // windows specially
109 if (ps->o.wintype_option[index_of_lowest_one(w->window_types)].focus ||
110 (ps->o.mark_wmwin_focused && is_wmwin) ||
111 (ps->o.mark_ovredir_focused && wm_ref_client_of(w->tree_ref) == NULL && !is_wmwin) ||
112 (w->a.map_state == XCB_MAP_STATE_VIEWABLE &&
113 c2_match(ps->c2_state, w, &ps->o.focus_blacklist, NULL))) {
114 return true;
115 }
116 return false;
117 }
118
119 struct group_callback_data {
120 struct session *ps;
121 xcb_window_t leader;
122 };
123
124 /**
125 * Get a rectangular region a window occupies, excluding shadow.
126 */
127 static void win_get_region_local(const struct win *w, region_t *res) {
128 assert(w->widthb >= 0 && w->heightb >= 0);
129 pixman_region32_fini(res);
130 pixman_region32_init_rect(res, 0, 0, (uint)w->widthb, (uint)w->heightb);
131 }
132
133 void win_get_region_frame_local(const struct win *w, region_t *res) {
134 const margin_t extents = win_calc_frame_extents(w);
135 auto outer_width = w->widthb;
136 auto outer_height = w->heightb;
137
138 pixman_region32_fini(res);
139 pixman_region32_init_rects(
140 res,
141 (rect_t[]){
142 // top
143 {.x1 = 0, .y1 = 0, .x2 = outer_width, .y2 = extents.top},
144 // bottom
145 {.x1 = 0, .y1 = outer_height - extents.bottom, .x2 = outer_width, .y2 = outer_height},
146 // left
147 {.x1 = 0, .y1 = 0, .x2 = extents.left, .y2 = outer_height},
148 // right
149 {.x1 = outer_width - extents.right, .y1 = 0, .x2 = outer_width, .y2 = outer_height},
150 },
151 4);
152
153 // limit the frame region to inside the window
154 region_t reg_win;
155 pixman_region32_init_rects(&reg_win, (rect_t[]){{0, 0, outer_width, outer_height}}, 1);
156 pixman_region32_intersect(res, &reg_win, res);
157 pixman_region32_fini(&reg_win);
158 }
159
160 gen_by_val(win_get_region_frame_local);
161
162 static inline void release_image_and_pixmap(backend_t *base, image_handle image) {
163 xcb_pixmap_t pixmap = base->ops.release_image(base, image);
164 if (pixmap != XCB_NONE) {
165 xcb_free_pixmap(base->c->c, pixmap);
166 }
167 }
168
169 /// Release the images attached to this window
170 static inline void win_release_pixmap(backend_t *base, struct win *w) {
171 log_debug("Releasing pixmap of window %#010x (%s)", win_id(w), w->name);
172 if (w->win_image) {
173 release_image_and_pixmap(base, w->win_image);
174 w->win_image = NULL;
175 }
176 }
177
178 static inline void win_release_shadow(backend_t *base, struct win *w) {
179 log_debug("Releasing shadow of window %#010x (%s)", win_id(w), w->name);
180 if (w->shadow_mask) {
181 release_image_and_pixmap(base, w->shadow_mask);
182 w->shadow_mask = NULL;
183 }
184 }
185
186 static inline void win_release_mask(backend_t *base, struct win *w) {
187 if (w->mask_image) {
188 release_image_and_pixmap(base, w->mask_image);
189 w->mask_image = NULL;
190 }
191 }
192
193 void win_release_saved_win_image(backend_t *base, struct win *w) {
194 if (w->saved_win_image) {
195 release_image_and_pixmap(base, w->saved_win_image);
196 w->saved_win_image = NULL;
197 }
198 }
199
200 void win_release_images(struct backend_base *backend, struct win *w) {
201 // We don't want to decide what we should do if the image we want to
202 // release is stale (do we clear the stale flags or not?) But if we are
203 // not releasing any images anyway, we don't care about the stale flags.
204 assert(w->win_image == NULL || !win_check_flags_all(w, WIN_FLAGS_PIXMAP_STALE));
205
206 win_release_pixmap(backend, w);
207 win_release_shadow(backend, w);
208 win_release_mask(backend, w);
209 win_release_saved_win_image(backend, w);
210 }
211
212 /// Returns true if the `prop` property is stale, as well as clears the stale
213 /// flag.
214 static bool win_fetch_and_unset_property_stale(struct win *w, xcb_atom_t prop);
215 /// Returns true if any of the properties are stale, as well as clear all the
216 /// stale flags.
217 static void win_clear_all_properties_stale(struct win *w);
218
219 /**
220 * Reread opacity property of a window.
221 */
222 bool win_update_opacity_prop(struct x_connection *c, struct atom *atoms, struct win *w,
223 bool detect_client_opacity) {
224 bool old_has_opacity_prop = w->has_opacity_prop;
225 auto old_opacity = w->opacity_prop;
226 // get frame opacity first
227 w->has_opacity_prop =
228 wid_get_opacity_prop(c, atoms, win_id(w), OPAQUE, &w->opacity_prop);
229
230 if (!w->has_opacity_prop && detect_client_opacity) {
231 // didn't find opacity prop on the frame, try to get client opacity
232 auto client_win = wm_ref_client_of(w->tree_ref);
233 if (client_win != NULL) {
234 w->has_opacity_prop = wid_get_opacity_prop(
235 c, atoms, wm_ref_win_id(client_win), OPAQUE, &w->opacity_prop);
236 }
237 }
238
239 if (w->has_opacity_prop) {
240 return !old_has_opacity_prop || w->opacity_prop != old_opacity;
241 }
242 return old_has_opacity_prop;
243 }
244
245 // TODO(yshui) make WIN_FLAGS_FACTOR_CHANGED more fine-grained, or find a better
246 // alternative
247 // way to do all this.
248
249 /// Fetch new window properties from the X server, and run appropriate updates.
250 /// Might set WIN_FLAGS_FACTOR_CHANGED
251 static void win_update_properties(session_t *ps, struct win *w) {
252 // we cannot receive property change when window has been destroyed
253 assert(w->state != WSTATE_DESTROYED);
254
255 if (win_fetch_and_unset_property_stale(w, ps->atoms->a_NET_WM_WINDOW_TYPE)) {
256 if (win_update_wintype(&ps->c, ps->atoms, w)) {
257 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
258 }
259 }
260
261 if (win_fetch_and_unset_property_stale(w, ps->atoms->a_NET_WM_WINDOW_OPACITY) &&
262 win_update_opacity_prop(&ps->c, ps->atoms, w, ps->o.detect_client_opacity)) {
263 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
264 }
265
266 if (win_fetch_and_unset_property_stale(w, ps->atoms->a_NET_FRAME_EXTENTS)) {
267 auto client_win = win_client_id(w, /*fallback_to_self=*/false);
268 win_update_frame_extents(&ps->c, ps->atoms, w, client_win);
269 }
270
271 if (win_fetch_and_unset_property_stale(w, ps->atoms->aWM_NAME) ||
272 win_fetch_and_unset_property_stale(w, ps->atoms->a_NET_WM_NAME)) {
273 if (win_update_name(&ps->c, ps->atoms, w) == 1) {
274 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
275 }
276 }
277
278 if (win_fetch_and_unset_property_stale(w, ps->atoms->aWM_CLASS)) {
279 if (win_update_class(&ps->c, ps->atoms, w)) {
280 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
281 }
282 }
283
284 if (win_fetch_and_unset_property_stale(w, ps->atoms->aWM_WINDOW_ROLE)) {
285 if (win_update_role(&ps->c, ps->atoms, w) == 1) {
286 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
287 }
288 }
289
290 if (win_fetch_and_unset_property_stale(w, ps->atoms->a_COMPTON_SHADOW)) {
291 if (win_update_prop_shadow(&ps->c, ps->atoms, w)) {
292 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
293 }
294 }
295
296 if (win_fetch_and_unset_property_stale(w, ps->atoms->a_NET_WM_STATE)) {
297 if (win_update_prop_fullscreen(&ps->c, ps->atoms, w)) {
298 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
299 }
300 }
301
302 if (ps->o.track_leader &&
303 (win_fetch_and_unset_property_stale(w, ps->atoms->aWM_CLIENT_LEADER) ||
304 win_fetch_and_unset_property_stale(w, ps->atoms->aWM_TRANSIENT_FOR) ||
305 win_fetch_and_unset_property_stale(w, XCB_ATOM_WM_HINTS))) {
306 auto client_win = win_client_id(w, /*fallback_to_self=*/true);
307 auto new_leader = win_get_leader_property(&ps->c, ps->atoms, client_win,
308 ps->o.detect_transient,
309 ps->o.detect_client_leader);
310 wm_ref_set_leader(ps->wm, w->tree_ref, new_leader);
311 }
312
313 win_clear_all_properties_stale(w);
314 }
315
316 /// Handle primary flags. These flags are set as direct results of raw X11 window data
317 /// changes.
318 void win_process_primary_flags(session_t *ps, struct win *w) {
319 log_trace("Processing flags for window %#010x (%s), was rendered: %d, flags: "
320 "%#" PRIx64,
321 win_id(w), w->name, w->to_paint, w->flags);
322
323 if (win_check_flags_all(w, WIN_FLAGS_MAPPED)) {
324 win_map_start(ps, w);
325 win_clear_flags(w, WIN_FLAGS_MAPPED);
326 }
327
328 if (w->state != WSTATE_MAPPED) {
329 // Window is not mapped, so we ignore all its changes until it's mapped
330 // again.
331 return;
332 }
333
334 if (win_check_flags_all(w, WIN_FLAGS_CLIENT_STALE)) {
335 win_on_client_update(ps, w);
336 win_clear_flags(w, WIN_FLAGS_CLIENT_STALE);
337 }
338
339 if (win_check_flags_any(w, WIN_FLAGS_SIZE_STALE | WIN_FLAGS_POSITION_STALE)) {
340 // For damage calculation purposes, we don't care if the window
341 // is mapped in X server, we only care if we rendered it last
342 // frame.
343 //
344 // We do not process window flags for unmapped windows even when
345 // it was rendered, so an window fading out won't move even if the
346 // underlying unmapped window is moved. When the window is
347 // mapped again when it's still fading out, it should have the
348 // same effect as a mapped window being moved, meaning we have
349 // to add both the previous and the new window extents to
350 // damage.
351 //
352 // All that is basically me saying what really matters is if the
353 // window was rendered last frame, not if it's mapped in X server.
354
355 // Update window geometry
356 w->previous.g = w->g;
357 w->g = w->pending_g;
358
359 // Whether a window is fullscreen changes based on its geometry
360 win_update_is_fullscreen(ps, w);
361
362 if (win_check_flags_all(w, WIN_FLAGS_SIZE_STALE)) {
363 win_on_win_size_change(w, ps->o.shadow_offset_x,
364 ps->o.shadow_offset_y, ps->o.shadow_radius);
365 win_update_bounding_shape(&ps->c, w, ps->o.detect_rounded_corners);
366 win_clear_flags(w, WIN_FLAGS_SIZE_STALE);
367
368 // Window shape/size changed, invalidate the images we built
369 // log_trace("free out dated pict");
370 win_set_flags(w, WIN_FLAGS_PIXMAP_STALE | WIN_FLAGS_FACTOR_CHANGED);
371
372 win_release_mask(ps->backend_data, w);
373 win_release_shadow(ps->backend_data, w);
374 ps->pending_updates = true;
375 }
376
377 if (win_check_flags_all(w, WIN_FLAGS_POSITION_STALE)) {
378 win_clear_flags(w, WIN_FLAGS_POSITION_STALE);
379 }
380 }
381
382 if (win_check_flags_all(w, WIN_FLAGS_PROPERTY_STALE)) {
383 win_update_properties(ps, w);
384 win_clear_flags(w, WIN_FLAGS_PROPERTY_STALE);
385 }
386 }
387
388 /// Handle secondary flags. These flags are set during the processing of primary flags.
389 /// Flags are separated into primaries and secondaries because processing of secondary
390 /// flags must happen after primary flags of ALL windows are processed, to make sure some
391 /// global states (e.g. active window group) are consistent because they will be used in
392 /// the processing of secondary flags.
393 void win_process_secondary_flags(session_t *ps, struct win *w) {
394 if (w->state != WSTATE_MAPPED) {
395 return;
396 }
397
398 // Handle window focus change. Set appropriate flags if focused states of
399 // this window changed in the wm tree.
400 bool new_focused = wm_focused_win(ps->wm) == w->tree_ref;
401 bool new_group_focused = wm_focused_leader(ps->wm) == wm_ref_leader(w->tree_ref);
402 if (new_focused != w->is_focused) {
403 log_debug("Window %#010x (%s) focus state changed from %d to %d",
404 win_id(w), w->name, w->is_focused, new_focused);
405 w->is_focused = new_focused;
406 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
407 // Send D-Bus signal
408 if (ps->o.dbus) {
409 if (new_focused) {
410 cdbus_ev_win_focusin(session_get_cdbus(ps), w);
411 } else {
412 cdbus_ev_win_focusout(session_get_cdbus(ps), w);
413 }
414 }
415 }
416 if (new_group_focused != w->is_group_focused) {
417 log_debug("Window %#010x (%s) group focus state changed from %d to %d",
418 win_id(w), w->name, w->is_group_focused, new_group_focused);
419 w->is_group_focused = new_group_focused;
420 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
421 }
422
423 if (w->flags == 0) {
424 return;
425 }
426
427 // Save the old window options, so if shadow changes from true to false,
428 // we can release the shadow.
429 auto old_options = win_options(w);
430
431 // Factor change flags could be set by previous stages, so must be handled
432 // last
433 if (win_check_flags_all(w, WIN_FLAGS_FACTOR_CHANGED)) {
434 win_on_factor_change(ps, w);
435 win_clear_flags(w, WIN_FLAGS_FACTOR_CHANGED);
436 }
437
438 auto new_options = win_options(w);
439
440 if (new_options.shadow != old_options.shadow && !new_options.shadow) {
441 win_release_shadow(ps->backend_data, w);
442 }
443 }
444
445 void win_process_image_flags(session_t *ps, struct win *w) {
446 // Assert that the MAPPED flag is already handled.
447 assert(!win_check_flags_all(w, WIN_FLAGS_MAPPED));
448
449 if (w->state != WSTATE_MAPPED || !win_check_flags_any(w, WIN_FLAGS_PIXMAP_STALE)) {
450 // 1. Flags of invisible windows are processed when they are mapped
451 // 2. We don't need to update window image if pixmap is not stale
452 return;
453 }
454
455 if (win_check_flags_all(w, WIN_FLAGS_PIXMAP_ERROR) || !ps->redirected) {
456 // 1. We have previously failed to bind the pixmap, don't try again.
457 // 2. If we aren't redirected, window images will be refreshed upon
458 // redirection anyway.
459 win_clear_flags(w, WIN_FLAGS_PIXMAP_STALE);
460 return;
461 }
462
463 // Image needs to be updated, update it.
464 win_clear_flags(w, WIN_FLAGS_PIXMAP_STALE);
465
466 // Check to make sure the window is still mapped, otherwise we won't be able to
467 // rebind pixmap after releasing it, yet we might still need the pixmap for
468 // rendering.
469 auto pixmap = x_new_id(&ps->c);
470 auto e = xcb_request_check(
471 ps->c.c, xcb_composite_name_window_pixmap_checked(ps->c.c, win_id(w), pixmap));
472 if (e != NULL) {
473 log_debug("Failed to get named pixmap for window %#010x(%s): %s. "
474 "Retaining its current window image",
475 win_id(w), w->name, x_strerror(&ps->c, e));
476 free(e);
477 return;
478 }
479
480 log_debug("New named pixmap for %#010x (%s) : %#010x", win_id(w), w->name, pixmap);
481
482 // Must release images first, otherwise breaks NVIDIA driver
483 win_release_pixmap(ps->backend_data, w);
484 w->win_image = ps->backend_data->ops.bind_pixmap(
485 ps->backend_data, pixmap, x_get_visual_info(&ps->c, w->a.visual));
486 if (!w->win_image) {
487 log_error("Failed to bind pixmap");
488 xcb_free_pixmap(ps->c.c, pixmap);
489 win_set_flags(w, WIN_FLAGS_PIXMAP_ERROR);
490 }
491 }
492
493 /**
494 * Check if a window has rounded corners.
495 * XXX This is really dumb
496 */
497 static bool attr_pure win_has_rounded_corners(const struct win *w) {
498 if (!w->bounding_shaped) {
499 return false;
500 }
501
502 // Quit if border_size() returns XCB_NONE
503 if (!pixman_region32_not_empty((region_t *)&w->bounding_shape)) {
504 return false;
505 }
506
507 // Determine the minimum width/height of a rectangle that could mark
508 // a window as having rounded corners
509 auto minwidth =
510 (uint16_t)max2(w->widthb * (1 - ROUNDED_PERCENT), w->widthb - ROUNDED_PIXELS);
511 auto minheight =
512 (uint16_t)max2(w->heightb * (1 - ROUNDED_PERCENT), w->heightb - ROUNDED_PIXELS);
513
514 // Get the rectangles in the bounding region
515 int nrects = 0;
516 const rect_t *rects =
517 pixman_region32_rectangles((region_t *)&w->bounding_shape, &nrects);
518
519 // Look for a rectangle large enough for this window be considered
520 // having rounded corners
521 for (int i = 0; i < nrects; ++i) {
522 if (rects[i].x2 - rects[i].x1 >= minwidth &&
523 rects[i].y2 - rects[i].y1 >= minheight) {
524 return true;
525 }
526 }
527 return false;
528 }
529
530 int win_update_name(struct x_connection *c, struct atom *atoms, struct win *w) {
531 char **strlst = NULL;
532 int nstr = 0;
533 auto client_win = win_client_id(w, /*fallback_to_self=*/true);
534
535 if (!(wid_get_text_prop(c, atoms, client_win, atoms->a_NET_WM_NAME, &strlst, &nstr))) {
536 log_debug("(%#010x): _NET_WM_NAME unset, falling back to WM_NAME.", client_win);
537
538 if (!wid_get_text_prop(c, atoms, client_win, atoms->aWM_NAME, &strlst, &nstr)) {
539 log_debug("Unsetting window name for %#010x", client_win);
540 free(w->name);
541 w->name = NULL;
542 return -1;
543 }
544 }
545
546 int ret = 0;
547 if (!w->name || strcmp(w->name, strlst[0]) != 0) {
548 ret = 1;
549 free(w->name);
550 w->name = strdup(strlst[0]);
551 }
552
553 free(strlst);
554
555 log_debug("(%#010x): client = %#010x, name = \"%s\", ret = %d", win_id(w),
556 client_win, w->name, ret);
557 return ret;
558 }
559
560 int win_update_role(struct x_connection *c, struct atom *atoms, struct win *w) {
561 char **strlst = NULL;
562 int nstr = 0;
563 auto client_win = win_client_id(w, /*fallback_to_self=*/true);
564
565 if (!wid_get_text_prop(c, atoms, client_win, atoms->aWM_WINDOW_ROLE, &strlst, &nstr)) {
566 return -1;
567 }
568
569 int ret = 0;
570 if (!w->role || strcmp(w->role, strlst[0]) != 0) {
571 ret = 1;
572 free(w->role);
573 w->role = strdup(strlst[0]);
574 }
575
576 free(strlst);
577
578 log_trace("(%#010x): client = %#010x, role = \"%s\", ret = %d", win_id(w),
579 client_win, w->role, ret);
580 return ret;
581 }
582
583 /**
584 * Check if a window is bounding-shaped.
585 */
586 static inline bool win_bounding_shaped(struct x_connection *c, xcb_window_t wid) {
587 xcb_shape_query_extents_reply_t *reply;
588 bool bounding_shaped;
589 reply = xcb_shape_query_extents_reply(c->c, xcb_shape_query_extents(c->c, wid), NULL);
590 bounding_shaped = reply && reply->bounding_shaped;
591 free(reply);
592
593 return bounding_shaped;
594 }
595
596 static uint32_t
597 wid_get_prop_window_types(struct x_connection *c, struct atom *atoms, xcb_window_t wid) {
598 winprop_t prop =
599 x_get_prop(c, wid, atoms->a_NET_WM_WINDOW_TYPE, 32L, XCB_ATOM_ATOM, 32);
600
601 static_assert(NUM_WINTYPES <= 32, "too many window types");
602
603 uint32_t ret = 0;
604 for (unsigned i = 0; i < prop.nitems; ++i) {
605 for (wintype_t j = 1; j < NUM_WINTYPES; ++j) {
606 if (get_atom_with_nul(atoms, WINTYPES[j].atom, c->c) == prop.atom[i]) {
607 ret |= (1U << j);
608 break;
609 }
610 }
611 }
612
613 free_winprop(&prop);
614
615 return ret;
616 }
617
618 // XXX should distinguish between frame has alpha and window body has alpha
619 bool win_has_alpha(const struct win *w) {
620 return w->pictfmt && w->pictfmt->type == XCB_RENDER_PICT_TYPE_DIRECT &&
621 w->pictfmt->direct.alpha_mask;
622 }
623
624 bool win_client_has_alpha(const struct win *w) {
625 return w->client_pictfmt && w->client_pictfmt->type == XCB_RENDER_PICT_TYPE_DIRECT &&
626 w->client_pictfmt->direct.alpha_mask;
627 }
628
629 winmode_t win_calc_mode_raw(const struct win *w) {
630 if (win_has_alpha(w)) {
631 if (wm_ref_client_of(w->tree_ref) == NULL) {
632 // This is a window not managed by the WM, and it has
633 // alpha, so it's transparent. No need to check WM frame.
634 return WMODE_TRANS;
635 }
636 // The WM window has alpha
637 if (win_client_has_alpha(w)) {
638 // The client window also has alpha, the entire window is
639 // transparent
640 return WMODE_TRANS;
641 }
642 if (win_has_frame(w)) {
643 // The client window doesn't have alpha, but we have a WM
644 // frame window, which has alpha.
645 return WMODE_FRAME_TRANS;
646 }
647 // Although the WM window has alpha, the frame window has 0 size,
648 // so consider the window solid
649 }
650
651 if (w->frame_opacity != 1.0 && win_has_frame(w)) {
652 return WMODE_FRAME_TRANS;
653 }
654
655 // log_trace("Window %#010x(%s) is solid", w->client_win, w->name);
656 return WMODE_SOLID;
657 }
658
659 winmode_t win_calc_mode(const struct win *w) {
660 if (win_animatable_get(w, WIN_SCRIPT_OPACITY) < 1.0) {
661 return WMODE_TRANS;
662 }
663 return win_calc_mode_raw(w);
664 }
665
666 /**
667 * Calculate and return the opacity target of a window.
668 *
669 * The priority of opacity settings are:
670 *
671 * inactive_opacity_override (if set, and unfocused) > _NET_WM_WINDOW_OPACITY (if
672 * set) > opacity-rules (if matched) > window type default opacity >
673 * active/inactive opacity
674 *
675 * @param ps current session
676 * @param w struct _win object representing the window
677 *
678 * @return target opacity
679 */
680 static double win_calc_opacity_target(session_t *ps, const struct win *w, bool focused) {
681 double opacity = 1;
682
683 if (w->state == WSTATE_UNMAPPED || w->state == WSTATE_DESTROYED) {
684 // be consistent
685 return 0;
686 }
687 // Try obeying opacity property and window type opacity firstly
688 auto window_type = index_of_lowest_one(w->window_types);
689 if (w->has_opacity_prop) {
690 opacity = ((double)w->opacity_prop) / OPAQUE;
691 } else if (!safe_isnan(w->options.opacity)) {
692 opacity = w->options.opacity;
693 } else if (!safe_isnan(ps->o.wintype_option[window_type].opacity)) {
694 opacity = ps->o.wintype_option[window_type].opacity;
695 } else {
696 // Respect active_opacity only when the window is physically
697 // focused
698 if (w->is_focused) {
699 opacity = ps->o.active_opacity;
700 } else if (!focused) {
701 // Respect inactive_opacity in some cases
702 opacity = ps->o.inactive_opacity;
703 }
704 }
705
706 // respect inactive override
707 if (ps->o.inactive_opacity_override && !focused) {
708 opacity = ps->o.inactive_opacity;
709 }
710
711 return opacity;
712 }
713
714 static inline double win_get_blur_opacity(const struct win *w) {
715 auto wopts = win_options(w);
716 return w->state == WSTATE_MAPPED ? wopts.blur_opacity : 0.0;
717 }
718
719 /// Finish the unmapping of a window (e.g. after fading has finished).
720 /// Doesn't free `w`
721 void unmap_win_finish(session_t *ps, struct win *w) {
722 // We are in unmap_win, this window definitely was viewable
723 if (ps->backend_data) {
724 // Only the pixmap needs to be freed and reacquired when mapping.
725 // Shadow image can be preserved.
726 win_release_pixmap(ps->backend_data, w);
727 } else {
728 assert(!w->win_image);
729 assert(!w->shadow_mask);
730 }
731
732 // Try again at binding images when the window is mapped next time
733 if (w->state != WSTATE_DESTROYED) {
734 win_clear_flags(w, WIN_FLAGS_PIXMAP_ERROR);
735 }
736 assert(w->running_animation_instance == NULL);
737 }
738
739 /**
740 * Determine whether a window is to be dimmed.
741 */
742 static void win_update_dim(session_t *ps, struct win *w, bool focused) {
743 // Make sure we do nothing if the window is unmapped / being destroyed
744 if (w->state == WSTATE_UNMAPPED) {
745 return;
746 }
747
748 if (ps->o.inactive_dim > 0 && !focused) {
749 w->options.dim = ps->o.inactive_dim;
750 } else {
751 w->options.dim = 0;
752 }
753 }
754
755 /**
756 * Reread _COMPTON_SHADOW property from a window.
757 *
758 * The property must be set on the outermost window, usually the WM frame.
759 */
760 void win_update_prop_shadow_raw(struct x_connection *c, struct atom *atoms, struct win *w) {
761 winprop_t prop =
762 x_get_prop(c, win_id(w), atoms->a_COMPTON_SHADOW, 1, XCB_ATOM_CARDINAL, 32);
763
764 if (!prop.nitems) {
765 w->prop_shadow = -1;
766 } else {
767 w->prop_shadow = *prop.c32;
768 }
769
770 free_winprop(&prop);
771 }
772
773 /**
774 * Determine if a window should have shadow, and update things depending
775 * on shadow state.
776 */
777 static void win_determine_shadow(session_t *ps, struct win *w) {
778 log_debug("Determining shadow of window %#010x (%s)", win_id(w), w->name);
779 w->options.shadow = TRI_UNKNOWN;
780
781 if (w->a.map_state != XCB_MAP_STATE_VIEWABLE) {
782 return;
783 }
784 if (!ps->o.wintype_option[index_of_lowest_one(w->window_types)].shadow) {
785 log_debug("Shadow disabled by wintypes");
786 w->options.shadow = TRI_FALSE;
787 } else if (c2_match(ps->c2_state, w, &ps->o.shadow_blacklist, NULL)) {
788 log_debug("Shadow disabled by shadow-exclude");
789 w->options.shadow = TRI_FALSE;
790 } else if (ps->o.shadow_ignore_shaped && w->bounding_shaped && !w->rounded_corners) {
791 log_debug("Shadow disabled by shadow-ignore-shaped");
792 w->options.shadow = TRI_FALSE;
793 } else if (w->prop_shadow == 0) {
794 log_debug("Shadow disabled by shadow property");
795 w->options.shadow = TRI_FALSE;
796 }
797 }
798
799 /**
800 * Reread _COMPTON_SHADOW property from a window and update related
801 * things.
802 */
803 static bool win_update_prop_shadow(struct x_connection *c, struct atom *atoms, struct win *w) {
804 long long attr_shadow_old = w->prop_shadow;
805 win_update_prop_shadow_raw(c, atoms, w);
806 return w->prop_shadow != attr_shadow_old;
807 }
808
809 /**
810 * Update window EWMH fullscreen state.
811 */
812 bool win_update_prop_fullscreen(struct x_connection *c, const struct atom *atoms,
813 struct win *w) {
814 auto prop = x_get_prop(c, win_client_id(w, /*fallback_to_self=*/true),
815 atoms->a_NET_WM_STATE, 12, XCB_ATOM_ATOM, 0);
816 bool is_fullscreen = false;
817 for (uint32_t i = 0; i < prop.nitems; i++) {
818 if (prop.atom[i] == atoms->a_NET_WM_STATE_FULLSCREEN) {
819 is_fullscreen = true;
820 break;
821 }
822 }
823 free_winprop(&prop);
824
825 bool changed = w->is_ewmh_fullscreen != is_fullscreen;
826 w->is_ewmh_fullscreen = is_fullscreen;
827 return changed;
828 }
829
830 static void win_determine_clip_shadow_above(session_t *ps, struct win *w) {
831 bool should_crop =
832 (ps->o.wintype_option[index_of_lowest_one(w->window_types)].clip_shadow_above ||
833 c2_match(ps->c2_state, w, &ps->o.shadow_clip_list, NULL));
834 w->options.clip_shadow_above = should_crop ? TRI_TRUE : TRI_UNKNOWN;
835 }
836
837 /**
838 * Determine if a window should have color inverted.
839 */
840 static void win_determine_invert_color(session_t *ps, struct win *w) {
841 w->options.invert_color = TRI_UNKNOWN;
842 if (w->a.map_state != XCB_MAP_STATE_VIEWABLE) {
843 return;
844 }
845
846 if (c2_match(ps->c2_state, w, &ps->o.invert_color_list, NULL)) {
847 w->options.invert_color = TRI_TRUE;
848 }
849 }
850
851 /**
852 * Determine if a window should have background blurred.
853 */
854 static void win_determine_blur_background(session_t *ps, struct win *w) {
855 log_debug("Determining blur-background of window %#010x (%s)", win_id(w), w->name);
856 w->options.blur_background = TRI_UNKNOWN;
857 if (w->a.map_state != XCB_MAP_STATE_VIEWABLE) {
858 return;
859 }
860
861 bool blur_background_new = ps->o.blur_method != BLUR_METHOD_NONE;
862 if (blur_background_new) {
863 if (!ps->o.wintype_option[index_of_lowest_one(w->window_types)].blur_background) {
864 log_debug("Blur background disabled by wintypes");
865 w->options.blur_background = TRI_FALSE;
866 } else if (c2_match(ps->c2_state, w, &ps->o.blur_background_blacklist, NULL)) {
867 log_debug("Blur background disabled by blur-background-exclude");
868 w->options.blur_background = TRI_FALSE;
869 }
870 }
871 }
872
873 /**
874 * Determine if a window should have rounded corners.
875 */
876 static void win_determine_rounded_corners(session_t *ps, struct win *w) {
877 void *radius_override = NULL;
878 bool blacklisted = c2_match(ps->c2_state, w, &ps->o.rounded_corners_blacklist, NULL);
879 if (blacklisted) {
880 w->options.corner_radius = 0;
881 return;
882 }
883
884 bool matched =
885 c2_match(ps->c2_state, w, &ps->o.corner_radius_rules, &radius_override);
886 if (matched) {
887 log_debug("Window %#010x (%s) matched corner rule! %d", win_id(w),
888 w->name, (int)(long)radius_override);
889 }
890
891 // Don't round full screen windows & excluded windows,
892 // unless we find a corner override in corner_radius_rules
893 if (!matched && w->is_fullscreen) {
894 w->options.corner_radius = 0;
895 log_debug("Not rounding corners for window %#010x", win_id(w));
896 } else {
897 if (matched) {
898 w->options.corner_radius = (int)(long)radius_override;
899 } else {
900 w->options.corner_radius = -1;
901 }
902
903 log_debug("Rounding corners for window %#010x", win_id(w));
904 // Initialize the border color to an invalid value
905 w->border_col[0] = w->border_col[1] = w->border_col[2] =
906 w->border_col[3] = -1.0F;
907 }
908 }
909
910 /**
911 * Determine custom window shader to use for a window.
912 */
913 static void win_determine_fg_shader(session_t *ps, struct win *w) {
914 if (w->a.map_state != XCB_MAP_STATE_VIEWABLE) {
915 return;
916 }
917
918 w->options.shader = NULL;
919
920 void *val = NULL;
921 if (c2_match(ps->c2_state, w, &ps->o.window_shader_fg_rules, &val)) {
922 w->options.shader = val;
923 }
924 }
925
926 /**
927 * Update window opacity according to opacity rules.
928 */
929 void win_update_opacity_rule(session_t *ps, struct win *w) {
930 if (w->a.map_state != XCB_MAP_STATE_VIEWABLE) {
931 return;
932 }
933
934 double opacity = NAN;
935 void *val = NULL;
936 if (c2_match(ps->c2_state, w, &ps->o.opacity_rules, &val)) {
937 opacity = ((double)(long)val) / 100.0;
938 }
939
940 w->options.opacity = opacity;
941 }
942
943 static bool
944 win_update_rule(struct session *ps, struct win *w, const c2_condition *rule, bool inspect) {
945 void *pdata = NULL;
946 if (inspect) {
947 printf(" %s ... ", c2_condition_to_str(rule));
948 }
949 bool matched = c2_match_one(ps->c2_state, w, rule, &pdata);
950 if (inspect) {
951 printf("%s\n", matched ? ANSI("1;32") "matched\033[0m" : "not matched");
952 }
953 if (!matched) {
954 return false;
955 }
956
957 auto wopts_next = (struct window_maybe_options *)pdata;
958 if (inspect) {
959 inspect_dump_window_maybe_options(*wopts_next);
960 }
961 w->options = win_maybe_options_fold(*wopts_next, w->options);
962 return false;
963 }
964
965 /**
966 * Function to be called on window data changes.
967 *
968 * TODO(yshui) need better name
969 */
970 void win_on_factor_change(session_t *ps, struct win *w) {
971 auto wid = win_client_id(w, /*fallback_to_self=*/true);
972 bool inspect = (ps->o.inspect_win != XCB_NONE && win_id(w) == ps->o.inspect_win) ||
973 ps->o.inspect_monitor;
974 log_debug("Window %#010x, client %#010x (%s) factor change", win_id(w), wid, w->name);
975 c2_window_state_update(ps->c2_state, &w->c2_state, ps->c.c, wid, win_id(w));
976 // Focus and is_fullscreen needs to be updated first, as other rules might depend
977 // on the focused state of the window
978 win_update_is_fullscreen(ps, w);
979
980 if (ps->o.inspect_monitor) {
981 printf("Window %#010x (Client %#010x):\n======\n\n", win_id(w),
982 win_client_id(w, /*fallback_to_self=*/true));
983 }
984
985 assert(w->window_types != 0);
986 if (list_is_empty(&ps->o.rules)) {
987 bool focused = win_is_focused(ps, w);
988 auto window_type = index_of_lowest_one(w->window_types);
989 // Universal rules take precedence over wintype_option and
990 // other exclusion/inclusion lists. And it also supersedes
991 // some of the "override" options.
992 win_determine_shadow(ps, w);
993 win_determine_clip_shadow_above(ps, w);
994 win_determine_invert_color(ps, w);
995 win_determine_blur_background(ps, w);
996 win_determine_rounded_corners(ps, w);
997 win_determine_fg_shader(ps, w);
998 win_update_opacity_rule(ps, w);
999 win_update_dim(ps, w, focused);
1000 w->mode = win_calc_mode(w);
1001 log_debug("Window mode changed to %d", w->mode);
1002 win_update_opacity_rule(ps, w);
1003 w->opacity = win_calc_opacity_target(ps, w, focused);
1004 w->options.paint = TRI_UNKNOWN;
1005 w->options.unredir = WINDOW_UNREDIR_INVALID;
1006 w->options.fade = TRI_UNKNOWN;
1007 w->options.transparent_clipping = TRI_UNKNOWN;
1008 if (w->a.map_state == XCB_MAP_STATE_VIEWABLE &&
1009 c2_match(ps->c2_state, w, &ps->o.paint_blacklist, NULL)) {
1010 w->options.paint = TRI_FALSE;
1011 }
1012 if (w->a.map_state == XCB_MAP_STATE_VIEWABLE &&
1013 c2_match(ps->c2_state, w, &ps->o.unredir_if_possible_blacklist, NULL)) {
1014 if (ps->o.wintype_option[window_type].redir_ignore) {
1015 w->options.unredir = WINDOW_UNREDIR_PASSIVE;
1016 } else {
1017 w->options.unredir = WINDOW_UNREDIR_TERMINATE;
1018 }
1019 } else if (win_is_bypassing_compositor(ps, w)) {
1020 // Here we deviate from EWMH a bit. EWMH says we must not
1021 // unredirect the screen if the window requesting bypassing would
1022 // look different after unredirecting. Instead we always follow
1023 // the request.
1024 w->options.unredir = WINDOW_UNREDIR_FORCED;
1025 } else if (ps->o.wintype_option[window_type].redir_ignore) {
1026 w->options.unredir = WINDOW_UNREDIR_WHEN_POSSIBLE;
1027 }
1028
1029 if (c2_match(ps->c2_state, w, &ps->o.fade_blacklist, NULL)) {
1030 w->options.fade = TRI_FALSE;
1031 }
1032 if (c2_match(ps->c2_state, w, &ps->o.transparent_clipping_blacklist, NULL)) {
1033 w->options.transparent_clipping = TRI_FALSE;
1034 }
1035 w->options.full_shadow =
1036 tri_from_bool(ps->o.wintype_option[window_type].full_shadow);
1037 } else {
1038 w->options = WIN_MAYBE_OPTIONS_DEFAULT;
1039 assert(w->state == WSTATE_MAPPED);
1040 if (inspect) {
1041 printf("Checking " BOLD("window rules") ":\n");
1042 }
1043 c2_condition_list_foreach_rev(&ps->o.rules, i) {
1044 win_update_rule(ps, w, i, inspect);
1045 }
1046 if (safe_isnan(w->options.opacity) && w->has_opacity_prop) {
1047 w->options.opacity = ((double)w->opacity_prop) / OPAQUE;
1048 }
1049 if (w->options.unredir == WINDOW_UNREDIR_INVALID &&
1050 win_is_bypassing_compositor(ps, w)) {
1051 // If `unredir` is not set by a rule, we follow the bypassing
1052 // compositor property.
1053 w->options.unredir = WINDOW_UNREDIR_FORCED;
1054 }
1055 w->opacity = win_options(w).opacity;
1056 }
1057
1058 w->mode = win_calc_mode(w);
1059 log_debug("Window mode changed to %d", w->mode);
1060
1061 if (ps->debug_window != XCB_NONE &&
1062 (win_id(w) == ps->debug_window ||
1063 (win_client_id(w, /*fallback_to_self=*/false) == ps->debug_window))) {
1064 w->options.paint = TRI_FALSE;
1065 }
1066
1067 if (inspect) {
1068 inspect_dump_window(ps->c2_state, &ps->o, w);
1069 printf("\n");
1070 if (!ps->o.inspect_monitor) {
1071 quit(ps);
1072 }
1073 }
1074 }
1075
1076 /**
1077 * Update cache data in struct _win that depends on window size.
1078 */
1079 void win_on_win_size_change(struct win *w, int shadow_offset_x, int shadow_offset_y,
1080 int shadow_radius) {
1081 log_trace("Window %#010x (%s) size changed, was %dx%d, now %dx%d", win_id(w),
1082 w->name, w->widthb, w->heightb, w->g.width + w->g.border_width * 2,
1083 w->g.height + w->g.border_width * 2);
1084
1085 w->widthb = w->g.width + w->g.border_width * 2;
1086 w->heightb = w->g.height + w->g.border_width * 2;
1087 w->shadow_dx = shadow_offset_x;
1088 w->shadow_dy = shadow_offset_y;
1089 w->shadow_width = w->widthb + shadow_radius * 2;
1090 w->shadow_height = w->heightb + shadow_radius * 2;
1091
1092 // We don't handle property updates of non-visible windows until they are
1093 // mapped.
1094 assert(w->state == WSTATE_MAPPED);
1095 }
1096
1097 /**
1098 * Update window type.
1099 */
1100 bool win_update_wintype(struct x_connection *c, struct atom *atoms, struct win *w) {
1101 const uint32_t wtypes_old = w->window_types;
1102 auto wid = win_client_id(w, /*fallback_to_self=*/true);
1103
1104 // Detect window type here
1105 w->window_types = wid_get_prop_window_types(c, atoms, wid);
1106
1107 // Conform to EWMH standard, if _NET_WM_WINDOW_TYPE is not present, take
1108 // override-redirect windows or windows without WM_TRANSIENT_FOR as
1109 // _NET_WM_WINDOW_TYPE_NORMAL, otherwise as _NET_WM_WINDOW_TYPE_DIALOG.
1110 if (w->window_types == 0) {
1111 if (w->a.override_redirect ||
1112 !wid_has_prop(c->c, wid, atoms->aWM_TRANSIENT_FOR)) {
1113 w->window_types = (1 << WINTYPE_NORMAL);
1114 } else {
1115 w->window_types = (1 << WINTYPE_DIALOG);
1116 }
1117 }
1118
1119 log_debug("Window (%#010x) has type %#x", win_id(w), w->window_types);
1120
1121 return w->window_types != wtypes_old;
1122 }
1123
1124 /**
1125 * Update window after its client window changed.
1126 *
1127 * @param ps current session
1128 * @param w struct _win of the parent window
1129 */
1130 void win_on_client_update(session_t *ps, struct win *w) {
1131 // If the window isn't mapped yet, stop here, as the function will be
1132 // called in map_win()
1133 if (w->a.map_state != XCB_MAP_STATE_VIEWABLE) {
1134 return;
1135 }
1136
1137 win_update_wintype(&ps->c, ps->atoms, w);
1138
1139 xcb_window_t client_win_id = win_client_id(w, /*fallback_to_self=*/true);
1140 // Get frame widths. The window is in damaged area already.
1141 win_update_frame_extents(&ps->c, ps->atoms, w, client_win_id);
1142
1143 // Get window group
1144 if (ps->o.track_leader) {
1145 auto new_leader = win_get_leader_property(&ps->c, ps->atoms, client_win_id,
1146 ps->o.detect_transient,
1147 ps->o.detect_client_leader);
1148 wm_ref_set_leader(ps->wm, w->tree_ref, new_leader);
1149 }
1150
1151 // Get window name and class if we are tracking them
1152 win_update_name(&ps->c, ps->atoms, w);
1153 win_update_class(&ps->c, ps->atoms, w);
1154 win_update_role(&ps->c, ps->atoms, w);
1155 c2_window_state_mark_dirty_for_client_change(ps->c2_state, &w->c2_state);
1156
1157 // Update everything related to conditions
1158 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
1159
1160 auto r = XCB_AWAIT(xcb_get_window_attributes, &ps->c, client_win_id);
1161 if (!r) {
1162 return;
1163 }
1164
1165 w->client_pictfmt = x_get_pictform_for_visual(&ps->c, r->visual);
1166 free(r);
1167 }
1168
1169 /**
1170 * Free all resources in a <code>struct _win</code>.
1171 */
1172 void free_win_res(session_t *ps, struct win *w) {
1173 // Above should be done during unmapping
1174 // Except when we are called by session_destroy
1175
1176 pixman_region32_fini(&w->damaged);
1177 pixman_region32_fini(&w->bounding_shape);
1178 // BadDamage may be thrown if the window is destroyed
1179 x_set_error_action_ignore(&ps->c, xcb_damage_destroy(ps->c.c, w->damage));
1180 free(w->name);
1181 free(w->class_instance);
1182 free(w->class_general);
1183 free(w->role);
1184
1185 free(w->stale_props);
1186 w->stale_props = NULL;
1187 w->stale_props_capacity = 0;
1188 c2_window_state_destroy(ps->c2_state, &w->c2_state);
1189 }
1190
1191 /// Query the Xorg for information about window `win`, and assign a window to `cursor` if
1192 /// this window should be managed.
1193 struct win *win_maybe_allocate(session_t *ps, struct wm_ref *cursor,
1194 const xcb_get_window_attributes_reply_t *attrs) {
1195 static const struct win win_def = {
1196 .frame_opacity = 1.0,
1197 .in_openclose = true, // set to false after first map is done,
1198 // true here because window is just created
1199 .flags = 0, // updated by
1200 // property/attributes/etc
1201 // change
1202
1203 .mode = WMODE_TRANS,
1204 .opacity_prop = OPAQUE,
1205 .opacity_set = 1,
1206 .frame_extents = MARGIN_INIT,
1207 .prop_shadow = -1,
1208 };
1209
1210 // Reject overlay window
1211 if (wm_ref_win_id(cursor) == ps->overlay) {
1212 // Would anyone reparent windows to the overlay window? Doing this
1213 // just in case.
1214 return NULL;
1215 }
1216
1217 xcb_window_t wid = wm_ref_win_id(cursor);
1218 log_debug("Managing window %#010x", wid);
1219 if (attrs->map_state == XCB_MAP_STATE_UNVIEWABLE) {
1220 // Failed to get window attributes or geometry probably means
1221 // the window is gone already. Unviewable means the window is
1222 // already reparented elsewhere.
1223 // BTW, we don't care about Input Only windows, except for
1224 // stacking proposes, so we need to keep track of them still.
1225 return NULL;
1226 }
1227
1228 if (attrs->_class == XCB_WINDOW_CLASS_INPUT_ONLY) {
1229 // No need to manage this window, but we still keep it on the
1230 // window stack
1231 return NULL;
1232 }
1233
1234 // Allocate and initialize the new win structure
1235 auto new = cmalloc(struct win);
1236
1237 // Fill structure
1238 // We only need to initialize the part that are not initialized
1239 // by map_win
1240 *new = win_def;
1241 new->a = *attrs;
1242 new->shadow_opacity = ps->o.shadow_opacity;
1243 pixman_region32_init(&new->bounding_shape);
1244
1245 xcb_generic_error_t *e;
1246 auto g = xcb_get_geometry_reply(ps->c.c, xcb_get_geometry(ps->c.c, wid), &e);
1247 if (!g) {
1248 log_debug("Failed to get geometry of window %#010x: %s", wid,
1249 x_strerror(&ps->c, e));
1250 free(e);
1251 free(new);
1252 return NULL;
1253 }
1254 new->pending_g = (struct win_geometry){
1255 .x = g->x,
1256 .y = g->y,
1257 .width = g->width,
1258 .height = g->height,
1259 .border_width = g->border_width,
1260 };
1261
1262 free(g);
1263
1264 // Create Damage for window (if not Input Only)
1265 new->damage = x_new_id(&ps->c);
1266 e = xcb_request_check(
1267 ps->c.c, xcb_damage_create_checked(ps->c.c, new->damage, wid,
1268 XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY));
1269 if (e) {
1270 log_debug("Failed to create damage for window %#010x: %s", wid,
1271 x_strerror(&ps->c, e));
1272 free(e);
1273 free(new);
1274 return NULL;
1275 }
1276
1277 // Set window event mask
1278 uint32_t frame_event_mask = XCB_EVENT_MASK_PROPERTY_CHANGE |
1279 XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
1280 XCB_EVENT_MASK_STRUCTURE_NOTIFY;
1281 if (!ps->o.use_ewmh_active_win) {
1282 frame_event_mask |= XCB_EVENT_MASK_FOCUS_CHANGE;
1283 }
1284 x_set_error_action_ignore(
1285 &ps->c, xcb_change_window_attributes(ps->c.c, wid, XCB_CW_EVENT_MASK,
1286 (const uint32_t[]){frame_event_mask}));
1287
1288 // Get notification when the shape of a window changes
1289 if (ps->c.e.has_shape) {
1290 x_set_error_action_ignore(&ps->c, xcb_shape_select_input(ps->c.c, wid, 1));
1291 }
1292
1293 new->pictfmt = x_get_pictform_for_visual(&ps->c, new->a.visual);
1294 new->client_pictfmt = NULL;
1295 new->tree_ref = cursor;
1296 new->options = WIN_MAYBE_OPTIONS_DEFAULT;
1297 new->options_override = WIN_MAYBE_OPTIONS_DEFAULT;
1298 new->options_default = &ps->window_options_default;
1299
1300 // Set all the stale flags on this new window, so it's properties will get
1301 // updated when it's mapped
1302 win_set_flags(new, WIN_FLAGS_SIZE_STALE | WIN_FLAGS_POSITION_STALE |
1303 WIN_FLAGS_PROPERTY_STALE | WIN_FLAGS_FACTOR_CHANGED);
1304 xcb_atom_t init_stale_props[] = {
1305 ps->atoms->a_NET_WM_WINDOW_TYPE, ps->atoms->a_NET_WM_WINDOW_OPACITY,
1306 ps->atoms->a_NET_FRAME_EXTENTS, ps->atoms->aWM_NAME,
1307 ps->atoms->a_NET_WM_NAME, ps->atoms->aWM_CLASS,
1308 ps->atoms->aWM_WINDOW_ROLE, ps->atoms->a_COMPTON_SHADOW,
1309 ps->atoms->aWM_CLIENT_LEADER, ps->atoms->aWM_TRANSIENT_FOR,
1310 ps->atoms->a_NET_WM_STATE,
1311 };
1312 win_set_properties_stale(new, init_stale_props, ARR_SIZE(init_stale_props));
1313 c2_window_state_init(ps->c2_state, &new->c2_state);
1314 pixman_region32_init(&new->damaged);
1315
1316 wm_ref_set(cursor, new);
1317
1318 return new;
1319 }
1320
1321 /**
1322 * Update leader of a window.
1323 */
1324 static xcb_window_t
1325 win_get_leader_property(struct x_connection *c, struct atom *atoms, xcb_window_t wid,
1326 bool detect_transient, bool detect_client_leader) {
1327 xcb_window_t leader = XCB_NONE;
1328 bool exists = false;
1329
1330 // Read the leader properties
1331 if (detect_transient) {
1332 leader = wid_get_prop_window(c, wid, atoms->aWM_TRANSIENT_FOR, &exists);
1333 log_debug("Leader via WM_TRANSIENT_FOR of window %#010x: %#010x", wid, leader);
1334 if (exists && (leader == c->screen_info->root || leader == XCB_NONE)) {
1335 // If WM_TRANSIENT_FOR is set to NONE or the root window, use the
1336 // window group leader.
1337 //
1338 // Ref:
1339 // https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html#idm44981516332096
1340 auto prop = x_get_prop(c, wid, XCB_ATOM_WM_HINTS, INT_MAX,
1341 XCB_ATOM_WM_HINTS, 32);
1342 if (prop.nitems >= 9) { // 9-th member is window_group
1343 leader = prop.c32[8];
1344 log_debug("Leader via WM_HINTS of window %#010x: %#010x",
1345 wid, leader);
1346 } else {
1347 leader = XCB_NONE;
1348 }
1349 free_winprop(&prop);
1350 }
1351 }
1352
1353 if (detect_client_leader && leader == XCB_NONE) {
1354 leader = wid_get_prop_window(c, wid, atoms->aWM_CLIENT_LEADER, &exists);
1355 log_debug("Leader via WM_CLIENT_LEADER of window %#010x: %#010x", wid, leader);
1356 }
1357
1358 log_debug("window %#010x: leader %#010x", wid, leader);
1359 return leader;
1360 }
1361
1362 /**
1363 * Retrieve the <code>WM_CLASS</code> of a window and update its
1364 * <code>win</code> structure.
1365 */
1366 bool win_update_class(struct x_connection *c, struct atom *atoms, struct win *w) {
1367 char **strlst = NULL;
1368 int nstr = 0;
1369 auto client_win = win_client_id(w, /*fallback_to_self=*/true);
1370
1371 // Free and reset old strings
1372 free(w->class_instance);
1373 free(w->class_general);
1374 w->class_instance = NULL;
1375 w->class_general = NULL;
1376
1377 // Retrieve the property string list
1378 if (!wid_get_text_prop(c, atoms, client_win, atoms->aWM_CLASS, &strlst, &nstr)) {
1379 return false;
1380 }
1381
1382 // Copy the strings if successful
1383 w->class_instance = strdup(strlst[0]);
1384
1385 if (nstr > 1) {
1386 w->class_general = strdup(strlst[1]);
1387 }
1388
1389 free(strlst);
1390
1391 log_trace("(%#010x): client = %#010x, instance = \"%s\", general = \"%s\"",
1392 win_id(w), client_win, w->class_instance, w->class_general);
1393
1394 return true;
1395 }
1396
1397 /**
1398 * Get a rectangular region a window (and possibly its shadow) occupies.
1399 *
1400 * Note w->shadow and shadow geometry must be correct before calling this
1401 * function.
1402 */
1403 void win_extents(const struct win *w, region_t *res) {
1404 pixman_region32_clear(res);
1405 if (w->state != WSTATE_MAPPED) {
1406 return;
1407 }
1408
1409 pixman_region32_union_rect(res, res, w->g.x, w->g.y, (uint)w->widthb, (uint)w->heightb);
1410 if (win_options(w).shadow) {
1411 assert(w->shadow_width >= 0 && w->shadow_height >= 0);
1412 pixman_region32_union_rect(res, res, w->g.x + w->shadow_dx,
1413 w->g.y + w->shadow_dy, (uint)w->shadow_width,
1414 (uint)w->shadow_height);
1415 }
1416 }
1417
1418 gen_by_val(win_extents);
1419
1420 /**
1421 * Update the out-dated bounding shape of a window.
1422 *
1423 * Mark the window shape as updated
1424 */
1425 void win_update_bounding_shape(struct x_connection *c, struct win *w,
1426 bool detect_rounded_corners) {
1427 // We don't handle property updates of non-visible windows until they are
1428 // mapped.
1429 assert(w->state == WSTATE_MAPPED);
1430
1431 pixman_region32_clear(&w->bounding_shape);
1432 // Start with the window rectangular region
1433 win_get_region_local(w, &w->bounding_shape);
1434
1435 if (c->e.has_shape) {
1436 w->bounding_shaped = win_bounding_shaped(c, win_id(w));
1437 }
1438
1439 // Only request for a bounding region if the window is shaped
1440 // (while loop is used to avoid goto, not an actual loop)
1441 while (w->bounding_shaped) {
1442 /*
1443 * if window doesn't exist anymore, this will generate an error
1444 * as well as not generate a region.
1445 */
1446
1447 xcb_shape_get_rectangles_reply_t *r = xcb_shape_get_rectangles_reply(
1448 c->c, xcb_shape_get_rectangles(c->c, win_id(w), XCB_SHAPE_SK_BOUNDING),
1449 NULL);
1450
1451 if (!r) {
1452 break;
1453 }
1454
1455 xcb_rectangle_t *xrects = xcb_shape_get_rectangles_rectangles(r);
1456 int nrects = xcb_shape_get_rectangles_rectangles_length(r);
1457 rect_t *rects = from_x_rects(nrects, xrects);
1458 free(r);
1459
1460 region_t br;
1461 pixman_region32_init_rects(&br, rects, nrects);
1462 free(rects);
1463
1464 // Add border width because we are using a different origin.
1465 // X thinks the top left of the inner window is the origin
1466 // (for the bounding shape, although xcb_get_geometry thinks
1467 // the outer top left (outer means outside of the window
1468 // border) is the origin),
1469 // We think the top left of the border is the origin
1470 pixman_region32_translate(&br, w->g.border_width, w->g.border_width);
1471
1472 // Intersect the bounding region we got with the window rectangle,
1473 // to make sure the bounding region is not bigger than the window
1474 // rectangle
1475 pixman_region32_intersect(&w->bounding_shape, &w->bounding_shape, &br);
1476 pixman_region32_fini(&br);
1477 break;
1478 }
1479
1480 if (w->bounding_shaped && detect_rounded_corners) {
1481 w->rounded_corners = win_has_rounded_corners(w);
1482 }
1483 }
1484
1485 /**
1486 * Retrieve frame extents from a window.
1487 */
1488 void win_update_frame_extents(struct x_connection *c, struct atom *atoms, struct win *w,
1489 xcb_window_t client) {
1490 if (client == XCB_NONE) {
1491 w->frame_extents = (margin_t){0};
1492 return;
1493 }
1494
1495 winprop_t prop =
1496 x_get_prop(c, client, atoms->a_NET_FRAME_EXTENTS, 4L, XCB_ATOM_CARDINAL, 32);
1497
1498 if (prop.nitems == 4) {
1499 int extents[4];
1500 for (int i = 0; i < 4; i++) {
1501 if (prop.c32[i] > (uint32_t)INT_MAX) {
1502 log_warn("Your window manager sets a absurd "
1503 "_NET_FRAME_EXTENTS value (%u), "
1504 "ignoring it.",
1505 prop.c32[i]);
1506 memset(extents, 0, sizeof(extents));
1507 break;
1508 }
1509 extents[i] = (int)prop.c32[i];
1510 }
1511
1512 w->frame_extents.left = extents[0];
1513 w->frame_extents.right = extents[1];
1514 w->frame_extents.top = extents[2];
1515 w->frame_extents.bottom = extents[3];
1516 }
1517
1518 log_trace("(%#010x): %d, %d, %d, %d", win_id(w), w->frame_extents.left,
1519 w->frame_extents.right, w->frame_extents.top, w->frame_extents.bottom);
1520
1521 free_winprop(&prop);
1522 }
1523
1524 /// Finish the destruction of a window (e.g. after fading has finished).
1525 /// Frees `w`
1526 void win_destroy_finish(session_t *ps, struct win *w) {
1527 log_debug("Trying to finish destroying (%#010x)", win_id(w));
1528
1529 unmap_win_finish(ps, w);
1530
1531 // Unmapping might preserve the shadow image, so free it here
1532 win_release_shadow(ps->backend_data, w);
1533 win_release_mask(ps->backend_data, w);
1534
1535 free_win_res(ps, w);
1536
1537 wm_reap_zombie(w->tree_ref);
1538 free(w);
1539 }
1540
1541 /// Start destroying a window. Windows cannot always be destroyed immediately
1542 /// because of fading and such.
1543 void win_destroy_start(struct win *w) {
1544 BUG_ON(w == NULL);
1545 log_debug("Destroying %#010x (%s)", win_id(w), w->name);
1546
1547 if (w->state != WSTATE_UNMAPPED) {
1548 // Only UNMAPPED state has window resources freed,
1549 // otherwise we need to call unmap_win_finish to free
1550 // them.
1551 log_warn("Did X server not unmap window %#010x before destroying "
1552 "it?",
1553 win_id(w));
1554 }
1555 // Clear IMAGES_STALE flags since the window is destroyed: Clear
1556 // PIXMAP_STALE as there is no pixmap available anymore, so STALE
1557 // doesn't make sense.
1558 // XXX Clear SHADOW_STALE as setting/clearing flags on a destroyed
1559 // window doesn't work leading to an inconsistent state where the
1560 // shadow is refreshed but the flags are stuck in STALE. Do this
1561 // before changing the window state to destroying
1562 win_clear_flags(w, WIN_FLAGS_PIXMAP_STALE);
1563
1564 // Clear some flags about stale window information. Because now
1565 // the window is destroyed, we can't update them anyway.
1566 win_clear_flags(w, WIN_FLAGS_SIZE_STALE | WIN_FLAGS_POSITION_STALE |
1567 WIN_FLAGS_PROPERTY_STALE | WIN_FLAGS_FACTOR_CHANGED);
1568
1569 // Update state flags of a managed window
1570 w->state = WSTATE_DESTROYED;
1571 w->opacity = 0.0F;
1572 w->a.map_state = XCB_MAP_STATE_UNMAPPED;
1573 w->in_openclose = true;
1574 }
1575
1576 void unmap_win_start(struct win *w) {
1577 assert(w);
1578 assert(w->a._class != XCB_WINDOW_CLASS_INPUT_ONLY);
1579
1580 log_debug("Unmapping %#010x (%s)", win_id(w), w->name);
1581
1582 assert(w->state != WSTATE_DESTROYED);
1583
1584 if (unlikely(w->state == WSTATE_UNMAPPED)) {
1585 assert(win_check_flags_all(w, WIN_FLAGS_MAPPED));
1586 // Window is mapped, but we hadn't had a chance to handle the MAPPED flag.
1587 // Clear the pending map as this window is now unmapped
1588 win_clear_flags(w, WIN_FLAGS_MAPPED);
1589 return;
1590 }
1591
1592 // Note we don't update focused window here. This will either be
1593 // triggered by subsequence Focus{In, Out} event, or by recheck_focus
1594
1595 w->a.map_state = XCB_MAP_STATE_UNMAPPED;
1596 w->state = WSTATE_UNMAPPED;
1597 w->opacity = 0.0F;
1598 }
1599
1600 static inline struct win_script_context
1601 win_script_context_prepare(struct session *ps, struct win *w) {
1602 auto monitor_index = win_find_monitor(&ps->monitors, w);
1603 auto monitor =
1604 monitor_index >= 0
1605 ? *pixman_region32_extents(&ps->monitors.regions[monitor_index])
1606 : (pixman_box32_t){
1607 .x1 = 0, .y1 = 0, .x2 = ps->root_width, .y2 = ps->root_height};
1608 struct win_script_context ret = {
1609 .x = w->g.x,
1610 .y = w->g.y,
1611 .width = w->widthb,
1612 .height = w->heightb,
1613 .opacity = w->opacity,
1614 .x_before = w->previous.g.x,
1615 .y_before = w->previous.g.y,
1616 .width_before = w->previous.g.width + w->previous.g.border_width * 2,
1617 .height_before = w->previous.g.height + w->previous.g.border_width * 2,
1618 .opacity_before = w->previous.opacity,
1619 .blur_opacity = win_get_blur_opacity(w),
1620 .blur_opacity_before = w->previous.blur_opacity,
1621 .monitor_x = monitor.x1,
1622 .monitor_y = monitor.y1,
1623 .monitor_width = monitor.x2 - monitor.x1,
1624 .monitor_height = monitor.y2 - monitor.y1,
1625 .shadow_color_before = w->previous.shadow_color,
1626 .shadow_color = w->options.shadow_color,
1627 };
1628 return ret;
1629 }
1630
1631 double win_animatable_get(const struct win *w, enum win_script_output output) {
1632 if (w->running_animation_instance && w->running_animation.output_indices[output] >= 0) {
1633 return w->running_animation_instance
1634 ->memory[w->running_animation.output_indices[output]];
1635 }
1636
1637 auto wopts = win_options(w);
1638 switch (output) {
1639 case WIN_SCRIPT_BLUR_OPACITY: return win_get_blur_opacity(w);
1640 case WIN_SCRIPT_OPACITY:
1641 case WIN_SCRIPT_SHADOW_OPACITY: return w->opacity;
1642 case WIN_SCRIPT_CROP_X:
1643 case WIN_SCRIPT_CROP_Y:
1644 case WIN_SCRIPT_OFFSET_X:
1645 case WIN_SCRIPT_OFFSET_Y:
1646 case WIN_SCRIPT_SHADOW_OFFSET_X:
1647 case WIN_SCRIPT_SHADOW_OFFSET_Y: return 0;
1648 case WIN_SCRIPT_SCALE_X:
1649 case WIN_SCRIPT_SCALE_Y:
1650 case WIN_SCRIPT_SHADOW_SCALE_X:
1651 case WIN_SCRIPT_SHADOW_SCALE_Y: return 1;
1652 case WIN_SCRIPT_CROP_WIDTH:
1653 case WIN_SCRIPT_CROP_HEIGHT: return INFINITY;
1654 case WIN_SCRIPT_SAVED_IMAGE_BLEND: return 0;
1655 case WIN_SCRIPT_SHADOW_RED: return wopts.shadow_color.red;
1656 case WIN_SCRIPT_SHADOW_GREEN: return wopts.shadow_color.green;
1657 case WIN_SCRIPT_SHADOW_BLUE: return wopts.shadow_color.blue;
1658 default: unreachable();
1659 }
1660 unreachable();
1661 }
1662
1663 #define WSTATE_PAIR(a, b) ((int)(a) * NUM_OF_WSTATES + (int)(b))
1664 /// Advance the animation of a window.
1665 ///
1666 /// Returns true if animation was running before this function is called, and is no
1667 /// longer running now. Returns false if animation is still running, or if there was no
1668 /// animation running when this is called.
1669 static bool win_advance_animation(struct win *w, double delta_t,
1670 const struct win_script_context *win_ctx) {
1671 // No state changes, if there's a animation running, we just continue it.
1672 if (w->running_animation_instance == NULL) {
1673 return false;
1674 }
1675 log_verbose("Advance animation for %#010x (%s) %f seconds", win_id(w), w->name, delta_t);
1676 if (!script_instance_is_finished(w->running_animation_instance)) {
1677 auto elapsed_slot =
1678 script_elapsed_slot(w->running_animation_instance->script);
1679 w->running_animation_instance->memory[elapsed_slot] += delta_t;
1680 auto result = script_instance_evaluate(w->running_animation_instance,
1681 (void *)win_ctx, false);
1682 if (result != SCRIPT_EVAL_OK) {
1683 log_error("Failed to run animation script: %d", result);
1684 return true;
1685 }
1686 return false;
1687 }
1688 return true;
1689 }
1690
1691 bool win_process_animation_and_state_change(struct session *ps, struct win *w, double delta_t) {
1692 // If the window hasn't ever been damaged yet, it won't be rendered in this frame.
1693 // Or if it doesn't have a image bound, it won't be rendered either. (This can
1694 // happen is a window is destroyed during a backend reset. Backend resets releases
1695 // all images, and if a window is freed during that, its image cannot be
1696 // reacquired.)
1697 //
1698 // If the window won't be rendered, and it is also unmapped/destroyed, it won't
1699 // receive damage events or reacquire an image. In this case we can skip its
1700 // animation. For mapped windows, we need to provisionally start animation,
1701 // because its first damage event might come a bit late.
1702 bool will_never_render =
1703 (!w->ever_damaged || w->win_image == NULL) && w->state != WSTATE_MAPPED;
1704 auto win_ctx = win_script_context_prepare(ps, w);
1705
1706 bool size_changed = win_size_changed(w->previous.g, w->g);
1707 bool position_changed = win_position_changed(w->previous.g, w->g);
1708
1709 auto old_state = w->previous.state;
1710
1711 w->previous.state = w->state;
1712 w->previous.opacity = w->opacity;
1713 w->previous.g = w->g;
1714 w->previous.shadow_color = w->options.shadow_color;
1715 w->previous.blur_opacity = win_get_blur_opacity(w);
1716
1717 if (!ps->redirected || will_never_render) {
1718 // This window won't be rendered, so we don't need to run the animations.
1719 bool state_changed = old_state != w->state ||
1720 win_ctx.opacity_before != win_ctx.opacity ||
1721 size_changed || position_changed;
1722 return state_changed || (w->running_animation_instance != NULL);
1723 }
1724
1725 // Try to determine the right animation trigger based on state changes. Note there
1726 // is some complications here. X automatically unmaps windows before destroying
1727 // them. So a "close" trigger will also be fired from a UNMAPPED -> DESTROYED
1728 // transition, besides the more obvious MAPPED -> DESTROYED transition. But this
1729 // also means, if the user didn't configure a animation for "hide", but did
1730 // for "close", there is a chance this animation won't be triggered, if there is a
1731 // gap between the UnmapNotify and DestroyNotify. There is no way on our end of
1732 // fixing this without using hacks.
1733 enum animation_trigger trigger = ANIMATION_TRIGGER_INVALID;
1734
1735 // Animation trigger priority:
1736 // state > position > size > opacity > color
1737 if (old_state != w->state) {
1738 // Send D-Bus signal
1739 if (ps->o.dbus) {
1740 switch (w->state) {
1741 case WSTATE_UNMAPPED:
1742 cdbus_ev_win_unmapped(session_get_cdbus(ps), w);
1743 break;
1744 case WSTATE_MAPPED:
1745 cdbus_ev_win_mapped(session_get_cdbus(ps), w);
1746 break;
1747 case WSTATE_DESTROYED:
1748 cdbus_ev_win_destroyed(session_get_cdbus(ps), w);
1749 break;
1750 }
1751 }
1752
1753 switch (WSTATE_PAIR(old_state, w->state)) {
1754 case WSTATE_PAIR(WSTATE_UNMAPPED, WSTATE_MAPPED):
1755 trigger = w->in_openclose ? ANIMATION_TRIGGER_OPEN
1756 : ANIMATION_TRIGGER_SHOW;
1757 break;
1758 case WSTATE_PAIR(WSTATE_UNMAPPED, WSTATE_DESTROYED):
1759 if ((!ps->o.no_fading_destroyed_argb || !win_has_alpha(w)) &&
1760 w->running_animation_instance != NULL) {
1761 trigger = ANIMATION_TRIGGER_CLOSE;
1762 }
1763 break;
1764 case WSTATE_PAIR(WSTATE_MAPPED, WSTATE_DESTROYED):
1765 // TODO(yshui) we should deprecate "no-fading-destroyed-argb" and
1766 // ask user to write fading rules (after we have added such
1767 // rules). Ditto below.
1768 if (!ps->o.no_fading_destroyed_argb || !win_has_alpha(w)) {
1769 trigger = ANIMATION_TRIGGER_CLOSE;
1770 }
1771 break;
1772 case WSTATE_PAIR(WSTATE_MAPPED, WSTATE_UNMAPPED):
1773 trigger = ANIMATION_TRIGGER_HIDE;
1774 break;
1775 default:
1776 log_error("Impossible state transition from %d to %d", old_state,
1777 w->state);
1778 assert(false);
1779 return true;
1780 }
1781 } else if (size_changed) {
1782 assert(w->state == WSTATE_MAPPED);
1783 trigger = ANIMATION_TRIGGER_SIZE;
1784 } else if (position_changed) {
1785 assert(w->state == WSTATE_MAPPED);
1786 trigger = ANIMATION_TRIGGER_POSITION;
1787 } else if (win_ctx.opacity_before != win_ctx.opacity) {
1788 assert(w->state == WSTATE_MAPPED);
1789 trigger = win_ctx.opacity > win_ctx.opacity_before
1790 ? ANIMATION_TRIGGER_INCREASE_OPACITY
1791 : ANIMATION_TRIGGER_DECREASE_OPACITY;
1792 } else if (win_ctx.blur_opacity_before != win_ctx.blur_opacity) {
1793 trigger = win_ctx.blur_opacity > win_ctx.blur_opacity_before
1794 ? ANIMATION_TRIGGER_INCREASE_OPACITY
1795 : ANIMATION_TRIGGER_DECREASE_OPACITY;
1796 } else if (!color_eq(win_ctx.shadow_color_before, win_ctx.shadow_color)) {
1797 assert(w->state == WSTATE_MAPPED);
1798 trigger = ANIMATION_TRIGGER_COLOR;
1799 }
1800
1801 if (trigger == ANIMATION_TRIGGER_INVALID) {
1802 // No state changes, if there's a animation running, we just continue it.
1803 return win_advance_animation(w, delta_t, &win_ctx);
1804 }
1805
1806 if (w->running_animation_instance &&
1807 (w->running_animation.suppressions & (1 << trigger)) != 0) {
1808 log_debug("Not starting animation %s for window %#010x (%s) because it "
1809 "is being suppressed.",
1810 animation_trigger_names[trigger], win_id(w), w->name);
1811 return win_advance_animation(w, delta_t, &win_ctx);
1812 }
1813
1814 if (w->animation_block[trigger] > 0) {
1815 log_debug("Not starting animation %s for window %#010x (%s) because it "
1816 "is blocked.",
1817 animation_trigger_names[trigger], win_id(w), w->name);
1818 return win_advance_animation(w, delta_t, &win_ctx);
1819 }
1820
1821 auto wopts = win_options(w);
1822 if (wopts.animations[trigger].script == NULL) {
1823 return true;
1824 }
1825
1826 if (wopts.animations[trigger].is_generated && !wopts.fade) {
1827 // Window's animation is fading (as signified by the fact that it's
1828 // generated), but the user has disabled fading for this window.
1829 return true;
1830 }
1831
1832 log_debug("Starting animation %s for window %#010x (%s)",
1833 animation_trigger_names[trigger], win_id(w), w->name);
1834
1835 if (win_check_flags_any(w, WIN_FLAGS_PIXMAP_STALE)) {
1836 // Grab the old pixmap, animations might need it
1837 if (w->saved_win_image) {
1838 win_release_saved_win_image(ps->backend_data, w);
1839 }
1840 if (ps->drivers & DRIVER_NVIDIA) {
1841 // NVIDIA doesn't like us grabbing the new pixmap before releasing
1842 // the old one. So we copy the content of the old pixmap so we can
1843 // release it.
1844 if (w->win_image != NULL) {
1845 w->saved_win_image = ps->backend_data->ops.new_image(
1846 ps->backend_data, BACKEND_IMAGE_FORMAT_PIXMAP,
1847 (ivec2){
1848 .width = (int)win_ctx.width_before,
1849 .height = (int)win_ctx.height_before,
1850 });
1851 region_t copy_region;
1852 pixman_region32_init_rect(&copy_region, 0, 0,
1853 (uint)win_ctx.width_before,
1854 (uint)win_ctx.height_before);
1855 ps->backend_data->ops.copy_area(
1856 ps->backend_data, (ivec2){}, w->saved_win_image,
1857 w->win_image, &copy_region);
1858 pixman_region32_fini(&copy_region);
1859 }
1860 } else {
1861 w->saved_win_image = w->win_image;
1862 w->win_image = NULL;
1863 }
1864 w->saved_win_image_scale = (vec2){
1865 .x = win_ctx.width / win_ctx.width_before,
1866 .y = win_ctx.height / win_ctx.height_before,
1867 };
1868 }
1869
1870 auto new_animation = script_instance_new(wopts.animations[trigger].script);
1871 if (w->running_animation_instance) {
1872 // Interrupt the old animation and start the new animation from where the
1873 // old has left off. Note we still need to advance the old animation for
1874 // the last interval.
1875 win_advance_animation(w, delta_t, &win_ctx);
1876 auto memory = w->running_animation_instance->memory;
1877 auto output_indices = w->running_animation.output_indices;
1878 if (output_indices[WIN_SCRIPT_SAVED_IMAGE_BLEND] >= 0) {
1879 memory[output_indices[WIN_SCRIPT_SAVED_IMAGE_BLEND]] =
1880 1 - memory[output_indices[WIN_SCRIPT_SAVED_IMAGE_BLEND]];
1881 }
1882 if (size_changed || position_changed) {
1883 // If the window has moved, we need to adjust scripts
1884 // outputs so that the window will stay in the same position and
1885 // size after applying the animation. This way the window's size
1886 // and position won't change discontinuously.
1887 struct {
1888 int output;
1889 double delta;
1890 } adjustments[] = {
1891 {WIN_SCRIPT_OFFSET_X, win_ctx.x_before - win_ctx.x},
1892 {WIN_SCRIPT_OFFSET_Y, win_ctx.y_before - win_ctx.y},
1893 {WIN_SCRIPT_SHADOW_OFFSET_X, win_ctx.x_before - win_ctx.x},
1894 {WIN_SCRIPT_SHADOW_OFFSET_Y, win_ctx.y_before - win_ctx.y},
1895 };
1896 for (size_t i = 0; i < ARR_SIZE(adjustments); i++) {
1897 if (output_indices[adjustments[i].output] >= 0) {
1898 memory[output_indices[adjustments[i].output]] +=
1899 adjustments[i].delta;
1900 }
1901 }
1902
1903 struct {
1904 int output;
1905 double factor;
1906 } factors[] = {
1907 {WIN_SCRIPT_SCALE_X, win_ctx.width_before / win_ctx.width},
1908 {WIN_SCRIPT_SCALE_Y, win_ctx.height_before / win_ctx.height},
1909 {WIN_SCRIPT_SHADOW_SCALE_X, win_ctx.width_before / win_ctx.width},
1910 {WIN_SCRIPT_SHADOW_SCALE_Y, win_ctx.height_before / win_ctx.height},
1911 };
1912 for (size_t i = 0; i < ARR_SIZE(factors); i++) {
1913 if (output_indices[factors[i].output] >= 0) {
1914 memory[output_indices[factors[i].output]] *=
1915 factors[i].factor;
1916 }
1917 }
1918 }
1919 script_instance_resume_from(w->running_animation_instance, new_animation);
1920 free(w->running_animation_instance);
1921 }
1922 w->running_animation_instance = new_animation;
1923 w->running_animation = wopts.animations[trigger];
1924 script_instance_evaluate(w->running_animation_instance, &win_ctx, true);
1925 return script_instance_is_finished(w->running_animation_instance);
1926 }
1927
1928 #undef WSTATE_PAIR
1929
1930 /// Find which monitor a window is on.
1931 int win_find_monitor(const struct x_monitors *monitors, const struct win *mw) {
1932 int ret = -1;
1933 for (int i = 0; i < monitors->count; i++) {
1934 auto e = pixman_region32_extents(&monitors->regions[i]);
1935 if (e->x1 <= mw->g.x && e->y1 <= mw->g.y &&
1936 e->x2 >= mw->g.x + mw->widthb && e->y2 >= mw->g.y + mw->heightb) {
1937 log_verbose("Window %#010x (%s), %dx%d+%dx%d, is entirely on the "
1938 "monitor %d (%dx%d+%dx%d)",
1939 win_id(mw), mw->name, mw->g.x, mw->g.y, mw->widthb,
1940 mw->heightb, i, e->x1, e->y1, e->x2 - e->x1,
1941 e->y2 - e->y1);
1942 return i;
1943 }
1944 }
1945 log_verbose("Window %#010x (%s), %dx%d+%dx%d, is not entirely on any monitor",
1946 win_id(mw), mw->name, mw->g.x, mw->g.y, mw->widthb, mw->heightb);
1947 return ret;
1948 }
1949
1950 bool win_set_pending_geometry(struct win *w, struct win_geometry g) {
1951 // We check against pending_g here, because there might have been multiple
1952 // configure notifies in this cycle, or the window could receive multiple updates
1953 // while it's unmapped. `pending_g` should be equal to `g` otherwise.
1954 bool position_changed = w->pending_g.x != g.x || w->pending_g.y != g.y;
1955 bool size_changed = w->pending_g.width != g.width || w->pending_g.height != g.height ||
1956 w->pending_g.border_width != g.border_width;
1957 if (position_changed || size_changed) {
1958 // Queue pending updates
1959 win_set_flags(w, WIN_FLAGS_FACTOR_CHANGED);
1960
1961 // At least one of the following if's is true
1962 if (position_changed) {
1963 log_trace("Window %#010x position changed, %dx%d -> %dx%d",
1964 win_id(w), w->g.x, w->g.y, g.x, g.y);
1965 w->pending_g.x = g.x;
1966 w->pending_g.y = g.y;
1967 win_set_flags(w, WIN_FLAGS_POSITION_STALE);
1968 }
1969
1970 if (size_changed) {
1971 log_trace("Window %#010x size changed, %dx%d -> %dx%d", win_id(w),
1972 w->g.width, w->g.height, g.width, g.height);
1973 w->pending_g.width = g.width;
1974 w->pending_g.height = g.height;
1975 w->pending_g.border_width = g.border_width;
1976 win_set_flags(w, WIN_FLAGS_SIZE_STALE);
1977 }
1978 }
1979 return position_changed || size_changed;
1980 }
1981
1982 struct win_get_geometry_request {
1983 struct x_async_request_base base;
1984 struct session *ps;
1985 xcb_window_t wid;
1986 };
1987
1988 static void win_handle_get_geometry_reply(struct x_connection *c,
1989 struct x_async_request_base *req_base,
1990 const xcb_raw_generic_event_t *reply_or_error) {
1991 auto req = (struct win_get_geometry_request *)req_base;
1992 auto wid = req->wid;
1993 auto ps = req->ps;
1994 free(req);
1995
1996 if (reply_or_error == NULL) {
1997 // Shutting down
1998 return;
1999 }
2000
2001 if (reply_or_error->response_type == 0) {
2002 log_debug("Failed to get geometry of window %#010x: %s", wid,
2003 x_strerror(c, (xcb_generic_error_t *)reply_or_error));
2004 return;
2005 }
2006
2007 auto cursor = wm_find(ps->wm, wid);
2008 if (cursor == NULL) {
2009 // Rare, window is destroyed then its ID is reused
2010 if (wm_is_consistent(ps->wm)) {
2011 log_error("Successfully fetched geometry of a non-existent "
2012 "window %#010x",
2013 wid);
2014 assert(false);
2015 }
2016 return;
2017 }
2018
2019 auto w = wm_ref_deref(cursor);
2020 if (w == NULL) {
2021 // Not yet managed. Rare, window is destroyed then its ID is reused
2022 return;
2023 }
2024
2025 auto r = (const xcb_get_geometry_reply_t *)reply_or_error;
2026 ps->pending_updates |= win_set_pending_geometry(w, win_geometry_from_get_geometry(r));
2027 }
2028
2029 /// Start the mapping of a window. We cannot map immediately since we might need to fade
2030 /// the window in.
2031 void win_map_start(struct session *ps, struct win *w) {
2032 assert(w);
2033
2034 // Don't care about window mapping if it's an InputOnly window
2035 // Also, try avoiding mapping a window twice
2036 if (w->a._class == XCB_WINDOW_CLASS_INPUT_ONLY) {
2037 return;
2038 }
2039
2040 log_debug("Mapping (%#010x \"%s\"), old state %d", win_id(w), w->name, w->state);
2041
2042 assert(w->state != WSTATE_DESTROYED);
2043 if (w->state == WSTATE_MAPPED) {
2044 log_error("Mapping an already mapped window");
2045 assert(false);
2046 return;
2047 }
2048
2049 // Rant: window size could change after we queried its geometry here and
2050 // before we get its pixmap. Later, when we get back to the event
2051 // processing loop, we will get the notification about size change from
2052 // Xserver and try to refresh the pixmap, while the pixmap is actually
2053 // already up-to-date (i.e. the notification is stale). There is basically
2054 // no real way to prevent this, aside from grabbing the server.
2055
2056 // XXX Can we assume map_state is always viewable?
2057 w->a.map_state = XCB_MAP_STATE_VIEWABLE;
2058
2059 // Update window mode here to check for ARGB windows
2060 w->mode = win_calc_mode(w);
2061
2062 w->state = WSTATE_MAPPED;
2063 win_set_flags(
2064 w, WIN_FLAGS_PIXMAP_STALE | WIN_FLAGS_CLIENT_STALE | WIN_FLAGS_FACTOR_CHANGED);
2065
2066 auto req = ccalloc(1, struct win_get_geometry_request);
2067 req->base = (struct x_async_request_base){
2068 .callback = win_handle_get_geometry_reply,
2069 .sequence = xcb_get_geometry(ps->c.c, win_id(w)).sequence,
2070 };
2071 req->wid = win_id(w);
2072 req->ps = ps;
2073 x_await_request(&ps->c, &req->base);
2074 }
2075
2076 /// Set flags on a window. Some sanity checks are performed
2077 void win_set_flags(struct win *w, uint64_t flags) {
2078 log_verbose("Set flags %" PRIu64 " to window %#010x (%s)", flags, win_id(w), w->name);
2079 if (unlikely(w->state == WSTATE_DESTROYED)) {
2080 log_error("Flags set on a destroyed window %#010x (%s)", win_id(w), w->name);
2081 return;
2082 }
2083
2084 w->flags |= flags;
2085 }
2086
2087 /// Clear flags on a window. Some sanity checks are performed
2088 void win_clear_flags(struct win *w, uint64_t flags) {
2089 log_verbose("Clear flags %" PRIu64 " from window %#010x (%s)", flags, win_id(w),
2090 w->name);
2091 if (unlikely(w->state == WSTATE_DESTROYED)) {
2092 log_warn("Flags %" PRIu64 " cleared on a destroyed window %#010x (%s)",
2093 flags, win_id(w), w->name);
2094 return;
2095 }
2096
2097 w->flags = w->flags & (~flags);
2098 }
2099
2100 void win_set_properties_stale(struct win *w, const xcb_atom_t *props, int nprops) {
2101 auto const bits_per_element = sizeof(*w->stale_props) * 8;
2102 size_t new_capacity = w->stale_props_capacity;
2103
2104 // Calculate the new capacity of the properties array
2105 for (int i = 0; i < nprops; i++) {
2106 if (props[i] >= new_capacity * bits_per_element) {
2107 new_capacity = props[i] / bits_per_element + 1;
2108 }
2109 }
2110
2111 // Reallocate if necessary
2112 if (new_capacity > w->stale_props_capacity) {
2113 w->stale_props =
2114 crealloc(w->stale_props, new_capacity * sizeof(*w->stale_props));
2115
2116 // Clear the content of the newly allocated bytes
2117 memset(w->stale_props + w->stale_props_capacity, 0,
2118 (new_capacity - w->stale_props_capacity) * sizeof(*w->stale_props));
2119 w->stale_props_capacity = new_capacity;
2120 }
2121
2122 // Set the property bits
2123 for (int i = 0; i < nprops; i++) {
2124 w->stale_props[props[i] / bits_per_element] |=
2125 1UL << (props[i] % bits_per_element);
2126 }
2127 win_set_flags(w, WIN_FLAGS_PROPERTY_STALE);
2128 }
2129
2130 static void win_clear_all_properties_stale(struct win *w) {
2131 memset(w->stale_props, 0, w->stale_props_capacity * sizeof(*w->stale_props));
2132 win_clear_flags(w, WIN_FLAGS_PROPERTY_STALE);
2133 }
2134
2135 static bool win_fetch_and_unset_property_stale(struct win *w, xcb_atom_t prop) {
2136 auto const bits_per_element = sizeof(*w->stale_props) * 8;
2137 if (prop >= w->stale_props_capacity * bits_per_element) {
2138 return false;
2139 }
2140
2141 auto const mask = 1UL << (prop % bits_per_element);
2142 bool ret = w->stale_props[prop / bits_per_element] & mask;
2143 w->stale_props[prop / bits_per_element] &= ~mask;
2144 return ret;
2145 }
2146
2147 bool win_check_flags_any(struct win *w, uint64_t flags) {
2148 return (w->flags & flags) != 0;
2149 }
2150
2151 bool win_check_flags_all(struct win *w, uint64_t flags) {
2152 return (w->flags & flags) == flags;
2153 }
2154
2155 /**
2156 * Check if a window is a fullscreen window.
2157 *
2158 * It's not using w->border_size for performance measures.
2159 */
2160 void win_update_is_fullscreen(const session_t *ps, struct win *w) {
2161 if (!ps->o.no_ewmh_fullscreen && w->is_ewmh_fullscreen) {
2162 w->is_fullscreen = true;
2163 return;
2164 }
2165 w->is_fullscreen = w->g.x <= 0 && w->g.y <= 0 &&
2166 (w->g.x + w->widthb) >= ps->root_width &&
2167 (w->g.y + w->heightb) >= ps->root_height &&
2168 (!w->bounding_shaped || w->rounded_corners);
2169 }
2170
2171 /**
2172 * Check if a window has BYPASS_COMPOSITOR property set
2173 *
2174 * TODO(yshui) cache this property
2175 */
2176 bool win_is_bypassing_compositor(const session_t *ps, const struct win *w) {
2177 bool ret = false;
2178 auto wid = win_client_id(w, /*fallback_to_self=*/true);
2179
2180 auto prop = x_get_prop(&ps->c, wid, ps->atoms->a_NET_WM_BYPASS_COMPOSITOR, 1L,
2181 XCB_ATOM_CARDINAL, 32);
2182
2183 if (prop.nitems && *prop.c32 == 1) {
2184 ret = true;
2185 }
2186
2187 free_winprop(&prop);
2188 return ret;
2189 }