]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
bugfix: don’t send workspace command when at beginning/end of workspaces (Thanks...
[i3/i3] / i3bar / src / xcb.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3bar - an xcb-based status- and ws-bar for i3
5  * © 2010-2012 Axel Wagner and contributors (see also: LICENSE)
6  *
7  * xcb.c: Communicating with X
8  *
9  */
10 #include <xcb/xcb.h>
11 #include <xcb/xproto.h>
12 #include <xcb/xcb_atom.h>
13 #include <xcb/xcb_aux.h>
14
15 #ifdef XCB_COMPAT
16 #include "xcb_compat.h"
17 #endif
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <i3/ipc.h>
25 #include <ev.h>
26 #include <errno.h>
27 #include <limits.h>
28 #include <err.h>
29
30 #include <X11/Xlib.h>
31 #include <X11/XKBlib.h>
32 #include <X11/extensions/XKB.h>
33
34 #include "common.h"
35 #include "libi3.h"
36
37 /* We save the Atoms in an easy to access array, indexed by an enum */
38 enum {
39     #define ATOM_DO(name) name,
40     #include "xcb_atoms.def"
41     NUM_ATOMS
42 };
43
44 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
45 xcb_atom_t               atoms[NUM_ATOMS];
46
47 /* Variables, that are the same for all functions at all times */
48 xcb_connection_t *xcb_connection;
49 int              screen;
50 xcb_screen_t     *root_screen;
51 xcb_window_t     xcb_root;
52
53 /* This is needed for integration with libi3 */
54 xcb_connection_t *conn;
55
56 /* The font we'll use */
57 static i3Font font;
58
59 /* These are only relevant for XKB, which we only need for grabbing modifiers */
60 Display          *xkb_dpy;
61 int              xkb_event_base;
62 int              mod_pressed = 0;
63
64 /* Because the statusline is the same on all outputs, we have
65  * global buffer to render it on */
66 xcb_gcontext_t   statusline_ctx;
67 xcb_gcontext_t   statusline_clear;
68 xcb_pixmap_t     statusline_pm;
69 uint32_t         statusline_width;
70
71 /* Event-Watchers, to interact with the user */
72 ev_prepare *xcb_prep;
73 ev_check   *xcb_chk;
74 ev_io      *xcb_io;
75 ev_io      *xkb_io;
76
77 /* The parsed colors */
78 struct xcb_colors_t {
79     uint32_t bar_fg;
80     uint32_t bar_bg;
81     uint32_t active_ws_fg;
82     uint32_t active_ws_bg;
83     uint32_t active_ws_border;
84     uint32_t inactive_ws_fg;
85     uint32_t inactive_ws_bg;
86     uint32_t inactive_ws_border;
87     uint32_t urgent_ws_bg;
88     uint32_t urgent_ws_fg;
89     uint32_t urgent_ws_border;
90     uint32_t focus_ws_bg;
91     uint32_t focus_ws_fg;
92     uint32_t focus_ws_border;
93 };
94 struct xcb_colors_t colors;
95
96 /* We define xcb_request_failed as a macro to include the relevant line-number */
97 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
98 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
99     xcb_generic_error_t *err;
100     if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
101         fprintf(stderr, "[%s:%d] ERROR: %s. X Error Code: %d\n", __FILE__, line, err_msg, err->error_code);
102         return err->error_code;
103     }
104     return 0;
105 }
106
107 /*
108  * Redraws the statusline to the buffer
109  *
110  */
111 void refresh_statusline(void) {
112     struct status_block *block;
113
114     uint32_t old_statusline_width = statusline_width;
115     statusline_width = 0;
116
117     /* Predict the text width of all blocks (in pixels). */
118     TAILQ_FOREACH(block, &statusline_head, blocks) {
119         if (i3string_get_num_bytes(block->full_text) == 0)
120             continue;
121
122         block->width = predict_text_width(block->full_text);
123         /* If this is not the last block, add some pixels for a separator. */
124         if (TAILQ_NEXT(block, blocks) != NULL)
125             block->width += 9;
126         statusline_width += block->width;
127     }
128
129     /* If the statusline is bigger than our screen we need to make sure that
130      * the pixmap provides enough space, so re-allocate if the width grew */
131     if (statusline_width > root_screen->width_in_pixels &&
132         statusline_width > old_statusline_width)
133         realloc_sl_buffer();
134
135     /* Clear the statusline pixmap. */
136     xcb_rectangle_t rect = { 0, 0, root_screen->width_in_pixels, font.height };
137     xcb_poly_fill_rectangle(xcb_connection, statusline_pm, statusline_clear, 1, &rect);
138
139     /* Draw the text of each block. */
140     uint32_t x = 0;
141     TAILQ_FOREACH(block, &statusline_head, blocks) {
142         if (i3string_get_num_bytes(block->full_text) == 0)
143             continue;
144
145         uint32_t colorpixel = (block->color ? get_colorpixel(block->color) : colors.bar_fg);
146         set_font_colors(statusline_ctx, colorpixel, colors.bar_bg);
147         draw_text(block->full_text, statusline_pm, statusline_ctx, x, 0, block->width);
148         x += block->width;
149
150         if (TAILQ_NEXT(block, blocks) != NULL) {
151             /* This is not the last block, draw a separator. */
152             set_font_colors(statusline_ctx, get_colorpixel("#666666"), colors.bar_bg);
153             xcb_poly_line(xcb_connection, XCB_COORD_MODE_ORIGIN, statusline_pm,
154                           statusline_ctx, 2,
155                           (xcb_point_t[]){ { x - 5, 2 }, { x - 5, font.height - 2 } });
156         }
157     }
158 }
159
160 /*
161  * Hides all bars (unmaps them)
162  *
163  */
164 void hide_bars(void) {
165     if (!config.hide_on_modifier) {
166         return;
167     }
168
169     i3_output *walk;
170     SLIST_FOREACH(walk, outputs, slist) {
171         if (!walk->active) {
172             continue;
173         }
174         xcb_unmap_window(xcb_connection, walk->bar);
175     }
176     stop_child();
177 }
178
179 /*
180  * Unhides all bars (maps them)
181  *
182  */
183 void unhide_bars(void) {
184     if (!config.hide_on_modifier) {
185         return;
186     }
187
188     i3_output           *walk;
189     xcb_void_cookie_t   cookie;
190     uint32_t            mask;
191     uint32_t            values[5];
192
193     cont_child();
194
195     SLIST_FOREACH(walk, outputs, slist) {
196         if (walk->bar == XCB_NONE) {
197             continue;
198         }
199         mask = XCB_CONFIG_WINDOW_X |
200                XCB_CONFIG_WINDOW_Y |
201                XCB_CONFIG_WINDOW_WIDTH |
202                XCB_CONFIG_WINDOW_HEIGHT |
203                XCB_CONFIG_WINDOW_STACK_MODE;
204         values[0] = walk->rect.x;
205         if (config.position == POS_TOP)
206             values[1] = walk->rect.y;
207         else values[1] = walk->rect.y + walk->rect.h - font.height - 6;
208         values[2] = walk->rect.w;
209         values[3] = font.height + 6;
210         values[4] = XCB_STACK_MODE_ABOVE;
211         DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
212         cookie = xcb_configure_window_checked(xcb_connection,
213                                               walk->bar,
214                                               mask,
215                                               values);
216
217         if (xcb_request_failed(cookie, "Could not reconfigure window")) {
218             exit(EXIT_FAILURE);
219         }
220         xcb_map_window(xcb_connection, walk->bar);
221     }
222 }
223
224 /*
225  * Parse the colors into a format that we can use
226  *
227  */
228 void init_colors(const struct xcb_color_strings_t *new_colors) {
229 #define PARSE_COLOR(name, def) \
230     do { \
231         colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
232     } while  (0)
233     PARSE_COLOR(bar_fg, "#FFFFFF");
234     PARSE_COLOR(bar_bg, "#000000");
235     PARSE_COLOR(active_ws_fg, "#FFFFFF");
236     PARSE_COLOR(active_ws_bg, "#333333");
237     PARSE_COLOR(active_ws_border, "#333333");
238     PARSE_COLOR(inactive_ws_fg, "#888888");
239     PARSE_COLOR(inactive_ws_bg, "#222222");
240     PARSE_COLOR(inactive_ws_border, "#333333");
241     PARSE_COLOR(urgent_ws_fg, "#FFFFFF");
242     PARSE_COLOR(urgent_ws_bg, "#900000");
243     PARSE_COLOR(urgent_ws_border, "#2f343a");
244     PARSE_COLOR(focus_ws_fg, "#FFFFFF");
245     PARSE_COLOR(focus_ws_bg, "#285577");
246     PARSE_COLOR(focus_ws_border, "#4c7899");
247 #undef PARSE_COLOR
248 }
249
250 /*
251  * Handle a button-press-event (i.e. a mouse click on one of our bars).
252  * We determine, whether the click occured on a ws-button or if the scroll-
253  * wheel was used and change the workspace appropriately
254  *
255  */
256 void handle_button(xcb_button_press_event_t *event) {
257     i3_ws *cur_ws;
258
259     /* Determine, which bar was clicked */
260     i3_output *walk;
261     xcb_window_t bar = event->event;
262     SLIST_FOREACH(walk, outputs, slist) {
263         if (walk->bar == bar) {
264             break;
265         }
266     }
267
268     if (walk == NULL) {
269         DLOG("Unknown Bar klicked!\n");
270         return;
271     }
272
273     /* TODO: Move this to extern get_ws_for_output() */
274     TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
275         if (cur_ws->visible) {
276             break;
277         }
278     }
279
280     if (cur_ws == NULL) {
281         DLOG("No Workspace active?\n");
282         return;
283     }
284
285     int32_t x = event->event_x >= 0 ? event->event_x : 0;
286
287     DLOG("Got Button %d\n", event->detail);
288
289     switch (event->detail) {
290         case 1:
291             /* Left Mousbutton. We determine, which button was clicked
292              * and set cur_ws accordingly */
293             TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
294                 DLOG("x = %d\n", x);
295                 if (x >= 0 && x < cur_ws->name_width + 10) {
296                     break;
297                 }
298                 x -= cur_ws->name_width + 11;
299             }
300             if (cur_ws == NULL) {
301                 return;
302             }
303             break;
304         case 4:
305             /* Mouse wheel up. We select the previous ws, if any.
306              * If there is no more workspace, don’t even send the workspace
307              * command, otherwise (with workspace auto_back_and_forth) we’d end
308              * up on the wrong workspace. */
309             if (cur_ws == TAILQ_FIRST(walk->workspaces))
310                 return;
311
312             cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
313             break;
314         case 5:
315             /* Mouse wheel down. We select the next ws, if any.
316              * If there is no more workspace, don’t even send the workspace
317              * command, otherwise (with workspace auto_back_and_forth) we’d end
318              * up on the wrong workspace. */
319             if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head))
320                 return;
321
322             cur_ws = TAILQ_NEXT(cur_ws, tailq);
323             break;
324     }
325
326     /* To properly handle workspace names with double quotes in them, we need
327      * to escape the double quotes. Unfortunately, that’s rather ugly in C: We
328      * first count the number of double quotes, then we allocate a large enough
329      * buffer, then we copy character by character. */
330     int num_quotes = 0;
331     size_t namelen = 0;
332     const char *utf8_name = i3string_as_utf8(cur_ws->name);
333     for (const char *walk = utf8_name; *walk != '\0'; walk++) {
334         if (*walk == '"')
335             num_quotes++;
336         /* While we’re looping through the name anyway, we can save one
337          * strlen(). */
338         namelen++;
339     }
340
341     const size_t len = namelen + strlen("workspace \"\"") + 1;
342     char *buffer = scalloc(len+num_quotes);
343     strncpy(buffer, "workspace \"", strlen("workspace \""));
344     int inpos, outpos;
345     for (inpos = 0, outpos = strlen("workspace \"");
346          inpos < namelen;
347          inpos++, outpos++) {
348         if (utf8_name[inpos] == '"') {
349             buffer[outpos] = '\\';
350             outpos++;
351         }
352         buffer[outpos] = utf8_name[inpos];
353     }
354     buffer[outpos] = '"';
355     i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
356     free(buffer);
357 }
358
359 /*
360  * Configures the x coordinate of all trayclients. To be called after adding a
361  * new tray client or removing an old one.
362  *
363  */
364 static void configure_trayclients(void) {
365     trayclient *trayclient;
366     i3_output *output;
367     SLIST_FOREACH(output, outputs, slist) {
368         if (!output->active)
369             continue;
370
371         int clients = 0;
372         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
373             if (!trayclient->mapped)
374                 continue;
375             clients++;
376
377             DLOG("Configuring tray window %08x to x=%d\n",
378                  trayclient->win, output->rect.w - (clients * (font.height + 2)));
379             uint32_t x = output->rect.w - (clients * (font.height + 2));
380             xcb_configure_window(xcb_connection,
381                                  trayclient->win,
382                                  XCB_CONFIG_WINDOW_X,
383                                  &x);
384         }
385     }
386 }
387
388 /*
389  * Handles ClientMessages (messages sent from another client directly to us).
390  *
391  * At the moment, only the tray window will receive client messages. All
392  * supported client messages currently are _NET_SYSTEM_TRAY_OPCODE.
393  *
394  */
395 static void handle_client_message(xcb_client_message_event_t* event) {
396     if (event->type == atoms[_NET_SYSTEM_TRAY_OPCODE] &&
397         event->format == 32) {
398         DLOG("_NET_SYSTEM_TRAY_OPCODE received\n");
399         /* event->data.data32[0] is the timestamp */
400         uint32_t op = event->data.data32[1];
401         uint32_t mask;
402         uint32_t values[2];
403         if (op == SYSTEM_TRAY_REQUEST_DOCK) {
404             xcb_window_t client = event->data.data32[2];
405
406             /* Listen for PropertyNotify events to get the most recent value of
407              * the XEMBED_MAPPED atom, also listen for UnmapNotify events */
408             mask = XCB_CW_EVENT_MASK;
409             values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE |
410                         XCB_EVENT_MASK_STRUCTURE_NOTIFY;
411             xcb_change_window_attributes(xcb_connection,
412                                          client,
413                                          mask,
414                                          values);
415
416             /* Request the _XEMBED_INFO property. The XEMBED specification
417              * (which is referred by the tray specification) says this *has* to
418              * be set, but VLC does not set it… */
419             bool map_it = true;
420             int xe_version = 1;
421             xcb_get_property_cookie_t xembedc;
422             xcb_generic_error_t *error;
423             xembedc = xcb_get_property(xcb_connection,
424                                        0,
425                                        client,
426                                        atoms[_XEMBED_INFO],
427                                        XCB_GET_PROPERTY_TYPE_ANY,
428                                        0,
429                                        2 * 32);
430
431             xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
432                                                                        xembedc,
433                                                                        &error);
434             if (error != NULL) {
435                 ELOG("Error getting _XEMBED_INFO property: error_code %d\n",
436                      error->error_code);
437                 free(error);
438                 return;
439             }
440             if (xembedr != NULL && xembedr->length != 0) {
441                 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
442                 uint32_t *xembed = xcb_get_property_value(xembedr);
443                 DLOG("xembed version = %d\n", xembed[0]);
444                 DLOG("xembed flags = %d\n", xembed[1]);
445                 map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
446                 xe_version = xembed[0];
447                 if (xe_version > 1)
448                     xe_version = 1;
449                 free(xembedr);
450             } else {
451                 ELOG("Window %08x violates the XEMBED protocol, _XEMBED_INFO not set\n", client);
452             }
453
454             DLOG("X window %08x requested docking\n", client);
455             i3_output *walk, *output = NULL;
456             SLIST_FOREACH(walk, outputs, slist) {
457                 if (!walk->active)
458                     continue;
459                 if (config.tray_output) {
460                     if ((strcasecmp(walk->name, config.tray_output) != 0) &&
461                         (!walk->primary || strcasecmp("primary", config.tray_output) != 0))
462                         continue;
463                 }
464
465                 DLOG("using output %s\n", walk->name);
466                 output = walk;
467                 break;
468             }
469             /* In case of tray_output == primary and there is no primary output
470              * configured, we fall back to the first available output. */
471             if (output == NULL && strcasecmp("primary", config.tray_output) == 0) {
472                 SLIST_FOREACH(walk, outputs, slist) {
473                     if (!walk->active)
474                         continue;
475                     DLOG("Falling back to output %s because no primary output is configured\n", walk->name);
476                     output = walk;
477                     break;
478                 }
479             }
480             if (output == NULL) {
481                 ELOG("No output found\n");
482                 return;
483             }
484             xcb_reparent_window(xcb_connection,
485                                 client,
486                                 output->bar,
487                                 output->rect.w - font.height - 2,
488                                 2);
489             /* We reconfigure the window to use a reasonable size. The systray
490              * specification explicitly says:
491              *   Tray icons may be assigned any size by the system tray, and
492              *   should do their best to cope with any size effectively
493              */
494             mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
495             values[0] = font.height;
496             values[1] = font.height;
497             xcb_configure_window(xcb_connection,
498                                  client,
499                                  mask,
500                                  values);
501
502             /* send the XEMBED_EMBEDDED_NOTIFY message */
503             void *event = scalloc(32);
504             xcb_client_message_event_t *ev = event;
505             ev->response_type = XCB_CLIENT_MESSAGE;
506             ev->window = client;
507             ev->type = atoms[_XEMBED];
508             ev->format = 32;
509             ev->data.data32[0] = XCB_CURRENT_TIME;
510             ev->data.data32[1] = atoms[XEMBED_EMBEDDED_NOTIFY];
511             ev->data.data32[2] = output->bar;
512             ev->data.data32[3] = xe_version;
513             xcb_send_event(xcb_connection,
514                            0,
515                            client,
516                            XCB_EVENT_MASK_NO_EVENT,
517                            (char*)ev);
518             free(event);
519
520             /* Put the client inside the save set. Upon termination (whether
521              * killed or normal exit does not matter) of i3bar, these clients
522              * will be correctly reparented to their most closest living
523              * ancestor. Without this, tray icons might die when i3bar
524              * exits/crashes. */
525             xcb_change_save_set(xcb_connection, XCB_SET_MODE_INSERT, client);
526
527             if (map_it) {
528                 DLOG("Mapping dock client\n");
529                 xcb_map_window(xcb_connection, client);
530             } else {
531                 DLOG("Not mapping dock client yet\n");
532             }
533             trayclient *tc = smalloc(sizeof(trayclient));
534             tc->win = client;
535             tc->mapped = map_it;
536             tc->xe_version = xe_version;
537             TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
538
539             /* Trigger an update to copy the statusline text to the appropriate
540              * position */
541             configure_trayclients();
542             draw_bars(false);
543         }
544     }
545 }
546
547 /*
548  * Handles UnmapNotify events. These events happen when a tray window unmaps
549  * itself. We then update our data structure
550  *
551  */
552 static void handle_unmap_notify(xcb_unmap_notify_event_t* event) {
553     DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
554
555     i3_output *walk;
556     SLIST_FOREACH(walk, outputs, slist) {
557         if (!walk->active)
558             continue;
559         DLOG("checking output %s\n", walk->name);
560         trayclient *trayclient;
561         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
562             if (trayclient->win != event->window)
563                 continue;
564
565             DLOG("Removing tray client with window ID %08x\n", event->window);
566             TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
567
568             /* Trigger an update, we now have more space for the statusline */
569             configure_trayclients();
570             draw_bars(false);
571             return;
572         }
573     }
574 }
575
576 /*
577  * Handle PropertyNotify messages. Currently only the _XEMBED_INFO property is
578  * handled, which tells us whether a dock client should be mapped or unmapped.
579  *
580  */
581 static void handle_property_notify(xcb_property_notify_event_t *event) {
582     DLOG("PropertyNotify\n");
583     if (event->atom == atoms[_XEMBED_INFO] &&
584         event->state == XCB_PROPERTY_NEW_VALUE) {
585         DLOG("xembed_info updated\n");
586         trayclient *trayclient = NULL, *walk;
587         i3_output *o_walk;
588         SLIST_FOREACH(o_walk, outputs, slist) {
589             if (!o_walk->active)
590                 continue;
591
592             TAILQ_FOREACH(walk, o_walk->trayclients, tailq) {
593                 if (walk->win != event->window)
594                     continue;
595                 trayclient = walk;
596                 break;
597             }
598
599             if (trayclient)
600                 break;
601         }
602         if (!trayclient) {
603             ELOG("PropertyNotify received for unknown window %08x\n",
604                  event->window);
605             return;
606         }
607         xcb_get_property_cookie_t xembedc;
608         xembedc = xcb_get_property_unchecked(xcb_connection,
609                                              0,
610                                              trayclient->win,
611                                              atoms[_XEMBED_INFO],
612                                              XCB_GET_PROPERTY_TYPE_ANY,
613                                              0,
614                                              2 * 32);
615
616         xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
617                                                                    xembedc,
618                                                                    NULL);
619         if (xembedr == NULL || xembedr->length == 0) {
620             DLOG("xembed_info unset\n");
621             return;
622         }
623
624         DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
625         uint32_t *xembed = xcb_get_property_value(xembedr);
626         DLOG("xembed version = %d\n", xembed[0]);
627         DLOG("xembed flags = %d\n", xembed[1]);
628         bool map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
629         DLOG("map-state now %d\n", map_it);
630         if (trayclient->mapped && !map_it) {
631             /* need to unmap the window */
632             xcb_unmap_window(xcb_connection, trayclient->win);
633             trayclient->mapped = map_it;
634             configure_trayclients();
635             draw_bars(false);
636         } else if (!trayclient->mapped && map_it) {
637             /* need to map the window */
638             xcb_map_window(xcb_connection, trayclient->win);
639             trayclient->mapped = map_it;
640             configure_trayclients();
641             draw_bars(false);
642         }
643         free(xembedr);
644     }
645 }
646
647 /*
648  * Handle ConfigureRequests by denying them and sending the client a
649  * ConfigureNotify with its actual size.
650  *
651  */
652 static void handle_configure_request(xcb_configure_request_event_t *event) {
653     DLOG("ConfigureRequest for window = %08x\n", event->window);
654
655     trayclient *trayclient;
656     i3_output *output;
657     SLIST_FOREACH(output, outputs, slist) {
658         if (!output->active)
659             continue;
660
661         int clients = 0;
662         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
663             if (!trayclient->mapped)
664                 continue;
665             clients++;
666
667             if (trayclient->win != event->window)
668                 continue;
669
670             xcb_rectangle_t rect;
671             rect.x = output->rect.w - (clients * (font.height + 2));
672             rect.y = 2;
673             rect.width = font.height;
674             rect.height = font.height;
675
676             DLOG("This is a tray window. x = %d\n", rect.x);
677             fake_configure_notify(xcb_connection, rect, event->window, 0);
678             return;
679         }
680     }
681
682     DLOG("WARNING: Could not find corresponding tray window.\n");
683 }
684
685 /*
686  * This function is called immediately before the main loop locks. We flush xcb
687  * then (and only then)
688  *
689  */
690 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
691     xcb_flush(xcb_connection);
692 }
693
694 /*
695  * This function is called immediately after the main loop locks, so when one
696  * of the watchers registered an event.
697  * We check whether an X-Event arrived and handle it.
698  *
699  */
700 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
701     xcb_generic_event_t *event;
702
703     if (xcb_connection_has_error(xcb_connection)) {
704         ELOG("X11 connection was closed unexpectedly - maybe your X server terminated / crashed?\n");
705         exit(1);
706     }
707
708     while ((event = xcb_poll_for_event(xcb_connection)) != NULL) {
709         switch (event->response_type & ~0x80) {
710             case XCB_EXPOSE:
711                 /* Expose-events happen, when the window needs to be redrawn */
712                 redraw_bars();
713                 break;
714             case XCB_BUTTON_PRESS:
715                 /* Button-press-events are mouse-buttons clicked on one of our bars */
716                 handle_button((xcb_button_press_event_t*) event);
717                 break;
718             case XCB_CLIENT_MESSAGE:
719                 /* Client messages are used for client-to-client communication, for
720                  * example system tray widgets talk to us directly via client messages. */
721                 handle_client_message((xcb_client_message_event_t*) event);
722                 break;
723             case XCB_UNMAP_NOTIFY:
724             case XCB_DESTROY_NOTIFY:
725                 /* UnmapNotifies are received when a tray window unmaps itself */
726                 handle_unmap_notify((xcb_unmap_notify_event_t*) event);
727                 break;
728             case XCB_PROPERTY_NOTIFY:
729                 /* PropertyNotify */
730                 handle_property_notify((xcb_property_notify_event_t*) event);
731                 break;
732             case XCB_CONFIGURE_REQUEST:
733                 /* ConfigureRequest, sent by a tray child */
734                 handle_configure_request((xcb_configure_request_event_t*) event);
735                 break;
736         }
737         free(event);
738     }
739 }
740
741 /*
742  * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
743  * are triggered
744  *
745  */
746 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
747 }
748
749 /*
750  * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
751  *
752  */
753 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
754     XkbEvent ev;
755     int modstate = 0;
756
757     DLOG("Got XKB-Event!\n");
758
759     while (XPending(xkb_dpy)) {
760         XNextEvent(xkb_dpy, (XEvent*)&ev);
761
762         if (ev.type != xkb_event_base) {
763             ELOG("No Xkb-Event!\n");
764             continue;
765         }
766
767         if (ev.any.xkb_type != XkbStateNotify) {
768             ELOG("No State Notify!\n");
769             continue;
770         }
771
772         unsigned int mods = ev.state.mods;
773         modstate = mods & config.modifier;
774     }
775
776 #define DLOGMOD(modmask, status, barfunc) \
777     do { \
778         switch (modmask) { \
779             case ShiftMask: \
780                 DLOG("ShiftMask got " #status "!\n"); \
781                 break; \
782             case ControlMask: \
783                 DLOG("ControlMask got " #status "!\n"); \
784                 break; \
785             case Mod1Mask: \
786                 DLOG("Mod1Mask got " #status "!\n"); \
787                 break; \
788             case Mod2Mask: \
789                 DLOG("Mod2Mask got " #status "!\n"); \
790                 break; \
791             case Mod3Mask: \
792                 DLOG("Mod3Mask got " #status "!\n"); \
793                 break; \
794             case Mod4Mask: \
795                 DLOG("Mod4Mask got " #status "!\n"); \
796                 break; \
797             case Mod5Mask: \
798                 DLOG("Mod5Mask got " #status "!\n"); \
799                 break; \
800         } \
801         barfunc(); \
802     } while (0)
803
804     if (modstate != mod_pressed) {
805         if (modstate == 0) {
806             DLOGMOD(config.modifier, released, hide_bars);
807         } else {
808             DLOGMOD(config.modifier, pressed, unhide_bars);
809         }
810         mod_pressed = modstate;
811     }
812
813 #undef DLOGMOD
814 }
815
816 /*
817  * Early initialization of the connection to X11: Everything which does not
818  * depend on 'config'.
819  *
820  */
821 char *init_xcb_early() {
822     /* FIXME: xcb_connect leaks Memory */
823     xcb_connection = xcb_connect(NULL, &screen);
824     if (xcb_connection_has_error(xcb_connection)) {
825         ELOG("Cannot open display\n");
826         exit(EXIT_FAILURE);
827     }
828     conn = xcb_connection;
829     DLOG("Connected to xcb\n");
830
831     /* We have to request the atoms we need */
832     #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
833     #include "xcb_atoms.def"
834
835     root_screen = xcb_aux_get_screen(xcb_connection, screen);
836     xcb_root = root_screen->root;
837
838     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
839      * this way, we can choose to crop it */
840     uint32_t mask = XCB_GC_FOREGROUND;
841     uint32_t vals[] = { colors.bar_bg, colors.bar_bg };
842
843     statusline_clear = xcb_generate_id(xcb_connection);
844     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
845                                                                statusline_clear,
846                                                                xcb_root,
847                                                                mask,
848                                                                vals);
849
850     statusline_ctx = xcb_generate_id(xcb_connection);
851     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
852                                                             statusline_ctx,
853                                                             xcb_root,
854                                                             0,
855                                                             NULL);
856
857     statusline_pm = xcb_generate_id(xcb_connection);
858     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
859                                                                root_screen->root_depth,
860                                                                statusline_pm,
861                                                                xcb_root,
862                                                                root_screen->width_in_pixels,
863                                                                root_screen->height_in_pixels);
864
865
866     /* The various Watchers to communicate with xcb */
867     xcb_io = smalloc(sizeof(ev_io));
868     xcb_prep = smalloc(sizeof(ev_prepare));
869     xcb_chk = smalloc(sizeof(ev_check));
870
871     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
872     ev_prepare_init(xcb_prep, &xcb_prep_cb);
873     ev_check_init(xcb_chk, &xcb_chk_cb);
874
875     ev_io_start(main_loop, xcb_io);
876     ev_prepare_start(main_loop, xcb_prep);
877     ev_check_start(main_loop, xcb_chk);
878
879     /* Now we get the atoms and save them in a nice data structure */
880     get_atoms();
881
882     xcb_get_property_cookie_t path_cookie;
883     path_cookie = xcb_get_property_unchecked(xcb_connection,
884                                    0,
885                                    xcb_root,
886                                    atoms[I3_SOCKET_PATH],
887                                    XCB_GET_PROPERTY_TYPE_ANY,
888                                    0, PATH_MAX);
889
890     /* We check, if i3 set its socket-path */
891     xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
892                                                                   path_cookie,
893                                                                   NULL);
894     char *path = NULL;
895     if (path_reply) {
896         int len = xcb_get_property_value_length(path_reply);
897         if (len != 0) {
898             path = strndup(xcb_get_property_value(path_reply), len);
899         }
900     }
901
902
903     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
904         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
905         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
906         exit(EXIT_FAILURE);
907     }
908
909     return path;
910 }
911
912 /*
913  * Initialization which depends on 'config' being usable. Called after the
914  * configuration has arrived.
915  *
916  */
917 void init_xcb_late(char *fontname) {
918     if (fontname == NULL)
919         fontname = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
920
921     /* Load the font */
922     font = load_font(fontname, true);
923     set_font(&font);
924     DLOG("Calculated Font-height: %d\n", font.height);
925
926     xcb_flush(xcb_connection);
927
928     /* To grab modifiers without blocking other applications from receiving key-events
929      * involving that modifier, we sadly have to use xkb which is not yet fully supported
930      * in xcb */
931     if (config.hide_on_modifier) {
932         int xkb_major, xkb_minor, xkb_errbase, xkb_err;
933         xkb_major = XkbMajorVersion;
934         xkb_minor = XkbMinorVersion;
935
936         xkb_dpy = XkbOpenDisplay(NULL,
937                                  &xkb_event_base,
938                                  &xkb_errbase,
939                                  &xkb_major,
940                                  &xkb_minor,
941                                  &xkb_err);
942
943         if (xkb_dpy == NULL) {
944             ELOG("No XKB!\n");
945             exit(EXIT_FAILURE);
946         }
947
948         if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
949             ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
950             exit(EXIT_FAILURE);
951         }
952
953         int i1;
954         if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
955             ELOG("XKB not supported by X-server!\n");
956             exit(EXIT_FAILURE);
957         }
958
959         if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
960             ELOG("Could not grab Key!\n");
961             exit(EXIT_FAILURE);
962         }
963
964         xkb_io = smalloc(sizeof(ev_io));
965         ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
966         ev_io_start(main_loop, xkb_io);
967         XFlush(xkb_dpy);
968     }
969 }
970
971 /*
972  * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
973  * for the X11 display we are running on, then acquiring the selection for this
974  * atom. Afterwards, tray clients will send ClientMessages to our window.
975  *
976  */
977 void init_tray(void) {
978     DLOG("Initializing system tray functionality\n");
979     /* request the tray manager atom for the X11 display we are running on */
980     char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
981     snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
982     xcb_intern_atom_cookie_t tray_cookie;
983     xcb_intern_atom_reply_t *tray_reply;
984     tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
985
986     /* tray support: we need a window to own the selection */
987     xcb_window_t selwin = xcb_generate_id(xcb_connection);
988     uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
989     uint32_t selval[] = { 1 };
990     xcb_create_window(xcb_connection,
991                       root_screen->root_depth,
992                       selwin,
993                       xcb_root,
994                       -1, -1,
995                       1, 1,
996                       1,
997                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
998                       root_screen->root_visual,
999                       selmask,
1000                       selval);
1001
1002     uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
1003     /* set the atoms */
1004     xcb_change_property(xcb_connection,
1005                         XCB_PROP_MODE_REPLACE,
1006                         selwin,
1007                         atoms[_NET_SYSTEM_TRAY_ORIENTATION],
1008                         XCB_ATOM_CARDINAL,
1009                         32,
1010                         1,
1011                         &orientation);
1012
1013     if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
1014         ELOG("Could not get atom %s\n", atomname);
1015         exit(EXIT_FAILURE);
1016     }
1017
1018     xcb_set_selection_owner(xcb_connection,
1019                             selwin,
1020                             tray_reply->atom,
1021                             XCB_CURRENT_TIME);
1022
1023     /* Verify that we have the selection */
1024     xcb_get_selection_owner_cookie_t selcookie;
1025     xcb_get_selection_owner_reply_t *selreply;
1026
1027     selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
1028     if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
1029         ELOG("Could not get selection owner for %s\n", atomname);
1030         exit(EXIT_FAILURE);
1031     }
1032
1033     if (selreply->owner != selwin) {
1034         ELOG("Could not set the %s selection. " \
1035              "Maybe another tray is already running?\n", atomname);
1036         /* NOTE that this error is not fatal. We just can’t provide tray
1037          * functionality */
1038         free(selreply);
1039         return;
1040     }
1041
1042     /* Inform clients waiting for a new _NET_SYSTEM_TRAY that we are here */
1043     void *event = scalloc(32);
1044     xcb_client_message_event_t *ev = event;
1045     ev->response_type = XCB_CLIENT_MESSAGE;
1046     ev->window = xcb_root;
1047     ev->type = atoms[MANAGER];
1048     ev->format = 32;
1049     ev->data.data32[0] = XCB_CURRENT_TIME;
1050     ev->data.data32[1] = tray_reply->atom;
1051     ev->data.data32[2] = selwin;
1052     xcb_send_event(xcb_connection,
1053                    0,
1054                    xcb_root,
1055                    0xFFFFFF,
1056                    (char*)ev);
1057     free(event);
1058     free(tray_reply);
1059 }
1060
1061 /*
1062  * Cleanup the xcb-stuff.
1063  * Called once, before the program terminates.
1064  *
1065  */
1066 void clean_xcb(void) {
1067     i3_output *o_walk;
1068     free_workspaces();
1069     SLIST_FOREACH(o_walk, outputs, slist) {
1070         destroy_window(o_walk);
1071         FREE(o_walk->trayclients);
1072         FREE(o_walk->workspaces);
1073         FREE(o_walk->name);
1074     }
1075     FREE_SLIST(outputs, i3_output);
1076     FREE(outputs);
1077
1078     xcb_flush(xcb_connection);
1079     xcb_disconnect(xcb_connection);
1080
1081     ev_check_stop(main_loop, xcb_chk);
1082     ev_prepare_stop(main_loop, xcb_prep);
1083     ev_io_stop(main_loop, xcb_io);
1084
1085     FREE(xcb_chk);
1086     FREE(xcb_prep);
1087     FREE(xcb_io);
1088 }
1089
1090 /*
1091  * Get the earlier requested atoms and save them in the prepared data structure
1092  *
1093  */
1094 void get_atoms(void) {
1095     xcb_intern_atom_reply_t *reply;
1096     #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1097         if (reply == NULL) { \
1098             ELOG("Could not get atom %s\n", #name); \
1099             exit(EXIT_FAILURE); \
1100         } \
1101         atoms[name] = reply->atom; \
1102         free(reply);
1103
1104     #include "xcb_atoms.def"
1105     DLOG("Got Atoms\n");
1106 }
1107
1108 /*
1109  * Reparents all tray clients of the specified output to the root window. This
1110  * is either used when shutting down, when an output appears (xrandr --output
1111  * VGA1 --off) or when the primary output changes.
1112  *
1113  * Applications using the tray will start the protocol from the beginning again
1114  * afterwards.
1115  *
1116  */
1117 void kick_tray_clients(i3_output *output) {
1118     trayclient *trayclient;
1119     while (!TAILQ_EMPTY(output->trayclients)) {
1120         trayclient = TAILQ_FIRST(output->trayclients);
1121         /* Unmap, then reparent (to root) the tray client windows */
1122         xcb_unmap_window(xcb_connection, trayclient->win);
1123         xcb_reparent_window(xcb_connection,
1124                             trayclient->win,
1125                             xcb_root,
1126                             0,
1127                             0);
1128
1129         /* We remove the trayclient right here. We might receive an UnmapNotify
1130          * event afterwards, but better safe than sorry. */
1131         TAILQ_REMOVE(output->trayclients, trayclient, tailq);
1132     }
1133 }
1134
1135 /*
1136  * Destroy the bar of the specified output
1137  *
1138  */
1139 void destroy_window(i3_output *output) {
1140     if (output == NULL) {
1141         return;
1142     }
1143     if (output->bar == XCB_NONE) {
1144         return;
1145     }
1146
1147     kick_tray_clients(output);
1148     xcb_destroy_window(xcb_connection, output->bar);
1149     output->bar = XCB_NONE;
1150 }
1151
1152 /*
1153  * Reallocate the statusline-buffer
1154  *
1155  */
1156 void realloc_sl_buffer(void) {
1157     DLOG("Re-allocating statusline-buffer, statusline_width = %d, root_screen->width_in_pixels = %d\n",
1158          statusline_width, root_screen->width_in_pixels);
1159     xcb_free_pixmap(xcb_connection, statusline_pm);
1160     statusline_pm = xcb_generate_id(xcb_connection);
1161     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1162                                                                root_screen->root_depth,
1163                                                                statusline_pm,
1164                                                                xcb_root,
1165                                                                MAX(root_screen->width_in_pixels, statusline_width),
1166                                                                root_screen->height_in_pixels);
1167
1168     uint32_t mask = XCB_GC_FOREGROUND;
1169     uint32_t vals[2] = { colors.bar_bg, colors.bar_bg };
1170     xcb_free_gc(xcb_connection, statusline_clear);
1171     statusline_clear = xcb_generate_id(xcb_connection);
1172     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1173                                                                statusline_clear,
1174                                                                xcb_root,
1175                                                                mask,
1176                                                                vals);
1177
1178     mask |= XCB_GC_BACKGROUND;
1179     vals[0] = colors.bar_fg;
1180     statusline_ctx = xcb_generate_id(xcb_connection);
1181     xcb_free_gc(xcb_connection, statusline_ctx);
1182     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1183                                                             statusline_ctx,
1184                                                             xcb_root,
1185                                                             mask,
1186                                                             vals);
1187
1188     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1189         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1190         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1191         exit(EXIT_FAILURE);
1192     }
1193
1194 }
1195
1196 /*
1197  * Reconfigure all bars and create new bars for recently activated outputs
1198  *
1199  */
1200 void reconfig_windows(void) {
1201     uint32_t mask;
1202     uint32_t values[5];
1203     static bool tray_configured = false;
1204
1205     i3_output *walk;
1206     SLIST_FOREACH(walk, outputs, slist) {
1207         if (!walk->active) {
1208             /* If an output is not active, we destroy its bar */
1209             /* FIXME: Maybe we rather want to unmap? */
1210             DLOG("Destroying window for output %s\n", walk->name);
1211             destroy_window(walk);
1212             continue;
1213         }
1214         if (walk->bar == XCB_NONE) {
1215             DLOG("Creating Window for output %s\n", walk->name);
1216
1217             walk->bar = xcb_generate_id(xcb_connection);
1218             walk->buffer = xcb_generate_id(xcb_connection);
1219             mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
1220             /* Black background */
1221             values[0] = colors.bar_bg;
1222             /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
1223             values[1] = config.hide_on_modifier;
1224             /* We enable the following EventMask fields:
1225              * EXPOSURE, to get expose events (we have to re-draw then)
1226              * SUBSTRUCTURE_REDIRECT, to get ConfigureRequests when the tray
1227              *                        child windows use ConfigureWindow
1228              * BUTTON_PRESS, to handle clicks on the workspace buttons
1229              * */
1230             values[2] = XCB_EVENT_MASK_EXPOSURE |
1231                         XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
1232             if (!config.disable_ws) {
1233                 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
1234             }
1235             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1236                                                                      root_screen->root_depth,
1237                                                                      walk->bar,
1238                                                                      xcb_root,
1239                                                                      walk->rect.x, walk->rect.y + walk->rect.h - font.height - 6,
1240                                                                      walk->rect.w, font.height + 6,
1241                                                                      1,
1242                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
1243                                                                      root_screen->root_visual,
1244                                                                      mask,
1245                                                                      values);
1246
1247             /* The double-buffer we use to render stuff off-screen */
1248             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1249                                                                     root_screen->root_depth,
1250                                                                     walk->buffer,
1251                                                                     walk->bar,
1252                                                                     walk->rect.w,
1253                                                                     walk->rect.h);
1254
1255             /* Set the WM_CLASS and WM_NAME (we don't need UTF-8) atoms */
1256             xcb_void_cookie_t class_cookie;
1257             class_cookie = xcb_change_property(xcb_connection,
1258                                                XCB_PROP_MODE_REPLACE,
1259                                                walk->bar,
1260                                                XCB_ATOM_WM_CLASS,
1261                                                XCB_ATOM_STRING,
1262                                                8,
1263                                                (strlen("i3bar") + 1) * 2,
1264                                                "i3bar\0i3bar\0");
1265
1266             char *name;
1267             if (asprintf(&name, "i3bar for output %s", walk->name) == -1)
1268                 err(EXIT_FAILURE, "asprintf()");
1269             xcb_void_cookie_t name_cookie;
1270             name_cookie = xcb_change_property(xcb_connection,
1271                                               XCB_PROP_MODE_REPLACE,
1272                                               walk->bar,
1273                                               XCB_ATOM_WM_NAME,
1274                                               XCB_ATOM_STRING,
1275                                               8,
1276                                               strlen(name),
1277                                               name);
1278             free(name);
1279
1280             /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
1281              * this one */
1282             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1283                                                                 XCB_PROP_MODE_REPLACE,
1284                                                                 walk->bar,
1285                                                                 atoms[_NET_WM_WINDOW_TYPE],
1286                                                                 XCB_ATOM_ATOM,
1287                                                                 32,
1288                                                                 1,
1289                                                                 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1290
1291             /* We need to tell i3, where to reserve space for i3bar */
1292             /* left, right, top, bottom, left_start_y, left_end_y,
1293              * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
1294              * bottom_end_x */
1295             /* A local struct to save the strut_partial property */
1296             struct {
1297                 uint32_t left;
1298                 uint32_t right;
1299                 uint32_t top;
1300                 uint32_t bottom;
1301                 uint32_t left_start_y;
1302                 uint32_t left_end_y;
1303                 uint32_t right_start_y;
1304                 uint32_t right_end_y;
1305                 uint32_t top_start_x;
1306                 uint32_t top_end_x;
1307                 uint32_t bottom_start_x;
1308                 uint32_t bottom_end_x;
1309             } __attribute__((__packed__)) strut_partial = {0,};
1310             switch (config.position) {
1311                 case POS_NONE:
1312                     break;
1313                 case POS_TOP:
1314                     strut_partial.top = font.height + 6;
1315                     strut_partial.top_start_x = walk->rect.x;
1316                     strut_partial.top_end_x = walk->rect.x + walk->rect.w;
1317                     break;
1318                 case POS_BOT:
1319                     strut_partial.bottom = font.height + 6;
1320                     strut_partial.bottom_start_x = walk->rect.x;
1321                     strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
1322                     break;
1323             }
1324             xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
1325                                                                  XCB_PROP_MODE_REPLACE,
1326                                                                  walk->bar,
1327                                                                  atoms[_NET_WM_STRUT_PARTIAL],
1328                                                                  XCB_ATOM_CARDINAL,
1329                                                                  32,
1330                                                                  12,
1331                                                                  &strut_partial);
1332
1333             /* We also want a graphics-context for the bars (it defines the properties
1334              * with which we draw to them) */
1335             walk->bargc = xcb_generate_id(xcb_connection);
1336             xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1337                                                                 walk->bargc,
1338                                                                 walk->bar,
1339                                                                 0,
1340                                                                 NULL);
1341
1342             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1343             xcb_void_cookie_t map_cookie;
1344             if (!config.hide_on_modifier) {
1345                 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1346             }
1347
1348             if (xcb_request_failed(win_cookie,   "Could not create window") ||
1349                 xcb_request_failed(pm_cookie,    "Could not create pixmap") ||
1350                 xcb_request_failed(dock_cookie,  "Could not set dock mode") ||
1351                 xcb_request_failed(class_cookie, "Could not set WM_CLASS")  ||
1352                 xcb_request_failed(name_cookie,  "Could not set WM_NAME")   ||
1353                 xcb_request_failed(strut_cookie, "Could not set strut")     ||
1354                 xcb_request_failed(gc_cookie,    "Could not create graphical context") ||
1355                 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
1356                 exit(EXIT_FAILURE);
1357             }
1358
1359             if (!tray_configured &&
1360                 (!config.tray_output ||
1361                  strcasecmp("none", config.tray_output) != 0)) {
1362                 init_tray();
1363                 tray_configured = true;
1364             }
1365         } else {
1366             /* We already have a bar, so we just reconfigure it */
1367             mask = XCB_CONFIG_WINDOW_X |
1368                    XCB_CONFIG_WINDOW_Y |
1369                    XCB_CONFIG_WINDOW_WIDTH |
1370                    XCB_CONFIG_WINDOW_HEIGHT |
1371                    XCB_CONFIG_WINDOW_STACK_MODE;
1372             values[0] = walk->rect.x;
1373             values[1] = walk->rect.y + walk->rect.h - font.height - 6;
1374             values[2] = walk->rect.w;
1375             values[3] = font.height + 6;
1376             values[4] = XCB_STACK_MODE_ABOVE;
1377
1378             DLOG("Destroying buffer for output %s", walk->name);
1379             xcb_free_pixmap(xcb_connection, walk->buffer);
1380
1381             DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1382             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1383                                                                         walk->bar,
1384                                                                         mask,
1385                                                                         values);
1386
1387             DLOG("Recreating buffer for output %s", walk->name);
1388             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1389                                                                     root_screen->root_depth,
1390                                                                     walk->buffer,
1391                                                                     walk->bar,
1392                                                                     walk->rect.w,
1393                                                                     walk->rect.h);
1394
1395             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
1396                 exit(EXIT_FAILURE);
1397             }
1398             if (xcb_request_failed(pm_cookie,  "Could not create pixmap")) {
1399                 exit(EXIT_FAILURE);
1400             }
1401         }
1402     }
1403 }
1404
1405 /*
1406  * Render the bars, with buttons and statusline
1407  *
1408  */
1409 void draw_bars(bool unhide) {
1410     DLOG("Drawing Bars...\n");
1411     int i = 0;
1412
1413     refresh_statusline();
1414
1415     static char *last_urgent_ws = NULL;
1416     bool walks_away = true;
1417
1418     i3_output *outputs_walk;
1419     SLIST_FOREACH(outputs_walk, outputs, slist) {
1420         if (!outputs_walk->active) {
1421             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1422             continue;
1423         }
1424         if (outputs_walk->bar == XCB_NONE) {
1425             /* Oh shit, an active output without an own bar. Create it now! */
1426             reconfig_windows();
1427         }
1428         /* First things first: clear the backbuffer */
1429         uint32_t color = colors.bar_bg;
1430         xcb_change_gc(xcb_connection,
1431                       outputs_walk->bargc,
1432                       XCB_GC_FOREGROUND,
1433                       &color);
1434         xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font.height + 6 };
1435         xcb_poly_fill_rectangle(xcb_connection,
1436                                 outputs_walk->buffer,
1437                                 outputs_walk->bargc,
1438                                 1,
1439                                 &rect);
1440
1441         if (!TAILQ_EMPTY(&statusline_head)) {
1442             DLOG("Printing statusline!\n");
1443
1444             /* Luckily we already prepared a seperate pixmap containing the rendered
1445              * statusline, we just have to copy the relevant parts to the relevant
1446              * position */
1447             trayclient *trayclient;
1448             int traypx = 0;
1449             TAILQ_FOREACH(trayclient, outputs_walk->trayclients, tailq) {
1450                 if (!trayclient->mapped)
1451                     continue;
1452                 /* We assume the tray icons are quadratic (we use the font
1453                  * *height* as *width* of the icons) because we configured them
1454                  * like this. */
1455                 traypx += font.height + 2;
1456             }
1457             /* Add 2px of padding if there are any tray icons */
1458             if (traypx > 0)
1459                 traypx += 2;
1460             xcb_copy_area(xcb_connection,
1461                           statusline_pm,
1462                           outputs_walk->buffer,
1463                           outputs_walk->bargc,
1464                           MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
1465                           MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - traypx - 4)), 3,
1466                           MIN(outputs_walk->rect.w - traypx - 4, statusline_width), font.height);
1467         }
1468
1469         if (config.disable_ws) {
1470             continue;
1471         }
1472
1473         i3_ws *ws_walk;
1474
1475         TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1476             DLOG("Drawing Button for WS %s at x = %d, len = %d\n", i3string_as_utf8(ws_walk->name), i, ws_walk->name_width);
1477             uint32_t fg_color = colors.inactive_ws_fg;
1478             uint32_t bg_color = colors.inactive_ws_bg;
1479             uint32_t border_color = colors.inactive_ws_border;
1480             if (ws_walk->visible) {
1481                 if (!ws_walk->focused) {
1482                     fg_color = colors.active_ws_fg;
1483                     bg_color = colors.active_ws_bg;
1484                     border_color = colors.active_ws_border;
1485                 } else {
1486                     fg_color = colors.focus_ws_fg;
1487                     bg_color = colors.focus_ws_bg;
1488                     border_color = colors.focus_ws_border;
1489                     if (last_urgent_ws && strcmp(i3string_as_utf8(ws_walk->name), last_urgent_ws) == 0)
1490                         walks_away = false;
1491                 }
1492             }
1493             if (ws_walk->urgent) {
1494                 DLOG("WS %s is urgent!\n", i3string_as_utf8(ws_walk->name));
1495                 fg_color = colors.urgent_ws_fg;
1496                 bg_color = colors.urgent_ws_bg;
1497                 border_color = colors.urgent_ws_border;
1498                 unhide = true;
1499                 if (!ws_walk->focused) {
1500                     FREE(last_urgent_ws);
1501                     last_urgent_ws = sstrdup(i3string_as_utf8(ws_walk->name));
1502                 }
1503             }
1504             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1505             uint32_t vals_border[] = { border_color, border_color };
1506             xcb_change_gc(xcb_connection,
1507                           outputs_walk->bargc,
1508                           mask,
1509                           vals_border);
1510             xcb_rectangle_t rect_border = { i, 0, ws_walk->name_width + 10, font.height + 4 };
1511             xcb_poly_fill_rectangle(xcb_connection,
1512                                     outputs_walk->buffer,
1513                                     outputs_walk->bargc,
1514                                     1,
1515                                     &rect_border);
1516             uint32_t vals[] = { bg_color, bg_color };
1517             xcb_change_gc(xcb_connection,
1518                           outputs_walk->bargc,
1519                           mask,
1520                           vals);
1521             xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font.height + 2 };
1522             xcb_poly_fill_rectangle(xcb_connection,
1523                                     outputs_walk->buffer,
1524                                     outputs_walk->bargc,
1525                                     1,
1526                                     &rect);
1527             set_font_colors(outputs_walk->bargc, fg_color, bg_color);
1528             draw_text(ws_walk->name, outputs_walk->buffer, outputs_walk->bargc, i + 5, 2, ws_walk->name_width);
1529             i += 10 + ws_walk->name_width + 1;
1530         }
1531
1532         i = 0;
1533     }
1534
1535     if (!mod_pressed) {
1536         if (unhide) {
1537             /* The urgent-hint should get noticed, so we unhide the bars shortly */
1538             unhide_bars();
1539         } else if (walks_away) {
1540             FREE(last_urgent_ws);
1541             hide_bars();
1542         }
1543     }
1544
1545     redraw_bars();
1546 }
1547
1548 /*
1549  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1550  *
1551  */
1552 void redraw_bars(void) {
1553     i3_output *outputs_walk;
1554     SLIST_FOREACH(outputs_walk, outputs, slist) {
1555         if (!outputs_walk->active) {
1556             continue;
1557         }
1558         xcb_copy_area(xcb_connection,
1559                       outputs_walk->buffer,
1560                       outputs_walk->bar,
1561                       outputs_walk->bargc,
1562                       0, 0,
1563                       0, 0,
1564                       outputs_walk->rect.w,
1565                       outputs_walk->rect.h);
1566         xcb_flush(xcb_connection);
1567     }
1568 }