]> git.sur5r.net Git - i3/i3/blob - src/mainx.c
84df8b2e632d82c780cec8d4a007a3f5b83eb3f4
[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_event.h>
30 #include <xcb/xcb_property.h>
31 #include <xcb/xcb_keysyms.h>
32 #include <xcb/xcb_icccm.h>
33
34 #include <ev.h>
35
36 #include "config.h"
37 #include "data.h"
38 #include "debug.h"
39 #include "handlers.h"
40 #include "click.h"
41 #include "i3.h"
42 #include "layout.h"
43 #include "queue.h"
44 #include "table.h"
45 #include "util.h"
46 #include "xcb.h"
47 #include "randr.h"
48 #include "xinerama.h"
49 #include "manage.h"
50 #include "ipc.h"
51 #include "log.h"
52 #include "sighandler.h"
53
54 xcb_connection_t *global_conn;
55
56 /* This is the path to i3, copied from argv[0] when starting up */
57 char **start_argv;
58
59 /* This is our connection to X11 for use with XKB */
60 Display *xkbdpy;
61
62 xcb_key_symbols_t *keysyms;
63
64 /* The list of key bindings */
65 struct bindings_head *bindings;
66
67 /* The list of exec-lines */
68 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
69
70 /* The list of assignments */
71 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
72
73 /* This is a list of Stack_Windows, global, for easier/faster access on expose events */
74 struct stack_wins_head stack_wins = SLIST_HEAD_INITIALIZER(stack_wins);
75
76 /* The event handlers need to be global because they are accessed by our custom event handler
77    in handle_button_press(), needed for graphical resizing */
78 xcb_event_handlers_t evenths;
79 xcb_atom_t atoms[NUM_ATOMS];
80
81 xcb_window_t root;
82 int num_screens = 0;
83
84 /* The depth of the root screen (used e.g. for creating new pixmaps later) */
85 uint8_t root_depth;
86
87 /* We hope that XKB is supported and set this to false */
88 bool xkb_supported = true;
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(evenths.c);
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(evenths.c)) != NULL) {
116                 xcb_event_handle(&evenths, event);
117                 free(event);
118         }
119 }
120
121 /*
122  * When using xmodmap to change the keyboard mapping, this event
123  * is only sent via XKB. Therefore, we need this special handler.
124  *
125  */
126 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
127         DLOG("Handling XKB event\n");
128         XEvent ev;
129         /* When using xmodmap, every change (!) gets an own event.
130          * Therefore, we just read all events and only handle the
131          * mapping_notify once (we do not receive any other XKB
132          * events anyway). */
133         while (XPending(xkbdpy))
134                 XNextEvent(xkbdpy, &ev);
135
136         xcb_key_symbols_free(keysyms);
137         keysyms = xcb_key_symbols_alloc(global_conn);
138
139         xcb_get_numlock_mask(global_conn);
140
141         ungrab_all_keys(global_conn);
142         DLOG("Re-grabbing...\n");
143         grab_all_keys(global_conn);
144         DLOG("Done\n");
145
146 }
147
148
149 int main(int argc, char *argv[], char *env[]) {
150         int i, screens, opt;
151         char *override_configpath = NULL;
152         bool autostart = true;
153         bool only_check_config = false;
154         bool force_xinerama = false;
155         xcb_connection_t *conn;
156         xcb_property_handlers_t prophs;
157         xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
158         static struct option long_options[] = {
159                 {"no-autostart", no_argument, 0, 'a'},
160                 {"config", required_argument, 0, 'c'},
161                 {"version", no_argument, 0, 'v'},
162                 {"help", no_argument, 0, 'h'},
163                 {"force-xinerama", no_argument, 0, 0},
164                 {0, 0, 0, 0}
165         };
166         int option_index = 0;
167
168         setlocale(LC_ALL, "");
169
170         /* Disable output buffering to make redirects in .xsession actually useful for debugging */
171         if (!isatty(fileno(stdout)))
172                 setbuf(stdout, NULL);
173
174         start_argv = argv;
175
176         while ((opt = getopt_long(argc, argv, "c:Cvahld:V", long_options, &option_index)) != -1) {
177                 switch (opt) {
178                         case 'a':
179                                 LOG("Autostart disabled using -a\n");
180                                 autostart = false;
181                                 break;
182                         case 'c':
183                                 override_configpath = sstrdup(optarg);
184                                 break;
185                         case 'C':
186                                 LOG("Checking configuration file only (-C)\n");
187                                 only_check_config = true;
188                                 break;
189                         case 'v':
190                                 printf("i3 version " I3_VERSION " © 2009 Michael Stapelberg and contributors\n");
191                                 exit(EXIT_SUCCESS);
192                         case 'V':
193                                 set_verbosity(true);
194                                 break;
195                         case 'd':
196                                 LOG("Enabling debug loglevel %s\n", optarg);
197                                 add_loglevel(optarg);
198                                 break;
199                         case 'l':
200                                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
201                                 break;
202                         case 0:
203                                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
204                                         force_xinerama = true;
205                                         ELOG("Using Xinerama instead of RandR. This option should be "
206                                              "avoided at all cost because it does not refresh the list "
207                                              "of screens, so you cannot configure displays at runtime. "
208                                              "Please check if your driver really does not support RandR "
209                                              "and disable this option as soon as you can.\n");
210                                         break;
211                                 }
212                                 /* fall-through */
213                         default:
214                                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
215                                 fprintf(stderr, "\n");
216                                 fprintf(stderr, "-a: disable autostart\n");
217                                 fprintf(stderr, "-v: display version and exit\n");
218                                 fprintf(stderr, "-V: enable verbose mode\n");
219                                 fprintf(stderr, "-d <loglevel>: enable debug loglevel <loglevel>\n");
220                                 fprintf(stderr, "-c <configfile>: use the provided configfile instead\n");
221                                 fprintf(stderr, "-C: check configuration file and exit\n");
222                                 fprintf(stderr, "--force-xinerama: Use Xinerama instead of RandR. This "
223                                                 "option should only be used if you are stuck with the "
224                                                 "nvidia closed source driver which does not support RandR.\n");
225                                 exit(EXIT_FAILURE);
226                 }
227         }
228
229         LOG("i3 version " I3_VERSION " starting\n");
230
231         /* Initialize the table data structures for each workspace */
232         init_table();
233
234         memset(&evenths, 0, sizeof(xcb_event_handlers_t));
235         memset(&prophs, 0, sizeof(xcb_property_handlers_t));
236
237         conn = global_conn = xcb_connect(NULL, &screens);
238
239         if (xcb_connection_has_error(conn))
240                 die("Cannot open display\n");
241
242         load_configuration(conn, override_configpath, false);
243         if (only_check_config) {
244                 LOG("Done checking configuration file. Exiting.\n");
245                 exit(0);
246         }
247
248         /* Create the initial container on the first workspace. This used to
249          * be part of init_table, but since it possibly requires an X
250          * connection and a loaded configuration (default mode for new
251          * containers may be stacking, which requires a new window to be
252          * created), it had to be delayed. */
253         expand_table_cols(TAILQ_FIRST(workspaces));
254         expand_table_rows(TAILQ_FIRST(workspaces));
255
256         /* Place requests for the atoms we need as soon as possible */
257         #define REQUEST_ATOM(name) atom_cookies[name] = xcb_intern_atom(conn, 0, strlen(#name), #name);
258
259         REQUEST_ATOM(_NET_SUPPORTED);
260         REQUEST_ATOM(_NET_WM_STATE_FULLSCREEN);
261         REQUEST_ATOM(_NET_SUPPORTING_WM_CHECK);
262         REQUEST_ATOM(_NET_WM_NAME);
263         REQUEST_ATOM(_NET_WM_STATE);
264         REQUEST_ATOM(_NET_WM_WINDOW_TYPE);
265         REQUEST_ATOM(_NET_WM_DESKTOP);
266         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
267         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
268         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
269         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
270         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
271         REQUEST_ATOM(_NET_WM_STRUT_PARTIAL);
272         REQUEST_ATOM(WM_PROTOCOLS);
273         REQUEST_ATOM(WM_DELETE_WINDOW);
274         REQUEST_ATOM(UTF8_STRING);
275         REQUEST_ATOM(WM_STATE);
276         REQUEST_ATOM(WM_CLIENT_LEADER);
277         REQUEST_ATOM(_NET_CURRENT_DESKTOP);
278         REQUEST_ATOM(_NET_ACTIVE_WINDOW);
279         REQUEST_ATOM(_NET_WORKAREA);
280
281         /* TODO: this has to be more beautiful somewhen */
282         int major, minor, error;
283
284         major = XkbMajorVersion;
285         minor = XkbMinorVersion;
286
287         int evBase, errBase;
288
289         if ((xkbdpy = XkbOpenDisplay(getenv("DISPLAY"), &evBase, &errBase, &major, &minor, &error)) == NULL) {
290                 ELOG("ERROR: XkbOpenDisplay() failed, disabling XKB support\n");
291                 xkb_supported = false;
292         }
293
294         if (xkb_supported) {
295                 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
296                         fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
297                         return 1;
298                 }
299
300                 int i1;
301                 if (!XkbQueryExtension(xkbdpy,&i1,&evBase,&errBase,&major,&minor)) {
302                         fprintf(stderr, "XKB not supported by X-server\n");
303                         return 1;
304                 }
305                 /* end of ugliness */
306
307                 if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd, XkbMapNotifyMask, XkbMapNotifyMask)) {
308                         fprintf(stderr, "Could not set XKB event mask\n");
309                         return 1;
310                 }
311         }
312
313         /* Initialize event loop using libev */
314         struct ev_loop *loop = ev_loop_new(0);
315         if (loop == NULL)
316                 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
317
318         struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
319         struct ev_io *xkb = scalloc(sizeof(struct ev_io));
320         struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
321         struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
322
323         ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
324         ev_io_start(loop, xcb_watcher);
325
326         if (xkb_supported) {
327                 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
328                 ev_io_start(loop, xkb);
329
330                 /* Flush the buffer so that libev can properly get new events */
331                 XFlush(xkbdpy);
332         }
333
334         ev_check_init(xcb_check, xcb_check_cb);
335         ev_check_start(loop, xcb_check);
336
337         ev_prepare_init(xcb_prepare, xcb_prepare_cb);
338         ev_prepare_start(loop, xcb_prepare);
339
340         /* Grab the server to delay any events until we enter the eventloop */
341         xcb_grab_server(conn);
342
343         xcb_event_handlers_init(conn, &evenths);
344
345         /* DEBUG: Trap all events and print them */
346         for (i = 2; i < 128; ++i)
347                 xcb_event_set_handler(&evenths, i, handle_event, 0);
348
349         for (i = 0; i < 256; ++i)
350                 xcb_event_set_error_handler(&evenths, i, (xcb_generic_error_handler_t)handle_event, 0);
351
352         /* Expose = an Application should redraw itself, in this case it’s our titlebars. */
353         xcb_event_set_expose_handler(&evenths, handle_expose_event, NULL);
354
355         /* Key presses/releases are pretty obvious, I think */
356         xcb_event_set_key_press_handler(&evenths, handle_key_press, NULL);
357         xcb_event_set_key_release_handler(&evenths, handle_key_release, NULL);
358
359         /* Enter window = user moved his mouse over the window */
360         xcb_event_set_enter_notify_handler(&evenths, handle_enter_notify, NULL);
361
362         /* Button press = user pushed a mouse button over one of our windows */
363         xcb_event_set_button_press_handler(&evenths, handle_button_press, NULL);
364
365         /* Map notify = there is a new window */
366         xcb_event_set_map_request_handler(&evenths, handle_map_request, &prophs);
367
368         /* Unmap notify = window disappeared. When sent from a client, we don’t manage
369            it any longer. Usually, the client destroys the window shortly afterwards. */
370         xcb_event_set_unmap_notify_handler(&evenths, handle_unmap_notify_event, NULL);
371
372         /* Configure notify = window’s configuration (geometry, stacking, …). We only need
373            it to set up ignore the following enter_notify events */
374         xcb_event_set_configure_notify_handler(&evenths, handle_configure_event, NULL);
375
376         /* Configure request = window tried to change size on its own */
377         xcb_event_set_configure_request_handler(&evenths, handle_configure_request, NULL);
378
379         /* Motion notify = user moved his cursor (over the root window and may
380          * cross virtual screen boundaries doing that) */
381         xcb_event_set_motion_notify_handler(&evenths, handle_motion_notify, NULL);
382
383         /* Mapping notify = keyboard mapping changed (Xmodmap), re-grab bindings */
384         xcb_event_set_mapping_notify_handler(&evenths, handle_mapping_notify, NULL);
385
386         /* Client message are sent to the root window. The only interesting client message
387            for us is _NET_WM_STATE, we honour _NET_WM_STATE_FULLSCREEN */
388         xcb_event_set_client_message_handler(&evenths, handle_client_message, NULL);
389
390         /* Initialize the property handlers */
391         xcb_property_handlers_init(&prophs, &evenths);
392
393         /* Watch size hints (to obey correct aspect ratio) */
394         xcb_property_set_handler(&prophs, WM_NORMAL_HINTS, UINT_MAX, handle_normal_hints, NULL);
395
396         /* Get the root window and set the event mask */
397         xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
398         root = root_screen->root;
399         root_depth = root_screen->root_depth;
400
401         uint32_t mask = XCB_CW_EVENT_MASK;
402         uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
403                               XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
404                                                                            projector), the root window gets a
405                                                                            ConfigureNotify */
406                               XCB_EVENT_MASK_POINTER_MOTION |
407                               XCB_EVENT_MASK_PROPERTY_CHANGE |
408                               XCB_EVENT_MASK_ENTER_WINDOW };
409         xcb_void_cookie_t cookie;
410         cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
411         check_error(conn, cookie, "Another window manager seems to be running");
412
413         /* Setup NetWM atoms */
414         #define GET_ATOM(name) { \
415                 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, atom_cookies[name], NULL); \
416                 if (!reply) { \
417                         ELOG("Could not get atom " #name "\n"); \
418                         exit(-1); \
419                 } \
420                 atoms[name] = reply->atom; \
421                 free(reply); \
422         }
423
424         GET_ATOM(_NET_SUPPORTED);
425         GET_ATOM(_NET_WM_STATE_FULLSCREEN);
426         GET_ATOM(_NET_SUPPORTING_WM_CHECK);
427         GET_ATOM(_NET_WM_NAME);
428         GET_ATOM(_NET_WM_STATE);
429         GET_ATOM(_NET_WM_WINDOW_TYPE);
430         GET_ATOM(_NET_WM_DESKTOP);
431         GET_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
432         GET_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
433         GET_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
434         GET_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
435         GET_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
436         GET_ATOM(_NET_WM_STRUT_PARTIAL);
437         GET_ATOM(WM_PROTOCOLS);
438         GET_ATOM(WM_DELETE_WINDOW);
439         GET_ATOM(UTF8_STRING);
440         GET_ATOM(WM_STATE);
441         GET_ATOM(WM_CLIENT_LEADER);
442         GET_ATOM(_NET_CURRENT_DESKTOP);
443         GET_ATOM(_NET_ACTIVE_WINDOW);
444         GET_ATOM(_NET_WORKAREA);
445
446         xcb_property_set_handler(&prophs, atoms[_NET_WM_WINDOW_TYPE], UINT_MAX, handle_window_type, NULL);
447         /* TODO: In order to comply with EWMH, we have to watch _NET_WM_STRUT_PARTIAL */
448
449         /* Watch _NET_WM_NAME (= title of the window in UTF-8) property */
450         xcb_property_set_handler(&prophs, atoms[_NET_WM_NAME], 128, handle_windowname_change, NULL);
451
452         /* Watch WM_TRANSIENT_FOR property (to which client this popup window belongs) */
453         xcb_property_set_handler(&prophs, WM_TRANSIENT_FOR, UINT_MAX, handle_transient_for, NULL);
454
455         /* Watch WM_NAME (= title of the window in compound text) property for legacy applications */
456         xcb_watch_wm_name(&prophs, 128, handle_windowname_change_legacy, NULL);
457
458         /* Watch WM_CLASS (= class of the window) */
459         xcb_property_set_handler(&prophs, WM_CLASS, 128, handle_windowclass_change, NULL);
460
461         /* Watch WM_CLIENT_LEADER (= logical parent window for toolbars etc.) */
462         xcb_property_set_handler(&prophs, atoms[WM_CLIENT_LEADER], UINT_MAX, handle_clientleader_change, NULL);
463
464         /* Watch WM_HINTS (contains the urgent property) */
465         xcb_property_set_handler(&prophs, WM_HINTS, UINT_MAX, handle_hints, NULL);
466
467         /* Set up the atoms we support */
468         check_error(conn, xcb_change_property_checked(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTED],
469                        ATOM, 32, 7, atoms), "Could not set _NET_SUPPORTED");
470         /* Set up the window manager’s name */
471         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTING_WM_CHECK], WINDOW, 32, 1, &root);
472         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_WM_NAME], atoms[UTF8_STRING], 8, strlen("i3"), "i3");
473
474         keysyms = xcb_key_symbols_alloc(conn);
475
476         xcb_get_numlock_mask(conn);
477
478         grab_all_keys(conn);
479
480         int randr_base;
481         if (force_xinerama) {
482                 initialize_xinerama(conn);
483         } else {
484                 DLOG("Checking for XRandR...\n");
485                 initialize_randr(conn, &randr_base);
486
487                 xcb_event_set_handler(&evenths,
488                                       randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY,
489                                       handle_screen_change,
490                                       NULL);
491         }
492
493         xcb_flush(conn);
494
495         /* Get pointer position to see on which screen we’re starting */
496         xcb_query_pointer_reply_t *reply;
497         if ((reply = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, root), NULL)) == NULL) {
498                 ELOG("Could not get pointer position\n");
499                 return 1;
500         }
501
502         Output *screen = get_output_containing(reply->root_x, reply->root_y);
503         if (screen == NULL) {
504                 ELOG("ERROR: No screen at %d x %d, starting on the first screen\n",
505                     reply->root_x, reply->root_y);
506                 screen = get_first_output();
507         }
508
509         DLOG("Starting on %p\n", screen->current_workspace);
510         c_ws = screen->current_workspace;
511
512         manage_existing_windows(conn, &prophs, root);
513
514         /* Create the UNIX domain socket for IPC */
515         if (config.ipc_socket_path != NULL) {
516                 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
517                 if (ipc_socket == -1) {
518                         ELOG("Could not create the IPC socket, IPC disabled\n");
519                 } else {
520                         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
521                         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
522                         ev_io_start(loop, ipc_io);
523                 }
524         }
525
526         /* Handle the events which arrived until now */
527         xcb_check_cb(NULL, NULL, 0);
528
529         setup_signal_handler();
530
531         /* Ignore SIGPIPE to survive errors when an IPC client disconnects
532          * while we are sending him a message */
533         signal(SIGPIPE, SIG_IGN);
534
535         /* Ungrab the server to receive events and enter libev’s eventloop */
536         xcb_ungrab_server(conn);
537
538         /* Autostarting exec-lines */
539         struct Autostart *exec;
540         if (autostart) {
541                 TAILQ_FOREACH(exec, &autostarts, autostarts) {
542                         LOG("auto-starting %s\n", exec->command);
543                         start_application(exec->command);
544                 }
545         }
546
547         ev_loop(loop, 0);
548
549         /* not reached */
550         return 0;
551 }