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.
21 #if defined(__OpenBSD__)
22 #include <sys/cdefs.h>
25 #include <xcb/xcb_icccm.h>
35 static iconv_t conversion_descriptor = 0;
36 struct keyvalue_table_head by_parent = TAILQ_HEAD_INITIALIZER(by_parent);
37 struct keyvalue_table_head by_child = TAILQ_HEAD_INITIALIZER(by_child);
39 int min(int a, int b) {
40 return (a < b ? a : b);
43 int max(int a, int b) {
44 return (a > b ? a : b);
48 * Logs the given message to stdout while prefixing the current time to it.
49 * This is to be called by LOG() which includes filename/linenumber
52 void slog(char *fmt, ...) {
57 /* Get current time */
58 time_t t = time(NULL);
59 /* Convert time to local time (determined by the locale) */
60 struct tm *tmp = localtime(&t);
61 /* Generate time prefix */
62 strftime(timebuf, sizeof(timebuf), "%x %X - ", tmp);
63 printf("%s", timebuf);
69 * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
70 * the called functions returns NULL, meaning that there is no more memory available
73 void *smalloc(size_t size) {
74 void *result = malloc(size);
75 exit_if_null(result, "Error: out of memory (malloc(%zd))\n", size);
79 void *scalloc(size_t size) {
80 void *result = calloc(size, 1);
81 exit_if_null(result, "Error: out of memory (calloc(%zd))\n", size);
85 char *sstrdup(const char *str) {
86 char *result = strdup(str);
87 exit_if_null(result, "Error: out of memory (strdup())\n");
92 * The table_* functions emulate the behaviour of libxcb-wm, which in libxcb 0.3.4 suddenly
96 bool table_put(struct keyvalue_table_head *head, uint32_t key, void *value) {
97 struct keyvalue_element *element = scalloc(sizeof(struct keyvalue_element));
99 element->value = value;
101 TAILQ_INSERT_TAIL(head, element, elements);
105 void *table_remove(struct keyvalue_table_head *head, uint32_t key) {
106 struct keyvalue_element *element;
108 TAILQ_FOREACH(element, head, elements)
109 if (element->key == key) {
110 void *value = element->value;
111 TAILQ_REMOVE(head, element, elements);
119 void *table_get(struct keyvalue_table_head *head, uint32_t key) {
120 struct keyvalue_element *element;
122 TAILQ_FOREACH(element, head, elements)
123 if (element->key == key)
124 return element->value;
130 * Starts the given application by passing it through a shell. We use double fork
131 * to avoid zombie processes. As the started application’s parent exits (immediately),
132 * the application is reparented to init (process-id 1), which correctly handles
133 * childs, so we don’t have to do it :-).
135 * The shell is determined by looking for the SHELL environment variable. If it
136 * does not exist, /bin/sh is used.
139 void start_application(const char *command) {
143 /* Stores the path of the shell */
144 static const char *shell = NULL;
147 if ((shell = getenv("SHELL")) == NULL)
150 /* This is the child */
151 execl(shell, shell, "-c", command, NULL);
160 * Checks a generic cookie for errors and quits with the given message if there
164 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
165 xcb_generic_error_t *error = xcb_request_check(conn, cookie);
167 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
168 xcb_disconnect(conn);
174 * Converts the given string to UCS-2 big endian for use with
175 * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
176 * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
177 * returned. It has to be freed when done.
180 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
181 size_t input_size = strlen(input) + 1;
182 /* UCS-2 consumes exactly two bytes for each glyph */
183 int buffer_size = input_size * 2;
185 char *buffer = smalloc(buffer_size);
186 size_t output_size = buffer_size;
187 /* We need to use an additional pointer, because iconv() modifies it */
188 char *output = buffer;
190 /* We convert the input into UCS-2 big endian */
191 if (conversion_descriptor == 0) {
192 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
193 if (conversion_descriptor == 0) {
194 fprintf(stderr, "error opening the conversion context\n");
199 /* Get the conversion descriptor back to original state */
200 iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
202 /* Convert our text */
203 int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
204 if (rc == (size_t)-1) {
205 perror("Converting to UCS-2 failed");
206 if (real_strlen != NULL)
211 if (real_strlen != NULL)
212 *real_strlen = ((buffer_size - output_size) / 2) - 1;
218 * Returns the client which comes next in focus stack (= was selected before) for
219 * the given container, optionally excluding the given client.
222 Client *get_last_focused_client(xcb_connection_t *conn, Container *container, Client *exclude) {
224 SLIST_FOREACH(current, &(container->workspace->focus_stack), focus_clients)
225 if ((current->container == container) && ((exclude == NULL) || (current != exclude)))
232 * Sets the given client as focused by updating the data structures correctly,
233 * updating the X input focus and finally re-decorating both windows (to signalize
234 * the user the new focus situation)
237 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
238 /* The dock window cannot be focused, but enter notifies are still handled correctly */
242 /* Store the old client */
243 Client *old_client = SLIST_FIRST(&(c_ws->focus_stack));
245 /* Check if the focus needs to be changed at all */
246 if (!set_anyways && (old_client == client))
249 /* Store current_row/current_col */
250 c_ws->current_row = current_row;
251 c_ws->current_col = current_col;
252 c_ws = client->workspace;
253 /* Load current_col/current_row if we switch to a client without a container */
254 current_col = c_ws->current_col;
255 current_row = c_ws->current_row;
257 /* Update container */
258 if (client->container != NULL) {
259 client->container->currently_focused = client;
261 current_col = client->container->col;
262 current_row = client->container->row;
266 /* Set focus to the entered window, and flush xcb buffer immediately */
267 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
268 //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
270 if (client->container != NULL) {
271 /* Get the client which was last focused in this particular container, it may be a different
272 one than old_client */
273 Client *last_focused = get_last_focused_client(conn, client->container, NULL);
275 /* In stacking containers, raise the client in respect to the one which was focused before */
276 if ((client->container->mode == MODE_STACK || client->container->mode == MODE_TABBED) &&
277 client->container->workspace->fullscreen_client == NULL) {
278 /* We need to get the client again, this time excluding the current client, because
279 * we might have just gone into stacking mode and need to raise */
280 Client *last_focused = get_last_focused_client(conn, client->container, client);
282 if (last_focused != NULL) {
283 LOG("raising above frame %p / child %p\n", last_focused->frame, last_focused->child);
284 uint32_t values[] = { last_focused->frame, XCB_STACK_MODE_ABOVE };
285 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
289 /* If it is the same one as old_client, we save us the unnecessary redecorate */
290 if ((last_focused != NULL) && (last_focused != old_client))
291 redecorate_window(conn, last_focused);
294 /* If the last client was a floating client, we need to go to the next
295 * tiling client in stack and re-decorate it. */
296 if (old_client != NULL && client_is_floating(old_client)) {
297 LOG("Coming from floating client, searching next tiling...\n");
299 SLIST_FOREACH(current, &(client->workspace->focus_stack), focus_clients) {
300 if (client_is_floating(current))
303 LOG("Found window: %p / child %p\n", current->frame, current->child);
304 redecorate_window(conn, current);
310 SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
311 SLIST_INSERT_HEAD(&(client->workspace->focus_stack), client, focus_clients);
313 /* If we’re in stacking mode, this renders the container to update changes in the title
314 bars and to raise the focused client */
315 if ((old_client != NULL) && (old_client != client) && !old_client->dock)
316 redecorate_window(conn, old_client);
318 /* redecorate_window flushes, so we don’t need to */
319 redecorate_window(conn, client);
323 * Called when the user switches to another mode or when the container is
324 * destroyed and thus needs to be cleaned up.
327 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
328 /* When going out of stacking mode, we need to close the window */
329 struct Stack_Window *stack_win = &(container->stack_win);
331 SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
333 xcb_free_gc(conn, stack_win->pixmap.gc);
334 xcb_free_pixmap(conn, stack_win->pixmap.id);
335 xcb_destroy_window(conn, stack_win->window);
337 stack_win->rect.width = -1;
338 stack_win->rect.height = -1;
342 * Switches the layout of the given container taking care of the necessary house-keeping
345 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
346 if (mode == MODE_STACK || mode == MODE_TABBED) {
347 /* When we’re already in stacking mode, nothing has to be done */
348 if ((mode == MODE_STACK && container->mode == MODE_STACK) ||
349 (mode == MODE_TABBED && container->mode == MODE_TABBED))
352 if (container->mode == MODE_STACK || container->mode == MODE_TABBED)
355 /* When entering stacking mode, we need to open a window on which we can draw the
356 title bars of the clients, it has height 1 because we don’t bother here with
357 calculating the correct height - it will be adjusted when rendering anyways. */
358 Rect rect = {container->x, container->y, container->width, 1};
363 /* Don’t generate events for our new window, it should *not* be managed */
364 mask |= XCB_CW_OVERRIDE_REDIRECT;
367 /* We want to know when… */
368 mask |= XCB_CW_EVENT_MASK;
369 values[1] = XCB_EVENT_MASK_ENTER_WINDOW | /* …mouse is moved into our window */
370 XCB_EVENT_MASK_BUTTON_PRESS | /* …mouse is pressed */
371 XCB_EVENT_MASK_EXPOSURE; /* …our window needs to be redrawn */
373 struct Stack_Window *stack_win = &(container->stack_win);
374 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, false, mask, values);
376 stack_win->rect.height = 0;
378 /* Initialize the entry for our cached pixmap. It will be
379 * created as soon as it’s needed (see cached_pixmap_prepare). */
380 memset(&(stack_win->pixmap), 0, sizeof(struct Cached_Pixmap));
381 stack_win->pixmap.referred_rect = &stack_win->rect;
382 stack_win->pixmap.referred_drawable = stack_win->window;
384 stack_win->container = container;
386 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
388 if (container->mode == MODE_STACK || container->mode == MODE_TABBED)
389 leave_stack_mode(conn, container);
392 container->mode = mode;
394 /* Force reconfiguration of each client */
397 CIRCLEQ_FOREACH(client, &(container->clients), clients)
398 client->force_reconfigure = true;
402 if (container->currently_focused != NULL) {
403 /* We need to make sure that this client is above *each* of the
404 * other clients in this container */
405 Client *last_focused = get_last_focused_client(conn, container, container->currently_focused);
407 CIRCLEQ_FOREACH(client, &(container->clients), clients) {
408 if (client == container->currently_focused || client == last_focused)
411 LOG("setting %08x below %08x / %08x\n", client->frame, container->currently_focused->frame);
412 uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
413 xcb_configure_window(conn, client->frame,
414 XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
417 if (last_focused != NULL) {
418 LOG("Putting last_focused directly underneath the currently focused\n");
419 uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
420 xcb_configure_window(conn, last_focused->frame,
421 XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
425 set_focus(conn, container->currently_focused, true);
430 * Gets the first matching client for the given window class/window title.
431 * If the paramater specific is set to a specific client, only this one
435 Client *get_matching_client(xcb_connection_t *conn, const char *window_classtitle,
437 char *to_class, *to_title, *to_title_ucs = NULL;
438 int to_title_ucs_len = 0;
439 Client *matching = NULL;
441 to_class = sstrdup(window_classtitle);
443 /* If a title was specified, split both strings at the slash */
444 if ((to_title = strstr(to_class, "/")) != NULL) {
445 *(to_title++) = '\0';
446 /* Convert to UCS-2 */
447 to_title_ucs = convert_utf8_to_ucs2(to_title, &to_title_ucs_len);
450 /* If we were given a specific client we only check if that one matches */
451 if (specific != NULL) {
452 if (client_matches_class_name(specific, to_class, to_title, to_title_ucs, to_title_ucs_len))
457 LOG("Getting clients for class \"%s\" / title \"%s\"\n", to_class, to_title);
458 for (int workspace = 0; workspace < num_workspaces; workspace++) {
459 if (workspaces[workspace].screen == NULL)
463 SLIST_FOREACH(client, &(workspaces[workspace].focus_stack), focus_clients) {
464 LOG("Checking client with class=%s, name=%s\n", client->window_class, client->name);
465 if (!client_matches_class_name(client, to_class, to_title, to_title_ucs, to_title_ucs_len))
479 #if defined(__OpenBSD__)
483 * Find the first occurrence of the byte string s in byte string l.
486 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
487 register char *cur, *last;
488 const char *cl = (const char *)l;
489 const char *cs = (const char *)s;
491 /* we need something to compare */
492 if (l_len == 0 || s_len == 0)
495 /* "s" must be smaller or equal to "l" */
499 /* special case where s_len == 1 */
501 return memchr(l, (int)*cs, l_len);
503 /* the last position where its possible to find "s" in "l" */
504 last = (char *)cl + l_len - s_len;
506 for (cur = (char *)cl; cur <= last; cur++)
507 if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)