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>
20 #include <X11/extensions/Xinerama.h>
24 #include <X11/Xft/Xft.h>
28 #define VERSION "unknown"
31 #define resname "MyMenu"
32 #define resclass "mymenu"
34 #define SYM_BUF_SIZE 4
37 #define default_fontname "monospace"
39 #define default_fontname "fixed"
42 #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:"
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
50 * If we don't have or we don't want an "ignore case" completion
51 * style, fall back to `strstr(3)`
53 #ifndef USE_STRCASESTR
54 #define strcasestr strstr
57 /* The number of char to read */
58 #define STDIN_CHUNKS 128
60 /* The number of lines to allocate in advance */
61 #define LINES_CHUNK 64
63 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
64 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
66 /* The states of the event loop */
67 enum state { LOOPING, OK_LOOP, OK, ERR };
70 * For the drawing-related function. The text to be rendere could be
71 * the prompt, a completion or a highlighted completion
73 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
75 /* These are the possible action to be performed after user input. */
89 /* A big set of values that needs to be carried around for drawing. A
90 big struct to rule them all */
92 Display *d; /* Connection to xorg */
100 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
102 int y_zero; /* like x_zero but for the y axis */
104 size_t offset; /* scroll offset */
107 short first_selected;
108 short multiple_select;
110 /* four border width */
116 short horizontal_layout;
121 int ps1w; /* ps1 width */
122 int ps1h; /* ps1 height */
124 int text_height; /* cache for the vertical layout */
138 XftColor xft_colors[3];
149 /* Wrap the linked list of completions */
151 struct completion *completions;
156 /* idea stolen from lemonbar. ty lemonboy */
170 /* Return a newly allocated (and empty) completion list */
172 compls_new(size_t length)
174 struct completions *cs = malloc(sizeof(struct completions));
179 cs->completions = calloc(length, sizeof(struct completion));
180 if (cs->completions == NULL) {
190 /* Delete the wrapper and the whole list */
192 compls_delete(struct completions *cs)
197 free(cs->completions);
202 * Create a completion list from a text and the list of possible
203 * completions (null terminated). Expects a non-null `cs'. `lines' and
204 * `vlines' should have the same length OR `vlines' is NULL.
207 filter(struct completions *cs, char *text, char **lines, char **vlines)
217 if (lines[index] == NULL)
220 l = vlines[index] != NULL ? vlines[index] : lines[index];
222 if (strcasestr(l, text) != NULL) {
223 struct completion *c = &cs->completions[matching];
225 c->rcompletion = lines[index];
231 cs->length = matching;
235 /* Update the given completion */
237 update_completions(struct completions *cs, char *text, char **lines,
238 char **vlines, short first_selected)
240 filter(cs, text, lines, vlines);
241 if (first_selected && cs->length > 0)
246 * Select the next or previous selection and update some state. `text'
247 * will be updated with the text of the completion and `textlen' with
248 * the new length. If the memory cannot be allocated `status' will be
252 complete(struct completions *cs, short first_selected, short p, char **text,
253 int *textlen, enum state *status)
255 struct completion *n;
258 if (cs == NULL || cs->length == 0)
262 * If the first is always selected and the first entry is
263 * different from the text, expand the text and return
265 if (first_selected && cs->selected == 0
266 && strcmp(cs->completions->completion, *text) != 0 && !p) {
268 *text = strdup(cs->completions->completion);
273 *textlen = strlen(*text);
277 index = cs->selected;
279 if (index == -1 && p)
282 = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
284 n = &cs->completions[cs->selected];
287 *text = strdup(n->completion);
289 fprintf(stderr, "Memory allocation error!\n");
293 *textlen = strlen(*text);
296 /* Push the character c at the end of the string pointed by p */
298 pushc(char **p, int maxlen, char c)
302 len = strnlen(*p, maxlen);
303 if (!(len < maxlen - 2)) {
306 maxlen += maxlen >> 1;
307 newptr = realloc(*p, maxlen);
308 if (newptr == NULL) /* bad */
314 (*p)[len + 1] = '\0';
319 * Remove the last rune from the *UTF-8* string! This is different
320 * from just setting the last byte to 0 (in some cases ofc). Return a
321 * pointer (e) to the last nonzero char. If e < p then p is empty!
341 * If c is a starting byte (11......) or is under
344 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
351 /* Remove the last word plus trailing white spaces from the given string */
358 if ((len = strlen(w)) == 0)
367 if (in_word && isspace(*e))
370 if (!in_word && !isspace(*e))
376 * If the string is surrounded by quates (`"') remove them and replace
377 * every `\"' in the string with a single double-quote.
380 normalize_str(const char *str)
385 if ((len = strlen(str)) == 0)
388 if ((s = calloc(len, sizeof(char))) == NULL)
399 str += 2; /* skip this and the next char */
405 str++; /* skip only this char */
417 read_stdin(char **buf)
420 size_t len = STDIN_CHUNKS;
422 *buf = malloc(len * sizeof(char));
430 r = read(0, *buf + offset, STDIN_CHUNKS);
438 *buf = realloc(*buf, len);
442 for (i = offset; i < len; ++i)
447 fprintf(stderr, "Error in allocating memory for stdin.\n");
448 exit(EX_UNAVAILABLE);
452 readlines(char ***lns, char **buf)
454 size_t i, len, ll, lines;
460 len = read_stdin(buf);
463 *lns = malloc(ll * sizeof(char *));
468 for (i = 0; i < len; i++) {
477 if (in_line && c == '\n')
480 if (!in_line && c != '\n') {
482 (*lns)[lines] = (*buf) + i;
485 if (lines == ll) { /* resize */
487 *lns = realloc(*lns, ll * sizeof(char *));
494 (*lns)[lines] = NULL;
499 fprintf(stderr, "Error in memory allocation.\n");
500 exit(EX_UNAVAILABLE);
504 * Compute the dimensions of the string str once rendered.
505 * It'll return the width and set ret_width and ret_height if not NULL
508 text_extents(char *str, int len, struct rendering *r, int *ret_width,
514 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
515 height = r->font->ascent - r->font->descent;
516 width = gi.width - gi.x;
519 XmbTextExtents(r->font, str, len, NULL, &rect);
520 height = rect.height;
523 if (ret_width != NULL)
525 if (ret_height != NULL)
526 *ret_height = height;
531 draw_string(char *str, int len, int x, int y, struct rendering *r,
537 xftcolor = r->xft_colors[0];
539 xftcolor = r->xft_colors[1];
540 if (tt == COMPL_HIGH)
541 xftcolor = r->xft_colors[2];
543 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
550 if (tt == COMPL_HIGH)
552 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
556 /* Duplicate the string and substitute every space with a 'n` */
565 if (str == NULL || len == 0)
568 if ((dup = strdup(str)) == NULL)
571 for (i = 0; i < len; ++i)
579 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
580 enum obj_type t, char *text)
582 GC *border_color, bg;
583 int *padding, *borders;
584 int ret = 0, inner_width, inner_height, x;
588 border_color = r->p_borders_bg;
589 padding = r->p_padding;
590 borders = r->p_borders;
594 border_color = r->c_borders_bg;
595 padding = r->c_padding;
596 borders = r->c_borders;
600 border_color = r->ch_borders_bg;
601 padding = r->ch_padding;
602 borders = r->ch_borders;
607 ret = borders[0] + padding[0] + r->text_height + padding[2]
610 inner_width = inner_width(r) - borders[1] - borders[3];
611 inner_height = padding[0] + r->text_height + padding[2];
614 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
618 XFillRectangle(r->d, r->w, border_color[1],
619 r->x_zero + inner_width(r) - borders[1], y, borders[1], ret);
622 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
623 y + borders[0] + padding[0] + r->text_height + padding[2],
624 r->width, borders[2]);
628 r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
631 x = r->x_zero + borders[3];
633 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
636 y += padding[0] + r->text_height;
638 if (prefix != NULL) {
639 draw_string(prefix, strlen(prefix), x, y, r, t);
642 draw_string(text, strlen(text), x, y, r, t);
648 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
649 enum obj_type t, char *text)
651 GC *border_color, bg;
652 int *padding, *borders;
653 int ret = 0, inner_width, inner_height, y, text_width;
657 border_color = r->p_borders_bg;
658 padding = r->p_padding;
659 borders = r->p_borders;
663 border_color = r->c_borders_bg;
664 padding = r->c_padding;
665 borders = r->c_borders;
669 border_color = r->ch_borders_bg;
670 padding = r->ch_padding;
671 borders = r->ch_borders;
676 if (padding[0] < 0 || padding[2] < 0)
677 padding[0] = padding[2]
678 = (inner_height(r) - borders[0] - borders[2]
682 /* If they are still lesser than 0, set 'em to 0 */
683 if (padding[0] < 0 || padding[2] < 0)
684 padding[0] = padding[2] = 0;
686 /* Get the text width */
687 text_extents(text, strlen(text), r, &text_width, NULL);
689 text_width += prefix_width;
691 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
693 inner_width = padding[3] + text_width + padding[1];
694 inner_height = inner_height(r) - borders[0] - borders[2];
698 r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
701 XFillRectangle(r->d, r->w, border_color[1],
702 x + borders[3] + inner_width, r->y_zero, borders[1],
706 XFillRectangle(r->d, r->w, border_color[2], x,
707 r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
710 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
715 y = r->y_zero + borders[0];
716 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
719 y += padding[0] + r->text_height;
721 if (prefix != NULL) {
722 draw_string(prefix, strlen(prefix), x, y, r, t);
725 draw_string(text, strlen(text), x, y, r, t);
730 /* ,-----------------------------------------------------------------, */
731 /* | 20 char text | completion | completion | completion | compl | */
732 /* `-----------------------------------------------------------------' */
734 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
739 /* Draw the prompt */
740 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
742 for (i = r->offset; i < cs->length; ++i) {
744 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
747 r, x, NULL, 0, t, cs->completions[i].completion);
749 if (x > inner_width(r))
754 /* ,-----------------------------------------------------------------, */
756 /* |-----------------------------------------------------------------| */
758 /* |-----------------------------------------------------------------| */
760 /* `-----------------------------------------------------------------' */
762 draw_vertically(struct rendering *r, char *text, struct completions *cs)
767 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
769 for (i = r->offset; i < cs->length; ++i) {
771 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
774 r, y, NULL, 0, t, cs->completions[i].completion);
776 if (y > inner_height(r))
782 draw(struct rendering *r, char *text, struct completions *cs)
784 /* Draw the background */
785 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
786 inner_width(r), inner_height(r));
788 /* Draw the contents */
789 if (r->horizontal_layout)
790 draw_horizontally(r, text, cs);
792 draw_vertically(r, text, cs);
794 /* Draw the borders */
795 if (r->borders[0] != 0)
796 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
799 if (r->borders[1] != 0)
800 XFillRectangle(r->d, r->w, r->borders_bg[1],
801 r->width - r->borders[1], 0, r->borders[1],
804 if (r->borders[2] != 0)
805 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
806 r->height - r->borders[2], r->width, r->borders[2]);
808 if (r->borders[3] != 0)
809 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
810 r->borders[3], r->height);
816 /* Set some WM stuff */
818 set_win_atoms_hints(Display *d, Window w, int width, int height)
821 XClassHint *class_hint;
822 XSizeHints *size_hint;
824 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
825 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
826 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
827 (unsigned char *)&type, 1);
829 /* some window managers honor this properties */
830 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
831 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
832 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
833 (unsigned char *)&type, 1);
835 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
836 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
837 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
838 (unsigned char *)&type, 1);
840 /* Setting window hints */
841 class_hint = XAllocClassHint();
842 if (class_hint == NULL) {
843 fprintf(stderr, "Could not allocate memory for class hint\n");
844 exit(EX_UNAVAILABLE);
847 class_hint->res_name = resname;
848 class_hint->res_class = resclass;
849 XSetClassHint(d, w, class_hint);
852 size_hint = XAllocSizeHints();
853 if (size_hint == NULL) {
854 fprintf(stderr, "Could not allocate memory for size hint\n");
855 exit(EX_UNAVAILABLE);
858 size_hint->flags = PMinSize | PBaseSize;
859 size_hint->min_width = width;
860 size_hint->base_width = width;
861 size_hint->min_height = height;
862 size_hint->base_height = height;
867 /* Get the width and height of the window `w' */
869 get_wh(Display *d, Window *w, int *width, int *height)
871 XWindowAttributes win_attr;
873 XGetWindowAttributes(d, *w, &win_attr);
874 *height = win_attr.height;
875 *width = win_attr.width;
879 grabfocus(Display *d, Window w)
882 for (i = 0; i < 100; ++i) {
886 XGetInputFocus(d, &focuswin, &revert_to_win);
891 XSetInputFocus(d, w, RevertToParent, CurrentTime);
898 * I know this may seem a little hackish BUT is the only way I managed
899 * to actually grab that goddam keyboard. Only one call to
900 * XGrabKeyboard does not always end up with the keyboard grabbed!
903 take_keyboard(Display *d, Window w)
906 for (i = 0; i < 100; i++) {
907 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
913 fprintf(stderr, "Cannot grab keyboard\n");
918 parse_color(const char *str, const char *def)
929 /* +1 for the # ath the start */
930 if (*str != '#' || len > 9 || len < 4)
932 ++str; /* skip the # */
935 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
942 /* expand #rgb -> #rrggbb */
943 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
944 | (tmp.v & 0x00f) * 0x0011;
946 /* assume 0xff opacity */
949 } /* colors in #aarrggbb need no adjustments */
951 /* premultiply the alpha */
953 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
954 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
955 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
962 fprintf(stderr, "Invalid color: \"%s\".\n", str);
964 return parse_color(def, NULL);
970 * Given a string try to parse it as a number or return `default_value'.
973 parse_integer(const char *str, int default_value)
979 lval = strtol(str, &ep, 10);
981 if (str[0] == '\0' || *ep != '\0') { /* NaN */
983 "'%s' is not a valid number! Using %d as default.\n",
985 return default_value;
988 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
989 || (lval > INT_MAX || lval < INT_MIN)) {
990 fprintf(stderr, "%s out of range! Using %d as default.\n",
992 return default_value;
998 /* Like parse_integer but recognize the percentages (i.e. strings ending with
1001 parse_int_with_percentage(const char *str, int default_value, int max)
1003 int len = strlen(str);
1005 if (len > 0 && str[len - 1] == '%') {
1009 if ((cpy = strdup(str)) == NULL)
1012 cpy[len - 1] = '\0';
1013 val = parse_integer(cpy, default_value);
1015 return val * max / 100;
1018 return parse_integer(str, default_value);
1022 * Like parse_int_with_percentage but understands some special values:
1023 * - middle that is (max-self)/2
1025 * - end that is (max-self)
1028 parse_int_with_pos(const char *str, int default_value, int max, int self)
1030 if (!strcmp(str, "start"))
1032 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1033 return (max - self) / 2;
1034 if (!strcmp(str, "end"))
1036 return parse_int_with_percentage(str, default_value, max);
1039 /* Parse a string like a CSS value. */
1040 /* TODO: harden a bit this function */
1042 parse_csslike(const char *str)
1045 char *s, *token, **ret;
1052 ret = malloc(4 * sizeof(char *));
1058 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1059 ret[i] = strdup(token);
1062 for (j = 1; j < 4; j++)
1063 ret[j] = strdup(ret[0]);
1066 ret[2] = strdup(ret[0]);
1067 ret[3] = strdup(ret[1]);
1071 ret[3] = strdup(ret[1]);
1073 /* before we didn't check for the return type of strdup, here we will
1077 for (i = 0; i < 4; ++i)
1078 any_null = ret[i] == NULL || any_null;
1081 for (i = 0; i < 4; ++i)
1085 if (i == 0 || any_null) {
1095 * Given an event, try to understand what the users wants. If the
1096 * return value is ADD_CHAR then `input' is a pointer to a string that
1097 * will need to be free'ed later.
1100 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1102 char str[SYM_BUF_SIZE] = { 0 };
1105 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1108 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1109 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1111 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1114 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1117 /* Try to read what key was pressed */
1119 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1120 if (s == XBufferOverflow) {
1122 "Buffer overflow when trying to create keyboard "
1127 if (ev->state & ControlMask) {
1128 if (!strcmp(str, "")) /* C-u */
1130 if (!strcmp(str, "")) /* C-w */
1132 if (!strcmp(str, "")) /* C-h */
1134 if (!strcmp(str, "\r")) /* C-m */
1135 return CONFIRM_CONTINUE;
1136 if (!strcmp(str, "")) /* C-p */
1138 if (!strcmp(str, "")) /* C-n */
1140 if (!strcmp(str, "")) /* C-c */
1142 if (!strcmp(str, "\t")) /* C-i */
1143 return TOGGLE_FIRST_SELECTED;
1146 *input = strdup(str);
1147 if (*input == NULL) {
1148 fprintf(stderr, "Error while allocating memory for key.\n");
1156 confirm(enum state *status, struct rendering *r, struct completions *cs,
1157 char **text, int *textlen)
1159 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1160 /* if there is something selected expand it and return */
1161 int index = cs->selected == -1 ? 0 : cs->selected;
1162 struct completion *c = cs->completions;
1176 if (*text == NULL) {
1177 fprintf(stderr, "Memory allocation error\n");
1181 *textlen = strlen(*text);
1185 if (!r->free_text) /* cannot accept arbitrary text */
1191 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1192 char **lines, char **vlines)
1194 enum state status = LOOPING;
1196 while (status == LOOPING) {
1198 XNextEvent(r->d, &e);
1200 if (XFilterEvent(&e, r->w))
1205 XRefreshKeyboardMapping(&e.xmapping);
1210 if (e.xfocus.window != r->w)
1211 grabfocus(r->d, r->w);
1214 case VisibilityNotify:
1215 if (e.xvisibility.state != VisibilityUnobscured)
1216 XRaiseWindow(r->d, r->w);
1220 get_wh(r->d, &r->w, &r->width, &r->height);
1225 XKeyPressedEvent *ev = (XKeyPressedEvent *)&e;
1228 switch (parse_event(r->d, ev, r->xic, &input)) {
1235 confirm(&status, r, cs, text, textlen);
1239 case CONFIRM_CONTINUE: {
1241 confirm(&status, r, cs, text, textlen);
1246 complete(cs, r->first_selected, 1, text,
1248 r->offset = cs->selected;
1253 complete(cs, r->first_selected, 0, text,
1255 r->offset = cs->selected;
1261 update_completions(cs, *text, lines, vlines,
1268 update_completions(cs, *text, lines, vlines,
1275 for (i = 0; i < *textlen; ++i)
1277 update_completions(cs, *text, lines, vlines,
1286 str_len = strlen(input);
1289 * sometimes a strange key is pressed
1290 * i.e. ctrl alone), so input will be
1291 * empty. Don't need to update
1292 * completion in that case
1297 for (i = 0; i < str_len; ++i) {
1299 text, *textlen, input[i]);
1300 if (*textlen == -1) {
1302 "Memory allocation "
1309 if (status != ERR) {
1310 update_completions(cs, *text, lines,
1311 vlines, r->first_selected);
1319 case TOGGLE_FIRST_SELECTED:
1320 r->first_selected = !r->first_selected;
1321 if (r->first_selected && cs->selected < 0)
1323 if (!r->first_selected && cs->selected == 0)
1330 XButtonPressedEvent *ev = (XButtonPressedEvent *)&e;
1331 /* if (ev->button == Button1) { /\* click *\/ */
1332 /* int x = ev->x - r.border_w; */
1333 /* int y = ev->y - r.border_n; */
1334 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1337 if (ev->button == Button4) /* scroll up */
1338 r->offset = MAX((ssize_t)r->offset - 1, 0);
1340 if (ev->button == Button5) /* scroll down */
1342 = MIN(r->offset + 1, cs->length - 1);
1355 load_font(struct rendering *r, const char *fontname)
1358 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1361 char **missing_charset_list;
1362 int missing_charset_count;
1364 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1365 &missing_charset_count, NULL);
1366 if (r->font != NULL)
1369 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1371 if (!strcmp(fontname, default_fontname))
1374 return load_font(r, default_fontname);
1379 xim_init(struct rendering *r, XrmDatabase *xdb)
1381 XIMStyle best_match_style;
1385 /* Open the X input method */
1386 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1389 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1390 fprintf(stderr, "Input Styles could not be retrieved\n");
1391 exit(EX_UNAVAILABLE);
1394 best_match_style = 0;
1395 for (i = 0; i < xis->count_styles; ++i) {
1396 XIMStyle ts = xis->supported_styles[i];
1397 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1398 best_match_style = ts;
1404 if (!best_match_style)
1406 "No matching input style could be determined\n");
1408 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1409 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1411 err(1, "XCreateIC");
1415 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1416 XVisualInfo vinfo, int x, int y, int ox, int oy,
1417 unsigned long background_pixel)
1419 XSetWindowAttributes attr;
1421 /* Create the window */
1422 attr.colormap = cmap;
1423 attr.override_redirect = 1;
1424 attr.border_pixel = 0;
1425 attr.background_pixel = background_pixel;
1426 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1427 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1429 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1430 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1431 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1432 | CWOverrideRedirect,
1437 ps1extents(struct rendering *r)
1440 dup = strdupn(r->ps1);
1442 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1447 usage(char *prgname)
1450 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1451 " [-d separator] [-e window] [-f font] [-G color] [-g "
1453 " [-H height] [-I color] [-i size] [-J color] [-j "
1454 "size] [-l layout]\n"
1455 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1457 " [-t color] [-W width] [-x coord] [-y coord]\n",
1462 main(int argc, char **argv)
1464 struct completions *cs;
1469 Window parent_window;
1471 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1472 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1473 ch_borders_bg[4]; /* N E S W */
1476 int offset_x, offset_y, x, y;
1477 int textlen, d_width, d_height;
1479 char *sep, *parent_window_id;
1480 char **lines, *buf, **vlines;
1481 char *fontname, *text, *xrm;
1484 /* stdio & rpath: to read/write stdio/stdout/stderr */
1485 /* unix: to connect to XOrg */
1486 pledge("stdio rpath unix", "");
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 /* Read the completions */
1527 nlines = readlines(&lines, &buf);
1533 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1536 for (i = 0; i < nlines; i++) {
1538 t = strstr(lines[i], sep);
1540 vlines[i] = lines[i];
1546 setlocale(LC_ALL, getenv("LANG"));
1550 /* where the monitor start (used only with xinerama) */
1551 offset_x = offset_y = 0;
1553 /* default width and height */
1557 /* default position on the screen */
1560 for (i = 0; i < 4; ++i) {
1561 /* default paddings */
1562 r.p_padding[i] = 10;
1563 r.c_padding[i] = 10;
1564 r.ch_padding[i] = 10;
1566 /* default borders */
1570 r.ch_borders[i] = 0;
1573 /* the prompt. We duplicate the string so later is easy to
1574 * free (in the case it's been overwritten by the user) */
1575 if ((r.ps1 = strdup("$ ")) == NULL)
1578 /* same for the font name */
1579 if ((fontname = strdup(default_fontname)) == NULL)
1583 if ((text = malloc(textlen * sizeof(char))) == NULL)
1586 /* struct completions *cs = filter(text, lines); */
1587 if ((cs = compls_new(nlines)) == NULL)
1588 err(1, "compls_new");
1590 /* start talking to xorg */
1591 r.d = XOpenDisplay(NULL);
1593 fprintf(stderr, "Could not open display!\n");
1594 return EX_UNAVAILABLE;
1598 if (!(parent_window_id
1599 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1600 parent_window = DefaultRootWindow(r.d);
1604 /* get display size */
1605 get_wh(r.d, &parent_window, &d_width, &d_height);
1608 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1609 XineramaScreenInfo *info;
1612 int number_of_screens, monitors, i;
1613 int root_x, root_y, win_x, win_y;
1617 number_of_screens = XScreenCount(r.d);
1618 for (i = 0; i < number_of_screens; ++i) {
1619 root = XRootWindow(r.d, i);
1620 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1621 &root_y, &win_x, &win_y, &mask);
1627 fprintf(stderr, "No mouse found.\n");
1632 /* Now find in which monitor the mice is */
1633 info = XineramaQueryScreens(r.d, &monitors);
1635 for (i = 0; i < monitors; ++i) {
1636 if (info[i].x_org <= root_x
1637 && root_x <= (info[i].x_org
1639 && info[i].y_org <= root_y
1640 && root_y <= (info[i].y_org
1641 + info[i].height)) {
1642 offset_x = info[i].x_org;
1643 offset_y = info[i].y_org;
1644 d_width = info[i].width;
1645 d_height = info[i].height;
1654 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1655 cmap = XCreateColormap(
1656 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1658 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1659 fgs[2] = parse_color("#000", NULL);
1661 bgs[0] = bgs[1] = parse_color("#000", NULL);
1662 bgs[2] = parse_color("#fff", NULL);
1664 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1665 = parse_color("#000", NULL);
1667 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1668 = parse_color("#000", NULL);
1669 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1670 = parse_color("#000", NULL);
1671 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1672 = ch_borders_bg[3] = parse_color("#000", NULL);
1674 r.horizontal_layout = 1;
1676 /* Read the resources */
1678 xrm = XResourceManagerString(r.d);
1684 xdb = XrmGetStringDatabase(xrm);
1686 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1689 if ((fontname = strdup(value.addr)) == NULL)
1692 fprintf(stderr, "no font defined, using %s\n",
1697 xdb, "MyMenu.layout", "*", datatype, &value)
1700 = !strcmp(value.addr, "horizontal");
1703 "no layout defined, using horizontal\n");
1706 xdb, "MyMenu.prompt", "*", datatype, &value)
1709 r.ps1 = normalize_str(value.addr);
1712 "no prompt defined, using \"%s\" as "
1717 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1721 sizes = parse_csslike(value.addr);
1723 for (i = 0; i < 4; ++i)
1725 = parse_integer(sizes[i], 0);
1728 "error while parsing "
1729 "MyMenu.prompt.border.size");
1732 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1736 colors = parse_csslike(value.addr);
1738 for (i = 0; i < 4; ++i)
1739 p_borders_bg[i] = parse_color(
1743 "error while parsing "
1744 "MyMenu.prompt.border.color");
1747 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1751 colors = parse_csslike(value.addr);
1753 for (i = 0; i < 4; ++i)
1755 = parse_integer(colors[i], 0);
1758 "error while parsing "
1759 "MyMenu.prompt.padding");
1762 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1764 r.width = parse_int_with_percentage(
1765 value.addr, r.width, d_width);
1767 fprintf(stderr, "no width defined, using %d\n",
1771 xdb, "MyMenu.height", "*", datatype, &value)
1773 r.height = parse_int_with_percentage(
1774 value.addr, r.height, d_height);
1776 fprintf(stderr, "no height defined, using %d\n",
1779 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1781 x = parse_int_with_pos(
1782 value.addr, x, d_width, r.width);
1784 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1786 y = parse_int_with_pos(
1787 value.addr, y, d_height, r.height);
1790 xdb, "MyMenu.border.size", "*", datatype, &value)
1793 borders = parse_csslike(value.addr);
1794 if (borders != NULL)
1795 for (i = 0; i < 4; ++i)
1797 = parse_int_with_percentage(
1804 "error while parsing "
1805 "MyMenu.border.size\n");
1809 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1812 fgs[0] = parse_color(value.addr, "#fff");
1814 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1817 bgs[0] = parse_color(value.addr, "#000");
1820 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1823 fgs[1] = parse_color(value.addr, "#fff");
1825 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1828 bgs[1] = parse_color(value.addr, "#000");
1830 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1834 paddings = parse_csslike(value.addr);
1835 if (paddings != NULL)
1836 for (i = 0; i < 4; ++i)
1837 r.c_padding[i] = parse_integer(
1841 "Error while parsing "
1842 "MyMenu.completion.padding");
1845 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1849 sizes = parse_csslike(value.addr);
1851 for (i = 0; i < 4; ++i)
1853 = parse_integer(sizes[i], 0);
1856 "Error while parsing "
1857 "MyMenu.completion.border.size");
1860 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1864 sizes = parse_csslike(value.addr);
1866 for (i = 0; i < 4; ++i)
1867 c_borders_bg[i] = parse_color(
1871 "Error while parsing "
1872 "MyMenu.completion.border.color");
1875 /* Completion Highlighted */
1876 if (XrmGetResource(xdb,
1877 "MyMenu.completion_highlighted.foreground", "*",
1880 fgs[2] = parse_color(value.addr, "#000");
1882 if (XrmGetResource(xdb,
1883 "MyMenu.completion_highlighted.background", "*",
1886 bgs[2] = parse_color(value.addr, "#fff");
1888 if (XrmGetResource(xdb,
1889 "MyMenu.completion_highlighted.padding", "*",
1893 paddings = parse_csslike(value.addr);
1894 if (paddings != NULL)
1895 for (i = 0; i < 4; ++i)
1896 r.ch_padding[i] = parse_integer(
1900 "Error while parsing "
1901 "MyMenu.completion_highlighted."
1905 if (XrmGetResource(xdb,
1906 "MyMenu.completion_highlighted.border.size", "*",
1910 sizes = parse_csslike(value.addr);
1912 for (i = 0; i < 4; ++i)
1914 = parse_integer(sizes[i], 0);
1917 "Error while parsing "
1918 "MyMenu.completion_highlighted."
1922 if (XrmGetResource(xdb,
1923 "MyMenu.completion_highlighted.border.color", "*",
1927 colors = parse_csslike(value.addr);
1929 for (i = 0; i < 4; ++i)
1930 ch_borders_bg[i] = parse_color(
1934 "Error while parsing "
1935 "MyMenu.completion_highlighted."
1941 xdb, "MyMenu.border.color", "*", datatype, &value)
1944 colors = parse_csslike(value.addr);
1946 for (i = 0; i < 4; ++i)
1947 borders_bg[i] = parse_color(
1951 "error while parsing "
1952 "MyMenu.border.color\n");
1956 /* Second round of args parsing */
1957 optind = 0; /* reset the option index */
1958 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1961 r.first_selected = 1;
1964 /* free_text -- already catched */
1966 /* separator -- this case was already catched */
1968 /* embedding mymenu this case was already catched. */
1970 /* multiple selection this case was already catched.
1975 newprompt = strdup(optarg);
1976 if (newprompt != NULL) {
1983 x = parse_int_with_pos(optarg, x, d_width, r.width);
1986 y = parse_int_with_pos(optarg, y, d_height, r.height);
1990 if ((paddings = parse_csslike(optarg)) != NULL)
1991 for (i = 0; i < 4; ++i)
1992 r.p_padding[i] = parse_integer(
1998 if ((colors = parse_csslike(optarg)) != NULL)
1999 for (i = 0; i < 4; ++i)
2000 p_borders_bg[i] = parse_color(
2006 if ((sizes = parse_csslike(optarg)) != NULL)
2007 for (i = 0; i < 4; ++i)
2009 = parse_integer(sizes[i], 0);
2014 if ((colors = parse_csslike(optarg)) != NULL)
2015 for (i = 0; i < 4; ++i)
2016 c_borders_bg[i] = parse_color(
2022 if ((sizes = parse_csslike(optarg)) != NULL)
2023 for (i = 0; i < 4; ++i)
2025 = parse_integer(sizes[i], 0);
2030 if ((colors = parse_csslike(optarg)) != NULL)
2031 for (i = 0; i < 4; ++i)
2032 ch_borders_bg[i] = parse_color(
2038 if ((sizes = parse_csslike(optarg)) != NULL)
2039 for (i = 0; i < 4; ++i)
2041 = parse_integer(sizes[i], 0);
2045 r.horizontal_layout = !strcmp(optarg, "horizontal");
2049 if ((newfont = strdup(optarg)) != NULL) {
2056 r.width = parse_int_with_percentage(
2057 optarg, r.width, d_width);
2060 r.height = parse_int_with_percentage(
2061 optarg, r.height, d_height);
2065 if ((borders = parse_csslike(optarg)) != NULL) {
2066 for (i = 0; i < 4; ++i)
2067 r.borders[i] = parse_integer(
2070 fprintf(stderr, "Error parsing b option\n");
2075 if ((colors = parse_csslike(optarg)) != NULL) {
2076 for (i = 0; i < 4; ++i)
2077 borders_bg[i] = parse_color(
2081 "error while parsing B option\n");
2085 fgs[0] = parse_color(optarg, NULL);
2088 bgs[0] = parse_color(optarg, NULL);
2091 fgs[1] = parse_color(optarg, NULL);
2094 bgs[1] = parse_color(optarg, NULL);
2097 fgs[2] = parse_color(optarg, NULL);
2100 fgs[2] = parse_color(optarg, NULL);
2103 fprintf(stderr, "Unrecognized option %c\n", ch);
2109 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2110 fprintf(stderr, "height, width, x or y are lesser than 0.");
2114 /* since only now we know if the first should be selected,
2115 * update the completion here */
2116 update_completions(cs, text, lines, vlines, r.first_selected);
2118 /* update the prompt lenght, only now we surely know the length of it
2120 r.ps1len = strlen(r.ps1);
2122 /* Create the window */
2123 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2125 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2126 XMapRaised(r.d, r.w);
2128 /* If embed, listen for other events as well */
2130 Window *children, parent, root;
2131 unsigned int children_no;
2133 XSelectInput(r.d, parent_window, FocusChangeMask);
2134 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2137 for (i = 0; i < children_no && children[i] != r.w;
2140 r.d, children[i], FocusChangeMask);
2143 grabfocus(r.d, r.w);
2146 take_keyboard(r.d, r.w);
2148 r.x_zero = r.borders[3];
2149 r.y_zero = r.borders[0];
2154 for (i = 0; i < 3; ++i) {
2155 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2156 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2159 for (i = 0; i < 4; ++i) {
2160 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2161 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2162 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2163 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2167 /* Load the colors in our GCs */
2168 for (i = 0; i < 3; ++i) {
2169 XSetForeground(r.d, r.fgs[i], fgs[i]);
2170 XSetForeground(r.d, r.bgs[i], bgs[i]);
2173 for (i = 0; i < 4; ++i) {
2174 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2175 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2176 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2177 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2180 if (load_font(&r, fontname) == -1)
2184 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2186 for (i = 0; i < 3; ++i) {
2188 XRenderColor xrcolor;
2190 c = *(rgba_t *)&fgs[i];
2191 xrcolor.red = EXPANDBITS(c.rgba.r);
2192 xrcolor.green = EXPANDBITS(c.rgba.g);
2193 xrcolor.blue = EXPANDBITS(c.rgba.b);
2194 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2196 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2200 /* compute prompt dimensions */
2206 /* Now we need only the ability to write */
2207 pledge("stdio", "");
2210 /* Cache text height */
2211 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2213 /* Draw the window for the first time */
2217 while (status == LOOPING || status == OK_LOOP) {
2218 status = loop(&r, &text, &textlen, cs, lines, vlines);
2221 printf("%s\n", text);
2223 if (!r.multiple_select && status == OK_LOOP)
2227 XUngrabKeyboard(r.d, CurrentTime);
2230 for (i = 0; i < 3; ++i)
2231 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2234 for (i = 0; i < 3; ++i) {
2235 XFreeGC(r.d, r.fgs[i]);
2236 XFreeGC(r.d, r.bgs[i]);
2239 for (i = 0; i < 4; ++i) {
2240 XFreeGC(r.d, r.borders_bg[i]);
2241 XFreeGC(r.d, r.p_borders_bg[i]);
2242 XFreeGC(r.d, r.c_borders_bg[i]);
2243 XFreeGC(r.d, r.ch_borders_bg[i]);
2250 for (i = 0; i < 3; ++i)
2251 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2252 XftFontClose(r.d, r.font);
2253 XftDrawDestroy(r.xftdraw);
2255 XFreeFontSet(r.d, r.font);
2267 XFreeColormap(r.d, cmap);
2269 XDestroyWindow(r.d, r.w);
2272 return status != OK;