]> git.sur5r.net Git - i3/i3/blob - src/handlers.c
Bugfix: Correctly raise the currently focused client when going into stack mode
[i3/i3] / src / handlers.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  */
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
21 #include <X11/XKBlib.h>
22
23 #include "i3.h"
24 #include "debug.h"
25 #include "table.h"
26 #include "layout.h"
27 #include "commands.h"
28 #include "data.h"
29 #include "xcb.h"
30 #include "util.h"
31 #include "xinerama.h"
32 #include "config.h"
33 #include "queue.h"
34 #include "resize.h"
35 #include "client.h"
36 #include "manage.h"
37 #include "floating.h"
38
39 /* After mapping/unmapping windows, a notify event is generated. However, we don’t want it,
40    since it’d trigger an infinite loop of switching between the different windows when
41    changing workspaces */
42 static SLIST_HEAD(ignore_head, Ignore_Event) ignore_events;
43
44 static void add_ignore_event(const int sequence) {
45         struct Ignore_Event *event = smalloc(sizeof(struct Ignore_Event));
46
47         event->sequence = sequence;
48         event->added = time(NULL);
49
50         LOG("Adding sequence %d to ignorelist\n", sequence);
51
52         SLIST_INSERT_HEAD(&ignore_events, event, ignore_events);
53 }
54
55 /*
56  * Checks if the given sequence is ignored and returns true if so.
57  *
58  */
59 static bool event_is_ignored(const int sequence) {
60         struct Ignore_Event *event;
61         time_t now = time(NULL);
62         for (event = SLIST_FIRST(&ignore_events); event != SLIST_END(&ignore_events);) {
63                 if ((now - event->added) > 5) {
64                         struct Ignore_Event *save = event;
65                         event = SLIST_NEXT(event, ignore_events);
66                         SLIST_REMOVE(&ignore_events, save, Ignore_Event, ignore_events);
67                         free(save);
68                 } else event = SLIST_NEXT(event, ignore_events);
69         }
70
71         SLIST_FOREACH(event, &ignore_events, ignore_events) {
72                 if (event->sequence == sequence) {
73                         LOG("Ignoring event (sequence %d)\n", sequence);
74                         SLIST_REMOVE(&ignore_events, event, Ignore_Event, ignore_events);
75                         free(event);
76                         return true;
77                 }
78         }
79
80         return false;
81 }
82
83 /*
84  * Due to bindings like Mode_switch + <a>, we need to bind some keys in XCB_GRAB_MODE_SYNC.
85  * Therefore, we just replay all key presses.
86  *
87  */
88 int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
89         LOG("got key release, just passing\n");
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         LOG("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         LOG("(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         LOG("(removed upper 8 bits, state = %d)\n", state_filtered);
110
111         /* We need to get the keysym group (There are group 1 to group 4, each holding
112            two keysyms (without shift and with shift) using Xkb because X fails to
113            provide them reliably (it works in Xephyr, it does not in real X) */
114         XkbStateRec state;
115         if (XkbGetState(xkbdpy, XkbUseCoreKbd, &state) == Success && (state.group+1) == 2)
116                 state_filtered |= BIND_MODE_SWITCH;
117
118         LOG("(checked mode_switch, state %d)\n", state_filtered);
119
120         /* Find the binding */
121         Binding *bind;
122         TAILQ_FOREACH(bind, &bindings, bindings)
123                 if (bind->keycode == event->detail && bind->mods == state_filtered)
124                         break;
125
126         /* No match? Then it was an actively grabbed key, that is with Mode_switch, and
127            the user did not press Mode_switch, so just pass it… */
128         if (bind == TAILQ_END(&bindings)) {
129                 xcb_allow_events(conn, ReplayKeyboard, event->time);
130                 xcb_flush(conn);
131                 return 1;
132         }
133
134         parse_command(conn, bind->command);
135         if (state_filtered & BIND_MODE_SWITCH) {
136                 LOG("Mode_switch -> allow_events(SyncKeyboard)\n");
137                 xcb_allow_events(conn, SyncKeyboard, event->time);
138                 xcb_flush(conn);
139         }
140         return 1;
141 }
142
143
144 /*
145  * When the user moves the mouse pointer onto a window, this callback gets called.
146  *
147  */
148 int handle_enter_notify(void *ignored, xcb_connection_t *conn, xcb_enter_notify_event_t *event) {
149         LOG("enter_notify for %08x, mode = %d, detail %d, serial %d\n", event->event, event->mode, event->detail, event->sequence);
150         if (event->mode != XCB_NOTIFY_MODE_NORMAL) {
151                 LOG("This was not a normal notify, ignoring\n");
152                 return 1;
153         }
154         /* Some events are not interesting, because they were not generated actively by the
155            user, but by reconfiguration of windows */
156         if (event_is_ignored(event->sequence))
157                 return 1;
158
159         /* This was either a focus for a client’s parent (= titlebar)… */
160         Client *client = table_get(&by_parent, event->event);
161         /* …or the client itself */
162         if (client == NULL)
163                 client = table_get(&by_child, event->event);
164
165         /* Check for stack windows */
166         if (client == NULL) {
167                 struct Stack_Window *stack_win;
168                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
169                         if (stack_win->window == event->event) {
170                                 client = stack_win->container->currently_focused;
171                                 break;
172                         }
173         }
174
175
176         /* If not, then the user moved his cursor to the root window. In that case, we adjust c_ws */
177         if (client == NULL) {
178                 LOG("Getting screen at %d x %d\n", event->root_x, event->root_y);
179                 i3Screen *screen = get_screen_containing(event->root_x, event->root_y);
180                 if (screen == NULL) {
181                         LOG("ERROR: No such screen\n");
182                         return 0;
183                 }
184                 c_ws->current_row = current_row;
185                 c_ws->current_col = current_col;
186                 c_ws = &workspaces[screen->current_workspace];
187                 current_row = c_ws->current_row;
188                 current_col = c_ws->current_col;
189                 LOG("We're now on virtual screen number %d\n", screen->num);
190                 return 1;
191         }
192
193         /* Do plausibility checks: This event may be useless for us if it occurs on a window
194            which is in a stacked container but not the focused one */
195         if (client->container != NULL &&
196             client->container->mode == MODE_STACK &&
197             client->container->currently_focused != client) {
198                 LOG("Plausibility check says: no\n");
199                 return 1;
200         }
201
202         if (client->workspace != c_ws && client->workspace->screen == c_ws->screen) {
203                 /* This can happen when a client gets assigned to a different workspace than
204                  * the current one (see src/mainx.c:reparent_window). Shortly after it was created,
205                  * an enter_notify will follow. */
206                 LOG("enter_notify for a client on a different workspace but the same screen, ignoring\n");
207                 return 1;
208         }
209
210         set_focus(conn, client, false);
211
212         return 1;
213 }
214
215 /*
216  * Checks if the button press was on a stack window, handles focus setting and returns true
217  * if so, or false otherwise.
218  *
219  */
220 static bool button_press_stackwin(xcb_connection_t *conn, xcb_button_press_event_t *event) {
221         struct Stack_Window *stack_win;
222         SLIST_FOREACH(stack_win, &stack_wins, stack_windows) {
223                 if (stack_win->window != event->event)
224                         continue;
225
226                 /* A stack window was clicked, we check if it was button4 or button5
227                    which are scroll up / scroll down. */
228                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
229                         direction_t direction = (event->detail == XCB_BUTTON_INDEX_4 ? D_UP : D_DOWN);
230                         focus_window_in_container(conn, CUR_CELL, direction);
231                         return true;
232                 }
233
234                 /* It was no scrolling, so we calculate the destination client by
235                    dividing the Y position of the event through the height of a window
236                    decoration and then set the focus to this client. */
237                 i3Font *font = load_font(conn, config.font);
238                 int decoration_height = (font->height + 2 + 2);
239                 int destination = (event->event_y / decoration_height),
240                     c = 0;
241                 Client *client;
242
243                 LOG("Click on stack_win for client %d\n", destination);
244                 CIRCLEQ_FOREACH(client, &(stack_win->container->clients), clients)
245                         if (c++ == destination) {
246                                 set_focus(conn, client, true);
247                                 return true;
248                         }
249
250                 return true;
251         }
252
253         return false;
254 }
255
256 /*
257  * Checks if the button press was on a bar, switches to the workspace and returns true
258  * if so, or false otherwise.
259  *
260  */
261 static bool button_press_bar(xcb_connection_t *conn, xcb_button_press_event_t *event) {
262         i3Screen *screen;
263         TAILQ_FOREACH(screen, virtual_screens, screens) {
264                 if (screen->bar != event->event)
265                         continue;
266
267                 LOG("Click on a bar\n");
268
269                 /* Check if the button was one of button4 or button5 (scroll up / scroll down) */
270                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
271                         int add = (event->detail == XCB_BUTTON_INDEX_4 ? -1 : 1);
272                         for (int i = c_ws->num + add; (i >= 0) && (i < 10); i += add)
273                                 if (workspaces[i].screen == screen) {
274                                         show_workspace(conn, i+1);
275                                         return true;
276                                 }
277                         return true;
278                 }
279                 i3Font *font = load_font(conn, config.font);
280                 int workspace = event->event_x / (font->height + 6),
281                     c = 0;
282                 /* Because workspaces can be on different screens, we need to loop
283                    through all of them and decide to count it based on its ->screen */
284                 for (int i = 0; i < 10; i++)
285                         if ((workspaces[i].screen == screen) && (c++ == workspace)) {
286                                 show_workspace(conn, i+1);
287                                 return true;
288                         }
289                 return true;
290         }
291
292         return false;
293 }
294
295 int handle_button_press(void *ignored, xcb_connection_t *conn, xcb_button_press_event_t *event) {
296         LOG("button press!\n");
297         LOG("state = %d\n", event->state);
298         /* This was either a focus for a client’s parent (= titlebar)… */
299         Client *client = table_get(&by_child, event->event);
300         bool border_click = false;
301         if (client == NULL) {
302                 client = table_get(&by_parent, event->event);
303                 border_click = true;
304         }
305         /* See if this was a click with Mod1. If so, we need to move around
306          * the client if it was floating. if not, we just process as usual. */
307         if ((event->state & XCB_MOD_MASK_1) != 0) {
308                 if (client == NULL) {
309                         LOG("Not handling, Mod1 was pressed and no client found\n");
310                         return 1;
311                 }
312                 if (client->floating >= FLOATING_AUTO_ON) {
313                         floating_drag_window(conn, client, event);
314                         return 1;
315                 }
316         }
317
318         if (client == NULL) {
319                 /* The client was neither on a client’s titlebar nor on a client itself, maybe on a stack_window? */
320                 if (button_press_stackwin(conn, event))
321                         return 1;
322
323                 /* Or on a bar? */
324                 if (button_press_bar(conn, event))
325                         return 1;
326
327                 LOG("Could not handle this button press\n");
328                 return 1;
329         }
330
331         /* Set focus in any case */
332         set_focus(conn, client, true);
333
334         /* Let’s see if this was on the borders (= resize). If not, we’re done */
335         LOG("press button on x=%d, y=%d\n", event->event_x, event->event_y);
336         resize_orientation_t orientation = O_VERTICAL;
337         Container *con = client->container;
338         int first, second;
339
340         if (client->dock) {
341                 LOG("dock. done.\n");
342                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
343                 xcb_flush(conn);
344                 return 1;
345         }
346
347         LOG("event->event_x = %d, client->rect.width = %d\n", event->event_x, client->rect.width);
348
349         if (!border_click) {
350                 LOG("client. done.\n");
351                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
352                 /* Floating clients should be raised on click */
353                 if (client->floating >= FLOATING_AUTO_ON)
354                         xcb_raise_window(conn, client->frame);
355                 xcb_flush(conn);
356                 return 1;
357         }
358
359         /* Don’t handle events inside the titlebar, only borders are interesting */
360         i3Font *font = load_font(conn, config.font);
361         if (event->event_y >= 2 && event->event_y <= (font->height + 2 + 2)) {
362                 LOG("click on titlebar\n");
363
364                 /* Floating clients can be dragged by grabbing their titlebar */
365                 if (client->floating >= FLOATING_AUTO_ON) {
366                         /* Firstly, we raise it. Maybe the user just wanted to raise it without grabbing */
367                         xcb_raise_window(conn, client->frame);
368                         xcb_flush(conn);
369
370                         floating_drag_window(conn, client, event);
371                 }
372                 return 1;
373         }
374
375         if (client->floating >= FLOATING_AUTO_ON)
376                 return floating_border_click(conn, client, event);
377
378         if (event->event_y < 2) {
379                 /* This was a press on the top border */
380                 if (con->row == 0)
381                         return 1;
382                 first = con->row - 1;
383                 second = con->row;
384                 orientation = O_HORIZONTAL;
385         } else if (event->event_y >= (client->rect.height - 2)) {
386                 /* …bottom border */
387                 first = con->row + (con->rowspan - 1);
388                 if (!cell_exists(con->col, first) ||
389                     (first == (con->workspace->rows-1)))
390                         return 1;
391
392                 second = first + 1;
393                 orientation = O_HORIZONTAL;
394         } else if (event->event_x <= 2) {
395                 /* …left border */
396                 if (con->col == 0)
397                         return 1;
398
399                 first = con->col - 1;
400                 second = con->col;
401         } else if (event->event_x > 2) {
402                 /* …right border */
403                 first = con->col + (con->colspan - 1);
404                 LOG("column %d\n", first);
405
406                 if (!cell_exists(first, con->row) ||
407                     (first == (con->workspace->cols-1)))
408                         return 1;
409
410                 second = first + 1;
411         }
412
413         return resize_graphical_handler(conn, con->workspace, first, second, orientation, event);
414 }
415
416 /*
417  * A new window appeared on the screen (=was mapped), so let’s manage it.
418  *
419  */
420 int handle_map_request(void *prophs, xcb_connection_t *conn, xcb_map_request_event_t *event) {
421         xcb_get_window_attributes_cookie_t cookie;
422         xcb_get_window_attributes_reply_t *reply;
423
424         cookie = xcb_get_window_attributes_unchecked(conn, event->window);
425
426         if ((reply = xcb_get_window_attributes_reply(conn, cookie, NULL)) == NULL) {
427                 LOG("Could not get window attributes\n");
428                 return -1;
429         }
430
431         window_attributes_t wa = { TAG_VALUE };
432         LOG("override_redirect = %d\n", reply->override_redirect);
433         wa.u.override_redirect = reply->override_redirect;
434         LOG("window = 0x%08x, serial is %d.\n", event->window, event->sequence);
435         add_ignore_event(event->sequence);
436
437         manage_window(prophs, conn, event->window, wa);
438         return 1;
439 }
440
441 /*
442  * Configure requests are received when the application wants to resize windows on their own.
443  *
444  * We generate a synthethic configure notify event to signalize the client its "new" position.
445  *
446  */
447 int handle_configure_request(void *prophs, xcb_connection_t *conn, xcb_configure_request_event_t *event) {
448         LOG("configure-request, serial %d\n", event->sequence);
449         LOG("event->window = %08x\n", event->window);
450         LOG("application wants to be at %dx%d with %dx%d\n", event->x, event->y, event->width, event->height);
451
452         Client *client = table_get(&by_child, event->window);
453         if (client == NULL) {
454                 LOG("This client is not mapped, so we don't care and just tell the client that he will get its size\n");
455                 uint32_t mask = 0;
456                 uint32_t values[7];
457                 int c = 0;
458 #define COPY_MASK_MEMBER(mask_member, event_member) do { \
459                 if (event->value_mask & mask_member) { \
460                         mask |= mask_member; \
461                         values[c++] = event->event_member; \
462                 } \
463 } while (0)
464
465                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_X, x);
466                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_Y, y);
467                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_WIDTH, width);
468                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_HEIGHT, height);
469                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_BORDER_WIDTH, border_width);
470                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_SIBLING, sibling);
471                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_STACK_MODE, stack_mode);
472
473                 xcb_configure_window(conn, event->window, mask, values);
474                 xcb_flush(conn);
475
476                 return 1;
477         }
478
479         if (client->fullscreen) {
480                 LOG("Client is in fullscreen mode\n");
481
482                 Rect child_rect = client->container->workspace->rect;
483                 child_rect.x = child_rect.y = 0;
484                 fake_configure_notify(conn, child_rect, client->child);
485
486                 return 1;
487         }
488
489         fake_absolute_configure_notify(conn, client);
490
491         return 1;
492 }
493
494 /*
495  * Configuration notifies are only handled because we need to set up ignore for the following
496  * enter notify events
497  *
498  */
499 int handle_configure_event(void *prophs, xcb_connection_t *conn, xcb_configure_notify_event_t *event) {
500         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
501
502         LOG("handle_configure_event for window %08x\n", event->window);
503         LOG("event->type = %d, \n", event->response_type);
504         LOG("event->x = %d, ->y = %d, ->width = %d, ->height = %d\n", event->x, event->y, event->width, event->height);
505
506         /* We ignore this sequence twice because events for child and frame should be ignored */
507         add_ignore_event(event->sequence);
508         add_ignore_event(event->sequence);
509
510         if (event->event == root) {
511                 LOG("reconfigure of the root window, need to xinerama\n");
512                 /* FIXME: Somehow, this is occuring too often. Therefore, we check for 0/0,
513                    but is there a better way? */
514                 if (event->x == 0 && event->y == 0)
515                         xinerama_requery_screens(conn);
516                 return 1;
517         }
518
519         return 1;
520 }
521
522 /*
523  * Our window decorations were unmapped. That means, the window will be killed now,
524  * so we better clean up before.
525  *
526  */
527 int handle_unmap_notify_event(void *data, xcb_connection_t *conn, xcb_unmap_notify_event_t *event) {
528         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
529
530         add_ignore_event(event->sequence);
531
532         Client *client = table_get(&by_child, event->window);
533         /* First, we need to check if the client is awaiting an unmap-request which
534            was generated by us reparenting the window. In that case, we just ignore it. */
535         if (client != NULL && client->awaiting_useless_unmap) {
536                 LOG("Dropping this unmap request, it was generated by reparenting\n");
537                 client->awaiting_useless_unmap = false;
538                 return 1;
539         }
540
541         LOG("event->window = %08x, event->event = %08x\n", event->window, event->event);
542         LOG("UnmapNotify for 0x%08x (received from 0x%08x)\n", event->window, event->event);
543         if (client == NULL) {
544                 LOG("not a managed window. Ignoring.\n");
545
546                 /* This was most likely the destroyed frame of a client which is
547                  * currently being unmapped, so we add this sequence (again!) to
548                  * the ignore list (enter_notify events will get sent for both,
549                  * the child and its frame). */
550                 add_ignore_event(event->sequence);
551
552                 return 0;
553         }
554
555         client = table_remove(&by_child, event->window);
556
557         if (client->name != NULL)
558                 free(client->name);
559
560         /* Clients without a container are either floating or dock windows */
561         if (client->container != NULL) {
562                 Container *con = client->container;
563
564                 /* If this was the fullscreen client, we need to unset it */
565                 if (client->fullscreen)
566                         con->workspace->fullscreen_client = NULL;
567
568                 /* Remove the client from the list of clients */
569                 client_remove_from_container(conn, client, con, true);
570
571                 /* Set focus to the last focused client in this container */
572                 con->currently_focused = get_last_focused_client(conn, con, NULL);
573
574                 /* Only if this is the active container, we need to really change focus */
575                 if ((con->currently_focused != NULL) && ((con == CUR_CELL) || client->fullscreen))
576                         set_focus(conn, con->currently_focused, true);
577         } else if (client->floating >= FLOATING_AUTO_ON) {
578                 SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
579         }
580
581         if (client->dock) {
582                 LOG("Removing from dock clients\n");
583                 SLIST_REMOVE(&(client->workspace->screen->dock_clients), client, Client, dock_clients);
584         }
585
586         if (client->floating) {
587                 LOG("Removing from floating clients\n");
588                 TAILQ_REMOVE(&(client->workspace->floating_clients), client, floating_clients);
589         }
590
591         LOG("child of 0x%08x.\n", client->frame);
592         xcb_reparent_window(conn, client->child, root, 0, 0);
593         xcb_destroy_window(conn, client->frame);
594         xcb_flush(conn);
595         table_remove(&by_parent, client->frame);
596
597         if (client->container != NULL) {
598                 cleanup_table(conn, client->container->workspace);
599                 fix_colrowspan(conn, client->container->workspace);
600         }
601
602         /* Let’s see how many clients there are left on the workspace to delete it if it’s empty */
603         bool workspace_empty = SLIST_EMPTY(&(client->workspace->focus_stack));
604         bool workspace_active = false;
605         Client *to_focus = (!workspace_empty ? SLIST_FIRST(&(client->workspace->focus_stack)) : NULL);
606
607         /* If this workspace is currently active, we don’t delete it */
608         i3Screen *screen;
609         TAILQ_FOREACH(screen, virtual_screens, screens)
610                 if (screen->current_workspace == client->workspace->num) {
611                         workspace_active = true;
612                         workspace_empty = false;
613                         break;
614                 }
615
616         if (workspace_empty) {
617                 LOG("setting ws to NULL for workspace %d (%p)\n", client->workspace->num,
618                                 client->workspace);
619                 client->workspace->screen = NULL;
620         }
621
622         free(client);
623
624         render_layout(conn);
625
626         /* Ensure the focus is set to the next client in the focus stack */
627         if (workspace_active && to_focus != NULL)
628                 set_focus(conn, to_focus, true);
629
630         return 1;
631 }
632
633 /*
634  * Called when a window changes its title
635  *
636  */
637 int handle_windowname_change(void *data, xcb_connection_t *conn, uint8_t state,
638                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
639         LOG("window's name changed.\n");
640         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
641                 LOG("_NET_WM_NAME not specified, not changing\n");
642                 return 1;
643         }
644         Client *client = table_get(&by_child, window);
645         if (client == NULL)
646                 return 1;
647
648         /* Save the old pointer to make the update atomic */
649         char *new_name;
650         int new_len;
651         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
652         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
653         char *ucs2_name = convert_utf8_to_ucs2(new_name, &new_len);
654         LOG("Name should change to \"%s\"\n", new_name);
655         free(new_name);
656
657         /* Check if they are the same and don’t update if so.
658            Note the use of new_len * 2 to check all bytes as each glyph takes 2 bytes.
659            Also note the use of memcmp() instead of strncmp() because the latter stops on nullbytes,
660            but UCS-2 uses nullbytes to fill up glyphs which only use one byte. */
661         if ((new_len == client->name_len) &&
662             (client->name != NULL) &&
663             (memcmp(client->name, ucs2_name, new_len * 2) == 0)) {
664                 LOG("Name did not change, not updating\n");
665                 free(ucs2_name);
666                 return 1;
667         }
668
669         char *old_name = client->name;
670         client->name = ucs2_name;
671         client->name_len = new_len;
672         client->uses_net_wm_name = true;
673
674         FREE(old_name);
675
676         /* If the client is a dock window, we don’t need to render anything */
677         if (client->dock)
678                 return 1;
679
680         if (client->container != NULL && client->container->mode == MODE_STACK)
681                 render_container(conn, client->container);
682         else decorate_window(conn, client, client->frame, client->titlegc, 0);
683         xcb_flush(conn);
684
685         return 1;
686 }
687
688 /*
689  * We handle legacy window names (titles) which are in COMPOUND_TEXT encoding. However, we
690  * just pass them along, so when containing non-ASCII characters, those will be rendering
691  * incorrectly. In order to correctly render unicode window titles in i3, an application
692  * has to set _NET_WM_NAME, which is in UTF-8 encoding.
693  *
694  * On every update, a message is put out to the user, so he may improve the situation and
695  * update applications which display filenames in their title to correctly use
696  * _NET_WM_NAME and therefore support unicode.
697  *
698  */
699 int handle_windowname_change_legacy(void *data, xcb_connection_t *conn, uint8_t state,
700                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
701         LOG("window's name changed (legacy).\n");
702         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
703                 LOG("prop == NULL\n");
704                 return 1;
705         }
706         Client *client = table_get(&by_child, window);
707         if (client == NULL)
708                 return 1;
709
710         if (client->uses_net_wm_name) {
711                 LOG("This client is capable of _NET_WM_NAME, ignoring legacy name\n");
712                 return 1;
713         }
714
715         /* Save the old pointer to make the update atomic */
716         char *new_name;
717         if (asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop)) == -1) {
718                 perror("Could not get old name");
719                 LOG("Could not get old name\n");
720                 return 1;
721         }
722         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
723         LOG("Name should change to \"%s\"\n", new_name);
724
725         /* Check if they are the same and don’t update if so. */
726         if (client->name != NULL &&
727             strlen(new_name) == strlen(client->name) &&
728             strcmp(client->name, new_name) == 0) {
729                 LOG("Name did not change, not updating\n");
730                 free(new_name);
731                 return 1;
732         }
733
734         LOG("Using legacy window title. Note that in order to get Unicode window titles in i3,"
735             "the application has to set _NET_WM_NAME which is in UTF-8 encoding.\n");
736
737         char *old_name = client->name;
738         client->name = new_name;
739         client->name_len = -1;
740
741         if (old_name != NULL)
742                 free(old_name);
743
744         /* If the client is a dock window, we don’t need to render anything */
745         if (client->dock)
746                 return 1;
747
748         if (client->container != NULL && client->container->mode == MODE_STACK)
749                 render_container(conn, client->container);
750         else decorate_window(conn, client, client->frame, client->titlegc, 0);
751         xcb_flush(conn);
752
753         return 1;
754 }
755
756 /*
757  * Updates the client’s WM_CLASS property
758  *
759  */
760 int handle_windowclass_change(void *data, xcb_connection_t *conn, uint8_t state,
761                              xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
762         LOG("window class changed\n");
763         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
764                 LOG("prop == NULL\n");
765                 return 1;
766         }
767         Client *client = table_get(&by_child, window);
768         if (client == NULL)
769                 return 1;
770         char *new_class;
771         if (asprintf(&new_class, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop)) == -1) {
772                 perror("Could not get window class");
773                 LOG("Could not get window class\n");
774                 return 1;
775         }
776
777         LOG("changed to %s\n", new_class);
778         char *old_class = client->window_class;
779         client->window_class = new_class;
780         FREE(old_class);
781
782         if (!client->initialized) {
783                 LOG("Client is not yet initialized, not putting it to floating\n");
784                 return 1;
785         }
786
787         if (strcmp(new_class, "tools") == 0 || strcmp(new_class, "Dialog") == 0) {
788                 LOG("tool/dialog window, should we put it floating?\n");
789                 if (client->floating == FLOATING_AUTO_OFF)
790                         toggle_floating_mode(conn, client, true);
791         }
792
793         return 1;
794 }
795
796 /*
797  * Expose event means we should redraw our windows (= title bar)
798  *
799  */
800 int handle_expose_event(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
801         /* event->count is the number of minimum remaining expose events for this window, so we
802            skip all events but the last one */
803         if (event->count != 0)
804                 return 1;
805         LOG("window = %08x\n", event->window);
806
807         Client *client = table_get(&by_parent, event->window);
808         if (client == NULL) {
809                 /* There was no client in the table, so this is probably an expose event for
810                    one of our stack_windows. */
811                 struct Stack_Window *stack_win;
812                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
813                         if (stack_win->window == event->window) {
814                                 render_container(conn, stack_win->container);
815                                 return 1;
816                         }
817
818                 /* …or one of the bars? */
819                 i3Screen *screen;
820                 TAILQ_FOREACH(screen, virtual_screens, screens)
821                         if (screen->bar == event->window)
822                                 render_layout(conn);
823                 return 1;
824         }
825
826         LOG("got client %s\n", client->name);
827         if (client->dock) {
828                 LOG("this is a dock\n");
829                 return 1;
830         }
831
832         if (client->container == NULL || client->container->mode != MODE_STACK)
833                 decorate_window(conn, client, client->frame, client->titlegc, 0);
834         else {
835                 uint32_t background_color;
836                 /* Distinguish if the window is currently focused… */
837                 if (CUR_CELL->currently_focused == client)
838                         background_color = config.client.focused.background;
839                 /* …or if it is the focused window in a not focused container */
840                 else background_color = config.client.focused_inactive.background;
841
842                 /* Set foreground color to current focused color, line width to 2 */
843                 uint32_t values[] = {background_color, 2};
844                 xcb_change_gc(conn, client->titlegc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
845
846                 /* Draw the border, the ±1 is for line width = 2 */
847                 xcb_point_t points[] = {{1, 0},                                           /* left upper edge */
848                                         {1, client->rect.height-1},                       /* left bottom edge */
849                                         {client->rect.width-1, client->rect.height-1},    /* right bottom edge */
850                                         {client->rect.width-1, 0}};                       /* right upper edge */
851                 xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, client->frame, client->titlegc, 4, points);
852
853                 /* Draw a black background */
854                 xcb_change_gc_single(conn, client->titlegc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
855                 xcb_rectangle_t crect = {2, 0, client->rect.width - (2 + 2), client->rect.height - 2};
856                 xcb_poly_fill_rectangle(conn, client->frame, client->titlegc, 1, &crect);
857         }
858         xcb_flush(conn);
859         return 1;
860 }
861
862 /*
863  * Handle client messages (EWMH)
864  *
865  */
866 int handle_client_message(void *data, xcb_connection_t *conn, xcb_client_message_event_t *event) {
867         LOG("client_message\n");
868
869         if (event->type == atoms[_NET_WM_STATE]) {
870                 if (event->format != 32 || event->data.data32[1] != atoms[_NET_WM_STATE_FULLSCREEN])
871                         return 0;
872
873                 LOG("fullscreen\n");
874
875                 Client *client = table_get(&by_child, event->window);
876                 if (client == NULL)
877                         return 0;
878
879                 /* Check if the fullscreen state should be toggled */
880                 if ((client->fullscreen &&
881                      (event->data.data32[0] == _NET_WM_STATE_REMOVE ||
882                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)) ||
883                     (!client->fullscreen &&
884                      (event->data.data32[0] == _NET_WM_STATE_ADD ||
885                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)))
886                         client_toggle_fullscreen(conn, client);
887         } else {
888                 LOG("unhandled clientmessage\n");
889                 return 0;
890         }
891
892         return 1;
893 }
894
895 int handle_window_type(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
896                         xcb_atom_t atom, xcb_get_property_reply_t *property) {
897         /* TODO: Implement this one. To do this, implement a little test program which sleep(1)s
898          before changing this property. */
899         LOG("_NET_WM_WINDOW_TYPE changed, this is not yet implemented.\n");
900         return 0;
901 }
902
903 /*
904  * Handles the size hints set by a window, but currently only the part necessary for displaying
905  * clients proportionally inside their frames (mplayer for example)
906  *
907  * See ICCCM 4.1.2.3 for more details
908  *
909  */
910 int handle_normal_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
911                         xcb_atom_t name, xcb_get_property_reply_t *reply) {
912         LOG("handle_normal_hints\n");
913         Client *client = table_get(&by_child, window);
914         if (client == NULL) {
915                 LOG("No such client\n");
916                 return 1;
917         }
918         xcb_size_hints_t size_hints;
919         LOG("client is %08x / child %08x\n", client->frame, client->child);
920
921         /* If the hints were already in this event, use them, if not, request them */
922         if (reply != NULL)
923                 xcb_get_wm_size_hints_from_reply(&size_hints, reply);
924         else
925                 xcb_get_wm_normal_hints_reply(conn, xcb_get_wm_normal_hints_unchecked(conn, client->child), &size_hints, NULL);
926
927         if ((size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE)) {
928                 LOG("min size set\n");
929                 LOG("gots min_width = %d, min_height = %d\n", size_hints.min_width, size_hints.min_height);
930         }
931
932         /* If no aspect ratio was set or if it was invalid, we ignore the hints */
933         if (!(size_hints.flags & XCB_SIZE_HINT_P_ASPECT) ||
934             (size_hints.min_aspect_num <= 0) ||
935             (size_hints.min_aspect_den <= 0)) {
936                 LOG("No aspect ratio set, ignoring\n");
937                 return 1;
938         }
939
940         LOG("window is %08x / %s\n", client->child, client->name);
941
942         int base_width = 0, base_height = 0;
943
944         /* base_width/height are the desired size of the window.
945            We check if either the program-specified size or the program-specified
946            min-size is available */
947         if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
948                 base_width = size_hints.base_width;
949                 base_height = size_hints.base_height;
950         } else if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
951                 base_width = size_hints.min_width;
952                 base_height = size_hints.min_height;
953         }
954
955         double width = client->rect.width - base_width;
956         double height = client->rect.height - base_height;
957         /* Convert numerator/denominator to a double */
958         double min_aspect = (double)size_hints.min_aspect_num / size_hints.min_aspect_den;
959         double max_aspect = (double)size_hints.max_aspect_num / size_hints.min_aspect_den;
960
961         LOG("min_aspect = %f, max_aspect = %f\n", min_aspect, max_aspect);
962         LOG("width = %f, height = %f\n", width, height);
963
964         /* Sanity checks, this is user-input, in a way */
965         if (max_aspect <= 0 || min_aspect <= 0 || height == 0 || (width / height) <= 0)
966                 return 1;
967
968         /* Check if we need to set proportional_* variables using the correct ratio */
969         if ((width / height) < min_aspect) {
970                 client->proportional_width = width;
971                 client->proportional_height = width / min_aspect;
972         } else if ((width / height) > max_aspect) {
973                 client->proportional_width = width;
974                 client->proportional_height = width / max_aspect;
975         } else return 1;
976
977         client->force_reconfigure = true;
978
979         if (client->container != NULL) {
980                 render_container(conn, client->container);
981                 xcb_flush(conn);
982         }
983
984         return 1;
985 }
986
987 /*
988  * Handles the transient for hints set by a window, signalizing that this window is a popup window
989  * for some other window.
990  *
991  * See ICCCM 4.1.2.6 for more details
992  *
993  */
994 int handle_transient_for(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
995                          xcb_atom_t name, xcb_get_property_reply_t *reply) {
996         LOG("Transient hint!\n");
997         Client *client = table_get(&by_child, window);
998         if (client == NULL) {
999                 LOG("No such client\n");
1000                 return 1;
1001         }
1002
1003         xcb_window_t transient_for;
1004
1005         if (reply != NULL) {
1006                 if (!xcb_get_wm_transient_for_from_reply(&transient_for, reply)) {
1007                         LOG("Not transient for any window\n");
1008                         return 1;
1009                 }
1010         } else {
1011                 if (!xcb_get_wm_transient_for_reply(conn, xcb_get_wm_transient_for_unchecked(conn, window),
1012                                                     &transient_for, NULL)) {
1013                         LOG("Not transient for any window\n");
1014                         return 1;
1015                 }
1016         }
1017
1018         if (client->floating == FLOATING_AUTO_OFF) {
1019                 LOG("This is a popup window, putting into floating\n");
1020                 toggle_floating_mode(conn, client, true);
1021         }
1022
1023         return 1;
1024 }