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