Debian Codegraph @

src/picom.c

raw symbols SCIP
1 // SPDX-License-Identifier: MIT
2 /*
3 * picom - a compositor for X11
4 *
5 * Based on `compton` - Copyright (c) 2011-2013, Christopher Jeffrey
6 * Based on `xcompmgr` - Copyright (c) 2003, Keith Packard
7 *
8 * Copyright (c) 2019-2023, Yuxuan Shui
9 *
10 * See LICENSE-mit for more information.
11 *
12 */
13
14 #include <X11/Xlib-xcb.h>
15 #include <X11/Xlib.h>
16 #include <X11/Xutil.h>
17 #include <ev.h>
18 #include <fcntl.h>
19 #include <inttypes.h>
20 #include <libgen.h>
21 #include <math.h>
22 #include <sched.h>
23 #include <stddef.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <sys/resource.h>
27 #include <time.h>
28 #include <unistd.h>
29 #include <xcb/composite.h>
30 #include <xcb/damage.h>
31 #include <xcb/glx.h>
32 #include <xcb/present.h>
33 #include <xcb/randr.h>
34 #include <xcb/render.h>
35 #include <xcb/sync.h>
36 #include <xcb/xcb_aux.h>
37 #include <xcb/xfixes.h>
38
39 #include <picom/backend.h>
40 #include <picom/types.h>
41 #include <test.h>
42
43 #include "api_internal.h"
44 #include "atom.h"
45 #include "backend/backend.h"
46 #include "c2.h"
47 #include "common.h"
48 #include "compiler.h"
49 #include "config.h"
50 #include "dbus.h"
51 #include "diagnostic.h"
52 #include "event.h"
53 #include "inspect.h"
54 #include "log.h"
55 #include "options.h"
56 #include "picom.h"
57 #include "region.h"
58 #include "renderer/command_builder.h"
59 #include "renderer/layout.h"
60 #include "renderer/renderer.h"
61 #include "utils/file_watch.h"
62 #include "utils/list.h"
63 #include "utils/misc.h"
64 #include "utils/process.h"
65 #include "utils/statistics.h"
66 #include "utils/str.h"
67 #include "utils/ui.h"
68 #include "utils/uthash_extra.h"
69 #include "vblank.h"
70 #include "wm/defs.h"
71 #include "wm/wm.h"
72 #include "x.h"
73
74 /// Get session_t pointer from a pointer to a member of session_t
75 #define session_ptr(ptr, member) \
76 ({ \
77 const __typeof__(((session_t *)0)->member) *__mptr = (ptr); \
78 (session_t *)((char *)__mptr - offsetof(session_t, member)); \
79 })
80
81 static bool must_use redirect_start(session_t *ps);
82
83 static void unredirect(session_t *ps);
84
85 // === Global constants ===
86
87 /// Name strings for window types.
88 const struct wintype_info WINTYPES[] = {
89 [WINTYPE_UNKNOWN] = {"unknown", NULL},
90 #define X(name, type) [WINTYPE_##type] = {#name, "_NET_WM_WINDOW_TYPE_" #type}
91 X(desktop, DESKTOP),
92 X(dock, DOCK),
93 X(toolbar, TOOLBAR),
94 X(menu, MENU),
95 X(utility, UTILITY),
96 X(splash, SPLASH),
97 X(dialog, DIALOG),
98 X(normal, NORMAL),
99 X(dropdown_menu, DROPDOWN_MENU),
100 X(popup_menu, POPUP_MENU),
101 X(tooltip, TOOLTIP),
102 X(notification, NOTIFICATION),
103 X(combo, COMBO),
104 X(dnd, DND),
105 #undef X
106 };
107
108 // === Global variables ===
109
110 /// Pointer to current session, as a global variable. Only used by
111 /// xerror(), which could not have a pointer to current session passed in.
112 /// XXX Limit what xerror can access by not having this pointer
113 session_t *ps_g = NULL;
114
115 void quit(session_t *ps) {
116 ps->quit = true;
117 ev_break(ps->loop, EVBREAK_ALL);
118 }
119
120 /**
121 * Convert struct timespec to milliseconds.
122 */
123 static inline int64_t timespec_ms(struct timespec ts) {
124 return (int64_t)ts.tv_sec * 1000 + (int64_t)ts.tv_nsec / 1000000;
125 }
126
127 enum vblank_callback_action check_render_finish(struct vblank_event *e attr_unused, void *ud) {
128 auto ps = (session_t *)ud;
129 if (!ps->backend_busy) {
130 return VBLANK_CALLBACK_DONE;
131 }
132
133 struct timespec render_time;
134 bool completed =
135 ps->backend_data->ops.last_render_time(ps->backend_data, &render_time);
136 if (!completed) {
137 // Render hasn't completed yet, we can't start another render.
138 // Check again at the next vblank.
139 log_debug("Last render did not complete during vblank, msc: "
140 "%" PRIu64,
141 ps->last_msc);
142 return VBLANK_CALLBACK_AGAIN;
143 }
144
145 // The frame has been finished and presented, record its render time.
146 if (global_debug_options.smart_frame_pacing) {
147 int render_time_us =
148 (int)(render_time.tv_sec * 1000000L + render_time.tv_nsec / 1000L);
149 render_statistics_add_render_time_sample(
150 &ps->render_stats, render_time_us + (int)ps->last_schedule_delay);
151 log_verbose("Last render call took: %d (gpu) + %d (cpu) us, "
152 "last_msc: %" PRIu64,
153 render_time_us, (int)ps->last_schedule_delay, ps->last_msc);
154 }
155 ps->backend_busy = false;
156 return VBLANK_CALLBACK_DONE;
157 }
158
159 enum vblank_callback_action
160 collect_vblank_interval_statistics(struct vblank_event *e, void *ud) {
161 auto ps = (session_t *)ud;
162 double vblank_interval = NAN;
163 assert(ps->frame_pacing);
164 assert(ps->vblank_scheduler);
165
166 if (!global_debug_options.smart_frame_pacing) {
167 // We don't need to collect statistics if we are not doing smart frame
168 // pacing.
169 return VBLANK_CALLBACK_DONE;
170 }
171
172 // TODO(yshui): this naive method of estimating vblank interval does not handle
173 // the variable refresh rate case very well. This includes the case
174 // of a VRR enabled monitor; or a monitor that's turned off, in which
175 // case the vblank events might slow down or stop all together.
176 // I tried using DPMS to detect monitor power state, and stop adding
177 // samples when the monitor is off, but I had a hard time to get it
178 // working reliably, there are just too many corner cases.
179
180 // Don't add sample again if we already collected statistics for this vblank
181 if (ps->last_msc < e->msc) {
182 if (ps->last_msc_instant != 0) {
183 auto frame_count = e->msc - ps->last_msc;
184 auto frame_time =
185 (int)((e->ust - ps->last_msc_instant) / frame_count);
186 if (frame_count == 1) {
187 render_statistics_add_vblank_time_sample(
188 &ps->render_stats, frame_time);
189 log_trace("Frame count %" PRIu64 ", frame time: %d us, "
190 "ust: "
191 "%" PRIu64,
192 frame_count, frame_time, e->ust);
193 } else {
194 log_trace("Frame count %" PRIu64 ", frame time: %d us, "
195 "msc: "
196 "%" PRIu64 ", not adding sample.",
197 frame_count, frame_time, e->ust);
198 }
199 }
200 ps->last_msc_instant = e->ust;
201 ps->last_msc = e->msc;
202 } else if (ps->last_msc > e->msc) {
203 log_warn("PresentCompleteNotify msc is going backwards, last_msc: "
204 "%" PRIu64 ", current msc: %" PRIu64,
205 ps->last_msc, e->msc);
206 ps->last_msc_instant = 0;
207 ps->last_msc = 0;
208 }
209
210 vblank_interval = render_statistics_get_vblank_time(&ps->render_stats);
211 log_trace("Vblank interval estimate: %f us", vblank_interval);
212 if (vblank_interval == 0) {
213 // We don't have enough data for vblank interval estimate, schedule
214 // another vblank event.
215 return VBLANK_CALLBACK_AGAIN;
216 }
217 return VBLANK_CALLBACK_DONE;
218 }
219
220 void schedule_render(session_t *ps, bool triggered_by_vblank);
221
222 /// vblank callback scheduled by schedule_render, when a render is ongoing.
223 ///
224 /// Check if previously queued render has finished, and reschedule render if it has.
225 enum vblank_callback_action reschedule_render_at_vblank(struct vblank_event *e, void *ud) {
226 auto ps = (session_t *)ud;
227 assert(ps->frame_pacing);
228 assert(ps->render_queued);
229 assert(ps->vblank_scheduler);
230
231 log_verbose("Rescheduling render at vblank, msc: %" PRIu64, e->msc);
232
233 collect_vblank_interval_statistics(e, ud);
234 check_render_finish(e, ud);
235
236 if (ps->backend_busy) {
237 return VBLANK_CALLBACK_AGAIN;
238 }
239
240 schedule_render(ps, false);
241 return VBLANK_CALLBACK_DONE;
242 }
243
244 /// How many seconds into the future should we start rendering the next frame.
245 ///
246 /// Renders are scheduled like this:
247 ///
248 /// 1. queue_redraw() queues a new render by calling schedule_render, if there
249 /// is no render currently scheduled. i.e. render_queued == false.
250 /// 2. then, we need to figure out the best time to start rendering. we need to
251 /// at least know when the next vblank will start, as we can't start render
252 /// before the current rendered frame is displayed on screen. we have this
253 /// information from the vblank scheduler, it will notify us when that happens.
254 /// we might also want to delay the rendering even further to reduce latency,
255 /// this is discussed below, in FUTURE WORKS.
256 /// 3. we schedule a render for that target point in time.
257 /// 4. draw_callback() is called at the schedule time (i.e. when scheduled
258 /// vblank event is delivered). Backend APIs are called to issue render
259 /// commands. render_queued is set to false, and backend_busy is set to true.
260 ///
261 /// There are some considerations in step 2:
262 ///
263 /// First of all, a vblank event being delivered
264 /// doesn't necessarily mean the frame has been displayed on screen. If a frame
265 /// takes too long to render, it might miss the current vblank, and will be
266 /// displayed on screen during one of the subsequent vblanks. So in
267 /// schedule_render_at_vblank, we ask the backend to see if it has finished
268 /// rendering. if not, render_queued is unchanged, and another vblank is
269 /// scheduled; otherwise, draw_callback_impl will be scheduled to be call at
270 /// an appropriate time. Second, we might not have rendered for the previous vblank,
271 /// in which case the last vblank event we received could be many frames in the past,
272 /// so we can't make scheduling decisions based on that. So we always schedule
273 /// a vblank event when render is queued, and make scheduling decisions when the
274 /// event is delivered.
275 ///
276 /// All of the above is what happens when frame_pacing is true. Otherwise
277 /// render_in_progress is either QUEUED or IDLE, and queue_redraw will always
278 /// schedule a render to be started immediately. PresentCompleteNotify will not
279 /// be received, and handle_end_of_vblank will not be called.
280 ///
281 /// The `triggered_by_timer` parameter is used to indicate whether this function
282 /// is triggered by a steady timer, i.e. we are rendering for each vblank. The
283 /// other case is when we stop rendering for a while because there is no changes
284 /// on screen, then something changed and schedule_render is triggered by a
285 /// DamageNotify. The idea is that when the schedule is triggered by a steady
286 /// timer, schedule_render will be called at a predictable offset into each
287 /// vblank.
288 ///
289 /// # FUTURE WORKS
290 ///
291 /// As discussed in step 2 above, we might want to delay the rendering even
292 /// further. If we know the time it takes to render a frame, and the interval
293 /// between vblanks, we can try to schedule the render to start at a point in
294 /// time that's closer to the next vblank. We should be able to get this
295 /// information by doing statistics on the render time of previous frames, which
296 /// is available from the backends; and the interval between vblank events,
297 /// which is available from the vblank scheduler.
298 ///
299 /// The code that does this is already implemented below, but disabled by
300 /// default. There are several problems with it, see bug #1072.
301 void schedule_render(session_t *ps, bool triggered_by_vblank attr_unused) {
302 // If the backend is busy, we will try again at the next vblank.
303 if (ps->backend_busy) {
304 // We should never have set backend_busy to true unless frame_pacing is
305 // enabled.
306 assert(ps->vblank_scheduler);
307 assert(ps->frame_pacing);
308 log_verbose("Backend busy, will reschedule render at next vblank.");
309 if (!vblank_scheduler_schedule(ps->vblank_scheduler,
310 reschedule_render_at_vblank, ps)) {
311 // TODO(yshui): handle error here
312 abort();
313 }
314 return;
315 }
316
317 // By default, we want to schedule render immediately, later in this function we
318 // might adjust that and move the render later, based on render timing statistics.
319 double delay_s = 0;
320 unsigned int divisor = 0;
321 struct timespec now;
322 clock_gettime(CLOCK_MONOTONIC, &now);
323 auto now_us = (uint64_t)now.tv_sec * 1000000 + (uint64_t)now.tv_nsec / 1000;
324
325 ps->next_render = now_us;
326
327 if (!ps->frame_pacing || !ps->redirected) {
328 // If not doing frame pacing, schedule a render immediately; if
329 // not redirected, we schedule immediately to have a chance to
330 // redirect. We won't have frame or render timing information
331 // anyway.
332 assert(!ev_is_active(&ps->draw_timer));
333 goto schedule;
334 }
335
336 // if global_debug_options.smart_frame_pacing is false, we won't have any render
337 // time or vblank interval estimates, so we would naturally fallback to schedule
338 // render immediately.
339 auto render_budget = render_statistics_get_budget(&ps->render_stats);
340 auto frame_time = render_statistics_get_vblank_time(&ps->render_stats);
341 if (frame_time == 0) {
342 // We don't have enough data for render time estimates, maybe there's
343 // no frame rendered yet, or the backend doesn't support render timing
344 // information, schedule render immediately.
345 log_verbose("Not enough data for render time estimates.");
346 goto schedule;
347 }
348
349 if (render_budget >= frame_time) {
350 // If the estimated render time is already longer than the estimated
351 // vblank interval, there is no way we can make it. Instead of always
352 // dropping frames, we try desperately to catch up and schedule a
353 // render immediately.
354 log_verbose("Render budget: %u us >= frame time: %" PRIu32 " us",
355 render_budget, frame_time);
356 goto schedule;
357 }
358
359 auto target_frame = (now_us + render_budget - ps->last_msc_instant) / frame_time + 1;
360 auto const deadline = ps->last_msc_instant + target_frame * frame_time;
361 unsigned int available = 0;
362 if (deadline > now_us) {
363 available = (unsigned int)(deadline - now_us);
364 }
365
366 if (available > render_budget) {
367 delay_s = (double)(available - render_budget) / 1000000.0;
368 ps->next_render = deadline - render_budget;
369 }
370
371 if (delay_s > 1) {
372 log_warn("Delay too long: %f s, render_budget: %d us, frame_time: "
373 "%" PRIu32 " us, now_us: %" PRIu64 " us, next_msc: %" PRIu64 " u"
374 "s",
375 delay_s, render_budget, frame_time, now_us, deadline);
376 }
377
378 log_verbose("Delay: %.6lf s, last_msc: %" PRIu64 ", render_budget: %d, "
379 "frame_time: %" PRIu32 ", now_us: %" PRIu64 ", next_render: %" PRIu64
380 ", next_msc: %" PRIu64 ", divisor: "
381 "%d",
382 delay_s, ps->last_msc_instant, render_budget, frame_time, now_us,
383 ps->next_render, deadline, divisor);
384
385 schedule:
386 // If the backend is not busy, we just need to schedule the render at the
387 // specified time; otherwise we need to wait for the next vblank event and
388 // reschedule.
389 ps->last_schedule_delay = 0;
390 assert(!ev_is_active(&ps->draw_timer));
391 ev_timer_set(&ps->draw_timer, delay_s, 0);
392 ev_timer_start(ps->loop, &ps->draw_timer);
393 }
394
395 void queue_redraw(session_t *ps) {
396 log_verbose("Queue redraw, render_queued: %d, backend_busy: %d",
397 ps->render_queued, ps->backend_busy);
398
399 if (ps->render_queued) {
400 return;
401 }
402 ps->render_queued = true;
403 schedule_render(ps, false);
404 }
405
406 /**
407 * Get a region of the screen size.
408 */
409 static inline void get_screen_region(session_t *ps, region_t *res) {
410 pixman_box32_t b = {.x1 = 0, .y1 = 0, .x2 = ps->root_width, .y2 = ps->root_height};
411 pixman_region32_fini(res);
412 pixman_region32_init_rects(res, &b, 1);
413 }
414
415 // === Windows ===
416
417 /**
418 * Rebuild cached <code>screen_reg</code>.
419 */
420 static void rebuild_screen_reg(session_t *ps) {
421 get_screen_region(ps, &ps->screen_reg);
422 }
423
424 /// Free up all the images and deinit the backend
425 static void destroy_backend(session_t *ps) {
426 wm_stack_foreach_safe(ps->wm, cursor, next_cursor) {
427 auto w = wm_ref_deref(cursor);
428 if (w == NULL) {
429 continue;
430 }
431 // An unmapped window shouldn't have a pixmap, unless it has animation
432 // running. (`w->previous.state != w->state` means there might be
433 // animation but we haven't had a chance to start it because
434 // `win_process_animation_and_state_change` hasn't been called.)
435 // TBH, this assertion is probably too complex than what it's worth.
436 assert(!w->win_image || w->state == WSTATE_MAPPED ||
437 w->running_animation_instance != NULL || w->previous.state != w->state);
438 // Wrapping up animation in progress
439 free(w->running_animation_instance);
440 w->running_animation_instance = NULL;
441
442 if (ps->backend_data) {
443 // Unmapped windows could still have shadow images.
444 // In some cases, the window might have PIXMAP_STALE flag set:
445 // 1. If the window is unmapped. Their stale flags won't be
446 // handled until they are mapped.
447 // 2. If we haven't had chance to handle the stale flags. This
448 // could happen if we received a root ConfigureNotify
449 // _immediately_ after we redirected.
450 win_clear_flags(w, WIN_FLAGS_PIXMAP_STALE);
451 win_release_images(ps->backend_data, w);
452 }
453
454 if (w->state == WSTATE_DESTROYED) {
455 win_destroy_finish(ps, w);
456 }
457 }
458
459 HASH_ITER2(ps->shaders, shader) {
460 if (shader->backend_shader != NULL) {
461 ps->backend_data->ops.destroy_shader(ps->backend_data,
462 shader->backend_shader);
463 shader->backend_shader = NULL;
464 }
465 }
466
467 if (ps->backend_data && ps->root_image) {
468 ps->backend_data->ops.release_image(ps->backend_data, ps->root_image);
469 ps->root_image = NULL;
470 }
471
472 if (ps->backend_data) {
473 if (ps->renderer) {
474 renderer_free(ps->backend_data, ps->renderer);
475 ps->renderer = NULL;
476 }
477 // deinit backend
478 if (ps->backend_blur_context) {
479 ps->backend_data->ops.destroy_blur_context(
480 ps->backend_data, ps->backend_blur_context);
481 ps->backend_blur_context = NULL;
482 }
483 ps->backend_data->ops.deinit(ps->backend_data);
484 ps->backend_data = NULL;
485 }
486 }
487
488 static bool initialize_blur(session_t *ps) {
489 struct kernel_blur_args kargs;
490 struct gaussian_blur_args gargs;
491 struct box_blur_args bargs;
492 struct dual_kawase_blur_args dkargs;
493
494 void *args = NULL;
495 switch (ps->o.blur_method) {
496 case BLUR_METHOD_BOX:
497 bargs.size = ps->o.blur_radius;
498 args = (void *)&bargs;
499 break;
500 case BLUR_METHOD_KERNEL:
501 kargs.kernel_count = ps->o.blur_kernel_count;
502 kargs.kernels = ps->o.blur_kerns;
503 args = (void *)&kargs;
504 break;
505 case BLUR_METHOD_GAUSSIAN:
506 gargs.size = ps->o.blur_radius;
507 gargs.deviation = ps->o.blur_deviation;
508 args = (void *)&gargs;
509 break;
510 case BLUR_METHOD_DUAL_KAWASE:
511 dkargs.size = ps->o.blur_radius;
512 dkargs.strength = ps->o.blur_strength;
513 args = (void *)&dkargs;
514 break;
515 default: return true;
516 }
517
518 enum backend_image_format format = ps->o.dithered_present
519 ? BACKEND_IMAGE_FORMAT_PIXMAP_HIGH
520 : BACKEND_IMAGE_FORMAT_PIXMAP;
521 ps->backend_blur_context = ps->backend_data->ops.create_blur_context(
522 ps->backend_data, ps->o.blur_method, format, args);
523 return ps->backend_blur_context != NULL;
524 }
525
526 /// Init the backend and bind all the window pixmap to backend images
527 static bool initialize_backend(session_t *ps) {
528 assert(!ps->backend_data);
529 // Reinitialize win_data
530 ps->backend_data = backend_init(ps->o.backend, ps, session_get_target_window(ps));
531 api_backend_plugins_invoke(backend_name(ps->o.backend), ps->backend_data);
532 if (!ps->backend_data) {
533 log_fatal("Failed to initialize backend, aborting...");
534 quit(ps);
535 return false;
536 }
537
538 if (!initialize_blur(ps)) {
539 log_fatal("Failed to prepare for background blur, aborting...");
540 goto err;
541 }
542
543 // Create shaders
544 if (!ps->backend_data->ops.create_shader && ps->shaders) {
545 log_warn("Shaders are not supported by selected backend %s, "
546 "they will be ignored",
547 backend_name(ps->o.backend));
548 } else {
549 HASH_ITER2(ps->shaders, shader) {
550 assert(shader->backend_shader == NULL);
551 shader->backend_shader = ps->backend_data->ops.create_shader(
552 ps->backend_data, shader->spec, shader->source);
553 if (shader->backend_shader == NULL) {
554 log_warn("Failed to create shader for shader "
555 "file %s, this shader will not be used",
556 shader_spec_get_path(shader->spec));
557 } else {
558 shader->attributes = 0;
559 if (ps->backend_data->ops.get_shader_attributes) {
560 shader->attributes =
561 ps->backend_data->ops.get_shader_attributes(
562 ps->backend_data, shader->backend_shader);
563 }
564 log_debug("Shader %s has attributes %" PRIu64,
565 shader_spec_get_path(shader->spec),
566 shader->attributes);
567 }
568 }
569 }
570
571 wm_stack_foreach(ps->wm, cursor) {
572 auto w = wm_ref_deref(cursor);
573 if (w != NULL) {
574 assert(w->state != WSTATE_DESTROYED);
575 // We need to reacquire image
576 log_debug("Marking window %#010x (%s) for update after "
577 "redirection",
578 win_id(w), w->name);
579 win_set_flags(w, WIN_FLAGS_PIXMAP_STALE);
580 ps->pending_updates = true;
581 }
582 }
583 ps->renderer =
584 renderer_new(ps->backend_data, ps->o.shadow_radius, ps->o.dithered_present);
585 if (!ps->renderer) {
586 log_fatal("Failed to create renderer, aborting...");
587 goto err;
588 }
589
590 return true;
591 err:
592 ps->backend_data->ops.deinit(ps->backend_data);
593 ps->backend_data = NULL;
594 quit(ps);
595 return false;
596 }
597
598 /// Handle configure event of the root window
599 void configure_root(session_t *ps) {
600 // TODO(yshui) re-initializing backend should be done outside of the
601 // critical section. Probably set a flag and do it in draw_callback_impl.
602 auto r = XCB_AWAIT(xcb_get_geometry, &ps->c, ps->c.screen_info->root);
603 if (!r) {
604 log_fatal("Failed to fetch root geometry");
605 abort();
606 }
607
608 log_info("Root configuration changed, new geometry: %dx%d", r->width, r->height);
609 if (ps->redirected) {
610 // On root window changes
611 BUG_ON_NULL(ps->backend_data);
612 if (ps->backend_data->ops.root_change == NULL) {
613 // deinit/reinit backend and free up resources if the backend
614 // cannot handle root change
615 destroy_backend(ps);
616 }
617 }
618
619 ps->root_width = r->width;
620 ps->root_height = r->height;
621 free(r);
622
623 rebuild_screen_reg(ps);
624
625 // Whether a window is fullscreen depends on the new screen
626 // size. So we need to refresh the fullscreen state of all
627 // windows.
628 wm_stack_foreach(ps->wm, cursor) {
629 auto w = wm_ref_deref(cursor);
630 if (w != NULL) {
631 win_update_is_fullscreen(ps, w);
632 }
633 }
634
635 if (!ps->redirected) {
636 return;
637 }
638
639 if (ps->backend_data != NULL) {
640 ps->backend_data->ops.root_change(ps->backend_data, ps);
641 } else {
642 if (!initialize_backend(ps)) {
643 log_fatal("Failed to re-initialize backend after root "
644 "change, aborting...");
645 ps->quit = true;
646 /* TODO(yshui) only event handlers should request
647 * ev_break, otherwise it's too hard to keep track of what
648 * can break the event loop */
649 ev_break(ps->loop, EVBREAK_ALL);
650 return;
651 }
652
653 // Re-acquire the root pixmap.
654 root_damaged(ps);
655 }
656 force_repaint(ps);
657 }
658
659 /**
660 * Go through the window stack and calculate some parameters for rendering.
661 *
662 * @return whether the operation succeeded
663 */
664 static bool paint_preprocess(session_t *ps, bool *animation, struct win **out_bottom) {
665 // XXX need better, more general name for `fade_running`. It really
666 // means if fade is still ongoing after the current frame is rendered
667 struct win *bottom = NULL;
668 *animation = false;
669 *out_bottom = NULL;
670
671 // First, let's process fading, and animated shaders
672 // TODO(yshui) check if a window is fully obscured, and if we don't need to
673 // process fading or animation for it.
674 wm_stack_foreach_safe(ps->wm, cursor, tmp) {
675 auto w = wm_ref_deref(cursor);
676 if (w == NULL) {
677 continue;
678 }
679
680 if (w->running_animation_instance != NULL) {
681 *animation = true;
682 }
683
684 if (win_has_frame(w)) {
685 w->frame_opacity = ps->o.frame_opacity;
686 } else {
687 w->frame_opacity = 1.0;
688 }
689
690 // Update window mode
691 w->mode = win_calc_mode(w);
692 }
693
694 // Opacity will not change, from this point onwards.
695
696 bool unredir_possible = false;
697 // Track whether it's the highest window to paint
698 bool is_highest = true;
699 if (ps->root_pixmap_shader != NULL &&
700 ps->root_pixmap_shader->attributes & SHADER_ATTRIBUTE_ANIMATED) {
701 *animation = true;
702 }
703 wm_stack_foreach_safe(ps->wm, cursor, next_cursor) {
704 __label__ skip_window;
705 auto w = wm_ref_deref(cursor);
706 if (w == NULL) {
707 continue;
708 }
709
710 bool to_paint = true;
711 // w->to_paint remembers whether this window is painted last time
712 const double window_opacity = win_animatable_get(w, WIN_SCRIPT_OPACITY);
713 const double blur_opacity = win_animatable_get(w, WIN_SCRIPT_BLUR_OPACITY);
714 auto window_options = win_options(w);
715 struct shader_info *fg_shader = NULL;
716 if (window_options.shader != NULL) {
717 HASH_FIND(hh, ps->shaders, window_options.shader->data,
718 window_options.shader->size, fg_shader);
719 }
720 if (fg_shader != NULL && fg_shader->attributes & SHADER_ATTRIBUTE_ANIMATED) {
721 *animation = true;
722 }
723
724 // log_trace("%d %d %s", w->a.map_state, w->ever_damaged, w->name);
725 log_trace("Checking whether window %#010x (%s) should be painted",
726 win_id(w), w->name);
727
728 // Give up if it's not damaged or invisible, or it's unmapped and its
729 // pixmap is gone (for example due to a ConfigureNotify), or when it's
730 // excluded
731 if ((w->state == WSTATE_UNMAPPED || w->state == WSTATE_DESTROYED) &&
732 w->running_animation_instance == NULL) {
733 log_trace("|- is unmapped");
734 to_paint = false;
735 } else if (unlikely(ps->debug_window != XCB_NONE) &&
736 (win_id(w) == ps->debug_window ||
737 win_client_id(w, /*fallback_to_self=*/false) == ps->debug_window)) {
738 log_trace("|- is the debug window");
739 to_paint = false;
740 } else if (!w->ever_damaged) {
741 log_trace("|- has not received any damages");
742 to_paint = false;
743 } else if (unlikely(w->g.x + w->g.width < 1 || w->g.y + w->g.height < 1 ||
744 w->g.x >= ps->root_width || w->g.y >= ps->root_height)) {
745 log_trace("|- is positioned outside of the screen");
746 to_paint = false;
747 } else if (unlikely(window_opacity * MAX_ALPHA < 1 &&
748 (!window_options.blur_background ||
749 blur_opacity * MAX_ALPHA < 1))) {
750 // For consistency, even a window has 0 opacity, we would still
751 // blur its background. (unless it's background is not blurred, or
752 // the blur opacity is 0)
753 log_trace("|- has 0 opacity");
754 to_paint = false;
755 } else if (!window_options.paint) {
756 log_trace("|- is excluded from painting");
757 to_paint = false;
758 } else if (unlikely((w->flags & WIN_FLAGS_PIXMAP_ERROR) != 0)) {
759 log_trace("|- has image errors");
760 to_paint = false;
761 }
762 // log_trace("%s %d %d %d", w->name, to_paint, w->opacity,
763 // w->paint_excluded);
764
765 // to_paint will never change after this point
766 if (!to_paint) {
767 log_trace("|- will not be painted");
768 goto skip_window;
769 }
770
771 log_trace("|- will be painted");
772 log_verbose("Window %#010x (%s) will be painted", win_id(w), w->name);
773
774 // (Un)redirect screen
775 // We could definitely unredirect the screen when there's no window to
776 // paint, but this is typically unnecessary, may cause flickering when
777 // fading is enabled, and could create inconsistency when the wallpaper
778 // is not correctly set.
779 if (ps->o.unredir_if_possible && is_highest && w->mode == WMODE_SOLID &&
780 !ps->o.force_win_blend && w->is_fullscreen &&
781 (window_options.unredir == WINDOW_UNREDIR_WHEN_POSSIBLE ||
782 window_options.unredir == WINDOW_UNREDIR_WHEN_POSSIBLE_ELSE_TERMINATE)) {
783 unredir_possible = true;
784 }
785
786 // Unredirect screen if some window is forcing unredir, even when they are
787 // not on the top.
788 if (ps->o.unredir_if_possible &&
789 window_options.unredir == WINDOW_UNREDIR_FORCED) {
790 unredir_possible = true;
791 }
792
793 bottom = w;
794
795 // If the screen is not redirected check if the window's unredir setting
796 // allows unredirection to be terminated.
797 if (ps->redirected || window_options.unredir == WINDOW_UNREDIR_TERMINATE ||
798 window_options.unredir == WINDOW_UNREDIR_WHEN_POSSIBLE_ELSE_TERMINATE) {
799 // Setting is_highest to false will stop all windows stacked below
800 // from triggering unredirection. But if `unredir_possible` is
801 // already set, this will not prevent unredirection.
802 is_highest = false;
803 }
804
805 skip_window:
806 if (w->state == WSTATE_DESTROYED && w->running_animation_instance == NULL) {
807 // the window should be destroyed because it was destroyed
808 // by X server and now its animations are finished
809 win_destroy_finish(ps, w);
810 w = NULL;
811 }
812
813 // Avoid setting w->to_paint if w is freed
814 if (w) {
815 w->to_paint = to_paint;
816 }
817 }
818
819 // If possible, unredirect all windows and stop painting
820 if (ps->o.redirected_force != UNSET) {
821 unredir_possible = !ps->o.redirected_force;
822 } else if (ps->o.unredir_if_possible && is_highest && !ps->redirected) {
823 // `is_highest` being true means there's no window with a unredir setting
824 // that allows unredirection to be terminated. So if screen is not
825 // redirected, keep it that way.
826 //
827 // (might not be the best naming.)
828 unredir_possible = true;
829 }
830 if (unredir_possible) {
831 if (ps->redirected) {
832 if (!ps->o.unredir_if_possible_delay || ps->tmout_unredir_hit) {
833 unredirect(ps);
834 } else if (!ev_is_active(&ps->unredir_timer)) {
835 ev_timer_set(
836 &ps->unredir_timer,
837 (double)ps->o.unredir_if_possible_delay / 1000.0, 0);
838 ev_timer_start(ps->loop, &ps->unredir_timer);
839 }
840 }
841 } else {
842 ev_timer_stop(ps->loop, &ps->unredir_timer);
843 if (!ps->redirected) {
844 if (!redirect_start(ps)) {
845 return false;
846 }
847 }
848 }
849
850 *out_bottom = bottom;
851 return true;
852 }
853
854 void root_damaged(session_t *ps) {
855 if (!ps->redirected) {
856 return;
857 }
858
859 if (ps->backend_data) {
860 if (ps->root_image) {
861 ps->backend_data->ops.release_image(ps->backend_data, ps->root_image);
862 ps->root_image = NULL;
863 }
864 auto pixmap = x_get_root_back_pixmap(&ps->c, ps->atoms);
865 if (pixmap != XCB_NONE) {
866 xcb_get_geometry_reply_t *r = xcb_get_geometry_reply(
867 ps->c.c, xcb_get_geometry(ps->c.c, pixmap), NULL);
868 if (!r) {
869 goto err;
870 }
871
872 // We used to assume that pixmaps pointed by the root background
873 // pixmap atoms are owned by the root window and have the same
874 // depth and hence the same visual that we can use to bind them.
875 // However, some applications break this assumption, e.g. the
876 // Xfce's desktop manager xfdesktop that sets the _XROOTPMAP_ID
877 // atom to a pixmap owned by it that seems to always have 32 bpp
878 // depth when the common root window's depth is 24 bpp. So use the
879 // root window's visual only if the root background pixmap's depth
880 // matches the root window's depth. Otherwise, find a suitable
881 // visual for the root background pixmap's depth and use it.
882 //
883 // We can't obtain a suitable visual for the root background
884 // pixmap the same way as the win_bind_pixmap function because it
885 // requires a window and we have only a pixmap. We also can't not
886 // bind the root background pixmap in case of depth mismatch
887 // because some options rely on it's content, e.g.
888 // transparent-clipping.
889 xcb_visualid_t visual =
890 r->depth == ps->c.screen_info->root_depth
891 ? ps->c.screen_info->root_visual
892 : x_get_visual_for_depth(ps->c.screen_info, r->depth);
893
894 ps->root_image = ps->backend_data->ops.bind_pixmap(
895 ps->backend_data, pixmap, x_get_visual_info(&ps->c, visual));
896 ps->root_image_generation += 1;
897 ps->root_image_extent = (rect_t){
898 .x1 = r->x, .x2 = r->x + r->width, .y1 = r->y, .y2 = r->y + r->height};
899 free(r);
900
901 if (!ps->root_image) {
902 err:
903 log_error("Failed to bind root back pixmap");
904 }
905 }
906 }
907
908 // Mark screen damaged
909 force_repaint(ps);
910 }
911
912 /// Force a full-screen repaint.
913 void force_repaint(session_t *ps) {
914 // `layout_manager` might be NULL if the screen is not redirected, if a render is
915 // started in this case it will always be a full-screen render.
916 if (ps->layout_manager != NULL) {
917 layout_manager_clear(ps->layout_manager);
918 }
919 queue_redraw(ps);
920 }
921
922 /**
923 * Setup window properties, then register us with the compositor selection (_NET_WM_CM_S)
924 *
925 * @return 0 if success, 1 if compositor already running, -1 if error.
926 */
927 static int register_cm(session_t *ps) {
928 assert(!ps->reg_win);
929
930 ps->reg_win = x_new_id(&ps->c);
931 auto e = xcb_request_check(
932 ps->c.c, xcb_create_window_checked(ps->c.c, XCB_COPY_FROM_PARENT, ps->reg_win,
933 ps->c.screen_info->root, 0, 0, 1, 1, 0, XCB_NONE,
934 ps->c.screen_info->root_visual, 0, NULL));
935
936 if (e) {
937 log_fatal("Failed to create window.");
938 free(e);
939 return -1;
940 }
941
942 const xcb_atom_t prop_atoms[] = {
943 ps->atoms->aWM_NAME,
944 ps->atoms->a_NET_WM_NAME,
945 ps->atoms->aWM_ICON_NAME,
946 };
947
948 const bool prop_is_utf8[] = {false, true, false};
949
950 // Set names and classes
951 for (size_t i = 0; i < ARR_SIZE(prop_atoms); i++) {
952 e = xcb_request_check(
953 ps->c.c, xcb_change_property_checked(
954 ps->c.c, XCB_PROP_MODE_REPLACE, ps->reg_win, prop_atoms[i],
955 prop_is_utf8[i] ? ps->atoms->aUTF8_STRING : XCB_ATOM_STRING,
956 8, strlen("picom"), "picom"));
957 if (e) {
958 log_error_x_error(&ps->c, e, "Failed to set window property %d",
959 prop_atoms[i]);
960 free(e);
961 }
962 }
963
964 const char picom_class[] = "picom\0picom";
965 e = xcb_request_check(
966 ps->c.c, xcb_change_property_checked(ps->c.c, XCB_PROP_MODE_REPLACE, ps->reg_win,
967 ps->atoms->aWM_CLASS, XCB_ATOM_STRING, 8,
968 ARR_SIZE(picom_class), picom_class));
969 if (e) {
970 log_error_x_error(&ps->c, e, "Failed to set the WM_CLASS property");
971 free(e);
972 }
973
974 // Set WM_CLIENT_MACHINE. As per EWMH, because we set _NET_WM_PID, we must also
975 // set WM_CLIENT_MACHINE.
976 {
977 auto const hostname_max = (unsigned long)sysconf(_SC_HOST_NAME_MAX);
978 char *hostname = malloc(hostname_max);
979
980 if (gethostname(hostname, hostname_max) == 0) {
981 e = xcb_request_check(
982 ps->c.c, xcb_change_property_checked(
983 ps->c.c, XCB_PROP_MODE_REPLACE, ps->reg_win,
984 ps->atoms->aWM_CLIENT_MACHINE, XCB_ATOM_STRING,
985 8, (uint32_t)strlen(hostname), hostname));
986 if (e) {
987 log_error_x_error(&ps->c, e,
988 "Failed to set the WM_CLIENT_MACHINE"
989 " property");
990 free(e);
991 }
992 } else {
993 log_error_errno("Failed to get hostname");
994 }
995
996 free(hostname);
997 }
998
999 // Set _NET_WM_PID
1000 {
1001 auto pid = getpid();
1002 xcb_change_property(ps->c.c, XCB_PROP_MODE_REPLACE, ps->reg_win,
1003 ps->atoms->a_NET_WM_PID, XCB_ATOM_CARDINAL, 32, 1, &pid);
1004 }
1005
1006 // Set COMPTON_VERSION
1007 e = xcb_request_check(ps->c.c, xcb_change_property_checked(
1008 ps->c.c, XCB_PROP_MODE_REPLACE, ps->reg_win,
1009 ps->atoms->aCOMPTON_VERSION, XCB_ATOM_STRING, 8,
1010 (uint32_t)strlen(PICOM_VERSION), PICOM_VERSION));
1011 if (e) {
1012 log_error_x_error(&ps->c, e, "Failed to set COMPTON_VERSION.");
1013 free(e);
1014 }
1015
1016 // Acquire X Selection _NET_WM_CM_S?
1017 if (!ps->o.no_x_selection) {
1018 const char register_prop[] = "_NET_WM_CM_S";
1019 xcb_atom_t atom;
1020
1021 char *buf = NULL;
1022 casprintf(&buf, "%s%d", register_prop, ps->c.screen);
1023 atom = get_atom_with_nul(ps->atoms, buf, ps->c.c);
1024 free(buf);
1025
1026 xcb_get_selection_owner_reply_t *reply = xcb_get_selection_owner_reply(
1027 ps->c.c, xcb_get_selection_owner(ps->c.c, atom), NULL);
1028
1029 if (reply && reply->owner != XCB_NONE) {
1030 // Another compositor already running
1031 free(reply);
1032 return 1;
1033 }
1034 free(reply);
1035 xcb_set_selection_owner(ps->c.c, ps->reg_win, atom, 0);
1036 }
1037
1038 return 0;
1039 }
1040
1041 /**
1042 * Write PID to a file.
1043 */
1044 static inline bool write_pid(session_t *ps) {
1045 if (!ps->o.write_pid_path) {
1046 return true;
1047 }
1048
1049 FILE *f = fopen(ps->o.write_pid_path, "w");
1050 if (unlikely(!f)) {
1051 log_error("Failed to write PID to \"%s\".", ps->o.write_pid_path);
1052 return false;
1053 }
1054
1055 fprintf(f, "%ld\n", (long)getpid());
1056 fclose(f);
1057
1058 return true;
1059 }
1060
1061 /**
1062 * Initialize X composite overlay window.
1063 */
1064 static bool init_overlay(session_t *ps) {
1065 xcb_composite_get_overlay_window_reply_t *reply = xcb_composite_get_overlay_window_reply(
1066 ps->c.c, xcb_composite_get_overlay_window(ps->c.c, ps->c.screen_info->root), NULL);
1067 if (reply) {
1068 ps->overlay = reply->overlay_win;
1069 free(reply);
1070 } else {
1071 ps->overlay = XCB_NONE;
1072 }
1073 if (ps->overlay != XCB_NONE) {
1074 // Set window region of the overlay window, code stolen from
1075 // compiz-0.8.8
1076 if (!XCB_AWAIT_VOID(xcb_shape_mask, &ps->c, XCB_SHAPE_SO_SET,
1077 XCB_SHAPE_SK_BOUNDING, ps->overlay, 0, 0, 0)) {
1078 log_fatal("Failed to set the bounding shape of overlay, giving "
1079 "up.");
1080 return false;
1081 }
1082 if (!XCB_AWAIT_VOID(xcb_shape_rectangles, &ps->c, XCB_SHAPE_SO_SET,
1083 XCB_SHAPE_SK_INPUT, XCB_CLIP_ORDERING_UNSORTED,
1084 ps->overlay, 0, 0, 0, NULL)) {
1085 log_fatal("Failed to set the input shape of overlay, giving up.");
1086 return false;
1087 }
1088
1089 // Listen to Expose events on the overlay
1090 xcb_change_window_attributes(ps->c.c, ps->overlay, XCB_CW_EVENT_MASK,
1091 (const uint32_t[]){XCB_EVENT_MASK_EXPOSURE});
1092
1093 // Retrieve DamageNotify on root window if we are painting on an
1094 // overlay
1095 // root_damage = XDamageCreate(ps->dpy, root, XDamageReportNonEmpty);
1096
1097 // Unmap the overlay, we will map it when needed in redirect_start
1098 XCB_AWAIT_VOID(xcb_unmap_window, &ps->c, ps->overlay);
1099 } else {
1100 log_error("Cannot get X Composite overlay window. Falling "
1101 "back to painting on root window.");
1102 }
1103 log_debug("overlay = %#010x", ps->overlay);
1104
1105 return true;
1106 }
1107
1108 static bool init_debug_window(session_t *ps) {
1109 xcb_colormap_t colormap = x_new_id(&ps->c);
1110 ps->debug_window = x_new_id(&ps->c);
1111
1112 auto err = xcb_request_check(
1113 ps->c.c, xcb_create_colormap_checked(ps->c.c, XCB_COLORMAP_ALLOC_NONE,
1114 colormap, ps->c.screen_info->root,
1115 ps->c.screen_info->root_visual));
1116 if (err) {
1117 goto err_out;
1118 }
1119
1120 err = xcb_request_check(
1121 ps->c.c, xcb_create_window_checked(
1122 ps->c.c, (uint8_t)ps->c.screen_info->root_depth,
1123 ps->debug_window, ps->c.screen_info->root, 0, 0,
1124 to_u16_checked(ps->root_width), to_u16_checked(ps->root_height),
1125 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, ps->c.screen_info->root_visual,
1126 XCB_CW_COLORMAP, (uint32_t[]){colormap, 0}));
1127 if (err) {
1128 goto err_out;
1129 }
1130
1131 err = xcb_request_check(ps->c.c, xcb_map_window_checked(ps->c.c, ps->debug_window));
1132 if (err) {
1133 goto err_out;
1134 }
1135 return true;
1136
1137 err_out:
1138 free(err);
1139 return false;
1140 }
1141
1142 xcb_window_t session_get_target_window(session_t *ps) {
1143 if (ps->o.debug_mode) {
1144 return ps->debug_window;
1145 }
1146 return ps->overlay != XCB_NONE ? ps->overlay : ps->c.screen_info->root;
1147 }
1148
1149 #ifdef CONFIG_DBUS
1150 struct cdbus_data *session_get_cdbus(struct session *ps) {
1151 return ps->dbus_data;
1152 }
1153 #endif
1154
1155 uint8_t session_redirection_mode(session_t *ps) {
1156 if (ps->o.debug_mode) {
1157 // If the backend is not rendering to the screen, we don't need to
1158 // take over the screen.
1159 return XCB_COMPOSITE_REDIRECT_AUTOMATIC;
1160 }
1161 if (!backend_can_present(ps->o.backend)) {
1162 // if the backend doesn't render anything, we don't need to take over the
1163 // screen.
1164 return XCB_COMPOSITE_REDIRECT_AUTOMATIC;
1165 }
1166 return XCB_COMPOSITE_REDIRECT_MANUAL;
1167 }
1168
1169 /**
1170 * Redirect all windows.
1171 *
1172 * @return whether the operation succeeded or not
1173 */
1174 static bool redirect_start(session_t *ps) {
1175 assert(!ps->redirected);
1176 log_debug("Redirecting the screen.");
1177
1178 // Map overlay window. Done firstly according to this:
1179 // https://bugzilla.gnome.org/show_bug.cgi?id=597014
1180 if (ps->overlay != XCB_NONE) {
1181 xcb_map_window(ps->c.c, ps->overlay);
1182 }
1183
1184 bool success = XCB_AWAIT_VOID(xcb_composite_redirect_subwindows, &ps->c,
1185 ps->c.screen_info->root, session_redirection_mode(ps));
1186 if (!success) {
1187 log_fatal("Another composite manager is already running "
1188 "(and does not handle _NET_WM_CM_Sn correctly)");
1189 return false;
1190 }
1191
1192 xcb_aux_sync(ps->c.c);
1193
1194 if (!initialize_backend(ps)) {
1195 return false;
1196 }
1197
1198 assert(ps->backend_data);
1199 auto damage_count = ps->backend_data->ops.max_buffer_age(ps->backend_data);
1200 ps->layout_manager = layout_manager_new((unsigned)damage_count);
1201
1202 ps->frame_pacing = ps->o.frame_pacing && ps->o.vsync;
1203 if ((ps->o.benchmark || !ps->backend_data->ops.last_render_time) && ps->frame_pacing) {
1204 // Disable frame pacing if we are in benchmark mode or if the backend
1205 // doesn't report render time.
1206 log_info("Disabling frame pacing.");
1207 ps->frame_pacing = false;
1208 }
1209
1210 // Re-detect driver since we now have a backend
1211 ps->drivers = detect_driver(ps->c.c, ps->backend_data, ps->c.screen_info->root);
1212 apply_driver_workarounds(ps, ps->drivers);
1213
1214 if (ps->c.e.has_present && ps->frame_pacing) {
1215 // Initialize rendering and frame timing statistics, and frame pacing
1216 // states.
1217 ps->last_msc_instant = 0;
1218 ps->last_msc = 0;
1219 ps->last_schedule_delay = 0;
1220 render_statistics_reset(&ps->render_stats);
1221 enum vblank_scheduler_type scheduler_type =
1222 choose_vblank_scheduler(ps->drivers);
1223 if (global_debug_options.force_vblank_scheduler != LAST_VBLANK_SCHEDULER) {
1224 scheduler_type =
1225 (enum vblank_scheduler_type)global_debug_options.force_vblank_scheduler;
1226 }
1227 log_info("Using vblank scheduler: %s.", vblank_scheduler_str[scheduler_type]);
1228 ps->vblank_scheduler =
1229 vblank_scheduler_new(ps->loop, &ps->c, session_get_target_window(ps),
1230 scheduler_type, ps->o.use_realtime_scheduling);
1231 if (!ps->vblank_scheduler) {
1232 return false;
1233 }
1234 vblank_scheduler_schedule(ps->vblank_scheduler,
1235 collect_vblank_interval_statistics, ps);
1236 } else if (ps->frame_pacing) {
1237 log_error("Present extension is not supported, frame pacing disabled.");
1238 ps->frame_pacing = false;
1239 }
1240
1241 // Must call XSync() here
1242 xcb_aux_sync(ps->c.c);
1243
1244 ps->redirected = true;
1245 ps->first_frame = true;
1246
1247 root_damaged(ps);
1248
1249 // Repaint the whole screen
1250 force_repaint(ps);
1251 log_debug("Screen redirected.");
1252 return true;
1253 }
1254
1255 /**
1256 * Unredirect all windows.
1257 */
1258 static void unredirect(session_t *ps) {
1259 assert(ps->redirected);
1260 log_debug("Unredirecting the screen.");
1261
1262 destroy_backend(ps);
1263
1264 xcb_composite_unredirect_subwindows(ps->c.c, ps->c.screen_info->root,
1265 session_redirection_mode(ps));
1266 // Unmap overlay window
1267 if (ps->overlay != XCB_NONE &&
1268 session_redirection_mode(ps) == XCB_COMPOSITE_REDIRECT_MANUAL) {
1269 xcb_unmap_window(ps->c.c, ps->overlay);
1270 }
1271
1272 if (ps->layout_manager) {
1273 layout_manager_free(ps->layout_manager);
1274 ps->layout_manager = NULL;
1275 }
1276
1277 if (ps->vblank_scheduler) {
1278 vblank_scheduler_free(ps->vblank_scheduler);
1279 ps->vblank_scheduler = NULL;
1280 }
1281
1282 // Must call XSync() here
1283 xcb_aux_sync(ps->c.c);
1284
1285 ps->redirected = false;
1286 log_debug("Screen unredirected.");
1287 }
1288
1289 /// Handle queued events before we go to sleep.
1290 ///
1291 /// This function is called by ev_prepare watcher, which is called just before
1292 /// the event loop goes to sleep. X damage events are incremental, which means
1293 /// if we don't handle the ones X server already sent us, we won't get new ones.
1294 /// And if we don't get new ones, we won't render, i.e. we would freeze. libxcb
1295 /// keeps an internal queue of events, so we have to be 100% sure no events are
1296 /// left in that queue before we go to sleep.
1297 static void handle_x_events(struct session *ps) {
1298 uint32_t latest_completed = ps->c.latest_completed_request;
1299 while (true) {
1300 if (!x_prepare_for_sleep(&ps->c)) {
1301 log_fatal("X connection broke.");
1302 exit(1);
1303 }
1304
1305 // If we send any new requests, we should loop again to flush them. There
1306 // is no direct way to do this from xcb. So if we called `ev_handle`, or
1307 // if any pending requests were completed, we conservatively loop again.
1308 bool needs_flush = false;
1309 if (ps->vblank_scheduler) {
1310 vblank_handle_x_events(ps->vblank_scheduler);
1311 }
1312
1313 xcb_generic_event_t *ev;
1314 while ((ev = x_poll_for_event(&ps->c, true))) {
1315 ev_handle(ps, (xcb_generic_event_t *)ev);
1316 needs_flush = true;
1317 free(ev);
1318 };
1319
1320 if (ps->c.latest_completed_request != latest_completed) {
1321 needs_flush = true;
1322 latest_completed = ps->c.latest_completed_request;
1323 }
1324
1325 if (!needs_flush) {
1326 break;
1327 }
1328 }
1329
1330 int err = xcb_connection_has_error(ps->c.c);
1331 if (err) {
1332 log_fatal("X11 server connection broke (error %d)", err);
1333 exit(1);
1334 }
1335
1336 if (wm_has_tree_changes(ps->wm)) {
1337 log_debug("Window tree changed, queueing redraw.");
1338 ps->pending_updates = true;
1339 queue_redraw(ps);
1340 }
1341 }
1342
1343 static void handle_x_events_ev(EV_P attr_unused, ev_prepare *w, int revents attr_unused) {
1344 session_t *ps = session_ptr(w, event_check);
1345 handle_x_events(ps);
1346 }
1347
1348 struct new_window_attributes_request {
1349 struct x_async_request_base base;
1350 struct session *ps;
1351 wm_treeid id;
1352 };
1353
1354 static void handle_new_window_attributes_reply(struct x_connection * /*c*/,
1355 struct x_async_request_base *req_base,
1356 const xcb_raw_generic_event_t *reply_or_error) {
1357 auto req = (struct new_window_attributes_request *)req_base;
1358 auto ps = req->ps;
1359 auto id = req->id;
1360 auto new_window = wm_find(ps->wm, id.x);
1361 free(req);
1362
1363 if (reply_or_error == NULL) {
1364 // Shutting down
1365 return;
1366 }
1367
1368 if (reply_or_error->response_type == 0) {
1369 log_debug("Failed to get window attributes for newly created window "
1370 "%#010x",
1371 id.x);
1372 return;
1373 }
1374
1375 if (new_window == NULL) {
1376 // Highly unlikely. This window is destroyed, then another window is
1377 // created with the same window ID before this request completed, and the
1378 // latter window isn't in our tree yet.
1379 if (wm_is_consistent(ps->wm)) {
1380 log_error("Newly created window %#010x is not in the window tree",
1381 id.x);
1382 assert(false);
1383 }
1384 return;
1385 }
1386
1387 auto current_id = wm_ref_treeid(new_window);
1388 if (!wm_treeid_eq(current_id, id)) {
1389 log_debug("Window %#010x was not the window we queried anymore. Current "
1390 "gen %" PRIu64 ", expected %" PRIu64,
1391 id.x, current_id.gen, id.gen);
1392 return;
1393 }
1394
1395 auto toplevel = wm_ref_toplevel_of(ps->wm, new_window);
1396 if (toplevel != new_window) {
1397 log_debug("Newly created window %#010x was moved away from toplevel "
1398 "while we were waiting for its attributes",
1399 id.x);
1400 return;
1401 }
1402 if (wm_ref_deref(toplevel) != NULL) {
1403 // This is possible if a toplevel is reparented away, then reparented to
1404 // root so it became a toplevel again. If the GetWindowAttributes request
1405 // sent for the first time it became a toplevel wasn't completed for this
1406 // whole duration, it will create a managed window object for the
1407 // toplevel. But there is another get attributes request sent the
1408 // second time it became a toplevel. When we get the reply for the second
1409 // request, we will reach here.
1410 log_debug("Newly created window %#010x is already managed", id.x);
1411 return;
1412 }
1413
1414 auto w = win_maybe_allocate(
1415 ps, toplevel, (const xcb_get_window_attributes_reply_t *)reply_or_error);
1416 if (w != NULL && w->a.map_state == XCB_MAP_STATE_VIEWABLE) {
1417 win_set_flags(w, WIN_FLAGS_MAPPED);
1418 ps->pending_updates = true;
1419 }
1420 }
1421
1422 static void handle_new_windows(session_t *ps) {
1423 // Check tree changes first, because later property updates need accurate
1424 // client window information
1425 struct win *w = NULL;
1426 while (true) {
1427 auto wm_change = wm_dequeue_change(ps->wm);
1428 if (wm_change.type == WM_TREE_CHANGE_NONE) {
1429 break;
1430 }
1431 switch (wm_change.type) {
1432 case WM_TREE_CHANGE_TOPLEVEL_NEW:;
1433 auto req = ccalloc(1, struct new_window_attributes_request);
1434 // We don't directly record the toplevel wm_ref here, because any
1435 // number of things could happen before we get the reply. The
1436 // window can be reparented, destroyed, then get its window ID
1437 // reused, etc.
1438 req->id = wm_ref_treeid(wm_change.toplevel);
1439 req->ps = ps;
1440 req->base.callback = handle_new_window_attributes_reply,
1441 req->base.sequence =
1442 xcb_get_window_attributes(ps->c.c, req->id.x).sequence;
1443 x_await_request(&ps->c, &req->base);
1444 break;
1445 case WM_TREE_CHANGE_TOPLEVEL_KILLED:
1446 w = wm_ref_deref(wm_change.toplevel);
1447 if (w != NULL) {
1448 win_destroy_start(w);
1449 } else {
1450 // This window is not managed, no point keeping the zombie
1451 // around.
1452 wm_reap_zombie(wm_change.toplevel);
1453 }
1454 break;
1455 case WM_TREE_CHANGE_CLIENT:
1456 log_debug("Client window for window %#010x changed from "
1457 "%#010x to %#010x",
1458 wm_ref_win_id(wm_change.toplevel),
1459 wm_change.client.old.x, wm_change.client.new_.x);
1460 w = wm_ref_deref(wm_change.toplevel);
1461 if (w != NULL) {
1462 win_set_flags(w, WIN_FLAGS_CLIENT_STALE);
1463 } else {
1464 log_debug("An unmanaged window %#010x has a new client "
1465 "%#010x",
1466 wm_ref_win_id(wm_change.toplevel),
1467 wm_change.client.new_.x);
1468 }
1469 ev_update_focused(ps);
1470 break;
1471 case WM_TREE_CHANGE_TOPLEVEL_RESTACKED: break;
1472 default: unreachable();
1473 }
1474 }
1475 }
1476
1477 static void refresh_windows(session_t *ps) {
1478 wm_stack_foreach(ps->wm, cursor) {
1479 auto w = wm_ref_deref(cursor);
1480 if (w == NULL) {
1481 continue;
1482 }
1483 win_process_primary_flags(ps, w);
1484 }
1485 wm_refresh_leaders(ps->wm);
1486 wm_stack_foreach(ps->wm, cursor) {
1487 auto w = wm_ref_deref(cursor);
1488 if (w == NULL) {
1489 continue;
1490 }
1491 win_process_secondary_flags(ps, w);
1492 }
1493 }
1494
1495 static void refresh_images(session_t *ps) {
1496 wm_stack_foreach(ps->wm, cursor) {
1497 auto w = wm_ref_deref(cursor);
1498 if (w != NULL) {
1499 win_process_image_flags(ps, w);
1500 }
1501 }
1502 }
1503
1504 /**
1505 * Unredirection timeout callback.
1506 */
1507 static void tmout_unredir_callback(EV_P attr_unused, ev_timer *w, int revents attr_unused) {
1508 session_t *ps = session_ptr(w, unredir_timer);
1509 ps->tmout_unredir_hit = true;
1510 queue_redraw(ps);
1511 }
1512
1513 static void handle_pending_updates(struct session *ps, double delta_t) {
1514 // Process new windows, and maybe allocate struct managed_win for them
1515 handle_new_windows(ps);
1516
1517 if (ps->pending_updates) {
1518 log_debug("Delayed handling of events");
1519
1520 // Process window flags. This needs to happen before `refresh_images`
1521 // because this might set the pixmap stale window flag.
1522 refresh_windows(ps);
1523 ps->pending_updates = false;
1524 }
1525
1526 wm_stack_foreach_safe(ps->wm, cursor, tmp) {
1527 auto w = wm_ref_deref(cursor);
1528 BUG_ON(w != NULL && w->tree_ref != cursor);
1529 // Window might be freed by this function, if it's destroyed and its
1530 // animation finished
1531 if (w != NULL && win_process_animation_and_state_change(ps, w, delta_t)) {
1532 free(w->running_animation_instance);
1533 w->running_animation_instance = NULL;
1534 w->in_openclose = false;
1535 if (w->saved_win_image != NULL) {
1536 win_release_saved_win_image(ps->backend_data, w);
1537 }
1538 if (w->state == WSTATE_UNMAPPED) {
1539 unmap_win_finish(ps, w);
1540 } else if (w->state == WSTATE_DESTROYED) {
1541 win_destroy_finish(ps, w);
1542 }
1543 }
1544 }
1545
1546 // Process window flags (stale images)
1547 refresh_images(ps);
1548 assert(ps->pending_updates == false);
1549 }
1550
1551 /**
1552 * Turn on the program reset flag.
1553 *
1554 * This will result in the compositor resetting itself after next paint.
1555 */
1556 static void reset_enable(EV_P_ ev_signal *w attr_unused, int revents attr_unused) {
1557 log_info("picom is resetting...");
1558 ev_break(EV_A_ EVBREAK_ALL);
1559 }
1560
1561 static void exit_enable(EV_P attr_unused, ev_signal *w, int revents attr_unused) {
1562 session_t *ps = session_ptr(w, int_signal);
1563 log_info("picom is quitting...");
1564 quit(ps);
1565 }
1566
1567 static void draw_callback_impl(EV_P_ session_t *ps, int revents attr_unused) {
1568 assert(!ps->backend_busy);
1569 assert(ps->render_queued);
1570
1571 struct timespec now;
1572 int64_t draw_callback_enter_us;
1573 clock_gettime(CLOCK_MONOTONIC, &now);
1574
1575 // Fading step calculation
1576 auto now_ms = timespec_ms(now);
1577 int64_t delta_ms = 0L;
1578 if (ps->fade_time) {
1579 assert(now_ms >= ps->fade_time);
1580 delta_ms = now_ms - ps->fade_time;
1581 }
1582 ps->fade_time = now_ms;
1583
1584 draw_callback_enter_us = (now.tv_sec * 1000000LL + now.tv_nsec / 1000);
1585 if (ps->next_render != 0) {
1586 log_trace("Schedule delay: %" PRIi64 " us",
1587 draw_callback_enter_us - (int64_t)ps->next_render);
1588 }
1589
1590 handle_pending_updates(ps, (double)delta_ms / 1000.0);
1591
1592 int64_t after_handle_pending_updates_us;
1593 clock_gettime(CLOCK_MONOTONIC, &now);
1594 after_handle_pending_updates_us = (now.tv_sec * 1000000LL + now.tv_nsec / 1000);
1595 log_trace("handle_pending_updates took: %" PRIi64 " us",
1596 after_handle_pending_updates_us - draw_callback_enter_us);
1597
1598 if (ps->first_frame) {
1599 // If we are still rendering the first frame, if some of the windows are
1600 // unmapped/destroyed during the above handle_pending_updates() call, they
1601 // won't have pixmap before we rendered it, causing us to crash.
1602 // But we will only render them if they are in fading. So we just skip
1603 // fading for all windows here.
1604 //
1605 // Using foreach_safe here since skipping fading can cause window to be
1606 // freed if it's destroyed.
1607 //
1608 // TODO(yshui) I think maybe we don't need this anymore, since now we
1609 // immediate acquire pixmap right after `map_win_start`.
1610 wm_stack_foreach_safe(ps->wm, cursor, tmp) {
1611 auto w = wm_ref_deref(cursor);
1612 if (w == NULL) {
1613 continue;
1614 }
1615 free(w->running_animation_instance);
1616 w->running_animation_instance = NULL;
1617 if (w->state == WSTATE_DESTROYED) {
1618 win_destroy_finish(ps, w);
1619 }
1620 }
1621 }
1622
1623 if (ps->o.benchmark) {
1624 if (ps->o.benchmark_wid) {
1625 auto w = wm_find(ps->wm, ps->o.benchmark_wid);
1626 if (w == NULL) {
1627 log_fatal("Couldn't find specified benchmark window.");
1628 exit(1);
1629 }
1630 w = wm_ref_toplevel_of(ps->wm, w);
1631
1632 auto win = w == NULL ? NULL : wm_ref_deref(w);
1633 if (win == NULL) {
1634 region_t tmp;
1635 pixman_region32_init(&tmp);
1636 win_extents(win, &tmp);
1637 pixman_region32_translate(&tmp, -win->g.x, -win->g.y);
1638 pixman_region32_union(&win->damaged, &win->damaged, &tmp);
1639 pixman_region32_fini(&tmp);
1640 } else {
1641 force_repaint(ps);
1642 }
1643 } else {
1644 force_repaint(ps);
1645 }
1646 }
1647
1648 /* TODO(yshui) Have a stripped down version of paint_preprocess that is used when
1649 * screen is not redirected. its sole purpose should be to decide whether the
1650 * screen should be redirected. */
1651 bool animation = false;
1652 bool was_redirected = ps->redirected;
1653 struct win *bottom = NULL;
1654 if (!paint_preprocess(ps, &animation, &bottom)) {
1655 log_fatal("Pre-render preparation has failed, exiting...");
1656 exit(1);
1657 }
1658
1659 ps->tmout_unredir_hit = false;
1660
1661 if (!was_redirected && ps->redirected) {
1662 // paint_preprocess redirected the screen, which might change the state of
1663 // some of the windows (e.g. the window image might become stale).
1664 // so we rerun _draw_callback to make sure the rendering decision we make
1665 // is up-to-date, and all the new flags got handled.
1666 //
1667 // TODO(yshui) This is not ideal, we should try to avoid setting window
1668 // flags in paint_preprocess.
1669 log_debug("Re-run _draw_callback");
1670 return draw_callback_impl(EV_A_ ps, revents);
1671 }
1672
1673 int64_t after_preprocess_us;
1674 clock_gettime(CLOCK_MONOTONIC, &now);
1675 after_preprocess_us = (now.tv_sec * 1000000LL + now.tv_nsec / 1000);
1676 log_trace("paint_preprocess took: %" PRIi64 " us",
1677 after_preprocess_us - after_handle_pending_updates_us);
1678
1679 // If the screen is unredirected, we don't render anything.
1680 bool did_render = false;
1681 if (ps->redirected && ps->o.stoppaint_force != ON) {
1682 static int paint = 0;
1683
1684 log_verbose("Render start, frame %d", paint);
1685 uint64_t after_damage_us = 0;
1686 now = get_time_timespec();
1687 auto render_start_us =
1688 (uint64_t)now.tv_sec * 1000000UL + (uint64_t)now.tv_nsec / 1000;
1689 if (ps->backend_data->ops.device_status &&
1690 ps->backend_data->ops.device_status(ps->backend_data) !=
1691 DEVICE_STATUS_NORMAL) {
1692 log_error("Device reset detected");
1693 // Wait for reset to complete
1694 // Although ideally the backend should return
1695 // DEVICE_STATUS_NORMAL after a reset is completed, it's
1696 // not always possible.
1697 //
1698 // According to ARB_robustness (emphasis mine):
1699 //
1700 // "If a reset status other than NO_ERROR is returned
1701 // and subsequent calls return NO_ERROR, the context
1702 // reset was encountered and completed. If a reset
1703 // status is repeatedly returned, the context **may**
1704 // be in the process of resetting."
1705 //
1706 // Which means it may also not be in the process of
1707 // resetting. For example on AMDGPU devices, Mesa OpenGL
1708 // always return CONTEXT_RESET after a reset has started,
1709 // completed or not.
1710 //
1711 // So here we blindly wait 5 seconds and hope ourselves
1712 // best of the luck.
1713 sleep(5);
1714 log_info("Resetting picom after device reset");
1715 reset_enable(ps->loop, NULL, 0);
1716 return;
1717 }
1718 layout_manager_append_layout(
1719 ps->layout_manager, ps->wm, ps->root_image_generation,
1720 (ivec2){.width = ps->root_width, .height = ps->root_height});
1721 bool succeeded = renderer_render(
1722 ps->renderer, ps->backend_data, ps->root_image, &ps->root_image_extent,
1723 ps->layout_manager, ps->command_builder, ps->backend_blur_context,
1724 render_start_us, ps->sync_fence, ps->o.use_damage, ps->o.monitor_repaint,
1725 ps->o.force_win_blend, ps->o.blur_background_frame,
1726 ps->o.inactive_dim_fixed, ps->o.max_brightness,
1727 ps->o.crop_shadow_to_monitor ? &ps->monitors : NULL,
1728 ps->root_pixmap_shader, ps->shaders, &after_damage_us);
1729 if (!succeeded) {
1730 log_fatal("Render failure");
1731 abort();
1732 }
1733 did_render = true;
1734 if (ps->next_render > 0) {
1735 log_verbose("Render schedule deviation: %ld us (%s) %" PRIu64
1736 " %" PRIu64,
1737 labs((long)after_damage_us - (long)ps->next_render),
1738 after_damage_us < ps->next_render ? "early" : "late",
1739 after_damage_us, ps->next_render);
1740 ps->last_schedule_delay = 0;
1741 if (after_damage_us > ps->next_render) {
1742 ps->last_schedule_delay = after_damage_us - ps->next_render;
1743 }
1744 }
1745 log_verbose("Render end");
1746
1747 ps->first_frame = false;
1748 paint++;
1749 if (ps->o.benchmark && paint >= ps->o.benchmark) {
1750 exit(0);
1751 }
1752 }
1753
1754 // With frame pacing, we set backend_busy to true after the end of
1755 // vblank. Without frame pacing, we won't be receiving vblank events, so
1756 // we set backend_busy to false here, right after we issue the render
1757 // commands.
1758 // The other case is if we decided there is no change to render, in that
1759 // case no render command is issued, so we also set backend_busy to
1760 // false.
1761 ps->backend_busy = (ps->frame_pacing && did_render);
1762 ps->next_render = 0;
1763 ps->render_queued = false;
1764
1765 // TODO(yshui) Investigate how big the X critical section needs to be. There are
1766 // suggestions that rendering should be in the critical section as well.
1767
1768 // Queue redraw if animation is running. This should be picked up by next present
1769 // event.
1770 if (animation) {
1771 queue_redraw(ps);
1772 } else {
1773 ps->fade_time = 0L;
1774 }
1775 if (ps->vblank_scheduler && ps->backend_busy) {
1776 // Even if we might not want to render during next vblank, we want to keep
1777 // `backend_busy` up to date, so when the next render comes, we can
1778 // immediately know if we can render.
1779 vblank_scheduler_schedule(ps->vblank_scheduler, check_render_finish, ps);
1780 }
1781 }
1782
1783 static void draw_callback(EV_P_ ev_timer *w, int revents) {
1784 session_t *ps = session_ptr(w, draw_timer);
1785
1786 // The draw timer has to be stopped before calling the draw_callback_impl
1787 // function because it may be set and started there, e.g. when a custom
1788 // animated shader is used.
1789 ev_timer_stop(EV_A_ w);
1790 draw_callback_impl(EV_A_ ps, revents);
1791
1792 // Immediately start next frame if we are in benchmark mode.
1793 if (ps->o.benchmark) {
1794 ps->render_queued = true;
1795 ev_timer_set(w, 0, 0);
1796 ev_timer_start(EV_A_ w);
1797 }
1798 }
1799
1800 static void x_event_callback(EV_P attr_unused, ev_io *w, int revents attr_unused) {
1801 // Make sure the X connection is being read from at least once every time
1802 // we woke up because of readability of the X connection.
1803 //
1804 // `handle_x_events` is not guaranteed to read from X, so if we don't do
1805 // it here we could dead lock.
1806 struct session *ps = session_ptr(w, xiow);
1807 auto ev = x_poll_for_event(&ps->c, false);
1808 if (ev) {
1809 ev_handle(ps, (xcb_generic_event_t *)ev);
1810 free(ev);
1811 }
1812 }
1813
1814 static void config_file_change_cb(void *_ps) {
1815 auto ps = (struct session *)_ps;
1816 reset_enable(ps->loop, NULL, 0);
1817 }
1818
1819 static struct shader_info *
1820 load_shader_source(session_t *ps, const struct shader_specification *spec) {
1821 const char *path = shader_spec_get_path(spec);
1822 log_info("Loading shader source from %s", path);
1823
1824 struct shader_info *shader = NULL;
1825 HASH_FIND(hh, ps->shaders, spec->data, spec->size, shader);
1826 if (shader) {
1827 log_debug("Shader already loaded, reusing.");
1828 return shader;
1829 }
1830
1831 struct shader_source *source = NULL;
1832 HASH_FIND_STR(ps->shader_sources, path, source);
1833 if (source) {
1834 log_debug("Shader source already loaded, reusing");
1835 } else {
1836 FILE *f = fopen(path, "r");
1837 if (!f) {
1838 log_error("Failed to open custom shader file: %s", path);
1839 return NULL;
1840 }
1841
1842 struct stat statbuf;
1843 if (fstat(fileno(f), &statbuf) < 0) {
1844 log_error("Failed to access custom shader file: %s", path);
1845 fclose(f);
1846 return NULL;
1847 }
1848
1849 auto num_bytes = (size_t)statbuf.st_size;
1850 char *source_data = ccalloc(num_bytes + 1, char);
1851 auto read_bytes = fread(source_data, sizeof(char), num_bytes, f);
1852 auto error = ferror(f);
1853 fclose(f);
1854
1855 if (read_bytes < num_bytes || error) {
1856 // This is a difficult to hit error case, review thoroughly.
1857 log_error("Failed to read custom shader at %s. (read %zu bytes, "
1858 "expected %zu bytes)",
1859 path, read_bytes, num_bytes);
1860 free(source_data);
1861 return NULL;
1862 }
1863
1864 source = ccalloc(1, struct shader_source);
1865 source->path = path;
1866 source->source = source_data;
1867 HASH_ADD_KEYPTR(hh, ps->shader_sources, source->path,
1868 strlen(source->path), source);
1869 }
1870
1871 shader = ccalloc(1, struct shader_info);
1872 shader->spec = spec;
1873 shader->source = source->source;
1874 HASH_ADD_KEYPTR(hh, ps->shaders, shader->spec->data, shader->spec->size, shader);
1875 return shader;
1876 }
1877
1878 static struct window_options win_options_from_config(const struct options *opts) {
1879 struct window_options ret = {
1880 .blur_background = opts->blur_method != BLUR_METHOD_NONE,
1881 .full_shadow = false,
1882 .shadow = opts->shadow_enable,
1883 .shadow_color =
1884 (struct color){
1885 .red = opts->shadow_red,
1886 .green = opts->shadow_green,
1887 .blue = opts->shadow_blue,
1888 .alpha = 1.0,
1889 },
1890 .corner_radius = (unsigned)opts->corner_radius,
1891 .transparent_clipping = opts->transparent_clipping,
1892 .dim = 0,
1893 .fade = opts->fading_enable,
1894 .shader = opts->window_shader_fg,
1895 .invert_color = false,
1896 .paint = true,
1897 .clip_shadow_above = false,
1898 .unredir = WINDOW_UNREDIR_WHEN_POSSIBLE_ELSE_TERMINATE,
1899 .opacity = 1,
1900 .blur_opacity = 1,
1901 };
1902 memcpy(ret.animations, opts->animations, sizeof(ret.animations));
1903 return ret;
1904 }
1905
1906 static void show_config_warning_message_box(struct options *opt) {
1907 if (opt->problematic_options == NULL) {
1908 return;
1909 }
1910
1911 struct x_connection c;
1912 if (spawn_picomling(&c) != 0) {
1913 return;
1914 }
1915
1916 struct ui *ui = ui_new(&c);
1917 if (ui == NULL) {
1918 exit(1);
1919 }
1920
1921 auto lines = HASH_COUNT(opt->problematic_options) + 4;
1922 struct ui_message_box_line normal_line_template = {
1923 .text = NULL,
1924 .color = UI_COLOR_WHITE,
1925 .style = UI_STYLE_NORMAL,
1926 .justify = UI_JUSTIFY_LEFT,
1927 .pad_bottom = 3,
1928 };
1929 struct ui_message_box_content *content =
1930 malloc(sizeof(*content) + lines * sizeof(struct ui_message_box_line));
1931 content->num_lines = lines;
1932 content->margin = 10;
1933 content->scale = 0;
1934 content->lines[0] = (struct ui_message_box_line){
1935 .text = "picom Warning!",
1936 .color = UI_COLOR_YELLOW,
1937 .style = UI_STYLE_BOLD,
1938 .justify = UI_JUSTIFY_CENTER,
1939 .pad_bottom = 15,
1940 };
1941 content->lines[1] = normal_line_template;
1942 content->lines[1].text =
1943 "Some of your settings have generated warnings. Check the console";
1944 content->lines[2] = normal_line_template;
1945 content->lines[2].text =
1946 "output of picom for more information. Offending options are:";
1947 content->lines[2].pad_bottom = 10;
1948 struct option_name *o, *no;
1949 unsigned pos = 3;
1950 HASH_ITER(hh, opt->problematic_options, o, no) {
1951 char *buf = NULL;
1952 casprintf(&buf, " * %s", o->name);
1953 content->lines[pos] = normal_line_template;
1954 content->lines[pos].text = buf;
1955 pos++;
1956 }
1957 content->lines[pos - 1].pad_bottom = 10;
1958 content->lines[pos] = normal_line_template;
1959 content->lines[pos].text = "(Press ESC to close)";
1960 content->lines[pos].pad_bottom = 10;
1961 content->lines[pos].justify = UI_JUSTIFY_CENTER;
1962 ui_message_box_content_plan(ui, &c, content);
1963 ui_message_box_show(ui, &c, content, 15);
1964
1965 for (unsigned i = 3; i < lines - 1; i++) {
1966 free((void *)content->lines[i].text);
1967 }
1968 free(content);
1969 exit(0);
1970 }
1971
1972 // NOLINTBEGIN(readability-function-cognitive-complexity)
1973
1974 /// Initialize a session.
1975 ///
1976 /// @param argc number of command line arguments
1977 /// @param argv command line arguments
1978 /// @param dpy the X Display
1979 /// @param config_file the path to the config file
1980 /// @param all_xerrors whether we should report all X errors
1981 /// @param fork whether we will fork after initialization
1982 ///
1983 static session_t *session_init(int argc, char **argv, Display *dpy,
1984 const char *config_file, bool all_xerrors, bool fork) {
1985 static const session_t s_def = {
1986 .backend_data = NULL,
1987 .root_height = 0,
1988 .root_width = 0,
1989 // .root_damage = XCB_NONE,
1990 .overlay = XCB_NONE,
1991 .reg_win = XCB_NONE,
1992 .redirected = false,
1993 .fade_time = 0L,
1994 .quit = false,
1995
1996 .last_msc = 0,
1997
1998 #ifdef CONFIG_DBUS
1999 .dbus_data = NULL,
2000 #endif
2001 };
2002
2003 auto stderr_logger = stderr_logger_new();
2004 if (stderr_logger) {
2005 // stderr logger might fail to create if we are already
2006 // daemonized.
2007 log_add_target_tls(stderr_logger);
2008 }
2009
2010 // Allocate a session and copy default values into it
2011 session_t *ps = cmalloc(session_t);
2012 xcb_generic_error_t *e = NULL;
2013 *ps = s_def;
2014 ps->loop = EV_DEFAULT;
2015 pixman_region32_init(&ps->screen_reg);
2016
2017 // TODO(yshui) investigate what's the best window size
2018 render_statistics_init(&ps->render_stats, 128);
2019
2020 ps->o.show_all_xerrors = all_xerrors;
2021
2022 // Use the same Display across reset, primarily for resource leak checking
2023 x_connection_init(&ps->c, dpy);
2024 if (!x_extensions_init(&ps->c)) {
2025 goto err;
2026 }
2027
2028 ps->x_region = x_new_id(&ps->c);
2029 if (!XCB_AWAIT_VOID(xcb_xfixes_create_region, &ps->c, ps->x_region, 0, NULL)) {
2030 log_fatal("Failed to create a XFixes region");
2031 goto err;
2032 }
2033
2034 // Parse configuration file
2035 if (!parse_config(&ps->o, config_file)) {
2036 goto err;
2037 }
2038
2039 // Parse all of the rest command line options
2040 if (!get_cfg(&ps->o, argc, argv)) {
2041 log_fatal("Failed to get configuration, usually mean you have specified "
2042 "invalid options.");
2043 goto err;
2044 }
2045
2046 show_config_warning_message_box(&ps->o);
2047
2048 const char *basename = strrchr(argv[0], '/') ? strrchr(argv[0], '/') + 1 : argv[0];
2049
2050 if (strcmp(basename, "picom-inspect") == 0) {
2051 ps->o.backend = backend_find("dummy");
2052 ps->o.print_diagnostics = false;
2053 ps->o.dbus = false;
2054 if (!ps->o.inspect_monitor) {
2055 ps->o.inspect_win = inspect_select_window(&ps->c);
2056 }
2057 }
2058
2059 ps->window_options_default = win_options_from_config(&ps->o);
2060
2061 if (ps->o.window_shader_fg) {
2062 log_debug("Default window shader: \"%s\"",
2063 shader_spec_get_path(ps->o.window_shader_fg));
2064 }
2065
2066 if (ps->o.logpath) {
2067 auto l = file_logger_new(ps->o.logpath);
2068 if (l) {
2069 log_info("Switching to log file: %s", ps->o.logpath);
2070 if (stderr_logger) {
2071 log_remove_target_tls(stderr_logger);
2072 stderr_logger = NULL;
2073 }
2074 log_add_target_tls(l);
2075 stderr_logger = NULL;
2076 } else {
2077 log_error("Failed to setup log file %s, I will keep using stderr",
2078 ps->o.logpath);
2079 }
2080 }
2081
2082 if (strstr(argv[0], "compton")) {
2083 log_warn("This compositor has been renamed to \"picom\", the \"compton\" "
2084 "binary will not be installed in the future.");
2085 }
2086
2087 ps->atoms = init_atoms(ps->c.c);
2088 ps->c2_state = c2_state_new(ps->atoms);
2089
2090 // Get needed atoms for c2 condition lists
2091 options_postprocess_c2_lists(ps->c2_state, &ps->c, &ps->o);
2092
2093 // Load shader source file specified in the shader rules
2094 c2_condition_list_foreach(&ps->o.window_shader_fg_rules, i) {
2095 const struct shader_specification *spec = c2_condition_get_data(i);
2096 if (spec != NULL && load_shader_source(ps, spec) == NULL) {
2097 log_error("Failed to load shader source file for some of the "
2098 "window shader rules");
2099 }
2100 }
2101 if (ps->o.window_shader_fg != NULL &&
2102 load_shader_source(ps, ps->o.window_shader_fg) == NULL) {
2103 log_error("Failed to load window shader source file");
2104 }
2105 if (ps->o.root_pixmap_shader != NULL) {
2106 ps->root_pixmap_shader = load_shader_source(ps, ps->o.root_pixmap_shader);
2107 if (ps->root_pixmap_shader == NULL) {
2108 log_error("Failed to load root pixmap shader");
2109 }
2110 }
2111
2112 c2_condition_list_foreach(&ps->o.rules, i) {
2113 auto data = (struct window_maybe_options *)c2_condition_get_data(i);
2114 if (data->shader == NULL) {
2115 continue;
2116 }
2117 if (load_shader_source(ps, data->shader) == NULL) {
2118 log_error("Failed to load shader source file for window rules");
2119 }
2120 }
2121
2122 if (log_get_level_tls() <= LOG_LEVEL_DEBUG) {
2123 HASH_ITER2(ps->shaders, shader) {
2124 log_debug("Shader %s:", shader_spec_get_path(shader->spec));
2125 log_debug("%s", shader->source);
2126 }
2127 }
2128
2129 ps->sync_fence = XCB_NONE;
2130 if (ps->c.e.has_sync) {
2131 ps->sync_fence = x_new_id(&ps->c);
2132 e = xcb_request_check(
2133 ps->c.c, xcb_sync_create_fence_checked(
2134 ps->c.c, ps->c.screen_info->root, ps->sync_fence, 0));
2135 if (e) {
2136 if (ps->o.xrender_sync_fence) {
2137 log_error_x_error(&ps->c, e,
2138 "Failed to create a XSync fence. "
2139 "xrender-sync-fence will be "
2140 "disabled");
2141 ps->o.xrender_sync_fence = false;
2142 }
2143 ps->sync_fence = XCB_NONE;
2144 free(e);
2145 }
2146 } else if (ps->o.xrender_sync_fence) {
2147 log_error("XSync extension not found. No XSync fence sync is "
2148 "possible. (xrender-sync-fence can't be enabled)");
2149 ps->o.xrender_sync_fence = false;
2150 }
2151
2152 if (ps->o.crop_shadow_to_monitor && !ps->c.e.has_randr) {
2153 log_fatal("No X RandR extension. crop-shadow-to-monitor cannot be "
2154 "enabled.");
2155 goto err;
2156 }
2157
2158 bool compositor_running = false;
2159 if (session_redirection_mode(ps) == XCB_COMPOSITE_REDIRECT_MANUAL) {
2160 // We are running in the manual redirection mode, meaning we are running
2161 // as a proper compositor. So we need to register us as a compositor, etc.
2162
2163 // We are also here when --diagnostics is set. We want to be here because
2164 // that gives us more diagnostic information.
2165
2166 // Create registration window
2167 int ret = register_cm(ps);
2168 if (ret == -1) {
2169 goto err;
2170 }
2171
2172 compositor_running = ret == 1;
2173 }
2174
2175 ps->drivers = detect_driver(ps->c.c, ps->backend_data, ps->c.screen_info->root);
2176 apply_driver_workarounds(ps, ps->drivers);
2177
2178 if (ps->o.print_diagnostics) {
2179 ps->root_width = ps->c.screen_info->width_in_pixels;
2180 ps->root_height = ps->c.screen_info->height_in_pixels;
2181 print_diagnostics(ps, config_file, compositor_running);
2182 exit(0);
2183 }
2184
2185 if (ps->o.config_file_path) {
2186 ps->file_watch_handle = file_watch_init(ps->loop);
2187 if (ps->file_watch_handle) {
2188 file_watch_add(ps->file_watch_handle, ps->o.config_file_path,
2189 config_file_change_cb, ps);
2190 list_foreach(struct included_config_file, i,
2191 &ps->o.included_config_files, siblings) {
2192 file_watch_add(ps->file_watch_handle, i->path,
2193 config_file_change_cb, ps);
2194 }
2195 }
2196 }
2197
2198 // Monitor screen changes if vsync_sw is enabled and we are using
2199 // an auto-detected refresh rate, or when X RandR features are enabled
2200 if (ps->c.e.has_randr) {
2201 xcb_randr_select_input(ps->c.c, ps->c.screen_info->root,
2202 XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE);
2203 x_update_monitors_async(&ps->c, &ps->monitors);
2204 }
2205
2206 ev_io_init(&ps->xiow, x_event_callback, ConnectionNumber(ps->c.dpy), EV_READ);
2207 ev_io_start(ps->loop, &ps->xiow);
2208 ev_init(&ps->unredir_timer, tmout_unredir_callback);
2209 ev_init(&ps->draw_timer, draw_callback);
2210
2211 // Set up SIGUSR1 signal handler to reset program
2212 ev_signal_init(&ps->usr1_signal, reset_enable, SIGUSR1);
2213 ev_signal_init(&ps->int_signal, exit_enable, SIGINT);
2214 ev_signal_start(ps->loop, &ps->usr1_signal);
2215 ev_signal_start(ps->loop, &ps->int_signal);
2216
2217 // xcb can read multiple events from the socket when a request with reply is
2218 // made.
2219 //
2220 // Use an ev_prepare to make sure we cannot accidentally forget to handle them
2221 // before we go to sleep.
2222 //
2223 // If we don't drain the queue before goes to sleep (i.e. blocking on socket
2224 // input), we will be sleeping with events available in queue. Which might
2225 // cause us to block indefinitely because arrival of new events could be
2226 // dependent on processing of existing events (e.g. if we don't process damage
2227 // event and do damage subtract, new damage event won't be generated).
2228 //
2229 // So we make use of a ev_prepare handle, which is called right before libev
2230 // goes into sleep, to handle all the queued X events.
2231 ev_prepare_init(&ps->event_check, handle_x_events_ev);
2232 // Make sure nothing can cause xcb to read from the X socket after events are
2233 // handled and before we going to sleep.
2234 ev_set_priority(&ps->event_check, EV_MINPRI);
2235 ev_prepare_start(ps->loop, &ps->event_check);
2236
2237 // Initialize DBus. We need to do this early, because add_win might call dbus
2238 // functions
2239 if (ps->o.dbus) {
2240 #ifdef CONFIG_DBUS
2241 ps->dbus_data = cdbus_init(ps, DisplayString(ps->c.dpy));
2242 if (!ps->dbus_data) {
2243 ps->o.dbus = false;
2244 }
2245 #else
2246 log_fatal("DBus support not compiled in!");
2247 exit(1);
2248 #endif
2249 }
2250
2251 ps->wm = wm_new();
2252 wm_import_start(ps->wm, &ps->c, ps->atoms, ps->c.screen_info->root, NULL);
2253
2254 ps->command_builder = command_builder_new();
2255
2256 // wm_complete_import will set event masks on the root window, but its event
2257 // mask is missing things we need, so we need to set it again.
2258 e = xcb_request_check(
2259 ps->c.c, xcb_change_window_attributes_checked(
2260 ps->c.c, ps->c.screen_info->root, XCB_CW_EVENT_MASK,
2261 (const uint32_t[]){XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
2262 XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY |
2263 XCB_EVENT_MASK_PROPERTY_CHANGE}));
2264 if (e) {
2265 log_error_x_error(&ps->c, e, "Failed to setup root window event mask");
2266 free(e);
2267 goto err;
2268 }
2269
2270 // Query the size of the root window. We need the size information before any
2271 // window can be managed.
2272 auto r = XCB_AWAIT(xcb_get_geometry, &ps->c, ps->c.screen_info->root);
2273 if (!r) {
2274 log_fatal("Failed to get geometry of the root window");
2275 goto err;
2276 }
2277 ps->root_width = r->width;
2278 ps->root_height = r->height;
2279 free(r);
2280 rebuild_screen_reg(ps);
2281
2282 if (session_redirection_mode(ps) == XCB_COMPOSITE_REDIRECT_MANUAL && compositor_running) {
2283 // Don't take the overlay when there is another compositor
2284 // running, so we don't disrupt it.
2285
2286 // If we are printing diagnostic, we will continue a bit further
2287 // to get more diagnostic information, otherwise we will exit.
2288 log_fatal("Another composite manager is already running");
2289 goto err;
2290 }
2291
2292 if (session_redirection_mode(ps) == XCB_COMPOSITE_REDIRECT_MANUAL && !init_overlay(ps)) {
2293 goto err;
2294 }
2295
2296 if (session_redirection_mode(ps) == XCB_COMPOSITE_REDIRECT_AUTOMATIC) {
2297 // We are here if we don't really function as a compositor, so we are not
2298 // taking over the screen, and we don't need to register as a compositor
2299
2300 // We still need to know what the overlay window is, so we won't be
2301 // confused when we get events for the overlay window. Since
2302 // CompositeGetOverlayWindow also maps the overlay, we need to immediately
2303 // release it.
2304 auto get_overlay =
2305 xcb_composite_get_overlay_window(ps->c.c, ps->c.screen_info->root);
2306 XCB_AWAIT_VOID(xcb_composite_release_overlay_window, &ps->c,
2307 ps->c.screen_info->root);
2308 auto overlay_reply =
2309 xcb_composite_get_overlay_window_reply(ps->c.c, get_overlay, NULL);
2310 if (overlay_reply) {
2311 ps->overlay = overlay_reply->overlay_win;
2312 free(overlay_reply);
2313 }
2314
2315 // If we are in debug mode, we need to create a window for rendering if
2316 // the backend supports presenting.
2317
2318 // The old backends doesn't have a automatic redirection mode
2319 log_info("The compositor is started in automatic redirection mode.");
2320
2321 if (backend_can_present(ps->o.backend)) {
2322 // If the backend has `present`, we couldn't be in automatic
2323 // redirection mode unless we are in debug mode.
2324 assert(ps->o.debug_mode);
2325 if (!init_debug_window(ps)) {
2326 goto err;
2327 }
2328 }
2329 }
2330
2331 ps->pending_updates = true;
2332
2333 write_pid(ps);
2334
2335 if (fork && stderr_logger) {
2336 // Remove the stderr logger if we will fork
2337 log_remove_target_tls(stderr_logger);
2338 }
2339 return ps;
2340 err:
2341 render_statistics_destroy(&ps->render_stats);
2342 options_destroy(&ps->o);
2343 free(ps);
2344 return NULL;
2345 }
2346
2347 // NOLINTEND(readability-function-cognitive-complexity)
2348
2349 /**
2350 * Destroy a session.
2351 *
2352 * Does not close the X connection or free the <code>session_t</code>
2353 * structure, though.
2354 *
2355 * @param ps session to destroy
2356 */
2357 static void session_destroy(session_t *ps) {
2358 if (ps->redirected) {
2359 unredirect(ps);
2360 }
2361 command_builder_free(ps->command_builder);
2362 ps->command_builder = NULL;
2363
2364 if (ps->file_watch_handle) {
2365 file_watch_destroy(ps->loop, ps->file_watch_handle);
2366 ps->file_watch_handle = NULL;
2367 }
2368
2369 // Stop listening to events on root window
2370 xcb_change_window_attributes(ps->c.c, ps->c.screen_info->root, XCB_CW_EVENT_MASK,
2371 (const uint32_t[]){0});
2372
2373 #ifdef CONFIG_DBUS
2374 // Kill DBus connection
2375 if (ps->o.dbus) {
2376 assert(ps->dbus_data);
2377 cdbus_destroy(ps->dbus_data);
2378 ps->dbus_data = NULL;
2379 }
2380 #endif
2381
2382 wm_stack_foreach(ps->wm, cursor) {
2383 auto w = wm_ref_deref(cursor);
2384 if (w != NULL) {
2385 free_win_res(ps, w);
2386 }
2387 }
2388
2389 // Free blacklists
2390 options_destroy(&ps->o);
2391 c2_state_free(ps->c2_state);
2392
2393 pixman_region32_fini(&ps->screen_reg);
2394
2395 x_free_monitor_info(&ps->monitors);
2396
2397 render_statistics_destroy(&ps->render_stats);
2398
2399 // Release custom window shaders
2400 struct shader_info *shader, *tmp;
2401 HASH_ITER(hh, ps->shaders, shader, tmp) {
2402 HASH_DEL(ps->shaders, shader);
2403 assert(shader->backend_shader == NULL);
2404 free(shader);
2405 }
2406 HASH_ITER2(ps->shader_sources, source) {
2407 HASH_DEL(ps->shader_sources, source);
2408 free((void *)source->source);
2409 free(source);
2410 }
2411
2412 // Release overlay window
2413 if (ps->overlay && session_redirection_mode(ps) == XCB_COMPOSITE_REDIRECT_MANUAL) {
2414 xcb_composite_release_overlay_window(ps->c.c, ps->overlay);
2415 ps->overlay = XCB_NONE;
2416 }
2417
2418 if (ps->sync_fence != XCB_NONE) {
2419 xcb_sync_destroy_fence(ps->c.c, ps->sync_fence);
2420 ps->sync_fence = XCB_NONE;
2421 }
2422
2423 // Free reg_win
2424 if (ps->reg_win != XCB_NONE) {
2425 xcb_destroy_window(ps->c.c, ps->reg_win);
2426 ps->reg_win = XCB_NONE;
2427 }
2428
2429 if (ps->debug_window != XCB_NONE) {
2430 xcb_destroy_window(ps->c.c, ps->debug_window);
2431 ps->debug_window = XCB_NONE;
2432 }
2433
2434 if (ps->x_region != XCB_NONE) {
2435 xcb_xfixes_destroy_region(ps->c.c, ps->x_region);
2436 ps->x_region = XCB_NONE;
2437 }
2438
2439 // backend is deinitialized in unredirect()
2440 assert(ps->backend_data == NULL);
2441
2442 // Flush all events
2443 xcb_aux_sync(ps->c.c);
2444 ev_io_stop(ps->loop, &ps->xiow);
2445 destroy_atoms(ps->atoms);
2446
2447 // Stop libev event handlers
2448 ev_timer_stop(ps->loop, &ps->unredir_timer);
2449 ev_timer_stop(ps->loop, &ps->draw_timer);
2450 ev_prepare_stop(ps->loop, &ps->event_check);
2451 ev_signal_stop(ps->loop, &ps->usr1_signal);
2452 ev_signal_stop(ps->loop, &ps->int_signal);
2453
2454 // The X connection could hold references to wm if there are pending async
2455 // requests. Therefore the wm must be freed after the X connection.
2456 free_x_connection(&ps->c);
2457 wm_free(ps->wm);
2458 }
2459
2460 /**
2461 * Do the actual work.
2462 *
2463 * @param ps current session
2464 */
2465 static void session_run(session_t *ps) {
2466 if (ps->o.use_realtime_scheduling) {
2467 set_rr_scheduling();
2468 }
2469
2470 // In benchmark mode, we want draw_timer handler to always be active
2471 if (ps->o.benchmark) {
2472 ps->render_queued = true;
2473 ev_timer_set(&ps->draw_timer, 0, 0);
2474 ev_timer_start(ps->loop, &ps->draw_timer);
2475 } else {
2476 // Let's draw our first frame!
2477 queue_redraw(ps);
2478 }
2479 ev_run(ps->loop, 0);
2480 }
2481
2482 #ifdef CONFIG_FUZZER
2483 #define PICOM_MAIN(...) no_main(__VA_ARGS__)
2484 #else
2485 #define PICOM_MAIN(...) main(__VA_ARGS__)
2486 #endif
2487
2488 /// Early initialization of logging system. To catch early logs, especially
2489 /// from backend entrypoint functions.
2490 static void __attribute__((constructor(201))) init_early_logging(void) {
2491 log_init_tls();
2492 log_set_level_tls(LOG_LEVEL_WARN);
2493
2494 auto stderr_logger = stderr_logger_new();
2495 if (stderr_logger != NULL) {
2496 log_add_target_tls(stderr_logger);
2497 }
2498 }
2499
2500 /**
2501 * The function that everybody knows.
2502 */
2503 int PICOM_MAIN(int argc, char **argv) {
2504 // Set locale so window names with special characters are interpreted
2505 // correctly
2506 setlocale(LC_ALL, "");
2507
2508 parse_debug_options(&global_debug_options);
2509
2510 int exit_code;
2511 char *config_file = NULL;
2512 bool all_xerrors = false, need_fork = false;
2513 if (get_early_config(argc, argv, &config_file, &all_xerrors, &need_fork, &exit_code)) {
2514 return exit_code;
2515 }
2516
2517 int pfds[2];
2518 if (need_fork) {
2519 if (pipe2(pfds, O_CLOEXEC)) {
2520 perror("pipe2");
2521 return 1;
2522 }
2523 auto pid = fork();
2524 if (pid < 0) {
2525 perror("fork");
2526 return 1;
2527 }
2528 if (pid > 0) {
2529 // We are the parent
2530 close(pfds[1]);
2531 // We wait for the child to tell us it has finished initialization
2532 // by sending us something via the pipe.
2533 int tmp;
2534 if (read(pfds[0], &tmp, sizeof tmp) <= 0) {
2535 // Failed to read, the child has most likely died
2536 // We can probably waitpid() here.
2537 return 1;
2538 }
2539 // We are done
2540 return 0;
2541 }
2542 // We are the child
2543 close(pfds[0]);
2544 }
2545
2546 // Main loop
2547 bool quit = false;
2548 int ret_code = 0;
2549 char *pid_file = NULL;
2550
2551 do {
2552 Display *dpy = XOpenDisplay(NULL);
2553 if (!dpy) {
2554 log_fatal("Can't open display.");
2555 ret_code = 1;
2556 break;
2557 }
2558 XSetEventQueueOwner(dpy, XCBOwnsEventQueue);
2559
2560 // Reinit logging system so we don't get leftovers from previous sessions
2561 // or early logging.
2562 log_deinit_tls();
2563 log_init_tls();
2564
2565 ps_g = session_init(argc, argv, dpy, config_file, all_xerrors, need_fork);
2566 if (!ps_g) {
2567 log_fatal("Failed to create new session.");
2568 ret_code = 1;
2569 quit = true;
2570 goto end;
2571 }
2572 if (need_fork) {
2573 // Finishing up daemonization
2574 // Close files
2575 if (fclose(stdout) || fclose(stderr) || fclose(stdin)) {
2576 log_fatal("Failed to close standard input/output");
2577 ret_code = 1;
2578 break;
2579 }
2580 // Make us the session and process group leader so we don't get
2581 // killed when our parent die.
2582 setsid();
2583 // Notify the parent that we are done. This might cause the parent
2584 // to quit, so only do this after setsid()
2585 int tmp = 1;
2586 if (write(pfds[1], &tmp, sizeof tmp) != sizeof tmp) {
2587 log_fatal("Failed to notify parent process");
2588 ret_code = 1;
2589 break;
2590 }
2591 close(pfds[1]);
2592 // We only do this once
2593 need_fork = false;
2594 }
2595 session_run(ps_g);
2596 quit = ps_g->quit;
2597 if (quit && ps_g->o.write_pid_path) {
2598 pid_file = strdup(ps_g->o.write_pid_path);
2599 }
2600 session_destroy(ps_g);
2601 free(ps_g);
2602 ps_g = NULL;
2603 end:
2604 if (dpy) {
2605 XCloseDisplay(dpy);
2606 }
2607 } while (!quit);
2608
2609 free(config_file);
2610 if (pid_file) {
2611 log_trace("remove pid file %s", pid_file);
2612 unlink(pid_file);
2613 free(pid_file);
2614 }
2615
2616 log_deinit_tls();
2617
2618 return ret_code;
2619 }
2620
2621 #ifdef UNIT_TEST
2622 static void unittest_setup(void) {
2623 log_init_tls();
2624 // log_add_target_tls(stderr_logger_new());
2625 }
2626 void (*test_h_unittest_setup)(void) = unittest_setup;
2627 #endif