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