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