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