1 #include <ctype.h> /* isalnum */
5 #include <locale.h> /* setlocale */
9 #include <string.h> /* strdup, strlen */
15 #include <X11/Xresource.h>
16 #include <X11/Xutil.h>
17 #include <X11/keysym.h>
18 #include <X11/Xft/Xft.h>
20 #include <X11/extensions/Xinerama.h>
22 #define RESNAME "MyMenu"
23 #define RESCLASS "mymenu"
25 #define SYM_BUF_SIZE 4
27 #define DEFFONT "monospace"
29 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:G:g:I:i:J:j:"
31 #define MIN(a, b) ((a) < (b) ? (a) : (b))
32 #define MAX(a, b) ((a) > (b) ? (a) : (b))
34 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
36 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
37 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
39 /* The states of the event loop */
40 enum state { LOOPING, OK_LOOP, OK, ERR };
43 * For the drawing-related function. The text to be rendere could be
44 * the prompt, a completion or a highlighted completion
46 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
48 /* These are the possible action to be performed after user input. */
60 TOGGLE_FIRST_SELECTED,
65 /* A big set of values that needs to be carried around for drawing. A
66 * big struct to rule them all */
68 Display *d; /* Connection to xorg */
76 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
78 int y_zero; /* like x_zero but for the y axis */
80 int offset; /* scroll offset */
84 short multiple_select;
86 /* four border width */
92 short horizontal_layout;
97 int ps1w; /* ps1 width */
98 int ps1h; /* ps1 height */
100 int text_height; /* cache for the vertical layout */
113 XftColor xft_colors[3];
121 * The X (or Y, depending on the layour) at which the item is
127 /* Wrap the linked list of completions */
129 struct completion *completions;
134 /* idea stolen from lemonbar; ty lemonboy */
148 /* Return a newly allocated (and empty) completion list */
150 compls_new(size_t length)
152 struct completions *cs = malloc(sizeof(struct completions));
157 cs->completions = calloc(length, sizeof(struct completion));
158 if (cs->completions == NULL) {
168 /* Delete the wrapper and the whole list */
170 compls_delete(struct completions *cs)
175 free(cs->completions);
180 * Create a completion list from a text and the list of possible
181 * completions (null terminated). Expects a non-null `cs'. `lines' and
182 * `vlines' should have the same length OR `vlines' is NULL.
185 filter(struct completions *cs, char *text, char **lines, char **vlines)
195 if (lines[index] == NULL)
198 l = vlines[index] != NULL ? vlines[index] : lines[index];
200 if (strcasestr(l, text) != NULL) {
201 struct completion *c = &cs->completions[matching];
203 c->rcompletion = lines[index];
209 cs->length = matching;
213 /* Update the given completion */
215 update_completions(struct completions *cs, char *text, char **lines,
216 char **vlines, short first_selected)
218 filter(cs, text, lines, vlines);
219 if (first_selected && cs->length > 0)
224 * Select the next or previous selection and update some state. `text'
225 * will be updated with the text of the completion and `textlen' with
226 * the new length. If the memory cannot be allocated `status' will be
230 complete(struct completions *cs, short first_selected, short p,
231 char **text, int *textlen, enum state *status)
233 struct completion *n;
236 if (cs == NULL || cs->length == 0)
240 * If the first is always selected and the first entry is
241 * different from the text, expand the text and return
243 if (first_selected &&
245 strcmp(cs->completions->completion, *text) != 0 &&
248 *text = strdup(cs->completions->completion);
253 *textlen = strlen(*text);
257 index = cs->selected;
259 if (index == -1 && p)
261 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
264 n = &cs->completions[cs->selected];
267 *text = strdup(n->completion);
269 fprintf(stderr, "Memory allocation error!\n");
273 *textlen = strlen(*text);
276 /* Push the character c at the end of the string pointed by p */
278 pushc(char **p, int maxlen, char c)
282 len = strnlen(*p, maxlen);
283 if (!(len < maxlen - 2)) {
286 maxlen += maxlen >> 1;
287 newptr = realloc(*p, maxlen);
288 if (newptr == NULL) /* bad */
294 (*p)[len + 1] = '\0';
299 * Remove the last rune from the *UTF-8* string! This is different
300 * from just setting the last byte to 0 (in some cases ofc). Return a
301 * pointer (e) to the last nonzero char. If e < p then p is empty!
321 * If c is a starting byte (11......) or is under
324 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
331 /* Remove the last word plus trailing white spaces from the given string */
338 if ((len = strlen(w)) == 0)
347 if (in_word && isspace(*e))
350 if (!in_word && !isspace(*e))
356 * If the string is surrounded by quates (`"') remove them and replace
357 * every `\"' in the string with a single double-quote.
360 normalize_str(const char *str)
365 if ((len = strlen(str)) == 0)
368 if ((s = calloc(len, sizeof(char))) == NULL)
379 str += 2; /* skip this and the next char */
385 str++; /* skip only this char */
397 readlines(size_t *lineslen)
399 size_t len = 0, cap = 0;
402 char *line = NULL, **lines = NULL;
404 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
405 if (linelen != 0 && line[linelen-1] == '\n')
406 line[linelen-1] = '\0';
412 newcap = MAX(cap * 1.5, 32);
413 t = recallocarray(lines, cap, newcap, sizeof(char *));
415 err(1, "recallocarray");
420 if ((lines[len++] = strdup(line)) == NULL)
433 * Compute the dimensions of the string str once rendered.
434 * It'll return the width and set ret_width and ret_height if not NULL
437 text_extents(char *str, int len, struct rendering *r, int *ret_width,
442 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
443 height = r->font->ascent - r->font->descent;
444 width = gi.width - gi.x;
446 if (ret_width != NULL)
448 if (ret_height != NULL)
449 *ret_height = height;
454 draw_string(char *str, int len, int x, int y, struct rendering *r,
459 xftcolor = r->xft_colors[0];
461 xftcolor = r->xft_colors[1];
462 if (tt == COMPL_HIGH)
463 xftcolor = r->xft_colors[2];
465 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
468 /* Duplicate the string and substitute every space with a 'n` */
474 if (str == NULL || *str == '\0')
477 if ((dup = strdup(str)) == NULL)
480 for (t = dup; *t; ++t) {
489 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
490 enum obj_type t, char *text)
492 GC *border_color, bg;
493 int *padding, *borders;
494 int ret = 0, inner_width, inner_height, x;
498 border_color = r->p_borders_bg;
499 padding = r->p_padding;
500 borders = r->p_borders;
504 border_color = r->c_borders_bg;
505 padding = r->c_padding;
506 borders = r->c_borders;
510 border_color = r->ch_borders_bg;
511 padding = r->ch_padding;
512 borders = r->ch_borders;
517 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
519 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
520 inner_height = padding[0] + r->text_height + padding[2];
523 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
527 XFillRectangle(r->d, r->w, border_color[1],
528 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
531 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
532 y + borders[0] + padding[0] + r->text_height + padding[2],
533 r->width, borders[2]);
536 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
540 x = r->x_zero + borders[3];
542 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
545 y += padding[0] + r->text_height;
547 if (prefix != NULL) {
548 draw_string(prefix, strlen(prefix), x, y, r, t);
551 draw_string(text, strlen(text), x, y, r, t);
557 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
558 enum obj_type t, char *text)
560 GC *border_color, bg;
561 int *padding, *borders;
562 int ret = 0, inner_width, inner_height, y, text_width;
566 border_color = r->p_borders_bg;
567 padding = r->p_padding;
568 borders = r->p_borders;
572 border_color = r->c_borders_bg;
573 padding = r->c_padding;
574 borders = r->c_borders;
578 border_color = r->ch_borders_bg;
579 padding = r->ch_padding;
580 borders = r->ch_borders;
585 if (padding[0] < 0 || padding[2] < 0) {
586 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
590 padding[2] = padding[0];
593 /* If they are still lesser than 0, set 'em to 0 */
594 if (padding[0] < 0 || padding[2] < 0)
595 padding[0] = padding[2] = 0;
597 /* Get the text width */
598 text_extents(text, strlen(text), r, &text_width, NULL);
600 text_width += prefix_width;
602 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
604 inner_width = padding[3] + text_width + padding[1];
605 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
608 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
612 XFillRectangle(r->d, r->w, border_color[1],
613 x + borders[3] + inner_width, r->y_zero, borders[1],
617 XFillRectangle(r->d, r->w, border_color[2], x,
618 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
622 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
627 y = r->y_zero + borders[0];
628 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
631 y += padding[0] + r->text_height;
633 if (prefix != NULL) {
634 draw_string(prefix, strlen(prefix), x, y, r, t);
637 draw_string(text, strlen(text), x, y, r, t);
643 * ,-----------------------------------------------------------------,
644 * | 20 char text | completion | completion | completion | compl |
645 * `-----------------------------------------------------------------'
648 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
653 /* Draw the prompt */
654 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
656 for (i = r->offset; i < cs->length; ++i) {
659 if (cs->selected == (ssize_t)i)
664 cs->completions[i].offset = x;
666 x += draw_h_box(r, x, NULL, 0, t,
667 cs->completions[i].completion);
669 if (x > INNER_WIDTH(r))
673 for (i += 1; i < cs->length; ++i)
674 cs->completions[i].offset = -1;
678 * ,-----------------------------------------------------------------,
680 * |-----------------------------------------------------------------|
682 * |-----------------------------------------------------------------|
684 * `-----------------------------------------------------------------'
687 draw_vertically(struct rendering *r, char *text, struct completions *cs)
692 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
694 for (i = r->offset; i < cs->length; ++i) {
697 if (cs->selected == (ssize_t)i)
702 cs->completions[i].offset = y;
704 y += draw_v_box(r, y, NULL, 0, t,
705 cs->completions[i].completion);
707 if (y > INNER_HEIGHT(r))
711 for (i += 1; i < cs->length; ++i)
712 cs->completions[i].offset = -1;
716 draw(struct rendering *r, char *text, struct completions *cs)
718 /* Draw the background */
719 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
720 INNER_WIDTH(r), INNER_HEIGHT(r));
722 /* Draw the contents */
723 if (r->horizontal_layout)
724 draw_horizontally(r, text, cs);
726 draw_vertically(r, text, cs);
728 /* Draw the borders */
729 if (r->borders[0] != 0)
730 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
733 if (r->borders[1] != 0)
734 XFillRectangle(r->d, r->w, r->borders_bg[1],
735 r->width - r->borders[1], 0, r->borders[1],
738 if (r->borders[2] != 0)
739 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
740 r->height - r->borders[2], r->width, r->borders[2]);
742 if (r->borders[3] != 0)
743 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
744 r->borders[3], r->height);
750 /* Set some WM stuff */
752 set_win_atoms_hints(Display *d, Window w, int width, int height)
755 XClassHint *class_hint;
756 XSizeHints *size_hint;
758 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
759 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
760 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
761 (unsigned char *)&type, 1);
763 /* some window managers honor this properties */
764 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
765 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
766 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
767 (unsigned char *)&type, 1);
769 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
770 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
771 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
772 (unsigned char *)&type, 1);
774 /* Setting window hints */
775 class_hint = XAllocClassHint();
776 if (class_hint == NULL) {
777 fprintf(stderr, "Could not allocate memory for class hint\n");
778 exit(EX_UNAVAILABLE);
781 class_hint->res_name = RESNAME;
782 class_hint->res_class = RESCLASS;
783 XSetClassHint(d, w, class_hint);
786 size_hint = XAllocSizeHints();
787 if (size_hint == NULL) {
788 fprintf(stderr, "Could not allocate memory for size hint\n");
789 exit(EX_UNAVAILABLE);
792 size_hint->flags = PMinSize | PBaseSize;
793 size_hint->min_width = width;
794 size_hint->base_width = width;
795 size_hint->min_height = height;
796 size_hint->base_height = height;
801 /* Get the width and height of the window `w' */
803 get_wh(Display *d, Window *w, int *width, int *height)
805 XWindowAttributes win_attr;
807 XGetWindowAttributes(d, *w, &win_attr);
808 *height = win_attr.height;
809 *width = win_attr.width;
813 grabfocus(Display *d, Window w)
816 for (i = 0; i < 100; ++i) {
820 XGetInputFocus(d, &focuswin, &revert_to_win);
825 XSetInputFocus(d, w, RevertToParent, CurrentTime);
832 * I know this may seem a little hackish BUT is the only way I managed
833 * to actually grab that goddam keyboard. Only one call to
834 * XGrabKeyboard does not always end up with the keyboard grabbed!
837 take_keyboard(Display *d, Window w)
840 for (i = 0; i < 100; i++) {
841 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
842 CurrentTime) == GrabSuccess)
846 fprintf(stderr, "Cannot grab keyboard\n");
851 parse_color(const char *str, const char *def)
862 /* +1 for the # ath the start */
863 if (*str != '#' || len > 9 || len < 4)
865 ++str; /* skip the # */
868 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
875 /* expand #rgb -> #rrggbb */
876 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
877 | (tmp.v & 0x00f) * 0x0011;
879 /* assume 0xff opacity */
882 } /* colors in #aarrggbb need no adjustments */
884 /* premultiply the alpha */
886 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
887 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
888 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
895 fprintf(stderr, "Invalid color: \"%s\".\n", str);
897 return parse_color(def, NULL);
903 * Given a string try to parse it as a number or return `def'.
906 parse_integer(const char *str, int def)
911 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
912 if (errstr != NULL) {
913 warnx("'%s' is %s; using %d as default", str, errstr, def);
921 * Like parse_integer but recognize the percentages (i.e. strings
925 parse_int_with_percentage(const char *str, int default_value, int max)
927 int len = strlen(str);
929 if (len > 0 && str[len - 1] == '%') {
933 if ((cpy = strdup(str)) == NULL)
937 val = parse_integer(cpy, default_value);
939 return val * max / 100;
942 return parse_integer(str, default_value);
946 get_mouse_coords(Display *d, int *x, int *y)
953 root = DefaultRootWindow(d);
955 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
956 for (i = 0; i < ScreenCount(d); ++i) {
957 if (root == RootWindow(d, i))
964 * Like parse_int_with_percentage but understands some special values:
965 * - middle that is (max-self)/2
968 * - end that is (max-self)
969 * - mx x coordinate of the mouse
970 * - my y coordinate of the mouse
973 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
976 if (!strcmp(str, "start"))
978 if (!strcmp(str, "middle") || !strcmp(str, "center"))
979 return (max - self) / 2;
980 if (!strcmp(str, "end"))
982 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
985 get_mouse_coords(d, &x, &y);
986 if (!strcmp(str, "mx"))
991 return parse_int_with_percentage(str, default_value, max);
994 /* Parse a string like a CSS value. */
995 /* TODO: harden a bit this function */
997 parse_csslike(const char *str)
1000 char *s, *token, **ret;
1007 ret = malloc(4 * sizeof(char *));
1013 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1014 ret[i] = strdup(token);
1017 for (j = 1; j < 4; j++)
1018 ret[j] = strdup(ret[0]);
1021 ret[2] = strdup(ret[0]);
1022 ret[3] = strdup(ret[1]);
1026 ret[3] = strdup(ret[1]);
1029 * before we didn't check for the return type of strdup, here
1034 for (i = 0; i < 4; ++i)
1035 any_null = ret[i] == NULL || any_null;
1038 for (i = 0; i < 4; ++i)
1042 if (i == 0 || any_null) {
1052 * Given an event, try to understand what the users wants. If the
1053 * return value is ADD_CHAR then `input' is a pointer to a string that
1054 * will need to be free'ed later.
1057 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1059 char str[SYM_BUF_SIZE] = { 0 };
1062 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1065 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1066 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1068 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1071 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1074 /* Try to read what key was pressed */
1076 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1077 if (s == XBufferOverflow) {
1079 "Buffer overflow when trying to create keyboard "
1084 if (ev->state & ControlMask) {
1085 if (!strcmp(str, "")) /* C-u */
1087 if (!strcmp(str, "")) /* C-w */
1089 if (!strcmp(str, "")) /* C-h */
1091 if (!strcmp(str, "\r")) /* C-m */
1092 return CONFIRM_CONTINUE;
1093 if (!strcmp(str, "")) /* C-p */
1095 if (!strcmp(str, "")) /* C-n */
1097 if (!strcmp(str, "")) /* C-c */
1099 if (!strcmp(str, "\t")) /* C-i */
1100 return TOGGLE_FIRST_SELECTED;
1103 *input = strdup(str);
1104 if (*input == NULL) {
1105 fprintf(stderr, "Error while allocating memory for key.\n");
1113 confirm(enum state *status, struct rendering *r, struct completions *cs,
1114 char **text, int *textlen)
1116 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1117 /* if there is something selected expand it and return */
1118 int index = cs->selected == -1 ? 0 : cs->selected;
1119 struct completion *c = cs->completions;
1133 if (*text == NULL) {
1134 fprintf(stderr, "Memory allocation error\n");
1138 *textlen = strlen(*text);
1142 if (!r->free_text) /* cannot accept arbitrary text */
1147 * cs: completion list
1148 * offset: the offset of the click
1149 * first: the first (rendered) item
1150 * def: the default action
1153 select_clicked(struct completions *cs, size_t offset, size_t first,
1156 ssize_t selected = first;
1159 if (cs->length == 0)
1162 if (offset < cs->completions[selected].offset)
1165 /* skip the first entry */
1166 for (selected += 1; selected < cs->length; ++selected) {
1167 if (cs->completions[selected].offset == -1)
1170 if (offset < cs->completions[selected].offset) {
1171 cs->selected = selected - 1;
1178 cs->selected = selected - 1;
1184 handle_mouse(struct rendering *r, struct completions *cs,
1185 XButtonPressedEvent *e)
1189 if (r->horizontal_layout)
1194 switch (e->button) {
1196 return select_clicked(cs, off, r->offset, CONFIRM);
1199 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1213 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1214 char **lines, char **vlines)
1216 enum state status = LOOPING;
1218 while (status == LOOPING) {
1220 XNextEvent(r->d, &e);
1222 if (XFilterEvent(&e, r->w))
1227 XRefreshKeyboardMapping(&e.xmapping);
1232 if (e.xfocus.window != r->w)
1233 grabfocus(r->d, r->w);
1236 case VisibilityNotify:
1237 if (e.xvisibility.state != VisibilityUnobscured)
1238 XRaiseWindow(r->d, r->w);
1242 get_wh(r->d, &r->w, &r->width, &r->height);
1251 if (e.type == KeyPress)
1252 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1255 a = handle_mouse(r, cs,
1256 (XButtonPressedEvent *)&e);
1268 confirm(&status, r, cs, text, textlen);
1272 case CONFIRM_CONTINUE: {
1274 confirm(&status, r, cs, text, textlen);
1279 complete(cs, r->first_selected, 1, text,
1281 r->offset = cs->selected;
1286 complete(cs, r->first_selected, 0, text,
1288 r->offset = cs->selected;
1294 update_completions(cs, *text, lines, vlines,
1301 update_completions(cs, *text, lines, vlines,
1308 for (i = 0; i < *textlen; ++i)
1310 update_completions(cs, *text, lines, vlines,
1319 str_len = strlen(input);
1322 * sometimes a strange key is pressed
1323 * i.e. ctrl alone), so input will be
1324 * empty. Don't need to update
1325 * completion in that case
1330 for (i = 0; i < str_len; ++i) {
1331 *textlen = pushc(text, *textlen,
1333 if (*textlen == -1) {
1335 "Memory allocation "
1342 if (status != ERR) {
1343 update_completions(cs, *text, lines,
1344 vlines, r->first_selected);
1352 case TOGGLE_FIRST_SELECTED:
1353 r->first_selected = !r->first_selected;
1354 if (r->first_selected && cs->selected < 0)
1356 if (!r->first_selected && cs->selected == 0)
1361 r->offset = MIN(r->offset + 1, cs->length - 1);
1365 r->offset = MAX((ssize_t)r->offset - 1, 0);
1378 load_font(struct rendering *r, const char *fontname)
1380 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1385 xim_init(struct rendering *r, XrmDatabase *xdb)
1387 XIMStyle best_match_style;
1391 /* Open the X input method */
1392 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1395 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1396 fprintf(stderr, "Input Styles could not be retrieved\n");
1397 exit(EX_UNAVAILABLE);
1400 best_match_style = 0;
1401 for (i = 0; i < xis->count_styles; ++i) {
1402 XIMStyle ts = xis->supported_styles[i];
1403 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1404 best_match_style = ts;
1410 if (!best_match_style)
1412 "No matching input style could be determined\n");
1414 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1415 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1417 err(1, "XCreateIC");
1421 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1422 XVisualInfo vinfo, int x, int y, int ox, int oy,
1423 unsigned long background_pixel)
1425 XSetWindowAttributes attr;
1426 unsigned long vmask;
1428 /* Create the window */
1429 attr.colormap = cmap;
1430 attr.override_redirect = 1;
1431 attr.border_pixel = 0;
1432 attr.background_pixel = background_pixel;
1433 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1434 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1436 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1439 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1440 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1444 ps1extents(struct rendering *r)
1447 dup = strdupn(r->ps1);
1448 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1453 usage(char *prgname)
1456 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1457 " [-d separator] [-e window] [-f font] [-G color] [-g "
1459 " [-H height] [-I color] [-i size] [-J color] [-j "
1460 "size] [-l layout]\n"
1461 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1463 " [-t color] [-W width] [-x coord] [-y coord]\n",
1468 main(int argc, char **argv)
1470 struct completions *cs;
1475 Window parent_window;
1477 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1478 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1479 ch_borders_bg[4]; /* N E S W */
1482 int offset_x, offset_y, x, y;
1483 int textlen, d_width, d_height;
1485 char *sep, *parent_window_id;
1486 char **lines, **vlines;
1487 char *fontname, *text, *xrm;
1490 parent_window_id = NULL;
1492 r.first_selected = 0;
1494 r.multiple_select = 0;
1497 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1499 case 'h': /* help */
1502 case 'v': /* version */
1503 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1505 case 'e': /* embed */
1506 if ((parent_window_id = strdup(optarg)) == NULL)
1510 if ((sep = strdup(optarg)) == NULL)
1517 r.multiple_select = 1;
1524 lines = readlines(&nlines);
1530 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1533 for (i = 0; i < nlines; i++) {
1535 t = strstr(lines[i], sep);
1537 vlines[i] = lines[i];
1543 setlocale(LC_ALL, getenv("LANG"));
1547 /* where the monitor start (used only with xinerama) */
1548 offset_x = offset_y = 0;
1550 /* default width and height */
1554 /* default position on the screen */
1557 for (i = 0; i < 4; ++i) {
1558 /* default paddings */
1559 r.p_padding[i] = 10;
1560 r.c_padding[i] = 10;
1561 r.ch_padding[i] = 10;
1563 /* default borders */
1567 r.ch_borders[i] = 0;
1571 * The prompt. We duplicate the string so later is easy to
1572 * free (in the case it's been overwritten by the user)
1574 if ((r.ps1 = strdup("$ ")) == NULL)
1577 /* same for the font name */
1578 if ((fontname = strdup(DEFFONT)) == NULL)
1582 if ((text = malloc(textlen * sizeof(char))) == NULL)
1585 /* struct completions *cs = filter(text, lines); */
1586 if ((cs = compls_new(nlines)) == NULL)
1587 err(1, "compls_new");
1589 /* start talking to xorg */
1590 r.d = XOpenDisplay(NULL);
1592 fprintf(stderr, "Could not open display!\n");
1593 return EX_UNAVAILABLE;
1597 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1598 parent_window = DefaultRootWindow(r.d);
1602 /* get display size */
1603 get_wh(r.d, &parent_window, &d_width, &d_height);
1605 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1606 XineramaScreenInfo *info;
1609 int number_of_screens, monitors, i;
1610 int root_x, root_y, win_x, win_y;
1614 number_of_screens = XScreenCount(r.d);
1615 for (i = 0; i < number_of_screens; ++i) {
1616 root = XRootWindow(r.d, i);
1617 res = XQueryPointer(
1618 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1624 fprintf(stderr, "No mouse found.\n");
1629 /* Now find in which monitor the mice is */
1630 info = XineramaQueryScreens(r.d, &monitors);
1632 for (i = 0; i < monitors; ++i) {
1633 if (info[i].x_org <= root_x
1634 && root_x <= (info[i].x_org + info[i].width)
1635 && info[i].y_org <= root_y
1636 && root_y <= (info[i].y_org + info[i].height)) {
1637 offset_x = info[i].x_org;
1638 offset_y = info[i].y_org;
1639 d_width = info[i].width;
1640 d_height = info[i].height;
1648 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1649 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1652 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1653 fgs[2] = parse_color("#000", NULL);
1655 bgs[0] = bgs[1] = parse_color("#000", NULL);
1656 bgs[2] = parse_color("#fff", NULL);
1658 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1659 parse_color("#000", NULL);
1661 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1662 = parse_color("#000", NULL);
1663 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1664 = parse_color("#000", NULL);
1665 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1666 = parse_color("#000", NULL);
1668 r.horizontal_layout = 1;
1670 /* Read the resources */
1672 xrm = XResourceManagerString(r.d);
1678 xdb = XrmGetStringDatabase(xrm);
1680 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1682 if ((fontname = strdup(value.addr)) == NULL)
1685 fprintf(stderr, "no font defined, using %s\n", fontname);
1688 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1689 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1691 fprintf(stderr, "no layout defined, using horizontal\n");
1693 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1695 r.ps1 = normalize_str(value.addr);
1698 "no prompt defined, using \"%s\" as "
1703 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1705 sizes = parse_csslike(value.addr);
1707 for (i = 0; i < 4; ++i)
1708 r.p_borders[i] = parse_integer(sizes[i], 0);
1711 "error while parsing "
1712 "MyMenu.prompt.border.size");
1715 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1717 colors = parse_csslike(value.addr);
1719 for (i = 0; i < 4; ++i)
1720 p_borders_bg[i] = parse_color(colors[i], "#000");
1723 "error while parsing "
1724 "MyMenu.prompt.border.color");
1727 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1729 colors = parse_csslike(value.addr);
1731 for (i = 0; i < 4; ++i)
1732 r.p_padding[i] = parse_integer(colors[i], 0);
1735 "error while parsing "
1736 "MyMenu.prompt.padding");
1739 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1740 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1742 fprintf(stderr, "no width defined, using %d\n", r.width);
1744 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1745 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1747 fprintf(stderr, "no height defined, using %d\n", r.height);
1749 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1750 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1752 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1753 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1755 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1757 borders = parse_csslike(value.addr);
1758 if (borders != NULL)
1759 for (i = 0; i < 4; ++i)
1760 r.borders[i] = parse_int_with_percentage(
1761 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1764 "error while parsing "
1765 "MyMenu.border.size\n");
1769 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1770 fgs[0] = parse_color(value.addr, "#fff");
1772 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1773 bgs[0] = parse_color(value.addr, "#000");
1776 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1777 fgs[1] = parse_color(value.addr, "#fff");
1779 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1780 bgs[1] = parse_color(value.addr, "#000");
1782 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1784 paddings = parse_csslike(value.addr);
1785 if (paddings != NULL)
1786 for (i = 0; i < 4; ++i)
1787 r.c_padding[i] = parse_integer(paddings[i], 0);
1790 "Error while parsing "
1791 "MyMenu.completion.padding");
1794 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1796 sizes = parse_csslike(value.addr);
1798 for (i = 0; i < 4; ++i)
1799 r.c_borders[i] = parse_integer(sizes[i], 0);
1802 "Error while parsing "
1803 "MyMenu.completion.border.size");
1806 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1808 sizes = parse_csslike(value.addr);
1810 for (i = 0; i < 4; ++i)
1811 c_borders_bg[i] = parse_color(sizes[i], "#000");
1814 "Error while parsing "
1815 "MyMenu.completion.border.color");
1818 /* Completion Highlighted */
1820 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1821 fgs[2] = parse_color(value.addr, "#000");
1824 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1825 bgs[2] = parse_color(value.addr, "#fff");
1828 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1830 paddings = parse_csslike(value.addr);
1831 if (paddings != NULL)
1832 for (i = 0; i < 4; ++i)
1833 r.ch_padding[i] = parse_integer(paddings[i], 0);
1836 "Error while parsing "
1837 "MyMenu.completion_highlighted."
1841 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1844 sizes = parse_csslike(value.addr);
1846 for (i = 0; i < 4; ++i)
1847 r.ch_borders[i] = parse_integer(sizes[i], 0);
1850 "Error while parsing "
1851 "MyMenu.completion_highlighted."
1855 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1858 colors = parse_csslike(value.addr);
1860 for (i = 0; i < 4; ++i)
1861 ch_borders_bg[i] = parse_color(colors[i], "#000");
1864 "Error while parsing "
1865 "MyMenu.completion_highlighted."
1870 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1872 colors = parse_csslike(value.addr);
1874 for (i = 0; i < 4; ++i)
1875 borders_bg[i] = parse_color(colors[i], "#000");
1878 "error while parsing "
1879 "MyMenu.border.color\n");
1883 /* Second round of args parsing */
1884 optind = 0; /* reset the option index */
1885 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1888 r.first_selected = 1;
1891 /* free_text -- already catched */
1893 /* separator -- this case was already catched */
1895 /* embedding mymenu this case was already catched. */
1897 /* multiple selection this case was already catched.
1902 newprompt = strdup(optarg);
1903 if (newprompt != NULL) {
1910 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1913 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1917 if ((paddings = parse_csslike(optarg)) != NULL)
1918 for (i = 0; i < 4; ++i)
1919 r.p_padding[i] = parse_integer(paddings[i], 0);
1924 if ((colors = parse_csslike(optarg)) != NULL)
1925 for (i = 0; i < 4; ++i)
1926 p_borders_bg[i] = parse_color(colors[i], "#000");
1931 if ((sizes = parse_csslike(optarg)) != NULL)
1932 for (i = 0; i < 4; ++i)
1933 r.p_borders[i] = parse_integer(sizes[i], 0);
1938 if ((colors = parse_csslike(optarg)) != NULL)
1939 for (i = 0; i < 4; ++i)
1940 c_borders_bg[i] = parse_color(colors[i], "#000");
1945 if ((sizes = parse_csslike(optarg)) != NULL)
1946 for (i = 0; i < 4; ++i)
1947 r.c_borders[i] = parse_integer(sizes[i], 0);
1952 if ((colors = parse_csslike(optarg)) != NULL)
1953 for (i = 0; i < 4; ++i)
1954 ch_borders_bg[i] = parse_color(colors[i], "#000");
1959 if ((sizes = parse_csslike(optarg)) != NULL)
1960 for (i = 0; i < 4; ++i)
1961 r.ch_borders[i] = parse_integer(sizes[i], 0);
1965 r.horizontal_layout = !strcmp(optarg, "horizontal");
1969 if ((newfont = strdup(optarg)) != NULL) {
1976 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1979 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1983 if ((borders = parse_csslike(optarg)) != NULL) {
1984 for (i = 0; i < 4; ++i)
1985 r.borders[i] = parse_integer(borders[i], 0);
1987 fprintf(stderr, "Error parsing b option\n");
1992 if ((colors = parse_csslike(optarg)) != NULL) {
1993 for (i = 0; i < 4; ++i)
1994 borders_bg[i] = parse_color(colors[i], "#000");
1996 fprintf(stderr, "error while parsing B option\n");
2000 fgs[0] = parse_color(optarg, NULL);
2003 bgs[0] = parse_color(optarg, NULL);
2006 fgs[1] = parse_color(optarg, NULL);
2009 bgs[1] = parse_color(optarg, NULL);
2012 fgs[2] = parse_color(optarg, NULL);
2015 bgs[2] = parse_color(optarg, NULL);
2018 fprintf(stderr, "Unrecognized option %c\n", ch);
2024 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2025 fprintf(stderr, "height, width, x or y are lesser than 0.");
2029 /* since only now we know if the first should be selected,
2030 * update the completion here */
2031 update_completions(cs, text, lines, vlines, r.first_selected);
2033 /* update the prompt lenght, only now we surely know the length of it
2035 r.ps1len = strlen(r.ps1);
2037 /* Create the window */
2038 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2039 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2040 XMapRaised(r.d, r.w);
2042 /* If embed, listen for other events as well */
2044 Window *children, parent, root;
2045 unsigned int children_no;
2047 XSelectInput(r.d, parent_window, FocusChangeMask);
2048 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2050 for (i = 0; i < children_no && children[i] != r.w; ++i)
2051 XSelectInput(r.d, children[i], FocusChangeMask);
2054 grabfocus(r.d, r.w);
2057 take_keyboard(r.d, r.w);
2059 r.x_zero = r.borders[3];
2060 r.y_zero = r.borders[0];
2065 for (i = 0; i < 3; ++i) {
2066 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2067 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2070 for (i = 0; i < 4; ++i) {
2071 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2072 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2073 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2074 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2078 /* Load the colors in our GCs */
2079 for (i = 0; i < 3; ++i) {
2080 XSetForeground(r.d, r.fgs[i], fgs[i]);
2081 XSetForeground(r.d, r.bgs[i], bgs[i]);
2084 for (i = 0; i < 4; ++i) {
2085 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2086 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2087 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2088 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2091 if (load_font(&r, fontname) == -1)
2094 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2096 for (i = 0; i < 3; ++i) {
2098 XRenderColor xrcolor;
2100 c = *(rgba_t *)&fgs[i];
2101 xrcolor.red = EXPANDBITS(c.rgba.r);
2102 xrcolor.green = EXPANDBITS(c.rgba.g);
2103 xrcolor.blue = EXPANDBITS(c.rgba.b);
2104 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2105 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2108 /* compute prompt dimensions */
2114 if (pledge("stdio", "") == -1)
2118 /* Cache text height */
2119 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2121 /* Draw the window for the first time */
2125 while (status == LOOPING || status == OK_LOOP) {
2126 status = loop(&r, &text, &textlen, cs, lines, vlines);
2129 printf("%s\n", text);
2131 if (!r.multiple_select && status == OK_LOOP)
2135 XUngrabKeyboard(r.d, CurrentTime);
2137 for (i = 0; i < 3; ++i)
2138 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2140 for (i = 0; i < 3; ++i) {
2141 XFreeGC(r.d, r.fgs[i]);
2142 XFreeGC(r.d, r.bgs[i]);
2145 for (i = 0; i < 4; ++i) {
2146 XFreeGC(r.d, r.borders_bg[i]);
2147 XFreeGC(r.d, r.p_borders_bg[i]);
2148 XFreeGC(r.d, r.c_borders_bg[i]);
2149 XFreeGC(r.d, r.ch_borders_bg[i]);
2155 for (i = 0; i < 3; ++i)
2156 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2157 XftFontClose(r.d, r.font);
2158 XftDrawDestroy(r.xftdraw);
2168 XFreeColormap(r.d, cmap);
2170 XDestroyWindow(r.d, r.w);
2173 return status != OK;