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) (((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 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 */
117 short horizontal_layout;
122 int ps1w; /* ps1 width */
123 int ps1h; /* ps1 height */
134 XftColor xft_colors[3];
145 /* Wrap the linked list of completions */
147 struct completion *completions;
152 /* idea stolen from lemonbar. ty lemonboy */
166 /* Return a newly allocated (and empty) completion list */
168 compls_new(size_t length)
170 struct completions *cs = malloc(sizeof(struct completions));
175 cs->completions = calloc(length, sizeof(struct completion));
176 if (cs->completions == NULL) {
186 /* Delete the wrapper and the whole list */
188 compls_delete(struct completions *cs)
193 free(cs->completions);
198 * Create a completion list from a text and the list of possible
199 * completions (null terminated). Expects a non-null `cs'. `lines' and
200 * `vlines' should have the same length OR `vlines' is NULL.
203 filter(struct completions *cs, char *text, char **lines, char **vlines)
213 if (lines[index] == NULL)
216 l = vlines[index] != NULL ? vlines[index] : lines[index];
218 if (strcasestr(l, text) != NULL) {
219 struct completion *c = &cs->completions[matching];
221 c->rcompletion = lines[index];
227 cs->length = matching;
231 /* Update the given completion */
233 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
235 filter(cs, text, lines, vlines);
236 if (first_selected && cs->length > 0)
241 * Select the next or previous selection and update some state. `text'
242 * will be updated with the text of the completion and `textlen' with
243 * the new length. If the memory cannot be allocated `status' will be
247 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
249 struct completion *n;
252 if (cs == NULL || cs->length == 0)
256 * If the first is always selected and the first entry is
257 * different from the text, expand the text and return
261 && strcmp(cs->completions->completion, *text) != 0
264 *text = strdup(cs->completions->completion);
269 *textlen = strlen(*text);
273 index = cs->selected;
275 if (index == -1 && p)
277 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
279 n = &cs->completions[cs->selected];
282 *text = strdup(n->completion);
284 fprintf(stderr, "Memory allocation error!\n");
288 *textlen = strlen(*text);
291 /* Push the character c at the end of the string pointed by p */
293 pushc(char **p, int maxlen, char c)
297 len = strnlen(*p, maxlen);
298 if (!(len < maxlen -2)) {
301 maxlen += maxlen >> 1;
302 newptr = realloc(*p, maxlen);
303 if (newptr == NULL) /* bad */
314 * Remove the last rune from the *UTF-8* string! This is different
315 * from just setting the last byte to 0 (in some cases ofc). Return a
316 * pointer (e) to the last nonzero char. If e < p then p is empty!
336 * If c is a starting byte (11......) or is under
339 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
346 /* Remove the last word plus trailing white spaces from the given string */
353 if ((len = strlen(w)) == 0)
362 if (in_word && isspace(*e))
365 if (!in_word && !isspace(*e))
371 * If the string is surrounded by quates (`"') remove them and replace
372 * every `\"' in the string with a single double-quote.
375 normalize_str(const char *str)
380 if ((len = strlen(str)) == 0)
383 s = calloc(len, sizeof(char));
394 str += 2; /* skip this and the next char */
400 str++; /* skip only this char */
412 read_stdin(char **buf)
415 size_t len = STDIN_CHUNKS;
417 *buf = malloc(len * sizeof(char));
425 r = read(0, *buf + offset, STDIN_CHUNKS);
433 *buf = realloc(*buf, len);
437 for (i = offset; i < len; ++i)
442 fprintf(stderr, "Error in allocating memory for stdin.\n");
443 exit(EX_UNAVAILABLE);
447 readlines(char ***lns, char **buf)
449 size_t i, len, ll, lines;
455 len = read_stdin(buf);
458 *lns = malloc(ll * sizeof(char*));
463 for (i = 0; i < len; i++) {
472 if (in_line && c == '\n')
475 if (!in_line && c != '\n') {
477 (*lns)[lines] = (*buf) + i;
480 if (lines == ll) { /* resize */
482 *lns = realloc(*lns, ll * sizeof(char*));
489 (*lns)[lines] = NULL;
494 fprintf(stderr, "Error in memory allocation.\n");
495 exit(EX_UNAVAILABLE);
499 * Compute the dimensions of the string str once rendered.
500 * It'll return the width and set ret_width and ret_height if not NULL
503 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
509 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
510 height = r->font->ascent - r->font->descent;
511 width = gi.width - gi.x;
514 XmbTextExtents(r->font, str, len, NULL, &rect);
515 height = rect.height;
518 if (ret_width != NULL) *ret_width = width;
519 if (ret_height != NULL) *ret_height = height;
524 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
528 if (tt == PROMPT) xftcolor = r->xft_colors[0];
529 if (tt == COMPL) xftcolor = r->xft_colors[1];
530 if (tt == COMPL_HIGH) xftcolor = r->xft_colors[2];
532 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
535 if (tt == PROMPT) gc = r->fgs[0];
536 if (tt == COMPL) gc = r->fgs[1];
537 if (tt == COMPL_HIGH) gc = r->fgs[2];
538 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
542 /* Duplicate the string and substitute every space with a 'n` */
551 if (str == NULL || len == 0)
554 if ((dup = strdup(str)) == NULL)
557 for (i = 0; i < len; ++i)
564 /* ,-----------------------------------------------------------------, */
565 /* | 20 char text | completion | completion | completion | compl | */
566 /* `-----------------------------------------------------------------' */
568 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
571 int prompt_width, start_at;
574 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
576 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
577 start_at *= prompt_width;
578 start_at += r->padding;
580 texty = (inner_height(r) + r->ps1h + r->y_zero) / 2;
582 XFillRectangle(r->d, r->w, r->bgs[0], r->x_zero, r->y_zero, start_at, inner_height(r));
584 textlen = strlen(text);
585 if (textlen > prompt_width)
586 text = text + textlen - prompt_width;
588 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
589 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + r->ps1w, texty, r, PROMPT);
591 XFillRectangle(r->d, r->w, r->bgs[1], start_at, r->y_zero, r->width, inner_height(r));
593 for (i = r->offset; i < cs->length; ++i) {
594 struct completion *c;
599 c = &cs->completions[i];
600 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
601 h = cs->selected == (ssize_t)i ? r->bgs[2] : r->bgs[1];
602 len = strlen(c->completion);
603 text_width = text_extents(c->completion, len, r, NULL, NULL);
605 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
606 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
608 start_at += text_width + r->padding * 2;
610 if (start_at > inner_width(r))
611 break; /* don't draw completion out of the window */
615 /* ,-----------------------------------------------------------------, */
617 /* |-----------------------------------------------------------------| */
619 /* |-----------------------------------------------------------------| */
621 /* `-----------------------------------------------------------------' */
623 draw_vertically(struct rendering *r, char *text, struct completions *cs)
626 int height, start_at;
628 text_extents("fjpgl", 5, r, NULL, &height);
629 start_at = r->padding * 2 + height;
631 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, r->width, r->height);
632 XFillRectangle(r->d, r->w, r->bgs[0], r->x_zero, r->y_zero, r->width, start_at);
634 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
635 draw_string(text, strlen(text), r->x_zero + r->padding + r->ps1w, r->y_zero + height + r->padding, r, PROMPT);
637 start_at += r->y_zero;
639 for (i = r->offset; i < cs->length; ++i) {
640 struct completion *c;
645 c = &cs->completions[i];
646 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
647 h = cs->selected == (ssize_t)i ? r->bgs[2] : r->bgs[1];
648 len = strlen(c->completion);
650 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
651 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
653 start_at += height + r->padding * 2;
655 if (start_at > inner_height(r))
656 break; /* don't draw completion out of the window */
661 draw(struct rendering *r, char *text, struct completions *cs)
663 if (r->horizontal_layout)
664 draw_horizontally(r, text, cs);
666 draw_vertically(r, text, cs);
668 /* Draw the borders */
669 if (r->borders[0] != 0)
670 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
672 if (r->borders[1] != 0)
673 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0, r->borders[1], r->height);
675 if (r->borders[2] != 0)
676 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width, r->borders[2]);
678 if (r->borders[3] != 0)
679 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
685 /* Set some WM stuff */
687 set_win_atoms_hints(Display *d, Window w, int width, int height)
690 XClassHint *class_hint;
691 XSizeHints *size_hint;
693 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
696 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
697 XInternAtom(d, "ATOM", 0),
700 (unsigned char *)&type,
704 /* some window managers honor this properties */
705 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
708 XInternAtom(d, "_NET_WM_STATE", 0),
709 XInternAtom(d, "ATOM", 0),
712 (unsigned char *)&type,
716 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
719 XInternAtom(d, "_NET_WM_STATE", 0),
720 XInternAtom(d, "ATOM", 0),
723 (unsigned char *)&type,
727 /* Setting window hints */
728 class_hint = XAllocClassHint();
729 if (class_hint == NULL) {
730 fprintf(stderr, "Could not allocate memory for class hint\n");
731 exit(EX_UNAVAILABLE);
734 class_hint->res_name = resname;
735 class_hint->res_class = resclass;
736 XSetClassHint(d, w, class_hint);
739 size_hint = XAllocSizeHints();
740 if (size_hint == NULL) {
741 fprintf(stderr, "Could not allocate memory for size hint\n");
742 exit(EX_UNAVAILABLE);
745 size_hint->flags = PMinSize | PBaseSize;
746 size_hint->min_width = width;
747 size_hint->base_width = width;
748 size_hint->min_height = height;
749 size_hint->base_height = height;
754 /* Get the width and height of the window `w' */
756 get_wh(Display *d, Window *w, int *width, int *height)
758 XWindowAttributes win_attr;
760 XGetWindowAttributes(d, *w, &win_attr);
761 *height = win_attr.height;
762 *width = win_attr.width;
766 grabfocus(Display *d, Window w)
769 for (i = 0; i < 100; ++i) {
773 XGetInputFocus(d, &focuswin, &revert_to_win);
778 XSetInputFocus(d, w, RevertToParent, CurrentTime);
785 * I know this may seem a little hackish BUT is the only way I managed
786 * to actually grab that goddam keyboard. Only one call to
787 * XGrabKeyboard does not always end up with the keyboard grabbed!
790 take_keyboard(Display *d, Window w)
793 for (i = 0; i < 100; i++) {
794 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
798 fprintf(stderr, "Cannot grab keyboard\n");
803 parse_color(const char *str, const char *def)
814 /* +1 for the # ath the start */
815 if (*str != '#' || len > 9 || len < 4)
817 ++str; /* skip the # */
820 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
827 /* expand #rgb -> #rrggbb */
828 tmp.v = (tmp.v & 0xf00) * 0x1100
829 | (tmp.v & 0x0f0) * 0x0110
830 | (tmp.v & 0x00f) * 0x0011;
832 /* assume 0xff opacity */
835 } /* colors in #aarrggbb need no adjustments */
837 /* premultiply the alpha */
839 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
840 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
841 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
848 fprintf(stderr, "Invalid color: \"%s\".\n", str);
850 return parse_color(def, NULL);
856 * Given a string try to parse it as a number or return `default_value'.
859 parse_integer(const char *str, int default_value)
865 lval = strtol(str, &ep, 10);
867 if (str[0] == '\0' || *ep != '\0') { /* NaN */
868 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
869 return default_value;
872 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
873 (lval > INT_MAX || lval < INT_MIN)) {
874 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
875 return default_value;
881 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
883 parse_int_with_percentage(const char *str, int default_value, int max)
885 int len = strlen(str);
887 if (len > 0 && str[len-1] == '%') {
892 check_allocation(cpy);
894 val = parse_integer(cpy, default_value);
896 return val * max / 100;
899 return parse_integer(str, default_value);
903 * Like parse_int_with_percentage but understands some special values:
904 * - middle that is (max-self)/2
906 * - end that is (max-self)
909 parse_int_with_pos(const char *str, int default_value, int max, int self)
911 if (!strcmp(str, "start"))
913 if (!strcmp(str, "middle"))
914 return (max - self)/2;
915 if (!strcmp(str, "end"))
917 return parse_int_with_percentage(str, default_value, max);
920 /* Parse a string like a CSS value. */
921 /* TODO: harden a bit this function */
923 parse_csslike(const char *str)
926 char *s, *token, **ret;
933 ret = malloc(4 * sizeof(char*));
939 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
940 ret[i] = strdup(token);
943 for (j = 1; j < 4; j++)
944 ret[j] = strdup(ret[0]);
947 ret[2] = strdup(ret[0]);
948 ret[3] = strdup(ret[1]);
952 ret[3] = strdup(ret[1]);
954 /* before we didn't check for the return type of strdup, here we will */
957 for (i = 0; i < 4; ++i)
958 any_null = ret[i] == NULL || any_null;
961 for (i = 0; i < 4; ++i)
965 if (i == 0 || any_null) {
975 * Given an event, try to understand what the users wants. If the
976 * return value is ADD_CHAR then `input' is a pointer to a string that
977 * will need to be free'ed later.
980 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
982 char str[SYM_BUF_SIZE] = {0};
985 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
988 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
989 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
991 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
994 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
997 /* Try to read what key was pressed */
999 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1000 if (s == XBufferOverflow) {
1001 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1005 if (ev->state & ControlMask) {
1006 if (!strcmp(str, "")) /* C-u */
1008 if (!strcmp(str, "")) /* C-w */
1010 if (!strcmp(str, "")) /* C-h */
1012 if (!strcmp(str, "\r")) /* C-m */
1013 return CONFIRM_CONTINUE;
1014 if (!strcmp(str, "")) /* C-p */
1016 if (!strcmp(str, "")) /* C-n */
1018 if (!strcmp(str, "")) /* C-c */
1020 if (!strcmp(str, "\t")) /* C-i */
1021 return TOGGLE_FIRST_SELECTED;
1024 *input = strdup(str);
1025 if (*input == NULL) {
1026 fprintf(stderr, "Error while allocating memory for key.\n");
1034 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1036 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1037 /* if there is something selected expand it and return */
1038 int index = cs->selected == -1 ? 0 : cs->selected;
1039 struct completion *c = cs->completions;
1053 if (*text == NULL) {
1054 fprintf(stderr, "Memory allocation error\n");
1058 *textlen = strlen(*text);
1062 if (!r->free_text) /* cannot accept arbitrary text */
1068 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1070 enum state status = LOOPING;
1072 while (status == LOOPING) {
1074 XNextEvent(r->d, &e);
1076 if (XFilterEvent(&e, r->w))
1081 XRefreshKeyboardMapping(&e.xmapping);
1086 if (e.xfocus.window != r->w)
1087 grabfocus(r->d, r->w);
1090 case VisibilityNotify:
1091 if (e.xvisibility.state != VisibilityUnobscured)
1092 XRaiseWindow(r->d, r->w);
1096 get_wh(r->d, &r->w, &r->width, &r->height);
1101 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1104 switch (parse_event(r->d, ev, r->xic, &input)) {
1111 confirm(&status, r, cs, text, textlen);
1115 case CONFIRM_CONTINUE: {
1117 confirm(&status, r, cs, text, textlen);
1122 complete(cs, r->first_selected, 1, text, textlen, &status);
1123 r->offset = cs->selected;
1128 complete(cs, r->first_selected, 0, text, textlen, &status);
1129 r->offset = cs->selected;
1135 update_completions(cs, *text, lines, vlines, r->first_selected);
1141 update_completions(cs, *text, lines, vlines, r->first_selected);
1147 for (i = 0; i < *textlen; ++i)
1149 update_completions(cs, *text, lines, vlines, r->first_selected);
1157 str_len = strlen(input);
1160 * sometimes a strange key is pressed
1161 * i.e. ctrl alone), so input will be
1162 * empty. Don't need to update
1163 * completion in that case
1168 for (i = 0; i < str_len; ++i) {
1169 *textlen = pushc(text, *textlen, input[i]);
1170 if (*textlen == -1) {
1171 fprintf(stderr, "Memory allocation error\n");
1177 if (status != ERR) {
1178 update_completions(cs, *text, lines, vlines, r->first_selected);
1186 case TOGGLE_FIRST_SELECTED:
1187 r->first_selected = !r->first_selected;
1188 if (r->first_selected && cs->selected < 0)
1190 if (!r->first_selected && cs->selected == 0)
1197 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1198 /* if (ev->button == Button1) { /\* click *\/ */
1199 /* int x = ev->x - r.border_w; */
1200 /* int y = ev->y - r.border_n; */
1201 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1204 if (ev->button == Button4) /* scroll up */
1205 r->offset = MAX((ssize_t)r->offset - 1, 0);
1207 if (ev->button == Button5) /* scroll down */
1208 r->offset = MIN(r->offset + 1, cs->length - 1);
1221 load_font(struct rendering *r, const char *fontname)
1224 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1227 char **missing_charset_list;
1228 int missing_charset_count;
1230 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1231 if (r->font != NULL)
1234 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1236 if (!strcmp(fontname, default_fontname))
1239 return load_font(r, default_fontname);
1244 xim_init(struct rendering *r, XrmDatabase *xdb)
1247 XIMStyle best_match_style;
1251 /* Open the X input method */
1252 xim = XOpenIM(r->d, *xdb, resname, resclass);
1253 check_allocation(xim);
1255 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1256 fprintf(stderr, "Input Styles could not be retrieved\n");
1257 exit(EX_UNAVAILABLE);
1260 best_match_style = 0;
1261 for (i = 0; i < xis->count_styles; ++i) {
1262 XIMStyle ts = xis->supported_styles[i];
1263 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1264 best_match_style = ts;
1270 if (!best_match_style)
1271 fprintf(stderr, "No matching input style could be determined\n");
1273 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1274 check_allocation(r->xic);
1278 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1280 XSetWindowAttributes attr;
1282 /* Create the window */
1283 attr.colormap = cmap;
1284 attr.override_redirect = 1;
1285 attr.border_pixel = 0;
1286 attr.background_pixel = 0x80808080;
1287 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1289 r->w = XCreateWindow(r->d,
1292 r->width, r->height,
1297 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1302 ps1extents(struct rendering *r)
1305 dup = strdupn(r->ps1);
1306 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1311 usage(char *prgname)
1313 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1314 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1315 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1316 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1320 main(int argc, char **argv)
1322 struct completions *cs;
1327 Window parent_window;
1329 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1330 unsigned long borders_bg[4]; /* N E S W */
1333 int offset_x, offset_y, x, y;
1334 int textlen, d_width, d_height;
1336 char *sep, *parent_window_id;
1337 char **lines, *buf, **vlines;
1338 char *fontname, *text, *xrm;
1341 /* stdio & rpath: to read/write stdio/stdout/stderr */
1342 /* unix: to connect to XOrg */
1343 pledge("stdio rpath unix", "");
1347 parent_window_id = NULL;
1349 r.first_selected = 0;
1351 r.multiple_select = 0;
1354 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1356 case 'h': /* help */
1359 case 'v': /* version */
1360 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1362 case 'e': /* embed */
1363 parent_window_id = strdup(optarg);
1364 check_allocation(parent_window_id);
1367 sep = strdup(optarg);
1368 check_allocation(sep);
1373 r.multiple_select = 1;
1380 /* Read the completions */
1383 nlines = readlines(&lines, &buf);
1389 vlines = calloc(nlines, sizeof(char*));
1390 check_allocation(vlines);
1392 for (i = 0; i < nlines; i++) {
1394 t = strstr(lines[i], sep);
1396 vlines[i] = lines[i];
1402 setlocale(LC_ALL, getenv("LANG"));
1406 /* where the monitor start (used only with xinerama) */
1407 offset_x = offset_y = 0;
1409 /* default width and height */
1413 /* default position on the screen */
1416 /* default padding */
1419 /* default borders */
1420 r.borders[0] = r.borders[1] = r.borders[2] = r.borders[3] = 0;
1422 /* the prompt. We duplicate the string so later is easy to
1423 * free (in the case it's been overwritten by the user) */
1424 r.ps1 = strdup("$ ");
1425 check_allocation(r.ps1);
1427 /* same for the font name */
1428 fontname = strdup(default_fontname);
1429 check_allocation(fontname);
1432 text = malloc(textlen * sizeof(char));
1433 check_allocation(text);
1435 /* struct completions *cs = filter(text, lines); */
1436 cs = compls_new(nlines);
1437 check_allocation(cs);
1439 /* start talking to xorg */
1440 r.d = XOpenDisplay(NULL);
1442 fprintf(stderr, "Could not open display!\n");
1443 return EX_UNAVAILABLE;
1447 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1448 parent_window = DefaultRootWindow(r.d);
1452 /* get display size */
1453 get_wh(r.d, &parent_window, &d_width, &d_height);
1456 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1457 XineramaScreenInfo *info;
1460 int number_of_screens, monitors, i;
1461 int root_x, root_y, win_x, win_y;
1465 number_of_screens = XScreenCount(r.d);
1466 for (i = 0; i < number_of_screens; ++i) {
1467 root = XRootWindow(r.d, i);
1468 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1474 fprintf(stderr, "No mouse found.\n");
1479 /* Now find in which monitor the mice is */
1480 info = XineramaQueryScreens(r.d, &monitors);
1482 for (i = 0; i < monitors; ++i) {
1483 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1484 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1485 offset_x = info[i].x_org;
1486 offset_y = info[i].y_org;
1487 d_width = info[i].width;
1488 d_height = info[i].height;
1497 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1498 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1500 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1501 fgs[2] = parse_color("#000", NULL);
1503 bgs[0] = bgs[1] = parse_color("#000", NULL);
1504 bgs[2] = parse_color("#fff", NULL);
1506 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1508 r.horizontal_layout = 1;
1510 /* Read the resources */
1512 xrm = XResourceManagerString(r.d);
1518 xdb = XrmGetStringDatabase(xrm);
1520 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1522 fontname = strdup(value.addr);
1523 check_allocation(fontname);
1525 fprintf(stderr, "no font defined, using %s\n", fontname);
1528 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1529 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1531 fprintf(stderr, "no layout defined, using horizontal\n");
1533 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1535 r.ps1 = normalize_str(value.addr);
1537 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1540 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1541 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1543 fprintf(stderr, "no width defined, using %d\n", r.width);
1545 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1546 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1548 fprintf(stderr, "no height defined, using %d\n", r.height);
1550 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1551 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1553 fprintf(stderr, "no x defined, using %d\n", x);
1555 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1556 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1558 fprintf(stderr, "no y defined, using %d\n", y);
1560 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1561 r.padding = parse_integer(value.addr, r.padding);
1563 fprintf(stderr, "no padding defined, using %d\n", r.padding);
1565 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1568 borders = parse_csslike(value.addr);
1569 if (borders != NULL) {
1570 r.borders[0] = parse_integer(borders[0], 0);
1571 r.borders[1] = parse_integer(borders[1], 0);
1572 r.borders[2] = parse_integer(borders[2], 0);
1573 r.borders[3] = parse_integer(borders[3], 0);
1575 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1577 fprintf(stderr, "no border defined, using 0.\n");
1580 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1581 fgs[0] = parse_color(value.addr, "#fff");
1583 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1584 bgs[0] = parse_color(value.addr, "#000");
1587 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1588 fgs[1] = parse_color(value.addr, "#fff");
1590 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1591 bgs[1] = parse_color(value.addr, "#000");
1593 /* Completion Highlighted */
1594 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1595 fgs[2] = parse_color(value.addr, "#000");
1597 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1598 bgs[2] = parse_color(value.addr, "#fff");
1601 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1603 colors = parse_csslike(value.addr);
1604 if (colors != NULL) {
1605 borders_bg[0] = parse_color(colors[0], "#000");
1606 borders_bg[1] = parse_color(colors[1], "#000");
1607 borders_bg[2] = parse_color(colors[2], "#000");
1608 borders_bg[3] = parse_color(colors[3], "#000");
1610 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1614 /* Second round of args parsing */
1615 optind = 0; /* reset the option index */
1616 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1619 r.first_selected = 1;
1622 /* free_text -- already catched */
1624 /* separator -- this case was already catched */
1626 /* embedding mymenu this case was already catched. */
1628 /* multiple selection this case was already catched. */
1632 newprompt = strdup(optarg);
1633 if (newprompt != NULL) {
1640 x = parse_int_with_pos(optarg, x, d_width, r.width);
1643 y = parse_int_with_pos(optarg, y, d_height, r.height);
1646 r.padding = parse_integer(optarg, r.padding);
1649 r.horizontal_layout = !strcmp(optarg, "horizontal");
1653 if ((newfont = strdup(optarg)) != NULL) {
1660 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1663 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1667 if ((borders = parse_csslike(optarg)) != NULL) {
1668 r.borders[0] = parse_integer(borders[0], 0);
1669 r.borders[1] = parse_integer(borders[1], 0);
1670 r.borders[2] = parse_integer(borders[2], 0);
1671 r.borders[3] = parse_integer(borders[3], 0);
1673 fprintf(stderr, "Error parsing b option\n");
1678 if ((colors = parse_csslike(optarg)) != NULL) {
1679 borders_bg[0] = parse_color(colors[0], "#000");
1680 borders_bg[1] = parse_color(colors[1], "#000");
1681 borders_bg[2] = parse_color(colors[2], "#000");
1682 borders_bg[3] = parse_color(colors[3], "#000");
1684 fprintf(stderr, "error while parsing B option\n");
1688 fgs[0] = parse_color(optarg, NULL);
1691 bgs[0] = parse_color(optarg, NULL);
1694 fgs[1] = parse_color(optarg, NULL);
1697 bgs[1] = parse_color(optarg, NULL);
1700 fgs[2] = parse_color(optarg, NULL);
1703 fgs[2] = parse_color(optarg, NULL);
1706 fprintf(stderr, "Unrecognized option %c\n", ch);
1712 /* since only now we know if the first should be selected,
1713 * update the completion here */
1714 update_completions(cs, text, lines, vlines, r.first_selected);
1716 /* update the prompt lenght, only now we surely know the length of it */
1717 r.ps1len = strlen(r.ps1);
1719 /* Create the window */
1720 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1721 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1722 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1723 XMapRaised(r.d, r.w);
1725 /* If embed, listen for other events as well */
1727 Window *children, parent, root;
1728 unsigned int children_no;
1730 XSelectInput(r.d, parent_window, FocusChangeMask);
1731 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1732 for (i = 0; i < children_no && children[i] != r.w; ++i)
1733 XSelectInput(r.d, children[i], FocusChangeMask);
1736 grabfocus(r.d, r.w);
1739 take_keyboard(r.d, r.w);
1741 r.x_zero = r.borders[3];
1742 r.y_zero = r.borders[0];
1747 r.fgs[0] = XCreateGC(r.d, r.w, 0, &values),
1748 r.fgs[1] = XCreateGC(r.d, r.w, 0, &values),
1749 r.fgs[2] = XCreateGC(r.d, r.w, 0, &values),
1750 r.bgs[0] = XCreateGC(r.d, r.w, 0, &values),
1751 r.bgs[1] = XCreateGC(r.d, r.w, 0, &values),
1752 r.bgs[2] = XCreateGC(r.d, r.w, 0, &values),
1753 r.borders_bg[0] = XCreateGC(r.d, r.w, 0, &values);
1754 r.borders_bg[1] = XCreateGC(r.d, r.w, 0, &values);
1755 r.borders_bg[2] = XCreateGC(r.d, r.w, 0, &values);
1756 r.borders_bg[3] = XCreateGC(r.d, r.w, 0, &values);
1759 if (load_font(&r, fontname) == -1)
1763 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, DefaultColormap(r.d, 0));
1767 XRenderColor xrcolor;
1770 c = *(rgba_t*)&fgs[0];
1771 xrcolor.red = EXPANDBITS(c.rgba.r);
1772 xrcolor.green = EXPANDBITS(c.rgba.g);
1773 xrcolor.blue = EXPANDBITS(c.rgba.b);
1774 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1775 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[0]);
1778 c = *(rgba_t*)&fgs[1];
1779 xrcolor.red = EXPANDBITS(c.rgba.r);
1780 xrcolor.green = EXPANDBITS(c.rgba.g);
1781 xrcolor.blue = EXPANDBITS(c.rgba.b);
1782 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1783 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[1]);
1785 /* Completion highlighted */
1786 c = *(rgba_t*)&fgs[2];
1787 xrcolor.red = EXPANDBITS(c.rgba.r);
1788 xrcolor.green = EXPANDBITS(c.rgba.g);
1789 xrcolor.blue = EXPANDBITS(c.rgba.b);
1790 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1791 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[2]);
1795 /* Load the colors in our GCs */
1796 XSetForeground(r.d, r.fgs[0], fgs[0]);
1797 XSetForeground(r.d, r.bgs[0], bgs[0]);
1798 XSetForeground(r.d, r.fgs[1], fgs[1]);
1799 XSetForeground(r.d, r.bgs[1], bgs[1]);
1800 XSetForeground(r.d, r.fgs[2], fgs[2]);
1801 XSetForeground(r.d, r.bgs[2], bgs[2]);
1802 XSetForeground(r.d, r.borders_bg[0], borders_bg[0]);
1803 XSetForeground(r.d, r.borders_bg[1], borders_bg[1]);
1804 XSetForeground(r.d, r.borders_bg[2], borders_bg[2]);
1805 XSetForeground(r.d, r.borders_bg[3], borders_bg[3]);
1807 /* compute prompt dimensions */
1813 /* Now we need only the ability to write */
1814 pledge("stdio", "");
1817 /* Draw the window for the first time */
1821 while (status == LOOPING || status == OK_LOOP) {
1822 status = loop(&r, &text, &textlen, cs, lines, vlines);
1825 printf("%s\n", text);
1827 if (!r.multiple_select && status == OK_LOOP)
1831 XUngrabKeyboard(r.d, CurrentTime);
1834 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[0]);
1835 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[1]);
1836 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[2]);
1848 XDestroyWindow(r.d, r.w);
1851 return status != OK;