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