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