3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
19 # include <X11/extensions/Xinerama.h>
23 # include <X11/Xft/Xft.h>
27 # define VERSION "unknown"
33 #define resname "MyMenu"
34 #define resclass "mymenu"
36 #define SYM_BUF_SIZE 4
39 # define default_fontname "monospace"
41 # define default_fontname "fixed"
44 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
46 #define MIN(a, b) ((a) < (b) ? (a) : (b))
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
49 // If we don't have it or we don't want an "ignore case" completion
50 // style, fall back to `strstr(3)`
51 #ifndef USE_STRCASESTR
52 # define strcasestr strstr
55 // The initial number of items to read
56 #define INITIAL_ITEMS 64
59 #define check_allocation(a) { \
61 fprintf(stderr, "Could not allocate memory\n"); \
66 #define inner_height(r) (r->height - r->border_n - r->border_s)
67 #define inner_width(r) (r->width - r->border_e - r->border_w)
69 // The possible state of the event loop.
70 enum state {LOOPING, OK_LOOP, OK, ERR};
72 // for the drawing-related function. The text to be rendered could be
73 // the prompt, a completion or a highlighted completion
74 enum text_type {PROMPT, COMPL, COMPL_HIGH};
76 // These are the possible action to be performed after user input.
90 // A big set of values that needs to be carried around (for drawing
91 // functions). A struct to rule them all
93 Display *d; // connection to xorg
98 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
99 int y_zero; // the same a x_zero, only for the y axis
101 size_t offset; // a scrolling offset
105 bool multiple_select;
113 bool horizontal_layout;
126 GC completion_highlighted;
127 GC completion_highlighted_bg;
136 XftColor xft_completion;
137 XftColor xft_completion_highlighted;
148 // Wrap the linked list of completions
150 struct completion *completions;
155 // return a newly allocated (and empty) completion list
156 struct completions *compls_new(size_t lenght) {
157 struct completions *cs = malloc(sizeof(struct completions));
162 cs->completions = calloc(lenght, sizeof(struct completion));
163 if (cs->completions == nil) {
173 // Delete the wrapper and the whole list
174 void compls_delete(struct completions *cs) {
178 free(cs->completions);
182 // create a completion list from a text and the list of possible
183 // completions (null terminated). Expects a non-null `cs'. lines and
184 // vlines should have the same lenght OR vlines is null
185 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
193 char *l = vlines[index] != nil ? vlines[index] : lines[index];
197 if (strcasestr(l, text) != nil) {
198 struct completion *c = &cs->completions[matching];
200 c->rcompletion = lines[index];
206 cs->lenght = matching;
210 // update the given completion, that is: clean the old cs & generate a new one.
211 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
212 filter(cs, text, lines, vlines);
213 if (first_selected && cs->lenght > 0)
217 // select the next, or the previous, selection and update some
218 // state. `text' will be updated with the text of the completion and
219 // `textlen' with the new lenght of `text'. If the memory cannot be
220 // allocated, `status' will be set to `ERR'.
221 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
222 if (cs == nil || cs->lenght == 0)
225 // if the first is always selected, and the first entry is different
226 // from the text, expand the text and return
229 && strcmp(cs->completions->completion, *text) != 0
232 *text = strdup(cs->completions->completion);
237 *textlen = strlen(*text);
241 int index = cs->selected;
243 if (index == -1 && p)
245 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
247 struct completion *n = &cs->completions[cs->selected];
250 *text = strdup(n->completion);
252 fprintf(stderr, "Memory allocation error!\n");
256 *textlen = strlen(*text);
259 // push the character c at the end of the string pointed by p
260 int pushc(char **p, int maxlen, char c) {
261 int len = strnlen(*p, maxlen);
263 if (!(len < maxlen -2)) {
264 maxlen += maxlen >> 1;
265 char *newptr = realloc(*p, maxlen);
266 if (newptr == nil) { // bad!
277 // remove the last rune from the *utf8* string! This is different from
278 // just setting the last byte to 0 (in some cases ofc). Return a
279 // pointer (e) to the last non zero char. If e < p then p is empty!
280 char* popc(char *p) {
285 char *e = p + len - 1;
292 // if c is a starting byte (11......) or is under U+007F (ascii,
293 // basically) we're done
294 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
301 // remove the last word plus trailing whitespaces from the give string
314 if (in_word && isspace(*e))
317 if (!in_word && !isspace(*e))
322 // If the string is surrounded by quotes (`"`) remove them and replace
323 // every `\"` in the string with `"`
324 char *normalize_str(const char *str) {
325 int len = strlen(str);
329 char *s = calloc(len, sizeof(char));
338 str += 2; // skip this and the next char
345 str++; // skip only this char
355 // read an arbitrary amount of text until an EOF and store it in
356 // lns. `items` is the capacity of lns. It may increase lns with
357 // `realloc(3)` to store more line. Return the number of lines
358 // read. The last item will always be a NULL pointer. It ignore the
359 // "null" (empty) lines
360 size_t readlines(char ***lns, size_t items) {
365 ssize_t l = getline(lines + n, &linelen, stdin);
371 if (linelen == 0 || lines[n][0] == '\n') {
374 continue; // forget about this line
377 strtok(lines[n], "\n"); // get rid of the \n
381 if (n == items - 1) {
383 char **l = realloc(lines, sizeof(char*) * items);
395 // Compute the dimension of the string str once rendered, return the
396 // width and save the width and the height in ret_width and ret_height
397 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
402 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
403 height = r->font->ascent - r->font->descent;
404 width = gi.width - gi.x;
407 XmbTextExtents(*r->font, str, len, nil, &rect);
408 height = rect.height;
411 if (ret_width != nil) *ret_width = width;
412 if (ret_height != nil) *ret_height = height;
416 // Draw the string str
417 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
420 if (tt == PROMPT) xftcolor = r->xft_prompt;
421 if (tt == COMPL) xftcolor = r->xft_completion;
422 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
424 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
427 if (tt == PROMPT) gc = r->prompt;
428 if (tt == COMPL) gc = r->completion;
429 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
430 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
434 // Duplicate the string str and substitute every space with a 'n'
435 char *strdupn(char *str) {
436 int len = strlen(str);
438 if (str == nil || len == 0)
441 char *dup = strdup(str);
445 for (int i = 0; i < len; ++i)
452 // |------------------|----------------------------------------------|
453 // | 20 char text | completion | completion | completion | compl |
454 // |------------------|----------------------------------------------|
455 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
456 int prompt_width = 20; // char
459 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
460 int start_at = ps1xlen;
462 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
463 start_at = start_at * prompt_width + r->padding;
465 int texty = (inner_height(r) + height + r->y_zero) / 2;
467 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
469 int text_len = strlen(text);
470 if (text_len > prompt_width)
471 text = text + (text_len - prompt_width);
472 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
473 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
475 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
477 for (size_t i = r->offset; i < cs->lenght; ++i) {
478 struct completion *c = &cs->completions[i];
480 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
481 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
483 int len = strlen(c->completion);
484 int text_width = text_extents(c->completion, len, r, nil, nil);
486 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
488 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
490 start_at += text_width + r->padding * 2;
492 if (start_at > inner_width(r))
493 break; // don't draw completion if the space isn't enough
497 // |-----------------------------------------------------------------|
499 // |-----------------------------------------------------------------|
501 // |-----------------------------------------------------------------|
503 // |-----------------------------------------------------------------|
504 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
506 text_extents("fjpgl", 5, r, nil, &height);
507 int start_at = r->padding*2 + height;
509 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
510 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
512 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
514 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
515 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
517 start_at += r->y_zero;
519 for (size_t i = r->offset; i < cs->lenght; ++i){
520 struct completion *c = &cs->completions[i];
521 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
522 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
524 int len = strlen(c->completion);
525 text_extents(c->completion, len, r, &width, &height);
526 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
527 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
529 start_at += height + r->padding *2;
531 if (start_at > inner_height(r))
532 break; // don't draw completion if the space isn't enough
536 void draw(struct rendering *r, char *text, struct completions *cs) {
537 if (r->horizontal_layout)
538 draw_horizontally(r, text, cs);
540 draw_vertically(r, text, cs);
544 if (r->border_w != 0)
545 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
547 if (r->border_e != 0)
548 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
550 if (r->border_n != 0)
551 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
553 if (r->border_s != 0)
554 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
556 // send all the work to x
560 /* Set some WM stuff */
561 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
563 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
567 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
568 XInternAtom(d, "ATOM", false),
571 (unsigned char *)&type,
575 /* some window managers honor this properties */
576 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
579 XInternAtom(d, "_NET_WM_STATE", false),
580 XInternAtom(d, "ATOM", false),
583 (unsigned char *)&type,
587 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
590 XInternAtom(d, "_NET_WM_STATE", false),
591 XInternAtom(d, "ATOM", false),
594 (unsigned char *)&type,
598 // setting window hints
599 XClassHint *class_hint = XAllocClassHint();
600 if (class_hint == nil) {
601 fprintf(stderr, "Could not allocate memory for class hint\n");
602 exit(EX_UNAVAILABLE);
604 class_hint->res_name = resname;
605 class_hint->res_class = resclass;
606 XSetClassHint(d, w, class_hint);
609 XSizeHints *size_hint = XAllocSizeHints();
610 if (size_hint == nil) {
611 fprintf(stderr, "Could not allocate memory for size hint\n");
612 exit(EX_UNAVAILABLE);
614 size_hint->flags = PMinSize | PBaseSize;
615 size_hint->min_width = width;
616 size_hint->base_width = width;
617 size_hint->min_height = height;
618 size_hint->base_height = height;
623 // write the width and height of the window `w' respectively in `width'
625 void get_wh(Display *d, Window *w, int *width, int *height) {
626 XWindowAttributes win_attr;
627 XGetWindowAttributes(d, *w, &win_attr);
628 *height = win_attr.height;
629 *width = win_attr.width;
632 int grabfocus(Display *d, Window w) {
633 for (int i = 0; i < 100; ++i) {
636 XGetInputFocus(d, &focuswin, &revert_to_win);
639 XSetInputFocus(d, w, RevertToParent, CurrentTime);
645 // I know this may seem a little hackish BUT is the only way I managed
646 // to actually grab that goddam keyboard. Only one call to
647 // XGrabKeyboard does not always end up with the keyboard grabbed!
648 int take_keyboard(Display *d, Window w) {
650 for (i = 0; i < 100; i++) {
651 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
655 fprintf(stderr, "Cannot grab keyboard\n");
659 // release the keyboard.
660 void release_keyboard(Display *d) {
661 XUngrabKeyboard(d, CurrentTime);
664 // Given a string, try to parse it as a number or return
666 int parse_integer(const char *str, int default_value) {
669 long lval = strtol(str, &ep, 10);
670 if (str[0] == '\0' || *ep != '\0') { // NaN
671 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
672 return default_value;
674 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
675 (lval > INT_MAX || lval < INT_MIN)) {
676 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
677 return default_value;
682 // like parse_integer, but if the value ends with a `%' then its
683 // treated like a percentage (`max' is used to compute the percentage)
684 int parse_int_with_percentage(const char *str, int default_value, int max) {
685 int len = strlen(str);
686 if (len > 0 && str[len-1] == '%') {
687 char *cpy = strdup(str);
688 check_allocation(cpy);
690 int val = parse_integer(cpy, default_value);
692 return val * max / 100;
694 return parse_integer(str, default_value);
697 // like parse_int_with_percentage but understands some special values
698 // - "middle" that is (max - self) / 2
699 // - "start" that is 0
700 // - "end" that is (max - self)
701 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
702 if (!strcmp(str, "start"))
704 if (!strcmp(str, "middle"))
705 return (max - self)/2;
706 if (!strcmp(str, "end"))
708 return parse_int_with_percentage(str, default_value, max);
711 // parse a string like a css value (for example like the css
712 // margin/padding properties). Will ALWAYS return an array of 4 word
713 // TODO: harden this function!
714 char **parse_csslike(const char *str) {
715 char *s = strdup(str);
719 char **ret = malloc(4 * sizeof(char*));
727 while ((token = strsep(&s, " ")) != NULL && i < 4) {
728 ret[i] = strdup(token);
733 for (int j = 1; j < 4; j++)
734 ret[j] = strdup(ret[0]);
737 ret[2] = strdup(ret[0]);
738 ret[3] = strdup(ret[1]);
742 ret[3] = strdup(ret[1]);
744 // Before we didn't check for the return type of strdup, here we will
746 bool any_null = false;
747 for (int i = 0; i < 4; ++i)
748 any_null = ret[i] == nil || any_null;
751 for (int i = 0; i < 4; ++i)
755 if (i == 0 || any_null) {
764 // Given an event, try to understand what the user wants. If the
765 // return value is ADD_CHAR then `input' is a pointer to a string that
766 // will need to be free'ed.
767 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
768 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
771 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
772 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
774 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
777 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
780 // try to read what the user pressed
781 char str[SYM_BUF_SIZE] = {0};
783 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
784 if (s == XBufferOverflow) {
785 // should not happen since there are no utf-8 characters larger
787 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
791 if (ev->state & ControlMask) {
792 if (!strcmp(str, "")) // C-u
794 if (!strcmp(str, "")) // C-w
796 if (!strcmp(str, "")) // C-h
798 if (!strcmp(str, "\r")) // C-m
799 return CONFIRM_CONTINUE;
800 if (!strcmp(str, "")) // C-p
802 if (!strcmp(str, "")) // C-n
804 if (!strcmp(str, "")) // C-c
806 if (!strcmp(str, "\t")) // C-i
807 return TOGGLE_FIRST_SELECTED;
810 *input = strdup(str);
812 fprintf(stderr, "Error while allocating memory for key.\n");
819 // Given the name of the program (argv[0]?) print a small help on stderr
820 void usage(char *prgname) {
821 fprintf(stderr, "%s [-hvam] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
822 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
823 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
824 " [-e window_id]\n", prgname);
827 // small function used in the event loop
828 void confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen) {
829 if ((cs->selected != -1) || (cs->lenght > 0 && r->first_selected)) {
830 // if there is something selected expand it and return
831 int index = cs->selected == -1 ? 0 : cs->selected;
832 struct completion *c = cs->completions;
839 char *t = c->rcompletion;
843 fprintf(stderr, "Memory allocation error\n");
846 *textlen = strlen(*text);
849 // cannot accept arbitrary text
856 enum state loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines) {
857 enum state status = LOOPING;
858 while (status == LOOPING) {
860 XNextEvent(r->d, &e);
862 if (XFilterEvent(&e, r->w))
867 XRefreshKeyboardMapping(&e.xmapping);
872 if (e.xfocus.window != r->w)
873 grabfocus(r->d, r->w);
876 case VisibilityNotify:
877 if (e.xvisibility.state != VisibilityUnobscured)
878 XRaiseWindow(r->d, r->w);
882 get_wh(r->d, &r->w, &r->width, &r->height);
887 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
890 switch (parse_event(r->d, ev, r->xic, &input)) {
897 confirm(&status, r, cs, text, textlen);
901 case CONFIRM_CONTINUE: {
903 confirm(&status, r, cs, text, textlen);
908 complete(cs, r->first_selected, true, text, textlen, &status);
909 r->offset = cs->selected;
914 complete(cs, r->first_selected, false, text, textlen, &status);
915 r->offset = cs->selected;
921 update_completions(cs, *text, lines, vlines, r->first_selected);
927 update_completions(cs, *text, lines, vlines, r->first_selected);
932 for (int i = 0; i < *textlen; ++i)
934 update_completions(cs, *text, lines, vlines, r->first_selected);
940 int str_len = strlen(input);
942 // sometimes a strange key is pressed (i.e. ctrl alone),
943 // so input will be empty. Don't need to update completion
948 for (int i = 0; i < str_len; ++i) {
949 *textlen = pushc(text, *textlen, input[i]);
950 if (*textlen == -1) {
951 fprintf(stderr, "Memory allocation error\n");
957 update_completions(cs, *text, lines, vlines, r->first_selected);
964 case TOGGLE_FIRST_SELECTED:
965 r->first_selected = !r->first_selected;
966 if (r->first_selected && cs->selected < 0)
968 if (!r->first_selected && cs->selected == 0)
975 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
976 /* if (ev->button == Button1) { /\* click *\/ */
977 /* int x = ev->x - r.border_w; */
978 /* int y = ev->y - r.border_n; */
979 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
982 if (ev->button == Button4) /* scroll up */
983 r->offset = MAX((ssize_t)r->offset - 1, 0);
985 if (ev->button == Button5) /* scroll down */
986 r->offset = MIN(r->offset + 1, cs->lenght - 1);
998 int main(int argc, char **argv) {
1000 // stdio & rpat: to read and write stdio/stdout
1001 // unix: to connect to Xorg
1002 pledge("stdio rpath unix", "");
1007 // by default the first completion isn't selected
1008 bool first_selected = false;
1010 // our parent window
1011 char *parent_window_id = nil;
1013 // the user can input arbitrary text
1014 bool free_text = true;
1016 // the user can select multiple entries
1017 bool multiple_select = false;
1019 // first round of args parsing
1021 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1026 case 'v': // version
1027 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1030 parent_window_id = strdup(optarg);
1031 check_allocation(parent_window_id);
1034 sep = strdup(optarg);
1035 check_allocation(sep);
1042 multiple_select = true;
1050 // read the lines from stdin
1051 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
1052 check_allocation(lines);
1053 size_t nlines = readlines(&lines, INITIAL_ITEMS);
1054 char **vlines = nil;
1056 int l = strlen(sep);
1057 vlines = calloc(nlines, sizeof(char*));
1058 check_allocation(vlines);
1060 for (int i = 0; lines[i] != nil; i++) {
1061 char *t = strstr(lines[i], sep);
1063 vlines[i] = lines[i];
1069 setlocale(LC_ALL, getenv("LANG"));
1071 enum state status = LOOPING;
1073 // where the monitor start (used only with xinerama)
1077 // width and height of the window
1081 // position on the screen
1085 // the default padding
1088 // the default borders
1094 // the prompt. We duplicate the string so later is easy to free (in
1095 // the case the user provide its own prompt)
1096 char *ps1 = strdup("$ ");
1097 check_allocation(ps1);
1099 // same for the font name
1100 char *fontname = strdup(default_fontname);
1101 check_allocation(fontname);
1104 char *text = malloc(textlen * sizeof(char));
1105 check_allocation(text);
1107 /* struct completions *cs = filter(text, lines); */
1108 struct completions *cs = compls_new(nlines);
1109 check_allocation(cs);
1111 // start talking to xorg
1112 Display *d = XOpenDisplay(nil);
1114 fprintf(stderr, "Could not open display!\n");
1115 return EX_UNAVAILABLE;
1118 Window parent_window;
1120 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1121 parent_window = DefaultRootWindow(d);
1128 get_wh(d, &parent_window, &d_width, &d_height);
1131 if (!embed && XineramaIsActive(d)) {
1133 int number_of_screens = XScreenCount(d);
1136 int root_x, root_y, win_x, win_y;
1139 for (int i = 0; i < number_of_screens; ++i) {
1140 root = XRootWindow(d, i);
1141 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1145 fprintf(stderr, "No mouse found.\n");
1150 // now find in which monitor the mice is on
1152 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1154 for (int i = 0; i < monitors; ++i) {
1155 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1156 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1157 offset_x = info[i].x_org;
1158 offset_y = info[i].y_org;
1159 d_width = info[i].width;
1160 d_height = info[i].height;
1169 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1172 compl_highlighted_fg, compl_highlighted_bg,
1173 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1175 bool horizontal_layout = true;
1179 char *xrm = XResourceManagerString(d);
1180 XrmDatabase xdb = nil;
1182 xdb = XrmGetStringDatabase(xrm);
1186 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1187 fontname = strdup(value.addr);
1188 check_allocation(fontname);
1190 fprintf(stderr, "no font defined, using %s\n", fontname);
1193 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1194 horizontal_layout = !strcmp(value.addr, "horizontal");
1196 fprintf(stderr, "no layout defined, using horizontal\n");
1198 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1200 ps1 = normalize_str(value.addr);
1202 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1205 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1206 width = parse_int_with_percentage(value.addr, width, d_width);
1208 fprintf(stderr, "no width defined, using %d\n", width);
1210 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1211 height = parse_int_with_percentage(value.addr, height, d_height);
1213 fprintf(stderr, "no height defined, using %d\n", height);
1215 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1216 x = parse_int_with_pos(value.addr, x, d_width, width);
1218 fprintf(stderr, "no x defined, using %d\n", x);
1220 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1221 y = parse_int_with_pos(value.addr, y, d_height, height);
1223 fprintf(stderr, "no y defined, using %d\n", y);
1225 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1226 padding = parse_integer(value.addr, padding);
1228 fprintf(stderr, "no padding defined, using %d\n", padding);
1230 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1231 char **borders = parse_csslike(value.addr);
1232 if (borders != nil) {
1233 border_n = parse_integer(borders[0], 0);
1234 border_e = parse_integer(borders[1], 0);
1235 border_s = parse_integer(borders[2], 0);
1236 border_w = parse_integer(borders[3], 0);
1238 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1241 fprintf(stderr, "no border defined, using 0.\n");
1245 // TODO: tmp needs to be free'd after every allocation?
1248 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1249 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1251 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1253 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1254 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1256 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1259 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1260 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1262 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1264 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1265 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1267 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1269 // completion highlighted
1270 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1271 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1273 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1275 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1276 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1278 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1281 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1282 char **colors = parse_csslike(value.addr);
1283 if (colors != nil) {
1284 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1285 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1286 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1287 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1289 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1292 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1293 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1294 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1295 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1299 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1300 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1301 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1302 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1303 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1304 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1305 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1306 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1307 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1310 // second round of args parsing
1311 optind = 0; // reset the option index
1312 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1315 first_selected = true;
1318 // free_text -- this case was already catched
1321 // separator -- this case was already catched
1324 // (embedding mymenu) this case was already catched.
1326 // (multiple selection) this case was already catched.
1329 char *newprompt = strdup(optarg);
1330 if (newprompt != nil) {
1337 x = parse_int_with_pos(optarg, x, d_width, width);
1340 y = parse_int_with_pos(optarg, y, d_height, height);
1343 padding = parse_integer(optarg, padding);
1346 horizontal_layout = !strcmp(optarg, "horizontal");
1349 char *newfont = strdup(optarg);
1350 if (newfont != nil) {
1357 width = parse_int_with_percentage(optarg, width, d_width);
1360 height = parse_int_with_percentage(optarg, height, d_height);
1363 char **borders = parse_csslike(optarg);
1364 if (borders != nil) {
1365 border_n = parse_integer(borders[0], 0);
1366 border_e = parse_integer(borders[1], 0);
1367 border_s = parse_integer(borders[2], 0);
1368 border_w = parse_integer(borders[3], 0);
1370 fprintf(stderr, "Error parsing b option\n");
1375 char **colors = parse_csslike(optarg);
1376 if (colors != nil) {
1378 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1379 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1380 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1381 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1383 fprintf(stderr, "error while parsing B option\n");
1389 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1394 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1399 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1404 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1409 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1414 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1418 fprintf(stderr, "Unrecognized option %c\n", ch);
1424 // since only now we know if the first should be selected, update
1425 // the completion here
1426 update_completions(cs, text, lines, vlines, first_selected);
1430 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1432 char **missing_charset_list;
1433 int missing_charset_count;
1434 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1436 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1437 return EX_UNAVAILABLE;
1441 // create the window
1442 XSetWindowAttributes attr;
1443 attr.override_redirect = true;
1444 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1446 Window w = XCreateWindow(d, // display
1447 parent_window, // parent
1448 x + offset_x, y + offset_y, // x y
1449 width, height, // w h
1451 CopyFromParent, // depth
1452 InputOutput, // class
1453 CopyFromParent, // visual
1454 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1457 set_win_atoms_hints(d, w, width, height);
1459 // we want some events
1460 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1463 // if embed, listen for other events as well
1465 XSelectInput(d, parent_window, FocusChangeMask);
1466 Window *children, parent, root;
1467 unsigned int children_no;
1468 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1469 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1470 XSelectInput(d, children[i], FocusChangeMask);
1477 take_keyboard(d, w);
1479 // Create some graphics contexts
1481 /* values.font = font->fid; */
1483 struct rendering r = {
1492 .free_text = free_text,
1493 .first_selected = first_selected,
1494 .multiple_select = multiple_select,
1495 .border_n = border_n,
1496 .border_e = border_e,
1497 .border_s = border_s,
1498 .border_w = border_w,
1499 .horizontal_layout = horizontal_layout,
1501 .ps1len = strlen(ps1),
1502 .prompt = XCreateGC(d, w, 0, &values),
1503 .prompt_bg = XCreateGC(d, w, 0, &values),
1504 .completion = XCreateGC(d, w, 0, &values),
1505 .completion_bg = XCreateGC(d, w, 0, &values),
1506 .completion_highlighted = XCreateGC(d, w, 0, &values),
1507 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1508 .border_n_bg = XCreateGC(d, w, 0, &values),
1509 .border_e_bg = XCreateGC(d, w, 0, &values),
1510 .border_s_bg = XCreateGC(d, w, 0, &values),
1511 .border_w_bg = XCreateGC(d, w, 0, &values),
1520 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1523 XRenderColor xrcolor;
1524 xrcolor.red = p_fg.red;
1525 xrcolor.green = p_fg.red;
1526 xrcolor.blue = p_fg.red;
1527 xrcolor.alpha = 65535;
1528 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1531 xrcolor.red = compl_fg.red;
1532 xrcolor.green = compl_fg.green;
1533 xrcolor.blue = compl_fg.blue;
1534 xrcolor.alpha = 65535;
1535 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1537 // completion highlighted
1538 xrcolor.red = compl_highlighted_fg.red;
1539 xrcolor.green = compl_highlighted_fg.green;
1540 xrcolor.blue = compl_highlighted_fg.blue;
1541 xrcolor.alpha = 65535;
1542 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1545 // load the colors in our GCs
1546 XSetForeground(d, r.prompt, p_fg.pixel);
1547 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1548 XSetForeground(d, r.completion, compl_fg.pixel);
1549 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1550 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1551 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1552 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1553 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1554 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1555 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1557 // open the X input method
1558 XIM xim = XOpenIM(d, xdb, resname, resclass);
1559 check_allocation(xim);
1561 XIMStyles *xis = nil;
1562 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1563 fprintf(stderr, "Input Styles could not be retrieved\n");
1564 return EX_UNAVAILABLE;
1567 XIMStyle bestMatchStyle = 0;
1568 for (int i = 0; i < xis->count_styles; ++i) {
1569 XIMStyle ts = xis->supported_styles[i];
1570 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1571 bestMatchStyle = ts;
1577 if (!bestMatchStyle) {
1578 fprintf(stderr, "No matching input style could be determined\n");
1581 r.xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1582 check_allocation(r.xic);
1584 // draw the window for the first time
1588 while (status == LOOPING || status == OK_LOOP) {
1589 status = loop(&r, &text, &textlen, cs, lines, vlines);
1592 printf("%s\n", text);
1594 if (!multiple_select && status == OK_LOOP)
1598 release_keyboard(r.d);
1601 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1602 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1603 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1612 while ((l = *lns) != nil) {
1621 XDestroyWindow(r.d, r.w);
1624 return status != OK;