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