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