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