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