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