]> git.sur5r.net Git - i3/i3/blob - src/main.c
Make i3 compatible with the very latest xcb
[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
19 xcb_window_t root;
20 uint8_t root_depth;
21
22 xcb_key_symbols_t *keysyms;
23
24 /* Those are our connections to X11 for use with libXcursor and XKB */
25 Display *xlibdpy, *xkbdpy;
26
27 /* The list of key bindings */
28 struct bindings_head *bindings;
29
30 /* The list of exec-lines */
31 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
32
33 /* The list of assignments */
34 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
35
36 /* We hope that those are supported and set them to true */
37 bool xcursor_supported = true;
38 bool xkb_supported = true;
39
40 /*
41  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
42  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
43  *
44  */
45 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
46     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
47 }
48
49 /*
50  * Flush before blocking (and waiting for new events)
51  *
52  */
53 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
54     xcb_flush(conn);
55 }
56
57 /*
58  * Instead of polling the X connection socket we leave this to
59  * xcb_poll_for_event() which knows better than we can ever know.
60  *
61  */
62 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
63     xcb_generic_event_t *event;
64
65     while ((event = xcb_poll_for_event(conn)) != NULL) {
66         if (event->response_type == 0) {
67             ELOG("X11 Error received! sequence %x\n", event->sequence);
68             continue;
69         }
70
71         /* Strip off the highest bit (set if the event is generated) */
72         int type = (event->response_type & 0x7F);
73
74         handle_event(type, event);
75
76         free(event);
77     }
78 }
79
80
81 /*
82  * When using xmodmap to change the keyboard mapping, this event
83  * is only sent via XKB. Therefore, we need this special handler.
84  *
85  */
86 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
87     DLOG("Handling XKB event\n");
88     XkbEvent ev;
89
90     /* When using xmodmap, every change (!) gets an own event.
91      * Therefore, we just read all events and only handle the
92      * mapping_notify once. */
93     bool mapping_changed = false;
94     while (XPending(xkbdpy)) {
95         XNextEvent(xkbdpy, (XEvent*)&ev);
96         /* While we should never receive a non-XKB event,
97          * better do sanity checking */
98         if (ev.type != xkb_event_base)
99             continue;
100
101         if (ev.any.xkb_type == XkbMapNotify) {
102             mapping_changed = true;
103             continue;
104         }
105
106         if (ev.any.xkb_type != XkbStateNotify) {
107             ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
108             continue;
109         }
110
111         /* See The XKB Extension: Library Specification, section 14.1 */
112         /* We check if the current group (each group contains
113          * two levels) has been changed. Mode_switch activates
114          * group XkbGroup2Index */
115         if (xkb_current_group == ev.state.group)
116             continue;
117
118         xkb_current_group = ev.state.group;
119
120         if (ev.state.group == XkbGroup2Index) {
121             DLOG("Mode_switch enabled\n");
122             grab_all_keys(conn, true);
123         }
124
125         if (ev.state.group == XkbGroup1Index) {
126             DLOG("Mode_switch disabled\n");
127             ungrab_all_keys(conn);
128             grab_all_keys(conn, false);
129         }
130     }
131
132     if (!mapping_changed)
133         return;
134
135     DLOG("Keyboard mapping changed, updating keybindings\n");
136     xcb_key_symbols_free(keysyms);
137     keysyms = xcb_key_symbols_alloc(conn);
138
139     xcb_get_numlock_mask(conn);
140
141     ungrab_all_keys(conn);
142     DLOG("Re-grabbing...\n");
143     translate_keysyms();
144     grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
145     DLOG("Done\n");
146 }
147
148 int main(int argc, char *argv[]) {
149     //parse_cmd("[ foo ] attach, attach ; focus");
150     int screens;
151     char *override_configpath = NULL;
152     bool autostart = true;
153     char *layout_path = NULL;
154     bool delete_layout_path = false;
155     bool only_check_config = false;
156     bool force_xinerama = false;
157     bool disable_signalhandler = false;
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         {"layout", required_argument, 0, 'L'},
164         {"restart", required_argument, 0, 0},
165         {"force-xinerama", no_argument, 0, 0},
166         {"disable-signalhandler", no_argument, 0, 0},
167         {0, 0, 0, 0}
168     };
169     int option_index = 0, opt;
170
171     setlocale(LC_ALL, "");
172
173     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
174     if (!isatty(fileno(stdout)))
175         setbuf(stdout, NULL);
176
177     start_argv = argv;
178
179     while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
180         switch (opt) {
181             case 'a':
182                 LOG("Autostart disabled using -a\n");
183                 autostart = false;
184                 break;
185             case 'L':
186                 FREE(layout_path);
187                 layout_path = sstrdup(optarg);
188                 delete_layout_path = false;
189                 break;
190             case 'c':
191                 FREE(override_configpath);
192                 override_configpath = sstrdup(optarg);
193                 break;
194             case 'C':
195                 LOG("Checking configuration file only (-C)\n");
196                 only_check_config = true;
197                 break;
198             case 'v':
199                 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
200                 exit(EXIT_SUCCESS);
201             case 'V':
202                 set_verbosity(true);
203                 break;
204             case 'd':
205                 LOG("Enabling debug loglevel %s\n", optarg);
206                 add_loglevel(optarg);
207                 break;
208             case 'l':
209                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
210                 break;
211             case 0:
212                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
213                     force_xinerama = true;
214                     ELOG("Using Xinerama instead of RandR. This option should be "
215                          "avoided at all cost because it does not refresh the list "
216                          "of screens, so you cannot configure displays at runtime. "
217                          "Please check if your driver really does not support RandR "
218                          "and disable this option as soon as you can.\n");
219                     break;
220                 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
221                     disable_signalhandler = true;
222                     break;
223                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
224                     FREE(layout_path);
225                     layout_path = sstrdup(optarg);
226                     delete_layout_path = true;
227                     break;
228                 }
229                 /* fall-through */
230             default:
231                 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
232                 fprintf(stderr, "\n");
233                 fprintf(stderr, "-a: disable autostart\n");
234                 fprintf(stderr, "-L <layoutfile>: load the layout from <layoutfile>\n");
235                 fprintf(stderr, "-v: display version and exit\n");
236                 fprintf(stderr, "-V: enable verbose mode\n");
237                 fprintf(stderr, "-d <loglevel>: enable debug loglevel <loglevel>\n");
238                 fprintf(stderr, "-c <configfile>: use the provided configfile instead\n");
239                 fprintf(stderr, "-C: check configuration file and exit\n");
240                 fprintf(stderr, "--force-xinerama: Use Xinerama instead of RandR. This "
241                                 "option should only be used if you are stuck with the "
242                                 "nvidia closed source driver which does not support RandR.\n");
243                 exit(EXIT_FAILURE);
244         }
245     }
246
247     LOG("i3 (tree) version " I3_VERSION " starting\n");
248
249     conn = xcb_connect(NULL, &screens);
250     if (xcb_connection_has_error(conn))
251         errx(EXIT_FAILURE, "Cannot open display\n");
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     load_configuration(conn, override_configpath, false);
258     if (only_check_config) {
259         LOG("Done checking configuration file. Exiting.\n");
260         exit(0);
261     }
262
263     if (config.ipc_socket_path == NULL) {
264         config.ipc_socket_path = getenv("I3SOCK");
265     }
266
267     uint32_t mask = XCB_CW_EVENT_MASK;
268     uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
269                           XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
270                                                                            projector), the root window gets a
271                                                                            ConfigureNotify */
272                           XCB_EVENT_MASK_POINTER_MOTION |
273                           XCB_EVENT_MASK_PROPERTY_CHANGE |
274                           XCB_EVENT_MASK_ENTER_WINDOW };
275     xcb_void_cookie_t cookie;
276     cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
277     check_error(conn, cookie, "Another window manager seems to be running");
278
279     /* Place requests for the atoms we need as soon as possible */
280     #define xmacro(atom) \
281         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
282     #include "atoms.xmacro"
283     #undef xmacro
284
285     /* Initialize the Xlib connection */
286     xlibdpy = xkbdpy = XOpenDisplay(NULL);
287
288     /* Try to load the X cursors and initialize the XKB extension */
289     if (xlibdpy == NULL) {
290         ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
291         xcursor_supported = false;
292         xkb_supported = false;
293     } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
294         ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
295         return 1;
296     } else {
297         xcursor_load_cursors();
298         /*init_xkb();*/
299     }
300
301     if (xkb_supported) {
302         int errBase,
303             major = XkbMajorVersion,
304             minor = XkbMinorVersion;
305
306         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
307             fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
308             return 1;
309         }
310
311         int i1;
312         if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
313             fprintf(stderr, "XKB not supported by X-server\n");
314             return 1;
315         }
316         /* end of ugliness */
317
318         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
319                              XkbMapNotifyMask | XkbStateNotifyMask,
320                              XkbMapNotifyMask | XkbStateNotifyMask)) {
321             fprintf(stderr, "Could not set XKB event mask\n");
322             return 1;
323         }
324     }
325
326     /* Setup NetWM atoms */
327     #define xmacro(name) \
328         do { \
329             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
330             if (!reply) { \
331                 ELOG("Could not get atom " #name "\n"); \
332                 exit(-1); \
333             } \
334             A_ ## name = reply->atom; \
335             free(reply); \
336         } while (0);
337     #include "atoms.xmacro"
338     #undef xmacro
339
340     property_handlers_init();
341
342     /* Set up the atoms we support */
343     xcb_atom_t supported_atoms[] = {
344 #define xmacro(atom) A_ ## atom,
345 #include "atoms.xmacro"
346 #undef xmacro
347     };
348     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, A_ATOM, 32, 7, supported_atoms);
349     /* Set up the window manager’s name */
350     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, A_WINDOW, 32, 1, &root);
351     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
352
353     keysyms = xcb_key_symbols_alloc(conn);
354
355     xcb_get_numlock_mask(conn);
356
357     translate_keysyms();
358     grab_all_keys(conn, false);
359
360     bool needs_tree_init = true;
361     if (layout_path) {
362         LOG("Trying to restore the layout from %s...", layout_path);
363         needs_tree_init = !tree_restore(layout_path);
364         if (delete_layout_path)
365             unlink(layout_path);
366         free(layout_path);
367     }
368     if (needs_tree_init)
369         tree_init();
370
371     if (force_xinerama) {
372         xinerama_init();
373     } else {
374         DLOG("Checking for XRandR...\n");
375         randr_init(&randr_base);
376     }
377
378     tree_render();
379
380     struct ev_loop *loop = ev_loop_new(0);
381     if (loop == NULL)
382             die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
383
384     /* Create the UNIX domain socket for IPC */
385     if (config.ipc_socket_path != NULL) {
386         int ipc_socket = ipc_create_socket(config.ipc_socket_path);
387         if (ipc_socket == -1) {
388             ELOG("Could not create the IPC socket, IPC disabled\n");
389         } else {
390             struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
391             ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
392             ev_io_start(loop, ipc_io);
393         }
394     }
395
396     struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
397     struct ev_io *xkb = scalloc(sizeof(struct ev_io));
398     struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
399     struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
400
401     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
402     ev_io_start(loop, xcb_watcher);
403
404
405     if (xkb_supported) {
406         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
407         ev_io_start(loop, xkb);
408
409         /* Flush the buffer so that libev can properly get new events */
410         XFlush(xkbdpy);
411     }
412
413     ev_check_init(xcb_check, xcb_check_cb);
414     ev_check_start(loop, xcb_check);
415
416     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
417     ev_prepare_start(loop, xcb_prepare);
418
419     xcb_flush(conn);
420
421     manage_existing_windows(root);
422
423     if (!disable_signalhandler)
424         setup_signal_handler();
425
426     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
427      * while we are sending him a message */
428     signal(SIGPIPE, SIG_IGN);
429
430     /* Autostarting exec-lines */
431     if (autostart) {
432         struct Autostart *exec;
433         TAILQ_FOREACH(exec, &autostarts, autostarts) {
434             LOG("auto-starting %s\n", exec->command);
435             start_application(exec->command);
436         }
437     }
438
439     ev_loop(loop, 0);
440 }