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