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