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