]> git.sur5r.net Git - i3/i3/blob - src/handlers.c
477666236c2053f11954d6abc91f51fa3e797ec5
[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_wm.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                         LOG("Entry is older than five seconds, cleaning up\n");
61                         struct Ignore_Event *save = event;
62                         event = SLIST_NEXT(event, ignore_events);
63                         SLIST_REMOVE(&ignore_events, save, Ignore_Event, ignore_events);
64                         free(save);
65                 } else event = SLIST_NEXT(event, ignore_events);
66         }
67
68         SLIST_FOREACH(event, &ignore_events, ignore_events) {
69                 if (event->sequence == sequence) {
70                         LOG("Ignoring event (sequence %d)\n", sequence);
71                         SLIST_REMOVE(&ignore_events, event, Ignore_Event, ignore_events);
72                         free(event);
73                         return true;
74                 }
75         }
76
77         return false;
78 }
79
80 /*
81  * Due to bindings like Mode_switch + <a>, we need to bind some keys in XCB_GRAB_MODE_SYNC.
82  * Therefore, we just replay all key presses.
83  *
84  */
85 int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
86         LOG("got key release, just passing\n");
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\n", event->detail);
99
100         /* We need to get the keysym group (There are group 1 to group 4, each holding
101            two keysyms (without shift and with shift) using Xkb because X fails to
102            provide them reliably (it works in Xephyr, it does not in real X) */
103         XkbStateRec state;
104         if (XkbGetState(xkbdpy, XkbUseCoreKbd, &state) == Success && (state.group+1) == 2)
105                 event->state |= 0x2;
106
107         LOG("state %d\n", event->state);
108
109         /* Remove the numlock bit, all other bits are modifiers we can bind to */
110         uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
111
112         /* Find the binding */
113         Binding *bind;
114         TAILQ_FOREACH(bind, &bindings, bindings)
115                 if (bind->keycode == event->detail && bind->mods == state_filtered)
116                         break;
117
118         /* No match? Then it was an actively grabbed key, that is with Mode_switch, and
119            the user did not press Mode_switch, so just pass it… */
120         if (bind == TAILQ_END(&bindings)) {
121                 xcb_allow_events(conn, ReplayKeyboard, event->time);
122                 xcb_flush(conn);
123                 return 1;
124         }
125
126         parse_command(conn, bind->command);
127         if (event->state & 0x2) {
128                 LOG("Mode_switch -> allow_events(SyncKeyboard)\n");
129                 xcb_allow_events(conn, SyncKeyboard, event->time);
130                 xcb_flush(conn);
131         }
132         return 1;
133 }
134
135
136 /*
137  * When the user moves the mouse pointer onto a window, this callback gets called.
138  *
139  */
140 int handle_enter_notify(void *ignored, xcb_connection_t *conn, xcb_enter_notify_event_t *event) {
141         LOG("enter_notify for %08x, mode = %d, detail %d, serial %d\n", event->event, event->mode, event->detail, event->sequence);
142         if (event->mode != XCB_NOTIFY_MODE_NORMAL) {
143                 LOG("This was not a normal notify, ignoring\n");
144                 return 1;
145         }
146         /* Some events are not interesting, because they were not generated actively by the
147            user, but be reconfiguration of windows */
148         if (event_is_ignored(event->sequence))
149                 return 1;
150
151         /* This was either a focus for a client’s parent (= titlebar)… */
152         Client *client = table_get(byParent, event->event);
153         /* …or the client itself */
154         if (client == NULL)
155                 client = table_get(byChild, event->event);
156
157         /* Check for stack windows */
158         if (client == NULL) {
159                 struct Stack_Window *stack_win;
160                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
161                         if (stack_win->window == event->event) {
162                                 client = stack_win->container->currently_focused;
163                                 break;
164                         }
165         }
166
167
168         /* If not, then the user moved his cursor to the root window. In that case, we adjust c_ws */
169         if (client == NULL) {
170                 LOG("Getting screen at %d x %d\n", event->root_x, event->root_y);
171                 i3Screen *screen = get_screen_containing(event->root_x, event->root_y);
172                 if (screen == NULL) {
173                         LOG("ERROR: No such screen\n");
174                         return 0;
175                 }
176                 c_ws->current_row = current_row;
177                 c_ws->current_col = current_col;
178                 c_ws = &workspaces[screen->current_workspace];
179                 current_row = c_ws->current_row;
180                 current_col = c_ws->current_col;
181                 LOG("We're now on virtual screen number %d\n", screen->num);
182                 return 1;
183         }
184
185         /* Do plausibility checks: This event may be useless for us if it occurs on a window
186            which is in a stacked container but not the focused one */
187         if (client->container != NULL &&
188             client->container->mode == MODE_STACK &&
189             client->container->currently_focused != client) {
190                 LOG("Plausibility check says: no\n");
191                 return 1;
192         }
193
194         set_focus(conn, client, false);
195
196         return 1;
197 }
198
199 /*
200  * Checks if the button press was on a stack window, handles focus setting and returns true
201  * if so, or false otherwise.
202  *
203  */
204 static bool button_press_stackwin(xcb_connection_t *conn, xcb_button_press_event_t *event) {
205         struct Stack_Window *stack_win;
206         SLIST_FOREACH(stack_win, &stack_wins, stack_windows) {
207                 if (stack_win->window != event->event)
208                         continue;
209
210                 /* A stack window was clicked, we check if it was button4 or button5
211                    which are scroll up / scroll down. */
212                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
213                         direction_t direction = (event->detail == XCB_BUTTON_INDEX_4 ? D_UP : D_DOWN);
214                         focus_window_in_container(conn, CUR_CELL, direction);
215                         return true;
216                 }
217
218                 /* It was no scrolling, so we calculate the destination client by
219                    dividing the Y position of the event through the height of a window
220                    decoration and then set the focus to this client. */
221                 i3Font *font = load_font(conn, config.font);
222                 int decoration_height = (font->height + 2 + 2);
223                 int destination = (event->event_y / decoration_height),
224                     c = 0;
225                 Client *client;
226
227                 LOG("Click on stack_win for client %d\n", destination);
228                 CIRCLEQ_FOREACH(client, &(stack_win->container->clients), clients)
229                         if (c++ == destination) {
230                                 set_focus(conn, client, true);
231                                 return true;
232                         }
233
234                 return true;
235         }
236
237         return false;
238 }
239
240 /*
241  * Checks if the button press was on a bar, switches to the workspace and returns true
242  * if so, or false otherwise.
243  *
244  */
245 static bool button_press_bar(xcb_connection_t *conn, xcb_button_press_event_t *event) {
246         i3Screen *screen;
247         TAILQ_FOREACH(screen, virtual_screens, screens) {
248                 if (screen->bar != event->event)
249                         continue;
250
251                 LOG("Click on a bar\n");
252
253                 /* Check if the button was one of button4 or button5 (scroll up / scroll down) */
254                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
255                         int dest_workspace = (event->detail == XCB_BUTTON_INDEX_4 ?
256                                               c_ws->num - 1 :
257                                               c_ws->num + 1);
258                         if ((dest_workspace >= 0) && (dest_workspace < 10))
259                                 show_workspace(conn, dest_workspace+1);
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(byChild, event->event);
282         bool border_click = false;
283         if (client == NULL) {
284                 client = table_get(byParent, 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                 /* Convert 0 (for default width_factor) to actual numbers */
471                 if (first->width_factor == 0)
472                         first->width_factor = ((float)ws->rect.width / ws->cols) / ws->rect.width;
473                 if (second->width_factor == 0)
474                         second->width_factor = ((float)ws->rect.width / ws->cols) / ws->rect.width;
475
476                 first->width_factor *= (float)(first->width + (new_position - event->root_x)) / first->width;
477                 second->width_factor *= (float)(second->width - (new_position - event->root_x)) / second->width;
478         } else {
479                 LOG("Resize was from Y = %d to Y = %d\n", event->root_y, new_position);
480                 if (event->root_y == new_position) {
481                         LOG("Nothing changed, not updating anything\n");
482                         return 1;
483                 }
484
485                 /* Convert 0 (for default height_factor) to actual numbers */
486                 if (first->height_factor == 0)
487                         first->height_factor = ((float)ws->rect.height / ws->rows) / ws->rect.height;
488                 if (second->height_factor == 0)
489                         second->height_factor = ((float)ws->rect.height / ws->rows) / ws->rect.height;
490
491                 first->height_factor *= (float)(first->height + (new_position - event->root_y)) / first->height;
492                 second->height_factor *= (float)(second->height - (new_position - event->root_y)) / second->height;
493         }
494
495         render_layout(conn);
496
497         return 1;
498 }
499
500 /*
501  * A new window appeared on the screen (=was mapped), so let’s manage it.
502  *
503  */
504 int handle_map_request(void *prophs, xcb_connection_t *conn, xcb_map_request_event_t *event) {
505         xcb_get_window_attributes_cookie_t cookie;
506         xcb_get_window_attributes_reply_t *reply;
507
508         cookie = xcb_get_window_attributes_unchecked(conn, event->window);
509
510         if ((reply = xcb_get_window_attributes_reply(conn, cookie, NULL)) == NULL) {
511                 LOG("Could not get window attributes\n");
512                 return -1;
513         }
514
515         window_attributes_t wa = { TAG_VALUE };
516         LOG("override_redirect = %d\n", reply->override_redirect);
517         wa.u.override_redirect = reply->override_redirect;
518         LOG("window = 0x%08x, serial is %d.\n", event->window, event->sequence);
519         add_ignore_event(event->sequence);
520
521         manage_window(prophs, conn, event->window, wa);
522         return 1;
523 }
524
525 /*
526  * Configure requests are received when the application wants to resize windows on their own.
527  *
528  * We generate a synthethic configure notify event to signalize the client its "new" position.
529  *
530  */
531 int handle_configure_request(void *prophs, xcb_connection_t *conn, xcb_configure_request_event_t *event) {
532         LOG("configure-request, serial %d\n", event->sequence);
533         LOG("event->window = %08x\n", event->window);
534         LOG("application wants to be at %dx%d with %dx%d\n", event->x, event->y, event->width, event->height);
535
536         Client *client = table_get(byChild, event->window);
537         if (client == NULL) {
538                 LOG("This client is not mapped, so we don't care and just tell the client that he will get its size\n");
539                 Rect rect = {event->x, event->y, event->width, event->height};
540                 fake_configure_notify(conn, rect, event->window);
541                 return 1;
542         }
543
544         fake_configure_notify(conn, client->child_rect, client->child);
545
546         return 1;
547 }
548
549 /*
550  * Configuration notifies are only handled because we need to set up ignore for the following
551  * enter notify events
552  *
553  */
554 int handle_configure_event(void *prophs, xcb_connection_t *conn, xcb_configure_notify_event_t *event) {
555         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
556
557         LOG("handle_configure_event for window %08x\n", event->window);
558         LOG("event->type = %d, \n", event->response_type);
559         LOG("event->x = %d, ->y = %d, ->width = %d, ->height = %d\n", event->x, event->y, event->width, event->height);
560         add_ignore_event(event->sequence);
561
562         if (event->event == root) {
563                 LOG("reconfigure of the root window, need to xinerama\n");
564                 /* FIXME: Somehow, this is occuring too often. Therefore, we check for 0/0,
565                    but is there a better way? */
566                 if (event->x == 0 && event->y == 0)
567                         xinerama_requery_screens(conn);
568                 return 1;
569         }
570
571         return 1;
572 }
573
574 /*
575  * Our window decorations were unmapped. That means, the window will be killed now,
576  * so we better clean up before.
577  *
578  */
579 int handle_unmap_notify_event(void *data, xcb_connection_t *conn, xcb_unmap_notify_event_t *event) {
580         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
581
582         add_ignore_event(event->sequence);
583
584         Client *client = table_get(byChild, event->window);
585         /* First, we need to check if the client is awaiting an unmap-request which
586            was generated by us reparenting the window. In that case, we just ignore it. */
587         if (client != NULL && client->awaiting_useless_unmap) {
588                 LOG("Dropping this unmap request, it was generated by reparenting\n");
589                 client->awaiting_useless_unmap = false;
590                 return 1;
591         }
592
593         LOG("event->window = %08x, event->event = %08x\n", event->window, event->event);
594         LOG("UnmapNotify for 0x%08x (received from 0x%08x)\n", event->window, event->event);
595         if (client == NULL) {
596                 LOG("not a managed window. Ignoring.\n");
597                 return 0;
598         }
599
600         client = table_remove(byChild, event->window);
601
602         if (client->name != NULL)
603                 free(client->name);
604
605         if (client->container != NULL) {
606                 Container *con = client->container;
607
608                 /* If this was the fullscreen client, we need to unset it */
609                 if (client->fullscreen)
610                         con->workspace->fullscreen_client = NULL;
611
612                 /* Remove the client from the list of clients */
613                 remove_client_from_container(conn, client, con);
614
615                 /* Set focus to the last focused client in this container */
616                 con->currently_focused = NULL;
617                 Client *focus_client;
618                 SLIST_FOREACH(focus_client, &(con->workspace->focus_stack), focus_clients)
619                         if (focus_client->container == con) {
620                                 con->currently_focused = focus_client;
621                                 /* Only if this is the active container, we need to really change focus */
622                                 if (con == CUR_CELL)
623                                         set_focus(conn, focus_client, false);
624                                 break;
625                         }
626         }
627
628         if (client->dock) {
629                 LOG("Removing from dock clients\n");
630                 SLIST_REMOVE(&(client->workspace->dock_clients), client, Client, dock_clients);
631         }
632
633         LOG("child of 0x%08x.\n", client->frame);
634         xcb_reparent_window(conn, client->child, root, 0, 0);
635         xcb_destroy_window(conn, client->frame);
636         xcb_flush(conn);
637         table_remove(byParent, client->frame);
638
639         if (client->container != NULL)
640                 cleanup_table(conn, client->container->workspace);
641
642         /* Let’s see how many clients there are left on the workspace to delete it if it’s empty */
643         bool workspace_empty = true;
644         FOR_TABLE(client->workspace)
645                 if (!CIRCLEQ_EMPTY(&(client->workspace->table[cols][rows]->clients))) {
646                         workspace_empty = false;
647                         break;
648                 }
649
650         if (workspace_empty && (c_ws != client->workspace))
651                 client->workspace->screen = NULL;
652
653         free(client);
654
655         render_layout(conn);
656
657         return 1;
658 }
659
660 /*
661  * Called when a window changes its title
662  *
663  */
664 int handle_windowname_change(void *data, xcb_connection_t *conn, uint8_t state,
665                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
666         LOG("window's name changed.\n");
667         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
668                 LOG("_NET_WM_NAME not specified, not changing\n");
669                 return 1;
670         }
671         Client *client = table_get(byChild, window);
672         if (client == NULL)
673                 return 1;
674
675         /* Save the old pointer to make the update atomic */
676         char *new_name;
677         int new_len;
678         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
679         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
680         char *ucs2_name = convert_utf8_to_ucs2(new_name, &new_len);
681         LOG("Name should change to \"%s\"\n", new_name);
682         free(new_name);
683
684         /* Check if they are the same and don’t update if so.
685            Note the use of new_len * 2 to check all bytes as each glyph takes 2 bytes.
686            Also note the use of memcmp() instead of strncmp() because the latter stops on nullbytes,
687            but UCS-2 uses nullbytes to fill up glyphs which only use one byte. */
688         if ((new_len == client->name_len) &&
689             (client->name != NULL) &&
690             (memcmp(client->name, ucs2_name, new_len * 2) == 0)) {
691                 LOG("Name did not change, not updating\n");
692                 free(ucs2_name);
693                 return 1;
694         }
695
696         char *old_name = client->name;
697         client->name = ucs2_name;
698         client->name_len = new_len;
699         client->uses_net_wm_name = true;
700
701         if (old_name != NULL)
702                 free(old_name);
703
704         /* If the client is a dock window, we don’t need to render anything */
705         if (client->dock)
706                 return 1;
707
708         if (client->container->mode == MODE_STACK)
709                 render_container(conn, client->container);
710         else decorate_window(conn, client, client->frame, client->titlegc, 0);
711         xcb_flush(conn);
712
713         return 1;
714 }
715
716 /*
717  * We handle legacy window names (titles) which are in COMPOUND_TEXT encoding. However, we
718  * just pass them along, so when containing non-ASCII characters, those will be rendering
719  * incorrectly. In order to correctly render unicode window titles in i3, an application
720  * has to set _NET_WM_NAME, which is in UTF-8 encoding.
721  *
722  * On every update, a message is put out to the user, so he may improve the situation and
723  * update applications which display filenames in their title to correctly use
724  * _NET_WM_NAME and therefore support unicode.
725  *
726  */
727 int handle_windowname_change_legacy(void *data, xcb_connection_t *conn, uint8_t state,
728                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
729         LOG("window's name changed (legacy).\n");
730         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
731                 LOG("prop == NULL\n");
732                 return 1;
733         }
734         Client *client = table_get(byChild, window);
735         if (client == NULL)
736                 return 1;
737
738         if (client->uses_net_wm_name) {
739                 LOG("This client is capable of _NET_WM_NAME, ignoring legacy name\n");
740                 return 1;
741         }
742
743         /* Save the old pointer to make the update atomic */
744         char *new_name;
745         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
746         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
747         LOG("Name should change to \"%s\"\n", new_name);
748
749         /* Check if they are the same and don’t update if so. */
750         if (client->name != NULL &&
751             strlen(new_name) == strlen(client->name) &&
752             strcmp(client->name, new_name) == 0) {
753                 LOG("Name did not change, not updating\n");
754                 free(new_name);
755                 return 1;
756         }
757
758         LOG("Using legacy window title. Note that in order to get Unicode window titles in i3,"
759             "the application has to set _NET_WM_NAME which is in UTF-8 encoding.\n");
760
761         char *old_name = client->name;
762         client->name = new_name;
763         client->name_len = -1;
764
765         if (old_name != NULL)
766                 free(old_name);
767
768         /* If the client is a dock window, we don’t need to render anything */
769         if (client->dock)
770                 return 1;
771
772         if (client->container->mode == MODE_STACK)
773                 render_container(conn, client->container);
774         else decorate_window(conn, client, client->frame, client->titlegc, 0);
775         xcb_flush(conn);
776
777         return 1;
778 }
779
780 /*
781  * Expose event means we should redraw our windows (= title bar)
782  *
783  */
784 int handle_expose_event(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
785         /* event->count is the number of minimum remaining expose events for this window, so we
786            skip all events but the last one */
787         if (event->count != 0)
788                 return 1;
789         LOG("window = %08x\n", event->window);
790
791         Client *client = table_get(byParent, event->window);
792         if (client == NULL) {
793                 /* There was no client in the table, so this is probably an expose event for
794                    one of our stack_windows. */
795                 struct Stack_Window *stack_win;
796                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
797                         if (stack_win->window == event->window) {
798                                 render_container(conn, stack_win->container);
799                                 return 1;
800                         }
801
802                 /* …or one of the bars? */
803                 i3Screen *screen;
804                 TAILQ_FOREACH(screen, virtual_screens, screens) {
805                         if (screen->bar == event->window) {
806                                 render_layout(conn);
807                         }
808                 }
809                 return 1;
810         }
811
812         LOG("got client %s\n", client->name);
813         if (client->dock) {
814                 LOG("this is a dock\n");
815                 return 1;
816         }
817
818         if (client->container->mode != MODE_STACK)
819                 decorate_window(conn, client, client->frame, client->titlegc, 0);
820         else {
821                 uint32_t background_color;
822                 /* Distinguish if the window is currently focused… */
823                 if (CUR_CELL->currently_focused == client)
824                         background_color = get_colorpixel(conn, "#285577");
825                 /* …or if it is the focused window in a not focused container */
826                 else background_color = get_colorpixel(conn, "#555555");
827
828                 /* Set foreground color to current focused color, line width to 2 */
829                 uint32_t values[] = {background_color, 2};
830                 xcb_change_gc(conn, client->titlegc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
831
832                 /* Draw the border, the ±1 is for line width = 2 */
833                 xcb_point_t points[] = {{1, 0},                                           /* left upper edge */
834                                         {1, client->rect.height-1},                       /* left bottom edge */
835                                         {client->rect.width-1, client->rect.height-1},    /* right bottom edge */
836                                         {client->rect.width-1, 0}};                       /* right upper edge */
837                 xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, client->frame, client->titlegc, 4, points);
838
839                 /* Draw a black background */
840                 xcb_change_gc_single(conn, client->titlegc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
841                 xcb_rectangle_t crect = {2, 0, client->rect.width - (2 + 2), client->rect.height - 2};
842                 xcb_poly_fill_rectangle(conn, client->frame, client->titlegc, 1, &crect);
843         }
844         xcb_flush(conn);
845         return 1;
846 }
847
848 /*
849  * Handle client messages (EWMH)
850  *
851  */
852 int handle_client_message(void *data, xcb_connection_t *conn, xcb_client_message_event_t *event) {
853         LOG("client_message\n");
854
855         if (event->type == atoms[_NET_WM_STATE]) {
856                 if (event->format != 32 || event->data.data32[1] != atoms[_NET_WM_STATE_FULLSCREEN])
857                         return 0;
858
859                 LOG("fullscreen\n");
860
861                 Client *client = table_get(byChild, event->window);
862                 if (client == NULL)
863                         return 0;
864
865                 /* Check if the fullscreen state should be toggled */
866                 if ((client->fullscreen &&
867                      (event->data.data32[0] == _NET_WM_STATE_REMOVE ||
868                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)) ||
869                     (!client->fullscreen &&
870                      (event->data.data32[0] == _NET_WM_STATE_ADD ||
871                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)))
872                         toggle_fullscreen(conn, client);
873         } else {
874                 LOG("unhandled clientmessage\n");
875                 return 0;
876         }
877
878         return 1;
879 }
880
881 int handle_window_type(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
882                         xcb_atom_t atom, xcb_get_property_reply_t *property) {
883         /* TODO: Implement this one. To do this, implement a little test program which sleep(1)s
884          before changing this property. */
885         LOG("_NET_WM_WINDOW_TYPE changed, this is not yet implemented.\n");
886         return 0;
887 }
888
889 /*
890  * Handles the size hints set by a window, but currently only the part necessary for displaying
891  * clients proportionally inside their frames (mplayer for example)
892  *
893  * See ICCCM 4.1.2.3 for more details
894  *
895  */
896 int handle_normal_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
897                         xcb_atom_t name, xcb_get_property_reply_t *reply) {
898         LOG("handle_normal_hints\n");
899         Client *client = table_get(byChild, window);
900         if (client == NULL) {
901                 LOG("No such client\n");
902                 return 1;
903         }
904         xcb_size_hints_t size_hints;
905
906         /* If the hints were already in this event, use them, if not, request them */
907         if (reply != NULL)
908                 xcb_get_wm_size_hints_from_reply(&size_hints, reply);
909         else
910                 xcb_get_wm_normal_hints_reply(conn, xcb_get_wm_normal_hints_unchecked(conn, client->child), &size_hints, NULL);
911
912         /* If no aspect ratio was set or if it was invalid, we ignore the hints */
913         if (!(size_hints.flags & XCB_SIZE_HINT_P_ASPECT) ||
914             (size_hints.min_aspect_num <= 0) ||
915             (size_hints.min_aspect_den <= 0)) {
916                 LOG("No aspect ratio set, ignoring\n");
917                 return 1;
918         }
919
920         LOG("window is %08x / %s\n", client->child, client->name);
921
922         int base_width = 0, base_height = 0,
923             min_width = 0, min_height = 0;
924
925         /* base_width/height are the desired size of the window.
926            We check if either the program-specified size or the program-specified
927            min-size is available */
928         if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
929                 base_width = size_hints.base_width;
930                 base_height = size_hints.base_height;
931         } else if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
932                 base_width = size_hints.min_width;
933                 base_height = size_hints.min_height;
934         }
935
936         if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
937                 min_width = size_hints.min_width;
938                 min_height = size_hints.min_height;
939         } else if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
940                 min_width = size_hints.base_width;
941                 min_height = size_hints.base_height;
942         }
943
944         double width = client->rect.width - base_width;
945         double height = client->rect.height - base_height;
946         /* Convert numerator/denominator to a double */
947         double min_aspect = (double)size_hints.min_aspect_num / size_hints.min_aspect_den;
948         double max_aspect = (double)size_hints.max_aspect_num / size_hints.min_aspect_den;
949
950         LOG("min_aspect = %f, max_aspect = %f\n", min_aspect, max_aspect);
951         LOG("width = %f, height = %f\n", width, height);
952
953         /* Sanity checks, this is user-input, in a way */
954         if (max_aspect <= 0 || min_aspect <= 0 || height == 0 || (width / height) <= 0)
955                 return 1;
956
957         /* Check if we need to set proportional_* variables using the correct ratio */
958         if ((width / height) < min_aspect) {
959                 client->proportional_width = width;
960                 client->proportional_height = width / min_aspect;
961         } else if ((width / height) > max_aspect) {
962                 client->proportional_width = width;
963                 client->proportional_height = width / max_aspect;
964         } else return 1;
965
966         client->force_reconfigure = true;
967
968         if (client->container != NULL) {
969                 render_container(conn, client->container);
970                 xcb_flush(conn);
971         }
972
973         return 1;
974 }