]> git.sur5r.net Git - i3/i3/blob - src/mainx.c
9c38c4acd74b2c9c45f356b518fc9807c171234e
[i3/i3] / src / mainx.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  */
11 #include <stdio.h>
12 #include <assert.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17 #include <stdbool.h>
18 #include <assert.h>
19 #include <limits.h>
20 #include <locale.h>
21 #include <fcntl.h>
22 #include <getopt.h>
23
24 #include <X11/XKBlib.h>
25 #include <X11/extensions/XKB.h>
26
27 #include <xcb/xcb.h>
28 #include <xcb/xcb_atom.h>
29 #include <xcb/xcb_aux.h>
30 #include <xcb/xcb_event.h>
31 #include <xcb/xcb_property.h>
32 #include <xcb/xcb_keysyms.h>
33 #include <xcb/xcb_icccm.h>
34 #include <xcb/xinerama.h>
35
36 #include <ev.h>
37
38 #include "config.h"
39 #include "data.h"
40 #include "debug.h"
41 #include "handlers.h"
42 #include "click.h"
43 #include "i3.h"
44 #include "layout.h"
45 #include "queue.h"
46 #include "table.h"
47 #include "util.h"
48 #include "xcb.h"
49 #include "xinerama.h"
50 #include "manage.h"
51 #include "ipc.h"
52 #include "log.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         xcb_connection_t *conn;
154         xcb_property_handlers_t prophs;
155         xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
156         static struct option long_options[] = {
157                 {"no-autostart", no_argument, 0, 'a'},
158                 {"config", required_argument, 0, 'c'},
159                 {"version", no_argument, 0, 'v'},
160                 {"help", no_argument, 0, 'h'},
161                 {0, 0, 0, 0}
162         };
163         int option_index = 0;
164
165         setlocale(LC_ALL, "");
166
167         /* Disable output buffering to make redirects in .xsession actually useful for debugging */
168         if (!isatty(fileno(stdout)))
169                 setbuf(stdout, NULL);
170
171         start_argv = argv;
172
173         while ((opt = getopt_long(argc, argv, "c:vahld:V", long_options, &option_index)) != -1) {
174                 switch (opt) {
175                         case 'a':
176                                 LOG("Autostart disabled using -a\n");
177                                 autostart = false;
178                                 break;
179                         case 'c':
180                                 override_configpath = sstrdup(optarg);
181                                 break;
182                         case 'v':
183                                 printf("i3 version " I3_VERSION " © 2009 Michael Stapelberg and contributors\n");
184                                 exit(EXIT_SUCCESS);
185                         case 'V':
186                                 set_verbosity(true);
187                                 break;
188                         case 'd':
189                                 LOG("Enabling debug loglevel %s\n", optarg);
190                                 add_loglevel(optarg);
191                                 break;
192                         case 'l':
193                                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
194                                 break;
195                         default:
196                                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V]\n", argv[0]);
197                                 fprintf(stderr, "\n");
198                                 fprintf(stderr, "-a: disable autostart\n");
199                                 fprintf(stderr, "-v: display version and exit\n");
200                                 fprintf(stderr, "-V: enable verbose mode\n");
201                                 fprintf(stderr, "-d <loglevel>: enable debug loglevel <loglevel>\n");
202                                 fprintf(stderr, "-c <configfile>: use the provided configfile instead\n");
203                                 exit(EXIT_FAILURE);
204                 }
205         }
206
207         LOG("i3 version " I3_VERSION " starting\n");
208
209         /* Initialize the table data structures for each workspace */
210         init_table();
211
212         memset(&evenths, 0, sizeof(xcb_event_handlers_t));
213         memset(&prophs, 0, sizeof(xcb_property_handlers_t));
214
215         conn = global_conn = xcb_connect(NULL, &screens);
216
217         if (xcb_connection_has_error(conn))
218                 die("Cannot open display\n");
219
220         load_configuration(conn, override_configpath, false);
221
222         /* Create the initial container on the first workspace. This used to
223          * be part of init_table, but since it possibly requires an X
224          * connection and a loaded configuration (default mode for new
225          * containers may be stacking, which requires a new window to be
226          * created), it had to be delayed. */
227         expand_table_cols(TAILQ_FIRST(workspaces));
228         expand_table_rows(TAILQ_FIRST(workspaces));
229
230         /* Place requests for the atoms we need as soon as possible */
231         #define REQUEST_ATOM(name) atom_cookies[name] = xcb_intern_atom(conn, 0, strlen(#name), #name);
232
233         REQUEST_ATOM(_NET_SUPPORTED);
234         REQUEST_ATOM(_NET_WM_STATE_FULLSCREEN);
235         REQUEST_ATOM(_NET_SUPPORTING_WM_CHECK);
236         REQUEST_ATOM(_NET_WM_NAME);
237         REQUEST_ATOM(_NET_WM_STATE);
238         REQUEST_ATOM(_NET_WM_WINDOW_TYPE);
239         REQUEST_ATOM(_NET_WM_DESKTOP);
240         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
241         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
242         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
243         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
244         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
245         REQUEST_ATOM(_NET_WM_STRUT_PARTIAL);
246         REQUEST_ATOM(WM_PROTOCOLS);
247         REQUEST_ATOM(WM_DELETE_WINDOW);
248         REQUEST_ATOM(UTF8_STRING);
249         REQUEST_ATOM(WM_STATE);
250         REQUEST_ATOM(WM_CLIENT_LEADER);
251
252         /* TODO: this has to be more beautiful somewhen */
253         int major, minor, error;
254
255         major = XkbMajorVersion;
256         minor = XkbMinorVersion;
257
258         int evBase, errBase;
259
260         if ((xkbdpy = XkbOpenDisplay(getenv("DISPLAY"), &evBase, &errBase, &major, &minor, &error)) == NULL) {
261                 ELOG("ERROR: XkbOpenDisplay() failed, disabling XKB support\n");
262                 xkb_supported = false;
263         }
264
265         if (xkb_supported) {
266                 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
267                         fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
268                         return 1;
269                 }
270
271                 int i1;
272                 if (!XkbQueryExtension(xkbdpy,&i1,&evBase,&errBase,&major,&minor)) {
273                         fprintf(stderr, "XKB not supported by X-server\n");
274                         return 1;
275                 }
276                 /* end of ugliness */
277
278                 if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd, XkbMapNotifyMask, XkbMapNotifyMask)) {
279                         fprintf(stderr, "Could not set XKB event mask\n");
280                         return 1;
281                 }
282         }
283
284         /* Initialize event loop using libev */
285         struct ev_loop *loop = ev_default_loop(0);
286         if (loop == NULL)
287                 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
288
289         struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
290         struct ev_io *xkb = scalloc(sizeof(struct ev_io));
291         struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
292         struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
293
294         ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
295         ev_io_start(loop, xcb_watcher);
296
297         if (xkb_supported) {
298                 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
299                 ev_io_start(loop, xkb);
300
301                 /* Flush the buffer so that libev can properly get new events */
302                 XFlush(xkbdpy);
303         }
304
305         ev_check_init(xcb_check, xcb_check_cb);
306         ev_check_start(loop, xcb_check);
307
308         ev_prepare_init(xcb_prepare, xcb_prepare_cb);
309         ev_prepare_start(loop, xcb_prepare);
310
311         /* Grab the server to delay any events until we enter the eventloop */
312         xcb_grab_server(conn);
313
314         xcb_event_handlers_init(conn, &evenths);
315
316         /* DEBUG: Trap all events and print them */
317         for (i = 2; i < 128; ++i)
318                 xcb_event_set_handler(&evenths, i, handle_event, 0);
319
320         for (i = 0; i < 256; ++i)
321                 xcb_event_set_error_handler(&evenths, i, (xcb_generic_error_handler_t)handle_event, 0);
322
323         /* Expose = an Application should redraw itself, in this case it’s our titlebars. */
324         xcb_event_set_expose_handler(&evenths, handle_expose_event, NULL);
325
326         /* Key presses/releases are pretty obvious, I think */
327         xcb_event_set_key_press_handler(&evenths, handle_key_press, NULL);
328         xcb_event_set_key_release_handler(&evenths, handle_key_release, NULL);
329
330         /* Enter window = user moved his mouse over the window */
331         xcb_event_set_enter_notify_handler(&evenths, handle_enter_notify, NULL);
332
333         /* Button press = user pushed a mouse button over one of our windows */
334         xcb_event_set_button_press_handler(&evenths, handle_button_press, NULL);
335
336         /* Map notify = there is a new window */
337         xcb_event_set_map_request_handler(&evenths, handle_map_request, &prophs);
338
339         /* Unmap notify = window disappeared. When sent from a client, we don’t manage
340            it any longer. Usually, the client destroys the window shortly afterwards. */
341         xcb_event_set_unmap_notify_handler(&evenths, handle_unmap_notify_event, NULL);
342
343         /* Configure notify = window’s configuration (geometry, stacking, …). We only need
344            it to set up ignore the following enter_notify events */
345         xcb_event_set_configure_notify_handler(&evenths, handle_configure_event, NULL);
346
347         /* Configure request = window tried to change size on its own */
348         xcb_event_set_configure_request_handler(&evenths, handle_configure_request, NULL);
349
350         /* Motion notify = user moved his cursor (over the root window and may
351          * cross virtual screen boundaries doing that) */
352         xcb_event_set_motion_notify_handler(&evenths, handle_motion_notify, NULL);
353
354         /* Mapping notify = keyboard mapping changed (Xmodmap), re-grab bindings */
355         xcb_event_set_mapping_notify_handler(&evenths, handle_mapping_notify, NULL);
356
357         /* Client message are sent to the root window. The only interesting client message
358            for us is _NET_WM_STATE, we honour _NET_WM_STATE_FULLSCREEN */
359         xcb_event_set_client_message_handler(&evenths, handle_client_message, NULL);
360
361         /* Initialize the property handlers */
362         xcb_property_handlers_init(&prophs, &evenths);
363
364         /* Watch size hints (to obey correct aspect ratio) */
365         xcb_property_set_handler(&prophs, WM_NORMAL_HINTS, UINT_MAX, handle_normal_hints, NULL);
366
367         /* Get the root window and set the event mask */
368         xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
369         root = root_screen->root;
370         root_depth = root_screen->root_depth;
371
372         uint32_t mask = XCB_CW_EVENT_MASK;
373         uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
374                               XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
375                                                                            projector), the root window gets a
376                                                                            ConfigureNotify */
377                               XCB_EVENT_MASK_POINTER_MOTION |
378                               XCB_EVENT_MASK_PROPERTY_CHANGE |
379                               XCB_EVENT_MASK_ENTER_WINDOW };
380         xcb_void_cookie_t cookie;
381         cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
382         check_error(conn, cookie, "Another window manager seems to be running");
383
384         /* Setup NetWM atoms */
385         #define GET_ATOM(name) { \
386                 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, atom_cookies[name], NULL); \
387                 if (!reply) { \
388                         ELOG("Could not get atom " #name "\n"); \
389                         exit(-1); \
390                 } \
391                 atoms[name] = reply->atom; \
392                 free(reply); \
393         }
394
395         GET_ATOM(_NET_SUPPORTED);
396         GET_ATOM(_NET_WM_STATE_FULLSCREEN);
397         GET_ATOM(_NET_SUPPORTING_WM_CHECK);
398         GET_ATOM(_NET_WM_NAME);
399         GET_ATOM(_NET_WM_STATE);
400         GET_ATOM(_NET_WM_WINDOW_TYPE);
401         GET_ATOM(_NET_WM_DESKTOP);
402         GET_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
403         GET_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
404         GET_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
405         GET_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
406         GET_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
407         GET_ATOM(_NET_WM_STRUT_PARTIAL);
408         GET_ATOM(WM_PROTOCOLS);
409         GET_ATOM(WM_DELETE_WINDOW);
410         GET_ATOM(UTF8_STRING);
411         GET_ATOM(WM_STATE);
412         GET_ATOM(WM_CLIENT_LEADER);
413
414         xcb_property_set_handler(&prophs, atoms[_NET_WM_WINDOW_TYPE], UINT_MAX, handle_window_type, NULL);
415         /* TODO: In order to comply with EWMH, we have to watch _NET_WM_STRUT_PARTIAL */
416
417         /* Watch _NET_WM_NAME (= title of the window in UTF-8) property */
418         xcb_property_set_handler(&prophs, atoms[_NET_WM_NAME], 128, handle_windowname_change, NULL);
419
420         /* Watch WM_TRANSIENT_FOR property (to which client this popup window belongs) */
421         xcb_property_set_handler(&prophs, WM_TRANSIENT_FOR, UINT_MAX, handle_transient_for, NULL);
422
423         /* Watch WM_NAME (= title of the window in compound text) property for legacy applications */
424         xcb_watch_wm_name(&prophs, 128, handle_windowname_change_legacy, NULL);
425
426         /* Watch WM_CLASS (= class of the window) */
427         xcb_property_set_handler(&prophs, WM_CLASS, 128, handle_windowclass_change, NULL);
428
429         /* Watch WM_CLIENT_LEADER (= logical parent window for toolbars etc.) */
430         xcb_property_set_handler(&prophs, atoms[WM_CLIENT_LEADER], UINT_MAX, handle_clientleader_change, NULL);
431
432         /* Watch WM_HINTS (contains the urgent property) */
433         xcb_property_set_handler(&prophs, WM_HINTS, UINT_MAX, handle_hints, NULL);
434
435         /* Set up the atoms we support */
436         check_error(conn, xcb_change_property_checked(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTED],
437                        ATOM, 32, 7, atoms), "Could not set _NET_SUPPORTED");
438         /* Set up the window manager’s name */
439         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTING_WM_CHECK], WINDOW, 32, 1, &root);
440         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_WM_NAME], atoms[UTF8_STRING], 8, strlen("i3"), "i3");
441
442         keysyms = xcb_key_symbols_alloc(conn);
443
444         xcb_get_numlock_mask(conn);
445
446         grab_all_keys(conn);
447
448         /* Autostarting exec-lines */
449         struct Autostart *exec;
450         if (autostart) {
451                 TAILQ_FOREACH(exec, &autostarts, autostarts) {
452                         LOG("auto-starting %s\n", exec->command);
453                         start_application(exec->command);
454                 }
455         }
456
457         /* check for Xinerama */
458         DLOG("Checking for Xinerama...\n");
459         initialize_xinerama(conn);
460
461         xcb_flush(conn);
462
463         /* Get pointer position to see on which screen we’re starting */
464         xcb_query_pointer_reply_t *reply;
465         if ((reply = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, root), NULL)) == NULL) {
466                 ELOG("Could not get pointer position\n");
467                 return 1;
468         }
469
470         i3Screen *screen = get_screen_containing(reply->root_x, reply->root_y);
471         if (screen == NULL) {
472                 ELOG("ERROR: No screen at %d x %d, starting on the first screen\n",
473                     reply->root_x, reply->root_y);
474                 screen = TAILQ_FIRST(virtual_screens);
475         }
476
477         DLOG("Starting on %d\n", screen->current_workspace);
478         c_ws = screen->current_workspace;
479
480         manage_existing_windows(conn, &prophs, root);
481
482         /* Create the UNIX domain socket for IPC */
483         if (config.ipc_socket_path != NULL) {
484                 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
485                 if (ipc_socket == -1) {
486                         ELOG("Could not create the IPC socket, IPC disabled\n");
487                 } else {
488                         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
489                         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
490                         ev_io_start(loop, ipc_io);
491                 }
492         }
493
494         /* Handle the events which arrived until now */
495         xcb_check_cb(NULL, NULL, 0);
496
497         /* Ungrab the server to receive events and enter libev’s eventloop */
498         xcb_ungrab_server(conn);
499         ev_loop(loop, 0);
500
501         /* not reached */
502         return 0;
503 }