]> git.sur5r.net Git - i3/i3/blob - src/handlers.c
Bugfix: Delete empty workspaces even when they’re not the active workspace
[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 = &workspaces[screen->current_workspace];
177                 LOG("We're now on virtual screen number %d\n", screen->num);
178                 return 1;
179         }
180
181         /* Do plausibility checks: This event may be useless for us if it occurs on a window
182            which is in a stacked container but not the focused one */
183         if (client->container != NULL &&
184             client->container->mode == MODE_STACK &&
185             client->container->currently_focused != client) {
186                 LOG("Plausibility check says: no\n");
187                 return 1;
188         }
189
190         set_focus(conn, client, false);
191
192         return 1;
193 }
194
195 /*
196  * Checks if the button press was on a stack window, handles focus setting and returns true
197  * if so, or false otherwise.
198  *
199  */
200 static bool button_press_stackwin(xcb_connection_t *conn, xcb_button_press_event_t *event) {
201         struct Stack_Window *stack_win;
202         SLIST_FOREACH(stack_win, &stack_wins, stack_windows) {
203                 if (stack_win->window != event->event)
204                         continue;
205
206                 /* A stack window was clicked, we check if it was button4 or button5
207                    which are scroll up / scroll down. */
208                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
209                         direction_t direction = (event->detail == XCB_BUTTON_INDEX_4 ? D_UP : D_DOWN);
210                         focus_window_in_container(conn, CUR_CELL, direction);
211                         return true;
212                 }
213
214                 /* It was no scrolling, so we calculate the destination client by
215                    dividing the Y position of the event through the height of a window
216                    decoration and then set the focus to this client. */
217                 i3Font *font = load_font(conn, config.font);
218                 int decoration_height = (font->height + 2 + 2);
219                 int destination = (event->event_y / decoration_height),
220                     c = 0;
221                 Client *client;
222
223                 LOG("Click on stack_win for client %d\n", destination);
224                 CIRCLEQ_FOREACH(client, &(stack_win->container->clients), clients)
225                         if (c++ == destination) {
226                                 set_focus(conn, client, true);
227                                 return true;
228                         }
229
230                 return true;
231         }
232
233         return false;
234 }
235
236 /*
237  * Checks if the button press was on a bar, switches to the workspace and returns true
238  * if so, or false otherwise.
239  *
240  */
241 static bool button_press_bar(xcb_connection_t *conn, xcb_button_press_event_t *event) {
242         i3Screen *screen;
243         TAILQ_FOREACH(screen, virtual_screens, screens) {
244                 if (screen->bar != event->event)
245                         continue;
246
247                 LOG("Click on a bar\n");
248
249                 /* Check if the button was one of button4 or button5 (scroll up / scroll down) */
250                 if (event->detail == XCB_BUTTON_INDEX_4 || event->detail == XCB_BUTTON_INDEX_5) {
251                         int dest_workspace = (event->detail == XCB_BUTTON_INDEX_4 ?
252                                               c_ws->num - 1 :
253                                               c_ws->num + 1);
254                         if ((dest_workspace >= 0) && (dest_workspace < 10))
255                                 show_workspace(conn, dest_workspace+1);
256                         return true;
257                 }
258                 i3Font *font = load_font(conn, config.font);
259                 int workspace = event->event_x / (font->height + 6),
260                     c = 0;
261                 /* Because workspaces can be on different screens, we need to loop
262                    through all of them and decide to count it based on its ->screen */
263                 for (int i = 0; i < 10; i++)
264                         if ((workspaces[i].screen == screen) && (c++ == workspace)) {
265                                 show_workspace(conn, i+1);
266                                 return true;
267                         }
268                 return true;
269         }
270
271         return false;
272 }
273
274 int handle_button_press(void *ignored, xcb_connection_t *conn, xcb_button_press_event_t *event) {
275         LOG("button press!\n");
276         /* This was either a focus for a client’s parent (= titlebar)… */
277         Client *client = table_get(byChild, event->event);
278         bool border_click = false;
279         if (client == NULL) {
280                 client = table_get(byParent, event->event);
281                 border_click = true;
282         }
283         if (client == NULL) {
284                 /* The client was neither on a client’s titlebar nor on a client itself, maybe on a stack_window? */
285                 if (button_press_stackwin(conn, event))
286                         return 1;
287
288                 /* Or on a bar? */
289                 if (button_press_bar(conn, event))
290                         return 1;
291
292                 LOG("Could not handle this button press\n");
293                 return 1;
294         }
295
296         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
297         xcb_screen_t *root_screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
298
299         /* Set focus in any case */
300         set_focus(conn, client, true);
301
302         /* Let’s see if this was on the borders (= resize). If not, we’re done */
303         LOG("press button on x=%d, y=%d\n", event->event_x, event->event_y);
304
305         Container *con = client->container,
306                   *first = NULL,
307                   *second = NULL;
308         enum { O_HORIZONTAL, O_VERTICAL } orientation = O_VERTICAL;
309         int new_position;
310
311         if (con == NULL) {
312                 LOG("dock. done.\n");
313                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
314                 xcb_flush(conn);
315                 return 1;
316         }
317
318         LOG("event->event_x = %d, client->rect.width = %d\n", event->event_x, client->rect.width);
319
320         if (!border_click) {
321                 LOG("client. done.\n");
322                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
323                 xcb_flush(conn);
324                 return 1;
325         }
326
327         /* Don’t handle events inside the titlebar, only borders are interesting */
328         i3Font *font = load_font(conn, config.font);
329         if (event->event_y >= 2 && event->event_y <= (font->height + 2 + 2)) {
330                 LOG("click on titlebar\n");
331                 return 1;
332         }
333
334         if (event->event_y < 2) {
335                 /* This was a press on the top border */
336                 if (con->row == 0)
337                         return 1;
338                 first = con->workspace->table[con->col][con->row-1];
339                 second = con;
340                 orientation = O_HORIZONTAL;
341         } else if (event->event_y >= (client->rect.height - 2)) {
342                 /* …bottom border */
343                 if (con->row == (con->workspace->rows-1))
344                         return 1;
345                 first = con;
346                 second = con->workspace->table[con->col][con->row+1];
347                 orientation = O_HORIZONTAL;
348         } else if (event->event_x <= 2) {
349                 /* …left border */
350                 if (con->col == 0)
351                         return 1;
352                 first = con->workspace->table[con->col-1][con->row];
353                 second = con;
354         } else if (event->event_x > 2) {
355                 /* …right border */
356                 if (con->col == (con->workspace->cols-1))
357                         return 1;
358                 first = con;
359                 second = con->workspace->table[con->col+1][con->row];
360         }
361
362         /* FIXME: horizontal resizing causes empty spaces to exist */
363         if (orientation == O_HORIZONTAL) {
364                 LOG("Sorry, horizontal resizing is not yet activated due to creating layout bugs."
365                     "If you are brave, enable the code for yourself and try fixing it.\n");
366                 return 1;
367         }
368
369         uint32_t mask = 0;
370         uint32_t values[2];
371
372         mask = XCB_CW_OVERRIDE_REDIRECT;
373         values[0] = 1;
374
375         /* Open a new window, the resizebar. Grab the pointer and move the window around
376            as the user moves the pointer. */
377         Rect grabrect = {0, 0, root_screen->width_in_pixels, root_screen->height_in_pixels};
378         xcb_window_t grabwin = create_window(conn, grabrect, XCB_WINDOW_CLASS_INPUT_ONLY, -1, mask, values);
379
380         Rect helprect;
381         if (orientation == O_VERTICAL) {
382                 helprect.x = event->root_x;
383                 helprect.y = 0;
384                 helprect.width = 2;
385                 helprect.height = root_screen->height_in_pixels; /* this has to be the cell’s height */
386                 new_position = event->root_x;
387         } else {
388                 helprect.x = 0;
389                 helprect.y = event->root_y;
390                 helprect.width = root_screen->width_in_pixels; /* this has to be the cell’s width */
391                 helprect.height = 2;
392                 new_position = event->root_y;
393         }
394
395         mask = XCB_CW_BACK_PIXEL;
396         values[0] = get_colorpixel(conn, "#4c7899");
397
398         mask |= XCB_CW_OVERRIDE_REDIRECT;
399         values[1] = 1;
400
401         xcb_window_t helpwin = create_window(conn, helprect, XCB_WINDOW_CLASS_INPUT_OUTPUT,
402                                              (orientation == O_VERTICAL ?
403                                               XCB_CURSOR_SB_V_DOUBLE_ARROW :
404                                               XCB_CURSOR_SB_H_DOUBLE_ARROW), mask, values);
405
406         xcb_circulate_window(conn, XCB_CIRCULATE_RAISE_LOWEST, helpwin);
407
408         xcb_grab_pointer(conn, false, root, XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION,
409                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, grabwin, XCB_NONE, XCB_CURRENT_TIME);
410
411         xcb_flush(conn);
412
413         xcb_generic_event_t *inside_event;
414         /* I’ve always wanted to have my own eventhandler… */
415         while ((inside_event = xcb_wait_for_event(conn))) {
416                 /* Same as get_event_handler in xcb */
417                 int nr = inside_event->response_type;
418                 if (nr == 0) {
419                         /* An error occured */
420                         handle_event(NULL, conn, inside_event);
421                         free(inside_event);
422                         continue;
423                 }
424                 assert(nr < 256);
425                 nr &= XCB_EVENT_RESPONSE_TYPE_MASK;
426                 assert(nr >= 2);
427
428                 /* Check if we need to escape this loop */
429                 if (nr == XCB_BUTTON_RELEASE)
430                         break;
431
432                 switch (nr) {
433                         case XCB_MOTION_NOTIFY:
434                                 if (orientation == O_VERTICAL) {
435                                         values[0] = new_position = ((xcb_motion_notify_event_t*)inside_event)->root_x;
436                                         xcb_configure_window(conn, helpwin, XCB_CONFIG_WINDOW_X, values);
437                                 } else {
438                                         values[0] = new_position = ((xcb_motion_notify_event_t*)inside_event)->root_y;
439                                         xcb_configure_window(conn, helpwin, XCB_CONFIG_WINDOW_Y, values);
440                                 }
441
442                                 xcb_flush(conn);
443                                 break;
444                         default:
445                                 LOG("Passing to original handler\n");
446                                 /* Use original handler */
447                                 xcb_event_handle(&evenths, inside_event);
448                                 break;
449                 }
450                 free(inside_event);
451         }
452
453         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
454         xcb_destroy_window(conn, helpwin);
455         xcb_destroy_window(conn, grabwin);
456         xcb_flush(conn);
457
458         Workspace *ws = con->workspace;
459         if (orientation == O_VERTICAL) {
460                 LOG("Resize was from X = %d to X = %d\n", event->root_x, new_position);
461                 if (event->root_x == new_position) {
462                         LOG("Nothing changed, not updating anything\n");
463                         return 1;
464                 }
465
466                 /* Convert 0 (for default width_factor) to actual numbers */
467                 if (first->width_factor == 0)
468                         first->width_factor = ((float)ws->rect.width / ws->cols) / ws->rect.width;
469                 if (second->width_factor == 0)
470                         second->width_factor = ((float)ws->rect.width / ws->cols) / ws->rect.width;
471
472                 first->width_factor *= (float)(first->width + (new_position - event->root_x)) / first->width;
473                 second->width_factor *= (float)(second->width - (new_position - event->root_x)) / second->width;
474         } else {
475                 LOG("Resize was from Y = %d to Y = %d\n", event->root_y, new_position);
476                 if (event->root_y == new_position) {
477                         LOG("Nothing changed, not updating anything\n");
478                         return 1;
479                 }
480
481                 /* Convert 0 (for default height_factor) to actual numbers */
482                 if (first->height_factor == 0)
483                         first->height_factor = ((float)ws->rect.height / ws->rows) / ws->rect.height;
484                 if (second->height_factor == 0)
485                         second->height_factor = ((float)ws->rect.height / ws->rows) / ws->rect.height;
486
487                 first->height_factor *= (float)(first->height + (new_position - event->root_y)) / first->height;
488                 second->height_factor *= (float)(second->height - (new_position - event->root_y)) / second->height;
489         }
490
491         render_layout(conn);
492
493         return 1;
494 }
495
496 /*
497  * A new window appeared on the screen (=was mapped), so let’s manage it.
498  *
499  */
500 int handle_map_request(void *prophs, xcb_connection_t *conn, xcb_map_request_event_t *event) {
501         xcb_get_window_attributes_cookie_t cookie;
502         xcb_get_window_attributes_reply_t *reply;
503
504         cookie = xcb_get_window_attributes_unchecked(conn, event->window);
505
506         if ((reply = xcb_get_window_attributes_reply(conn, cookie, NULL)) == NULL) {
507                 LOG("Could not get window attributes\n");
508                 return -1;
509         }
510
511         window_attributes_t wa = { TAG_VALUE };
512         LOG("override_redirect = %d\n", reply->override_redirect);
513         wa.u.override_redirect = reply->override_redirect;
514         LOG("window = 0x%08x, serial is %d.\n", event->window, event->sequence);
515         add_ignore_event(event->sequence);
516
517         manage_window(prophs, conn, event->window, wa);
518         return 1;
519 }
520
521 /*
522  * Configure requests are received when the application wants to resize windows on their own.
523  *
524  * We generate a synthethic configure notify event to signalize the client its "new" position.
525  *
526  */
527 int handle_configure_request(void *prophs, xcb_connection_t *conn, xcb_configure_request_event_t *event) {
528         LOG("configure-request, serial %d\n", event->sequence);
529         LOG("event->window = %08x\n", event->window);
530         LOG("application wants to be at %dx%d with %dx%d\n", event->x, event->y, event->width, event->height);
531
532         Client *client = table_get(byChild, event->window);
533         if (client == NULL) {
534                 LOG("This client is not mapped, so we don't care and just tell the client that he will get its size\n");
535                 Rect rect = {event->x, event->y, event->width, event->height};
536                 fake_configure_notify(conn, rect, event->window);
537                 return 1;
538         }
539
540         fake_configure_notify(conn, client->child_rect, client->child);
541
542         return 1;
543 }
544
545 /*
546  * Configuration notifies are only handled because we need to set up ignore for the following
547  * enter notify events
548  *
549  */
550 int handle_configure_event(void *prophs, xcb_connection_t *conn, xcb_configure_notify_event_t *event) {
551         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
552
553         LOG("handle_configure_event for window %08x\n", event->window);
554         LOG("event->type = %d, \n", event->response_type);
555         LOG("event->x = %d, ->y = %d, ->width = %d, ->height = %d\n", event->x, event->y, event->width, event->height);
556         add_ignore_event(event->sequence);
557
558         if (event->event == root) {
559                 LOG("reconfigure of the root window, need to xinerama\n");
560                 /* FIXME: Somehow, this is occuring too often. Therefore, we check for 0/0,
561                    but is there a better way? */
562                 if (event->x == 0 && event->y == 0)
563                         xinerama_requery_screens(conn);
564                 return 1;
565         }
566
567         return 1;
568 }
569
570 /*
571  * Our window decorations were unmapped. That means, the window will be killed now,
572  * so we better clean up before.
573  *
574  */
575 int handle_unmap_notify_event(void *data, xcb_connection_t *conn, xcb_unmap_notify_event_t *event) {
576         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
577
578         add_ignore_event(event->sequence);
579
580         Client *client = table_get(byChild, event->window);
581         /* First, we need to check if the client is awaiting an unmap-request which
582            was generated by us reparenting the window. In that case, we just ignore it. */
583         if (client != NULL && client->awaiting_useless_unmap) {
584                 LOG("Dropping this unmap request, it was generated by reparenting\n");
585                 client->awaiting_useless_unmap = false;
586                 return 1;
587         }
588
589         LOG("event->window = %08x, event->event = %08x\n", event->window, event->event);
590         LOG("UnmapNotify for 0x%08x (received from 0x%08x)\n", event->window, event->event);
591         if (client == NULL) {
592                 LOG("not a managed window. Ignoring.\n");
593                 return 0;
594         }
595
596         client = table_remove(byChild, event->window);
597
598         if (client->name != NULL)
599                 free(client->name);
600
601         if (client->container != NULL) {
602                 Container *con = client->container;
603
604                 /* If this was the fullscreen client, we need to unset it */
605                 if (client->fullscreen)
606                         con->workspace->fullscreen_client = NULL;
607
608                 /* Remove the client from the list of clients */
609                 remove_client_from_container(conn, client, con);
610
611                 /* Set focus to the last focused client in this container */
612                 con->currently_focused = NULL;
613                 Client *focus_client;
614                 SLIST_FOREACH(focus_client, &(con->workspace->focus_stack), focus_clients)
615                         if (focus_client->container == con) {
616                                 con->currently_focused = focus_client;
617                                 /* Only if this is the active container, we need to really change focus */
618                                 if (con == CUR_CELL)
619                                         set_focus(conn, focus_client, false);
620                                 break;
621                         }
622         }
623
624         if (client->dock) {
625                 LOG("Removing from dock clients\n");
626                 SLIST_REMOVE(&(client->workspace->dock_clients), client, Client, dock_clients);
627         }
628
629         LOG("child of 0x%08x.\n", client->frame);
630         xcb_reparent_window(conn, client->child, root, 0, 0);
631         xcb_destroy_window(conn, client->frame);
632         xcb_flush(conn);
633         table_remove(byParent, client->frame);
634
635         if (client->container != NULL)
636                 cleanup_table(conn, client->container->workspace);
637
638         /* Let’s see how many clients there are left on the workspace to delete it if it’s empty */
639         bool workspace_empty = true;
640         FOR_TABLE(client->workspace)
641                 if (!CIRCLEQ_EMPTY(&(client->workspace->table[cols][rows]->clients))) {
642                         workspace_empty = false;
643                         break;
644                 }
645
646         if (workspace_empty)
647                 client->workspace->screen = NULL;
648
649         free(client);
650
651         render_layout(conn);
652
653         return 1;
654 }
655
656 /*
657  * Called when a window changes its title
658  *
659  */
660 int handle_windowname_change(void *data, xcb_connection_t *conn, uint8_t state,
661                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
662         LOG("window's name changed.\n");
663         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
664                 LOG("_NET_WM_NAME not specified, not changing\n");
665                 return 1;
666         }
667         Client *client = table_get(byChild, window);
668         if (client == NULL)
669                 return 1;
670
671         /* Save the old pointer to make the update atomic */
672         char *new_name;
673         int new_len;
674         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
675         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
676         char *ucs2_name = convert_utf8_to_ucs2(new_name, &new_len);
677         LOG("Name should change to \"%s\"\n", new_name);
678         free(new_name);
679
680         /* Check if they are the same and don’t update if so.
681            Note the use of new_len * 2 to check all bytes as each glyph takes 2 bytes.
682            Also note the use of memcmp() instead of strncmp() because the latter stops on nullbytes,
683            but UCS-2 uses nullbytes to fill up glyphs which only use one byte. */
684         if ((new_len == client->name_len) &&
685             (client->name != NULL) &&
686             (memcmp(client->name, ucs2_name, new_len * 2) == 0)) {
687                 LOG("Name did not change, not updating\n");
688                 free(ucs2_name);
689                 return 1;
690         }
691
692         char *old_name = client->name;
693         client->name = ucs2_name;
694         client->name_len = new_len;
695         client->uses_net_wm_name = true;
696
697         if (old_name != NULL)
698                 free(old_name);
699
700         /* If the client is a dock window, we don’t need to render anything */
701         if (client->dock)
702                 return 1;
703
704         if (client->container->mode == MODE_STACK)
705                 render_container(conn, client->container);
706         else decorate_window(conn, client, client->frame, client->titlegc, 0);
707         xcb_flush(conn);
708
709         return 1;
710 }
711
712 /*
713  * We handle legacy window names (titles) which are in COMPOUND_TEXT encoding. However, we
714  * just pass them along, so when containing non-ASCII characters, those will be rendering
715  * incorrectly. In order to correctly render unicode window titles in i3, an application
716  * has to set _NET_WM_NAME, which is in UTF-8 encoding.
717  *
718  * On every update, a message is put out to the user, so he may improve the situation and
719  * update applications which display filenames in their title to correctly use
720  * _NET_WM_NAME and therefore support unicode.
721  *
722  */
723 int handle_windowname_change_legacy(void *data, xcb_connection_t *conn, uint8_t state,
724                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
725         LOG("window's name changed (legacy).\n");
726         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
727                 LOG("prop == NULL\n");
728                 return 1;
729         }
730         Client *client = table_get(byChild, window);
731         if (client == NULL)
732                 return 1;
733
734         if (client->uses_net_wm_name) {
735                 LOG("This client is capable of _NET_WM_NAME, ignoring legacy name\n");
736                 return 1;
737         }
738
739         /* Save the old pointer to make the update atomic */
740         char *new_name;
741         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
742         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
743         LOG("Name should change to \"%s\"\n", new_name);
744
745         /* Check if they are the same and don’t update if so. */
746         if (client->name != NULL &&
747             strlen(new_name) == strlen(client->name) &&
748             strcmp(client->name, new_name) == 0) {
749                 LOG("Name did not change, not updating\n");
750                 free(new_name);
751                 return 1;
752         }
753
754         LOG("Using legacy window title. Note that in order to get Unicode window titles in i3,"
755             "the application has to set _NET_WM_NAME which is in UTF-8 encoding.\n");
756
757         char *old_name = client->name;
758         client->name = new_name;
759         client->name_len = -1;
760
761         if (old_name != NULL)
762                 free(old_name);
763
764         /* If the client is a dock window, we don’t need to render anything */
765         if (client->dock)
766                 return 1;
767
768         if (client->container->mode == MODE_STACK)
769                 render_container(conn, client->container);
770         else decorate_window(conn, client, client->frame, client->titlegc, 0);
771         xcb_flush(conn);
772
773         return 1;
774 }
775
776 /*
777  * Expose event means we should redraw our windows (= title bar)
778  *
779  */
780 int handle_expose_event(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
781         /* event->count is the number of minimum remaining expose events for this window, so we
782            skip all events but the last one */
783         if (event->count != 0)
784                 return 1;
785         LOG("window = %08x\n", event->window);
786
787         Client *client = table_get(byParent, event->window);
788         if (client == NULL) {
789                 /* There was no client in the table, so this is probably an expose event for
790                    one of our stack_windows. */
791                 struct Stack_Window *stack_win;
792                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
793                         if (stack_win->window == event->window) {
794                                 render_container(conn, stack_win->container);
795                                 return 1;
796                         }
797
798                 /* …or one of the bars? */
799                 i3Screen *screen;
800                 TAILQ_FOREACH(screen, virtual_screens, screens) {
801                         if (screen->bar == event->window) {
802                                 render_layout(conn);
803                         }
804                 }
805                 return 1;
806         }
807
808         LOG("got client %s\n", client->name);
809         if (client->dock) {
810                 LOG("this is a dock\n");
811                 return 1;
812         }
813
814         if (client->container->mode != MODE_STACK)
815                 decorate_window(conn, client, client->frame, client->titlegc, 0);
816         else {
817                 uint32_t background_color;
818                 /* Distinguish if the window is currently focused… */
819                 if (CUR_CELL->currently_focused == client)
820                         background_color = get_colorpixel(conn, "#285577");
821                 /* …or if it is the focused window in a not focused container */
822                 else background_color = get_colorpixel(conn, "#555555");
823
824                 /* Set foreground color to current focused color, line width to 2 */
825                 uint32_t values[] = {background_color, 2};
826                 xcb_change_gc(conn, client->titlegc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
827
828                 /* Draw the border, the ±1 is for line width = 2 */
829                 xcb_point_t points[] = {{1, 0},                                           /* left upper edge */
830                                         {1, client->rect.height-1},                       /* left bottom edge */
831                                         {client->rect.width-1, client->rect.height-1},    /* right bottom edge */
832                                         {client->rect.width-1, 0}};                       /* right upper edge */
833                 xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, client->frame, client->titlegc, 4, points);
834
835                 /* Draw a black background */
836                 xcb_change_gc_single(conn, client->titlegc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
837                 xcb_rectangle_t crect = {2, 0, client->rect.width - (2 + 2), client->rect.height - 2};
838                 xcb_poly_fill_rectangle(conn, client->frame, client->titlegc, 1, &crect);
839         }
840         xcb_flush(conn);
841         return 1;
842 }
843
844 /*
845  * Handle client messages (EWMH)
846  *
847  */
848 int handle_client_message(void *data, xcb_connection_t *conn, xcb_client_message_event_t *event) {
849         LOG("client_message\n");
850
851         if (event->type == atoms[_NET_WM_STATE]) {
852                 if (event->format != 32 || event->data.data32[1] != atoms[_NET_WM_STATE_FULLSCREEN])
853                         return 0;
854
855                 LOG("fullscreen\n");
856
857                 Client *client = table_get(byChild, event->window);
858                 if (client == NULL)
859                         return 0;
860
861                 /* Check if the fullscreen state should be toggled */
862                 if ((client->fullscreen &&
863                      (event->data.data32[0] == _NET_WM_STATE_REMOVE ||
864                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)) ||
865                     (!client->fullscreen &&
866                      (event->data.data32[0] == _NET_WM_STATE_ADD ||
867                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)))
868                         toggle_fullscreen(conn, client);
869         } else {
870                 LOG("unhandled clientmessage\n");
871                 return 0;
872         }
873
874         return 1;
875 }
876
877 int handle_window_type(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
878                         xcb_atom_t atom, xcb_get_property_reply_t *property) {
879         /* TODO: Implement this one. To do this, implement a little test program which sleep(1)s
880          before changing this property. */
881         LOG("_NET_WM_WINDOW_TYPE changed, this is not yet implemented.\n");
882         return 0;
883 }
884
885 /*
886  * Handles the size hints set by a window, but currently only the part necessary for displaying
887  * clients proportionally inside their frames (mplayer for example)
888  *
889  * See ICCCM 4.1.2.3 for more details
890  *
891  */
892 int handle_normal_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
893                         xcb_atom_t name, xcb_get_property_reply_t *reply) {
894         LOG("handle_normal_hints\n");
895         Client *client = table_get(byChild, window);
896         if (client == NULL) {
897                 LOG("No such client\n");
898                 return 1;
899         }
900         xcb_size_hints_t size_hints;
901
902         /* If the hints were already in this event, use them, if not, request them */
903         if (reply != NULL)
904                 xcb_get_wm_size_hints_from_reply(&size_hints, reply);
905         else
906                 xcb_get_wm_normal_hints_reply(conn, xcb_get_wm_normal_hints_unchecked(conn, client->child), &size_hints, NULL);
907
908         /* If no aspect ratio was set or if it was invalid, we ignore the hints */
909         if (!(size_hints.flags & XCB_SIZE_HINT_P_ASPECT) ||
910             (size_hints.min_aspect_num <= 0) ||
911             (size_hints.min_aspect_den <= 0)) {
912                 LOG("No aspect ratio set, ignoring\n");
913                 return 1;
914         }
915
916         LOG("window is %08x / %s\n", client->child, client->name);
917
918         int base_width = 0, base_height = 0,
919             min_width = 0, min_height = 0;
920
921         /* base_width/height are the desired size of the window.
922            We check if either the program-specified size or the program-specified
923            min-size is available */
924         if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
925                 base_width = size_hints.base_width;
926                 base_height = size_hints.base_height;
927         } else if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
928                 base_width = size_hints.min_width;
929                 base_height = size_hints.min_height;
930         }
931
932         if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
933                 min_width = size_hints.min_width;
934                 min_height = size_hints.min_height;
935         } else if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
936                 min_width = size_hints.base_width;
937                 min_height = size_hints.base_height;
938         }
939
940         double width = client->rect.width - base_width;
941         double height = client->rect.height - base_height;
942         /* Convert numerator/denominator to a double */
943         double min_aspect = (double)size_hints.min_aspect_num / size_hints.min_aspect_den;
944         double max_aspect = (double)size_hints.max_aspect_num / size_hints.min_aspect_den;
945
946         LOG("min_aspect = %f, max_aspect = %f\n", min_aspect, max_aspect);
947         LOG("width = %f, height = %f\n", width, height);
948
949         /* Sanity checks, this is user-input, in a way */
950         if (max_aspect <= 0 || min_aspect <= 0 || height == 0 || (width / height) <= 0)
951                 return 1;
952
953         /* Check if we need to set proportional_* variables using the correct ratio */
954         if ((width / height) < min_aspect) {
955                 client->proportional_width = width;
956                 client->proportional_height = width / min_aspect;
957         } else if ((width / height) > max_aspect) {
958                 client->proportional_width = width;
959                 client->proportional_height = width / max_aspect;
960         } else return 1;
961
962         client->force_reconfigure = true;
963
964         if (client->container != NULL) {
965                 render_container(conn, client->container);
966                 xcb_flush(conn);
967         }
968
969         return 1;
970 }