i3
main.c
Go to the documentation of this file.
1 #undef I3__FILE__
2 #define I3__FILE__ "main.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2013 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * main.c: Initialization, main loop
10  *
11  */
12 #include <ev.h>
13 #include <fcntl.h>
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <sys/un.h>
17 #include <sys/time.h>
18 #include <sys/resource.h>
19 #include <sys/mman.h>
20 #include <sys/stat.h>
21 #include <libgen.h>
22 #include "all.h"
23 #include "shmlog.h"
24 
25 #include "sd-daemon.h"
26 
27 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
28  * this before starting any other process, since we set RLIMIT_CORE to
29  * RLIM_INFINITY for i3 debugging versions. */
30 struct rlimit original_rlimit_core;
31 
34 
35 /* We keep the xcb_check watcher around to be able to enable and disable it
36  * temporarily for drag_pointer(). */
37 static struct ev_check *xcb_check;
38 
39 extern Con *focused;
40 
41 char **start_argv;
42 
43 xcb_connection_t *conn;
44 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
46 
47 /* Display handle for libstartup-notification */
48 SnDisplay *sndisplay;
49 
50 /* The last timestamp we got from X11 (timestamps are included in some events
51  * and are used for some things, like determining a unique ID in startup
52  * notification). */
53 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
54 
55 xcb_screen_t *root_screen;
56 xcb_window_t root;
57 
58 /* Color depth, visual id and colormap to use when creating windows and
59  * pixmaps. Will use 32 bit depth and an appropriate visual, if available,
60  * otherwise the root window’s default (usually 24 bit TrueColor). */
61 uint8_t root_depth;
62 xcb_visualid_t visual_id;
63 xcb_colormap_t colormap;
64 
65 struct ev_loop *main_loop;
66 
67 xcb_key_symbols_t *keysyms;
68 
69 /* Default shmlog size if not set by user. */
70 const int default_shmlog_size = 25 * 1024 * 1024;
71 
72 /* The list of key bindings */
73 struct bindings_head *bindings;
74 
75 /* The list of exec-lines */
76 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
77 
78 /* The list of exec_always lines */
80 
81 /* The list of assignments */
82 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
83 
84 /* The list of workspace assignments (which workspace should end up on which
85  * output) */
87 
88 /* We hope that those are supported and set them to true */
89 bool xcursor_supported = true;
90 
91 /*
92  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
93  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
94  *
95  */
96 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
97  /* empty, because xcb_prepare_cb and xcb_check_cb are used */
98 }
99 
100 /*
101  * Flush before blocking (and waiting for new events)
102  *
103  */
104 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
105  xcb_flush(conn);
106 }
107 
108 /*
109  * Instead of polling the X connection socket we leave this to
110  * xcb_poll_for_event() which knows better than we can ever know.
111  *
112  */
113 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
114  xcb_generic_event_t *event;
115 
116  while ((event = xcb_poll_for_event(conn)) != NULL) {
117  if (event->response_type == 0) {
118  if (event_is_ignored(event->sequence, 0))
119  DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
120  else {
121  xcb_generic_error_t *error = (xcb_generic_error_t *)event;
122  DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
123  error->sequence, error->error_code);
124  }
125  free(event);
126  continue;
127  }
128 
129  /* Strip off the highest bit (set if the event is generated) */
130  int type = (event->response_type & 0x7F);
131 
132  handle_event(type, event);
133 
134  free(event);
135  }
136 }
137 
138 /*
139  * Enable or disable the main X11 event handling function.
140  * This is used by drag_pointer() which has its own, modal event handler, which
141  * takes precedence over the normal event handler.
142  *
143  */
144 void main_set_x11_cb(bool enable) {
145  DLOG("Setting main X11 callback to enabled=%d\n", enable);
146  if (enable) {
147  ev_check_start(main_loop, xcb_check);
148  /* Trigger the watcher explicitly to handle all remaining X11 events.
149  * drag_pointer()’s event handler exits in the middle of the loop. */
150  ev_feed_event(main_loop, xcb_check, 0);
151  } else {
152  ev_check_stop(main_loop, xcb_check);
153  }
154 }
155 
156 /*
157  * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
158  *
159  */
160 static void i3_exit(void) {
161 /* We need ev >= 4 for the following code. Since it is not *that* important (it
162  * only makes sure that there are no i3-nagbar instances left behind) we still
163  * support old systems with libev 3. */
164 #if EV_VERSION_MAJOR >= 4
165  ev_loop_destroy(main_loop);
166 #endif
167 
168  if (*shmlogname != '\0') {
169  fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
170  fflush(stderr);
171  shm_unlink(shmlogname);
172  }
173 }
174 
175 /*
176  * (One-shot) Handler for all signals with default action "Term", see signal(7)
177  *
178  * Unlinks the SHM log and re-raises the signal.
179  *
180  */
181 static void handle_signal(int sig, siginfo_t *info, void *data) {
182  if (*shmlogname != '\0') {
183  shm_unlink(shmlogname);
184  }
185  raise(sig);
186 }
187 
188 int main(int argc, char *argv[]) {
189  /* Keep a symbol pointing to the I3_VERSION string constant so that we have
190  * it in gdb backtraces. */
191  const char *i3_version __attribute__((unused)) = I3_VERSION;
192  char *override_configpath = NULL;
193  bool autostart = true;
194  char *layout_path = NULL;
195  bool delete_layout_path = false;
196  bool force_xinerama = false;
197  char *fake_outputs = NULL;
198  bool disable_signalhandler = false;
199  bool only_check_config = false;
200  static struct option long_options[] = {
201  {"no-autostart", no_argument, 0, 'a'},
202  {"config", required_argument, 0, 'c'},
203  {"version", no_argument, 0, 'v'},
204  {"moreversion", no_argument, 0, 'm'},
205  {"more-version", no_argument, 0, 'm'},
206  {"more_version", no_argument, 0, 'm'},
207  {"help", no_argument, 0, 'h'},
208  {"layout", required_argument, 0, 'L'},
209  {"restart", required_argument, 0, 0},
210  {"force-xinerama", no_argument, 0, 0},
211  {"force_xinerama", no_argument, 0, 0},
212  {"disable-signalhandler", no_argument, 0, 0},
213  {"shmlog-size", required_argument, 0, 0},
214  {"shmlog_size", required_argument, 0, 0},
215  {"get-socketpath", no_argument, 0, 0},
216  {"get_socketpath", no_argument, 0, 0},
217  {"fake_outputs", required_argument, 0, 0},
218  {"fake-outputs", required_argument, 0, 0},
219  {"force-old-config-parser-v4.4-only", no_argument, 0, 0},
220  {0, 0, 0, 0}};
221  int option_index = 0, opt;
222 
223  setlocale(LC_ALL, "");
224 
225  /* Get the RLIMIT_CORE limit at startup time to restore this before
226  * starting processes. */
227  getrlimit(RLIMIT_CORE, &original_rlimit_core);
228 
229  /* Disable output buffering to make redirects in .xsession actually useful for debugging */
230  if (!isatty(fileno(stdout)))
231  setbuf(stdout, NULL);
232 
233  srand(time(NULL));
234 
235  /* Init logging *before* initializing debug_build to guarantee early
236  * (file) logging. */
237  init_logging();
238 
239  /* On release builds, disable SHM logging by default. */
240  shmlog_size = (is_debug_build() || strstr(argv[0], "i3-with-shmlog") != NULL ? default_shmlog_size : 0);
241 
242  start_argv = argv;
243 
244  while ((opt = getopt_long(argc, argv, "c:CvmaL:hld:V", long_options, &option_index)) != -1) {
245  switch (opt) {
246  case 'a':
247  LOG("Autostart disabled using -a\n");
248  autostart = false;
249  break;
250  case 'L':
251  FREE(layout_path);
252  layout_path = sstrdup(optarg);
253  delete_layout_path = false;
254  break;
255  case 'c':
256  FREE(override_configpath);
257  override_configpath = sstrdup(optarg);
258  break;
259  case 'C':
260  LOG("Checking configuration file only (-C)\n");
261  only_check_config = true;
262  break;
263  case 'v':
264  printf("i3 version " I3_VERSION " © 2009-2014 Michael Stapelberg and contributors\n");
265  exit(EXIT_SUCCESS);
266  break;
267  case 'm':
268  printf("Binary i3 version: " I3_VERSION " © 2009-2014 Michael Stapelberg and contributors\n");
270  exit(EXIT_SUCCESS);
271  break;
272  case 'V':
273  set_verbosity(true);
274  break;
275  case 'd':
276  LOG("Enabling debug logging\n");
277  set_debug_logging(true);
278  break;
279  case 'l':
280  /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
281  break;
282  case 0:
283  if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
284  strcmp(long_options[option_index].name, "force_xinerama") == 0) {
285  force_xinerama = true;
286  ELOG("Using Xinerama instead of RandR. This option should be "
287  "avoided at all cost because it does not refresh the list "
288  "of screens, so you cannot configure displays at runtime. "
289  "Please check if your driver really does not support RandR "
290  "and disable this option as soon as you can.\n");
291  break;
292  } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
293  disable_signalhandler = true;
294  break;
295  } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
296  strcmp(long_options[option_index].name, "get_socketpath") == 0) {
297  char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
298  if (socket_path) {
299  printf("%s\n", socket_path);
300  exit(EXIT_SUCCESS);
301  }
302 
303  exit(EXIT_FAILURE);
304  } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
305  strcmp(long_options[option_index].name, "shmlog_size") == 0) {
306  shmlog_size = atoi(optarg);
307  /* Re-initialize logging immediately to get as many
308  * logmessages as possible into the SHM log. */
309  init_logging();
310  LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
311  break;
312  } else if (strcmp(long_options[option_index].name, "restart") == 0) {
313  FREE(layout_path);
314  layout_path = sstrdup(optarg);
315  delete_layout_path = true;
316  break;
317  } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
318  strcmp(long_options[option_index].name, "fake_outputs") == 0) {
319  LOG("Initializing fake outputs: %s\n", optarg);
320  fake_outputs = sstrdup(optarg);
321  break;
322  } else if (strcmp(long_options[option_index].name, "force-old-config-parser-v4.4-only") == 0) {
323  ELOG("You are passing --force-old-config-parser-v4.4-only, but that flag was removed by now.\n");
324  break;
325  }
326  /* fall-through */
327  default:
328  fprintf(stderr, "Usage: %s [-c configfile] [-d all] [-a] [-v] [-V] [-C]\n", argv[0]);
329  fprintf(stderr, "\n");
330  fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
331  fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
332  fprintf(stderr, "\t-C validate configuration file and exit\n");
333  fprintf(stderr, "\t-d all enable debug output\n");
334  fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
335  fprintf(stderr, "\t-v display version and exit\n");
336  fprintf(stderr, "\t-V enable verbose mode\n");
337  fprintf(stderr, "\n");
338  fprintf(stderr, "\t--force-xinerama\n"
339  "\tUse Xinerama instead of RandR.\n"
340  "\tThis option should only be used if you are stuck with the\n"
341  "\told nVidia closed source driver (older than 302.17), which does\n"
342  "\tnot support RandR.\n");
343  fprintf(stderr, "\n");
344  fprintf(stderr, "\t--get-socketpath\n"
345  "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
346  fprintf(stderr, "\n");
347  fprintf(stderr, "\t--shmlog-size <limit>\n"
348  "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
349  "\tto 0 disables SHM logging entirely.\n"
350  "\tThe default is %d bytes.\n",
351  shmlog_size);
352  fprintf(stderr, "\n");
353  fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
354  "to send to a currently running i3 (like i3-msg). This allows you to\n"
355  "use nice and logical commands, such as:\n"
356  "\n"
357  "\ti3 border none\n"
358  "\ti3 floating toggle\n"
359  "\ti3 kill window\n"
360  "\n");
361  exit(EXIT_FAILURE);
362  }
363  }
364 
365  if (only_check_config) {
366  exit(parse_configuration(override_configpath, false) ? 0 : 1);
367  }
368 
369  /* If the user passes more arguments, we act like i3-msg would: Just send
370  * the arguments as an IPC message to i3. This allows for nice semantic
371  * commands such as 'i3 border none'. */
372  if (optind < argc) {
373  /* We enable verbose mode so that the user knows what’s going on.
374  * This should make it easier to find mistakes when the user passes
375  * arguments by mistake. */
376  set_verbosity(true);
377 
378  LOG("Additional arguments passed. Sending them as a command to i3.\n");
379  char *payload = NULL;
380  while (optind < argc) {
381  if (!payload) {
382  payload = sstrdup(argv[optind]);
383  } else {
384  char *both;
385  sasprintf(&both, "%s %s", payload, argv[optind]);
386  free(payload);
387  payload = both;
388  }
389  optind++;
390  }
391  DLOG("Command is: %s (%zd bytes)\n", payload, strlen(payload));
392  char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
393  if (!socket_path) {
394  ELOG("Could not get i3 IPC socket path\n");
395  return 1;
396  }
397 
398  int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
399  if (sockfd == -1)
400  err(EXIT_FAILURE, "Could not create socket");
401 
402  struct sockaddr_un addr;
403  memset(&addr, 0, sizeof(struct sockaddr_un));
404  addr.sun_family = AF_LOCAL;
405  strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
406  if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
407  err(EXIT_FAILURE, "Could not connect to i3");
408 
409  if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
410  (uint8_t *)payload) == -1)
411  err(EXIT_FAILURE, "IPC: write()");
412 
413  uint32_t reply_length;
414  uint32_t reply_type;
415  uint8_t *reply;
416  int ret;
417  if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
418  if (ret == -1)
419  err(EXIT_FAILURE, "IPC: read()");
420  return 1;
421  }
422  if (reply_type != I3_IPC_MESSAGE_TYPE_COMMAND)
423  errx(EXIT_FAILURE, "IPC: received reply of type %d but expected %d (COMMAND)", reply_type, I3_IPC_MESSAGE_TYPE_COMMAND);
424  printf("%.*s\n", reply_length, reply);
425  return 0;
426  }
427 
428  /* Enable logging to handle the case when the user did not specify --shmlog-size */
429  init_logging();
430 
431  /* Try to enable core dumps by default when running a debug build */
432  if (is_debug_build()) {
433  struct rlimit limit = {RLIM_INFINITY, RLIM_INFINITY};
434  setrlimit(RLIMIT_CORE, &limit);
435 
436  /* The following code is helpful, but not required. We thus don’t pay
437  * much attention to error handling, non-linux or other edge cases. */
438  LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
439  size_t cwd_size = 1024;
440  char *cwd = smalloc(cwd_size);
441  char *cwd_ret;
442  while ((cwd_ret = getcwd(cwd, cwd_size)) == NULL && errno == ERANGE) {
443  cwd_size = cwd_size * 2;
444  cwd = srealloc(cwd, cwd_size);
445  }
446  if (cwd_ret != NULL)
447  LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
448  int patternfd;
449  if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
450  memset(cwd, '\0', cwd_size);
451  if (read(patternfd, cwd, cwd_size) > 0)
452  /* a trailing newline is included in cwd */
453  LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
454  close(patternfd);
455  }
456  free(cwd);
457  }
458 
459  LOG("i3 " I3_VERSION " starting\n");
460 
461  conn = xcb_connect(NULL, &conn_screen);
462  if (xcb_connection_has_error(conn))
463  errx(EXIT_FAILURE, "Cannot open display\n");
464 
465  sndisplay = sn_xcb_display_new(conn, NULL, NULL);
466 
467  /* Initialize the libev event loop. This needs to be done before loading
468  * the config file because the parser will install an ev_child watcher
469  * for the nagbar when config errors are found. */
470  main_loop = EV_DEFAULT;
471  if (main_loop == NULL)
472  die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
473 
474  root_screen = xcb_aux_get_screen(conn, conn_screen);
475  root = root_screen->root;
476 
477  /* By default, we use the same depth and visual as the root window, which
478  * usually is TrueColor (24 bit depth) and the corresponding visual.
479  * However, we also check if a 32 bit depth and visual are available (for
480  * transparency) and use it if so. */
481  root_depth = root_screen->root_depth;
482  visual_id = root_screen->root_visual;
483  colormap = root_screen->default_colormap;
484 
485  DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
486  DLOG("root_screen->height_in_pixels = %d, root_screen->height_in_millimeters = %d, dpi = %d\n",
487  root_screen->height_in_pixels, root_screen->height_in_millimeters,
488  (int)((double)root_screen->height_in_pixels * 25.4 / (double)root_screen->height_in_millimeters));
489  DLOG("One logical pixel corresponds to %d physical pixels on this display.\n", logical_px(1));
490 
491  xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
492  xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
493 
494  load_configuration(conn, override_configpath, false);
495 
496  if (config.ipc_socket_path == NULL) {
497  /* Fall back to a file name in /tmp/ based on the PID */
498  if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
500  else
502  }
503 
504  xcb_void_cookie_t cookie;
505  cookie = xcb_change_window_attributes_checked(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ROOT_EVENT_MASK});
506  check_error(conn, cookie, "Another window manager seems to be running");
507 
508  xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
509  if (greply == NULL) {
510  ELOG("Could not get geometry of the root window, exiting\n");
511  return 1;
512  }
513  DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
514 
515 /* Place requests for the atoms we need as soon as possible */
516 #define xmacro(atom) \
517  xcb_intern_atom_cookie_t atom##_cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
518 #include "atoms.xmacro"
519 #undef xmacro
520 
522 
523  /* Set a cursor for the root window (otherwise the root window will show no
524  cursor until the first client is launched). */
525  if (xcursor_supported)
527  else
529 
530  const xcb_query_extension_reply_t *extreply;
531  extreply = xcb_get_extension_data(conn, &xcb_xkb_id);
532  if (!extreply->present) {
533  DLOG("xkb is not present on this server\n");
534  } else {
535  DLOG("initializing xcb-xkb\n");
536  xcb_xkb_use_extension(conn, XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);
537  xcb_xkb_select_events(conn,
538  XCB_XKB_ID_USE_CORE_KBD,
539  XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
540  0,
541  XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
542  0xff,
543  0xff,
544  NULL);
545  xkb_base = extreply->first_event;
546  }
547 
548  restore_connect();
549 
550 /* Setup NetWM atoms */
551 #define xmacro(name) \
552  do { \
553  xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
554  if (!reply) { \
555  ELOG("Could not get atom " #name "\n"); \
556  exit(-1); \
557  } \
558  A_##name = reply->atom; \
559  free(reply); \
560  } while (0);
561 #include "atoms.xmacro"
562 #undef xmacro
563 
565 
567 
568  keysyms = xcb_key_symbols_alloc(conn);
569 
571 
573  grab_all_keys(conn, false);
574 
575  bool needs_tree_init = true;
576  if (layout_path) {
577  LOG("Trying to restore the layout from %s...", layout_path);
578  needs_tree_init = !tree_restore(layout_path, greply);
579  if (delete_layout_path) {
580  unlink(layout_path);
581  const char *dir = dirname(layout_path);
582  /* possibly fails with ENOTEMPTY if there are files (or
583  * sockets) left. */
584  rmdir(dir);
585  }
586  free(layout_path);
587  }
588  if (needs_tree_init)
589  tree_init(greply);
590 
591  free(greply);
592 
593  /* Setup fake outputs for testing */
594  if (fake_outputs == NULL && config.fake_outputs != NULL)
595  fake_outputs = config.fake_outputs;
596 
597  if (fake_outputs != NULL) {
598  fake_outputs_init(fake_outputs);
599  FREE(fake_outputs);
600  config.fake_outputs = NULL;
601  } else if (force_xinerama || config.force_xinerama) {
602  /* Force Xinerama (for drivers which don't support RandR yet, esp. the
603  * nVidia binary graphics driver), when specified either in the config
604  * file or on command-line */
605  xinerama_init();
606  } else {
607  DLOG("Checking for XRandR...\n");
609  }
610 
612 
613  xcb_query_pointer_reply_t *pointerreply;
614  Output *output = NULL;
615  if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
616  ELOG("Could not query pointer position, using first screen\n");
617  } else {
618  DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
619  output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
620  if (!output) {
621  ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
622  pointerreply->root_x, pointerreply->root_y);
623  output = get_first_output();
624  }
625 
627  }
628 
629  tree_render();
630 
631  /* Create the UNIX domain socket for IPC */
632  int ipc_socket = ipc_create_socket(config.ipc_socket_path);
633  if (ipc_socket == -1) {
634  ELOG("Could not create the IPC socket, IPC disabled\n");
635  } else {
636  struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
637  ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
638  ev_io_start(main_loop, ipc_io);
639  }
640 
641  /* Also handle the UNIX domain sockets passed via socket activation. The
642  * parameter 1 means "remove the environment variables", we don’t want to
643  * pass these to child processes. */
645  if (listen_fds < 0)
646  ELOG("socket activation: Error in sd_listen_fds\n");
647  else if (listen_fds == 0)
648  DLOG("socket activation: no sockets passed\n");
649  else {
650  int flags;
651  for (int fd = SD_LISTEN_FDS_START;
653  fd++) {
654  DLOG("socket activation: also listening on fd %d\n", fd);
655 
656  /* sd_listen_fds() enables FD_CLOEXEC by default.
657  * However, we need to keep the file descriptors open for in-place
658  * restarting, therefore we explicitly disable FD_CLOEXEC. */
659  if ((flags = fcntl(fd, F_GETFD)) < 0 ||
660  fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
661  ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
662  }
663 
664  struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
665  ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
666  ev_io_start(main_loop, ipc_io);
667  }
668  }
669 
670  /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
671  x_set_i3_atoms();
673 
674  /* Set the ewmh desktop properties. */
679 
680  struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
681  xcb_check = scalloc(sizeof(struct ev_check));
682  struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
683 
684  ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
685  ev_io_start(main_loop, xcb_watcher);
686 
687  ev_check_init(xcb_check, xcb_check_cb);
688  ev_check_start(main_loop, xcb_check);
689 
690  ev_prepare_init(xcb_prepare, xcb_prepare_cb);
691  ev_prepare_start(main_loop, xcb_prepare);
692 
693  xcb_flush(conn);
694 
695  /* What follows is a fugly consequence of X11 protocol race conditions like
696  * the following: In an i3 in-place restart, i3 will reparent all windows
697  * to the root window, then exec() itself. In the new process, it calls
698  * manage_existing_windows. However, in case any application sent a
699  * generated UnmapNotify message to the WM (as GIMP does), this message
700  * will be handled by i3 *after* managing the window, thus i3 thinks the
701  * window just closed itself. In reality, the message was sent in the time
702  * period where i3 wasn’t running yet.
703  *
704  * To prevent this, we grab the server (disables processing of any other
705  * connections), then discard all pending events (since we didn’t do
706  * anything, there cannot be any meaningful responses), then ungrab the
707  * server. */
708  xcb_grab_server(conn);
709  {
710  xcb_aux_sync(conn);
711  xcb_generic_event_t *event;
712  while ((event = xcb_poll_for_event(conn)) != NULL) {
713  if (event->response_type == 0) {
714  free(event);
715  continue;
716  }
717 
718  /* Strip off the highest bit (set if the event is generated) */
719  int type = (event->response_type & 0x7F);
720 
721  /* We still need to handle MapRequests which are sent in the
722  * timespan starting from when we register as a window manager and
723  * this piece of code which drops events. */
724  if (type == XCB_MAP_REQUEST)
725  handle_event(type, event);
726 
727  free(event);
728  }
730  }
731  xcb_ungrab_server(conn);
732 
733  if (autostart) {
734  LOG("This is not an in-place restart, copying root window contents to a pixmap\n");
735  xcb_screen_t *root = xcb_aux_get_screen(conn, conn_screen);
736  uint16_t width = root->width_in_pixels;
737  uint16_t height = root->height_in_pixels;
738  xcb_pixmap_t pixmap = xcb_generate_id(conn);
739  xcb_gcontext_t gc = xcb_generate_id(conn);
740 
741  xcb_create_pixmap(conn, root->root_depth, pixmap, root->root, width, height);
742 
743  xcb_create_gc(conn, gc, root->root,
744  XCB_GC_FUNCTION | XCB_GC_PLANE_MASK | XCB_GC_FILL_STYLE | XCB_GC_SUBWINDOW_MODE,
745  (uint32_t[]){XCB_GX_COPY, ~0, XCB_FILL_STYLE_SOLID, XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS});
746 
747  xcb_copy_area(conn, root->root, pixmap, gc, 0, 0, 0, 0, width, height);
748  xcb_change_window_attributes_checked(conn, root->root, XCB_CW_BACK_PIXMAP, (uint32_t[]){pixmap});
749  xcb_flush(conn);
750  xcb_free_gc(conn, gc);
751  xcb_free_pixmap(conn, pixmap);
752  }
753 
754  struct sigaction action;
755 
756  action.sa_sigaction = handle_signal;
757  action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
758  sigemptyset(&action.sa_mask);
759 
760  if (!disable_signalhandler)
762  else {
763  /* Catch all signals with default action "Core", see signal(7) */
764  if (sigaction(SIGQUIT, &action, NULL) == -1 ||
765  sigaction(SIGILL, &action, NULL) == -1 ||
766  sigaction(SIGABRT, &action, NULL) == -1 ||
767  sigaction(SIGFPE, &action, NULL) == -1 ||
768  sigaction(SIGSEGV, &action, NULL) == -1)
769  ELOG("Could not setup signal handler");
770  }
771 
772  /* Catch all signals with default action "Term", see signal(7) */
773  if (sigaction(SIGHUP, &action, NULL) == -1 ||
774  sigaction(SIGINT, &action, NULL) == -1 ||
775  sigaction(SIGALRM, &action, NULL) == -1 ||
776  sigaction(SIGUSR1, &action, NULL) == -1 ||
777  sigaction(SIGUSR2, &action, NULL) == -1)
778  ELOG("Could not setup signal handler");
779 
780  /* Ignore SIGPIPE to survive errors when an IPC client disconnects
781  * while we are sending them a message */
782  signal(SIGPIPE, SIG_IGN);
783 
784  /* Autostarting exec-lines */
785  if (autostart) {
786  struct Autostart *exec;
788  LOG("auto-starting %s\n", exec->command);
790  }
791  }
792 
793  /* Autostarting exec_always-lines */
794  struct Autostart *exec_always;
796  LOG("auto-starting (always!) %s\n", exec_always->command);
797  start_application(exec_always->command, exec_always->no_startup_id);
798  }
799 
800  /* Start i3bar processes for all configured bars */
801  Barconfig *barconfig;
802  TAILQ_FOREACH(barconfig, &barconfigs, configs) {
803  char *command = NULL;
804  sasprintf(&command, "%s --bar_id=%s --socket=\"%s\"",
805  barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
806  barconfig->id, current_socketpath);
807  LOG("Starting bar process: %s\n", command);
808  start_application(command, true);
809  free(command);
810  }
811 
812  /* Make sure to destroy the event loop to invoke the cleeanup callbacks
813  * when calling exit() */
814  atexit(i3_exit);
815 
816  ev_loop(main_loop, 0);
817 }
#define SD_LISTEN_FDS_START
Definition: sd-daemon.h:102
struct reservedpx __attribute__
bool is_debug_build() __attribute__((const ))
Returns true if this version of i3 is a debug build (anything which is not a release version)...
int logical_px(const int logical)
Convert a logical amount of pixels (e.g.
char * sstrdup(const char *str)
Safe-wrapper around strdup which exits if malloc returns NULL (meaning that there is no more memory a...
int sd_listen_fds(int unset_environment)
Definition: sd-daemon.c:47
#define XCB_NUM_LOCK
Definition: xcb.h:27
void tree_render(void)
Renders the tree, that is rendering all outputs using render_con() and pushing the changes to X11 usi...
Definition: tree.c:516
void ewmh_update_number_of_desktops(void)
Updates _NET_NUMBER_OF_DESKTOPS which we interpret as the number of noninternal workspaces.
Definition: ewmh.c:47
int listen_fds
The number of file descriptors passed via socket activation.
Definition: main.c:33
bool only_check_config
char * get_process_filename(const char *prefix)
Returns the name of a temporary file with the specified prefix.
uint32_t height
Definition: data.h:33
Config config
Definition: config.c:17
#define ROOT_EVENT_MASK
Definition: xcb.h:47
SnDisplay * sndisplay
Definition: main.c:48
xcb_visualid_t visual_id
Definition: main.c:62
char ** start_argv
Definition: main.c:41
#define LOG(fmt,...)
Definition: libi3.h:76
void load_configuration(xcb_connection_t *conn, const char *override_configpath, bool reload)
Reads the configuration from ~/.i3/config or /etc/i3/config if not found.
Definition: config.c:134
void xinerama_init(void)
We have just established a connection to the X server and need the initial Xinerama information to se...
Definition: xinerama.c:95
void translate_keysyms(void)
Translates keysymbols to keycodes for all bindings which use keysyms.
Definition: bindings.c:246
void ewmh_update_desktop_names(void)
Updates _NET_DESKTOP_NAMES: "The names of all virtual desktops.
Definition: ewmh.c:68
Con * con_descend_focused(Con *con)
Returns the focused con inside this client, descending the tree as far as possible.
Definition: con.c:1029
char * fake_outputs
Overwrites output detection (for testing), see src/fake_outputs.c.
Definition: config.h:155
xcb_screen_t * root_screen
Definition: main.c:55
void ewmh_update_desktop_viewport(void)
Updates _NET_DESKTOP_VIEWPORT, which is an array of pairs of cardinals that define the top left corne...
Definition: ewmh.c:106
bool parse_configuration(const char *override_configpath, bool use_nagbar)
Finds the configuration file to use (either the one specified by override_configpath), the user’s one or the system default) and calls parse_file().
Definition: config.c:115
static void xcb_got_event(EV_P_ struct ev_io *w, int revents)
Definition: main.c:96
struct ev_loop * main_loop
Definition: main.c:65
uint32_t width
Definition: data.h:32
xcb_timestamp_t last_timestamp
The last timestamp we got from X11 (timestamps are included in some events and are used for some thin...
Definition: main.c:53
char * shmlogname
Definition: log.c:44
An Output is a physical output on your graphics driver.
Definition: data.h:313
int ipc_recv_message(int sockfd, uint32_t *message_type, uint32_t *reply_length, uint8_t **reply)
Reads a message from the given socket file descriptor and stores its length (reply_length) as well as...
void grab_all_keys(xcb_connection_t *conn, bool bind_mode_switch)
Grab the bound keys (tell X to send us keypress events for those keycodes)
Definition: bindings.c:108
void display_running_version(void)
Connects to i3 to find out the currently running version.
bool xcursor_supported
Definition: main.c:89
void set_verbosity(bool _verbose)
Set verbosity of i3.
Definition: log.c:185
static void handle_signal(int sig, siginfo_t *info, void *data)
Definition: main.c:181
#define DLOG(fmt,...)
Definition: libi3.h:86
void manage_existing_windows(xcb_window_t root)
Go through all existing windows (if the window manager is restarted) and manage them.
Definition: manage.c:21
char * root_atom_contents(const char *atomname, xcb_connection_t *provided_conn, int screen)
Try to get the contents of the given atom (for example I3_SOCKET_PATH) from the X11 root window and r...
static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents)
Definition: main.c:104
static xcb_pixmap_t pixmap
Definition: sighandler.c:28
xcb_colormap_t colormap
Definition: main.c:63
int sasprintf(char **strp, const char *fmt,...)
Safe-wrapper around asprintf which exits if it returns -1 (meaning that there is no more memory avail...
int ipc_create_socket(const char *filename)
Creates the UNIX domain socket at the given path, sets it to non-blocking mode, bind()s and listen()s...
Definition: ipc.c:1056
uint8_t root_depth
Definition: main.c:61
bool tree_restore(const char *path, xcb_get_geometry_reply_t *geometry)
Loads tree from ~/.i3/_restart.json (used for in-place restarts).
Definition: tree.c:68
#define die(...)
Definition: util.h:17
int shmlog_size
Definition: log.c:47
Con * focused
Definition: tree.c:15
Con * con
Pointer to the Con which represents this output.
Definition: data.h:331
void ewmh_update_workarea(void)
i3 currently does not support _NET_WORKAREA, because it does not correspond to i3’s concept of works...
Definition: ewmh.c:166
char * id
Automatically generated ID for this bar config.
Definition: config.h:226
void main_set_x11_cb(bool enable)
Enable or disable the main X11 event handling function.
Definition: main.c:144
bool event_is_ignored(const int sequence, const int response_type)
Checks if the given sequence is ignored and returns true if so.
Definition: handlers.c:54
int randr_base
Definition: handlers.c:23
void ewmh_update_current_desktop(void)
Updates _NET_CURRENT_DESKTOP with the current desktop number.
Definition: ewmh.c:21
struct autostarts_head autostarts
Definition: main.c:76
char * ipc_socket_path
Definition: config.h:94
bool no_startup_id
no_startup_id flag for start_application().
Definition: data.h:301
void con_focus(Con *con)
Sets input focus to the given container.
Definition: con.c:193
void xcursor_set_root_cursor(int cursor_id)
Sets the cursor of the root window to the 'pointer' cursor.
Definition: xcursor.c:57
void setup_signal_handler(void)
Setup signal handlers to safely handle SIGSEGV and SIGFPE.
Definition: sighandler.c:317
int ipc_send_message(int sockfd, const uint32_t message_size, const uint32_t message_type, const uint8_t *payload)
Formats a message (payload) of the given size and type and sends it to i3 via the given socket file d...
Output * get_first_output(void)
Returns the first output which is active.
Definition: randr.c:65
static void i3_exit(void)
Definition: main.c:160
struct assignments_head assignments
Definition: main.c:82
void fake_outputs_init(const char *output_spec)
Creates outputs according to the given specification.
Definition: fake_outputs.c:37
const int default_shmlog_size
Definition: main.c:70
void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message)
Checks a generic cookie for errors and quits with the given message if there was an error...
Definition: util.c:153
char * i3bar_command
Command that should be run to execute i3bar, give a full path if i3bar is not in your $PATH...
Definition: config.h:279
void ewmh_setup_hints(void)
Set up the EWMH hints on the root window.
Definition: ewmh.c:206
void xcursor_load_cursors(void)
Definition: xcursor.c:28
#define ELOG(fmt,...)
Definition: libi3.h:81
void randr_init(int *event_base)
We have just established a connection to the X server and need the initial XRandR information to setu...
Definition: randr.c:822
unsigned int xcb_numlock_mask
Definition: xcb.c:14
int xkb_base
Definition: handlers.c:24
A 'Con' represents everything from the X11 root window down to a single X11 window.
Definition: data.h:496
void xcb_set_root_cursor(int cursor)
Set the cursor of the root window to the given cursor id.
Definition: xcb.c:194
void * scalloc(size_t size)
Safe-wrapper around calloc which exits if malloc returns NULL (meaning that there is no more memory a...
struct bindings_head * bindings
Definition: main.c:73
char * current_socketpath
Definition: ipc.c:23
uint32_t aio_get_mod_mask_for(uint32_t keysym, xcb_key_symbols_t *symbols)
All-in-one function which returns the modifier mask (XCB_MOD_MASK_*) for the given keysymbol...
void scratchpad_fix_resolution(void)
When starting i3 initially (and after each change to the connected outputs), this function fixes the ...
Definition: scratchpad.c:251
bool force_xinerama
By default, use the RandR API for multi-monitor setups.
Definition: config.h:152
Output * get_output_containing(unsigned int x, unsigned int y)
Returns the active (!) output which contains the coordinates x, y or NULL if there is no output which...
Definition: randr.c:80
xcb_window_t root
Definition: main.c:56
void tree_init(xcb_get_geometry_reply_t *geometry)
Initializes the tree by creating the root node, adding all RandR outputs to the tree (that means rand...
Definition: tree.c:117
#define TAILQ_HEAD_INITIALIZER(head)
Definition: queue.h:324
char * command
Command, like in command mode.
Definition: data.h:298
static void xcb_check_cb(EV_P_ ev_check *w, int revents)
Definition: main.c:113
void ipc_new_client(EV_P_ struct ev_io *w, int revents)
Handler for activity on the listening socket, meaning that a new client has just connected and we sho...
Definition: ipc.c:1022
struct barconfig_head barconfigs
Definition: config.c:19
void init_logging(void)
Initializes logging by creating an error logfile in /tmp (or XDG_RUNTIME_DIR, see get_process_filenam...
Definition: log.c:81
int main(int argc, char *argv[])
Definition: main.c:188
Con * output_get_content(Con *output)
Returns the output container below the given output container.
Definition: output.c:18
void start_application(const char *command, bool no_startup_id)
Starts the given application by passing it through a shell.
Definition: startup.c:133
void * smalloc(size_t size)
Safe-wrapper around malloc which exits if malloc returns NULL (meaning that there is no more memory a...
void x_set_i3_atoms(void)
Sets up i3 specific atoms (I3_SOCKET_PATH and I3_CONFIG_PATH)
Definition: x.c:1127
xcb_key_symbols_t * keysyms
Definition: main.c:67
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:347
void restore_connect(void)
Opens a separate connection to X11 for placeholder windows when restoring layouts.
static struct ev_check * xcb_check
Definition: main.c:37
void * srealloc(void *ptr, size_t size)
Safe-wrapper around realloc which exits if realloc returns NULL (meaning that there is no more memory...
Holds the status bar configuration (i3bar).
Definition: config.h:223
xcb_connection_t * conn
Definition: main.c:43
struct rlimit original_rlimit_core
The original value of RLIMIT_CORE when i3 was started.
Definition: main.c:30
#define FREE(pointer)
Definition: util.h:48
struct autostarts_always_head autostarts_always
Definition: main.c:79
void property_handlers_init(void)
Sets the appropriate atoms for the property handlers after the atoms were received from X11...
Definition: handlers.c:1274
Holds a command specified by either an:
Definition: data.h:296
struct ws_assignments_head ws_assignments
Definition: main.c:86
void set_debug_logging(const bool _debug_logging)
Set debug logging.
Definition: log.c:201
void handle_event(int type, xcb_generic_event_t *event)
Takes an xcb_generic_event_t and calls the appropriate handler, based on the event type...
Definition: handlers.c:1320
int conn_screen
Definition: main.c:45