]> git.sur5r.net Git - i3/i3/blob - src/handlers.c
Refactor the interface of commands.c
[i3/i3] / src / handlers.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * handlers.c: Small handlers for various events (keypresses, focus changes,
8  *             …).
9  *
10  */
11 #include "all.h"
12
13 #include <time.h>
14 #include <xcb/randr.h>
15 #include <X11/XKBlib.h>
16 #define SN_API_NOT_YET_FROZEN 1
17 #include <libsn/sn-monitor.h>
18
19 int randr_base = -1;
20
21 /* After mapping/unmapping windows, a notify event is generated. However, we don’t want it,
22    since it’d trigger an infinite loop of switching between the different windows when
23    changing workspaces */
24 static SLIST_HEAD(ignore_head, Ignore_Event) ignore_events;
25
26 /*
27  * Adds the given sequence to the list of events which are ignored.
28  * If this ignore should only affect a specific response_type, pass
29  * response_type, otherwise, pass -1.
30  *
31  * Every ignored sequence number gets garbage collected after 5 seconds.
32  *
33  */
34 void add_ignore_event(const int sequence, const int response_type) {
35     struct Ignore_Event *event = smalloc(sizeof(struct Ignore_Event));
36
37     event->sequence = sequence;
38     event->response_type = response_type;
39     event->added = time(NULL);
40
41     SLIST_INSERT_HEAD(&ignore_events, event, ignore_events);
42 }
43
44 /*
45  * Checks if the given sequence is ignored and returns true if so.
46  *
47  */
48 bool event_is_ignored(const int sequence, const int response_type) {
49     struct Ignore_Event *event;
50     time_t now = time(NULL);
51     for (event = SLIST_FIRST(&ignore_events); event != SLIST_END(&ignore_events);) {
52         if ((now - event->added) > 5) {
53             struct Ignore_Event *save = event;
54             event = SLIST_NEXT(event, ignore_events);
55             SLIST_REMOVE(&ignore_events, save, Ignore_Event, ignore_events);
56             free(save);
57         } else event = SLIST_NEXT(event, ignore_events);
58     }
59
60     SLIST_FOREACH(event, &ignore_events, ignore_events) {
61         if (event->sequence != sequence)
62             continue;
63
64         if (event->response_type != -1 &&
65             event->response_type != response_type)
66             continue;
67
68         /* instead of removing a sequence number we better wait until it gets
69          * garbage collected. it may generate multiple events (there are multiple
70          * enter_notifies for one configure_request, for example). */
71         //SLIST_REMOVE(&ignore_events, event, Ignore_Event, ignore_events);
72         //free(event);
73         return true;
74     }
75
76     return false;
77 }
78
79
80 /*
81  * There was a key press. We compare this key code with our bindings table and pass
82  * the bound action to parse_command().
83  *
84  */
85 static void handle_key_press(xcb_key_press_event_t *event) {
86
87     last_timestamp = event->time;
88
89     DLOG("Keypress %d, state raw = %d\n", event->detail, event->state);
90
91     /* Remove the numlock bit, all other bits are modifiers we can bind to */
92     uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
93     DLOG("(removed numlock, state = %d)\n", state_filtered);
94     /* Only use the lower 8 bits of the state (modifier masks) so that mouse
95      * button masks are filtered out */
96     state_filtered &= 0xFF;
97     DLOG("(removed upper 8 bits, state = %d)\n", state_filtered);
98
99     if (xkb_current_group == XkbGroup2Index)
100         state_filtered |= BIND_MODE_SWITCH;
101
102     DLOG("(checked mode_switch, state %d)\n", state_filtered);
103
104     /* Find the binding */
105     Binding *bind = get_binding(state_filtered, event->detail);
106
107     /* No match? Then the user has Mode_switch enabled but does not have a
108      * specific keybinding. Fall back to the default keybindings (without
109      * Mode_switch). Makes it much more convenient for users of a hybrid
110      * layout (like us, ru). */
111     if (bind == NULL) {
112         state_filtered &= ~(BIND_MODE_SWITCH);
113         DLOG("no match, new state_filtered = %d\n", state_filtered);
114         if ((bind = get_binding(state_filtered, event->detail)) == NULL) {
115             ELOG("Could not lookup key binding (modifiers %d, keycode %d)\n",
116                  state_filtered, event->detail);
117             return;
118         }
119     }
120
121     struct CommandResult *command_output = parse_command(bind->command);
122
123     if (command_output->needs_tree_render)
124         tree_render();
125
126     free(command_output->json_output);
127 }
128
129 /*
130  * Called with coordinates of an enter_notify event or motion_notify event
131  * to check if the user crossed virtual screen boundaries and adjust the
132  * current workspace, if so.
133  *
134  */
135 static void check_crossing_screen_boundary(uint32_t x, uint32_t y) {
136     Output *output;
137
138     /* If the user disable focus follows mouse, we have nothing to do here */
139     if (config.disable_focus_follows_mouse)
140         return;
141
142     if ((output = get_output_containing(x, y)) == NULL) {
143         ELOG("ERROR: No such screen\n");
144         return;
145     }
146
147     if (output->con == NULL) {
148         ELOG("ERROR: The screen is not recognized by i3 (no container associated)\n");
149         return;
150     }
151
152     /* Focus the output on which the user moved his cursor */
153     Con *old_focused = focused;
154     Con *next = con_descend_focused(output_get_content(output->con));
155     /* Since we are switching outputs, this *must* be a different workspace, so
156      * call workspace_show() */
157     workspace_show(con_get_workspace(next));
158     con_focus(next);
159
160     /* If the focus changed, we re-render to get updated decorations */
161     if (old_focused != focused)
162         tree_render();
163 }
164
165 /*
166  * When the user moves the mouse pointer onto a window, this callback gets called.
167  *
168  */
169 static void handle_enter_notify(xcb_enter_notify_event_t *event) {
170     Con *con;
171
172     last_timestamp = event->time;
173
174     DLOG("enter_notify for %08x, mode = %d, detail %d, serial %d\n",
175          event->event, event->mode, event->detail, event->sequence);
176     DLOG("coordinates %d, %d\n", event->event_x, event->event_y);
177     if (event->mode != XCB_NOTIFY_MODE_NORMAL) {
178         DLOG("This was not a normal notify, ignoring\n");
179         return;
180     }
181     /* Some events are not interesting, because they were not generated
182      * actively by the user, but by reconfiguration of windows */
183     if (event_is_ignored(event->sequence, XCB_ENTER_NOTIFY)) {
184         DLOG("Event ignored\n");
185         return;
186     }
187
188     bool enter_child = false;
189     /* Get container by frame or by child window */
190     if ((con = con_by_frame_id(event->event)) == NULL) {
191         con = con_by_window_id(event->event);
192         enter_child = true;
193     }
194
195     /* If not, then the user moved his cursor to the root window. In that case, we adjust c_ws */
196     if (con == NULL) {
197         DLOG("Getting screen at %d x %d\n", event->root_x, event->root_y);
198         check_crossing_screen_boundary(event->root_x, event->root_y);
199         return;
200     }
201
202     if (con->parent->type == CT_DOCKAREA) {
203         DLOG("Ignoring, this is a dock client\n");
204         return;
205     }
206
207     /* see if the user entered the window on a certain window decoration */
208     int layout = (enter_child ? con->parent->layout : con->layout);
209     if (layout == L_DEFAULT) {
210         Con *child;
211         TAILQ_FOREACH(child, &(con->nodes_head), nodes)
212             if (rect_contains(child->deco_rect, event->event_x, event->event_y)) {
213                 LOG("using child %p / %s instead!\n", child, child->name);
214                 con = child;
215                 break;
216             }
217     }
218
219 #if 0
220     if (client->workspace != c_ws && client->workspace->output == c_ws->output) {
221             /* This can happen when a client gets assigned to a different workspace than
222              * the current one (see src/mainx.c:reparent_window). Shortly after it was created,
223              * an enter_notify will follow. */
224             DLOG("enter_notify for a client on a different workspace but the same screen, ignoring\n");
225             return 1;
226     }
227 #endif
228
229     if (config.disable_focus_follows_mouse)
230         return;
231
232     /* Get the currently focused workspace to check if the focus change also
233      * involves changing workspaces. If so, we need to call workspace_show() to
234      * correctly update state and send the IPC event. */
235     Con *ws = con_get_workspace(con);
236     if (ws != con_get_workspace(focused))
237         workspace_show(ws);
238
239     con_focus(con_descend_focused(con));
240     tree_render();
241
242     return;
243 }
244
245 /*
246  * When the user moves the mouse but does not change the active window
247  * (e.g. when having no windows opened but moving mouse on the root screen
248  * and crossing virtual screen boundaries), this callback gets called.
249  *
250  */
251 static void handle_motion_notify(xcb_motion_notify_event_t *event) {
252
253     last_timestamp = event->time;
254
255     /* Skip events where the pointer was over a child window, we are only
256      * interested in events on the root window. */
257     if (event->child != 0)
258         return;
259
260     Con *con;
261     if ((con = con_by_frame_id(event->event)) == NULL) {
262         check_crossing_screen_boundary(event->root_x, event->root_y);
263         return;
264     }
265
266     if (config.disable_focus_follows_mouse)
267         return;
268
269     if (con->layout != L_DEFAULT)
270         return;
271
272     /* see over which rect the user is */
273     Con *current;
274     TAILQ_FOREACH(current, &(con->nodes_head), nodes) {
275         if (!rect_contains(current->deco_rect, event->event_x, event->event_y))
276             continue;
277
278         /* We found the rect, let’s see if this window is focused */
279         if (TAILQ_FIRST(&(con->focus_head)) == current)
280             return;
281
282         con_focus(current);
283         x_push_changes(croot);
284         return;
285     }
286
287     return;
288 }
289
290 /*
291  * Called when the keyboard mapping changes (for example by using Xmodmap),
292  * we need to update our key bindings then (re-translate symbols).
293  *
294  */
295 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
296     if (event->request != XCB_MAPPING_KEYBOARD &&
297         event->request != XCB_MAPPING_MODIFIER)
298         return;
299
300     DLOG("Received mapping_notify for keyboard or modifier mapping, re-grabbing keys\n");
301     xcb_refresh_keyboard_mapping(keysyms, event);
302
303     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
304
305     ungrab_all_keys(conn);
306     translate_keysyms();
307     grab_all_keys(conn, false);
308
309     return;
310 }
311
312 /*
313  * A new window appeared on the screen (=was mapped), so let’s manage it.
314  *
315  */
316 static void handle_map_request(xcb_map_request_event_t *event) {
317     xcb_get_window_attributes_cookie_t cookie;
318
319     cookie = xcb_get_window_attributes_unchecked(conn, event->window);
320
321     DLOG("window = 0x%08x, serial is %d.\n", event->window, event->sequence);
322     add_ignore_event(event->sequence, -1);
323
324     manage_window(event->window, cookie, false);
325     x_push_changes(croot);
326     return;
327 }
328
329 /*
330  * Configure requests are received when the application wants to resize windows
331  * on their own.
332  *
333  * We generate a synthethic configure notify event to signalize the client its
334  * "new" position.
335  *
336  */
337 static void handle_configure_request(xcb_configure_request_event_t *event) {
338     Con *con;
339
340     DLOG("window 0x%08x wants to be at %dx%d with %dx%d\n",
341         event->window, event->x, event->y, event->width, event->height);
342
343     /* For unmanaged windows, we just execute the configure request. As soon as
344      * it gets mapped, we will take over anyways. */
345     if ((con = con_by_window_id(event->window)) == NULL) {
346         DLOG("Configure request for unmanaged window, can do that.\n");
347
348         uint32_t mask = 0;
349         uint32_t values[7];
350         int c = 0;
351 #define COPY_MASK_MEMBER(mask_member, event_member) do { \
352         if (event->value_mask & mask_member) { \
353             mask |= mask_member; \
354             values[c++] = event->event_member; \
355         } \
356 } while (0)
357
358         COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_X, x);
359         COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_Y, y);
360         COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_WIDTH, width);
361         COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_HEIGHT, height);
362         COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_BORDER_WIDTH, border_width);
363         COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_SIBLING, sibling);
364         COPY_MASK_MEMBER(XCB_CONFIG_WINDOW_STACK_MODE, stack_mode);
365
366         xcb_configure_window(conn, event->window, mask, values);
367         xcb_flush(conn);
368
369         return;
370     }
371
372     DLOG("Configure request!\n");
373     if (con_is_floating(con) && con_is_leaf(con)) {
374         /* find the height for the decorations */
375         int deco_height = config.font.height + 5;
376         /* we actually need to apply the size/position changes to the *parent*
377          * container */
378         Rect bsr = con_border_style_rect(con);
379         if (con->border_style == BS_NORMAL) {
380             bsr.y += deco_height;
381             bsr.height -= deco_height;
382         }
383         Con *floatingcon = con->parent;
384
385         Rect newrect = floatingcon->rect;
386
387         if (event->value_mask & XCB_CONFIG_WINDOW_X) {
388             newrect.x = event->x + (-1) * bsr.x;
389             DLOG("proposed x = %d, new x is %d\n", event->x, newrect.x);
390         }
391         if (event->value_mask & XCB_CONFIG_WINDOW_Y) {
392             newrect.y = event->y + (-1) * bsr.y;
393             DLOG("proposed y = %d, new y is %d\n", event->y, newrect.y);
394         }
395         if (event->value_mask & XCB_CONFIG_WINDOW_WIDTH) {
396             newrect.width = event->width + (-1) * bsr.width;
397             newrect.width += con->border_width * 2;
398             DLOG("proposed width = %d, new width is %d (x11 border %d)\n",
399                  event->width, newrect.width, con->border_width);
400         }
401         if (event->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
402             newrect.height = event->height + (-1) * bsr.height;
403             newrect.height += con->border_width * 2;
404             DLOG("proposed height = %d, new height is %d (x11 border %d)\n",
405                  event->height, newrect.height, con->border_width);
406         }
407
408         DLOG("Container is a floating leaf node, will do that.\n");
409         floating_reposition(floatingcon, newrect);
410         return;
411     }
412
413     /* Dock windows can be reconfigured in their height */
414     if (con->parent && con->parent->type == CT_DOCKAREA) {
415         DLOG("Dock window, only height reconfiguration allowed\n");
416         if (event->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
417             DLOG("Height given, changing\n");
418
419             con->geometry.height = event->height;
420             tree_render();
421         }
422     }
423
424     fake_absolute_configure_notify(con);
425
426     return;
427 }
428 #if 0
429
430 /*
431  * Configuration notifies are only handled because we need to set up ignore for
432  * the following enter notify events.
433  *
434  */
435 int handle_configure_event(void *prophs, xcb_connection_t *conn, xcb_configure_notify_event_t *event) {
436     DLOG("configure_event, sequence %d\n", event->sequence);
437         /* We ignore this sequence twice because events for child and frame should be ignored */
438         add_ignore_event(event->sequence);
439         add_ignore_event(event->sequence);
440
441         return 1;
442 }
443 #endif
444
445 /*
446  * Gets triggered upon a RandR screen change event, that is when the user
447  * changes the screen configuration in any way (mode, position, …)
448  *
449  */
450 static void handle_screen_change(xcb_generic_event_t *e) {
451     DLOG("RandR screen change\n");
452
453     randr_query_outputs();
454
455     ipc_send_event("output", I3_IPC_EVENT_OUTPUT, "{\"change\":\"unspecified\"}");
456
457     return;
458 }
459
460 /*
461  * Our window decorations were unmapped. That means, the window will be killed
462  * now, so we better clean up before.
463  *
464  */
465 static void handle_unmap_notify_event(xcb_unmap_notify_event_t *event) {
466     DLOG("UnmapNotify for 0x%08x (received from 0x%08x), serial %d\n", event->window, event->event, event->sequence);
467     xcb_get_input_focus_cookie_t cookie;
468     Con *con = con_by_window_id(event->window);
469     if (con == NULL) {
470         /* This could also be an UnmapNotify for the frame. We need to
471          * decrement the ignore_unmap counter. */
472         con = con_by_frame_id(event->window);
473         if (con == NULL) {
474             LOG("Not a managed window, ignoring UnmapNotify event\n");
475             return;
476         }
477
478         if (con->ignore_unmap > 0)
479             con->ignore_unmap--;
480         /* See the end of this function. */
481         cookie = xcb_get_input_focus(conn);
482         DLOG("ignore_unmap = %d for frame of container %p\n", con->ignore_unmap, con);
483         goto ignore_end;
484     }
485
486     /* See the end of this function. */
487     cookie = xcb_get_input_focus(conn);
488
489     if (con->ignore_unmap > 0) {
490         DLOG("ignore_unmap = %d, dec\n", con->ignore_unmap);
491         con->ignore_unmap--;
492         goto ignore_end;
493     }
494
495     tree_close(con, DONT_KILL_WINDOW, false, false);
496     tree_render();
497     x_push_changes(croot);
498
499 ignore_end:
500     /* If the client (as opposed to i3) destroyed or unmapped a window, an
501      * EnterNotify event will follow (indistinguishable from an EnterNotify
502      * event caused by moving your mouse), causing i3 to set focus to whichever
503      * window is now visible.
504      *
505      * In a complex stacked or tabbed layout (take two v-split containers in a
506      * tabbed container), when the bottom window in tab2 is closed, the bottom
507      * window of tab1 is visible instead. X11 will thus send an EnterNotify
508      * event for the bottom window of tab1, while the focus should be set to
509      * the remaining window of tab2.
510      *
511      * Therefore, we ignore all EnterNotify events which have the same sequence
512      * as an UnmapNotify event. */
513     add_ignore_event(event->sequence, XCB_ENTER_NOTIFY);
514
515     /* Since we just ignored the sequence of this UnmapNotify, we want to make
516      * sure that following events use a different sequence. When putting xterm
517      * into fullscreen and moving the pointer to a different window, without
518      * using GetInputFocus, subsequent (legitimate) EnterNotify events arrived
519      * with the same sequence and thus were ignored (see ticket #609). */
520     free(xcb_get_input_focus_reply(conn, cookie, NULL));
521 }
522
523 /*
524  * A destroy notify event is sent when the window is not unmapped, but
525  * immediately destroyed (for example when starting a window and immediately
526  * killing the program which started it).
527  *
528  * We just pass on the event to the unmap notify handler (by copying the
529  * important fields in the event data structure).
530  *
531  */
532 static void handle_destroy_notify_event(xcb_destroy_notify_event_t *event) {
533     DLOG("destroy notify for 0x%08x, 0x%08x\n", event->event, event->window);
534
535     xcb_unmap_notify_event_t unmap;
536     unmap.sequence = event->sequence;
537     unmap.event = event->event;
538     unmap.window = event->window;
539
540     handle_unmap_notify_event(&unmap);
541 }
542
543 /*
544  * Called when a window changes its title
545  *
546  */
547 static bool handle_windowname_change(void *data, xcb_connection_t *conn, uint8_t state,
548                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
549     Con *con;
550     if ((con = con_by_window_id(window)) == NULL || con->window == NULL)
551         return false;
552
553     window_update_name(con->window, prop, false);
554
555     x_push_changes(croot);
556
557     return true;
558 }
559
560 /*
561  * Handles legacy window name updates (WM_NAME), see also src/window.c,
562  * window_update_name_legacy().
563  *
564  */
565 static bool handle_windowname_change_legacy(void *data, xcb_connection_t *conn, uint8_t state,
566                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
567     Con *con;
568     if ((con = con_by_window_id(window)) == NULL || con->window == NULL)
569         return false;
570
571     window_update_name_legacy(con->window, prop, false);
572
573     x_push_changes(croot);
574
575     return true;
576 }
577
578 /*
579  * Called when a window changes its WM_WINDOW_ROLE.
580  *
581  */
582 static bool handle_windowrole_change(void *data, xcb_connection_t *conn, uint8_t state,
583                                      xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
584     Con *con;
585     if ((con = con_by_window_id(window)) == NULL || con->window == NULL)
586         return false;
587
588     window_update_role(con->window, prop, false);
589
590     return true;
591 }
592
593 #if 0
594 /*
595  * Updates the client’s WM_CLASS property
596  *
597  */
598 static int handle_windowclass_change(void *data, xcb_connection_t *conn, uint8_t state,
599                              xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
600     Con *con;
601     if ((con = con_by_window_id(window)) == NULL || con->window == NULL)
602         return 1;
603
604     window_update_class(con->window, prop, false);
605
606     return 0;
607 }
608 #endif
609
610 /*
611  * Expose event means we should redraw our windows (= title bar)
612  *
613  */
614 static void handle_expose_event(xcb_expose_event_t *event) {
615     Con *parent;
616
617     DLOG("window = %08x\n", event->window);
618
619     if ((parent = con_by_frame_id(event->window)) == NULL) {
620         LOG("expose event for unknown window, ignoring\n");
621         return;
622     }
623
624     /* Since we render to our pixmap on every change anyways, expose events
625      * only tell us that the X server lost (parts of) the window contents. We
626      * can handle that by copying the appropriate part from our pixmap to the
627      * window. */
628     xcb_copy_area(conn, parent->pixmap, parent->frame, parent->pm_gc,
629                   event->x, event->y, event->x, event->y,
630                   event->width, event->height);
631     xcb_flush(conn);
632
633     return;
634 }
635
636 /*
637  * Handle client messages (EWMH)
638  *
639  */
640 static void handle_client_message(xcb_client_message_event_t *event) {
641     /* If this is a startup notification ClientMessage, the library will handle
642      * it and call our monitor_event() callback. */
643     if (sn_xcb_display_process_event(sndisplay, (xcb_generic_event_t*)event))
644         return;
645
646     LOG("ClientMessage for window 0x%08x\n", event->window);
647     if (event->type == A__NET_WM_STATE) {
648         if (event->format != 32 || event->data.data32[1] != A__NET_WM_STATE_FULLSCREEN) {
649             DLOG("atom in clientmessage is %d, fullscreen is %d\n",
650                     event->data.data32[1], A__NET_WM_STATE_FULLSCREEN);
651             DLOG("not about fullscreen atom\n");
652             return;
653         }
654
655         Con *con = con_by_window_id(event->window);
656         if (con == NULL) {
657             DLOG("Could not get window for client message\n");
658             return;
659         }
660
661         /* Check if the fullscreen state should be toggled */
662         if ((con->fullscreen_mode != CF_NONE &&
663              (event->data.data32[0] == _NET_WM_STATE_REMOVE ||
664               event->data.data32[0] == _NET_WM_STATE_TOGGLE)) ||
665             (con->fullscreen_mode == CF_NONE &&
666              (event->data.data32[0] == _NET_WM_STATE_ADD ||
667               event->data.data32[0] == _NET_WM_STATE_TOGGLE))) {
668             DLOG("toggling fullscreen\n");
669             con_toggle_fullscreen(con, CF_OUTPUT);
670         }
671
672         tree_render();
673         x_push_changes(croot);
674     } else if (event->type == A_I3_SYNC) {
675         DLOG("i3 sync, yay\n");
676         xcb_window_t window = event->data.data32[0];
677         uint32_t rnd = event->data.data32[1];
678         DLOG("Sending random value %d back to X11 window 0x%08x\n", rnd, window);
679
680         void *reply = scalloc(32);
681         xcb_client_message_event_t *ev = reply;
682
683         ev->response_type = XCB_CLIENT_MESSAGE;
684         ev->window = window;
685         ev->type = A_I3_SYNC;
686         ev->format = 32;
687         ev->data.data32[0] = window;
688         ev->data.data32[1] = rnd;
689
690         xcb_send_event(conn, false, window, XCB_EVENT_MASK_NO_EVENT, (char*)ev);
691         xcb_flush(conn);
692         free(reply);
693     } else {
694         DLOG("unhandled clientmessage\n");
695         return;
696     }
697 }
698
699 #if 0
700 int handle_window_type(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
701                         xcb_atom_t atom, xcb_get_property_reply_t *property) {
702         /* TODO: Implement this one. To do this, implement a little test program which sleep(1)s
703          before changing this property. */
704         ELOG("_NET_WM_WINDOW_TYPE changed, this is not yet implemented.\n");
705         return 0;
706 }
707 #endif
708
709 /*
710  * Handles the size hints set by a window, but currently only the part necessary for displaying
711  * clients proportionally inside their frames (mplayer for example)
712  *
713  * See ICCCM 4.1.2.3 for more details
714  *
715  */
716 static bool handle_normal_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
717                         xcb_atom_t name, xcb_get_property_reply_t *reply) {
718     Con *con = con_by_window_id(window);
719     if (con == NULL) {
720         DLOG("Received WM_NORMAL_HINTS for unknown client\n");
721         return false;
722     }
723
724     xcb_size_hints_t size_hints;
725
726         //CLIENT_LOG(client);
727
728     /* If the hints were already in this event, use them, if not, request them */
729     if (reply != NULL)
730         xcb_icccm_get_wm_size_hints_from_reply(&size_hints, reply);
731     else
732         xcb_icccm_get_wm_normal_hints_reply(conn, xcb_icccm_get_wm_normal_hints_unchecked(conn, con->window->id), &size_hints, NULL);
733
734     if ((size_hints.flags & XCB_ICCCM_SIZE_HINT_P_MIN_SIZE)) {
735         // TODO: Minimum size is not yet implemented
736         DLOG("Minimum size: %d (width) x %d (height)\n", size_hints.min_width, size_hints.min_height);
737     }
738
739     bool changed = false;
740     if ((size_hints.flags & XCB_ICCCM_SIZE_HINT_P_RESIZE_INC)) {
741         if (size_hints.width_inc > 0 && size_hints.width_inc < 0xFFFF)
742             if (con->width_increment != size_hints.width_inc) {
743                 con->width_increment = size_hints.width_inc;
744                 changed = true;
745             }
746         if (size_hints.height_inc > 0 && size_hints.height_inc < 0xFFFF)
747             if (con->height_increment != size_hints.height_inc) {
748                 con->height_increment = size_hints.height_inc;
749                 changed = true;
750             }
751
752         if (changed)
753             DLOG("resize increments changed\n");
754     }
755
756     int base_width = 0, base_height = 0;
757
758     /* base_width/height are the desired size of the window.
759        We check if either the program-specified size or the program-specified
760        min-size is available */
761     if (size_hints.flags & XCB_ICCCM_SIZE_HINT_BASE_SIZE) {
762         base_width = size_hints.base_width;
763         base_height = size_hints.base_height;
764     } else if (size_hints.flags & XCB_ICCCM_SIZE_HINT_P_MIN_SIZE) {
765         /* TODO: is this right? icccm says not */
766         base_width = size_hints.min_width;
767         base_height = size_hints.min_height;
768     }
769
770     if (base_width != con->base_width ||
771         base_height != con->base_height) {
772         con->base_width = base_width;
773         con->base_height = base_height;
774         DLOG("client's base_height changed to %d\n", base_height);
775         DLOG("client's base_width changed to %d\n", base_width);
776         changed = true;
777     }
778
779     /* If no aspect ratio was set or if it was invalid, we ignore the hints */
780     if (!(size_hints.flags & XCB_ICCCM_SIZE_HINT_P_ASPECT) ||
781         (size_hints.min_aspect_num <= 0) ||
782         (size_hints.min_aspect_den <= 0)) {
783         goto render_and_return;
784     }
785
786     /* XXX: do we really use rect here, not window_rect? */
787     double width = con->rect.width - base_width;
788     double height = con->rect.height - base_height;
789     /* Convert numerator/denominator to a double */
790     double min_aspect = (double)size_hints.min_aspect_num / size_hints.min_aspect_den;
791     double max_aspect = (double)size_hints.max_aspect_num / size_hints.min_aspect_den;
792
793     DLOG("Aspect ratio set: minimum %f, maximum %f\n", min_aspect, max_aspect);
794     DLOG("width = %f, height = %f\n", width, height);
795
796     /* Sanity checks, this is user-input, in a way */
797     if (max_aspect <= 0 || min_aspect <= 0 || height == 0 || (width / height) <= 0)
798         goto render_and_return;
799
800     /* Check if we need to set proportional_* variables using the correct ratio */
801     if ((width / height) < min_aspect) {
802         if (con->proportional_width != width ||
803             con->proportional_height != (width / min_aspect)) {
804             con->proportional_width = width;
805             con->proportional_height = width / min_aspect;
806             changed = true;
807         }
808     } else if ((width / height) > max_aspect) {
809         if (con->proportional_width != width ||
810             con->proportional_height != (width / max_aspect)) {
811             con->proportional_width = width;
812             con->proportional_height = width / max_aspect;
813             changed = true;
814         }
815     } else goto render_and_return;
816
817 render_and_return:
818     if (changed)
819         tree_render();
820     FREE(reply);
821     return true;
822 }
823
824 /*
825  * Handles the WM_HINTS property for extracting the urgency state of the window.
826  *
827  */
828 static bool handle_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
829                   xcb_atom_t name, xcb_get_property_reply_t *reply) {
830     Con *con = con_by_window_id(window);
831     if (con == NULL) {
832         DLOG("Received WM_HINTS for unknown client\n");
833         return false;
834     }
835
836     xcb_icccm_wm_hints_t hints;
837
838     if (reply == NULL)
839         if (!(reply = xcb_get_property_reply(conn, xcb_icccm_get_wm_hints(conn, window), NULL)))
840             return false;
841
842     if (!xcb_icccm_get_wm_hints_from_reply(&hints, reply))
843         return false;
844
845     if (!con->urgent && focused == con) {
846         DLOG("Ignoring urgency flag for current client\n");
847         con->window->urgent = 0;
848         goto end;
849     }
850
851     /* Update the flag on the client directly */
852     con->urgent = (xcb_icccm_wm_hints_get_urgency(&hints) != 0);
853     //CLIENT_LOG(con);
854     if (con->window) {
855         if (con->urgent) {
856             con->window->urgent = time(NULL);
857         } else {
858             con->window->urgent = 0;
859         }
860     }
861     LOG("Urgency flag changed to %d\n", con->urgent);
862
863     Con *ws;
864     /* Set the urgency flag on the workspace, if a workspace could be found
865      * (for dock clients, that is not the case). */
866     if ((ws = con_get_workspace(con)) != NULL)
867         workspace_update_urgent_flag(ws);
868
869     tree_render();
870
871 end:
872     if (con->window)
873         window_update_hints(con->window, reply);
874     else free(reply);
875     return true;
876 }
877
878 /*
879  * Handles the transient for hints set by a window, signalizing that this window is a popup window
880  * for some other window.
881  *
882  * See ICCCM 4.1.2.6 for more details
883  *
884  */
885 static bool handle_transient_for(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
886                          xcb_atom_t name, xcb_get_property_reply_t *prop) {
887     Con *con;
888
889     if ((con = con_by_window_id(window)) == NULL || con->window == NULL) {
890         DLOG("No such window\n");
891         return false;
892     }
893
894     if (prop == NULL) {
895         prop = xcb_get_property_reply(conn, xcb_get_property_unchecked(conn,
896                                 false, window, XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 0, 32), NULL);
897         if (prop == NULL)
898             return false;
899     }
900
901     window_update_transient_for(con->window, prop);
902
903     return true;
904 }
905
906 /*
907  * Handles changes of the WM_CLIENT_LEADER atom which specifies if this is a
908  * toolwindow (or similar) and to which window it belongs (logical parent).
909  *
910  */
911 static bool handle_clientleader_change(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
912                         xcb_atom_t name, xcb_get_property_reply_t *prop) {
913     Con *con;
914     if ((con = con_by_window_id(window)) == NULL || con->window == NULL)
915         return false;
916
917     if (prop == NULL) {
918         prop = xcb_get_property_reply(conn, xcb_get_property_unchecked(conn,
919                                 false, window, A_WM_CLIENT_LEADER, XCB_ATOM_WINDOW, 0, 32), NULL);
920         if (prop == NULL)
921             return false;
922     }
923
924     window_update_leader(con->window, prop);
925
926     return true;
927 }
928
929 /*
930  * Handles FocusIn events which are generated by clients (i3’s focus changes
931  * don’t generate FocusIn events due to a different EventMask) and updates the
932  * decorations accordingly.
933  *
934  */
935 static void handle_focus_in(xcb_focus_in_event_t *event) {
936     DLOG("focus change in, for window 0x%08x\n", event->event);
937     Con *con;
938     if ((con = con_by_window_id(event->event)) == NULL || con->window == NULL)
939         return;
940     DLOG("That is con %p / %s\n", con, con->name);
941
942     if (event->mode == XCB_NOTIFY_MODE_GRAB ||
943         event->mode == XCB_NOTIFY_MODE_UNGRAB) {
944         DLOG("FocusIn event for grab/ungrab, ignoring\n");
945         return;
946     }
947
948     if (event->detail == XCB_NOTIFY_DETAIL_POINTER) {
949         DLOG("notify detail is pointer, ignoring this event\n");
950         return;
951     }
952
953     if (focused_id == event->event) {
954         DLOG("focus matches the currently focused window, not doing anything\n");
955         return;
956     }
957
958     /* Skip dock clients, they cannot get the i3 focus. */
959     if (con->parent->type == CT_DOCKAREA) {
960         DLOG("This is a dock client, not focusing.\n");
961         return;
962     }
963
964     DLOG("focus is different, updating decorations\n");
965
966     /* Get the currently focused workspace to check if the focus change also
967      * involves changing workspaces. If so, we need to call workspace_show() to
968      * correctly update state and send the IPC event. */
969     Con *ws = con_get_workspace(con);
970     if (ws != con_get_workspace(focused))
971         workspace_show(ws);
972
973     con_focus(con);
974     /* We update focused_id because we don’t need to set focus again */
975     focused_id = event->event;
976     x_push_changes(croot);
977     return;
978 }
979
980 /* Returns false if the event could not be processed (e.g. the window could not
981  * be found), true otherwise */
982 typedef bool (*cb_property_handler_t)(void *data, xcb_connection_t *c, uint8_t state, xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *property);
983
984 struct property_handler_t {
985     xcb_atom_t atom;
986     uint32_t long_len;
987     cb_property_handler_t cb;
988 };
989
990 static struct property_handler_t property_handlers[] = {
991     { 0, 128, handle_windowname_change },
992     { 0, UINT_MAX, handle_hints },
993     { 0, 128, handle_windowname_change_legacy },
994     { 0, UINT_MAX, handle_normal_hints },
995     { 0, UINT_MAX, handle_clientleader_change },
996     { 0, UINT_MAX, handle_transient_for },
997     { 0, 128, handle_windowrole_change }
998 };
999 #define NUM_HANDLERS (sizeof(property_handlers) / sizeof(struct property_handler_t))
1000
1001 /*
1002  * Sets the appropriate atoms for the property handlers after the atoms were
1003  * received from X11
1004  *
1005  */
1006 void property_handlers_init() {
1007
1008     sn_monitor_context_new(sndisplay, conn_screen, startup_monitor_event, NULL, NULL);
1009
1010     property_handlers[0].atom = A__NET_WM_NAME;
1011     property_handlers[1].atom = XCB_ATOM_WM_HINTS;
1012     property_handlers[2].atom = XCB_ATOM_WM_NAME;
1013     property_handlers[3].atom = XCB_ATOM_WM_NORMAL_HINTS;
1014     property_handlers[4].atom = A_WM_CLIENT_LEADER;
1015     property_handlers[5].atom = XCB_ATOM_WM_TRANSIENT_FOR;
1016     property_handlers[6].atom = A_WM_WINDOW_ROLE;
1017 }
1018
1019 static void property_notify(uint8_t state, xcb_window_t window, xcb_atom_t atom) {
1020     struct property_handler_t *handler = NULL;
1021     xcb_get_property_reply_t *propr = NULL;
1022
1023     for (int c = 0; c < sizeof(property_handlers) / sizeof(struct property_handler_t); c++) {
1024         if (property_handlers[c].atom != atom)
1025             continue;
1026
1027         handler = &property_handlers[c];
1028         break;
1029     }
1030
1031     if (handler == NULL) {
1032         //DLOG("Unhandled property notify for atom %d (0x%08x)\n", atom, atom);
1033         return;
1034     }
1035
1036     if (state != XCB_PROPERTY_DELETE) {
1037         xcb_get_property_cookie_t cookie = xcb_get_property(conn, 0, window, atom, XCB_GET_PROPERTY_TYPE_ANY, 0, handler->long_len);
1038         propr = xcb_get_property_reply(conn, cookie, 0);
1039     }
1040
1041     /* the handler will free() the reply unless it returns false */
1042     if (!handler->cb(NULL, conn, state, window, atom, propr))
1043         FREE(propr);
1044 }
1045
1046 /*
1047  * Takes an xcb_generic_event_t and calls the appropriate handler, based on the
1048  * event type.
1049  *
1050  */
1051 void handle_event(int type, xcb_generic_event_t *event) {
1052     if (randr_base > -1 &&
1053         type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
1054         handle_screen_change(event);
1055         return;
1056     }
1057
1058     switch (type) {
1059         case XCB_KEY_PRESS:
1060             handle_key_press((xcb_key_press_event_t*)event);
1061             break;
1062
1063         case XCB_BUTTON_PRESS:
1064             handle_button_press((xcb_button_press_event_t*)event);
1065             break;
1066
1067         case XCB_MAP_REQUEST:
1068             handle_map_request((xcb_map_request_event_t*)event);
1069             break;
1070
1071         case XCB_UNMAP_NOTIFY:
1072             handle_unmap_notify_event((xcb_unmap_notify_event_t*)event);
1073             break;
1074
1075         case XCB_DESTROY_NOTIFY:
1076             handle_destroy_notify_event((xcb_destroy_notify_event_t*)event);
1077             break;
1078
1079         case XCB_EXPOSE:
1080             handle_expose_event((xcb_expose_event_t*)event);
1081             break;
1082
1083         case XCB_MOTION_NOTIFY:
1084             handle_motion_notify((xcb_motion_notify_event_t*)event);
1085             break;
1086
1087         /* Enter window = user moved his mouse over the window */
1088         case XCB_ENTER_NOTIFY:
1089             handle_enter_notify((xcb_enter_notify_event_t*)event);
1090             break;
1091
1092         /* Client message are sent to the root window. The only interesting
1093          * client message for us is _NET_WM_STATE, we honour
1094          * _NET_WM_STATE_FULLSCREEN */
1095         case XCB_CLIENT_MESSAGE:
1096             handle_client_message((xcb_client_message_event_t*)event);
1097             break;
1098
1099         /* Configure request = window tried to change size on its own */
1100         case XCB_CONFIGURE_REQUEST:
1101             handle_configure_request((xcb_configure_request_event_t*)event);
1102             break;
1103
1104         /* Mapping notify = keyboard mapping changed (Xmodmap), re-grab bindings */
1105         case XCB_MAPPING_NOTIFY:
1106             handle_mapping_notify((xcb_mapping_notify_event_t*)event);
1107             break;
1108
1109         case XCB_FOCUS_IN:
1110             handle_focus_in((xcb_focus_in_event_t*)event);
1111             break;
1112
1113         case XCB_PROPERTY_NOTIFY: {
1114             xcb_property_notify_event_t *e = (xcb_property_notify_event_t*)event;
1115             last_timestamp = e->time;
1116             property_notify(e->state, e->window, e->atom);
1117             break;
1118         }
1119
1120         default:
1121             //DLOG("Unhandled event of type %d\n", type);
1122             break;
1123     }
1124 }