1 #include <ctype.h> /* isalnum */
5 #include <locale.h> /* setlocale */
9 #include <string.h> /* strdup, strlen */
15 #include <X11/Xresource.h>
16 #include <X11/Xutil.h>
17 #include <X11/keysym.h>
18 #include <X11/Xft/Xft.h>
20 #include <X11/extensions/Xinerama.h>
22 #define RESNAME "MyMenu"
23 #define RESCLASS "mymenu"
25 #define SYM_BUF_SIZE 4
27 #define DEFFONT "monospace"
29 #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:"
31 #define MIN(a, b) ((a) < (b) ? (a) : (b))
32 #define MAX(a, b) ((a) > (b) ? (a) : (b))
34 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
36 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
37 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
39 /* The states of the event loop */
40 enum state { LOOPING, OK_LOOP, OK, ERR };
43 * For the drawing-related function. The text to be rendere could be
44 * the prompt, a completion or a highlighted completion
46 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
48 /* These are the possible action to be performed after user input. */
60 TOGGLE_FIRST_SELECTED,
65 /* A big set of values that needs to be carried around for drawing. A
66 * big struct to rule them all */
68 Display *d; /* Connection to xorg */
76 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
78 int y_zero; /* like x_zero but for the y axis */
80 int offset; /* scroll offset */
84 short multiple_select;
86 /* four border width */
92 short horizontal_layout;
97 int ps1w; /* ps1 width */
98 int ps1h; /* ps1 height */
100 int text_height; /* cache for the vertical layout */
113 XftColor xft_colors[3];
121 * The X (or Y, depending on the layour) at which the item is
127 /* Wrap the linked list of completions */
129 struct completion *completions;
134 /* idea stolen from lemonbar; ty lemonboy */
148 /* Return a newly allocated (and empty) completion list */
150 compls_new(size_t length)
152 struct completions *cs = malloc(sizeof(struct completions));
157 cs->completions = calloc(length, sizeof(struct completion));
158 if (cs->completions == NULL) {
168 /* Delete the wrapper and the whole list */
170 compls_delete(struct completions *cs)
175 free(cs->completions);
180 * Create a completion list from a text and the list of possible
181 * completions (null terminated). Expects a non-null `cs'. `lines' and
182 * `vlines' should have the same length OR `vlines' is NULL.
185 filter(struct completions *cs, char *text, char **lines, char **vlines)
195 if (lines[index] == NULL)
198 l = vlines[index] != NULL ? vlines[index] : lines[index];
200 if (strcasestr(l, text) != NULL) {
201 struct completion *c = &cs->completions[matching];
203 c->rcompletion = lines[index];
209 cs->length = matching;
213 /* Update the given completion */
215 update_completions(struct completions *cs, char *text, char **lines,
216 char **vlines, short first_selected)
218 filter(cs, text, lines, vlines);
219 if (first_selected && cs->length > 0)
224 * Select the next or previous selection and update some state. `text'
225 * will be updated with the text of the completion and `textlen' with
226 * the new length. If the memory cannot be allocated `status' will be
230 complete(struct completions *cs, short first_selected, short p,
231 char **text, int *textlen, enum state *status)
233 struct completion *n;
236 if (cs == NULL || cs->length == 0)
240 * If the first is always selected and the first entry is
241 * different from the text, expand the text and return
243 if (first_selected &&
245 strcmp(cs->completions->completion, *text) != 0 &&
248 *text = strdup(cs->completions->completion);
253 *textlen = strlen(*text);
257 index = cs->selected;
259 if (index == -1 && p)
261 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
264 n = &cs->completions[cs->selected];
267 *text = strdup(n->completion);
269 fprintf(stderr, "Memory allocation error!\n");
273 *textlen = strlen(*text);
276 /* Push the character c at the end of the string pointed by p */
278 pushc(char **p, int maxlen, char c)
282 len = strnlen(*p, maxlen);
283 if (!(len < maxlen - 2)) {
286 maxlen += maxlen >> 1;
287 newptr = realloc(*p, maxlen);
288 if (newptr == NULL) /* bad */
294 (*p)[len + 1] = '\0';
299 * Remove the last rune from the *UTF-8* string! This is different
300 * from just setting the last byte to 0 (in some cases ofc). Return a
301 * pointer (e) to the last nonzero char. If e < p then p is empty!
321 * If c is a starting byte (11......) or is under
324 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
331 /* Remove the last word plus trailing white spaces from the given string */
338 if ((len = strlen(w)) == 0)
347 if (in_word && isspace(*e))
350 if (!in_word && !isspace(*e))
356 * If the string is surrounded by quates (`"') remove them and replace
357 * every `\"' in the string with a single double-quote.
360 normalize_str(const char *str)
365 if ((len = strlen(str)) == 0)
368 if ((s = calloc(len, sizeof(char))) == NULL)
379 str += 2; /* skip this and the next char */
385 str++; /* skip only this char */
397 readlines(size_t *lineslen)
399 size_t len = 0, cap = 0;
402 char *line = NULL, **lines = NULL;
404 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
405 if (linelen != 0 && line[linelen-1] == '\n')
406 line[linelen-1] = '\0';
412 newcap = MAX(cap * 1.5, 32);
413 t = recallocarray(lines, cap, newcap, sizeof(char *));
415 err(1, "recallocarray");
420 if ((lines[len++] = strdup(line)) == NULL)
433 * Compute the dimensions of the string str once rendered.
434 * It'll return the width and set ret_width and ret_height if not NULL
437 text_extents(char *str, int len, struct rendering *r, int *ret_width,
442 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
443 height = r->font->ascent - r->font->descent;
444 width = gi.width - gi.x;
446 if (ret_width != NULL)
448 if (ret_height != NULL)
449 *ret_height = height;
454 draw_string(char *str, int len, int x, int y, struct rendering *r,
459 xftcolor = r->xft_colors[0];
461 xftcolor = r->xft_colors[1];
462 if (tt == COMPL_HIGH)
463 xftcolor = r->xft_colors[2];
465 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
468 /* Duplicate the string and substitute every space with a 'n` */
474 if (str == NULL || *str == '\0')
477 if ((dup = strdup(str)) == NULL)
480 for (t = dup; *t; ++t) {
489 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
490 enum obj_type t, char *text)
492 GC *border_color, bg;
493 int *padding, *borders;
494 int ret = 0, inner_width, inner_height, x;
498 border_color = r->p_borders_bg;
499 padding = r->p_padding;
500 borders = r->p_borders;
504 border_color = r->c_borders_bg;
505 padding = r->c_padding;
506 borders = r->c_borders;
510 border_color = r->ch_borders_bg;
511 padding = r->ch_padding;
512 borders = r->ch_borders;
517 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
519 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
520 inner_height = padding[0] + r->text_height + padding[2];
523 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
527 XFillRectangle(r->d, r->w, border_color[1],
528 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
531 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
532 y + borders[0] + padding[0] + r->text_height + padding[2],
533 r->width, borders[2]);
536 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
540 x = r->x_zero + borders[3];
542 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
545 y += padding[0] + r->text_height;
547 if (prefix != NULL) {
548 draw_string(prefix, strlen(prefix), x, y, r, t);
551 draw_string(text, strlen(text), x, y, r, t);
557 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
558 enum obj_type t, char *text)
560 GC *border_color, bg;
561 int *padding, *borders;
562 int ret = 0, inner_width, inner_height, y, text_width;
566 border_color = r->p_borders_bg;
567 padding = r->p_padding;
568 borders = r->p_borders;
572 border_color = r->c_borders_bg;
573 padding = r->c_padding;
574 borders = r->c_borders;
578 border_color = r->ch_borders_bg;
579 padding = r->ch_padding;
580 borders = r->ch_borders;
585 if (padding[0] < 0 || padding[2] < 0) {
586 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
590 padding[2] = padding[0];
593 /* If they are still lesser than 0, set 'em to 0 */
594 if (padding[0] < 0 || padding[2] < 0)
595 padding[0] = padding[2] = 0;
597 /* Get the text width */
598 text_extents(text, strlen(text), r, &text_width, NULL);
600 text_width += prefix_width;
602 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
604 inner_width = padding[3] + text_width + padding[1];
605 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
608 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
612 XFillRectangle(r->d, r->w, border_color[1],
613 x + borders[3] + inner_width, r->y_zero, borders[1],
617 XFillRectangle(r->d, r->w, border_color[2], x,
618 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
622 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
627 y = r->y_zero + borders[0];
628 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
631 y += padding[0] + r->text_height;
633 if (prefix != NULL) {
634 draw_string(prefix, strlen(prefix), x, y, r, t);
637 draw_string(text, strlen(text), x, y, r, t);
643 * ,-----------------------------------------------------------------,
644 * | 20 char text | completion | completion | completion | compl |
645 * `-----------------------------------------------------------------'
648 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
653 /* Draw the prompt */
654 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
656 for (i = r->offset; i < cs->length; ++i) {
659 if (cs->selected == (ssize_t)i)
664 cs->completions[i].offset = x;
666 x += draw_h_box(r, x, NULL, 0, t,
667 cs->completions[i].completion);
669 if (x > INNER_WIDTH(r))
673 for (i += 1; i < cs->length; ++i)
674 cs->completions[i].offset = -1;
678 * ,-----------------------------------------------------------------,
680 * |-----------------------------------------------------------------|
682 * |-----------------------------------------------------------------|
684 * `-----------------------------------------------------------------'
687 draw_vertically(struct rendering *r, char *text, struct completions *cs)
692 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
694 for (i = r->offset; i < cs->length; ++i) {
697 if (cs->selected == (ssize_t)i)
702 cs->completions[i].offset = y;
704 y += draw_v_box(r, y, NULL, 0, t,
705 cs->completions[i].completion);
707 if (y > INNER_HEIGHT(r))
711 for (i += 1; i < cs->length; ++i)
712 cs->completions[i].offset = -1;
716 draw(struct rendering *r, char *text, struct completions *cs)
718 /* Draw the background */
719 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
720 INNER_WIDTH(r), INNER_HEIGHT(r));
722 /* Draw the contents */
723 if (r->horizontal_layout)
724 draw_horizontally(r, text, cs);
726 draw_vertically(r, text, cs);
728 /* Draw the borders */
729 if (r->borders[0] != 0)
730 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
733 if (r->borders[1] != 0)
734 XFillRectangle(r->d, r->w, r->borders_bg[1],
735 r->width - r->borders[1], 0, r->borders[1],
738 if (r->borders[2] != 0)
739 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
740 r->height - r->borders[2], r->width, r->borders[2]);
742 if (r->borders[3] != 0)
743 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
744 r->borders[3], r->height);
750 /* Set some WM stuff */
752 set_win_atoms_hints(Display *d, Window w, int width, int height)
755 XClassHint *class_hint;
756 XSizeHints *size_hint;
758 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
759 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
760 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
761 (unsigned char *)&type, 1);
763 /* some window managers honor this properties */
764 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
765 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
766 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
767 (unsigned char *)&type, 1);
769 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
770 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
771 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
772 (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;
812 /* find the current xinerama monitor if possible */
814 findmonitor(Display *d, int *x, int *y, int *width, int *height)
816 XineramaScreenInfo *info;
819 int screens, monitors, i;
820 int rootx, rooty, winx, winy;
824 if (!XineramaIsActive(d))
827 screens = XScreenCount(d);
828 for (i = 0; i < screens; ++i) {
829 root = XRootWindow(d, i);
830 res = XQueryPointer(d, root, &rr, &rr, &rootx, &rooty, &winx,
839 /* Now find in which monitor the mice is */
840 info = XineramaQueryScreens(d, &monitors);
844 for (i = 0; i < monitors; ++i) {
845 if (info[i].x_org <= rootx &&
846 rootx <= (info[i].x_org + info[i].width) &&
847 info[i].y_org <= rooty &&
848 rooty <= (info[i].y_org + info[i].height)) {
851 *width = info[i].width;
852 *height = info[i].height;
861 grabfocus(Display *d, Window w)
864 for (i = 0; i < 100; ++i) {
868 XGetInputFocus(d, &focuswin, &revert_to_win);
873 XSetInputFocus(d, w, RevertToParent, CurrentTime);
880 * I know this may seem a little hackish BUT is the only way I managed
881 * to actually grab that goddam keyboard. Only one call to
882 * XGrabKeyboard does not always end up with the keyboard grabbed!
885 take_keyboard(Display *d, Window w)
888 for (i = 0; i < 100; i++) {
889 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
890 CurrentTime) == GrabSuccess)
894 fprintf(stderr, "Cannot grab keyboard\n");
899 parse_color(const char *str, const char *def)
910 /* +1 for the # ath the start */
911 if (*str != '#' || len > 9 || len < 4)
913 ++str; /* skip the # */
916 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
923 /* expand #rgb -> #rrggbb */
924 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
925 | (tmp.v & 0x00f) * 0x0011;
927 /* assume 0xff opacity */
930 } /* colors in #aarrggbb need no adjustments */
932 /* premultiply the alpha */
934 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
935 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
936 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
943 fprintf(stderr, "Invalid color: \"%s\".\n", str);
945 return parse_color(def, NULL);
951 * Given a string try to parse it as a number or return `def'.
954 parse_integer(const char *str, int def)
959 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
960 if (errstr != NULL) {
961 warnx("'%s' is %s; using %d as default", str, errstr, def);
969 * Like parse_integer but recognize the percentages (i.e. strings
973 parse_int_with_percentage(const char *str, int default_value, int max)
975 int len = strlen(str);
977 if (len > 0 && str[len - 1] == '%') {
981 if ((cpy = strdup(str)) == NULL)
985 val = parse_integer(cpy, default_value);
987 return val * max / 100;
990 return parse_integer(str, default_value);
994 get_mouse_coords(Display *d, int *x, int *y)
1001 root = DefaultRootWindow(d);
1003 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1004 for (i = 0; i < ScreenCount(d); ++i) {
1005 if (root == RootWindow(d, i))
1012 * Like parse_int_with_percentage but understands some special values:
1013 * - middle that is (max-self)/2
1016 * - end that is (max-self)
1017 * - mx x coordinate of the mouse
1018 * - my y coordinate of the mouse
1021 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1024 if (!strcmp(str, "start"))
1026 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1027 return (max - self) / 2;
1028 if (!strcmp(str, "end"))
1030 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1033 get_mouse_coords(d, &x, &y);
1034 if (!strcmp(str, "mx"))
1039 return parse_int_with_percentage(str, default_value, max);
1042 /* Parse a string like a CSS value. */
1043 /* TODO: harden a bit this function */
1045 parse_csslike(const char *str)
1048 char *s, *token, **ret;
1055 ret = malloc(4 * sizeof(char *));
1061 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1062 ret[i] = strdup(token);
1065 for (j = 1; j < 4; j++)
1066 ret[j] = strdup(ret[0]);
1069 ret[2] = strdup(ret[0]);
1070 ret[3] = strdup(ret[1]);
1074 ret[3] = strdup(ret[1]);
1077 * before we didn't check for the return type of strdup, here
1082 for (i = 0; i < 4; ++i)
1083 any_null = ret[i] == NULL || any_null;
1086 for (i = 0; i < 4; ++i)
1090 if (i == 0 || any_null) {
1100 * Given an event, try to understand what the users wants. If the
1101 * return value is ADD_CHAR then `input' is a pointer to a string that
1102 * will need to be free'ed later.
1105 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1107 char str[SYM_BUF_SIZE] = { 0 };
1110 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1113 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1114 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1116 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1119 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1122 /* Try to read what key was pressed */
1124 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1125 if (s == XBufferOverflow) {
1127 "Buffer overflow when trying to create keyboard "
1132 if (ev->state & ControlMask) {
1133 if (!strcmp(str, "")) /* C-u */
1135 if (!strcmp(str, "")) /* C-w */
1137 if (!strcmp(str, "")) /* C-h */
1139 if (!strcmp(str, "\r")) /* C-m */
1140 return CONFIRM_CONTINUE;
1141 if (!strcmp(str, "")) /* C-p */
1143 if (!strcmp(str, "")) /* C-n */
1145 if (!strcmp(str, "")) /* C-c */
1147 if (!strcmp(str, "\t")) /* C-i */
1148 return TOGGLE_FIRST_SELECTED;
1151 *input = strdup(str);
1152 if (*input == NULL) {
1153 fprintf(stderr, "Error while allocating memory for key.\n");
1161 confirm(enum state *status, struct rendering *r, struct completions *cs,
1162 char **text, int *textlen)
1164 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1165 /* if there is something selected expand it and return */
1166 int index = cs->selected == -1 ? 0 : cs->selected;
1167 struct completion *c = cs->completions;
1181 if (*text == NULL) {
1182 fprintf(stderr, "Memory allocation error\n");
1186 *textlen = strlen(*text);
1190 if (!r->free_text) /* cannot accept arbitrary text */
1195 * cs: completion list
1196 * offset: the offset of the click
1197 * first: the first (rendered) item
1198 * def: the default action
1201 select_clicked(struct completions *cs, size_t offset, size_t first,
1204 ssize_t selected = first;
1207 if (cs->length == 0)
1210 if (offset < cs->completions[selected].offset)
1213 /* skip the first entry */
1214 for (selected += 1; selected < cs->length; ++selected) {
1215 if (cs->completions[selected].offset == -1)
1218 if (offset < cs->completions[selected].offset) {
1219 cs->selected = selected - 1;
1226 cs->selected = selected - 1;
1232 handle_mouse(struct rendering *r, struct completions *cs,
1233 XButtonPressedEvent *e)
1237 if (r->horizontal_layout)
1242 switch (e->button) {
1244 return select_clicked(cs, off, r->offset, CONFIRM);
1247 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1261 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1262 char **lines, char **vlines)
1264 enum state status = LOOPING;
1266 while (status == LOOPING) {
1268 XNextEvent(r->d, &e);
1270 if (XFilterEvent(&e, r->w))
1275 XRefreshKeyboardMapping(&e.xmapping);
1280 if (e.xfocus.window != r->w)
1281 grabfocus(r->d, r->w);
1284 case VisibilityNotify:
1285 if (e.xvisibility.state != VisibilityUnobscured)
1286 XRaiseWindow(r->d, r->w);
1290 get_wh(r->d, &r->w, &r->width, &r->height);
1299 if (e.type == KeyPress)
1300 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1303 a = handle_mouse(r, cs,
1304 (XButtonPressedEvent *)&e);
1316 confirm(&status, r, cs, text, textlen);
1320 case CONFIRM_CONTINUE: {
1322 confirm(&status, r, cs, text, textlen);
1327 complete(cs, r->first_selected, 1, text,
1329 r->offset = cs->selected;
1334 complete(cs, r->first_selected, 0, text,
1336 r->offset = cs->selected;
1342 update_completions(cs, *text, lines, vlines,
1349 update_completions(cs, *text, lines, vlines,
1356 for (i = 0; i < *textlen; ++i)
1358 update_completions(cs, *text, lines, vlines,
1367 str_len = strlen(input);
1370 * sometimes a strange key is pressed
1371 * i.e. ctrl alone), so input will be
1372 * empty. Don't need to update
1373 * completion in that case
1378 for (i = 0; i < str_len; ++i) {
1379 *textlen = pushc(text, *textlen,
1381 if (*textlen == -1) {
1383 "Memory allocation "
1390 if (status != ERR) {
1391 update_completions(cs, *text, lines,
1392 vlines, r->first_selected);
1400 case TOGGLE_FIRST_SELECTED:
1401 r->first_selected = !r->first_selected;
1402 if (r->first_selected && cs->selected < 0)
1404 if (!r->first_selected && cs->selected == 0)
1409 r->offset = MIN(r->offset + 1, cs->length - 1);
1413 r->offset = MAX((ssize_t)r->offset - 1, 0);
1426 load_font(struct rendering *r, const char *fontname)
1428 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1433 xim_init(struct rendering *r, XrmDatabase *xdb)
1435 XIMStyle best_match_style;
1439 /* Open the X input method */
1440 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1443 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1444 fprintf(stderr, "Input Styles could not be retrieved\n");
1445 exit(EX_UNAVAILABLE);
1448 best_match_style = 0;
1449 for (i = 0; i < xis->count_styles; ++i) {
1450 XIMStyle ts = xis->supported_styles[i];
1451 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1452 best_match_style = ts;
1458 if (!best_match_style)
1460 "No matching input style could be determined\n");
1462 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1463 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1465 err(1, "XCreateIC");
1469 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1470 XVisualInfo vinfo, int x, int y, int ox, int oy,
1471 unsigned long background_pixel)
1473 XSetWindowAttributes attr;
1474 unsigned long vmask;
1476 /* Create the window */
1477 attr.colormap = cmap;
1478 attr.override_redirect = 1;
1479 attr.border_pixel = 0;
1480 attr.background_pixel = background_pixel;
1481 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1482 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1484 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1487 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1488 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1492 ps1extents(struct rendering *r)
1495 dup = strdupn(r->ps1);
1496 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1501 usage(char *prgname)
1504 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1505 " [-d separator] [-e window] [-f font] [-G color] [-g "
1507 " [-H height] [-I color] [-i size] [-J color] [-j "
1508 "size] [-l layout]\n"
1509 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1511 " [-t color] [-W width] [-x coord] [-y coord]\n",
1516 main(int argc, char **argv)
1518 struct completions *cs;
1523 Window parent_window;
1525 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1526 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1527 ch_borders_bg[4]; /* N E S W */
1530 int offset_x, offset_y, x, y;
1531 int textlen, d_width, d_height;
1533 char *sep, *parent_window_id;
1534 char **lines, **vlines;
1535 char *fontname, *text, *xrm;
1538 parent_window_id = NULL;
1540 r.first_selected = 0;
1542 r.multiple_select = 0;
1545 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1547 case 'h': /* help */
1550 case 'v': /* version */
1551 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1553 case 'e': /* embed */
1554 if ((parent_window_id = strdup(optarg)) == NULL)
1558 if ((sep = strdup(optarg)) == NULL)
1565 r.multiple_select = 1;
1572 lines = readlines(&nlines);
1578 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1581 for (i = 0; i < nlines; i++) {
1583 t = strstr(lines[i], sep);
1585 vlines[i] = lines[i];
1591 setlocale(LC_ALL, getenv("LANG"));
1595 /* where the monitor start (used only with xinerama) */
1596 offset_x = offset_y = 0;
1598 /* default width and height */
1602 /* default position on the screen */
1605 for (i = 0; i < 4; ++i) {
1606 /* default paddings */
1607 r.p_padding[i] = 10;
1608 r.c_padding[i] = 10;
1609 r.ch_padding[i] = 10;
1611 /* default borders */
1615 r.ch_borders[i] = 0;
1619 * The prompt. We duplicate the string so later is easy to
1620 * free (in the case it's been overwritten by the user)
1622 if ((r.ps1 = strdup("$ ")) == NULL)
1625 /* same for the font name */
1626 if ((fontname = strdup(DEFFONT)) == NULL)
1630 if ((text = malloc(textlen * sizeof(char))) == NULL)
1633 /* struct completions *cs = filter(text, lines); */
1634 if ((cs = compls_new(nlines)) == NULL)
1635 err(1, "compls_new");
1637 /* start talking to xorg */
1638 r.d = XOpenDisplay(NULL);
1640 fprintf(stderr, "Could not open display!\n");
1641 return EX_UNAVAILABLE;
1645 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1646 parent_window = DefaultRootWindow(r.d);
1650 /* get display size */
1651 get_wh(r.d, &parent_window, &d_width, &d_height);
1654 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1656 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1657 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1660 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1661 fgs[2] = parse_color("#000", NULL);
1663 bgs[0] = bgs[1] = parse_color("#000", NULL);
1664 bgs[2] = parse_color("#fff", NULL);
1666 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1667 parse_color("#000", NULL);
1669 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1670 = parse_color("#000", NULL);
1671 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1672 = parse_color("#000", NULL);
1673 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1674 = parse_color("#000", NULL);
1676 r.horizontal_layout = 1;
1678 /* Read the resources */
1680 xrm = XResourceManagerString(r.d);
1686 xdb = XrmGetStringDatabase(xrm);
1688 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1690 if ((fontname = strdup(value.addr)) == NULL)
1693 fprintf(stderr, "no font defined, using %s\n", fontname);
1696 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1697 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1699 fprintf(stderr, "no layout defined, using horizontal\n");
1701 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1703 r.ps1 = normalize_str(value.addr);
1706 "no prompt defined, using \"%s\" as "
1711 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1713 sizes = parse_csslike(value.addr);
1715 for (i = 0; i < 4; ++i)
1716 r.p_borders[i] = parse_integer(sizes[i], 0);
1719 "error while parsing "
1720 "MyMenu.prompt.border.size");
1723 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1725 colors = parse_csslike(value.addr);
1727 for (i = 0; i < 4; ++i)
1728 p_borders_bg[i] = parse_color(colors[i], "#000");
1731 "error while parsing "
1732 "MyMenu.prompt.border.color");
1735 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1737 colors = parse_csslike(value.addr);
1739 for (i = 0; i < 4; ++i)
1740 r.p_padding[i] = parse_integer(colors[i], 0);
1743 "error while parsing "
1744 "MyMenu.prompt.padding");
1747 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1748 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1750 fprintf(stderr, "no width defined, using %d\n", r.width);
1752 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1753 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1755 fprintf(stderr, "no height defined, using %d\n", r.height);
1757 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1758 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1760 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1761 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1763 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1765 borders = parse_csslike(value.addr);
1766 if (borders != NULL)
1767 for (i = 0; i < 4; ++i)
1768 r.borders[i] = parse_int_with_percentage(
1769 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1772 "error while parsing "
1773 "MyMenu.border.size\n");
1777 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1778 fgs[0] = parse_color(value.addr, "#fff");
1780 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1781 bgs[0] = parse_color(value.addr, "#000");
1784 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1785 fgs[1] = parse_color(value.addr, "#fff");
1787 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1788 bgs[1] = parse_color(value.addr, "#000");
1790 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1792 paddings = parse_csslike(value.addr);
1793 if (paddings != NULL)
1794 for (i = 0; i < 4; ++i)
1795 r.c_padding[i] = parse_integer(paddings[i], 0);
1798 "Error while parsing "
1799 "MyMenu.completion.padding");
1802 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1804 sizes = parse_csslike(value.addr);
1806 for (i = 0; i < 4; ++i)
1807 r.c_borders[i] = parse_integer(sizes[i], 0);
1810 "Error while parsing "
1811 "MyMenu.completion.border.size");
1814 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1816 sizes = parse_csslike(value.addr);
1818 for (i = 0; i < 4; ++i)
1819 c_borders_bg[i] = parse_color(sizes[i], "#000");
1822 "Error while parsing "
1823 "MyMenu.completion.border.color");
1826 /* Completion Highlighted */
1828 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1829 fgs[2] = parse_color(value.addr, "#000");
1832 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1833 bgs[2] = parse_color(value.addr, "#fff");
1836 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1838 paddings = parse_csslike(value.addr);
1839 if (paddings != NULL)
1840 for (i = 0; i < 4; ++i)
1841 r.ch_padding[i] = parse_integer(paddings[i], 0);
1844 "Error while parsing "
1845 "MyMenu.completion_highlighted."
1849 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1852 sizes = parse_csslike(value.addr);
1854 for (i = 0; i < 4; ++i)
1855 r.ch_borders[i] = parse_integer(sizes[i], 0);
1858 "Error while parsing "
1859 "MyMenu.completion_highlighted."
1863 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1866 colors = parse_csslike(value.addr);
1868 for (i = 0; i < 4; ++i)
1869 ch_borders_bg[i] = parse_color(colors[i], "#000");
1872 "Error while parsing "
1873 "MyMenu.completion_highlighted."
1878 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1880 colors = parse_csslike(value.addr);
1882 for (i = 0; i < 4; ++i)
1883 borders_bg[i] = parse_color(colors[i], "#000");
1886 "error while parsing "
1887 "MyMenu.border.color\n");
1891 /* Second round of args parsing */
1892 optind = 0; /* reset the option index */
1893 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1896 r.first_selected = 1;
1899 /* free_text -- already catched */
1901 /* separator -- this case was already catched */
1903 /* embedding mymenu this case was already catched. */
1905 /* multiple selection this case was already catched.
1910 newprompt = strdup(optarg);
1911 if (newprompt != NULL) {
1918 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1921 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1925 if ((paddings = parse_csslike(optarg)) != NULL)
1926 for (i = 0; i < 4; ++i)
1927 r.p_padding[i] = parse_integer(paddings[i], 0);
1932 if ((colors = parse_csslike(optarg)) != NULL)
1933 for (i = 0; i < 4; ++i)
1934 p_borders_bg[i] = parse_color(colors[i], "#000");
1939 if ((sizes = parse_csslike(optarg)) != NULL)
1940 for (i = 0; i < 4; ++i)
1941 r.p_borders[i] = parse_integer(sizes[i], 0);
1946 if ((colors = parse_csslike(optarg)) != NULL)
1947 for (i = 0; i < 4; ++i)
1948 c_borders_bg[i] = parse_color(colors[i], "#000");
1953 if ((sizes = parse_csslike(optarg)) != NULL)
1954 for (i = 0; i < 4; ++i)
1955 r.c_borders[i] = parse_integer(sizes[i], 0);
1960 if ((colors = parse_csslike(optarg)) != NULL)
1961 for (i = 0; i < 4; ++i)
1962 ch_borders_bg[i] = parse_color(colors[i], "#000");
1967 if ((sizes = parse_csslike(optarg)) != NULL)
1968 for (i = 0; i < 4; ++i)
1969 r.ch_borders[i] = parse_integer(sizes[i], 0);
1973 r.horizontal_layout = !strcmp(optarg, "horizontal");
1977 if ((newfont = strdup(optarg)) != NULL) {
1984 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1987 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1991 if ((borders = parse_csslike(optarg)) != NULL) {
1992 for (i = 0; i < 4; ++i)
1993 r.borders[i] = parse_integer(borders[i], 0);
1995 fprintf(stderr, "Error parsing b option\n");
2000 if ((colors = parse_csslike(optarg)) != NULL) {
2001 for (i = 0; i < 4; ++i)
2002 borders_bg[i] = parse_color(colors[i], "#000");
2004 fprintf(stderr, "error while parsing B option\n");
2008 fgs[0] = parse_color(optarg, NULL);
2011 bgs[0] = parse_color(optarg, NULL);
2014 fgs[1] = parse_color(optarg, NULL);
2017 bgs[1] = parse_color(optarg, NULL);
2020 fgs[2] = parse_color(optarg, NULL);
2023 bgs[2] = parse_color(optarg, NULL);
2026 fprintf(stderr, "Unrecognized option %c\n", ch);
2032 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2033 fprintf(stderr, "height, width, x or y are lesser than 0.");
2037 /* since only now we know if the first should be selected,
2038 * update the completion here */
2039 update_completions(cs, text, lines, vlines, r.first_selected);
2041 /* update the prompt lenght, only now we surely know the length of it
2043 r.ps1len = strlen(r.ps1);
2045 /* Create the window */
2046 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2047 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2048 XMapRaised(r.d, r.w);
2050 /* If embed, listen for other events as well */
2052 Window *children, parent, root;
2053 unsigned int children_no;
2055 XSelectInput(r.d, parent_window, FocusChangeMask);
2056 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2058 for (i = 0; i < children_no && children[i] != r.w; ++i)
2059 XSelectInput(r.d, children[i], FocusChangeMask);
2062 grabfocus(r.d, r.w);
2065 take_keyboard(r.d, r.w);
2067 r.x_zero = r.borders[3];
2068 r.y_zero = r.borders[0];
2073 for (i = 0; i < 3; ++i) {
2074 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2075 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2078 for (i = 0; i < 4; ++i) {
2079 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2080 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2081 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2082 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2086 /* Load the colors in our GCs */
2087 for (i = 0; i < 3; ++i) {
2088 XSetForeground(r.d, r.fgs[i], fgs[i]);
2089 XSetForeground(r.d, r.bgs[i], bgs[i]);
2092 for (i = 0; i < 4; ++i) {
2093 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2094 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2095 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2096 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2099 if (load_font(&r, fontname) == -1)
2102 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2104 for (i = 0; i < 3; ++i) {
2106 XRenderColor xrcolor;
2108 c = *(rgba_t *)&fgs[i];
2109 xrcolor.red = EXPANDBITS(c.rgba.r);
2110 xrcolor.green = EXPANDBITS(c.rgba.g);
2111 xrcolor.blue = EXPANDBITS(c.rgba.b);
2112 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2113 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2116 /* compute prompt dimensions */
2122 if (pledge("stdio", "") == -1)
2126 /* Cache text height */
2127 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2129 /* Draw the window for the first time */
2133 while (status == LOOPING || status == OK_LOOP) {
2134 status = loop(&r, &text, &textlen, cs, lines, vlines);
2137 printf("%s\n", text);
2139 if (!r.multiple_select && status == OK_LOOP)
2143 XUngrabKeyboard(r.d, CurrentTime);
2145 for (i = 0; i < 3; ++i)
2146 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2148 for (i = 0; i < 3; ++i) {
2149 XFreeGC(r.d, r.fgs[i]);
2150 XFreeGC(r.d, r.bgs[i]);
2153 for (i = 0; i < 4; ++i) {
2154 XFreeGC(r.d, r.borders_bg[i]);
2155 XFreeGC(r.d, r.p_borders_bg[i]);
2156 XFreeGC(r.d, r.c_borders_bg[i]);
2157 XFreeGC(r.d, r.ch_borders_bg[i]);
2163 for (i = 0; i < 3; ++i)
2164 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2165 XftFontClose(r.d, r.font);
2166 XftDrawDestroy(r.xftdraw);
2176 XFreeColormap(r.d, cmap);
2178 XDestroyWindow(r.d, r.w);
2181 return status != OK;