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