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:"
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 #define EXPANDBITS(x) ((0xffff * x) / 0xff)
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 64
60 /* The number of lines to allocate in advance */
61 #define LINES_CHUNK 32
64 #define check_allocation(a) { \
66 fprintf(stderr, "Could not allocate memory\n"); \
71 #define inner_height(r) (r->height - r->border_n - r->border_s)
72 #define inner_width(r) (r->width - r->border_e - r->border_w)
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 text_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 */
105 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause the borders) */
106 int y_zero; /* like x_zero but for the y axis */
108 size_t offset; /* scroll offset */
111 short first_selected;
112 short multiple_select;
114 /* four border width */
120 short horizontal_layout;
133 GC completion_highlighted;
134 GC completion_highlighted_bg;
143 XftColor xft_completion;
144 XftColor xft_completion_highlighted;
155 /* Wrap the linked list of completions */
157 struct completion *completions;
162 /* idea stolen from lemonbar. ty lemonboy */
173 /* Return a newly allocated (and empty) completion list */
175 compls_new(size_t length)
177 struct completions *cs = malloc(sizeof(struct completions));
182 cs->completions = calloc(length, sizeof(struct completion));
183 if (cs->completions == NULL) {
193 /* Delete the wrapper and the whole list */
195 compls_delete(struct completions *cs)
200 free(cs->completions);
205 * Create a completion list from a text and the list of possible
206 * completions (null terminated). Expects a non-null `cs'. `lines' and
207 * `vlines' should have the same length OR `vlines' is NULL.
210 filter(struct completions *cs, char *text, char **lines, char **vlines)
219 if (lines[index] == NULL)
222 char *l = vlines[index] != NULL ? vlines[index] : lines[index];
224 if (strcasestr(l, text) != NULL) {
225 struct completion *c = &cs->completions[matching];
227 c->rcompletion = lines[index];
233 cs->length = matching;
237 /* Update the given completion */
239 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
241 filter(cs, text, lines, vlines);
242 if (first_selected && cs->length > 0)
247 * Select the next or previous selection and update some state. `text'
248 * will be updated with the text of the completion and `textlen' with
249 * the new length. If the memory cannot be allocated `status' will be
253 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
255 struct completion *n;
258 if (cs == NULL || cs->length == 0)
262 * If the first is always selected and the first entry is
263 * different from the text, expand the text and return
267 && strcmp(cs->completions->completion, *text) != 0
270 *text = strdup(cs->completions->completion);
275 *textlen = strlen(*text);
279 index = cs->selected;
281 if (index == -1 && p)
283 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
285 n = &cs->completions[cs->selected];
288 *text = strdup(n->completion);
290 fprintf(stderr, "Memory allocation error!\n");
294 *textlen = strlen(*text);
297 /* Push the character c at the end of the string pointed by p */
299 pushc(char **p, int maxlen, char c)
301 int len = strnlen(*p, maxlen);
303 if (!(len < maxlen -2)) {
306 maxlen += maxlen >> 1;
307 newptr = realloc(*p, maxlen);
308 if (newptr == NULL) /* bad */
319 * Remove the last rune from the *UTF-8* string! This is different
320 * from just setting the last byte to 0 (in some cases ofc). Return a
321 * pointer (e) to the last nonzero char. If e < p then p is empty!
341 * If c is a starting byte (11......) or is under
344 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
351 /* Remove the last word plus trailing white spaces from the given string */
369 if (in_word && isspace(*e))
372 if (!in_word && !isspace(*e))
378 * If the string is surrounded by quates (`"') remove them and replace
379 * every `\"' in the string with a single double-quote.
382 normalize_str(const char *str)
391 s = calloc(len, sizeof(char));
402 str += 2; /* skip this and the next char */
408 str++; /* skip only this char */
420 read_stdin(char **buf)
423 size_t len = STDIN_CHUNKS;
425 *buf = malloc(len * sizeof(char));
433 r = read(0, *buf + offset, STDIN_CHUNKS);
441 *buf = realloc(*buf, len);
445 for (i = offset; i < len; ++i)
450 fprintf(stderr, "Error in allocating memory for stdin.\n");
451 exit(EX_UNAVAILABLE);
455 readlines(char ***lns, char **buf)
457 size_t len, ll, lines;
463 len = read_stdin(buf);
466 *lns = malloc(ll * sizeof(char*));
471 for (size_t i = 0; i < len; i++) {
480 if (in_line && c == '\n')
483 if (!in_line && c != '\n') {
485 (*lns)[lines] = (*buf) + i;
488 if (lines == ll) { /* resize */
490 *lns = realloc(*lns, ll * sizeof(char*));
497 (*lns)[lines] = NULL;
502 fprintf(stderr, "Error in memory allocation.\n");
503 exit(EX_UNAVAILABLE);
507 * Compute the dimensions of the string str once rendered.
508 * It'll return the width and set ret_width and ret_height if not NULL
511 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
517 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
518 height = r->font->ascent - r->font->descent;
519 width = gi.width - gi.x;
522 XmbTextExtents(r->font, str, len, NULL, &rect);
523 height = rect.height;
526 if (ret_width != NULL) *ret_width = width;
527 if (ret_height != NULL) *ret_height = height;
532 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
536 if (tt == PROMPT) xftcolor = r->xft_prompt;
537 if (tt == COMPL) xftcolor = r->xft_completion;
538 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
540 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
543 if (tt == PROMPT) gc = r->prompt;
544 if (tt == COMPL) gc = r->completion;
545 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
546 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
550 /* Duplicate the string and substitute every space with a 'n` */
559 if (str == NULL || len == 0)
566 for (i = 0; i < len; ++i)
573 /* |------------------|----------------------------------------------| */
574 /* | 20 char text | completion | completion | completion | compl | */
575 /* |------------------|----------------------------------------------| */
577 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
580 int prompt_width, ps1xlen, start_at;
585 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
587 ps1dup = strdupn(r->ps1);
588 ps1xlen = text_extents(ps1dup != NULL ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
591 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
592 start_at *= prompt_width;
593 start_at += r->padding;
595 texty = (inner_height(r) + height + r->y_zero) / 2;
597 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
599 textlen = strlen(text);
600 if (textlen > prompt_width)
601 text = text + textlen - prompt_width;
603 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
604 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
606 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
608 for (i = r->offset; i < cs->length; ++i) {
609 struct completion *c;
614 c = &cs->completions[i];
615 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
616 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
617 len = strlen(c->completion);
618 text_width = text_extents(c->completion, len, r, NULL, NULL);
620 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
621 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
623 start_at += text_width + r->padding * 2;
625 if (start_at > inner_width(r))
626 break; /* don't draw completion out of the window */
630 /* |-----------------------------------------------------------------| */
632 /* |-----------------------------------------------------------------| */
634 /* |-----------------------------------------------------------------| */
636 /* |-----------------------------------------------------------------| */
638 draw_vertically(struct rendering *r, char *text, struct completions *cs)
641 int height, start_at;
645 text_extents("fjpgl", 5, r, NULL, &height);
646 start_at = r->padding * 2 + height;
648 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
649 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
651 ps1dup = strdupn(r->ps1);
652 ps1xlen = text_extents(ps1dup == NULL ? ps1dup : r->ps1, r->ps1len, r, NULL, NULL);
655 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
656 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
658 start_at += r->y_zero;
660 for (i = r->offset; i < cs->length; ++i) {
661 struct completion *c;
666 c = &cs->completions[i];
667 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
668 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
669 len = strlen(c->completion);
671 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
672 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
674 start_at += height + r->padding * 2;
676 if (start_at > inner_height(r))
677 break; /* don't draw completion out of the window */
682 draw(struct rendering *r, char *text, struct completions *cs)
684 if (r->horizontal_layout)
685 draw_horizontally(r, text, cs);
687 draw_vertically(r, text, cs);
689 /* Draw the borders */
690 if (r->border_w != 0)
691 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
693 if (r->border_e != 0)
694 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
696 if (r->border_n != 0)
697 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
699 if (r->border_s != 0)
700 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
706 /* Set some WM stuff */
708 set_win_atoms_hints(Display *d, Window w, int width, int height)
711 XClassHint *class_hint;
712 XSizeHints *size_hint;
714 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
718 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
719 XInternAtom(d, "ATOM", 0),
722 (unsigned char *)&type,
726 /* some window managers honor this properties */
727 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
730 XInternAtom(d, "_NET_WM_STATE", 0),
731 XInternAtom(d, "ATOM", 0),
734 (unsigned char *)&type,
738 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
741 XInternAtom(d, "_NET_WM_STATE", 0),
742 XInternAtom(d, "ATOM", 0),
745 (unsigned char *)&type,
749 /* Setting window hints */
750 class_hint = XAllocClassHint();
751 if (class_hint == NULL) {
752 fprintf(stderr, "Could not allocate memory for class hint\n");
753 exit(EX_UNAVAILABLE);
755 class_hint->res_name = resname;
756 class_hint->res_class = resclass;
757 XSetClassHint(d, w, class_hint);
760 size_hint = XAllocSizeHints();
761 if (size_hint == NULL) {
762 fprintf(stderr, "Could not allocate memory for size hint\n");
763 exit(EX_UNAVAILABLE);
765 size_hint->flags = PMinSize | PBaseSize;
766 size_hint->min_width = width;
767 size_hint->base_width = width;
768 size_hint->min_height = height;
769 size_hint->base_height = height;
774 /* Get the width and height of the window `w' */
776 get_wh(Display *d, Window *w, int *width, int *height)
778 XWindowAttributes win_attr;
780 XGetWindowAttributes(d, *w, &win_attr);
781 *height = win_attr.height;
782 *width = win_attr.width;
786 grabfocus(Display *d, Window w)
789 for (i = 0; i < 100; ++i) {
793 XGetInputFocus(d, &focuswin, &revert_to_win);
798 XSetInputFocus(d, w, RevertToParent, CurrentTime);
805 * I know this may seem a little hackish BUT is the only way I managed
806 * to actually grab that goddam keyboard. Only one call to
807 * XGrabKeyboard does not always end up with the keyboard grabbed!
810 take_keyboard(Display *d, Window w)
814 for (i = 0; i < 100; i++) {
815 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
819 fprintf(stderr, "Cannot grab keyboard\n");
824 parse_color(const char *str, const char *def)
835 /* +1 for the # ath the start */
836 if (*str != '#' || len > 9 || len < 4)
838 ++str; /* skip the # */
841 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
848 /* expand #rgb -> #rrggbb */
849 tmp.v = (tmp.v & 0xf00) * 0x1100
850 | (tmp.v & 0x0f0) * 0x0110
851 | (tmp.v & 0x00f) * 0x0011;
853 /* assume 0xff opacity */
856 } /* colors in #aarrggbb need no adjustments */
858 /* premultiply the alpha */
860 tmp.r = (tmp.r * tmp.a) / 255;
861 tmp.g = (tmp.g * tmp.a) / 255;
862 tmp.b = (tmp.b * tmp.a) / 255;
869 fprintf(stderr, "Invalid color: \"%s\".\n", str);
871 return parse_color(def, NULL);
877 * Given a string try to parse it as a number or return `default_value'.
880 parse_integer(const char *str, int default_value)
886 lval = strtol(str, &ep, 10);
888 if (str[0] == '\0' || *ep != '\0') { /* NaN */
889 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
890 return default_value;
893 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
894 (lval > INT_MAX || lval < INT_MIN)) {
895 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
896 return default_value;
902 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
904 parse_int_with_percentage(const char *str, int default_value, int max)
906 int len = strlen(str);
908 if (len > 0 && str[len-1] == '%') {
913 check_allocation(cpy);
915 val = parse_integer(cpy, default_value);
917 return val * max / 100;
919 return parse_integer(str, default_value);
923 * Like parse_int_with_percentage but understands some special values:
924 * - middle that is (max-self)/2
926 * - end that is (max-self)
929 parse_int_with_pos(const char *str, int default_value, int max, int self)
931 if (!strcmp(str, "start"))
933 if (!strcmp(str, "middle"))
934 return (max - self)/2;
935 if (!strcmp(str, "end"))
937 return parse_int_with_percentage(str, default_value, max);
940 /* Parse a string like a CSS value. */
941 /* TODO: harden a bit this function */
943 parse_csslike(const char *str)
946 char *s, *token, **ret;
953 ret = malloc(4 * sizeof(char*));
960 while ((token = strsep(&s, " ")) != NULL && i < 4) {
961 ret[i] = strdup(token);
966 for (int j = 1; j < 4; j++)
967 ret[j] = strdup(ret[0]);
970 ret[2] = strdup(ret[0]);
971 ret[3] = strdup(ret[1]);
975 ret[3] = strdup(ret[1]);
977 /* before we didn't check for the return type of strdup, here we will */
980 for (i = 0; i < 4; ++i)
981 any_null = ret[i] == NULL || any_null;
984 for (i = 0; i < 4; ++i)
988 if (i == 0 || any_null) {
998 * Given an event, try to understand what the users wants. If the
999 * return value is ADD_CHAR then `input' is a pointer to a string that
1000 * will need to be free'ed later.
1003 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1005 char str[SYM_BUF_SIZE] = {0};
1008 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1011 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1012 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1014 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1017 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1020 /* Try to read what key was pressed */
1022 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1023 if (s == XBufferOverflow) {
1024 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1028 if (ev->state & ControlMask) {
1029 if (!strcmp(str, "")) /* C-u */
1031 if (!strcmp(str, "")) /* C-w */
1033 if (!strcmp(str, "")) /* C-h */
1035 if (!strcmp(str, "\r")) /* C-m */
1036 return CONFIRM_CONTINUE;
1037 if (!strcmp(str, "")) /* C-p */
1039 if (!strcmp(str, "")) /* C-n */
1041 if (!strcmp(str, "")) /* C-c */
1043 if (!strcmp(str, "\t")) /* C-i */
1044 return TOGGLE_FIRST_SELECTED;
1047 *input = strdup(str);
1048 if (*input == NULL) {
1049 fprintf(stderr, "Error while allocating memory for key.\n");
1057 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1059 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1060 /* if there is something selected expand it and return */
1061 int index = cs->selected == -1 ? 0 : cs->selected;
1062 struct completion *c = cs->completions;
1076 if (*text == NULL) {
1077 fprintf(stderr, "Memory allocation error\n");
1081 *textlen = strlen(*text);
1085 if (!r->free_text) /* cannot accept arbitrary text */
1091 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1093 enum state status = LOOPING;
1095 while (status == LOOPING) {
1097 XNextEvent(r->d, &e);
1099 if (XFilterEvent(&e, r->w))
1104 XRefreshKeyboardMapping(&e.xmapping);
1109 if (e.xfocus.window != r->w)
1110 grabfocus(r->d, r->w);
1113 case VisibilityNotify:
1114 if (e.xvisibility.state != VisibilityUnobscured)
1115 XRaiseWindow(r->d, r->w);
1119 get_wh(r->d, &r->w, &r->width, &r->height);
1124 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1127 switch (parse_event(r->d, ev, r->xic, &input)) {
1134 confirm(&status, r, cs, text, textlen);
1138 case CONFIRM_CONTINUE: {
1140 confirm(&status, r, cs, text, textlen);
1145 complete(cs, r->first_selected, 1, text, textlen, &status);
1146 r->offset = cs->selected;
1151 complete(cs, r->first_selected, 0, text, textlen, &status);
1152 r->offset = cs->selected;
1158 update_completions(cs, *text, lines, vlines, r->first_selected);
1164 update_completions(cs, *text, lines, vlines, r->first_selected);
1170 for (i = 0; i < *textlen; ++i)
1172 update_completions(cs, *text, lines, vlines, r->first_selected);
1180 str_len = strlen(input);
1183 * sometimes a strange key is pressed
1184 * i.e. ctrl alone), so input will be
1185 * empty. Don't need to update
1186 * completion in that case
1191 for (i = 0; i < str_len; ++i) {
1192 *textlen = pushc(text, *textlen, input[i]);
1193 if (*textlen == -1) {
1194 fprintf(stderr, "Memory allocation error\n");
1200 if (status != ERR) {
1201 update_completions(cs, *text, lines, vlines, r->first_selected);
1209 case TOGGLE_FIRST_SELECTED:
1210 r->first_selected = !r->first_selected;
1211 if (r->first_selected && cs->selected < 0)
1213 if (!r->first_selected && cs->selected == 0)
1220 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1221 /* if (ev->button == Button1) { /\* click *\/ */
1222 /* int x = ev->x - r.border_w; */
1223 /* int y = ev->y - r.border_n; */
1224 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1227 if (ev->button == Button4) /* scroll up */
1228 r->offset = MAX((ssize_t)r->offset - 1, 0);
1230 if (ev->button == Button5) /* scroll down */
1231 r->offset = MIN(r->offset + 1, cs->length - 1);
1244 load_font(struct rendering *r, const char *fontname)
1247 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1250 char **missing_charset_list;
1251 int missing_charset_count;
1253 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1254 if (r->font != NULL)
1257 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1259 if (!strcmp(fontname, default_fontname))
1262 return load_font(r, default_fontname);
1267 usage(char *prgname)
1269 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1270 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1271 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1272 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1276 main(int argc, char **argv)
1278 struct completions *cs;
1279 XSetWindowAttributes attr;
1283 Window parent_window, w;
1289 XIMStyle best_match_style;
1291 unsigned long p_fg, compl_fg, compl_highlighted_fg;
1292 unsigned long p_bg, compl_bg, compl_highlighted_bg;
1293 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1295 int offset_x, offset_y, width, height, x, y;
1296 int padding, textlen;
1297 int border_n, border_e, border_s, border_w;
1298 int d_width, d_height;
1300 short first_selected, free_text, multiple_select;
1301 short embed, horizontal_layout;
1302 char *sep, *parent_window_id;
1303 char **lines, *buf, **vlines;
1304 char *ps1, *fontname, *text, *xrm;
1307 /* stdio & rpath: to read/write stdio/stdout/stderr */
1308 /* unix: to connect to XOrg */
1309 pledge("stdio rpath unix", "");
1314 parent_window_id = NULL;
1316 multiple_select = 0;
1318 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1320 case 'h': /* help */
1323 case 'v': /* version */
1324 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1326 case 'e': /* embed */
1327 parent_window_id = strdup(optarg);
1328 check_allocation(parent_window_id);
1331 sep = strdup(optarg);
1332 check_allocation(sep);
1339 multiple_select = 1;
1347 /* Read the completions */
1350 nlines = readlines(&lines, &buf);
1356 vlines = calloc(nlines, sizeof(char*));
1357 check_allocation(vlines);
1359 for (i = 0; i < nlines; i++) {
1361 t = strstr(lines[i], sep);
1363 vlines[i] = lines[i];
1369 setlocale(LC_ALL, getenv("LANG"));
1373 /* where the monitor start (used only with xinerama) */
1374 offset_x = offset_y = 0;
1376 /* default width and height */
1380 /* default position on the screen */
1383 /* default padding */
1386 /* default borders */
1387 border_n = border_e = border_s = border_w = 0;
1389 /* the prompt. We duplicate the string so later is easy to
1390 * free (in the case it's been overwritten by the user) */
1392 check_allocation(ps1);
1394 /* same for the font name */
1395 fontname = strdup(default_fontname);
1396 check_allocation(fontname);
1399 text = malloc(textlen * sizeof(char));
1400 check_allocation(text);
1402 /* struct completions *cs = filter(text, lines); */
1403 cs = compls_new(nlines);
1404 check_allocation(cs);
1406 /* start talking to xorg */
1407 d = XOpenDisplay(NULL);
1409 fprintf(stderr, "Could not open display!\n");
1410 return EX_UNAVAILABLE;
1414 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1415 parent_window = DefaultRootWindow(d);
1419 /* get display size */
1420 get_wh(d, &parent_window, &d_width, &d_height);
1423 if (!embed && XineramaIsActive(d)) { /* find the mice */
1424 XineramaScreenInfo *info;
1427 int number_of_screens, monitors, i;
1428 int root_x, root_y, win_x, win_y;
1432 number_of_screens = XScreenCount(d);
1433 for (i = 0; i < number_of_screens; ++i) {
1434 root = XRootWindow(d, i);
1435 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1439 fprintf(stderr, "No mouse found.\n");
1444 /* Now find in which monitor the mice is */
1445 info = XineramaQueryScreens(d, &monitors);
1447 for (i = 0; i < monitors; ++i) {
1448 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1449 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1450 offset_x = info[i].x_org;
1451 offset_y = info[i].y_org;
1452 d_width = info[i].width;
1453 d_height = info[i].height;
1461 XMatchVisualInfo(d, DefaultScreen(d), 32, TrueColor, &vinfo);
1463 cmap = XCreateColormap(d, XDefaultRootWindow(d), vinfo.visual, AllocNone);
1465 p_fg = compl_fg = parse_color("#fff", NULL);
1466 compl_highlighted_fg = parse_color("#000", NULL);
1468 p_bg = compl_bg = parse_color("#000", NULL);
1469 compl_highlighted_bg = parse_color("#fff", NULL);
1471 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", NULL);
1473 horizontal_layout = 1;
1475 /* Read the resources */
1477 xrm = XResourceManagerString(d);
1483 xdb = XrmGetStringDatabase(xrm);
1485 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1487 fontname = strdup(value.addr);
1488 check_allocation(fontname);
1490 fprintf(stderr, "no font defined, using %s\n", fontname);
1493 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1494 horizontal_layout = !strcmp(value.addr, "horizontal");
1496 fprintf(stderr, "no layout defined, using horizontal\n");
1498 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1500 ps1 = normalize_str(value.addr);
1502 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1505 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1506 width = parse_int_with_percentage(value.addr, width, d_width);
1508 fprintf(stderr, "no width defined, using %d\n", width);
1510 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1511 height = parse_int_with_percentage(value.addr, height, d_height);
1513 fprintf(stderr, "no height defined, using %d\n", height);
1515 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1516 x = parse_int_with_pos(value.addr, x, d_width, width);
1518 fprintf(stderr, "no x defined, using %d\n", x);
1520 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1521 y = parse_int_with_pos(value.addr, y, d_height, height);
1523 fprintf(stderr, "no y defined, using %d\n", y);
1525 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1526 padding = parse_integer(value.addr, padding);
1528 fprintf(stderr, "no padding defined, using %d\n", padding);
1530 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1533 borders = parse_csslike(value.addr);
1534 if (borders != NULL) {
1535 border_n = parse_integer(borders[0], 0);
1536 border_e = parse_integer(borders[1], 0);
1537 border_s = parse_integer(borders[2], 0);
1538 border_w = parse_integer(borders[3], 0);
1540 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1542 fprintf(stderr, "no border defined, using 0.\n");
1545 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1546 p_fg = parse_color(value.addr, "#fff");
1548 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1549 p_bg = parse_color(value.addr, "#000");
1552 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1553 compl_fg = parse_color(value.addr, "#fff");
1555 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1556 compl_bg = parse_color(value.addr, "#000");
1558 compl_bg = parse_color("#000", NULL);
1560 /* Completion Highlighted */
1561 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1562 compl_highlighted_fg = parse_color(value.addr, "#000");
1564 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1565 compl_highlighted_bg = parse_color(value.addr, "#fff");
1567 compl_highlighted_bg = parse_color("#fff", NULL);
1570 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1572 colors = parse_csslike(value.addr);
1573 if (colors != NULL) {
1574 border_n_bg = parse_color(colors[0], "#000");
1575 border_e_bg = parse_color(colors[1], "#000");
1576 border_s_bg = parse_color(colors[2], "#000");
1577 border_w_bg = parse_color(colors[3], "#000");
1579 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1583 /* Second round of args parsing */
1584 optind = 0; /* reset the option index */
1585 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1592 /* free_text -- already catched */
1594 /* separator -- this case was already catched */
1596 /* embedding mymenu this case was already catched. */
1598 /* multiple selection this case was already catched. */
1603 newprompt = strdup(optarg);
1604 if (newprompt != NULL) {
1611 x = parse_int_with_pos(optarg, x, d_width, width);
1614 y = parse_int_with_pos(optarg, y, d_height, height);
1617 padding = parse_integer(optarg, padding);
1620 horizontal_layout = !strcmp(optarg, "horizontal");
1624 if ((newfont = strdup(optarg)) != NULL) {
1631 width = parse_int_with_percentage(optarg, width, d_width);
1634 height = parse_int_with_percentage(optarg, height, d_height);
1638 if ((borders = parse_csslike(optarg)) != NULL) {
1639 border_n = parse_integer(borders[0], 0);
1640 border_e = parse_integer(borders[1], 0);
1641 border_s = parse_integer(borders[2], 0);
1642 border_w = parse_integer(borders[3], 0);
1644 fprintf(stderr, "Error parsing b option\n");
1649 if ((colors = parse_csslike(optarg)) != NULL) {
1650 border_n_bg = parse_color(colors[0], "#000");
1651 border_e_bg = parse_color(colors[1], "#000");
1652 border_s_bg = parse_color(colors[2], "#000");
1653 border_w_bg = parse_color(colors[3], "#000");
1655 fprintf(stderr, "error while parsing B option\n");
1659 p_fg = parse_color(optarg, NULL);
1663 p_bg = parse_color(optarg, NULL);
1667 compl_fg = parse_color(optarg, NULL);
1671 compl_bg = parse_color(optarg, NULL);
1675 compl_highlighted_fg = parse_color(optarg, NULL);
1679 compl_highlighted_bg = parse_color(optarg, NULL);
1683 fprintf(stderr, "Unrecognized option %c\n", ch);
1689 /* since only now we know if the first should be selected,
1690 * update the completion here */
1691 update_completions(cs, text, lines, vlines, first_selected);
1693 /* Create the window */
1694 attr.colormap = cmap;
1695 attr.override_redirect = 1;
1696 attr.border_pixel = 0;
1697 attr.background_pixel = 0x80808080;
1698 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1700 w = XCreateWindow(d,
1702 x + offset_x, y + offset_y,
1708 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1711 set_win_atoms_hints(d, w, width, height);
1713 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1716 /* If embed, listen for other events as well */
1718 Window *children, parent, root;
1719 unsigned int children_no;
1721 XSelectInput(d, parent_window, FocusChangeMask);
1722 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1723 for (i = 0; i < children_no && children[i] != w; ++i)
1724 XSelectInput(d, children[i], FocusChangeMask);
1730 take_keyboard(d, w);
1732 struct rendering r = {
1741 .free_text = free_text,
1742 .first_selected = first_selected,
1743 .multiple_select = multiple_select,
1744 .border_n = border_n,
1745 .border_e = border_e,
1746 .border_s = border_s,
1747 .border_w = border_w,
1748 .horizontal_layout = horizontal_layout,
1750 .ps1len = strlen(ps1),
1751 .prompt = XCreateGC(d, w, 0, &values),
1752 .prompt_bg = XCreateGC(d, w, 0, &values),
1753 .completion = XCreateGC(d, w, 0, &values),
1754 .completion_bg = XCreateGC(d, w, 0, &values),
1755 .completion_highlighted = XCreateGC(d, w, 0, &values),
1756 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1757 .border_n_bg = XCreateGC(d, w, 0, &values),
1758 .border_e_bg = XCreateGC(d, w, 0, &values),
1759 .border_s_bg = XCreateGC(d, w, 0, &values),
1760 .border_w_bg = XCreateGC(d, w, 0, &values),
1763 if (load_font(&r, fontname) == -1)
1767 r.xftdraw = XftDrawCreate(d, w, vinfo.visual, DefaultColormap(d, 0));
1771 XRenderColor xrcolor;
1774 c = *(rgba_t*)&p_fg;
1775 xrcolor.red = EXPANDBITS(c.r);
1776 xrcolor.green = EXPANDBITS(c.g);
1777 xrcolor.blue = EXPANDBITS(c.b);
1778 xrcolor.alpha = EXPANDBITS(c.a);
1779 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1782 c = *(rgba_t*)&compl_fg;
1783 xrcolor.red = EXPANDBITS(c.r);
1784 xrcolor.green = EXPANDBITS(c.g);
1785 xrcolor.blue = EXPANDBITS(c.b);
1786 xrcolor.alpha = EXPANDBITS(c.a);
1787 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1789 /* Completion highlighted */
1790 c = *(rgba_t*)&compl_highlighted_fg;
1791 xrcolor.red = EXPANDBITS(c.r);
1792 xrcolor.green = EXPANDBITS(c.g);
1793 xrcolor.blue = EXPANDBITS(c.b);
1794 xrcolor.alpha = EXPANDBITS(c.a);
1795 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1799 /* Load the colors in our GCs */
1800 XSetForeground(d, r.prompt, p_fg);
1801 XSetForeground(d, r.prompt_bg, p_bg);
1802 XSetForeground(d, r.completion, compl_fg);
1803 XSetForeground(d, r.completion_bg, compl_bg);
1804 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg);
1805 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg);
1806 XSetForeground(d, r.border_n_bg, border_n_bg);
1807 XSetForeground(d, r.border_e_bg, border_e_bg);
1808 XSetForeground(d, r.border_s_bg, border_s_bg);
1809 XSetForeground(d, r.border_w_bg, border_w_bg);
1811 /* Open the X input method */
1812 xim = XOpenIM(d, xdb, resname, resclass);
1813 check_allocation(xim);
1815 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1816 fprintf(stderr, "Input Styles could not be retrieved\n");
1817 return EX_UNAVAILABLE;
1820 best_match_style = 0;
1821 for (i = 0; i < xis->count_styles; ++i) {
1822 XIMStyle ts = xis->supported_styles[i];
1823 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1824 best_match_style = ts;
1830 if (!best_match_style)
1831 fprintf(stderr, "No matching input style could be determined\n");
1833 r.xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, w, XNFocusWindow, w, NULL);
1834 check_allocation(r.xic);
1836 /* Draw the window for the first time */
1840 while (status == LOOPING || status == OK_LOOP) {
1841 status = loop(&r, &text, &textlen, cs, lines, vlines);
1844 printf("%s\n", text);
1846 if (!multiple_select && status == OK_LOOP)
1850 XUngrabKeyboard(d, CurrentTime);
1853 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1854 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1855 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1867 XDestroyWindow(r.d, r.w);
1870 return status != OK;