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