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