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