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 */
107 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause the borders) */
108 int y_zero; /* like x_zero but for the y axis */
110 size_t offset; /* scroll offset */
113 short first_selected;
114 short multiple_select;
116 /* four border width */
122 short horizontal_layout;
127 int ps1w; /* ps1 width */
128 int ps1h; /* ps1 height */
130 int text_height; /* cache for the vertical layout */
144 XftColor xft_colors[3];
155 /* Wrap the linked list of completions */
157 struct completion *completions;
162 /* idea stolen from lemonbar. ty lemonboy */
176 /* Return a newly allocated (and empty) completion list */
178 compls_new(size_t length)
180 struct completions *cs = malloc(sizeof(struct completions));
185 cs->completions = calloc(length, sizeof(struct completion));
186 if (cs->completions == NULL) {
196 /* Delete the wrapper and the whole list */
198 compls_delete(struct completions *cs)
203 free(cs->completions);
208 * Create a completion list from a text and the list of possible
209 * completions (null terminated). Expects a non-null `cs'. `lines' and
210 * `vlines' should have the same length OR `vlines' is NULL.
213 filter(struct completions *cs, char *text, char **lines, char **vlines)
223 if (lines[index] == NULL)
226 l = vlines[index] != NULL ? vlines[index] : lines[index];
228 if (strcasestr(l, text) != NULL) {
229 struct completion *c = &cs->completions[matching];
231 c->rcompletion = lines[index];
237 cs->length = matching;
241 /* Update the given completion */
243 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
245 filter(cs, text, lines, vlines);
246 if (first_selected && cs->length > 0)
251 * Select the next or previous selection and update some state. `text'
252 * will be updated with the text of the completion and `textlen' with
253 * the new length. If the memory cannot be allocated `status' will be
257 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
259 struct completion *n;
262 if (cs == NULL || cs->length == 0)
266 * If the first is always selected and the first entry is
267 * different from the text, expand the text and return
271 && strcmp(cs->completions->completion, *text) != 0
274 *text = strdup(cs->completions->completion);
279 *textlen = strlen(*text);
283 index = cs->selected;
285 if (index == -1 && p)
287 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
289 n = &cs->completions[cs->selected];
292 *text = strdup(n->completion);
294 fprintf(stderr, "Memory allocation error!\n");
298 *textlen = strlen(*text);
301 /* Push the character c at the end of the string pointed by p */
303 pushc(char **p, int maxlen, char c)
307 len = strnlen(*p, maxlen);
308 if (!(len < maxlen -2)) {
311 maxlen += maxlen >> 1;
312 newptr = realloc(*p, maxlen);
313 if (newptr == NULL) /* bad */
324 * Remove the last rune from the *UTF-8* string! This is different
325 * from just setting the last byte to 0 (in some cases ofc). Return a
326 * pointer (e) to the last nonzero char. If e < p then p is empty!
346 * If c is a starting byte (11......) or is under
349 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
356 /* Remove the last word plus trailing white spaces from the given string */
363 if ((len = strlen(w)) == 0)
372 if (in_word && isspace(*e))
375 if (!in_word && !isspace(*e))
381 * If the string is surrounded by quates (`"') remove them and replace
382 * every `\"' in the string with a single double-quote.
385 normalize_str(const char *str)
390 if ((len = strlen(str)) == 0)
393 s = calloc(len, sizeof(char));
404 str += 2; /* skip this and the next char */
410 str++; /* skip only this char */
422 read_stdin(char **buf)
425 size_t len = STDIN_CHUNKS;
427 *buf = malloc(len * sizeof(char));
435 r = read(0, *buf + offset, STDIN_CHUNKS);
443 *buf = realloc(*buf, len);
447 for (i = offset; i < len; ++i)
452 fprintf(stderr, "Error in allocating memory for stdin.\n");
453 exit(EX_UNAVAILABLE);
457 readlines(char ***lns, char **buf)
459 size_t i, len, ll, lines;
465 len = read_stdin(buf);
468 *lns = malloc(ll * sizeof(char*));
473 for (i = 0; i < len; i++) {
482 if (in_line && c == '\n')
485 if (!in_line && c != '\n') {
487 (*lns)[lines] = (*buf) + i;
490 if (lines == ll) { /* resize */
492 *lns = realloc(*lns, ll * sizeof(char*));
499 (*lns)[lines] = NULL;
504 fprintf(stderr, "Error in memory allocation.\n");
505 exit(EX_UNAVAILABLE);
509 * Compute the dimensions of the string str once rendered.
510 * It'll return the width and set ret_width and ret_height if not NULL
513 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)
1348 XIMStyle best_match_style;
1352 /* Open the X input method */
1353 xim = XOpenIM(r->d, *xdb, resname, resclass);
1354 check_allocation(xim);
1356 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1357 fprintf(stderr, "Input Styles could not be retrieved\n");
1358 exit(EX_UNAVAILABLE);
1361 best_match_style = 0;
1362 for (i = 0; i < xis->count_styles; ++i) {
1363 XIMStyle ts = xis->supported_styles[i];
1364 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1365 best_match_style = ts;
1371 if (!best_match_style)
1372 fprintf(stderr, "No matching input style could be determined\n");
1374 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1375 check_allocation(r->xic);
1379 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1381 XSetWindowAttributes attr;
1383 /* Create the window */
1384 attr.colormap = cmap;
1385 attr.override_redirect = 1;
1386 attr.border_pixel = 0;
1387 attr.background_pixel = 0x80808080;
1388 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1390 r->w = XCreateWindow(r->d,
1393 r->width, r->height,
1398 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1403 ps1extents(struct rendering *r)
1406 dup = strdupn(r->ps1);
1407 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1412 usage(char *prgname)
1415 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1416 " [-d separator] [-e window] [-f font] [-G color] [-g size]\n"
1417 " [-H height] [-I color] [-i size] [-J color] [-j size] [-l layout]\n"
1418 " [-P padding] [-p prompt] [-S color] [-s color] [-T color]\n"
1419 " [-t color] [-W width] [-x coord] [-y coord]\n", prgname);
1423 main(int argc, char **argv)
1425 struct completions *cs;
1430 Window parent_window;
1432 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1433 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4], ch_borders_bg[4]; /* N E S W */
1436 int offset_x, offset_y, x, y;
1437 int textlen, d_width, d_height;
1439 char *sep, *parent_window_id;
1440 char **lines, *buf, **vlines;
1441 char *fontname, *text, *xrm;
1444 /* stdio & rpath: to read/write stdio/stdout/stderr */
1445 /* unix: to connect to XOrg */
1446 pledge("stdio rpath unix", "");
1450 parent_window_id = NULL;
1452 r.first_selected = 0;
1454 r.multiple_select = 0;
1457 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1459 case 'h': /* help */
1462 case 'v': /* version */
1463 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1465 case 'e': /* embed */
1466 parent_window_id = strdup(optarg);
1467 check_allocation(parent_window_id);
1470 sep = strdup(optarg);
1471 check_allocation(sep);
1476 r.multiple_select = 1;
1483 /* Read the completions */
1486 nlines = readlines(&lines, &buf);
1492 vlines = calloc(nlines, sizeof(char*));
1493 check_allocation(vlines);
1495 for (i = 0; i < nlines; i++) {
1497 t = strstr(lines[i], sep);
1499 vlines[i] = lines[i];
1505 setlocale(LC_ALL, getenv("LANG"));
1509 /* where the monitor start (used only with xinerama) */
1510 offset_x = offset_y = 0;
1512 /* default width and height */
1516 /* default position on the screen */
1519 for (i = 0; i < 4; ++i) {
1520 /* default paddings */
1521 r.p_padding[i] = 10;
1522 r.c_padding[i] = 10;
1523 r.ch_padding[i] = 10;
1525 /* default borders */
1529 r.ch_borders[i] = 0;
1532 /* the prompt. We duplicate the string so later is easy to
1533 * free (in the case it's been overwritten by the user) */
1534 r.ps1 = strdup("$ ");
1535 check_allocation(r.ps1);
1537 /* same for the font name */
1538 fontname = strdup(default_fontname);
1539 check_allocation(fontname);
1542 text = malloc(textlen * sizeof(char));
1543 check_allocation(text);
1545 /* struct completions *cs = filter(text, lines); */
1546 cs = compls_new(nlines);
1547 check_allocation(cs);
1549 /* start talking to xorg */
1550 r.d = XOpenDisplay(NULL);
1552 fprintf(stderr, "Could not open display!\n");
1553 return EX_UNAVAILABLE;
1557 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1558 parent_window = DefaultRootWindow(r.d);
1562 /* get display size */
1563 get_wh(r.d, &parent_window, &d_width, &d_height);
1566 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1567 XineramaScreenInfo *info;
1570 int number_of_screens, monitors, i;
1571 int root_x, root_y, win_x, win_y;
1575 number_of_screens = XScreenCount(r.d);
1576 for (i = 0; i < number_of_screens; ++i) {
1577 root = XRootWindow(r.d, i);
1578 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1584 fprintf(stderr, "No mouse found.\n");
1589 /* Now find in which monitor the mice is */
1590 info = XineramaQueryScreens(r.d, &monitors);
1592 for (i = 0; i < monitors; ++i) {
1593 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1594 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1595 offset_x = info[i].x_org;
1596 offset_y = info[i].y_org;
1597 d_width = info[i].width;
1598 d_height = info[i].height;
1607 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1608 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1610 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1611 fgs[2] = parse_color("#000", NULL);
1613 bgs[0] = bgs[1] = parse_color("#000", NULL);
1614 bgs[2] = parse_color("#fff", NULL);
1616 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1618 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3] = parse_color("#000", NULL);
1619 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3] = parse_color("#000", NULL);
1620 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3] = parse_color("#000", NULL);
1622 r.horizontal_layout = 1;
1624 /* Read the resources */
1626 xrm = XResourceManagerString(r.d);
1632 xdb = XrmGetStringDatabase(xrm);
1634 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1636 fontname = strdup(value.addr);
1637 check_allocation(fontname);
1639 fprintf(stderr, "no font defined, using %s\n", fontname);
1642 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1643 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1645 fprintf(stderr, "no layout defined, using horizontal\n");
1647 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1649 r.ps1 = normalize_str(value.addr);
1651 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1654 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value) == 1) {
1656 sizes = parse_csslike(value.addr);
1658 for (i = 0; i < 4; ++i)
1659 r.p_borders[i] = parse_integer(sizes[i], 0);
1661 fprintf(stderr, "error while parsing MyMenu.prompt.border.size");
1664 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value) == 1) {
1666 colors = parse_csslike(value.addr);
1668 for (i = 0; i < 4; ++i)
1669 p_borders_bg[i] = parse_color(colors[i], "#000");
1671 fprintf(stderr, "error while parsing MyMenu.prompt.border.color");
1674 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value) == 1) {
1676 colors = parse_csslike(value.addr);
1678 for (i = 0; i < 4; ++i)
1679 r.p_padding[i] = parse_integer(colors[i], 0);
1681 fprintf(stderr, "error while parsing MyMenu.prompt.padding");
1684 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1685 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1687 fprintf(stderr, "no width defined, using %d\n", r.width);
1689 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1690 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1692 fprintf(stderr, "no height defined, using %d\n", r.height);
1694 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1695 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1697 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1698 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1700 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1702 borders = parse_csslike(value.addr);
1703 if (borders != NULL)
1704 for (i = 0; i < 4; ++i)
1705 r.borders[i] = parse_int_with_percentage(borders[i], 0, (i % 2) == 0 ? r.height : r.width);
1707 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1711 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1712 fgs[0] = parse_color(value.addr, "#fff");
1714 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1715 bgs[0] = parse_color(value.addr, "#000");
1718 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1719 fgs[1] = parse_color(value.addr, "#fff");
1721 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1722 bgs[1] = parse_color(value.addr, "#000");
1724 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value) == 1) {
1726 paddings = parse_csslike(value.addr);
1727 if (paddings != NULL)
1728 for (i = 0; i < 4; ++i)
1729 r.c_padding[i] = parse_integer(paddings[i], 0);
1731 fprintf(stderr, "Error while parsing MyMenu.completion.padding");
1734 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value) == 1) {
1736 sizes = parse_csslike(value.addr);
1738 for (i = 0; i < 4; ++i)
1739 r.c_borders[i] = parse_integer(sizes[i], 0);
1741 fprintf(stderr, "Error while parsing MyMenu.completion.border.size");
1744 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value) == 1) {
1746 sizes = parse_csslike(value.addr);
1748 for (i = 0; i < 4; ++i)
1749 c_borders_bg[i] = parse_color(sizes[i], "#000");
1751 fprintf(stderr, "Error while parsing MyMenu.completion.border.color");
1754 /* Completion Highlighted */
1755 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1756 fgs[2] = parse_color(value.addr, "#000");
1758 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1759 bgs[2] = parse_color(value.addr, "#fff");
1761 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value) == 1) {
1763 paddings = parse_csslike(value.addr);
1764 if (paddings != NULL)
1765 for (i = 0; i < 4; ++i)
1766 r.ch_padding[i] = parse_integer(paddings[i], 0);
1768 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.padding");
1771 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype, &value) == 1) {
1773 sizes = parse_csslike(value.addr);
1775 for (i = 0; i < 4; ++i)
1776 r.ch_borders[i] = parse_integer(sizes[i], 0);
1778 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.size");
1781 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype, &value) == 1) {
1783 colors = parse_csslike(value.addr);
1785 for (i = 0; i < 4; ++i)
1786 ch_borders_bg[i] = parse_color(colors[i], "#000");
1788 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.color");
1792 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1794 colors = parse_csslike(value.addr);
1796 for (i = 0; i < 4; ++i)
1797 borders_bg[i] = parse_color(colors[i], "#000");
1799 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1803 /* Second round of args parsing */
1804 optind = 0; /* reset the option index */
1805 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1808 r.first_selected = 1;
1811 /* free_text -- already catched */
1813 /* separator -- this case was already catched */
1815 /* embedding mymenu this case was already catched. */
1817 /* multiple selection this case was already catched. */
1821 newprompt = strdup(optarg);
1822 if (newprompt != NULL) {
1829 x = parse_int_with_pos(optarg, x, d_width, r.width);
1832 y = parse_int_with_pos(optarg, y, d_height, r.height);
1836 if ((paddings = parse_csslike(optarg)) != NULL)
1837 for (i = 0; i < 4; ++i)
1838 r.p_padding[i] = parse_integer(paddings[i], 0);
1843 if ((colors = parse_csslike(optarg)) != NULL)
1844 for (i = 0; i < 4; ++i)
1845 p_borders_bg[i] = parse_color(colors[i], "#000");
1850 if ((sizes = parse_csslike(optarg)) != NULL)
1851 for (i = 0; i < 4; ++i)
1852 r.p_borders[i] = parse_integer(sizes[i], 0);
1857 if ((colors = parse_csslike(optarg)) != NULL)
1858 for (i = 0; i < 4; ++i)
1859 c_borders_bg[i] = parse_color(colors[i], "#000");
1864 if ((sizes = parse_csslike(optarg)) != NULL)
1865 for (i = 0; i < 4; ++i)
1866 r.c_borders[i] = parse_integer(sizes[i], 0);
1871 if ((colors = parse_csslike(optarg)) != NULL)
1872 for (i = 0; i < 4; ++i)
1873 ch_borders_bg[i] = parse_color(colors[i], "#000");
1878 if ((sizes = parse_csslike(optarg)) != NULL)
1879 for (i = 0; i < 4; ++i)
1880 r.ch_borders[i] = parse_integer(sizes[i], 0);
1884 r.horizontal_layout = !strcmp(optarg, "horizontal");
1888 if ((newfont = strdup(optarg)) != NULL) {
1895 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1898 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1902 if ((borders = parse_csslike(optarg)) != NULL) {
1903 for (i = 0; i < 4; ++i)
1904 r.borders[i] = parse_integer(borders[i], 0);
1906 fprintf(stderr, "Error parsing b option\n");
1911 if ((colors = parse_csslike(optarg)) != NULL) {
1912 for (i = 0; i < 4; ++i)
1913 borders_bg[i] = parse_color(colors[i], "#000");
1915 fprintf(stderr, "error while parsing B option\n");
1919 fgs[0] = parse_color(optarg, NULL);
1922 bgs[0] = parse_color(optarg, NULL);
1925 fgs[1] = parse_color(optarg, NULL);
1928 bgs[1] = parse_color(optarg, NULL);
1931 fgs[2] = parse_color(optarg, NULL);
1934 fgs[2] = parse_color(optarg, NULL);
1937 fprintf(stderr, "Unrecognized option %c\n", ch);
1943 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1944 fprintf(stderr, "height, width, x or y are lesser than 0.");
1948 /* since only now we know if the first should be selected,
1949 * update the completion here */
1950 update_completions(cs, text, lines, vlines, r.first_selected);
1952 /* update the prompt lenght, only now we surely know the length of it */
1953 r.ps1len = strlen(r.ps1);
1955 /* Create the window */
1956 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1957 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1958 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1959 XMapRaised(r.d, r.w);
1961 /* If embed, listen for other events as well */
1963 Window *children, parent, root;
1964 unsigned int children_no;
1966 XSelectInput(r.d, parent_window, FocusChangeMask);
1967 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1968 for (i = 0; i < children_no && children[i] != r.w; ++i)
1969 XSelectInput(r.d, children[i], FocusChangeMask);
1972 grabfocus(r.d, r.w);
1975 take_keyboard(r.d, r.w);
1977 r.x_zero = r.borders[3];
1978 r.y_zero = r.borders[0];
1983 for (i = 0; i < 3; ++i) {
1984 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1985 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
1988 for (i = 0; i < 4; ++i) {
1989 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1990 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1991 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1992 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1996 /* Load the colors in our GCs */
1997 for (i = 0; i < 3; ++i) {
1998 XSetForeground(r.d, r.fgs[i], fgs[i]);
1999 XSetForeground(r.d, r.bgs[i], bgs[i]);
2002 for (i = 0; i < 4; ++i) {
2003 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2004 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2005 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2006 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2009 if (load_font(&r, fontname) == -1)
2013 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2017 XRenderColor xrcolor;
2020 c = *(rgba_t*)&fgs[0];
2021 xrcolor.red = EXPANDBITS(c.rgba.r);
2022 xrcolor.green = EXPANDBITS(c.rgba.g);
2023 xrcolor.blue = EXPANDBITS(c.rgba.b);
2024 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2025 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[0]);
2028 c = *(rgba_t*)&fgs[1];
2029 xrcolor.red = EXPANDBITS(c.rgba.r);
2030 xrcolor.green = EXPANDBITS(c.rgba.g);
2031 xrcolor.blue = EXPANDBITS(c.rgba.b);
2032 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2033 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[1]);
2035 /* Completion highlighted */
2036 c = *(rgba_t*)&fgs[2];
2037 xrcolor.red = EXPANDBITS(c.rgba.r);
2038 xrcolor.green = EXPANDBITS(c.rgba.g);
2039 xrcolor.blue = EXPANDBITS(c.rgba.b);
2040 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2041 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[2]);
2045 /* compute prompt dimensions */
2051 /* Now we need only the ability to write */
2052 pledge("stdio", "");
2055 /* Cache text height */
2056 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2058 /* Draw the window for the first time */
2062 while (status == LOOPING || status == OK_LOOP) {
2063 status = loop(&r, &text, &textlen, cs, lines, vlines);
2066 printf("%s\n", text);
2068 if (!r.multiple_select && status == OK_LOOP)
2072 XUngrabKeyboard(r.d, CurrentTime);
2075 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[0]);
2076 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[1]);
2077 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[2]);
2089 XDestroyWindow(r.d, r.w);
2092 return status != OK;