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` */
468 if (str == NULL || len == 0)
471 if ((dup = strdup(str)) == NULL)
474 for (i = 0; i < len; ++i)
482 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
484 GC *border_color, bg;
485 int *padding, *borders;
486 int ret = 0, inner_width, inner_height, x;
490 border_color = r->p_borders_bg;
491 padding = r->p_padding;
492 borders = r->p_borders;
496 border_color = r->c_borders_bg;
497 padding = r->c_padding;
498 borders = r->c_borders;
502 border_color = r->ch_borders_bg;
503 padding = r->ch_padding;
504 borders = r->ch_borders;
509 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
511 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
512 inner_height = padding[0] + r->text_height + padding[2];
515 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
518 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + INNER_WIDTH(r) - borders[1], y,
522 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
523 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
526 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
529 x = r->x_zero + borders[3];
531 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
534 y += padding[0] + r->text_height;
536 if (prefix != NULL) {
537 draw_string(prefix, strlen(prefix), x, y, r, t);
540 draw_string(text, strlen(text), x, y, r, t);
546 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
548 GC *border_color, bg;
549 int *padding, *borders;
550 int ret = 0, inner_width, inner_height, y, text_width;
554 border_color = r->p_borders_bg;
555 padding = r->p_padding;
556 borders = r->p_borders;
560 border_color = r->c_borders_bg;
561 padding = r->c_padding;
562 borders = r->c_borders;
566 border_color = r->ch_borders_bg;
567 padding = r->ch_padding;
568 borders = r->ch_borders;
573 if (padding[0] < 0 || padding[2] < 0)
574 padding[0] = padding[2]
575 = (INNER_HEIGHT(r) - borders[0] - borders[2] - r->text_height) / 2;
577 /* If they are still lesser than 0, set 'em to 0 */
578 if (padding[0] < 0 || padding[2] < 0)
579 padding[0] = padding[2] = 0;
581 /* Get the text width */
582 text_extents(text, strlen(text), r, &text_width, NULL);
584 text_width += prefix_width;
586 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
588 inner_width = padding[3] + text_width + padding[1];
589 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
592 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
595 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
596 borders[1], INNER_HEIGHT(r));
599 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + INNER_HEIGHT(r) - borders[2],
603 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], INNER_HEIGHT(r));
607 y = r->y_zero + borders[0];
608 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
611 y += padding[0] + r->text_height;
613 if (prefix != NULL) {
614 draw_string(prefix, strlen(prefix), x, y, r, t);
617 draw_string(text, strlen(text), x, y, r, t);
622 /* ,-----------------------------------------------------------------, */
623 /* | 20 char text | completion | completion | completion | compl | */
624 /* `-----------------------------------------------------------------' */
626 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
631 /* Draw the prompt */
632 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
634 for (i = r->offset; i < cs->length; ++i) {
635 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
637 cs->completions[i].offset = x;
639 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
641 if (x > INNER_WIDTH(r))
645 for (i += 1; i < cs->length; ++i)
646 cs->completions[i].offset = -1;
649 /* ,-----------------------------------------------------------------, */
651 /* |-----------------------------------------------------------------| */
653 /* |-----------------------------------------------------------------| */
655 /* `-----------------------------------------------------------------' */
657 draw_vertically(struct rendering *r, char *text, struct completions *cs)
662 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
664 for (i = r->offset; i < cs->length; ++i) {
665 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
667 cs->completions[i].offset = y;
669 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
671 if (y > INNER_HEIGHT(r))
675 for (i += 1; i < cs->length; ++i)
676 cs->completions[i].offset = -1;
680 draw(struct rendering *r, char *text, struct completions *cs)
682 /* Draw the background */
684 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, INNER_WIDTH(r), INNER_HEIGHT(r));
686 /* Draw the contents */
687 if (r->horizontal_layout)
688 draw_horizontally(r, text, cs);
690 draw_vertically(r, text, cs);
692 /* Draw the borders */
693 if (r->borders[0] != 0)
694 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
696 if (r->borders[1] != 0)
697 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
698 r->borders[1], r->height);
700 if (r->borders[2] != 0)
701 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
704 if (r->borders[3] != 0)
705 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
711 /* Set some WM stuff */
713 set_win_atoms_hints(Display *d, Window w, int width, int height)
716 XClassHint *class_hint;
717 XSizeHints *size_hint;
719 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
720 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
721 32, PropModeReplace, (unsigned char *)&type, 1);
723 /* some window managers honor this properties */
724 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
725 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
726 PropModeReplace, (unsigned char *)&type, 1);
728 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
729 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
730 PropModeAppend, (unsigned char *)&type, 1);
732 /* Setting window hints */
733 class_hint = XAllocClassHint();
734 if (class_hint == NULL) {
735 fprintf(stderr, "Could not allocate memory for class hint\n");
736 exit(EX_UNAVAILABLE);
739 class_hint->res_name = RESNAME;
740 class_hint->res_class = RESCLASS;
741 XSetClassHint(d, w, class_hint);
744 size_hint = XAllocSizeHints();
745 if (size_hint == NULL) {
746 fprintf(stderr, "Could not allocate memory for size hint\n");
747 exit(EX_UNAVAILABLE);
750 size_hint->flags = PMinSize | PBaseSize;
751 size_hint->min_width = width;
752 size_hint->base_width = width;
753 size_hint->min_height = height;
754 size_hint->base_height = height;
759 /* Get the width and height of the window `w' */
761 get_wh(Display *d, Window *w, int *width, int *height)
763 XWindowAttributes win_attr;
765 XGetWindowAttributes(d, *w, &win_attr);
766 *height = win_attr.height;
767 *width = win_attr.width;
771 grabfocus(Display *d, Window w)
774 for (i = 0; i < 100; ++i) {
778 XGetInputFocus(d, &focuswin, &revert_to_win);
783 XSetInputFocus(d, w, RevertToParent, CurrentTime);
790 * I know this may seem a little hackish BUT is the only way I managed
791 * to actually grab that goddam keyboard. Only one call to
792 * XGrabKeyboard does not always end up with the keyboard grabbed!
795 take_keyboard(Display *d, Window w)
798 for (i = 0; i < 100; i++) {
799 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
804 fprintf(stderr, "Cannot grab keyboard\n");
809 parse_color(const char *str, const char *def)
820 /* +1 for the # ath the start */
821 if (*str != '#' || len > 9 || len < 4)
823 ++str; /* skip the # */
826 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
833 /* expand #rgb -> #rrggbb */
834 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
835 | (tmp.v & 0x00f) * 0x0011;
837 /* assume 0xff opacity */
840 } /* colors in #aarrggbb need no adjustments */
842 /* premultiply the alpha */
844 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
845 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
846 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
853 fprintf(stderr, "Invalid color: \"%s\".\n", str);
855 return parse_color(def, NULL);
861 * Given a string try to parse it as a number or return `def'.
864 parse_integer(const char *str, int def)
869 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
870 if (errstr != NULL) {
871 warnx("'%s' is %s; using %d as default", str, errstr, def);
878 /* Like parse_integer but recognize the percentages (i.e. strings ending with
881 parse_int_with_percentage(const char *str, int default_value, int max)
883 int len = strlen(str);
885 if (len > 0 && str[len - 1] == '%') {
889 if ((cpy = strdup(str)) == NULL)
893 val = parse_integer(cpy, default_value);
895 return val * max / 100;
898 return parse_integer(str, default_value);
902 get_mouse_coords(Display *d, int *x, int *y)
909 root = DefaultRootWindow(d);
911 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
912 for (i = 0; i < ScreenCount(d); ++i) {
913 if (root == RootWindow(d, i))
920 * Like parse_int_with_percentage but understands some special values:
921 * - middle that is (max-self)/2
924 * - end that is (max-self)
925 * - mx x coordinate of the mouse
926 * - my y coordinate of the mouse
929 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
931 if (!strcmp(str, "start"))
933 if (!strcmp(str, "middle") || !strcmp(str, "center"))
934 return (max - self) / 2;
935 if (!strcmp(str, "end"))
937 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
940 get_mouse_coords(d, &x, &y);
941 if (!strcmp(str, "mx"))
946 return parse_int_with_percentage(str, default_value, max);
949 /* Parse a string like a CSS value. */
950 /* TODO: harden a bit this function */
952 parse_csslike(const char *str)
955 char *s, *token, **ret;
962 ret = malloc(4 * sizeof(char *));
968 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
969 ret[i] = strdup(token);
972 for (j = 1; j < 4; j++)
973 ret[j] = strdup(ret[0]);
976 ret[2] = strdup(ret[0]);
977 ret[3] = strdup(ret[1]);
981 ret[3] = strdup(ret[1]);
983 /* before we didn't check for the return type of strdup, here we will
987 for (i = 0; i < 4; ++i)
988 any_null = ret[i] == NULL || any_null;
991 for (i = 0; i < 4; ++i)
995 if (i == 0 || any_null) {
1005 * Given an event, try to understand what the users wants. If the
1006 * return value is ADD_CHAR then `input' is a pointer to a string that
1007 * will need to be free'ed later.
1010 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1012 char str[SYM_BUF_SIZE] = { 0 };
1015 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1018 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1019 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1021 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1024 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1027 /* Try to read what key was pressed */
1029 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1030 if (s == XBufferOverflow) {
1032 "Buffer overflow when trying to create keyboard "
1037 if (ev->state & ControlMask) {
1038 if (!strcmp(str, "")) /* C-u */
1040 if (!strcmp(str, "")) /* C-w */
1042 if (!strcmp(str, "")) /* C-h */
1044 if (!strcmp(str, "\r")) /* C-m */
1045 return CONFIRM_CONTINUE;
1046 if (!strcmp(str, "")) /* C-p */
1048 if (!strcmp(str, "")) /* C-n */
1050 if (!strcmp(str, "")) /* C-c */
1052 if (!strcmp(str, "\t")) /* C-i */
1053 return TOGGLE_FIRST_SELECTED;
1056 *input = strdup(str);
1057 if (*input == NULL) {
1058 fprintf(stderr, "Error while allocating memory for key.\n");
1066 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1068 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1069 /* if there is something selected expand it and return */
1070 int index = cs->selected == -1 ? 0 : cs->selected;
1071 struct completion *c = cs->completions;
1085 if (*text == NULL) {
1086 fprintf(stderr, "Memory allocation error\n");
1090 *textlen = strlen(*text);
1094 if (!r->free_text) /* cannot accept arbitrary text */
1098 /* cs: completion list
1099 * offset: the offset of the click
1100 * first: the first (rendered) item
1101 * def: the default action
1104 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1106 ssize_t selected = first;
1109 if (cs->length == 0)
1112 if (offset < cs->completions[selected].offset)
1115 /* skip the first entry */
1116 for (selected += 1; selected < cs->length; ++selected) {
1117 if (cs->completions[selected].offset == -1)
1120 if (offset < cs->completions[selected].offset) {
1121 cs->selected = selected - 1;
1128 cs->selected = selected - 1;
1134 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1138 if (r->horizontal_layout)
1143 switch (e->button) {
1145 return select_clicked(cs, off, r->offset, CONFIRM);
1148 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1162 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1165 enum state status = LOOPING;
1167 while (status == LOOPING) {
1169 XNextEvent(r->d, &e);
1171 if (XFilterEvent(&e, r->w))
1176 XRefreshKeyboardMapping(&e.xmapping);
1181 if (e.xfocus.window != r->w)
1182 grabfocus(r->d, r->w);
1185 case VisibilityNotify:
1186 if (e.xvisibility.state != VisibilityUnobscured)
1187 XRaiseWindow(r->d, r->w);
1191 get_wh(r->d, &r->w, &r->width, &r->height);
1200 if (e.type == KeyPress)
1201 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1203 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1215 confirm(&status, r, cs, text, textlen);
1219 case CONFIRM_CONTINUE: {
1221 confirm(&status, r, cs, text, textlen);
1226 complete(cs, r->first_selected, 1, text, textlen, &status);
1227 r->offset = cs->selected;
1232 complete(cs, r->first_selected, 0, text, textlen, &status);
1233 r->offset = cs->selected;
1239 update_completions(cs, *text, lines, vlines, r->first_selected);
1245 update_completions(cs, *text, lines, vlines, r->first_selected);
1251 for (i = 0; i < *textlen; ++i)
1253 update_completions(cs, *text, lines, vlines, r->first_selected);
1261 str_len = strlen(input);
1264 * sometimes a strange key is pressed
1265 * i.e. ctrl alone), so input will be
1266 * empty. Don't need to update
1267 * completion in that case
1272 for (i = 0; i < str_len; ++i) {
1273 *textlen = pushc(text, *textlen, input[i]);
1274 if (*textlen == -1) {
1276 "Memory allocation "
1283 if (status != ERR) {
1285 cs, *text, lines, vlines, r->first_selected);
1293 case TOGGLE_FIRST_SELECTED:
1294 r->first_selected = !r->first_selected;
1295 if (r->first_selected && cs->selected < 0)
1297 if (!r->first_selected && cs->selected == 0)
1302 r->offset = MIN(r->offset + 1, cs->length - 1);
1306 r->offset = MAX((ssize_t)r->offset - 1, 0);
1319 load_font(struct rendering *r, const char *fontname)
1321 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1326 xim_init(struct rendering *r, XrmDatabase *xdb)
1328 XIMStyle best_match_style;
1332 /* Open the X input method */
1333 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1336 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1337 fprintf(stderr, "Input Styles could not be retrieved\n");
1338 exit(EX_UNAVAILABLE);
1341 best_match_style = 0;
1342 for (i = 0; i < xis->count_styles; ++i) {
1343 XIMStyle ts = xis->supported_styles[i];
1344 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1345 best_match_style = ts;
1351 if (!best_match_style)
1352 fprintf(stderr, "No matching input style could be determined\n");
1354 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1355 XNFocusWindow, r->w, NULL);
1357 err(1, "XCreateIC");
1361 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1362 int y, int ox, int oy, unsigned long background_pixel)
1364 XSetWindowAttributes attr;
1366 /* Create the window */
1367 attr.colormap = cmap;
1368 attr.override_redirect = 1;
1369 attr.border_pixel = 0;
1370 attr.background_pixel = background_pixel;
1371 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1372 | ButtonPress | VisibilityChangeMask;
1374 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1375 vinfo.depth, InputOutput, vinfo.visual,
1376 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1380 ps1extents(struct rendering *r)
1383 dup = strdupn(r->ps1);
1384 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1389 usage(char *prgname)
1392 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1393 " [-d separator] [-e window] [-f font] [-G color] [-g "
1395 " [-H height] [-I color] [-i size] [-J color] [-j "
1396 "size] [-l layout]\n"
1397 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1399 " [-t color] [-W width] [-x coord] [-y coord]\n",
1404 main(int argc, char **argv)
1406 struct completions *cs;
1411 Window parent_window;
1413 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1414 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1415 ch_borders_bg[4]; /* N E S W */
1418 int offset_x, offset_y, x, y;
1419 int textlen, d_width, d_height;
1421 char *sep, *parent_window_id;
1422 char **lines, **vlines;
1423 char *fontname, *text, *xrm;
1426 parent_window_id = NULL;
1428 r.first_selected = 0;
1430 r.multiple_select = 0;
1433 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1435 case 'h': /* help */
1438 case 'v': /* version */
1439 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1441 case 'e': /* embed */
1442 if ((parent_window_id = strdup(optarg)) == NULL)
1446 if ((sep = strdup(optarg)) == NULL)
1453 r.multiple_select = 1;
1460 lines = readlines(&nlines);
1466 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1469 for (i = 0; i < nlines; i++) {
1471 t = strstr(lines[i], sep);
1473 vlines[i] = lines[i];
1479 setlocale(LC_ALL, getenv("LANG"));
1483 /* where the monitor start (used only with xinerama) */
1484 offset_x = offset_y = 0;
1486 /* default width and height */
1490 /* default position on the screen */
1493 for (i = 0; i < 4; ++i) {
1494 /* default paddings */
1495 r.p_padding[i] = 10;
1496 r.c_padding[i] = 10;
1497 r.ch_padding[i] = 10;
1499 /* default borders */
1503 r.ch_borders[i] = 0;
1506 /* the prompt. We duplicate the string so later is easy to
1507 * free (in the case it's been overwritten by the user) */
1508 if ((r.ps1 = strdup("$ ")) == NULL)
1511 /* same for the font name */
1512 if ((fontname = strdup(DEFFONT)) == NULL)
1516 if ((text = malloc(textlen * sizeof(char))) == NULL)
1519 /* struct completions *cs = filter(text, lines); */
1520 if ((cs = compls_new(nlines)) == NULL)
1521 err(1, "compls_new");
1523 /* start talking to xorg */
1524 r.d = XOpenDisplay(NULL);
1526 fprintf(stderr, "Could not open display!\n");
1527 return EX_UNAVAILABLE;
1531 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1532 parent_window = DefaultRootWindow(r.d);
1536 /* get display size */
1537 get_wh(r.d, &parent_window, &d_width, &d_height);
1539 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1540 XineramaScreenInfo *info;
1543 int number_of_screens, monitors, i;
1544 int root_x, root_y, win_x, win_y;
1548 number_of_screens = XScreenCount(r.d);
1549 for (i = 0; i < number_of_screens; ++i) {
1550 root = XRootWindow(r.d, i);
1551 res = XQueryPointer(
1552 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1558 fprintf(stderr, "No mouse found.\n");
1563 /* Now find in which monitor the mice is */
1564 info = XineramaQueryScreens(r.d, &monitors);
1566 for (i = 0; i < monitors; ++i) {
1567 if (info[i].x_org <= root_x
1568 && root_x <= (info[i].x_org + info[i].width)
1569 && info[i].y_org <= root_y
1570 && root_y <= (info[i].y_org + info[i].height)) {
1571 offset_x = info[i].x_org;
1572 offset_y = info[i].y_org;
1573 d_width = info[i].width;
1574 d_height = info[i].height;
1582 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1583 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1585 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1586 fgs[2] = parse_color("#000", NULL);
1588 bgs[0] = bgs[1] = parse_color("#000", NULL);
1589 bgs[2] = parse_color("#fff", NULL);
1591 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1593 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1594 = parse_color("#000", NULL);
1595 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1596 = parse_color("#000", NULL);
1597 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1598 = parse_color("#000", NULL);
1600 r.horizontal_layout = 1;
1602 /* Read the resources */
1604 xrm = XResourceManagerString(r.d);
1610 xdb = XrmGetStringDatabase(xrm);
1612 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1614 if ((fontname = strdup(value.addr)) == NULL)
1617 fprintf(stderr, "no font defined, using %s\n", fontname);
1620 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1621 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1623 fprintf(stderr, "no layout defined, using horizontal\n");
1625 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1627 r.ps1 = normalize_str(value.addr);
1630 "no prompt defined, using \"%s\" as "
1635 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1637 sizes = parse_csslike(value.addr);
1639 for (i = 0; i < 4; ++i)
1640 r.p_borders[i] = parse_integer(sizes[i], 0);
1643 "error while parsing "
1644 "MyMenu.prompt.border.size");
1647 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1649 colors = parse_csslike(value.addr);
1651 for (i = 0; i < 4; ++i)
1652 p_borders_bg[i] = parse_color(colors[i], "#000");
1655 "error while parsing "
1656 "MyMenu.prompt.border.color");
1659 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1661 colors = parse_csslike(value.addr);
1663 for (i = 0; i < 4; ++i)
1664 r.p_padding[i] = parse_integer(colors[i], 0);
1667 "error while parsing "
1668 "MyMenu.prompt.padding");
1671 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1672 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1674 fprintf(stderr, "no width defined, using %d\n", r.width);
1676 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1677 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1679 fprintf(stderr, "no height defined, using %d\n", r.height);
1681 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1682 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1684 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1685 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1687 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1689 borders = parse_csslike(value.addr);
1690 if (borders != NULL)
1691 for (i = 0; i < 4; ++i)
1692 r.borders[i] = parse_int_with_percentage(
1693 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1696 "error while parsing "
1697 "MyMenu.border.size\n");
1701 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1702 fgs[0] = parse_color(value.addr, "#fff");
1704 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1705 bgs[0] = parse_color(value.addr, "#000");
1708 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1709 fgs[1] = parse_color(value.addr, "#fff");
1711 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1712 bgs[1] = parse_color(value.addr, "#000");
1714 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1716 paddings = parse_csslike(value.addr);
1717 if (paddings != NULL)
1718 for (i = 0; i < 4; ++i)
1719 r.c_padding[i] = parse_integer(paddings[i], 0);
1722 "Error while parsing "
1723 "MyMenu.completion.padding");
1726 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1728 sizes = parse_csslike(value.addr);
1730 for (i = 0; i < 4; ++i)
1731 r.c_borders[i] = parse_integer(sizes[i], 0);
1734 "Error while parsing "
1735 "MyMenu.completion.border.size");
1738 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1740 sizes = parse_csslike(value.addr);
1742 for (i = 0; i < 4; ++i)
1743 c_borders_bg[i] = parse_color(sizes[i], "#000");
1746 "Error while parsing "
1747 "MyMenu.completion.border.color");
1750 /* Completion Highlighted */
1752 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1753 fgs[2] = parse_color(value.addr, "#000");
1756 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1757 bgs[2] = parse_color(value.addr, "#fff");
1760 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1762 paddings = parse_csslike(value.addr);
1763 if (paddings != NULL)
1764 for (i = 0; i < 4; ++i)
1765 r.ch_padding[i] = parse_integer(paddings[i], 0);
1768 "Error while parsing "
1769 "MyMenu.completion_highlighted."
1773 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1776 sizes = parse_csslike(value.addr);
1778 for (i = 0; i < 4; ++i)
1779 r.ch_borders[i] = parse_integer(sizes[i], 0);
1782 "Error while parsing "
1783 "MyMenu.completion_highlighted."
1787 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1790 colors = parse_csslike(value.addr);
1792 for (i = 0; i < 4; ++i)
1793 ch_borders_bg[i] = parse_color(colors[i], "#000");
1796 "Error while parsing "
1797 "MyMenu.completion_highlighted."
1802 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1804 colors = parse_csslike(value.addr);
1806 for (i = 0; i < 4; ++i)
1807 borders_bg[i] = parse_color(colors[i], "#000");
1810 "error while parsing "
1811 "MyMenu.border.color\n");
1815 /* Second round of args parsing */
1816 optind = 0; /* reset the option index */
1817 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1820 r.first_selected = 1;
1823 /* free_text -- already catched */
1825 /* separator -- this case was already catched */
1827 /* embedding mymenu this case was already catched. */
1829 /* multiple selection this case was already catched.
1834 newprompt = strdup(optarg);
1835 if (newprompt != NULL) {
1842 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1845 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1849 if ((paddings = parse_csslike(optarg)) != NULL)
1850 for (i = 0; i < 4; ++i)
1851 r.p_padding[i] = parse_integer(paddings[i], 0);
1856 if ((colors = parse_csslike(optarg)) != NULL)
1857 for (i = 0; i < 4; ++i)
1858 p_borders_bg[i] = parse_color(colors[i], "#000");
1863 if ((sizes = parse_csslike(optarg)) != NULL)
1864 for (i = 0; i < 4; ++i)
1865 r.p_borders[i] = parse_integer(sizes[i], 0);
1870 if ((colors = parse_csslike(optarg)) != NULL)
1871 for (i = 0; i < 4; ++i)
1872 c_borders_bg[i] = parse_color(colors[i], "#000");
1877 if ((sizes = parse_csslike(optarg)) != NULL)
1878 for (i = 0; i < 4; ++i)
1879 r.c_borders[i] = parse_integer(sizes[i], 0);
1884 if ((colors = parse_csslike(optarg)) != NULL)
1885 for (i = 0; i < 4; ++i)
1886 ch_borders_bg[i] = parse_color(colors[i], "#000");
1891 if ((sizes = parse_csslike(optarg)) != NULL)
1892 for (i = 0; i < 4; ++i)
1893 r.ch_borders[i] = parse_integer(sizes[i], 0);
1897 r.horizontal_layout = !strcmp(optarg, "horizontal");
1901 if ((newfont = strdup(optarg)) != NULL) {
1908 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1911 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1915 if ((borders = parse_csslike(optarg)) != NULL) {
1916 for (i = 0; i < 4; ++i)
1917 r.borders[i] = parse_integer(borders[i], 0);
1919 fprintf(stderr, "Error parsing b option\n");
1924 if ((colors = parse_csslike(optarg)) != NULL) {
1925 for (i = 0; i < 4; ++i)
1926 borders_bg[i] = parse_color(colors[i], "#000");
1928 fprintf(stderr, "error while parsing B option\n");
1932 fgs[0] = parse_color(optarg, NULL);
1935 bgs[0] = parse_color(optarg, NULL);
1938 fgs[1] = parse_color(optarg, NULL);
1941 bgs[1] = parse_color(optarg, NULL);
1944 fgs[2] = parse_color(optarg, NULL);
1947 bgs[2] = parse_color(optarg, NULL);
1950 fprintf(stderr, "Unrecognized option %c\n", ch);
1956 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1957 fprintf(stderr, "height, width, x or y are lesser than 0.");
1961 /* since only now we know if the first should be selected,
1962 * update the completion here */
1963 update_completions(cs, text, lines, vlines, r.first_selected);
1965 /* update the prompt lenght, only now we surely know the length of it
1967 r.ps1len = strlen(r.ps1);
1969 /* Create the window */
1970 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1971 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1972 XMapRaised(r.d, r.w);
1974 /* If embed, listen for other events as well */
1976 Window *children, parent, root;
1977 unsigned int children_no;
1979 XSelectInput(r.d, parent_window, FocusChangeMask);
1980 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1982 for (i = 0; i < children_no && children[i] != r.w; ++i)
1983 XSelectInput(r.d, children[i], FocusChangeMask);
1986 grabfocus(r.d, r.w);
1989 take_keyboard(r.d, r.w);
1991 r.x_zero = r.borders[3];
1992 r.y_zero = r.borders[0];
1997 for (i = 0; i < 3; ++i) {
1998 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1999 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2002 for (i = 0; i < 4; ++i) {
2003 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2004 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2005 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2006 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2010 /* Load the colors in our GCs */
2011 for (i = 0; i < 3; ++i) {
2012 XSetForeground(r.d, r.fgs[i], fgs[i]);
2013 XSetForeground(r.d, r.bgs[i], bgs[i]);
2016 for (i = 0; i < 4; ++i) {
2017 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2018 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2019 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2020 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2023 if (load_font(&r, fontname) == -1)
2026 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2028 for (i = 0; i < 3; ++i) {
2030 XRenderColor xrcolor;
2032 c = *(rgba_t *)&fgs[i];
2033 xrcolor.red = EXPANDBITS(c.rgba.r);
2034 xrcolor.green = EXPANDBITS(c.rgba.g);
2035 xrcolor.blue = EXPANDBITS(c.rgba.b);
2036 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2037 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2040 /* compute prompt dimensions */
2046 if (pledge("stdio", "") == -1)
2050 /* Cache text height */
2051 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2053 /* Draw the window for the first time */
2057 while (status == LOOPING || status == OK_LOOP) {
2058 status = loop(&r, &text, &textlen, cs, lines, vlines);
2061 printf("%s\n", text);
2063 if (!r.multiple_select && status == OK_LOOP)
2067 XUngrabKeyboard(r.d, CurrentTime);
2069 for (i = 0; i < 3; ++i)
2070 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2072 for (i = 0; i < 3; ++i) {
2073 XFreeGC(r.d, r.fgs[i]);
2074 XFreeGC(r.d, r.bgs[i]);
2077 for (i = 0; i < 4; ++i) {
2078 XFreeGC(r.d, r.borders_bg[i]);
2079 XFreeGC(r.d, r.p_borders_bg[i]);
2080 XFreeGC(r.d, r.c_borders_bg[i]);
2081 XFreeGC(r.d, r.ch_borders_bg[i]);
2087 for (i = 0; i < 3; ++i)
2088 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2089 XftFontClose(r.d, r.font);
2090 XftDrawDestroy(r.xftdraw);
2100 XFreeColormap(r.d, cmap);
2102 XDestroyWindow(r.d, r.w);
2105 return status != OK;