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` */
466 if (str == NULL || len == 0)
469 if ((dup = strdup(str)) == NULL)
472 for (t = dup; *t; ++t) {
481 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
483 GC *border_color, bg;
484 int *padding, *borders;
485 int ret = 0, inner_width, inner_height, x;
489 border_color = r->p_borders_bg;
490 padding = r->p_padding;
491 borders = r->p_borders;
495 border_color = r->c_borders_bg;
496 padding = r->c_padding;
497 borders = r->c_borders;
501 border_color = r->ch_borders_bg;
502 padding = r->ch_padding;
503 borders = r->ch_borders;
508 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
510 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
511 inner_height = padding[0] + r->text_height + padding[2];
514 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
517 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + INNER_WIDTH(r) - borders[1], y,
521 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
522 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
525 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
528 x = r->x_zero + borders[3];
530 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
533 y += padding[0] + r->text_height;
535 if (prefix != NULL) {
536 draw_string(prefix, strlen(prefix), x, y, r, t);
539 draw_string(text, strlen(text), x, y, r, t);
545 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
547 GC *border_color, bg;
548 int *padding, *borders;
549 int ret = 0, inner_width, inner_height, y, text_width;
553 border_color = r->p_borders_bg;
554 padding = r->p_padding;
555 borders = r->p_borders;
559 border_color = r->c_borders_bg;
560 padding = r->c_padding;
561 borders = r->c_borders;
565 border_color = r->ch_borders_bg;
566 padding = r->ch_padding;
567 borders = r->ch_borders;
572 if (padding[0] < 0 || padding[2] < 0)
573 padding[0] = padding[2]
574 = (INNER_HEIGHT(r) - borders[0] - borders[2] - r->text_height) / 2;
576 /* If they are still lesser than 0, set 'em to 0 */
577 if (padding[0] < 0 || padding[2] < 0)
578 padding[0] = padding[2] = 0;
580 /* Get the text width */
581 text_extents(text, strlen(text), r, &text_width, NULL);
583 text_width += prefix_width;
585 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
587 inner_width = padding[3] + text_width + padding[1];
588 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
591 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
594 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
595 borders[1], INNER_HEIGHT(r));
598 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + INNER_HEIGHT(r) - borders[2],
602 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], INNER_HEIGHT(r));
606 y = r->y_zero + borders[0];
607 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
610 y += padding[0] + r->text_height;
612 if (prefix != NULL) {
613 draw_string(prefix, strlen(prefix), x, y, r, t);
616 draw_string(text, strlen(text), x, y, r, t);
621 /* ,-----------------------------------------------------------------, */
622 /* | 20 char text | completion | completion | completion | compl | */
623 /* `-----------------------------------------------------------------' */
625 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
630 /* Draw the prompt */
631 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
633 for (i = r->offset; i < cs->length; ++i) {
634 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
636 cs->completions[i].offset = x;
638 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
640 if (x > INNER_WIDTH(r))
644 for (i += 1; i < cs->length; ++i)
645 cs->completions[i].offset = -1;
648 /* ,-----------------------------------------------------------------, */
650 /* |-----------------------------------------------------------------| */
652 /* |-----------------------------------------------------------------| */
654 /* `-----------------------------------------------------------------' */
656 draw_vertically(struct rendering *r, char *text, struct completions *cs)
661 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
663 for (i = r->offset; i < cs->length; ++i) {
664 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
666 cs->completions[i].offset = y;
668 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
670 if (y > INNER_HEIGHT(r))
674 for (i += 1; i < cs->length; ++i)
675 cs->completions[i].offset = -1;
679 draw(struct rendering *r, char *text, struct completions *cs)
681 /* Draw the background */
683 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, INNER_WIDTH(r), INNER_HEIGHT(r));
685 /* Draw the contents */
686 if (r->horizontal_layout)
687 draw_horizontally(r, text, cs);
689 draw_vertically(r, text, cs);
691 /* Draw the borders */
692 if (r->borders[0] != 0)
693 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
695 if (r->borders[1] != 0)
696 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
697 r->borders[1], r->height);
699 if (r->borders[2] != 0)
700 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
703 if (r->borders[3] != 0)
704 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
710 /* Set some WM stuff */
712 set_win_atoms_hints(Display *d, Window w, int width, int height)
715 XClassHint *class_hint;
716 XSizeHints *size_hint;
718 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
719 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
720 32, PropModeReplace, (unsigned char *)&type, 1);
722 /* some window managers honor this properties */
723 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
724 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
725 PropModeReplace, (unsigned char *)&type, 1);
727 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
728 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
729 PropModeAppend, (unsigned char *)&type, 1);
731 /* Setting window hints */
732 class_hint = XAllocClassHint();
733 if (class_hint == NULL) {
734 fprintf(stderr, "Could not allocate memory for class hint\n");
735 exit(EX_UNAVAILABLE);
738 class_hint->res_name = RESNAME;
739 class_hint->res_class = RESCLASS;
740 XSetClassHint(d, w, class_hint);
743 size_hint = XAllocSizeHints();
744 if (size_hint == NULL) {
745 fprintf(stderr, "Could not allocate memory for size hint\n");
746 exit(EX_UNAVAILABLE);
749 size_hint->flags = PMinSize | PBaseSize;
750 size_hint->min_width = width;
751 size_hint->base_width = width;
752 size_hint->min_height = height;
753 size_hint->base_height = height;
758 /* Get the width and height of the window `w' */
760 get_wh(Display *d, Window *w, int *width, int *height)
762 XWindowAttributes win_attr;
764 XGetWindowAttributes(d, *w, &win_attr);
765 *height = win_attr.height;
766 *width = win_attr.width;
770 grabfocus(Display *d, Window w)
773 for (i = 0; i < 100; ++i) {
777 XGetInputFocus(d, &focuswin, &revert_to_win);
782 XSetInputFocus(d, w, RevertToParent, CurrentTime);
789 * I know this may seem a little hackish BUT is the only way I managed
790 * to actually grab that goddam keyboard. Only one call to
791 * XGrabKeyboard does not always end up with the keyboard grabbed!
794 take_keyboard(Display *d, Window w)
797 for (i = 0; i < 100; i++) {
798 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
803 fprintf(stderr, "Cannot grab keyboard\n");
808 parse_color(const char *str, const char *def)
819 /* +1 for the # ath the start */
820 if (*str != '#' || len > 9 || len < 4)
822 ++str; /* skip the # */
825 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
832 /* expand #rgb -> #rrggbb */
833 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
834 | (tmp.v & 0x00f) * 0x0011;
836 /* assume 0xff opacity */
839 } /* colors in #aarrggbb need no adjustments */
841 /* premultiply the alpha */
843 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
844 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
845 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
852 fprintf(stderr, "Invalid color: \"%s\".\n", str);
854 return parse_color(def, NULL);
860 * Given a string try to parse it as a number or return `def'.
863 parse_integer(const char *str, int def)
868 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
869 if (errstr != NULL) {
870 warnx("'%s' is %s; using %d as default", str, errstr, def);
877 /* Like parse_integer but recognize the percentages (i.e. strings ending with
880 parse_int_with_percentage(const char *str, int default_value, int max)
882 int len = strlen(str);
884 if (len > 0 && str[len - 1] == '%') {
888 if ((cpy = strdup(str)) == NULL)
892 val = parse_integer(cpy, default_value);
894 return val * max / 100;
897 return parse_integer(str, default_value);
901 get_mouse_coords(Display *d, int *x, int *y)
908 root = DefaultRootWindow(d);
910 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
911 for (i = 0; i < ScreenCount(d); ++i) {
912 if (root == RootWindow(d, i))
919 * Like parse_int_with_percentage but understands some special values:
920 * - middle that is (max-self)/2
923 * - end that is (max-self)
924 * - mx x coordinate of the mouse
925 * - my y coordinate of the mouse
928 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
930 if (!strcmp(str, "start"))
932 if (!strcmp(str, "middle") || !strcmp(str, "center"))
933 return (max - self) / 2;
934 if (!strcmp(str, "end"))
936 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
939 get_mouse_coords(d, &x, &y);
940 if (!strcmp(str, "mx"))
945 return parse_int_with_percentage(str, default_value, max);
948 /* Parse a string like a CSS value. */
949 /* TODO: harden a bit this function */
951 parse_csslike(const char *str)
954 char *s, *token, **ret;
961 ret = malloc(4 * sizeof(char *));
967 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
968 ret[i] = strdup(token);
971 for (j = 1; j < 4; j++)
972 ret[j] = strdup(ret[0]);
975 ret[2] = strdup(ret[0]);
976 ret[3] = strdup(ret[1]);
980 ret[3] = strdup(ret[1]);
982 /* before we didn't check for the return type of strdup, here we will
986 for (i = 0; i < 4; ++i)
987 any_null = ret[i] == NULL || any_null;
990 for (i = 0; i < 4; ++i)
994 if (i == 0 || any_null) {
1004 * Given an event, try to understand what the users wants. If the
1005 * return value is ADD_CHAR then `input' is a pointer to a string that
1006 * will need to be free'ed later.
1009 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1011 char str[SYM_BUF_SIZE] = { 0 };
1014 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1017 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1018 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1020 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1023 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1026 /* Try to read what key was pressed */
1028 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1029 if (s == XBufferOverflow) {
1031 "Buffer overflow when trying to create keyboard "
1036 if (ev->state & ControlMask) {
1037 if (!strcmp(str, "")) /* C-u */
1039 if (!strcmp(str, "")) /* C-w */
1041 if (!strcmp(str, "")) /* C-h */
1043 if (!strcmp(str, "\r")) /* C-m */
1044 return CONFIRM_CONTINUE;
1045 if (!strcmp(str, "")) /* C-p */
1047 if (!strcmp(str, "")) /* C-n */
1049 if (!strcmp(str, "")) /* C-c */
1051 if (!strcmp(str, "\t")) /* C-i */
1052 return TOGGLE_FIRST_SELECTED;
1055 *input = strdup(str);
1056 if (*input == NULL) {
1057 fprintf(stderr, "Error while allocating memory for key.\n");
1065 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1067 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1068 /* if there is something selected expand it and return */
1069 int index = cs->selected == -1 ? 0 : cs->selected;
1070 struct completion *c = cs->completions;
1084 if (*text == NULL) {
1085 fprintf(stderr, "Memory allocation error\n");
1089 *textlen = strlen(*text);
1093 if (!r->free_text) /* cannot accept arbitrary text */
1097 /* cs: completion list
1098 * offset: the offset of the click
1099 * first: the first (rendered) item
1100 * def: the default action
1103 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1105 ssize_t selected = first;
1108 if (cs->length == 0)
1111 if (offset < cs->completions[selected].offset)
1114 /* skip the first entry */
1115 for (selected += 1; selected < cs->length; ++selected) {
1116 if (cs->completions[selected].offset == -1)
1119 if (offset < cs->completions[selected].offset) {
1120 cs->selected = selected - 1;
1127 cs->selected = selected - 1;
1133 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1137 if (r->horizontal_layout)
1142 switch (e->button) {
1144 return select_clicked(cs, off, r->offset, CONFIRM);
1147 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1161 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1164 enum state status = LOOPING;
1166 while (status == LOOPING) {
1168 XNextEvent(r->d, &e);
1170 if (XFilterEvent(&e, r->w))
1175 XRefreshKeyboardMapping(&e.xmapping);
1180 if (e.xfocus.window != r->w)
1181 grabfocus(r->d, r->w);
1184 case VisibilityNotify:
1185 if (e.xvisibility.state != VisibilityUnobscured)
1186 XRaiseWindow(r->d, r->w);
1190 get_wh(r->d, &r->w, &r->width, &r->height);
1199 if (e.type == KeyPress)
1200 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1202 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1214 confirm(&status, r, cs, text, textlen);
1218 case CONFIRM_CONTINUE: {
1220 confirm(&status, r, cs, text, textlen);
1225 complete(cs, r->first_selected, 1, text, textlen, &status);
1226 r->offset = cs->selected;
1231 complete(cs, r->first_selected, 0, text, textlen, &status);
1232 r->offset = cs->selected;
1238 update_completions(cs, *text, lines, vlines, r->first_selected);
1244 update_completions(cs, *text, lines, vlines, r->first_selected);
1250 for (i = 0; i < *textlen; ++i)
1252 update_completions(cs, *text, lines, vlines, r->first_selected);
1260 str_len = strlen(input);
1263 * sometimes a strange key is pressed
1264 * i.e. ctrl alone), so input will be
1265 * empty. Don't need to update
1266 * completion in that case
1271 for (i = 0; i < str_len; ++i) {
1272 *textlen = pushc(text, *textlen, input[i]);
1273 if (*textlen == -1) {
1275 "Memory allocation "
1282 if (status != ERR) {
1284 cs, *text, lines, vlines, r->first_selected);
1292 case TOGGLE_FIRST_SELECTED:
1293 r->first_selected = !r->first_selected;
1294 if (r->first_selected && cs->selected < 0)
1296 if (!r->first_selected && cs->selected == 0)
1301 r->offset = MIN(r->offset + 1, cs->length - 1);
1305 r->offset = MAX((ssize_t)r->offset - 1, 0);
1318 load_font(struct rendering *r, const char *fontname)
1320 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1325 xim_init(struct rendering *r, XrmDatabase *xdb)
1327 XIMStyle best_match_style;
1331 /* Open the X input method */
1332 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1335 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1336 fprintf(stderr, "Input Styles could not be retrieved\n");
1337 exit(EX_UNAVAILABLE);
1340 best_match_style = 0;
1341 for (i = 0; i < xis->count_styles; ++i) {
1342 XIMStyle ts = xis->supported_styles[i];
1343 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1344 best_match_style = ts;
1350 if (!best_match_style)
1351 fprintf(stderr, "No matching input style could be determined\n");
1353 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1354 XNFocusWindow, r->w, NULL);
1356 err(1, "XCreateIC");
1360 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1361 int y, int ox, int oy, unsigned long background_pixel)
1363 XSetWindowAttributes attr;
1365 /* Create the window */
1366 attr.colormap = cmap;
1367 attr.override_redirect = 1;
1368 attr.border_pixel = 0;
1369 attr.background_pixel = background_pixel;
1370 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1371 | ButtonPress | VisibilityChangeMask;
1373 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1374 vinfo.depth, InputOutput, vinfo.visual,
1375 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1379 ps1extents(struct rendering *r)
1382 dup = strdupn(r->ps1);
1383 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1388 usage(char *prgname)
1391 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1392 " [-d separator] [-e window] [-f font] [-G color] [-g "
1394 " [-H height] [-I color] [-i size] [-J color] [-j "
1395 "size] [-l layout]\n"
1396 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1398 " [-t color] [-W width] [-x coord] [-y coord]\n",
1403 main(int argc, char **argv)
1405 struct completions *cs;
1410 Window parent_window;
1412 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1413 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1414 ch_borders_bg[4]; /* N E S W */
1417 int offset_x, offset_y, x, y;
1418 int textlen, d_width, d_height;
1420 char *sep, *parent_window_id;
1421 char **lines, **vlines;
1422 char *fontname, *text, *xrm;
1425 parent_window_id = NULL;
1427 r.first_selected = 0;
1429 r.multiple_select = 0;
1432 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1434 case 'h': /* help */
1437 case 'v': /* version */
1438 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1440 case 'e': /* embed */
1441 if ((parent_window_id = strdup(optarg)) == NULL)
1445 if ((sep = strdup(optarg)) == NULL)
1452 r.multiple_select = 1;
1459 lines = readlines(&nlines);
1465 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1468 for (i = 0; i < nlines; i++) {
1470 t = strstr(lines[i], sep);
1472 vlines[i] = lines[i];
1478 setlocale(LC_ALL, getenv("LANG"));
1482 /* where the monitor start (used only with xinerama) */
1483 offset_x = offset_y = 0;
1485 /* default width and height */
1489 /* default position on the screen */
1492 for (i = 0; i < 4; ++i) {
1493 /* default paddings */
1494 r.p_padding[i] = 10;
1495 r.c_padding[i] = 10;
1496 r.ch_padding[i] = 10;
1498 /* default borders */
1502 r.ch_borders[i] = 0;
1505 /* the prompt. We duplicate the string so later is easy to
1506 * free (in the case it's been overwritten by the user) */
1507 if ((r.ps1 = strdup("$ ")) == NULL)
1510 /* same for the font name */
1511 if ((fontname = strdup(DEFFONT)) == NULL)
1515 if ((text = malloc(textlen * sizeof(char))) == NULL)
1518 /* struct completions *cs = filter(text, lines); */
1519 if ((cs = compls_new(nlines)) == NULL)
1520 err(1, "compls_new");
1522 /* start talking to xorg */
1523 r.d = XOpenDisplay(NULL);
1525 fprintf(stderr, "Could not open display!\n");
1526 return EX_UNAVAILABLE;
1530 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1531 parent_window = DefaultRootWindow(r.d);
1535 /* get display size */
1536 get_wh(r.d, &parent_window, &d_width, &d_height);
1538 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1539 XineramaScreenInfo *info;
1542 int number_of_screens, monitors, i;
1543 int root_x, root_y, win_x, win_y;
1547 number_of_screens = XScreenCount(r.d);
1548 for (i = 0; i < number_of_screens; ++i) {
1549 root = XRootWindow(r.d, i);
1550 res = XQueryPointer(
1551 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1557 fprintf(stderr, "No mouse found.\n");
1562 /* Now find in which monitor the mice is */
1563 info = XineramaQueryScreens(r.d, &monitors);
1565 for (i = 0; i < monitors; ++i) {
1566 if (info[i].x_org <= root_x
1567 && root_x <= (info[i].x_org + info[i].width)
1568 && info[i].y_org <= root_y
1569 && root_y <= (info[i].y_org + info[i].height)) {
1570 offset_x = info[i].x_org;
1571 offset_y = info[i].y_org;
1572 d_width = info[i].width;
1573 d_height = info[i].height;
1581 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1582 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1584 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1585 fgs[2] = parse_color("#000", NULL);
1587 bgs[0] = bgs[1] = parse_color("#000", NULL);
1588 bgs[2] = parse_color("#fff", NULL);
1590 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1592 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1593 = parse_color("#000", NULL);
1594 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1595 = parse_color("#000", NULL);
1596 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1597 = parse_color("#000", NULL);
1599 r.horizontal_layout = 1;
1601 /* Read the resources */
1603 xrm = XResourceManagerString(r.d);
1609 xdb = XrmGetStringDatabase(xrm);
1611 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1613 if ((fontname = strdup(value.addr)) == NULL)
1616 fprintf(stderr, "no font defined, using %s\n", fontname);
1619 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1620 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1622 fprintf(stderr, "no layout defined, using horizontal\n");
1624 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1626 r.ps1 = normalize_str(value.addr);
1629 "no prompt defined, using \"%s\" as "
1634 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1636 sizes = parse_csslike(value.addr);
1638 for (i = 0; i < 4; ++i)
1639 r.p_borders[i] = parse_integer(sizes[i], 0);
1642 "error while parsing "
1643 "MyMenu.prompt.border.size");
1646 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1648 colors = parse_csslike(value.addr);
1650 for (i = 0; i < 4; ++i)
1651 p_borders_bg[i] = parse_color(colors[i], "#000");
1654 "error while parsing "
1655 "MyMenu.prompt.border.color");
1658 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1660 colors = parse_csslike(value.addr);
1662 for (i = 0; i < 4; ++i)
1663 r.p_padding[i] = parse_integer(colors[i], 0);
1666 "error while parsing "
1667 "MyMenu.prompt.padding");
1670 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1671 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1673 fprintf(stderr, "no width defined, using %d\n", r.width);
1675 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1676 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1678 fprintf(stderr, "no height defined, using %d\n", r.height);
1680 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1681 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1683 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1684 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1686 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1688 borders = parse_csslike(value.addr);
1689 if (borders != NULL)
1690 for (i = 0; i < 4; ++i)
1691 r.borders[i] = parse_int_with_percentage(
1692 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1695 "error while parsing "
1696 "MyMenu.border.size\n");
1700 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1701 fgs[0] = parse_color(value.addr, "#fff");
1703 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1704 bgs[0] = parse_color(value.addr, "#000");
1707 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1708 fgs[1] = parse_color(value.addr, "#fff");
1710 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1711 bgs[1] = parse_color(value.addr, "#000");
1713 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1715 paddings = parse_csslike(value.addr);
1716 if (paddings != NULL)
1717 for (i = 0; i < 4; ++i)
1718 r.c_padding[i] = parse_integer(paddings[i], 0);
1721 "Error while parsing "
1722 "MyMenu.completion.padding");
1725 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1727 sizes = parse_csslike(value.addr);
1729 for (i = 0; i < 4; ++i)
1730 r.c_borders[i] = parse_integer(sizes[i], 0);
1733 "Error while parsing "
1734 "MyMenu.completion.border.size");
1737 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1739 sizes = parse_csslike(value.addr);
1741 for (i = 0; i < 4; ++i)
1742 c_borders_bg[i] = parse_color(sizes[i], "#000");
1745 "Error while parsing "
1746 "MyMenu.completion.border.color");
1749 /* Completion Highlighted */
1751 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1752 fgs[2] = parse_color(value.addr, "#000");
1755 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1756 bgs[2] = parse_color(value.addr, "#fff");
1759 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1761 paddings = parse_csslike(value.addr);
1762 if (paddings != NULL)
1763 for (i = 0; i < 4; ++i)
1764 r.ch_padding[i] = parse_integer(paddings[i], 0);
1767 "Error while parsing "
1768 "MyMenu.completion_highlighted."
1772 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1775 sizes = parse_csslike(value.addr);
1777 for (i = 0; i < 4; ++i)
1778 r.ch_borders[i] = parse_integer(sizes[i], 0);
1781 "Error while parsing "
1782 "MyMenu.completion_highlighted."
1786 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1789 colors = parse_csslike(value.addr);
1791 for (i = 0; i < 4; ++i)
1792 ch_borders_bg[i] = parse_color(colors[i], "#000");
1795 "Error while parsing "
1796 "MyMenu.completion_highlighted."
1801 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1803 colors = parse_csslike(value.addr);
1805 for (i = 0; i < 4; ++i)
1806 borders_bg[i] = parse_color(colors[i], "#000");
1809 "error while parsing "
1810 "MyMenu.border.color\n");
1814 /* Second round of args parsing */
1815 optind = 0; /* reset the option index */
1816 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1819 r.first_selected = 1;
1822 /* free_text -- already catched */
1824 /* separator -- this case was already catched */
1826 /* embedding mymenu this case was already catched. */
1828 /* multiple selection this case was already catched.
1833 newprompt = strdup(optarg);
1834 if (newprompt != NULL) {
1841 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1844 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1848 if ((paddings = parse_csslike(optarg)) != NULL)
1849 for (i = 0; i < 4; ++i)
1850 r.p_padding[i] = parse_integer(paddings[i], 0);
1855 if ((colors = parse_csslike(optarg)) != NULL)
1856 for (i = 0; i < 4; ++i)
1857 p_borders_bg[i] = parse_color(colors[i], "#000");
1862 if ((sizes = parse_csslike(optarg)) != NULL)
1863 for (i = 0; i < 4; ++i)
1864 r.p_borders[i] = parse_integer(sizes[i], 0);
1869 if ((colors = parse_csslike(optarg)) != NULL)
1870 for (i = 0; i < 4; ++i)
1871 c_borders_bg[i] = parse_color(colors[i], "#000");
1876 if ((sizes = parse_csslike(optarg)) != NULL)
1877 for (i = 0; i < 4; ++i)
1878 r.c_borders[i] = parse_integer(sizes[i], 0);
1883 if ((colors = parse_csslike(optarg)) != NULL)
1884 for (i = 0; i < 4; ++i)
1885 ch_borders_bg[i] = parse_color(colors[i], "#000");
1890 if ((sizes = parse_csslike(optarg)) != NULL)
1891 for (i = 0; i < 4; ++i)
1892 r.ch_borders[i] = parse_integer(sizes[i], 0);
1896 r.horizontal_layout = !strcmp(optarg, "horizontal");
1900 if ((newfont = strdup(optarg)) != NULL) {
1907 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1910 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1914 if ((borders = parse_csslike(optarg)) != NULL) {
1915 for (i = 0; i < 4; ++i)
1916 r.borders[i] = parse_integer(borders[i], 0);
1918 fprintf(stderr, "Error parsing b option\n");
1923 if ((colors = parse_csslike(optarg)) != NULL) {
1924 for (i = 0; i < 4; ++i)
1925 borders_bg[i] = parse_color(colors[i], "#000");
1927 fprintf(stderr, "error while parsing B option\n");
1931 fgs[0] = parse_color(optarg, NULL);
1934 bgs[0] = parse_color(optarg, NULL);
1937 fgs[1] = parse_color(optarg, NULL);
1940 bgs[1] = parse_color(optarg, NULL);
1943 fgs[2] = parse_color(optarg, NULL);
1946 bgs[2] = parse_color(optarg, NULL);
1949 fprintf(stderr, "Unrecognized option %c\n", ch);
1955 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1956 fprintf(stderr, "height, width, x or y are lesser than 0.");
1960 /* since only now we know if the first should be selected,
1961 * update the completion here */
1962 update_completions(cs, text, lines, vlines, r.first_selected);
1964 /* update the prompt lenght, only now we surely know the length of it
1966 r.ps1len = strlen(r.ps1);
1968 /* Create the window */
1969 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1970 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1971 XMapRaised(r.d, r.w);
1973 /* If embed, listen for other events as well */
1975 Window *children, parent, root;
1976 unsigned int children_no;
1978 XSelectInput(r.d, parent_window, FocusChangeMask);
1979 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1981 for (i = 0; i < children_no && children[i] != r.w; ++i)
1982 XSelectInput(r.d, children[i], FocusChangeMask);
1985 grabfocus(r.d, r.w);
1988 take_keyboard(r.d, r.w);
1990 r.x_zero = r.borders[3];
1991 r.y_zero = r.borders[0];
1996 for (i = 0; i < 3; ++i) {
1997 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1998 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2001 for (i = 0; i < 4; ++i) {
2002 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2003 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2004 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2005 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2009 /* Load the colors in our GCs */
2010 for (i = 0; i < 3; ++i) {
2011 XSetForeground(r.d, r.fgs[i], fgs[i]);
2012 XSetForeground(r.d, r.bgs[i], bgs[i]);
2015 for (i = 0; i < 4; ++i) {
2016 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2017 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2018 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2019 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2022 if (load_font(&r, fontname) == -1)
2025 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2027 for (i = 0; i < 3; ++i) {
2029 XRenderColor xrcolor;
2031 c = *(rgba_t *)&fgs[i];
2032 xrcolor.red = EXPANDBITS(c.rgba.r);
2033 xrcolor.green = EXPANDBITS(c.rgba.g);
2034 xrcolor.blue = EXPANDBITS(c.rgba.b);
2035 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2036 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2039 /* compute prompt dimensions */
2045 if (pledge("stdio", "") == -1)
2049 /* Cache text height */
2050 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2052 /* Draw the window for the first time */
2056 while (status == LOOPING || status == OK_LOOP) {
2057 status = loop(&r, &text, &textlen, cs, lines, vlines);
2060 printf("%s\n", text);
2062 if (!r.multiple_select && status == OK_LOOP)
2066 XUngrabKeyboard(r.d, CurrentTime);
2068 for (i = 0; i < 3; ++i)
2069 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2071 for (i = 0; i < 3; ++i) {
2072 XFreeGC(r.d, r.fgs[i]);
2073 XFreeGC(r.d, r.bgs[i]);
2076 for (i = 0; i < 4; ++i) {
2077 XFreeGC(r.d, r.borders_bg[i]);
2078 XFreeGC(r.d, r.p_borders_bg[i]);
2079 XFreeGC(r.d, r.c_borders_bg[i]);
2080 XFreeGC(r.d, r.ch_borders_bg[i]);
2086 for (i = 0; i < 3; ++i)
2087 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2088 XftFontClose(r.d, r.font);
2089 XftDrawDestroy(r.xftdraw);
2099 XFreeColormap(r.d, cmap);
2101 XDestroyWindow(r.d, r.w);
2104 return status != OK;