]> git.sur5r.net Git - i3/i3/blob - src/util.c
Implement kill-command to kill the current window, document it
[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         printf("reserving %d bytes\n", buffer_size);
155
156         char *buffer = smalloc(buffer_size);
157         size_t output_size = buffer_size;
158         /* We need to use an additional pointer, because iconv() modifies it */
159         char *output = buffer;
160
161         /* We convert the input into UCS-2 big endian */
162         if (conversion_descriptor == 0) {
163                 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
164                 if (conversion_descriptor == 0) {
165                         fprintf(stderr, "error opening the conversion context\n");
166                         exit(1);
167                 }
168         }
169
170         /* Get the conversion descriptor back to original state */
171         iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
172
173         /* Convert our text */
174         int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
175         if (rc == (size_t)-1) {
176                 perror("Converting to UCS-2 failed");
177                 *real_strlen = 0;
178                 return NULL;
179         }
180
181         *real_strlen = ((buffer_size - output_size) / 2) - 1;
182
183         return buffer;
184 }
185
186 /*
187  * Removes the given client from the container, either because it will be inserted into another
188  * one or because it was unmapped
189  *
190  */
191 void remove_client_from_container(xcb_connection_t *conn, Client *client, Container *container) {
192         CIRCLEQ_REMOVE(&(container->clients), client, clients);
193
194         /* If the container will be empty now and is in stacking mode, we need to
195            unmap the stack_win */
196         if (CIRCLEQ_EMPTY(&(container->clients)) && container->mode == MODE_STACK) {
197                 struct Stack_Window *stack_win = &(container->stack_win);
198                 stack_win->rect.height = 0;
199                 xcb_unmap_window(conn, stack_win->window);
200         }
201 }
202
203 /*
204  * Sets the given client as focused by updating the data structures correctly,
205  * updating the X input focus and finally re-decorating both windows (to signalize
206  * the user the new focus situation)
207  *
208  */
209 void set_focus(xcb_connection_t *conn, Client *client) {
210         /* The dock window cannot be focused */
211         /* TODO: does this play well with dzen2’s popup menus? or do we just need to set the input
212            focus but not update our internal structures? */
213         if (client->dock)
214                 return;
215
216         /* Store the old client */
217         Client *old_client = CUR_CELL->currently_focused;
218
219         /* TODO: check if the focus needs to be changed at all */
220         /* Store current_row/current_col */
221         c_ws->current_row = current_row;
222         c_ws->current_col = current_col;
223         c_ws = client->container->workspace;
224
225         /* Update container */
226         client->container->currently_focused = client;
227
228         current_col = client->container->col;
229         current_row = client->container->row;
230
231         LOG("set_focus(frame %08x, child %08x, name %s)\n", client->frame, client->child, client->name);
232         /* Set focus to the entered window, and flush xcb buffer immediately */
233         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, client->child, XCB_CURRENT_TIME);
234         //xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, 10, 10);
235
236         /* Get the client which was last focused in this particular container, it may be a different
237            one than old_client */
238         Client *last_container_client;
239         SLIST_FOREACH(last_container_client, &(c_ws->focus_stack), focus_clients)
240                 if (last_container_client->container == client->container) {
241                         /* But if it is the same one as old_client, we save us the unnecessary redecorate */
242                         if (last_container_client != old_client)
243                                 redecorate_window(conn, last_container_client);
244                         break;
245                 }
246
247         /* If we’re in stacking mode, this renders the container to update changes in the title
248            bars and to raise the focused client */
249         if ((old_client != NULL) && (old_client != client) && !old_client->dock)
250                 redecorate_window(conn, old_client);
251
252         SLIST_REMOVE(&(client->container->workspace->focus_stack), client, Client, focus_clients);
253         SLIST_INSERT_HEAD(&(client->container->workspace->focus_stack), client, focus_clients);
254
255         /* redecorate_window flushes, so we don’t need to */
256         redecorate_window(conn, client);
257 }
258
259 /*
260  * Called when the user switches to another mode or when the container is
261  * destroyed and thus needs to be cleaned up.
262  *
263  */
264 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
265         /* When going out of stacking mode, we need to close the window */
266         struct Stack_Window *stack_win = &(container->stack_win);
267
268         SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
269
270         xcb_free_gc(conn, stack_win->gc);
271         xcb_destroy_window(conn, stack_win->window);
272
273         stack_win->rect.width = -1;
274         stack_win->rect.height = -1;
275 }
276
277 /*
278  * Switches the layout of the given container taking care of the necessary house-keeping
279  *
280  */
281 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
282         if (mode == MODE_STACK) {
283                 /* When we’re already in stacking mode, nothing has to be done */
284                 if (container->mode == MODE_STACK)
285                         return;
286
287                 /* When entering stacking mode, we need to open a window on which we can draw the
288                    title bars of the clients, it has height 1 because we don’t bother here with
289                    calculating the correct height - it will be adjusted when rendering anyways. */
290                 Rect rect = {container->x, container->y, container->width, 1 };
291
292                 uint32_t mask = 0;
293                 uint32_t values[2];
294
295                 /* Don’t generate events for our new window, it should *not* be managed */
296                 mask |= XCB_CW_OVERRIDE_REDIRECT;
297                 values[0] = 1;
298
299                 /* We want to know when… */
300                 mask |= XCB_CW_EVENT_MASK;
301                 values[1] =     XCB_EVENT_MASK_BUTTON_PRESS |   /* …mouse is pressed */
302                                 XCB_EVENT_MASK_EXPOSURE;        /* …our window needs to be redrawn */
303
304                 struct Stack_Window *stack_win = &(container->stack_win);
305                 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, mask, values);
306
307                 /* Generate a graphics context for the titlebar */
308                 stack_win->gc = xcb_generate_id(conn);
309                 xcb_create_gc(conn, stack_win->gc, stack_win->window, 0, 0);
310
311                 stack_win->container = container;
312
313                 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
314         } else {
315                 if (container->mode == MODE_STACK)
316                         leave_stack_mode(conn, container);
317         }
318         container->mode = mode;
319
320         /* Force reconfiguration of each client */
321         Client *client;
322
323         CIRCLEQ_FOREACH(client, &(container->clients), clients)
324                 client->force_reconfigure = true;
325
326         render_layout(conn);
327 }
328
329 /*
330  * Warps the pointer into the given client (in the middle of it, to be specific), therefore
331  * selecting it
332  *
333  */
334 void warp_pointer_into(xcb_connection_t *conn, Client *client) {
335         int mid_x = client->rect.width / 2,
336             mid_y = client->rect.height / 2;
337         xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, mid_x, mid_y);
338 }
339
340 /*
341  * Toggles fullscreen mode for the given client. It updates the data structures and
342  * reconfigures (= resizes/moves) the client and its frame to the full size of the
343  * screen. When leaving fullscreen, re-rendering the layout is forced.
344  *
345  */
346 void toggle_fullscreen(xcb_connection_t *conn, Client *client) {
347         /* clients without a container (docks) cannot be focused */
348         assert(client->container != NULL);
349
350         Workspace *workspace = client->container->workspace;
351
352         workspace->fullscreen_client = (client->fullscreen ? NULL : client);
353
354         client->fullscreen = !client->fullscreen;
355
356         if (client->fullscreen) {
357                 LOG("Entering fullscreen mode...\n");
358                 /* We just entered fullscreen mode, let’s configure the window */
359                  uint32_t mask = XCB_CONFIG_WINDOW_X |
360                                  XCB_CONFIG_WINDOW_Y |
361                                  XCB_CONFIG_WINDOW_WIDTH |
362                                  XCB_CONFIG_WINDOW_HEIGHT;
363                 uint32_t values[4] = {workspace->rect.x,
364                                       workspace->rect.y,
365                                       workspace->rect.width,
366                                       workspace->rect.height};
367
368                 LOG("child itself will be at %dx%d with size %dx%d\n",
369                                 values[0], values[1], values[2], values[3]);
370
371                 xcb_configure_window(conn, client->frame, mask, values);
372
373                 /* Child’s coordinates are relative to the parent (=frame) */
374                 values[0] = 0;
375                 values[1] = 0;
376                 xcb_configure_window(conn, client->child, mask, values);
377
378                 /* Raise the window */
379                 values[0] = XCB_STACK_MODE_ABOVE;
380                 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_STACK_MODE, values);
381
382                 Rect child_rect = workspace->rect;
383                 child_rect.x = child_rect.y = 0;
384                 fake_configure_notify(conn, child_rect, client->child);
385         } else {
386                 LOG("leaving fullscreen mode\n");
387                 /* Because the coordinates of the window haven’t changed, it would not be
388                    re-configured if we don’t set the following flag */
389                 client->force_reconfigure = true;
390                 /* We left fullscreen mode, redraw the whole layout to ensure enternotify events are disabled */
391                 render_layout(conn);
392         }
393
394         xcb_flush(conn);
395 }
396
397 /*
398  * Returns true if the client supports the given protocol atom (like WM_DELETE_WINDOW)
399  *
400  */
401 static bool client_supports_protocol(xcb_connection_t *conn, Client *client, xcb_atom_t atom) {
402         xcb_get_property_cookie_t cookie;
403         xcb_get_wm_protocols_reply_t protocols;
404         bool result = false;
405
406         cookie = xcb_get_wm_protocols_unchecked(conn, client->child, atoms[WM_PROTOCOLS]);
407         if (xcb_get_wm_protocols_reply(conn, cookie, &protocols, NULL) != 1)
408                 return false;
409
410         /* Check if the client’s protocols have the requested atom set */
411         for (uint32_t i = 0; i < protocols.atoms_len; i++)
412                 if (protocols.atoms[i] == atom)
413                         result = true;
414
415         xcb_get_wm_protocols_reply_wipe(&protocols);
416
417         return result;
418 }
419
420 /*
421  * Kills the given window using WM_DELETE_WINDOW or xcb_kill_window
422  *
423  */
424 void kill_window(xcb_connection_t *conn, Client *window) {
425         /* If the client does not support WM_DELETE_WINDOW, we kill it the hard way */
426         if (!client_supports_protocol(conn, window, atoms[WM_DELETE_WINDOW])) {
427                 LOG("Killing window the hard way\n");
428                 xcb_kill_client(conn, window->child);
429                 return;
430         }
431
432         xcb_client_message_event_t ev;
433
434         memset(&ev, 0, sizeof(xcb_client_message_event_t));
435
436         ev.response_type = XCB_CLIENT_MESSAGE;
437         ev.window = window->child;
438         ev.type = atoms[WM_PROTOCOLS];
439         ev.format = 32;
440         ev.data.data32[0] = atoms[WM_DELETE_WINDOW];
441         ev.data.data32[1] = XCB_CURRENT_TIME;
442
443         LOG("Sending WM_DELETE to the client\n");
444         xcb_send_event(conn, false, window->child, XCB_EVENT_MASK_NO_EVENT, (char*)&ev);
445         xcb_flush(conn);
446 }