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>
20 #include <X11/extensions/Xinerama.h>
24 #include <X11/Xft/Xft.h>
28 #define VERSION "unknown"
31 #define resname "MyMenu"
32 #define resclass "mymenu"
34 #define SYM_BUF_SIZE 4
37 #define default_fontname "monospace"
39 #define default_fontname "fixed"
42 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:G:g:I:i:J:j:"
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
50 * If we don't have or we don't want an "ignore case" completion
51 * style, fall back to `strstr(3)`
53 #ifndef USE_STRCASESTR
54 #define strcasestr strstr
57 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
58 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
60 /* The states of the event loop */
61 enum state { LOOPING, OK_LOOP, OK, ERR };
64 * For the drawing-related function. The text to be rendere could be
65 * the prompt, a completion or a highlighted completion
67 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
69 /* These are the possible action to be performed after user input. */
81 TOGGLE_FIRST_SELECTED,
86 /* A big set of values that needs to be carried around for drawing. A
87 * big struct to rule them all */
89 Display *d; /* Connection to xorg */
97 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
99 int y_zero; /* like x_zero but for the y axis */
101 int offset; /* scroll offset */
104 short first_selected;
105 short multiple_select;
107 /* four border width */
113 short horizontal_layout;
118 int ps1w; /* ps1 width */
119 int ps1h; /* ps1 height */
121 int text_height; /* cache for the vertical layout */
135 XftColor xft_colors[3];
144 int offset; /* the x (or y, depending on the layout) coordinate at
145 which the item is rendered */
148 /* Wrap the linked list of completions */
150 struct completion *completions;
155 /* idea stolen from lemonbar. ty lemonboy */
169 /* Return a newly allocated (and empty) completion list */
171 compls_new(size_t length)
173 struct completions *cs = malloc(sizeof(struct completions));
178 cs->completions = calloc(length, sizeof(struct completion));
179 if (cs->completions == NULL) {
189 /* Delete the wrapper and the whole list */
191 compls_delete(struct completions *cs)
196 free(cs->completions);
201 * Create a completion list from a text and the list of possible
202 * completions (null terminated). Expects a non-null `cs'. `lines' and
203 * `vlines' should have the same length OR `vlines' is NULL.
206 filter(struct completions *cs, char *text, char **lines, char **vlines)
216 if (lines[index] == NULL)
219 l = vlines[index] != NULL ? vlines[index] : lines[index];
221 if (strcasestr(l, text) != NULL) {
222 struct completion *c = &cs->completions[matching];
224 c->rcompletion = lines[index];
230 cs->length = matching;
234 /* Update the given completion */
237 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
239 filter(cs, text, lines, vlines);
240 if (first_selected && cs->length > 0)
245 * Select the next or previous selection and update some state. `text'
246 * will be updated with the text of the completion and `textlen' with
247 * the new length. If the memory cannot be allocated `status' will be
251 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
254 struct completion *n;
257 if (cs == NULL || cs->length == 0)
261 * If the first is always selected and the first entry is
262 * different from the text, expand the text and return
264 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
267 *text = strdup(cs->completions->completion);
272 *textlen = strlen(*text);
276 index = cs->selected;
278 if (index == -1 && p)
280 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
282 n = &cs->completions[cs->selected];
285 *text = strdup(n->completion);
287 fprintf(stderr, "Memory allocation error!\n");
291 *textlen = strlen(*text);
294 /* Push the character c at the end of the string pointed by p */
296 pushc(char **p, int maxlen, char c)
300 len = strnlen(*p, maxlen);
301 if (!(len < maxlen - 2)) {
304 maxlen += maxlen >> 1;
305 newptr = realloc(*p, maxlen);
306 if (newptr == NULL) /* bad */
312 (*p)[len + 1] = '\0';
317 * Remove the last rune from the *UTF-8* string! This is different
318 * from just setting the last byte to 0 (in some cases ofc). Return a
319 * pointer (e) to the last nonzero char. If e < p then p is empty!
339 * If c is a starting byte (11......) or is under
342 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
349 /* Remove the last word plus trailing white spaces from the given string */
356 if ((len = strlen(w)) == 0)
365 if (in_word && isspace(*e))
368 if (!in_word && !isspace(*e))
374 * If the string is surrounded by quates (`"') remove them and replace
375 * every `\"' in the string with a single double-quote.
378 normalize_str(const char *str)
383 if ((len = strlen(str)) == 0)
386 if ((s = calloc(len, sizeof(char))) == NULL)
397 str += 2; /* skip this and the next char */
403 str++; /* skip only this char */
415 readlines(size_t *lineslen)
417 size_t len = 0, cap = 0;
420 char *line = NULL, **lines = NULL;
422 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
423 if (linelen != 0 && line[linelen-1] == '\n')
424 line[linelen-1] = '\0';
430 newcap = MAX(cap * 1.5, 32);
431 t = recallocarray(lines, cap, newcap, sizeof(char *));
433 err(1, "recallocarray");
438 if ((lines[len++] = strdup(line)) == NULL)
451 * Compute the dimensions of the string str once rendered.
452 * It'll return the width and set ret_width and ret_height if not NULL
455 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
460 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
461 height = r->font->ascent - r->font->descent;
462 width = gi.width - gi.x;
465 XmbTextExtents(r->font, str, len, NULL, &rect);
466 height = rect.height;
469 if (ret_width != NULL)
471 if (ret_height != NULL)
472 *ret_height = height;
477 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
482 xftcolor = r->xft_colors[0];
484 xftcolor = r->xft_colors[1];
485 if (tt == COMPL_HIGH)
486 xftcolor = r->xft_colors[2];
488 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
495 if (tt == COMPL_HIGH)
497 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
501 /* Duplicate the string and substitute every space with a 'n` */
510 if (str == NULL || len == 0)
513 if ((dup = strdup(str)) == NULL)
516 for (i = 0; i < len; ++i)
524 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
526 GC *border_color, bg;
527 int *padding, *borders;
528 int ret = 0, inner_width, inner_height, x;
532 border_color = r->p_borders_bg;
533 padding = r->p_padding;
534 borders = r->p_borders;
538 border_color = r->c_borders_bg;
539 padding = r->c_padding;
540 borders = r->c_borders;
544 border_color = r->ch_borders_bg;
545 padding = r->ch_padding;
546 borders = r->ch_borders;
551 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
553 inner_width = inner_width(r) - borders[1] - borders[3];
554 inner_height = padding[0] + r->text_height + padding[2];
557 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
560 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1], y,
564 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
565 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
568 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
571 x = r->x_zero + borders[3];
573 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
576 y += padding[0] + r->text_height;
578 if (prefix != NULL) {
579 draw_string(prefix, strlen(prefix), x, y, r, t);
582 draw_string(text, strlen(text), x, y, r, t);
588 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
590 GC *border_color, bg;
591 int *padding, *borders;
592 int ret = 0, inner_width, inner_height, y, text_width;
596 border_color = r->p_borders_bg;
597 padding = r->p_padding;
598 borders = r->p_borders;
602 border_color = r->c_borders_bg;
603 padding = r->c_padding;
604 borders = r->c_borders;
608 border_color = r->ch_borders_bg;
609 padding = r->ch_padding;
610 borders = r->ch_borders;
615 if (padding[0] < 0 || padding[2] < 0)
616 padding[0] = padding[2]
617 = (inner_height(r) - borders[0] - borders[2] - r->text_height) / 2;
619 /* If they are still lesser than 0, set 'em to 0 */
620 if (padding[0] < 0 || padding[2] < 0)
621 padding[0] = padding[2] = 0;
623 /* Get the text width */
624 text_extents(text, strlen(text), r, &text_width, NULL);
626 text_width += prefix_width;
628 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
630 inner_width = padding[3] + text_width + padding[1];
631 inner_height = inner_height(r) - borders[0] - borders[2];
634 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
637 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
638 borders[1], inner_height(r));
641 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2],
645 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
649 y = r->y_zero + borders[0];
650 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
653 y += padding[0] + r->text_height;
655 if (prefix != NULL) {
656 draw_string(prefix, strlen(prefix), x, y, r, t);
659 draw_string(text, strlen(text), x, y, r, t);
664 /* ,-----------------------------------------------------------------, */
665 /* | 20 char text | completion | completion | completion | compl | */
666 /* `-----------------------------------------------------------------' */
668 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
673 /* Draw the prompt */
674 x += draw_h_box(r, x, 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 = x;
681 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
683 if (x > inner_width(r))
687 for (i += 1; i < cs->length; ++i)
688 cs->completions[i].offset = -1;
691 /* ,-----------------------------------------------------------------, */
693 /* |-----------------------------------------------------------------| */
695 /* |-----------------------------------------------------------------| */
697 /* `-----------------------------------------------------------------' */
699 draw_vertically(struct rendering *r, char *text, struct completions *cs)
704 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
706 for (i = r->offset; i < cs->length; ++i) {
707 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
709 cs->completions[i].offset = y;
711 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
713 if (y > inner_height(r))
717 for (i += 1; i < cs->length; ++i)
718 cs->completions[i].offset = -1;
722 draw(struct rendering *r, char *text, struct completions *cs)
724 /* Draw the background */
726 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
728 /* Draw the contents */
729 if (r->horizontal_layout)
730 draw_horizontally(r, text, cs);
732 draw_vertically(r, text, cs);
734 /* Draw the borders */
735 if (r->borders[0] != 0)
736 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
738 if (r->borders[1] != 0)
739 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
740 r->borders[1], r->height);
742 if (r->borders[2] != 0)
743 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
746 if (r->borders[3] != 0)
747 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
753 /* Set some WM stuff */
755 set_win_atoms_hints(Display *d, Window w, int width, int height)
758 XClassHint *class_hint;
759 XSizeHints *size_hint;
761 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
762 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
763 32, PropModeReplace, (unsigned char *)&type, 1);
765 /* some window managers honor this properties */
766 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
767 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
768 PropModeReplace, (unsigned char *)&type, 1);
770 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
771 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
772 PropModeAppend, (unsigned char *)&type, 1);
774 /* Setting window hints */
775 class_hint = XAllocClassHint();
776 if (class_hint == NULL) {
777 fprintf(stderr, "Could not allocate memory for class hint\n");
778 exit(EX_UNAVAILABLE);
781 class_hint->res_name = resname;
782 class_hint->res_class = resclass;
783 XSetClassHint(d, w, class_hint);
786 size_hint = XAllocSizeHints();
787 if (size_hint == NULL) {
788 fprintf(stderr, "Could not allocate memory for size hint\n");
789 exit(EX_UNAVAILABLE);
792 size_hint->flags = PMinSize | PBaseSize;
793 size_hint->min_width = width;
794 size_hint->base_width = width;
795 size_hint->min_height = height;
796 size_hint->base_height = height;
801 /* Get the width and height of the window `w' */
803 get_wh(Display *d, Window *w, int *width, int *height)
805 XWindowAttributes win_attr;
807 XGetWindowAttributes(d, *w, &win_attr);
808 *height = win_attr.height;
809 *width = win_attr.width;
813 grabfocus(Display *d, Window w)
816 for (i = 0; i < 100; ++i) {
820 XGetInputFocus(d, &focuswin, &revert_to_win);
825 XSetInputFocus(d, w, RevertToParent, CurrentTime);
832 * I know this may seem a little hackish BUT is the only way I managed
833 * to actually grab that goddam keyboard. Only one call to
834 * XGrabKeyboard does not always end up with the keyboard grabbed!
837 take_keyboard(Display *d, Window w)
840 for (i = 0; i < 100; i++) {
841 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
846 fprintf(stderr, "Cannot grab keyboard\n");
851 parse_color(const char *str, const char *def)
862 /* +1 for the # ath the start */
863 if (*str != '#' || len > 9 || len < 4)
865 ++str; /* skip the # */
868 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
875 /* expand #rgb -> #rrggbb */
876 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
877 | (tmp.v & 0x00f) * 0x0011;
879 /* assume 0xff opacity */
882 } /* colors in #aarrggbb need no adjustments */
884 /* premultiply the alpha */
886 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
887 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
888 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
895 fprintf(stderr, "Invalid color: \"%s\".\n", str);
897 return parse_color(def, NULL);
903 * Given a string try to parse it as a number or return `default_value'.
906 parse_integer(const char *str, int default_value)
912 lval = strtol(str, &ep, 10);
914 if (str[0] == '\0' || *ep != '\0') { /* NaN */
915 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str,
917 return default_value;
920 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
921 || (lval > INT_MAX || lval < INT_MIN)) {
922 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
923 return default_value;
929 /* Like parse_integer but recognize the percentages (i.e. strings ending with
932 parse_int_with_percentage(const char *str, int default_value, int max)
934 int len = strlen(str);
936 if (len > 0 && str[len - 1] == '%') {
940 if ((cpy = strdup(str)) == NULL)
944 val = parse_integer(cpy, default_value);
946 return val * max / 100;
949 return parse_integer(str, default_value);
953 get_mouse_coords(Display *d, int *x, int *y)
960 root = DefaultRootWindow(d);
962 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
963 for (i = 0; i < ScreenCount(d); ++i) {
964 if (root == RootWindow(d, i))
971 * Like parse_int_with_percentage but understands some special values:
972 * - middle that is (max-self)/2
975 * - end that is (max-self)
976 * - mx x coordinate of the mouse
977 * - my y coordinate of the mouse
980 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
982 if (!strcmp(str, "start"))
984 if (!strcmp(str, "middle") || !strcmp(str, "center"))
985 return (max - self) / 2;
986 if (!strcmp(str, "end"))
988 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
991 get_mouse_coords(d, &x, &y);
992 if (!strcmp(str, "mx"))
997 return parse_int_with_percentage(str, default_value, max);
1000 /* Parse a string like a CSS value. */
1001 /* TODO: harden a bit this function */
1003 parse_csslike(const char *str)
1006 char *s, *token, **ret;
1013 ret = malloc(4 * sizeof(char *));
1019 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1020 ret[i] = strdup(token);
1023 for (j = 1; j < 4; j++)
1024 ret[j] = strdup(ret[0]);
1027 ret[2] = strdup(ret[0]);
1028 ret[3] = strdup(ret[1]);
1032 ret[3] = strdup(ret[1]);
1034 /* before we didn't check for the return type of strdup, here we will
1038 for (i = 0; i < 4; ++i)
1039 any_null = ret[i] == NULL || any_null;
1042 for (i = 0; i < 4; ++i)
1046 if (i == 0 || any_null) {
1056 * Given an event, try to understand what the users wants. If the
1057 * return value is ADD_CHAR then `input' is a pointer to a string that
1058 * will need to be free'ed later.
1061 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1063 char str[SYM_BUF_SIZE] = { 0 };
1066 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1069 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1070 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1072 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1075 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1078 /* Try to read what key was pressed */
1080 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1081 if (s == XBufferOverflow) {
1083 "Buffer overflow when trying to create keyboard "
1088 if (ev->state & ControlMask) {
1089 if (!strcmp(str, "")) /* C-u */
1091 if (!strcmp(str, "")) /* C-w */
1093 if (!strcmp(str, "")) /* C-h */
1095 if (!strcmp(str, "\r")) /* C-m */
1096 return CONFIRM_CONTINUE;
1097 if (!strcmp(str, "")) /* C-p */
1099 if (!strcmp(str, "")) /* C-n */
1101 if (!strcmp(str, "")) /* C-c */
1103 if (!strcmp(str, "\t")) /* C-i */
1104 return TOGGLE_FIRST_SELECTED;
1107 *input = strdup(str);
1108 if (*input == NULL) {
1109 fprintf(stderr, "Error while allocating memory for key.\n");
1117 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1119 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1120 /* if there is something selected expand it and return */
1121 int index = cs->selected == -1 ? 0 : cs->selected;
1122 struct completion *c = cs->completions;
1136 if (*text == NULL) {
1137 fprintf(stderr, "Memory allocation error\n");
1141 *textlen = strlen(*text);
1145 if (!r->free_text) /* cannot accept arbitrary text */
1149 /* cs: completion list
1150 * offset: the offset of the click
1151 * first: the first (rendered) item
1152 * def: the default action
1155 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1157 ssize_t selected = first;
1160 if (cs->length == 0)
1163 if (offset < cs->completions[selected].offset)
1166 /* skip the first entry */
1167 for (selected += 1; selected < cs->length; ++selected) {
1168 if (cs->completions[selected].offset == -1)
1171 if (offset < cs->completions[selected].offset) {
1172 cs->selected = selected - 1;
1179 cs->selected = selected - 1;
1185 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1189 if (r->horizontal_layout)
1194 switch (e->button) {
1196 return select_clicked(cs, off, r->offset, CONFIRM);
1199 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1213 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1216 enum state status = LOOPING;
1218 while (status == LOOPING) {
1220 XNextEvent(r->d, &e);
1222 if (XFilterEvent(&e, r->w))
1227 XRefreshKeyboardMapping(&e.xmapping);
1232 if (e.xfocus.window != r->w)
1233 grabfocus(r->d, r->w);
1236 case VisibilityNotify:
1237 if (e.xvisibility.state != VisibilityUnobscured)
1238 XRaiseWindow(r->d, r->w);
1242 get_wh(r->d, &r->w, &r->width, &r->height);
1251 if (e.type == KeyPress)
1252 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1254 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1266 confirm(&status, r, cs, text, textlen);
1270 case CONFIRM_CONTINUE: {
1272 confirm(&status, r, cs, text, textlen);
1277 complete(cs, r->first_selected, 1, text, textlen, &status);
1278 r->offset = cs->selected;
1283 complete(cs, r->first_selected, 0, text, textlen, &status);
1284 r->offset = cs->selected;
1290 update_completions(cs, *text, lines, vlines, r->first_selected);
1296 update_completions(cs, *text, lines, vlines, r->first_selected);
1302 for (i = 0; i < *textlen; ++i)
1304 update_completions(cs, *text, lines, vlines, r->first_selected);
1312 str_len = strlen(input);
1315 * sometimes a strange key is pressed
1316 * i.e. ctrl alone), so input will be
1317 * empty. Don't need to update
1318 * completion in that case
1323 for (i = 0; i < str_len; ++i) {
1324 *textlen = pushc(text, *textlen, input[i]);
1325 if (*textlen == -1) {
1327 "Memory allocation "
1334 if (status != ERR) {
1336 cs, *text, lines, vlines, r->first_selected);
1344 case TOGGLE_FIRST_SELECTED:
1345 r->first_selected = !r->first_selected;
1346 if (r->first_selected && cs->selected < 0)
1348 if (!r->first_selected && cs->selected == 0)
1353 r->offset = MIN(r->offset + 1, cs->length - 1);
1357 r->offset = MAX((ssize_t)r->offset - 1, 0);
1370 load_font(struct rendering *r, const char *fontname)
1373 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1376 char **missing_charset_list;
1377 int missing_charset_count;
1379 r->font = XCreateFontSet(
1380 r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1381 if (r->font != NULL)
1384 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1386 if (!strcmp(fontname, default_fontname))
1389 return load_font(r, default_fontname);
1394 xim_init(struct rendering *r, XrmDatabase *xdb)
1396 XIMStyle best_match_style;
1400 /* Open the X input method */
1401 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1404 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1405 fprintf(stderr, "Input Styles could not be retrieved\n");
1406 exit(EX_UNAVAILABLE);
1409 best_match_style = 0;
1410 for (i = 0; i < xis->count_styles; ++i) {
1411 XIMStyle ts = xis->supported_styles[i];
1412 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1413 best_match_style = ts;
1419 if (!best_match_style)
1420 fprintf(stderr, "No matching input style could be determined\n");
1422 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1423 XNFocusWindow, r->w, NULL);
1425 err(1, "XCreateIC");
1429 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1430 int y, int ox, int oy, unsigned long background_pixel)
1432 XSetWindowAttributes attr;
1434 /* Create the window */
1435 attr.colormap = cmap;
1436 attr.override_redirect = 1;
1437 attr.border_pixel = 0;
1438 attr.background_pixel = background_pixel;
1439 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1440 | ButtonPress | VisibilityChangeMask;
1442 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1443 vinfo.depth, InputOutput, vinfo.visual,
1444 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1448 ps1extents(struct rendering *r)
1451 dup = strdupn(r->ps1);
1452 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1457 usage(char *prgname)
1460 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1461 " [-d separator] [-e window] [-f font] [-G color] [-g "
1463 " [-H height] [-I color] [-i size] [-J color] [-j "
1464 "size] [-l layout]\n"
1465 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1467 " [-t color] [-W width] [-x coord] [-y coord]\n",
1472 main(int argc, char **argv)
1474 struct completions *cs;
1479 Window parent_window;
1481 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1482 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1483 ch_borders_bg[4]; /* N E S W */
1486 int offset_x, offset_y, x, y;
1487 int textlen, d_width, d_height;
1489 char *sep, *parent_window_id;
1490 char **lines, **vlines;
1491 char *fontname, *text, *xrm;
1494 parent_window_id = NULL;
1496 r.first_selected = 0;
1498 r.multiple_select = 0;
1501 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1503 case 'h': /* help */
1506 case 'v': /* version */
1507 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1509 case 'e': /* embed */
1510 if ((parent_window_id = strdup(optarg)) == NULL)
1514 if ((sep = strdup(optarg)) == NULL)
1521 r.multiple_select = 1;
1528 lines = readlines(&nlines);
1534 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1537 for (i = 0; i < nlines; i++) {
1539 t = strstr(lines[i], sep);
1541 vlines[i] = lines[i];
1547 setlocale(LC_ALL, getenv("LANG"));
1551 /* where the monitor start (used only with xinerama) */
1552 offset_x = offset_y = 0;
1554 /* default width and height */
1558 /* default position on the screen */
1561 for (i = 0; i < 4; ++i) {
1562 /* default paddings */
1563 r.p_padding[i] = 10;
1564 r.c_padding[i] = 10;
1565 r.ch_padding[i] = 10;
1567 /* default borders */
1571 r.ch_borders[i] = 0;
1574 /* the prompt. We duplicate the string so later is easy to
1575 * free (in the case it's been overwritten by the user) */
1576 if ((r.ps1 = strdup("$ ")) == NULL)
1579 /* same for the font name */
1580 if ((fontname = strdup(default_fontname)) == NULL)
1584 if ((text = malloc(textlen * sizeof(char))) == NULL)
1587 /* struct completions *cs = filter(text, lines); */
1588 if ((cs = compls_new(nlines)) == NULL)
1589 err(1, "compls_new");
1591 /* start talking to xorg */
1592 r.d = XOpenDisplay(NULL);
1594 fprintf(stderr, "Could not open display!\n");
1595 return EX_UNAVAILABLE;
1599 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1600 parent_window = DefaultRootWindow(r.d);
1604 /* get display size */
1605 get_wh(r.d, &parent_window, &d_width, &d_height);
1608 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1609 XineramaScreenInfo *info;
1612 int number_of_screens, monitors, i;
1613 int root_x, root_y, win_x, win_y;
1617 number_of_screens = XScreenCount(r.d);
1618 for (i = 0; i < number_of_screens; ++i) {
1619 root = XRootWindow(r.d, i);
1620 res = XQueryPointer(
1621 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1627 fprintf(stderr, "No mouse found.\n");
1632 /* Now find in which monitor the mice is */
1633 info = XineramaQueryScreens(r.d, &monitors);
1635 for (i = 0; i < monitors; ++i) {
1636 if (info[i].x_org <= root_x
1637 && root_x <= (info[i].x_org + info[i].width)
1638 && info[i].y_org <= root_y
1639 && root_y <= (info[i].y_org + info[i].height)) {
1640 offset_x = info[i].x_org;
1641 offset_y = info[i].y_org;
1642 d_width = info[i].width;
1643 d_height = info[i].height;
1652 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1653 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1655 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1656 fgs[2] = parse_color("#000", NULL);
1658 bgs[0] = bgs[1] = parse_color("#000", NULL);
1659 bgs[2] = parse_color("#fff", NULL);
1661 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1663 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1664 = parse_color("#000", NULL);
1665 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1666 = parse_color("#000", NULL);
1667 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1668 = parse_color("#000", NULL);
1670 r.horizontal_layout = 1;
1672 /* Read the resources */
1674 xrm = XResourceManagerString(r.d);
1680 xdb = XrmGetStringDatabase(xrm);
1682 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1684 if ((fontname = strdup(value.addr)) == NULL)
1687 fprintf(stderr, "no font defined, using %s\n", fontname);
1690 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1691 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1693 fprintf(stderr, "no layout defined, using horizontal\n");
1695 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1697 r.ps1 = normalize_str(value.addr);
1700 "no prompt defined, using \"%s\" as "
1705 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1707 sizes = parse_csslike(value.addr);
1709 for (i = 0; i < 4; ++i)
1710 r.p_borders[i] = parse_integer(sizes[i], 0);
1713 "error while parsing "
1714 "MyMenu.prompt.border.size");
1717 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1719 colors = parse_csslike(value.addr);
1721 for (i = 0; i < 4; ++i)
1722 p_borders_bg[i] = parse_color(colors[i], "#000");
1725 "error while parsing "
1726 "MyMenu.prompt.border.color");
1729 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1731 colors = parse_csslike(value.addr);
1733 for (i = 0; i < 4; ++i)
1734 r.p_padding[i] = parse_integer(colors[i], 0);
1737 "error while parsing "
1738 "MyMenu.prompt.padding");
1741 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1742 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1744 fprintf(stderr, "no width defined, using %d\n", r.width);
1746 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1747 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1749 fprintf(stderr, "no height defined, using %d\n", r.height);
1751 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1752 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1754 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1755 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1757 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1759 borders = parse_csslike(value.addr);
1760 if (borders != NULL)
1761 for (i = 0; i < 4; ++i)
1762 r.borders[i] = parse_int_with_percentage(
1763 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1766 "error while parsing "
1767 "MyMenu.border.size\n");
1771 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1772 fgs[0] = parse_color(value.addr, "#fff");
1774 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1775 bgs[0] = parse_color(value.addr, "#000");
1778 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1779 fgs[1] = parse_color(value.addr, "#fff");
1781 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1782 bgs[1] = parse_color(value.addr, "#000");
1784 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1786 paddings = parse_csslike(value.addr);
1787 if (paddings != NULL)
1788 for (i = 0; i < 4; ++i)
1789 r.c_padding[i] = parse_integer(paddings[i], 0);
1792 "Error while parsing "
1793 "MyMenu.completion.padding");
1796 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1798 sizes = parse_csslike(value.addr);
1800 for (i = 0; i < 4; ++i)
1801 r.c_borders[i] = parse_integer(sizes[i], 0);
1804 "Error while parsing "
1805 "MyMenu.completion.border.size");
1808 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1810 sizes = parse_csslike(value.addr);
1812 for (i = 0; i < 4; ++i)
1813 c_borders_bg[i] = parse_color(sizes[i], "#000");
1816 "Error while parsing "
1817 "MyMenu.completion.border.color");
1820 /* Completion Highlighted */
1822 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1823 fgs[2] = parse_color(value.addr, "#000");
1826 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1827 bgs[2] = parse_color(value.addr, "#fff");
1830 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1832 paddings = parse_csslike(value.addr);
1833 if (paddings != NULL)
1834 for (i = 0; i < 4; ++i)
1835 r.ch_padding[i] = parse_integer(paddings[i], 0);
1838 "Error while parsing "
1839 "MyMenu.completion_highlighted."
1843 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1846 sizes = parse_csslike(value.addr);
1848 for (i = 0; i < 4; ++i)
1849 r.ch_borders[i] = parse_integer(sizes[i], 0);
1852 "Error while parsing "
1853 "MyMenu.completion_highlighted."
1857 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1860 colors = parse_csslike(value.addr);
1862 for (i = 0; i < 4; ++i)
1863 ch_borders_bg[i] = parse_color(colors[i], "#000");
1866 "Error while parsing "
1867 "MyMenu.completion_highlighted."
1872 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1874 colors = parse_csslike(value.addr);
1876 for (i = 0; i < 4; ++i)
1877 borders_bg[i] = parse_color(colors[i], "#000");
1880 "error while parsing "
1881 "MyMenu.border.color\n");
1885 /* Second round of args parsing */
1886 optind = 0; /* reset the option index */
1887 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1890 r.first_selected = 1;
1893 /* free_text -- already catched */
1895 /* separator -- this case was already catched */
1897 /* embedding mymenu this case was already catched. */
1899 /* multiple selection this case was already catched.
1904 newprompt = strdup(optarg);
1905 if (newprompt != NULL) {
1912 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1915 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1919 if ((paddings = parse_csslike(optarg)) != NULL)
1920 for (i = 0; i < 4; ++i)
1921 r.p_padding[i] = parse_integer(paddings[i], 0);
1926 if ((colors = parse_csslike(optarg)) != NULL)
1927 for (i = 0; i < 4; ++i)
1928 p_borders_bg[i] = parse_color(colors[i], "#000");
1933 if ((sizes = parse_csslike(optarg)) != NULL)
1934 for (i = 0; i < 4; ++i)
1935 r.p_borders[i] = parse_integer(sizes[i], 0);
1940 if ((colors = parse_csslike(optarg)) != NULL)
1941 for (i = 0; i < 4; ++i)
1942 c_borders_bg[i] = parse_color(colors[i], "#000");
1947 if ((sizes = parse_csslike(optarg)) != NULL)
1948 for (i = 0; i < 4; ++i)
1949 r.c_borders[i] = parse_integer(sizes[i], 0);
1954 if ((colors = parse_csslike(optarg)) != NULL)
1955 for (i = 0; i < 4; ++i)
1956 ch_borders_bg[i] = parse_color(colors[i], "#000");
1961 if ((sizes = parse_csslike(optarg)) != NULL)
1962 for (i = 0; i < 4; ++i)
1963 r.ch_borders[i] = parse_integer(sizes[i], 0);
1967 r.horizontal_layout = !strcmp(optarg, "horizontal");
1971 if ((newfont = strdup(optarg)) != NULL) {
1978 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1981 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1985 if ((borders = parse_csslike(optarg)) != NULL) {
1986 for (i = 0; i < 4; ++i)
1987 r.borders[i] = parse_integer(borders[i], 0);
1989 fprintf(stderr, "Error parsing b option\n");
1994 if ((colors = parse_csslike(optarg)) != NULL) {
1995 for (i = 0; i < 4; ++i)
1996 borders_bg[i] = parse_color(colors[i], "#000");
1998 fprintf(stderr, "error while parsing B option\n");
2002 fgs[0] = parse_color(optarg, NULL);
2005 bgs[0] = parse_color(optarg, NULL);
2008 fgs[1] = parse_color(optarg, NULL);
2011 bgs[1] = parse_color(optarg, NULL);
2014 fgs[2] = parse_color(optarg, NULL);
2017 bgs[2] = parse_color(optarg, NULL);
2020 fprintf(stderr, "Unrecognized option %c\n", ch);
2026 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2027 fprintf(stderr, "height, width, x or y are lesser than 0.");
2031 /* since only now we know if the first should be selected,
2032 * update the completion here */
2033 update_completions(cs, text, lines, vlines, r.first_selected);
2035 /* update the prompt lenght, only now we surely know the length of it
2037 r.ps1len = strlen(r.ps1);
2039 /* Create the window */
2040 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2041 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2042 XMapRaised(r.d, r.w);
2044 /* If embed, listen for other events as well */
2046 Window *children, parent, root;
2047 unsigned int children_no;
2049 XSelectInput(r.d, parent_window, FocusChangeMask);
2050 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2052 for (i = 0; i < children_no && children[i] != r.w; ++i)
2053 XSelectInput(r.d, children[i], FocusChangeMask);
2056 grabfocus(r.d, r.w);
2059 take_keyboard(r.d, r.w);
2061 r.x_zero = r.borders[3];
2062 r.y_zero = r.borders[0];
2067 for (i = 0; i < 3; ++i) {
2068 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2069 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2072 for (i = 0; i < 4; ++i) {
2073 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2074 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2075 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2076 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2080 /* Load the colors in our GCs */
2081 for (i = 0; i < 3; ++i) {
2082 XSetForeground(r.d, r.fgs[i], fgs[i]);
2083 XSetForeground(r.d, r.bgs[i], bgs[i]);
2086 for (i = 0; i < 4; ++i) {
2087 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2088 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2089 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2090 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2093 if (load_font(&r, fontname) == -1)
2097 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2099 for (i = 0; i < 3; ++i) {
2101 XRenderColor xrcolor;
2103 c = *(rgba_t *)&fgs[i];
2104 xrcolor.red = EXPANDBITS(c.rgba.r);
2105 xrcolor.green = EXPANDBITS(c.rgba.g);
2106 xrcolor.blue = EXPANDBITS(c.rgba.b);
2107 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2108 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2112 /* compute prompt dimensions */
2118 if (pledge("stdio", "") == -1)
2122 /* Cache text height */
2123 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2125 /* Draw the window for the first time */
2129 while (status == LOOPING || status == OK_LOOP) {
2130 status = loop(&r, &text, &textlen, cs, lines, vlines);
2133 printf("%s\n", text);
2135 if (!r.multiple_select && status == OK_LOOP)
2139 XUngrabKeyboard(r.d, CurrentTime);
2142 for (i = 0; i < 3; ++i)
2143 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2146 for (i = 0; i < 3; ++i) {
2147 XFreeGC(r.d, r.fgs[i]);
2148 XFreeGC(r.d, r.bgs[i]);
2151 for (i = 0; i < 4; ++i) {
2152 XFreeGC(r.d, r.borders_bg[i]);
2153 XFreeGC(r.d, r.p_borders_bg[i]);
2154 XFreeGC(r.d, r.c_borders_bg[i]);
2155 XFreeGC(r.d, r.ch_borders_bg[i]);
2162 for (i = 0; i < 3; ++i)
2163 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2164 XftFontClose(r.d, r.font);
2165 XftDrawDestroy(r.xftdraw);
2167 XFreeFontSet(r.d, r.font);
2178 XFreeColormap(r.d, cmap);
2180 XDestroyWindow(r.d, r.w);
2183 return status != OK;