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