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