]> git.sur5r.net Git - i3/i3/blob - src/mainx.c
Implement stack-limit for further defining how stack windows should look
[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
53 xcb_connection_t *global_conn;
54
55 /* This is the path to i3, copied from argv[0] when starting up */
56 char **start_argv;
57
58 /* This is our connection to X11 for use with XKB */
59 Display *xkbdpy;
60
61 xcb_key_symbols_t *keysyms;
62
63 /* The list of key bindings */
64 struct bindings_head bindings = TAILQ_HEAD_INITIALIZER(bindings);
65
66 /* The list of exec-lines */
67 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
68
69 /* The list of assignments */
70 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
71
72 /* This is a list of Stack_Windows, global, for easier/faster access on expose events */
73 struct stack_wins_head stack_wins = SLIST_HEAD_INITIALIZER(stack_wins);
74
75 /* The event handlers need to be global because they are accessed by our custom event handler
76    in handle_button_press(), needed for graphical resizing */
77 xcb_event_handlers_t evenths;
78 xcb_atom_t atoms[NUM_ATOMS];
79
80 xcb_window_t root;
81 int num_screens = 0;
82
83 /* The depth of the root screen (used e.g. for creating new pixmaps later) */
84 uint8_t root_depth;
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(evenths.c);
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(evenths.c)) != NULL) {
112                 xcb_event_handle(&evenths, event);
113                 free(event);
114         }
115 }
116
117 /*
118  * When using xmodmap to change the keyboard mapping, this event
119  * is only sent via XKB. Therefore, we need this special handler.
120  *
121  */
122 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
123         LOG("got xkb event, yay\n");
124         XEvent ev;
125         /* When using xmodmap, every change (!) gets an own event.
126          * Therefore, we just read all events and only handle the
127          * mapping_notify once (we do not receive any other XKB
128          * events anyway). */
129         while (XPending(xkbdpy))
130                 XNextEvent(xkbdpy, &ev);
131
132         xcb_key_symbols_free(keysyms);
133         keysyms = xcb_key_symbols_alloc(global_conn);
134
135         xcb_get_numlock_mask(global_conn);
136
137         ungrab_all_keys(global_conn);
138         LOG("Re-grabbing...\n");
139         grab_all_keys(global_conn);
140         LOG("Done\n");
141
142 }
143
144
145 int main(int argc, char *argv[], char *env[]) {
146         int i, screens, opt;
147         char *override_configpath = NULL;
148         bool autostart = true;
149         xcb_connection_t *conn;
150         xcb_property_handlers_t prophs;
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                 {0, 0, 0, 0}
158         };
159         int option_index = 0;
160
161         setlocale(LC_ALL, "");
162
163         /* Disable output buffering to make redirects in .xsession actually useful for debugging */
164         if (!isatty(fileno(stdout)))
165                 setbuf(stdout, NULL);
166
167         start_argv = argv;
168
169         while ((opt = getopt_long(argc, argv, "c:vahl", long_options, &option_index)) != -1) {
170                 switch (opt) {
171                         case 'a':
172                                 LOG("Autostart disabled using -a\n");
173                                 autostart = false;
174                                 break;
175                         case 'c':
176                                 override_configpath = sstrdup(optarg);
177                                 break;
178                         case 'v':
179                                 printf("i3 version " I3_VERSION " © 2009 Michael Stapelberg and contributors\n");
180                                 exit(EXIT_SUCCESS);
181                         case 'l':
182                                 config_use_lexer = true;
183                                 break;
184                         default:
185                                 fprintf(stderr, "Usage: %s [-c configfile] [-a] [-v]\n", argv[0]);
186                                 fprintf(stderr, "\n");
187                                 fprintf(stderr, "-a: disable autostart\n");
188                                 fprintf(stderr, "-v: display version and exit\n");
189                                 fprintf(stderr, "-c <configfile>: use the provided configfile instead\n");
190                                 exit(EXIT_FAILURE);
191                 }
192         }
193
194         LOG("i3 version " I3_VERSION " starting\n");
195
196         /* Initialize the table data structures for each workspace */
197         init_table();
198
199         memset(&evenths, 0, sizeof(xcb_event_handlers_t));
200         memset(&prophs, 0, sizeof(xcb_property_handlers_t));
201
202         conn = global_conn = xcb_connect(NULL, &screens);
203
204         if (xcb_connection_has_error(conn))
205                 die("Cannot open display\n");
206
207         load_configuration(conn, override_configpath, false);
208
209         /* Place requests for the atoms we need as soon as possible */
210         #define REQUEST_ATOM(name) atom_cookies[name] = xcb_intern_atom(conn, 0, strlen(#name), #name);
211
212         REQUEST_ATOM(_NET_SUPPORTED);
213         REQUEST_ATOM(_NET_WM_STATE_FULLSCREEN);
214         REQUEST_ATOM(_NET_SUPPORTING_WM_CHECK);
215         REQUEST_ATOM(_NET_WM_NAME);
216         REQUEST_ATOM(_NET_WM_STATE);
217         REQUEST_ATOM(_NET_WM_WINDOW_TYPE);
218         REQUEST_ATOM(_NET_WM_DESKTOP);
219         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
220         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
221         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
222         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
223         REQUEST_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
224         REQUEST_ATOM(_NET_WM_STRUT_PARTIAL);
225         REQUEST_ATOM(WM_PROTOCOLS);
226         REQUEST_ATOM(WM_DELETE_WINDOW);
227         REQUEST_ATOM(UTF8_STRING);
228         REQUEST_ATOM(WM_STATE);
229         REQUEST_ATOM(WM_CLIENT_LEADER);
230
231         /* TODO: this has to be more beautiful somewhen */
232         int major, minor, error;
233
234         major = XkbMajorVersion;
235         minor = XkbMinorVersion;
236
237         int evBase, errBase;
238
239         if ((xkbdpy = XkbOpenDisplay(getenv("DISPLAY"), &evBase, &errBase, &major, &minor, &error)) == NULL) {
240                 fprintf(stderr, "XkbOpenDisplay() failed\n");
241                 return 1;
242         }
243
244         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
245                 fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
246                 return 1;
247         }
248
249         int i1;
250         if (!XkbQueryExtension(xkbdpy,&i1,&evBase,&errBase,&major,&minor)) {
251                 fprintf(stderr, "XKB not supported by X-server\n");
252                 return 1;
253         }
254         /* end of ugliness */
255
256         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd, XkbMapNotifyMask, XkbMapNotifyMask)) {
257                 fprintf(stderr, "Could not set XKB event mask\n");
258                 return 1;
259         }
260
261         /* Initialize event loop using libev */
262         struct ev_loop *loop = ev_default_loop(0);
263         if (loop == NULL)
264                 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
265
266         struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
267         struct ev_io *xkb = scalloc(sizeof(struct ev_io));
268         struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
269         struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
270
271         ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
272         ev_io_start(loop, xcb_watcher);
273
274         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
275         ev_io_start(loop, xkb);
276
277         /* Flush the buffer so that libev can properly get new events */
278         XFlush(xkbdpy);
279
280         ev_check_init(xcb_check, xcb_check_cb);
281         ev_check_start(loop, xcb_check);
282
283         ev_prepare_init(xcb_prepare, xcb_prepare_cb);
284         ev_prepare_start(loop, xcb_prepare);
285
286         /* Grab the server to delay any events until we enter the eventloop */
287         xcb_grab_server(conn);
288
289         xcb_event_handlers_init(conn, &evenths);
290
291         /* DEBUG: Trap all events and print them */
292         for (i = 2; i < 128; ++i)
293                 xcb_event_set_handler(&evenths, i, handle_event, 0);
294
295         for (i = 0; i < 256; ++i)
296                 xcb_event_set_error_handler(&evenths, i, (xcb_generic_error_handler_t)handle_event, 0);
297
298         /* Expose = an Application should redraw itself, in this case it’s our titlebars. */
299         xcb_event_set_expose_handler(&evenths, handle_expose_event, NULL);
300
301         /* Key presses/releases are pretty obvious, I think */
302         xcb_event_set_key_press_handler(&evenths, handle_key_press, NULL);
303         xcb_event_set_key_release_handler(&evenths, handle_key_release, NULL);
304
305         /* Enter window = user moved his mouse over the window */
306         xcb_event_set_enter_notify_handler(&evenths, handle_enter_notify, NULL);
307
308         /* Button press = user pushed a mouse button over one of our windows */
309         xcb_event_set_button_press_handler(&evenths, handle_button_press, NULL);
310
311         /* Map notify = there is a new window */
312         xcb_event_set_map_request_handler(&evenths, handle_map_request, &prophs);
313
314         /* Unmap notify = window disappeared. When sent from a client, we don’t manage
315            it any longer. Usually, the client destroys the window shortly afterwards. */
316         xcb_event_set_unmap_notify_handler(&evenths, handle_unmap_notify_event, NULL);
317
318         /* Configure notify = window’s configuration (geometry, stacking, …). We only need
319            it to set up ignore the following enter_notify events */
320         xcb_event_set_configure_notify_handler(&evenths, handle_configure_event, NULL);
321
322         /* Configure request = window tried to change size on its own */
323         xcb_event_set_configure_request_handler(&evenths, handle_configure_request, NULL);
324
325         /* Motion notify = user moved his cursor (over the root window and may
326          * cross virtual screen boundaries doing that) */
327         xcb_event_set_motion_notify_handler(&evenths, handle_motion_notify, NULL);
328
329         /* Mapping notify = keyboard mapping changed (Xmodmap), re-grab bindings */
330         xcb_event_set_mapping_notify_handler(&evenths, handle_mapping_notify, NULL);
331
332         /* Client message are sent to the root window. The only interesting client message
333            for us is _NET_WM_STATE, we honour _NET_WM_STATE_FULLSCREEN */
334         xcb_event_set_client_message_handler(&evenths, handle_client_message, NULL);
335
336         /* Initialize the property handlers */
337         xcb_property_handlers_init(&prophs, &evenths);
338
339         /* Watch size hints (to obey correct aspect ratio) */
340         xcb_property_set_handler(&prophs, WM_NORMAL_HINTS, UINT_MAX, handle_normal_hints, NULL);
341
342         /* Get the root window and set the event mask */
343         xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
344         root = root_screen->root;
345         root_depth = root_screen->root_depth;
346
347         uint32_t mask = XCB_CW_EVENT_MASK;
348         uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
349                               XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
350                                                                            projector), the root window gets a
351                                                                            ConfigureNotify */
352                               XCB_EVENT_MASK_POINTER_MOTION |
353                               XCB_EVENT_MASK_PROPERTY_CHANGE |
354                               XCB_EVENT_MASK_ENTER_WINDOW };
355         xcb_change_window_attributes(conn, root, mask, values);
356
357         /* Setup NetWM atoms */
358         #define GET_ATOM(name) { \
359                 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, atom_cookies[name], NULL); \
360                 if (!reply) { \
361                         LOG("Could not get atom " #name "\n"); \
362                         exit(-1); \
363                 } \
364                 atoms[name] = reply->atom; \
365                 free(reply); \
366         }
367
368         GET_ATOM(_NET_SUPPORTED);
369         GET_ATOM(_NET_WM_STATE_FULLSCREEN);
370         GET_ATOM(_NET_SUPPORTING_WM_CHECK);
371         GET_ATOM(_NET_WM_NAME);
372         GET_ATOM(_NET_WM_STATE);
373         GET_ATOM(_NET_WM_WINDOW_TYPE);
374         GET_ATOM(_NET_WM_DESKTOP);
375         GET_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
376         GET_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
377         GET_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
378         GET_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
379         GET_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
380         GET_ATOM(_NET_WM_STRUT_PARTIAL);
381         GET_ATOM(WM_PROTOCOLS);
382         GET_ATOM(WM_DELETE_WINDOW);
383         GET_ATOM(UTF8_STRING);
384         GET_ATOM(WM_STATE);
385         GET_ATOM(WM_CLIENT_LEADER);
386
387         xcb_property_set_handler(&prophs, atoms[_NET_WM_WINDOW_TYPE], UINT_MAX, handle_window_type, NULL);
388         /* TODO: In order to comply with EWMH, we have to watch _NET_WM_STRUT_PARTIAL */
389
390         /* Watch _NET_WM_NAME (= title of the window in UTF-8) property */
391         xcb_property_set_handler(&prophs, atoms[_NET_WM_NAME], 128, handle_windowname_change, NULL);
392
393         /* Watch WM_TRANSIENT_FOR property (to which client this popup window belongs) */
394         xcb_property_set_handler(&prophs, WM_TRANSIENT_FOR, UINT_MAX, handle_transient_for, NULL);
395
396         /* Watch WM_NAME (= title of the window in compound text) property for legacy applications */
397         xcb_watch_wm_name(&prophs, 128, handle_windowname_change_legacy, NULL);
398
399         /* Watch WM_CLASS (= class of the window) */
400         xcb_property_set_handler(&prophs, WM_CLASS, 128, handle_windowclass_change, NULL);
401
402         /* Watch WM_CLIENT_LEADER (= logical parent window for toolbars etc.) */
403         xcb_property_set_handler(&prophs, atoms[WM_CLIENT_LEADER], UINT_MAX, handle_clientleader_change, NULL);
404
405         /* Watch WM_HINTS (contains the urgent property) */
406         xcb_property_set_handler(&prophs, WM_HINTS, UINT_MAX, handle_hints, NULL);
407
408         /* Set up the atoms we support */
409         check_error(conn, xcb_change_property_checked(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTED],
410                        ATOM, 32, 7, atoms), "Could not set _NET_SUPPORTED");
411         /* Set up the window manager’s name */
412         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_SUPPORTING_WM_CHECK], WINDOW, 32, 1, &root);
413         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, atoms[_NET_WM_NAME], atoms[UTF8_STRING], 8, strlen("i3"), "i3");
414
415         keysyms = xcb_key_symbols_alloc(conn);
416
417         xcb_get_numlock_mask(conn);
418
419         grab_all_keys(conn);
420
421         /* Autostarting exec-lines */
422         struct Autostart *exec;
423         if (autostart) {
424                 TAILQ_FOREACH(exec, &autostarts, autostarts) {
425                         LOG("auto-starting %s\n", exec->command);
426                         start_application(exec->command);
427                 }
428         }
429
430         /* check for Xinerama */
431         LOG("Checking for Xinerama...\n");
432         initialize_xinerama(conn);
433
434         xcb_flush(conn);
435
436         /* Get pointer position to see on which screen we’re starting */
437         xcb_query_pointer_reply_t *reply;
438         if ((reply = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, root), NULL)) == NULL) {
439                 LOG("Could not get pointer position\n");
440                 return 1;
441         }
442
443         i3Screen *screen = get_screen_containing(reply->root_x, reply->root_y);
444         if (screen == NULL) {
445                 LOG("ERROR: No screen at %d x %d, starting on the first screen\n",
446                     reply->root_x, reply->root_y);
447                 screen = TAILQ_FIRST(virtual_screens);
448         }
449
450         LOG("Starting on %d\n", screen->current_workspace);
451         c_ws = &workspaces[screen->current_workspace];
452
453         manage_existing_windows(conn, &prophs, root);
454
455         /* Create the UNIX domain socket for IPC */
456         if (config.ipc_socket_path != NULL) {
457                 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
458                 if (ipc_socket == -1) {
459                         LOG("Could not create the IPC socket, IPC disabled\n");
460                 } else {
461                         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
462                         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
463                         ev_io_start(loop, ipc_io);
464                 }
465         }
466
467         /* Handle the events which arrived until now */
468         xcb_check_cb(NULL, NULL, 0);
469
470         /* Ungrab the server to receive events and enter libev’s eventloop */
471         xcb_ungrab_server(conn);
472         ev_loop(loop, 0);
473
474         /* not reached */
475         return 0;
476 }