]> git.sur5r.net Git - i3/i3/blob - src/main.c
5736324fd15513fe398a6fc57b80ec97eff67a75
[i3/i3] / src / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  */
4 #include <ev.h>
5 #include <fcntl.h>
6 #include <limits.h>
7 #include "all.h"
8
9 static int xkb_event_base;
10
11 int xkb_current_group;
12
13 extern Con *focused;
14
15 char **start_argv;
16
17 xcb_connection_t *conn;
18 xcb_event_handlers_t evenths;
19 xcb_property_handlers_t prophs;
20 xcb_atom_t atoms[NUM_ATOMS];
21
22 xcb_window_t root;
23 uint8_t root_depth;
24
25 xcb_key_symbols_t *keysyms;
26
27 /* Those are our connections to X11 for use with libXcursor and XKB */
28 Display *xlibdpy, *xkbdpy;
29
30 /* The list of key bindings */
31 struct bindings_head *bindings;
32
33 /* The list of exec-lines */
34 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
35
36 /* The list of assignments */
37 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
38
39 /* We hope that those are supported and set them to true */
40 bool xcursor_supported = true;
41 bool xkb_supported = true;
42
43 /*
44  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
45  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
46  *
47  */
48 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
49     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
50 }
51
52 /*
53  * Flush before blocking (and waiting for new events)
54  *
55  */
56 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
57     xcb_flush(conn);
58 }
59
60 /*
61  * Instead of polling the X connection socket we leave this to
62  * xcb_poll_for_event() which knows better than we can ever know.
63  *
64  */
65 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
66     xcb_generic_event_t *event;
67
68     while ((event = xcb_poll_for_event(conn)) != NULL) {
69             xcb_event_handle(&evenths, event);
70             free(event);
71     }
72 }
73
74
75 /*
76  * When using xmodmap to change the keyboard mapping, this event
77  * is only sent via XKB. Therefore, we need this special handler.
78  *
79  */
80 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
81     DLOG("Handling XKB event\n");
82     XkbEvent ev;
83
84     /* When using xmodmap, every change (!) gets an own event.
85      * Therefore, we just read all events and only handle the
86      * mapping_notify once. */
87     bool mapping_changed = false;
88     while (XPending(xkbdpy)) {
89         XNextEvent(xkbdpy, (XEvent*)&ev);
90         /* While we should never receive a non-XKB event,
91          * better do sanity checking */
92         if (ev.type != xkb_event_base)
93             continue;
94
95         if (ev.any.xkb_type == XkbMapNotify) {
96             mapping_changed = true;
97             continue;
98         }
99
100         if (ev.any.xkb_type != XkbStateNotify) {
101             ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
102             continue;
103         }
104
105         /* See The XKB Extension: Library Specification, section 14.1 */
106         /* We check if the current group (each group contains
107          * two levels) has been changed. Mode_switch activates
108          * group XkbGroup2Index */
109         if (xkb_current_group == ev.state.group)
110             continue;
111
112         xkb_current_group = ev.state.group;
113
114         if (ev.state.group == XkbGroup2Index) {
115             DLOG("Mode_switch enabled\n");
116             grab_all_keys(conn, true);
117         }
118
119         if (ev.state.group == XkbGroup1Index) {
120             DLOG("Mode_switch disabled\n");
121             ungrab_all_keys(conn);
122             grab_all_keys(conn, false);
123         }
124     }
125
126     if (!mapping_changed)
127         return;
128
129     DLOG("Keyboard mapping changed, updating keybindings\n");
130     xcb_key_symbols_free(keysyms);
131     keysyms = xcb_key_symbols_alloc(conn);
132
133     xcb_get_numlock_mask(conn);
134
135     ungrab_all_keys(conn);
136     DLOG("Re-grabbing...\n");
137     translate_keysyms();
138     grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
139     DLOG("Done\n");
140 }
141
142 int main(int argc, char *argv[]) {
143     //parse_cmd("[ foo ] attach, attach ; focus");
144     int screens;
145     char *override_configpath = NULL;
146     bool autostart = true;
147     char *layout_path = NULL;
148     bool delete_layout_path;
149     bool only_check_config = false;
150     bool force_xinerama = false;
151     xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
152     static struct option long_options[] = {
153         {"no-autostart", no_argument, 0, 'a'},
154         {"config", required_argument, 0, 'c'},
155         {"version", no_argument, 0, 'v'},
156         {"help", no_argument, 0, 'h'},
157         {"layout", required_argument, 0, 'L'},
158         {"restart", required_argument, 0, 0},
159         {"force-xinerama", no_argument, 0, 0},
160         {0, 0, 0, 0}
161     };
162     int option_index = 0, opt;
163
164     setlocale(LC_ALL, "");
165
166     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
167     if (!isatty(fileno(stdout)))
168         setbuf(stdout, NULL);
169
170     start_argv = argv;
171
172     while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
173         switch (opt) {
174             case 'a':
175                 LOG("Autostart disabled using -a\n");
176                 autostart = false;
177                 break;
178             case 'L':
179                 FREE(layout_path);
180                 layout_path = sstrdup(optarg);
181                 delete_layout_path = false;
182                 break;
183             case 'c':
184                 FREE(override_configpath);
185                 override_configpath = sstrdup(optarg);
186                 break;
187             case 'C':
188                 LOG("Checking configuration file only (-C)\n");
189                 only_check_config = true;
190                 break;
191             case 'v':
192                 printf("i3 version " I3_VERSION " © 2009 Michael Stapelberg and contributors\n");
193                 exit(EXIT_SUCCESS);
194             case 'V':
195                 set_verbosity(true);
196                 break;
197             case 'd':
198                 LOG("Enabling debug loglevel %s\n", optarg);
199                 add_loglevel(optarg);
200                 break;
201             case 'l':
202                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
203                 break;
204             case 0:
205                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
206                     force_xinerama = true;
207                     ELOG("Using Xinerama instead of RandR. This option should be "
208                          "avoided at all cost because it does not refresh the list "
209                          "of screens, so you cannot configure displays at runtime. "
210                          "Please check if your driver really does not support RandR "
211                          "and disable this option as soon as you can.\n");
212                     break;
213                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
214                     FREE(layout_path);
215                     layout_path = sstrdup(optarg);
216                     delete_layout_path = true;
217                     break;
218                 }
219                 /* fall-through */
220             default:
221                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
222                 fprintf(stderr, "\n");
223                 fprintf(stderr, "-a: disable autostart\n");
224                 fprintf(stderr, "-L <layoutfile>: load the layout from <layoutfile>\n");
225                 fprintf(stderr, "-v: display version and exit\n");
226                 fprintf(stderr, "-V: enable verbose mode\n");
227                 fprintf(stderr, "-d <loglevel>: enable debug loglevel <loglevel>\n");
228                 fprintf(stderr, "-c <configfile>: use the provided configfile instead\n");
229                 fprintf(stderr, "-C: check configuration file and exit\n");
230                 fprintf(stderr, "--force-xinerama: Use Xinerama instead of RandR. This "
231                                 "option should only be used if you are stuck with the "
232                                 "nvidia closed source driver which does not support RandR.\n");
233                 exit(EXIT_FAILURE);
234         }
235     }
236
237     LOG("i3 (tree) version " I3_VERSION " starting\n");
238
239     conn = xcb_connect(NULL, &screens);
240     if (xcb_connection_has_error(conn))
241         errx(EXIT_FAILURE, "Cannot open display\n");
242
243     load_configuration(conn, override_configpath, false);
244     if (only_check_config) {
245         LOG("Done checking configuration file. Exiting.\n");
246         exit(0);
247     }
248
249     if (config.ipc_socket_path == NULL) {
250         config.ipc_socket_path = getenv("I3SOCK");
251     }
252
253     xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
254     root = root_screen->root;
255     root_depth = root_screen->root_depth;
256
257     uint32_t mask = XCB_CW_EVENT_MASK;
258     uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
259                           XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
260                                                                            projector), the root window gets a
261                                                                            ConfigureNotify */
262                           XCB_EVENT_MASK_POINTER_MOTION |
263                           XCB_EVENT_MASK_PROPERTY_CHANGE |
264                           XCB_EVENT_MASK_ENTER_WINDOW };
265     xcb_void_cookie_t cookie;
266     cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
267     check_error(conn, cookie, "Another window manager seems to be running");
268
269     /* Place requests for the atoms we need as soon as possible */
270     #define REQUEST_ATOM(name) atom_cookies[name] = xcb_intern_atom(conn, 0, strlen(#name), #name);
271
272     REQUEST_ATOM(_NET_SUPPORTED);
273     REQUEST_ATOM(_NET_WM_STATE_FULLSCREEN);
274     REQUEST_ATOM(_NET_SUPPORTING_WM_CHECK);
275     REQUEST_ATOM(_NET_WM_NAME);
276     REQUEST_ATOM(_NET_WM_STATE);
277     REQUEST_ATOM(_NET_WM_WINDOW_TYPE);
278     REQUEST_ATOM(_NET_WM_DESKTOP);
279     REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
280     REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
281     REQUEST_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
282     REQUEST_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
283     REQUEST_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
284     REQUEST_ATOM(_NET_WM_STRUT_PARTIAL);
285     REQUEST_ATOM(WM_PROTOCOLS);
286     REQUEST_ATOM(WM_DELETE_WINDOW);
287     REQUEST_ATOM(UTF8_STRING);
288     REQUEST_ATOM(WM_STATE);
289     REQUEST_ATOM(WM_CLIENT_LEADER);
290     REQUEST_ATOM(_NET_CURRENT_DESKTOP);
291     REQUEST_ATOM(_NET_ACTIVE_WINDOW);
292     REQUEST_ATOM(_NET_WORKAREA);
293
294     /* Initialize the Xlib connection */
295     xlibdpy = xkbdpy = XOpenDisplay(NULL);
296
297     /* Try to load the X cursors and initialize the XKB extension */
298     if (xlibdpy == NULL) {
299         ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
300         xcursor_supported = false;
301         xkb_supported = false;
302     } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
303         ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
304         return 1;
305     } else {
306         xcursor_load_cursors();
307         /*init_xkb();*/
308     }
309
310     if (xkb_supported) {
311         int errBase,
312             major = XkbMajorVersion,
313             minor = XkbMinorVersion;
314
315         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
316             fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
317             return 1;
318         }
319
320         int i1;
321         if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
322             fprintf(stderr, "XKB not supported by X-server\n");
323             return 1;
324         }
325         /* end of ugliness */
326
327         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
328                              XkbMapNotifyMask | XkbStateNotifyMask,
329                              XkbMapNotifyMask | XkbStateNotifyMask)) {
330             fprintf(stderr, "Could not set XKB event mask\n");
331             return 1;
332         }
333     }
334
335     memset(&evenths, 0, sizeof(xcb_event_handlers_t));
336     memset(&prophs, 0, sizeof(xcb_property_handlers_t));
337
338     xcb_event_handlers_init(conn, &evenths);
339     xcb_property_handlers_init(&prophs, &evenths);
340     xcb_event_set_key_press_handler(&evenths, handle_key_press, NULL);
341
342     xcb_event_set_button_press_handler(&evenths, handle_button_press, NULL);
343
344     xcb_event_set_map_request_handler(&evenths, handle_map_request, NULL);
345
346     xcb_event_set_unmap_notify_handler(&evenths, handle_unmap_notify_event, NULL);
347     xcb_event_set_destroy_notify_handler(&evenths, handle_destroy_notify_event, NULL);
348
349     xcb_event_set_expose_handler(&evenths, handle_expose_event, NULL);
350
351     xcb_event_set_motion_notify_handler(&evenths, handle_motion_notify, NULL);
352
353     /* Enter window = user moved his mouse over the window */
354     xcb_event_set_enter_notify_handler(&evenths, handle_enter_notify, NULL);
355
356     /* Client message are sent to the root window. The only interesting client message
357        for us is _NET_WM_STATE, we honour _NET_WM_STATE_FULLSCREEN */
358     xcb_event_set_client_message_handler(&evenths, handle_client_message, NULL);
359
360     /* Configure request = window tried to change size on its own */
361     xcb_event_set_configure_request_handler(&evenths, handle_configure_request, NULL);
362
363     /* Setup NetWM atoms */
364     #define GET_ATOM(name) \
365         do { \
366             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, atom_cookies[name], NULL); \
367             if (!reply) { \
368                 ELOG("Could not get atom " #name "\n"); \
369                 exit(-1); \
370             } \
371             atoms[name] = reply->atom; \
372             free(reply); \
373         } while (0)
374
375     GET_ATOM(_NET_SUPPORTED);
376     GET_ATOM(_NET_WM_STATE_FULLSCREEN);
377     GET_ATOM(_NET_SUPPORTING_WM_CHECK);
378     GET_ATOM(_NET_WM_NAME);
379     GET_ATOM(_NET_WM_STATE);
380     GET_ATOM(_NET_WM_WINDOW_TYPE);
381     GET_ATOM(_NET_WM_DESKTOP);
382     GET_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
383     GET_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
384     GET_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
385     GET_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
386     GET_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
387     GET_ATOM(_NET_WM_STRUT_PARTIAL);
388     GET_ATOM(WM_PROTOCOLS);
389     GET_ATOM(WM_DELETE_WINDOW);
390     GET_ATOM(UTF8_STRING);
391     GET_ATOM(WM_STATE);
392     GET_ATOM(WM_CLIENT_LEADER);
393     GET_ATOM(_NET_CURRENT_DESKTOP);
394     GET_ATOM(_NET_ACTIVE_WINDOW);
395     GET_ATOM(_NET_WORKAREA);
396
397     /* Watch _NET_WM_NAME (title of the window encoded in UTF-8) */
398     xcb_property_set_handler(&prophs, atoms[_NET_WM_NAME], 128, handle_windowname_change, NULL);
399
400     /* Watch WM_HINTS (contains the urgent property) */
401     xcb_property_set_handler(&prophs, WM_HINTS, UINT_MAX, handle_hints, NULL);
402
403     /* Watch WM_NAME (title of the window encoded in COMPOUND_TEXT) */
404     xcb_watch_wm_name(&prophs, 128, handle_windowname_change_legacy, NULL);
405
406     /* Watch WM_NORMAL_HINTS (aspect ratio, size increments, …) */
407     xcb_property_set_handler(&prophs, WM_NORMAL_HINTS, UINT_MAX, handle_normal_hints, NULL);
408
409     /* Watch WM_CLIENT_LEADER (= logical parent window for toolbars etc.) */
410     xcb_property_set_handler(&prophs, atoms[WM_CLIENT_LEADER], UINT_MAX, handle_clientleader_change, NULL);
411
412     /* Watch WM_TRANSIENT_FOR property (to which client this popup window belongs) */
413     xcb_property_set_handler(&prophs, WM_TRANSIENT_FOR, UINT_MAX, handle_transient_for, NULL);
414
415     /* Set up the atoms we support */
416     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTED], ATOM, 32, 7, atoms);
417     /* Set up the window manager’s name */
418     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTING_WM_CHECK], WINDOW, 32, 1, &root);
419     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_WM_NAME], atoms[UTF8_STRING], 8, strlen("i3"), "i3");
420
421     keysyms = xcb_key_symbols_alloc(conn);
422
423     xcb_get_numlock_mask(conn);
424
425     translate_keysyms();
426     grab_all_keys(conn, false);
427
428     bool needs_tree_init = true;
429     if (layout_path) {
430         LOG("Trying to restore the layout from %s...", layout_path);
431         needs_tree_init = !tree_restore(layout_path);
432         if (delete_layout_path)
433             unlink(layout_path);
434         free(layout_path);
435     }
436     if (needs_tree_init)
437         tree_init();
438
439     int randr_base;
440     if (force_xinerama) {
441         xinerama_init();
442     } else {
443         DLOG("Checking for XRandR...\n");
444         randr_init(&randr_base);
445
446         xcb_event_set_handler(&evenths,
447                               randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY,
448                               handle_screen_change,
449                               NULL);
450     }
451
452     tree_render();
453
454     struct ev_loop *loop = ev_loop_new(0);
455     if (loop == NULL)
456             die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
457
458     /* Create the UNIX domain socket for IPC */
459     if (config.ipc_socket_path != NULL) {
460         int ipc_socket = ipc_create_socket(config.ipc_socket_path);
461         if (ipc_socket == -1) {
462             ELOG("Could not create the IPC socket, IPC disabled\n");
463         } else {
464             struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
465             ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
466             ev_io_start(loop, ipc_io);
467         }
468     }
469
470     struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
471     struct ev_io *xkb = scalloc(sizeof(struct ev_io));
472     struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
473     struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
474
475     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
476     ev_io_start(loop, xcb_watcher);
477
478
479     if (xkb_supported) {
480         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
481         ev_io_start(loop, xkb);
482
483         /* Flush the buffer so that libev can properly get new events */
484         XFlush(xkbdpy);
485     }
486
487     ev_check_init(xcb_check, xcb_check_cb);
488     ev_check_start(loop, xcb_check);
489
490     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
491     ev_prepare_start(loop, xcb_prepare);
492
493     xcb_flush(conn);
494
495     manage_existing_windows(root);
496
497     setup_signal_handler();
498
499     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
500      * while we are sending him a message */
501     signal(SIGPIPE, SIG_IGN);
502
503     /* Autostarting exec-lines */
504     if (autostart) {
505         struct Autostart *exec;
506         TAILQ_FOREACH(exec, &autostarts, autostarts) {
507             LOG("auto-starting %s\n", exec->command);
508             start_application(exec->command);
509         }
510     }
511
512     ev_loop(loop, 0);
513 }