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