]> 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 #include <ev.h>
5 #include <fcntl.h>
6 #include "all.h"
7
8 #include "sd-daemon.h"
9
10 static int xkb_event_base;
11
12 int xkb_current_group;
13
14 extern Con *focused;
15
16 char **start_argv;
17
18 xcb_connection_t *conn;
19
20 xcb_screen_t *root_screen;
21 xcb_window_t root;
22 uint8_t root_depth;
23
24 struct ev_loop *main_loop;
25
26 xcb_key_symbols_t *keysyms;
27
28 /* Those are our connections to X11 for use with libXcursor and XKB */
29 Display *xlibdpy, *xkbdpy;
30
31 /* The list of key bindings */
32 struct bindings_head *bindings;
33
34 /* The list of exec-lines */
35 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
36
37 /* The list of exec_always lines */
38 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
39
40 /* The list of assignments */
41 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
42
43 /* The list of workspace assignments (which workspace should end up on which
44  * output) */
45 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
46
47 /* We hope that those are supported and set them to true */
48 bool xcursor_supported = true;
49 bool xkb_supported = true;
50
51 /*
52  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
53  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
54  *
55  */
56 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
57     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
58 }
59
60 /*
61  * Flush before blocking (and waiting for new events)
62  *
63  */
64 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
65     xcb_flush(conn);
66 }
67
68 /*
69  * Instead of polling the X connection socket we leave this to
70  * xcb_poll_for_event() which knows better than we can ever know.
71  *
72  */
73 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
74     xcb_generic_event_t *event;
75
76     while ((event = xcb_poll_for_event(conn)) != NULL) {
77         if (event->response_type == 0) {
78             if (event_is_ignored(event->sequence, 0))
79                 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
80             else {
81                 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
82                 ELOG("X11 Error received! sequence 0x%x, error_code = %d\n",
83                      error->sequence, error->error_code);
84             }
85             free(event);
86             continue;
87         }
88
89         /* Strip off the highest bit (set if the event is generated) */
90         int type = (event->response_type & 0x7F);
91
92         handle_event(type, event);
93
94         free(event);
95     }
96 }
97
98
99 /*
100  * When using xmodmap to change the keyboard mapping, this event
101  * is only sent via XKB. Therefore, we need this special handler.
102  *
103  */
104 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
105     DLOG("Handling XKB event\n");
106     XkbEvent ev;
107
108     /* When using xmodmap, every change (!) gets an own event.
109      * Therefore, we just read all events and only handle the
110      * mapping_notify once. */
111     bool mapping_changed = false;
112     while (XPending(xkbdpy)) {
113         XNextEvent(xkbdpy, (XEvent*)&ev);
114         /* While we should never receive a non-XKB event,
115          * better do sanity checking */
116         if (ev.type != xkb_event_base)
117             continue;
118
119         if (ev.any.xkb_type == XkbMapNotify) {
120             mapping_changed = true;
121             continue;
122         }
123
124         if (ev.any.xkb_type != XkbStateNotify) {
125             ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
126             continue;
127         }
128
129         /* See The XKB Extension: Library Specification, section 14.1 */
130         /* We check if the current group (each group contains
131          * two levels) has been changed. Mode_switch activates
132          * group XkbGroup2Index */
133         if (xkb_current_group == ev.state.group)
134             continue;
135
136         xkb_current_group = ev.state.group;
137
138         if (ev.state.group == XkbGroup2Index) {
139             DLOG("Mode_switch enabled\n");
140             grab_all_keys(conn, true);
141         }
142
143         if (ev.state.group == XkbGroup1Index) {
144             DLOG("Mode_switch disabled\n");
145             ungrab_all_keys(conn);
146             grab_all_keys(conn, false);
147         }
148     }
149
150     if (!mapping_changed)
151         return;
152
153     DLOG("Keyboard mapping changed, updating keybindings\n");
154     xcb_key_symbols_free(keysyms);
155     keysyms = xcb_key_symbols_alloc(conn);
156
157     xcb_get_numlock_mask(conn);
158
159     ungrab_all_keys(conn);
160     DLOG("Re-grabbing...\n");
161     translate_keysyms();
162     grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
163     DLOG("Done\n");
164 }
165
166 int main(int argc, char *argv[]) {
167     //parse_cmd("[ foo ] attach, attach ; focus");
168     int screens;
169     char *override_configpath = NULL;
170     bool autostart = true;
171     char *layout_path = NULL;
172     bool delete_layout_path = false;
173     bool only_check_config = false;
174     bool force_xinerama = false;
175     bool disable_signalhandler = false;
176     static struct option long_options[] = {
177         {"no-autostart", no_argument, 0, 'a'},
178         {"config", required_argument, 0, 'c'},
179         {"version", no_argument, 0, 'v'},
180         {"help", no_argument, 0, 'h'},
181         {"layout", required_argument, 0, 'L'},
182         {"restart", required_argument, 0, 0},
183         {"force-xinerama", no_argument, 0, 0},
184         {"disable-signalhandler", no_argument, 0, 0},
185         {0, 0, 0, 0}
186     };
187     int option_index = 0, opt;
188
189     setlocale(LC_ALL, "");
190
191     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
192     if (!isatty(fileno(stdout)))
193         setbuf(stdout, NULL);
194
195     init_logging();
196
197     start_argv = argv;
198
199     while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
200         switch (opt) {
201             case 'a':
202                 LOG("Autostart disabled using -a\n");
203                 autostart = false;
204                 break;
205             case 'L':
206                 FREE(layout_path);
207                 layout_path = sstrdup(optarg);
208                 delete_layout_path = false;
209                 break;
210             case 'c':
211                 FREE(override_configpath);
212                 override_configpath = sstrdup(optarg);
213                 break;
214             case 'C':
215                 LOG("Checking configuration file only (-C)\n");
216                 only_check_config = true;
217                 break;
218             case 'v':
219                 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
220                 exit(EXIT_SUCCESS);
221             case 'V':
222                 set_verbosity(true);
223                 break;
224             case 'd':
225                 LOG("Enabling debug loglevel %s\n", optarg);
226                 add_loglevel(optarg);
227                 break;
228             case 'l':
229                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
230                 break;
231             case 0:
232                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
233                     force_xinerama = true;
234                     ELOG("Using Xinerama instead of RandR. This option should be "
235                          "avoided at all cost because it does not refresh the list "
236                          "of screens, so you cannot configure displays at runtime. "
237                          "Please check if your driver really does not support RandR "
238                          "and disable this option as soon as you can.\n");
239                     break;
240                 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
241                     disable_signalhandler = true;
242                     break;
243                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
244                     FREE(layout_path);
245                     layout_path = sstrdup(optarg);
246                     delete_layout_path = true;
247                     break;
248                 }
249                 /* fall-through */
250             default:
251                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
252                 fprintf(stderr, "\n");
253                 fprintf(stderr, "-a: disable autostart\n");
254                 fprintf(stderr, "-L <layoutfile>: load the layout from <layoutfile>\n");
255                 fprintf(stderr, "-v: display version and exit\n");
256                 fprintf(stderr, "-V: enable verbose mode\n");
257                 fprintf(stderr, "-d <loglevel>: enable debug loglevel <loglevel>\n");
258                 fprintf(stderr, "-c <configfile>: use the provided configfile instead\n");
259                 fprintf(stderr, "-C: check configuration file and exit\n");
260                 fprintf(stderr, "--force-xinerama: Use Xinerama instead of RandR. This "
261                                 "option should only be used if you are stuck with the "
262                                 "nvidia closed source driver which does not support RandR.\n");
263                 exit(EXIT_FAILURE);
264         }
265     }
266
267     LOG("i3 (tree) version " I3_VERSION " starting\n");
268
269     conn = xcb_connect(NULL, &screens);
270     if (xcb_connection_has_error(conn))
271         errx(EXIT_FAILURE, "Cannot open display\n");
272
273     /* Initialize the libev event loop. This needs to be done before loading
274      * the config file because the parser will install an ev_child watcher
275      * for the nagbar when config errors are found. */
276     main_loop = EV_DEFAULT;
277     if (main_loop == NULL)
278             die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
279
280     root_screen = xcb_aux_get_screen(conn, screens);
281     root = root_screen->root;
282     root_depth = root_screen->root_depth;
283     xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
284     xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
285
286     load_configuration(conn, override_configpath, false);
287     if (only_check_config) {
288         LOG("Done checking configuration file. Exiting.\n");
289         exit(0);
290     }
291
292     if (config.ipc_socket_path == NULL) {
293         /* Fall back to a file name in /tmp/ based on the PID */
294         if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
295             config.ipc_socket_path = get_process_filename("ipc-socket");
296         else
297             config.ipc_socket_path = sstrdup(config.ipc_socket_path);
298     }
299
300     uint32_t mask = XCB_CW_EVENT_MASK;
301     uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
302                           XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
303                                                                            projector), the root window gets a
304                                                                            ConfigureNotify */
305                           XCB_EVENT_MASK_POINTER_MOTION |
306                           XCB_EVENT_MASK_PROPERTY_CHANGE |
307                           XCB_EVENT_MASK_ENTER_WINDOW };
308     xcb_void_cookie_t cookie;
309     cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
310     check_error(conn, cookie, "Another window manager seems to be running");
311
312     xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
313     if (greply == NULL) {
314         ELOG("Could not get geometry of the root window, exiting\n");
315         return 1;
316     }
317     DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
318
319     /* Place requests for the atoms we need as soon as possible */
320     #define xmacro(atom) \
321         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
322     #include "atoms.xmacro"
323     #undef xmacro
324
325     /* Initialize the Xlib connection */
326     xlibdpy = xkbdpy = XOpenDisplay(NULL);
327
328     /* Try to load the X cursors and initialize the XKB extension */
329     if (xlibdpy == NULL) {
330         ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
331         xcursor_supported = false;
332         xkb_supported = false;
333     } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
334         ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
335         return 1;
336     } else {
337         xcursor_load_cursors();
338         /*init_xkb();*/
339     }
340
341     /* Set a cursor for the root window (otherwise the root window will show no
342        cursor until the first client is launched). */
343     if (xcursor_supported) {
344         xcursor_set_root_cursor();
345     } else {
346         xcb_cursor_t cursor_id = xcb_generate_id(conn);
347         i3Font cursor_font = load_font("cursor", false);
348         int xcb_cursor = xcursor_get_xcb_cursor(XCURSOR_CURSOR_POINTER);
349         xcb_create_glyph_cursor(conn, cursor_id, cursor_font.id, cursor_font.id,
350                 xcb_cursor, xcb_cursor + 1, 0, 0, 0, 65535, 65535, 65535);
351         xcb_change_window_attributes(conn, root, XCB_CW_CURSOR, &cursor_id);
352         xcb_free_cursor(conn, cursor_id);
353     }
354
355     if (xkb_supported) {
356         int errBase,
357             major = XkbMajorVersion,
358             minor = XkbMinorVersion;
359
360         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
361             fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
362             return 1;
363         }
364
365         int i1;
366         if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
367             fprintf(stderr, "XKB not supported by X-server\n");
368             return 1;
369         }
370         /* end of ugliness */
371
372         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
373                              XkbMapNotifyMask | XkbStateNotifyMask,
374                              XkbMapNotifyMask | XkbStateNotifyMask)) {
375             fprintf(stderr, "Could not set XKB event mask\n");
376             return 1;
377         }
378     }
379
380     /* Setup NetWM atoms */
381     #define xmacro(name) \
382         do { \
383             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
384             if (!reply) { \
385                 ELOG("Could not get atom " #name "\n"); \
386                 exit(-1); \
387             } \
388             A_ ## name = reply->atom; \
389             free(reply); \
390         } while (0);
391     #include "atoms.xmacro"
392     #undef xmacro
393
394     property_handlers_init();
395
396     /* Set up the atoms we support */
397     xcb_atom_t supported_atoms[] = {
398 #define xmacro(atom) A_ ## atom,
399 #include "atoms.xmacro"
400 #undef xmacro
401     };
402     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, XCB_ATOM_ATOM, 32, 16, supported_atoms);
403     /* Set up the window manager’s name */
404     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, XCB_ATOM_WINDOW, 32, 1, &root);
405     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
406
407     keysyms = xcb_key_symbols_alloc(conn);
408
409     xcb_get_numlock_mask(conn);
410
411     translate_keysyms();
412     grab_all_keys(conn, false);
413
414     bool needs_tree_init = true;
415     if (layout_path) {
416         LOG("Trying to restore the layout from %s...", layout_path);
417         needs_tree_init = !tree_restore(layout_path, greply);
418         if (delete_layout_path)
419             unlink(layout_path);
420         free(layout_path);
421     }
422     if (needs_tree_init)
423         tree_init(greply);
424
425     free(greply);
426
427     if (force_xinerama) {
428         xinerama_init();
429     } else {
430         DLOG("Checking for XRandR...\n");
431         randr_init(&randr_base);
432     }
433
434     xcb_query_pointer_reply_t *pointerreply;
435     Output *output = NULL;
436     if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
437         ELOG("Could not query pointer position, using first screen\n");
438         output = get_first_output();
439     } else {
440         DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
441         output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
442         if (!output) {
443             ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
444                  pointerreply->root_x, pointerreply->root_y);
445             output = get_first_output();
446         }
447
448         con_focus(con_descend_focused(output_get_content(output->con)));
449     }
450
451     tree_render();
452
453     /* Create the UNIX domain socket for IPC */
454     int ipc_socket = ipc_create_socket(config.ipc_socket_path);
455     if (ipc_socket == -1) {
456         ELOG("Could not create the IPC socket, IPC disabled\n");
457     } else {
458         free(config.ipc_socket_path);
459         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
460         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
461         ev_io_start(main_loop, ipc_io);
462     }
463
464     /* Also handle the UNIX domain sockets passed via socket activation */
465     int fds = sd_listen_fds(1);
466     if (fds < 0)
467         ELOG("socket activation: Error in sd_listen_fds\n");
468     else if (fds == 0)
469         DLOG("socket activation: no sockets passed\n");
470     else {
471         for (int fd = SD_LISTEN_FDS_START; fd < (SD_LISTEN_FDS_START + fds); fd++) {
472             DLOG("socket activation: also listening on fd %d\n", fd);
473             struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
474             ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
475             ev_io_start(main_loop, ipc_io);
476         }
477     }
478
479     /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
480     x_set_i3_atoms();
481
482     struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
483     struct ev_io *xkb = scalloc(sizeof(struct ev_io));
484     struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
485     struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
486
487     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
488     ev_io_start(main_loop, xcb_watcher);
489
490
491     if (xkb_supported) {
492         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
493         ev_io_start(main_loop, xkb);
494
495         /* Flush the buffer so that libev can properly get new events */
496         XFlush(xkbdpy);
497     }
498
499     ev_check_init(xcb_check, xcb_check_cb);
500     ev_check_start(main_loop, xcb_check);
501
502     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
503     ev_prepare_start(main_loop, xcb_prepare);
504
505     xcb_flush(conn);
506
507     manage_existing_windows(root);
508
509     if (!disable_signalhandler)
510         setup_signal_handler();
511
512     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
513      * while we are sending him a message */
514     signal(SIGPIPE, SIG_IGN);
515
516     /* Autostarting exec-lines */
517     if (autostart) {
518         struct Autostart *exec;
519         TAILQ_FOREACH(exec, &autostarts, autostarts) {
520             LOG("auto-starting %s\n", exec->command);
521             start_application(exec->command);
522         }
523     }
524
525     /* Autostarting exec_always-lines */
526     struct Autostart *exec_always;
527     TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
528         LOG("auto-starting (always!) %s\n", exec_always->command);
529         start_application(exec_always->command);
530     }
531
532     ev_loop(main_loop, 0);
533 }