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