]> git.sur5r.net Git - i3/i3/blob - src/util.c
Bugfix: Correctly unmap stack windows and don’t re-map them too early
[i3/i3] / src / util.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  * util.c: Utility functions, which can be useful everywhere.
11  *
12  */
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <string.h>
17 #include <sys/wait.h>
18 #include <stdarg.h>
19 #include <assert.h>
20 #include <iconv.h>
21
22 #include <xcb/xcb_icccm.h>
23
24 #include "i3.h"
25 #include "data.h"
26 #include "table.h"
27 #include "layout.h"
28 #include "util.h"
29 #include "xcb.h"
30 #include "client.h"
31
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);
35
36 int min(int a, int b) {
37         return (a < b ? a : b);
38 }
39
40 int max(int a, int b) {
41         return (a > b ? a : b);
42 }
43
44 /*
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
47  *
48  */
49 void slog(char *fmt, ...) {
50         va_list args;
51         char timebuf[64];
52
53         va_start(args, 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);
61         vprintf(fmt, args);
62         va_end(args);
63 }
64
65 /*
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
68  *
69  */
70 void *smalloc(size_t size) {
71         void *result = malloc(size);
72         exit_if_null(result, "Error: out of memory (malloc(%zd))\n", size);
73         return result;
74 }
75
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);
79         return result;
80 }
81
82 char *sstrdup(const char *str) {
83         char *result = strdup(str);
84         exit_if_null(result, "Error: out of memory (strdup())\n");
85         return result;
86 }
87
88 /*
89  * The table_* functions emulate the behaviour of libxcb-wm, which in libxcb 0.3.4 suddenly
90  * vanished. Great.
91  *
92  */
93 bool table_put(struct keyvalue_table_head *head, uint32_t key, void *value) {
94         struct keyvalue_element *element = scalloc(sizeof(struct keyvalue_element));
95         element->key = key;
96         element->value = value;
97
98         TAILQ_INSERT_TAIL(head, element, elements);
99         return true;
100 }
101
102 void *table_remove(struct keyvalue_table_head *head, uint32_t key) {
103         struct keyvalue_element *element;
104
105         TAILQ_FOREACH(element, head, elements)
106                 if (element->key == key) {
107                         void *value = element->value;
108                         TAILQ_REMOVE(head, element, elements);
109                         free(element);
110                         return value;
111                 }
112
113         return NULL;
114 }
115
116 void *table_get(struct keyvalue_table_head *head, uint32_t key) {
117         struct keyvalue_element *element;
118
119         TAILQ_FOREACH(element, head, elements)
120                 if (element->key == key)
121                         return element->value;
122
123         return NULL;
124 }
125
126 /*
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 :-).
131  *
132  * The shell is determined by looking for the SHELL environment variable. If it
133  * does not exist, /bin/sh is used.
134  *
135  */
136 void start_application(const char *command) {
137         if (fork() == 0) {
138                 /* Child process */
139                 if (fork() == 0) {
140                         /* Stores the path of the shell */
141                         static const char *shell = NULL;
142
143                         if (shell == NULL)
144                                 if ((shell = getenv("SHELL")) == NULL)
145                                         shell = "/bin/sh";
146
147                         /* This is the child */
148                         execl(shell, shell, "-c", command, NULL);
149                         /* not reached */
150                 }
151                 exit(0);
152         }
153         wait(0);
154 }
155
156 /*
157  * Checks a generic cookie for errors and quits with the given message if there
158  * was an error.
159  *
160  */
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);
163         if (error != NULL) {
164                 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
165                 xcb_disconnect(conn);
166                 exit(-1);
167         }
168 }
169
170 /*
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.
175  *
176  */
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;
181
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;
186
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");
192                         exit(1);
193                 }
194         }
195
196         /* Get the conversion descriptor back to original state */
197         iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
198
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)
204                         *real_strlen = 0;
205                 return NULL;
206         }
207
208         if (real_strlen != NULL)
209                 *real_strlen = ((buffer_size - output_size) / 2) - 1;
210
211         return buffer;
212 }
213
214 /*
215  * Returns the client which comes next in focus stack (= was selected before) for
216  * the given container, optionally excluding the given client.
217  *
218  */
219 Client *get_last_focused_client(xcb_connection_t *conn, Container *container, Client *exclude) {
220         Client *current;
221         SLIST_FOREACH(current, &(container->workspace->focus_stack), focus_clients)
222                 if ((current->container == container) && ((exclude == NULL) || (current != exclude)))
223                         return current;
224         return NULL;
225 }
226
227 /*
228  * Unmaps all clients (and stack windows) of the given workspace.
229  *
230  * This needs to be called separately when temporarily rendering
231  * a workspace which is not the active workspace to force
232  * reconfiguration of all clients, like in src/xinerama.c when
233  * re-assigning a workspace to another screen.
234  *
235  */
236 void unmap_workspace(xcb_connection_t *conn, Workspace *u_ws) {
237         Client *client;
238         struct Stack_Window *stack_win;
239
240         /* Ignore notify events because they would cause focus to be changed */
241         ignore_enter_notify_forall(conn, u_ws, true);
242
243         /* Unmap all clients of the given workspace */
244         int unmapped_clients = 0;
245         FOR_TABLE(u_ws)
246                 CIRCLEQ_FOREACH(client, &(u_ws->table[cols][rows]->clients), clients) {
247                         LOG("unmapping normal client %p / %p / %p\n", client, client->frame, client->child);
248                         xcb_unmap_window(conn, client->frame);
249                         unmapped_clients++;
250                 }
251
252         /* To find floating clients, we traverse the focus stack */
253         SLIST_FOREACH(client, &(u_ws->focus_stack), focus_clients) {
254                 if (!client_is_floating(client))
255                         continue;
256
257                 LOG("unmapping floating client %p / %p / %p\n", client, client->frame, client->child);
258
259                 xcb_unmap_window(conn, client->frame);
260                 unmapped_clients++;
261         }
262
263         /* If we did not unmap any clients, the workspace is empty and we can destroy it, at least
264          * if it is not the current workspace. */
265         if (unmapped_clients == 0 && u_ws != c_ws) {
266                 /* Re-assign the workspace of all dock clients which use this workspace */
267                 Client *dock;
268                 LOG("workspace %p is empty\n", u_ws);
269                 SLIST_FOREACH(dock, &(u_ws->screen->dock_clients), dock_clients) {
270                         if (dock->workspace != u_ws)
271                                 continue;
272
273                         LOG("Re-assigning dock client to c_ws (%p)\n", c_ws);
274                         dock->workspace = c_ws;
275                 }
276                 u_ws->screen = NULL;
277         }
278
279         /* Unmap the stack windows on the given workspace, if any */
280         SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
281                 if (stack_win->container->workspace == u_ws)
282                         xcb_unmap_window(conn, stack_win->window);
283
284         ignore_enter_notify_forall(conn, u_ws, false);
285 }
286
287 /*
288  * Sets the given client as focused by updating the data structures correctly,
289  * updating the X input focus and finally re-decorating both windows (to signalize
290  * the user the new focus situation)
291  *
292  */
293 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
294         /* The dock window cannot be focused, but enter notifies are still handled correctly */
295         if (client->dock)
296                 return;
297
298         /* Store the old client */
299         Client *old_client = SLIST_FIRST(&(c_ws->focus_stack));
300
301         /* Check if the focus needs to be changed at all */
302         if (!set_anyways && (old_client == client)) {
303                 LOG("old_client == client, not changing focus\n");
304                 return;
305         }
306
307         /* Store current_row/current_col */
308         c_ws->current_row = current_row;
309         c_ws->current_col = current_col;
310         c_ws = client->workspace;
311         /* Load current_col/current_row if we switch to a client without a container */
312         current_col = c_ws->current_col;
313         current_row = c_ws->current_row;
314
315         /* Update container */
316         if (client->container != NULL) {
317                 client->container->currently_focused = client;
318
319                 current_col = client->container->col;
320                 current_row = client->container->row;
321         }
322
323         LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
324         /* Set focus to the entered window, and flush xcb buffer immediately */
325         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
326         //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
327
328         if (client->container != NULL) {
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);
332
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);
338
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);
343                         }
344                 }
345
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);
349         }
350
351         /* If the last client was a floating client, we need to go to the next
352          * tiling client in stack and re-decorate it. */
353         if (old_client != NULL && client_is_floating(old_client)) {
354                 LOG("Coming from floating client, searching next tiling...\n");
355                 Client *current;
356                 SLIST_FOREACH(current, &(client->workspace->focus_stack), focus_clients) {
357                         if (client_is_floating(current))
358                                 continue;
359
360                         LOG("Found window: %p / child %p\n", current->frame, current->child);
361                         redecorate_window(conn, current);
362                         break;
363                 }
364
365         }
366
367         SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
368         SLIST_INSERT_HEAD(&(client->workspace->focus_stack), client, focus_clients);
369
370         /* If we’re in stacking mode, this renders the container to update changes in the title
371            bars and to raise the focused client */
372         if ((old_client != NULL) && (old_client != client) && !old_client->dock)
373                 redecorate_window(conn, old_client);
374
375         /* redecorate_window flushes, so we don’t need to */
376         redecorate_window(conn, client);
377 }
378
379 /*
380  * Called when the user switches to another mode or when the container is
381  * destroyed and thus needs to be cleaned up.
382  *
383  */
384 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
385         /* When going out of stacking mode, we need to close the window */
386         struct Stack_Window *stack_win = &(container->stack_win);
387
388         SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
389
390         xcb_free_gc(conn, stack_win->pixmap.gc);
391         xcb_free_pixmap(conn, stack_win->pixmap.id);
392         xcb_destroy_window(conn, stack_win->window);
393
394         stack_win->rect.width = -1;
395         stack_win->rect.height = -1;
396 }
397
398 /*
399  * Switches the layout of the given container taking care of the necessary house-keeping
400  *
401  */
402 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
403         if (mode == MODE_STACK) {
404                 /* When we’re already in stacking mode, nothing has to be done */
405                 if (container->mode == MODE_STACK)
406                         return;
407
408                 /* When entering stacking mode, we need to open a window on which we can draw the
409                    title bars of the clients, it has height 1 because we don’t bother here with
410                    calculating the correct height - it will be adjusted when rendering anyways. */
411                 Rect rect = {container->x, container->y, container->width, 1};
412
413                 uint32_t mask = 0;
414                 uint32_t values[2];
415
416                 /* Don’t generate events for our new window, it should *not* be managed */
417                 mask |= XCB_CW_OVERRIDE_REDIRECT;
418                 values[0] = 1;
419
420                 /* We want to know when… */
421                 mask |= XCB_CW_EVENT_MASK;
422                 values[1] =     XCB_EVENT_MASK_ENTER_WINDOW |   /* …mouse is moved into our window */
423                                 XCB_EVENT_MASK_BUTTON_PRESS |   /* …mouse is pressed */
424                                 XCB_EVENT_MASK_EXPOSURE;        /* …our window needs to be redrawn */
425
426                 struct Stack_Window *stack_win = &(container->stack_win);
427                 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, false, mask, values);
428
429                 stack_win->rect.height = 0;
430
431                 /* Initialize the entry for our cached pixmap. It will be
432                  * created as soon as it’s needed (see cached_pixmap_prepare). */
433                 memset(&(stack_win->pixmap), 0, sizeof(struct Cached_Pixmap));
434                 stack_win->pixmap.referred_rect = &stack_win->rect;
435                 stack_win->pixmap.referred_drawable = stack_win->window;
436
437                 stack_win->container = container;
438
439                 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
440         } else {
441                 if (container->mode == MODE_STACK)
442                         leave_stack_mode(conn, container);
443         }
444         container->mode = mode;
445
446         /* Force reconfiguration of each client */
447         Client *client;
448
449         CIRCLEQ_FOREACH(client, &(container->clients), clients)
450                 client->force_reconfigure = true;
451
452         render_layout(conn);
453
454         if (container->currently_focused != NULL) {
455                 /* We need to make sure that this client is above *each* of the
456                  * other clients in this container */
457                 Client *last_focused = get_last_focused_client(conn, container, container->currently_focused);
458
459                 CIRCLEQ_FOREACH(client, &(container->clients), clients) {
460                         if (client == container->currently_focused || client == last_focused)
461                                 continue;
462
463                         LOG("setting %08x below %08x / %08x\n", client->frame, container->currently_focused->frame);
464                         uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
465                         xcb_configure_window(conn, client->frame,
466                                              XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
467                 }
468
469                 if (last_focused != NULL) {
470                         LOG("Putting last_focused directly underneath the currently focused\n");
471                         uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
472                         xcb_configure_window(conn, last_focused->frame,
473                                              XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
474                 }
475
476
477                 set_focus(conn, container->currently_focused, true);
478         }
479 }
480
481 /*
482  * Gets the first matching client for the given window class/window title.
483  * If the paramater specific is set to a specific client, only this one
484  * will be checked.
485  *
486  */
487 Client *get_matching_client(xcb_connection_t *conn, const char *window_classtitle,
488                             Client *specific) {
489         char *to_class, *to_title, *to_title_ucs = NULL;
490         int to_title_ucs_len = 0;
491         Client *matching = NULL;
492
493         to_class = sstrdup(window_classtitle);
494
495         /* If a title was specified, split both strings at the slash */
496         if ((to_title = strstr(to_class, "/")) != NULL) {
497                 *(to_title++) = '\0';
498                 /* Convert to UCS-2 */
499                 to_title_ucs = convert_utf8_to_ucs2(to_title, &to_title_ucs_len);
500         }
501
502         /* If we were given a specific client we only check if that one matches */
503         if (specific != NULL) {
504                 if (client_matches_class_name(specific, to_class, to_title, to_title_ucs, to_title_ucs_len))
505                         matching = specific;
506                 goto done;
507         }
508
509         LOG("Getting clients for class \"%s\" / title \"%s\"\n", to_class, to_title);
510         for (int workspace = 0; workspace < 10; workspace++) {
511                 if (workspaces[workspace].screen == NULL)
512                         continue;
513
514                 Client *client;
515                 SLIST_FOREACH(client, &(workspaces[workspace].focus_stack), focus_clients) {
516                         LOG("Checking client with class=%s, name=%s\n", client->window_class, client->name);
517                         if (!client_matches_class_name(client, to_class, to_title, to_title_ucs, to_title_ucs_len))
518                                 continue;
519
520                         matching = client;
521                         goto done;
522                 }
523         }
524
525 done:
526         free(to_class);
527         FREE(to_title_ucs);
528         return matching;
529 }