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