1 #include <ctype.h> /* isalnum */
4 #include <locale.h> /* setlocale */
8 #include <string.h> /* strdup, strlen */
14 #include <X11/Xresource.h>
15 #include <X11/Xutil.h>
16 #include <X11/keysym.h>
19 #include <X11/extensions/Xinerama.h>
23 #include <X11/Xft/Xft.h>
27 #define VERSION "unknown"
30 #define resname "MyMenu"
31 #define resclass "mymenu"
33 #define SYM_BUF_SIZE 4
36 #define default_fontname "monospace"
38 #define default_fontname "fixed"
41 #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:"
43 #define MIN(a, b) ((a) < (b) ? (a) : (b))
44 #define MAX(a, b) ((a) > (b) ? (a) : (b))
46 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
49 * If we don't have or we don't want an "ignore case" completion
50 * style, fall back to `strstr(3)`
52 #ifndef USE_STRCASESTR
53 #define strcasestr strstr
56 /* The number of char to read */
57 #define STDIN_CHUNKS 128
59 /* The number of lines to allocate in advance */
60 #define LINES_CHUNK 64
63 #define check_allocation(a) \
66 fprintf(stderr, "Could not allocate memory\n"); \
71 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
72 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
74 /* The states of the event loop */
75 enum state { LOOPING, OK_LOOP, OK, ERR };
78 * For the drawing-related function. The text to be rendere could be
79 * the prompt, a completion or a highlighted completion
81 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
83 /* These are the possible action to be performed after user input. */
97 /* A big set of values that needs to be carried around for drawing. A
98 big struct to rule them all */
100 Display *d; /* Connection to xorg */
108 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
110 int y_zero; /* like x_zero but for the y axis */
112 size_t offset; /* scroll offset */
115 short first_selected;
116 short multiple_select;
118 /* four border width */
124 short horizontal_layout;
129 int ps1w; /* ps1 width */
130 int ps1h; /* ps1 height */
132 int text_height; /* cache for the vertical layout */
146 XftColor xft_colors[3];
157 /* Wrap the linked list of completions */
159 struct completion *completions;
164 /* idea stolen from lemonbar. ty lemonboy */
178 /* Return a newly allocated (and empty) completion list */
180 compls_new(size_t length)
182 struct completions *cs = malloc(sizeof(struct completions));
187 cs->completions = calloc(length, sizeof(struct completion));
188 if (cs->completions == NULL) {
198 /* Delete the wrapper and the whole list */
200 compls_delete(struct completions *cs)
205 free(cs->completions);
210 * Create a completion list from a text and the list of possible
211 * completions (null terminated). Expects a non-null `cs'. `lines' and
212 * `vlines' should have the same length OR `vlines' is NULL.
215 filter(struct completions *cs, char *text, char **lines, char **vlines)
225 if (lines[index] == NULL)
228 l = vlines[index] != NULL ? vlines[index] : lines[index];
230 if (strcasestr(l, text) != NULL) {
231 struct completion *c = &cs->completions[matching];
233 c->rcompletion = lines[index];
239 cs->length = matching;
243 /* Update the given completion */
245 update_completions(struct completions *cs, char *text, char **lines,
246 char **vlines, short first_selected)
248 filter(cs, text, lines, vlines);
249 if (first_selected && cs->length > 0)
254 * Select the next or previous selection and update some state. `text'
255 * will be updated with the text of the completion and `textlen' with
256 * the new length. If the memory cannot be allocated `status' will be
260 complete(struct completions *cs, short first_selected, short p, char **text,
261 int *textlen, enum state *status)
263 struct completion *n;
266 if (cs == NULL || cs->length == 0)
270 * If the first is always selected and the first entry is
271 * different from the text, expand the text and return
273 if (first_selected && cs->selected == 0
274 && strcmp(cs->completions->completion, *text) != 0 && !p) {
276 *text = strdup(cs->completions->completion);
281 *textlen = strlen(*text);
285 index = cs->selected;
287 if (index == -1 && p)
290 = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
292 n = &cs->completions[cs->selected];
295 *text = strdup(n->completion);
297 fprintf(stderr, "Memory allocation error!\n");
301 *textlen = strlen(*text);
304 /* Push the character c at the end of the string pointed by p */
306 pushc(char **p, int maxlen, char c)
310 len = strnlen(*p, maxlen);
311 if (!(len < maxlen - 2)) {
314 maxlen += maxlen >> 1;
315 newptr = realloc(*p, maxlen);
316 if (newptr == NULL) /* bad */
322 (*p)[len + 1] = '\0';
327 * Remove the last rune from the *UTF-8* string! This is different
328 * from just setting the last byte to 0 (in some cases ofc). Return a
329 * pointer (e) to the last nonzero char. If e < p then p is empty!
349 * If c is a starting byte (11......) or is under
352 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
359 /* Remove the last word plus trailing white spaces from the given string */
366 if ((len = strlen(w)) == 0)
375 if (in_word && isspace(*e))
378 if (!in_word && !isspace(*e))
384 * If the string is surrounded by quates (`"') remove them and replace
385 * every `\"' in the string with a single double-quote.
388 normalize_str(const char *str)
393 if ((len = strlen(str)) == 0)
396 s = calloc(len, sizeof(char));
407 str += 2; /* skip this and the next char */
413 str++; /* skip only this char */
425 read_stdin(char **buf)
428 size_t len = STDIN_CHUNKS;
430 *buf = malloc(len * sizeof(char));
438 r = read(0, *buf + offset, STDIN_CHUNKS);
446 *buf = realloc(*buf, len);
450 for (i = offset; i < len; ++i)
455 fprintf(stderr, "Error in allocating memory for stdin.\n");
456 exit(EX_UNAVAILABLE);
460 readlines(char ***lns, char **buf)
462 size_t i, len, ll, lines;
468 len = read_stdin(buf);
471 *lns = malloc(ll * sizeof(char *));
476 for (i = 0; i < len; i++) {
485 if (in_line && c == '\n')
488 if (!in_line && c != '\n') {
490 (*lns)[lines] = (*buf) + i;
493 if (lines == ll) { /* resize */
495 *lns = realloc(*lns, ll * sizeof(char *));
502 (*lns)[lines] = NULL;
507 fprintf(stderr, "Error in memory allocation.\n");
508 exit(EX_UNAVAILABLE);
512 * Compute the dimensions of the string str once rendered.
513 * It'll return the width and set ret_width and ret_height if not NULL
516 text_extents(char *str, int len, struct rendering *r, int *ret_width,
522 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
523 height = r->font->ascent - r->font->descent;
524 width = gi.width - gi.x;
527 XmbTextExtents(r->font, str, len, NULL, &rect);
528 height = rect.height;
531 if (ret_width != NULL)
533 if (ret_height != NULL)
534 *ret_height = height;
539 draw_string(char *str, int len, int x, int y, struct rendering *r,
545 xftcolor = r->xft_colors[0];
547 xftcolor = r->xft_colors[1];
548 if (tt == COMPL_HIGH)
549 xftcolor = r->xft_colors[2];
551 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
558 if (tt == COMPL_HIGH)
560 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
564 /* Duplicate the string and substitute every space with a 'n` */
573 if (str == NULL || len == 0)
576 if ((dup = strdup(str)) == NULL)
579 for (i = 0; i < len; ++i)
587 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
588 enum obj_type t, char *text)
590 GC *border_color, bg;
591 int *padding, *borders;
592 int ret = 0, inner_width, inner_height, x;
596 border_color = r->p_borders_bg;
597 padding = r->p_padding;
598 borders = r->p_borders;
602 border_color = r->c_borders_bg;
603 padding = r->c_padding;
604 borders = r->c_borders;
608 border_color = r->ch_borders_bg;
609 padding = r->ch_padding;
610 borders = r->ch_borders;
615 ret = borders[0] + padding[0] + r->text_height + padding[2]
618 inner_width = inner_width(r) - borders[1] - borders[3];
619 inner_height = padding[0] + r->text_height + padding[2];
622 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
626 XFillRectangle(r->d, r->w, border_color[1],
627 r->x_zero + inner_width(r) - borders[1], y, borders[1], ret);
630 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
631 y + borders[0] + padding[0] + r->text_height + padding[2],
632 r->width, borders[2]);
636 r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
639 x = r->x_zero + borders[3];
641 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
644 y += padding[0] + r->text_height;
646 if (prefix != NULL) {
647 draw_string(prefix, strlen(prefix), x, y, r, t);
650 draw_string(text, strlen(text), x, y, r, t);
656 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
657 enum obj_type t, char *text)
659 GC *border_color, bg;
660 int *padding, *borders;
661 int ret = 0, inner_width, inner_height, y, text_width;
665 border_color = r->p_borders_bg;
666 padding = r->p_padding;
667 borders = r->p_borders;
671 border_color = r->c_borders_bg;
672 padding = r->c_padding;
673 borders = r->c_borders;
677 border_color = r->ch_borders_bg;
678 padding = r->ch_padding;
679 borders = r->ch_borders;
684 if (padding[0] < 0 || padding[2] < 0)
685 padding[0] = padding[2]
686 = (inner_height(r) - borders[0] - borders[2]
690 /* If they are still lesser than 0, set 'em to 0 */
691 if (padding[0] < 0 || padding[2] < 0)
692 padding[0] = padding[2] = 0;
694 /* Get the text width */
695 text_extents(text, strlen(text), r, &text_width, NULL);
697 text_width += prefix_width;
699 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
701 inner_width = padding[3] + text_width + padding[1];
702 inner_height = inner_height(r) - borders[0] - borders[2];
706 r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
709 XFillRectangle(r->d, r->w, border_color[1],
710 x + borders[3] + inner_width, r->y_zero, borders[1],
714 XFillRectangle(r->d, r->w, border_color[2], x,
715 r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
718 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
723 y = r->y_zero + borders[0];
724 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
727 y += padding[0] + r->text_height;
729 if (prefix != NULL) {
730 draw_string(prefix, strlen(prefix), x, y, r, t);
733 draw_string(text, strlen(text), x, y, r, t);
738 /* ,-----------------------------------------------------------------, */
739 /* | 20 char text | completion | completion | completion | compl | */
740 /* `-----------------------------------------------------------------' */
742 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
747 /* Draw the prompt */
748 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
750 for (i = r->offset; i < cs->length; ++i) {
752 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
755 r, x, NULL, 0, t, cs->completions[i].completion);
757 if (x > inner_width(r))
762 /* ,-----------------------------------------------------------------, */
764 /* |-----------------------------------------------------------------| */
766 /* |-----------------------------------------------------------------| */
768 /* `-----------------------------------------------------------------' */
770 draw_vertically(struct rendering *r, char *text, struct completions *cs)
775 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
777 for (i = r->offset; i < cs->length; ++i) {
779 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
782 r, y, NULL, 0, t, cs->completions[i].completion);
784 if (y > inner_height(r))
790 draw(struct rendering *r, char *text, struct completions *cs)
792 /* Draw the background */
793 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
794 inner_width(r), inner_height(r));
796 /* Draw the contents */
797 if (r->horizontal_layout)
798 draw_horizontally(r, text, cs);
800 draw_vertically(r, text, cs);
802 /* Draw the borders */
803 if (r->borders[0] != 0)
804 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
807 if (r->borders[1] != 0)
808 XFillRectangle(r->d, r->w, r->borders_bg[1],
809 r->width - r->borders[1], 0, r->borders[1],
812 if (r->borders[2] != 0)
813 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
814 r->height - r->borders[2], r->width, r->borders[2]);
816 if (r->borders[3] != 0)
817 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
818 r->borders[3], r->height);
824 /* Set some WM stuff */
826 set_win_atoms_hints(Display *d, Window w, int width, int height)
829 XClassHint *class_hint;
830 XSizeHints *size_hint;
832 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
833 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
834 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
835 (unsigned char *)&type, 1);
837 /* some window managers honor this properties */
838 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
839 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
840 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
841 (unsigned char *)&type, 1);
843 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
844 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
845 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
846 (unsigned char *)&type, 1);
848 /* Setting window hints */
849 class_hint = XAllocClassHint();
850 if (class_hint == NULL) {
851 fprintf(stderr, "Could not allocate memory for class hint\n");
852 exit(EX_UNAVAILABLE);
855 class_hint->res_name = resname;
856 class_hint->res_class = resclass;
857 XSetClassHint(d, w, class_hint);
860 size_hint = XAllocSizeHints();
861 if (size_hint == NULL) {
862 fprintf(stderr, "Could not allocate memory for size hint\n");
863 exit(EX_UNAVAILABLE);
866 size_hint->flags = PMinSize | PBaseSize;
867 size_hint->min_width = width;
868 size_hint->base_width = width;
869 size_hint->min_height = height;
870 size_hint->base_height = height;
875 /* Get the width and height of the window `w' */
877 get_wh(Display *d, Window *w, int *width, int *height)
879 XWindowAttributes win_attr;
881 XGetWindowAttributes(d, *w, &win_attr);
882 *height = win_attr.height;
883 *width = win_attr.width;
887 grabfocus(Display *d, Window w)
890 for (i = 0; i < 100; ++i) {
894 XGetInputFocus(d, &focuswin, &revert_to_win);
899 XSetInputFocus(d, w, RevertToParent, CurrentTime);
906 * I know this may seem a little hackish BUT is the only way I managed
907 * to actually grab that goddam keyboard. Only one call to
908 * XGrabKeyboard does not always end up with the keyboard grabbed!
911 take_keyboard(Display *d, Window w)
914 for (i = 0; i < 100; i++) {
915 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
921 fprintf(stderr, "Cannot grab keyboard\n");
926 parse_color(const char *str, const char *def)
937 /* +1 for the # ath the start */
938 if (*str != '#' || len > 9 || len < 4)
940 ++str; /* skip the # */
943 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
950 /* expand #rgb -> #rrggbb */
951 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
952 | (tmp.v & 0x00f) * 0x0011;
954 /* assume 0xff opacity */
957 } /* colors in #aarrggbb need no adjustments */
959 /* premultiply the alpha */
961 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
962 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
963 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
970 fprintf(stderr, "Invalid color: \"%s\".\n", str);
972 return parse_color(def, NULL);
978 * Given a string try to parse it as a number or return `default_value'.
981 parse_integer(const char *str, int default_value)
987 lval = strtol(str, &ep, 10);
989 if (str[0] == '\0' || *ep != '\0') { /* NaN */
991 "'%s' is not a valid number! Using %d as default.\n",
993 return default_value;
996 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
997 || (lval > INT_MAX || lval < INT_MIN)) {
998 fprintf(stderr, "%s out of range! Using %d as default.\n",
1000 return default_value;
1006 /* Like parse_integer but recognize the percentages (i.e. strings ending with
1009 parse_int_with_percentage(const char *str, int default_value, int max)
1011 int len = strlen(str);
1013 if (len > 0 && str[len - 1] == '%') {
1018 check_allocation(cpy);
1019 cpy[len - 1] = '\0';
1020 val = parse_integer(cpy, default_value);
1022 return val * max / 100;
1025 return parse_integer(str, default_value);
1029 * Like parse_int_with_percentage but understands some special values:
1030 * - middle that is (max-self)/2
1032 * - end that is (max-self)
1035 parse_int_with_pos(const char *str, int default_value, int max, int self)
1037 if (!strcmp(str, "start"))
1039 if (!strcmp(str, "middle"))
1040 return (max - self) / 2;
1041 if (!strcmp(str, "end"))
1043 return parse_int_with_percentage(str, default_value, max);
1046 /* Parse a string like a CSS value. */
1047 /* TODO: harden a bit this function */
1049 parse_csslike(const char *str)
1052 char *s, *token, **ret;
1059 ret = malloc(4 * sizeof(char *));
1065 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1066 ret[i] = strdup(token);
1069 for (j = 1; j < 4; j++)
1070 ret[j] = strdup(ret[0]);
1073 ret[2] = strdup(ret[0]);
1074 ret[3] = strdup(ret[1]);
1078 ret[3] = strdup(ret[1]);
1080 /* before we didn't check for the return type of strdup, here we will
1084 for (i = 0; i < 4; ++i)
1085 any_null = ret[i] == NULL || any_null;
1088 for (i = 0; i < 4; ++i)
1092 if (i == 0 || any_null) {
1102 * Given an event, try to understand what the users wants. If the
1103 * return value is ADD_CHAR then `input' is a pointer to a string that
1104 * will need to be free'ed later.
1107 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1109 char str[SYM_BUF_SIZE] = { 0 };
1112 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1115 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1116 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1118 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1121 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1124 /* Try to read what key was pressed */
1126 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1127 if (s == XBufferOverflow) {
1129 "Buffer overflow when trying to create keyboard "
1134 if (ev->state & ControlMask) {
1135 if (!strcmp(str, "")) /* C-u */
1137 if (!strcmp(str, "")) /* C-w */
1139 if (!strcmp(str, "")) /* C-h */
1141 if (!strcmp(str, "\r")) /* C-m */
1142 return CONFIRM_CONTINUE;
1143 if (!strcmp(str, "")) /* C-p */
1145 if (!strcmp(str, "")) /* C-n */
1147 if (!strcmp(str, "")) /* C-c */
1149 if (!strcmp(str, "\t")) /* C-i */
1150 return TOGGLE_FIRST_SELECTED;
1153 *input = strdup(str);
1154 if (*input == NULL) {
1155 fprintf(stderr, "Error while allocating memory for key.\n");
1163 confirm(enum state *status, struct rendering *r, struct completions *cs,
1164 char **text, int *textlen)
1166 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1167 /* if there is something selected expand it and return */
1168 int index = cs->selected == -1 ? 0 : cs->selected;
1169 struct completion *c = cs->completions;
1183 if (*text == NULL) {
1184 fprintf(stderr, "Memory allocation error\n");
1188 *textlen = strlen(*text);
1192 if (!r->free_text) /* cannot accept arbitrary text */
1198 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1199 char **lines, char **vlines)
1201 enum state status = LOOPING;
1203 while (status == LOOPING) {
1205 XNextEvent(r->d, &e);
1207 if (XFilterEvent(&e, r->w))
1212 XRefreshKeyboardMapping(&e.xmapping);
1217 if (e.xfocus.window != r->w)
1218 grabfocus(r->d, r->w);
1221 case VisibilityNotify:
1222 if (e.xvisibility.state != VisibilityUnobscured)
1223 XRaiseWindow(r->d, r->w);
1227 get_wh(r->d, &r->w, &r->width, &r->height);
1232 XKeyPressedEvent *ev = (XKeyPressedEvent *)&e;
1235 switch (parse_event(r->d, ev, r->xic, &input)) {
1242 confirm(&status, r, cs, text, textlen);
1246 case CONFIRM_CONTINUE: {
1248 confirm(&status, r, cs, text, textlen);
1253 complete(cs, r->first_selected, 1, text,
1255 r->offset = cs->selected;
1260 complete(cs, r->first_selected, 0, text,
1262 r->offset = cs->selected;
1268 update_completions(cs, *text, lines, vlines,
1275 update_completions(cs, *text, lines, vlines,
1282 for (i = 0; i < *textlen; ++i)
1284 update_completions(cs, *text, lines, vlines,
1293 str_len = strlen(input);
1296 * sometimes a strange key is pressed
1297 * i.e. ctrl alone), so input will be
1298 * empty. Don't need to update
1299 * completion in that case
1304 for (i = 0; i < str_len; ++i) {
1306 text, *textlen, input[i]);
1307 if (*textlen == -1) {
1309 "Memory allocation "
1316 if (status != ERR) {
1317 update_completions(cs, *text, lines,
1318 vlines, r->first_selected);
1326 case TOGGLE_FIRST_SELECTED:
1327 r->first_selected = !r->first_selected;
1328 if (r->first_selected && cs->selected < 0)
1330 if (!r->first_selected && cs->selected == 0)
1337 XButtonPressedEvent *ev = (XButtonPressedEvent *)&e;
1338 /* if (ev->button == Button1) { /\* click *\/ */
1339 /* int x = ev->x - r.border_w; */
1340 /* int y = ev->y - r.border_n; */
1341 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1344 if (ev->button == Button4) /* scroll up */
1345 r->offset = MAX((ssize_t)r->offset - 1, 0);
1347 if (ev->button == Button5) /* scroll down */
1349 = MIN(r->offset + 1, cs->length - 1);
1362 load_font(struct rendering *r, const char *fontname)
1365 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1368 char **missing_charset_list;
1369 int missing_charset_count;
1371 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1372 &missing_charset_count, NULL);
1373 if (r->font != NULL)
1376 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1378 if (!strcmp(fontname, default_fontname))
1381 return load_font(r, default_fontname);
1386 xim_init(struct rendering *r, XrmDatabase *xdb)
1388 XIMStyle best_match_style;
1392 /* Open the X input method */
1393 r->xim = XOpenIM(r->d, *xdb, resname, resclass);
1394 check_allocation(r->xim);
1396 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1397 fprintf(stderr, "Input Styles could not be retrieved\n");
1398 exit(EX_UNAVAILABLE);
1401 best_match_style = 0;
1402 for (i = 0; i < xis->count_styles; ++i) {
1403 XIMStyle ts = xis->supported_styles[i];
1404 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1405 best_match_style = ts;
1411 if (!best_match_style)
1413 "No matching input style could be determined\n");
1415 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1416 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1417 check_allocation(r->xic);
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;
1427 /* Create the window */
1428 attr.colormap = cmap;
1429 attr.override_redirect = 1;
1430 attr.border_pixel = 0;
1431 attr.background_pixel = background_pixel;
1432 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1433 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1435 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1436 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1437 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1438 | CWOverrideRedirect,
1443 ps1extents(struct rendering *r)
1446 dup = strdupn(r->ps1);
1448 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, *buf, **vlines;
1487 char *fontname, *text, *xrm;
1490 /* stdio & rpath: to read/write stdio/stdout/stderr */
1491 /* unix: to connect to XOrg */
1492 pledge("stdio rpath unix", "");
1496 parent_window_id = NULL;
1498 r.first_selected = 0;
1500 r.multiple_select = 0;
1503 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1505 case 'h': /* help */
1508 case 'v': /* version */
1509 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1511 case 'e': /* embed */
1512 parent_window_id = strdup(optarg);
1513 check_allocation(parent_window_id);
1516 sep = strdup(optarg);
1517 check_allocation(sep);
1522 r.multiple_select = 1;
1529 /* Read the completions */
1532 nlines = readlines(&lines, &buf);
1538 vlines = calloc(nlines, sizeof(char *));
1539 check_allocation(vlines);
1541 for (i = 0; i < nlines; i++) {
1543 t = strstr(lines[i], sep);
1545 vlines[i] = lines[i];
1551 setlocale(LC_ALL, getenv("LANG"));
1555 /* where the monitor start (used only with xinerama) */
1556 offset_x = offset_y = 0;
1558 /* default width and height */
1562 /* default position on the screen */
1565 for (i = 0; i < 4; ++i) {
1566 /* default paddings */
1567 r.p_padding[i] = 10;
1568 r.c_padding[i] = 10;
1569 r.ch_padding[i] = 10;
1571 /* default borders */
1575 r.ch_borders[i] = 0;
1578 /* the prompt. We duplicate the string so later is easy to
1579 * free (in the case it's been overwritten by the user) */
1580 r.ps1 = strdup("$ ");
1581 check_allocation(r.ps1);
1583 /* same for the font name */
1584 fontname = strdup(default_fontname);
1585 check_allocation(fontname);
1588 text = malloc(textlen * sizeof(char));
1589 check_allocation(text);
1591 /* struct completions *cs = filter(text, lines); */
1592 cs = compls_new(nlines);
1593 check_allocation(cs);
1595 /* start talking to xorg */
1596 r.d = XOpenDisplay(NULL);
1598 fprintf(stderr, "Could not open display!\n");
1599 return EX_UNAVAILABLE;
1603 if (!(parent_window_id
1604 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1605 parent_window = DefaultRootWindow(r.d);
1609 /* get display size */
1610 get_wh(r.d, &parent_window, &d_width, &d_height);
1613 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1614 XineramaScreenInfo *info;
1617 int number_of_screens, monitors, i;
1618 int root_x, root_y, win_x, win_y;
1622 number_of_screens = XScreenCount(r.d);
1623 for (i = 0; i < number_of_screens; ++i) {
1624 root = XRootWindow(r.d, i);
1625 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1626 &root_y, &win_x, &win_y, &mask);
1632 fprintf(stderr, "No mouse found.\n");
1637 /* Now find in which monitor the mice is */
1638 info = XineramaQueryScreens(r.d, &monitors);
1640 for (i = 0; i < monitors; ++i) {
1641 if (info[i].x_org <= root_x
1642 && root_x <= (info[i].x_org
1644 && info[i].y_org <= root_y
1645 && root_y <= (info[i].y_org
1646 + info[i].height)) {
1647 offset_x = info[i].x_org;
1648 offset_y = info[i].y_org;
1649 d_width = info[i].width;
1650 d_height = info[i].height;
1659 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1660 cmap = XCreateColormap(
1661 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1663 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1664 fgs[2] = parse_color("#000", NULL);
1666 bgs[0] = bgs[1] = parse_color("#000", NULL);
1667 bgs[2] = parse_color("#fff", NULL);
1669 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1670 = parse_color("#000", NULL);
1672 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1673 = parse_color("#000", NULL);
1674 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1675 = parse_color("#000", NULL);
1676 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1677 = ch_borders_bg[3] = parse_color("#000", NULL);
1679 r.horizontal_layout = 1;
1681 /* Read the resources */
1683 xrm = XResourceManagerString(r.d);
1689 xdb = XrmGetStringDatabase(xrm);
1691 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1694 fontname = strdup(value.addr);
1695 check_allocation(fontname);
1697 fprintf(stderr, "no font defined, using %s\n",
1702 xdb, "MyMenu.layout", "*", datatype, &value)
1705 = !strcmp(value.addr, "horizontal");
1708 "no layout defined, using horizontal\n");
1711 xdb, "MyMenu.prompt", "*", datatype, &value)
1714 r.ps1 = normalize_str(value.addr);
1717 "no prompt defined, using \"%s\" as "
1722 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1726 sizes = parse_csslike(value.addr);
1728 for (i = 0; i < 4; ++i)
1730 = parse_integer(sizes[i], 0);
1733 "error while parsing "
1734 "MyMenu.prompt.border.size");
1737 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1741 colors = parse_csslike(value.addr);
1743 for (i = 0; i < 4; ++i)
1744 p_borders_bg[i] = parse_color(
1748 "error while parsing "
1749 "MyMenu.prompt.border.color");
1752 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1756 colors = parse_csslike(value.addr);
1758 for (i = 0; i < 4; ++i)
1760 = parse_integer(colors[i], 0);
1763 "error while parsing "
1764 "MyMenu.prompt.padding");
1767 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1769 r.width = parse_int_with_percentage(
1770 value.addr, r.width, d_width);
1772 fprintf(stderr, "no width defined, using %d\n",
1776 xdb, "MyMenu.height", "*", datatype, &value)
1778 r.height = parse_int_with_percentage(
1779 value.addr, r.height, d_height);
1781 fprintf(stderr, "no height defined, using %d\n",
1784 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1786 x = parse_int_with_pos(
1787 value.addr, x, d_width, r.width);
1789 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1791 y = parse_int_with_pos(
1792 value.addr, y, d_height, r.height);
1795 xdb, "MyMenu.border.size", "*", datatype, &value)
1798 borders = parse_csslike(value.addr);
1799 if (borders != NULL)
1800 for (i = 0; i < 4; ++i)
1802 = parse_int_with_percentage(
1809 "error while parsing "
1810 "MyMenu.border.size\n");
1814 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1817 fgs[0] = parse_color(value.addr, "#fff");
1819 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1822 bgs[0] = parse_color(value.addr, "#000");
1825 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1828 fgs[1] = parse_color(value.addr, "#fff");
1830 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1833 bgs[1] = parse_color(value.addr, "#000");
1835 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1839 paddings = parse_csslike(value.addr);
1840 if (paddings != NULL)
1841 for (i = 0; i < 4; ++i)
1842 r.c_padding[i] = parse_integer(
1846 "Error while parsing "
1847 "MyMenu.completion.padding");
1850 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1854 sizes = parse_csslike(value.addr);
1856 for (i = 0; i < 4; ++i)
1858 = parse_integer(sizes[i], 0);
1861 "Error while parsing "
1862 "MyMenu.completion.border.size");
1865 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1869 sizes = parse_csslike(value.addr);
1871 for (i = 0; i < 4; ++i)
1872 c_borders_bg[i] = parse_color(
1876 "Error while parsing "
1877 "MyMenu.completion.border.color");
1880 /* Completion Highlighted */
1881 if (XrmGetResource(xdb,
1882 "MyMenu.completion_highlighted.foreground", "*",
1885 fgs[2] = parse_color(value.addr, "#000");
1887 if (XrmGetResource(xdb,
1888 "MyMenu.completion_highlighted.background", "*",
1891 bgs[2] = parse_color(value.addr, "#fff");
1893 if (XrmGetResource(xdb,
1894 "MyMenu.completion_highlighted.padding", "*",
1898 paddings = parse_csslike(value.addr);
1899 if (paddings != NULL)
1900 for (i = 0; i < 4; ++i)
1901 r.ch_padding[i] = parse_integer(
1905 "Error while parsing "
1906 "MyMenu.completion_highlighted."
1910 if (XrmGetResource(xdb,
1911 "MyMenu.completion_highlighted.border.size", "*",
1915 sizes = parse_csslike(value.addr);
1917 for (i = 0; i < 4; ++i)
1919 = parse_integer(sizes[i], 0);
1922 "Error while parsing "
1923 "MyMenu.completion_highlighted."
1927 if (XrmGetResource(xdb,
1928 "MyMenu.completion_highlighted.border.color", "*",
1932 colors = parse_csslike(value.addr);
1934 for (i = 0; i < 4; ++i)
1935 ch_borders_bg[i] = parse_color(
1939 "Error while parsing "
1940 "MyMenu.completion_highlighted."
1946 xdb, "MyMenu.border.color", "*", datatype, &value)
1949 colors = parse_csslike(value.addr);
1951 for (i = 0; i < 4; ++i)
1952 borders_bg[i] = parse_color(
1956 "error while parsing "
1957 "MyMenu.border.color\n");
1961 /* Second round of args parsing */
1962 optind = 0; /* reset the option index */
1963 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1966 r.first_selected = 1;
1969 /* free_text -- already catched */
1971 /* separator -- this case was already catched */
1973 /* embedding mymenu this case was already catched. */
1975 /* multiple selection this case was already catched.
1980 newprompt = strdup(optarg);
1981 if (newprompt != NULL) {
1988 x = parse_int_with_pos(optarg, x, d_width, r.width);
1991 y = parse_int_with_pos(optarg, y, d_height, r.height);
1995 if ((paddings = parse_csslike(optarg)) != NULL)
1996 for (i = 0; i < 4; ++i)
1997 r.p_padding[i] = parse_integer(
2003 if ((colors = parse_csslike(optarg)) != NULL)
2004 for (i = 0; i < 4; ++i)
2005 p_borders_bg[i] = parse_color(
2011 if ((sizes = parse_csslike(optarg)) != NULL)
2012 for (i = 0; i < 4; ++i)
2014 = parse_integer(sizes[i], 0);
2019 if ((colors = parse_csslike(optarg)) != NULL)
2020 for (i = 0; i < 4; ++i)
2021 c_borders_bg[i] = parse_color(
2027 if ((sizes = parse_csslike(optarg)) != NULL)
2028 for (i = 0; i < 4; ++i)
2030 = parse_integer(sizes[i], 0);
2035 if ((colors = parse_csslike(optarg)) != NULL)
2036 for (i = 0; i < 4; ++i)
2037 ch_borders_bg[i] = parse_color(
2043 if ((sizes = parse_csslike(optarg)) != NULL)
2044 for (i = 0; i < 4; ++i)
2046 = parse_integer(sizes[i], 0);
2050 r.horizontal_layout = !strcmp(optarg, "horizontal");
2054 if ((newfont = strdup(optarg)) != NULL) {
2061 r.width = parse_int_with_percentage(
2062 optarg, r.width, d_width);
2065 r.height = parse_int_with_percentage(
2066 optarg, r.height, d_height);
2070 if ((borders = parse_csslike(optarg)) != NULL) {
2071 for (i = 0; i < 4; ++i)
2072 r.borders[i] = parse_integer(
2075 fprintf(stderr, "Error parsing b option\n");
2080 if ((colors = parse_csslike(optarg)) != NULL) {
2081 for (i = 0; i < 4; ++i)
2082 borders_bg[i] = parse_color(
2086 "error while parsing B option\n");
2090 fgs[0] = parse_color(optarg, NULL);
2093 bgs[0] = parse_color(optarg, NULL);
2096 fgs[1] = parse_color(optarg, NULL);
2099 bgs[1] = parse_color(optarg, NULL);
2102 fgs[2] = parse_color(optarg, NULL);
2105 fgs[2] = parse_color(optarg, NULL);
2108 fprintf(stderr, "Unrecognized option %c\n", ch);
2114 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2115 fprintf(stderr, "height, width, x or y are lesser than 0.");
2119 /* since only now we know if the first should be selected,
2120 * update the completion here */
2121 update_completions(cs, text, lines, vlines, r.first_selected);
2123 /* update the prompt lenght, only now we surely know the length of it
2125 r.ps1len = strlen(r.ps1);
2127 /* Create the window */
2128 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2130 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2131 XMapRaised(r.d, r.w);
2133 /* If embed, listen for other events as well */
2135 Window *children, parent, root;
2136 unsigned int children_no;
2138 XSelectInput(r.d, parent_window, FocusChangeMask);
2139 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2142 for (i = 0; i < children_no && children[i] != r.w;
2145 r.d, children[i], FocusChangeMask);
2148 grabfocus(r.d, r.w);
2151 take_keyboard(r.d, r.w);
2153 r.x_zero = r.borders[3];
2154 r.y_zero = r.borders[0];
2159 for (i = 0; i < 3; ++i) {
2160 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2161 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2164 for (i = 0; i < 4; ++i) {
2165 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2166 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2167 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2168 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2172 /* Load the colors in our GCs */
2173 for (i = 0; i < 3; ++i) {
2174 XSetForeground(r.d, r.fgs[i], fgs[i]);
2175 XSetForeground(r.d, r.bgs[i], bgs[i]);
2178 for (i = 0; i < 4; ++i) {
2179 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2180 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2181 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2182 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2185 if (load_font(&r, fontname) == -1)
2189 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2191 for (i = 0; i < 3; ++i) {
2193 XRenderColor xrcolor;
2195 c = *(rgba_t *)&fgs[i];
2196 xrcolor.red = EXPANDBITS(c.rgba.r);
2197 xrcolor.green = EXPANDBITS(c.rgba.g);
2198 xrcolor.blue = EXPANDBITS(c.rgba.b);
2199 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2201 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2205 /* compute prompt dimensions */
2211 /* Now we need only the ability to write */
2212 pledge("stdio", "");
2215 /* Cache text height */
2216 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2218 /* Draw the window for the first time */
2222 while (status == LOOPING || status == OK_LOOP) {
2223 status = loop(&r, &text, &textlen, cs, lines, vlines);
2226 printf("%s\n", text);
2228 if (!r.multiple_select && status == OK_LOOP)
2232 XUngrabKeyboard(r.d, CurrentTime);
2235 for (i = 0; i < 3; ++i)
2236 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2239 for (i = 0; i < 3; ++i) {
2240 XFreeGC(r.d, r.fgs[i]);
2241 XFreeGC(r.d, r.bgs[i]);
2244 for (i = 0; i < 4; ++i) {
2245 XFreeGC(r.d, r.borders_bg[i]);
2246 XFreeGC(r.d, r.p_borders_bg[i]);
2247 XFreeGC(r.d, r.c_borders_bg[i]);
2248 XFreeGC(r.d, r.ch_borders_bg[i]);
2255 for (i = 0; i < 3; ++i)
2256 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2257 XftFontClose(r.d, r.font);
2258 XftDrawDestroy(r.xftdraw);
2260 XFreeFontSet(r.d, r.font);
2272 XFreeColormap(r.d, cmap);
2274 XDestroyWindow(r.d, r.w);
2277 return status != OK;