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>
31 static iconv_t conversion_descriptor = 0;
32 struct keyvalue_table_head by_parent = TAILQ_HEAD_INITIALIZER(by_parent);
33 struct keyvalue_table_head by_child = TAILQ_HEAD_INITIALIZER(by_child);
35 int min(int a, int b) {
36 return (a < b ? a : b);
39 int max(int a, int b) {
40 return (a > b ? a : b);
44 * Logs the given message to stdout while prefixing the current time to it.
45 * This is to be called by LOG() which includes filename/linenumber
48 void slog(char *fmt, ...) {
53 /* Get current time */
54 time_t t = time(NULL);
55 /* Convert time to local time (determined by the locale) */
56 struct tm *tmp = localtime(&t);
57 /* Generate time prefix */
58 strftime(timebuf, sizeof(timebuf), "%x %X - ", tmp);
59 printf("%s", timebuf);
65 * Prints the message (see printf()) to stderr, then exits the program.
68 void die(char *fmt, ...) {
72 vfprintf(stderr, fmt, args);
79 * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
80 * the called functions returns NULL, meaning that there is no more memory available
83 void *smalloc(size_t size) {
84 void *result = malloc(size);
85 exit_if_null(result, "Too less memory for malloc(%d)\n", size);
89 void *scalloc(size_t size) {
90 void *result = calloc(size, 1);
91 exit_if_null(result, "Too less memory for calloc(%d)\n", size);
95 char *sstrdup(const char *str) {
96 char *result = strdup(str);
97 exit_if_null(result, "Too less memory for strdup()\n");
102 * The table_* functions emulate the behaviour of libxcb-wm, which in libxcb 0.3.4 suddenly
106 bool table_put(struct keyvalue_table_head *head, uint32_t key, void *value) {
107 struct keyvalue_element *element = scalloc(sizeof(struct keyvalue_element));
109 element->value = value;
111 TAILQ_INSERT_TAIL(head, element, elements);
115 void *table_remove(struct keyvalue_table_head *head, uint32_t key) {
116 struct keyvalue_element *element;
118 TAILQ_FOREACH(element, head, elements)
119 if (element->key == key) {
120 void *value = element->value;
121 TAILQ_REMOVE(head, element, elements);
129 void *table_get(struct keyvalue_table_head *head, uint32_t key) {
130 struct keyvalue_element *element;
132 TAILQ_FOREACH(element, head, elements)
133 if (element->key == key)
134 return element->value;
140 * Starts the given application by passing it through a shell. We use double fork
141 * to avoid zombie processes. As the started application’s parent exits (immediately),
142 * the application is reparented to init (process-id 1), which correctly handles
143 * childs, so we don’t have to do it :-).
145 * The shell is determined by looking for the SHELL environment variable. If it
146 * does not exist, /bin/sh is used.
149 void start_application(const char *command) {
153 /* Stores the path of the shell */
154 static const char *shell = NULL;
157 if ((shell = getenv("SHELL")) == NULL)
160 /* This is the child */
161 execl(shell, shell, "-c", command, NULL);
170 * Checks a generic cookie for errors and quits with the given message if there
174 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
175 xcb_generic_error_t *error = xcb_request_check(conn, cookie);
177 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
178 xcb_disconnect(conn);
184 * Converts the given string to UCS-2 big endian for use with
185 * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
186 * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
187 * returned. It has to be freed when done.
190 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
191 size_t input_size = strlen(input) + 1;
192 /* UCS-2 consumes exactly two bytes for each glyph */
193 int buffer_size = input_size * 2;
195 char *buffer = smalloc(buffer_size);
196 size_t output_size = buffer_size;
197 /* We need to use an additional pointer, because iconv() modifies it */
198 char *output = buffer;
200 /* We convert the input into UCS-2 big endian */
201 if (conversion_descriptor == 0) {
202 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
203 if (conversion_descriptor == 0) {
204 fprintf(stderr, "error opening the conversion context\n");
209 /* Get the conversion descriptor back to original state */
210 iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
212 /* Convert our text */
213 int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
214 if (rc == (size_t)-1) {
215 perror("Converting to UCS-2 failed");
220 *real_strlen = ((buffer_size - output_size) / 2) - 1;
226 * Removes the given client from the container, either because it will be inserted into another
227 * one or because it was unmapped
230 void remove_client_from_container(xcb_connection_t *conn, Client *client, Container *container) {
231 CIRCLEQ_REMOVE(&(container->clients), client, clients);
233 SLIST_REMOVE(&(container->workspace->focus_stack), client, Client, focus_clients);
235 /* If the container will be empty now and is in stacking mode, we need to
236 unmap the stack_win */
237 if (CIRCLEQ_EMPTY(&(container->clients)) && container->mode == MODE_STACK) {
238 struct Stack_Window *stack_win = &(container->stack_win);
239 stack_win->rect.height = 0;
240 xcb_unmap_window(conn, stack_win->window);
245 * Returns the client which comes next in focus stack (= was selected before) for
246 * the given container, optionally excluding the given client.
249 Client *get_last_focused_client(xcb_connection_t *conn, Container *container, Client *exclude) {
251 SLIST_FOREACH(current, &(container->workspace->focus_stack), focus_clients)
252 if ((current->container == container) && ((exclude == NULL) || (current != exclude)))
258 * Unmaps all clients (and stack windows) of the given workspace.
260 * This needs to be called separately when temporarily rendering
261 * a workspace which is not the active workspace to force
262 * reconfiguration of all clients, like in src/xinerama.c when
263 * re-assigning a workspace to another screen.
266 void unmap_workspace(xcb_connection_t *conn, Workspace *u_ws) {
268 struct Stack_Window *stack_win;
270 /* Ignore notify events because they would cause focus to be changed */
271 ignore_enter_notify_forall(conn, u_ws, true);
273 /* Unmap all clients of the current workspace */
274 int unmapped_clients = 0;
276 CIRCLEQ_FOREACH(client, &(u_ws->table[cols][rows]->clients), clients) {
277 xcb_unmap_window(conn, client->frame);
281 /* If we did not unmap any clients, the workspace is empty and we can destroy it */
282 if (unmapped_clients == 0)
285 /* Unmap the stack windows on the current workspace, if any */
286 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
287 if (stack_win->container->workspace == u_ws)
288 xcb_unmap_window(conn, stack_win->window);
290 ignore_enter_notify_forall(conn, u_ws, false);
294 * Sets the given client as focused by updating the data structures correctly,
295 * updating the X input focus and finally re-decorating both windows (to signalize
296 * the user the new focus situation)
299 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
300 /* The dock window cannot be focused, but enter notifies are still handled correctly */
304 /* Store the old client */
305 Client *old_client = CUR_CELL->currently_focused;
307 /* Check if the focus needs to be changed at all */
308 if (!set_anyways && (old_client == client)) {
309 LOG("old_client == client, not changing focus\n");
313 /* Store current_row/current_col */
314 c_ws->current_row = current_row;
315 c_ws->current_col = current_col;
316 c_ws = client->container->workspace;
318 /* Update container */
319 client->container->currently_focused = client;
321 current_col = client->container->col;
322 current_row = client->container->row;
324 LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
325 /* Set focus to the entered window, and flush xcb buffer immediately */
326 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
327 //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
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);
350 /* If we’re in stacking mode, this renders the container to update changes in the title
351 bars and to raise the focused client */
352 if ((old_client != NULL) && (old_client != client) && !old_client->dock)
353 redecorate_window(conn, old_client);
355 SLIST_REMOVE(&(client->container->workspace->focus_stack), client, Client, focus_clients);
356 SLIST_INSERT_HEAD(&(client->container->workspace->focus_stack), client, focus_clients);
358 /* redecorate_window flushes, so we don’t need to */
359 redecorate_window(conn, client);
363 * Called when the user switches to another mode or when the container is
364 * destroyed and thus needs to be cleaned up.
367 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
368 /* When going out of stacking mode, we need to close the window */
369 struct Stack_Window *stack_win = &(container->stack_win);
371 SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
373 xcb_free_gc(conn, stack_win->gc);
374 xcb_destroy_window(conn, stack_win->window);
376 stack_win->rect.width = -1;
377 stack_win->rect.height = -1;
381 * Switches the layout of the given container taking care of the necessary house-keeping
384 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
385 if (mode == MODE_STACK) {
386 /* When we’re already in stacking mode, nothing has to be done */
387 if (container->mode == MODE_STACK)
390 /* When entering stacking mode, we need to open a window on which we can draw the
391 title bars of the clients, it has height 1 because we don’t bother here with
392 calculating the correct height - it will be adjusted when rendering anyways. */
393 Rect rect = {container->x, container->y, container->width, 1 };
398 /* Don’t generate events for our new window, it should *not* be managed */
399 mask |= XCB_CW_OVERRIDE_REDIRECT;
402 /* We want to know when… */
403 mask |= XCB_CW_EVENT_MASK;
404 values[1] = XCB_EVENT_MASK_ENTER_WINDOW | /* …mouse is moved into our window */
405 XCB_EVENT_MASK_BUTTON_PRESS | /* …mouse is pressed */
406 XCB_EVENT_MASK_EXPOSURE; /* …our window needs to be redrawn */
408 struct Stack_Window *stack_win = &(container->stack_win);
409 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, mask, values);
411 /* Generate a graphics context for the titlebar */
412 stack_win->gc = xcb_generate_id(conn);
413 xcb_create_gc(conn, stack_win->gc, stack_win->window, 0, 0);
415 stack_win->container = container;
417 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
419 if (container->mode == MODE_STACK)
420 leave_stack_mode(conn, container);
422 container->mode = mode;
424 /* Force reconfiguration of each client */
427 CIRCLEQ_FOREACH(client, &(container->clients), clients)
428 client->force_reconfigure = true;
432 if (container->currently_focused != NULL)
433 set_focus(conn, container->currently_focused, true);
437 * Warps the pointer into the given client (in the middle of it, to be specific), therefore
441 void warp_pointer_into(xcb_connection_t *conn, Client *client) {
442 int mid_x = client->rect.width / 2,
443 mid_y = client->rect.height / 2;
444 xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, mid_x, mid_y);
448 * Toggles fullscreen mode for the given client. It updates the data structures and
449 * reconfigures (= resizes/moves) the client and its frame to the full size of the
450 * screen. When leaving fullscreen, re-rendering the layout is forced.
453 void toggle_fullscreen(xcb_connection_t *conn, Client *client) {
454 /* clients without a container (docks) cannot be focused */
455 assert(client->container != NULL);
457 Workspace *workspace = client->container->workspace;
459 if (!client->fullscreen) {
460 if (workspace->fullscreen_client != NULL) {
461 LOG("Not entering fullscreen mode, there already is a fullscreen client.\n");
464 client->fullscreen = true;
465 workspace->fullscreen_client = client;
466 LOG("Entering fullscreen mode...\n");
467 /* We just entered fullscreen mode, let’s configure the window */
468 uint32_t mask = XCB_CONFIG_WINDOW_X |
469 XCB_CONFIG_WINDOW_Y |
470 XCB_CONFIG_WINDOW_WIDTH |
471 XCB_CONFIG_WINDOW_HEIGHT;
472 uint32_t values[4] = {workspace->rect.x,
474 workspace->rect.width,
475 workspace->rect.height};
477 LOG("child itself will be at %dx%d with size %dx%d\n",
478 values[0], values[1], values[2], values[3]);
480 xcb_configure_window(conn, client->frame, mask, values);
482 /* Child’s coordinates are relative to the parent (=frame) */
485 xcb_configure_window(conn, client->child, mask, values);
487 /* Raise the window */
488 values[0] = XCB_STACK_MODE_ABOVE;
489 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_STACK_MODE, values);
491 Rect child_rect = workspace->rect;
492 child_rect.x = child_rect.y = 0;
493 fake_configure_notify(conn, child_rect, client->child);
495 LOG("leaving fullscreen mode\n");
496 client->fullscreen = false;
497 workspace->fullscreen_client = NULL;
498 /* Because the coordinates of the window haven’t changed, it would not be
499 re-configured if we don’t set the following flag */
500 client->force_reconfigure = true;
501 /* We left fullscreen mode, redraw the whole layout to ensure enternotify events are disabled */
509 * Returns true if the client supports the given protocol atom (like WM_DELETE_WINDOW)
512 static bool client_supports_protocol(xcb_connection_t *conn, Client *client, xcb_atom_t atom) {
513 xcb_get_property_cookie_t cookie;
514 xcb_get_wm_protocols_reply_t protocols;
517 cookie = xcb_get_wm_protocols_unchecked(conn, client->child, atoms[WM_PROTOCOLS]);
518 if (xcb_get_wm_protocols_reply(conn, cookie, &protocols, NULL) != 1)
521 /* Check if the client’s protocols have the requested atom set */
522 for (uint32_t i = 0; i < protocols.atoms_len; i++)
523 if (protocols.atoms[i] == atom)
526 xcb_get_wm_protocols_reply_wipe(&protocols);
532 * Kills the given window using WM_DELETE_WINDOW or xcb_kill_window
535 void kill_window(xcb_connection_t *conn, Client *window) {
536 /* If the client does not support WM_DELETE_WINDOW, we kill it the hard way */
537 if (!client_supports_protocol(conn, window, atoms[WM_DELETE_WINDOW])) {
538 LOG("Killing window the hard way\n");
539 xcb_kill_client(conn, window->child);
543 xcb_client_message_event_t ev;
545 memset(&ev, 0, sizeof(xcb_client_message_event_t));
547 ev.response_type = XCB_CLIENT_MESSAGE;
548 ev.window = window->child;
549 ev.type = atoms[WM_PROTOCOLS];
551 ev.data.data32[0] = atoms[WM_DELETE_WINDOW];
552 ev.data.data32[1] = XCB_CURRENT_TIME;
554 LOG("Sending WM_DELETE to the client\n");
555 xcb_send_event(conn, false, window->child, XCB_EVENT_MASK_NO_EVENT, (char*)&ev);