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