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