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