]> git.sur5r.net Git - i3/i3/blob - src/main.c
Merge branch 'master' into next
[i3/i3] / src / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * main.c: Initialization, main loop
8  *
9  */
10 #include <ev.h>
11 #include <fcntl.h>
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <sys/un.h>
15 #include <sys/time.h>
16 #include <sys/resource.h>
17 #include <sys/mman.h>
18 #include <sys/stat.h>
19 #include "all.h"
20
21 #include "sd-daemon.h"
22
23 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
24  * this before starting any other process, since we set RLIMIT_CORE to
25  * RLIM_INFINITY for i3 debugging versions. */
26 struct rlimit original_rlimit_core;
27
28 /* Whether this version of i3 is a debug build or a release build. */
29 bool debug_build = false;
30
31 /** The number of file descriptors passed via socket activation. */
32 int listen_fds;
33
34 static int xkb_event_base;
35
36 int xkb_current_group;
37
38 extern Con *focused;
39
40 char **start_argv;
41
42 xcb_connection_t *conn;
43 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
44 int conn_screen;
45
46 /* Display handle for libstartup-notification */
47 SnDisplay *sndisplay;
48
49 /* The last timestamp we got from X11 (timestamps are included in some events
50  * and are used for some things, like determining a unique ID in startup
51  * notification). */
52 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
53
54 xcb_screen_t *root_screen;
55 xcb_window_t root;
56
57 /* Color depth, visual id and colormap to use when creating windows and
58  * pixmaps. Will use 32 bit depth and an appropriate visual, if available,
59  * otherwise the root window’s default (usually 24 bit TrueColor). */
60 uint8_t root_depth;
61 xcb_visualid_t visual_id;
62 xcb_colormap_t colormap;
63
64 struct ev_loop *main_loop;
65
66 xcb_key_symbols_t *keysyms;
67
68 /* Those are our connections to X11 for use with libXcursor and XKB */
69 Display *xlibdpy, *xkbdpy;
70
71 /* The list of key bindings */
72 struct bindings_head *bindings;
73
74 /* The list of exec-lines */
75 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
76
77 /* The list of exec_always lines */
78 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
79
80 /* The list of assignments */
81 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
82
83 /* The list of workspace assignments (which workspace should end up on which
84  * output) */
85 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
86
87 /* We hope that those are supported and set them to true */
88 bool xcursor_supported = true;
89 bool xkb_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                 ELOG("X11 Error received! 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 /*
145  * When using xmodmap to change the keyboard mapping, this event
146  * is only sent via XKB. Therefore, we need this special handler.
147  *
148  */
149 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
150     DLOG("Handling XKB event\n");
151     XkbEvent ev;
152
153     /* When using xmodmap, every change (!) gets an own event.
154      * Therefore, we just read all events and only handle the
155      * mapping_notify once. */
156     bool mapping_changed = false;
157     while (XPending(xkbdpy)) {
158         XNextEvent(xkbdpy, (XEvent*)&ev);
159         /* While we should never receive a non-XKB event,
160          * better do sanity checking */
161         if (ev.type != xkb_event_base)
162             continue;
163
164         if (ev.any.xkb_type == XkbMapNotify) {
165             mapping_changed = true;
166             continue;
167         }
168
169         if (ev.any.xkb_type != XkbStateNotify) {
170             ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
171             continue;
172         }
173
174         /* See The XKB Extension: Library Specification, section 14.1 */
175         /* We check if the current group (each group contains
176          * two levels) has been changed. Mode_switch activates
177          * group XkbGroup2Index */
178         if (xkb_current_group == ev.state.group)
179             continue;
180
181         xkb_current_group = ev.state.group;
182
183         if (ev.state.group == XkbGroup2Index) {
184             DLOG("Mode_switch enabled\n");
185             grab_all_keys(conn, true);
186         }
187
188         if (ev.state.group == XkbGroup1Index) {
189             DLOG("Mode_switch disabled\n");
190             ungrab_all_keys(conn);
191             grab_all_keys(conn, false);
192         }
193     }
194
195     if (!mapping_changed)
196         return;
197
198     DLOG("Keyboard mapping changed, updating keybindings\n");
199     xcb_key_symbols_free(keysyms);
200     keysyms = xcb_key_symbols_alloc(conn);
201
202     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
203
204     ungrab_all_keys(conn);
205     DLOG("Re-grabbing...\n");
206     translate_keysyms();
207     grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
208     DLOG("Done\n");
209 }
210
211 /*
212  * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
213  *
214  */
215 static void i3_exit() {
216 /* We need ev >= 4 for the following code. Since it is not *that* important (it
217  * only makes sure that there are no i3-nagbar instances left behind) we still
218  * support old systems with libev 3. */
219 #if EV_VERSION_MAJOR >= 4
220     ev_loop_destroy(main_loop);
221 #endif
222
223     if (*shmlogname != '\0') {
224         fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
225         fflush(stderr);
226         shm_unlink(shmlogname);
227     }
228 }
229
230 /*
231  * (One-shot) Handler for all signals with default action "Term", see signal(7)
232  *
233  * Unlinks the SHM log and re-raises the signal.
234  *
235  */
236 static void handle_signal(int sig, siginfo_t *info, void *data) {
237     fprintf(stderr, "Received signal %d, terminating\n", sig);
238     if (*shmlogname != '\0') {
239         fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
240         shm_unlink(shmlogname);
241     }
242     fflush(stderr);
243     raise(sig);
244 }
245
246 int main(int argc, char *argv[]) {
247     char *override_configpath = NULL;
248     bool autostart = true;
249     char *layout_path = NULL;
250     bool delete_layout_path = false;
251     bool force_xinerama = false;
252     bool disable_signalhandler = false;
253     bool enable_32bit_visual = false;
254     static struct option long_options[] = {
255         {"no-autostart", no_argument, 0, 'a'},
256         {"config", required_argument, 0, 'c'},
257         {"version", no_argument, 0, 'v'},
258         {"help", no_argument, 0, 'h'},
259         {"layout", required_argument, 0, 'L'},
260         {"restart", required_argument, 0, 0},
261         {"force-xinerama", no_argument, 0, 0},
262         {"force_xinerama", no_argument, 0, 0},
263         {"disable-signalhandler", no_argument, 0, 0},
264         {"shmlog-size", required_argument, 0, 0},
265         {"shmlog_size", required_argument, 0, 0},
266         {"get-socketpath", no_argument, 0, 0},
267         {"get_socketpath", no_argument, 0, 0},
268         {"enable-32bit-visual", no_argument, 0, 0},
269         {"enable_32bit_visual", no_argument, 0, 0},
270         {0, 0, 0, 0}
271     };
272     int option_index = 0, opt;
273     xcb_void_cookie_t colormap_cookie;
274
275     setlocale(LC_ALL, "");
276
277     /* Get the RLIMIT_CORE limit at startup time to restore this before
278      * starting processes. */
279     getrlimit(RLIMIT_CORE, &original_rlimit_core);
280
281     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
282     if (!isatty(fileno(stdout)))
283         setbuf(stdout, NULL);
284
285     srand(time(NULL));
286
287     /* Init logging *before* initializing debug_build to guarantee early
288      * (file) logging. */
289     init_logging();
290
291     /* I3_VERSION contains either something like this:
292      *     "4.0.2 (2011-11-11, branch "release")".
293      * or: "4.0.2-123-gCOFFEEBABE (2011-11-11, branch "next")".
294      *
295      * So we check for the offset of the first opening round bracket to
296      * determine whether this is a git version or a release version. */
297     debug_build = ((strchr(I3_VERSION, '(') - I3_VERSION) > 10);
298
299     /* On non-release builds, disable SHM logging by default. */
300     shmlog_size = (debug_build ? 25 * 1024 * 1024 : 0);
301
302     start_argv = argv;
303
304     while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
305         switch (opt) {
306             case 'a':
307                 LOG("Autostart disabled using -a\n");
308                 autostart = false;
309                 break;
310             case 'L':
311                 FREE(layout_path);
312                 layout_path = sstrdup(optarg);
313                 delete_layout_path = false;
314                 break;
315             case 'c':
316                 FREE(override_configpath);
317                 override_configpath = sstrdup(optarg);
318                 break;
319             case 'C':
320                 LOG("Checking configuration file only (-C)\n");
321                 only_check_config = true;
322                 break;
323             case 'v':
324                 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
325                 exit(EXIT_SUCCESS);
326             case 'V':
327                 set_verbosity(true);
328                 break;
329             case 'd':
330                 LOG("Enabling debug loglevel %s\n", optarg);
331                 add_loglevel(optarg);
332                 break;
333             case 'l':
334                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
335                 break;
336             case 0:
337                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
338                     strcmp(long_options[option_index].name, "force_xinerama") == 0) {
339                     force_xinerama = true;
340                     ELOG("Using Xinerama instead of RandR. This option should be "
341                          "avoided at all cost because it does not refresh the list "
342                          "of screens, so you cannot configure displays at runtime. "
343                          "Please check if your driver really does not support RandR "
344                          "and disable this option as soon as you can.\n");
345                     break;
346                 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
347                     disable_signalhandler = true;
348                     break;
349                 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
350                            strcmp(long_options[option_index].name, "get_socketpath") == 0) {
351                     char *socket_path = root_atom_contents("I3_SOCKET_PATH");
352                     if (socket_path) {
353                         printf("%s\n", socket_path);
354                         return 0;
355                     }
356
357                     return 1;
358                 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
359                            strcmp(long_options[option_index].name, "shmlog_size") == 0) {
360                     shmlog_size = atoi(optarg);
361                     /* Re-initialize logging immediately to get as many
362                      * logmessages as possible into the SHM log. */
363                     init_logging();
364                     LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
365                     break;
366                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
367                     FREE(layout_path);
368                     layout_path = sstrdup(optarg);
369                     delete_layout_path = true;
370                     break;
371                 } else if (strcmp(long_options[option_index].name, "enable_32bit_visual") == 0 ||
372                            strcmp(long_options[option_index].name, "enable-32bit-visual") == 0) {
373                     LOG("Enabling 32 bit visual (if available)\n");
374                     enable_32bit_visual = true;
375                     break;
376                 }
377                 /* fall-through */
378             default:
379                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
380                 fprintf(stderr, "\n");
381                 fprintf(stderr, "\t-a          disable autostart ('exec' lines in config)\n");
382                 fprintf(stderr, "\t-c <file>   use the provided configfile instead\n");
383                 fprintf(stderr, "\t-C          validate configuration file and exit\n");
384                 fprintf(stderr, "\t-d <level>  enable debug output with the specified loglevel\n");
385                 fprintf(stderr, "\t-L <file>   path to the serialized layout during restarts\n");
386                 fprintf(stderr, "\t-v          display version and exit\n");
387                 fprintf(stderr, "\t-V          enable verbose mode\n");
388                 fprintf(stderr, "\n");
389                 fprintf(stderr, "\t--force-xinerama\n"
390                                 "\tUse Xinerama instead of RandR.\n"
391                                 "\tThis option should only be used if you are stuck with the\n"
392                                 "\tnvidia closed source driver which does not support RandR.\n");
393                 fprintf(stderr, "\n");
394                 fprintf(stderr, "\t--get-socketpath\n"
395                                 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
396                 fprintf(stderr, "\n");
397                 fprintf(stderr, "\t--shmlog-size <limit>\n"
398                                 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
399                                 "\tto 0 disables SHM logging entirely.\n"
400                                 "\tThe default is %d bytes.\n", shmlog_size);
401                 fprintf(stderr, "\n");
402                 fprintf(stderr, "\t--enable-32bit-visual\n"
403                                 "\tMakes i3 use a 32 bit visual, if available. Necessary for\n"
404                                 "\tpseudo-transparency with xcompmgr.\n");
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 the user passes more arguments, we act like i3-msg would: Just send
419      * the arguments as an IPC message to i3. This allows for nice semantic
420      * commands such as 'i3 border none'. */
421     if (optind < argc) {
422         /* We enable verbose mode so that the user knows what’s going on.
423          * This should make it easier to find mistakes when the user passes
424          * arguments by mistake. */
425         set_verbosity(true);
426
427         LOG("Additional arguments passed. Sending them as a command to i3.\n");
428         char *payload = NULL;
429         while (optind < argc) {
430             if (!payload) {
431                 payload = sstrdup(argv[optind]);
432             } else {
433                 char *both;
434                 sasprintf(&both, "%s %s", payload, argv[optind]);
435                 free(payload);
436                 payload = both;
437             }
438             optind++;
439         }
440         LOG("Command is: %s (%d bytes)\n", payload, strlen(payload));
441         char *socket_path = root_atom_contents("I3_SOCKET_PATH");
442         if (!socket_path) {
443             ELOG("Could not get i3 IPC socket path\n");
444             return 1;
445         }
446
447         int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
448         if (sockfd == -1)
449             err(EXIT_FAILURE, "Could not create socket");
450
451         struct sockaddr_un addr;
452         memset(&addr, 0, sizeof(struct sockaddr_un));
453         addr.sun_family = AF_LOCAL;
454         strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
455         if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
456             err(EXIT_FAILURE, "Could not connect to i3");
457
458         if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
459                              (uint8_t*)payload) == -1)
460             err(EXIT_FAILURE, "IPC: write()");
461
462         uint32_t reply_length;
463         uint8_t *reply;
464         int ret;
465         if ((ret = ipc_recv_message(sockfd, I3_IPC_MESSAGE_TYPE_COMMAND,
466                                     &reply_length, &reply)) != 0) {
467             if (ret == -1)
468                 err(EXIT_FAILURE, "IPC: read()");
469             return 1;
470         }
471         printf("%.*s\n", reply_length, reply);
472         return 0;
473     }
474
475     /* Enable logging to handle the case when the user did not specify --shmlog-size */
476     init_logging();
477
478     /* Try to enable core dumps by default when running a debug build */
479     if (debug_build) {
480         struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY };
481         setrlimit(RLIMIT_CORE, &limit);
482
483         /* The following code is helpful, but not required. We thus don’t pay
484          * much attention to error handling, non-linux or other edge cases. */
485         char cwd[PATH_MAX];
486         LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
487         if (getcwd(cwd, sizeof(cwd)) != NULL)
488             LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
489         int patternfd;
490         if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
491             memset(cwd, '\0', sizeof(cwd));
492             if (read(patternfd, cwd, sizeof(cwd)) > 0)
493                 /* a trailing newline is included in cwd */
494                 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
495             close(patternfd);
496         }
497     }
498
499     LOG("i3 (tree) version " I3_VERSION " starting\n");
500
501     conn = xcb_connect(NULL, &conn_screen);
502     if (xcb_connection_has_error(conn))
503         errx(EXIT_FAILURE, "Cannot open display\n");
504
505     sndisplay = sn_xcb_display_new(conn, NULL, NULL);
506
507     /* Initialize the libev event loop. This needs to be done before loading
508      * the config file because the parser will install an ev_child watcher
509      * for the nagbar when config errors are found. */
510     main_loop = EV_DEFAULT;
511     if (main_loop == NULL)
512             die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
513
514     root_screen = xcb_aux_get_screen(conn, conn_screen);
515     root = root_screen->root;
516
517     /* By default, we use the same depth and visual as the root window, which
518      * usually is TrueColor (24 bit depth) and the corresponding visual.
519      * However, we also check if a 32 bit depth and visual are available (for
520      * transparency) and use it if so. */
521     root_depth = root_screen->root_depth;
522     visual_id = root_screen->root_visual;
523     colormap = root_screen->default_colormap;
524
525     if (enable_32bit_visual) {
526         xcb_depth_iterator_t depth_iter;
527         xcb_visualtype_iterator_t visual_iter;
528         for (depth_iter = xcb_screen_allowed_depths_iterator(root_screen);
529              depth_iter.rem;
530              xcb_depth_next(&depth_iter)) {
531             if (depth_iter.data->depth != 32)
532                 continue;
533             visual_iter = xcb_depth_visuals_iterator(depth_iter.data);
534             if (!visual_iter.rem)
535                 continue;
536
537             visual_id = visual_iter.data->visual_id;
538             root_depth = depth_iter.data->depth;
539             colormap = xcb_generate_id(conn);
540             colormap_cookie = xcb_create_colormap_checked(conn, XCB_COLORMAP_ALLOC_NONE, colormap, root, visual_id);
541             DLOG("Found a visual with 32 bit depth.\n");
542             break;
543         }
544     }
545
546     DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
547
548     xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
549     xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
550
551     load_configuration(conn, override_configpath, false);
552     if (only_check_config) {
553         LOG("Done checking configuration file. Exiting.\n");
554         exit(0);
555     }
556
557     if (config.ipc_socket_path == NULL) {
558         /* Fall back to a file name in /tmp/ based on the PID */
559         if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
560             config.ipc_socket_path = get_process_filename("ipc-socket");
561         else
562             config.ipc_socket_path = sstrdup(config.ipc_socket_path);
563     }
564
565     uint32_t mask = XCB_CW_EVENT_MASK;
566     uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
567                           XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
568                                                                            projector), the root window gets a
569                                                                            ConfigureNotify */
570                           XCB_EVENT_MASK_POINTER_MOTION |
571                           XCB_EVENT_MASK_PROPERTY_CHANGE |
572                           XCB_EVENT_MASK_ENTER_WINDOW };
573     xcb_void_cookie_t cookie;
574     cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
575     check_error(conn, cookie, "Another window manager seems to be running");
576
577     /* By now we already checked for replies once, so let’s see if colormap
578      * creation worked (if requested). */
579     if (colormap != root_screen->default_colormap) {
580         xcb_generic_error_t *error = xcb_request_check(conn, colormap_cookie);
581         if (error != NULL) {
582             ELOG("Could not create ColorMap for 32 bit visual, falling back to X11 default.\n");
583             root_depth = root_screen->root_depth;
584             visual_id = root_screen->root_visual;
585             colormap = root_screen->default_colormap;
586             DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
587             free(error);
588         }
589     }
590
591     xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
592     if (greply == NULL) {
593         ELOG("Could not get geometry of the root window, exiting\n");
594         return 1;
595     }
596     DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
597
598     /* Place requests for the atoms we need as soon as possible */
599     #define xmacro(atom) \
600         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
601     #include "atoms.xmacro"
602     #undef xmacro
603
604     /* Initialize the Xlib connection */
605     xlibdpy = xkbdpy = XOpenDisplay(NULL);
606
607     /* Try to load the X cursors and initialize the XKB extension */
608     if (xlibdpy == NULL) {
609         ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
610         xcursor_supported = false;
611         xkb_supported = false;
612     } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
613         ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
614         return 1;
615     } else {
616         xcursor_load_cursors();
617         /*init_xkb();*/
618     }
619
620     /* Set a cursor for the root window (otherwise the root window will show no
621        cursor until the first client is launched). */
622     if (xcursor_supported)
623         xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
624     else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
625
626     if (xkb_supported) {
627         int errBase,
628             major = XkbMajorVersion,
629             minor = XkbMinorVersion;
630
631         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
632             fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
633             return 1;
634         }
635
636         int i1;
637         if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
638             fprintf(stderr, "XKB not supported by X-server\n");
639             return 1;
640         }
641         /* end of ugliness */
642
643         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
644                              XkbMapNotifyMask | XkbStateNotifyMask,
645                              XkbMapNotifyMask | XkbStateNotifyMask)) {
646             fprintf(stderr, "Could not set XKB event mask\n");
647             return 1;
648         }
649     }
650
651     /* Setup NetWM atoms */
652     #define xmacro(name) \
653         do { \
654             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
655             if (!reply) { \
656                 ELOG("Could not get atom " #name "\n"); \
657                 exit(-1); \
658             } \
659             A_ ## name = reply->atom; \
660             free(reply); \
661         } while (0);
662     #include "atoms.xmacro"
663     #undef xmacro
664
665     property_handlers_init();
666
667     ewmh_setup_hints();
668
669     keysyms = xcb_key_symbols_alloc(conn);
670
671     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
672
673     translate_keysyms();
674     grab_all_keys(conn, false);
675
676     bool needs_tree_init = true;
677     if (layout_path) {
678         LOG("Trying to restore the layout from %s...", layout_path);
679         needs_tree_init = !tree_restore(layout_path, greply);
680         if (delete_layout_path)
681             unlink(layout_path);
682         free(layout_path);
683     }
684     if (needs_tree_init)
685         tree_init(greply);
686
687     free(greply);
688
689     /* Force Xinerama (for drivers which don't support RandR yet, esp. the
690      * nVidia binary graphics driver), when specified either in the config
691      * file or on command-line */
692     if (force_xinerama || config.force_xinerama) {
693         xinerama_init();
694     } else {
695         DLOG("Checking for XRandR...\n");
696         randr_init(&randr_base);
697     }
698
699     xcb_query_pointer_reply_t *pointerreply;
700     Output *output = NULL;
701     if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
702         ELOG("Could not query pointer position, using first screen\n");
703         output = get_first_output();
704     } else {
705         DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
706         output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
707         if (!output) {
708             ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
709                  pointerreply->root_x, pointerreply->root_y);
710             output = get_first_output();
711         }
712
713         con_focus(con_descend_focused(output_get_content(output->con)));
714     }
715
716     tree_render();
717
718     /* Create the UNIX domain socket for IPC */
719     int ipc_socket = ipc_create_socket(config.ipc_socket_path);
720     if (ipc_socket == -1) {
721         ELOG("Could not create the IPC socket, IPC disabled\n");
722     } else {
723         free(config.ipc_socket_path);
724         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
725         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
726         ev_io_start(main_loop, ipc_io);
727     }
728
729     /* Also handle the UNIX domain sockets passed via socket activation. The
730      * parameter 1 means "remove the environment variables", we don’t want to
731      * pass these to child processes. */
732     listen_fds = sd_listen_fds(0);
733     if (listen_fds < 0)
734         ELOG("socket activation: Error in sd_listen_fds\n");
735     else if (listen_fds == 0)
736         DLOG("socket activation: no sockets passed\n");
737     else {
738         int flags;
739         for (int fd = SD_LISTEN_FDS_START;
740              fd < (SD_LISTEN_FDS_START + listen_fds);
741              fd++) {
742             DLOG("socket activation: also listening on fd %d\n", fd);
743
744             /* sd_listen_fds() enables FD_CLOEXEC by default.
745              * However, we need to keep the file descriptors open for in-place
746              * restarting, therefore we explicitly disable FD_CLOEXEC. */
747             if ((flags = fcntl(fd, F_GETFD)) < 0 ||
748                 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
749                 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
750             }
751
752             struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
753             ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
754             ev_io_start(main_loop, ipc_io);
755         }
756     }
757
758     /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
759     x_set_i3_atoms();
760
761     struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
762     struct ev_io *xkb = scalloc(sizeof(struct ev_io));
763     struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
764     struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
765
766     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
767     ev_io_start(main_loop, xcb_watcher);
768
769
770     if (xkb_supported) {
771         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
772         ev_io_start(main_loop, xkb);
773
774         /* Flush the buffer so that libev can properly get new events */
775         XFlush(xkbdpy);
776     }
777
778     ev_check_init(xcb_check, xcb_check_cb);
779     ev_check_start(main_loop, xcb_check);
780
781     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
782     ev_prepare_start(main_loop, xcb_prepare);
783
784     xcb_flush(conn);
785
786     manage_existing_windows(root);
787
788     struct sigaction action;
789
790     action.sa_sigaction = handle_signal;
791     action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
792     sigemptyset(&action.sa_mask);
793
794     if (!disable_signalhandler)
795         setup_signal_handler();
796     else {
797         /* Catch all signals with default action "Core", see signal(7) */
798         if (sigaction(SIGQUIT, &action, NULL) == -1 ||
799             sigaction(SIGILL, &action, NULL) == -1 ||
800             sigaction(SIGABRT, &action, NULL) == -1 ||
801             sigaction(SIGFPE, &action, NULL) == -1 ||
802             sigaction(SIGSEGV, &action, NULL) == -1)
803             ELOG("Could not setup signal handler");
804     }
805
806     /* Catch all signals with default action "Term", see signal(7) */
807     if (sigaction(SIGHUP, &action, NULL) == -1 ||
808         sigaction(SIGINT, &action, NULL) == -1 ||
809         sigaction(SIGALRM, &action, NULL) == -1 ||
810         sigaction(SIGUSR1, &action, NULL) == -1 ||
811         sigaction(SIGUSR2, &action, NULL) == -1)
812         ELOG("Could not setup signal handler");
813
814     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
815      * while we are sending him a message */
816     signal(SIGPIPE, SIG_IGN);
817
818     /* Autostarting exec-lines */
819     if (autostart) {
820         struct Autostart *exec;
821         TAILQ_FOREACH(exec, &autostarts, autostarts) {
822             LOG("auto-starting %s\n", exec->command);
823             start_application(exec->command, exec->no_startup_id);
824         }
825     }
826
827     /* Autostarting exec_always-lines */
828     struct Autostart *exec_always;
829     TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
830         LOG("auto-starting (always!) %s\n", exec_always->command);
831         start_application(exec_always->command, exec_always->no_startup_id);
832     }
833
834     /* Start i3bar processes for all configured bars */
835     Barconfig *barconfig;
836     TAILQ_FOREACH(barconfig, &barconfigs, configs) {
837         char *command = NULL;
838         sasprintf(&command, "%s --bar_id=%s --socket=\"%s\"",
839                 barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
840                 barconfig->id, current_socketpath);
841         LOG("Starting bar process: %s\n", command);
842         start_application(command, true);
843         free(command);
844     }
845
846     /* Make sure to destroy the event loop to invoke the cleeanup callbacks
847      * when calling exit() */
848     atexit(i3_exit);
849
850     ev_loop(main_loop, 0);
851 }