]> git.sur5r.net Git - i3/i3/blob - i3-nagbar/main.c
i3-nagbar: Set button inner-width to the width of the label
[i3/i3] / i3-nagbar / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2013 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * i3-nagbar is a utility which displays a nag message, for example in the case
8  * when the user has an error in his configuration file.
9  *
10  */
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <sys/wait.h>
15 #include <stdlib.h>
16 #include <stdbool.h>
17 #include <unistd.h>
18 #include <string.h>
19 #include <errno.h>
20 #include <err.h>
21 #include <stdint.h>
22 #include <getopt.h>
23 #include <limits.h>
24 #include <fcntl.h>
25
26 #include <xcb/xcb.h>
27 #include <xcb/xcb_aux.h>
28 #include <xcb/xcb_event.h>
29
30 #include "libi3.h"
31 #include "i3-nagbar.h"
32
33 static char *argv0 = NULL;
34
35 typedef struct {
36     i3String *label;
37     char *action;
38     int16_t x;
39     uint16_t width;
40 } button_t;
41
42 static xcb_window_t win;
43 static xcb_pixmap_t pixmap;
44 static xcb_gcontext_t pixmap_gc;
45 static xcb_rectangle_t rect = { 0, 0, 600, 20 };
46 static i3Font font;
47 static i3String *prompt;
48 static button_t *buttons;
49 static int buttoncnt;
50
51 /* Result of get_colorpixel() for the various colors. */
52 static uint32_t color_background;        /* background of the bar */
53 static uint32_t color_button_background; /* background for buttons */
54 static uint32_t color_border;            /* color of the button border */
55 static uint32_t color_border_bottom;     /* color of the bottom border */
56 static uint32_t color_text;              /* color of the text */
57
58 xcb_window_t root;
59 xcb_connection_t *conn;
60 xcb_screen_t *root_screen;
61
62 /*
63  * Having verboselog() and errorlog() is necessary when using libi3.
64  *
65  */
66 void verboselog(char *fmt, ...) {
67     va_list args;
68
69     va_start(args, fmt);
70     vfprintf(stdout, fmt, args);
71     va_end(args);
72 }
73
74 void errorlog(char *fmt, ...) {
75     va_list args;
76
77     va_start(args, fmt);
78     vfprintf(stderr, fmt, args);
79     va_end(args);
80 }
81
82 /*
83  * Starts the given application by passing it through a shell. We use double fork
84  * to avoid zombie processes. As the started application’s parent exits (immediately),
85  * the application is reparented to init (process-id 1), which correctly handles
86  * childs, so we don’t have to do it :-).
87  *
88  * The shell is determined by looking for the SHELL environment variable. If it
89  * does not exist, /bin/sh is used.
90  *
91  */
92 static void start_application(const char *command) {
93     printf("executing: %s\n", command);
94     if (fork() == 0) {
95         /* Child process */
96         setsid();
97         if (fork() == 0) {
98             /* Stores the path of the shell */
99             static const char *shell = NULL;
100
101             if (shell == NULL)
102                 if ((shell = getenv("SHELL")) == NULL)
103                     shell = "/bin/sh";
104
105             /* This is the child */
106             execl(shell, shell, "-c", command, (void*)NULL);
107             /* not reached */
108         }
109         exit(0);
110     }
111     wait(0);
112 }
113
114 static button_t *get_button_at(int16_t x, int16_t y) {
115     for (int c = 0; c < buttoncnt; c++)
116         if (x >= (buttons[c].x) && x <= (buttons[c].x + buttons[c].width))
117             return &buttons[c];
118
119     return NULL;
120 }
121
122 static void handle_button_press(xcb_connection_t *conn, xcb_button_press_event_t *event) {
123     printf("button pressed on x = %d, y = %d\n",
124             event->event_x, event->event_y);
125     /* TODO: set a flag for the button, re-render */
126 }
127
128 /*
129  * Called when the user releases the mouse button. Checks whether the
130  * coordinates are over a button and executes the appropriate action.
131  *
132  */
133 static void handle_button_release(xcb_connection_t *conn, xcb_button_release_event_t *event) {
134     printf("button released on x = %d, y = %d\n",
135             event->event_x, event->event_y);
136     /* If the user hits the close button, we exit(0) */
137     if (event->event_x >= (rect.width - 32))
138         exit(0);
139     button_t *button = get_button_at(event->event_x, event->event_y);
140     if (!button)
141         return;
142
143     /* We need to create a custom script containing our actual command
144      * since not every terminal emulator which is contained in
145      * i3-sensible-terminal supports -e with multiple arguments (and not
146      * all of them support -e with one quoted argument either).
147      *
148      * NB: The paths need to be unique, that is, don’t assume users close
149      * their nagbars at any point in time (and they still need to work).
150      * */
151     char *script_path = get_process_filename("nagbar-cmd");
152
153     int fd = open(script_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
154     if (fd == -1) {
155         warn("Could not create temporary script to store the nagbar command");
156         return;
157     }
158     FILE *script = fdopen(fd, "w");
159     if (script == NULL) {
160         warn("Could not fdopen() temporary script to store the nagbar command");
161         return;
162     }
163     fprintf(script, "#!/bin/sh\nrm %s\n%s", script_path, button->action);
164     /* Also closes fd */
165     fclose(script);
166
167     char *link_path;
168     sasprintf(&link_path, "%s.nagbar_cmd", script_path);
169     symlink(get_exe_path(argv0), link_path);
170
171     char *terminal_cmd;
172     sasprintf(&terminal_cmd, "i3-sensible-terminal -e %s", link_path);
173     printf("argv0 = %s\n", argv0);
174     printf("terminal_cmd = %s\n", terminal_cmd);
175
176     start_application(terminal_cmd);
177
178     free(link_path);
179     free(terminal_cmd);
180     free(script_path);
181
182     /* TODO: unset flag, re-render */
183 }
184
185 /*
186  * Handles expose events (redraws of the window) and rendering in general. Will
187  * be called from the code with event == NULL or from X with event != NULL.
188  *
189  */
190 static int handle_expose(xcb_connection_t *conn, xcb_expose_event_t *event) {
191     /* re-draw the background */
192     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_background });
193     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &rect);
194
195     /* restore font color */
196     set_font_colors(pixmap_gc, color_text, color_background);
197     draw_text(prompt, pixmap, pixmap_gc,
198             4 + 4, 4 + 4, rect.width - 4 - 4);
199
200     /* render close button */
201     const char *close_button_label = "X";
202     int line_width = 4;
203     /* set width to the width of the label */
204     int w = predict_text_width(i3string_from_utf8(close_button_label));
205     /* account for left/right padding, which seems to be set to 8px (total) below */
206     w += 8;
207     int y = rect.width;
208     uint32_t values[3];
209     values[0] = color_button_background;
210     values[1] = line_width;
211     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
212
213     xcb_rectangle_t close = { y - w - (2 * line_width), 0, w + (2 * line_width), rect.height };
214     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &close);
215
216     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_border });
217     xcb_point_t points[] = {
218         { y - w - (2 * line_width), line_width / 2 },
219         { y - (line_width / 2), line_width / 2 },
220         { y - (line_width / 2), (rect.height - (line_width / 2)) - 2 },
221         { y - w - (2 * line_width), (rect.height - (line_width / 2)) - 2 },
222         { y - w - (2 * line_width), line_width / 2 }
223     };
224     xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, pixmap, pixmap_gc, 5, points);
225
226     values[0] = 1;
227     set_font_colors(pixmap_gc, color_text, color_button_background);
228     /* the x term here seems to set left/right padding */
229     draw_text_ascii(close_button_label, pixmap, pixmap_gc, y - w - line_width + w / 2 - 4,
230             4 + 4 - 1, rect.width - y + w + line_width - w / 2 + 4);
231     y -= w;
232
233     y -= 20;
234
235     /* render custom buttons */
236     line_width = 1;
237     for (int c = 0; c < buttoncnt; c++) {
238         /* set w to the width of the label */
239         w = predict_text_width(buttons[c].label);
240         /* account for left/right padding, which seems to be set to 12px (total) below */
241         w += 12;
242         y -= 30;
243         xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_button_background });
244         close = (xcb_rectangle_t){ y - w - (2 * line_width), 2, w + (2 * line_width), rect.height - 6 };
245         xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &close);
246
247         xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ color_border });
248         buttons[c].x = y - w - (2 * line_width);
249         buttons[c].width = w;
250         xcb_point_t points2[] = {
251             { y - w - (2 * line_width), (line_width / 2) + 2 },
252             { y - (line_width / 2), (line_width / 2) + 2 },
253             { y - (line_width / 2), (rect.height - 4 - (line_width / 2)) },
254             { y - w - (2 * line_width), (rect.height - 4 - (line_width / 2)) },
255             { y - w - (2 * line_width), (line_width / 2) + 2 }
256         };
257         xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, pixmap, pixmap_gc, 5, points2);
258
259         values[0] = color_text;
260         values[1] = color_button_background;
261         set_font_colors(pixmap_gc, color_text, color_button_background);
262         /* the x term seems to set left/right padding */
263         draw_text(buttons[c].label, pixmap, pixmap_gc,
264                 y - w - line_width + 6, 4 + 3, rect.width - y + w + line_width - 6);
265
266         y -= w;
267     }
268
269     /* border line at the bottom */
270     line_width = 2;
271     values[0] = color_border_bottom;
272     values[1] = line_width;
273     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND | XCB_GC_LINE_WIDTH, values);
274     xcb_point_t bottom[] = {
275         { 0, rect.height - 0 },
276         { rect.width, rect.height - 0 }
277     };
278     xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, pixmap, pixmap_gc, 2, bottom);
279
280
281     /* Copy the contents of the pixmap to the real window */
282     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, rect.width, rect.height);
283     xcb_flush(conn);
284
285     return 1;
286 }
287
288 int main(int argc, char *argv[]) {
289     /* The following lines are a terribly horrible kludge. Because terminal
290      * emulators have different ways of interpreting the -e command line
291      * argument (some need -e "less /etc/fstab", others need -e less
292      * /etc/fstab), we need to write commands to a script and then just run
293      * that script. However, since on some machines, $XDG_RUNTIME_DIR and
294      * $TMPDIR are mounted with noexec, we cannot directly execute the script
295      * either.
296      *
297      * Initially, we tried to pass the command via the environment variable
298      * _I3_NAGBAR_CMD. But turns out that some terminal emulators such as
299      * xfce4-terminal run all windows from a single master process and only
300      * pass on the command (not the environment) to that master process.
301      *
302      * Therefore, we symlink i3-nagbar (which MUST reside on an executable
303      * filesystem) with a special name and run that symlink. When i3-nagbar
304      * recognizes it’s started as a binary ending in .nagbar_cmd, it strips off
305      * the .nagbar_cmd suffix and runs /bin/sh on argv[0]. That way, we can run
306      * a shell script on a noexec filesystem.
307      *
308      * From a security point of view, i3-nagbar is just an alias to /bin/sh in
309      * certain circumstances. This should not open any new security issues, I
310      * hope. */
311     char *cmd = NULL;
312     const size_t argv0_len = strlen(argv[0]);
313     if (argv0_len > strlen(".nagbar_cmd") &&
314         strcmp(argv[0] + argv0_len - strlen(".nagbar_cmd"), ".nagbar_cmd") == 0) {
315         unlink(argv[0]);
316         cmd = strdup(argv[0]);
317         *(cmd + argv0_len - strlen(".nagbar_cmd")) = '\0';
318         execl("/bin/sh", "/bin/sh", cmd, NULL);
319         err(EXIT_FAILURE, "execv(/bin/sh, /bin/sh, %s)", cmd);
320     }
321
322     argv0 = argv[0];
323
324     char *pattern = sstrdup("-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1");
325     int o, option_index = 0;
326     enum { TYPE_ERROR = 0, TYPE_WARNING = 1 } bar_type = TYPE_ERROR;
327
328     static struct option long_options[] = {
329         {"version", no_argument, 0, 'v'},
330         {"font", required_argument, 0, 'f'},
331         {"button", required_argument, 0, 'b'},
332         {"help", no_argument, 0, 'h'},
333         {"message", required_argument, 0, 'm'},
334         {"type", required_argument, 0, 't'},
335         {0, 0, 0, 0}
336     };
337
338     char *options_string = "b:f:m:t:vh";
339
340     prompt = i3string_from_utf8("Please do not run this program.");
341
342     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
343         switch (o) {
344             case 'v':
345                 printf("i3-nagbar " I3_VERSION);
346                 return 0;
347             case 'f':
348                 FREE(pattern);
349                 pattern = sstrdup(optarg);
350                 break;
351             case 'm':
352                 i3string_free(prompt);
353                 prompt = i3string_from_utf8(optarg);
354                 break;
355             case 't':
356                 bar_type = (strcasecmp(optarg, "warning") == 0 ? TYPE_WARNING : TYPE_ERROR);
357                 break;
358             case 'h':
359                 printf("i3-nagbar " I3_VERSION "\n");
360                 printf("i3-nagbar [-m <message>] [-b <button> <action>] [-t warning|error] [-f <font>] [-v]\n");
361                 return 0;
362             case 'b':
363                 buttons = realloc(buttons, sizeof(button_t) * (buttoncnt + 1));
364                 buttons[buttoncnt].label = i3string_from_utf8(optarg);
365                 buttons[buttoncnt].action = argv[optind];
366                 printf("button with label *%s* and action *%s*\n",
367                         i3string_as_utf8(buttons[buttoncnt].label),
368                         buttons[buttoncnt].action);
369                 buttoncnt++;
370                 printf("now %d buttons\n", buttoncnt);
371                 if (optind < argc)
372                     optind++;
373                 break;
374         }
375     }
376
377     int screens;
378     if ((conn = xcb_connect(NULL, &screens)) == NULL ||
379         xcb_connection_has_error(conn))
380         die("Cannot open display\n");
381
382     /* Place requests for the atoms we need as soon as possible */
383     #define xmacro(atom) \
384         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
385     #include "atoms.xmacro"
386     #undef xmacro
387
388     root_screen = xcb_aux_get_screen(conn, screens);
389     root = root_screen->root;
390
391     if (bar_type == TYPE_ERROR) {
392         /* Red theme for error messages */
393         color_button_background = get_colorpixel("#680a0a");
394         color_background = get_colorpixel("#900000");
395         color_text = get_colorpixel("#ffffff");
396         color_border = get_colorpixel("#d92424");
397         color_border_bottom = get_colorpixel("#470909");
398     } else {
399         /* Yellowish theme for warnings */
400         color_button_background = get_colorpixel("#ffc100");
401         color_background = get_colorpixel("#ffa8000");
402         color_text = get_colorpixel("#000000");
403         color_border = get_colorpixel("#ab7100");
404         color_border_bottom = get_colorpixel("#ab7100");
405     }
406
407     font = load_font(pattern, true);
408     set_font(&font);
409
410     /* Open an input window */
411     win = xcb_generate_id(conn);
412
413     xcb_create_window(
414         conn,
415         XCB_COPY_FROM_PARENT,
416         win, /* the window id */
417         root, /* parent == root */
418         50, 50, 500, font.height + 8 + 8 /* 8 px padding */, /* dimensions */
419         0, /* x11 border = 0, we draw our own */
420         XCB_WINDOW_CLASS_INPUT_OUTPUT,
421         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
422         XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
423         (uint32_t[]){
424             0, /* back pixel: black */
425             XCB_EVENT_MASK_EXPOSURE |
426             XCB_EVENT_MASK_STRUCTURE_NOTIFY |
427             XCB_EVENT_MASK_BUTTON_PRESS |
428             XCB_EVENT_MASK_BUTTON_RELEASE
429         });
430
431     /* Map the window (make it visible) */
432     xcb_map_window(conn, win);
433
434     /* Setup NetWM atoms */
435     #define xmacro(name) \
436         do { \
437             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
438             if (!reply) \
439                 die("Could not get atom " # name "\n"); \
440             \
441             A_ ## name = reply->atom; \
442             free(reply); \
443         } while (0);
444     #include "atoms.xmacro"
445     #undef xmacro
446
447     /* Set dock mode */
448     xcb_change_property(conn,
449         XCB_PROP_MODE_REPLACE,
450         win,
451         A__NET_WM_WINDOW_TYPE,
452         A_ATOM,
453         32,
454         1,
455         (unsigned char*) &A__NET_WM_WINDOW_TYPE_DOCK);
456
457     /* Reserve some space at the top of the screen */
458     struct {
459         uint32_t left;
460         uint32_t right;
461         uint32_t top;
462         uint32_t bottom;
463         uint32_t left_start_y;
464         uint32_t left_end_y;
465         uint32_t right_start_y;
466         uint32_t right_end_y;
467         uint32_t top_start_x;
468         uint32_t top_end_x;
469         uint32_t bottom_start_x;
470         uint32_t bottom_end_x;
471     } __attribute__((__packed__)) strut_partial = {0,};
472
473     strut_partial.top = font.height + 6;
474     strut_partial.top_start_x = 0;
475     strut_partial.top_end_x = 800;
476
477     xcb_change_property(conn,
478         XCB_PROP_MODE_REPLACE,
479         win,
480         A__NET_WM_STRUT_PARTIAL,
481         A_CARDINAL,
482         32,
483         12,
484         &strut_partial);
485
486     /* Create pixmap */
487     pixmap = xcb_generate_id(conn);
488     pixmap_gc = xcb_generate_id(conn);
489     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, font.height + 8);
490     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
491
492     /* Grab the keyboard to get all input */
493     xcb_flush(conn);
494
495     xcb_generic_event_t *event;
496     while ((event = xcb_wait_for_event(conn)) != NULL) {
497         if (event->response_type == 0) {
498             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
499             continue;
500         }
501
502         /* Strip off the highest bit (set if the event is generated) */
503         int type = (event->response_type & 0x7F);
504
505         switch (type) {
506             case XCB_EXPOSE:
507                 handle_expose(conn, (xcb_expose_event_t*)event);
508                 break;
509
510             case XCB_BUTTON_PRESS:
511                 handle_button_press(conn, (xcb_button_press_event_t*)event);
512                 break;
513
514             case XCB_BUTTON_RELEASE:
515                 handle_button_release(conn, (xcb_button_release_event_t*)event);
516                 break;
517
518             case XCB_CONFIGURE_NOTIFY: {
519                 xcb_configure_notify_event_t *configure_notify = (xcb_configure_notify_event_t*)event;
520                 rect = (xcb_rectangle_t){
521                     configure_notify->x,
522                     configure_notify->y,
523                     configure_notify->width,
524                     configure_notify->height
525                 };
526
527                 /* Recreate the pixmap / gc */
528                 xcb_free_pixmap(conn, pixmap);
529                 xcb_free_gc(conn, pixmap_gc);
530
531                 xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, rect.width, rect.height);
532                 xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
533                 break;
534             }
535         }
536
537         free(event);
538     }
539
540     FREE(pattern);
541
542     return 0;
543 }