]> git.sur5r.net Git - i3/i3/blob - src/handlers.c
5d171403d5703a7f3b2cd5879e072dc41f993152
[i3/i3] / src / handlers.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  */
11 #include <stdio.h>
12 #include <assert.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <time.h>
16
17 #include <xcb/xcb.h>
18 #include <xcb/xcb_atom.h>
19 #include <xcb/xcb_icccm.h>
20
21 #include <X11/XKBlib.h>
22
23 #include "i3.h"
24 #include "debug.h"
25 #include "table.h"
26 #include "layout.h"
27 #include "commands.h"
28 #include "data.h"
29 #include "xcb.h"
30 #include "util.h"
31 #include "xinerama.h"
32 #include "config.h"
33 #include "queue.h"
34 #include "resize.h"
35 #include "client.h"
36 #include "manage.h"
37 #include "floating.h"
38 #include "workspace.h"
39
40 /* After mapping/unmapping windows, a notify event is generated. However, we don’t want it,
41    since it’d trigger an infinite loop of switching between the different windows when
42    changing workspaces */
43 static SLIST_HEAD(ignore_head, Ignore_Event) ignore_events;
44
45 static void add_ignore_event(const int sequence) {
46         struct Ignore_Event *event = smalloc(sizeof(struct Ignore_Event));
47
48         event->sequence = sequence;
49         event->added = time(NULL);
50
51         SLIST_INSERT_HEAD(&ignore_events, event, ignore_events);
52 }
53
54 /*
55  * Checks if the given sequence is ignored and returns true if so.
56  *
57  */
58 static bool event_is_ignored(const int sequence) {
59         struct Ignore_Event *event;
60         time_t now = time(NULL);
61         for (event = SLIST_FIRST(&ignore_events); event != SLIST_END(&ignore_events);) {
62                 if ((now - event->added) > 5) {
63                         struct Ignore_Event *save = event;
64                         event = SLIST_NEXT(event, ignore_events);
65                         SLIST_REMOVE(&ignore_events, save, Ignore_Event, ignore_events);
66                         free(save);
67                 } else event = SLIST_NEXT(event, ignore_events);
68         }
69
70         SLIST_FOREACH(event, &ignore_events, ignore_events) {
71                 if (event->sequence == sequence) {
72                         SLIST_REMOVE(&ignore_events, event, Ignore_Event, ignore_events);
73                         free(event);
74                         return true;
75                 }
76         }
77
78         return false;
79 }
80
81 /*
82  * Due to bindings like Mode_switch + <a>, we need to bind some keys in XCB_GRAB_MODE_SYNC.
83  * Therefore, we just replay all key presses.
84  *
85  */
86 int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
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, state raw = %d\n", event->detail, event->state);
99
100         /* Remove the numlock bit, all other bits are modifiers we can bind to */
101         uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
102         LOG("(removed numlock, state = %d)\n", state_filtered);
103         /* Only use the lower 8 bits of the state (modifier masks) so that mouse
104          * button masks are filtered out */
105         state_filtered &= 0xFF;
106         LOG("(removed upper 8 bits, state = %d)\n", state_filtered);
107
108         /* We need to get the keysym group (There are group 1 to group 4, each holding
109            two keysyms (without shift and with shift) using Xkb because X fails to
110            provide them reliably (it works in Xephyr, it does not in real X) */
111         XkbStateRec state;
112         if (XkbGetState(xkbdpy, XkbUseCoreKbd, &state) == Success && (state.group+1) == 2)
113                 state_filtered |= BIND_MODE_SWITCH;
114
115         LOG("(checked mode_switch, state %d)\n", state_filtered);
116
117         /* Find the binding */
118         Binding *bind;
119         TAILQ_FOREACH(bind, &bindings, bindings) {
120                 /* First compare the modifiers */
121                 if (bind->mods != state_filtered)
122                         continue;
123
124                 /* If a symbol was specified by the user, we need to look in
125                  * the array of translated keycodes for the event’s keycode */
126                 if (bind->symbol != NULL) {
127                         if (memmem(bind->translated_to,
128                                    bind->number_keycodes * sizeof(xcb_keycode_t),
129                                    &(event->detail), sizeof(xcb_keycode_t)) != NULL)
130                                 break;
131                 } else {
132                         /* This case is easier: The user specified a keycode */
133                         if (bind->keycode == event->detail)
134                                 break;
135                 }
136         }
137
138         /* No match? Then it was an actively grabbed key, that is with Mode_switch, and
139            the user did not press Mode_switch, so just pass it… */
140         if (bind == TAILQ_END(&bindings)) {
141                 xcb_allow_events(conn, ReplayKeyboard, event->time);
142                 xcb_flush(conn);
143                 return 1;
144         }
145
146         parse_command(conn, bind->command);
147         if (state_filtered & BIND_MODE_SWITCH) {
148                 LOG("Mode_switch -> allow_events(SyncKeyboard)\n");
149                 xcb_allow_events(conn, SyncKeyboard, event->time);
150                 xcb_flush(conn);
151         }
152         return 1;
153 }
154
155 /*
156  * Called with coordinates of an enter_notify event or motion_notify event
157  * to check if the user crossed virtual screen boundaries and adjust the
158  * current workspace, if so.
159  *
160  */
161 static void check_crossing_screen_boundary(uint32_t x, uint32_t y) {
162         i3Screen *screen;
163
164         if ((screen = get_screen_containing(x, y)) == NULL) {
165                 LOG("ERROR: No such screen\n");
166                 return;
167         }
168         if (screen == c_ws->screen)
169                 return;
170
171         c_ws->current_row = current_row;
172         c_ws->current_col = current_col;
173         c_ws = &workspaces[screen->current_workspace];
174         current_row = c_ws->current_row;
175         current_col = c_ws->current_col;
176         LOG("We're now on virtual screen number %d\n", screen->num);
177 }
178
179 /*
180  * When the user moves the mouse pointer onto a window, this callback gets called.
181  *
182  */
183 int handle_enter_notify(void *ignored, xcb_connection_t *conn, xcb_enter_notify_event_t *event) {
184         LOG("enter_notify for %08x, mode = %d, detail %d, serial %d\n", event->event, event->mode, event->detail, event->sequence);
185         if (event->mode != XCB_NOTIFY_MODE_NORMAL) {
186                 LOG("This was not a normal notify, ignoring\n");
187                 return 1;
188         }
189         /* Some events are not interesting, because they were not generated actively by the
190            user, but by reconfiguration of windows */
191         if (event_is_ignored(event->sequence))
192                 return 1;
193
194         /* This was either a focus for a client’s parent (= titlebar)… */
195         Client *client = table_get(&by_parent, event->event);
196         /* …or the client itself */
197         if (client == NULL)
198                 client = table_get(&by_child, event->event);
199
200         /* Check for stack windows */
201         if (client == NULL) {
202                 struct Stack_Window *stack_win;
203                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
204                         if (stack_win->window == event->event) {
205                                 client = stack_win->container->currently_focused;
206                                 break;
207                         }
208         }
209
210
211         /* If not, then the user moved his cursor to the root window. In that case, we adjust c_ws */
212         if (client == NULL) {
213                 LOG("Getting screen at %d x %d\n", event->root_x, event->root_y);
214                 check_crossing_screen_boundary(event->root_x, event->root_y);
215                 return 1;
216         }
217
218         /* Do plausibility checks: This event may be useless for us if it occurs on a window
219            which is in a stacked container but not the focused one */
220         if (client->container != NULL &&
221             client->container->mode == MODE_STACK &&
222             client->container->currently_focused != client) {
223                 LOG("Plausibility check says: no\n");
224                 return 1;
225         }
226
227         if (client->workspace != c_ws && client->workspace->screen == c_ws->screen) {
228                 /* This can happen when a client gets assigned to a different workspace than
229                  * the current one (see src/mainx.c:reparent_window). Shortly after it was created,
230                  * an enter_notify will follow. */
231                 LOG("enter_notify for a client on a different workspace but the same screen, ignoring\n");
232                 return 1;
233         }
234
235         set_focus(conn, client, false);
236
237         return 1;
238 }
239
240 /*
241  * When the user moves the mouse but does not change the active window
242  * (e.g. when having no windows opened but moving mouse on the root screen
243  * and crossing virtual screen boundaries), this callback gets called.
244  *
245  */
246 int handle_motion_notify(void *ignored, xcb_connection_t *conn, xcb_motion_notify_event_t *event) {
247         /* Skip events where the pointer was over a child window, we are only
248          * interested in events on the root window. */
249         if (event->child != 0)
250                 return 1;
251
252         check_crossing_screen_boundary(event->root_x, event->root_y);
253
254         return 1;
255 }
256
257 /*
258  * Called when the keyboard mapping changes (for example by using Xmodmap),
259  * we need to update our key bindings then (re-translate symbols).
260  *
261  */
262 int handle_mapping_notify(void *ignored, xcb_connection_t *conn, xcb_mapping_notify_event_t *event) {
263         if (event->request != XCB_MAPPING_KEYBOARD &&
264             event->request != XCB_MAPPING_MODIFIER)
265                 return 0;
266
267         LOG("Received mapping_notify for keyboard or modifier mapping, re-grabbing keys\n");
268         xcb_refresh_keyboard_mapping(keysyms, event);
269
270         xcb_get_numlock_mask(conn);
271
272         ungrab_all_keys(conn);
273         grab_all_keys(conn);
274
275         return 0;
276 }
277
278 /*
279  * Checks if the button press was on a stack window, handles focus setting and returns true
280  * if so, or false otherwise.
281  *
282  */
283 static bool button_press_stackwin(xcb_connection_t *conn, xcb_button_press_event_t *event) {
284         struct Stack_Window *stack_win;
285         SLIST_FOREACH(stack_win, &stack_wins, stack_windows) {
286                 if (stack_win->window != event->event)
287                         continue;
288
289                 /* A stack window was clicked, we check if it was button4 or button5
290                    which are scroll up / scroll down. */
291                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
292                         direction_t direction = (event->detail == XCB_BUTTON_INDEX_4 ? D_UP : D_DOWN);
293                         focus_window_in_container(conn, CUR_CELL, direction);
294                         return true;
295                 }
296
297                 /* It was no scrolling, so we calculate the destination client by
298                    dividing the Y position of the event through the height of a window
299                    decoration and then set the focus to this client. */
300                 i3Font *font = load_font(conn, config.font);
301                 int decoration_height = (font->height + 2 + 2);
302                 int destination = (event->event_y / decoration_height),
303                     c = 0,
304                     num_clients = 0;
305                 Client *client;
306
307                 CIRCLEQ_FOREACH(client, &(stack_win->container->clients), clients)
308                         num_clients++;
309
310                 if (stack_win->container->mode == MODE_TABBED)
311                         destination = (event->event_x / (stack_win->container->width / num_clients));
312
313                 LOG("Click on stack_win for client %d\n", destination);
314                 CIRCLEQ_FOREACH(client, &(stack_win->container->clients), clients)
315                         if (c++ == destination) {
316                                 set_focus(conn, client, true);
317                                 return true;
318                         }
319
320                 return true;
321         }
322
323         return false;
324 }
325
326 /*
327  * Checks if the button press was on a bar, switches to the workspace and returns true
328  * if so, or false otherwise.
329  *
330  */
331 static bool button_press_bar(xcb_connection_t *conn, xcb_button_press_event_t *event) {
332         i3Screen *screen;
333         TAILQ_FOREACH(screen, virtual_screens, screens) {
334                 if (screen->bar != event->event)
335                         continue;
336
337                 LOG("Click on a bar\n");
338
339                 /* Check if the button was one of button4 or button5 (scroll up / scroll down) */
340                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
341                         int add = (event->detail == XCB_BUTTON_INDEX_4 ? -1 : 1);
342                         for (int i = c_ws->num + add; (i >= 0) && (i < 10); i += add)
343                                 if (workspaces[i].screen == screen) {
344                                         workspace_show(conn, i+1);
345                                         return true;
346                                 }
347                         return true;
348                 }
349                 int drawn = 0;
350                 /* Because workspaces can be on different screens, we need to loop
351                    through all of them and decide to count it based on its ->screen */
352                 for (int i = 0; i < 10; i++) {
353                         if (workspaces[i].screen != screen)
354                                 continue;
355                         LOG("Checking if click was on workspace %d with drawn = %d, tw = %d\n",
356                                         i, drawn, workspaces[i].text_width);
357                         if (event->event_x > (drawn + 1) &&
358                             event->event_x <= (drawn + 1 + workspaces[i].text_width + 5 + 5)) {
359                                 workspace_show(conn, i+1);
360                                 return true;
361                         }
362
363                         drawn += workspaces[i].text_width + 5 + 5 + 2;
364                 }
365                 return true;
366         }
367
368         return false;
369 }
370
371 int handle_button_press(void *ignored, xcb_connection_t *conn, xcb_button_press_event_t *event) {
372         LOG("Button %d pressed\n", event->state);
373         /* This was either a focus for a client’s parent (= titlebar)… */
374         Client *client = table_get(&by_child, event->event);
375         bool border_click = false;
376         if (client == NULL) {
377                 client = table_get(&by_parent, event->event);
378                 border_click = true;
379         }
380         /* See if this was a click with the configured modifier. If so, we need
381          * to move around the client if it was floating. if not, we just process
382          * as usual. */
383         if (config.floating_modifier != 0 &&
384             (event->state & config.floating_modifier) != 0) {
385                 if (client == NULL) {
386                         LOG("Not handling, floating_modifier was pressed and no client found\n");
387                         return 1;
388                 }
389                 if (client_is_floating(client)) {
390                         LOG("button %d pressed\n", event->detail);
391                         if (event->detail == 1) {
392                                 LOG("left mouse button, dragging\n");
393                                 floating_drag_window(conn, client, event);
394                         } else if (event->detail == 3) {
395                                 LOG("right mouse button\n");
396                                 floating_resize_window(conn, client, event);
397                         }
398                         return 1;
399                 } else {
400                         /* The client is in tiling layout. We can still
401                          * initiate a resize with the right mouse button,
402                          * by chosing the border which is the most near one
403                          * to the position of the mouse pointer */
404                         if (event->detail == 3) {
405                                 int to_right = client->rect.width - event->event_x,
406                                     to_left = event->event_x,
407                                     to_top = event->event_y,
408                                     to_bottom = client->rect.height - event->event_y;
409                                 resize_orientation_t orientation = O_VERTICAL;
410                                 Container *con = client->container;
411                                 int first, second;
412
413                                 LOG("click was %d px to the right, %d px to the left, %d px to top, %d px to bottom\n",
414                                                 to_right, to_left, to_top, to_bottom);
415
416                                 if (to_right < to_left &&
417                                     to_right < to_top &&
418                                     to_right < to_bottom) {
419                                         /* …right border */
420                                         first = con->col + (con->colspan - 1);
421                                         LOG("column %d\n", first);
422
423                                         if (!cell_exists(first, con->row) ||
424                                             (first == (con->workspace->cols-1)))
425                                                 return 1;
426
427                                         second = first + 1;
428                                 } else if (to_left < to_right &&
429                                            to_left < to_top &&
430                                            to_left < to_bottom) {
431                                         /* …left border */
432                                         if (con->col == 0)
433                                                 return 1;
434
435                                         first = con->col - 1;
436                                         second = con->col;
437                                 } else if (to_top < to_right &&
438                                            to_top < to_left &&
439                                            to_top < to_bottom) {
440                                         /* This was a press on the top border */
441                                         if (con->row == 0)
442                                                 return 1;
443                                         first = con->row - 1;
444                                         second = con->row;
445                                         orientation = O_HORIZONTAL;
446                                 } else if (to_bottom < to_right &&
447                                            to_bottom < to_left &&
448                                            to_bottom < to_top) {
449                                         /* …bottom border */
450                                         first = con->row + (con->rowspan - 1);
451                                         if (!cell_exists(con->col, first) ||
452                                             (first == (con->workspace->rows-1)))
453                                                 return 1;
454
455                                         second = first + 1;
456                                         orientation = O_HORIZONTAL;
457                                 }
458
459                                return resize_graphical_handler(conn, con->workspace, first, second, orientation, event);
460                         }
461                 }
462         }
463
464         if (client == NULL) {
465                 /* The client was neither on a client’s titlebar nor on a client itself, maybe on a stack_window? */
466                 if (button_press_stackwin(conn, event))
467                         return 1;
468
469                 /* Or on a bar? */
470                 if (button_press_bar(conn, event))
471                         return 1;
472
473                 LOG("Could not handle this button press\n");
474                 return 1;
475         }
476
477         /* Set focus in any case */
478         set_focus(conn, client, true);
479
480         /* Let’s see if this was on the borders (= resize). If not, we’re done */
481         LOG("press button on x=%d, y=%d\n", event->event_x, event->event_y);
482         resize_orientation_t orientation = O_VERTICAL;
483         Container *con = client->container;
484         int first, second;
485
486         if (client->dock) {
487                 LOG("dock. done.\n");
488                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
489                 xcb_flush(conn);
490                 return 1;
491         }
492
493         LOG("event->event_x = %d, client->rect.width = %d\n", event->event_x, client->rect.width);
494
495         /* Some clients (xfontsel for example) seem to pass clicks on their
496          * window to the parent window, thus we receive an event here which in
497          * reality is a border_click. Check for the position and fix state. */
498         if (border_click &&
499             event->event_x >= client->child_rect.x &&
500             event->event_x <= (client->child_rect.x + client->child_rect.width) &&
501             event->event_y >= client->child_rect.y &&
502             event->event_y <= (client->child_rect.y + client->child_rect.height)) {
503                 LOG("Fixing border_click = false because of click in child\n");
504                 border_click = false;
505         }
506
507         if (!border_click) {
508                 LOG("client. done.\n");
509                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
510                 /* Floating clients should be raised on click */
511                 if (client_is_floating(client))
512                         xcb_raise_window(conn, client->frame);
513                 xcb_flush(conn);
514                 return 1;
515         }
516
517         /* Don’t handle events inside the titlebar, only borders are interesting */
518         i3Font *font = load_font(conn, config.font);
519         if (event->event_y >= 2 && event->event_y <= (font->height + 2 + 2)) {
520                 LOG("click on titlebar\n");
521
522                 /* Floating clients can be dragged by grabbing their titlebar */
523                 if (client_is_floating(client)) {
524                         /* Firstly, we raise it. Maybe the user just wanted to raise it without grabbing */
525                         xcb_raise_window(conn, client->frame);
526                         xcb_flush(conn);
527
528                         floating_drag_window(conn, client, event);
529                 }
530                 return 1;
531         }
532
533         if (client_is_floating(client))
534                 return floating_border_click(conn, client, event);
535
536         if (event->event_y < 2) {
537                 /* This was a press on the top border */
538                 if (con->row == 0)
539                         return 1;
540                 first = con->row - 1;
541                 second = con->row;
542                 orientation = O_HORIZONTAL;
543         } else if (event->event_y >= (client->rect.height - 2)) {
544                 /* …bottom border */
545                 first = con->row + (con->rowspan - 1);
546                 if (!cell_exists(con->col, first) ||
547                     (first == (con->workspace->rows-1)))
548                         return 1;
549
550                 second = first + 1;
551                 orientation = O_HORIZONTAL;
552         } else if (event->event_x <= 2) {
553                 /* …left border */
554                 if (con->col == 0)
555                         return 1;
556
557                 first = con->col - 1;
558                 second = con->col;
559         } else if (event->event_x > 2) {
560                 /* …right border */
561                 first = con->col + (con->colspan - 1);
562                 LOG("column %d\n", first);
563
564                 if (!cell_exists(first, con->row) ||
565                     (first == (con->workspace->cols-1)))
566                         return 1;
567
568                 second = first + 1;
569         }
570
571         return resize_graphical_handler(conn, con->workspace, first, second, orientation, event);
572 }
573
574 /*
575  * A new window appeared on the screen (=was mapped), so let’s manage it.
576  *
577  */
578 int handle_map_request(void *prophs, xcb_connection_t *conn, xcb_map_request_event_t *event) {
579         xcb_get_window_attributes_cookie_t cookie;
580
581         cookie = xcb_get_window_attributes_unchecked(conn, event->window);
582
583         LOG("window = 0x%08x, serial is %d.\n", event->window, event->sequence);
584         add_ignore_event(event->sequence);
585
586         manage_window(prophs, conn, event->window, cookie, false);
587         return 1;
588 }
589
590 /*
591  * Configure requests are received when the application wants to resize windows on their own.
592  *
593  * We generate a synthethic configure notify event to signalize the client its "new" position.
594  *
595  */
596 int handle_configure_request(void *prophs, xcb_connection_t *conn, xcb_configure_request_event_t *event) {
597         LOG("window 0x%08x wants to be at %dx%d with %dx%d\n",
598             event->window, event->x, event->y, event->width, event->height);
599
600         Client *client = table_get(&by_child, event->window);
601         if (client == NULL) {
602                 uint32_t mask = 0;
603                 uint32_t values[7];
604                 int c = 0;
605 #define COPY_MASK_MEMBER(mask_member, event_member) do { \
606                 if (event->value_mask & mask_member) { \
607                         mask |= mask_member; \
608                         values[c++] = event->event_member; \
609                 } \
610 } while (0)
611
612                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_X, x);
613                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_Y, y);
614                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_WIDTH, width);
615                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_HEIGHT, height);
616                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_BORDER_WIDTH, border_width);
617                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_SIBLING, sibling);
618                 COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_STACK_MODE, stack_mode);
619
620                 xcb_configure_window(conn, event->window, mask, values);
621                 xcb_flush(conn);
622
623                 return 1;
624         }
625
626         if (client->fullscreen) {
627                 LOG("Client is in fullscreen mode\n");
628
629                 Rect child_rect = client->workspace->rect;
630                 child_rect.x = child_rect.y = 0;
631                 fake_configure_notify(conn, child_rect, client->child);
632
633                 return 1;
634         }
635
636         /* Floating clients can be reconfigured */
637         if (client_is_floating(client)) {
638                 i3Font *font = load_font(conn, config.font);
639
640                 if (event->value_mask & XCB_CONFIG_WINDOW_X)
641                         client->rect.x = event->x;
642                 if (event->value_mask & XCB_CONFIG_WINDOW_Y)
643                         client->rect.y = event->y;
644                 if (event->value_mask & XCB_CONFIG_WINDOW_WIDTH)
645                         client->rect.width = event->width + 2 + 2;
646                 if (event->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
647                         client->rect.height = event->height + (font->height + 2 + 2) + 2;
648
649                 LOG("Accepted new position/size for floating client: (%d, %d) size %d x %d\n",
650                     client->rect.x, client->rect.y, client->rect.width, client->rect.height);
651
652                 /* Push the new position/size to X11 */
653                 reposition_client(conn, client);
654                 resize_client(conn, client);
655                 xcb_flush(conn);
656
657                 return 1;
658         }
659
660         if (client->fullscreen) {
661                 LOG("Client is in fullscreen mode\n");
662
663                 Rect child_rect = client->container->workspace->rect;
664                 child_rect.x = child_rect.y = 0;
665                 fake_configure_notify(conn, child_rect, client->child);
666
667                 return 1;
668         }
669
670         fake_absolute_configure_notify(conn, client);
671
672         return 1;
673 }
674
675 /*
676  * Configuration notifies are only handled because we need to set up ignore for the following
677  * enter notify events
678  *
679  */
680 int handle_configure_event(void *prophs, xcb_connection_t *conn, xcb_configure_notify_event_t *event) {
681         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
682
683         /* We ignore this sequence twice because events for child and frame should be ignored */
684         add_ignore_event(event->sequence);
685         add_ignore_event(event->sequence);
686
687         if (event->event == root) {
688                 LOG("event->x = %d, ->y = %d, ->width = %d, ->height = %d\n", event->x, event->y, event->width, event->height);
689                 LOG("reconfigure of the root window, need to xinerama\n");
690                 /* FIXME: Somehow, this is occuring too often. Therefore, we check for 0/0,
691                    but is there a better way? */
692                 if (event->x == 0 && event->y == 0)
693                         xinerama_requery_screens(conn);
694                 return 1;
695         }
696
697         return 1;
698 }
699
700 /*
701  * Our window decorations were unmapped. That means, the window will be killed now,
702  * so we better clean up before.
703  *
704  */
705 int handle_unmap_notify_event(void *data, xcb_connection_t *conn, xcb_unmap_notify_event_t *event) {
706         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
707
708         add_ignore_event(event->sequence);
709
710         Client *client = table_get(&by_child, event->window);
711         /* First, we need to check if the client is awaiting an unmap-request which
712            was generated by us reparenting the window. In that case, we just ignore it. */
713         if (client != NULL && client->awaiting_useless_unmap) {
714                 client->awaiting_useless_unmap = false;
715                 return 1;
716         }
717
718         LOG("event->window = %08x, event->event = %08x\n", event->window, event->event);
719         LOG("UnmapNotify for 0x%08x (received from 0x%08x)\n", event->window, event->event);
720         if (client == NULL) {
721                 LOG("not a managed window. Ignoring.\n");
722
723                 /* This was most likely the destroyed frame of a client which is
724                  * currently being unmapped, so we add this sequence (again!) to
725                  * the ignore list (enter_notify events will get sent for both,
726                  * the child and its frame). */
727                 add_ignore_event(event->sequence);
728
729                 return 0;
730         }
731
732         client = table_remove(&by_child, event->window);
733
734         /* If this was the fullscreen client, we need to unset it */
735         if (client->fullscreen)
736                 client->workspace->fullscreen_client = NULL;
737
738         /* Clients without a container are either floating or dock windows */
739         if (client->container != NULL) {
740                 Container *con = client->container;
741
742                 /* Remove the client from the list of clients */
743                 client_remove_from_container(conn, client, con, true);
744
745                 /* Set focus to the last focused client in this container */
746                 con->currently_focused = get_last_focused_client(conn, con, NULL);
747
748                 /* Only if this is the active container, we need to really change focus */
749                 if ((con->currently_focused != NULL) && ((con == CUR_CELL) || client->fullscreen))
750                         set_focus(conn, con->currently_focused, true);
751         } else if (client_is_floating(client)) {
752                 LOG("Removing from floating clients\n");
753                 TAILQ_REMOVE(&(client->workspace->floating_clients), client, floating_clients);
754                 SLIST_REMOVE(&(client->workspace->focus_stack), client, Client, focus_clients);
755         }
756
757         if (client->dock) {
758                 LOG("Removing from dock clients\n");
759                 SLIST_REMOVE(&(client->workspace->screen->dock_clients), client, Client, dock_clients);
760         }
761
762         LOG("child of 0x%08x.\n", client->frame);
763         xcb_reparent_window(conn, client->child, root, 0, 0);
764
765         client_unmap(conn, client);
766
767         xcb_destroy_window(conn, client->frame);
768         xcb_flush(conn);
769         table_remove(&by_parent, client->frame);
770
771         if (client->container != NULL) {
772                 Workspace *workspace = client->container->workspace;
773                 cleanup_table(conn, workspace);
774                 fix_colrowspan(conn, workspace);
775         }
776
777         /* Let’s see how many clients there are left on the workspace to delete it if it’s empty */
778         bool workspace_empty = SLIST_EMPTY(&(client->workspace->focus_stack));
779         bool workspace_active = false;
780         Client *to_focus = (!workspace_empty ? SLIST_FIRST(&(client->workspace->focus_stack)) : NULL);
781
782         /* If this workspace is currently active, we don’t delete it */
783         i3Screen *screen;
784         TAILQ_FOREACH(screen, virtual_screens, screens)
785                 if (screen->current_workspace == client->workspace->num) {
786                         workspace_active = true;
787                         workspace_empty = false;
788                         break;
789                 }
790
791         if (workspace_empty)
792                 client->workspace->screen = NULL;
793
794         FREE(client->window_class);
795         FREE(client->name);
796         free(client);
797
798         render_layout(conn);
799
800         /* Ensure the focus is set to the next client in the focus stack */
801         if (workspace_active && to_focus != NULL)
802                 set_focus(conn, to_focus, true);
803
804         return 1;
805 }
806
807 /*
808  * Called when a window changes its title
809  *
810  */
811 int handle_windowname_change(void *data, xcb_connection_t *conn, uint8_t state,
812                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
813         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
814                 LOG("_NET_WM_NAME not specified, not changing\n");
815                 return 1;
816         }
817         Client *client = table_get(&by_child, window);
818         if (client == NULL)
819                 return 1;
820
821         /* Save the old pointer to make the update atomic */
822         char *new_name;
823         int new_len;
824         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
825         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
826         char *ucs2_name = convert_utf8_to_ucs2(new_name, &new_len);
827         LOG("_NET_WM_NAME changed to \"%s\"\n", new_name);
828         free(new_name);
829
830         /* Check if they are the same and don’t update if so.
831            Note the use of new_len * 2 to check all bytes as each glyph takes 2 bytes.
832            Also note the use of memcmp() instead of strncmp() because the latter stops on nullbytes,
833            but UCS-2 uses nullbytes to fill up glyphs which only use one byte. */
834         if ((new_len == client->name_len) &&
835             (client->name != NULL) &&
836             (memcmp(client->name, ucs2_name, new_len * 2) == 0)) {
837                 free(ucs2_name);
838                 return 1;
839         }
840
841         char *old_name = client->name;
842         client->name = ucs2_name;
843         client->name_len = new_len;
844         client->uses_net_wm_name = true;
845
846         FREE(old_name);
847
848         /* If the client is a dock window, we don’t need to render anything */
849         if (client->dock)
850                 return 1;
851
852         if (client->container != NULL &&
853             (client->container->mode == MODE_STACK ||
854              client->container->mode == MODE_TABBED))
855                 render_container(conn, client->container);
856         else decorate_window(conn, client, client->frame, client->titlegc, 0, 0);
857         xcb_flush(conn);
858
859         return 1;
860 }
861
862 /*
863  * We handle legacy window names (titles) which are in COMPOUND_TEXT encoding. However, we
864  * just pass them along, so when containing non-ASCII characters, those will be rendering
865  * incorrectly. In order to correctly render unicode window titles in i3, an application
866  * has to set _NET_WM_NAME, which is in UTF-8 encoding.
867  *
868  * On every update, a message is put out to the user, so he may improve the situation and
869  * update applications which display filenames in their title to correctly use
870  * _NET_WM_NAME and therefore support unicode.
871  *
872  */
873 int handle_windowname_change_legacy(void *data, xcb_connection_t *conn, uint8_t state,
874                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
875         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
876                 LOG("prop == NULL\n");
877                 return 1;
878         }
879         Client *client = table_get(&by_child, window);
880         if (client == NULL)
881                 return 1;
882
883         /* Client capable of _NET_WM_NAME, ignore legacy name changes */
884         if (client->uses_net_wm_name)
885                 return 1;
886
887         /* Save the old pointer to make the update atomic */
888         char *new_name;
889         if (asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop)) == -1) {
890                 perror("Could not get old name");
891                 LOG("Could not get old name\n");
892                 return 1;
893         }
894         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
895         LOG("WM_NAME changed to \"%s\"\n", new_name);
896
897         /* Check if they are the same and don’t update if so. */
898         if (client->name != NULL &&
899             strlen(new_name) == strlen(client->name) &&
900             strcmp(client->name, new_name) == 0) {
901                 free(new_name);
902                 return 1;
903         }
904
905         LOG("Using legacy window title. Note that in order to get Unicode window titles in i3, "
906             "the application has to set _NET_WM_NAME which is in UTF-8 encoding.\n");
907
908         char *old_name = client->name;
909         client->name = new_name;
910         client->name_len = -1;
911
912         if (old_name != NULL)
913                 free(old_name);
914
915         /* If the client is a dock window, we don’t need to render anything */
916         if (client->dock)
917                 return 1;
918
919         if (client->container != NULL &&
920             (client->container->mode == MODE_STACK ||
921              client->container->mode == MODE_TABBED))
922                 render_container(conn, client->container);
923         else decorate_window(conn, client, client->frame, client->titlegc, 0, 0);
924         xcb_flush(conn);
925
926         return 1;
927 }
928
929 /*
930  * Updates the client’s WM_CLASS property
931  *
932  */
933 int handle_windowclass_change(void *data, xcb_connection_t *conn, uint8_t state,
934                              xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
935         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
936                 LOG("prop == NULL\n");
937                 return 1;
938         }
939         Client *client = table_get(&by_child, window);
940         if (client == NULL)
941                 return 1;
942         char *new_class;
943         if (asprintf(&new_class, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop)) == -1) {
944                 perror("Could not get window class");
945                 LOG("Could not get window class\n");
946                 return 1;
947         }
948
949         LOG("WM_CLASS changed to %s\n", new_class);
950         char *old_class = client->window_class;
951         client->window_class = new_class;
952         FREE(old_class);
953
954         if (!client->initialized)
955                 return 1;
956
957         if (strcmp(new_class, "tools") == 0 || strcmp(new_class, "Dialog") == 0) {
958                 LOG("tool/dialog window, should we put it floating?\n");
959                 if (client->floating == FLOATING_AUTO_OFF)
960                         toggle_floating_mode(conn, client, true);
961         }
962
963         return 1;
964 }
965
966 /*
967  * Expose event means we should redraw our windows (= title bar)
968  *
969  */
970 int handle_expose_event(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
971         /* event->count is the number of minimum remaining expose events for this window, so we
972            skip all events but the last one */
973         if (event->count != 0)
974                 return 1;
975         LOG("window = %08x\n", event->window);
976
977         Client *client = table_get(&by_parent, event->window);
978         if (client == NULL) {
979                 /* There was no client in the table, so this is probably an expose event for
980                    one of our stack_windows. */
981                 struct Stack_Window *stack_win;
982                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
983                         if (stack_win->window == event->window) {
984                                 render_container(conn, stack_win->container);
985                                 return 1;
986                         }
987
988                 /* …or one of the bars? */
989                 i3Screen *screen;
990                 TAILQ_FOREACH(screen, virtual_screens, screens)
991                         if (screen->bar == event->window)
992                                 render_layout(conn);
993                 return 1;
994         }
995
996         if (client->dock)
997                 return 1;
998
999         if (client->container == NULL ||
1000             (client->container->mode != MODE_STACK &&
1001              client->container->mode != MODE_TABBED))
1002                 decorate_window(conn, client, client->frame, client->titlegc, 0, 0);
1003         else {
1004                 uint32_t background_color;
1005                 if (client->urgent)
1006                         background_color = config.client.urgent.background;
1007                 /* Distinguish if the window is currently focused… */
1008                 else if (CUR_CELL->currently_focused == client)
1009                         background_color = config.client.focused.background;
1010                 /* …or if it is the focused window in a not focused container */
1011                 else background_color = config.client.focused_inactive.background;
1012
1013                 /* Set foreground color to current focused color, line width to 2 */
1014                 uint32_t values[] = {background_color, 2};
1015                 xcb_change_gc(conn, client->titlegc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
1016
1017                 /* Draw the border, the ±1 is for line width = 2 */
1018                 xcb_point_t points[] = {{1, 0},                                           /* left upper edge */
1019                                         {1, client->rect.height-1},                       /* left bottom edge */
1020                                         {client->rect.width-1, client->rect.height-1},    /* right bottom edge */
1021                                         {client->rect.width-1, 0}};                       /* right upper edge */
1022                 xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, client->frame, client->titlegc, 4, points);
1023
1024                 /* Draw a black background */
1025                 xcb_change_gc_single(conn, client->titlegc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
1026                 xcb_rectangle_t crect = {2, 0, client->rect.width - (2 + 2), client->rect.height - 2};
1027                 xcb_poly_fill_rectangle(conn, client->frame, client->titlegc, 1, &crect);
1028         }
1029         xcb_flush(conn);
1030         return 1;
1031 }
1032
1033 /*
1034  * Handle client messages (EWMH)
1035  *
1036  */
1037 int handle_client_message(void *data, xcb_connection_t *conn, xcb_client_message_event_t *event) {
1038         if (event->type == atoms[_NET_WM_STATE]) {
1039                 if (event->format != 32 || event->data.data32[1] != atoms[_NET_WM_STATE_FULLSCREEN])
1040                         return 0;
1041
1042                 Client *client = table_get(&by_child, event->window);
1043                 if (client == NULL)
1044                         return 0;
1045
1046                 /* Check if the fullscreen state should be toggled */
1047                 if ((client->fullscreen &&
1048                      (event->data.data32[0] == _NET_WM_STATE_REMOVE ||
1049                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)) ||
1050                     (!client->fullscreen &&
1051                      (event->data.data32[0] == _NET_WM_STATE_ADD ||
1052                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)))
1053                         client_toggle_fullscreen(conn, client);
1054         } else {
1055                 LOG("unhandled clientmessage\n");
1056                 return 0;
1057         }
1058
1059         return 1;
1060 }
1061
1062 int handle_window_type(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
1063                         xcb_atom_t atom, xcb_get_property_reply_t *property) {
1064         /* TODO: Implement this one. To do this, implement a little test program which sleep(1)s
1065          before changing this property. */
1066         LOG("_NET_WM_WINDOW_TYPE changed, this is not yet implemented.\n");
1067         return 0;
1068 }
1069
1070 /*
1071  * Handles the size hints set by a window, but currently only the part necessary for displaying
1072  * clients proportionally inside their frames (mplayer for example)
1073  *
1074  * See ICCCM 4.1.2.3 for more details
1075  *
1076  */
1077 int handle_normal_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
1078                         xcb_atom_t name, xcb_get_property_reply_t *reply) {
1079         Client *client = table_get(&by_child, window);
1080         if (client == NULL) {
1081                 LOG("Received WM_SIZE_HINTS for unknown client\n");
1082                 return 1;
1083         }
1084         xcb_size_hints_t size_hints;
1085
1086         CLIENT_LOG(client);
1087
1088         /* If the hints were already in this event, use them, if not, request them */
1089         if (reply != NULL)
1090                 xcb_get_wm_size_hints_from_reply(&size_hints, reply);
1091         else
1092                 xcb_get_wm_normal_hints_reply(conn, xcb_get_wm_normal_hints_unchecked(conn, client->child), &size_hints, NULL);
1093
1094         if ((size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE)) {
1095                 // TODO: Minimum size is not yet implemented
1096                 //LOG("Minimum size: %d (width) x %d (height)\n", size_hints.min_width, size_hints.min_height);
1097         }
1098
1099         if ((size_hints.flags & XCB_SIZE_HINT_P_RESIZE_INC)) {
1100                 bool changed = false;
1101
1102                 if (size_hints.width_inc > 0)
1103                         if (client->width_increment != size_hints.width_inc) {
1104                                 client->width_increment = size_hints.width_inc;
1105                                 changed = true;
1106                         }
1107                 if (size_hints.height_inc > 0)
1108                         if (client->height_increment != size_hints.height_inc) {
1109                                 client->height_increment = size_hints.height_inc;
1110                                 changed = true;
1111                         }
1112
1113                 if (changed) {
1114                         resize_client(conn, client);
1115                         xcb_flush(conn);
1116                 }
1117         }
1118
1119         int base_width = 0, base_height = 0;
1120
1121         /* base_width/height are the desired size of the window.
1122            We check if either the program-specified size or the program-specified
1123            min-size is available */
1124         if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
1125                 base_width = size_hints.base_width;
1126                 base_height = size_hints.base_height;
1127         } else if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
1128                 base_width = size_hints.min_width;
1129                 base_height = size_hints.min_height;
1130         }
1131
1132         client->base_width = base_width;
1133         client->base_height = base_height;
1134
1135         /* If no aspect ratio was set or if it was invalid, we ignore the hints */
1136         if (!(size_hints.flags & XCB_SIZE_HINT_P_ASPECT) ||
1137             (size_hints.min_aspect_num <= 0) ||
1138             (size_hints.min_aspect_den <= 0)) {
1139                 return 1;
1140         }
1141
1142         double width = client->rect.width - base_width;
1143         double height = client->rect.height - base_height;
1144         /* Convert numerator/denominator to a double */
1145         double min_aspect = (double)size_hints.min_aspect_num / size_hints.min_aspect_den;
1146         double max_aspect = (double)size_hints.max_aspect_num / size_hints.min_aspect_den;
1147
1148         LOG("Aspect ratio set: minimum %f, maximum %f\n", min_aspect, max_aspect);
1149         LOG("width = %f, height = %f\n", width, height);
1150
1151         /* Sanity checks, this is user-input, in a way */
1152         if (max_aspect <= 0 || min_aspect <= 0 || height == 0 || (width / height) <= 0)
1153                 return 1;
1154
1155         /* Check if we need to set proportional_* variables using the correct ratio */
1156         if ((width / height) < min_aspect) {
1157                 client->proportional_width = width;
1158                 client->proportional_height = width / min_aspect;
1159         } else if ((width / height) > max_aspect) {
1160                 client->proportional_width = width;
1161                 client->proportional_height = width / max_aspect;
1162         } else return 1;
1163
1164         client->force_reconfigure = true;
1165
1166         if (client->container != NULL) {
1167                 render_container(conn, client->container);
1168                 xcb_flush(conn);
1169         }
1170
1171         return 1;
1172 }
1173
1174 /*
1175  * Handles the WM_HINTS property for extracting the urgency state of the window.
1176  *
1177  */
1178 int handle_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
1179                   xcb_atom_t name, xcb_get_property_reply_t *reply) {
1180         Client *client = table_get(&by_child, window);
1181         if (client == NULL) {
1182                 LOG("Received WM_HINTS for unknown client\n");
1183                 return 1;
1184         }
1185         xcb_wm_hints_t hints;
1186
1187         if (reply != NULL) {
1188                 if (!xcb_get_wm_hints_from_reply(&hints, reply))
1189                         return 1;
1190         } else {
1191                 if (!xcb_get_wm_hints_reply(conn, xcb_get_wm_hints_unchecked(conn, client->child), &hints, NULL))
1192                         return 1;
1193         }
1194
1195         /* Update the flag on the client directly */
1196         client->urgent = (xcb_wm_hints_get_urgency(&hints) != 0);
1197         CLIENT_LOG(client);
1198         LOG("Urgency flag changed to %d\n", client->urgent);
1199
1200         workspace_update_urgent_flag(client->workspace);
1201         redecorate_window(conn, client);
1202
1203         /* If the workspace this client is on is not visible, we need to redraw
1204          * the workspace bar */
1205         if (!workspace_is_visible(client->workspace)) {
1206                 i3Screen *screen = client->workspace->screen;
1207                 render_workspace(conn, screen, &(workspaces[screen->current_workspace]));
1208                 xcb_flush(conn);
1209         }
1210
1211         return 1;
1212 }
1213
1214 /*
1215  * Handles the transient for hints set by a window, signalizing that this window is a popup window
1216  * for some other window.
1217  *
1218  * See ICCCM 4.1.2.6 for more details
1219  *
1220  */
1221 int handle_transient_for(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
1222                          xcb_atom_t name, xcb_get_property_reply_t *reply) {
1223         Client *client = table_get(&by_child, window);
1224         if (client == NULL) {
1225                 LOG("No such client\n");
1226                 return 1;
1227         }
1228
1229         xcb_window_t transient_for;
1230
1231         if (reply != NULL) {
1232                 if (!xcb_get_wm_transient_for_from_reply(&transient_for, reply))
1233                         return 1;
1234         } else {
1235                 if (!xcb_get_wm_transient_for_reply(conn, xcb_get_wm_transient_for_unchecked(conn, window),
1236                                                     &transient_for, NULL))
1237                         return 1;
1238         }
1239
1240         if (client->floating == FLOATING_AUTO_OFF) {
1241                 LOG("This is a popup window, putting into floating\n");
1242                 toggle_floating_mode(conn, client, true);
1243         }
1244
1245         return 1;
1246 }
1247
1248 /*
1249  * Handles changes of the WM_CLIENT_LEADER atom which specifies if this is a
1250  * toolwindow (or similar) and to which window it belongs (logical parent).
1251  *
1252  */
1253 int handle_clientleader_change(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
1254                         xcb_atom_t name, xcb_get_property_reply_t *prop) {
1255         if (prop == NULL) {
1256                 prop = xcb_get_property_reply(conn, xcb_get_property_unchecked(conn,
1257                                         false, window, WM_CLIENT_LEADER, WINDOW, 0, 32), NULL);
1258                 if (prop == NULL)
1259                         return 1;
1260         }
1261
1262         Client *client = table_get(&by_child, window);
1263         if (client == NULL)
1264                 return 1;
1265
1266         xcb_window_t *leader = xcb_get_property_value(prop);
1267         if (leader == NULL || *leader == 0)
1268                 return 1;
1269
1270         LOG("Client leader changed to %08x\n", *leader);
1271
1272         client->leader = *leader;
1273
1274         return 1;
1275 }