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