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