]> git.sur5r.net Git - i3/i3/blob - src/main.c
Include <limits.h> in all.h
[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
283     load_configuration(conn, override_configpath, false);
284     if (only_check_config) {
285         LOG("Done checking configuration file. Exiting.\n");
286         exit(0);
287     }
288
289     if (config.ipc_socket_path == NULL) {
290         /* Fall back to a file name in /tmp/ based on the PID */
291         if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
292             config.ipc_socket_path = get_process_filename("ipc-socket");
293         else
294             config.ipc_socket_path = sstrdup(config.ipc_socket_path);
295     }
296
297     uint32_t mask = XCB_CW_EVENT_MASK;
298     uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
299                           XCB_EVENT_MASK_STRUCTURE_NOTIFY |         /* when the user adds a screen (e.g. video
300                                                                            projector), the root window gets a
301                                                                            ConfigureNotify */
302                           XCB_EVENT_MASK_POINTER_MOTION |
303                           XCB_EVENT_MASK_PROPERTY_CHANGE |
304                           XCB_EVENT_MASK_ENTER_WINDOW };
305     xcb_void_cookie_t cookie;
306     cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
307     check_error(conn, cookie, "Another window manager seems to be running");
308
309     xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
310     if (greply == NULL) {
311         ELOG("Could not get geometry of the root window, exiting\n");
312         return 1;
313     }
314     DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
315
316     /* Place requests for the atoms we need as soon as possible */
317     #define xmacro(atom) \
318         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
319     #include "atoms.xmacro"
320     #undef xmacro
321
322     /* Initialize the Xlib connection */
323     xlibdpy = xkbdpy = XOpenDisplay(NULL);
324
325     /* Try to load the X cursors and initialize the XKB extension */
326     if (xlibdpy == NULL) {
327         ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
328         xcursor_supported = false;
329         xkb_supported = false;
330     } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
331         ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
332         return 1;
333     } else {
334         xcursor_load_cursors();
335         /*init_xkb();*/
336     }
337
338     /* Set a cursor for the root window (otherwise the root window will show no
339        cursor until the first client is launched). */
340     if (xcursor_supported) {
341         xcursor_set_root_cursor();
342     } else {
343         xcb_cursor_t cursor_id = xcb_generate_id(conn);
344         i3Font cursor_font = load_font("cursor", false);
345         int xcb_cursor = xcursor_get_xcb_cursor(XCURSOR_CURSOR_POINTER);
346         xcb_create_glyph_cursor(conn, cursor_id, cursor_font.id, cursor_font.id,
347                 xcb_cursor, xcb_cursor + 1, 0, 0, 0, 65535, 65535, 65535);
348         xcb_change_window_attributes(conn, root, XCB_CW_CURSOR, &cursor_id);
349         xcb_free_cursor(conn, cursor_id);
350     }
351
352     if (xkb_supported) {
353         int errBase,
354             major = XkbMajorVersion,
355             minor = XkbMinorVersion;
356
357         if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
358             fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
359             return 1;
360         }
361
362         int i1;
363         if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
364             fprintf(stderr, "XKB not supported by X-server\n");
365             return 1;
366         }
367         /* end of ugliness */
368
369         if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
370                              XkbMapNotifyMask | XkbStateNotifyMask,
371                              XkbMapNotifyMask | XkbStateNotifyMask)) {
372             fprintf(stderr, "Could not set XKB event mask\n");
373             return 1;
374         }
375     }
376
377     /* Setup NetWM atoms */
378     #define xmacro(name) \
379         do { \
380             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
381             if (!reply) { \
382                 ELOG("Could not get atom " #name "\n"); \
383                 exit(-1); \
384             } \
385             A_ ## name = reply->atom; \
386             free(reply); \
387         } while (0);
388     #include "atoms.xmacro"
389     #undef xmacro
390
391     property_handlers_init();
392
393     /* Set up the atoms we support */
394     xcb_atom_t supported_atoms[] = {
395 #define xmacro(atom) A_ ## atom,
396 #include "atoms.xmacro"
397 #undef xmacro
398     };
399     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, A_ATOM, 32, 16, supported_atoms);
400     /* Set up the window manager’s name */
401     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, A_WINDOW, 32, 1, &root);
402     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
403
404     keysyms = xcb_key_symbols_alloc(conn);
405
406     xcb_get_numlock_mask(conn);
407
408     translate_keysyms();
409     grab_all_keys(conn, false);
410
411     bool needs_tree_init = true;
412     if (layout_path) {
413         LOG("Trying to restore the layout from %s...", layout_path);
414         needs_tree_init = !tree_restore(layout_path, greply);
415         if (delete_layout_path)
416             unlink(layout_path);
417         free(layout_path);
418     }
419     if (needs_tree_init)
420         tree_init(greply);
421
422     free(greply);
423
424     if (force_xinerama) {
425         xinerama_init();
426     } else {
427         DLOG("Checking for XRandR...\n");
428         randr_init(&randr_base);
429     }
430
431     tree_render();
432
433     /* Create the UNIX domain socket for IPC */
434     int ipc_socket = ipc_create_socket(config.ipc_socket_path);
435     if (ipc_socket == -1) {
436         ELOG("Could not create the IPC socket, IPC disabled\n");
437     } else {
438         free(config.ipc_socket_path);
439         struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
440         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
441         ev_io_start(main_loop, ipc_io);
442     }
443
444     /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
445     x_set_i3_atoms();
446
447     struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
448     struct ev_io *xkb = scalloc(sizeof(struct ev_io));
449     struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
450     struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
451
452     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
453     ev_io_start(main_loop, xcb_watcher);
454
455
456     if (xkb_supported) {
457         ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
458         ev_io_start(main_loop, xkb);
459
460         /* Flush the buffer so that libev can properly get new events */
461         XFlush(xkbdpy);
462     }
463
464     ev_check_init(xcb_check, xcb_check_cb);
465     ev_check_start(main_loop, xcb_check);
466
467     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
468     ev_prepare_start(main_loop, xcb_prepare);
469
470     xcb_flush(conn);
471
472     manage_existing_windows(root);
473
474     if (!disable_signalhandler)
475         setup_signal_handler();
476
477     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
478      * while we are sending him a message */
479     signal(SIGPIPE, SIG_IGN);
480
481     /* Autostarting exec-lines */
482     if (autostart) {
483         struct Autostart *exec;
484         TAILQ_FOREACH(exec, &autostarts, autostarts) {
485             LOG("auto-starting %s\n", exec->command);
486             start_application(exec->command);
487         }
488     }
489
490     /* Autostarting exec_always-lines */
491     struct Autostart *exec_always;
492     TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
493         LOG("auto-starting (always!) %s\n", exec_always->command);
494         start_application(exec_always->command);
495     }
496
497     ev_loop(main_loop, 0);
498 }