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 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->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)
220 if (lines[index] == NULL)
223 l = vlines[index] != NULL ? vlines[index] : lines[index];
225 if (strcasestr(l, text) != NULL) {
226 struct completion *c = &cs->completions[matching];
228 c->rcompletion = lines[index];
234 cs->length = matching;
238 /* Update the given completion */
240 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
242 filter(cs, text, lines, vlines);
243 if (first_selected && cs->length > 0)
248 * Select the next or previous selection and update some state. `text'
249 * will be updated with the text of the completion and `textlen' with
250 * the new length. If the memory cannot be allocated `status' will be
254 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
256 struct completion *n;
259 if (cs == NULL || cs->length == 0)
263 * If the first is always selected and the first entry is
264 * different from the text, expand the text and return
268 && strcmp(cs->completions->completion, *text) != 0
271 *text = strdup(cs->completions->completion);
276 *textlen = strlen(*text);
280 index = cs->selected;
282 if (index == -1 && p)
284 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
286 n = &cs->completions[cs->selected];
289 *text = strdup(n->completion);
291 fprintf(stderr, "Memory allocation error!\n");
295 *textlen = strlen(*text);
298 /* Push the character c at the end of the string pointed by p */
300 pushc(char **p, int maxlen, char c)
304 len = strnlen(*p, maxlen);
305 if (!(len < maxlen -2)) {
308 maxlen += maxlen >> 1;
309 newptr = realloc(*p, maxlen);
310 if (newptr == NULL) /* bad */
321 * Remove the last rune from the *UTF-8* string! This is different
322 * from just setting the last byte to 0 (in some cases ofc). Return a
323 * pointer (e) to the last nonzero char. If e < p then p is empty!
343 * If c is a starting byte (11......) or is under
346 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
353 /* Remove the last word plus trailing white spaces from the given string */
360 if ((len = strlen(w)) == 0)
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)
387 if ((len = strlen(str)) == 0)
390 s = calloc(len, sizeof(char));
401 str += 2; /* skip this and the next char */
407 str++; /* skip only this char */
419 read_stdin(char **buf)
422 size_t len = STDIN_CHUNKS;
424 *buf = malloc(len * sizeof(char));
432 r = read(0, *buf + offset, STDIN_CHUNKS);
440 *buf = realloc(*buf, len);
444 for (i = offset; i < len; ++i)
449 fprintf(stderr, "Error in allocating memory for stdin.\n");
450 exit(EX_UNAVAILABLE);
454 readlines(char ***lns, char **buf)
456 size_t i, len, ll, lines;
462 len = read_stdin(buf);
465 *lns = malloc(ll * sizeof(char*));
470 for (i = 0; i < len; i++) {
479 if (in_line && c == '\n')
482 if (!in_line && c != '\n') {
484 (*lns)[lines] = (*buf) + i;
487 if (lines == ll) { /* resize */
489 *lns = realloc(*lns, ll * sizeof(char*));
496 (*lns)[lines] = NULL;
501 fprintf(stderr, "Error in memory allocation.\n");
502 exit(EX_UNAVAILABLE);
506 * Compute the dimensions of the string str once rendered.
507 * It'll return the width and set ret_width and ret_height if not NULL
510 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
516 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
517 height = r->font->ascent - r->font->descent;
518 width = gi.width - gi.x;
521 XmbTextExtents(r->font, str, len, NULL, &rect);
522 height = rect.height;
525 if (ret_width != NULL) *ret_width = width;
526 if (ret_height != NULL) *ret_height = height;
531 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
535 if (tt == PROMPT) xftcolor = r->xft_prompt;
536 if (tt == COMPL) xftcolor = r->xft_completion;
537 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
539 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
542 if (tt == PROMPT) gc = r->prompt;
543 if (tt == COMPL) gc = r->completion;
544 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
545 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
549 /* Duplicate the string and substitute every space with a 'n` */
558 if (str == NULL || len == 0)
561 if ((dup = strdup(str)) == NULL)
564 for (i = 0; i < len; ++i)
571 /* |------------------|----------------------------------------------| */
572 /* | 20 char text | completion | completion | completion | compl | */
573 /* |------------------|----------------------------------------------| */
575 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
578 int prompt_width, ps1xlen, start_at;
583 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
585 ps1dup = strdupn(r->ps1);
586 ps1xlen = text_extents(ps1dup != NULL ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
589 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
590 start_at *= prompt_width;
591 start_at += r->padding;
593 texty = (inner_height(r) + height + r->y_zero) / 2;
595 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
597 textlen = strlen(text);
598 if (textlen > prompt_width)
599 text = text + textlen - prompt_width;
601 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
602 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
604 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
606 for (i = r->offset; i < cs->length; ++i) {
607 struct completion *c;
612 c = &cs->completions[i];
613 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
614 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
615 len = strlen(c->completion);
616 text_width = text_extents(c->completion, len, r, NULL, NULL);
618 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
619 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
621 start_at += text_width + r->padding * 2;
623 if (start_at > inner_width(r))
624 break; /* don't draw completion out of the window */
628 /* |-----------------------------------------------------------------| */
630 /* |-----------------------------------------------------------------| */
632 /* |-----------------------------------------------------------------| */
634 /* |-----------------------------------------------------------------| */
636 draw_vertically(struct rendering *r, char *text, struct completions *cs)
639 int height, start_at;
643 text_extents("fjpgl", 5, r, NULL, &height);
644 start_at = r->padding * 2 + height;
646 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
647 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
649 ps1dup = strdupn(r->ps1);
650 ps1xlen = text_extents(ps1dup == NULL ? ps1dup : r->ps1, r->ps1len, r, NULL, NULL);
653 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
654 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
656 start_at += r->y_zero;
658 for (i = r->offset; i < cs->length; ++i) {
659 struct completion *c;
664 c = &cs->completions[i];
665 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
666 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
667 len = strlen(c->completion);
669 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
670 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
672 start_at += height + r->padding * 2;
674 if (start_at > inner_height(r))
675 break; /* don't draw completion out of the window */
680 draw(struct rendering *r, char *text, struct completions *cs)
682 if (r->horizontal_layout)
683 draw_horizontally(r, text, cs);
685 draw_vertically(r, text, cs);
687 /* Draw the borders */
688 if (r->border_w != 0)
689 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
691 if (r->border_e != 0)
692 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
694 if (r->border_n != 0)
695 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
697 if (r->border_s != 0)
698 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
704 /* Set some WM stuff */
706 set_win_atoms_hints(Display *d, Window w, int width, int height)
709 XClassHint *class_hint;
710 XSizeHints *size_hint;
712 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
715 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
716 XInternAtom(d, "ATOM", 0),
719 (unsigned char *)&type,
723 /* some window managers honor this properties */
724 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
727 XInternAtom(d, "_NET_WM_STATE", 0),
728 XInternAtom(d, "ATOM", 0),
731 (unsigned char *)&type,
735 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
738 XInternAtom(d, "_NET_WM_STATE", 0),
739 XInternAtom(d, "ATOM", 0),
742 (unsigned char *)&type,
746 /* Setting window hints */
747 class_hint = XAllocClassHint();
748 if (class_hint == NULL) {
749 fprintf(stderr, "Could not allocate memory for class hint\n");
750 exit(EX_UNAVAILABLE);
753 class_hint->res_name = resname;
754 class_hint->res_class = resclass;
755 XSetClassHint(d, w, class_hint);
758 size_hint = XAllocSizeHints();
759 if (size_hint == NULL) {
760 fprintf(stderr, "Could not allocate memory for size hint\n");
761 exit(EX_UNAVAILABLE);
764 size_hint->flags = PMinSize | PBaseSize;
765 size_hint->min_width = width;
766 size_hint->base_width = width;
767 size_hint->min_height = height;
768 size_hint->base_height = height;
773 /* Get the width and height of the window `w' */
775 get_wh(Display *d, Window *w, int *width, int *height)
777 XWindowAttributes win_attr;
779 XGetWindowAttributes(d, *w, &win_attr);
780 *height = win_attr.height;
781 *width = win_attr.width;
785 grabfocus(Display *d, Window w)
788 for (i = 0; i < 100; ++i) {
792 XGetInputFocus(d, &focuswin, &revert_to_win);
797 XSetInputFocus(d, w, RevertToParent, CurrentTime);
804 * I know this may seem a little hackish BUT is the only way I managed
805 * to actually grab that goddam keyboard. Only one call to
806 * XGrabKeyboard does not always end up with the keyboard grabbed!
809 take_keyboard(Display *d, Window w)
812 for (i = 0; i < 100; i++) {
813 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
817 fprintf(stderr, "Cannot grab keyboard\n");
822 parse_color(const char *str, const char *def)
833 /* +1 for the # ath the start */
834 if (*str != '#' || len > 9 || len < 4)
836 ++str; /* skip the # */
839 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
846 /* expand #rgb -> #rrggbb */
847 tmp.v = (tmp.v & 0xf00) * 0x1100
848 | (tmp.v & 0x0f0) * 0x0110
849 | (tmp.v & 0x00f) * 0x0011;
851 /* assume 0xff opacity */
854 } /* colors in #aarrggbb need no adjustments */
856 /* premultiply the alpha */
858 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
859 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
860 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
867 fprintf(stderr, "Invalid color: \"%s\".\n", str);
869 return parse_color(def, NULL);
875 * Given a string try to parse it as a number or return `default_value'.
878 parse_integer(const char *str, int default_value)
884 lval = strtol(str, &ep, 10);
886 if (str[0] == '\0' || *ep != '\0') { /* NaN */
887 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
888 return default_value;
891 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
892 (lval > INT_MAX || lval < INT_MIN)) {
893 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
894 return default_value;
900 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
902 parse_int_with_percentage(const char *str, int default_value, int max)
904 int len = strlen(str);
906 if (len > 0 && str[len-1] == '%') {
911 check_allocation(cpy);
913 val = parse_integer(cpy, default_value);
915 return val * max / 100;
918 return parse_integer(str, default_value);
922 * Like parse_int_with_percentage but understands some special values:
923 * - middle that is (max-self)/2
925 * - end that is (max-self)
928 parse_int_with_pos(const char *str, int default_value, int max, int self)
930 if (!strcmp(str, "start"))
932 if (!strcmp(str, "middle"))
933 return (max - self)/2;
934 if (!strcmp(str, "end"))
936 return parse_int_with_percentage(str, default_value, max);
939 /* Parse a string like a CSS value. */
940 /* TODO: harden a bit this function */
942 parse_csslike(const char *str)
945 char *s, *token, **ret;
952 ret = malloc(4 * sizeof(char*));
958 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
959 ret[i] = strdup(token);
962 for (j = 1; j < 4; j++)
963 ret[j] = strdup(ret[0]);
966 ret[2] = strdup(ret[0]);
967 ret[3] = strdup(ret[1]);
971 ret[3] = strdup(ret[1]);
973 /* before we didn't check for the return type of strdup, here we will */
976 for (i = 0; i < 4; ++i)
977 any_null = ret[i] == NULL || any_null;
980 for (i = 0; i < 4; ++i)
984 if (i == 0 || any_null) {
994 * Given an event, try to understand what the users wants. If the
995 * return value is ADD_CHAR then `input' is a pointer to a string that
996 * will need to be free'ed later.
999 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1001 char str[SYM_BUF_SIZE] = {0};
1004 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1007 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1008 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1010 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1013 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1016 /* Try to read what key was pressed */
1018 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1019 if (s == XBufferOverflow) {
1020 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1024 if (ev->state & ControlMask) {
1025 if (!strcmp(str, "")) /* C-u */
1027 if (!strcmp(str, "")) /* C-w */
1029 if (!strcmp(str, "")) /* C-h */
1031 if (!strcmp(str, "\r")) /* C-m */
1032 return CONFIRM_CONTINUE;
1033 if (!strcmp(str, "")) /* C-p */
1035 if (!strcmp(str, "")) /* C-n */
1037 if (!strcmp(str, "")) /* C-c */
1039 if (!strcmp(str, "\t")) /* C-i */
1040 return TOGGLE_FIRST_SELECTED;
1043 *input = strdup(str);
1044 if (*input == NULL) {
1045 fprintf(stderr, "Error while allocating memory for key.\n");
1053 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1055 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1056 /* if there is something selected expand it and return */
1057 int index = cs->selected == -1 ? 0 : cs->selected;
1058 struct completion *c = cs->completions;
1072 if (*text == NULL) {
1073 fprintf(stderr, "Memory allocation error\n");
1077 *textlen = strlen(*text);
1081 if (!r->free_text) /* cannot accept arbitrary text */
1087 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1089 enum state status = LOOPING;
1091 while (status == LOOPING) {
1093 XNextEvent(r->d, &e);
1095 if (XFilterEvent(&e, r->w))
1100 XRefreshKeyboardMapping(&e.xmapping);
1105 if (e.xfocus.window != r->w)
1106 grabfocus(r->d, r->w);
1109 case VisibilityNotify:
1110 if (e.xvisibility.state != VisibilityUnobscured)
1111 XRaiseWindow(r->d, r->w);
1115 get_wh(r->d, &r->w, &r->width, &r->height);
1120 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1123 switch (parse_event(r->d, ev, r->xic, &input)) {
1130 confirm(&status, r, cs, text, textlen);
1134 case CONFIRM_CONTINUE: {
1136 confirm(&status, r, cs, text, textlen);
1141 complete(cs, r->first_selected, 1, text, textlen, &status);
1142 r->offset = cs->selected;
1147 complete(cs, r->first_selected, 0, text, textlen, &status);
1148 r->offset = cs->selected;
1154 update_completions(cs, *text, lines, vlines, r->first_selected);
1160 update_completions(cs, *text, lines, vlines, r->first_selected);
1166 for (i = 0; i < *textlen; ++i)
1168 update_completions(cs, *text, lines, vlines, r->first_selected);
1176 str_len = strlen(input);
1179 * sometimes a strange key is pressed
1180 * i.e. ctrl alone), so input will be
1181 * empty. Don't need to update
1182 * completion in that case
1187 for (i = 0; i < str_len; ++i) {
1188 *textlen = pushc(text, *textlen, input[i]);
1189 if (*textlen == -1) {
1190 fprintf(stderr, "Memory allocation error\n");
1196 if (status != ERR) {
1197 update_completions(cs, *text, lines, vlines, r->first_selected);
1205 case TOGGLE_FIRST_SELECTED:
1206 r->first_selected = !r->first_selected;
1207 if (r->first_selected && cs->selected < 0)
1209 if (!r->first_selected && cs->selected == 0)
1216 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1217 /* if (ev->button == Button1) { /\* click *\/ */
1218 /* int x = ev->x - r.border_w; */
1219 /* int y = ev->y - r.border_n; */
1220 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1223 if (ev->button == Button4) /* scroll up */
1224 r->offset = MAX((ssize_t)r->offset - 1, 0);
1226 if (ev->button == Button5) /* scroll down */
1227 r->offset = MIN(r->offset + 1, cs->length - 1);
1240 load_font(struct rendering *r, const char *fontname)
1243 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1246 char **missing_charset_list;
1247 int missing_charset_count;
1249 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1250 if (r->font != NULL)
1253 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1255 if (!strcmp(fontname, default_fontname))
1258 return load_font(r, default_fontname);
1263 xim_init(struct rendering *r, XrmDatabase *xdb)
1266 XIMStyle best_match_style;
1270 /* Open the X input method */
1271 xim = XOpenIM(r->d, *xdb, resname, resclass);
1272 check_allocation(xim);
1274 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1275 fprintf(stderr, "Input Styles could not be retrieved\n");
1276 exit(EX_UNAVAILABLE);
1279 best_match_style = 0;
1280 for (i = 0; i < xis->count_styles; ++i) {
1281 XIMStyle ts = xis->supported_styles[i];
1282 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1283 best_match_style = ts;
1289 if (!best_match_style)
1290 fprintf(stderr, "No matching input style could be determined\n");
1292 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1293 check_allocation(r->xic);
1297 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1299 XSetWindowAttributes attr;
1301 /* Create the window */
1302 attr.colormap = cmap;
1303 attr.override_redirect = 1;
1304 attr.border_pixel = 0;
1305 attr.background_pixel = 0x80808080;
1306 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1308 r->w = XCreateWindow(r->d,
1311 r->width, r->height,
1316 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1321 usage(char *prgname)
1323 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1324 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1325 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1326 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1330 main(int argc, char **argv)
1332 struct completions *cs;
1337 Window parent_window;
1339 unsigned long p_fg, compl_fg, compl_highlighted_fg;
1340 unsigned long p_bg, compl_bg, compl_highlighted_bg;
1341 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1344 int offset_x, offset_y, x, y;
1345 int textlen, d_width, d_height;
1347 char *sep, *parent_window_id;
1348 char **lines, *buf, **vlines;
1349 char *fontname, *text, *xrm;
1352 /* stdio & rpath: to read/write stdio/stdout/stderr */
1353 /* unix: to connect to XOrg */
1354 pledge("stdio rpath unix", "");
1358 parent_window_id = NULL;
1360 r.first_selected = 0;
1362 r.multiple_select = 0;
1365 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1367 case 'h': /* help */
1370 case 'v': /* version */
1371 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1373 case 'e': /* embed */
1374 parent_window_id = strdup(optarg);
1375 check_allocation(parent_window_id);
1378 sep = strdup(optarg);
1379 check_allocation(sep);
1386 r.multiple_select = 1;
1394 /* Read the completions */
1397 nlines = readlines(&lines, &buf);
1403 vlines = calloc(nlines, sizeof(char*));
1404 check_allocation(vlines);
1406 for (i = 0; i < nlines; i++) {
1408 t = strstr(lines[i], sep);
1410 vlines[i] = lines[i];
1416 setlocale(LC_ALL, getenv("LANG"));
1420 /* where the monitor start (used only with xinerama) */
1421 offset_x = offset_y = 0;
1423 /* default width and height */
1427 /* default position on the screen */
1430 /* default padding */
1433 /* default borders */
1434 r.border_n = r.border_e = r.border_s = r.border_w = 0;
1436 /* the prompt. We duplicate the string so later is easy to
1437 * free (in the case it's been overwritten by the user) */
1438 r.ps1 = strdup("$ ");
1439 check_allocation(r.ps1);
1441 /* same for the font name */
1442 fontname = strdup(default_fontname);
1443 check_allocation(fontname);
1446 text = malloc(textlen * sizeof(char));
1447 check_allocation(text);
1449 /* struct completions *cs = filter(text, lines); */
1450 cs = compls_new(nlines);
1451 check_allocation(cs);
1453 /* start talking to xorg */
1454 r.d = XOpenDisplay(NULL);
1456 fprintf(stderr, "Could not open display!\n");
1457 return EX_UNAVAILABLE;
1461 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1462 parent_window = DefaultRootWindow(r.d);
1466 /* get display size */
1467 get_wh(r.d, &parent_window, &d_width, &d_height);
1470 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1471 XineramaScreenInfo *info;
1474 int number_of_screens, monitors, i;
1475 int root_x, root_y, win_x, win_y;
1479 number_of_screens = XScreenCount(r.d);
1480 for (i = 0; i < number_of_screens; ++i) {
1481 root = XRootWindow(r.d, i);
1482 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1488 fprintf(stderr, "No mouse found.\n");
1493 /* Now find in which monitor the mice is */
1494 info = XineramaQueryScreens(r.d, &monitors);
1496 for (i = 0; i < monitors; ++i) {
1497 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1498 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1499 offset_x = info[i].x_org;
1500 offset_y = info[i].y_org;
1501 d_width = info[i].width;
1502 d_height = info[i].height;
1511 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1512 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1514 p_fg = compl_fg = parse_color("#fff", NULL);
1515 compl_highlighted_fg = parse_color("#000", NULL);
1517 p_bg = compl_bg = parse_color("#000", NULL);
1518 compl_highlighted_bg = parse_color("#fff", NULL);
1520 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", NULL);
1522 r.horizontal_layout = 1;
1524 /* Read the resources */
1526 xrm = XResourceManagerString(r.d);
1532 xdb = XrmGetStringDatabase(xrm);
1534 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1536 fontname = strdup(value.addr);
1537 check_allocation(fontname);
1539 fprintf(stderr, "no font defined, using %s\n", fontname);
1542 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1543 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1545 fprintf(stderr, "no layout defined, using horizontal\n");
1547 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1549 r.ps1 = normalize_str(value.addr);
1551 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1554 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1555 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1557 fprintf(stderr, "no width defined, using %d\n", r.width);
1559 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1560 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1562 fprintf(stderr, "no height defined, using %d\n", r.height);
1564 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1565 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1567 fprintf(stderr, "no x defined, using %d\n", x);
1569 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1570 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1572 fprintf(stderr, "no y defined, using %d\n", y);
1574 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1575 r.padding = parse_integer(value.addr, r.padding);
1577 fprintf(stderr, "no padding defined, using %d\n", r.padding);
1579 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1582 borders = parse_csslike(value.addr);
1583 if (borders != NULL) {
1584 r.border_n = parse_integer(borders[0], 0);
1585 r.border_e = parse_integer(borders[1], 0);
1586 r.border_s = parse_integer(borders[2], 0);
1587 r.border_w = parse_integer(borders[3], 0);
1589 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1591 fprintf(stderr, "no border defined, using 0.\n");
1594 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1595 p_fg = parse_color(value.addr, "#fff");
1597 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1598 p_bg = parse_color(value.addr, "#000");
1601 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1602 compl_fg = parse_color(value.addr, "#fff");
1604 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1605 compl_bg = parse_color(value.addr, "#000");
1607 compl_bg = parse_color("#000", NULL);
1609 /* Completion Highlighted */
1610 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1611 compl_highlighted_fg = parse_color(value.addr, "#000");
1613 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1614 compl_highlighted_bg = parse_color(value.addr, "#fff");
1616 compl_highlighted_bg = parse_color("#fff", NULL);
1619 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1621 colors = parse_csslike(value.addr);
1622 if (colors != NULL) {
1623 border_n_bg = parse_color(colors[0], "#000");
1624 border_e_bg = parse_color(colors[1], "#000");
1625 border_s_bg = parse_color(colors[2], "#000");
1626 border_w_bg = parse_color(colors[3], "#000");
1628 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1632 /* Second round of args parsing */
1633 optind = 0; /* reset the option index */
1634 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1637 r.first_selected = 1;
1640 /* free_text -- already catched */
1642 /* separator -- this case was already catched */
1644 /* embedding mymenu this case was already catched. */
1646 /* multiple selection this case was already catched. */
1650 newprompt = strdup(optarg);
1651 if (newprompt != NULL) {
1658 x = parse_int_with_pos(optarg, x, d_width, r.width);
1661 y = parse_int_with_pos(optarg, y, d_height, r.height);
1664 r.padding = parse_integer(optarg, r.padding);
1667 r.horizontal_layout = !strcmp(optarg, "horizontal");
1671 if ((newfont = strdup(optarg)) != NULL) {
1678 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1681 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1685 if ((borders = parse_csslike(optarg)) != NULL) {
1686 r.border_n = parse_integer(borders[0], 0);
1687 r.border_e = parse_integer(borders[1], 0);
1688 r.border_s = parse_integer(borders[2], 0);
1689 r.border_w = parse_integer(borders[3], 0);
1691 fprintf(stderr, "Error parsing b option\n");
1696 if ((colors = parse_csslike(optarg)) != NULL) {
1697 border_n_bg = parse_color(colors[0], "#000");
1698 border_e_bg = parse_color(colors[1], "#000");
1699 border_s_bg = parse_color(colors[2], "#000");
1700 border_w_bg = parse_color(colors[3], "#000");
1702 fprintf(stderr, "error while parsing B option\n");
1706 p_fg = parse_color(optarg, NULL);
1709 p_bg = parse_color(optarg, NULL);
1712 compl_fg = parse_color(optarg, NULL);
1715 compl_bg = parse_color(optarg, NULL);
1718 compl_highlighted_fg = parse_color(optarg, NULL);
1721 compl_highlighted_bg = parse_color(optarg, NULL);
1724 fprintf(stderr, "Unrecognized option %c\n", ch);
1730 /* since only now we know if the first should be selected,
1731 * update the completion here */
1732 update_completions(cs, text, lines, vlines, r.first_selected);
1734 /* update the prompt lenght, only now we surely know the length of it */
1735 r.ps1len = strlen(r.ps1);
1737 /* Create the window */
1738 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1739 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1740 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1741 XMapRaised(r.d, r.w);
1743 /* If embed, listen for other events as well */
1745 Window *children, parent, root;
1746 unsigned int children_no;
1748 XSelectInput(r.d, parent_window, FocusChangeMask);
1749 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1750 for (i = 0; i < children_no && children[i] != r.w; ++i)
1751 XSelectInput(r.d, children[i], FocusChangeMask);
1754 grabfocus(r.d, r.w);
1757 take_keyboard(r.d, r.w);
1759 r.x_zero = r.border_w;
1760 r.y_zero = r.border_n;
1765 r.prompt = XCreateGC(r.d, r.w, 0, &values),
1766 r.prompt_bg = XCreateGC(r.d, r.w, 0, &values);
1767 r.completion = XCreateGC(r.d, r.w, 0, &values);
1768 r.completion_bg = XCreateGC(r.d, r.w, 0, &values);
1769 r.completion_highlighted = XCreateGC(r.d, r.w, 0, &values);
1770 r.completion_highlighted_bg = XCreateGC(r.d, r.w, 0, &values);
1771 r.border_n_bg = XCreateGC(r.d, r.w, 0, &values);
1772 r.border_e_bg = XCreateGC(r.d, r.w, 0, &values);
1773 r.border_s_bg = XCreateGC(r.d, r.w, 0, &values);
1774 r.border_w_bg = XCreateGC(r.d, r.w, 0, &values);
1777 if (load_font(&r, fontname) == -1)
1781 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, DefaultColormap(r.d, 0));
1785 XRenderColor xrcolor;
1788 c = *(rgba_t*)&p_fg;
1789 xrcolor.red = EXPANDBITS(c.rgba.r);
1790 xrcolor.green = EXPANDBITS(c.rgba.g);
1791 xrcolor.blue = EXPANDBITS(c.rgba.b);
1792 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1793 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_prompt);
1796 c = *(rgba_t*)&compl_fg;
1797 xrcolor.red = EXPANDBITS(c.rgba.r);
1798 xrcolor.green = EXPANDBITS(c.rgba.g);
1799 xrcolor.blue = EXPANDBITS(c.rgba.b);
1800 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1801 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion);
1803 /* Completion highlighted */
1804 c = *(rgba_t*)&compl_highlighted_fg;
1805 xrcolor.red = EXPANDBITS(c.rgba.r);
1806 xrcolor.green = EXPANDBITS(c.rgba.g);
1807 xrcolor.blue = EXPANDBITS(c.rgba.b);
1808 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1809 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion_highlighted);
1813 /* Load the colors in our GCs */
1814 XSetForeground(r.d, r.prompt, p_fg);
1815 XSetForeground(r.d, r.prompt_bg, p_bg);
1816 XSetForeground(r.d, r.completion, compl_fg);
1817 XSetForeground(r.d, r.completion_bg, compl_bg);
1818 XSetForeground(r.d, r.completion_highlighted, compl_highlighted_fg);
1819 XSetForeground(r.d, r.completion_highlighted_bg, compl_highlighted_bg);
1820 XSetForeground(r.d, r.border_n_bg, border_n_bg);
1821 XSetForeground(r.d, r.border_e_bg, border_e_bg);
1822 XSetForeground(r.d, r.border_s_bg, border_s_bg);
1823 XSetForeground(r.d, r.border_w_bg, border_w_bg);
1827 /* Draw the window for the first time */
1831 while (status == LOOPING || status == OK_LOOP) {
1832 status = loop(&r, &text, &textlen, cs, lines, vlines);
1835 printf("%s\n", text);
1837 if (!r.multiple_select && status == OK_LOOP)
1841 XUngrabKeyboard(r.d, CurrentTime);
1844 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1845 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1846 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1858 XDestroyWindow(r.d, r.w);
1861 return status != OK;