]> git.sur5r.net Git - i3/i3/blob - src/handlers.c
Bugfix: Don’t mess up x/y coordinates in configurerequests for floating windows
[i3/i3] / src / handlers.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009-2010 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  */
11 #include <stdio.h>
12 #include <assert.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <time.h>
16
17 #include <xcb/xcb.h>
18 #include <xcb/xcb_atom.h>
19 #include <xcb/xcb_icccm.h>
20 #include <xcb/randr.h>
21
22 #include <X11/XKBlib.h>
23
24 #include "i3.h"
25 #include "debug.h"
26 #include "table.h"
27 #include "layout.h"
28 #include "commands.h"
29 #include "data.h"
30 #include "xcb.h"
31 #include "util.h"
32 #include "randr.h"
33 #include "config.h"
34 #include "queue.h"
35 #include "resize.h"
36 #include "client.h"
37 #include "manage.h"
38 #include "floating.h"
39 #include "workspace.h"
40 #include "log.h"
41 #include "container.h"
42
43 /* After mapping/unmapping windows, a notify event is generated. However, we don’t want it,
44    since it’d trigger an infinite loop of switching between the different windows when
45    changing workspaces */
46 static SLIST_HEAD(ignore_head, Ignore_Event) ignore_events;
47
48 static void add_ignore_event(const int sequence) {
49         struct Ignore_Event *event = smalloc(sizeof(struct Ignore_Event));
50
51         event->sequence = sequence;
52         event->added = time(NULL);
53
54         SLIST_INSERT_HEAD(&ignore_events, event, ignore_events);
55 }
56
57 /*
58  * Checks if the given sequence is ignored and returns true if so.
59  *
60  */
61 static bool event_is_ignored(const int sequence) {
62         struct Ignore_Event *event;
63         time_t now = time(NULL);
64         for (event = SLIST_FIRST(&ignore_events); event != SLIST_END(&ignore_events);) {
65                 if ((now - event->added) > 5) {
66                         struct Ignore_Event *save = event;
67                         event = SLIST_NEXT(event, ignore_events);
68                         SLIST_REMOVE(&ignore_events, save, Ignore_Event, ignore_events);
69                         free(save);
70                 } else event = SLIST_NEXT(event, ignore_events);
71         }
72
73         SLIST_FOREACH(event, &ignore_events, ignore_events) {
74                 if (event->sequence == sequence) {
75                         SLIST_REMOVE(&ignore_events, event, Ignore_Event, ignore_events);
76                         free(event);
77                         return true;
78                 }
79         }
80
81         return false;
82 }
83
84 /*
85  * Due to bindings like Mode_switch + <a>, we need to bind some keys in XCB_GRAB_MODE_SYNC.
86  * Therefore, we just replay all key presses.
87  *
88  */
89 int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
90         xcb_allow_events(conn, XCB_ALLOW_REPLAY_KEYBOARD, event->time);
91         xcb_flush(conn);
92         return 1;
93 }
94
95 /*
96  * There was a key press. We compare this key code with our bindings table and pass
97  * the bound action to parse_command().
98  *
99  */
100 int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
101         DLOG("Keypress %d, state raw = %d\n", event->detail, event->state);
102
103         /* Remove the numlock bit, all other bits are modifiers we can bind to */
104         uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
105         DLOG("(removed numlock, state = %d)\n", state_filtered);
106         /* Only use the lower 8 bits of the state (modifier masks) so that mouse
107          * button masks are filtered out */
108         state_filtered &= 0xFF;
109         DLOG("(removed upper 8 bits, state = %d)\n", state_filtered);
110
111         if (xkb_supported) {
112                 /* We need to get the keysym group (There are group 1 to group 4, each holding
113                    two keysyms (without shift and with shift) using Xkb because X fails to
114                    provide them reliably (it works in Xephyr, it does not in real X) */
115                 XkbStateRec state;
116                 if (XkbGetState(xkbdpy, XkbUseCoreKbd, &state) == Success && (state.group+1) == 2)
117                         state_filtered |= BIND_MODE_SWITCH;
118         }
119
120         DLOG("(checked mode_switch, state %d)\n", state_filtered);
121
122         /* Find the binding */
123         Binding *bind;
124         TAILQ_FOREACH(bind, bindings, bindings) {
125                 /* First compare the modifiers */
126                 if (bind->mods != state_filtered)
127                         continue;
128
129                 /* If a symbol was specified by the user, we need to look in
130                  * the array of translated keycodes for the event’s keycode */
131                 if (bind->symbol != NULL) {
132                         if (memmem(bind->translated_to,
133                                    bind->number_keycodes * sizeof(xcb_keycode_t),
134                                    &(event->detail), sizeof(xcb_keycode_t)) != NULL)
135                                 break;
136                 } else {
137                         /* This case is easier: The user specified a keycode */
138                         if (bind->keycode == event->detail)
139                                 break;
140                 }
141         }
142
143         /* No match? Then it was an actively grabbed key, that is with Mode_switch, and
144            the user did not press Mode_switch, so just pass it… */
145         if (bind == TAILQ_END(bindings)) {
146                 xcb_allow_events(conn, ReplayKeyboard, event->time);
147                 xcb_flush(conn);
148                 return 1;
149         }
150
151         parse_command(conn, bind->command);
152         if (state_filtered & BIND_MODE_SWITCH) {
153                 DLOG("Mode_switch -> allow_events(SyncKeyboard)\n");
154                 xcb_allow_events(conn, SyncKeyboard, event->time);
155                 xcb_flush(conn);
156         }
157         return 1;
158 }
159
160 /*
161  * Called with coordinates of an enter_notify event or motion_notify event
162  * to check if the user crossed virtual screen boundaries and adjust the
163  * current workspace, if so.
164  *
165  */
166 static void check_crossing_screen_boundary(uint32_t x, uint32_t y) {
167         Output *output;
168
169         if ((output = get_output_containing(x, y)) == NULL) {
170                 ELOG("ERROR: No such screen\n");
171                 return;
172         }
173         if (output == c_ws->output)
174                 return;
175
176         c_ws->current_row = current_row;
177         c_ws->current_col = current_col;
178         c_ws = output->current_workspace;
179         current_row = c_ws->current_row;
180         current_col = c_ws->current_col;
181         DLOG("We're now on output %p\n", output);
182
183         /* While usually this function is only called when the user switches
184          * to a different output using his mouse (and thus the output is
185          * empty), it may be that the following race condition occurs:
186          * 1) the user actives a new output (say VGA1).
187          * 2) the cursor is sent to the first pixel of the new VGA1, thus
188          *    generating an enter_notify for the screen (the enter_notify
189          *    is not yet received by i3).
190          * 3) i3 requeries screen configuration and maps a workspace onto the
191          *    new output.
192          * 4) the enter_notify event arrives and c_ws is set to the new
193          *    workspace but the existing windows on the new workspace are not
194          *    focused.
195          *
196          * Therefore, we re-set the focus here to be sure it’s correct. */
197         Client *first_client = SLIST_FIRST(&(c_ws->focus_stack));
198         if (first_client != NULL)
199                 set_focus(global_conn, first_client, true);
200 }
201
202 /*
203  * When the user moves the mouse pointer onto a window, this callback gets called.
204  *
205  */
206 int handle_enter_notify(void *ignored, xcb_connection_t *conn, xcb_enter_notify_event_t *event) {
207         DLOG("enter_notify for %08x, mode = %d, detail %d, serial %d\n", event->event, event->mode, event->detail, event->sequence);
208         if (event->mode != XCB_NOTIFY_MODE_NORMAL) {
209                 DLOG("This was not a normal notify, ignoring\n");
210                 return 1;
211         }
212         /* Some events are not interesting, because they were not generated actively by the
213            user, but by reconfiguration of windows */
214         if (event_is_ignored(event->sequence))
215                 return 1;
216
217         /* This was either a focus for a client’s parent (= titlebar)… */
218         Client *client = table_get(&by_parent, event->event);
219         /* …or the client itself */
220         if (client == NULL)
221                 client = table_get(&by_child, event->event);
222
223         /* Check for stack windows */
224         if (client == NULL) {
225                 struct Stack_Window *stack_win;
226                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
227                         if (stack_win->window == event->event) {
228                                 client = stack_win->container->currently_focused;
229                                 break;
230                         }
231         }
232
233
234         /* If not, then the user moved his cursor to the root window. In that case, we adjust c_ws */
235         if (client == NULL) {
236                 DLOG("Getting screen at %d x %d\n", event->root_x, event->root_y);
237                 check_crossing_screen_boundary(event->root_x, event->root_y);
238                 return 1;
239         }
240
241         /* Do plausibility checks: This event may be useless for us if it occurs on a window
242            which is in a stacked container but not the focused one */
243         if (client->container != NULL &&
244             client->container->mode == MODE_STACK &&
245             client->container->currently_focused != client) {
246                 DLOG("Plausibility check says: no\n");
247                 return 1;
248         }
249
250         if (client->workspace != c_ws && client->workspace->output == c_ws->output) {
251                 /* This can happen when a client gets assigned to a different workspace than
252                  * the current one (see src/mainx.c:reparent_window). Shortly after it was created,
253                  * an enter_notify will follow. */
254                 DLOG("enter_notify for a client on a different workspace but the same screen, ignoring\n");
255                 return 1;
256         }
257
258         if (!config.disable_focus_follows_mouse)
259                 set_focus(conn, client, false);
260
261         return 1;
262 }
263
264 /*
265  * When the user moves the mouse but does not change the active window
266  * (e.g. when having no windows opened but moving mouse on the root screen
267  * and crossing virtual screen boundaries), this callback gets called.
268  *
269  */
270 int handle_motion_notify(void *ignored, xcb_connection_t *conn, xcb_motion_notify_event_t *event) {
271         /* Skip events where the pointer was over a child window, we are only
272          * interested in events on the root window. */
273         if (event->child != 0)
274                 return 1;
275
276         check_crossing_screen_boundary(event->root_x, event->root_y);
277
278         return 1;
279 }
280
281 /*
282  * Called when the keyboard mapping changes (for example by using Xmodmap),
283  * we need to update our key bindings then (re-translate symbols).
284  *
285  */
286 int handle_mapping_notify(void *ignored, xcb_connection_t *conn, xcb_mapping_notify_event_t *event) {
287         if (event->request != XCB_MAPPING_KEYBOARD &&
288             event->request != XCB_MAPPING_MODIFIER)
289                 return 0;
290
291         DLOG("Received mapping_notify for keyboard or modifier mapping, re-grabbing keys\n");
292         xcb_refresh_keyboard_mapping(keysyms, event);
293
294         xcb_get_numlock_mask(conn);
295
296         ungrab_all_keys(conn);
297         grab_all_keys(conn);
298
299         return 0;
300 }
301
302 /*
303  * A new window appeared on the screen (=was mapped), so let’s manage it.
304  *
305  */
306 int handle_map_request(void *prophs, xcb_connection_t *conn, xcb_map_request_event_t *event) {
307         xcb_get_window_attributes_cookie_t cookie;
308
309         cookie = xcb_get_window_attributes_unchecked(conn, event->window);
310
311         DLOG("window = 0x%08x, serial is %d.\n", event->window, event->sequence);
312         add_ignore_event(event->sequence);
313
314         manage_window(prophs, conn, event->window, cookie, false);
315         return 1;
316 }
317
318 /*
319  * Configure requests are received when the application wants to resize windows on their own.
320  *
321  * We generate a synthethic configure notify event to signalize the client its "new" position.
322  *
323  */
324 int handle_configure_request(void *prophs, xcb_connection_t *conn, xcb_configure_request_event_t *event) {
325         DLOG("window 0x%08x wants to be at %dx%d with %dx%d\n",
326             event->window, event->x, event->y, event->width, event->height);
327
328         Client *client = table_get(&by_child, event->window);
329         if (client == NULL) {
330                 uint32_t mask = 0;
331                 uint32_t values[7];
332                 int c = 0;
333 #define COPY_MASK_MEMBER(mask_member, event_member) do { \
334                 if (event->value_mask & mask_member) { \
335                         mask |= mask_member; \
336                         values[c++] = event->event_member; \
337                 } \
338 } while (0)
339
340                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_X, x);
341                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_Y, y);
342                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_WIDTH, width);
343                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_HEIGHT, height);
344                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_BORDER_WIDTH, border_width);
345                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_SIBLING, sibling);
346                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_STACK_MODE, stack_mode);
347
348                 xcb_configure_window(conn, event->window, mask, values);
349                 xcb_flush(conn);
350
351                 return 1;
352         }
353
354         if (client->fullscreen) {
355                 DLOG("Client is in fullscreen mode\n");
356
357                 Rect child_rect = client->workspace->rect;
358                 child_rect.x = child_rect.y = 0;
359                 fake_configure_notify(conn, child_rect, client->child);
360
361                 return 1;
362         }
363
364         /* Floating clients can be reconfigured */
365         if (client_is_floating(client)) {
366                 i3Font *font = load_font(conn, config.font);
367                 int mode = (client->container != NULL ? client->container->mode : MODE_DEFAULT);
368                 /* TODO: refactor this code. we need a function to translate
369                  * coordinates of child_rect/rect. */
370
371                 if (event->value_mask & XCB_CONFIG_WINDOW_X) {
372                         if (mode == MODE_STACK || mode == MODE_TABBED) {
373                                 client->rect.x = event->x - 2;
374                         } else {
375                                 if (client->titlebar_position == TITLEBAR_OFF && client->borderless)
376                                         client->rect.x = event->x;
377                                 else if (client->titlebar_position == TITLEBAR_OFF && !client->borderless)
378                                         client->rect.x = event->x - 1;
379                                 else client->rect.x = event->x - 2;
380                         }
381                 }
382                 if (event->value_mask & XCB_CONFIG_WINDOW_Y) {
383                         if (mode == MODE_STACK || mode == MODE_TABBED) {
384                                 client->rect.y = event->y - 2;
385                         } else {
386                                 if (client->titlebar_position == TITLEBAR_OFF && client->borderless)
387                                         client->rect.y = event->y;
388                                 else if (client->titlebar_position == TITLEBAR_OFF && !client->borderless)
389                                         client->rect.y = event->y - 1;
390                                 else client->rect.y = event->y - font->height - 2 - 2;
391                         }
392                 }
393                 if (event->value_mask & XCB_CONFIG_WINDOW_WIDTH) {
394                         if (mode == MODE_STACK || mode == MODE_TABBED) {
395                                 client->rect.width = event->width + 2 + 2;
396                         } else {
397                                 if (client->titlebar_position == TITLEBAR_OFF && client->borderless)
398                                         client->rect.width = event->width;
399                                 else if (client->titlebar_position == TITLEBAR_OFF && !client->borderless)
400                                         client->rect.width = event->width + (1 + 1);
401                                 else client->rect.width = event->width + (2 + 2);
402                         }
403                 }
404                 if (event->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
405                         if (mode == MODE_STACK || mode == MODE_TABBED) {
406                                 client->rect.height = event->height + 2;
407                         } else {
408                                 if (client->titlebar_position == TITLEBAR_OFF && client->borderless)
409                                         client->rect.height = event->height;
410                                 else if (client->titlebar_position == TITLEBAR_OFF && !client->borderless)
411                                         client->rect.height = event->height + (1 + 1);
412                                 else client->rect.height = event->height + (font->height + 2 + 2) + 2;
413                         }
414                 }
415
416                 DLOG("Accepted new position/size for floating client: (%d, %d) size %d x %d\n",
417                     client->rect.x, client->rect.y, client->rect.width, client->rect.height);
418
419                 /* Push the new position/size to X11 */
420                 reposition_client(conn, client);
421                 resize_client(conn, client);
422                 xcb_flush(conn);
423
424                 return 1;
425         }
426
427         /* Dock clients can be reconfigured in their height */
428         if (client->dock) {
429                 DLOG("Reconfiguring height of this dock client\n");
430
431                 if (!(event->value_mask & XCB_CONFIG_WINDOW_HEIGHT)) {
432                         DLOG("Ignoring configure request, no height given\n");
433                         return 1;
434                 }
435
436                 client->desired_height = event->height;
437                 render_workspace(conn, c_ws->output, c_ws);
438                 xcb_flush(conn);
439
440                 return 1;
441         }
442
443         if (client->fullscreen) {
444                 DLOG("Client is in fullscreen mode\n");
445
446                 Rect child_rect = client->container->workspace->rect;
447                 child_rect.x = child_rect.y = 0;
448                 fake_configure_notify(conn, child_rect, client->child);
449
450                 return 1;
451         }
452
453         fake_absolute_configure_notify(conn, client);
454
455         return 1;
456 }
457
458 /*
459  * Configuration notifies are only handled because we need to set up ignore for
460  * the following enter notify events.
461  *
462  */
463 int handle_configure_event(void *prophs, xcb_connection_t *conn, xcb_configure_notify_event_t *event) {
464         /* We ignore this sequence twice because events for child and frame should be ignored */
465         add_ignore_event(event->sequence);
466         add_ignore_event(event->sequence);
467
468         return 1;
469 }
470
471 /*
472  * Gets triggered upon a RandR screen change event, that is when the user
473  * changes the screen configuration in any way (mode, position, …)
474  *
475  */
476 int handle_screen_change(void *prophs, xcb_connection_t *conn,
477                          xcb_generic_event_t *e) {
478         DLOG("RandR screen change\n");
479
480         randr_query_outputs(conn);
481
482         return 1;
483 }
484
485 /*
486  * Our window decorations were unmapped. That means, the window will be killed now,
487  * so we better clean up before.
488  *
489  */
490 int handle_unmap_notify_event(void *data, xcb_connection_t *conn, xcb_unmap_notify_event_t *event) {
491         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
492
493         add_ignore_event(event->sequence);
494
495         Client *client = table_get(&by_child, event->window);
496         /* First, we need to check if the client is awaiting an unmap-request which
497            was generated by us reparenting the window. In that case, we just ignore it. */
498         if (client != NULL && client->awaiting_useless_unmap) {
499                 client->awaiting_useless_unmap = false;
500                 return 1;
501         }
502
503         DLOG("event->window = %08x, event->event = %08x\n", event->window, event->event);
504         DLOG("UnmapNotify for 0x%08x (received from 0x%08x)\n", event->window, event->event);
505         if (client == NULL) {
506                 DLOG("not a managed window. Ignoring.\n");
507
508                 /* This was most likely the destroyed frame of a client which is
509                  * currently being unmapped, so we add this sequence (again!) to
510                  * the ignore list (enter_notify events will get sent for both,
511                  * the child and its frame). */
512                 add_ignore_event(event->sequence);
513
514                 return 0;
515         }
516
517         client = table_remove(&by_child, event->window);
518
519         /* If this was the fullscreen client, we need to unset it */
520         if (client->fullscreen)
521                 client->workspace->fullscreen_client = NULL;
522
523         /* Clients without a container are either floating or dock windows */
524         if (client->container != NULL) {
525                 Container *con = client->container;
526
527                 /* Remove the client from the list of clients */
528                 client_remove_from_container(conn, client, con, true);
529
530                 /* Set focus to the last focused client in this container */
531                 con->currently_focused = get_last_focused_client(conn, con, NULL);
532
533                 /* Only if this is the active container, we need to really change focus */
534                 if ((con->currently_focused != NULL) && ((con == CUR_CELL) || client->fullscreen))
535                         set_focus(conn, con->currently_focused, true);
536         } else if (client_is_floating(client)) {
537                 DLOG("Removing from floating clients\n");
538                 TAILQ_REMOVE(&(client->workspace->floating_clients), client, floating_clients);
539                 SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
540         }
541
542         if (client->dock) {
543                 DLOG("Removing from dock clients\n");
544                 SLIST_REMOVE(&(client->workspace->output->dock_clients), client, Client, dock_clients);
545         }
546
547         DLOG("child of 0x%08x.\n", client->frame);
548         xcb_reparent_window(conn, client->child, root, 0, 0);
549
550         client_unmap(conn, client);
551
552         xcb_destroy_window(conn, client->frame);
553         xcb_flush(conn);
554         table_remove(&by_parent, client->frame);
555
556         if (client->container != NULL) {
557                 Workspace *workspace = client->container->workspace;
558                 cleanup_table(conn, workspace);
559                 fix_colrowspan(conn, workspace);
560         }
561
562         /* Let’s see how many clients there are left on the workspace to delete it if it’s empty */
563         bool workspace_empty = SLIST_EMPTY(&(client->workspace->focus_stack));
564         bool workspace_active = false;
565         Client *to_focus = (!workspace_empty ? SLIST_FIRST(&(client->workspace->focus_stack)) : NULL);
566
567         /* If this workspace is currently active, we don’t delete it */
568         Output *screen;
569         TAILQ_FOREACH(screen, &outputs, outputs)
570                 if (screen->current_workspace == client->workspace) {
571                         workspace_active = true;
572                         workspace_empty = false;
573                         break;
574                 }
575
576         if (workspace_empty)
577                 client->workspace->output = NULL;
578
579         /* Remove the urgency flag if set */
580         client->urgent = false;
581         workspace_update_urgent_flag(client->workspace);
582
583         FREE(client->window_class_instance);
584         FREE(client->window_class_class);
585         FREE(client->name);
586         free(client);
587
588         render_layout(conn);
589
590         /* Ensure the focus is set to the next client in the focus stack or to
591          * the screen itself (if we do not focus the screen, it can happen that
592          * the focus is "nowhere" and thus keypress events will not be received
593          * by i3, thus the user cannot use any hotkeys). */
594         if (workspace_active) {
595                 if (to_focus != NULL)
596                         set_focus(conn, to_focus, true);
597                 else {
598                         DLOG("Restoring focus to root screen\n");
599                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, root, XCB_CURRENT_TIME);
600                         xcb_flush(conn);
601                 }
602         }
603
604         return 1;
605 }
606
607 /*
608  * Called when a window changes its title
609  *
610  */
611 int handle_windowname_change(void *data, xcb_connection_t *conn, uint8_t state,
612                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
613         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
614                 DLOG("_NET_WM_NAME not specified, not changing\n");
615                 return 1;
616         }
617         Client *client = table_get(&by_child, window);
618         if (client == NULL)
619                 return 1;
620
621         /* Save the old pointer to make the update atomic */
622         char *new_name;
623         int new_len;
624         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
625         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
626         char *ucs2_name = convert_utf8_to_ucs2(new_name, &new_len);
627         LOG("_NET_WM_NAME changed to \"%s\"\n", new_name);
628         free(new_name);
629
630         /* Check if they are the same and don’t update if so.
631            Note the use of new_len * 2 to check all bytes as each glyph takes 2 bytes.
632            Also note the use of memcmp() instead of strncmp() because the latter stops on nullbytes,
633            but UCS-2 uses nullbytes to fill up glyphs which only use one byte. */
634         if ((new_len == client->name_len) &&
635             (client->name != NULL) &&
636             (memcmp(client->name, ucs2_name, new_len * 2) == 0)) {
637                 free(ucs2_name);
638                 return 1;
639         }
640
641         char *old_name = client->name;
642         client->name = ucs2_name;
643         client->name_len = new_len;
644         client->uses_net_wm_name = true;
645
646         FREE(old_name);
647
648         /* If the client is a dock window, we don’t need to render anything */
649         if (client->dock)
650                 return 1;
651
652         int mode = container_mode(client->container, true);
653         if (mode == MODE_STACK || mode == MODE_TABBED)
654                 render_container(conn, client->container);
655         else decorate_window(conn, client, client->frame, client->titlegc, 0, 0);
656         xcb_flush(conn);
657
658         return 1;
659 }
660
661 /*
662  * We handle legacy window names (titles) which are in COMPOUND_TEXT encoding. However, we
663  * just pass them along, so when containing non-ASCII characters, those will be rendering
664  * incorrectly. In order to correctly render unicode window titles in i3, an application
665  * has to set _NET_WM_NAME, which is in UTF-8 encoding.
666  *
667  * On every update, a message is put out to the user, so he may improve the situation and
668  * update applications which display filenames in their title to correctly use
669  * _NET_WM_NAME and therefore support unicode.
670  *
671  */
672 int handle_windowname_change_legacy(void *data, xcb_connection_t *conn, uint8_t state,
673                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
674         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
675                 DLOG("prop == NULL\n");
676                 return 1;
677         }
678         Client *client = table_get(&by_child, window);
679         if (client == NULL)
680                 return 1;
681
682         /* Client capable of _NET_WM_NAME, ignore legacy name changes */
683         if (client->uses_net_wm_name)
684                 return 1;
685
686         /* Save the old pointer to make the update atomic */
687         char *new_name;
688         if (asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop)) == -1) {
689                 perror("Could not get old name");
690                 DLOG("Could not get old name\n");
691                 return 1;
692         }
693         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
694         LOG("WM_NAME changed to \"%s\"\n", new_name);
695
696         /* Check if they are the same and don’t update if so. */
697         if (client->name != NULL &&
698             strlen(new_name) == strlen(client->name) &&
699             strcmp(client->name, new_name) == 0) {
700                 free(new_name);
701                 return 1;
702         }
703
704         LOG("Using legacy window title. Note that in order to get Unicode window titles in i3, "
705             "the application has to set _NET_WM_NAME which is in UTF-8 encoding.\n");
706
707         char *old_name = client->name;
708         client->name = new_name;
709         client->name_len = -1;
710
711         if (old_name != NULL)
712                 free(old_name);
713
714         /* If the client is a dock window, we don’t need to render anything */
715         if (client->dock)
716                 return 1;
717
718         if (client->container != NULL &&
719             (client->container->mode == MODE_STACK ||
720              client->container->mode == MODE_TABBED))
721                 render_container(conn, client->container);
722         else decorate_window(conn, client, client->frame, client->titlegc, 0, 0);
723         xcb_flush(conn);
724
725         return 1;
726 }
727
728 /*
729  * Updates the client’s WM_CLASS property
730  *
731  */
732 int handle_windowclass_change(void *data, xcb_connection_t *conn, uint8_t state,
733                              xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
734         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
735                 DLOG("prop == NULL\n");
736                 return 1;
737         }
738         Client *client = table_get(&by_child, window);
739         if (client == NULL)
740                 return 1;
741
742         /* We cannot use asprintf here since this property contains two
743          * null-terminated strings (for compatibility reasons). Instead, we
744          * use strdup() on both strings */
745         char *new_class = xcb_get_property_value(prop);
746
747         FREE(client->window_class_instance);
748         FREE(client->window_class_class);
749
750         client->window_class_instance = strdup(new_class);
751         if ((strlen(new_class) + 1) < xcb_get_property_value_length(prop))
752                 client->window_class_class = strdup(new_class + strlen(new_class) + 1);
753         else client->window_class_class = NULL;
754         LOG("WM_CLASS changed to %s (instance), %s (class)\n",
755             client->window_class_instance, client->window_class_class);
756
757         return 0;
758 }
759
760 /*
761  * Expose event means we should redraw our windows (= title bar)
762  *
763  */
764 int handle_expose_event(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
765         /* event->count is the number of minimum remaining expose events for this window, so we
766            skip all events but the last one */
767         if (event->count != 0)
768                 return 1;
769         DLOG("window = %08x\n", event->window);
770
771         Client *client = table_get(&by_parent, event->window);
772         if (client == NULL) {
773                 /* There was no client in the table, so this is probably an expose event for
774                    one of our stack_windows. */
775                 struct Stack_Window *stack_win;
776                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
777                         if (stack_win->window == event->window) {
778                                 render_container(conn, stack_win->container);
779                                 return 1;
780                         }
781
782                 /* …or one of the bars? */
783                 Output *output;
784                 TAILQ_FOREACH(output, &outputs, outputs)
785                         if (output->bar == event->window)
786                                 render_layout(conn);
787                 return 1;
788         }
789
790         if (client->dock)
791                 return 1;
792
793         if (container_mode(client->container, true) == MODE_DEFAULT)
794                 decorate_window(conn, client, client->frame, client->titlegc, 0, 0);
795         else {
796                 uint32_t background_color;
797                 if (client->urgent)
798                         background_color = config.client.urgent.background;
799                 /* Distinguish if the window is currently focused… */
800                 else if (CUR_CELL != NULL && CUR_CELL->currently_focused == client)
801                         background_color = config.client.focused.background;
802                 /* …or if it is the focused window in a not focused container */
803                 else background_color = config.client.focused_inactive.background;
804
805                 /* Set foreground color to current focused color, line width to 2 */
806                 uint32_t values[] = {background_color, 2};
807                 xcb_change_gc(conn, client->titlegc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
808
809                 /* Draw the border, the ±1 is for line width = 2 */
810                 xcb_point_t points[] = {{1, 0},                                           /* left upper edge */
811                                         {1, client->rect.height-1},                       /* left bottom edge */
812                                         {client->rect.width-1, client->rect.height-1},    /* right bottom edge */
813                                         {client->rect.width-1, 0}};                       /* right upper edge */
814                 xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, client->frame, client->titlegc, 4, points);
815
816                 /* Draw a black background */
817                 xcb_change_gc_single(conn, client->titlegc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
818                 if (client->titlebar_position == TITLEBAR_OFF && !client->borderless) {
819                         xcb_rectangle_t crect = {1, 0, client->rect.width - (1 + 1), client->rect.height - 1};
820                         xcb_poly_fill_rectangle(conn, client->frame, client->titlegc, 1, &crect);
821                 } else {
822                         xcb_rectangle_t crect = {2, 0, client->rect.width - (2 + 2), client->rect.height - 2};
823                         xcb_poly_fill_rectangle(conn, client->frame, client->titlegc, 1, &crect);
824                 }
825         }
826         xcb_flush(conn);
827         return 1;
828 }
829
830 /*
831  * Handle client messages (EWMH)
832  *
833  */
834 int handle_client_message(void *data, xcb_connection_t *conn, xcb_client_message_event_t *event) {
835         if (event->type == atoms[_NET_WM_STATE]) {
836                 if (event->format != 32 || event->data.data32[1] != atoms[_NET_WM_STATE_FULLSCREEN])
837                         return 0;
838
839                 Client *client = table_get(&by_child, event->window);
840                 if (client == NULL)
841                         return 0;
842
843                 /* Check if the fullscreen state should be toggled */
844                 if ((client->fullscreen &&
845                      (event->data.data32[0] == _NET_WM_STATE_REMOVE ||
846                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)) ||
847                     (!client->fullscreen &&
848                      (event->data.data32[0] == _NET_WM_STATE_ADD ||
849                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)))
850                         client_toggle_fullscreen(conn, client);
851         } else {
852                 ELOG("unhandled clientmessage\n");
853                 return 0;
854         }
855
856         return 1;
857 }
858
859 int handle_window_type(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
860                         xcb_atom_t atom, xcb_get_property_reply_t *property) {
861         /* TODO: Implement this one. To do this, implement a little test program which sleep(1)s
862          before changing this property. */
863         ELOG("_NET_WM_WINDOW_TYPE changed, this is not yet implemented.\n");
864         return 0;
865 }
866
867 /*
868  * Handles the size hints set by a window, but currently only the part necessary for displaying
869  * clients proportionally inside their frames (mplayer for example)
870  *
871  * See ICCCM 4.1.2.3 for more details
872  *
873  */
874 int handle_normal_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
875                         xcb_atom_t name, xcb_get_property_reply_t *reply) {
876         Client *client = table_get(&by_child, window);
877         if (client == NULL) {
878                 DLOG("Received WM_SIZE_HINTS for unknown client\n");
879                 return 1;
880         }
881         xcb_size_hints_t size_hints;
882
883         CLIENT_LOG(client);
884
885         /* If the hints were already in this event, use them, if not, request them */
886         if (reply != NULL)
887                 xcb_get_wm_size_hints_from_reply(&size_hints, reply);
888         else
889                 xcb_get_wm_normal_hints_reply(conn, xcb_get_wm_normal_hints_unchecked(conn, client->child), &size_hints, NULL);
890
891         if ((size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE)) {
892                 // TODO: Minimum size is not yet implemented
893                 DLOG("Minimum size: %d (width) x %d (height)\n", size_hints.min_width, size_hints.min_height);
894         }
895
896         bool changed = false;
897         if ((size_hints.flags & XCB_SIZE_HINT_P_RESIZE_INC)) {
898                 if (size_hints.width_inc > 0 && size_hints.width_inc < 0xFFFF)
899                         if (client->width_increment != size_hints.width_inc) {
900                                 client->width_increment = size_hints.width_inc;
901                                 changed = true;
902                         }
903                 if (size_hints.height_inc > 0 && size_hints.height_inc < 0xFFFF)
904                         if (client->height_increment != size_hints.height_inc) {
905                                 client->height_increment = size_hints.height_inc;
906                                 changed = true;
907                         }
908
909                 if (changed)
910                         DLOG("resize increments changed\n");
911         }
912
913         int base_width = 0, base_height = 0;
914
915         /* base_width/height are the desired size of the window.
916            We check if either the program-specified size or the program-specified
917            min-size is available */
918         if (size_hints.flags & XCB_SIZE_HINT_BASE_SIZE) {
919                 base_width = size_hints.base_width;
920                 base_height = size_hints.base_height;
921         } else if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
922                 /* TODO: is this right? icccm says not */
923                 base_width = size_hints.min_width;
924                 base_height = size_hints.min_height;
925         }
926
927         if (base_width != client->base_width ||
928             base_height != client->base_height) {
929                 client->base_width = base_width;
930                 client->base_height = base_height;
931                 DLOG("client's base_height changed to %d\n", base_height);
932                 DLOG("client's base_width changed to %d\n", base_width);
933                 changed = true;
934         }
935
936         if (changed) {
937                 if (client->fullscreen)
938                         DLOG("Not resizing client, it is in fullscreen mode\n");
939                 else {
940                         resize_client(conn, client);
941                         xcb_flush(conn);
942                 }
943         }
944
945         /* If no aspect ratio was set or if it was invalid, we ignore the hints */
946         if (!(size_hints.flags & XCB_SIZE_HINT_P_ASPECT) ||
947             (size_hints.min_aspect_num <= 0) ||
948             (size_hints.min_aspect_den <= 0)) {
949                 return 1;
950         }
951
952         double width = client->rect.width - base_width;
953         double height = client->rect.height - base_height;
954         /* Convert numerator/denominator to a double */
955         double min_aspect = (double)size_hints.min_aspect_num / size_hints.min_aspect_den;
956         double max_aspect = (double)size_hints.max_aspect_num / size_hints.min_aspect_den;
957
958         DLOG("Aspect ratio set: minimum %f, maximum %f\n", min_aspect, max_aspect);
959         DLOG("width = %f, height = %f\n", width, height);
960
961         /* Sanity checks, this is user-input, in a way */
962         if (max_aspect <= 0 || min_aspect <= 0 || height == 0 || (width / height) <= 0)
963                 return 1;
964
965         /* Check if we need to set proportional_* variables using the correct ratio */
966         if ((width / height) < min_aspect) {
967                 client->proportional_width = width;
968                 client->proportional_height = width / min_aspect;
969         } else if ((width / height) > max_aspect) {
970                 client->proportional_width = width;
971                 client->proportional_height = width / max_aspect;
972         } else return 1;
973
974         client->force_reconfigure = true;
975
976         if (client->container != NULL) {
977                 render_container(conn, client->container);
978                 xcb_flush(conn);
979         }
980
981         return 1;
982 }
983
984 /*
985  * Handles the WM_HINTS property for extracting the urgency state of the window.
986  *
987  */
988 int handle_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
989                   xcb_atom_t name, xcb_get_property_reply_t *reply) {
990         Client *client = table_get(&by_child, window);
991         if (client == NULL) {
992                 DLOG("Received WM_HINTS for unknown client\n");
993                 return 1;
994         }
995         xcb_wm_hints_t hints;
996
997         if (reply != NULL) {
998                 if (!xcb_get_wm_hints_from_reply(&hints, reply))
999                         return 1;
1000         } else {
1001                 if (!xcb_get_wm_hints_reply(conn, xcb_get_wm_hints_unchecked(conn, client->child), &hints, NULL))
1002                         return 1;
1003         }
1004
1005         Client *last_focused = SLIST_FIRST(&(c_ws->focus_stack));
1006         if (!client->urgent && client == last_focused) {
1007                 DLOG("Ignoring urgency flag for current client\n");
1008                 return 1;
1009         }
1010
1011         /* Update the flag on the client directly */
1012         client->urgent = (xcb_wm_hints_get_urgency(&hints) != 0);
1013         CLIENT_LOG(client);
1014         LOG("Urgency flag changed to %d\n", client->urgent);
1015
1016         workspace_update_urgent_flag(client->workspace);
1017         redecorate_window(conn, client);
1018
1019         /* If the workspace this client is on is not visible, we need to redraw
1020          * the workspace bar */
1021         if (!workspace_is_visible(client->workspace)) {
1022                 Output *output = client->workspace->output;
1023                 render_workspace(conn, output, output->current_workspace);
1024                 xcb_flush(conn);
1025         }
1026
1027         return 1;
1028 }
1029
1030 /*
1031  * Handles the transient for hints set by a window, signalizing that this window is a popup window
1032  * for some other window.
1033  *
1034  * See ICCCM 4.1.2.6 for more details
1035  *
1036  */
1037 int handle_transient_for(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
1038                          xcb_atom_t name, xcb_get_property_reply_t *reply) {
1039         Client *client = table_get(&by_child, window);
1040         if (client == NULL) {
1041                 DLOG("No such client\n");
1042                 return 1;
1043         }
1044
1045         xcb_window_t transient_for;
1046
1047         if (reply != NULL) {
1048                 if (!xcb_get_wm_transient_for_from_reply(&transient_for, reply))
1049                         return 1;
1050         } else {
1051                 if (!xcb_get_wm_transient_for_reply(conn, xcb_get_wm_transient_for_unchecked(conn, window),
1052                                                     &transient_for, NULL))
1053                         return 1;
1054         }
1055
1056         if (client->floating == FLOATING_AUTO_OFF) {
1057                 DLOG("This is a popup window, putting into floating\n");
1058                 toggle_floating_mode(conn, client, true);
1059         }
1060
1061         return 1;
1062 }
1063
1064 /*
1065  * Handles changes of the WM_CLIENT_LEADER atom which specifies if this is a
1066  * toolwindow (or similar) and to which window it belongs (logical parent).
1067  *
1068  */
1069 int handle_clientleader_change(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
1070                         xcb_atom_t name, xcb_get_property_reply_t *prop) {
1071         if (prop == NULL) {
1072                 prop = xcb_get_property_reply(conn, xcb_get_property_unchecked(conn,
1073                                         false, window, WM_CLIENT_LEADER, WINDOW, 0, 32), NULL);
1074                 if (prop == NULL)
1075                         return 1;
1076         }
1077
1078         Client *client = table_get(&by_child, window);
1079         if (client == NULL)
1080                 return 1;
1081
1082         xcb_window_t *leader = xcb_get_property_value(prop);
1083         if (leader == NULL)
1084                 return 1;
1085
1086         DLOG("Client leader changed to %08x\n", *leader);
1087
1088         client->leader = *leader;
1089
1090         return 1;
1091 }