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