]> git.sur5r.net Git - i3/i3/blob - src/util.c
2ca1e1ca1ab82f63d397eeedc7b3dfc2d77b5e9b
[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 "i3.h"
23 #include "data.h"
24 #include "table.h"
25 #include "layout.h"
26 #include "util.h"
27 #include "xcb.h"
28
29 static iconv_t conversion_descriptor = 0;
30
31 int min(int a, int b) {
32         return (a < b ? a : b);
33 }
34
35 int max(int a, int b) {
36         return (a > b ? a : b);
37 }
38
39 /*
40  * Logs the given message to stdout while prefixing the current time to it.
41  * This is to be called by LOG() which includes filename/linenumber
42  *
43  */
44 void slog(char *fmt, ...) {
45         va_list args;
46         char timebuf[64];
47
48         va_start(args, fmt);
49         /* Get current time */
50         time_t t = time(NULL);
51         /* Convert time to local time (determined by the locale) */
52         struct tm *tmp = localtime(&t);
53         /* Generate time prefix */
54         strftime(timebuf, sizeof(timebuf), "%x %X - ", tmp);
55         printf("%s", timebuf);
56         vprintf(fmt, args);
57         va_end(args);
58 }
59
60 /*
61  * Prints the message (see printf()) to stderr, then exits the program.
62  *
63  */
64 void die(char *fmt, ...) {
65         va_list args;
66
67         va_start(args, fmt);
68         vfprintf(stderr, fmt, args);
69         va_end(args);
70
71         exit(EXIT_FAILURE);
72 }
73
74 /*
75  * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
76  * the called functions returns NULL, meaning that there is no more memory available
77  *
78  */
79 void *smalloc(size_t size) {
80         void *result = malloc(size);
81         exit_if_null(result, "Too less memory for malloc(%d)\n", size);
82         return result;
83 }
84
85 void *scalloc(size_t size) {
86         void *result = calloc(size, 1);
87         exit_if_null(result, "Too less memory for calloc(%d)\n", size);
88         return result;
89 }
90
91 char *sstrdup(const char *str) {
92         char *result = strdup(str);
93         exit_if_null(result, "Too less memory for strdup()\n");
94         return result;
95 }
96
97 /*
98  * Starts the given application by passing it through a shell. We use double fork
99  * to avoid zombie processes. As the started application’s parent exits (immediately),
100  * the application is reparented to init (process-id 1), which correctly handles
101  * childs, so we don’t have to do it :-).
102  *
103  * The shell is determined by looking for the SHELL environment variable. If it
104  * does not exist, /bin/sh is used.
105  *
106  */
107 void start_application(const char *command) {
108         if (fork() == 0) {
109                 /* Child process */
110                 if (fork() == 0) {
111                         /* Stores the path of the shell */
112                         static const char *shell = NULL;
113
114                         if (shell == NULL)
115                                 if ((shell = getenv("SHELL")) == NULL)
116                                         shell = "/bin/sh";
117
118                         /* This is the child */
119                         execl(shell, shell, "-c", command, NULL);
120                         /* not reached */
121                 }
122                 exit(0);
123         }
124         wait(0);
125 }
126
127 /*
128  * Checks a generic cookie for errors and quits with the given message if there
129  * was an error.
130  *
131  */
132 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
133         xcb_generic_error_t *error = xcb_request_check(conn, cookie);
134         if (error != NULL) {
135                 fprintf(stderr, "ERROR: %s : %d\n", err_message , error->error_code);
136                 xcb_disconnect(conn);
137                 exit(-1);
138         }
139 }
140
141 /*
142  * Converts the given string to UCS-2 big endian for use with
143  * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
144  * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
145  * returned. It has to be freed when done.
146  *
147  */
148 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
149         size_t input_size = strlen(input) + 1;
150         /* UCS-2 consumes exactly two bytes for each glyph */
151         int buffer_size = input_size * 2;
152         printf("reserving %d bytes\n", buffer_size);
153
154         char *buffer = smalloc(buffer_size);
155         size_t output_size = buffer_size;
156         /* We need to use an additional pointer, because iconv() modifies it */
157         char *output = buffer;
158
159         /* We convert the input into UCS-2 big endian */
160         if (conversion_descriptor == 0) {
161                 conversion_descriptor = iconv_open("UCS-2BE", "UTF-8");
162                 if (conversion_descriptor == 0) {
163                         fprintf(stderr, "error opening the conversion context\n");
164                         exit(1);
165                 }
166         }
167
168         /* Get the conversion descriptor back to original state */
169         iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
170
171         /* Convert our text */
172         int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
173         if (rc == (size_t)-1) {
174                 fprintf(stderr, "Converting to UCS-2 failed\n");
175                 perror("erron\n");
176                 exit(1);
177         }
178
179         *real_strlen = ((buffer_size - output_size) / 2) - 1;
180
181         return buffer;
182 }
183
184 /*
185  * Removes the given client from the container, either because it will be inserted into another
186  * one or because it was unmapped
187  *
188  */
189 void remove_client_from_container(xcb_connection_t *conn, Client *client, Container *container) {
190         CIRCLEQ_REMOVE(&(container->clients), client, clients);
191
192         /* If the container will be empty now and is in stacking mode, we need to
193            unmap the stack_win */
194         if (CIRCLEQ_EMPTY(&(container->clients)) && container->mode == MODE_STACK) {
195                 struct Stack_Window *stack_win = &(container->stack_win);
196                 stack_win->rect.height = 0;
197                 xcb_unmap_window(conn, stack_win->window);
198         }
199 }
200
201 /*
202  * Sets the given client as focused by updating the data structures correctly,
203  * updating the X input focus and finally re-decorating both windows (to signalize
204  * the user the new focus situation)
205  *
206  */
207 void set_focus(xcb_connection_t *conn, Client *client) {
208         /* The dock window cannot be focused */
209         /* TODO: does this play well with dzen2’s popup menus? or do we just need to set the input
210            focus but not update our internal structures? */
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         /* If we’re in stacking mode, this renders the container to update changes in the title
235            bars and to raise the focused client */
236         if ((old_client != NULL) && (old_client != client) && !old_client->dock)
237                 redecorate_window(conn, old_client);
238
239         SLIST_REMOVE(&(client->container->workspace->focus_stack), client, Client, focus_clients);
240         SLIST_INSERT_HEAD(&(client->container->workspace->focus_stack), client, focus_clients);
241
242         /* redecorate_window flushes, so we don’t need to */
243         redecorate_window(conn, client);
244 }
245
246 /*
247  * Called when the user switches to another mode or when the container is
248  * destroyed and thus needs to be cleaned up.
249  *
250  */
251 void leave_stack_mode(xcb_connection_t *conn, Container *container) {
252         /* When going out of stacking mode, we need to close the window */
253         struct Stack_Window *stack_win = &(container->stack_win);
254
255         SLIST_REMOVE(&stack_wins, stack_win, Stack_Window, stack_windows);
256
257         xcb_free_gc(conn, stack_win->gc);
258         xcb_destroy_window(conn, stack_win->window);
259
260         stack_win->rect.width = -1;
261         stack_win->rect.height = -1;
262 }
263
264 /*
265  * Switches the layout of the given container taking care of the necessary house-keeping
266  *
267  */
268 void switch_layout_mode(xcb_connection_t *conn, Container *container, int mode) {
269         if (mode == MODE_STACK) {
270                 /* When we’re already in stacking mode, nothing has to be done */
271                 if (container->mode == MODE_STACK)
272                         return;
273
274                 /* When entering stacking mode, we need to open a window on which we can draw the
275                    title bars of the clients, it has height 1 because we don’t bother here with
276                    calculating the correct height - it will be adjusted when rendering anyways. */
277                 Rect rect = {container->x, container->y, container->width, 1 };
278
279                 uint32_t mask = 0;
280                 uint32_t values[2];
281
282                 /* Don’t generate events for our new window, it should *not* be managed */
283                 mask |= XCB_CW_OVERRIDE_REDIRECT;
284                 values[0] = 1;
285
286                 /* We want to know when… */
287                 mask |= XCB_CW_EVENT_MASK;
288                 values[1] =     XCB_EVENT_MASK_BUTTON_PRESS |   /* …mouse is pressed */
289                                 XCB_EVENT_MASK_EXPOSURE;        /* …our window needs to be redrawn */
290
291                 struct Stack_Window *stack_win = &(container->stack_win);
292                 stack_win->window = create_window(conn, rect, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_CURSOR_LEFT_PTR, mask, values);
293
294                 /* Generate a graphics context for the titlebar */
295                 stack_win->gc = xcb_generate_id(conn);
296                 xcb_create_gc(conn, stack_win->gc, stack_win->window, 0, 0);
297
298                 stack_win->container = container;
299
300                 SLIST_INSERT_HEAD(&stack_wins, stack_win, stack_windows);
301         } else {
302                 if (container->mode == MODE_STACK)
303                         leave_stack_mode(conn, container);
304         }
305         container->mode = mode;
306
307         /* Force reconfiguration of each client */
308         Client *client;
309
310         CIRCLEQ_FOREACH(client, &(container->clients), clients)
311                 client->force_reconfigure = true;
312
313         render_layout(conn);
314 }
315
316 /*
317  * Warps the pointer into the given client (in the middle of it, to be specific), therefore
318  * selecting it
319  *
320  */
321 void warp_pointer_into(xcb_connection_t *conn, Client *client) {
322         int mid_x = client->rect.width / 2,
323             mid_y = client->rect.height / 2;
324         xcb_warp_pointer(conn, XCB_NONE, client->child, 0, 0, 0, 0, mid_x, mid_y);
325 }
326
327 /*
328  * Toggles fullscreen mode for the given client. It updates the data structures and
329  * reconfigures (= resizes/moves) the client and its frame to the full size of the
330  * screen. When leaving fullscreen, re-rendering the layout is forced.
331  *
332  */
333 void toggle_fullscreen(xcb_connection_t *conn, Client *client) {
334         /* clients without a container (docks) cannot be focused */
335         assert(client->container != NULL);
336
337         Workspace *workspace = client->container->workspace;
338
339         workspace->fullscreen_client = (client->fullscreen ? NULL : client);
340
341         client->fullscreen = !client->fullscreen;
342
343         if (client->fullscreen) {
344                 LOG("Entering fullscreen mode...\n");
345                 /* We just entered fullscreen mode, let’s configure the window */
346                  uint32_t mask = XCB_CONFIG_WINDOW_X |
347                                  XCB_CONFIG_WINDOW_Y |
348                                  XCB_CONFIG_WINDOW_WIDTH |
349                                  XCB_CONFIG_WINDOW_HEIGHT;
350                 uint32_t values[4] = {workspace->rect.x,
351                                       workspace->rect.y,
352                                       workspace->rect.width,
353                                       workspace->rect.height};
354
355                 LOG("child itself will be at %dx%d with size %dx%d\n",
356                                 values[0], values[1], values[2], values[3]);
357
358                 xcb_configure_window(conn, client->frame, mask, values);
359
360                 /* Child’s coordinates are relative to the parent (=frame) */
361                 values[0] = 0;
362                 values[1] = 0;
363                 xcb_configure_window(conn, client->child, mask, values);
364
365                 /* Raise the window */
366                 values[0] = XCB_STACK_MODE_ABOVE;
367                 xcb_configure_window(conn, client->frame, XCB_CONFIG_WINDOW_STACK_MODE, values);
368
369         } else {
370                 LOG("leaving fullscreen mode\n");
371                 /* Because the coordinates of the window haven’t changed, it would not be
372                    re-configured if we don’t set the following flag */
373                 client->force_reconfigure = true;
374                 /* We left fullscreen mode, redraw the container */
375                 render_container(conn, client->container);
376         }
377
378         xcb_flush(conn);
379 }