4 * i3 - an improved dynamic tiling window manager
6 * © 2009 Michael Stapelberg and contributors
8 * See file LICENSE for license information.
10 * util.c: Utility functions, which can be useful everywhere.
22 #include <xcb/xcb_icccm.h>
32 static iconv_t conversion_descriptor = 0;
33 struct keyvalue_table_head by_parent = TAILQ_HEAD_INITIALIZER(by_parent);
34 struct keyvalue_table_head by_child = TAILQ_HEAD_INITIALIZER(by_child);
36 int min(int a, int b) {
37 return (a < b ? a : b);
40 int max(int a, int b) {
41 return (a > b ? a : b);
45 * Logs the given message to stdout while prefixing the current time to it.
46 * This is to be called by LOG() which includes filename/linenumber
49 void slog(char *fmt, ...) {
54 /* Get current time */
55 time_t t = time(NULL);
56 /* Convert time to local time (determined by the locale) */
57 struct tm *tmp = localtime(&t);
58 /* Generate time prefix */
59 strftime(timebuf, sizeof(timebuf), "%x %X - ", tmp);
60 printf("%s", timebuf);
66 * Prints the message (see printf()) to stderr, then exits the program.
69 void die(char *fmt, ...) {
73 vfprintf(stderr, fmt, args);
80 * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
81 * the called functions returns NULL, meaning that there is no more memory available
84 void *smalloc(size_t size) {
85 void *result = malloc(size);
86 exit_if_null(result, "Too less memory for malloc(%d)\n", size);
90 void *scalloc(size_t size) {
91 void *result = calloc(size, 1);
92 exit_if_null(result, "Too less memory for calloc(%d)\n", size);
96 char *sstrdup(const char *str) {
97 char *result = strdup(str);
98 exit_if_null(result, "Too less memory for strdup()\n");
103 * The table_* functions emulate the behaviour of libxcb-wm, which in libxcb 0.3.4 suddenly
107 bool table_put(struct keyvalue_table_head *head, uint32_t key, void *value) {
108 struct keyvalue_element *element = scalloc(sizeof(struct keyvalue_element));
110 element->value = value;
112 TAILQ_INSERT_TAIL(head, element, elements);
116 void *table_remove(struct keyvalue_table_head *head, uint32_t key) {
117 struct keyvalue_element *element;
119 TAILQ_FOREACH(element, head, elements)
120 if (element->key == key) {
121 void *value = element->value;
122 TAILQ_REMOVE(head, element, elements);
130 void *table_get(struct keyvalue_table_head *head, uint32_t key) {
131 struct keyvalue_element *element;
133 TAILQ_FOREACH(element, head, elements)
134 if (element->key == key)
135 return element->value;
141 * Starts the given application by passing it through a shell. We use double fork
142 * to avoid zombie processes. As the started application’s parent exits (immediately),
143 * the application is reparented to init (process-id 1), which correctly handles
144 * childs, so we don’t have to do it :-).
146 * The shell is determined by looking for the SHELL environment variable. If it
147 * does not exist, /bin/sh is used.
150 void start_application(const char *command) {
154 /* Stores the path of the shell */
155 static const char *shell = NULL;
158 if ((shell = getenv("SHELL")) == NULL)
161 /* This is the child */
162 execl(shell, shell, "-c", command, NULL);
171 * Checks a generic cookie for errors and quits with the given message if there
175 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
176 xcb_generic_error_t *error = xcb_request_check(conn, cookie);
178 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
179 xcb_disconnect(conn);
185 * Converts the given string to UCS-2 big endian for use with
186 * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
187 * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
188 * returned. It has to be freed when done.
191 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
192 size_t input_size = strlen(input) + 1;
193 /* UCS-2 consumes exactly two bytes for each glyph */
194 int buffer_size = input_size * 2;
196 char *buffer = smalloc(buffer_size);
197 size_t output_size = buffer_size;
198 /* We need to use an additional pointer, because iconv() modifies it */
199 char *output = buffer;
201 /* We convert the input into UCS-2 big endian */
202 if (conversion_descriptor == 0) {
203 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
204 if (conversion_descriptor == 0) {
205 fprintf(stderr, "error opening the conversion context\n");
210 /* Get the conversion descriptor back to original state */
211 iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
213 /* Convert our text */
214 int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
215 if (rc == (size_t)-1) {
216 perror("Converting to UCS-2 failed");
217 if (real_strlen != NULL)
222 if (real_strlen != NULL)
223 *real_strlen = ((buffer_size - output_size) / 2) - 1;
229 * Returns the client which comes next in focus stack (= was selected before) for
230 * the given container, optionally excluding the given client.
233 Client *get_last_focused_client(xcb_connection_t *conn, Container *container, Client *exclude) {
235 SLIST_FOREACH(current, &(container->workspace->focus_stack), focus_clients)
236 if ((current->container == container) && ((exclude == NULL) || (current != exclude)))
242 * Unmaps all clients (and stack windows) of the given workspace.
244 * This needs to be called separately when temporarily rendering
245 * a workspace which is not the active workspace to force
246 * reconfiguration of all clients, like in src/xinerama.c when
247 * re-assigning a workspace to another screen.
250 void unmap_workspace(xcb_connection_t *conn, Workspace *u_ws) {
252 struct Stack_Window *stack_win;
254 /* Ignore notify events because they would cause focus to be changed */
255 ignore_enter_notify_forall(conn, u_ws, true);
257 /* Unmap all clients of the current workspace */
258 int unmapped_clients = 0;
260 CIRCLEQ_FOREACH(client, &(u_ws->table[cols][rows]->clients), clients) {
261 xcb_unmap_window(conn, client->frame);
265 /* If we did not unmap any clients, the workspace is empty and we can destroy it */
266 if (unmapped_clients == 0) {
267 /* Re-assign the workspace of all dock clients which use this workspace */
269 SLIST_FOREACH(dock, &(u_ws->screen->dock_clients), dock_clients) {
270 if (dock->workspace != u_ws)
273 LOG("Re-assigning dock client to c_ws (%p)\n", c_ws);
274 dock->workspace = c_ws;
279 /* Unmap the stack windows on the current workspace, if any */
280 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
281 if (stack_win->container->workspace == u_ws)
282 xcb_unmap_window(conn, stack_win->window);
284 ignore_enter_notify_forall(conn, u_ws, false);
288 * Sets the given client as focused by updating the data structures correctly,
289 * updating the X input focus and finally re-decorating both windows (to signalize
290 * the user the new focus situation)
293 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
294 /* The dock window cannot be focused, but enter notifies are still handled correctly */
298 /* Store the old client */
299 Client *old_client = CUR_CELL->currently_focused;
301 /* Check if the focus needs to be changed at all */
302 if (!set_anyways && (old_client == client)) {
303 LOG("old_client == client, not changing focus\n");
307 /* Store current_row/current_col */
308 c_ws->current_row = current_row;
309 c_ws->current_col = current_col;
310 c_ws = client->container->workspace;
312 /* Update container */
313 client->container->currently_focused = client;
315 current_col = client->container->col;
316 current_row = client->container->row;
318 LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
319 /* Set focus to the entered window, and flush xcb buffer immediately */
320 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
321 //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
323 /* Get the client which was last focused in this particular container, it may be a different
324 one than old_client */
325 Client *last_focused = get_last_focused_client(conn, client->container, NULL);
327 /* In stacking containers, raise the client in respect to the one which was focused before */
328 if (client->container->mode == MODE_STACK && client->container->workspace->fullscreen_client == NULL) {
329 /* We need to get the client again, this time excluding the current client, because
330 * we might have just gone into stacking mode and need to raise */
331 Client *last_focused = get_last_focused_client(conn, client->container, client);
333 if (last_focused != NULL) {
334 LOG("raising above frame %p / child %p\n", last_focused->frame, last_focused->child);
335 uint32_t values[] = { last_focused->frame, XCB_STACK_MODE_ABOVE };
336 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
340 /* If it is the same one as old_client, we save us the unnecessary redecorate */
341 if ((last_focused != NULL) && (last_focused != old_client))
342 redecorate_window(conn, last_focused);
344 /* If we’re in stacking mode, this renders the container to update changes in the title
345 bars and to raise the focused client */
346 if ((old_client != NULL) && (old_client != client) && !old_client->dock)
347 redecorate_window(conn, old_client);
349 SLIST_REMOVE(&(client->container->workspace->focus_stack), client, Client, focus_clients);
350 SLIST_INSERT_HEAD(&(client->container->workspace->focus_stack), client, focus_clients);
352 /* redecorate_window flushes, so we don’t need to */
353 redecorate_window(conn, client);
357 * Called when the user switches to another mode or when the container is
358 * destroyed and thus needs to be cleaned up.
361 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
362 /* When going out of stacking mode, we need to close the window */
363 struct Stack_Window *stack_win = &(container->stack_win);
365 SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
367 xcb_free_gc(conn, stack_win->gc);
368 xcb_destroy_window(conn, stack_win->window);
370 stack_win->rect.width = -1;
371 stack_win->rect.height = -1;
375 * Switches the layout of the given container taking care of the necessary house-keeping
378 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
379 if (mode == MODE_STACK) {
380 /* When we’re already in stacking mode, nothing has to be done */
381 if (container->mode == MODE_STACK)
384 /* When entering stacking mode, we need to open a window on which we can draw the
385 title bars of the clients, it has height 1 because we don’t bother here with
386 calculating the correct height - it will be adjusted when rendering anyways. */
387 Rect rect = {container->x, container->y, container->width, 1 };
392 /* Don’t generate events for our new window, it should *not* be managed */
393 mask |= XCB_CW_OVERRIDE_REDIRECT;
396 /* We want to know when… */
397 mask |= XCB_CW_EVENT_MASK;
398 values[1] = XCB_EVENT_MASK_ENTER_WINDOW | /* …mouse is moved into our window */
399 XCB_EVENT_MASK_BUTTON_PRESS | /* …mouse is pressed */
400 XCB_EVENT_MASK_EXPOSURE; /* …our window needs to be redrawn */
402 struct Stack_Window *stack_win = &(container->stack_win);
403 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, mask, values);
405 /* Generate a graphics context for the titlebar */
406 stack_win->gc = xcb_generate_id(conn);
407 xcb_create_gc(conn, stack_win->gc, stack_win->window, 0, 0);
409 stack_win->container = container;
411 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
413 if (container->mode == MODE_STACK)
414 leave_stack_mode(conn, container);
416 container->mode = mode;
418 /* Force reconfiguration of each client */
421 CIRCLEQ_FOREACH(client, &(container->clients), clients)
422 client->force_reconfigure = true;
426 if (container->currently_focused != NULL)
427 set_focus(conn, container->currently_focused, true);
431 * Toggles fullscreen mode for the given client. It updates the data structures and
432 * reconfigures (= resizes/moves) the client and its frame to the full size of the
433 * screen. When leaving fullscreen, re-rendering the layout is forced.
436 void toggle_fullscreen(xcb_connection_t *conn, Client *client) {
437 /* clients without a container (docks) cannot be focused */
438 assert(client->container != NULL);
440 Workspace *workspace = client->container->workspace;
442 if (!client->fullscreen) {
443 if (workspace->fullscreen_client != NULL) {
444 LOG("Not entering fullscreen mode, there already is a fullscreen client.\n");
447 client->fullscreen = true;
448 workspace->fullscreen_client = client;
449 LOG("Entering fullscreen mode...\n");
450 /* We just entered fullscreen mode, let’s configure the window */
451 uint32_t mask = XCB_CONFIG_WINDOW_X |
452 XCB_CONFIG_WINDOW_Y |
453 XCB_CONFIG_WINDOW_WIDTH |
454 XCB_CONFIG_WINDOW_HEIGHT;
455 uint32_t values[4] = {workspace->rect.x,
457 workspace->rect.width,
458 workspace->rect.height};
460 LOG("child itself will be at %dx%d with size %dx%d\n",
461 values[0], values[1], values[2], values[3]);
463 xcb_configure_window(conn, client->frame, mask, values);
465 /* Child’s coordinates are relative to the parent (=frame) */
468 xcb_configure_window(conn, client->child, mask, values);
470 /* Raise the window */
471 values[0] = XCB_STACK_MODE_ABOVE;
472 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_STACK_MODE, values);
474 Rect child_rect = workspace->rect;
475 child_rect.x = child_rect.y = 0;
476 fake_configure_notify(conn, child_rect, client->child);
478 LOG("leaving fullscreen mode\n");
479 client->fullscreen = false;
480 workspace->fullscreen_client = NULL;
481 /* Because the coordinates of the window haven’t changed, it would not be
482 re-configured if we don’t set the following flag */
483 client->force_reconfigure = true;
484 /* We left fullscreen mode, redraw the whole layout to ensure enternotify events are disabled */
492 * Gets the first matching client for the given window class/window title.
493 * If the paramater specific is set to a specific client, only this one
497 Client *get_matching_client(xcb_connection_t *conn, const char *window_classtitle,
499 char *to_class, *to_title, *to_title_ucs = NULL;
500 int to_title_ucs_len;
501 Client *matching = NULL;
503 to_class = sstrdup(window_classtitle);
505 /* If a title was specified, split both strings at the slash */
506 if ((to_title = strstr(to_class, "/")) != NULL) {
507 *(to_title++) = '\0';
508 /* Convert to UCS-2 */
509 to_title_ucs = convert_utf8_to_ucs2(to_title, &to_title_ucs_len);
512 /* If we were given a specific client we only check if that one matches */
513 if (specific != NULL) {
514 if (client_matches_class_name(specific, to_class, to_title, to_title_ucs, to_title_ucs_len))
519 LOG("Getting clients for class \"%s\" / title \"%s\"\n", to_class, to_title);
520 for (int workspace = 0; workspace < 10; workspace++) {
521 if (workspaces[workspace].screen == NULL)
524 FOR_TABLE(&(workspaces[workspace])) {
525 Container *con = workspaces[workspace].table[cols][rows];
528 CIRCLEQ_FOREACH(client, &(con->clients), clients) {
529 LOG("Checking client with class=%s, name=%s\n", client->window_class, client->name);
530 if (!client_matches_class_name(client, to_class, to_title, to_title_ucs, to_title_ucs_len))