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 * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
67 * the called functions returns NULL, meaning that there is no more memory available
70 void *smalloc(size_t size) {
71 void *result = malloc(size);
72 exit_if_null(result, "Error: out of memory (malloc(%zd))\n", size);
76 void *scalloc(size_t size) {
77 void *result = calloc(size, 1);
78 exit_if_null(result, "Error: out of memory (calloc(%zd))\n", size);
82 char *sstrdup(const char *str) {
83 char *result = strdup(str);
84 exit_if_null(result, "Error: out of memory (strdup())\n");
89 * The table_* functions emulate the behaviour of libxcb-wm, which in libxcb 0.3.4 suddenly
93 bool table_put(struct keyvalue_table_head *head, uint32_t key, void *value) {
94 struct keyvalue_element *element = scalloc(sizeof(struct keyvalue_element));
96 element->value = value;
98 TAILQ_INSERT_TAIL(head, element, elements);
102 void *table_remove(struct keyvalue_table_head *head, uint32_t key) {
103 struct keyvalue_element *element;
105 TAILQ_FOREACH(element, head, elements)
106 if (element->key == key) {
107 void *value = element->value;
108 TAILQ_REMOVE(head, element, elements);
116 void *table_get(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 return element->value;
127 * Starts the given application by passing it through a shell. We use double fork
128 * to avoid zombie processes. As the started application’s parent exits (immediately),
129 * the application is reparented to init (process-id 1), which correctly handles
130 * childs, so we don’t have to do it :-).
132 * The shell is determined by looking for the SHELL environment variable. If it
133 * does not exist, /bin/sh is used.
136 void start_application(const char *command) {
140 /* Stores the path of the shell */
141 static const char *shell = NULL;
144 if ((shell = getenv("SHELL")) == NULL)
147 /* This is the child */
148 execl(shell, shell, "-c", command, NULL);
157 * Checks a generic cookie for errors and quits with the given message if there
161 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
162 xcb_generic_error_t *error = xcb_request_check(conn, cookie);
164 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
165 xcb_disconnect(conn);
171 * Converts the given string to UCS-2 big endian for use with
172 * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
173 * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
174 * returned. It has to be freed when done.
177 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
178 size_t input_size = strlen(input) + 1;
179 /* UCS-2 consumes exactly two bytes for each glyph */
180 int buffer_size = input_size * 2;
182 char *buffer = smalloc(buffer_size);
183 size_t output_size = buffer_size;
184 /* We need to use an additional pointer, because iconv() modifies it */
185 char *output = buffer;
187 /* We convert the input into UCS-2 big endian */
188 if (conversion_descriptor == 0) {
189 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
190 if (conversion_descriptor == 0) {
191 fprintf(stderr, "error opening the conversion context\n");
196 /* Get the conversion descriptor back to original state */
197 iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
199 /* Convert our text */
200 int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
201 if (rc == (size_t)-1) {
202 perror("Converting to UCS-2 failed");
203 if (real_strlen != NULL)
208 if (real_strlen != NULL)
209 *real_strlen = ((buffer_size - output_size) / 2) - 1;
215 * Returns the client which comes next in focus stack (= was selected before) for
216 * the given container, optionally excluding the given client.
219 Client *get_last_focused_client(xcb_connection_t *conn, Container *container, Client *exclude) {
221 SLIST_FOREACH(current, &(container->workspace->focus_stack), focus_clients)
222 if ((current->container == container) && ((exclude == NULL) || (current != exclude)))
228 * Unmaps all clients (and stack windows) of the given workspace.
230 * This needs to be called separately when temporarily rendering
231 * a workspace which is not the active workspace to force
232 * reconfiguration of all clients, like in src/xinerama.c when
233 * re-assigning a workspace to another screen.
236 void unmap_workspace(xcb_connection_t *conn, Workspace *u_ws) {
238 struct Stack_Window *stack_win;
240 /* Ignore notify events because they would cause focus to be changed */
241 ignore_enter_notify_forall(conn, u_ws, true);
243 /* Unmap all clients of the given workspace */
244 int unmapped_clients = 0;
246 CIRCLEQ_FOREACH(client, &(u_ws->table[cols][rows]->clients), clients) {
247 LOG("unmapping normal client %p / %p / %p\n", client, client->frame, client->child);
248 xcb_unmap_window(conn, client->frame);
252 /* To find floating clients, we traverse the focus stack */
253 SLIST_FOREACH(client, &(u_ws->focus_stack), focus_clients) {
254 if (!client_is_floating(client))
257 LOG("unmapping floating client %p / %p / %p\n", client, client->frame, client->child);
259 xcb_unmap_window(conn, client->frame);
263 /* If we did not unmap any clients, the workspace is empty and we can destroy it, at least
264 * if it is not the current workspace. */
265 if (unmapped_clients == 0 && u_ws != c_ws) {
266 /* Re-assign the workspace of all dock clients which use this workspace */
268 LOG("workspace %p is empty\n", u_ws);
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 given 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 = SLIST_FIRST(&(c_ws->focus_stack));
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->workspace;
311 /* Load current_col/current_row if we switch to a client without a container */
312 current_col = c_ws->current_col;
313 current_row = c_ws->current_row;
315 /* Update container */
316 if (client->container != NULL) {
317 client->container->currently_focused = client;
319 current_col = client->container->col;
320 current_row = client->container->row;
323 LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
324 /* Set focus to the entered window, and flush xcb buffer immediately */
325 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
326 //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
328 if (client->container != NULL) {
329 /* Get the client which was last focused in this particular container, it may be a different
330 one than old_client */
331 Client *last_focused = get_last_focused_client(conn, client->container, NULL);
333 /* In stacking containers, raise the client in respect to the one which was focused before */
334 if (client->container->mode == MODE_STACK && client->container->workspace->fullscreen_client == NULL) {
335 /* We need to get the client again, this time excluding the current client, because
336 * we might have just gone into stacking mode and need to raise */
337 Client *last_focused = get_last_focused_client(conn, client->container, client);
339 if (last_focused != NULL) {
340 LOG("raising above frame %p / child %p\n", last_focused->frame, last_focused->child);
341 uint32_t values[] = { last_focused->frame, XCB_STACK_MODE_ABOVE };
342 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
346 /* If it is the same one as old_client, we save us the unnecessary redecorate */
347 if ((last_focused != NULL) && (last_focused != old_client))
348 redecorate_window(conn, last_focused);
351 /* If the last client was a floating client, we need to go to the next
352 * tiling client in stack and re-decorate it. */
353 if (old_client != NULL && client_is_floating(old_client)) {
354 LOG("Coming from floating client, searching next tiling...\n");
356 SLIST_FOREACH(current, &(client->workspace->focus_stack), focus_clients) {
357 if (client_is_floating(current))
360 LOG("Found window: %p / child %p\n", current->frame, current->child);
361 redecorate_window(conn, current);
367 SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
368 SLIST_INSERT_HEAD(&(client->workspace->focus_stack), client, focus_clients);
370 /* If we’re in stacking mode, this renders the container to update changes in the title
371 bars and to raise the focused client */
372 if ((old_client != NULL) && (old_client != client) && !old_client->dock)
373 redecorate_window(conn, old_client);
375 /* redecorate_window flushes, so we don’t need to */
376 redecorate_window(conn, client);
380 * Called when the user switches to another mode or when the container is
381 * destroyed and thus needs to be cleaned up.
384 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
385 /* When going out of stacking mode, we need to close the window */
386 struct Stack_Window *stack_win = &(container->stack_win);
388 SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
390 xcb_free_gc(conn, stack_win->pixmap.gc);
391 xcb_free_pixmap(conn, stack_win->pixmap.id);
392 xcb_destroy_window(conn, stack_win->window);
394 stack_win->rect.width = -1;
395 stack_win->rect.height = -1;
399 * Switches the layout of the given container taking care of the necessary house-keeping
402 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
403 if (mode == MODE_STACK) {
404 /* When we’re already in stacking mode, nothing has to be done */
405 if (container->mode == MODE_STACK)
408 /* When entering stacking mode, we need to open a window on which we can draw the
409 title bars of the clients, it has height 1 because we don’t bother here with
410 calculating the correct height - it will be adjusted when rendering anyways. */
411 Rect rect = {container->x, container->y, container->width, 1};
416 /* Don’t generate events for our new window, it should *not* be managed */
417 mask |= XCB_CW_OVERRIDE_REDIRECT;
420 /* We want to know when… */
421 mask |= XCB_CW_EVENT_MASK;
422 values[1] = XCB_EVENT_MASK_ENTER_WINDOW | /* …mouse is moved into our window */
423 XCB_EVENT_MASK_BUTTON_PRESS | /* …mouse is pressed */
424 XCB_EVENT_MASK_EXPOSURE; /* …our window needs to be redrawn */
426 struct Stack_Window *stack_win = &(container->stack_win);
427 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, false, mask, values);
429 stack_win->rect.height = 0;
431 /* Initialize the entry for our cached pixmap. It will be
432 * created as soon as it’s needed (see cached_pixmap_prepare). */
433 memset(&(stack_win->pixmap), 0, sizeof(struct Cached_Pixmap));
434 stack_win->pixmap.referred_rect = &stack_win->rect;
435 stack_win->pixmap.referred_drawable = stack_win->window;
437 stack_win->container = container;
439 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
441 if (container->mode == MODE_STACK)
442 leave_stack_mode(conn, container);
444 container->mode = mode;
446 /* Force reconfiguration of each client */
449 CIRCLEQ_FOREACH(client, &(container->clients), clients)
450 client->force_reconfigure = true;
454 if (container->currently_focused != NULL) {
455 /* We need to make sure that this client is above *each* of the
456 * other clients in this container */
457 Client *last_focused = get_last_focused_client(conn, container, container->currently_focused);
459 CIRCLEQ_FOREACH(client, &(container->clients), clients) {
460 if (client == container->currently_focused || client == last_focused)
463 LOG("setting %08x below %08x / %08x\n", client->frame, container->currently_focused->frame);
464 uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
465 xcb_configure_window(conn, client->frame,
466 XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
469 if (last_focused != NULL) {
470 LOG("Putting last_focused directly underneath the currently focused\n");
471 uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
472 xcb_configure_window(conn, last_focused->frame,
473 XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
477 set_focus(conn, container->currently_focused, true);
482 * Gets the first matching client for the given window class/window title.
483 * If the paramater specific is set to a specific client, only this one
487 Client *get_matching_client(xcb_connection_t *conn, const char *window_classtitle,
489 char *to_class, *to_title, *to_title_ucs = NULL;
490 int to_title_ucs_len = 0;
491 Client *matching = NULL;
493 to_class = sstrdup(window_classtitle);
495 /* If a title was specified, split both strings at the slash */
496 if ((to_title = strstr(to_class, "/")) != NULL) {
497 *(to_title++) = '\0';
498 /* Convert to UCS-2 */
499 to_title_ucs = convert_utf8_to_ucs2(to_title, &to_title_ucs_len);
502 /* If we were given a specific client we only check if that one matches */
503 if (specific != NULL) {
504 if (client_matches_class_name(specific, to_class, to_title, to_title_ucs, to_title_ucs_len))
509 LOG("Getting clients for class \"%s\" / title \"%s\"\n", to_class, to_title);
510 for (int workspace = 0; workspace < 10; workspace++) {
511 if (workspaces[workspace].screen == NULL)
515 SLIST_FOREACH(client, &(workspaces[workspace].focus_stack), focus_clients) {
516 LOG("Checking client with class=%s, name=%s\n", client->window_class, client->name);
517 if (!client_matches_class_name(client, to_class, to_title, to_title_ucs, to_title_ucs_len))