3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
15 #include <X11/Xutil.h> // XLookupString
16 #include <X11/Xresource.h>
17 #include <X11/Xcms.h> // colors
18 #include <X11/keysym.h>
21 # include <X11/extensions/Xinerama.h>
25 # include <X11/Xft/Xft.h>
29 # define VERSION "unknown"
35 #define resname "MyMenu"
36 #define resclass "mymenu"
38 #define SYM_BUF_SIZE 4
41 # define default_fontname "monospace"
43 # define default_fontname "fixed"
46 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
51 #define EXPANDBITS(x) ((0xffff * x) / 0xff)
53 // If we don't have it or we don't want an "ignore case" completion
54 // style, fall back to `strstr(3)`
55 #ifndef USE_STRCASESTR
56 # define strcasestr strstr
59 // The number of char to read
60 #define STDIN_CHUNKS 64
62 // the number of lines to allocate in advance
63 #define LINES_CHUNK 32
66 #define check_allocation(a) { \
68 fprintf(stderr, "Could not allocate memory\n"); \
73 #define inner_height(r) (r->height - r->border_n - r->border_s)
74 #define inner_width(r) (r->width - r->border_e - r->border_w)
76 // The possible state of the event loop.
77 enum state {LOOPING, OK_LOOP, OK, ERR};
79 // for the drawing-related function. The text to be rendered could be
80 // the prompt, a completion or a highlighted completion
81 enum text_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
98 // functions). A struct to rule them all
100 Display *d; // connection to xorg
105 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
106 int y_zero; // the same a x_zero, only for the y axis
108 size_t offset; // a scrolling offset
112 bool multiple_select;
120 bool horizontal_layout;
133 GC completion_highlighted;
134 GC completion_highlighted_bg;
143 XftColor xft_completion;
144 XftColor xft_completion_highlighted;
155 // Wrap the linked list of completions
157 struct completion *completions;
162 // return a newly allocated (and empty) completion list
163 struct completions *compls_new(size_t lenght) {
164 struct completions *cs = malloc(sizeof(struct completions));
169 cs->completions = calloc(lenght, sizeof(struct completion));
170 if (cs->completions == nil) {
180 /* idea stolen from lemonbar. ty lemonboy */
191 // Delete the wrapper and the whole list
192 void compls_delete(struct completions *cs) {
196 free(cs->completions);
200 // create a completion list from a text and the list of possible
201 // completions (null terminated). Expects a non-null `cs'. lines and
202 // vlines should have the same lenght OR vlines is null
203 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
211 char *l = vlines[index] != nil ? vlines[index] : lines[index];
215 if (strcasestr(l, text) != nil) {
216 struct completion *c = &cs->completions[matching];
218 c->rcompletion = lines[index];
224 cs->lenght = matching;
228 // update the given completion, that is: clean the old cs & generate a new one.
229 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
230 filter(cs, text, lines, vlines);
231 if (first_selected && cs->lenght > 0)
235 // select the next, or the previous, selection and update some
236 // state. `text' will be updated with the text of the completion and
237 // `textlen' with the new lenght of `text'. If the memory cannot be
238 // allocated, `status' will be set to `ERR'.
239 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
240 if (cs == nil || cs->lenght == 0)
243 // if the first is always selected, and the first entry is different
244 // from the text, expand the text and return
247 && strcmp(cs->completions->completion, *text) != 0
250 *text = strdup(cs->completions->completion);
255 *textlen = strlen(*text);
259 int index = cs->selected;
261 if (index == -1 && p)
263 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
265 struct completion *n = &cs->completions[cs->selected];
268 *text = strdup(n->completion);
270 fprintf(stderr, "Memory allocation error!\n");
274 *textlen = strlen(*text);
277 // push the character c at the end of the string pointed by p
278 int pushc(char **p, int maxlen, char c) {
279 int len = strnlen(*p, maxlen);
281 if (!(len < maxlen -2)) {
282 maxlen += maxlen >> 1;
283 char *newptr = realloc(*p, maxlen);
284 if (newptr == nil) { // bad!
295 // remove the last rune from the *utf8* string! This is different from
296 // just setting the last byte to 0 (in some cases ofc). Return a
297 // pointer (e) to the last non zero char. If e < p then p is empty!
298 char* popc(char *p) {
303 char *e = p + len - 1;
310 // if c is a starting byte (11......) or is under U+007F (ascii,
311 // basically) we're done
312 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
319 // remove the last word plus trailing whitespaces from the give string
332 if (in_word && isspace(*e))
335 if (!in_word && !isspace(*e))
340 // If the string is surrounded by quotes (`"`) remove them and replace
341 // every `\"` in the string with `"`
342 char *normalize_str(const char *str) {
343 int len = strlen(str);
347 char *s = calloc(len, sizeof(char));
356 str += 2; // skip this and the next char
363 str++; // skip only this char
373 size_t read_stdin(char **buf) {
375 size_t len = STDIN_CHUNKS;
376 *buf = malloc(len * sizeof(char));
381 ssize_t r = read(0, *buf + offset, STDIN_CHUNKS);
388 *buf = realloc(*buf, len);
392 for (size_t i = offset; i < len; ++i)
397 fprintf(stderr, "Error in allocating memory for stdin.\n");
398 exit(EX_UNAVAILABLE);
402 size_t readlines(char ***lns, char **buf) {
404 size_t len = read_stdin(buf);
406 size_t ll = LINES_CHUNK;
407 *lns = malloc(ll * sizeof(char*));
409 bool in_line = false;
410 for (size_t i = 0; i < len; i++) {
419 if (in_line && c == '\n')
422 if (!in_line && c != '\n') {
424 (*lns)[lines] = (*buf) + i;
427 if (lines == ll) { // resize
429 *lns = realloc(*lns, ll * sizeof(char*));
431 fprintf(stderr, "Error in memory allocation.\n");
432 exit(EX_UNAVAILABLE);
441 // Compute the dimension of the string str once rendered, return the
442 // width and save the width and the height in ret_width and ret_height
443 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
448 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
449 height = r->font->ascent - r->font->descent;
450 width = gi.width - gi.x;
453 XmbTextExtents(*r->font, str, len, nil, &rect);
454 height = rect.height;
457 if (ret_width != nil) *ret_width = width;
458 if (ret_height != nil) *ret_height = height;
462 // Draw the string str
463 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
466 if (tt == PROMPT) xftcolor = r->xft_prompt;
467 if (tt == COMPL) xftcolor = r->xft_completion;
468 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
470 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
473 if (tt == PROMPT) gc = r->prompt;
474 if (tt == COMPL) gc = r->completion;
475 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
476 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
480 // Duplicate the string str and substitute every space with a 'n'
481 char *strdupn(char *str) {
482 int len = strlen(str);
484 if (str == nil || len == 0)
487 char *dup = strdup(str);
491 for (int i = 0; i < len; ++i)
498 // |------------------|----------------------------------------------|
499 // | 20 char text | completion | completion | completion | compl |
500 // |------------------|----------------------------------------------|
501 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
502 int prompt_width = 20; // char
504 char *ps1dup = strdupn(r->ps1);
506 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
508 int start_at = ps1xlen;
510 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
511 start_at = start_at * prompt_width + r->padding;
513 int texty = (inner_height(r) + height + r->y_zero) / 2;
515 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
517 int text_len = strlen(text);
518 if (text_len > prompt_width)
519 text = text + (text_len - prompt_width);
520 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
521 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
523 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
525 for (size_t i = r->offset; i < cs->lenght; ++i) {
526 struct completion *c = &cs->completions[i];
528 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
529 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
531 int len = strlen(c->completion);
532 int text_width = text_extents(c->completion, len, r, nil, nil);
534 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
536 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
538 start_at += text_width + r->padding * 2;
540 if (start_at > inner_width(r))
541 break; // don't draw completion if the space isn't enough
545 // |-----------------------------------------------------------------|
547 // |-----------------------------------------------------------------|
549 // |-----------------------------------------------------------------|
551 // |-----------------------------------------------------------------|
552 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
554 text_extents("fjpgl", 5, r, nil, &height);
555 int start_at = r->padding*2 + height;
557 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
558 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
560 char *ps1dup = strdupn(r->ps1);
561 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, nil, nil);
564 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
565 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
567 start_at += r->y_zero;
569 for (size_t i = r->offset; i < cs->lenght; ++i){
570 struct completion *c = &cs->completions[i];
571 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
572 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
574 int len = strlen(c->completion);
575 text_extents(c->completion, len, r, &width, &height);
576 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
577 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
579 start_at += height + r->padding *2;
581 if (start_at > inner_height(r))
582 break; // don't draw completion if the space isn't enough
586 void draw(struct rendering *r, char *text, struct completions *cs) {
587 if (r->horizontal_layout)
588 draw_horizontally(r, text, cs);
590 draw_vertically(r, text, cs);
594 if (r->border_w != 0)
595 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
597 if (r->border_e != 0)
598 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
600 if (r->border_n != 0)
601 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
603 if (r->border_s != 0)
604 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
606 // send all the work to x
610 /* Set some WM stuff */
611 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
613 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
617 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
618 XInternAtom(d, "ATOM", false),
621 (unsigned char *)&type,
625 /* some window managers honor this properties */
626 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
629 XInternAtom(d, "_NET_WM_STATE", false),
630 XInternAtom(d, "ATOM", false),
633 (unsigned char *)&type,
637 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
640 XInternAtom(d, "_NET_WM_STATE", false),
641 XInternAtom(d, "ATOM", false),
644 (unsigned char *)&type,
648 // setting window hints
649 XClassHint *class_hint = XAllocClassHint();
650 if (class_hint == nil) {
651 fprintf(stderr, "Could not allocate memory for class hint\n");
652 exit(EX_UNAVAILABLE);
654 class_hint->res_name = resname;
655 class_hint->res_class = resclass;
656 XSetClassHint(d, w, class_hint);
659 XSizeHints *size_hint = XAllocSizeHints();
660 if (size_hint == nil) {
661 fprintf(stderr, "Could not allocate memory for size hint\n");
662 exit(EX_UNAVAILABLE);
664 size_hint->flags = PMinSize | PBaseSize;
665 size_hint->min_width = width;
666 size_hint->base_width = width;
667 size_hint->min_height = height;
668 size_hint->base_height = height;
673 // write the width and height of the window `w' respectively in `width'
675 void get_wh(Display *d, Window *w, int *width, int *height) {
676 XWindowAttributes win_attr;
677 XGetWindowAttributes(d, *w, &win_attr);
678 *height = win_attr.height;
679 *width = win_attr.width;
682 int grabfocus(Display *d, Window w) {
683 for (int i = 0; i < 100; ++i) {
686 XGetInputFocus(d, &focuswin, &revert_to_win);
689 XSetInputFocus(d, w, RevertToParent, CurrentTime);
695 // I know this may seem a little hackish BUT is the only way I managed
696 // to actually grab that goddam keyboard. Only one call to
697 // XGrabKeyboard does not always end up with the keyboard grabbed!
698 int take_keyboard(Display *d, Window w) {
700 for (i = 0; i < 100; i++) {
701 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
705 fprintf(stderr, "Cannot grab keyboard\n");
709 // release the keyboard.
710 void release_keyboard(Display *d) {
711 XUngrabKeyboard(d, CurrentTime);
714 unsigned long parse_color(const char *str, const char *def) {
718 size_t len = strlen(str);
720 // +1 for the '#' at the start, hence 9 and 4 (instead of 8 and 3)
721 if (*str != '#' || len > 9 || len < 4)
723 ++str; // skip the '#'
727 rgba_t tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
734 // expand: #rgb -> #rrggbb
735 tmp.v = (tmp.v & 0xf00) * 0x1100
736 | (tmp.v & 0x0f0) * 0x0110
737 | (tmp.v & 0x00f) * 0x0011;
739 // assume it has 100% opacity
742 } // colors in aarrggbb format needs no fixes
744 // premultiply the alpha
746 tmp.r = (tmp.r * tmp.a) / 255;
747 tmp.g = (tmp.g * tmp.a) / 255;
748 tmp.b = (tmp.b * tmp.a) / 255;
755 fprintf(stderr, "Invalid color: \"%s\".\n", str);
757 return parse_color(def, nil);
762 // Given a string, try to parse it as a number or return
764 int parse_integer(const char *str, int default_value) {
767 long lval = strtol(str, &ep, 10);
768 if (str[0] == '\0' || *ep != '\0') { // NaN
769 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
770 return default_value;
772 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
773 (lval > INT_MAX || lval < INT_MIN)) {
774 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
775 return default_value;
780 // like parse_integer, but if the value ends with a `%' then its
781 // treated like a percentage (`max' is used to compute the percentage)
782 int parse_int_with_percentage(const char *str, int default_value, int max) {
783 int len = strlen(str);
784 if (len > 0 && str[len-1] == '%') {
785 char *cpy = strdup(str);
786 check_allocation(cpy);
788 int val = parse_integer(cpy, default_value);
790 return val * max / 100;
792 return parse_integer(str, default_value);
795 // like parse_int_with_percentage but understands some special values
796 // - "middle" that is (max - self) / 2
797 // - "start" that is 0
798 // - "end" that is (max - self)
799 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
800 if (!strcmp(str, "start"))
802 if (!strcmp(str, "middle"))
803 return (max - self)/2;
804 if (!strcmp(str, "end"))
806 return parse_int_with_percentage(str, default_value, max);
809 // parse a string like a css value (for example like the css
810 // margin/padding properties). Will ALWAYS return an array of 4 word
811 // TODO: harden this function!
812 char **parse_csslike(const char *str) {
813 char *s = strdup(str);
817 char **ret = malloc(4 * sizeof(char*));
825 while ((token = strsep(&s, " ")) != NULL && i < 4) {
826 ret[i] = strdup(token);
831 for (int j = 1; j < 4; j++)
832 ret[j] = strdup(ret[0]);
835 ret[2] = strdup(ret[0]);
836 ret[3] = strdup(ret[1]);
840 ret[3] = strdup(ret[1]);
842 // Before we didn't check for the return type of strdup, here we will
844 bool any_null = false;
845 for (int i = 0; i < 4; ++i)
846 any_null = ret[i] == nil || any_null;
849 for (int i = 0; i < 4; ++i)
853 if (i == 0 || any_null) {
862 // Given an event, try to understand what the user wants. If the
863 // return value is ADD_CHAR then `input' is a pointer to a string that
864 // will need to be free'ed.
865 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
866 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
869 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
870 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
872 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
875 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
878 // try to read what the user pressed
879 char str[SYM_BUF_SIZE] = {0};
881 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
882 if (s == XBufferOverflow) {
883 // should not happen since there are no utf-8 characters larger
885 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
889 if (ev->state & ControlMask) {
890 if (!strcmp(str, "")) // C-u
892 if (!strcmp(str, "")) // C-w
894 if (!strcmp(str, "")) // C-h
896 if (!strcmp(str, "\r")) // C-m
897 return CONFIRM_CONTINUE;
898 if (!strcmp(str, "")) // C-p
900 if (!strcmp(str, "")) // C-n
902 if (!strcmp(str, "")) // C-c
904 if (!strcmp(str, "\t")) // C-i
905 return TOGGLE_FIRST_SELECTED;
908 *input = strdup(str);
910 fprintf(stderr, "Error while allocating memory for key.\n");
917 // Given the name of the program (argv[0]?) print a small help on stderr
918 void usage(char *prgname) {
919 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
920 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
921 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
922 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
925 // small function used in the event loop
926 void confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen) {
927 if ((cs->selected != -1) || (cs->lenght > 0 && r->first_selected)) {
928 // if there is something selected expand it and return
929 int index = cs->selected == -1 ? 0 : cs->selected;
930 struct completion *c = cs->completions;
937 char *t = c->rcompletion;
941 fprintf(stderr, "Memory allocation error\n");
944 *textlen = strlen(*text);
947 // cannot accept arbitrary text
954 enum state loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines) {
955 enum state status = LOOPING;
956 while (status == LOOPING) {
958 XNextEvent(r->d, &e);
960 if (XFilterEvent(&e, r->w))
965 XRefreshKeyboardMapping(&e.xmapping);
970 if (e.xfocus.window != r->w)
971 grabfocus(r->d, r->w);
974 case VisibilityNotify:
975 if (e.xvisibility.state != VisibilityUnobscured)
976 XRaiseWindow(r->d, r->w);
980 get_wh(r->d, &r->w, &r->width, &r->height);
985 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
988 switch (parse_event(r->d, ev, r->xic, &input)) {
995 confirm(&status, r, cs, text, textlen);
999 case CONFIRM_CONTINUE: {
1001 confirm(&status, r, cs, text, textlen);
1006 complete(cs, r->first_selected, true, text, textlen, &status);
1007 r->offset = cs->selected;
1012 complete(cs, r->first_selected, false, text, textlen, &status);
1013 r->offset = cs->selected;
1019 update_completions(cs, *text, lines, vlines, r->first_selected);
1025 update_completions(cs, *text, lines, vlines, r->first_selected);
1030 for (int i = 0; i < *textlen; ++i)
1032 update_completions(cs, *text, lines, vlines, r->first_selected);
1038 int str_len = strlen(input);
1040 // sometimes a strange key is pressed (i.e. ctrl alone),
1041 // so input will be empty. Don't need to update completion
1046 for (int i = 0; i < str_len; ++i) {
1047 *textlen = pushc(text, *textlen, input[i]);
1048 if (*textlen == -1) {
1049 fprintf(stderr, "Memory allocation error\n");
1054 if (status != ERR) {
1055 update_completions(cs, *text, lines, vlines, r->first_selected);
1062 case TOGGLE_FIRST_SELECTED:
1063 r->first_selected = !r->first_selected;
1064 if (r->first_selected && cs->selected < 0)
1066 if (!r->first_selected && cs->selected == 0)
1073 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1074 /* if (ev->button == Button1) { /\* click *\/ */
1075 /* int x = ev->x - r.border_w; */
1076 /* int y = ev->y - r.border_n; */
1077 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1080 if (ev->button == Button4) /* scroll up */
1081 r->offset = MAX((ssize_t)r->offset - 1, 0);
1083 if (ev->button == Button5) /* scroll down */
1084 r->offset = MIN(r->offset + 1, cs->lenght - 1);
1096 int main(int argc, char **argv) {
1098 // stdio & rpat: to read and write stdio/stdout
1099 // unix: to connect to Xorg
1100 pledge("stdio rpath unix", "");
1105 // by default the first completion isn't selected
1106 bool first_selected = false;
1108 // our parent window
1109 char *parent_window_id = nil;
1111 // the user can input arbitrary text
1112 bool free_text = true;
1114 // the user can select multiple entries
1115 bool multiple_select = false;
1117 // first round of args parsing
1119 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1124 case 'v': // version
1125 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1128 parent_window_id = strdup(optarg);
1129 check_allocation(parent_window_id);
1132 sep = strdup(optarg);
1133 check_allocation(sep);
1140 multiple_select = true;
1148 // read the lines from stdin
1151 size_t nlines = readlines(&lines, &buf);
1153 char **vlines = nil;
1155 int l = strlen(sep);
1156 vlines = calloc(nlines, sizeof(char*));
1157 check_allocation(vlines);
1159 for (int i = 0; lines[i] != nil; i++) {
1160 char *t = strstr(lines[i], sep);
1162 vlines[i] = lines[i];
1168 setlocale(LC_ALL, getenv("LANG"));
1170 enum state status = LOOPING;
1172 // where the monitor start (used only with xinerama)
1176 // width and height of the window
1180 // position on the screen
1184 // the default padding
1187 // the default borders
1193 // the prompt. We duplicate the string so later is easy to free (in
1194 // the case the user provide its own prompt)
1195 char *ps1 = strdup("$ ");
1196 check_allocation(ps1);
1198 // same for the font name
1199 char *fontname = strdup(default_fontname);
1200 check_allocation(fontname);
1203 char *text = malloc(textlen * sizeof(char));
1204 check_allocation(text);
1206 /* struct completions *cs = filter(text, lines); */
1207 struct completions *cs = compls_new(nlines);
1208 check_allocation(cs);
1210 // start talking to xorg
1211 Display *d = XOpenDisplay(nil);
1213 fprintf(stderr, "Could not open display!\n");
1214 return EX_UNAVAILABLE;
1217 Window parent_window;
1219 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1220 parent_window = DefaultRootWindow(d);
1227 get_wh(d, &parent_window, &d_width, &d_height);
1230 if (!embed && XineramaIsActive(d)) {
1232 int number_of_screens = XScreenCount(d);
1235 int root_x, root_y, win_x, win_y;
1238 for (int i = 0; i < number_of_screens; ++i) {
1239 root = XRootWindow(d, i);
1240 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1244 fprintf(stderr, "No mouse found.\n");
1249 // now find in which monitor the mice is on
1251 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1253 for (int i = 0; i < monitors; ++i) {
1254 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1255 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1256 offset_x = info[i].x_org;
1257 offset_y = info[i].y_org;
1258 d_width = info[i].width;
1259 d_height = info[i].height;
1268 /* Colormap cmap = DefaultColormap(d, DefaultScreen(d)); */
1270 XMatchVisualInfo(d, DefaultScreen(d), 32, TrueColor, &vinfo);
1273 cmap = XCreateColormap(d, XDefaultRootWindow(d), vinfo.visual, AllocNone);
1275 unsigned long p_fg = parse_color("#fff", nil);
1276 unsigned long compl_fg = parse_color("#fff", nil);
1277 unsigned long compl_highlighted_fg = parse_color("#000", nil);
1279 unsigned long p_bg = parse_color("#000", nil);
1280 unsigned long compl_bg = parse_color("#000", nil);
1281 unsigned long compl_highlighted_bg = parse_color("#fff", nil);
1283 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1284 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", nil);
1286 bool horizontal_layout = true;
1290 char *xrm = XResourceManagerString(d);
1291 XrmDatabase xdb = nil;
1293 xdb = XrmGetStringDatabase(xrm);
1297 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1299 fontname = strdup(value.addr);
1300 check_allocation(fontname);
1302 fprintf(stderr, "no font defined, using %s\n", fontname);
1305 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1306 horizontal_layout = !strcmp(value.addr, "horizontal");
1308 fprintf(stderr, "no layout defined, using horizontal\n");
1310 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1312 ps1 = normalize_str(value.addr);
1314 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1317 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1318 width = parse_int_with_percentage(value.addr, width, d_width);
1320 fprintf(stderr, "no width defined, using %d\n", width);
1322 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1323 height = parse_int_with_percentage(value.addr, height, d_height);
1325 fprintf(stderr, "no height defined, using %d\n", height);
1327 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1328 x = parse_int_with_pos(value.addr, x, d_width, width);
1330 fprintf(stderr, "no x defined, using %d\n", x);
1332 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1333 y = parse_int_with_pos(value.addr, y, d_height, height);
1335 fprintf(stderr, "no y defined, using %d\n", y);
1337 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1338 padding = parse_integer(value.addr, padding);
1340 fprintf(stderr, "no padding defined, using %d\n", padding);
1342 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1343 char **borders = parse_csslike(value.addr);
1344 if (borders != nil) {
1345 border_n = parse_integer(borders[0], 0);
1346 border_e = parse_integer(borders[1], 0);
1347 border_s = parse_integer(borders[2], 0);
1348 border_w = parse_integer(borders[3], 0);
1350 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1353 fprintf(stderr, "no border defined, using 0.\n");
1357 // TODO: tmp needs to be free'd after every allocation?
1360 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1361 p_fg = parse_color(value.addr, "#fff");
1363 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1364 p_bg = parse_color(value.addr, "#000");
1367 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1368 compl_fg = parse_color(value.addr, "#fff");
1370 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1371 compl_bg = parse_color(value.addr, "#000");
1373 compl_bg = parse_color("#000", nil);
1375 // completion highlighted
1376 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1377 compl_highlighted_fg = parse_color(value.addr, "#000");
1379 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1380 compl_highlighted_bg = parse_color(value.addr, "#fff");
1382 compl_highlighted_bg = parse_color("#fff", nil);
1385 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1386 char **colors = parse_csslike(value.addr);
1387 if (colors != nil) {
1388 border_n_bg = parse_color(colors[0], "#000");
1389 border_e_bg = parse_color(colors[1], "#000");
1390 border_s_bg = parse_color(colors[2], "#000");
1391 border_w_bg = parse_color(colors[3], "#000");
1393 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1398 // second round of args parsing
1399 optind = 0; // reset the option index
1400 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1403 first_selected = true;
1406 // free_text -- this case was already catched
1409 // separator -- this case was already catched
1412 // (embedding mymenu) this case was already catched.
1414 // (multiple selection) this case was already catched.
1417 char *newprompt = strdup(optarg);
1418 if (newprompt != nil) {
1425 x = parse_int_with_pos(optarg, x, d_width, width);
1428 y = parse_int_with_pos(optarg, y, d_height, height);
1431 padding = parse_integer(optarg, padding);
1434 horizontal_layout = !strcmp(optarg, "horizontal");
1437 char *newfont = strdup(optarg);
1438 if (newfont != nil) {
1445 width = parse_int_with_percentage(optarg, width, d_width);
1448 height = parse_int_with_percentage(optarg, height, d_height);
1451 char **borders = parse_csslike(optarg);
1452 if (borders != nil) {
1453 border_n = parse_integer(borders[0], 0);
1454 border_e = parse_integer(borders[1], 0);
1455 border_s = parse_integer(borders[2], 0);
1456 border_w = parse_integer(borders[3], 0);
1458 fprintf(stderr, "Error parsing b option\n");
1463 char **colors = parse_csslike(optarg);
1464 if (colors != nil) {
1465 border_n_bg = parse_color(colors[0], "#000");
1466 border_e_bg = parse_color(colors[1], "#000");
1467 border_s_bg = parse_color(colors[2], "#000");
1468 border_w_bg = parse_color(colors[3], "#000");
1470 fprintf(stderr, "error while parsing B option\n");
1475 p_fg = parse_color(optarg, nil);
1479 p_bg = parse_color(optarg, nil);
1483 compl_fg = parse_color(optarg, nil);
1487 compl_bg = parse_color(optarg, nil);
1491 compl_highlighted_fg = parse_color(optarg, nil);
1495 compl_highlighted_bg = parse_color(optarg, nil);
1499 fprintf(stderr, "Unrecognized option %c\n", ch);
1505 // since only now we know if the first should be selected, update
1506 // the completion here
1507 update_completions(cs, text, lines, vlines, first_selected);
1511 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1513 char **missing_charset_list;
1514 int missing_charset_count;
1515 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1517 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1518 return EX_UNAVAILABLE;
1522 // create the window
1523 XSetWindowAttributes attr;
1524 attr.colormap = cmap;
1525 attr.override_redirect = true;
1526 attr.border_pixel = 0;
1527 attr.background_pixel = 0x80808080;
1528 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1530 Window w = XCreateWindow(d, // display
1531 parent_window, // parent
1532 x + offset_x, y + offset_y, // x y
1533 width, height, // w h
1535 vinfo.depth, // depth
1536 InputOutput, // class
1537 vinfo.visual, // visual
1538 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, // value mask
1541 set_win_atoms_hints(d, w, width, height);
1543 // we want some events
1544 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1547 // if embed, listen for other events as well
1549 XSelectInput(d, parent_window, FocusChangeMask);
1550 Window *children, parent, root;
1551 unsigned int children_no;
1552 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1553 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1554 XSelectInput(d, children[i], FocusChangeMask);
1561 take_keyboard(d, w);
1563 // Create some graphics contexts
1565 /* values.font = font->fid; */
1567 struct rendering r = {
1576 .free_text = free_text,
1577 .first_selected = first_selected,
1578 .multiple_select = multiple_select,
1579 .border_n = border_n,
1580 .border_e = border_e,
1581 .border_s = border_s,
1582 .border_w = border_w,
1583 .horizontal_layout = horizontal_layout,
1585 .ps1len = strlen(ps1),
1586 .prompt = XCreateGC(d, w, 0, &values),
1587 .prompt_bg = XCreateGC(d, w, 0, &values),
1588 .completion = XCreateGC(d, w, 0, &values),
1589 .completion_bg = XCreateGC(d, w, 0, &values),
1590 .completion_highlighted = XCreateGC(d, w, 0, &values),
1591 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1592 .border_n_bg = XCreateGC(d, w, 0, &values),
1593 .border_e_bg = XCreateGC(d, w, 0, &values),
1594 .border_s_bg = XCreateGC(d, w, 0, &values),
1595 .border_w_bg = XCreateGC(d, w, 0, &values),
1604 r.xftdraw = XftDrawCreate(d, w, vinfo.visual, DefaultColormap(d, 0));
1609 XRenderColor xrcolor;
1612 c = *(rgba_t*)&p_fg;
1613 xrcolor.red = EXPANDBITS(c.r);
1614 xrcolor.green = EXPANDBITS(c.g);
1615 xrcolor.blue = EXPANDBITS(c.b);
1616 xrcolor.alpha = EXPANDBITS(c.a);
1617 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1620 c = *(rgba_t*)&compl_fg;
1621 xrcolor.red = EXPANDBITS(c.r);
1622 xrcolor.green = EXPANDBITS(c.g);
1623 xrcolor.blue = EXPANDBITS(c.b);
1624 xrcolor.alpha = EXPANDBITS(c.a);
1625 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1627 // completion highlighted
1628 c = *(rgba_t*)&compl_highlighted_fg;
1629 xrcolor.red = EXPANDBITS(c.r);
1630 xrcolor.green = EXPANDBITS(c.g);
1631 xrcolor.blue = EXPANDBITS(c.b);
1632 xrcolor.alpha = EXPANDBITS(c.a);
1633 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1637 // load the colors in our GCs
1638 /* XSetForeground(d, r.prompt, p_fg.pixel); */
1639 XSetForeground(d, r.prompt, p_fg);
1640 XSetForeground(d, r.prompt_bg, p_bg);
1641 /* XSetForeground(d, r.completion, compl_fg.pixel); */
1642 XSetForeground(d, r.completion, compl_fg);
1643 XSetForeground(d, r.completion_bg, compl_bg);
1644 /* XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel); */
1645 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg);
1646 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg);
1647 XSetForeground(d, r.border_n_bg, border_n_bg);
1648 XSetForeground(d, r.border_e_bg, border_e_bg);
1649 XSetForeground(d, r.border_s_bg, border_s_bg);
1650 XSetForeground(d, r.border_w_bg, border_w_bg);
1652 // open the X input method
1653 XIM xim = XOpenIM(d, xdb, resname, resclass);
1654 check_allocation(xim);
1656 XIMStyles *xis = nil;
1657 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1658 fprintf(stderr, "Input Styles could not be retrieved\n");
1659 return EX_UNAVAILABLE;
1662 XIMStyle bestMatchStyle = 0;
1663 for (int i = 0; i < xis->count_styles; ++i) {
1664 XIMStyle ts = xis->supported_styles[i];
1665 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1666 bestMatchStyle = ts;
1672 if (!bestMatchStyle) {
1673 fprintf(stderr, "No matching input style could be determined\n");
1676 r.xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1677 check_allocation(r.xic);
1679 // draw the window for the first time
1683 while (status == LOOPING || status == OK_LOOP) {
1684 status = loop(&r, &text, &textlen, cs, lines, vlines);
1687 printf("%s\n", text);
1689 if (!multiple_select && status == OK_LOOP)
1693 release_keyboard(r.d);
1696 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1697 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1698 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1710 XDestroyWindow(r.d, r.w);
1713 return status != OK;