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