]> git.sur5r.net Git - i3/i3/blob - src/main.c
062a48626d8765d1a99bd803847fe952b8fa424f
[i3/i3] / src / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2011 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 "all.h"
18
19 #include "sd-daemon.h"
20
21 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
22  * this before starting any other process, since we set RLIMIT_CORE to
23  * RLIM_INFINITY for i3 debugging versions. */
24 struct rlimit original_rlimit_core;
25
26 static int xkb_event_base;
27
28 int xkb_current_group;
29
30 extern Con *focused;
31
32 char **start_argv;
33
34 xcb_connection_t *conn;
35 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
36 int conn_screen;
37
38 /* Display handle for libstartup-notification */
39 SnDisplay *sndisplay;
40
41 /* The last timestamp we got from X11 (timestamps are included in some events
42  * and are used for some things, like determining a unique ID in startup
43  * notification). */
44 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
45
46 xcb_screen_t *root_screen;
47 xcb_window_t root;
48 uint8_t root_depth;
49
50 struct ev_loop *main_loop;
51
52 xcb_key_symbols_t *keysyms;
53
54 /* Those are our connections to X11 for use with libXcursor and XKB */
55 Display *xlibdpy, *xkbdpy;
56
57 /* The list of key bindings */
58 struct bindings_head *bindings;
59
60 /* The list of exec-lines */
61 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
62
63 /* The list of exec_always lines */
64 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
65
66 /* The list of assignments */
67 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
68
69 /* The list of workspace assignments (which workspace should end up on which
70  * output) */
71 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
72
73 /* We hope that those are supported and set them to true */
74 bool xcursor_supported = true;
75 bool xkb_supported = true;
76
77 /* This will be set to true when -C is used so that functions can behave
78  * slightly differently. We don’t want i3-nagbar to be started when validating
79  * the config, for example. */
80 bool only_check_config = false;
81
82 /*
83  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
84  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
85  *
86  */
87 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
88     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
89 }
90
91 /*
92  * Flush before blocking (and waiting for new events)
93  *
94  */
95 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
96     xcb_flush(conn);
97 }
98
99 /*
100  * Instead of polling the X connection socket we leave this to
101  * xcb_poll_for_event() which knows better than we can ever know.
102  *
103  */
104 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
105     xcb_generic_event_t *event;
106
107     while ((event = xcb_poll_for_event(conn)) != NULL) {
108         if (event->response_type == 0) {
109             if (event_is_ignored(event->sequence, 0))
110                 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
111             else {
112                 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
113                 ELOG("X11 Error received! sequence 0x%x, error_code = %d\n",
114                      error->sequence, error->error_code);
115             }
116             free(event);
117             continue;
118         }
119
120         /* Strip off the highest bit (set if the event is generated) */
121         int type = (event->response_type & 0x7F);
122
123         handle_event(type, event);
124
125         free(event);
126     }
127 }
128
129
130 /*
131  * When using xmodmap to change the keyboard mapping, this event
132  * is only sent via XKB. Therefore, we need this special handler.
133  *
134  */
135 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
136     DLOG("Handling XKB event\n");
137     XkbEvent ev;
138
139     /* When using xmodmap, every change (!) gets an own event.
140      * Therefore, we just read all events and only handle the
141      * mapping_notify once. */
142     bool mapping_changed = false;
143     while (XPending(xkbdpy)) {
144         XNextEvent(xkbdpy, (XEvent*)&ev);
145         /* While we should never receive a non-XKB event,
146          * better do sanity checking */
147         if (ev.type != xkb_event_base)
148             continue;
149
150         if (ev.any.xkb_type == XkbMapNotify) {
151             mapping_changed = true;
152             continue;
153         }
154
155         if (ev.any.xkb_type != XkbStateNotify) {
156             ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
157             continue;
158         }
159
160         /* See The XKB Extension: Library Specification, section 14.1 */
161         /* We check if the current group (each group contains
162          * two levels) has been changed. Mode_switch activates
163          * group XkbGroup2Index */
164         if (xkb_current_group == ev.state.group)
165             continue;
166
167         xkb_current_group = ev.state.group;
168
169         if (ev.state.group == XkbGroup2Index) {
170             DLOG("Mode_switch enabled\n");
171             grab_all_keys(conn, true);
172         }
173
174         if (ev.state.group == XkbGroup1Index) {
175             DLOG("Mode_switch disabled\n");
176             ungrab_all_keys(conn);
177             grab_all_keys(conn, false);
178         }
179     }
180
181     if (!mapping_changed)
182         return;
183
184     DLOG("Keyboard mapping changed, updating keybindings\n");
185     xcb_key_symbols_free(keysyms);
186     keysyms = xcb_key_symbols_alloc(conn);
187
188     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
189
190     ungrab_all_keys(conn);
191     DLOG("Re-grabbing...\n");
192     translate_keysyms();
193     grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
194     DLOG("Done\n");
195 }
196
197 /*
198  * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
199  *
200  */
201 static void i3_exit() {
202 /* We need ev >= 4 for the following code. Since it is not *that* important (it
203  * only makes sure that there are no i3-nagbar instances left behind) we still
204  * support old systems with libev 3. */
205 #if EV_VERSION_MAJOR >= 4
206     ev_loop_destroy(main_loop);
207 #endif
208 }
209
210 int main(int argc, char *argv[]) {
211     char *override_configpath = NULL;
212     bool autostart = true;
213     char *layout_path = NULL;
214     bool delete_layout_path = false;
215     bool force_xinerama = false;
216     bool disable_signalhandler = false;
217     static struct option long_options[] = {
218         {"no-autostart", no_argument, 0, 'a'},
219         {"config", required_argument, 0, 'c'},
220         {"version", no_argument, 0, 'v'},
221         {"help", no_argument, 0, 'h'},
222         {"layout", required_argument, 0, 'L'},
223         {"restart", required_argument, 0, 0},
224         {"force-xinerama", no_argument, 0, 0},
225         {"force_xinerama", no_argument, 0, 0},
226         {"disable-signalhandler", no_argument, 0, 0},
227         {"get-socketpath", no_argument, 0, 0},
228         {"get_socketpath", no_argument, 0, 0},
229         {0, 0, 0, 0}
230     };
231     int option_index = 0, opt;
232
233     setlocale(LC_ALL, "");
234
235     /* Get the RLIMIT_CORE limit at startup time to restore this before
236      * starting processes. */
237     getrlimit(RLIMIT_CORE, &original_rlimit_core);
238
239     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
240     if (!isatty(fileno(stdout)))
241         setbuf(stdout, NULL);
242
243     srand(time(NULL));
244
245     init_logging();
246
247     start_argv = argv;
248
249     while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
250         switch (opt) {
251             case 'a':
252                 LOG("Autostart disabled using -a\n");
253                 autostart = false;
254                 break;
255             case 'L':
256                 FREE(layout_path);
257                 layout_path = sstrdup(optarg);
258                 delete_layout_path = false;
259                 break;
260             case 'c':
261                 FREE(override_configpath);
262                 override_configpath = sstrdup(optarg);
263                 break;
264             case 'C':
265                 LOG("Checking configuration file only (-C)\n");
266                 only_check_config = true;
267                 break;
268             case 'v':
269                 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
270                 exit(EXIT_SUCCESS);
271             case 'V':
272                 set_verbosity(true);
273                 break;
274             case 'd':
275                 LOG("Enabling debug loglevel %s\n", optarg);
276                 add_loglevel(optarg);
277                 break;
278             case 'l':
279                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
280                 break;
281             case 0:
282                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
283                     strcmp(long_options[option_index].name, "force_xinerama") == 0) {
284                     force_xinerama = true;
285                     ELOG("Using Xinerama instead of RandR. This option should be "
286                          "avoided at all cost because it does not refresh the list "
287                          "of screens, so you cannot configure displays at runtime. "
288                          "Please check if your driver really does not support RandR "
289                          "and disable this option as soon as you can.\n");
290                     break;
291                 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
292                     disable_signalhandler = true;
293                     break;
294                 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
295                            strcmp(long_options[option_index].name, "get_socketpath") == 0) {
296                     char *socket_path = socket_path_from_x11();
297                     if (socket_path) {
298                         printf("%s\n", socket_path);
299                         return 0;
300                     }
301
302                     return 1;
303                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
304                     FREE(layout_path);
305                     layout_path = sstrdup(optarg);
306                     delete_layout_path = true;
307                     break;
308                 }
309                 /* fall-through */
310             default:
311                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
312                 fprintf(stderr, "\n");
313                 fprintf(stderr, "\t-a          disable autostart ('exec' lines in config)\n");
314                 fprintf(stderr, "\t-c <file>   use the provided configfile instead\n");
315                 fprintf(stderr, "\t-C          validate configuration file and exit\n");
316                 fprintf(stderr, "\t-d <level>  enable debug output with the specified loglevel\n");
317                 fprintf(stderr, "\t-L <file>   path to the serialized layout during restarts\n");
318                 fprintf(stderr, "\t-v          display version and exit\n");
319                 fprintf(stderr, "\t-V          enable verbose mode\n");
320                 fprintf(stderr, "\n");
321                 fprintf(stderr, "\t--force-xinerama\n"
322                                 "\tUse Xinerama instead of RandR.\n"
323                                 "\tThis option should only be used if you are stuck with the\n"
324                                 "\tnvidia closed source driver which does not support RandR.\n");
325                 fprintf(stderr, "\n");
326                 fprintf(stderr, "\t--get-socketpath\n"
327                                 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
328                 fprintf(stderr, "\n");
329                 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
330                                 "to send to a currently running i3 (like i3-msg). This allows you to\n"
331                                 "use nice and logical commands, such as:\n"
332                                 "\n"
333                                 "\ti3 border none\n"
334                                 "\ti3 floating toggle\n"
335                                 "\ti3 kill window\n"
336                                 "\n");
337                 exit(EXIT_FAILURE);
338         }
339     }
340
341     /* If the user passes more arguments, we act like i3-msg would: Just send
342      * the arguments as an IPC message to i3. This allows for nice semantic
343      * commands such as 'i3 border none'. */
344     if (optind < argc) {
345         /* We enable verbose mode so that the user knows what’s going on.
346          * This should make it easier to find mistakes when the user passes
347          * arguments by mistake. */
348         set_verbosity(true);
349
350         LOG("Additional arguments passed. Sending them as a command to i3.\n");
351         char *payload = NULL;
352         while (optind < argc) {
353             if (!payload) {
354                 payload = sstrdup(argv[optind]);
355             } else {
356                 char *both;
357                 sasprintf(&both, "%s %s", payload, argv[optind]);
358                 free(payload);
359                 payload = both;
360             }
361             optind++;
362         }
363         LOG("Command is: %s (%d bytes)\n", payload, strlen(payload));
364         char *socket_path = socket_path_from_x11();
365         if (!socket_path) {
366             ELOG("Could not get i3 IPC socket path\n");
367             return 1;
368         }
369
370         int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
371         if (sockfd == -1)
372             err(EXIT_FAILURE, "Could not create socket");
373
374         struct sockaddr_un addr;
375         memset(&addr, 0, sizeof(struct sockaddr_un));
376         addr.sun_family = AF_LOCAL;
377         strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
378         if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
379             err(EXIT_FAILURE, "Could not connect to i3");
380
381         if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
382                              (uint8_t*)payload) == -1)
383             err(EXIT_FAILURE, "IPC: write()");
384
385         uint32_t reply_length;
386         uint8_t *reply;
387         int ret;
388         if ((ret = ipc_recv_message(sockfd, I3_IPC_MESSAGE_TYPE_COMMAND,
389                                     &reply_length, &reply)) != 0) {
390             if (ret == -1)
391                 err(EXIT_FAILURE, "IPC: read()");
392             return 1;
393         }
394         printf("%.*s\n", reply_length, reply);
395         return 0;
396     }
397
398     /* I3_VERSION contains either something like this:
399      *     "4.0.2 (2011-11-11, branch "release")".
400      * or: "4.0.2-123-gCOFFEEBABE (2011-11-11, branch "next")".
401      *
402      * So we check for the offset of the first opening round bracket to
403      * determine whether this is a git version or a release version. */
404     if ((strchr(I3_VERSION, '(') - I3_VERSION) > 10) {
405         struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY };
406         setrlimit(RLIMIT_CORE, &limit);
407
408         /* The following code is helpful, but not required. We thus don’t pay
409          * much attention to error handling, non-linux or other edge cases. */
410         char cwd[PATH_MAX];
411         LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
412         if (getcwd(cwd, sizeof(cwd)) != NULL)
413             LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
414         int patternfd;
415         if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
416             memset(cwd, '\0', sizeof(cwd));
417             if (read(patternfd, cwd, sizeof(cwd)) > 0)
418                 /* a trailing newline is included in cwd */
419                 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
420             close(patternfd);
421         }
422     }
423
424     LOG("i3 (tree) version " I3_VERSION " starting\n");
425
426     conn = xcb_connect(NULL, &conn_screen);
427     if (xcb_connection_has_error(conn))
428         errx(EXIT_FAILURE, "Cannot open display\n");
429
430     sndisplay = sn_xcb_display_new(conn, NULL, NULL);
431
432     /* Initialize the libev event loop. This needs to be done before loading
433      * the config file because the parser will install an ev_child watcher
434      * for the nagbar when config errors are found. */
435     main_loop = EV_DEFAULT;
436     if (main_loop == NULL)
437             die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
438
439     root_screen = xcb_aux_get_screen(conn, conn_screen);
440     root = root_screen->root;
441     root_depth = root_screen->root_depth;
442     xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
443     xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
444
445     load_configuration(conn, override_configpath, false);
446     if (only_check_config) {
447         LOG("Done checking configuration file. Exiting.\n");
448         exit(0);
449     }
450
451     if (config.ipc_socket_path == NULL) {
452         /* Fall back to a file name in /tmp/ based on the PID */
453         if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
454             config.ipc_socket_path = get_process_filename("ipc-socket");
455         else
456             config.ipc_socket_path = sstrdup(config.ipc_socket_path);
457     }
458
459     uint32_t mask = XCB_CW_EVENT_MASK;
460     uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
461                           XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
462                                                                            projector), the root window gets a
463                                                                            ConfigureNotify */
464                           XCB_EVENT_MASK_POINTER_MOTION |
465                           XCB_EVENT_MASK_PROPERTY_CHANGE |
466                           XCB_EVENT_MASK_ENTER_WINDOW };
467     xcb_void_cookie_t cookie;
468     cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
469     check_error(conn, cookie, "Another window manager seems to be running");
470
471     xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
472     if (greply == NULL) {
473         ELOG("Could not get geometry of the root window, exiting\n");
474         return 1;
475     }
476     DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
477
478     /* Place requests for the atoms we need as soon as possible */
479     #define xmacro(atom) \
480         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
481     #include "atoms.xmacro"
482     #undef xmacro
483
484     /* Initialize the Xlib connection */
485     xlibdpy = xkbdpy = XOpenDisplay(NULL);
486
487     /* Try to load the X cursors and initialize the XKB extension */
488     if (xlibdpy == NULL) {
489         ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
490         xcursor_supported = false;
491         xkb_supported = false;
492     } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
493         ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
494         return 1;
495     } else {
496         xcursor_load_cursors();
497         /*init_xkb();*/
498     }
499
500     /* Set a cursor for the root window (otherwise the root window will show no
501        cursor until the first client is launched). */
502     if (xcursor_supported)
503         xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
504     else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
505
506     if (xkb_supported) {
507         int errBase,
508             major = XkbMajorVersion,
509             minor = XkbMinorVersion;
510
511         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
512             fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
513             return 1;
514         }
515
516         int i1;
517         if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
518             fprintf(stderr, "XKB not supported by X-server\n");
519             return 1;
520         }
521         /* end of ugliness */
522
523         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
524                              XkbMapNotifyMask | XkbStateNotifyMask,
525                              XkbMapNotifyMask | XkbStateNotifyMask)) {
526             fprintf(stderr, "Could not set XKB event mask\n");
527             return 1;
528         }
529     }
530
531     /* Setup NetWM atoms */
532     #define xmacro(name) \
533         do { \
534             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
535             if (!reply) { \
536                 ELOG("Could not get atom " #name "\n"); \
537                 exit(-1); \
538             } \
539             A_ ## name = reply->atom; \
540             free(reply); \
541         } while (0);
542     #include "atoms.xmacro"
543     #undef xmacro
544
545     property_handlers_init();
546
547     /* Set up the atoms we support */
548     xcb_atom_t supported_atoms[] = {
549 #define xmacro(atom) A_ ## atom,
550 #include "atoms.xmacro"
551 #undef xmacro
552     };
553     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, XCB_ATOM_ATOM, 32, 16, supported_atoms);
554     /* Set up the window manager’s name */
555     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, XCB_ATOM_WINDOW, 32, 1, &root);
556     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
557
558     keysyms = xcb_key_symbols_alloc(conn);
559
560     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
561
562     translate_keysyms();
563     grab_all_keys(conn, false);
564
565     bool needs_tree_init = true;
566     if (layout_path) {
567         LOG("Trying to restore the layout from %s...", layout_path);
568         needs_tree_init = !tree_restore(layout_path, greply);
569         if (delete_layout_path)
570             unlink(layout_path);
571         free(layout_path);
572     }
573     if (needs_tree_init)
574         tree_init(greply);
575
576     free(greply);
577
578     /* Force Xinerama (for drivers which don't support RandR yet, esp. the
579      * nVidia binary graphics driver), when specified either in the config
580      * file or on command-line */
581     if (force_xinerama || config.force_xinerama) {
582         xinerama_init();
583     } else {
584         DLOG("Checking for XRandR...\n");
585         randr_init(&randr_base);
586     }
587
588     xcb_query_pointer_reply_t *pointerreply;
589     Output *output = NULL;
590     if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
591         ELOG("Could not query pointer position, using first screen\n");
592         output = get_first_output();
593     } else {
594         DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
595         output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
596         if (!output) {
597             ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
598                  pointerreply->root_x, pointerreply->root_y);
599             output = get_first_output();
600         }
601
602         con_focus(con_descend_focused(output_get_content(output->con)));
603     }
604
605     tree_render();
606
607     /* Create the UNIX domain socket for IPC */
608     int ipc_socket = ipc_create_socket(config.ipc_socket_path);
609     if (ipc_socket == -1) {
610         ELOG("Could not create the IPC socket, IPC disabled\n");
611     } else {
612         free(config.ipc_socket_path);
613         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
614         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
615         ev_io_start(main_loop, ipc_io);
616     }
617
618     /* Also handle the UNIX domain sockets passed via socket activation */
619     int fds = sd_listen_fds(1);
620     if (fds < 0)
621         ELOG("socket activation: Error in sd_listen_fds\n");
622     else if (fds == 0)
623         DLOG("socket activation: no sockets passed\n");
624     else {
625         for (int fd = SD_LISTEN_FDS_START; fd < (SD_LISTEN_FDS_START + fds); fd++) {
626             DLOG("socket activation: also listening on fd %d\n", fd);
627             struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
628             ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
629             ev_io_start(main_loop, ipc_io);
630         }
631     }
632
633     /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
634     x_set_i3_atoms();
635
636     struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
637     struct ev_io *xkb = scalloc(sizeof(struct ev_io));
638     struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
639     struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
640
641     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
642     ev_io_start(main_loop, xcb_watcher);
643
644
645     if (xkb_supported) {
646         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
647         ev_io_start(main_loop, xkb);
648
649         /* Flush the buffer so that libev can properly get new events */
650         XFlush(xkbdpy);
651     }
652
653     ev_check_init(xcb_check, xcb_check_cb);
654     ev_check_start(main_loop, xcb_check);
655
656     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
657     ev_prepare_start(main_loop, xcb_prepare);
658
659     xcb_flush(conn);
660
661     manage_existing_windows(root);
662
663     if (!disable_signalhandler)
664         setup_signal_handler();
665
666     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
667      * while we are sending him a message */
668     signal(SIGPIPE, SIG_IGN);
669
670     /* Autostarting exec-lines */
671     if (autostart) {
672         struct Autostart *exec;
673         TAILQ_FOREACH(exec, &autostarts, autostarts) {
674             LOG("auto-starting %s\n", exec->command);
675             start_application(exec->command, exec->no_startup_id);
676         }
677     }
678
679     /* Autostarting exec_always-lines */
680     struct Autostart *exec_always;
681     TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
682         LOG("auto-starting (always!) %s\n", exec_always->command);
683         start_application(exec_always->command, exec_always->no_startup_id);
684     }
685
686     /* Start i3bar processes for all configured bars */
687     Barconfig *barconfig;
688     TAILQ_FOREACH(barconfig, &barconfigs, configs) {
689         char *command = NULL;
690         sasprintf(&command, "i3bar --bar_id=%s --socket=\"%s\"",
691                   barconfig->id, current_socketpath);
692         LOG("Starting bar process: %s\n", command);
693         start_application(command, true);
694         free(command);
695     }
696
697     /* Make sure to destroy the event loop to invoke the cleeanup callbacks
698      * when calling exit() */
699     atexit(i3_exit);
700
701     ev_loop(main_loop, 0);
702 }