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 /* 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
63 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
64 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
66 /* The states of the event loop */
67 enum state { LOOPING, OK_LOOP, OK, ERR };
70 * For the drawing-related function. The text to be rendere could be
71 * the prompt, a completion or a highlighted completion
73 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
75 /* These are the possible action to be performed after user input. */
87 TOGGLE_FIRST_SELECTED,
92 /* A big set of values that needs to be carried around for drawing. A
93 * big struct to rule them all */
95 Display *d; /* Connection to xorg */
103 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
105 int y_zero; /* like x_zero but for the y axis */
107 int offset; /* scroll offset */
110 short first_selected;
111 short multiple_select;
113 /* four border width */
119 short horizontal_layout;
124 int ps1w; /* ps1 width */
125 int ps1h; /* ps1 height */
127 int text_height; /* cache for the vertical layout */
141 XftColor xft_colors[3];
150 int offset; /* the x (or y, depending on the layout) coordinate at
151 which the item is rendered */
154 /* Wrap the linked list of completions */
156 struct completion *completions;
161 /* idea stolen from lemonbar. ty lemonboy */
175 /* Return a newly allocated (and empty) completion list */
177 compls_new(size_t length)
179 struct completions *cs = malloc(sizeof(struct completions));
184 cs->completions = calloc(length, sizeof(struct completion));
185 if (cs->completions == NULL) {
195 /* Delete the wrapper and the whole list */
197 compls_delete(struct completions *cs)
202 free(cs->completions);
207 * Create a completion list from a text and the list of possible
208 * completions (null terminated). Expects a non-null `cs'. `lines' and
209 * `vlines' should have the same length OR `vlines' is NULL.
212 filter(struct completions *cs, char *text, char **lines, char **vlines)
222 if (lines[index] == NULL)
225 l = vlines[index] != NULL ? vlines[index] : lines[index];
227 if (strcasestr(l, text) != NULL) {
228 struct completion *c = &cs->completions[matching];
230 c->rcompletion = lines[index];
236 cs->length = matching;
240 /* Update the given completion */
242 update_completions(struct completions *cs, char *text, char **lines,
243 char **vlines, short first_selected)
245 filter(cs, text, lines, vlines);
246 if (first_selected && cs->length > 0)
251 * Select the next or previous selection and update some state. `text'
252 * will be updated with the text of the completion and `textlen' with
253 * the new length. If the memory cannot be allocated `status' will be
257 complete(struct completions *cs, short first_selected, short p, char **text,
258 int *textlen, enum state *status)
260 struct completion *n;
263 if (cs == NULL || cs->length == 0)
267 * If the first is always selected and the first entry is
268 * different from the text, expand the text and return
270 if (first_selected && cs->selected == 0
271 && strcmp(cs->completions->completion, *text) != 0 && !p) {
273 *text = strdup(cs->completions->completion);
278 *textlen = strlen(*text);
282 index = cs->selected;
284 if (index == -1 && p)
287 = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
289 n = &cs->completions[cs->selected];
292 *text = strdup(n->completion);
294 fprintf(stderr, "Memory allocation error!\n");
298 *textlen = strlen(*text);
301 /* Push the character c at the end of the string pointed by p */
303 pushc(char **p, int maxlen, char c)
307 len = strnlen(*p, maxlen);
308 if (!(len < maxlen - 2)) {
311 maxlen += maxlen >> 1;
312 newptr = realloc(*p, maxlen);
313 if (newptr == NULL) /* bad */
319 (*p)[len + 1] = '\0';
324 * Remove the last rune from the *UTF-8* string! This is different
325 * from just setting the last byte to 0 (in some cases ofc). Return a
326 * pointer (e) to the last nonzero char. If e < p then p is empty!
346 * If c is a starting byte (11......) or is under
349 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
356 /* Remove the last word plus trailing white spaces from the given string */
363 if ((len = strlen(w)) == 0)
372 if (in_word && isspace(*e))
375 if (!in_word && !isspace(*e))
381 * If the string is surrounded by quates (`"') remove them and replace
382 * every `\"' in the string with a single double-quote.
385 normalize_str(const char *str)
390 if ((len = strlen(str)) == 0)
393 if ((s = calloc(len, sizeof(char))) == NULL)
404 str += 2; /* skip this and the next char */
410 str++; /* skip only this char */
422 read_stdin(char **buf)
425 size_t len = STDIN_CHUNKS;
427 *buf = malloc(len * sizeof(char));
435 r = read(0, *buf + offset, STDIN_CHUNKS);
443 *buf = realloc(*buf, len);
447 for (i = offset; i < len; ++i)
452 fprintf(stderr, "Error in allocating memory for stdin.\n");
453 exit(EX_UNAVAILABLE);
457 readlines(char ***lns, char **buf)
459 size_t i, len, ll, lines;
465 len = read_stdin(buf);
468 *lns = malloc(ll * sizeof(char *));
473 for (i = 0; i < len; i++) {
482 if (in_line && c == '\n')
485 if (!in_line && c != '\n') {
487 (*lns)[lines] = (*buf) + i;
490 if (lines == ll) { /* resize */
492 *lns = realloc(*lns, ll * sizeof(char *));
499 (*lns)[lines] = NULL;
504 fprintf(stderr, "Error in memory allocation.\n");
505 exit(EX_UNAVAILABLE);
509 * Compute the dimensions of the string str once rendered.
510 * It'll return the width and set ret_width and ret_height if not NULL
513 text_extents(char *str, int len, struct rendering *r, int *ret_width,
519 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
520 height = r->font->ascent - r->font->descent;
521 width = gi.width - gi.x;
524 XmbTextExtents(r->font, str, len, NULL, &rect);
525 height = rect.height;
528 if (ret_width != NULL)
530 if (ret_height != NULL)
531 *ret_height = height;
536 draw_string(char *str, int len, int x, int y, struct rendering *r,
542 xftcolor = r->xft_colors[0];
544 xftcolor = r->xft_colors[1];
545 if (tt == COMPL_HIGH)
546 xftcolor = r->xft_colors[2];
548 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
555 if (tt == COMPL_HIGH)
557 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
561 /* Duplicate the string and substitute every space with a 'n` */
570 if (str == NULL || len == 0)
573 if ((dup = strdup(str)) == NULL)
576 for (i = 0; i < len; ++i)
584 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
585 enum obj_type t, char *text)
587 GC *border_color, bg;
588 int *padding, *borders;
589 int ret = 0, inner_width, inner_height, x;
593 border_color = r->p_borders_bg;
594 padding = r->p_padding;
595 borders = r->p_borders;
599 border_color = r->c_borders_bg;
600 padding = r->c_padding;
601 borders = r->c_borders;
605 border_color = r->ch_borders_bg;
606 padding = r->ch_padding;
607 borders = r->ch_borders;
612 ret = borders[0] + padding[0] + r->text_height + padding[2]
615 inner_width = inner_width(r) - borders[1] - borders[3];
616 inner_height = padding[0] + r->text_height + padding[2];
619 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
623 XFillRectangle(r->d, r->w, border_color[1],
624 r->x_zero + inner_width(r) - borders[1], y, borders[1], ret);
627 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
628 y + borders[0] + padding[0] + r->text_height + padding[2],
629 r->width, borders[2]);
633 r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
636 x = r->x_zero + borders[3];
638 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
641 y += padding[0] + r->text_height;
643 if (prefix != NULL) {
644 draw_string(prefix, strlen(prefix), x, y, r, t);
647 draw_string(text, strlen(text), x, y, r, t);
653 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
654 enum obj_type t, char *text)
656 GC *border_color, bg;
657 int *padding, *borders;
658 int ret = 0, inner_width, inner_height, y, text_width;
662 border_color = r->p_borders_bg;
663 padding = r->p_padding;
664 borders = r->p_borders;
668 border_color = r->c_borders_bg;
669 padding = r->c_padding;
670 borders = r->c_borders;
674 border_color = r->ch_borders_bg;
675 padding = r->ch_padding;
676 borders = r->ch_borders;
681 if (padding[0] < 0 || padding[2] < 0)
682 padding[0] = padding[2]
683 = (inner_height(r) - borders[0] - borders[2]
687 /* If they are still lesser than 0, set 'em to 0 */
688 if (padding[0] < 0 || padding[2] < 0)
689 padding[0] = padding[2] = 0;
691 /* Get the text width */
692 text_extents(text, strlen(text), r, &text_width, NULL);
694 text_width += prefix_width;
696 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
698 inner_width = padding[3] + text_width + padding[1];
699 inner_height = inner_height(r) - borders[0] - borders[2];
703 r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
706 XFillRectangle(r->d, r->w, border_color[1],
707 x + borders[3] + inner_width, r->y_zero, borders[1],
711 XFillRectangle(r->d, r->w, border_color[2], x,
712 r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
715 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
720 y = r->y_zero + borders[0];
721 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
724 y += padding[0] + r->text_height;
726 if (prefix != NULL) {
727 draw_string(prefix, strlen(prefix), x, y, r, t);
730 draw_string(text, strlen(text), x, y, r, t);
735 /* ,-----------------------------------------------------------------, */
736 /* | 20 char text | completion | completion | completion | compl | */
737 /* `-----------------------------------------------------------------' */
739 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
744 /* Draw the prompt */
745 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
747 for (i = r->offset; i < cs->length; ++i) {
749 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
751 cs->completions[i].offset = x;
754 r, x, NULL, 0, t, cs->completions[i].completion);
756 if (x > inner_width(r))
760 for (i += 1; i < cs->length; ++i)
761 cs->completions[i].offset = -1;
764 /* ,-----------------------------------------------------------------, */
766 /* |-----------------------------------------------------------------| */
768 /* |-----------------------------------------------------------------| */
770 /* `-----------------------------------------------------------------' */
772 draw_vertically(struct rendering *r, char *text, struct completions *cs)
777 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
779 for (i = r->offset; i < cs->length; ++i) {
781 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
783 cs->completions[i].offset = y;
786 r, y, NULL, 0, t, cs->completions[i].completion);
788 if (y > inner_height(r))
792 for (i += 1; i < cs->length; ++i)
793 cs->completions[i].offset = -1;
797 draw(struct rendering *r, char *text, struct completions *cs)
799 /* Draw the background */
800 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
801 inner_width(r), inner_height(r));
803 /* Draw the contents */
804 if (r->horizontal_layout)
805 draw_horizontally(r, text, cs);
807 draw_vertically(r, text, cs);
809 /* Draw the borders */
810 if (r->borders[0] != 0)
811 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
814 if (r->borders[1] != 0)
815 XFillRectangle(r->d, r->w, r->borders_bg[1],
816 r->width - r->borders[1], 0, r->borders[1],
819 if (r->borders[2] != 0)
820 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
821 r->height - r->borders[2], r->width, r->borders[2]);
823 if (r->borders[3] != 0)
824 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
825 r->borders[3], r->height);
831 /* Set some WM stuff */
833 set_win_atoms_hints(Display *d, Window w, int width, int height)
836 XClassHint *class_hint;
837 XSizeHints *size_hint;
839 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
840 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
841 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
842 (unsigned char *)&type, 1);
844 /* some window managers honor this properties */
845 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
846 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
847 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
848 (unsigned char *)&type, 1);
850 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
851 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
852 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
853 (unsigned char *)&type, 1);
855 /* Setting window hints */
856 class_hint = XAllocClassHint();
857 if (class_hint == NULL) {
858 fprintf(stderr, "Could not allocate memory for class hint\n");
859 exit(EX_UNAVAILABLE);
862 class_hint->res_name = resname;
863 class_hint->res_class = resclass;
864 XSetClassHint(d, w, class_hint);
867 size_hint = XAllocSizeHints();
868 if (size_hint == NULL) {
869 fprintf(stderr, "Could not allocate memory for size hint\n");
870 exit(EX_UNAVAILABLE);
873 size_hint->flags = PMinSize | PBaseSize;
874 size_hint->min_width = width;
875 size_hint->base_width = width;
876 size_hint->min_height = height;
877 size_hint->base_height = height;
882 /* Get the width and height of the window `w' */
884 get_wh(Display *d, Window *w, int *width, int *height)
886 XWindowAttributes win_attr;
888 XGetWindowAttributes(d, *w, &win_attr);
889 *height = win_attr.height;
890 *width = win_attr.width;
894 grabfocus(Display *d, Window w)
897 for (i = 0; i < 100; ++i) {
901 XGetInputFocus(d, &focuswin, &revert_to_win);
906 XSetInputFocus(d, w, RevertToParent, CurrentTime);
913 * I know this may seem a little hackish BUT is the only way I managed
914 * to actually grab that goddam keyboard. Only one call to
915 * XGrabKeyboard does not always end up with the keyboard grabbed!
918 take_keyboard(Display *d, Window w)
921 for (i = 0; i < 100; i++) {
922 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
928 fprintf(stderr, "Cannot grab keyboard\n");
933 parse_color(const char *str, const char *def)
944 /* +1 for the # ath the start */
945 if (*str != '#' || len > 9 || len < 4)
947 ++str; /* skip the # */
950 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
957 /* expand #rgb -> #rrggbb */
958 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
959 | (tmp.v & 0x00f) * 0x0011;
961 /* assume 0xff opacity */
964 } /* colors in #aarrggbb need no adjustments */
966 /* premultiply the alpha */
968 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
969 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
970 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
977 fprintf(stderr, "Invalid color: \"%s\".\n", str);
979 return parse_color(def, NULL);
985 * Given a string try to parse it as a number or return `default_value'.
988 parse_integer(const char *str, int default_value)
994 lval = strtol(str, &ep, 10);
996 if (str[0] == '\0' || *ep != '\0') { /* NaN */
998 "'%s' is not a valid number! Using %d as default.\n",
1000 return default_value;
1003 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
1004 || (lval > INT_MAX || lval < INT_MIN)) {
1005 fprintf(stderr, "%s out of range! Using %d as default.\n",
1006 str, default_value);
1007 return default_value;
1013 /* Like parse_integer but recognize the percentages (i.e. strings ending with
1016 parse_int_with_percentage(const char *str, int default_value, int max)
1018 int len = strlen(str);
1020 if (len > 0 && str[len - 1] == '%') {
1024 if ((cpy = strdup(str)) == NULL)
1027 cpy[len - 1] = '\0';
1028 val = parse_integer(cpy, default_value);
1030 return val * max / 100;
1033 return parse_integer(str, default_value);
1037 * Like parse_int_with_percentage but understands some special values:
1038 * - middle that is (max-self)/2
1040 * - end that is (max-self)
1043 parse_int_with_pos(const char *str, int default_value, int max, int self)
1045 if (!strcmp(str, "start"))
1047 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1048 return (max - self) / 2;
1049 if (!strcmp(str, "end"))
1051 return parse_int_with_percentage(str, default_value, max);
1054 /* Parse a string like a CSS value. */
1055 /* TODO: harden a bit this function */
1057 parse_csslike(const char *str)
1060 char *s, *token, **ret;
1067 ret = malloc(4 * sizeof(char *));
1073 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1074 ret[i] = strdup(token);
1077 for (j = 1; j < 4; j++)
1078 ret[j] = strdup(ret[0]);
1081 ret[2] = strdup(ret[0]);
1082 ret[3] = strdup(ret[1]);
1086 ret[3] = strdup(ret[1]);
1088 /* before we didn't check for the return type of strdup, here we will
1092 for (i = 0; i < 4; ++i)
1093 any_null = ret[i] == NULL || any_null;
1096 for (i = 0; i < 4; ++i)
1100 if (i == 0 || any_null) {
1110 * Given an event, try to understand what the users wants. If the
1111 * return value is ADD_CHAR then `input' is a pointer to a string that
1112 * will need to be free'ed later.
1115 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1117 char str[SYM_BUF_SIZE] = { 0 };
1120 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1123 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1124 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1126 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1129 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1132 /* Try to read what key was pressed */
1134 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1135 if (s == XBufferOverflow) {
1137 "Buffer overflow when trying to create keyboard "
1142 if (ev->state & ControlMask) {
1143 if (!strcmp(str, "")) /* C-u */
1145 if (!strcmp(str, "")) /* C-w */
1147 if (!strcmp(str, "")) /* C-h */
1149 if (!strcmp(str, "\r")) /* C-m */
1150 return CONFIRM_CONTINUE;
1151 if (!strcmp(str, "")) /* C-p */
1153 if (!strcmp(str, "")) /* C-n */
1155 if (!strcmp(str, "")) /* C-c */
1157 if (!strcmp(str, "\t")) /* C-i */
1158 return TOGGLE_FIRST_SELECTED;
1161 *input = strdup(str);
1162 if (*input == NULL) {
1163 fprintf(stderr, "Error while allocating memory for key.\n");
1171 confirm(enum state *status, struct rendering *r, struct completions *cs,
1172 char **text, int *textlen)
1174 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1175 /* if there is something selected expand it and return */
1176 int index = cs->selected == -1 ? 0 : cs->selected;
1177 struct completion *c = cs->completions;
1191 if (*text == NULL) {
1192 fprintf(stderr, "Memory allocation error\n");
1196 *textlen = strlen(*text);
1200 if (!r->free_text) /* cannot accept arbitrary text */
1204 /* cs: completion list
1205 * offset: the offset of the click
1206 * first: the first (rendered) item
1207 * def: the default action
1211 struct completions *cs, size_t offset, size_t first, enum action def)
1213 ssize_t selected = first;
1216 if (cs->length == 0)
1219 if (offset < cs->completions[selected].offset)
1222 /* skip the first entry */
1223 for (selected += 1; selected < cs->length; ++selected) {
1224 if (cs->completions[selected].offset == -1) {
1225 printf("caught -1\n");
1228 if (offset < cs->completions[selected].offset) {
1229 cs->selected = selected - 1;
1236 cs->selected = selected - 1;
1243 struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1247 if (r->horizontal_layout)
1252 switch (e->button) {
1254 return select_clicked(cs, off, r->offset, CONFIRM);
1257 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1271 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1272 char **lines, char **vlines)
1274 enum state status = LOOPING;
1276 while (status == LOOPING) {
1278 XNextEvent(r->d, &e);
1280 if (XFilterEvent(&e, r->w))
1285 XRefreshKeyboardMapping(&e.xmapping);
1290 if (e.xfocus.window != r->w)
1291 grabfocus(r->d, r->w);
1294 case VisibilityNotify:
1295 if (e.xvisibility.state != VisibilityUnobscured)
1296 XRaiseWindow(r->d, r->w);
1300 get_wh(r->d, &r->w, &r->width, &r->height);
1309 if (e.type == KeyPress)
1310 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1314 r, cs, (XButtonPressedEvent *)&e);
1326 confirm(&status, r, cs, text, textlen);
1330 case CONFIRM_CONTINUE: {
1332 confirm(&status, r, cs, text, textlen);
1337 complete(cs, r->first_selected, 1, text,
1339 r->offset = cs->selected;
1344 complete(cs, r->first_selected, 0, text,
1346 r->offset = cs->selected;
1352 update_completions(cs, *text, lines, vlines,
1359 update_completions(cs, *text, lines, vlines,
1366 for (i = 0; i < *textlen; ++i)
1368 update_completions(cs, *text, lines, vlines,
1377 str_len = strlen(input);
1380 * sometimes a strange key is pressed
1381 * i.e. ctrl alone), so input will be
1382 * empty. Don't need to update
1383 * completion in that case
1388 for (i = 0; i < str_len; ++i) {
1390 text, *textlen, input[i]);
1391 if (*textlen == -1) {
1393 "Memory allocation "
1400 if (status != ERR) {
1401 update_completions(cs, *text, lines,
1402 vlines, r->first_selected);
1410 case TOGGLE_FIRST_SELECTED:
1411 r->first_selected = !r->first_selected;
1412 if (r->first_selected && cs->selected < 0)
1414 if (!r->first_selected && cs->selected == 0)
1420 = MIN(r->offset + 1, cs->length - 1);
1424 r->offset = MAX((ssize_t)r->offset - 1, 0);
1437 load_font(struct rendering *r, const char *fontname)
1440 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1443 char **missing_charset_list;
1444 int missing_charset_count;
1446 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1447 &missing_charset_count, NULL);
1448 if (r->font != NULL)
1451 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1453 if (!strcmp(fontname, default_fontname))
1456 return load_font(r, default_fontname);
1461 xim_init(struct rendering *r, XrmDatabase *xdb)
1463 XIMStyle best_match_style;
1467 /* Open the X input method */
1468 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1471 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1472 fprintf(stderr, "Input Styles could not be retrieved\n");
1473 exit(EX_UNAVAILABLE);
1476 best_match_style = 0;
1477 for (i = 0; i < xis->count_styles; ++i) {
1478 XIMStyle ts = xis->supported_styles[i];
1479 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1480 best_match_style = ts;
1486 if (!best_match_style)
1488 "No matching input style could be determined\n");
1490 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1491 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1493 err(1, "XCreateIC");
1497 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1498 XVisualInfo vinfo, int x, int y, int ox, int oy,
1499 unsigned long background_pixel)
1501 XSetWindowAttributes attr;
1503 /* Create the window */
1504 attr.colormap = cmap;
1505 attr.override_redirect = 1;
1506 attr.border_pixel = 0;
1507 attr.background_pixel = background_pixel;
1508 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1509 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1511 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1512 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1513 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1514 | CWOverrideRedirect,
1519 ps1extents(struct rendering *r)
1522 dup = strdupn(r->ps1);
1524 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1529 usage(char *prgname)
1532 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1533 " [-d separator] [-e window] [-f font] [-G color] [-g "
1535 " [-H height] [-I color] [-i size] [-J color] [-j "
1536 "size] [-l layout]\n"
1537 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1539 " [-t color] [-W width] [-x coord] [-y coord]\n",
1544 main(int argc, char **argv)
1546 struct completions *cs;
1551 Window parent_window;
1553 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1554 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1555 ch_borders_bg[4]; /* N E S W */
1558 int offset_x, offset_y, x, y;
1559 int textlen, d_width, d_height;
1561 char *sep, *parent_window_id;
1562 char **lines, *buf, **vlines;
1563 char *fontname, *text, *xrm;
1566 /* stdio & rpath: to read/write stdio/stdout/stderr */
1567 /* unix: to connect to XOrg */
1568 pledge("stdio rpath unix", "");
1572 parent_window_id = NULL;
1574 r.first_selected = 0;
1576 r.multiple_select = 0;
1579 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1581 case 'h': /* help */
1584 case 'v': /* version */
1585 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1587 case 'e': /* embed */
1588 if ((parent_window_id = strdup(optarg)) == NULL)
1592 if ((sep = strdup(optarg)) == NULL)
1599 r.multiple_select = 1;
1606 /* Read the completions */
1609 nlines = readlines(&lines, &buf);
1615 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1618 for (i = 0; i < nlines; i++) {
1620 t = strstr(lines[i], sep);
1622 vlines[i] = lines[i];
1628 setlocale(LC_ALL, getenv("LANG"));
1632 /* where the monitor start (used only with xinerama) */
1633 offset_x = offset_y = 0;
1635 /* default width and height */
1639 /* default position on the screen */
1642 for (i = 0; i < 4; ++i) {
1643 /* default paddings */
1644 r.p_padding[i] = 10;
1645 r.c_padding[i] = 10;
1646 r.ch_padding[i] = 10;
1648 /* default borders */
1652 r.ch_borders[i] = 0;
1655 /* the prompt. We duplicate the string so later is easy to
1656 * free (in the case it's been overwritten by the user) */
1657 if ((r.ps1 = strdup("$ ")) == NULL)
1660 /* same for the font name */
1661 if ((fontname = strdup(default_fontname)) == NULL)
1665 if ((text = malloc(textlen * sizeof(char))) == NULL)
1668 /* struct completions *cs = filter(text, lines); */
1669 if ((cs = compls_new(nlines)) == NULL)
1670 err(1, "compls_new");
1672 /* start talking to xorg */
1673 r.d = XOpenDisplay(NULL);
1675 fprintf(stderr, "Could not open display!\n");
1676 return EX_UNAVAILABLE;
1680 if (!(parent_window_id
1681 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1682 parent_window = DefaultRootWindow(r.d);
1686 /* get display size */
1687 get_wh(r.d, &parent_window, &d_width, &d_height);
1690 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1691 XineramaScreenInfo *info;
1694 int number_of_screens, monitors, i;
1695 int root_x, root_y, win_x, win_y;
1699 number_of_screens = XScreenCount(r.d);
1700 for (i = 0; i < number_of_screens; ++i) {
1701 root = XRootWindow(r.d, i);
1702 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1703 &root_y, &win_x, &win_y, &mask);
1709 fprintf(stderr, "No mouse found.\n");
1714 /* Now find in which monitor the mice is */
1715 info = XineramaQueryScreens(r.d, &monitors);
1717 for (i = 0; i < monitors; ++i) {
1718 if (info[i].x_org <= root_x
1719 && root_x <= (info[i].x_org
1721 && info[i].y_org <= root_y
1722 && root_y <= (info[i].y_org
1723 + info[i].height)) {
1724 offset_x = info[i].x_org;
1725 offset_y = info[i].y_org;
1726 d_width = info[i].width;
1727 d_height = info[i].height;
1736 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1737 cmap = XCreateColormap(
1738 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1740 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1741 fgs[2] = parse_color("#000", NULL);
1743 bgs[0] = bgs[1] = parse_color("#000", NULL);
1744 bgs[2] = parse_color("#fff", NULL);
1746 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1747 = parse_color("#000", NULL);
1749 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1750 = parse_color("#000", NULL);
1751 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1752 = parse_color("#000", NULL);
1753 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1754 = ch_borders_bg[3] = parse_color("#000", NULL);
1756 r.horizontal_layout = 1;
1758 /* Read the resources */
1760 xrm = XResourceManagerString(r.d);
1766 xdb = XrmGetStringDatabase(xrm);
1768 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1771 if ((fontname = strdup(value.addr)) == NULL)
1774 fprintf(stderr, "no font defined, using %s\n",
1779 xdb, "MyMenu.layout", "*", datatype, &value)
1782 = !strcmp(value.addr, "horizontal");
1785 "no layout defined, using horizontal\n");
1788 xdb, "MyMenu.prompt", "*", datatype, &value)
1791 r.ps1 = normalize_str(value.addr);
1794 "no prompt defined, using \"%s\" as "
1799 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1803 sizes = parse_csslike(value.addr);
1805 for (i = 0; i < 4; ++i)
1807 = parse_integer(sizes[i], 0);
1810 "error while parsing "
1811 "MyMenu.prompt.border.size");
1814 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1818 colors = parse_csslike(value.addr);
1820 for (i = 0; i < 4; ++i)
1821 p_borders_bg[i] = parse_color(
1825 "error while parsing "
1826 "MyMenu.prompt.border.color");
1829 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1833 colors = parse_csslike(value.addr);
1835 for (i = 0; i < 4; ++i)
1837 = parse_integer(colors[i], 0);
1840 "error while parsing "
1841 "MyMenu.prompt.padding");
1844 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1846 r.width = parse_int_with_percentage(
1847 value.addr, r.width, d_width);
1849 fprintf(stderr, "no width defined, using %d\n",
1853 xdb, "MyMenu.height", "*", datatype, &value)
1855 r.height = parse_int_with_percentage(
1856 value.addr, r.height, d_height);
1858 fprintf(stderr, "no height defined, using %d\n",
1861 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1863 x = parse_int_with_pos(
1864 value.addr, x, d_width, r.width);
1866 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1868 y = parse_int_with_pos(
1869 value.addr, y, d_height, r.height);
1872 xdb, "MyMenu.border.size", "*", datatype, &value)
1875 borders = parse_csslike(value.addr);
1876 if (borders != NULL)
1877 for (i = 0; i < 4; ++i)
1879 = parse_int_with_percentage(
1886 "error while parsing "
1887 "MyMenu.border.size\n");
1891 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1894 fgs[0] = parse_color(value.addr, "#fff");
1896 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1899 bgs[0] = parse_color(value.addr, "#000");
1902 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1905 fgs[1] = parse_color(value.addr, "#fff");
1907 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1910 bgs[1] = parse_color(value.addr, "#000");
1912 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1916 paddings = parse_csslike(value.addr);
1917 if (paddings != NULL)
1918 for (i = 0; i < 4; ++i)
1919 r.c_padding[i] = parse_integer(
1923 "Error while parsing "
1924 "MyMenu.completion.padding");
1927 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1931 sizes = parse_csslike(value.addr);
1933 for (i = 0; i < 4; ++i)
1935 = parse_integer(sizes[i], 0);
1938 "Error while parsing "
1939 "MyMenu.completion.border.size");
1942 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1946 sizes = parse_csslike(value.addr);
1948 for (i = 0; i < 4; ++i)
1949 c_borders_bg[i] = parse_color(
1953 "Error while parsing "
1954 "MyMenu.completion.border.color");
1957 /* Completion Highlighted */
1958 if (XrmGetResource(xdb,
1959 "MyMenu.completion_highlighted.foreground", "*",
1962 fgs[2] = parse_color(value.addr, "#000");
1964 if (XrmGetResource(xdb,
1965 "MyMenu.completion_highlighted.background", "*",
1968 bgs[2] = parse_color(value.addr, "#fff");
1970 if (XrmGetResource(xdb,
1971 "MyMenu.completion_highlighted.padding", "*",
1975 paddings = parse_csslike(value.addr);
1976 if (paddings != NULL)
1977 for (i = 0; i < 4; ++i)
1978 r.ch_padding[i] = parse_integer(
1982 "Error while parsing "
1983 "MyMenu.completion_highlighted."
1987 if (XrmGetResource(xdb,
1988 "MyMenu.completion_highlighted.border.size", "*",
1992 sizes = parse_csslike(value.addr);
1994 for (i = 0; i < 4; ++i)
1996 = parse_integer(sizes[i], 0);
1999 "Error while parsing "
2000 "MyMenu.completion_highlighted."
2004 if (XrmGetResource(xdb,
2005 "MyMenu.completion_highlighted.border.color", "*",
2009 colors = parse_csslike(value.addr);
2011 for (i = 0; i < 4; ++i)
2012 ch_borders_bg[i] = parse_color(
2016 "Error while parsing "
2017 "MyMenu.completion_highlighted."
2023 xdb, "MyMenu.border.color", "*", datatype, &value)
2026 colors = parse_csslike(value.addr);
2028 for (i = 0; i < 4; ++i)
2029 borders_bg[i] = parse_color(
2033 "error while parsing "
2034 "MyMenu.border.color\n");
2038 /* Second round of args parsing */
2039 optind = 0; /* reset the option index */
2040 while ((ch = getopt(argc, argv, ARGS)) != -1) {
2043 r.first_selected = 1;
2046 /* free_text -- already catched */
2048 /* separator -- this case was already catched */
2050 /* embedding mymenu this case was already catched. */
2052 /* multiple selection this case was already catched.
2057 newprompt = strdup(optarg);
2058 if (newprompt != NULL) {
2065 x = parse_int_with_pos(optarg, x, d_width, r.width);
2068 y = parse_int_with_pos(optarg, y, d_height, r.height);
2072 if ((paddings = parse_csslike(optarg)) != NULL)
2073 for (i = 0; i < 4; ++i)
2074 r.p_padding[i] = parse_integer(
2080 if ((colors = parse_csslike(optarg)) != NULL)
2081 for (i = 0; i < 4; ++i)
2082 p_borders_bg[i] = parse_color(
2088 if ((sizes = parse_csslike(optarg)) != NULL)
2089 for (i = 0; i < 4; ++i)
2091 = parse_integer(sizes[i], 0);
2096 if ((colors = parse_csslike(optarg)) != NULL)
2097 for (i = 0; i < 4; ++i)
2098 c_borders_bg[i] = parse_color(
2104 if ((sizes = parse_csslike(optarg)) != NULL)
2105 for (i = 0; i < 4; ++i)
2107 = parse_integer(sizes[i], 0);
2112 if ((colors = parse_csslike(optarg)) != NULL)
2113 for (i = 0; i < 4; ++i)
2114 ch_borders_bg[i] = parse_color(
2120 if ((sizes = parse_csslike(optarg)) != NULL)
2121 for (i = 0; i < 4; ++i)
2123 = parse_integer(sizes[i], 0);
2127 r.horizontal_layout = !strcmp(optarg, "horizontal");
2131 if ((newfont = strdup(optarg)) != NULL) {
2138 r.width = parse_int_with_percentage(
2139 optarg, r.width, d_width);
2142 r.height = parse_int_with_percentage(
2143 optarg, r.height, d_height);
2147 if ((borders = parse_csslike(optarg)) != NULL) {
2148 for (i = 0; i < 4; ++i)
2149 r.borders[i] = parse_integer(
2152 fprintf(stderr, "Error parsing b option\n");
2157 if ((colors = parse_csslike(optarg)) != NULL) {
2158 for (i = 0; i < 4; ++i)
2159 borders_bg[i] = parse_color(
2163 "error while parsing B option\n");
2167 fgs[0] = parse_color(optarg, NULL);
2170 bgs[0] = parse_color(optarg, NULL);
2173 fgs[1] = parse_color(optarg, NULL);
2176 bgs[1] = parse_color(optarg, NULL);
2179 fgs[2] = parse_color(optarg, NULL);
2182 fgs[2] = parse_color(optarg, NULL);
2185 fprintf(stderr, "Unrecognized option %c\n", ch);
2191 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2192 fprintf(stderr, "height, width, x or y are lesser than 0.");
2196 /* since only now we know if the first should be selected,
2197 * update the completion here */
2198 update_completions(cs, text, lines, vlines, r.first_selected);
2200 /* update the prompt lenght, only now we surely know the length of it
2202 r.ps1len = strlen(r.ps1);
2204 /* Create the window */
2205 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2207 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2208 XMapRaised(r.d, r.w);
2210 /* If embed, listen for other events as well */
2212 Window *children, parent, root;
2213 unsigned int children_no;
2215 XSelectInput(r.d, parent_window, FocusChangeMask);
2216 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2219 for (i = 0; i < children_no && children[i] != r.w;
2222 r.d, children[i], FocusChangeMask);
2225 grabfocus(r.d, r.w);
2228 take_keyboard(r.d, r.w);
2230 r.x_zero = r.borders[3];
2231 r.y_zero = r.borders[0];
2236 for (i = 0; i < 3; ++i) {
2237 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2238 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2241 for (i = 0; i < 4; ++i) {
2242 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2243 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2244 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2245 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2249 /* Load the colors in our GCs */
2250 for (i = 0; i < 3; ++i) {
2251 XSetForeground(r.d, r.fgs[i], fgs[i]);
2252 XSetForeground(r.d, r.bgs[i], bgs[i]);
2255 for (i = 0; i < 4; ++i) {
2256 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2257 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2258 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2259 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2262 if (load_font(&r, fontname) == -1)
2266 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2268 for (i = 0; i < 3; ++i) {
2270 XRenderColor xrcolor;
2272 c = *(rgba_t *)&fgs[i];
2273 xrcolor.red = EXPANDBITS(c.rgba.r);
2274 xrcolor.green = EXPANDBITS(c.rgba.g);
2275 xrcolor.blue = EXPANDBITS(c.rgba.b);
2276 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2278 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2282 /* compute prompt dimensions */
2288 /* Now we need only the ability to write */
2289 pledge("stdio", "");
2292 /* Cache text height */
2293 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2295 /* Draw the window for the first time */
2299 while (status == LOOPING || status == OK_LOOP) {
2300 status = loop(&r, &text, &textlen, cs, lines, vlines);
2303 printf("%s\n", text);
2305 if (!r.multiple_select && status == OK_LOOP)
2309 XUngrabKeyboard(r.d, CurrentTime);
2312 for (i = 0; i < 3; ++i)
2313 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2316 for (i = 0; i < 3; ++i) {
2317 XFreeGC(r.d, r.fgs[i]);
2318 XFreeGC(r.d, r.bgs[i]);
2321 for (i = 0; i < 4; ++i) {
2322 XFreeGC(r.d, r.borders_bg[i]);
2323 XFreeGC(r.d, r.p_borders_bg[i]);
2324 XFreeGC(r.d, r.c_borders_bg[i]);
2325 XFreeGC(r.d, r.ch_borders_bg[i]);
2332 for (i = 0; i < 3; ++i)
2333 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2334 XftFontClose(r.d, r.font);
2335 XftDrawDestroy(r.xftdraw);
2337 XFreeFontSet(r.d, r.font);
2349 XFreeColormap(r.d, cmap);
2351 XDestroyWindow(r.d, r.w);
2354 return status != OK;