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>
23 #define VERSION "unknown"
26 #define resname "MyMenu"
27 #define resclass "mymenu"
29 #define SYM_BUF_SIZE 4
31 #define default_fontname "monospace"
33 #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:"
35 #define MIN(a, b) ((a) < (b) ? (a) : (b))
36 #define MAX(a, b) ((a) > (b) ? (a) : (b))
38 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
40 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
41 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
43 /* The states of the event loop */
44 enum state { LOOPING, OK_LOOP, OK, ERR };
47 * For the drawing-related function. The text to be rendere could be
48 * the prompt, a completion or a highlighted completion
50 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
52 /* These are the possible action to be performed after user input. */
64 TOGGLE_FIRST_SELECTED,
69 /* A big set of values that needs to be carried around for drawing. A
70 * big struct to rule them all */
72 Display *d; /* Connection to xorg */
80 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
82 int y_zero; /* like x_zero but for the y axis */
84 int offset; /* scroll offset */
88 short multiple_select;
90 /* four border width */
96 short horizontal_layout;
101 int ps1w; /* ps1 width */
102 int ps1h; /* ps1 height */
104 int text_height; /* cache for the vertical layout */
117 XftColor xft_colors[3];
123 int offset; /* the x (or y, depending on the layout) coordinate at
124 which the item is rendered */
127 /* Wrap the linked list of completions */
129 struct completion *completions;
134 /* idea stolen from lemonbar. ty lemonboy */
148 /* Return a newly allocated (and empty) completion list */
150 compls_new(size_t length)
152 struct completions *cs = malloc(sizeof(struct completions));
157 cs->completions = calloc(length, sizeof(struct completion));
158 if (cs->completions == NULL) {
168 /* Delete the wrapper and the whole list */
170 compls_delete(struct completions *cs)
175 free(cs->completions);
180 * Create a completion list from a text and the list of possible
181 * completions (null terminated). Expects a non-null `cs'. `lines' and
182 * `vlines' should have the same length OR `vlines' is NULL.
185 filter(struct completions *cs, char *text, char **lines, char **vlines)
195 if (lines[index] == NULL)
198 l = vlines[index] != NULL ? vlines[index] : lines[index];
200 if (strcasestr(l, text) != NULL) {
201 struct completion *c = &cs->completions[matching];
203 c->rcompletion = lines[index];
209 cs->length = matching;
213 /* Update the given completion */
216 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
218 filter(cs, text, lines, vlines);
219 if (first_selected && cs->length > 0)
224 * Select the next or previous selection and update some state. `text'
225 * will be updated with the text of the completion and `textlen' with
226 * the new length. If the memory cannot be allocated `status' will be
230 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
233 struct completion *n;
236 if (cs == NULL || cs->length == 0)
240 * If the first is always selected and the first entry is
241 * different from the text, expand the text and return
243 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
246 *text = strdup(cs->completions->completion);
251 *textlen = strlen(*text);
255 index = cs->selected;
257 if (index == -1 && p)
259 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
261 n = &cs->completions[cs->selected];
264 *text = strdup(n->completion);
266 fprintf(stderr, "Memory allocation error!\n");
270 *textlen = strlen(*text);
273 /* Push the character c at the end of the string pointed by p */
275 pushc(char **p, int maxlen, char c)
279 len = strnlen(*p, maxlen);
280 if (!(len < maxlen - 2)) {
283 maxlen += maxlen >> 1;
284 newptr = realloc(*p, maxlen);
285 if (newptr == NULL) /* bad */
291 (*p)[len + 1] = '\0';
296 * Remove the last rune from the *UTF-8* string! This is different
297 * from just setting the last byte to 0 (in some cases ofc). Return a
298 * pointer (e) to the last nonzero char. If e < p then p is empty!
318 * If c is a starting byte (11......) or is under
321 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
328 /* Remove the last word plus trailing white spaces from the given string */
335 if ((len = strlen(w)) == 0)
344 if (in_word && isspace(*e))
347 if (!in_word && !isspace(*e))
353 * If the string is surrounded by quates (`"') remove them and replace
354 * every `\"' in the string with a single double-quote.
357 normalize_str(const char *str)
362 if ((len = strlen(str)) == 0)
365 if ((s = calloc(len, sizeof(char))) == NULL)
376 str += 2; /* skip this and the next char */
382 str++; /* skip only this char */
394 readlines(size_t *lineslen)
396 size_t len = 0, cap = 0;
399 char *line = NULL, **lines = NULL;
401 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
402 if (linelen != 0 && line[linelen-1] == '\n')
403 line[linelen-1] = '\0';
409 newcap = MAX(cap * 1.5, 32);
410 t = recallocarray(lines, cap, newcap, sizeof(char *));
412 err(1, "recallocarray");
417 if ((lines[len++] = strdup(line)) == NULL)
430 * Compute the dimensions of the string str once rendered.
431 * It'll return the width and set ret_width and ret_height if not NULL
434 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
438 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
439 height = r->font->ascent - r->font->descent;
440 width = gi.width - gi.x;
442 if (ret_width != NULL)
444 if (ret_height != NULL)
445 *ret_height = height;
450 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
454 xftcolor = r->xft_colors[0];
456 xftcolor = r->xft_colors[1];
457 if (tt == COMPL_HIGH)
458 xftcolor = r->xft_colors[2];
460 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
463 /* Duplicate the string and substitute every space with a 'n` */
472 if (str == NULL || len == 0)
475 if ((dup = strdup(str)) == NULL)
478 for (i = 0; i < len; ++i)
486 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
488 GC *border_color, bg;
489 int *padding, *borders;
490 int ret = 0, inner_width, inner_height, x;
494 border_color = r->p_borders_bg;
495 padding = r->p_padding;
496 borders = r->p_borders;
500 border_color = r->c_borders_bg;
501 padding = r->c_padding;
502 borders = r->c_borders;
506 border_color = r->ch_borders_bg;
507 padding = r->ch_padding;
508 borders = r->ch_borders;
513 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
515 inner_width = inner_width(r) - borders[1] - borders[3];
516 inner_height = padding[0] + r->text_height + padding[2];
519 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
522 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1], y,
526 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
527 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
530 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
533 x = r->x_zero + borders[3];
535 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
538 y += padding[0] + r->text_height;
540 if (prefix != NULL) {
541 draw_string(prefix, strlen(prefix), x, y, r, t);
544 draw_string(text, strlen(text), x, y, r, t);
550 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
552 GC *border_color, bg;
553 int *padding, *borders;
554 int ret = 0, inner_width, inner_height, y, text_width;
558 border_color = r->p_borders_bg;
559 padding = r->p_padding;
560 borders = r->p_borders;
564 border_color = r->c_borders_bg;
565 padding = r->c_padding;
566 borders = r->c_borders;
570 border_color = r->ch_borders_bg;
571 padding = r->ch_padding;
572 borders = r->ch_borders;
577 if (padding[0] < 0 || padding[2] < 0)
578 padding[0] = padding[2]
579 = (inner_height(r) - borders[0] - borders[2] - r->text_height) / 2;
581 /* If they are still lesser than 0, set 'em to 0 */
582 if (padding[0] < 0 || padding[2] < 0)
583 padding[0] = padding[2] = 0;
585 /* Get the text width */
586 text_extents(text, strlen(text), r, &text_width, NULL);
588 text_width += prefix_width;
590 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
592 inner_width = padding[3] + text_width + padding[1];
593 inner_height = inner_height(r) - borders[0] - borders[2];
596 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
599 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
600 borders[1], inner_height(r));
603 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2],
607 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
611 y = r->y_zero + borders[0];
612 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
615 y += padding[0] + r->text_height;
617 if (prefix != NULL) {
618 draw_string(prefix, strlen(prefix), x, y, r, t);
621 draw_string(text, strlen(text), x, y, r, t);
626 /* ,-----------------------------------------------------------------, */
627 /* | 20 char text | completion | completion | completion | compl | */
628 /* `-----------------------------------------------------------------' */
630 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
635 /* Draw the prompt */
636 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
638 for (i = r->offset; i < cs->length; ++i) {
639 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
641 cs->completions[i].offset = x;
643 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
645 if (x > inner_width(r))
649 for (i += 1; i < cs->length; ++i)
650 cs->completions[i].offset = -1;
653 /* ,-----------------------------------------------------------------, */
655 /* |-----------------------------------------------------------------| */
657 /* |-----------------------------------------------------------------| */
659 /* `-----------------------------------------------------------------' */
661 draw_vertically(struct rendering *r, char *text, struct completions *cs)
666 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
668 for (i = r->offset; i < cs->length; ++i) {
669 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
671 cs->completions[i].offset = y;
673 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
675 if (y > inner_height(r))
679 for (i += 1; i < cs->length; ++i)
680 cs->completions[i].offset = -1;
684 draw(struct rendering *r, char *text, struct completions *cs)
686 /* Draw the background */
688 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
690 /* Draw the contents */
691 if (r->horizontal_layout)
692 draw_horizontally(r, text, cs);
694 draw_vertically(r, text, cs);
696 /* Draw the borders */
697 if (r->borders[0] != 0)
698 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
700 if (r->borders[1] != 0)
701 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
702 r->borders[1], r->height);
704 if (r->borders[2] != 0)
705 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
708 if (r->borders[3] != 0)
709 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
715 /* Set some WM stuff */
717 set_win_atoms_hints(Display *d, Window w, int width, int height)
720 XClassHint *class_hint;
721 XSizeHints *size_hint;
723 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
724 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
725 32, PropModeReplace, (unsigned char *)&type, 1);
727 /* some window managers honor this properties */
728 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
729 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
730 PropModeReplace, (unsigned char *)&type, 1);
732 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
733 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
734 PropModeAppend, (unsigned char *)&type, 1);
736 /* Setting window hints */
737 class_hint = XAllocClassHint();
738 if (class_hint == NULL) {
739 fprintf(stderr, "Could not allocate memory for class hint\n");
740 exit(EX_UNAVAILABLE);
743 class_hint->res_name = resname;
744 class_hint->res_class = resclass;
745 XSetClassHint(d, w, class_hint);
748 size_hint = XAllocSizeHints();
749 if (size_hint == NULL) {
750 fprintf(stderr, "Could not allocate memory for size hint\n");
751 exit(EX_UNAVAILABLE);
754 size_hint->flags = PMinSize | PBaseSize;
755 size_hint->min_width = width;
756 size_hint->base_width = width;
757 size_hint->min_height = height;
758 size_hint->base_height = height;
763 /* Get the width and height of the window `w' */
765 get_wh(Display *d, Window *w, int *width, int *height)
767 XWindowAttributes win_attr;
769 XGetWindowAttributes(d, *w, &win_attr);
770 *height = win_attr.height;
771 *width = win_attr.width;
775 grabfocus(Display *d, Window w)
778 for (i = 0; i < 100; ++i) {
782 XGetInputFocus(d, &focuswin, &revert_to_win);
787 XSetInputFocus(d, w, RevertToParent, CurrentTime);
794 * I know this may seem a little hackish BUT is the only way I managed
795 * to actually grab that goddam keyboard. Only one call to
796 * XGrabKeyboard does not always end up with the keyboard grabbed!
799 take_keyboard(Display *d, Window w)
802 for (i = 0; i < 100; i++) {
803 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
808 fprintf(stderr, "Cannot grab keyboard\n");
813 parse_color(const char *str, const char *def)
824 /* +1 for the # ath the start */
825 if (*str != '#' || len > 9 || len < 4)
827 ++str; /* skip the # */
830 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
837 /* expand #rgb -> #rrggbb */
838 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
839 | (tmp.v & 0x00f) * 0x0011;
841 /* assume 0xff opacity */
844 } /* colors in #aarrggbb need no adjustments */
846 /* premultiply the alpha */
848 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
849 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
850 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
857 fprintf(stderr, "Invalid color: \"%s\".\n", str);
859 return parse_color(def, NULL);
865 * Given a string try to parse it as a number or return `def'.
868 parse_integer(const char *str, int def)
873 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
874 if (errstr != NULL) {
875 warnx("'%s' is %s; using %d as default", str, errstr, def);
882 /* Like parse_integer but recognize the percentages (i.e. strings ending with
885 parse_int_with_percentage(const char *str, int default_value, int max)
887 int len = strlen(str);
889 if (len > 0 && str[len - 1] == '%') {
893 if ((cpy = strdup(str)) == NULL)
897 val = parse_integer(cpy, default_value);
899 return val * max / 100;
902 return parse_integer(str, default_value);
906 get_mouse_coords(Display *d, int *x, int *y)
913 root = DefaultRootWindow(d);
915 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
916 for (i = 0; i < ScreenCount(d); ++i) {
917 if (root == RootWindow(d, i))
924 * Like parse_int_with_percentage but understands some special values:
925 * - middle that is (max-self)/2
928 * - end that is (max-self)
929 * - mx x coordinate of the mouse
930 * - my y coordinate of the mouse
933 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
935 if (!strcmp(str, "start"))
937 if (!strcmp(str, "middle") || !strcmp(str, "center"))
938 return (max - self) / 2;
939 if (!strcmp(str, "end"))
941 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
944 get_mouse_coords(d, &x, &y);
945 if (!strcmp(str, "mx"))
950 return parse_int_with_percentage(str, default_value, max);
953 /* Parse a string like a CSS value. */
954 /* TODO: harden a bit this function */
956 parse_csslike(const char *str)
959 char *s, *token, **ret;
966 ret = malloc(4 * sizeof(char *));
972 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
973 ret[i] = strdup(token);
976 for (j = 1; j < 4; j++)
977 ret[j] = strdup(ret[0]);
980 ret[2] = strdup(ret[0]);
981 ret[3] = strdup(ret[1]);
985 ret[3] = strdup(ret[1]);
987 /* before we didn't check for the return type of strdup, here we will
991 for (i = 0; i < 4; ++i)
992 any_null = ret[i] == NULL || any_null;
995 for (i = 0; i < 4; ++i)
999 if (i == 0 || any_null) {
1009 * Given an event, try to understand what the users wants. If the
1010 * return value is ADD_CHAR then `input' is a pointer to a string that
1011 * will need to be free'ed later.
1014 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1016 char str[SYM_BUF_SIZE] = { 0 };
1019 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1022 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1023 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1025 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1028 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1031 /* Try to read what key was pressed */
1033 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1034 if (s == XBufferOverflow) {
1036 "Buffer overflow when trying to create keyboard "
1041 if (ev->state & ControlMask) {
1042 if (!strcmp(str, "")) /* C-u */
1044 if (!strcmp(str, "")) /* C-w */
1046 if (!strcmp(str, "")) /* C-h */
1048 if (!strcmp(str, "\r")) /* C-m */
1049 return CONFIRM_CONTINUE;
1050 if (!strcmp(str, "")) /* C-p */
1052 if (!strcmp(str, "")) /* C-n */
1054 if (!strcmp(str, "")) /* C-c */
1056 if (!strcmp(str, "\t")) /* C-i */
1057 return TOGGLE_FIRST_SELECTED;
1060 *input = strdup(str);
1061 if (*input == NULL) {
1062 fprintf(stderr, "Error while allocating memory for key.\n");
1070 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1072 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1073 /* if there is something selected expand it and return */
1074 int index = cs->selected == -1 ? 0 : cs->selected;
1075 struct completion *c = cs->completions;
1089 if (*text == NULL) {
1090 fprintf(stderr, "Memory allocation error\n");
1094 *textlen = strlen(*text);
1098 if (!r->free_text) /* cannot accept arbitrary text */
1102 /* cs: completion list
1103 * offset: the offset of the click
1104 * first: the first (rendered) item
1105 * def: the default action
1108 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1110 ssize_t selected = first;
1113 if (cs->length == 0)
1116 if (offset < cs->completions[selected].offset)
1119 /* skip the first entry */
1120 for (selected += 1; selected < cs->length; ++selected) {
1121 if (cs->completions[selected].offset == -1)
1124 if (offset < cs->completions[selected].offset) {
1125 cs->selected = selected - 1;
1132 cs->selected = selected - 1;
1138 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1142 if (r->horizontal_layout)
1147 switch (e->button) {
1149 return select_clicked(cs, off, r->offset, CONFIRM);
1152 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1166 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1169 enum state status = LOOPING;
1171 while (status == LOOPING) {
1173 XNextEvent(r->d, &e);
1175 if (XFilterEvent(&e, r->w))
1180 XRefreshKeyboardMapping(&e.xmapping);
1185 if (e.xfocus.window != r->w)
1186 grabfocus(r->d, r->w);
1189 case VisibilityNotify:
1190 if (e.xvisibility.state != VisibilityUnobscured)
1191 XRaiseWindow(r->d, r->w);
1195 get_wh(r->d, &r->w, &r->width, &r->height);
1204 if (e.type == KeyPress)
1205 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1207 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1219 confirm(&status, r, cs, text, textlen);
1223 case CONFIRM_CONTINUE: {
1225 confirm(&status, r, cs, text, textlen);
1230 complete(cs, r->first_selected, 1, text, textlen, &status);
1231 r->offset = cs->selected;
1236 complete(cs, r->first_selected, 0, text, textlen, &status);
1237 r->offset = cs->selected;
1243 update_completions(cs, *text, lines, vlines, r->first_selected);
1249 update_completions(cs, *text, lines, vlines, r->first_selected);
1255 for (i = 0; i < *textlen; ++i)
1257 update_completions(cs, *text, lines, vlines, r->first_selected);
1265 str_len = strlen(input);
1268 * sometimes a strange key is pressed
1269 * i.e. ctrl alone), so input will be
1270 * empty. Don't need to update
1271 * completion in that case
1276 for (i = 0; i < str_len; ++i) {
1277 *textlen = pushc(text, *textlen, input[i]);
1278 if (*textlen == -1) {
1280 "Memory allocation "
1287 if (status != ERR) {
1289 cs, *text, lines, vlines, r->first_selected);
1297 case TOGGLE_FIRST_SELECTED:
1298 r->first_selected = !r->first_selected;
1299 if (r->first_selected && cs->selected < 0)
1301 if (!r->first_selected && cs->selected == 0)
1306 r->offset = MIN(r->offset + 1, cs->length - 1);
1310 r->offset = MAX((ssize_t)r->offset - 1, 0);
1323 load_font(struct rendering *r, const char *fontname)
1325 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1330 xim_init(struct rendering *r, XrmDatabase *xdb)
1332 XIMStyle best_match_style;
1336 /* Open the X input method */
1337 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1340 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1341 fprintf(stderr, "Input Styles could not be retrieved\n");
1342 exit(EX_UNAVAILABLE);
1345 best_match_style = 0;
1346 for (i = 0; i < xis->count_styles; ++i) {
1347 XIMStyle ts = xis->supported_styles[i];
1348 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1349 best_match_style = ts;
1355 if (!best_match_style)
1356 fprintf(stderr, "No matching input style could be determined\n");
1358 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1359 XNFocusWindow, r->w, NULL);
1361 err(1, "XCreateIC");
1365 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1366 int y, int ox, int oy, unsigned long background_pixel)
1368 XSetWindowAttributes attr;
1370 /* Create the window */
1371 attr.colormap = cmap;
1372 attr.override_redirect = 1;
1373 attr.border_pixel = 0;
1374 attr.background_pixel = background_pixel;
1375 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1376 | ButtonPress | VisibilityChangeMask;
1378 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1379 vinfo.depth, InputOutput, vinfo.visual,
1380 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1384 ps1extents(struct rendering *r)
1387 dup = strdupn(r->ps1);
1388 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1393 usage(char *prgname)
1396 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1397 " [-d separator] [-e window] [-f font] [-G color] [-g "
1399 " [-H height] [-I color] [-i size] [-J color] [-j "
1400 "size] [-l layout]\n"
1401 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1403 " [-t color] [-W width] [-x coord] [-y coord]\n",
1408 main(int argc, char **argv)
1410 struct completions *cs;
1415 Window parent_window;
1417 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1418 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1419 ch_borders_bg[4]; /* N E S W */
1422 int offset_x, offset_y, x, y;
1423 int textlen, d_width, d_height;
1425 char *sep, *parent_window_id;
1426 char **lines, **vlines;
1427 char *fontname, *text, *xrm;
1430 parent_window_id = NULL;
1432 r.first_selected = 0;
1434 r.multiple_select = 0;
1437 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1439 case 'h': /* help */
1442 case 'v': /* version */
1443 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1445 case 'e': /* embed */
1446 if ((parent_window_id = strdup(optarg)) == NULL)
1450 if ((sep = strdup(optarg)) == NULL)
1457 r.multiple_select = 1;
1464 lines = readlines(&nlines);
1470 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1473 for (i = 0; i < nlines; i++) {
1475 t = strstr(lines[i], sep);
1477 vlines[i] = lines[i];
1483 setlocale(LC_ALL, getenv("LANG"));
1487 /* where the monitor start (used only with xinerama) */
1488 offset_x = offset_y = 0;
1490 /* default width and height */
1494 /* default position on the screen */
1497 for (i = 0; i < 4; ++i) {
1498 /* default paddings */
1499 r.p_padding[i] = 10;
1500 r.c_padding[i] = 10;
1501 r.ch_padding[i] = 10;
1503 /* default borders */
1507 r.ch_borders[i] = 0;
1510 /* the prompt. We duplicate the string so later is easy to
1511 * free (in the case it's been overwritten by the user) */
1512 if ((r.ps1 = strdup("$ ")) == NULL)
1515 /* same for the font name */
1516 if ((fontname = strdup(default_fontname)) == NULL)
1520 if ((text = malloc(textlen * sizeof(char))) == NULL)
1523 /* struct completions *cs = filter(text, lines); */
1524 if ((cs = compls_new(nlines)) == NULL)
1525 err(1, "compls_new");
1527 /* start talking to xorg */
1528 r.d = XOpenDisplay(NULL);
1530 fprintf(stderr, "Could not open display!\n");
1531 return EX_UNAVAILABLE;
1535 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1536 parent_window = DefaultRootWindow(r.d);
1540 /* get display size */
1541 get_wh(r.d, &parent_window, &d_width, &d_height);
1543 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1544 XineramaScreenInfo *info;
1547 int number_of_screens, monitors, i;
1548 int root_x, root_y, win_x, win_y;
1552 number_of_screens = XScreenCount(r.d);
1553 for (i = 0; i < number_of_screens; ++i) {
1554 root = XRootWindow(r.d, i);
1555 res = XQueryPointer(
1556 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1562 fprintf(stderr, "No mouse found.\n");
1567 /* Now find in which monitor the mice is */
1568 info = XineramaQueryScreens(r.d, &monitors);
1570 for (i = 0; i < monitors; ++i) {
1571 if (info[i].x_org <= root_x
1572 && root_x <= (info[i].x_org + info[i].width)
1573 && info[i].y_org <= root_y
1574 && root_y <= (info[i].y_org + info[i].height)) {
1575 offset_x = info[i].x_org;
1576 offset_y = info[i].y_org;
1577 d_width = info[i].width;
1578 d_height = info[i].height;
1586 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1587 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1589 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1590 fgs[2] = parse_color("#000", NULL);
1592 bgs[0] = bgs[1] = parse_color("#000", NULL);
1593 bgs[2] = parse_color("#fff", NULL);
1595 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1597 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1598 = parse_color("#000", NULL);
1599 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1600 = parse_color("#000", NULL);
1601 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1602 = parse_color("#000", NULL);
1604 r.horizontal_layout = 1;
1606 /* Read the resources */
1608 xrm = XResourceManagerString(r.d);
1614 xdb = XrmGetStringDatabase(xrm);
1616 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1618 if ((fontname = strdup(value.addr)) == NULL)
1621 fprintf(stderr, "no font defined, using %s\n", fontname);
1624 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1625 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1627 fprintf(stderr, "no layout defined, using horizontal\n");
1629 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1631 r.ps1 = normalize_str(value.addr);
1634 "no prompt defined, using \"%s\" as "
1639 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1641 sizes = parse_csslike(value.addr);
1643 for (i = 0; i < 4; ++i)
1644 r.p_borders[i] = parse_integer(sizes[i], 0);
1647 "error while parsing "
1648 "MyMenu.prompt.border.size");
1651 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1653 colors = parse_csslike(value.addr);
1655 for (i = 0; i < 4; ++i)
1656 p_borders_bg[i] = parse_color(colors[i], "#000");
1659 "error while parsing "
1660 "MyMenu.prompt.border.color");
1663 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1665 colors = parse_csslike(value.addr);
1667 for (i = 0; i < 4; ++i)
1668 r.p_padding[i] = parse_integer(colors[i], 0);
1671 "error while parsing "
1672 "MyMenu.prompt.padding");
1675 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1676 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1678 fprintf(stderr, "no width defined, using %d\n", r.width);
1680 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1681 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1683 fprintf(stderr, "no height defined, using %d\n", r.height);
1685 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1686 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1688 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1689 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1691 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1693 borders = parse_csslike(value.addr);
1694 if (borders != NULL)
1695 for (i = 0; i < 4; ++i)
1696 r.borders[i] = parse_int_with_percentage(
1697 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1700 "error while parsing "
1701 "MyMenu.border.size\n");
1705 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1706 fgs[0] = parse_color(value.addr, "#fff");
1708 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1709 bgs[0] = parse_color(value.addr, "#000");
1712 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1713 fgs[1] = parse_color(value.addr, "#fff");
1715 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1716 bgs[1] = parse_color(value.addr, "#000");
1718 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1720 paddings = parse_csslike(value.addr);
1721 if (paddings != NULL)
1722 for (i = 0; i < 4; ++i)
1723 r.c_padding[i] = parse_integer(paddings[i], 0);
1726 "Error while parsing "
1727 "MyMenu.completion.padding");
1730 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1732 sizes = parse_csslike(value.addr);
1734 for (i = 0; i < 4; ++i)
1735 r.c_borders[i] = parse_integer(sizes[i], 0);
1738 "Error while parsing "
1739 "MyMenu.completion.border.size");
1742 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1744 sizes = parse_csslike(value.addr);
1746 for (i = 0; i < 4; ++i)
1747 c_borders_bg[i] = parse_color(sizes[i], "#000");
1750 "Error while parsing "
1751 "MyMenu.completion.border.color");
1754 /* Completion Highlighted */
1756 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1757 fgs[2] = parse_color(value.addr, "#000");
1760 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1761 bgs[2] = parse_color(value.addr, "#fff");
1764 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1766 paddings = parse_csslike(value.addr);
1767 if (paddings != NULL)
1768 for (i = 0; i < 4; ++i)
1769 r.ch_padding[i] = parse_integer(paddings[i], 0);
1772 "Error while parsing "
1773 "MyMenu.completion_highlighted."
1777 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1780 sizes = parse_csslike(value.addr);
1782 for (i = 0; i < 4; ++i)
1783 r.ch_borders[i] = parse_integer(sizes[i], 0);
1786 "Error while parsing "
1787 "MyMenu.completion_highlighted."
1791 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1794 colors = parse_csslike(value.addr);
1796 for (i = 0; i < 4; ++i)
1797 ch_borders_bg[i] = parse_color(colors[i], "#000");
1800 "Error while parsing "
1801 "MyMenu.completion_highlighted."
1806 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1808 colors = parse_csslike(value.addr);
1810 for (i = 0; i < 4; ++i)
1811 borders_bg[i] = parse_color(colors[i], "#000");
1814 "error while parsing "
1815 "MyMenu.border.color\n");
1819 /* Second round of args parsing */
1820 optind = 0; /* reset the option index */
1821 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1824 r.first_selected = 1;
1827 /* free_text -- already catched */
1829 /* separator -- this case was already catched */
1831 /* embedding mymenu this case was already catched. */
1833 /* multiple selection this case was already catched.
1838 newprompt = strdup(optarg);
1839 if (newprompt != NULL) {
1846 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1849 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1853 if ((paddings = parse_csslike(optarg)) != NULL)
1854 for (i = 0; i < 4; ++i)
1855 r.p_padding[i] = parse_integer(paddings[i], 0);
1860 if ((colors = parse_csslike(optarg)) != NULL)
1861 for (i = 0; i < 4; ++i)
1862 p_borders_bg[i] = parse_color(colors[i], "#000");
1867 if ((sizes = parse_csslike(optarg)) != NULL)
1868 for (i = 0; i < 4; ++i)
1869 r.p_borders[i] = parse_integer(sizes[i], 0);
1874 if ((colors = parse_csslike(optarg)) != NULL)
1875 for (i = 0; i < 4; ++i)
1876 c_borders_bg[i] = parse_color(colors[i], "#000");
1881 if ((sizes = parse_csslike(optarg)) != NULL)
1882 for (i = 0; i < 4; ++i)
1883 r.c_borders[i] = parse_integer(sizes[i], 0);
1888 if ((colors = parse_csslike(optarg)) != NULL)
1889 for (i = 0; i < 4; ++i)
1890 ch_borders_bg[i] = parse_color(colors[i], "#000");
1895 if ((sizes = parse_csslike(optarg)) != NULL)
1896 for (i = 0; i < 4; ++i)
1897 r.ch_borders[i] = parse_integer(sizes[i], 0);
1901 r.horizontal_layout = !strcmp(optarg, "horizontal");
1905 if ((newfont = strdup(optarg)) != NULL) {
1912 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1915 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1919 if ((borders = parse_csslike(optarg)) != NULL) {
1920 for (i = 0; i < 4; ++i)
1921 r.borders[i] = parse_integer(borders[i], 0);
1923 fprintf(stderr, "Error parsing b option\n");
1928 if ((colors = parse_csslike(optarg)) != NULL) {
1929 for (i = 0; i < 4; ++i)
1930 borders_bg[i] = parse_color(colors[i], "#000");
1932 fprintf(stderr, "error while parsing B option\n");
1936 fgs[0] = parse_color(optarg, NULL);
1939 bgs[0] = parse_color(optarg, NULL);
1942 fgs[1] = parse_color(optarg, NULL);
1945 bgs[1] = parse_color(optarg, NULL);
1948 fgs[2] = parse_color(optarg, NULL);
1951 bgs[2] = parse_color(optarg, NULL);
1954 fprintf(stderr, "Unrecognized option %c\n", ch);
1960 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1961 fprintf(stderr, "height, width, x or y are lesser than 0.");
1965 /* since only now we know if the first should be selected,
1966 * update the completion here */
1967 update_completions(cs, text, lines, vlines, r.first_selected);
1969 /* update the prompt lenght, only now we surely know the length of it
1971 r.ps1len = strlen(r.ps1);
1973 /* Create the window */
1974 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1975 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1976 XMapRaised(r.d, r.w);
1978 /* If embed, listen for other events as well */
1980 Window *children, parent, root;
1981 unsigned int children_no;
1983 XSelectInput(r.d, parent_window, FocusChangeMask);
1984 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1986 for (i = 0; i < children_no && children[i] != r.w; ++i)
1987 XSelectInput(r.d, children[i], FocusChangeMask);
1990 grabfocus(r.d, r.w);
1993 take_keyboard(r.d, r.w);
1995 r.x_zero = r.borders[3];
1996 r.y_zero = r.borders[0];
2001 for (i = 0; i < 3; ++i) {
2002 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2003 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2006 for (i = 0; i < 4; ++i) {
2007 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2008 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2009 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2010 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2014 /* Load the colors in our GCs */
2015 for (i = 0; i < 3; ++i) {
2016 XSetForeground(r.d, r.fgs[i], fgs[i]);
2017 XSetForeground(r.d, r.bgs[i], bgs[i]);
2020 for (i = 0; i < 4; ++i) {
2021 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2022 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2023 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2024 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2027 if (load_font(&r, fontname) == -1)
2030 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2032 for (i = 0; i < 3; ++i) {
2034 XRenderColor xrcolor;
2036 c = *(rgba_t *)&fgs[i];
2037 xrcolor.red = EXPANDBITS(c.rgba.r);
2038 xrcolor.green = EXPANDBITS(c.rgba.g);
2039 xrcolor.blue = EXPANDBITS(c.rgba.b);
2040 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2041 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2044 /* compute prompt dimensions */
2050 if (pledge("stdio", "") == -1)
2054 /* Cache text height */
2055 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2057 /* Draw the window for the first time */
2061 while (status == LOOPING || status == OK_LOOP) {
2062 status = loop(&r, &text, &textlen, cs, lines, vlines);
2065 printf("%s\n", text);
2067 if (!r.multiple_select && status == OK_LOOP)
2071 XUngrabKeyboard(r.d, CurrentTime);
2073 for (i = 0; i < 3; ++i)
2074 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2076 for (i = 0; i < 3; ++i) {
2077 XFreeGC(r.d, r.fgs[i]);
2078 XFreeGC(r.d, r.bgs[i]);
2081 for (i = 0; i < 4; ++i) {
2082 XFreeGC(r.d, r.borders_bg[i]);
2083 XFreeGC(r.d, r.p_borders_bg[i]);
2084 XFreeGC(r.d, r.c_borders_bg[i]);
2085 XFreeGC(r.d, r.ch_borders_bg[i]);
2091 for (i = 0; i < 3; ++i)
2092 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2093 XftFontClose(r.d, r.font);
2094 XftDrawDestroy(r.xftdraw);
2104 XFreeColormap(r.d, cmap);
2106 XDestroyWindow(r.d, r.w);
2109 return status != OK;