]> git.sur5r.net Git - i3/i3/blob - src/main.c
Implement fake-outputs option (cmdline, cfg) for multi-monitor testing
[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(void) {
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     /* Keep a symbol pointing to the I3_VERSION string constant so that we have
248      * it in gdb backtraces. */
249     const char *i3_version = I3_VERSION;
250     char *override_configpath = NULL;
251     bool autostart = true;
252     char *layout_path = NULL;
253     bool delete_layout_path = false;
254     bool force_xinerama = false;
255     char *fake_outputs = NULL;
256     bool disable_signalhandler = false;
257     static struct option long_options[] = {
258         {"no-autostart", no_argument, 0, 'a'},
259         {"config", required_argument, 0, 'c'},
260         {"version", no_argument, 0, 'v'},
261         {"help", no_argument, 0, 'h'},
262         {"layout", required_argument, 0, 'L'},
263         {"restart", required_argument, 0, 0},
264         {"force-xinerama", no_argument, 0, 0},
265         {"force_xinerama", no_argument, 0, 0},
266         {"disable-signalhandler", no_argument, 0, 0},
267         {"shmlog-size", required_argument, 0, 0},
268         {"shmlog_size", required_argument, 0, 0},
269         {"get-socketpath", no_argument, 0, 0},
270         {"get_socketpath", no_argument, 0, 0},
271         {"fake_outputs", required_argument, 0, 0},
272         {"fake-outputs", required_argument, 0, 0},
273         {0, 0, 0, 0}
274     };
275     int option_index = 0, opt;
276     xcb_void_cookie_t colormap_cookie;
277
278     setlocale(LC_ALL, "");
279
280     /* Get the RLIMIT_CORE limit at startup time to restore this before
281      * starting processes. */
282     getrlimit(RLIMIT_CORE, &original_rlimit_core);
283
284     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
285     if (!isatty(fileno(stdout)))
286         setbuf(stdout, NULL);
287
288     srand(time(NULL));
289
290     /* Init logging *before* initializing debug_build to guarantee early
291      * (file) logging. */
292     init_logging();
293
294     /* i3_version contains either something like this:
295      *     "4.0.2 (2011-11-11, branch "release")".
296      * or: "4.0.2-123-gCOFFEEBABE (2011-11-11, branch "next")".
297      *
298      * So we check for the offset of the first opening round bracket to
299      * determine whether this is a git version or a release version. */
300     debug_build = ((strchr(i3_version, '(') - i3_version) > 10);
301
302     /* On non-release builds, disable SHM logging by default. */
303     shmlog_size = (debug_build ? 25 * 1024 * 1024 : 0);
304
305     start_argv = argv;
306
307     while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
308         switch (opt) {
309             case 'a':
310                 LOG("Autostart disabled using -a\n");
311                 autostart = false;
312                 break;
313             case 'L':
314                 FREE(layout_path);
315                 layout_path = sstrdup(optarg);
316                 delete_layout_path = false;
317                 break;
318             case 'c':
319                 FREE(override_configpath);
320                 override_configpath = sstrdup(optarg);
321                 break;
322             case 'C':
323                 LOG("Checking configuration file only (-C)\n");
324                 only_check_config = true;
325                 break;
326             case 'v':
327                 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
328                 exit(EXIT_SUCCESS);
329             case 'V':
330                 set_verbosity(true);
331                 break;
332             case 'd':
333                 LOG("Enabling debug loglevel %s\n", optarg);
334                 add_loglevel(optarg);
335                 break;
336             case 'l':
337                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
338                 break;
339             case 0:
340                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
341                     strcmp(long_options[option_index].name, "force_xinerama") == 0) {
342                     force_xinerama = true;
343                     ELOG("Using Xinerama instead of RandR. This option should be "
344                          "avoided at all cost because it does not refresh the list "
345                          "of screens, so you cannot configure displays at runtime. "
346                          "Please check if your driver really does not support RandR "
347                          "and disable this option as soon as you can.\n");
348                     break;
349                 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
350                     disable_signalhandler = true;
351                     break;
352                 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
353                            strcmp(long_options[option_index].name, "get_socketpath") == 0) {
354                     char *socket_path = root_atom_contents("I3_SOCKET_PATH");
355                     if (socket_path) {
356                         printf("%s\n", socket_path);
357                         return 0;
358                     }
359
360                     return 1;
361                 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
362                            strcmp(long_options[option_index].name, "shmlog_size") == 0) {
363                     shmlog_size = atoi(optarg);
364                     /* Re-initialize logging immediately to get as many
365                      * logmessages as possible into the SHM log. */
366                     init_logging();
367                     LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
368                     break;
369                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
370                     FREE(layout_path);
371                     layout_path = sstrdup(optarg);
372                     delete_layout_path = true;
373                     break;
374                 } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
375                            strcmp(long_options[option_index].name, "fake_outputs") == 0) {
376                     LOG("Initializing fake outputs: %s\n", optarg);
377                     fake_outputs = sstrdup(optarg);
378                     break;
379                 }
380                 /* fall-through */
381             default:
382                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
383                 fprintf(stderr, "\n");
384                 fprintf(stderr, "\t-a          disable autostart ('exec' lines in config)\n");
385                 fprintf(stderr, "\t-c <file>   use the provided configfile instead\n");
386                 fprintf(stderr, "\t-C          validate configuration file and exit\n");
387                 fprintf(stderr, "\t-d <level>  enable debug output with the specified loglevel\n");
388                 fprintf(stderr, "\t-L <file>   path to the serialized layout during restarts\n");
389                 fprintf(stderr, "\t-v          display version and exit\n");
390                 fprintf(stderr, "\t-V          enable verbose mode\n");
391                 fprintf(stderr, "\n");
392                 fprintf(stderr, "\t--force-xinerama\n"
393                                 "\tUse Xinerama instead of RandR.\n"
394                                 "\tThis option should only be used if you are stuck with the\n"
395                                 "\tnvidia closed source driver which does not support RandR.\n");
396                 fprintf(stderr, "\n");
397                 fprintf(stderr, "\t--get-socketpath\n"
398                                 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
399                 fprintf(stderr, "\n");
400                 fprintf(stderr, "\t--shmlog-size <limit>\n"
401                                 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
402                                 "\tto 0 disables SHM logging entirely.\n"
403                                 "\tThe default is %d bytes.\n", shmlog_size);
404                 fprintf(stderr, "\n");
405                 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
406                                 "to send to a currently running i3 (like i3-msg). This allows you to\n"
407                                 "use nice and logical commands, such as:\n"
408                                 "\n"
409                                 "\ti3 border none\n"
410                                 "\ti3 floating toggle\n"
411                                 "\ti3 kill window\n"
412                                 "\n");
413                 exit(EXIT_FAILURE);
414         }
415     }
416
417     /* If the user passes more arguments, we act like i3-msg would: Just send
418      * the arguments as an IPC message to i3. This allows for nice semantic
419      * commands such as 'i3 border none'. */
420     if (optind < argc) {
421         /* We enable verbose mode so that the user knows what’s going on.
422          * This should make it easier to find mistakes when the user passes
423          * arguments by mistake. */
424         set_verbosity(true);
425
426         LOG("Additional arguments passed. Sending them as a command to i3.\n");
427         char *payload = NULL;
428         while (optind < argc) {
429             if (!payload) {
430                 payload = sstrdup(argv[optind]);
431             } else {
432                 char *both;
433                 sasprintf(&both, "%s %s", payload, argv[optind]);
434                 free(payload);
435                 payload = both;
436             }
437             optind++;
438         }
439         LOG("Command is: %s (%d bytes)\n", payload, strlen(payload));
440         char *socket_path = root_atom_contents("I3_SOCKET_PATH");
441         if (!socket_path) {
442             ELOG("Could not get i3 IPC socket path\n");
443             return 1;
444         }
445
446         int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
447         if (sockfd == -1)
448             err(EXIT_FAILURE, "Could not create socket");
449
450         struct sockaddr_un addr;
451         memset(&addr, 0, sizeof(struct sockaddr_un));
452         addr.sun_family = AF_LOCAL;
453         strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
454         if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
455             err(EXIT_FAILURE, "Could not connect to i3");
456
457         if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
458                              (uint8_t*)payload) == -1)
459             err(EXIT_FAILURE, "IPC: write()");
460
461         uint32_t reply_length;
462         uint8_t *reply;
463         int ret;
464         if ((ret = ipc_recv_message(sockfd, I3_IPC_MESSAGE_TYPE_COMMAND,
465                                     &reply_length, &reply)) != 0) {
466             if (ret == -1)
467                 err(EXIT_FAILURE, "IPC: read()");
468             return 1;
469         }
470         printf("%.*s\n", reply_length, reply);
471         return 0;
472     }
473
474     /* Enable logging to handle the case when the user did not specify --shmlog-size */
475     init_logging();
476
477     /* Try to enable core dumps by default when running a debug build */
478     if (debug_build) {
479         struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY };
480         setrlimit(RLIMIT_CORE, &limit);
481
482         /* The following code is helpful, but not required. We thus don’t pay
483          * much attention to error handling, non-linux or other edge cases. */
484         char cwd[PATH_MAX];
485         LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
486         if (getcwd(cwd, sizeof(cwd)) != NULL)
487             LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
488         int patternfd;
489         if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
490             memset(cwd, '\0', sizeof(cwd));
491             if (read(patternfd, cwd, sizeof(cwd)) > 0)
492                 /* a trailing newline is included in cwd */
493                 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
494             close(patternfd);
495         }
496     }
497
498     LOG("i3 (tree) version " I3_VERSION " starting\n");
499
500     conn = xcb_connect(NULL, &conn_screen);
501     if (xcb_connection_has_error(conn))
502         errx(EXIT_FAILURE, "Cannot open display\n");
503
504     sndisplay = sn_xcb_display_new(conn, NULL, NULL);
505
506     /* Initialize the libev event loop. This needs to be done before loading
507      * the config file because the parser will install an ev_child watcher
508      * for the nagbar when config errors are found. */
509     main_loop = EV_DEFAULT;
510     if (main_loop == NULL)
511             die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
512
513     root_screen = xcb_aux_get_screen(conn, conn_screen);
514     root = root_screen->root;
515
516     /* By default, we use the same depth and visual as the root window, which
517      * usually is TrueColor (24 bit depth) and the corresponding visual.
518      * However, we also check if a 32 bit depth and visual are available (for
519      * transparency) and use it if so. */
520     root_depth = root_screen->root_depth;
521     visual_id = root_screen->root_visual;
522     colormap = root_screen->default_colormap;
523
524     DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
525
526     xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
527     xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
528
529     load_configuration(conn, override_configpath, false);
530     if (only_check_config) {
531         LOG("Done checking configuration file. Exiting.\n");
532         exit(0);
533     }
534
535     if (config.ipc_socket_path == NULL) {
536         /* Fall back to a file name in /tmp/ based on the PID */
537         if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
538             config.ipc_socket_path = get_process_filename("ipc-socket");
539         else
540             config.ipc_socket_path = sstrdup(config.ipc_socket_path);
541     }
542
543     uint32_t mask = XCB_CW_EVENT_MASK;
544     uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
545                           XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
546                                                                            projector), the root window gets a
547                                                                            ConfigureNotify */
548                           XCB_EVENT_MASK_POINTER_MOTION |
549                           XCB_EVENT_MASK_PROPERTY_CHANGE |
550                           XCB_EVENT_MASK_ENTER_WINDOW };
551     xcb_void_cookie_t cookie;
552     cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
553     check_error(conn, cookie, "Another window manager seems to be running");
554
555     /* By now we already checked for replies once, so let’s see if colormap
556      * creation worked (if requested). */
557     if (colormap != root_screen->default_colormap) {
558         xcb_generic_error_t *error = xcb_request_check(conn, colormap_cookie);
559         if (error != NULL) {
560             ELOG("Could not create ColorMap for 32 bit visual, falling back to X11 default.\n");
561             root_depth = root_screen->root_depth;
562             visual_id = root_screen->root_visual;
563             colormap = root_screen->default_colormap;
564             DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
565             free(error);
566         }
567     }
568
569     xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
570     if (greply == NULL) {
571         ELOG("Could not get geometry of the root window, exiting\n");
572         return 1;
573     }
574     DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
575
576     /* Place requests for the atoms we need as soon as possible */
577     #define xmacro(atom) \
578         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
579     #include "atoms.xmacro"
580     #undef xmacro
581
582     /* Initialize the Xlib connection */
583     xlibdpy = xkbdpy = XOpenDisplay(NULL);
584
585     /* Try to load the X cursors and initialize the XKB extension */
586     if (xlibdpy == NULL) {
587         ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
588         xcursor_supported = false;
589         xkb_supported = false;
590     } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
591         ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
592         return 1;
593     } else {
594         xcursor_load_cursors();
595         /*init_xkb();*/
596     }
597
598     /* Set a cursor for the root window (otherwise the root window will show no
599        cursor until the first client is launched). */
600     if (xcursor_supported)
601         xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
602     else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
603
604     if (xkb_supported) {
605         int errBase,
606             major = XkbMajorVersion,
607             minor = XkbMinorVersion;
608
609         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
610             fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
611             return 1;
612         }
613
614         int i1;
615         if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
616             fprintf(stderr, "XKB not supported by X-server\n");
617             return 1;
618         }
619         /* end of ugliness */
620
621         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
622                              XkbMapNotifyMask | XkbStateNotifyMask,
623                              XkbMapNotifyMask | XkbStateNotifyMask)) {
624             fprintf(stderr, "Could not set XKB event mask\n");
625             return 1;
626         }
627     }
628
629     /* Setup NetWM atoms */
630     #define xmacro(name) \
631         do { \
632             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
633             if (!reply) { \
634                 ELOG("Could not get atom " #name "\n"); \
635                 exit(-1); \
636             } \
637             A_ ## name = reply->atom; \
638             free(reply); \
639         } while (0);
640     #include "atoms.xmacro"
641     #undef xmacro
642
643     property_handlers_init();
644
645     ewmh_setup_hints();
646
647     keysyms = xcb_key_symbols_alloc(conn);
648
649     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
650
651     translate_keysyms();
652     grab_all_keys(conn, false);
653
654     bool needs_tree_init = true;
655     if (layout_path) {
656         LOG("Trying to restore the layout from %s...", layout_path);
657         needs_tree_init = !tree_restore(layout_path, greply);
658         if (delete_layout_path)
659             unlink(layout_path);
660         free(layout_path);
661     }
662     if (needs_tree_init)
663         tree_init(greply);
664
665     free(greply);
666
667     /* Setup fake outputs for testing */
668     if (fake_outputs == NULL && config.fake_outputs != NULL)
669         fake_outputs = config.fake_outputs;
670
671     if (fake_outputs != NULL) {
672         fake_outputs_init(fake_outputs);
673         FREE(fake_outputs);
674         config.fake_outputs = NULL;
675     } else if (force_xinerama || config.force_xinerama) {
676         /* Force Xinerama (for drivers which don't support RandR yet, esp. the
677          * nVidia binary graphics driver), when specified either in the config
678          * file or on command-line */
679         xinerama_init();
680     } else {
681         DLOG("Checking for XRandR...\n");
682         randr_init(&randr_base);
683     }
684
685     xcb_query_pointer_reply_t *pointerreply;
686     Output *output = NULL;
687     if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
688         ELOG("Could not query pointer position, using first screen\n");
689         output = get_first_output();
690     } else {
691         DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
692         output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
693         if (!output) {
694             ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
695                  pointerreply->root_x, pointerreply->root_y);
696             output = get_first_output();
697         }
698
699         con_focus(con_descend_focused(output_get_content(output->con)));
700     }
701
702     tree_render();
703
704     /* Create the UNIX domain socket for IPC */
705     int ipc_socket = ipc_create_socket(config.ipc_socket_path);
706     if (ipc_socket == -1) {
707         ELOG("Could not create the IPC socket, IPC disabled\n");
708     } else {
709         free(config.ipc_socket_path);
710         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
711         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
712         ev_io_start(main_loop, ipc_io);
713     }
714
715     /* Also handle the UNIX domain sockets passed via socket activation. The
716      * parameter 1 means "remove the environment variables", we don’t want to
717      * pass these to child processes. */
718     listen_fds = sd_listen_fds(0);
719     if (listen_fds < 0)
720         ELOG("socket activation: Error in sd_listen_fds\n");
721     else if (listen_fds == 0)
722         DLOG("socket activation: no sockets passed\n");
723     else {
724         int flags;
725         for (int fd = SD_LISTEN_FDS_START;
726              fd < (SD_LISTEN_FDS_START + listen_fds);
727              fd++) {
728             DLOG("socket activation: also listening on fd %d\n", fd);
729
730             /* sd_listen_fds() enables FD_CLOEXEC by default.
731              * However, we need to keep the file descriptors open for in-place
732              * restarting, therefore we explicitly disable FD_CLOEXEC. */
733             if ((flags = fcntl(fd, F_GETFD)) < 0 ||
734                 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
735                 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
736             }
737
738             struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
739             ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
740             ev_io_start(main_loop, ipc_io);
741         }
742     }
743
744     /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
745     x_set_i3_atoms();
746
747     struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
748     struct ev_io *xkb = scalloc(sizeof(struct ev_io));
749     struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
750     struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
751
752     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
753     ev_io_start(main_loop, xcb_watcher);
754
755
756     if (xkb_supported) {
757         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
758         ev_io_start(main_loop, xkb);
759
760         /* Flush the buffer so that libev can properly get new events */
761         XFlush(xkbdpy);
762     }
763
764     ev_check_init(xcb_check, xcb_check_cb);
765     ev_check_start(main_loop, xcb_check);
766
767     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
768     ev_prepare_start(main_loop, xcb_prepare);
769
770     xcb_flush(conn);
771
772     manage_existing_windows(root);
773
774     struct sigaction action;
775
776     action.sa_sigaction = handle_signal;
777     action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
778     sigemptyset(&action.sa_mask);
779
780     if (!disable_signalhandler)
781         setup_signal_handler();
782     else {
783         /* Catch all signals with default action "Core", see signal(7) */
784         if (sigaction(SIGQUIT, &action, NULL) == -1 ||
785             sigaction(SIGILL, &action, NULL) == -1 ||
786             sigaction(SIGABRT, &action, NULL) == -1 ||
787             sigaction(SIGFPE, &action, NULL) == -1 ||
788             sigaction(SIGSEGV, &action, NULL) == -1)
789             ELOG("Could not setup signal handler");
790     }
791
792     /* Catch all signals with default action "Term", see signal(7) */
793     if (sigaction(SIGHUP, &action, NULL) == -1 ||
794         sigaction(SIGINT, &action, NULL) == -1 ||
795         sigaction(SIGALRM, &action, NULL) == -1 ||
796         sigaction(SIGUSR1, &action, NULL) == -1 ||
797         sigaction(SIGUSR2, &action, NULL) == -1)
798         ELOG("Could not setup signal handler");
799
800     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
801      * while we are sending him a message */
802     signal(SIGPIPE, SIG_IGN);
803
804     /* Autostarting exec-lines */
805     if (autostart) {
806         struct Autostart *exec;
807         TAILQ_FOREACH(exec, &autostarts, autostarts) {
808             LOG("auto-starting %s\n", exec->command);
809             start_application(exec->command, exec->no_startup_id);
810         }
811     }
812
813     /* Autostarting exec_always-lines */
814     struct Autostart *exec_always;
815     TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
816         LOG("auto-starting (always!) %s\n", exec_always->command);
817         start_application(exec_always->command, exec_always->no_startup_id);
818     }
819
820     /* Start i3bar processes for all configured bars */
821     Barconfig *barconfig;
822     TAILQ_FOREACH(barconfig, &barconfigs, configs) {
823         char *command = NULL;
824         sasprintf(&command, "%s --bar_id=%s --socket=\"%s\"",
825                 barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
826                 barconfig->id, current_socketpath);
827         LOG("Starting bar process: %s\n", command);
828         start_application(command, true);
829         free(command);
830     }
831
832     /* Make sure to destroy the event loop to invoke the cleeanup callbacks
833      * when calling exit() */
834     atexit(i3_exit);
835
836     ev_loop(main_loop, 0);
837 }