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