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