]> git.sur5r.net Git - i3/i3/blob - src/main.c
Merge branch 'release-4.16.1'
[i3/i3] / src / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * main.c: Initialization, main loop
8  *
9  */
10 #include "all.h"
11
12 #include <ev.h>
13 #include <fcntl.h>
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <sys/un.h>
17 #include <sys/time.h>
18 #include <sys/resource.h>
19 #include <sys/mman.h>
20 #include <sys/stat.h>
21 #include <libgen.h>
22 #include "shmlog.h"
23
24 #ifdef I3_ASAN_ENABLED
25 #include <sanitizer/lsan_interface.h>
26 #endif
27
28 #include "sd-daemon.h"
29
30 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
31  * this before starting any other process, since we set RLIMIT_CORE to
32  * RLIM_INFINITY for i3 debugging versions. */
33 struct rlimit original_rlimit_core;
34
35 /* The number of file descriptors passed via socket activation. */
36 int listen_fds;
37
38 /* We keep the xcb_prepare watcher around to be able to enable and disable it
39  * temporarily for drag_pointer(). */
40 static struct ev_prepare *xcb_prepare;
41
42 char **start_argv;
43
44 xcb_connection_t *conn;
45 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
46 int conn_screen;
47
48 /* Display handle for libstartup-notification */
49 SnDisplay *sndisplay;
50
51 /* The last timestamp we got from X11 (timestamps are included in some events
52  * and are used for some things, like determining a unique ID in startup
53  * notification). */
54 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
55
56 xcb_screen_t *root_screen;
57 xcb_window_t root;
58
59 /* Color depth, visual id and colormap to use when creating windows and
60  * pixmaps. Will use 32 bit depth and an appropriate visual, if available,
61  * otherwise the root window’s default (usually 24 bit TrueColor). */
62 uint8_t root_depth;
63 xcb_visualtype_t *visual_type;
64 xcb_colormap_t colormap;
65
66 struct ev_loop *main_loop;
67
68 xcb_key_symbols_t *keysyms;
69
70 /* Default shmlog size if not set by user. */
71 const int default_shmlog_size = 25 * 1024 * 1024;
72
73 /* The list of key bindings */
74 struct bindings_head *bindings;
75
76 /* The list of exec-lines */
77 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
78
79 /* The list of exec_always lines */
80 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
81
82 /* The list of assignments */
83 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
84
85 /* The list of workspace assignments (which workspace should end up on which
86  * output) */
87 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
88
89 /* We hope that those are supported and set them to true */
90 bool xcursor_supported = true;
91 bool xkb_supported = true;
92
93 bool force_xinerama = false;
94
95 /*
96  * This callback is only a dummy, see xcb_prepare_cb.
97  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
98  *
99  */
100 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
101     /* empty, because xcb_prepare_cb are used */
102 }
103
104 /*
105  * Called just before the event loop sleeps. Ensures xcb’s incoming and outgoing
106  * queues are empty so that any activity will trigger another event loop
107  * iteration, and hence another xcb_prepare_cb invocation.
108  *
109  */
110 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
111     /* Process all queued (and possibly new) events before the event loop
112        sleeps. */
113     xcb_generic_event_t *event;
114
115     while ((event = xcb_poll_for_event(conn)) != NULL) {
116         if (event->response_type == 0) {
117             if (event_is_ignored(event->sequence, 0))
118                 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
119             else {
120                 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
121                 DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
122                      error->sequence, error->error_code);
123             }
124             free(event);
125             continue;
126         }
127
128         /* Strip off the highest bit (set if the event is generated) */
129         int type = (event->response_type & 0x7F);
130
131         handle_event(type, event);
132
133         free(event);
134     }
135
136     /* Flush all queued events to X11. */
137     xcb_flush(conn);
138 }
139
140 /*
141  * Enable or disable the main X11 event handling function.
142  * This is used by drag_pointer() which has its own, modal event handler, which
143  * takes precedence over the normal event handler.
144  *
145  */
146 void main_set_x11_cb(bool enable) {
147     DLOG("Setting main X11 callback to enabled=%d\n", enable);
148     if (enable) {
149         ev_prepare_start(main_loop, xcb_prepare);
150         /* Trigger the watcher explicitly to handle all remaining X11 events.
151          * drag_pointer()’s event handler exits in the middle of the loop. */
152         ev_feed_event(main_loop, xcb_prepare, 0);
153     } else {
154         ev_prepare_stop(main_loop, xcb_prepare);
155     }
156 }
157
158 /*
159  * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
160  *
161  */
162 static void i3_exit(void) {
163     if (*shmlogname != '\0') {
164         fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
165         fflush(stderr);
166         shm_unlink(shmlogname);
167     }
168     ipc_shutdown(SHUTDOWN_REASON_EXIT);
169     unlink(config.ipc_socket_path);
170     xcb_disconnect(conn);
171
172 /* We need ev >= 4 for the following code. Since it is not *that* important (it
173  * only makes sure that there are no i3-nagbar instances left behind) we still
174  * support old systems with libev 3. */
175 #if EV_VERSION_MAJOR >= 4
176     ev_loop_destroy(main_loop);
177 #endif
178
179 #ifdef I3_ASAN_ENABLED
180     __lsan_do_leak_check();
181 #endif
182 }
183
184 /*
185  * (One-shot) Handler for all signals with default action "Core", see signal(7)
186  *
187  * Unlinks the SHM log and re-raises the signal.
188  *
189  */
190 static void handle_core_signal(int sig, siginfo_t *info, void *data) {
191     if (*shmlogname != '\0') {
192         shm_unlink(shmlogname);
193     }
194     raise(sig);
195 }
196
197 /*
198  * (One-shot) Handler for all signals with default action "Term", see signal(7)
199  *
200  * Exits the program gracefully.
201  *
202  */
203 static void handle_term_signal(struct ev_loop *loop, ev_signal *signal, int revents) {
204     /* We exit gracefully here in the sense that cleanup handlers
205      * installed via atexit are invoked. */
206     exit(128 + signal->signum);
207 }
208
209 /*
210  * Set up handlers for all signals with default action "Term", see signal(7)
211  *
212  */
213 static void setup_term_handlers(void) {
214     static struct ev_signal signal_watchers[6];
215     size_t num_watchers = sizeof(signal_watchers) / sizeof(signal_watchers[0]);
216
217     /* We have to rely on libev functionality here and should not use
218      * sigaction handlers because we need to invoke the exit handlers
219      * and cannot do so from an asynchronous signal handling context as
220      * not all code triggered during exit is signal safe (and exiting
221      * the main loop from said handler is not easily possible). libev's
222      * signal handlers does not impose such a constraint on us. */
223     ev_signal_init(&signal_watchers[0], handle_term_signal, SIGHUP);
224     ev_signal_init(&signal_watchers[1], handle_term_signal, SIGINT);
225     ev_signal_init(&signal_watchers[2], handle_term_signal, SIGALRM);
226     ev_signal_init(&signal_watchers[3], handle_term_signal, SIGTERM);
227     ev_signal_init(&signal_watchers[4], handle_term_signal, SIGUSR1);
228     ev_signal_init(&signal_watchers[5], handle_term_signal, SIGUSR1);
229     for (size_t i = 0; i < num_watchers; i++) {
230         ev_signal_start(main_loop, &signal_watchers[i]);
231         /* The signal handlers should not block ev_run from returning
232          * and so none of the signal handlers should hold a reference to
233          * the main loop. */
234         ev_unref(main_loop);
235     }
236 }
237
238 int main(int argc, char *argv[]) {
239     /* Keep a symbol pointing to the I3_VERSION string constant so that we have
240      * it in gdb backtraces. */
241     static const char *_i3_version __attribute__((used)) = I3_VERSION;
242     char *override_configpath = NULL;
243     bool autostart = true;
244     char *layout_path = NULL;
245     bool delete_layout_path = false;
246     bool disable_randr15 = false;
247     char *fake_outputs = NULL;
248     bool disable_signalhandler = false;
249     bool only_check_config = false;
250     static struct option long_options[] = {
251         {"no-autostart", no_argument, 0, 'a'},
252         {"config", required_argument, 0, 'c'},
253         {"version", no_argument, 0, 'v'},
254         {"moreversion", no_argument, 0, 'm'},
255         {"more-version", no_argument, 0, 'm'},
256         {"more_version", no_argument, 0, 'm'},
257         {"help", no_argument, 0, 'h'},
258         {"layout", required_argument, 0, 'L'},
259         {"restart", required_argument, 0, 0},
260         {"force-xinerama", no_argument, 0, 0},
261         {"force_xinerama", no_argument, 0, 0},
262         {"disable-randr15", no_argument, 0, 0},
263         {"disable_randr15", no_argument, 0, 0},
264         {"disable-signalhandler", no_argument, 0, 0},
265         {"shmlog-size", required_argument, 0, 0},
266         {"shmlog_size", required_argument, 0, 0},
267         {"get-socketpath", no_argument, 0, 0},
268         {"get_socketpath", no_argument, 0, 0},
269         {"fake_outputs", required_argument, 0, 0},
270         {"fake-outputs", required_argument, 0, 0},
271         {"force-old-config-parser-v4.4-only", no_argument, 0, 0},
272         {0, 0, 0, 0}};
273     int option_index = 0, opt;
274
275     setlocale(LC_ALL, "");
276
277     /* Get the RLIMIT_CORE limit at startup time to restore this before
278      * starting processes. */
279     getrlimit(RLIMIT_CORE, &original_rlimit_core);
280
281     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
282     if (!isatty(fileno(stdout)))
283         setbuf(stdout, NULL);
284
285     srand(time(NULL));
286
287     /* Init logging *before* initializing debug_build to guarantee early
288      * (file) logging. */
289     init_logging();
290
291     /* On release builds, disable SHM logging by default. */
292     shmlog_size = (is_debug_build() || strstr(argv[0], "i3-with-shmlog") != NULL ? default_shmlog_size : 0);
293
294     start_argv = argv;
295
296     while ((opt = getopt_long(argc, argv, "c:CvmaL:hld:V", long_options, &option_index)) != -1) {
297         switch (opt) {
298             case 'a':
299                 LOG("Autostart disabled using -a\n");
300                 autostart = false;
301                 break;
302             case 'L':
303                 FREE(layout_path);
304                 layout_path = sstrdup(optarg);
305                 delete_layout_path = false;
306                 break;
307             case 'c':
308                 FREE(override_configpath);
309                 override_configpath = sstrdup(optarg);
310                 break;
311             case 'C':
312                 LOG("Checking configuration file only (-C)\n");
313                 only_check_config = true;
314                 break;
315             case 'v':
316                 printf("i3 version %s © 2009 Michael Stapelberg and contributors\n", i3_version);
317                 exit(EXIT_SUCCESS);
318                 break;
319             case 'm':
320                 printf("Binary i3 version:  %s © 2009 Michael Stapelberg and contributors\n", i3_version);
321                 display_running_version();
322                 exit(EXIT_SUCCESS);
323                 break;
324             case 'V':
325                 set_verbosity(true);
326                 break;
327             case 'd':
328                 LOG("Enabling debug logging\n");
329                 set_debug_logging(true);
330                 break;
331             case 'l':
332                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
333                 break;
334             case 0:
335                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
336                     strcmp(long_options[option_index].name, "force_xinerama") == 0) {
337                     force_xinerama = true;
338                     ELOG("Using Xinerama instead of RandR. This option should be "
339                          "avoided at all cost because it does not refresh the list "
340                          "of screens, so you cannot configure displays at runtime. "
341                          "Please check if your driver really does not support RandR "
342                          "and disable this option as soon as you can.\n");
343                     break;
344                 } else if (strcmp(long_options[option_index].name, "disable-randr15") == 0 ||
345                            strcmp(long_options[option_index].name, "disable_randr15") == 0) {
346                     disable_randr15 = true;
347                     break;
348                 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
349                     disable_signalhandler = true;
350                     break;
351                 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
352                            strcmp(long_options[option_index].name, "get_socketpath") == 0) {
353                     char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
354                     if (socket_path) {
355                         printf("%s\n", socket_path);
356                         exit(EXIT_SUCCESS);
357                     }
358
359                     exit(EXIT_FAILURE);
360                 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
361                            strcmp(long_options[option_index].name, "shmlog_size") == 0) {
362                     shmlog_size = atoi(optarg);
363                     /* Re-initialize logging immediately to get as many
364                      * logmessages as possible into the SHM log. */
365                     init_logging();
366                     LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
367                     break;
368                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
369                     FREE(layout_path);
370                     layout_path = sstrdup(optarg);
371                     delete_layout_path = true;
372                     break;
373                 } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
374                            strcmp(long_options[option_index].name, "fake_outputs") == 0) {
375                     LOG("Initializing fake outputs: %s\n", optarg);
376                     fake_outputs = sstrdup(optarg);
377                     break;
378                 } else if (strcmp(long_options[option_index].name, "force-old-config-parser-v4.4-only") == 0) {
379                     ELOG("You are passing --force-old-config-parser-v4.4-only, but that flag was removed by now.\n");
380                     break;
381                 }
382             /* fall-through */
383             default:
384                 fprintf(stderr, "Usage: %s [-c configfile] [-d all] [-a] [-v] [-V] [-C]\n", argv[0]);
385                 fprintf(stderr, "\n");
386                 fprintf(stderr, "\t-a          disable autostart ('exec' lines in config)\n");
387                 fprintf(stderr, "\t-c <file>   use the provided configfile instead\n");
388                 fprintf(stderr, "\t-C          validate configuration file and exit\n");
389                 fprintf(stderr, "\t-d all      enable debug output\n");
390                 fprintf(stderr, "\t-L <file>   path to the serialized layout during restarts\n");
391                 fprintf(stderr, "\t-v          display version and exit\n");
392                 fprintf(stderr, "\t-V          enable verbose mode\n");
393                 fprintf(stderr, "\n");
394                 fprintf(stderr, "\t--force-xinerama\n"
395                                 "\tUse Xinerama instead of RandR.\n"
396                                 "\tThis option should only be used if you are stuck with the\n"
397                                 "\told nVidia closed source driver (older than 302.17), which does\n"
398                                 "\tnot support RandR.\n");
399                 fprintf(stderr, "\n");
400                 fprintf(stderr, "\t--get-socketpath\n"
401                                 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
402                 fprintf(stderr, "\n");
403                 fprintf(stderr, "\t--shmlog-size <limit>\n"
404                                 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
405                                 "\tto 0 disables SHM logging entirely.\n"
406                                 "\tThe default is %d bytes.\n",
407                         shmlog_size);
408                 fprintf(stderr, "\n");
409                 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
410                                 "to send to a currently running i3 (like i3-msg). This allows you to\n"
411                                 "use nice and logical commands, such as:\n"
412                                 "\n"
413                                 "\ti3 border none\n"
414                                 "\ti3 floating toggle\n"
415                                 "\ti3 kill window\n"
416                                 "\n");
417                 exit(EXIT_FAILURE);
418         }
419     }
420
421     if (only_check_config) {
422         exit(parse_configuration(override_configpath, false) ? 0 : 1);
423     }
424
425     /* If the user passes more arguments, we act like i3-msg would: Just send
426      * the arguments as an IPC message to i3. This allows for nice semantic
427      * commands such as 'i3 border none'. */
428     if (optind < argc) {
429         /* We enable verbose mode so that the user knows what’s going on.
430          * This should make it easier to find mistakes when the user passes
431          * arguments by mistake. */
432         set_verbosity(true);
433
434         LOG("Additional arguments passed. Sending them as a command to i3.\n");
435         char *payload = NULL;
436         while (optind < argc) {
437             if (!payload) {
438                 payload = sstrdup(argv[optind]);
439             } else {
440                 char *both;
441                 sasprintf(&both, "%s %s", payload, argv[optind]);
442                 free(payload);
443                 payload = both;
444             }
445             optind++;
446         }
447         DLOG("Command is: %s (%zd bytes)\n", payload, strlen(payload));
448         char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
449         if (!socket_path) {
450             ELOG("Could not get i3 IPC socket path\n");
451             return 1;
452         }
453
454         int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
455         if (sockfd == -1)
456             err(EXIT_FAILURE, "Could not create socket");
457
458         struct sockaddr_un addr;
459         memset(&addr, 0, sizeof(struct sockaddr_un));
460         addr.sun_family = AF_LOCAL;
461         strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
462         FREE(socket_path);
463         if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
464             err(EXIT_FAILURE, "Could not connect to i3");
465
466         if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_RUN_COMMAND,
467                              (uint8_t *)payload) == -1)
468             err(EXIT_FAILURE, "IPC: write()");
469         FREE(payload);
470
471         uint32_t reply_length;
472         uint32_t reply_type;
473         uint8_t *reply;
474         int ret;
475         if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
476             if (ret == -1)
477                 err(EXIT_FAILURE, "IPC: read()");
478             return 1;
479         }
480         if (reply_type != I3_IPC_REPLY_TYPE_COMMAND)
481             errx(EXIT_FAILURE, "IPC: received reply of type %d but expected %d (COMMAND)", reply_type, I3_IPC_REPLY_TYPE_COMMAND);
482         printf("%.*s\n", reply_length, reply);
483         FREE(reply);
484         return 0;
485     }
486
487     /* Enable logging to handle the case when the user did not specify --shmlog-size */
488     init_logging();
489
490     /* Try to enable core dumps by default when running a debug build */
491     if (is_debug_build()) {
492         struct rlimit limit = {RLIM_INFINITY, RLIM_INFINITY};
493         setrlimit(RLIMIT_CORE, &limit);
494
495         /* The following code is helpful, but not required. We thus don’t pay
496          * much attention to error handling, non-linux or other edge cases. */
497         LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
498         size_t cwd_size = 1024;
499         char *cwd = smalloc(cwd_size);
500         char *cwd_ret;
501         while ((cwd_ret = getcwd(cwd, cwd_size)) == NULL && errno == ERANGE) {
502             cwd_size = cwd_size * 2;
503             cwd = srealloc(cwd, cwd_size);
504         }
505         if (cwd_ret != NULL)
506             LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
507         int patternfd;
508         if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
509             memset(cwd, '\0', cwd_size);
510             if (read(patternfd, cwd, cwd_size) > 0)
511                 /* a trailing newline is included in cwd */
512                 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
513             close(patternfd);
514         }
515         free(cwd);
516     }
517
518     LOG("i3 %s starting\n", i3_version);
519
520     conn = xcb_connect(NULL, &conn_screen);
521     if (xcb_connection_has_error(conn))
522         errx(EXIT_FAILURE, "Cannot open display\n");
523
524     sndisplay = sn_xcb_display_new(conn, NULL, NULL);
525
526     /* Initialize the libev event loop. This needs to be done before loading
527      * the config file because the parser will install an ev_child watcher
528      * for the nagbar when config errors are found. */
529     main_loop = EV_DEFAULT;
530     if (main_loop == NULL)
531         die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
532
533     root_screen = xcb_aux_get_screen(conn, conn_screen);
534     root = root_screen->root;
535
536 /* Place requests for the atoms we need as soon as possible */
537 #define xmacro(atom) \
538     xcb_intern_atom_cookie_t atom##_cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
539 #include "atoms.xmacro"
540 #undef xmacro
541
542     root_depth = root_screen->root_depth;
543     colormap = root_screen->default_colormap;
544     visual_type = xcb_aux_find_visual_by_attrs(root_screen, -1, 32);
545     if (visual_type != NULL) {
546         root_depth = xcb_aux_get_depth_of_visual(root_screen, visual_type->visual_id);
547         colormap = xcb_generate_id(conn);
548
549         xcb_void_cookie_t cm_cookie = xcb_create_colormap_checked(conn,
550                                                                   XCB_COLORMAP_ALLOC_NONE,
551                                                                   colormap,
552                                                                   root,
553                                                                   visual_type->visual_id);
554
555         xcb_generic_error_t *error = xcb_request_check(conn, cm_cookie);
556         if (error != NULL) {
557             ELOG("Could not create colormap. Error code: %d\n", error->error_code);
558             exit(EXIT_FAILURE);
559         }
560     } else {
561         visual_type = get_visualtype(root_screen);
562     }
563
564     init_dpi();
565
566     DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_type->visual_id);
567     DLOG("root_screen->height_in_pixels = %d, root_screen->height_in_millimeters = %d\n",
568          root_screen->height_in_pixels, root_screen->height_in_millimeters);
569     DLOG("One logical pixel corresponds to %d physical pixels on this display.\n", logical_px(1));
570
571     xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
572     xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
573
574 /* Setup NetWM atoms */
575 #define xmacro(name)                                                                       \
576     do {                                                                                   \
577         xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
578         if (!reply) {                                                                      \
579             ELOG("Could not get atom " #name "\n");                                        \
580             exit(-1);                                                                      \
581         }                                                                                  \
582         A_##name = reply->atom;                                                            \
583         free(reply);                                                                       \
584     } while (0);
585 #include "atoms.xmacro"
586 #undef xmacro
587
588     load_configuration(conn, override_configpath, false);
589
590     if (config.ipc_socket_path == NULL) {
591         /* Fall back to a file name in /tmp/ based on the PID */
592         if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
593             config.ipc_socket_path = get_process_filename("ipc-socket");
594         else
595             config.ipc_socket_path = sstrdup(config.ipc_socket_path);
596     }
597
598     if (config.force_xinerama) {
599         force_xinerama = true;
600     }
601
602     xcb_void_cookie_t cookie;
603     cookie = xcb_change_window_attributes_checked(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ROOT_EVENT_MASK});
604     xcb_generic_error_t *error = xcb_request_check(conn, cookie);
605     if (error != NULL) {
606         ELOG("Another window manager seems to be running (X error %d)\n", error->error_code);
607 #ifdef I3_ASAN_ENABLED
608         __lsan_do_leak_check();
609 #endif
610         return 1;
611     }
612
613     xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
614     if (greply == NULL) {
615         ELOG("Could not get geometry of the root window, exiting\n");
616         return 1;
617     }
618     DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
619
620     xcursor_load_cursors();
621
622     /* Set a cursor for the root window (otherwise the root window will show no
623        cursor until the first client is launched). */
624     if (xcursor_supported)
625         xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
626     else
627         xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
628
629     const xcb_query_extension_reply_t *extreply;
630     extreply = xcb_get_extension_data(conn, &xcb_xkb_id);
631     xkb_supported = extreply->present;
632     if (!extreply->present) {
633         DLOG("xkb is not present on this server\n");
634     } else {
635         DLOG("initializing xcb-xkb\n");
636         xcb_xkb_use_extension(conn, XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);
637         xcb_xkb_select_events(conn,
638                               XCB_XKB_ID_USE_CORE_KBD,
639                               XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
640                               0,
641                               XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
642                               0xff,
643                               0xff,
644                               NULL);
645
646         /* Setting both, XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE and
647          * XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED, will lead to the
648          * X server sending us the full XKB state in KeyPress and KeyRelease:
649          * https://cgit.freedesktop.org/xorg/xserver/tree/xkb/xkbEvents.c?h=xorg-server-1.20.0#n927
650          *
651          * XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT enable detectable autorepeat:
652          * https://www.x.org/releases/current/doc/kbproto/xkbproto.html#Detectable_Autorepeat
653          * This affects bindings using the --release flag: instead of getting multiple KeyRelease
654          * events we get only one event when the key is physically released by the user.
655          */
656         const uint32_t mask = XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE |
657                               XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED |
658                               XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT;
659         xcb_xkb_per_client_flags_reply_t *pcf_reply;
660         /* The last three parameters are unset because they are only relevant
661          * when using a feature called “automatic reset of boolean controls”:
662          * https://www.x.org/releases/X11R7.7/doc/kbproto/xkbproto.html#Automatic_Reset_of_Boolean_Controls
663          * */
664         pcf_reply = xcb_xkb_per_client_flags_reply(
665             conn,
666             xcb_xkb_per_client_flags(
667                 conn,
668                 XCB_XKB_ID_USE_CORE_KBD,
669                 mask,
670                 mask,
671                 0 /* uint32_t ctrlsToChange */,
672                 0 /* uint32_t autoCtrls */,
673                 0 /* uint32_t autoCtrlsValues */),
674             NULL);
675
676 #define PCF_REPLY_ERROR(_value)                                    \
677     do {                                                           \
678         if (pcf_reply == NULL || !(pcf_reply->value & (_value))) { \
679             ELOG("Could not set " #_value "\n");                   \
680         }                                                          \
681     } while (0)
682
683         PCF_REPLY_ERROR(XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE);
684         PCF_REPLY_ERROR(XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED);
685         PCF_REPLY_ERROR(XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT);
686
687         free(pcf_reply);
688         xkb_base = extreply->first_event;
689     }
690
691     restore_connect();
692
693     property_handlers_init();
694
695     ewmh_setup_hints();
696
697     keysyms = xcb_key_symbols_alloc(conn);
698
699     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
700
701     if (!load_keymap())
702         die("Could not load keymap\n");
703
704     translate_keysyms();
705     grab_all_keys(conn);
706
707     bool needs_tree_init = true;
708     if (layout_path != NULL) {
709         LOG("Trying to restore the layout from \"%s\".\n", layout_path);
710         needs_tree_init = !tree_restore(layout_path, greply);
711         if (delete_layout_path) {
712             unlink(layout_path);
713             const char *dir = dirname(layout_path);
714             /* possibly fails with ENOTEMPTY if there are files (or
715              * sockets) left. */
716             rmdir(dir);
717         }
718     }
719     if (needs_tree_init)
720         tree_init(greply);
721
722     free(greply);
723
724     /* Setup fake outputs for testing */
725     if (fake_outputs == NULL && config.fake_outputs != NULL)
726         fake_outputs = config.fake_outputs;
727
728     if (fake_outputs != NULL) {
729         fake_outputs_init(fake_outputs);
730         FREE(fake_outputs);
731         config.fake_outputs = NULL;
732     } else if (force_xinerama) {
733         /* Force Xinerama (for drivers which don't support RandR yet, esp. the
734          * nVidia binary graphics driver), when specified either in the config
735          * file or on command-line */
736         xinerama_init();
737     } else {
738         DLOG("Checking for XRandR...\n");
739         randr_init(&randr_base, disable_randr15 || config.disable_randr15);
740     }
741
742     /* We need to force disabling outputs which have been loaded from the
743      * layout file but are no longer active. This can happen if the output has
744      * been disabled in the short time between writing the restart layout file
745      * and restarting i3. See #2326. */
746     if (layout_path != NULL && randr_base > -1) {
747         Con *con;
748         TAILQ_FOREACH(con, &(croot->nodes_head), nodes) {
749             Output *output;
750             TAILQ_FOREACH(output, &outputs, outputs) {
751                 if (output->active || strcmp(con->name, output_primary_name(output)) != 0)
752                     continue;
753
754                 /* This will correctly correlate the output with its content
755                  * container. We need to make the connection to properly
756                  * disable the output. */
757                 if (output->con == NULL) {
758                     output_init_con(output);
759                     output->changed = false;
760                 }
761
762                 output->to_be_disabled = true;
763                 randr_disable_output(output);
764             }
765         }
766     }
767     FREE(layout_path);
768
769     scratchpad_fix_resolution();
770
771     xcb_query_pointer_reply_t *pointerreply;
772     Output *output = NULL;
773     if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
774         ELOG("Could not query pointer position, using first screen\n");
775     } else {
776         DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
777         output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
778         if (!output) {
779             ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
780                  pointerreply->root_x, pointerreply->root_y);
781             output = get_first_output();
782         }
783
784         con_activate(con_descend_focused(output_get_content(output->con)));
785         free(pointerreply);
786     }
787
788     tree_render();
789
790     /* Create the UNIX domain socket for IPC */
791     int ipc_socket = ipc_create_socket(config.ipc_socket_path);
792     if (ipc_socket == -1) {
793         ELOG("Could not create the IPC socket, IPC disabled\n");
794     } else {
795         struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
796         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
797         ev_io_start(main_loop, ipc_io);
798     }
799
800     /* Also handle the UNIX domain sockets passed via socket activation. The
801      * parameter 1 means "remove the environment variables", we don’t want to
802      * pass these to child processes. */
803     listen_fds = sd_listen_fds(0);
804     if (listen_fds < 0)
805         ELOG("socket activation: Error in sd_listen_fds\n");
806     else if (listen_fds == 0)
807         DLOG("socket activation: no sockets passed\n");
808     else {
809         int flags;
810         for (int fd = SD_LISTEN_FDS_START;
811              fd < (SD_LISTEN_FDS_START + listen_fds);
812              fd++) {
813             DLOG("socket activation: also listening on fd %d\n", fd);
814
815             /* sd_listen_fds() enables FD_CLOEXEC by default.
816              * However, we need to keep the file descriptors open for in-place
817              * restarting, therefore we explicitly disable FD_CLOEXEC. */
818             if ((flags = fcntl(fd, F_GETFD)) < 0 ||
819                 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
820                 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
821             }
822
823             struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
824             ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
825             ev_io_start(main_loop, ipc_io);
826         }
827     }
828
829     /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
830     x_set_i3_atoms();
831     ewmh_update_workarea();
832
833     /* Set the ewmh desktop properties. */
834     ewmh_update_current_desktop();
835     ewmh_update_number_of_desktops();
836     ewmh_update_desktop_names();
837     ewmh_update_desktop_viewport();
838
839     struct ev_io *xcb_watcher = scalloc(1, sizeof(struct ev_io));
840     xcb_prepare = scalloc(1, sizeof(struct ev_prepare));
841
842     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
843     ev_io_start(main_loop, xcb_watcher);
844
845     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
846     ev_prepare_start(main_loop, xcb_prepare);
847
848     xcb_flush(conn);
849
850     /* What follows is a fugly consequence of X11 protocol race conditions like
851      * the following: In an i3 in-place restart, i3 will reparent all windows
852      * to the root window, then exec() itself. In the new process, it calls
853      * manage_existing_windows. However, in case any application sent a
854      * generated UnmapNotify message to the WM (as GIMP does), this message
855      * will be handled by i3 *after* managing the window, thus i3 thinks the
856      * window just closed itself. In reality, the message was sent in the time
857      * period where i3 wasn’t running yet.
858      *
859      * To prevent this, we grab the server (disables processing of any other
860      * connections), then discard all pending events (since we didn’t do
861      * anything, there cannot be any meaningful responses), then ungrab the
862      * server. */
863     xcb_grab_server(conn);
864     {
865         xcb_aux_sync(conn);
866         xcb_generic_event_t *event;
867         while ((event = xcb_poll_for_event(conn)) != NULL) {
868             if (event->response_type == 0) {
869                 free(event);
870                 continue;
871             }
872
873             /* Strip off the highest bit (set if the event is generated) */
874             int type = (event->response_type & 0x7F);
875
876             /* We still need to handle MapRequests which are sent in the
877              * timespan starting from when we register as a window manager and
878              * this piece of code which drops events. */
879             if (type == XCB_MAP_REQUEST)
880                 handle_event(type, event);
881
882             free(event);
883         }
884         manage_existing_windows(root);
885     }
886     xcb_ungrab_server(conn);
887
888     if (autostart) {
889         LOG("This is not an in-place restart, copying root window contents to a pixmap\n");
890         xcb_screen_t *root = xcb_aux_get_screen(conn, conn_screen);
891         uint16_t width = root->width_in_pixels;
892         uint16_t height = root->height_in_pixels;
893         xcb_pixmap_t pixmap = xcb_generate_id(conn);
894         xcb_gcontext_t gc = xcb_generate_id(conn);
895
896         xcb_create_pixmap(conn, root->root_depth, pixmap, root->root, width, height);
897
898         xcb_create_gc(conn, gc, root->root,
899                       XCB_GC_FUNCTION | XCB_GC_PLANE_MASK | XCB_GC_FILL_STYLE | XCB_GC_SUBWINDOW_MODE,
900                       (uint32_t[]){XCB_GX_COPY, ~0, XCB_FILL_STYLE_SOLID, XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS});
901
902         xcb_copy_area(conn, root->root, pixmap, gc, 0, 0, 0, 0, width, height);
903         xcb_change_window_attributes(conn, root->root, XCB_CW_BACK_PIXMAP, (uint32_t[]){pixmap});
904         xcb_flush(conn);
905         xcb_free_gc(conn, gc);
906         xcb_free_pixmap(conn, pixmap);
907     }
908
909 #if defined(__OpenBSD__)
910     if (pledge("stdio rpath wpath cpath proc exec unix", NULL) == -1)
911         err(EXIT_FAILURE, "pledge");
912 #endif
913
914     if (!disable_signalhandler)
915         setup_signal_handler();
916     else {
917         struct sigaction action;
918
919         action.sa_sigaction = handle_core_signal;
920         action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
921         sigemptyset(&action.sa_mask);
922
923         /* Catch all signals with default action "Core", see signal(7) */
924         if (sigaction(SIGQUIT, &action, NULL) == -1 ||
925             sigaction(SIGILL, &action, NULL) == -1 ||
926             sigaction(SIGABRT, &action, NULL) == -1 ||
927             sigaction(SIGFPE, &action, NULL) == -1 ||
928             sigaction(SIGSEGV, &action, NULL) == -1)
929             ELOG("Could not setup signal handler.\n");
930     }
931
932     setup_term_handlers();
933     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
934      * while we are sending them a message */
935     signal(SIGPIPE, SIG_IGN);
936
937     /* Autostarting exec-lines */
938     if (autostart) {
939         while (!TAILQ_EMPTY(&autostarts)) {
940             struct Autostart *exec = TAILQ_FIRST(&autostarts);
941
942             LOG("auto-starting %s\n", exec->command);
943             start_application(exec->command, exec->no_startup_id);
944
945             FREE(exec->command);
946             TAILQ_REMOVE(&autostarts, exec, autostarts);
947             FREE(exec);
948         }
949     }
950
951     /* Autostarting exec_always-lines */
952     while (!TAILQ_EMPTY(&autostarts_always)) {
953         struct Autostart *exec_always = TAILQ_FIRST(&autostarts_always);
954
955         LOG("auto-starting (always!) %s\n", exec_always->command);
956         start_application(exec_always->command, exec_always->no_startup_id);
957
958         FREE(exec_always->command);
959         TAILQ_REMOVE(&autostarts_always, exec_always, autostarts_always);
960         FREE(exec_always);
961     }
962
963     /* Start i3bar processes for all configured bars */
964     Barconfig *barconfig;
965     TAILQ_FOREACH(barconfig, &barconfigs, configs) {
966         char *command = NULL;
967         sasprintf(&command, "%s %s --bar_id=%s --socket=\"%s\"",
968                   barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
969                   barconfig->verbose ? "-V" : "",
970                   barconfig->id, current_socketpath);
971         LOG("Starting bar process: %s\n", command);
972         start_application(command, true);
973         free(command);
974     }
975
976     /* Make sure to destroy the event loop to invoke the cleanup callbacks
977      * when calling exit() */
978     atexit(i3_exit);
979
980     ev_loop(main_loop, 0);
981 }