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 get_mouse_coords(Display *d, int *x, int *y)
1044 root = DefaultRootWindow(d);
1046 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1047 for (i = 0; i < ScreenCount(d); ++i) {
1048 if (root == RootWindow(d, i))
1055 * Like parse_int_with_percentage but understands some special values:
1056 * - middle that is (max-self)/2
1059 * - end that is (max-self)
1060 * - mx x coordinate of the mouse
1061 * - my y coordinate of the mouse
1065 Display *d, const char *str, int default_value, int max, int self)
1067 if (!strcmp(str, "start"))
1069 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1070 return (max - self) / 2;
1071 if (!strcmp(str, "end"))
1073 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1076 get_mouse_coords(d, &x, &y);
1077 if (!strcmp(str, "mx"))
1082 return parse_int_with_percentage(str, default_value, max);
1085 /* Parse a string like a CSS value. */
1086 /* TODO: harden a bit this function */
1088 parse_csslike(const char *str)
1091 char *s, *token, **ret;
1098 ret = malloc(4 * sizeof(char *));
1104 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1105 ret[i] = strdup(token);
1108 for (j = 1; j < 4; j++)
1109 ret[j] = strdup(ret[0]);
1112 ret[2] = strdup(ret[0]);
1113 ret[3] = strdup(ret[1]);
1117 ret[3] = strdup(ret[1]);
1119 /* before we didn't check for the return type of strdup, here we will
1123 for (i = 0; i < 4; ++i)
1124 any_null = ret[i] == NULL || any_null;
1127 for (i = 0; i < 4; ++i)
1131 if (i == 0 || any_null) {
1141 * Given an event, try to understand what the users wants. If the
1142 * return value is ADD_CHAR then `input' is a pointer to a string that
1143 * will need to be free'ed later.
1146 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1148 char str[SYM_BUF_SIZE] = { 0 };
1151 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1154 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1155 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1157 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1160 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1163 /* Try to read what key was pressed */
1165 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1166 if (s == XBufferOverflow) {
1168 "Buffer overflow when trying to create keyboard "
1173 if (ev->state & ControlMask) {
1174 if (!strcmp(str, "")) /* C-u */
1176 if (!strcmp(str, "")) /* C-w */
1178 if (!strcmp(str, "")) /* C-h */
1180 if (!strcmp(str, "\r")) /* C-m */
1181 return CONFIRM_CONTINUE;
1182 if (!strcmp(str, "")) /* C-p */
1184 if (!strcmp(str, "")) /* C-n */
1186 if (!strcmp(str, "")) /* C-c */
1188 if (!strcmp(str, "\t")) /* C-i */
1189 return TOGGLE_FIRST_SELECTED;
1192 *input = strdup(str);
1193 if (*input == NULL) {
1194 fprintf(stderr, "Error while allocating memory for key.\n");
1202 confirm(enum state *status, struct rendering *r, struct completions *cs,
1203 char **text, int *textlen)
1205 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1206 /* if there is something selected expand it and return */
1207 int index = cs->selected == -1 ? 0 : cs->selected;
1208 struct completion *c = cs->completions;
1222 if (*text == NULL) {
1223 fprintf(stderr, "Memory allocation error\n");
1227 *textlen = strlen(*text);
1231 if (!r->free_text) /* cannot accept arbitrary text */
1235 /* cs: completion list
1236 * offset: the offset of the click
1237 * first: the first (rendered) item
1238 * def: the default action
1242 struct completions *cs, size_t offset, size_t first, enum action def)
1244 ssize_t selected = first;
1247 if (cs->length == 0)
1250 if (offset < cs->completions[selected].offset)
1253 /* skip the first entry */
1254 for (selected += 1; selected < cs->length; ++selected) {
1255 if (cs->completions[selected].offset == -1)
1258 if (offset < cs->completions[selected].offset) {
1259 cs->selected = selected - 1;
1266 cs->selected = selected - 1;
1273 struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1277 if (r->horizontal_layout)
1282 switch (e->button) {
1284 return select_clicked(cs, off, r->offset, CONFIRM);
1287 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1301 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1302 char **lines, char **vlines)
1304 enum state status = LOOPING;
1306 while (status == LOOPING) {
1308 XNextEvent(r->d, &e);
1310 if (XFilterEvent(&e, r->w))
1315 XRefreshKeyboardMapping(&e.xmapping);
1320 if (e.xfocus.window != r->w)
1321 grabfocus(r->d, r->w);
1324 case VisibilityNotify:
1325 if (e.xvisibility.state != VisibilityUnobscured)
1326 XRaiseWindow(r->d, r->w);
1330 get_wh(r->d, &r->w, &r->width, &r->height);
1339 if (e.type == KeyPress)
1340 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1344 r, cs, (XButtonPressedEvent *)&e);
1356 confirm(&status, r, cs, text, textlen);
1360 case CONFIRM_CONTINUE: {
1362 confirm(&status, r, cs, text, textlen);
1367 complete(cs, r->first_selected, 1, text,
1369 r->offset = cs->selected;
1374 complete(cs, r->first_selected, 0, text,
1376 r->offset = cs->selected;
1382 update_completions(cs, *text, lines, vlines,
1389 update_completions(cs, *text, lines, vlines,
1396 for (i = 0; i < *textlen; ++i)
1398 update_completions(cs, *text, lines, vlines,
1407 str_len = strlen(input);
1410 * sometimes a strange key is pressed
1411 * i.e. ctrl alone), so input will be
1412 * empty. Don't need to update
1413 * completion in that case
1418 for (i = 0; i < str_len; ++i) {
1420 text, *textlen, input[i]);
1421 if (*textlen == -1) {
1423 "Memory allocation "
1430 if (status != ERR) {
1431 update_completions(cs, *text, lines,
1432 vlines, r->first_selected);
1440 case TOGGLE_FIRST_SELECTED:
1441 r->first_selected = !r->first_selected;
1442 if (r->first_selected && cs->selected < 0)
1444 if (!r->first_selected && cs->selected == 0)
1450 = MIN(r->offset + 1, cs->length - 1);
1454 r->offset = MAX((ssize_t)r->offset - 1, 0);
1467 load_font(struct rendering *r, const char *fontname)
1470 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1473 char **missing_charset_list;
1474 int missing_charset_count;
1476 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1477 &missing_charset_count, NULL);
1478 if (r->font != NULL)
1481 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1483 if (!strcmp(fontname, default_fontname))
1486 return load_font(r, default_fontname);
1491 xim_init(struct rendering *r, XrmDatabase *xdb)
1493 XIMStyle best_match_style;
1497 /* Open the X input method */
1498 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1501 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1502 fprintf(stderr, "Input Styles could not be retrieved\n");
1503 exit(EX_UNAVAILABLE);
1506 best_match_style = 0;
1507 for (i = 0; i < xis->count_styles; ++i) {
1508 XIMStyle ts = xis->supported_styles[i];
1509 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1510 best_match_style = ts;
1516 if (!best_match_style)
1518 "No matching input style could be determined\n");
1520 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1521 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1523 err(1, "XCreateIC");
1527 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1528 XVisualInfo vinfo, int x, int y, int ox, int oy,
1529 unsigned long background_pixel)
1531 XSetWindowAttributes attr;
1533 /* Create the window */
1534 attr.colormap = cmap;
1535 attr.override_redirect = 1;
1536 attr.border_pixel = 0;
1537 attr.background_pixel = background_pixel;
1538 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1539 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1541 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1542 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1543 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1544 | CWOverrideRedirect,
1549 ps1extents(struct rendering *r)
1552 dup = strdupn(r->ps1);
1554 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1559 usage(char *prgname)
1562 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1563 " [-d separator] [-e window] [-f font] [-G color] [-g "
1565 " [-H height] [-I color] [-i size] [-J color] [-j "
1566 "size] [-l layout]\n"
1567 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1569 " [-t color] [-W width] [-x coord] [-y coord]\n",
1574 main(int argc, char **argv)
1576 struct completions *cs;
1581 Window parent_window;
1583 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1584 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1585 ch_borders_bg[4]; /* N E S W */
1588 int offset_x, offset_y, x, y;
1589 int textlen, d_width, d_height;
1591 char *sep, *parent_window_id;
1592 char **lines, *buf, **vlines;
1593 char *fontname, *text, *xrm;
1596 /* stdio & rpath: to read/write stdio/stdout/stderr */
1597 /* unix: to connect to XOrg */
1598 pledge("stdio rpath unix", "");
1602 parent_window_id = NULL;
1604 r.first_selected = 0;
1606 r.multiple_select = 0;
1609 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1611 case 'h': /* help */
1614 case 'v': /* version */
1615 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1617 case 'e': /* embed */
1618 if ((parent_window_id = strdup(optarg)) == NULL)
1622 if ((sep = strdup(optarg)) == NULL)
1629 r.multiple_select = 1;
1636 /* Read the completions */
1639 nlines = readlines(&lines, &buf);
1645 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1648 for (i = 0; i < nlines; i++) {
1650 t = strstr(lines[i], sep);
1652 vlines[i] = lines[i];
1658 setlocale(LC_ALL, getenv("LANG"));
1662 /* where the monitor start (used only with xinerama) */
1663 offset_x = offset_y = 0;
1665 /* default width and height */
1669 /* default position on the screen */
1672 for (i = 0; i < 4; ++i) {
1673 /* default paddings */
1674 r.p_padding[i] = 10;
1675 r.c_padding[i] = 10;
1676 r.ch_padding[i] = 10;
1678 /* default borders */
1682 r.ch_borders[i] = 0;
1685 /* the prompt. We duplicate the string so later is easy to
1686 * free (in the case it's been overwritten by the user) */
1687 if ((r.ps1 = strdup("$ ")) == NULL)
1690 /* same for the font name */
1691 if ((fontname = strdup(default_fontname)) == NULL)
1695 if ((text = malloc(textlen * sizeof(char))) == NULL)
1698 /* struct completions *cs = filter(text, lines); */
1699 if ((cs = compls_new(nlines)) == NULL)
1700 err(1, "compls_new");
1702 /* start talking to xorg */
1703 r.d = XOpenDisplay(NULL);
1705 fprintf(stderr, "Could not open display!\n");
1706 return EX_UNAVAILABLE;
1710 if (!(parent_window_id
1711 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1712 parent_window = DefaultRootWindow(r.d);
1716 /* get display size */
1717 get_wh(r.d, &parent_window, &d_width, &d_height);
1720 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1721 XineramaScreenInfo *info;
1724 int number_of_screens, monitors, i;
1725 int root_x, root_y, win_x, win_y;
1729 number_of_screens = XScreenCount(r.d);
1730 for (i = 0; i < number_of_screens; ++i) {
1731 root = XRootWindow(r.d, i);
1732 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1733 &root_y, &win_x, &win_y, &mask);
1739 fprintf(stderr, "No mouse found.\n");
1744 /* Now find in which monitor the mice is */
1745 info = XineramaQueryScreens(r.d, &monitors);
1747 for (i = 0; i < monitors; ++i) {
1748 if (info[i].x_org <= root_x
1749 && root_x <= (info[i].x_org
1751 && info[i].y_org <= root_y
1752 && root_y <= (info[i].y_org
1753 + info[i].height)) {
1754 offset_x = info[i].x_org;
1755 offset_y = info[i].y_org;
1756 d_width = info[i].width;
1757 d_height = info[i].height;
1766 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1767 cmap = XCreateColormap(
1768 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1770 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1771 fgs[2] = parse_color("#000", NULL);
1773 bgs[0] = bgs[1] = parse_color("#000", NULL);
1774 bgs[2] = parse_color("#fff", NULL);
1776 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1777 = parse_color("#000", NULL);
1779 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1780 = parse_color("#000", NULL);
1781 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1782 = parse_color("#000", NULL);
1783 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1784 = ch_borders_bg[3] = parse_color("#000", NULL);
1786 r.horizontal_layout = 1;
1788 /* Read the resources */
1790 xrm = XResourceManagerString(r.d);
1796 xdb = XrmGetStringDatabase(xrm);
1798 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1801 if ((fontname = strdup(value.addr)) == NULL)
1804 fprintf(stderr, "no font defined, using %s\n",
1809 xdb, "MyMenu.layout", "*", datatype, &value)
1812 = !strcmp(value.addr, "horizontal");
1815 "no layout defined, using horizontal\n");
1818 xdb, "MyMenu.prompt", "*", datatype, &value)
1821 r.ps1 = normalize_str(value.addr);
1824 "no prompt defined, using \"%s\" as "
1829 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1833 sizes = parse_csslike(value.addr);
1835 for (i = 0; i < 4; ++i)
1837 = parse_integer(sizes[i], 0);
1840 "error while parsing "
1841 "MyMenu.prompt.border.size");
1844 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1848 colors = parse_csslike(value.addr);
1850 for (i = 0; i < 4; ++i)
1851 p_borders_bg[i] = parse_color(
1855 "error while parsing "
1856 "MyMenu.prompt.border.color");
1859 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1863 colors = parse_csslike(value.addr);
1865 for (i = 0; i < 4; ++i)
1867 = parse_integer(colors[i], 0);
1870 "error while parsing "
1871 "MyMenu.prompt.padding");
1874 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1876 r.width = parse_int_with_percentage(
1877 value.addr, r.width, d_width);
1879 fprintf(stderr, "no width defined, using %d\n",
1883 xdb, "MyMenu.height", "*", datatype, &value)
1885 r.height = parse_int_with_percentage(
1886 value.addr, r.height, d_height);
1888 fprintf(stderr, "no height defined, using %d\n",
1891 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1893 x = parse_int_with_pos(
1894 r.d, value.addr, x, d_width, r.width);
1896 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1898 y = parse_int_with_pos(
1899 r.d, value.addr, y, d_height, r.height);
1902 xdb, "MyMenu.border.size", "*", datatype, &value)
1905 borders = parse_csslike(value.addr);
1906 if (borders != NULL)
1907 for (i = 0; i < 4; ++i)
1909 = parse_int_with_percentage(
1916 "error while parsing "
1917 "MyMenu.border.size\n");
1921 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1924 fgs[0] = parse_color(value.addr, "#fff");
1926 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1929 bgs[0] = parse_color(value.addr, "#000");
1932 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1935 fgs[1] = parse_color(value.addr, "#fff");
1937 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1940 bgs[1] = parse_color(value.addr, "#000");
1942 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1946 paddings = parse_csslike(value.addr);
1947 if (paddings != NULL)
1948 for (i = 0; i < 4; ++i)
1949 r.c_padding[i] = parse_integer(
1953 "Error while parsing "
1954 "MyMenu.completion.padding");
1957 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1961 sizes = parse_csslike(value.addr);
1963 for (i = 0; i < 4; ++i)
1965 = parse_integer(sizes[i], 0);
1968 "Error while parsing "
1969 "MyMenu.completion.border.size");
1972 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1976 sizes = parse_csslike(value.addr);
1978 for (i = 0; i < 4; ++i)
1979 c_borders_bg[i] = parse_color(
1983 "Error while parsing "
1984 "MyMenu.completion.border.color");
1987 /* Completion Highlighted */
1988 if (XrmGetResource(xdb,
1989 "MyMenu.completion_highlighted.foreground", "*",
1992 fgs[2] = parse_color(value.addr, "#000");
1994 if (XrmGetResource(xdb,
1995 "MyMenu.completion_highlighted.background", "*",
1998 bgs[2] = parse_color(value.addr, "#fff");
2000 if (XrmGetResource(xdb,
2001 "MyMenu.completion_highlighted.padding", "*",
2005 paddings = parse_csslike(value.addr);
2006 if (paddings != NULL)
2007 for (i = 0; i < 4; ++i)
2008 r.ch_padding[i] = parse_integer(
2012 "Error while parsing "
2013 "MyMenu.completion_highlighted."
2017 if (XrmGetResource(xdb,
2018 "MyMenu.completion_highlighted.border.size", "*",
2022 sizes = parse_csslike(value.addr);
2024 for (i = 0; i < 4; ++i)
2026 = parse_integer(sizes[i], 0);
2029 "Error while parsing "
2030 "MyMenu.completion_highlighted."
2034 if (XrmGetResource(xdb,
2035 "MyMenu.completion_highlighted.border.color", "*",
2039 colors = parse_csslike(value.addr);
2041 for (i = 0; i < 4; ++i)
2042 ch_borders_bg[i] = parse_color(
2046 "Error while parsing "
2047 "MyMenu.completion_highlighted."
2053 xdb, "MyMenu.border.color", "*", datatype, &value)
2056 colors = parse_csslike(value.addr);
2058 for (i = 0; i < 4; ++i)
2059 borders_bg[i] = parse_color(
2063 "error while parsing "
2064 "MyMenu.border.color\n");
2068 /* Second round of args parsing */
2069 optind = 0; /* reset the option index */
2070 while ((ch = getopt(argc, argv, ARGS)) != -1) {
2073 r.first_selected = 1;
2076 /* free_text -- already catched */
2078 /* separator -- this case was already catched */
2080 /* embedding mymenu this case was already catched. */
2082 /* multiple selection this case was already catched.
2087 newprompt = strdup(optarg);
2088 if (newprompt != NULL) {
2095 x = parse_int_with_pos(
2096 r.d, optarg, x, d_width, r.width);
2099 y = parse_int_with_pos(
2100 r.d, optarg, y, d_height, r.height);
2104 if ((paddings = parse_csslike(optarg)) != NULL)
2105 for (i = 0; i < 4; ++i)
2106 r.p_padding[i] = parse_integer(
2112 if ((colors = parse_csslike(optarg)) != NULL)
2113 for (i = 0; i < 4; ++i)
2114 p_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);
2128 if ((colors = parse_csslike(optarg)) != NULL)
2129 for (i = 0; i < 4; ++i)
2130 c_borders_bg[i] = parse_color(
2136 if ((sizes = parse_csslike(optarg)) != NULL)
2137 for (i = 0; i < 4; ++i)
2139 = parse_integer(sizes[i], 0);
2144 if ((colors = parse_csslike(optarg)) != NULL)
2145 for (i = 0; i < 4; ++i)
2146 ch_borders_bg[i] = parse_color(
2152 if ((sizes = parse_csslike(optarg)) != NULL)
2153 for (i = 0; i < 4; ++i)
2155 = parse_integer(sizes[i], 0);
2159 r.horizontal_layout = !strcmp(optarg, "horizontal");
2163 if ((newfont = strdup(optarg)) != NULL) {
2170 r.width = parse_int_with_percentage(
2171 optarg, r.width, d_width);
2174 r.height = parse_int_with_percentage(
2175 optarg, r.height, d_height);
2179 if ((borders = parse_csslike(optarg)) != NULL) {
2180 for (i = 0; i < 4; ++i)
2181 r.borders[i] = parse_integer(
2184 fprintf(stderr, "Error parsing b option\n");
2189 if ((colors = parse_csslike(optarg)) != NULL) {
2190 for (i = 0; i < 4; ++i)
2191 borders_bg[i] = parse_color(
2195 "error while parsing B option\n");
2199 fgs[0] = parse_color(optarg, NULL);
2202 bgs[0] = parse_color(optarg, NULL);
2205 fgs[1] = parse_color(optarg, NULL);
2208 bgs[1] = parse_color(optarg, NULL);
2211 fgs[2] = parse_color(optarg, NULL);
2214 fgs[2] = parse_color(optarg, NULL);
2217 fprintf(stderr, "Unrecognized option %c\n", ch);
2223 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2224 fprintf(stderr, "height, width, x or y are lesser than 0.");
2228 /* since only now we know if the first should be selected,
2229 * update the completion here */
2230 update_completions(cs, text, lines, vlines, r.first_selected);
2232 /* update the prompt lenght, only now we surely know the length of it
2234 r.ps1len = strlen(r.ps1);
2236 /* Create the window */
2237 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2239 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2240 XMapRaised(r.d, r.w);
2242 /* If embed, listen for other events as well */
2244 Window *children, parent, root;
2245 unsigned int children_no;
2247 XSelectInput(r.d, parent_window, FocusChangeMask);
2248 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2251 for (i = 0; i < children_no && children[i] != r.w;
2254 r.d, children[i], FocusChangeMask);
2257 grabfocus(r.d, r.w);
2260 take_keyboard(r.d, r.w);
2262 r.x_zero = r.borders[3];
2263 r.y_zero = r.borders[0];
2268 for (i = 0; i < 3; ++i) {
2269 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2270 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2273 for (i = 0; i < 4; ++i) {
2274 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2275 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2276 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2277 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2281 /* Load the colors in our GCs */
2282 for (i = 0; i < 3; ++i) {
2283 XSetForeground(r.d, r.fgs[i], fgs[i]);
2284 XSetForeground(r.d, r.bgs[i], bgs[i]);
2287 for (i = 0; i < 4; ++i) {
2288 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2289 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2290 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2291 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2294 if (load_font(&r, fontname) == -1)
2298 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2300 for (i = 0; i < 3; ++i) {
2302 XRenderColor xrcolor;
2304 c = *(rgba_t *)&fgs[i];
2305 xrcolor.red = EXPANDBITS(c.rgba.r);
2306 xrcolor.green = EXPANDBITS(c.rgba.g);
2307 xrcolor.blue = EXPANDBITS(c.rgba.b);
2308 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2310 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2314 /* compute prompt dimensions */
2320 /* Now we need only the ability to write */
2321 pledge("stdio", "");
2324 /* Cache text height */
2325 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2327 /* Draw the window for the first time */
2331 while (status == LOOPING || status == OK_LOOP) {
2332 status = loop(&r, &text, &textlen, cs, lines, vlines);
2335 printf("%s\n", text);
2337 if (!r.multiple_select && status == OK_LOOP)
2341 XUngrabKeyboard(r.d, CurrentTime);
2344 for (i = 0; i < 3; ++i)
2345 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2348 for (i = 0; i < 3; ++i) {
2349 XFreeGC(r.d, r.fgs[i]);
2350 XFreeGC(r.d, r.bgs[i]);
2353 for (i = 0; i < 4; ++i) {
2354 XFreeGC(r.d, r.borders_bg[i]);
2355 XFreeGC(r.d, r.p_borders_bg[i]);
2356 XFreeGC(r.d, r.c_borders_bg[i]);
2357 XFreeGC(r.d, r.ch_borders_bg[i]);
2364 for (i = 0; i < 3; ++i)
2365 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2366 XftFontClose(r.d, r.font);
2367 XftDrawDestroy(r.xftdraw);
2369 XFreeFontSet(r.d, r.font);
2381 XFreeColormap(r.d, cmap);
2383 XDestroyWindow(r.d, r.w);
2386 return status != OK;