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