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