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