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