]> git.sur5r.net Git - i3/i3/blob - src/handlers.c
8278a89a872bf81ae09ddaceec74df100192b683
[i3/i3] / src / handlers.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009 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_wm.h>
19 #include <xcb/xcb_icccm.h>
20
21 #include <X11/XKBlib.h>
22
23 #include "i3.h"
24 #include "debug.h"
25 #include "table.h"
26 #include "layout.h"
27 #include "commands.h"
28 #include "data.h"
29 #include "xcb.h"
30 #include "util.h"
31 #include "xinerama.h"
32 #include "config.h"
33 #include "queue.h"
34
35 /* After mapping/unmapping windows, a notify event is generated. However, we don’t want it,
36    since it’d trigger an infinite loop of switching between the different windows when
37    changing workspaces */
38 static SLIST_HEAD(ignore_head, Ignore_Event) ignore_events;
39
40 static void add_ignore_event(const int sequence) {
41         struct Ignore_Event *event = smalloc(sizeof(struct Ignore_Event));
42
43         event->sequence = sequence;
44         event->added = time(NULL);
45
46         LOG("Adding sequence %d to ignorelist\n", sequence);
47
48         SLIST_INSERT_HEAD(&ignore_events, event, ignore_events);
49 }
50
51 /*
52  * Checks if the given sequence is ignored and returns true if so.
53  *
54  */
55 static bool event_is_ignored(const int sequence) {
56         struct Ignore_Event *event;
57         time_t now = time(NULL);
58         for (event = SLIST_FIRST(&ignore_events); event != SLIST_END(&ignore_events);) {
59                 if ((now - event->added) > 5) {
60                         LOG("Entry is older than five seconds, cleaning up\n");
61                         struct Ignore_Event *save = event;
62                         event = SLIST_NEXT(event, ignore_events);
63                         SLIST_REMOVE(&ignore_events, save, Ignore_Event, ignore_events);
64                         free(save);
65                 } else event = SLIST_NEXT(event, ignore_events);
66         }
67
68         SLIST_FOREACH(event, &ignore_events, ignore_events) {
69                 if (event->sequence == sequence) {
70                         LOG("Ignoring event (sequence %d)\n", sequence);
71                         SLIST_REMOVE(&ignore_events, event, Ignore_Event, ignore_events);
72                         return true;
73                 }
74         }
75
76         return false;
77 }
78
79 /*
80  * Due to bindings like Mode_switch + <a>, we need to bind some keys in XCB_GRAB_MODE_SYNC.
81  * Therefore, we just replay all key presses.
82  *
83  */
84 int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
85         LOG("got key release, just passing\n");
86         xcb_allow_events(conn, XCB_ALLOW_REPLAY_KEYBOARD, event->time);
87         xcb_flush(conn);
88         return 1;
89 }
90
91 /*
92  * There was a key press. We compare this key code with our bindings table and pass
93  * the bound action to parse_command().
94  *
95  */
96 int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
97         LOG("Keypress %d\n", event->detail);
98
99         /* We need to get the keysym group (There are group 1 to group 4, each holding
100            two keysyms (without shift and with shift) using Xkb because X fails to
101            provide them reliably (it works in Xephyr, it does not in real X) */
102         XkbStateRec state;
103         if (XkbGetState(xkbdpy, XkbUseCoreKbd, &state) == Success && (state.group+1) == 2)
104                 event->state |= 0x2;
105
106         LOG("state %d\n", event->state);
107
108         /* Remove the numlock bit, all other bits are modifiers we can bind to */
109         uint16_t state_filtered = event->state & ~XCB_MOD_MASK_LOCK;
110
111         /* Find the binding */
112         Binding *bind;
113         TAILQ_FOREACH(bind, &bindings, bindings)
114                 if (bind->keycode == event->detail && bind->mods == state_filtered)
115                         break;
116
117         /* No match? Then it was an actively grabbed key, that is with Mode_switch, and
118            the user did not press Mode_switch, so just pass it… */
119         if (bind == TAILQ_END(&bindings)) {
120                 xcb_allow_events(conn, ReplayKeyboard, event->time);
121                 xcb_flush(conn);
122                 return 1;
123         }
124
125         parse_command(conn, bind->command);
126         if (event->state & 0x2) {
127                 LOG("Mode_switch -> allow_events(SyncKeyboard)\n");
128                 xcb_allow_events(conn, SyncKeyboard, event->time);
129                 xcb_flush(conn);
130         }
131         return 1;
132 }
133
134
135 /*
136  * When the user moves the mouse pointer onto a window, this callback gets called.
137  *
138  */
139 int handle_enter_notify(void *ignored, xcb_connection_t *conn, xcb_enter_notify_event_t *event) {
140         LOG("enter_notify for %08x, mode = %d, detail %d, serial %d\n", event->event, event->mode, event->detail, event->sequence);
141         if (event->mode != XCB_NOTIFY_MODE_NORMAL) {
142                 LOG("This was not a normal notify, ignoring\n");
143                 return 1;
144         }
145         /* Some events are not interesting, because they were not generated actively by the
146            user, but be reconfiguration of windows */
147         if (event_is_ignored(event->sequence))
148                 return 1;
149
150         /* This was either a focus for a client’s parent (= titlebar)… */
151         Client *client = table_get(byParent, event->event);
152         /* …or the client itself */
153         if (client == NULL)
154                 client = table_get(byChild, event->event);
155
156         /* If not, then the user moved his cursor to the root window. In that case, we adjust c_ws */
157         if (client == NULL) {
158                 LOG("Getting screen at %d x %d\n", event->root_x, event->root_y);
159                 i3Screen *screen = get_screen_containing(event->root_x, event->root_y);
160                 if (screen == NULL) {
161                         LOG("ERROR: No such screen\n");
162                         return 0;
163                 }
164                 c_ws = &workspaces[screen->current_workspace];
165                 LOG("We're now on virtual screen number %d\n", screen->num);
166                 return 1;
167         }
168
169         /* Do plausibility checks: This event may be useless for us if it occurs on a window
170            which is in a stacked container but not the focused one */
171         if (client->container != NULL &&
172             client->container->mode == MODE_STACK &&
173             client->container->currently_focused != client) {
174                 LOG("Plausibility check says: no\n");
175                 return 1;
176         }
177
178         set_focus(conn, client);
179
180         return 1;
181 }
182
183 int handle_button_press(void *ignored, xcb_connection_t *conn, xcb_button_press_event_t *event) {
184         LOG("button press!\n");
185         /* This was either a focus for a client’s parent (= titlebar)… */
186         Client *client = table_get(byChild, event->event);
187         bool border_click = false;
188         if (client == NULL) {
189                 client = table_get(byParent, event->event);
190                 border_click = true;
191         }
192         if (client == NULL) {
193                 /* The client was neither on a client’s titlebar nor on a client itself, maybe on a stack_window? */
194                 struct Stack_Window *stack_win;
195                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
196                         if (stack_win->window == event->event) {
197                                 /* A stack window was clicked. We calculate the destination client by
198                                    dividing the Y position of the event through the height of a window
199                                    decoration and then set the focus to this client. */
200                                 i3Font *font = load_font(conn, config.font);
201                                 int decoration_height = (font->height + 2 + 2);
202                                 int destination = (event->event_y / decoration_height),
203                                     c = 0;
204                                 Client *client;
205
206                                 LOG("Click on stack_win for client %d\n", destination);
207                                 CIRCLEQ_FOREACH(client, &(stack_win->container->clients), clients)
208                                         if (c++ == destination) {
209                                                 set_focus(conn, client);
210                                                 return 1;
211                                         }
212
213                                 return 1;
214                         }
215
216                 return 1;
217         }
218
219         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
220         xcb_screen_t *root_screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
221
222         /* Set focus in any case */
223         set_focus(conn, client);
224
225         /* Let’s see if this was on the borders (= resize). If not, we’re done */
226         LOG("press button on x=%d, y=%d\n", event->event_x, event->event_y);
227
228         Container *con = client->container,
229                   *first = NULL,
230                   *second = NULL;
231         enum { O_HORIZONTAL, O_VERTICAL } orientation = O_VERTICAL;
232         int new_position;
233
234         if (con == NULL) {
235                 LOG("dock. done.\n");
236                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
237                 xcb_flush(conn);
238                 return 1;
239         }
240
241         LOG("event->event_x = %d, client->rect.width = %d\n", event->event_x, client->rect.width);
242
243         if (!border_click) {
244                 LOG("client. done.\n");
245                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
246                 xcb_flush(conn);
247                 return 1;
248         }
249
250         /* Don’t handle events inside the titlebar, only borders are interesting */
251         i3Font *font = load_font(conn, config.font);
252         if (event->event_y >= 2 && event->event_y <= (font->height + 2 + 2)) {
253                 LOG("click on titlebar\n");
254                 return 1;
255         }
256
257         if (event->event_y < 2) {
258                 /* This was a press on the top border */
259                 if (con->row == 0)
260                         return 1;
261                 first = con->workspace->table[con->col][con->row-1];
262                 second = con;
263                 orientation = O_HORIZONTAL;
264         } else if (event->event_y >= (client->rect.height - 2)) {
265                 /* …bottom border */
266                 if (con->row == (con->workspace->rows-1))
267                         return 1;
268                 first = con;
269                 second = con->workspace->table[con->col][con->row+1];
270                 orientation = O_HORIZONTAL;
271         } else if (event->event_x <= 2) {
272                 /* …left border */
273                 if (con->col == 0)
274                         return 1;
275                 first = con->workspace->table[con->col-1][con->row];
276                 second = con;
277         } else if (event->event_x > 2) {
278                 /* …right border */
279                 if (con->col == (con->workspace->cols-1))
280                         return 1;
281                 first = con;
282                 second = con->workspace->table[con->col+1][con->row];
283         }
284
285         uint32_t mask = 0;
286         uint32_t values[2];
287
288         mask = XCB_CW_OVERRIDE_REDIRECT;
289         values[0] = 1;
290
291         /* Open a new window, the resizebar. Grab the pointer and move the window around
292            as the user moves the pointer. */
293         Rect grabrect = {0, 0, root_screen->width_in_pixels, root_screen->height_in_pixels};
294         xcb_window_t grabwin = create_window(conn, grabrect, XCB_WINDOW_CLASS_INPUT_ONLY, -1, mask, values);
295
296         Rect helprect;
297         if (orientation == O_VERTICAL) {
298                 helprect.x = event->root_x;
299                 helprect.y = 0;
300                 helprect.width = 2;
301                 helprect.height = root_screen->height_in_pixels; /* this has to be the cell’s height */
302                 new_position = event->root_x;
303         } else {
304                 helprect.x = 0;
305                 helprect.y = event->root_y;
306                 helprect.width = root_screen->width_in_pixels; /* this has to be the cell’s width */
307                 helprect.height = 2;
308                 new_position = event->root_y;
309         }
310
311         mask = XCB_CW_BACK_PIXEL;
312         values[0] = get_colorpixel(conn, "#4c7899");
313
314         mask |= XCB_CW_OVERRIDE_REDIRECT;
315         values[1] = 1;
316
317         xcb_window_t helpwin = create_window(conn, helprect, XCB_WINDOW_CLASS_INPUT_OUTPUT,
318                                              (orientation == O_VERTICAL ?
319                                               XCB_CURSOR_SB_V_DOUBLE_ARROW :
320                                               XCB_CURSOR_SB_H_DOUBLE_ARROW), mask, values);
321
322         xcb_circulate_window(conn, XCB_CIRCULATE_RAISE_LOWEST, helpwin);
323
324         xcb_grab_pointer(conn, false, root, XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION,
325                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, grabwin, XCB_NONE, XCB_CURRENT_TIME);
326
327         xcb_flush(conn);
328
329         xcb_generic_event_t *inside_event;
330         /* I’ve always wanted to have my own eventhandler… */
331         while ((inside_event = xcb_wait_for_event(conn))) {
332                 /* Same as get_event_handler in xcb */
333                 int nr = inside_event->response_type;
334                 if (nr == 0) {
335                         /* An error occured */
336                         handle_event(NULL, conn, inside_event);
337                         free(inside_event);
338                         continue;
339                 }
340                 assert(nr < 256);
341                 nr &= XCB_EVENT_RESPONSE_TYPE_MASK;
342                 assert(nr >= 2);
343
344                 /* Check if we need to escape this loop */
345                 if (nr == XCB_BUTTON_RELEASE)
346                         break;
347
348                 switch (nr) {
349                         case XCB_MOTION_NOTIFY:
350                                 if (orientation == O_VERTICAL) {
351                                         values[0] = new_position = ((xcb_motion_notify_event_t*)inside_event)->root_x;
352                                         xcb_configure_window(conn, helpwin, XCB_CONFIG_WINDOW_X, values);
353                                 } else {
354                                         values[0] = new_position = ((xcb_motion_notify_event_t*)inside_event)->root_y;
355                                         xcb_configure_window(conn, helpwin, XCB_CONFIG_WINDOW_Y, values);
356                                 }
357
358                                 xcb_flush(conn);
359                                 break;
360                         default:
361                                 LOG("Passing to original handler\n");
362                                 /* Use original handler */
363                                 xcb_event_handle(&evenths, inside_event);
364                                 break;
365                 }
366                 free(inside_event);
367         }
368
369         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
370         xcb_destroy_window(conn, helpwin);
371         xcb_destroy_window(conn, grabwin);
372         xcb_flush(conn);
373
374         Workspace *ws = con->workspace;
375         if (orientation == O_VERTICAL) {
376                 LOG("Resize was from X = %d to X = %d\n", event->root_x, new_position);
377                 if (event->root_x == new_position) {
378                         LOG("Nothing changed, not updating anything\n");
379                         return 1;
380                 }
381
382                 /* Convert 0 (for default width_factor) to actual numbers */
383                 if (first->width_factor == 0)
384                         first->width_factor = ((float)ws->rect.width / ws->cols) / ws->rect.width;
385                 if (second->width_factor == 0)
386                         second->width_factor = ((float)ws->rect.width / ws->cols) / ws->rect.width;
387
388                 first->width_factor *= (float)(first->width + (new_position - event->root_x)) / first->width;
389                 second->width_factor *= (float)(second->width - (new_position - event->root_x)) / second->width;
390         } else {
391                 LOG("Resize was from Y = %d to Y = %d\n", event->root_y, new_position);
392                 if (event->root_y == new_position) {
393                         LOG("Nothing changed, not updating anything\n");
394                         return 1;
395                 }
396
397                 /* Convert 0 (for default height_factor) to actual numbers */
398                 if (first->height_factor == 0)
399                         first->height_factor = ((float)ws->rect.height / ws->rows) / ws->rect.height;
400                 if (second->height_factor == 0)
401                         second->height_factor = ((float)ws->rect.height / ws->rows) / ws->rect.height;
402
403                 first->height_factor *= (float)(first->height + (new_position - event->root_y)) / first->height;
404                 second->height_factor *= (float)(second->height - (new_position - event->root_y)) / second->height;
405         }
406
407         render_layout(conn);
408
409         return 1;
410 }
411
412 /*
413  * A new window appeared on the screen (=was mapped), so let’s manage it.
414  *
415  */
416 int handle_map_request(void *prophs, xcb_connection_t *conn, xcb_map_request_event_t *event) {
417         xcb_get_window_attributes_cookie_t cookie;
418         xcb_get_window_attributes_reply_t *reply;
419
420         cookie = xcb_get_window_attributes_unchecked(conn, event->window);
421
422         if ((reply = xcb_get_window_attributes_reply(conn, cookie, NULL)) == NULL) {
423                 LOG("Could not get window attributes\n");
424                 return -1;
425         }
426
427         window_attributes_t wa = { TAG_VALUE };
428         LOG("override_redirect = %d\n", reply->override_redirect);
429         wa.u.override_redirect = reply->override_redirect;
430         LOG("window = 0x%08x, serial is %d.\n", event->window, event->sequence);
431         add_ignore_event(event->sequence);
432
433         manage_window(prophs, conn, event->window, wa);
434         return 1;
435 }
436
437 /*
438  * Configure requests are received when the application wants to resize windows on their own.
439  *
440  * We generate a synthethic configure notify event to signalize the client its "new" position.
441  *
442  */
443 int handle_configure_request(void *prophs, xcb_connection_t *conn, xcb_configure_request_event_t *event) {
444         LOG("configure-request, serial %d\n", event->sequence);
445         LOG("event->window = %08x\n", event->window);
446         LOG("application wants to be at %dx%d with %dx%d\n", event->x, event->y, event->width, event->height);
447
448         Client *client = table_get(byChild, event->window);
449         if (client == NULL) {
450                 LOG("No such client\n");
451                 return 1;
452         }
453
454         xcb_configure_notify_event_t generated_event;
455
456         generated_event.event = client->child;
457         generated_event.window = client->child;
458         generated_event.response_type = XCB_CONFIGURE_NOTIFY;
459
460         generated_event.x = client->child_rect.x;
461         generated_event.y = client->child_rect.y;
462         generated_event.width = client->child_rect.width;
463         generated_event.height = client->child_rect.height;
464
465         generated_event.border_width = 0;
466         generated_event.above_sibling = XCB_NONE;
467         generated_event.override_redirect = false;
468
469         xcb_send_event(conn, false, client->child, XCB_EVENT_MASK_STRUCTURE_NOTIFY, (char*)&generated_event);
470         xcb_flush(conn);
471
472         LOG("Told the client to stay at %dx%d with size %dx%d\n",
473             client->child_rect.x, client->child_rect.y, client->child_rect.width, client->child_rect.height);
474
475         return 1;
476 }
477
478 /*
479  * Configuration notifies are only handled because we need to set up ignore for the following
480  * enter notify events
481  *
482  */
483 int handle_configure_event(void *prophs, xcb_connection_t *conn, xcb_configure_notify_event_t *event) {
484         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
485
486         LOG("handle_configure_event for window %08x\n", event->window);
487         LOG("event->type = %d, \n", event->response_type);
488         LOG("event->x = %d, ->y = %d, ->width = %d, ->height = %d\n", event->x, event->y, event->width, event->height);
489         add_ignore_event(event->sequence);
490
491         if (event->event == root) {
492                 LOG("reconfigure of the root window, need to xinerama\n");
493                 /* FIXME: Somehow, this is occuring too often. Therefore, we check for 0/0,
494                    but is there a better way? */
495                 if (event->x == 0 && event->y == 0)
496                         xinerama_requery_screens(conn);
497                 return 1;
498         }
499
500         return 1;
501 }
502
503 /*
504  * Our window decorations were unmapped. That means, the window will be killed now,
505  * so we better clean up before.
506  *
507  */
508 int handle_unmap_notify_event(void *data, xcb_connection_t *conn, xcb_unmap_notify_event_t *event) {
509         xcb_window_t root = xcb_setup_roots_iterator(xcb_get_setup(conn)).data->root;
510
511         add_ignore_event(event->sequence);
512
513         Client *client = table_get(byChild, event->window);
514         /* First, we need to check if the client is awaiting an unmap-request which
515            was generated by us reparenting the window. In that case, we just ignore it. */
516         if (client != NULL && client->awaiting_useless_unmap) {
517                 LOG("Dropping this unmap request, it was generated by reparenting\n");
518                 client->awaiting_useless_unmap = false;
519                 return 1;
520         }
521
522         LOG("event->window = %08x, event->event = %08x\n", event->window, event->event);
523         LOG("UnmapNotify for 0x%08x (received from 0x%08x)\n", event->window, event->event);
524         if (client == NULL) {
525                 LOG("not a managed window. Ignoring.\n");
526                 return 0;
527         }
528
529         client = table_remove(byChild, event->window);
530
531         if (client->name != NULL)
532                 free(client->name);
533
534         if (client->container != NULL) {
535                 Container *con = client->container;
536
537                 /* If this was the fullscreen client, we need to unset it */
538                 if (client->fullscreen)
539                         con->workspace->fullscreen_client = NULL;
540
541                 /* Remove the client from the list of clients */
542                 remove_client_from_container(conn, client, con);
543
544                 /* Remove from the focus stack */
545                 LOG("Removing from focus stack\n");
546                 SLIST_REMOVE(&(con->workspace->focus_stack), client, Client, focus_clients);
547
548                 /* Set focus to the last focused client in this container */
549                 con->currently_focused = NULL;
550                 Client *focus_client;
551                 SLIST_FOREACH(focus_client, &(con->workspace->focus_stack), focus_clients)
552                         if (focus_client->container == con) {
553                                 con->currently_focused = focus_client;
554                                 set_focus(conn, focus_client);
555                                 break;
556                         }
557         }
558
559         if (client->dock) {
560                 LOG("Removing from dock clients\n");
561                 SLIST_REMOVE(&(client->workspace->dock_clients), client, Client, dock_clients);
562         }
563
564         LOG("child of 0x%08x.\n", client->frame);
565         xcb_reparent_window(conn, client->child, root, 0, 0);
566         xcb_destroy_window(conn, client->frame);
567         xcb_flush(conn);
568         table_remove(byParent, client->frame);
569
570         if (client->container != NULL)
571                 cleanup_table(conn, client->container->workspace);
572
573         free(client);
574
575         render_layout(conn);
576
577         return 1;
578 }
579
580 /*
581  * Called when a window changes its title
582  *
583  */
584 int handle_windowname_change(void *data, xcb_connection_t *conn, uint8_t state,
585                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
586         LOG("window's name changed.\n");
587         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
588                 LOG("_NET_WM_NAME not specified, not changing\n");
589                 return 1;
590         }
591         Client *client = table_get(byChild, window);
592         if (client == NULL)
593                 return 1;
594
595         /* Save the old pointer to make the update atomic */
596         char *new_name;
597         int new_len;
598         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
599         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
600         char *ucs2_name = convert_utf8_to_ucs2(new_name, &new_len);
601         LOG("Name should change to \"%s\"\n", new_name);
602         free(new_name);
603
604         /* Check if they are the same and don’t update if so.
605            Note the use of new_len * 2 to check all bytes as each glyph takes 2 bytes.
606            Also note the use of memcmp() instead of strncmp() because the latter stops on nullbytes,
607            but UCS-2 uses nullbytes to fill up glyphs which only use one byte. */
608         if ((new_len == client->name_len) &&
609             (client->name != NULL) &&
610             (memcmp(client->name, ucs2_name, new_len * 2) == 0)) {
611                 LOG("Name did not change, not updating\n");
612                 free(ucs2_name);
613                 return 1;
614         }
615
616         char *old_name = client->name;
617         client->name = ucs2_name;
618         client->name_len = new_len;
619         client->uses_net_wm_name = true;
620
621         if (old_name != NULL)
622                 free(old_name);
623
624         /* If the client is a dock window, we don’t need to render anything */
625         if (client->dock)
626                 return 1;
627
628         if (client->container->mode == MODE_STACK)
629                 render_container(conn, client->container);
630         else decorate_window(conn, client, client->frame, client->titlegc, 0);
631         xcb_flush(conn);
632
633         return 1;
634 }
635
636 /*
637  * We handle legacy window names (titles) which are in COMPOUND_TEXT encoding. However, we
638  * just pass them along, so when containing non-ASCII characters, those will be rendering
639  * incorrectly. In order to correctly render unicode window titles in i3, an application
640  * has to set _NET_WM_NAME, which is in UTF-8 encoding.
641  *
642  * On every update, a message is put out to the user, so he may improve the situation and
643  * update applications which display filenames in their title to correctly use
644  * _NET_WM_NAME and therefore support unicode.
645  *
646  */
647 int handle_windowname_change_legacy(void *data, xcb_connection_t *conn, uint8_t state,
648                                 xcb_window_t window, xcb_atom_t atom, xcb_get_property_reply_t *prop) {
649         LOG("window's name changed (legacy).\n");
650         if (prop == NULL || xcb_get_property_value_length(prop) == 0) {
651                 LOG("prop == NULL\n");
652                 return 1;
653         }
654         Client *client = table_get(byChild, window);
655         if (client == NULL)
656                 return 1;
657
658         if (client->uses_net_wm_name) {
659                 LOG("This client is capable of _NET_WM_NAME, ignoring legacy name\n");
660                 return 1;
661         }
662
663         /* Save the old pointer to make the update atomic */
664         char *new_name;
665         int new_len;
666         asprintf(&new_name, "%.*s", xcb_get_property_value_length(prop), (char*)xcb_get_property_value(prop));
667         /* Convert it to UCS-2 here for not having to convert it later every time we want to pass it to X */
668         LOG("Name should change to \"%s\"\n", new_name);
669
670         /* Check if they are the same and don’t update if so. */
671         if (client->name != NULL &&
672             strlen(new_name) == strlen(client->name) &&
673             strcmp(client->name, new_name) == 0) {
674                 LOG("Name did not change, not updating\n");
675                 free(new_name);
676                 return 1;
677         }
678
679         LOG("Using legacy window title. Note that in order to get Unicode window titles in i3,"
680             "the application has to set _NET_WM_NAME which is in UTF-8 encoding.\n");
681
682         char *old_name = client->name;
683         client->name = new_name;
684         client->name_len = -1;
685
686         if (old_name != NULL)
687                 free(old_name);
688
689         /* If the client is a dock window, we don’t need to render anything */
690         if (client->dock)
691                 return 1;
692
693         if (client->container->mode == MODE_STACK)
694                 render_container(conn, client->container);
695         else decorate_window(conn, client, client->frame, client->titlegc, 0);
696         xcb_flush(conn);
697
698         return 1;
699 }
700
701 /*
702  * Expose event means we should redraw our windows (= title bar)
703  *
704  */
705 int handle_expose_event(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
706         /* event->count is the number of minimum remaining expose events for this window, so we
707            skip all events but the last one */
708         if (event->count != 0)
709                 return 1;
710         LOG("window = %08x\n", event->window);
711
712         Client *client = table_get(byParent, event->window);
713         if (client == NULL) {
714                 /* There was no client in the table, so this is probably an expose event for
715                    one of our stack_windows. */
716                 struct Stack_Window *stack_win;
717                 SLIST_FOREACH(stack_win, &stack_wins, stack_windows)
718                         if (stack_win->window == event->window) {
719                                 render_container(conn, stack_win->container);
720                                 return 1;
721                         }
722
723                 /* …or one of the bars? */
724                 i3Screen *screen;
725                 TAILQ_FOREACH(screen, virtual_screens, screens) {
726                         if (screen->bar == event->window) {
727                                 render_layout(conn);
728                         }
729                 }
730                 return 1;
731         }
732
733         LOG("got client %s\n", client->name);
734         if (client->dock) {
735                 LOG("this is a dock\n");
736                 return 1;
737         }
738
739         if (client->container->mode != MODE_STACK)
740                 decorate_window(conn, client, client->frame, client->titlegc, 0);
741         else {
742                 uint32_t background_color;
743                 /* Distinguish if the window is currently focused… */
744                 if (CUR_CELL->currently_focused == client)
745                         background_color = get_colorpixel(conn, "#285577");
746                 /* …or if it is the focused window in a not focused container */
747                 else background_color = get_colorpixel(conn, "#555555");
748
749                 /* Set foreground color to current focused color, line width to 2 */
750                 uint32_t values[] = {background_color, 2};
751                 xcb_change_gc(conn, client->titlegc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
752
753                 /* Draw the border, the ±1 is for line width = 2 */
754                 xcb_point_t points[] = {{1, 0},                                           /* left upper edge */
755                                         {1, client->rect.height-1},                       /* left bottom edge */
756                                         {client->rect.width-1, client->rect.height-1},    /* right bottom edge */
757                                         {client->rect.width-1, 0}};                       /* right upper edge */
758                 xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, client->frame, client->titlegc, 4, points);
759
760                 /* Draw a black background */
761                 xcb_change_gc_single(conn, client->titlegc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
762                 xcb_rectangle_t crect = {2, 0, client->rect.width - (2 + 2), client->rect.height - 2};
763                 xcb_poly_fill_rectangle(conn, client->frame, client->titlegc, 1, &crect);
764         }
765         xcb_flush(conn);
766         return 1;
767 }
768
769 /*
770  * Handle client messages (EWMH)
771  *
772  */
773 int handle_client_message(void *data, xcb_connection_t *conn, xcb_client_message_event_t *event) {
774         LOG("client_message\n");
775
776         if (event->type == atoms[_NET_WM_STATE]) {
777                 if (event->format != 32 || event->data.data32[1] != atoms[_NET_WM_STATE_FULLSCREEN])
778                         return 0;
779
780                 LOG("fullscreen\n");
781
782                 Client *client = table_get(byChild, event->window);
783                 if (client == NULL)
784                         return 0;
785
786                 /* Check if the fullscreen state should be toggled */
787                 if ((client->fullscreen &&
788                      (event->data.data32[0] == _NET_WM_STATE_REMOVE ||
789                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)) ||
790                     (!client->fullscreen &&
791                      (event->data.data32[0] == _NET_WM_STATE_ADD ||
792                       event->data.data32[0] == _NET_WM_STATE_TOGGLE)))
793                         toggle_fullscreen(conn, client);
794         } else {
795                 LOG("unhandled clientmessage\n");
796                 return 0;
797         }
798
799         return 1;
800 }
801
802 int handle_window_type(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
803                         xcb_atom_t atom, xcb_get_property_reply_t *property) {
804         /* TODO: Implement this one. To do this, implement a little test program which sleep(1)s
805          before changing this property. */
806         LOG("_NET_WM_WINDOW_TYPE changed, this is not yet implemented.\n");
807         return 0;
808 }
809
810 /*
811  * Handles the size hints set by a window, but currently only the part necessary for displaying
812  * clients proportionally inside their frames (mplayer for example)
813  *
814  * See ICCCM 4.1.2.3 for more details
815  *
816  */
817 int handle_normal_hints(void *data, xcb_connection_t *conn, uint8_t state, xcb_window_t window,
818                         xcb_atom_t name, xcb_get_property_reply_t *reply) {
819         LOG("handle_normal_hints\n");
820         Client *client = table_get(byChild, window);
821         if (client == NULL) {
822                 LOG("No such client\n");
823                 return 1;
824         }
825         xcb_size_hints_t size_hints;
826
827         /* If the hints were already in this event, use them, if not, request them */
828         if (reply != NULL)
829                 xcb_get_wm_size_hints_from_reply(&size_hints, reply);
830         else
831                 xcb_get_wm_normal_hints_reply(conn, xcb_get_wm_normal_hints_unchecked(conn, client->child), &size_hints, NULL);
832
833         /* If no aspect ratio was set or if it was invalid, we ignore the hints */
834         if (!(size_hints.flags & XCB_SIZE_HINT_P_ASPECT) ||
835             (size_hints.min_aspect_num <= 0) ||
836             (size_hints.min_aspect_den <= 0)) {
837                 LOG("No aspect ratio set, ignoring\n");
838                 return 1;
839         }
840
841         LOG("window is %08x / %s\n", client->child, client->name);
842
843         int base_width = 0, base_height = 0,
844             min_width = 0, min_height = 0;
845
846         /* base_width/height are the desired size of the window.
847            We check if either the program-specified size or the program-specified
848            min-size is available */
849         if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
850                 base_width = size_hints.base_width;
851                 base_height = size_hints.base_height;
852         } else if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
853                 base_width = size_hints.min_width;
854                 base_height = size_hints.min_height;
855         }
856
857         if (size_hints.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
858                 min_width = size_hints.min_width;
859                 min_height = size_hints.min_height;
860         } else if (size_hints.flags & XCB_SIZE_HINT_P_SIZE) {
861                 min_width = size_hints.base_width;
862                 min_height = size_hints.base_height;
863         }
864
865         double width = client->rect.width - base_width;
866         double height = client->rect.height - base_height;
867         /* Convert numerator/denominator to a double */
868         double min_aspect = (double)size_hints.min_aspect_num / size_hints.min_aspect_den;
869         double max_aspect = (double)size_hints.max_aspect_num / size_hints.min_aspect_den;
870
871         LOG("min_aspect = %f, max_aspect = %f\n", min_aspect, max_aspect);
872         LOG("width = %f, height = %f\n", width, height);
873
874         /* Sanity checks, this is user-input, in a way */
875         if (max_aspect <= 0 || min_aspect <= 0 || height == 0 || (width / height) <= 0)
876                 return 1;
877
878         /* Check if we need to set proportional_* variables using the correct ratio */
879         if ((width / height) < min_aspect) {
880                 client->proportional_width = width;
881                 client->proportional_height = width / min_aspect;
882         } else if ((width / height) > max_aspect) {
883                 client->proportional_width = width;
884                 client->proportional_height = width / max_aspect;
885         } else return 1;
886
887         client->force_reconfigure = true;
888
889         if (client->container != NULL) {
890                 render_container(conn, client->container);
891                 xcb_flush(conn);
892         }
893
894         return 1;
895 }