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)))
229 * Sets the given client as focused by updating the data structures correctly,
230 * updating the X input focus and finally re-decorating both windows (to signalize
231 * the user the new focus situation)
234 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
235 /* The dock window cannot be focused, but enter notifies are still handled correctly */
239 /* Store the old client */
240 Client *old_client = SLIST_FIRST(&(c_ws->focus_stack));
242 /* Check if the focus needs to be changed at all */
243 if (!set_anyways && (old_client == client))
246 /* Store current_row/current_col */
247 c_ws->current_row = current_row;
248 c_ws->current_col = current_col;
249 c_ws = client->workspace;
250 /* Load current_col/current_row if we switch to a client without a container */
251 current_col = c_ws->current_col;
252 current_row = c_ws->current_row;
254 /* Update container */
255 if (client->container != NULL) {
256 client->container->currently_focused = client;
258 current_col = client->container->col;
259 current_row = client->container->row;
263 /* Set focus to the entered window, and flush xcb buffer immediately */
264 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
265 //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
267 if (client->container != NULL) {
268 /* Get the client which was last focused in this particular container, it may be a different
269 one than old_client */
270 Client *last_focused = get_last_focused_client(conn, client->container, NULL);
272 /* In stacking containers, raise the client in respect to the one which was focused before */
273 if (client->container->mode == MODE_STACK && client->container->workspace->fullscreen_client == NULL) {
274 /* We need to get the client again, this time excluding the current client, because
275 * we might have just gone into stacking mode and need to raise */
276 Client *last_focused = get_last_focused_client(conn, client->container, client);
278 if (last_focused != NULL) {
279 LOG("raising above frame %p / child %p\n", last_focused->frame, last_focused->child);
280 uint32_t values[] = { last_focused->frame, XCB_STACK_MODE_ABOVE };
281 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
285 /* If it is the same one as old_client, we save us the unnecessary redecorate */
286 if ((last_focused != NULL) && (last_focused != old_client))
287 redecorate_window(conn, last_focused);
290 /* If the last client was a floating client, we need to go to the next
291 * tiling client in stack and re-decorate it. */
292 if (old_client != NULL && client_is_floating(old_client)) {
293 LOG("Coming from floating client, searching next tiling...\n");
295 SLIST_FOREACH(current, &(client->workspace->focus_stack), focus_clients) {
296 if (client_is_floating(current))
299 LOG("Found window: %p / child %p\n", current->frame, current->child);
300 redecorate_window(conn, current);
306 SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
307 SLIST_INSERT_HEAD(&(client->workspace->focus_stack), client, focus_clients);
309 /* If we’re in stacking mode, this renders the container to update changes in the title
310 bars and to raise the focused client */
311 if ((old_client != NULL) && (old_client != client) && !old_client->dock)
312 redecorate_window(conn, old_client);
314 /* redecorate_window flushes, so we don’t need to */
315 redecorate_window(conn, client);
319 * Called when the user switches to another mode or when the container is
320 * destroyed and thus needs to be cleaned up.
323 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
324 /* When going out of stacking mode, we need to close the window */
325 struct Stack_Window *stack_win = &(container->stack_win);
327 SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
329 xcb_free_gc(conn, stack_win->pixmap.gc);
330 xcb_free_pixmap(conn, stack_win->pixmap.id);
331 xcb_destroy_window(conn, stack_win->window);
333 stack_win->rect.width = -1;
334 stack_win->rect.height = -1;
338 * Switches the layout of the given container taking care of the necessary house-keeping
341 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
342 if (mode == MODE_STACK) {
343 /* When we’re already in stacking mode, nothing has to be done */
344 if (container->mode == MODE_STACK)
347 /* When entering stacking mode, we need to open a window on which we can draw the
348 title bars of the clients, it has height 1 because we don’t bother here with
349 calculating the correct height - it will be adjusted when rendering anyways. */
350 Rect rect = {container->x, container->y, container->width, 1};
355 /* Don’t generate events for our new window, it should *not* be managed */
356 mask |= XCB_CW_OVERRIDE_REDIRECT;
359 /* We want to know when… */
360 mask |= XCB_CW_EVENT_MASK;
361 values[1] = XCB_EVENT_MASK_ENTER_WINDOW | /* …mouse is moved into our window */
362 XCB_EVENT_MASK_BUTTON_PRESS | /* …mouse is pressed */
363 XCB_EVENT_MASK_EXPOSURE; /* …our window needs to be redrawn */
365 struct Stack_Window *stack_win = &(container->stack_win);
366 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, false, mask, values);
368 stack_win->rect.height = 0;
370 /* Initialize the entry for our cached pixmap. It will be
371 * created as soon as it’s needed (see cached_pixmap_prepare). */
372 memset(&(stack_win->pixmap), 0, sizeof(struct Cached_Pixmap));
373 stack_win->pixmap.referred_rect = &stack_win->rect;
374 stack_win->pixmap.referred_drawable = stack_win->window;
376 stack_win->container = container;
378 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
380 if (container->mode == MODE_STACK)
381 leave_stack_mode(conn, container);
383 container->mode = mode;
385 /* Force reconfiguration of each client */
388 CIRCLEQ_FOREACH(client, &(container->clients), clients)
389 client->force_reconfigure = true;
393 if (container->currently_focused != NULL) {
394 /* We need to make sure that this client is above *each* of the
395 * other clients in this container */
396 Client *last_focused = get_last_focused_client(conn, container, container->currently_focused);
398 CIRCLEQ_FOREACH(client, &(container->clients), clients) {
399 if (client == container->currently_focused || client == last_focused)
402 LOG("setting %08x below %08x / %08x\n", client->frame, container->currently_focused->frame);
403 uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
404 xcb_configure_window(conn, client->frame,
405 XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
408 if (last_focused != NULL) {
409 LOG("Putting last_focused directly underneath the currently focused\n");
410 uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
411 xcb_configure_window(conn, last_focused->frame,
412 XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
416 set_focus(conn, container->currently_focused, true);
421 * Gets the first matching client for the given window class/window title.
422 * If the paramater specific is set to a specific client, only this one
426 Client *get_matching_client(xcb_connection_t *conn, const char *window_classtitle,
428 char *to_class, *to_title, *to_title_ucs = NULL;
429 int to_title_ucs_len = 0;
430 Client *matching = NULL;
432 to_class = sstrdup(window_classtitle);
434 /* If a title was specified, split both strings at the slash */
435 if ((to_title = strstr(to_class, "/")) != NULL) {
436 *(to_title++) = '\0';
437 /* Convert to UCS-2 */
438 to_title_ucs = convert_utf8_to_ucs2(to_title, &to_title_ucs_len);
441 /* If we were given a specific client we only check if that one matches */
442 if (specific != NULL) {
443 if (client_matches_class_name(specific, to_class, to_title, to_title_ucs, to_title_ucs_len))
448 LOG("Getting clients for class \"%s\" / title \"%s\"\n", to_class, to_title);
449 for (int workspace = 0; workspace < 10; workspace++) {
450 if (workspaces[workspace].screen == NULL)
454 SLIST_FOREACH(client, &(workspaces[workspace].focus_stack), focus_clients) {
455 LOG("Checking client with class=%s, name=%s\n", client->window_class, client->name);
456 if (!client_matches_class_name(client, to_class, to_title, to_title_ucs, to_title_ucs_len))