]> git.sur5r.net Git - i3/i3/blob - src/util.c
Merge branch 'next' into testcases
[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 /*
229  * Sets the given client as focused by updating the data structures correctly,
230  * updating the X input focus and finally re-decorating both windows (to signalize
231  * the user the new focus situation)
232  *
233  */
234 void set_focus(xcb_connection_t *conn, Client *client, bool set_anyways) {
235         /* The dock window cannot be focused, but enter notifies are still handled correctly */
236         if (client->dock)
237                 return;
238
239         /* Store the old client */
240         Client *old_client = SLIST_FIRST(&(c_ws->focus_stack));
241
242         /* Check if the focus needs to be changed at all */
243         if (!set_anyways && (old_client == client))
244                 return;
245
246         /* Store current_row/current_col */
247         c_ws->current_row = current_row;
248         c_ws->current_col = current_col;
249         c_ws = client->workspace;
250         /* Load current_col/current_row if we switch to a client without a container */
251         current_col = c_ws->current_col;
252         current_row = c_ws->current_row;
253
254         /* Update container */
255         if (client->container != NULL) {
256                 client->container->currently_focused = client;
257
258                 current_col = client->container->col;
259                 current_row = client->container->row;
260         }
261
262         CLIENT_LOG(client);
263         /* Set focus to the entered window, and flush xcb buffer immediately */
264         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
265         //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
266
267         if (client->container != NULL) {
268                 /* Get the client which was last focused in this particular container, it may be a different
269                    one than old_client */
270                 Client *last_focused = get_last_focused_client(conn, client->container, NULL);
271
272                 /* In stacking containers, raise the client in respect to the one which was focused before */
273                 if (client->container->mode == MODE_STACK && client->container->workspace->fullscreen_client == NULL) {
274                         /* We need to get the client again, this time excluding the current client, because
275                          * we might have just gone into stacking mode and need to raise */
276                         Client *last_focused = get_last_focused_client(conn, client->container, client);
277
278                         if (last_focused != NULL) {
279                                 LOG("raising above frame %p / child %p\n", last_focused->frame, last_focused->child);
280                                 uint32_t values[] = { last_focused->frame, XCB_STACK_MODE_ABOVE };
281                                 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
282                         }
283                 }
284
285                 /* If it is the same one as old_client, we save us the unnecessary redecorate */
286                 if ((last_focused != NULL) && (last_focused != old_client))
287                         redecorate_window(conn, last_focused);
288         }
289
290         /* If the last client was a floating client, we need to go to the next
291          * tiling client in stack and re-decorate it. */
292         if (old_client != NULL && client_is_floating(old_client)) {
293                 LOG("Coming from floating client, searching next tiling...\n");
294                 Client *current;
295                 SLIST_FOREACH(current, &(client->workspace->focus_stack), focus_clients) {
296                         if (client_is_floating(current))
297                                 continue;
298
299                         LOG("Found window: %p / child %p\n", current->frame, current->child);
300                         redecorate_window(conn, current);
301                         break;
302                 }
303
304         }
305
306         SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
307         SLIST_INSERT_HEAD(&(client->workspace->focus_stack), client, focus_clients);
308
309         /* If we’re in stacking mode, this renders the container to update changes in the title
310            bars and to raise the focused client */
311         if ((old_client != NULL) && (old_client != client) && !old_client->dock)
312                 redecorate_window(conn, old_client);
313
314         /* redecorate_window flushes, so we don’t need to */
315         redecorate_window(conn, client);
316 }
317
318 /*
319  * Called when the user switches to another mode or when the container is
320  * destroyed and thus needs to be cleaned up.
321  *
322  */
323 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
324         /* When going out of stacking mode, we need to close the window */
325         struct Stack_Window *stack_win = &(container->stack_win);
326
327         SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
328
329         xcb_free_gc(conn, stack_win->pixmap.gc);
330         xcb_free_pixmap(conn, stack_win->pixmap.id);
331         xcb_destroy_window(conn, stack_win->window);
332
333         stack_win->rect.width = -1;
334         stack_win->rect.height = -1;
335 }
336
337 /*
338  * Switches the layout of the given container taking care of the necessary house-keeping
339  *
340  */
341 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
342         if (mode == MODE_STACK) {
343                 /* When we’re already in stacking mode, nothing has to be done */
344                 if (container->mode == MODE_STACK)
345                         return;
346
347                 /* When entering stacking mode, we need to open a window on which we can draw the
348                    title bars of the clients, it has height 1 because we don’t bother here with
349                    calculating the correct height - it will be adjusted when rendering anyways. */
350                 Rect rect = {container->x, container->y, container->width, 1};
351
352                 uint32_t mask = 0;
353                 uint32_t values[2];
354
355                 /* Don’t generate events for our new window, it should *not* be managed */
356                 mask |= XCB_CW_OVERRIDE_REDIRECT;
357                 values[0] = 1;
358
359                 /* We want to know when… */
360                 mask |= XCB_CW_EVENT_MASK;
361                 values[1] =     XCB_EVENT_MASK_ENTER_WINDOW |   /* …mouse is moved into our window */
362                                 XCB_EVENT_MASK_BUTTON_PRESS |   /* …mouse is pressed */
363                                 XCB_EVENT_MASK_EXPOSURE;        /* …our window needs to be redrawn */
364
365                 struct Stack_Window *stack_win = &(container->stack_win);
366                 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, false, mask, values);
367
368                 stack_win->rect.height = 0;
369
370                 /* Initialize the entry for our cached pixmap. It will be
371                  * created as soon as it’s needed (see cached_pixmap_prepare). */
372                 memset(&(stack_win->pixmap), 0, sizeof(struct Cached_Pixmap));
373                 stack_win->pixmap.referred_rect = &stack_win->rect;
374                 stack_win->pixmap.referred_drawable = stack_win->window;
375
376                 stack_win->container = container;
377
378                 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
379         } else {
380                 if (container->mode == MODE_STACK)
381                         leave_stack_mode(conn, container);
382         }
383         container->mode = mode;
384
385         /* Force reconfiguration of each client */
386         Client *client;
387
388         CIRCLEQ_FOREACH(client, &(container->clients), clients)
389                 client->force_reconfigure = true;
390
391         render_layout(conn);
392
393         if (container->currently_focused != NULL) {
394                 /* We need to make sure that this client is above *each* of the
395                  * other clients in this container */
396                 Client *last_focused = get_last_focused_client(conn, container, container->currently_focused);
397
398                 CIRCLEQ_FOREACH(client, &(container->clients), clients) {
399                         if (client == container->currently_focused || client == last_focused)
400                                 continue;
401
402                         LOG("setting %08x below %08x / %08x\n", client->frame, container->currently_focused->frame);
403                         uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
404                         xcb_configure_window(conn, client->frame,
405                                              XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
406                 }
407
408                 if (last_focused != NULL) {
409                         LOG("Putting last_focused directly underneath the currently focused\n");
410                         uint32_t values[] = { container->currently_focused->frame, XCB_STACK_MODE_BELOW };
411                         xcb_configure_window(conn, last_focused->frame,
412                                              XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE, values);
413                 }
414
415
416                 set_focus(conn, container->currently_focused, true);
417         }
418 }
419
420 /*
421  * Gets the first matching client for the given window class/window title.
422  * If the paramater specific is set to a specific client, only this one
423  * will be checked.
424  *
425  */
426 Client *get_matching_client(xcb_connection_t *conn, const char *window_classtitle,
427                             Client *specific) {
428         char *to_class, *to_title, *to_title_ucs = NULL;
429         int to_title_ucs_len = 0;
430         Client *matching = NULL;
431
432         to_class = sstrdup(window_classtitle);
433
434         /* If a title was specified, split both strings at the slash */
435         if ((to_title = strstr(to_class, "/")) != NULL) {
436                 *(to_title++) = '\0';
437                 /* Convert to UCS-2 */
438                 to_title_ucs = convert_utf8_to_ucs2(to_title, &to_title_ucs_len);
439         }
440
441         /* If we were given a specific client we only check if that one matches */
442         if (specific != NULL) {
443                 if (client_matches_class_name(specific, to_class, to_title, to_title_ucs, to_title_ucs_len))
444                         matching = specific;
445                 goto done;
446         }
447
448         LOG("Getting clients for class \"%s\" / title \"%s\"\n", to_class, to_title);
449         for (int workspace = 0; workspace < 10; workspace++) {
450                 if (workspaces[workspace].screen == NULL)
451                         continue;
452
453                 Client *client;
454                 SLIST_FOREACH(client, &(workspaces[workspace].focus_stack), focus_clients) {
455                         LOG("Checking client with class=%s, name=%s\n", client->window_class, client->name);
456                         if (!client_matches_class_name(client, to_class, to_title, to_title_ucs, to_title_ucs_len))
457                                 continue;
458
459                         matching = client;
460                         goto done;
461                 }
462         }
463
464 done:
465         free(to_class);
466         FREE(to_title_ucs);
467         return matching;
468 }