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 SLIST_REMOVE(&(container->workspace->focus_stack), client, Client, focus_clients);
196 /* If the container will be empty now and is in stacking mode, we need to
197 unmap the stack_win */
198 if (CIRCLEQ_EMPTY(&(container->clients)) && container->mode == MODE_STACK) {
199 struct Stack_Window *stack_win = &(container->stack_win);
200 stack_win->rect.height = 0;
201 xcb_unmap_window(conn, stack_win->window);
206 * Sets the given client as focused by updating the data structures correctly,
207 * updating the X input focus and finally re-decorating both windows (to signalize
208 * the user the new focus situation)
211 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
212 /* The dock window cannot be focused, but enter notifies are still handled correctly */
216 /* Store the old client */
217 Client *old_client = CUR_CELL->currently_focused;
219 /* Check if the focus needs to be changed at all */
220 if (!set_anyways && (old_client == client)) {
221 LOG("old_client == client, not changing focus\n");
225 /* Store current_row/current_col */
226 c_ws->current_row = current_row;
227 c_ws->current_col = current_col;
228 c_ws = client->container->workspace;
230 /* Update container */
231 client->container->currently_focused = client;
233 current_col = client->container->col;
234 current_row = client->container->row;
236 LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
237 /* Set focus to the entered window, and flush xcb buffer immediately */
238 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
239 //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
241 /* Get the client which was last focused in this particular container, it may be a different
242 one than old_client */
243 Client *last_container_client;
244 SLIST_FOREACH(last_container_client, &(c_ws->focus_stack), focus_clients)
245 if (last_container_client->container == client->container) {
246 /* But if it is the same one as old_client, we save us the unnecessary redecorate */
247 if (last_container_client != old_client)
248 redecorate_window(conn, last_container_client);
252 /* If we’re in stacking mode, this renders the container to update changes in the title
253 bars and to raise the focused client */
254 if ((old_client != NULL) && (old_client != client) && !old_client->dock)
255 redecorate_window(conn, old_client);
257 SLIST_REMOVE(&(client->container->workspace->focus_stack), client, Client, focus_clients);
258 SLIST_INSERT_HEAD(&(client->container->workspace->focus_stack), client, focus_clients);
260 /* redecorate_window flushes, so we don’t need to */
261 redecorate_window(conn, client);
265 * Called when the user switches to another mode or when the container is
266 * destroyed and thus needs to be cleaned up.
269 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
270 /* When going out of stacking mode, we need to close the window */
271 struct Stack_Window *stack_win = &(container->stack_win);
273 SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
275 xcb_free_gc(conn, stack_win->gc);
276 xcb_destroy_window(conn, stack_win->window);
278 stack_win->rect.width = -1;
279 stack_win->rect.height = -1;
283 * Switches the layout of the given container taking care of the necessary house-keeping
286 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
287 if (mode == MODE_STACK) {
288 /* When we’re already in stacking mode, nothing has to be done */
289 if (container->mode == MODE_STACK)
292 /* When entering stacking mode, we need to open a window on which we can draw the
293 title bars of the clients, it has height 1 because we don’t bother here with
294 calculating the correct height - it will be adjusted when rendering anyways. */
295 Rect rect = {container->x, container->y, container->width, 1 };
300 /* Don’t generate events for our new window, it should *not* be managed */
301 mask |= XCB_CW_OVERRIDE_REDIRECT;
304 /* We want to know when… */
305 mask |= XCB_CW_EVENT_MASK;
306 values[1] = XCB_EVENT_MASK_ENTER_WINDOW | /* …mouse is moved into our window */
307 XCB_EVENT_MASK_BUTTON_PRESS | /* …mouse is pressed */
308 XCB_EVENT_MASK_EXPOSURE; /* …our window needs to be redrawn */
310 struct Stack_Window *stack_win = &(container->stack_win);
311 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, mask, values);
313 /* Generate a graphics context for the titlebar */
314 stack_win->gc = xcb_generate_id(conn);
315 xcb_create_gc(conn, stack_win->gc, stack_win->window, 0, 0);
317 stack_win->container = container;
319 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
321 if (container->mode == MODE_STACK)
322 leave_stack_mode(conn, container);
324 container->mode = mode;
326 /* Force reconfiguration of each client */
329 CIRCLEQ_FOREACH(client, &(container->clients), clients)
330 client->force_reconfigure = true;
336 * Warps the pointer into the given client (in the middle of it, to be specific), therefore
340 void warp_pointer_into(xcb_connection_t *conn, Client *client) {
341 int mid_x = client->rect.width / 2,
342 mid_y = client->rect.height / 2;
343 xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, mid_x, mid_y);
347 * Toggles fullscreen mode for the given client. It updates the data structures and
348 * reconfigures (= resizes/moves) the client and its frame to the full size of the
349 * screen. When leaving fullscreen, re-rendering the layout is forced.
352 void toggle_fullscreen(xcb_connection_t *conn, Client *client) {
353 /* clients without a container (docks) cannot be focused */
354 assert(client->container != NULL);
356 Workspace *workspace = client->container->workspace;
358 workspace->fullscreen_client = (client->fullscreen ? NULL : client);
360 client->fullscreen = !client->fullscreen;
362 if (client->fullscreen) {
363 LOG("Entering fullscreen mode...\n");
364 /* We just entered fullscreen mode, let’s configure the window */
365 uint32_t mask = XCB_CONFIG_WINDOW_X |
366 XCB_CONFIG_WINDOW_Y |
367 XCB_CONFIG_WINDOW_WIDTH |
368 XCB_CONFIG_WINDOW_HEIGHT;
369 uint32_t values[4] = {workspace->rect.x,
371 workspace->rect.width,
372 workspace->rect.height};
374 LOG("child itself will be at %dx%d with size %dx%d\n",
375 values[0], values[1], values[2], values[3]);
377 xcb_configure_window(conn, client->frame, mask, values);
379 /* Child’s coordinates are relative to the parent (=frame) */
382 xcb_configure_window(conn, client->child, mask, values);
384 /* Raise the window */
385 values[0] = XCB_STACK_MODE_ABOVE;
386 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_STACK_MODE, values);
388 Rect child_rect = workspace->rect;
389 child_rect.x = child_rect.y = 0;
390 fake_configure_notify(conn, child_rect, client->child);
392 LOG("leaving fullscreen mode\n");
393 /* Because the coordinates of the window haven’t changed, it would not be
394 re-configured if we don’t set the following flag */
395 client->force_reconfigure = true;
396 /* We left fullscreen mode, redraw the whole layout to ensure enternotify events are disabled */
404 * Returns true if the client supports the given protocol atom (like WM_DELETE_WINDOW)
407 static bool client_supports_protocol(xcb_connection_t *conn, Client *client, xcb_atom_t atom) {
408 xcb_get_property_cookie_t cookie;
409 xcb_get_wm_protocols_reply_t protocols;
412 cookie = xcb_get_wm_protocols_unchecked(conn, client->child, atoms[WM_PROTOCOLS]);
413 if (xcb_get_wm_protocols_reply(conn, cookie, &protocols, NULL) != 1)
416 /* Check if the client’s protocols have the requested atom set */
417 for (uint32_t i = 0; i < protocols.atoms_len; i++)
418 if (protocols.atoms[i] == atom)
421 xcb_get_wm_protocols_reply_wipe(&protocols);
427 * Kills the given window using WM_DELETE_WINDOW or xcb_kill_window
430 void kill_window(xcb_connection_t *conn, Client *window) {
431 /* If the client does not support WM_DELETE_WINDOW, we kill it the hard way */
432 if (!client_supports_protocol(conn, window, atoms[WM_DELETE_WINDOW])) {
433 LOG("Killing window the hard way\n");
434 xcb_kill_client(conn, window->child);
438 xcb_client_message_event_t ev;
440 memset(&ev, 0, sizeof(xcb_client_message_event_t));
442 ev.response_type = XCB_CLIENT_MESSAGE;
443 ev.window = window->child;
444 ev.type = atoms[WM_PROTOCOLS];
446 ev.data.data32[0] = atoms[WM_DELETE_WINDOW];
447 ev.data.data32[1] = XCB_CURRENT_TIME;
449 LOG("Sending WM_DELETE to the client\n");
450 xcb_send_event(conn, false, window->child, XCB_EVENT_MASK_NO_EVENT, (char*)&ev);