3 #include <string.h> /* strdup, strlen */
4 #include <ctype.h> /* isalnum */
5 #include <locale.h> /* setlocale */
14 #include <X11/Xutil.h>
15 #include <X11/Xresource.h>
17 #include <X11/keysym.h>
20 # include <X11/extensions/Xinerama.h>
24 # include <X11/Xft/Xft.h>
28 # define VERSION "unknown"
31 #define resname "MyMenu"
32 #define resclass "mymenu"
34 #define SYM_BUF_SIZE 4
37 # define default_fontname "monospace"
39 # define default_fontname "fixed"
42 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:G:g:I:i:J:j:"
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
50 * If we don't have or we don't want an "ignore case" completion
51 * style, fall back to `strstr(3)`
53 #ifndef USE_STRCASESTR
54 # define strcasestr strstr
57 /* The number of char to read */
58 #define STDIN_CHUNKS 128
60 /* The number of lines to allocate in advance */
61 #define LINES_CHUNK 64
64 #define check_allocation(a) { \
66 fprintf(stderr, "Could not allocate memory\n"); \
71 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
72 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
74 /* The states of the event loop */
75 enum state {LOOPING, OK_LOOP, OK, ERR};
78 * For the drawing-related function. The text to be rendere could be
79 * the prompt, a completion or a highlighted completion
81 enum obj_type {PROMPT, COMPL, COMPL_HIGH};
83 /* These are the possible action to be performed after user input. */
97 /* A big set of values that needs to be carried around for drawing. A
98 big struct to rule them all */
100 Display *d; /* Connection to xorg */
108 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause the borders) */
109 int y_zero; /* like x_zero but for the y axis */
111 size_t offset; /* scroll offset */
114 short first_selected;
115 short multiple_select;
117 /* four border width */
123 short horizontal_layout;
128 int ps1w; /* ps1 width */
129 int ps1h; /* ps1 height */
131 int text_height; /* cache for the vertical layout */
145 XftColor xft_colors[3];
156 /* Wrap the linked list of completions */
158 struct completion *completions;
163 /* idea stolen from lemonbar. ty lemonboy */
177 /* Return a newly allocated (and empty) completion list */
179 compls_new(size_t length)
181 struct completions *cs = malloc(sizeof(struct completions));
186 cs->completions = calloc(length, sizeof(struct completion));
187 if (cs->completions == NULL) {
197 /* Delete the wrapper and the whole list */
199 compls_delete(struct completions *cs)
204 free(cs->completions);
209 * Create a completion list from a text and the list of possible
210 * completions (null terminated). Expects a non-null `cs'. `lines' and
211 * `vlines' should have the same length OR `vlines' is NULL.
214 filter(struct completions *cs, char *text, char **lines, char **vlines)
224 if (lines[index] == NULL)
227 l = vlines[index] != NULL ? vlines[index] : lines[index];
229 if (strcasestr(l, text) != NULL) {
230 struct completion *c = &cs->completions[matching];
232 c->rcompletion = lines[index];
238 cs->length = matching;
242 /* Update the given completion */
244 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
246 filter(cs, text, lines, vlines);
247 if (first_selected && cs->length > 0)
252 * Select the next or previous selection and update some state. `text'
253 * will be updated with the text of the completion and `textlen' with
254 * the new length. If the memory cannot be allocated `status' will be
258 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
260 struct completion *n;
263 if (cs == NULL || cs->length == 0)
267 * If the first is always selected and the first entry is
268 * different from the text, expand the text and return
272 && strcmp(cs->completions->completion, *text) != 0
275 *text = strdup(cs->completions->completion);
280 *textlen = strlen(*text);
284 index = cs->selected;
286 if (index == -1 && p)
288 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
290 n = &cs->completions[cs->selected];
293 *text = strdup(n->completion);
295 fprintf(stderr, "Memory allocation error!\n");
299 *textlen = strlen(*text);
302 /* Push the character c at the end of the string pointed by p */
304 pushc(char **p, int maxlen, char c)
308 len = strnlen(*p, maxlen);
309 if (!(len < maxlen -2)) {
312 maxlen += maxlen >> 1;
313 newptr = realloc(*p, maxlen);
314 if (newptr == NULL) /* bad */
325 * Remove the last rune from the *UTF-8* string! This is different
326 * from just setting the last byte to 0 (in some cases ofc). Return a
327 * pointer (e) to the last nonzero char. If e < p then p is empty!
347 * If c is a starting byte (11......) or is under
350 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
357 /* Remove the last word plus trailing white spaces from the given string */
364 if ((len = strlen(w)) == 0)
373 if (in_word && isspace(*e))
376 if (!in_word && !isspace(*e))
382 * If the string is surrounded by quates (`"') remove them and replace
383 * every `\"' in the string with a single double-quote.
386 normalize_str(const char *str)
391 if ((len = strlen(str)) == 0)
394 s = calloc(len, sizeof(char));
405 str += 2; /* skip this and the next char */
411 str++; /* skip only this char */
423 read_stdin(char **buf)
426 size_t len = STDIN_CHUNKS;
428 *buf = malloc(len * sizeof(char));
436 r = read(0, *buf + offset, STDIN_CHUNKS);
444 *buf = realloc(*buf, len);
448 for (i = offset; i < len; ++i)
453 fprintf(stderr, "Error in allocating memory for stdin.\n");
454 exit(EX_UNAVAILABLE);
458 readlines(char ***lns, char **buf)
460 size_t i, len, ll, lines;
466 len = read_stdin(buf);
469 *lns = malloc(ll * sizeof(char*));
474 for (i = 0; i < len; i++) {
483 if (in_line && c == '\n')
486 if (!in_line && c != '\n') {
488 (*lns)[lines] = (*buf) + i;
491 if (lines == ll) { /* resize */
493 *lns = realloc(*lns, ll * sizeof(char*));
500 (*lns)[lines] = NULL;
505 fprintf(stderr, "Error in memory allocation.\n");
506 exit(EX_UNAVAILABLE);
510 * Compute the dimensions of the string str once rendered.
511 * It'll return the width and set ret_width and ret_height if not NULL
514 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
519 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
520 height = r->font->ascent - r->font->descent;
521 width = gi.width - gi.x;
524 XmbTextExtents(r->font, str, len, NULL, &rect);
525 height = rect.height;
528 if (ret_width != NULL) *ret_width = width;
529 if (ret_height != NULL) *ret_height = height;
534 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
538 if (tt == PROMPT) xftcolor = r->xft_colors[0];
539 if (tt == COMPL) xftcolor = r->xft_colors[1];
540 if (tt == COMPL_HIGH) xftcolor = r->xft_colors[2];
542 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
545 if (tt == PROMPT) gc = r->fgs[0];
546 if (tt == COMPL) gc = r->fgs[1];
547 if (tt == COMPL_HIGH) gc = r->fgs[2];
548 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
552 /* Duplicate the string and substitute every space with a 'n` */
561 if (str == NULL || len == 0)
564 if ((dup = strdup(str)) == NULL)
567 for (i = 0; i < len; ++i)
575 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
577 GC *border_color, bg;
578 int *padding, *borders;
579 int ret = 0, inner_width, inner_height, x;
583 border_color = r->p_borders_bg;
584 padding = r->p_padding;
585 borders = r->p_borders;
589 border_color = r->c_borders_bg;
590 padding = r->c_padding;
591 borders = r->c_borders;
595 border_color = r->ch_borders_bg;
596 padding = r->ch_padding;
597 borders = r->ch_borders;
602 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
604 inner_width = inner_width(r) - borders[1] - borders[3];
605 inner_height = padding[0] + r->text_height + padding[2];
608 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
611 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1] , y, borders[1], ret);
614 XFillRectangle(r->d, r->w, border_color[2], r->x_zero, y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
617 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
620 x = r->x_zero + borders[3];
622 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
625 y += padding[0] + r->text_height;
627 if (prefix != NULL) {
628 draw_string(prefix, strlen(prefix), x, y, r, t);
631 draw_string(text, strlen(text), x, y, r, t);
637 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
639 GC *border_color, bg;
640 int *padding, *borders;
641 int ret = 0, inner_width, inner_height, y, text_width;
645 border_color = r->p_borders_bg;
646 padding = r->p_padding;
647 borders = r->p_borders;
651 border_color = r->c_borders_bg;
652 padding = r->c_padding;
653 borders = r->c_borders;
657 border_color = r->ch_borders_bg;
658 padding = r->ch_padding;
659 borders = r->ch_borders;
664 if (padding[0] < 0 || padding[2] < 0)
665 padding[0] = padding[2] = (inner_height(r) - borders[0] - borders[2] - r->text_height)/2;
667 /* If they are still lesser than 0, set 'em to 0 */
668 if (padding[0] < 0 || padding[2] < 0)
669 padding[0] = padding[2] = 0;
671 /* Get the text width */
672 text_extents(text, strlen(text), r, &text_width, NULL);
674 text_width += prefix_width;
676 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
678 inner_width = padding[3] + text_width + padding[1];
679 inner_height = inner_height(r) - borders[0] - borders[2];
682 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
685 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero, borders[1], inner_height(r));
688 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
691 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
695 y = r->y_zero + borders[0];
696 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
699 y += padding[0] + r->text_height;
701 if (prefix != NULL) {
702 draw_string(prefix, strlen(prefix), x, y, r, t);
705 draw_string(text, strlen(text), x, y, r, t);
710 /* ,-----------------------------------------------------------------, */
711 /* | 20 char text | completion | completion | completion | compl | */
712 /* `-----------------------------------------------------------------' */
714 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
719 /* Draw the prompt */
720 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
722 for (i = r->offset; i < cs->length; ++i) {
723 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
725 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
727 if (x > inner_width(r))
732 /* ,-----------------------------------------------------------------, */
734 /* |-----------------------------------------------------------------| */
736 /* |-----------------------------------------------------------------| */
738 /* `-----------------------------------------------------------------' */
740 draw_vertically(struct rendering *r, char *text, struct completions *cs)
745 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
747 for (i = r->offset; i < cs->length; ++i) {
748 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
750 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
752 if (y > inner_height(r))
758 draw(struct rendering *r, char *text, struct completions *cs)
760 /* Draw the background */
761 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
763 /* Draw the contents */
764 if (r->horizontal_layout)
765 draw_horizontally(r, text, cs);
767 draw_vertically(r, text, cs);
769 /* Draw the borders */
770 if (r->borders[0] != 0)
771 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
773 if (r->borders[1] != 0)
774 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0, r->borders[1], r->height);
776 if (r->borders[2] != 0)
777 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width, r->borders[2]);
779 if (r->borders[3] != 0)
780 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
786 /* Set some WM stuff */
788 set_win_atoms_hints(Display *d, Window w, int width, int height)
791 XClassHint *class_hint;
792 XSizeHints *size_hint;
794 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
797 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
798 XInternAtom(d, "ATOM", 0),
801 (unsigned char *)&type,
805 /* some window managers honor this properties */
806 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
809 XInternAtom(d, "_NET_WM_STATE", 0),
810 XInternAtom(d, "ATOM", 0),
813 (unsigned char *)&type,
817 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
820 XInternAtom(d, "_NET_WM_STATE", 0),
821 XInternAtom(d, "ATOM", 0),
824 (unsigned char *)&type,
828 /* Setting window hints */
829 class_hint = XAllocClassHint();
830 if (class_hint == NULL) {
831 fprintf(stderr, "Could not allocate memory for class hint\n");
832 exit(EX_UNAVAILABLE);
835 class_hint->res_name = resname;
836 class_hint->res_class = resclass;
837 XSetClassHint(d, w, class_hint);
840 size_hint = XAllocSizeHints();
841 if (size_hint == NULL) {
842 fprintf(stderr, "Could not allocate memory for size hint\n");
843 exit(EX_UNAVAILABLE);
846 size_hint->flags = PMinSize | PBaseSize;
847 size_hint->min_width = width;
848 size_hint->base_width = width;
849 size_hint->min_height = height;
850 size_hint->base_height = height;
855 /* Get the width and height of the window `w' */
857 get_wh(Display *d, Window *w, int *width, int *height)
859 XWindowAttributes win_attr;
861 XGetWindowAttributes(d, *w, &win_attr);
862 *height = win_attr.height;
863 *width = win_attr.width;
867 grabfocus(Display *d, Window w)
870 for (i = 0; i < 100; ++i) {
874 XGetInputFocus(d, &focuswin, &revert_to_win);
879 XSetInputFocus(d, w, RevertToParent, CurrentTime);
886 * I know this may seem a little hackish BUT is the only way I managed
887 * to actually grab that goddam keyboard. Only one call to
888 * XGrabKeyboard does not always end up with the keyboard grabbed!
891 take_keyboard(Display *d, Window w)
894 for (i = 0; i < 100; i++) {
895 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
899 fprintf(stderr, "Cannot grab keyboard\n");
904 parse_color(const char *str, const char *def)
915 /* +1 for the # ath the start */
916 if (*str != '#' || len > 9 || len < 4)
918 ++str; /* skip the # */
921 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
928 /* expand #rgb -> #rrggbb */
929 tmp.v = (tmp.v & 0xf00) * 0x1100
930 | (tmp.v & 0x0f0) * 0x0110
931 | (tmp.v & 0x00f) * 0x0011;
933 /* assume 0xff opacity */
936 } /* colors in #aarrggbb need no adjustments */
938 /* premultiply the alpha */
940 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
941 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
942 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
949 fprintf(stderr, "Invalid color: \"%s\".\n", str);
951 return parse_color(def, NULL);
957 * Given a string try to parse it as a number or return `default_value'.
960 parse_integer(const char *str, int default_value)
966 lval = strtol(str, &ep, 10);
968 if (str[0] == '\0' || *ep != '\0') { /* NaN */
969 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
970 return default_value;
973 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
974 (lval > INT_MAX || lval < INT_MIN)) {
975 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
976 return default_value;
982 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
984 parse_int_with_percentage(const char *str, int default_value, int max)
986 int len = strlen(str);
988 if (len > 0 && str[len-1] == '%') {
993 check_allocation(cpy);
995 val = parse_integer(cpy, default_value);
997 return val * max / 100;
1000 return parse_integer(str, default_value);
1004 * Like parse_int_with_percentage but understands some special values:
1005 * - middle that is (max-self)/2
1007 * - end that is (max-self)
1010 parse_int_with_pos(const char *str, int default_value, int max, int self)
1012 if (!strcmp(str, "start"))
1014 if (!strcmp(str, "middle"))
1015 return (max - self)/2;
1016 if (!strcmp(str, "end"))
1018 return parse_int_with_percentage(str, default_value, max);
1021 /* Parse a string like a CSS value. */
1022 /* TODO: harden a bit this function */
1024 parse_csslike(const char *str)
1027 char *s, *token, **ret;
1034 ret = malloc(4 * sizeof(char*));
1040 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1041 ret[i] = strdup(token);
1044 for (j = 1; j < 4; j++)
1045 ret[j] = strdup(ret[0]);
1048 ret[2] = strdup(ret[0]);
1049 ret[3] = strdup(ret[1]);
1053 ret[3] = strdup(ret[1]);
1055 /* before we didn't check for the return type of strdup, here we will */
1058 for (i = 0; i < 4; ++i)
1059 any_null = ret[i] == NULL || any_null;
1062 for (i = 0; i < 4; ++i)
1066 if (i == 0 || any_null) {
1076 * Given an event, try to understand what the users wants. If the
1077 * return value is ADD_CHAR then `input' is a pointer to a string that
1078 * will need to be free'ed later.
1081 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1083 char str[SYM_BUF_SIZE] = {0};
1086 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1089 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1090 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1092 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1095 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1098 /* Try to read what key was pressed */
1100 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1101 if (s == XBufferOverflow) {
1102 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1106 if (ev->state & ControlMask) {
1107 if (!strcmp(str, "")) /* C-u */
1109 if (!strcmp(str, "")) /* C-w */
1111 if (!strcmp(str, "")) /* C-h */
1113 if (!strcmp(str, "\r")) /* C-m */
1114 return CONFIRM_CONTINUE;
1115 if (!strcmp(str, "")) /* C-p */
1117 if (!strcmp(str, "")) /* C-n */
1119 if (!strcmp(str, "")) /* C-c */
1121 if (!strcmp(str, "\t")) /* C-i */
1122 return TOGGLE_FIRST_SELECTED;
1125 *input = strdup(str);
1126 if (*input == NULL) {
1127 fprintf(stderr, "Error while allocating memory for key.\n");
1135 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1137 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1138 /* if there is something selected expand it and return */
1139 int index = cs->selected == -1 ? 0 : cs->selected;
1140 struct completion *c = cs->completions;
1154 if (*text == NULL) {
1155 fprintf(stderr, "Memory allocation error\n");
1159 *textlen = strlen(*text);
1163 if (!r->free_text) /* cannot accept arbitrary text */
1169 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1171 enum state status = LOOPING;
1173 while (status == LOOPING) {
1175 XNextEvent(r->d, &e);
1177 if (XFilterEvent(&e, r->w))
1182 XRefreshKeyboardMapping(&e.xmapping);
1187 if (e.xfocus.window != r->w)
1188 grabfocus(r->d, r->w);
1191 case VisibilityNotify:
1192 if (e.xvisibility.state != VisibilityUnobscured)
1193 XRaiseWindow(r->d, r->w);
1197 get_wh(r->d, &r->w, &r->width, &r->height);
1202 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1205 switch (parse_event(r->d, ev, r->xic, &input)) {
1212 confirm(&status, r, cs, text, textlen);
1216 case CONFIRM_CONTINUE: {
1218 confirm(&status, r, cs, text, textlen);
1223 complete(cs, r->first_selected, 1, text, textlen, &status);
1224 r->offset = cs->selected;
1229 complete(cs, r->first_selected, 0, text, textlen, &status);
1230 r->offset = cs->selected;
1236 update_completions(cs, *text, lines, vlines, r->first_selected);
1242 update_completions(cs, *text, lines, vlines, r->first_selected);
1248 for (i = 0; i < *textlen; ++i)
1250 update_completions(cs, *text, lines, vlines, r->first_selected);
1258 str_len = strlen(input);
1261 * sometimes a strange key is pressed
1262 * i.e. ctrl alone), so input will be
1263 * empty. Don't need to update
1264 * completion in that case
1269 for (i = 0; i < str_len; ++i) {
1270 *textlen = pushc(text, *textlen, input[i]);
1271 if (*textlen == -1) {
1272 fprintf(stderr, "Memory allocation error\n");
1278 if (status != ERR) {
1279 update_completions(cs, *text, lines, vlines, r->first_selected);
1287 case TOGGLE_FIRST_SELECTED:
1288 r->first_selected = !r->first_selected;
1289 if (r->first_selected && cs->selected < 0)
1291 if (!r->first_selected && cs->selected == 0)
1298 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1299 /* if (ev->button == Button1) { /\* click *\/ */
1300 /* int x = ev->x - r.border_w; */
1301 /* int y = ev->y - r.border_n; */
1302 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1305 if (ev->button == Button4) /* scroll up */
1306 r->offset = MAX((ssize_t)r->offset - 1, 0);
1308 if (ev->button == Button5) /* scroll down */
1309 r->offset = MIN(r->offset + 1, cs->length - 1);
1322 load_font(struct rendering *r, const char *fontname)
1325 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1328 char **missing_charset_list;
1329 int missing_charset_count;
1331 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1332 if (r->font != NULL)
1335 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1337 if (!strcmp(fontname, default_fontname))
1340 return load_font(r, default_fontname);
1345 xim_init(struct rendering *r, XrmDatabase *xdb)
1347 XIMStyle best_match_style;
1351 /* Open the X input method */
1352 r->xim = XOpenIM(r->d, *xdb, resname, resclass);
1353 check_allocation(r->xim);
1355 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1356 fprintf(stderr, "Input Styles could not be retrieved\n");
1357 exit(EX_UNAVAILABLE);
1360 best_match_style = 0;
1361 for (i = 0; i < xis->count_styles; ++i) {
1362 XIMStyle ts = xis->supported_styles[i];
1363 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1364 best_match_style = ts;
1370 if (!best_match_style)
1371 fprintf(stderr, "No matching input style could be determined\n");
1373 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1374 check_allocation(r->xic);
1378 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy, unsigned long background_pixel)
1380 XSetWindowAttributes attr;
1382 /* Create the window */
1383 attr.colormap = cmap;
1384 attr.override_redirect = 1;
1385 attr.border_pixel = 0;
1386 attr.background_pixel = background_pixel;
1387 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1389 r->w = XCreateWindow(r->d,
1392 r->width, r->height,
1397 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1402 ps1extents(struct rendering *r)
1405 dup = strdupn(r->ps1);
1406 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1411 usage(char *prgname)
1414 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1415 " [-d separator] [-e window] [-f font] [-G color] [-g size]\n"
1416 " [-H height] [-I color] [-i size] [-J color] [-j size] [-l layout]\n"
1417 " [-P padding] [-p prompt] [-S color] [-s color] [-T color]\n"
1418 " [-t color] [-W width] [-x coord] [-y coord]\n", prgname);
1422 main(int argc, char **argv)
1424 struct completions *cs;
1429 Window parent_window;
1431 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1432 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4], ch_borders_bg[4]; /* N E S W */
1435 int offset_x, offset_y, x, y;
1436 int textlen, d_width, d_height;
1438 char *sep, *parent_window_id;
1439 char **lines, *buf, **vlines;
1440 char *fontname, *text, *xrm;
1443 /* stdio & rpath: to read/write stdio/stdout/stderr */
1444 /* unix: to connect to XOrg */
1445 pledge("stdio rpath unix", "");
1449 parent_window_id = NULL;
1451 r.first_selected = 0;
1453 r.multiple_select = 0;
1456 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1458 case 'h': /* help */
1461 case 'v': /* version */
1462 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1464 case 'e': /* embed */
1465 parent_window_id = strdup(optarg);
1466 check_allocation(parent_window_id);
1469 sep = strdup(optarg);
1470 check_allocation(sep);
1475 r.multiple_select = 1;
1482 /* Read the completions */
1485 nlines = readlines(&lines, &buf);
1491 vlines = calloc(nlines, sizeof(char*));
1492 check_allocation(vlines);
1494 for (i = 0; i < nlines; i++) {
1496 t = strstr(lines[i], sep);
1498 vlines[i] = lines[i];
1504 setlocale(LC_ALL, getenv("LANG"));
1508 /* where the monitor start (used only with xinerama) */
1509 offset_x = offset_y = 0;
1511 /* default width and height */
1515 /* default position on the screen */
1518 for (i = 0; i < 4; ++i) {
1519 /* default paddings */
1520 r.p_padding[i] = 10;
1521 r.c_padding[i] = 10;
1522 r.ch_padding[i] = 10;
1524 /* default borders */
1528 r.ch_borders[i] = 0;
1531 /* the prompt. We duplicate the string so later is easy to
1532 * free (in the case it's been overwritten by the user) */
1533 r.ps1 = strdup("$ ");
1534 check_allocation(r.ps1);
1536 /* same for the font name */
1537 fontname = strdup(default_fontname);
1538 check_allocation(fontname);
1541 text = malloc(textlen * sizeof(char));
1542 check_allocation(text);
1544 /* struct completions *cs = filter(text, lines); */
1545 cs = compls_new(nlines);
1546 check_allocation(cs);
1548 /* start talking to xorg */
1549 r.d = XOpenDisplay(NULL);
1551 fprintf(stderr, "Could not open display!\n");
1552 return EX_UNAVAILABLE;
1556 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1557 parent_window = DefaultRootWindow(r.d);
1561 /* get display size */
1562 get_wh(r.d, &parent_window, &d_width, &d_height);
1565 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1566 XineramaScreenInfo *info;
1569 int number_of_screens, monitors, i;
1570 int root_x, root_y, win_x, win_y;
1574 number_of_screens = XScreenCount(r.d);
1575 for (i = 0; i < number_of_screens; ++i) {
1576 root = XRootWindow(r.d, i);
1577 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1583 fprintf(stderr, "No mouse found.\n");
1588 /* Now find in which monitor the mice is */
1589 info = XineramaQueryScreens(r.d, &monitors);
1591 for (i = 0; i < monitors; ++i) {
1592 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1593 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1594 offset_x = info[i].x_org;
1595 offset_y = info[i].y_org;
1596 d_width = info[i].width;
1597 d_height = info[i].height;
1606 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1607 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1609 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1610 fgs[2] = parse_color("#000", NULL);
1612 bgs[0] = bgs[1] = parse_color("#000", NULL);
1613 bgs[2] = parse_color("#fff", NULL);
1615 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1617 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3] = parse_color("#000", NULL);
1618 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3] = parse_color("#000", NULL);
1619 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3] = parse_color("#000", NULL);
1621 r.horizontal_layout = 1;
1623 /* Read the resources */
1625 xrm = XResourceManagerString(r.d);
1631 xdb = XrmGetStringDatabase(xrm);
1633 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1635 fontname = strdup(value.addr);
1636 check_allocation(fontname);
1638 fprintf(stderr, "no font defined, using %s\n", fontname);
1641 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1642 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1644 fprintf(stderr, "no layout defined, using horizontal\n");
1646 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1648 r.ps1 = normalize_str(value.addr);
1650 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1653 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value) == 1) {
1655 sizes = parse_csslike(value.addr);
1657 for (i = 0; i < 4; ++i)
1658 r.p_borders[i] = parse_integer(sizes[i], 0);
1660 fprintf(stderr, "error while parsing MyMenu.prompt.border.size");
1663 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value) == 1) {
1665 colors = parse_csslike(value.addr);
1667 for (i = 0; i < 4; ++i)
1668 p_borders_bg[i] = parse_color(colors[i], "#000");
1670 fprintf(stderr, "error while parsing MyMenu.prompt.border.color");
1673 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value) == 1) {
1675 colors = parse_csslike(value.addr);
1677 for (i = 0; i < 4; ++i)
1678 r.p_padding[i] = parse_integer(colors[i], 0);
1680 fprintf(stderr, "error while parsing MyMenu.prompt.padding");
1683 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1684 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1686 fprintf(stderr, "no width defined, using %d\n", r.width);
1688 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1689 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1691 fprintf(stderr, "no height defined, using %d\n", r.height);
1693 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1694 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1696 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1697 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1699 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1701 borders = parse_csslike(value.addr);
1702 if (borders != NULL)
1703 for (i = 0; i < 4; ++i)
1704 r.borders[i] = parse_int_with_percentage(borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1706 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1710 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1711 fgs[0] = parse_color(value.addr, "#fff");
1713 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1714 bgs[0] = parse_color(value.addr, "#000");
1717 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1718 fgs[1] = parse_color(value.addr, "#fff");
1720 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1721 bgs[1] = parse_color(value.addr, "#000");
1723 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value) == 1) {
1725 paddings = parse_csslike(value.addr);
1726 if (paddings != NULL)
1727 for (i = 0; i < 4; ++i)
1728 r.c_padding[i] = parse_integer(paddings[i], 0);
1730 fprintf(stderr, "Error while parsing MyMenu.completion.padding");
1733 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value) == 1) {
1735 sizes = parse_csslike(value.addr);
1737 for (i = 0; i < 4; ++i)
1738 r.c_borders[i] = parse_integer(sizes[i], 0);
1740 fprintf(stderr, "Error while parsing MyMenu.completion.border.size");
1743 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value) == 1) {
1745 sizes = parse_csslike(value.addr);
1747 for (i = 0; i < 4; ++i)
1748 c_borders_bg[i] = parse_color(sizes[i], "#000");
1750 fprintf(stderr, "Error while parsing MyMenu.completion.border.color");
1753 /* Completion Highlighted */
1754 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1755 fgs[2] = parse_color(value.addr, "#000");
1757 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1758 bgs[2] = parse_color(value.addr, "#fff");
1760 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value) == 1) {
1762 paddings = parse_csslike(value.addr);
1763 if (paddings != NULL)
1764 for (i = 0; i < 4; ++i)
1765 r.ch_padding[i] = parse_integer(paddings[i], 0);
1767 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.padding");
1770 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype, &value) == 1) {
1772 sizes = parse_csslike(value.addr);
1774 for (i = 0; i < 4; ++i)
1775 r.ch_borders[i] = parse_integer(sizes[i], 0);
1777 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.size");
1780 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype, &value) == 1) {
1782 colors = parse_csslike(value.addr);
1784 for (i = 0; i < 4; ++i)
1785 ch_borders_bg[i] = parse_color(colors[i], "#000");
1787 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.color");
1791 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1793 colors = parse_csslike(value.addr);
1795 for (i = 0; i < 4; ++i)
1796 borders_bg[i] = parse_color(colors[i], "#000");
1798 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1802 /* Second round of args parsing */
1803 optind = 0; /* reset the option index */
1804 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1807 r.first_selected = 1;
1810 /* free_text -- already catched */
1812 /* separator -- this case was already catched */
1814 /* embedding mymenu this case was already catched. */
1816 /* multiple selection this case was already catched. */
1820 newprompt = strdup(optarg);
1821 if (newprompt != NULL) {
1828 x = parse_int_with_pos(optarg, x, d_width, r.width);
1831 y = parse_int_with_pos(optarg, y, d_height, r.height);
1835 if ((paddings = parse_csslike(optarg)) != NULL)
1836 for (i = 0; i < 4; ++i)
1837 r.p_padding[i] = parse_integer(paddings[i], 0);
1842 if ((colors = parse_csslike(optarg)) != NULL)
1843 for (i = 0; i < 4; ++i)
1844 p_borders_bg[i] = parse_color(colors[i], "#000");
1849 if ((sizes = parse_csslike(optarg)) != NULL)
1850 for (i = 0; i < 4; ++i)
1851 r.p_borders[i] = parse_integer(sizes[i], 0);
1856 if ((colors = parse_csslike(optarg)) != NULL)
1857 for (i = 0; i < 4; ++i)
1858 c_borders_bg[i] = parse_color(colors[i], "#000");
1863 if ((sizes = parse_csslike(optarg)) != NULL)
1864 for (i = 0; i < 4; ++i)
1865 r.c_borders[i] = parse_integer(sizes[i], 0);
1870 if ((colors = parse_csslike(optarg)) != NULL)
1871 for (i = 0; i < 4; ++i)
1872 ch_borders_bg[i] = parse_color(colors[i], "#000");
1877 if ((sizes = parse_csslike(optarg)) != NULL)
1878 for (i = 0; i < 4; ++i)
1879 r.ch_borders[i] = parse_integer(sizes[i], 0);
1883 r.horizontal_layout = !strcmp(optarg, "horizontal");
1887 if ((newfont = strdup(optarg)) != NULL) {
1894 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1897 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1901 if ((borders = parse_csslike(optarg)) != NULL) {
1902 for (i = 0; i < 4; ++i)
1903 r.borders[i] = parse_integer(borders[i], 0);
1905 fprintf(stderr, "Error parsing b option\n");
1910 if ((colors = parse_csslike(optarg)) != NULL) {
1911 for (i = 0; i < 4; ++i)
1912 borders_bg[i] = parse_color(colors[i], "#000");
1914 fprintf(stderr, "error while parsing B option\n");
1918 fgs[0] = parse_color(optarg, NULL);
1921 bgs[0] = parse_color(optarg, NULL);
1924 fgs[1] = parse_color(optarg, NULL);
1927 bgs[1] = parse_color(optarg, NULL);
1930 fgs[2] = parse_color(optarg, NULL);
1933 fgs[2] = parse_color(optarg, NULL);
1936 fprintf(stderr, "Unrecognized option %c\n", ch);
1942 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1943 fprintf(stderr, "height, width, x or y are lesser than 0.");
1947 /* since only now we know if the first should be selected,
1948 * update the completion here */
1949 update_completions(cs, text, lines, vlines, r.first_selected);
1951 /* update the prompt lenght, only now we surely know the length of it */
1952 r.ps1len = strlen(r.ps1);
1954 /* Create the window */
1955 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1956 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1957 XMapRaised(r.d, r.w);
1959 /* If embed, listen for other events as well */
1961 Window *children, parent, root;
1962 unsigned int children_no;
1964 XSelectInput(r.d, parent_window, FocusChangeMask);
1965 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1966 for (i = 0; i < children_no && children[i] != r.w; ++i)
1967 XSelectInput(r.d, children[i], FocusChangeMask);
1970 grabfocus(r.d, r.w);
1973 take_keyboard(r.d, r.w);
1975 r.x_zero = r.borders[3];
1976 r.y_zero = r.borders[0];
1981 for (i = 0; i < 3; ++i) {
1982 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1983 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
1986 for (i = 0; i < 4; ++i) {
1987 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1988 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1989 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1990 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1994 /* Load the colors in our GCs */
1995 for (i = 0; i < 3; ++i) {
1996 XSetForeground(r.d, r.fgs[i], fgs[i]);
1997 XSetForeground(r.d, r.bgs[i], bgs[i]);
2000 for (i = 0; i < 4; ++i) {
2001 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2002 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2003 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2004 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2007 if (load_font(&r, fontname) == -1)
2011 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2013 for (i = 0; i < 3; ++i) {
2015 XRenderColor xrcolor;
2017 c = *(rgba_t*)&fgs[i];
2018 xrcolor.red = EXPANDBITS(c.rgba.r);
2019 xrcolor.green = EXPANDBITS(c.rgba.g);
2020 xrcolor.blue = EXPANDBITS(c.rgba.b);
2021 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2022 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2026 /* compute prompt dimensions */
2032 /* Now we need only the ability to write */
2033 pledge("stdio", "");
2036 /* Cache text height */
2037 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2039 /* Draw the window for the first time */
2043 while (status == LOOPING || status == OK_LOOP) {
2044 status = loop(&r, &text, &textlen, cs, lines, vlines);
2047 printf("%s\n", text);
2049 if (!r.multiple_select && status == OK_LOOP)
2053 XUngrabKeyboard(r.d, CurrentTime);
2056 for (i = 0; i < 3; ++i)
2057 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2060 for (i = 0; i < 3; ++i) {
2061 XFreeGC(r.d, r.fgs[i]);
2062 XFreeGC(r.d, r.bgs[i]);
2065 for (i = 0; i < 4; ++i) {
2066 XFreeGC(r.d, r.borders_bg[i]);
2067 XFreeGC(r.d, r.p_borders_bg[i]);
2068 XFreeGC(r.d, r.c_borders_bg[i]);
2069 XFreeGC(r.d, r.ch_borders_bg[i]);
2076 for (i = 0; i < 3; ++i)
2077 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2078 XftFontClose(r.d, r.font);
2079 XftDrawDestroy(r.xftdraw);
2081 XFreeFontSet(r.d, r.font);
2093 XFreeColormap(r.d, cmap);
2095 XDestroyWindow(r.d, r.w);
2098 return status != OK;