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