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