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];
119 int offset; /* the x (or y, depending on the layout) coordinate at
120 which the item is rendered */
123 /* Wrap the linked list of completions */
125 struct completion *completions;
130 /* idea stolen from lemonbar. ty lemonboy */
144 /* Return a newly allocated (and empty) completion list */
146 compls_new(size_t length)
148 struct completions *cs = malloc(sizeof(struct completions));
153 cs->completions = calloc(length, sizeof(struct completion));
154 if (cs->completions == NULL) {
164 /* Delete the wrapper and the whole list */
166 compls_delete(struct completions *cs)
171 free(cs->completions);
176 * Create a completion list from a text and the list of possible
177 * completions (null terminated). Expects a non-null `cs'. `lines' and
178 * `vlines' should have the same length OR `vlines' is NULL.
181 filter(struct completions *cs, char *text, char **lines, char **vlines)
191 if (lines[index] == NULL)
194 l = vlines[index] != NULL ? vlines[index] : lines[index];
196 if (strcasestr(l, text) != NULL) {
197 struct completion *c = &cs->completions[matching];
199 c->rcompletion = lines[index];
205 cs->length = matching;
209 /* Update the given completion */
212 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
214 filter(cs, text, lines, vlines);
215 if (first_selected && cs->length > 0)
220 * Select the next or previous selection and update some state. `text'
221 * will be updated with the text of the completion and `textlen' with
222 * the new length. If the memory cannot be allocated `status' will be
226 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
229 struct completion *n;
232 if (cs == NULL || cs->length == 0)
236 * If the first is always selected and the first entry is
237 * different from the text, expand the text and return
239 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
242 *text = strdup(cs->completions->completion);
247 *textlen = strlen(*text);
251 index = cs->selected;
253 if (index == -1 && p)
255 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
257 n = &cs->completions[cs->selected];
260 *text = strdup(n->completion);
262 fprintf(stderr, "Memory allocation error!\n");
266 *textlen = strlen(*text);
269 /* Push the character c at the end of the string pointed by p */
271 pushc(char **p, int maxlen, char c)
275 len = strnlen(*p, maxlen);
276 if (!(len < maxlen - 2)) {
279 maxlen += maxlen >> 1;
280 newptr = realloc(*p, maxlen);
281 if (newptr == NULL) /* bad */
287 (*p)[len + 1] = '\0';
292 * Remove the last rune from the *UTF-8* string! This is different
293 * from just setting the last byte to 0 (in some cases ofc). Return a
294 * pointer (e) to the last nonzero char. If e < p then p is empty!
314 * If c is a starting byte (11......) or is under
317 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
324 /* Remove the last word plus trailing white spaces from the given string */
331 if ((len = strlen(w)) == 0)
340 if (in_word && isspace(*e))
343 if (!in_word && !isspace(*e))
349 * If the string is surrounded by quates (`"') remove them and replace
350 * every `\"' in the string with a single double-quote.
353 normalize_str(const char *str)
358 if ((len = strlen(str)) == 0)
361 if ((s = calloc(len, sizeof(char))) == NULL)
372 str += 2; /* skip this and the next char */
378 str++; /* skip only this char */
390 readlines(size_t *lineslen)
392 size_t len = 0, cap = 0;
395 char *line = NULL, **lines = NULL;
397 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
398 if (linelen != 0 && line[linelen-1] == '\n')
399 line[linelen-1] = '\0';
405 newcap = MAX(cap * 1.5, 32);
406 t = recallocarray(lines, cap, newcap, sizeof(char *));
408 err(1, "recallocarray");
413 if ((lines[len++] = strdup(line)) == NULL)
426 * Compute the dimensions of the string str once rendered.
427 * It'll return the width and set ret_width and ret_height if not NULL
430 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
434 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
435 height = r->font->ascent - r->font->descent;
436 width = gi.width - gi.x;
438 if (ret_width != NULL)
440 if (ret_height != NULL)
441 *ret_height = height;
446 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
450 xftcolor = r->xft_colors[0];
452 xftcolor = r->xft_colors[1];
453 if (tt == COMPL_HIGH)
454 xftcolor = r->xft_colors[2];
456 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
459 /* Duplicate the string and substitute every space with a 'n` */
465 if (str == NULL || *str == '\0')
468 if ((dup = strdup(str)) == NULL)
471 for (t = dup; *t; ++t) {
480 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
482 GC *border_color, bg;
483 int *padding, *borders;
484 int ret = 0, inner_width, inner_height, x;
488 border_color = r->p_borders_bg;
489 padding = r->p_padding;
490 borders = r->p_borders;
494 border_color = r->c_borders_bg;
495 padding = r->c_padding;
496 borders = r->c_borders;
500 border_color = r->ch_borders_bg;
501 padding = r->ch_padding;
502 borders = r->ch_borders;
507 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
509 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
510 inner_height = padding[0] + r->text_height + padding[2];
513 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
516 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + INNER_WIDTH(r) - borders[1], y,
520 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
521 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
524 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
527 x = r->x_zero + borders[3];
529 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
532 y += padding[0] + r->text_height;
534 if (prefix != NULL) {
535 draw_string(prefix, strlen(prefix), x, y, r, t);
538 draw_string(text, strlen(text), x, y, r, t);
544 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
546 GC *border_color, bg;
547 int *padding, *borders;
548 int ret = 0, inner_width, inner_height, y, text_width;
552 border_color = r->p_borders_bg;
553 padding = r->p_padding;
554 borders = r->p_borders;
558 border_color = r->c_borders_bg;
559 padding = r->c_padding;
560 borders = r->c_borders;
564 border_color = r->ch_borders_bg;
565 padding = r->ch_padding;
566 borders = r->ch_borders;
571 if (padding[0] < 0 || padding[2] < 0)
572 padding[0] = padding[2]
573 = (INNER_HEIGHT(r) - borders[0] - borders[2] - r->text_height) / 2;
575 /* If they are still lesser than 0, set 'em to 0 */
576 if (padding[0] < 0 || padding[2] < 0)
577 padding[0] = padding[2] = 0;
579 /* Get the text width */
580 text_extents(text, strlen(text), r, &text_width, NULL);
582 text_width += prefix_width;
584 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
586 inner_width = padding[3] + text_width + padding[1];
587 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
590 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
593 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
594 borders[1], INNER_HEIGHT(r));
597 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + INNER_HEIGHT(r) - borders[2],
601 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], INNER_HEIGHT(r));
605 y = r->y_zero + borders[0];
606 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
609 y += padding[0] + r->text_height;
611 if (prefix != NULL) {
612 draw_string(prefix, strlen(prefix), x, y, r, t);
615 draw_string(text, strlen(text), x, y, r, t);
620 /* ,-----------------------------------------------------------------, */
621 /* | 20 char text | completion | completion | completion | compl | */
622 /* `-----------------------------------------------------------------' */
624 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
629 /* Draw the prompt */
630 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
632 for (i = r->offset; i < cs->length; ++i) {
633 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
635 cs->completions[i].offset = x;
637 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
639 if (x > INNER_WIDTH(r))
643 for (i += 1; i < cs->length; ++i)
644 cs->completions[i].offset = -1;
647 /* ,-----------------------------------------------------------------, */
649 /* |-----------------------------------------------------------------| */
651 /* |-----------------------------------------------------------------| */
653 /* `-----------------------------------------------------------------' */
655 draw_vertically(struct rendering *r, char *text, struct completions *cs)
660 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
662 for (i = r->offset; i < cs->length; ++i) {
663 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
665 cs->completions[i].offset = y;
667 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
669 if (y > INNER_HEIGHT(r))
673 for (i += 1; i < cs->length; ++i)
674 cs->completions[i].offset = -1;
678 draw(struct rendering *r, char *text, struct completions *cs)
680 /* Draw the background */
682 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, INNER_WIDTH(r), INNER_HEIGHT(r));
684 /* Draw the contents */
685 if (r->horizontal_layout)
686 draw_horizontally(r, text, cs);
688 draw_vertically(r, text, cs);
690 /* Draw the borders */
691 if (r->borders[0] != 0)
692 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
694 if (r->borders[1] != 0)
695 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
696 r->borders[1], r->height);
698 if (r->borders[2] != 0)
699 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
702 if (r->borders[3] != 0)
703 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
709 /* Set some WM stuff */
711 set_win_atoms_hints(Display *d, Window w, int width, int height)
714 XClassHint *class_hint;
715 XSizeHints *size_hint;
717 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
718 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
719 32, PropModeReplace, (unsigned char *)&type, 1);
721 /* some window managers honor this properties */
722 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
723 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
724 PropModeReplace, (unsigned char *)&type, 1);
726 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
727 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
728 PropModeAppend, (unsigned char *)&type, 1);
730 /* Setting window hints */
731 class_hint = XAllocClassHint();
732 if (class_hint == NULL) {
733 fprintf(stderr, "Could not allocate memory for class hint\n");
734 exit(EX_UNAVAILABLE);
737 class_hint->res_name = RESNAME;
738 class_hint->res_class = RESCLASS;
739 XSetClassHint(d, w, class_hint);
742 size_hint = XAllocSizeHints();
743 if (size_hint == NULL) {
744 fprintf(stderr, "Could not allocate memory for size hint\n");
745 exit(EX_UNAVAILABLE);
748 size_hint->flags = PMinSize | PBaseSize;
749 size_hint->min_width = width;
750 size_hint->base_width = width;
751 size_hint->min_height = height;
752 size_hint->base_height = height;
757 /* Get the width and height of the window `w' */
759 get_wh(Display *d, Window *w, int *width, int *height)
761 XWindowAttributes win_attr;
763 XGetWindowAttributes(d, *w, &win_attr);
764 *height = win_attr.height;
765 *width = win_attr.width;
769 grabfocus(Display *d, Window w)
772 for (i = 0; i < 100; ++i) {
776 XGetInputFocus(d, &focuswin, &revert_to_win);
781 XSetInputFocus(d, w, RevertToParent, CurrentTime);
788 * I know this may seem a little hackish BUT is the only way I managed
789 * to actually grab that goddam keyboard. Only one call to
790 * XGrabKeyboard does not always end up with the keyboard grabbed!
793 take_keyboard(Display *d, Window w)
796 for (i = 0; i < 100; i++) {
797 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
802 fprintf(stderr, "Cannot grab keyboard\n");
807 parse_color(const char *str, const char *def)
818 /* +1 for the # ath the start */
819 if (*str != '#' || len > 9 || len < 4)
821 ++str; /* skip the # */
824 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
831 /* expand #rgb -> #rrggbb */
832 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
833 | (tmp.v & 0x00f) * 0x0011;
835 /* assume 0xff opacity */
838 } /* colors in #aarrggbb need no adjustments */
840 /* premultiply the alpha */
842 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
843 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
844 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
851 fprintf(stderr, "Invalid color: \"%s\".\n", str);
853 return parse_color(def, NULL);
859 * Given a string try to parse it as a number or return `def'.
862 parse_integer(const char *str, int def)
867 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
868 if (errstr != NULL) {
869 warnx("'%s' is %s; using %d as default", str, errstr, def);
876 /* Like parse_integer but recognize the percentages (i.e. strings ending with
879 parse_int_with_percentage(const char *str, int default_value, int max)
881 int len = strlen(str);
883 if (len > 0 && str[len - 1] == '%') {
887 if ((cpy = strdup(str)) == NULL)
891 val = parse_integer(cpy, default_value);
893 return val * max / 100;
896 return parse_integer(str, default_value);
900 get_mouse_coords(Display *d, int *x, int *y)
907 root = DefaultRootWindow(d);
909 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
910 for (i = 0; i < ScreenCount(d); ++i) {
911 if (root == RootWindow(d, i))
918 * Like parse_int_with_percentage but understands some special values:
919 * - middle that is (max-self)/2
922 * - end that is (max-self)
923 * - mx x coordinate of the mouse
924 * - my y coordinate of the mouse
927 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
929 if (!strcmp(str, "start"))
931 if (!strcmp(str, "middle") || !strcmp(str, "center"))
932 return (max - self) / 2;
933 if (!strcmp(str, "end"))
935 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
938 get_mouse_coords(d, &x, &y);
939 if (!strcmp(str, "mx"))
944 return parse_int_with_percentage(str, default_value, max);
947 /* Parse a string like a CSS value. */
948 /* TODO: harden a bit this function */
950 parse_csslike(const char *str)
953 char *s, *token, **ret;
960 ret = malloc(4 * sizeof(char *));
966 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
967 ret[i] = strdup(token);
970 for (j = 1; j < 4; j++)
971 ret[j] = strdup(ret[0]);
974 ret[2] = strdup(ret[0]);
975 ret[3] = strdup(ret[1]);
979 ret[3] = strdup(ret[1]);
981 /* before we didn't check for the return type of strdup, here we will
985 for (i = 0; i < 4; ++i)
986 any_null = ret[i] == NULL || any_null;
989 for (i = 0; i < 4; ++i)
993 if (i == 0 || any_null) {
1003 * Given an event, try to understand what the users wants. If the
1004 * return value is ADD_CHAR then `input' is a pointer to a string that
1005 * will need to be free'ed later.
1008 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1010 char str[SYM_BUF_SIZE] = { 0 };
1013 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1016 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1017 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1019 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1022 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1025 /* Try to read what key was pressed */
1027 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1028 if (s == XBufferOverflow) {
1030 "Buffer overflow when trying to create keyboard "
1035 if (ev->state & ControlMask) {
1036 if (!strcmp(str, "")) /* C-u */
1038 if (!strcmp(str, "")) /* C-w */
1040 if (!strcmp(str, "")) /* C-h */
1042 if (!strcmp(str, "\r")) /* C-m */
1043 return CONFIRM_CONTINUE;
1044 if (!strcmp(str, "")) /* C-p */
1046 if (!strcmp(str, "")) /* C-n */
1048 if (!strcmp(str, "")) /* C-c */
1050 if (!strcmp(str, "\t")) /* C-i */
1051 return TOGGLE_FIRST_SELECTED;
1054 *input = strdup(str);
1055 if (*input == NULL) {
1056 fprintf(stderr, "Error while allocating memory for key.\n");
1064 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1066 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1067 /* if there is something selected expand it and return */
1068 int index = cs->selected == -1 ? 0 : cs->selected;
1069 struct completion *c = cs->completions;
1083 if (*text == NULL) {
1084 fprintf(stderr, "Memory allocation error\n");
1088 *textlen = strlen(*text);
1092 if (!r->free_text) /* cannot accept arbitrary text */
1096 /* cs: completion list
1097 * offset: the offset of the click
1098 * first: the first (rendered) item
1099 * def: the default action
1102 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1104 ssize_t selected = first;
1107 if (cs->length == 0)
1110 if (offset < cs->completions[selected].offset)
1113 /* skip the first entry */
1114 for (selected += 1; selected < cs->length; ++selected) {
1115 if (cs->completions[selected].offset == -1)
1118 if (offset < cs->completions[selected].offset) {
1119 cs->selected = selected - 1;
1126 cs->selected = selected - 1;
1132 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1136 if (r->horizontal_layout)
1141 switch (e->button) {
1143 return select_clicked(cs, off, r->offset, CONFIRM);
1146 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1160 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1163 enum state status = LOOPING;
1165 while (status == LOOPING) {
1167 XNextEvent(r->d, &e);
1169 if (XFilterEvent(&e, r->w))
1174 XRefreshKeyboardMapping(&e.xmapping);
1179 if (e.xfocus.window != r->w)
1180 grabfocus(r->d, r->w);
1183 case VisibilityNotify:
1184 if (e.xvisibility.state != VisibilityUnobscured)
1185 XRaiseWindow(r->d, r->w);
1189 get_wh(r->d, &r->w, &r->width, &r->height);
1198 if (e.type == KeyPress)
1199 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1201 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1213 confirm(&status, r, cs, text, textlen);
1217 case CONFIRM_CONTINUE: {
1219 confirm(&status, r, cs, text, textlen);
1224 complete(cs, r->first_selected, 1, text, textlen, &status);
1225 r->offset = cs->selected;
1230 complete(cs, r->first_selected, 0, text, textlen, &status);
1231 r->offset = cs->selected;
1237 update_completions(cs, *text, lines, vlines, r->first_selected);
1243 update_completions(cs, *text, lines, vlines, r->first_selected);
1249 for (i = 0; i < *textlen; ++i)
1251 update_completions(cs, *text, lines, vlines, r->first_selected);
1259 str_len = strlen(input);
1262 * sometimes a strange key is pressed
1263 * i.e. ctrl alone), so input will be
1264 * empty. Don't need to update
1265 * completion in that case
1270 for (i = 0; i < str_len; ++i) {
1271 *textlen = pushc(text, *textlen, input[i]);
1272 if (*textlen == -1) {
1274 "Memory allocation "
1281 if (status != ERR) {
1283 cs, *text, lines, vlines, r->first_selected);
1291 case TOGGLE_FIRST_SELECTED:
1292 r->first_selected = !r->first_selected;
1293 if (r->first_selected && cs->selected < 0)
1295 if (!r->first_selected && cs->selected == 0)
1300 r->offset = MIN(r->offset + 1, cs->length - 1);
1304 r->offset = MAX((ssize_t)r->offset - 1, 0);
1317 load_font(struct rendering *r, const char *fontname)
1319 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1324 xim_init(struct rendering *r, XrmDatabase *xdb)
1326 XIMStyle best_match_style;
1330 /* Open the X input method */
1331 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1334 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1335 fprintf(stderr, "Input Styles could not be retrieved\n");
1336 exit(EX_UNAVAILABLE);
1339 best_match_style = 0;
1340 for (i = 0; i < xis->count_styles; ++i) {
1341 XIMStyle ts = xis->supported_styles[i];
1342 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1343 best_match_style = ts;
1349 if (!best_match_style)
1350 fprintf(stderr, "No matching input style could be determined\n");
1352 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1353 XNFocusWindow, r->w, NULL);
1355 err(1, "XCreateIC");
1359 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1360 int y, int ox, int oy, unsigned long background_pixel)
1362 XSetWindowAttributes attr;
1364 /* Create the window */
1365 attr.colormap = cmap;
1366 attr.override_redirect = 1;
1367 attr.border_pixel = 0;
1368 attr.background_pixel = background_pixel;
1369 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1370 | ButtonPress | VisibilityChangeMask;
1372 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1373 vinfo.depth, InputOutput, vinfo.visual,
1374 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1378 ps1extents(struct rendering *r)
1381 dup = strdupn(r->ps1);
1382 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1387 usage(char *prgname)
1390 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1391 " [-d separator] [-e window] [-f font] [-G color] [-g "
1393 " [-H height] [-I color] [-i size] [-J color] [-j "
1394 "size] [-l layout]\n"
1395 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1397 " [-t color] [-W width] [-x coord] [-y coord]\n",
1402 main(int argc, char **argv)
1404 struct completions *cs;
1409 Window parent_window;
1411 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1412 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1413 ch_borders_bg[4]; /* N E S W */
1416 int offset_x, offset_y, x, y;
1417 int textlen, d_width, d_height;
1419 char *sep, *parent_window_id;
1420 char **lines, **vlines;
1421 char *fontname, *text, *xrm;
1424 parent_window_id = NULL;
1426 r.first_selected = 0;
1428 r.multiple_select = 0;
1431 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1433 case 'h': /* help */
1436 case 'v': /* version */
1437 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1439 case 'e': /* embed */
1440 if ((parent_window_id = strdup(optarg)) == NULL)
1444 if ((sep = strdup(optarg)) == NULL)
1451 r.multiple_select = 1;
1458 lines = readlines(&nlines);
1464 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1467 for (i = 0; i < nlines; i++) {
1469 t = strstr(lines[i], sep);
1471 vlines[i] = lines[i];
1477 setlocale(LC_ALL, getenv("LANG"));
1481 /* where the monitor start (used only with xinerama) */
1482 offset_x = offset_y = 0;
1484 /* default width and height */
1488 /* default position on the screen */
1491 for (i = 0; i < 4; ++i) {
1492 /* default paddings */
1493 r.p_padding[i] = 10;
1494 r.c_padding[i] = 10;
1495 r.ch_padding[i] = 10;
1497 /* default borders */
1501 r.ch_borders[i] = 0;
1504 /* the prompt. We duplicate the string so later is easy to
1505 * free (in the case it's been overwritten by the user) */
1506 if ((r.ps1 = strdup("$ ")) == NULL)
1509 /* same for the font name */
1510 if ((fontname = strdup(DEFFONT)) == NULL)
1514 if ((text = malloc(textlen * sizeof(char))) == NULL)
1517 /* struct completions *cs = filter(text, lines); */
1518 if ((cs = compls_new(nlines)) == NULL)
1519 err(1, "compls_new");
1521 /* start talking to xorg */
1522 r.d = XOpenDisplay(NULL);
1524 fprintf(stderr, "Could not open display!\n");
1525 return EX_UNAVAILABLE;
1529 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1530 parent_window = DefaultRootWindow(r.d);
1534 /* get display size */
1535 get_wh(r.d, &parent_window, &d_width, &d_height);
1537 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1538 XineramaScreenInfo *info;
1541 int number_of_screens, monitors, i;
1542 int root_x, root_y, win_x, win_y;
1546 number_of_screens = XScreenCount(r.d);
1547 for (i = 0; i < number_of_screens; ++i) {
1548 root = XRootWindow(r.d, i);
1549 res = XQueryPointer(
1550 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1556 fprintf(stderr, "No mouse found.\n");
1561 /* Now find in which monitor the mice is */
1562 info = XineramaQueryScreens(r.d, &monitors);
1564 for (i = 0; i < monitors; ++i) {
1565 if (info[i].x_org <= root_x
1566 && root_x <= (info[i].x_org + info[i].width)
1567 && info[i].y_org <= root_y
1568 && root_y <= (info[i].y_org + info[i].height)) {
1569 offset_x = info[i].x_org;
1570 offset_y = info[i].y_org;
1571 d_width = info[i].width;
1572 d_height = info[i].height;
1580 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1581 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1583 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1584 fgs[2] = parse_color("#000", NULL);
1586 bgs[0] = bgs[1] = parse_color("#000", NULL);
1587 bgs[2] = parse_color("#fff", NULL);
1589 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1591 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1592 = parse_color("#000", NULL);
1593 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1594 = parse_color("#000", NULL);
1595 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1596 = parse_color("#000", NULL);
1598 r.horizontal_layout = 1;
1600 /* Read the resources */
1602 xrm = XResourceManagerString(r.d);
1608 xdb = XrmGetStringDatabase(xrm);
1610 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1612 if ((fontname = strdup(value.addr)) == NULL)
1615 fprintf(stderr, "no font defined, using %s\n", fontname);
1618 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1619 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1621 fprintf(stderr, "no layout defined, using horizontal\n");
1623 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1625 r.ps1 = normalize_str(value.addr);
1628 "no prompt defined, using \"%s\" as "
1633 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1635 sizes = parse_csslike(value.addr);
1637 for (i = 0; i < 4; ++i)
1638 r.p_borders[i] = parse_integer(sizes[i], 0);
1641 "error while parsing "
1642 "MyMenu.prompt.border.size");
1645 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1647 colors = parse_csslike(value.addr);
1649 for (i = 0; i < 4; ++i)
1650 p_borders_bg[i] = parse_color(colors[i], "#000");
1653 "error while parsing "
1654 "MyMenu.prompt.border.color");
1657 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1659 colors = parse_csslike(value.addr);
1661 for (i = 0; i < 4; ++i)
1662 r.p_padding[i] = parse_integer(colors[i], 0);
1665 "error while parsing "
1666 "MyMenu.prompt.padding");
1669 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1670 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1672 fprintf(stderr, "no width defined, using %d\n", r.width);
1674 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1675 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1677 fprintf(stderr, "no height defined, using %d\n", r.height);
1679 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1680 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1682 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1683 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1685 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1687 borders = parse_csslike(value.addr);
1688 if (borders != NULL)
1689 for (i = 0; i < 4; ++i)
1690 r.borders[i] = parse_int_with_percentage(
1691 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1694 "error while parsing "
1695 "MyMenu.border.size\n");
1699 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1700 fgs[0] = parse_color(value.addr, "#fff");
1702 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1703 bgs[0] = parse_color(value.addr, "#000");
1706 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1707 fgs[1] = parse_color(value.addr, "#fff");
1709 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1710 bgs[1] = parse_color(value.addr, "#000");
1712 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1714 paddings = parse_csslike(value.addr);
1715 if (paddings != NULL)
1716 for (i = 0; i < 4; ++i)
1717 r.c_padding[i] = parse_integer(paddings[i], 0);
1720 "Error while parsing "
1721 "MyMenu.completion.padding");
1724 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1726 sizes = parse_csslike(value.addr);
1728 for (i = 0; i < 4; ++i)
1729 r.c_borders[i] = parse_integer(sizes[i], 0);
1732 "Error while parsing "
1733 "MyMenu.completion.border.size");
1736 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1738 sizes = parse_csslike(value.addr);
1740 for (i = 0; i < 4; ++i)
1741 c_borders_bg[i] = parse_color(sizes[i], "#000");
1744 "Error while parsing "
1745 "MyMenu.completion.border.color");
1748 /* Completion Highlighted */
1750 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1751 fgs[2] = parse_color(value.addr, "#000");
1754 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1755 bgs[2] = parse_color(value.addr, "#fff");
1758 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1760 paddings = parse_csslike(value.addr);
1761 if (paddings != NULL)
1762 for (i = 0; i < 4; ++i)
1763 r.ch_padding[i] = parse_integer(paddings[i], 0);
1766 "Error while parsing "
1767 "MyMenu.completion_highlighted."
1771 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1774 sizes = parse_csslike(value.addr);
1776 for (i = 0; i < 4; ++i)
1777 r.ch_borders[i] = parse_integer(sizes[i], 0);
1780 "Error while parsing "
1781 "MyMenu.completion_highlighted."
1785 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1788 colors = parse_csslike(value.addr);
1790 for (i = 0; i < 4; ++i)
1791 ch_borders_bg[i] = parse_color(colors[i], "#000");
1794 "Error while parsing "
1795 "MyMenu.completion_highlighted."
1800 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1802 colors = parse_csslike(value.addr);
1804 for (i = 0; i < 4; ++i)
1805 borders_bg[i] = parse_color(colors[i], "#000");
1808 "error while parsing "
1809 "MyMenu.border.color\n");
1813 /* Second round of args parsing */
1814 optind = 0; /* reset the option index */
1815 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1818 r.first_selected = 1;
1821 /* free_text -- already catched */
1823 /* separator -- this case was already catched */
1825 /* embedding mymenu this case was already catched. */
1827 /* multiple selection this case was already catched.
1832 newprompt = strdup(optarg);
1833 if (newprompt != NULL) {
1840 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1843 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1847 if ((paddings = parse_csslike(optarg)) != NULL)
1848 for (i = 0; i < 4; ++i)
1849 r.p_padding[i] = parse_integer(paddings[i], 0);
1854 if ((colors = parse_csslike(optarg)) != NULL)
1855 for (i = 0; i < 4; ++i)
1856 p_borders_bg[i] = parse_color(colors[i], "#000");
1861 if ((sizes = parse_csslike(optarg)) != NULL)
1862 for (i = 0; i < 4; ++i)
1863 r.p_borders[i] = parse_integer(sizes[i], 0);
1868 if ((colors = parse_csslike(optarg)) != NULL)
1869 for (i = 0; i < 4; ++i)
1870 c_borders_bg[i] = parse_color(colors[i], "#000");
1875 if ((sizes = parse_csslike(optarg)) != NULL)
1876 for (i = 0; i < 4; ++i)
1877 r.c_borders[i] = parse_integer(sizes[i], 0);
1882 if ((colors = parse_csslike(optarg)) != NULL)
1883 for (i = 0; i < 4; ++i)
1884 ch_borders_bg[i] = parse_color(colors[i], "#000");
1889 if ((sizes = parse_csslike(optarg)) != NULL)
1890 for (i = 0; i < 4; ++i)
1891 r.ch_borders[i] = parse_integer(sizes[i], 0);
1895 r.horizontal_layout = !strcmp(optarg, "horizontal");
1899 if ((newfont = strdup(optarg)) != NULL) {
1906 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1909 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1913 if ((borders = parse_csslike(optarg)) != NULL) {
1914 for (i = 0; i < 4; ++i)
1915 r.borders[i] = parse_integer(borders[i], 0);
1917 fprintf(stderr, "Error parsing b option\n");
1922 if ((colors = parse_csslike(optarg)) != NULL) {
1923 for (i = 0; i < 4; ++i)
1924 borders_bg[i] = parse_color(colors[i], "#000");
1926 fprintf(stderr, "error while parsing B option\n");
1930 fgs[0] = parse_color(optarg, NULL);
1933 bgs[0] = parse_color(optarg, NULL);
1936 fgs[1] = parse_color(optarg, NULL);
1939 bgs[1] = parse_color(optarg, NULL);
1942 fgs[2] = parse_color(optarg, NULL);
1945 bgs[2] = parse_color(optarg, NULL);
1948 fprintf(stderr, "Unrecognized option %c\n", ch);
1954 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1955 fprintf(stderr, "height, width, x or y are lesser than 0.");
1959 /* since only now we know if the first should be selected,
1960 * update the completion here */
1961 update_completions(cs, text, lines, vlines, r.first_selected);
1963 /* update the prompt lenght, only now we surely know the length of it
1965 r.ps1len = strlen(r.ps1);
1967 /* Create the window */
1968 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1969 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1970 XMapRaised(r.d, r.w);
1972 /* If embed, listen for other events as well */
1974 Window *children, parent, root;
1975 unsigned int children_no;
1977 XSelectInput(r.d, parent_window, FocusChangeMask);
1978 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1980 for (i = 0; i < children_no && children[i] != r.w; ++i)
1981 XSelectInput(r.d, children[i], FocusChangeMask);
1984 grabfocus(r.d, r.w);
1987 take_keyboard(r.d, r.w);
1989 r.x_zero = r.borders[3];
1990 r.y_zero = r.borders[0];
1995 for (i = 0; i < 3; ++i) {
1996 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1997 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2000 for (i = 0; i < 4; ++i) {
2001 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2002 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2003 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2004 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2008 /* Load the colors in our GCs */
2009 for (i = 0; i < 3; ++i) {
2010 XSetForeground(r.d, r.fgs[i], fgs[i]);
2011 XSetForeground(r.d, r.bgs[i], bgs[i]);
2014 for (i = 0; i < 4; ++i) {
2015 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2016 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2017 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2018 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2021 if (load_font(&r, fontname) == -1)
2024 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2026 for (i = 0; i < 3; ++i) {
2028 XRenderColor xrcolor;
2030 c = *(rgba_t *)&fgs[i];
2031 xrcolor.red = EXPANDBITS(c.rgba.r);
2032 xrcolor.green = EXPANDBITS(c.rgba.g);
2033 xrcolor.blue = EXPANDBITS(c.rgba.b);
2034 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2035 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2038 /* compute prompt dimensions */
2044 if (pledge("stdio", "") == -1)
2048 /* Cache text height */
2049 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2051 /* Draw the window for the first time */
2055 while (status == LOOPING || status == OK_LOOP) {
2056 status = loop(&r, &text, &textlen, cs, lines, vlines);
2059 printf("%s\n", text);
2061 if (!r.multiple_select && status == OK_LOOP)
2065 XUngrabKeyboard(r.d, CurrentTime);
2067 for (i = 0; i < 3; ++i)
2068 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2070 for (i = 0; i < 3; ++i) {
2071 XFreeGC(r.d, r.fgs[i]);
2072 XFreeGC(r.d, r.bgs[i]);
2075 for (i = 0; i < 4; ++i) {
2076 XFreeGC(r.d, r.borders_bg[i]);
2077 XFreeGC(r.d, r.p_borders_bg[i]);
2078 XFreeGC(r.d, r.c_borders_bg[i]);
2079 XFreeGC(r.d, r.ch_borders_bg[i]);
2085 for (i = 0; i < 3; ++i)
2086 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2087 XftFontClose(r.d, r.font);
2088 XftDrawDestroy(r.xftdraw);
2098 XFreeColormap(r.d, cmap);
2100 XDestroyWindow(r.d, r.w);
2103 return status != OK;