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;
60 static xcb_window_t win;
64 static i3String *prompt;
66 static button_t btn_close;
67 static button_t *buttons;
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 */
78 xcb_connection_t *conn;
79 xcb_screen_t *root_screen;
82 * Having verboselog(), errorlog() and debuglog() is necessary when using libi3.
85 void verboselog(char *fmt, ...) {
89 vfprintf(stdout, fmt, args);
93 void errorlog(char *fmt, ...) {
97 vfprintf(stderr, fmt, args);
101 void debuglog(char *fmt, ...) {
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 :-).
110 * The shell is determined by looking for the SHELL environment variable. If it
111 * does not exist, /bin/sh is used.
114 static void start_application(const char *command) {
115 printf("executing: %s\n", command);
120 /* This is the child */
121 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, NULL);
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))
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 */
144 * Called when the user releases the mouse button. Checks whether the
145 * coordinates are over a button and executes the appropriate action.
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)
154 button_t *button = get_button_at(event->event_x, event->event_y);
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).
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).
166 char *script_path = get_process_filename("nagbar-cmd");
168 int fd = open(script_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
170 warn("Could not create temporary script to store the nagbar command");
173 FILE *script = fdopen(fd, "w");
174 if (script == NULL) {
175 warn("Could not fdopen() temporary script to store the nagbar command");
178 fprintf(script, "#!/bin/sh\nrm %s\n%s", script_path, button->action);
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);
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);
194 start_application(terminal_cmd);
201 /* TODO: unset flag, re-render */
205 * Draws a button and returns its width
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;
214 draw_util_rectangle(&bar, color_border,
215 position - button->width,
216 MSG_PADDING - BTN_PADDING - BTN_BORDER,
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);
226 draw_util_text(button->label, &bar, color_text, color_button_background,
227 position - button->width + BTN_BORDER + BTN_PADDING,
230 return button->width;
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.
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);
242 draw_util_text(prompt, &bar, color_text, color_background,
243 MSG_PADDING, MSG_PADDING,
244 bar.width - 2 * MSG_PADDING);
246 int position = bar.width - (MSG_PADDING - BTN_BORDER - BTN_PADDING);
248 /* render close button */
249 position -= button_draw(&btn_close, position);
250 position -= CLOSE_BTN_GAP;
252 /* render custom buttons */
253 for (int i = 0; i < buttoncnt; i++) {
255 position -= button_draw(&buttons[i], position);
258 /* border line at the bottom */
259 draw_util_rectangle(&bar, color_border_bottom, 0, bar.height - BAR_BORDER, bar.width, BAR_BORDER);
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.
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};
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);
276 xcb_randr_get_output_primary_reply_t *primary = NULL;
277 xcb_randr_get_screen_resources_current_reply_t *res = NULL;
279 if ((primary = xcb_randr_get_output_primary_reply(conn, pcookie, NULL)) == NULL) {
280 DLOG("Could not determine the primary output.\n");
284 if ((res = xcb_randr_get_screen_resources_current_reply(conn, rcookie, NULL)) == NULL) {
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),
292 if (output == NULL || output->crtc == XCB_NONE)
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),
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");
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
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.
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.
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
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) {
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);
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;
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'},
369 char *options_string = "b:f:m:t:vh";
371 prompt = i3string_from_utf8("Please do not run this program.");
373 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
376 printf("i3-nagbar " I3_VERSION "\n");
380 pattern = sstrdup(optarg);
383 i3string_free(prompt);
384 prompt = i3string_from_utf8(optarg);
387 bar_type = (strcasecmp(optarg, "warning") == 0 ? TYPE_WARNING : TYPE_ERROR);
390 printf("i3-nagbar " I3_VERSION "\n");
391 printf("i3-nagbar [-m <message>] [-b <button> <action>] [-t warning|error] [-f <font>] [-v]\n");
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);
401 printf("now %d buttons\n", buttoncnt);
408 btn_close.label = i3string_from_utf8("X");
411 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
412 xcb_connection_has_error(conn))
413 die("Cannot open display\n");
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"
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);
426 root_screen = xcb_aux_get_screen(conn, screens);
427 root = root_screen->root;
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");
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");
446 font = load_font(pattern, true);
449 #if defined(__OpenBSD__)
450 if (pledge("stdio rpath wpath cpath getpw proc exec", NULL) == -1)
451 err(EXIT_FAILURE, "pledge");
454 xcb_rectangle_t win_pos = get_window_position();
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);
462 cursor = xcb_generate_id(conn);
463 i3Font cursor_font = load_font("cursor", false);
464 xcb_create_glyph_cursor(
467 cursor_font.specific.xcb.id,
468 cursor_font.specific.xcb.id,
470 XCB_CURSOR_LEFT_PTR + 1,
472 65535, 65535, 65535);
475 /* Open an input window */
476 win = xcb_generate_id(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,
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,
496 sn_launchee_context_setup_window(sncontext, win);
499 /* Map the window (make it visible) */
500 xcb_map_window(conn, win);
502 /* Setup NetWM atoms */
503 #define xmacro(name) \
505 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
507 die("Could not get atom " #name "\n"); \
509 A_##name = reply->atom; \
512 #include "atoms.xmacro"
516 xcb_change_property(conn,
517 XCB_PROP_MODE_REPLACE,
519 A__NET_WM_WINDOW_TYPE,
523 (unsigned char *)&A__NET_WM_WINDOW_TYPE_DOCK);
525 /* Reserve some space at the top of the screen */
531 uint32_t left_start_y;
533 uint32_t right_start_y;
534 uint32_t right_end_y;
535 uint32_t top_start_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));
542 strut_partial.top = font.height + logical_px(6);
543 strut_partial.top_start_x = 0;
544 strut_partial.top_end_x = 800;
546 xcb_change_property(conn,
547 XCB_PROP_MODE_REPLACE,
549 A__NET_WM_STRUT_PARTIAL,
555 /* Initialize the drawable bar */
556 draw_util_surface_init(conn, &bar, win, get_visualtype(root_screen), win_pos.width, win_pos.height);
558 /* Startup complete. */
560 sn_launchee_context_complete(sncontext);
561 sn_launchee_context_unref(sncontext);
564 /* Grab the keyboard to get all input */
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);
574 /* Strip off the highest bit (set if the event is generated) */
575 int type = (event->response_type & 0x7F);
579 if (((xcb_expose_event_t *)event)->count == 0) {
580 handle_expose(conn, (xcb_expose_event_t *)event);
585 case XCB_BUTTON_PRESS:
586 handle_button_press(conn, (xcb_button_press_event_t *)event);
589 case XCB_BUTTON_RELEASE:
590 handle_button_release(conn, (xcb_button_release_event_t *)event);
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);
606 draw_util_surface_free(conn, &bar);