]> git.sur5r.net Git - i3/i3/blob - src/mainx.c
Make i3 compatible with the very latest xcb
[i3/i3] / src / mainx.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009-2010 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  */
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 #include <stdbool.h>
17 #include <assert.h>
18 #include <limits.h>
19 #include <locale.h>
20 #include <fcntl.h>
21 #include <getopt.h>
22
23 #include <X11/XKBlib.h>
24 #include <X11/extensions/XKB.h>
25
26 #include <xcb/xcb.h>
27 #include <xcb/xcb_atom.h>
28 #include <xcb/xcb_aux.h>
29 #include <xcb/xcb_keysyms.h>
30 #include <xcb/xcb_icccm.h>
31
32 #include <ev.h>
33
34 #include "config.h"
35 #include "data.h"
36 #include "handlers.h"
37 #include "click.h"
38 #include "i3.h"
39 #include "layout.h"
40 #include "queue.h"
41 #include "table.h"
42 #include "util.h"
43 #include "xcb.h"
44 #include "randr.h"
45 #include "xinerama.h"
46 #include "manage.h"
47 #include "ipc.h"
48 #include "log.h"
49 #include "sighandler.h"
50
51 static int xkb_event_base;
52
53 int xkb_current_group;
54
55 xcb_connection_t *global_conn;
56
57 /* This is the path to i3, copied from argv[0] when starting up */
58 char **start_argv;
59
60 /* This is our connection to X11 for use with XKB */
61 Display *xkbdpy;
62
63 xcb_key_symbols_t *keysyms;
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 assignments */
72 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
73
74 /* This is a list of Stack_Windows, global, for easier/faster access on expose events */
75 struct stack_wins_head stack_wins = SLIST_HEAD_INITIALIZER(stack_wins);
76
77 xcb_window_t root;
78 int num_screens = 0;
79
80 /* The depth of the root screen (used e.g. for creating new pixmaps later) */
81 uint8_t root_depth;
82
83 /* We hope that XKB is supported and set this to false */
84 bool xkb_supported = true;
85
86 /*
87  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
88  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
89  *
90  */
91 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
92         /* empty, because xcb_prepare_cb and xcb_check_cb are used */
93 }
94
95 /*
96  * Flush before blocking (and waiting for new events)
97  *
98  */
99 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
100         xcb_flush(global_conn);
101 }
102
103 /*
104  * Instead of polling the X connection socket we leave this to
105  * xcb_poll_for_event() which knows better than we can ever know.
106  *
107  */
108 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
109         xcb_generic_event_t *event;
110
111         while ((event = xcb_poll_for_event(global_conn)) != NULL) {
112                 if (event->response_type == 0) {
113                         ELOG("X11 Error received! sequence %x\n", event->sequence);
114                         continue;
115                 }
116
117                 /* Strip off the highest bit (set if the event is generated) */
118                 int type = (event->response_type & 0x7F);
119
120                 handle_event(type, event);
121
122                 free(event);
123         }
124 }
125
126 /*
127  * When using xmodmap to change the keyboard mapping, this event
128  * is only sent via XKB. Therefore, we need this special handler.
129  *
130  */
131 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
132         DLOG("Handling XKB event\n");
133         XkbEvent ev;
134
135         /* When using xmodmap, every change (!) gets an own event.
136          * Therefore, we just read all events and only handle the
137          * mapping_notify once. */
138         bool mapping_changed = false;
139         while (XPending(xkbdpy)) {
140                 XNextEvent(xkbdpy, (XEvent*)&ev);
141                 /* While we should never receive a non-XKB event,
142                  * better do sanity checking */
143                 if (ev.type != xkb_event_base)
144                         continue;
145
146                 if (ev.any.xkb_type == XkbMapNotify) {
147                         mapping_changed = true;
148                         continue;
149                 }
150
151                 if (ev.any.xkb_type != XkbStateNotify) {
152                         ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
153                         continue;
154                 }
155
156                 /* See The XKB Extension: Library Specification, section 14.1 */
157                 /* We check if the current group (each group contains
158                  * two levels) has been changed. Mode_switch activates
159                  * group XkbGroup2Index */
160                 if (xkb_current_group == ev.state.group)
161                         continue;
162
163                 xkb_current_group = ev.state.group;
164
165                 if (ev.state.group == XkbGroup2Index) {
166                         DLOG("Mode_switch enabled\n");
167                         grab_all_keys(global_conn, true);
168                 }
169
170                 if (ev.state.group == XkbGroup1Index) {
171                         DLOG("Mode_switch disabled\n");
172                         ungrab_all_keys(global_conn);
173                         grab_all_keys(global_conn, false);
174                 }
175         }
176
177         if (!mapping_changed)
178                 return;
179
180         DLOG("Keyboard mapping changed, updating keybindings\n");
181         xcb_key_symbols_free(keysyms);
182         keysyms = xcb_key_symbols_alloc(global_conn);
183
184         xcb_get_numlock_mask(global_conn);
185
186         ungrab_all_keys(global_conn);
187         DLOG("Re-grabbing...\n");
188         translate_keysyms();
189         grab_all_keys(global_conn, (xkb_current_group == XkbGroup2Index));
190         DLOG("Done\n");
191 }
192
193
194 int main(int argc, char *argv[], char *env[]) {
195         int screens, opt;
196         char *override_configpath = NULL;
197         bool autostart = true;
198         bool only_check_config = false;
199         bool force_xinerama = false;
200         xcb_connection_t *conn;
201         static struct option long_options[] = {
202                 {"no-autostart", no_argument, 0, 'a'},
203                 {"config", required_argument, 0, 'c'},
204                 {"version", no_argument, 0, 'v'},
205                 {"help", no_argument, 0, 'h'},
206                 {"force-xinerama", no_argument, 0, 0},
207                 {0, 0, 0, 0}
208         };
209         int option_index = 0;
210
211         setlocale(LC_ALL, "");
212
213         /* Disable output buffering to make redirects in .xsession actually useful for debugging */
214         if (!isatty(fileno(stdout)))
215                 setbuf(stdout, NULL);
216
217         start_argv = argv;
218
219         while ((opt = getopt_long(argc, argv, "c:Cvahld:V", long_options, &option_index)) != -1) {
220                 switch (opt) {
221                         case 'a':
222                                 LOG("Autostart disabled using -a\n");
223                                 autostart = false;
224                                 break;
225                         case 'c':
226                                 override_configpath = sstrdup(optarg);
227                                 break;
228                         case 'C':
229                                 LOG("Checking configuration file only (-C)\n");
230                                 only_check_config = true;
231                                 break;
232                         case 'v':
233                                 printf("i3 version " I3_VERSION " © 2009-2010 Michael Stapelberg and contributors\n");
234                                 exit(EXIT_SUCCESS);
235                         case 'V':
236                                 set_verbosity(true);
237                                 break;
238                         case 'd':
239                                 LOG("Enabling debug loglevel %s\n", optarg);
240                                 add_loglevel(optarg);
241                                 break;
242                         case 'l':
243                                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
244                                 break;
245                         case 0:
246                                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
247                                         force_xinerama = true;
248                                         ELOG("Using Xinerama instead of RandR. This option should be "
249                                              "avoided at all cost because it does not refresh the list "
250                                              "of screens, so you cannot configure displays at runtime. "
251                                              "Please check if your driver really does not support RandR "
252                                              "and disable this option as soon as you can.\n");
253                                         break;
254                                 }
255                                 /* fall-through */
256                         default:
257                                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
258                                 fprintf(stderr, "\n");
259                                 fprintf(stderr, "-a: disable autostart\n");
260                                 fprintf(stderr, "-v: display version and exit\n");
261                                 fprintf(stderr, "-V: enable verbose mode\n");
262                                 fprintf(stderr, "-d <loglevel>: enable debug loglevel <loglevel>\n");
263                                 fprintf(stderr, "-c <configfile>: use the provided configfile instead\n");
264                                 fprintf(stderr, "-C: check configuration file and exit\n");
265                                 fprintf(stderr, "--force-xinerama: Use Xinerama instead of RandR. This "
266                                                 "option should only be used if you are stuck with the "
267                                                 "nvidia closed source driver which does not support RandR.\n");
268                                 exit(EXIT_FAILURE);
269                 }
270         }
271
272         LOG("i3 version " I3_VERSION " starting\n");
273
274         /* Initialize the table data structures for each workspace */
275         init_table();
276
277         conn = global_conn = xcb_connect(NULL, &screens);
278
279         if (xcb_connection_has_error(conn))
280                 die("Cannot open display\n");
281
282         /* Get the root window */
283         xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
284         root = root_screen->root;
285         root_depth = root_screen->root_depth;
286
287         load_configuration(conn, override_configpath, false);
288         if (only_check_config) {
289                 LOG("Done checking configuration file. Exiting.\n");
290                 exit(0);
291         }
292
293         /* Create the initial container on the first workspace. This used to
294          * be part of init_table, but since it possibly requires an X
295          * connection and a loaded configuration (default mode for new
296          * containers may be stacking, which requires a new window to be
297          * created), it had to be delayed. */
298         expand_table_cols(TAILQ_FIRST(workspaces));
299         expand_table_rows(TAILQ_FIRST(workspaces));
300
301         /* Place requests for the atoms we need as soon as possible */
302         #define xmacro(atom) \
303                 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
304         #include "atoms.xmacro"
305         #undef xmacro
306
307         /* TODO: this has to be more beautiful somewhen */
308         int major, minor, error;
309
310         major = XkbMajorVersion;
311         minor = XkbMinorVersion;
312
313         int errBase;
314
315         if ((xkbdpy = XkbOpenDisplay(getenv("DISPLAY"), &xkb_event_base, &errBase, &major, &minor, &error)) == NULL) {
316                 ELOG("ERROR: XkbOpenDisplay() failed, disabling XKB support\n");
317                 xkb_supported = false;
318         }
319
320         if (xkb_supported) {
321                 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
322                         fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
323                         return 1;
324                 }
325
326                 int i1;
327                 if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
328                         fprintf(stderr, "XKB not supported by X-server\n");
329                         return 1;
330                 }
331                 /* end of ugliness */
332
333                 if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
334                                      XkbMapNotifyMask | XkbStateNotifyMask,
335                                      XkbMapNotifyMask | XkbStateNotifyMask)) {
336                         fprintf(stderr, "Could not set XKB event mask\n");
337                         return 1;
338                 }
339         }
340
341         /* Initialize event loop using libev */
342         struct ev_loop *loop = ev_loop_new(0);
343         if (loop == NULL)
344                 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
345
346         struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
347         struct ev_io *xkb = scalloc(sizeof(struct ev_io));
348         struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
349         struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
350
351         ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
352         ev_io_start(loop, xcb_watcher);
353
354         if (xkb_supported) {
355                 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
356                 ev_io_start(loop, xkb);
357
358                 /* Flush the buffer so that libev can properly get new events */
359                 XFlush(xkbdpy);
360         }
361
362         ev_check_init(xcb_check, xcb_check_cb);
363         ev_check_start(loop, xcb_check);
364
365         ev_prepare_init(xcb_prepare, xcb_prepare_cb);
366         ev_prepare_start(loop, xcb_prepare);
367
368         /* Grab the server to delay any events until we enter the eventloop */
369         xcb_grab_server(conn);
370
371 #if 0
372         /* Expose = an Application should redraw itself, in this case it’s our titlebars. */
373         xcb_event_set_expose_handler(&evenths, handle_expose_event, NULL);
374
375         /* Key presses are pretty obvious, I think */
376         xcb_event_set_key_press_handler(&evenths, handle_key_press, NULL);
377
378         /* Enter window = user moved his mouse over the window */
379         xcb_event_set_enter_notify_handler(&evenths, handle_enter_notify, NULL);
380
381         /* Button press = user pushed a mouse button over one of our windows */
382         xcb_event_set_button_press_handler(&evenths, handle_button_press, NULL);
383
384         /* Map notify = there is a new window */
385         xcb_event_set_map_request_handler(&evenths, handle_map_request, &prophs);
386
387         /* Unmap notify = window disappeared. When sent from a client, we don’t manage
388            it any longer. Usually, the client destroys the window shortly afterwards. */
389         xcb_event_set_unmap_notify_handler(&evenths, handle_unmap_notify_event, NULL);
390
391         /* Destroy notify is handled the same as unmap notify */
392         xcb_event_set_destroy_notify_handler(&evenths, handle_destroy_notify_event, NULL);
393
394         /* Configure notify = window’s configuration (geometry, stacking, …). We only need
395            it to set up ignore the following enter_notify events */
396         xcb_event_set_configure_notify_handler(&evenths, handle_configure_event, NULL);
397
398         /* Configure request = window tried to change size on its own */
399         xcb_event_set_configure_request_handler(&evenths, handle_configure_request, NULL);
400
401         /* Motion notify = user moved his cursor (over the root window and may
402          * cross virtual screen boundaries doing that) */
403         xcb_event_set_motion_notify_handler(&evenths, handle_motion_notify, NULL);
404
405         /* Mapping notify = keyboard mapping changed (Xmodmap), re-grab bindings */
406         xcb_event_set_mapping_notify_handler(&evenths, handle_mapping_notify, NULL);
407
408         /* Client message are sent to the root window. The only interesting client message
409            for us is _NET_WM_STATE, we honour _NET_WM_STATE_FULLSCREEN */
410         xcb_event_set_client_message_handler(&evenths, handle_client_message, NULL);
411 #endif
412
413         /* set event mask */
414         uint32_t mask = XCB_CW_EVENT_MASK;
415         uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
416                               XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
417                                                                            projector), the root window gets a
418                                                                            ConfigureNotify */
419                               XCB_EVENT_MASK_POINTER_MOTION |
420                               XCB_EVENT_MASK_PROPERTY_CHANGE |
421                               XCB_EVENT_MASK_ENTER_WINDOW };
422         xcb_void_cookie_t cookie;
423         cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
424         check_error(conn, cookie, "Another window manager seems to be running");
425
426         /* Setup NetWM atoms */
427         #define xmacro(name) \
428                 do { \
429                         xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
430                         if (!reply) { \
431                                 ELOG("Could not get atom " #name "\n"); \
432                                 exit(-1); \
433                         } \
434                         A_ ## name = reply->atom; \
435                         free(reply); \
436                 } while (0);
437         #include "atoms.xmacro"
438         #undef xmacro
439
440         property_handlers_init();
441
442         /* Set up the atoms we support */
443         xcb_atom_t supported_atoms[] = {
444 #define xmacro(atom) A_ ## atom,
445 #include "atoms.xmacro"
446 #undef xmacro
447         };
448
449         /* Set up the atoms we support */
450         check_error(conn, xcb_change_property_checked(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED,
451                        A_ATOM, 32, 7, supported_atoms), "Could not set _NET_SUPPORTED");
452         /* Set up the window manager’s name */
453         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, A_WINDOW, 32, 1, &root);
454         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
455
456         keysyms = xcb_key_symbols_alloc(conn);
457
458         xcb_get_numlock_mask(conn);
459
460         translate_keysyms();
461         grab_all_keys(conn, false);
462
463         if (force_xinerama) {
464                 initialize_xinerama(conn);
465         } else {
466                 DLOG("Checking for XRandR...\n");
467                 initialize_randr(conn, &randr_base);
468         }
469
470         xcb_flush(conn);
471
472         /* Get pointer position to see on which screen we’re starting */
473         xcb_query_pointer_reply_t *reply;
474         if ((reply = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, root), NULL)) == NULL) {
475                 ELOG("Could not get pointer position\n");
476                 return 1;
477         }
478
479         Output *screen = get_output_containing(reply->root_x, reply->root_y);
480         if (screen == NULL) {
481                 ELOG("ERROR: No screen at %d x %d, starting on the first screen\n",
482                     reply->root_x, reply->root_y);
483                 screen = get_first_output();
484         }
485
486         DLOG("Starting on %p\n", screen->current_workspace);
487         c_ws = screen->current_workspace;
488
489         manage_existing_windows(conn, root);
490
491         /* Create the UNIX domain socket for IPC */
492         if (config.ipc_socket_path != NULL) {
493                 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
494                 if (ipc_socket == -1) {
495                         ELOG("Could not create the IPC socket, IPC disabled\n");
496                 } else {
497                         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
498                         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
499                         ev_io_start(loop, ipc_io);
500                 }
501         }
502
503         /* Handle the events which arrived until now */
504         xcb_check_cb(NULL, NULL, 0);
505
506         setup_signal_handler();
507
508         /* Ignore SIGPIPE to survive errors when an IPC client disconnects
509          * while we are sending him a message */
510         signal(SIGPIPE, SIG_IGN);
511
512         /* Ungrab the server to receive events and enter libev’s eventloop */
513         xcb_ungrab_server(conn);
514
515         /* Autostarting exec-lines */
516         struct Autostart *exec;
517         if (autostart) {
518                 TAILQ_FOREACH(exec, &autostarts, autostarts) {
519                         LOG("auto-starting %s\n", exec->command);
520                         start_application(exec->command);
521                 }
522         }
523
524         ev_loop(loop, 0);
525
526         /* not reached */
527         return 0;
528 }