]> git.sur5r.net Git - i3/i3/blob - src/util.c
Bugfix: Correctly redecorate clients when changing focus (Thanks msi)
[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  * Prints the message (see printf()) to stderr, then exits the program.
67  *
68  */
69 void die(char *fmt, ...) {
70         va_list args;
71
72         va_start(args, fmt);
73         vfprintf(stderr, fmt, args);
74         va_end(args);
75
76         exit(EXIT_FAILURE);
77 }
78
79 /*
80  * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
81  * the called functions returns NULL, meaning that there is no more memory available
82  *
83  */
84 void *smalloc(size_t size) {
85         void *result = malloc(size);
86         exit_if_null(result, "Error: out of memory (malloc(%d))\n", size);
87         return result;
88 }
89
90 void *scalloc(size_t size) {
91         void *result = calloc(size, 1);
92         exit_if_null(result, "Error: out of memory (calloc(%d))\n", size);
93         return result;
94 }
95
96 char *sstrdup(const char *str) {
97         char *result = strdup(str);
98         exit_if_null(result, "Error: out of memory (strdup())\n");
99         return result;
100 }
101
102 /*
103  * The table_* functions emulate the behaviour of libxcb-wm, which in libxcb 0.3.4 suddenly
104  * vanished. Great.
105  *
106  */
107 bool table_put(struct keyvalue_table_head *head, uint32_t key, void *value) {
108         struct keyvalue_element *element = scalloc(sizeof(struct keyvalue_element));
109         element->key = key;
110         element->value = value;
111
112         TAILQ_INSERT_TAIL(head, element, elements);
113         return true;
114 }
115
116 void *table_remove(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                         void *value = element->value;
122                         TAILQ_REMOVE(head, element, elements);
123                         free(element);
124                         return value;
125                 }
126
127         return NULL;
128 }
129
130 void *table_get(struct keyvalue_table_head *head, uint32_t key) {
131         struct keyvalue_element *element;
132
133         TAILQ_FOREACH(element, head, elements)
134                 if (element->key == key)
135                         return element->value;
136
137         return NULL;
138 }
139
140 /*
141  * Starts the given application by passing it through a shell. We use double fork
142  * to avoid zombie processes. As the started application’s parent exits (immediately),
143  * the application is reparented to init (process-id 1), which correctly handles
144  * childs, so we don’t have to do it :-).
145  *
146  * The shell is determined by looking for the SHELL environment variable. If it
147  * does not exist, /bin/sh is used.
148  *
149  */
150 void start_application(const char *command) {
151         if (fork() == 0) {
152                 /* Child process */
153                 if (fork() == 0) {
154                         /* Stores the path of the shell */
155                         static const char *shell = NULL;
156
157                         if (shell == NULL)
158                                 if ((shell = getenv("SHELL")) == NULL)
159                                         shell = "/bin/sh";
160
161                         /* This is the child */
162                         execl(shell, shell, "-c", command, NULL);
163                         /* not reached */
164                 }
165                 exit(0);
166         }
167         wait(0);
168 }
169
170 /*
171  * Checks a generic cookie for errors and quits with the given message if there
172  * was an error.
173  *
174  */
175 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
176         xcb_generic_error_t *error = xcb_request_check(conn, cookie);
177         if (error != NULL) {
178                 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
179                 xcb_disconnect(conn);
180                 exit(-1);
181         }
182 }
183
184 /*
185  * Converts the given string to UCS-2 big endian for use with
186  * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
187  * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
188  * returned. It has to be freed when done.
189  *
190  */
191 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
192         size_t input_size = strlen(input) + 1;
193         /* UCS-2 consumes exactly two bytes for each glyph */
194         int buffer_size = input_size * 2;
195
196         char *buffer = smalloc(buffer_size);
197         size_t output_size = buffer_size;
198         /* We need to use an additional pointer, because iconv() modifies it */
199         char *output = buffer;
200
201         /* We convert the input into UCS-2 big endian */
202         if (conversion_descriptor == 0) {
203                 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
204                 if (conversion_descriptor == 0) {
205                         fprintf(stderr, "error opening the conversion context\n");
206                         exit(1);
207                 }
208         }
209
210         /* Get the conversion descriptor back to original state */
211         iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
212
213         /* Convert our text */
214         int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
215         if (rc == (size_t)-1) {
216                 perror("Converting to UCS-2 failed");
217                 if (real_strlen != NULL)
218                         *real_strlen = 0;
219                 return NULL;
220         }
221
222         if (real_strlen != NULL)
223                 *real_strlen = ((buffer_size - output_size) / 2) - 1;
224
225         return buffer;
226 }
227
228 /*
229  * Returns the client which comes next in focus stack (= was selected before) for
230  * the given container, optionally excluding the given client.
231  *
232  */
233 Client *get_last_focused_client(xcb_connection_t *conn, Container *container, Client *exclude) {
234         Client *current;
235         SLIST_FOREACH(current, &(container->workspace->focus_stack), focus_clients)
236                 if ((current->container == container) && ((exclude == NULL) || (current != exclude)))
237                         return current;
238         return NULL;
239 }
240
241 /*
242  * Unmaps all clients (and stack windows) of the given workspace.
243  *
244  * This needs to be called separately when temporarily rendering
245  * a workspace which is not the active workspace to force
246  * reconfiguration of all clients, like in src/xinerama.c when
247  * re-assigning a workspace to another screen.
248  *
249  */
250 void unmap_workspace(xcb_connection_t *conn, Workspace *u_ws) {
251         Client *client;
252         struct Stack_Window *stack_win;
253
254         /* Ignore notify events because they would cause focus to be changed */
255         ignore_enter_notify_forall(conn, u_ws, true);
256
257         /* Unmap all clients of the given workspace */
258         int unmapped_clients = 0;
259         FOR_TABLE(u_ws)
260                 CIRCLEQ_FOREACH(client, &(u_ws->table[cols][rows]->clients), clients) {
261                         LOG("unmapping normal client %p / %p / %p\n", client, client->frame, client->child);
262                         xcb_unmap_window(conn, client->frame);
263                         unmapped_clients++;
264                 }
265
266         /* To find floating clients, we traverse the focus stack */
267         SLIST_FOREACH(client, &(u_ws->focus_stack), focus_clients) {
268                 if (!client_is_floating(client))
269                         continue;
270
271                 LOG("unmapping floating client %p / %p / %p\n", client, client->frame, client->child);
272
273                 xcb_unmap_window(conn, client->frame);
274                 unmapped_clients++;
275         }
276
277         /* If we did not unmap any clients, the workspace is empty and we can destroy it, at least
278          * if it is not the current workspace. */
279         if (unmapped_clients == 0 && u_ws != c_ws) {
280                 /* Re-assign the workspace of all dock clients which use this workspace */
281                 Client *dock;
282                 LOG("workspace %p is empty\n", u_ws);
283                 SLIST_FOREACH(dock, &(u_ws->screen->dock_clients), dock_clients) {
284                         if (dock->workspace != u_ws)
285                                 continue;
286
287                         LOG("Re-assigning dock client to c_ws (%p)\n", c_ws);
288                         dock->workspace = c_ws;
289                 }
290                 u_ws->screen = NULL;
291         }
292
293         /* Unmap the stack windows on the given workspace, if any */
294         SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
295                 if (stack_win->container->workspace == u_ws)
296                         xcb_unmap_window(conn, stack_win->window);
297
298         ignore_enter_notify_forall(conn, u_ws, false);
299 }
300
301 /*
302  * Sets the given client as focused by updating the data structures correctly,
303  * updating the X input focus and finally re-decorating both windows (to signalize
304  * the user the new focus situation)
305  *
306  */
307 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
308         /* The dock window cannot be focused, but enter notifies are still handled correctly */
309         if (client->dock)
310                 return;
311
312         /* Store the old client */
313         Client *old_client = SLIST_FIRST(&(c_ws->focus_stack));
314
315         /* Check if the focus needs to be changed at all */
316         if (!set_anyways && (old_client == client)) {
317                 LOG("old_client == client, not changing focus\n");
318                 return;
319         }
320
321         /* Store current_row/current_col */
322         c_ws->current_row = current_row;
323         c_ws->current_col = current_col;
324         c_ws = client->workspace;
325         /* Load current_col/current_row if we switch to a client without a container */
326         current_col = c_ws->current_col;
327         current_row = c_ws->current_row;
328
329         /* Update container */
330         if (client->container != NULL) {
331                 client->container->currently_focused = client;
332
333                 current_col = client->container->col;
334                 current_row = client->container->row;
335         }
336
337         LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
338         /* Set focus to the entered window, and flush xcb buffer immediately */
339         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
340         //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
341
342         if (client->container != NULL) {
343                 /* Get the client which was last focused in this particular container, it may be a different
344                    one than old_client */
345                 Client *last_focused = get_last_focused_client(conn, client->container, NULL);
346
347                 /* In stacking containers, raise the client in respect to the one which was focused before */
348                 if (client->container->mode == MODE_STACK && client->container->workspace->fullscreen_client == NULL) {
349                         /* We need to get the client again, this time excluding the current client, because
350                          * we might have just gone into stacking mode and need to raise */
351                         Client *last_focused = get_last_focused_client(conn, client->container, client);
352
353                         if (last_focused != NULL) {
354                                 LOG("raising above frame %p / child %p\n", last_focused->frame, last_focused->child);
355                                 uint32_t values[] = { last_focused->frame, XCB_STACK_MODE_ABOVE };
356                                 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
357                         }
358                 }
359
360                 /* If it is the same one as old_client, we save us the unnecessary redecorate */
361                 if ((last_focused != NULL) && (last_focused != old_client))
362                         redecorate_window(conn, last_focused);
363         }
364
365         /* If we’re in stacking mode, this renders the container to update changes in the title
366            bars and to raise the focused client */
367         if ((old_client != NULL) && (old_client != client) && !old_client->dock)
368                 redecorate_window(conn, old_client);
369
370         /* If the last client was a floating client, we need to go to the next
371          * tiling client in stack and re-decorate it. */
372         if (client_is_floating(old_client)) {
373                 LOG("Coming from floating client, searching next tiling...\n");
374                 Client *current;
375                 SLIST_FOREACH(current, &(client->workspace->focus_stack), focus_clients) {
376                         if (client_is_floating(current))
377                                 continue;
378
379                         LOG("Found window: %p / child %p\n", current->frame, current->child);
380                         redecorate_window(conn, current);
381                         break;
382                 }
383
384         }
385
386         SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
387         SLIST_INSERT_HEAD(&(client->workspace->focus_stack), client, focus_clients);
388
389         /* redecorate_window flushes, so we don’t need to */
390         redecorate_window(conn, client);
391 }
392
393 /*
394  * Called when the user switches to another mode or when the container is
395  * destroyed and thus needs to be cleaned up.
396  *
397  */
398 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
399         /* When going out of stacking mode, we need to close the window */
400         struct Stack_Window *stack_win = &(container->stack_win);
401
402         SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
403
404         xcb_free_gc(conn, stack_win->pixmap.gc);
405         xcb_free_pixmap(conn, stack_win->pixmap.id);
406         xcb_destroy_window(conn, stack_win->window);
407
408         stack_win->rect.width = -1;
409         stack_win->rect.height = -1;
410 }
411
412 /*
413  * Switches the layout of the given container taking care of the necessary house-keeping
414  *
415  */
416 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
417         if (mode == MODE_STACK) {
418                 /* When we’re already in stacking mode, nothing has to be done */
419                 if (container->mode == MODE_STACK)
420                         return;
421
422                 /* When entering stacking mode, we need to open a window on which we can draw the
423                    title bars of the clients, it has height 1 because we don’t bother here with
424                    calculating the correct height - it will be adjusted when rendering anyways. */
425                 Rect rect = {container->x, container->y, container->width, 1};
426
427                 uint32_t mask = 0;
428                 uint32_t values[2];
429
430                 /* Don’t generate events for our new window, it should *not* be managed */
431                 mask |= XCB_CW_OVERRIDE_REDIRECT;
432                 values[0] = 1;
433
434                 /* We want to know when… */
435                 mask |= XCB_CW_EVENT_MASK;
436                 values[1] =     XCB_EVENT_MASK_ENTER_WINDOW |   /* …mouse is moved into our window */
437                                 XCB_EVENT_MASK_BUTTON_PRESS |   /* …mouse is pressed */
438                                 XCB_EVENT_MASK_EXPOSURE;        /* …our window needs to be redrawn */
439
440                 struct Stack_Window *stack_win = &(container->stack_win);
441                 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, mask, values);
442
443                 /* Initialize the entry for our cached pixmap. It will be
444                  * created as soon as it’s needed (see cached_pixmap_prepare). */
445                 memset(&(stack_win->pixmap), 0, sizeof(struct Cached_Pixmap));
446                 stack_win->pixmap.referred_rect = &stack_win->rect;
447                 stack_win->pixmap.referred_drawable = stack_win->window;
448
449                 stack_win->container = container;
450
451                 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
452         } else {
453                 if (container->mode == MODE_STACK)
454                         leave_stack_mode(conn, container);
455         }
456         container->mode = mode;
457
458         /* Force reconfiguration of each client */
459         Client *client;
460
461         CIRCLEQ_FOREACH(client, &(container->clients), clients)
462                 client->force_reconfigure = true;
463
464         render_layout(conn);
465
466         if (container->currently_focused != NULL) {
467                 /* We need to make sure that this client is above *each* of the
468                  * other clients in this container */
469                 Client *last_focused = get_last_focused_client(conn, container, container->currently_focused);
470
471                 CIRCLEQ_FOREACH(client, &(container->clients), clients) {
472                         if (client == container->currently_focused || client == last_focused)
473                                 continue;
474
475                         LOG("setting %08x below %08x / %08x\n", client->frame, container->currently_focused->frame);
476                         uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
477                         xcb_configure_window(conn, client->frame,
478                                              XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
479                 }
480
481                 if (last_focused != NULL) {
482                         LOG("Putting last_focused directly underneath the currently focused\n");
483                         uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
484                         xcb_configure_window(conn, last_focused->frame,
485                                              XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
486                 }
487
488
489                 set_focus(conn, container->currently_focused, true);
490         }
491 }
492
493 /*
494  * Gets the first matching client for the given window class/window title.
495  * If the paramater specific is set to a specific client, only this one
496  * will be checked.
497  *
498  */
499 Client *get_matching_client(xcb_connection_t *conn, const char *window_classtitle,
500                             Client *specific) {
501         char *to_class, *to_title, *to_title_ucs = NULL;
502         int to_title_ucs_len = 0;
503         Client *matching = NULL;
504
505         to_class = sstrdup(window_classtitle);
506
507         /* If a title was specified, split both strings at the slash */
508         if ((to_title = strstr(to_class, "/")) != NULL) {
509                 *(to_title++) = '\0';
510                 /* Convert to UCS-2 */
511                 to_title_ucs = convert_utf8_to_ucs2(to_title, &to_title_ucs_len);
512         }
513
514         /* If we were given a specific client we only check if that one matches */
515         if (specific != NULL) {
516                 if (client_matches_class_name(specific, to_class, to_title, to_title_ucs, to_title_ucs_len))
517                         matching = specific;
518                 goto done;
519         }
520
521         LOG("Getting clients for class \"%s\" / title \"%s\"\n", to_class, to_title);
522         for (int workspace = 0; workspace < 10; workspace++) {
523                 if (workspaces[workspace].screen == NULL)
524                         continue;
525
526                 Client *client;
527                 SLIST_FOREACH(client, &(workspaces[workspace].focus_stack), focus_clients) {
528                         LOG("Checking client with class=%s, name=%s\n", client->window_class, client->name);
529                         if (!client_matches_class_name(client, to_class, to_title, to_title_ucs, to_title_ucs_len))
530                                 continue;
531
532                         matching = client;
533                         goto done;
534                 }
535         }
536
537 done:
538         free(to_class);
539         FREE(to_title_ucs);
540         return matching;
541 }