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