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