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