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;
33 int min(int a, int b) {
34 return (a < b ? a : b);
37 int max(int a, int b) {
38 return (a > b ? a : b);
42 * Logs the given message to stdout while prefixing the current time to it.
43 * This is to be called by LOG() which includes filename/linenumber
46 void slog(char *fmt, ...) {
51 /* Get current time */
52 time_t t = time(NULL);
53 /* Convert time to local time (determined by the locale) */
54 struct tm *tmp = localtime(&t);
55 /* Generate time prefix */
56 strftime(timebuf, sizeof(timebuf), "%x %X - ", tmp);
57 printf("%s", timebuf);
63 * Prints the message (see printf()) to stderr, then exits the program.
66 void die(char *fmt, ...) {
70 vfprintf(stderr, fmt, args);
77 * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
78 * the called functions returns NULL, meaning that there is no more memory available
81 void *smalloc(size_t size) {
82 void *result = malloc(size);
83 exit_if_null(result, "Too less memory for malloc(%d)\n", size);
87 void *scalloc(size_t size) {
88 void *result = calloc(size, 1);
89 exit_if_null(result, "Too less memory for calloc(%d)\n", size);
93 char *sstrdup(const char *str) {
94 char *result = strdup(str);
95 exit_if_null(result, "Too less memory for strdup()\n");
100 * Starts the given application by passing it through a shell. We use double fork
101 * to avoid zombie processes. As the started application’s parent exits (immediately),
102 * the application is reparented to init (process-id 1), which correctly handles
103 * childs, so we don’t have to do it :-).
105 * The shell is determined by looking for the SHELL environment variable. If it
106 * does not exist, /bin/sh is used.
109 void start_application(const char *command) {
113 /* Stores the path of the shell */
114 static const char *shell = NULL;
117 if ((shell = getenv("SHELL")) == NULL)
120 /* This is the child */
121 execl(shell, shell, "-c", command, NULL);
130 * Checks a generic cookie for errors and quits with the given message if there
134 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
135 xcb_generic_error_t *error = xcb_request_check(conn, cookie);
137 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
138 xcb_disconnect(conn);
144 * Converts the given string to UCS-2 big endian for use with
145 * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
146 * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
147 * returned. It has to be freed when done.
150 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
151 size_t input_size = strlen(input) + 1;
152 /* UCS-2 consumes exactly two bytes for each glyph */
153 int buffer_size = input_size * 2;
154 printf("reserving %d bytes\n", buffer_size);
156 char *buffer = smalloc(buffer_size);
157 size_t output_size = buffer_size;
158 /* We need to use an additional pointer, because iconv() modifies it */
159 char *output = buffer;
161 /* We convert the input into UCS-2 big endian */
162 if (conversion_descriptor == 0) {
163 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
164 if (conversion_descriptor == 0) {
165 fprintf(stderr, "error opening the conversion context\n");
170 /* Get the conversion descriptor back to original state */
171 iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
173 /* Convert our text */
174 int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
175 if (rc == (size_t)-1) {
176 perror("Converting to UCS-2 failed");
181 *real_strlen = ((buffer_size - output_size) / 2) - 1;
187 * Removes the given client from the container, either because it will be inserted into another
188 * one or because it was unmapped
191 void remove_client_from_container(xcb_connection_t *conn, Client *client, Container *container) {
192 CIRCLEQ_REMOVE(&(container->clients), client, clients);
194 /* If the container will be empty now and is in stacking mode, we need to
195 unmap the stack_win */
196 if (CIRCLEQ_EMPTY(&(container->clients)) && container->mode == MODE_STACK) {
197 struct Stack_Window *stack_win = &(container->stack_win);
198 stack_win->rect.height = 0;
199 xcb_unmap_window(conn, stack_win->window);
204 * Sets the given client as focused by updating the data structures correctly,
205 * updating the X input focus and finally re-decorating both windows (to signalize
206 * the user the new focus situation)
209 void set_focus(xcb_connection_t *conn, Client *client) {
210 /* The dock window cannot be focused */
211 /* TODO: does this play well with dzen2’s popup menus? or do we just need to set the input
212 focus but not update our internal structures? */
216 /* Store the old client */
217 Client *old_client = CUR_CELL->currently_focused;
219 /* TODO: check if the focus needs to be changed at all */
220 /* Store current_row/current_col */
221 c_ws->current_row = current_row;
222 c_ws->current_col = current_col;
223 c_ws = client->container->workspace;
225 /* Update container */
226 client->container->currently_focused = client;
228 current_col = client->container->col;
229 current_row = client->container->row;
231 LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
232 /* Set focus to the entered window, and flush xcb buffer immediately */
233 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
234 //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
236 /* Get the client which was last focused in this particular container, it may be a different
237 one than old_client */
238 Client *last_container_client;
239 SLIST_FOREACH(last_container_client, &(c_ws->focus_stack), focus_clients)
240 if (last_container_client->container == client->container) {
241 /* But if it is the same one as old_client, we save us the unnecessary redecorate */
242 if (last_container_client != old_client)
243 redecorate_window(conn, last_container_client);
247 /* If we’re in stacking mode, this renders the container to update changes in the title
248 bars and to raise the focused client */
249 if ((old_client != NULL) && (old_client != client) && !old_client->dock)
250 redecorate_window(conn, old_client);
252 SLIST_REMOVE(&(client->container->workspace->focus_stack), client, Client, focus_clients);
253 SLIST_INSERT_HEAD(&(client->container->workspace->focus_stack), client, focus_clients);
255 /* redecorate_window flushes, so we don’t need to */
256 redecorate_window(conn, client);
260 * Called when the user switches to another mode or when the container is
261 * destroyed and thus needs to be cleaned up.
264 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
265 /* When going out of stacking mode, we need to close the window */
266 struct Stack_Window *stack_win = &(container->stack_win);
268 SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
270 xcb_free_gc(conn, stack_win->gc);
271 xcb_destroy_window(conn, stack_win->window);
273 stack_win->rect.width = -1;
274 stack_win->rect.height = -1;
278 * Switches the layout of the given container taking care of the necessary house-keeping
281 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
282 if (mode == MODE_STACK) {
283 /* When we’re already in stacking mode, nothing has to be done */
284 if (container->mode == MODE_STACK)
287 /* When entering stacking mode, we need to open a window on which we can draw the
288 title bars of the clients, it has height 1 because we don’t bother here with
289 calculating the correct height - it will be adjusted when rendering anyways. */
290 Rect rect = {container->x, container->y, container->width, 1 };
295 /* Don’t generate events for our new window, it should *not* be managed */
296 mask |= XCB_CW_OVERRIDE_REDIRECT;
299 /* We want to know when… */
300 mask |= XCB_CW_EVENT_MASK;
301 values[1] = XCB_EVENT_MASK_BUTTON_PRESS | /* …mouse is pressed */
302 XCB_EVENT_MASK_EXPOSURE; /* …our window needs to be redrawn */
304 struct Stack_Window *stack_win = &(container->stack_win);
305 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, mask, values);
307 /* Generate a graphics context for the titlebar */
308 stack_win->gc = xcb_generate_id(conn);
309 xcb_create_gc(conn, stack_win->gc, stack_win->window, 0, 0);
311 stack_win->container = container;
313 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
315 if (container->mode == MODE_STACK)
316 leave_stack_mode(conn, container);
318 container->mode = mode;
320 /* Force reconfiguration of each client */
323 CIRCLEQ_FOREACH(client, &(container->clients), clients)
324 client->force_reconfigure = true;
330 * Warps the pointer into the given client (in the middle of it, to be specific), therefore
334 void warp_pointer_into(xcb_connection_t *conn, Client *client) {
335 int mid_x = client->rect.width / 2,
336 mid_y = client->rect.height / 2;
337 xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, mid_x, mid_y);
341 * Toggles fullscreen mode for the given client. It updates the data structures and
342 * reconfigures (= resizes/moves) the client and its frame to the full size of the
343 * screen. When leaving fullscreen, re-rendering the layout is forced.
346 void toggle_fullscreen(xcb_connection_t *conn, Client *client) {
347 /* clients without a container (docks) cannot be focused */
348 assert(client->container != NULL);
350 Workspace *workspace = client->container->workspace;
352 workspace->fullscreen_client = (client->fullscreen ? NULL : client);
354 client->fullscreen = !client->fullscreen;
356 if (client->fullscreen) {
357 LOG("Entering fullscreen mode...\n");
358 /* We just entered fullscreen mode, let’s configure the window */
359 uint32_t mask = XCB_CONFIG_WINDOW_X |
360 XCB_CONFIG_WINDOW_Y |
361 XCB_CONFIG_WINDOW_WIDTH |
362 XCB_CONFIG_WINDOW_HEIGHT;
363 uint32_t values[4] = {workspace->rect.x,
365 workspace->rect.width,
366 workspace->rect.height};
368 LOG("child itself will be at %dx%d with size %dx%d\n",
369 values[0], values[1], values[2], values[3]);
371 xcb_configure_window(conn, client->frame, mask, values);
373 /* Child’s coordinates are relative to the parent (=frame) */
376 xcb_configure_window(conn, client->child, mask, values);
378 /* Raise the window */
379 values[0] = XCB_STACK_MODE_ABOVE;
380 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_STACK_MODE, values);
382 Rect child_rect = workspace->rect;
383 child_rect.x = child_rect.y = 0;
384 fake_configure_notify(conn, child_rect, client->child);
386 LOG("leaving fullscreen mode\n");
387 /* Because the coordinates of the window haven’t changed, it would not be
388 re-configured if we don’t set the following flag */
389 client->force_reconfigure = true;
390 /* We left fullscreen mode, redraw the whole layout to ensure enternotify events are disabled */
398 * Returns true if the client supports the given protocol atom (like WM_DELETE_WINDOW)
401 static bool client_supports_protocol(xcb_connection_t *conn, Client *client, xcb_atom_t atom) {
402 xcb_get_property_cookie_t cookie;
403 xcb_get_wm_protocols_reply_t protocols;
406 cookie = xcb_get_wm_protocols_unchecked(conn, client->child, atoms[WM_PROTOCOLS]);
407 if (xcb_get_wm_protocols_reply(conn, cookie, &protocols, NULL) != 1)
410 /* Check if the client’s protocols have the requested atom set */
411 for (uint32_t i = 0; i < protocols.atoms_len; i++)
412 if (protocols.atoms[i] == atom)
415 xcb_get_wm_protocols_reply_wipe(&protocols);
421 * Kills the given window using WM_DELETE_WINDOW or xcb_kill_window
424 void kill_window(xcb_connection_t *conn, Client *window) {
425 /* If the client does not support WM_DELETE_WINDOW, we kill it the hard way */
426 if (!client_supports_protocol(conn, window, atoms[WM_DELETE_WINDOW])) {
427 LOG("Killing window the hard way\n");
428 xcb_kill_client(conn, window->child);
432 xcb_client_message_event_t ev;
434 memset(&ev, 0, sizeof(xcb_client_message_event_t));
436 ev.response_type = XCB_CLIENT_MESSAGE;
437 ev.window = window->child;
438 ev.type = atoms[WM_PROTOCOLS];
440 ev.data.data32[0] = atoms[WM_DELETE_WINDOW];
441 ev.data.data32[1] = XCB_CURRENT_TIME;
443 LOG("Sending WM_DELETE to the client\n");
444 xcb_send_event(conn, false, window->child, XCB_EVENT_MASK_NO_EVENT, (char*)&ev);