2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
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.
14 #include <sys/types.h>
30 #include <xcb/xcb_aux.h>
31 #include <xcb/xcb_event.h>
32 #include <xcb/randr.h>
33 #include <xcb/xcb_cursor.h>
35 #define SN_API_NOT_YET_FROZEN 1
36 #include <libsn/sn-launchee.h>
38 #include "i3-nagbar.h"
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
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)
51 static char *argv0 = NULL;
61 static xcb_window_t win;
65 static i3String *prompt;
67 static button_t btn_close;
68 static button_t *buttons;
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 */
79 xcb_connection_t *conn;
80 xcb_screen_t *root_screen;
83 * Having verboselog(), errorlog() and debuglog() is necessary when using libi3.
86 void verboselog(char *fmt, ...) {
90 vfprintf(stdout, fmt, args);
94 void errorlog(char *fmt, ...) {
98 vfprintf(stderr, fmt, args);
102 void debuglog(char *fmt, ...) {
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 :-).
111 * The shell is determined by looking for the SHELL environment variable. If it
112 * does not exist, /bin/sh is used.
115 static void start_application(const char *command) {
116 printf("executing: %s\n", command);
121 /* This is the child */
122 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, NULL);
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))
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 */
145 * Called when the user releases the mouse button. Checks whether the
146 * coordinates are over a button and executes the appropriate action.
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)
155 button_t *button = get_button_at(event->event_x, event->event_y);
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).
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).
167 char *script_path = get_process_filename("nagbar-cmd");
169 int fd = open(script_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
171 warn("Could not create temporary script to store the nagbar command");
174 FILE *script = fdopen(fd, "w");
175 if (script == NULL) {
176 warn("Could not fdopen() temporary script to store the nagbar command");
179 fprintf(script, "#!/bin/sh\nrm %s\n%s", script_path, button->action);
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);
191 if (button->terminal) {
192 sasprintf(&terminal_cmd, "i3-sensible-terminal -e %s", link_path);
194 terminal_cmd = sstrdup(link_path);
196 printf("argv0 = %s\n", argv0);
197 printf("terminal_cmd = %s\n", terminal_cmd);
199 start_application(terminal_cmd);
206 /* TODO: unset flag, re-render */
210 * Draws a button and returns its width
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;
219 draw_util_rectangle(&bar, color_border,
220 position - button->width,
221 MSG_PADDING - BTN_PADDING - BTN_BORDER,
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);
231 draw_util_text(button->label, &bar, color_text, color_button_background,
232 position - button->width + BTN_BORDER + BTN_PADDING,
235 return button->width;
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.
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);
247 draw_util_text(prompt, &bar, color_text, color_background,
248 MSG_PADDING, MSG_PADDING,
249 bar.width - 2 * MSG_PADDING);
251 int position = bar.width - (MSG_PADDING - BTN_BORDER - BTN_PADDING);
253 /* render close button */
254 position -= button_draw(&btn_close, position);
255 position -= CLOSE_BTN_GAP;
257 /* render custom buttons */
258 for (int i = 0; i < buttoncnt; i++) {
260 position -= button_draw(&buttons[i], position);
263 /* border line at the bottom */
264 draw_util_rectangle(&bar, color_border_bottom, 0, bar.height - BAR_BORDER, bar.width, BAR_BORDER);
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.
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};
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);
281 xcb_randr_get_output_primary_reply_t *primary = NULL;
282 xcb_randr_get_screen_resources_current_reply_t *res = NULL;
284 if ((primary = xcb_randr_get_output_primary_reply(conn, pcookie, NULL)) == NULL) {
285 DLOG("Could not determine the primary output.\n");
289 if ((res = xcb_randr_get_screen_resources_current_reply(conn, rcookie, NULL)) == NULL) {
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),
297 if (output == NULL || output->crtc == XCB_NONE)
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),
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");
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
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.
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.
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
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) {
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);
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;
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'},
375 char *options_string = "b:B:f:m:t:vh";
377 prompt = i3string_from_utf8("Please do not run this program.");
379 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
382 printf("i3-nagbar " I3_VERSION "\n");
386 pattern = sstrdup(optarg);
389 i3string_free(prompt);
390 prompt = i3string_from_utf8(optarg);
393 bar_type = (strcasecmp(optarg, "warning") == 0 ? TYPE_WARNING : TYPE_ERROR);
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");
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);
409 printf("now %d buttons\n", buttoncnt);
416 btn_close.label = i3string_from_utf8("X");
419 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
420 xcb_connection_has_error(conn))
421 die("Cannot open display");
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"
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);
434 root_screen = xcb_aux_get_screen(conn, screens);
435 root = root_screen->root;
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");
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");
454 font = load_font(pattern, true);
457 #if defined(__OpenBSD__)
458 if (pledge("stdio rpath wpath cpath getpw proc exec", NULL) == -1)
459 err(EXIT_FAILURE, "pledge");
462 xcb_rectangle_t win_pos = get_window_position();
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);
470 cursor = xcb_generate_id(conn);
471 i3Font cursor_font = load_font("cursor", false);
472 xcb_create_glyph_cursor(
475 cursor_font.specific.xcb.id,
476 cursor_font.specific.xcb.id,
478 XCB_CURSOR_LEFT_PTR + 1,
480 65535, 65535, 65535);
483 /* Open an input window */
484 win = xcb_generate_id(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,
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,
504 sn_launchee_context_setup_window(sncontext, win);
507 /* Map the window (make it visible) */
508 xcb_map_window(conn, win);
510 /* Setup NetWM atoms */
511 #define xmacro(name) \
513 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
515 die("Could not get atom " #name); \
517 A_##name = reply->atom; \
520 #include "atoms.xmacro"
524 xcb_change_property(conn,
525 XCB_PROP_MODE_REPLACE,
527 A__NET_WM_WINDOW_TYPE,
531 (unsigned char *)&A__NET_WM_WINDOW_TYPE_DOCK);
533 /* Reserve some space at the top of the screen */
539 uint32_t left_start_y;
541 uint32_t right_start_y;
542 uint32_t right_end_y;
543 uint32_t top_start_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));
550 strut_partial.top = font.height + logical_px(6);
551 strut_partial.top_start_x = 0;
552 strut_partial.top_end_x = 800;
554 xcb_change_property(conn,
555 XCB_PROP_MODE_REPLACE,
557 A__NET_WM_STRUT_PARTIAL,
563 /* Initialize the drawable bar */
564 draw_util_surface_init(conn, &bar, win, get_visualtype(root_screen), win_pos.width, win_pos.height);
566 /* Startup complete. */
568 sn_launchee_context_complete(sncontext);
569 sn_launchee_context_unref(sncontext);
572 /* Grab the keyboard to get all input */
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);
582 /* Strip off the highest bit (set if the event is generated) */
583 int type = (event->response_type & 0x7F);
587 if (((xcb_expose_event_t *)event)->count == 0) {
588 handle_expose(conn, (xcb_expose_event_t *)event);
593 case XCB_BUTTON_PRESS:
594 handle_button_press(conn, (xcb_button_press_event_t *)event);
597 case XCB_BUTTON_RELEASE:
598 handle_button_release(conn, (xcb_button_release_event_t *)event);
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);
614 draw_util_surface_free(conn, &bar);