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