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