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