1 #include <ctype.h> /* isalnum */
5 #include <locale.h> /* setlocale */
9 #include <string.h> /* strdup, strlen */
15 #include <X11/Xresource.h>
16 #include <X11/Xutil.h>
17 #include <X11/keysym.h>
18 #include <X11/Xft/Xft.h>
20 #include <X11/extensions/Xinerama.h>
23 #define VERSION "unknown"
26 #define resname "MyMenu"
27 #define resclass "mymenu"
29 #define SYM_BUF_SIZE 4
31 #define default_fontname "monospace"
33 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:G:g:I:i:J:j:"
35 #define MIN(a, b) ((a) < (b) ? (a) : (b))
36 #define MAX(a, b) ((a) > (b) ? (a) : (b))
38 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
41 * If we don't have or we don't want an "ignore case" completion
42 * style, fall back to `strstr(3)`
44 #ifndef USE_STRCASESTR
45 #define strcasestr strstr
48 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
49 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
51 /* The states of the event loop */
52 enum state { LOOPING, OK_LOOP, OK, ERR };
55 * For the drawing-related function. The text to be rendere could be
56 * the prompt, a completion or a highlighted completion
58 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
60 /* These are the possible action to be performed after user input. */
72 TOGGLE_FIRST_SELECTED,
77 /* A big set of values that needs to be carried around for drawing. A
78 * big struct to rule them all */
80 Display *d; /* Connection to xorg */
88 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
90 int y_zero; /* like x_zero but for the y axis */
92 int offset; /* scroll offset */
96 short multiple_select;
98 /* four border width */
104 short horizontal_layout;
109 int ps1w; /* ps1 width */
110 int ps1h; /* ps1 height */
112 int text_height; /* cache for the vertical layout */
125 XftColor xft_colors[3];
131 int offset; /* the x (or y, depending on the layout) coordinate at
132 which the item is rendered */
135 /* Wrap the linked list of completions */
137 struct completion *completions;
142 /* idea stolen from lemonbar. ty lemonboy */
156 /* Return a newly allocated (and empty) completion list */
158 compls_new(size_t length)
160 struct completions *cs = malloc(sizeof(struct completions));
165 cs->completions = calloc(length, sizeof(struct completion));
166 if (cs->completions == NULL) {
176 /* Delete the wrapper and the whole list */
178 compls_delete(struct completions *cs)
183 free(cs->completions);
188 * Create a completion list from a text and the list of possible
189 * completions (null terminated). Expects a non-null `cs'. `lines' and
190 * `vlines' should have the same length OR `vlines' is NULL.
193 filter(struct completions *cs, char *text, char **lines, char **vlines)
203 if (lines[index] == NULL)
206 l = vlines[index] != NULL ? vlines[index] : lines[index];
208 if (strcasestr(l, text) != NULL) {
209 struct completion *c = &cs->completions[matching];
211 c->rcompletion = lines[index];
217 cs->length = matching;
221 /* Update the given completion */
224 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
226 filter(cs, text, lines, vlines);
227 if (first_selected && cs->length > 0)
232 * Select the next or previous selection and update some state. `text'
233 * will be updated with the text of the completion and `textlen' with
234 * the new length. If the memory cannot be allocated `status' will be
238 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
241 struct completion *n;
244 if (cs == NULL || cs->length == 0)
248 * If the first is always selected and the first entry is
249 * different from the text, expand the text and return
251 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
254 *text = strdup(cs->completions->completion);
259 *textlen = strlen(*text);
263 index = cs->selected;
265 if (index == -1 && p)
267 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
269 n = &cs->completions[cs->selected];
272 *text = strdup(n->completion);
274 fprintf(stderr, "Memory allocation error!\n");
278 *textlen = strlen(*text);
281 /* Push the character c at the end of the string pointed by p */
283 pushc(char **p, int maxlen, char c)
287 len = strnlen(*p, maxlen);
288 if (!(len < maxlen - 2)) {
291 maxlen += maxlen >> 1;
292 newptr = realloc(*p, maxlen);
293 if (newptr == NULL) /* bad */
299 (*p)[len + 1] = '\0';
304 * Remove the last rune from the *UTF-8* string! This is different
305 * from just setting the last byte to 0 (in some cases ofc). Return a
306 * pointer (e) to the last nonzero char. If e < p then p is empty!
326 * If c is a starting byte (11......) or is under
329 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
336 /* Remove the last word plus trailing white spaces from the given string */
343 if ((len = strlen(w)) == 0)
352 if (in_word && isspace(*e))
355 if (!in_word && !isspace(*e))
361 * If the string is surrounded by quates (`"') remove them and replace
362 * every `\"' in the string with a single double-quote.
365 normalize_str(const char *str)
370 if ((len = strlen(str)) == 0)
373 if ((s = calloc(len, sizeof(char))) == NULL)
384 str += 2; /* skip this and the next char */
390 str++; /* skip only this char */
402 readlines(size_t *lineslen)
404 size_t len = 0, cap = 0;
407 char *line = NULL, **lines = NULL;
409 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
410 if (linelen != 0 && line[linelen-1] == '\n')
411 line[linelen-1] = '\0';
417 newcap = MAX(cap * 1.5, 32);
418 t = recallocarray(lines, cap, newcap, sizeof(char *));
420 err(1, "recallocarray");
425 if ((lines[len++] = strdup(line)) == NULL)
438 * Compute the dimensions of the string str once rendered.
439 * It'll return the width and set ret_width and ret_height if not NULL
442 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
446 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
447 height = r->font->ascent - r->font->descent;
448 width = gi.width - gi.x;
450 if (ret_width != NULL)
452 if (ret_height != NULL)
453 *ret_height = height;
458 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
462 xftcolor = r->xft_colors[0];
464 xftcolor = r->xft_colors[1];
465 if (tt == COMPL_HIGH)
466 xftcolor = r->xft_colors[2];
468 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
471 /* Duplicate the string and substitute every space with a 'n` */
480 if (str == NULL || len == 0)
483 if ((dup = strdup(str)) == NULL)
486 for (i = 0; i < len; ++i)
494 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
496 GC *border_color, bg;
497 int *padding, *borders;
498 int ret = 0, inner_width, inner_height, x;
502 border_color = r->p_borders_bg;
503 padding = r->p_padding;
504 borders = r->p_borders;
508 border_color = r->c_borders_bg;
509 padding = r->c_padding;
510 borders = r->c_borders;
514 border_color = r->ch_borders_bg;
515 padding = r->ch_padding;
516 borders = r->ch_borders;
521 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
523 inner_width = inner_width(r) - borders[1] - borders[3];
524 inner_height = padding[0] + r->text_height + padding[2];
527 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
530 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1], y,
534 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
535 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
538 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
541 x = r->x_zero + borders[3];
543 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
546 y += padding[0] + r->text_height;
548 if (prefix != NULL) {
549 draw_string(prefix, strlen(prefix), x, y, r, t);
552 draw_string(text, strlen(text), x, y, r, t);
558 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
560 GC *border_color, bg;
561 int *padding, *borders;
562 int ret = 0, inner_width, inner_height, y, text_width;
566 border_color = r->p_borders_bg;
567 padding = r->p_padding;
568 borders = r->p_borders;
572 border_color = r->c_borders_bg;
573 padding = r->c_padding;
574 borders = r->c_borders;
578 border_color = r->ch_borders_bg;
579 padding = r->ch_padding;
580 borders = r->ch_borders;
585 if (padding[0] < 0 || padding[2] < 0)
586 padding[0] = padding[2]
587 = (inner_height(r) - borders[0] - borders[2] - r->text_height) / 2;
589 /* If they are still lesser than 0, set 'em to 0 */
590 if (padding[0] < 0 || padding[2] < 0)
591 padding[0] = padding[2] = 0;
593 /* Get the text width */
594 text_extents(text, strlen(text), r, &text_width, NULL);
596 text_width += prefix_width;
598 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
600 inner_width = padding[3] + text_width + padding[1];
601 inner_height = inner_height(r) - borders[0] - borders[2];
604 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
607 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
608 borders[1], inner_height(r));
611 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2],
615 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
619 y = r->y_zero + borders[0];
620 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
623 y += padding[0] + r->text_height;
625 if (prefix != NULL) {
626 draw_string(prefix, strlen(prefix), x, y, r, t);
629 draw_string(text, strlen(text), x, y, r, t);
634 /* ,-----------------------------------------------------------------, */
635 /* | 20 char text | completion | completion | completion | compl | */
636 /* `-----------------------------------------------------------------' */
638 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
643 /* Draw the prompt */
644 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
646 for (i = r->offset; i < cs->length; ++i) {
647 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
649 cs->completions[i].offset = x;
651 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
653 if (x > inner_width(r))
657 for (i += 1; i < cs->length; ++i)
658 cs->completions[i].offset = -1;
661 /* ,-----------------------------------------------------------------, */
663 /* |-----------------------------------------------------------------| */
665 /* |-----------------------------------------------------------------| */
667 /* `-----------------------------------------------------------------' */
669 draw_vertically(struct rendering *r, char *text, struct completions *cs)
674 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
676 for (i = r->offset; i < cs->length; ++i) {
677 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
679 cs->completions[i].offset = y;
681 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
683 if (y > inner_height(r))
687 for (i += 1; i < cs->length; ++i)
688 cs->completions[i].offset = -1;
692 draw(struct rendering *r, char *text, struct completions *cs)
694 /* Draw the background */
696 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
698 /* Draw the contents */
699 if (r->horizontal_layout)
700 draw_horizontally(r, text, cs);
702 draw_vertically(r, text, cs);
704 /* Draw the borders */
705 if (r->borders[0] != 0)
706 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
708 if (r->borders[1] != 0)
709 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
710 r->borders[1], r->height);
712 if (r->borders[2] != 0)
713 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
716 if (r->borders[3] != 0)
717 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
723 /* Set some WM stuff */
725 set_win_atoms_hints(Display *d, Window w, int width, int height)
728 XClassHint *class_hint;
729 XSizeHints *size_hint;
731 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
732 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
733 32, PropModeReplace, (unsigned char *)&type, 1);
735 /* some window managers honor this properties */
736 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
737 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
738 PropModeReplace, (unsigned char *)&type, 1);
740 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
741 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
742 PropModeAppend, (unsigned char *)&type, 1);
744 /* Setting window hints */
745 class_hint = XAllocClassHint();
746 if (class_hint == NULL) {
747 fprintf(stderr, "Could not allocate memory for class hint\n");
748 exit(EX_UNAVAILABLE);
751 class_hint->res_name = resname;
752 class_hint->res_class = resclass;
753 XSetClassHint(d, w, class_hint);
756 size_hint = XAllocSizeHints();
757 if (size_hint == NULL) {
758 fprintf(stderr, "Could not allocate memory for size hint\n");
759 exit(EX_UNAVAILABLE);
762 size_hint->flags = PMinSize | PBaseSize;
763 size_hint->min_width = width;
764 size_hint->base_width = width;
765 size_hint->min_height = height;
766 size_hint->base_height = height;
771 /* Get the width and height of the window `w' */
773 get_wh(Display *d, Window *w, int *width, int *height)
775 XWindowAttributes win_attr;
777 XGetWindowAttributes(d, *w, &win_attr);
778 *height = win_attr.height;
779 *width = win_attr.width;
783 grabfocus(Display *d, Window w)
786 for (i = 0; i < 100; ++i) {
790 XGetInputFocus(d, &focuswin, &revert_to_win);
795 XSetInputFocus(d, w, RevertToParent, CurrentTime);
802 * I know this may seem a little hackish BUT is the only way I managed
803 * to actually grab that goddam keyboard. Only one call to
804 * XGrabKeyboard does not always end up with the keyboard grabbed!
807 take_keyboard(Display *d, Window w)
810 for (i = 0; i < 100; i++) {
811 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
816 fprintf(stderr, "Cannot grab keyboard\n");
821 parse_color(const char *str, const char *def)
832 /* +1 for the # ath the start */
833 if (*str != '#' || len > 9 || len < 4)
835 ++str; /* skip the # */
838 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
845 /* expand #rgb -> #rrggbb */
846 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
847 | (tmp.v & 0x00f) * 0x0011;
849 /* assume 0xff opacity */
852 } /* colors in #aarrggbb need no adjustments */
854 /* premultiply the alpha */
856 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
857 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
858 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
865 fprintf(stderr, "Invalid color: \"%s\".\n", str);
867 return parse_color(def, NULL);
873 * Given a string try to parse it as a number or return `default_value'.
876 parse_integer(const char *str, int default_value)
882 lval = strtol(str, &ep, 10);
884 if (str[0] == '\0' || *ep != '\0') { /* NaN */
885 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str,
887 return default_value;
890 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
891 || (lval > INT_MAX || lval < INT_MIN)) {
892 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
893 return default_value;
899 /* 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] == '%') {
910 if ((cpy = strdup(str)) == NULL)
914 val = parse_integer(cpy, default_value);
916 return val * max / 100;
919 return parse_integer(str, default_value);
923 get_mouse_coords(Display *d, int *x, int *y)
930 root = DefaultRootWindow(d);
932 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
933 for (i = 0; i < ScreenCount(d); ++i) {
934 if (root == RootWindow(d, i))
941 * Like parse_int_with_percentage but understands some special values:
942 * - middle that is (max-self)/2
945 * - end that is (max-self)
946 * - mx x coordinate of the mouse
947 * - my y coordinate of the mouse
950 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
952 if (!strcmp(str, "start"))
954 if (!strcmp(str, "middle") || !strcmp(str, "center"))
955 return (max - self) / 2;
956 if (!strcmp(str, "end"))
958 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
961 get_mouse_coords(d, &x, &y);
962 if (!strcmp(str, "mx"))
967 return parse_int_with_percentage(str, default_value, max);
970 /* Parse a string like a CSS value. */
971 /* TODO: harden a bit this function */
973 parse_csslike(const char *str)
976 char *s, *token, **ret;
983 ret = malloc(4 * sizeof(char *));
989 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
990 ret[i] = strdup(token);
993 for (j = 1; j < 4; j++)
994 ret[j] = strdup(ret[0]);
997 ret[2] = strdup(ret[0]);
998 ret[3] = strdup(ret[1]);
1002 ret[3] = strdup(ret[1]);
1004 /* before we didn't check for the return type of strdup, here we will
1008 for (i = 0; i < 4; ++i)
1009 any_null = ret[i] == NULL || any_null;
1012 for (i = 0; i < 4; ++i)
1016 if (i == 0 || any_null) {
1026 * Given an event, try to understand what the users wants. If the
1027 * return value is ADD_CHAR then `input' is a pointer to a string that
1028 * will need to be free'ed later.
1031 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1033 char str[SYM_BUF_SIZE] = { 0 };
1036 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1039 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1040 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1042 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1045 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1048 /* Try to read what key was pressed */
1050 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1051 if (s == XBufferOverflow) {
1053 "Buffer overflow when trying to create keyboard "
1058 if (ev->state & ControlMask) {
1059 if (!strcmp(str, "")) /* C-u */
1061 if (!strcmp(str, "")) /* C-w */
1063 if (!strcmp(str, "")) /* C-h */
1065 if (!strcmp(str, "\r")) /* C-m */
1066 return CONFIRM_CONTINUE;
1067 if (!strcmp(str, "")) /* C-p */
1069 if (!strcmp(str, "")) /* C-n */
1071 if (!strcmp(str, "")) /* C-c */
1073 if (!strcmp(str, "\t")) /* C-i */
1074 return TOGGLE_FIRST_SELECTED;
1077 *input = strdup(str);
1078 if (*input == NULL) {
1079 fprintf(stderr, "Error while allocating memory for key.\n");
1087 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1089 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1090 /* if there is something selected expand it and return */
1091 int index = cs->selected == -1 ? 0 : cs->selected;
1092 struct completion *c = cs->completions;
1106 if (*text == NULL) {
1107 fprintf(stderr, "Memory allocation error\n");
1111 *textlen = strlen(*text);
1115 if (!r->free_text) /* cannot accept arbitrary text */
1119 /* cs: completion list
1120 * offset: the offset of the click
1121 * first: the first (rendered) item
1122 * def: the default action
1125 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1127 ssize_t selected = first;
1130 if (cs->length == 0)
1133 if (offset < cs->completions[selected].offset)
1136 /* skip the first entry */
1137 for (selected += 1; selected < cs->length; ++selected) {
1138 if (cs->completions[selected].offset == -1)
1141 if (offset < cs->completions[selected].offset) {
1142 cs->selected = selected - 1;
1149 cs->selected = selected - 1;
1155 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1159 if (r->horizontal_layout)
1164 switch (e->button) {
1166 return select_clicked(cs, off, r->offset, CONFIRM);
1169 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1183 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1186 enum state status = LOOPING;
1188 while (status == LOOPING) {
1190 XNextEvent(r->d, &e);
1192 if (XFilterEvent(&e, r->w))
1197 XRefreshKeyboardMapping(&e.xmapping);
1202 if (e.xfocus.window != r->w)
1203 grabfocus(r->d, r->w);
1206 case VisibilityNotify:
1207 if (e.xvisibility.state != VisibilityUnobscured)
1208 XRaiseWindow(r->d, r->w);
1212 get_wh(r->d, &r->w, &r->width, &r->height);
1221 if (e.type == KeyPress)
1222 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1224 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1236 confirm(&status, r, cs, text, textlen);
1240 case CONFIRM_CONTINUE: {
1242 confirm(&status, r, cs, text, textlen);
1247 complete(cs, r->first_selected, 1, text, textlen, &status);
1248 r->offset = cs->selected;
1253 complete(cs, r->first_selected, 0, text, textlen, &status);
1254 r->offset = cs->selected;
1260 update_completions(cs, *text, lines, vlines, r->first_selected);
1266 update_completions(cs, *text, lines, vlines, r->first_selected);
1272 for (i = 0; i < *textlen; ++i)
1274 update_completions(cs, *text, lines, vlines, r->first_selected);
1282 str_len = strlen(input);
1285 * sometimes a strange key is pressed
1286 * i.e. ctrl alone), so input will be
1287 * empty. Don't need to update
1288 * completion in that case
1293 for (i = 0; i < str_len; ++i) {
1294 *textlen = pushc(text, *textlen, input[i]);
1295 if (*textlen == -1) {
1297 "Memory allocation "
1304 if (status != ERR) {
1306 cs, *text, lines, vlines, r->first_selected);
1314 case TOGGLE_FIRST_SELECTED:
1315 r->first_selected = !r->first_selected;
1316 if (r->first_selected && cs->selected < 0)
1318 if (!r->first_selected && cs->selected == 0)
1323 r->offset = MIN(r->offset + 1, cs->length - 1);
1327 r->offset = MAX((ssize_t)r->offset - 1, 0);
1340 load_font(struct rendering *r, const char *fontname)
1342 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1347 xim_init(struct rendering *r, XrmDatabase *xdb)
1349 XIMStyle best_match_style;
1353 /* Open the X input method */
1354 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1357 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1358 fprintf(stderr, "Input Styles could not be retrieved\n");
1359 exit(EX_UNAVAILABLE);
1362 best_match_style = 0;
1363 for (i = 0; i < xis->count_styles; ++i) {
1364 XIMStyle ts = xis->supported_styles[i];
1365 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1366 best_match_style = ts;
1372 if (!best_match_style)
1373 fprintf(stderr, "No matching input style could be determined\n");
1375 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1376 XNFocusWindow, r->w, NULL);
1378 err(1, "XCreateIC");
1382 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1383 int y, int ox, int oy, unsigned long background_pixel)
1385 XSetWindowAttributes attr;
1387 /* Create the window */
1388 attr.colormap = cmap;
1389 attr.override_redirect = 1;
1390 attr.border_pixel = 0;
1391 attr.background_pixel = background_pixel;
1392 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1393 | ButtonPress | VisibilityChangeMask;
1395 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1396 vinfo.depth, InputOutput, vinfo.visual,
1397 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1401 ps1extents(struct rendering *r)
1404 dup = strdupn(r->ps1);
1405 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1410 usage(char *prgname)
1413 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1414 " [-d separator] [-e window] [-f font] [-G color] [-g "
1416 " [-H height] [-I color] [-i size] [-J color] [-j "
1417 "size] [-l layout]\n"
1418 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1420 " [-t color] [-W width] [-x coord] [-y coord]\n",
1425 main(int argc, char **argv)
1427 struct completions *cs;
1432 Window parent_window;
1434 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1435 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1436 ch_borders_bg[4]; /* N E S W */
1439 int offset_x, offset_y, x, y;
1440 int textlen, d_width, d_height;
1442 char *sep, *parent_window_id;
1443 char **lines, **vlines;
1444 char *fontname, *text, *xrm;
1447 parent_window_id = NULL;
1449 r.first_selected = 0;
1451 r.multiple_select = 0;
1454 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1456 case 'h': /* help */
1459 case 'v': /* version */
1460 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1462 case 'e': /* embed */
1463 if ((parent_window_id = strdup(optarg)) == NULL)
1467 if ((sep = strdup(optarg)) == NULL)
1474 r.multiple_select = 1;
1481 lines = readlines(&nlines);
1487 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1490 for (i = 0; i < nlines; i++) {
1492 t = strstr(lines[i], sep);
1494 vlines[i] = lines[i];
1500 setlocale(LC_ALL, getenv("LANG"));
1504 /* where the monitor start (used only with xinerama) */
1505 offset_x = offset_y = 0;
1507 /* default width and height */
1511 /* default position on the screen */
1514 for (i = 0; i < 4; ++i) {
1515 /* default paddings */
1516 r.p_padding[i] = 10;
1517 r.c_padding[i] = 10;
1518 r.ch_padding[i] = 10;
1520 /* default borders */
1524 r.ch_borders[i] = 0;
1527 /* the prompt. We duplicate the string so later is easy to
1528 * free (in the case it's been overwritten by the user) */
1529 if ((r.ps1 = strdup("$ ")) == NULL)
1532 /* same for the font name */
1533 if ((fontname = strdup(default_fontname)) == NULL)
1537 if ((text = malloc(textlen * sizeof(char))) == NULL)
1540 /* struct completions *cs = filter(text, lines); */
1541 if ((cs = compls_new(nlines)) == NULL)
1542 err(1, "compls_new");
1544 /* start talking to xorg */
1545 r.d = XOpenDisplay(NULL);
1547 fprintf(stderr, "Could not open display!\n");
1548 return EX_UNAVAILABLE;
1552 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1553 parent_window = DefaultRootWindow(r.d);
1557 /* get display size */
1558 get_wh(r.d, &parent_window, &d_width, &d_height);
1560 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1561 XineramaScreenInfo *info;
1564 int number_of_screens, monitors, i;
1565 int root_x, root_y, win_x, win_y;
1569 number_of_screens = XScreenCount(r.d);
1570 for (i = 0; i < number_of_screens; ++i) {
1571 root = XRootWindow(r.d, i);
1572 res = XQueryPointer(
1573 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1579 fprintf(stderr, "No mouse found.\n");
1584 /* Now find in which monitor the mice is */
1585 info = XineramaQueryScreens(r.d, &monitors);
1587 for (i = 0; i < monitors; ++i) {
1588 if (info[i].x_org <= root_x
1589 && root_x <= (info[i].x_org + info[i].width)
1590 && info[i].y_org <= root_y
1591 && root_y <= (info[i].y_org + info[i].height)) {
1592 offset_x = info[i].x_org;
1593 offset_y = info[i].y_org;
1594 d_width = info[i].width;
1595 d_height = info[i].height;
1603 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1604 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1606 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1607 fgs[2] = parse_color("#000", NULL);
1609 bgs[0] = bgs[1] = parse_color("#000", NULL);
1610 bgs[2] = parse_color("#fff", NULL);
1612 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1614 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1615 = parse_color("#000", NULL);
1616 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1617 = parse_color("#000", NULL);
1618 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1619 = parse_color("#000", NULL);
1621 r.horizontal_layout = 1;
1623 /* Read the resources */
1625 xrm = XResourceManagerString(r.d);
1631 xdb = XrmGetStringDatabase(xrm);
1633 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1635 if ((fontname = strdup(value.addr)) == NULL)
1638 fprintf(stderr, "no font defined, using %s\n", fontname);
1641 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1642 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1644 fprintf(stderr, "no layout defined, using horizontal\n");
1646 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1648 r.ps1 = normalize_str(value.addr);
1651 "no prompt defined, using \"%s\" as "
1656 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1658 sizes = parse_csslike(value.addr);
1660 for (i = 0; i < 4; ++i)
1661 r.p_borders[i] = parse_integer(sizes[i], 0);
1664 "error while parsing "
1665 "MyMenu.prompt.border.size");
1668 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1670 colors = parse_csslike(value.addr);
1672 for (i = 0; i < 4; ++i)
1673 p_borders_bg[i] = parse_color(colors[i], "#000");
1676 "error while parsing "
1677 "MyMenu.prompt.border.color");
1680 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1682 colors = parse_csslike(value.addr);
1684 for (i = 0; i < 4; ++i)
1685 r.p_padding[i] = parse_integer(colors[i], 0);
1688 "error while parsing "
1689 "MyMenu.prompt.padding");
1692 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1693 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1695 fprintf(stderr, "no width defined, using %d\n", r.width);
1697 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1698 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1700 fprintf(stderr, "no height defined, using %d\n", r.height);
1702 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1703 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1705 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1706 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1708 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1710 borders = parse_csslike(value.addr);
1711 if (borders != NULL)
1712 for (i = 0; i < 4; ++i)
1713 r.borders[i] = parse_int_with_percentage(
1714 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1717 "error while parsing "
1718 "MyMenu.border.size\n");
1722 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1723 fgs[0] = parse_color(value.addr, "#fff");
1725 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1726 bgs[0] = parse_color(value.addr, "#000");
1729 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1730 fgs[1] = parse_color(value.addr, "#fff");
1732 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1733 bgs[1] = parse_color(value.addr, "#000");
1735 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1737 paddings = parse_csslike(value.addr);
1738 if (paddings != NULL)
1739 for (i = 0; i < 4; ++i)
1740 r.c_padding[i] = parse_integer(paddings[i], 0);
1743 "Error while parsing "
1744 "MyMenu.completion.padding");
1747 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1749 sizes = parse_csslike(value.addr);
1751 for (i = 0; i < 4; ++i)
1752 r.c_borders[i] = parse_integer(sizes[i], 0);
1755 "Error while parsing "
1756 "MyMenu.completion.border.size");
1759 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1761 sizes = parse_csslike(value.addr);
1763 for (i = 0; i < 4; ++i)
1764 c_borders_bg[i] = parse_color(sizes[i], "#000");
1767 "Error while parsing "
1768 "MyMenu.completion.border.color");
1771 /* Completion Highlighted */
1773 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1774 fgs[2] = parse_color(value.addr, "#000");
1777 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1778 bgs[2] = parse_color(value.addr, "#fff");
1781 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1783 paddings = parse_csslike(value.addr);
1784 if (paddings != NULL)
1785 for (i = 0; i < 4; ++i)
1786 r.ch_padding[i] = parse_integer(paddings[i], 0);
1789 "Error while parsing "
1790 "MyMenu.completion_highlighted."
1794 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1797 sizes = parse_csslike(value.addr);
1799 for (i = 0; i < 4; ++i)
1800 r.ch_borders[i] = parse_integer(sizes[i], 0);
1803 "Error while parsing "
1804 "MyMenu.completion_highlighted."
1808 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1811 colors = parse_csslike(value.addr);
1813 for (i = 0; i < 4; ++i)
1814 ch_borders_bg[i] = parse_color(colors[i], "#000");
1817 "Error while parsing "
1818 "MyMenu.completion_highlighted."
1823 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1825 colors = parse_csslike(value.addr);
1827 for (i = 0; i < 4; ++i)
1828 borders_bg[i] = parse_color(colors[i], "#000");
1831 "error while parsing "
1832 "MyMenu.border.color\n");
1836 /* Second round of args parsing */
1837 optind = 0; /* reset the option index */
1838 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1841 r.first_selected = 1;
1844 /* free_text -- already catched */
1846 /* separator -- this case was already catched */
1848 /* embedding mymenu this case was already catched. */
1850 /* multiple selection this case was already catched.
1855 newprompt = strdup(optarg);
1856 if (newprompt != NULL) {
1863 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1866 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1870 if ((paddings = parse_csslike(optarg)) != NULL)
1871 for (i = 0; i < 4; ++i)
1872 r.p_padding[i] = parse_integer(paddings[i], 0);
1877 if ((colors = parse_csslike(optarg)) != NULL)
1878 for (i = 0; i < 4; ++i)
1879 p_borders_bg[i] = parse_color(colors[i], "#000");
1884 if ((sizes = parse_csslike(optarg)) != NULL)
1885 for (i = 0; i < 4; ++i)
1886 r.p_borders[i] = parse_integer(sizes[i], 0);
1891 if ((colors = parse_csslike(optarg)) != NULL)
1892 for (i = 0; i < 4; ++i)
1893 c_borders_bg[i] = parse_color(colors[i], "#000");
1898 if ((sizes = parse_csslike(optarg)) != NULL)
1899 for (i = 0; i < 4; ++i)
1900 r.c_borders[i] = parse_integer(sizes[i], 0);
1905 if ((colors = parse_csslike(optarg)) != NULL)
1906 for (i = 0; i < 4; ++i)
1907 ch_borders_bg[i] = parse_color(colors[i], "#000");
1912 if ((sizes = parse_csslike(optarg)) != NULL)
1913 for (i = 0; i < 4; ++i)
1914 r.ch_borders[i] = parse_integer(sizes[i], 0);
1918 r.horizontal_layout = !strcmp(optarg, "horizontal");
1922 if ((newfont = strdup(optarg)) != NULL) {
1929 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1932 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1936 if ((borders = parse_csslike(optarg)) != NULL) {
1937 for (i = 0; i < 4; ++i)
1938 r.borders[i] = parse_integer(borders[i], 0);
1940 fprintf(stderr, "Error parsing b option\n");
1945 if ((colors = parse_csslike(optarg)) != NULL) {
1946 for (i = 0; i < 4; ++i)
1947 borders_bg[i] = parse_color(colors[i], "#000");
1949 fprintf(stderr, "error while parsing B option\n");
1953 fgs[0] = parse_color(optarg, NULL);
1956 bgs[0] = parse_color(optarg, NULL);
1959 fgs[1] = parse_color(optarg, NULL);
1962 bgs[1] = parse_color(optarg, NULL);
1965 fgs[2] = parse_color(optarg, NULL);
1968 bgs[2] = parse_color(optarg, NULL);
1971 fprintf(stderr, "Unrecognized option %c\n", ch);
1977 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1978 fprintf(stderr, "height, width, x or y are lesser than 0.");
1982 /* since only now we know if the first should be selected,
1983 * update the completion here */
1984 update_completions(cs, text, lines, vlines, r.first_selected);
1986 /* update the prompt lenght, only now we surely know the length of it
1988 r.ps1len = strlen(r.ps1);
1990 /* Create the window */
1991 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1992 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1993 XMapRaised(r.d, r.w);
1995 /* If embed, listen for other events as well */
1997 Window *children, parent, root;
1998 unsigned int children_no;
2000 XSelectInput(r.d, parent_window, FocusChangeMask);
2001 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2003 for (i = 0; i < children_no && children[i] != r.w; ++i)
2004 XSelectInput(r.d, children[i], FocusChangeMask);
2007 grabfocus(r.d, r.w);
2010 take_keyboard(r.d, r.w);
2012 r.x_zero = r.borders[3];
2013 r.y_zero = r.borders[0];
2018 for (i = 0; i < 3; ++i) {
2019 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2020 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2023 for (i = 0; i < 4; ++i) {
2024 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2025 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2026 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2027 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2031 /* Load the colors in our GCs */
2032 for (i = 0; i < 3; ++i) {
2033 XSetForeground(r.d, r.fgs[i], fgs[i]);
2034 XSetForeground(r.d, r.bgs[i], bgs[i]);
2037 for (i = 0; i < 4; ++i) {
2038 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2039 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2040 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2041 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2044 if (load_font(&r, fontname) == -1)
2047 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2049 for (i = 0; i < 3; ++i) {
2051 XRenderColor xrcolor;
2053 c = *(rgba_t *)&fgs[i];
2054 xrcolor.red = EXPANDBITS(c.rgba.r);
2055 xrcolor.green = EXPANDBITS(c.rgba.g);
2056 xrcolor.blue = EXPANDBITS(c.rgba.b);
2057 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2058 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2061 /* compute prompt dimensions */
2067 if (pledge("stdio", "") == -1)
2071 /* Cache text height */
2072 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2074 /* Draw the window for the first time */
2078 while (status == LOOPING || status == OK_LOOP) {
2079 status = loop(&r, &text, &textlen, cs, lines, vlines);
2082 printf("%s\n", text);
2084 if (!r.multiple_select && status == OK_LOOP)
2088 XUngrabKeyboard(r.d, CurrentTime);
2090 for (i = 0; i < 3; ++i)
2091 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2093 for (i = 0; i < 3; ++i) {
2094 XFreeGC(r.d, r.fgs[i]);
2095 XFreeGC(r.d, r.bgs[i]);
2098 for (i = 0; i < 4; ++i) {
2099 XFreeGC(r.d, r.borders_bg[i]);
2100 XFreeGC(r.d, r.p_borders_bg[i]);
2101 XFreeGC(r.d, r.c_borders_bg[i]);
2102 XFreeGC(r.d, r.ch_borders_bg[i]);
2108 for (i = 0; i < 3; ++i)
2109 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2110 XftFontClose(r.d, r.font);
2111 XftDrawDestroy(r.xftdraw);
2121 XFreeColormap(r.d, cmap);
2123 XDestroyWindow(r.d, r.w);
2126 return status != OK;