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