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 "hvae:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:"
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 #define INITIAL_ITEMS 64
57 #define check_allocation(a) { \
59 fprintf(stderr, "Could not allocate memory\n"); \
64 #define inner_height(r) (r->height - r->border_n - r->border_s)
65 #define inner_width(r) (r->width - r->border_e - r->border_w)
67 // The possible state of the event loop.
68 enum state {LOOPING, OK, ERR};
70 // for the drawing-related function. The text to be rendered could be
71 // the prompt, a completion or a highlighted completion
72 enum text_type {PROMPT, COMPL, COMPL_HIGH};
74 // These are the possible action to be performed after user input.
88 Display *d; // connection to xorg
93 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
94 int y_zero; // the same a x_zero, only for the y axis
102 bool horizontal_layout;
113 GC completion_highlighted;
114 GC completion_highlighted_bg;
123 XftColor xft_completion;
124 XftColor xft_completion_highlighted;
130 // A simple linked list to store the completions.
133 struct completion *next;
137 struct completion *completions;
142 // return a newly allocated (and empty) completion list
143 struct completions *compls_new() {
144 struct completions *cs = malloc(sizeof(struct completions));
149 cs->completions = nil;
155 struct completion *compl_new() {
156 struct completion *c = malloc(sizeof(struct completion));
165 // delete ONLY the given completion (i.e. does not free c->next...)
166 void compl_delete(struct completion *c) {
170 // delete the current completion and the next (c->next) and so on...
171 void compl_delete_rec(struct completion *c) {
173 struct completion *t = c->next;
179 void compls_delete(struct completions *cs) {
183 compl_delete_rec(cs->completions);
187 // create a completion list from a text and the list of possible
188 // completions (null terminated). Expects a non-null `cs'.
189 void filter(struct completions *cs, char *text, char **lines) {
190 struct completion *c = compl_new();
201 char *l = lines[index];
205 if (strcasestr(l, text) != nil) {
208 c->next = compl_new();
220 struct completion *f = cs->completions->next;
221 compl_delete(cs->completions);
223 cs->lenght = matching;
227 // update the given completion, that is: clean the old cs & generate a new one.
228 void update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
229 compl_delete_rec(cs->completions);
230 filter(cs, text, lines);
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;
267 // find the selected item
274 *text = strdup(n->completion);
276 fprintf(stderr, "Memory allocation error!\n");
280 *textlen = strlen(*text);
283 // push the character c at the end of the string pointed by p
284 int pushc(char **p, int maxlen, char c) {
285 int len = strnlen(*p, maxlen);
287 if (!(len < maxlen -2)) {
288 maxlen += maxlen >> 1;
289 char *newptr = realloc(*p, maxlen);
290 if (newptr == nil) { // bad!
301 // return the number of character
302 int utf8strnlen(char *s, int maxlen) {
304 while (*s && maxlen > 0) {
305 len += (*s++ & 0xc0) != 0x80;
311 // remove the last *glyph* from the *utf8* string!
312 // this is different from just setting the last byte to 0 (in some
313 // cases ofc). The actual implementation is quite inefficient because
314 // it remove the last byte until the number of glyphs doesn't change
315 void popc(char *p, int maxlen) {
316 int len = strnlen(p, maxlen);
321 int ulen = utf8strnlen(p, maxlen);
322 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
328 // If the string is surrounded by quotes (`"`) remove them and replace
329 // every `\"` in the string with `"`
330 char *normalize_str(const char *str) {
331 int len = strlen(str);
335 char *s = calloc(len, sizeof(char));
344 str += 2; // skip this and the next char
351 str++; // skip only this char
361 // read an arbitrary long line from stdin and return a pointer to it
362 // TODO: resize the allocated memory to exactly fit the string once
364 char *readline(bool *eof) {
366 char *str = calloc(maxlen, sizeof(char));
368 fprintf(stderr, "Cannot allocate memory!\n");
369 exit(EX_UNAVAILABLE);
373 while((c = getchar()) != EOF) {
377 maxlen = pushc(&str, maxlen, c);
380 fprintf(stderr, "Cannot allocate memory!\n");
381 exit(EX_UNAVAILABLE);
388 // read an arbitrary amount of text until an EOF and store it in
389 // lns. `items` is the capacity of lns. It may increase lns with
390 // `realloc(3)` to store more line. Return the number of lines
391 // read. The last item will always be a NULL pointer. It ignore the
392 // "null" (empty) lines
393 int readlines (char ***lns, int items) {
394 bool finished = false;
398 lines[n] = readline(&finished);
400 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
402 --n; // forget about this line
410 if (n == items - 1) {
412 char **l = realloc(lines, sizeof(char*) * items);
424 // Compute the dimension of the string str once rendered, return the
425 // width and save the width and the height in ret_width and ret_height
426 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
431 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
432 /* height = gi.height; */
433 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
434 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
435 height = r->font->ascent - r->font->descent;
436 width = gi.width - gi.x;
439 XmbTextExtents(*r->font, str, len, nil, &rect);
440 height = rect.height;
443 if (ret_width != nil) *ret_width = width;
444 if (ret_height != nil) *ret_height = height;
448 // Draw the string str
449 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
452 if (tt == PROMPT) xftcolor = r->xft_prompt;
453 if (tt == COMPL) xftcolor = r->xft_completion;
454 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
456 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
459 if (tt == PROMPT) gc = r->prompt;
460 if (tt == COMPL) gc = r->completion;
461 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
462 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
466 // Duplicate the string str and substitute every space with a 'n'
467 char *strdupn(char *str) {
468 int len = strlen(str);
470 if (str == nil || len == 0)
473 char *dup = strdup(str);
477 for (int i = 0; i < len; ++i)
484 // |------------------|----------------------------------------------|
485 // | 20 char text | completion | completion | completion | compl |
486 // |------------------|----------------------------------------------|
487 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
488 int prompt_width = 20; // char
491 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
492 int start_at = ps1xlen;
494 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
495 start_at = start_at * prompt_width + r->padding;
497 int texty = (inner_height(r) + height + r->y_zero) / 2;
499 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
501 int text_len = strlen(text);
502 if (text_len > prompt_width)
503 text = text + (text_len - prompt_width);
504 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
505 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
507 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
509 struct completion *c = cs->completions;
510 for (int i = 0; c != nil; ++i) {
511 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
512 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
514 int len = strlen(c->completion);
515 int text_width = text_extents(c->completion, len, r, nil, nil);
517 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
519 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
521 start_at += text_width + r->padding * 2;
523 if (start_at > inner_width(r))
524 break; // don't draw completion if the space isn't enough
530 // |-----------------------------------------------------------------|
532 // |-----------------------------------------------------------------|
534 // |-----------------------------------------------------------------|
536 // |-----------------------------------------------------------------|
537 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
539 text_extents("fjpgl", 5, r, nil, &height);
540 int start_at = height + r->padding;
542 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
543 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
545 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
547 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
548 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
550 start_at += r->padding + r->y_zero;
552 struct completion *c = cs->completions;
553 for (int i = 0; c != nil; ++i){
554 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
555 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
557 int len = strlen(c->completion);
558 text_extents(c->completion, len, r, &width, &height);
559 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
560 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
562 start_at += height + r->padding *2;
564 if (start_at > inner_height(r))
565 break; // don't draw completion if the space isn't enough
571 void draw(struct rendering *r, char *text, struct completions *cs) {
572 if (r->horizontal_layout)
573 draw_horizontally(r, text, cs);
575 draw_vertically(r, text, cs);
579 if (r->border_w != 0)
580 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
582 if (r->border_e != 0)
583 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
585 if (r->border_n != 0)
586 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
588 if (r->border_s != 0)
589 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
591 // send all the work to x
595 /* Set some WM stuff */
596 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
598 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
602 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
603 XInternAtom(d, "ATOM", false),
606 (unsigned char *)&type,
610 /* some window managers honor this properties */
611 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
614 XInternAtom(d, "_NET_WM_STATE", false),
615 XInternAtom(d, "ATOM", false),
618 (unsigned char *)&type,
622 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
625 XInternAtom(d, "_NET_WM_STATE", false),
626 XInternAtom(d, "ATOM", false),
629 (unsigned char *)&type,
633 // setting window hints
634 XClassHint *class_hint = XAllocClassHint();
635 if (class_hint == nil) {
636 fprintf(stderr, "Could not allocate memory for class hint\n");
637 exit(EX_UNAVAILABLE);
639 class_hint->res_name = resname;
640 class_hint->res_class = resclass;
641 XSetClassHint(d, w, class_hint);
644 XSizeHints *size_hint = XAllocSizeHints();
645 if (size_hint == nil) {
646 fprintf(stderr, "Could not allocate memory for size hint\n");
647 exit(EX_UNAVAILABLE);
649 size_hint->flags = PMinSize | PBaseSize;
650 size_hint->min_width = width;
651 size_hint->base_width = width;
652 size_hint->min_height = height;
653 size_hint->base_height = height;
658 // write the width and height of the window `w' respectively in `width'
660 void get_wh(Display *d, Window *w, int *width, int *height) {
661 XWindowAttributes win_attr;
662 XGetWindowAttributes(d, *w, &win_attr);
663 *height = win_attr.height;
664 *width = win_attr.width;
667 int grabfocus(Display *d, Window w) {
668 for (int i = 0; i < 100; ++i) {
671 XGetInputFocus(d, &focuswin, &revert_to_win);
674 XSetInputFocus(d, w, RevertToParent, CurrentTime);
680 // I know this may seem a little hackish BUT is the only way I managed
681 // to actually grab that goddam keyboard. Only one call to
682 // XGrabKeyboard does not always end up with the keyboard grabbed!
683 int take_keyboard(Display *d, Window w) {
685 for (i = 0; i < 100; i++) {
686 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
690 fprintf(stderr, "Cannot grab keyboard\n");
694 // release the keyboard.
695 void release_keyboard(Display *d) {
696 XUngrabKeyboard(d, CurrentTime);
699 // Given a string, try to parse it as a number or return
701 int parse_integer(const char *str, int default_value) {
704 long lval = strtol(str, &ep, 10);
705 if (str[0] == '\0' || *ep != '\0') { // NaN
706 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
707 return default_value;
709 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
710 (lval > INT_MAX || lval < INT_MIN)) {
711 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
712 return default_value;
717 // like parse_integer, but if the value ends with a `%' then its
718 // treated like a percentage (`max' is used to compute the percentage)
719 int parse_int_with_percentage(const char *str, int default_value, int max) {
720 int len = strlen(str);
721 if (len > 0 && str[len-1] == '%') {
722 char *cpy = strdup(str);
723 check_allocation(cpy);
725 int val = parse_integer(cpy, default_value);
727 return val * max / 100;
729 return parse_integer(str, default_value);
732 // like parse_int_with_percentage but understands some special values
733 // - "middle" that is (max - self) / 2
734 // - "start" that is 0
735 // - "end" that is (max - self)
736 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
737 if (!strcmp(str, "start"))
739 if (!strcmp(str, "middle"))
740 return (max - self)/2;
741 if (!strcmp(str, "end"))
743 return parse_int_with_percentage(str, default_value, max);
746 // parse a string like a css value (for example like the css
747 // margin/padding properties). Will ALWAYS return an array of 4 word
748 // TODO: harden this function!
749 char **parse_csslike(const char *str) {
750 char *s = strdup(str);
754 char **ret = malloc(4 * sizeof(char*));
762 while ((token = strsep(&s, " ")) != NULL && i < 4) {
763 ret[i] = strdup(token);
768 for (int j = 1; j < 4; j++)
769 ret[j] = strdup(ret[0]);
772 ret[2] = strdup(ret[0]);
773 ret[3] = strdup(ret[1]);
777 ret[3] = strdup(ret[1]);
779 // Before we didn't check for the return type of strdup, here we will
781 bool any_null = false;
782 for (int i = 0; i < 4; ++i)
783 any_null = ret[i] == nil || any_null;
786 for (int i = 0; i < 4; ++i)
790 if (i == 0 || any_null) {
799 // Given an event, try to understand what the user wants. If the
800 // return value is ADD_CHAR then `input' is a pointer to a string that
801 // will need to be free'ed.
802 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
803 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
806 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
807 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
809 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
812 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
815 // try to read what the user pressed
816 char str[SYM_BUF_SIZE] = {0};
818 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
819 if (s == XBufferOverflow) {
820 // should not happen since there are no utf-8 characters larger
822 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
826 if (ev->state & ControlMask) {
827 if (!strcmp(str, "")) // C-u
829 if (!strcmp(str, "")) // C-w
831 if (!strcmp(str, "")) // C-h
833 if (!strcmp(str, "\r")) // C-m
835 if (!strcmp(str, "")) // C-p
837 if (!strcmp(str, "")) // C-n
839 if (!strcmp(str, "")) // C-c
841 if (!strcmp(str, "\t")) // C-i
842 return TOGGLE_FIRST_SELECTED;
845 *input = strdup(str);
847 fprintf(stderr, "Error while allocating memory for key.\n");
854 // Given the name of the program (argv[0]?) print a small help on stderr
855 void usage(char *prgname) {
856 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
857 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
858 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
859 " [-w window_id]\n", prgname);
862 int main(int argc, char **argv) {
864 // stdio & rpat: to read and write stdio/stdout
865 // unix: to connect to Xorg
866 pledge("stdio rpath unix", "");
869 // by default the first completion isn't selected
870 bool first_selected = false;
872 char *parent_window_id = nil;
874 // first round of args parsing
876 while ((ch = getopt(argc, argv, ARGS)) != -1) {
882 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
885 parent_window_id = strdup(optarg);
886 check_allocation(parent_window_id);
893 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
894 readlines(&lines, INITIAL_ITEMS);
896 setlocale(LC_ALL, getenv("LANG"));
898 enum state status = LOOPING;
900 // where the monitor start (used only with xinerama)
904 // width and height of the window
908 // position on the screen
912 // the default padding
915 // the default borders
921 // the prompt. We duplicate the string so later is easy to free (in
922 // the case the user provide its own prompt)
923 char *ps1 = strdup("$ ");
924 check_allocation(ps1);
926 // same for the font name
927 char *fontname = strdup(default_fontname);
928 check_allocation(fontname);
931 char *text = malloc(textlen * sizeof(char));
932 check_allocation(text);
934 /* struct completions *cs = filter(text, lines); */
935 struct completions *cs = compls_new();
936 check_allocation(cs);
938 // start talking to xorg
939 Display *d = XOpenDisplay(nil);
941 fprintf(stderr, "Could not open display!\n");
942 return EX_UNAVAILABLE;
945 Window parent_window;
947 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
948 parent_window = DefaultRootWindow(d);
955 get_wh(d, &parent_window, &d_width, &d_height);
957 fprintf(stderr, "d_width %d, d_height %d\n", d_width, d_height);
960 if (!embed && XineramaIsActive(d)) {
962 int number_of_screens = XScreenCount(d);
965 int root_x, root_y, win_x, win_y;
968 for (int i = 0; i < number_of_screens; ++i) {
969 root = XRootWindow(d, i);
970 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
974 fprintf(stderr, "No mouse found.\n");
979 // now find in which monitor the mice is on
981 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
983 for (int i = 0; i < monitors; ++i) {
984 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
985 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
986 offset_x = info[i].x_org;
987 offset_y = info[i].y_org;
988 d_width = info[i].width;
989 d_height = info[i].height;
998 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1001 compl_highlighted_fg, compl_highlighted_bg,
1002 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1004 bool horizontal_layout = true;
1008 char *xrm = XResourceManagerString(d);
1009 XrmDatabase xdb = nil;
1011 xdb = XrmGetStringDatabase(xrm);
1015 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1016 fontname = strdup(value.addr);
1017 check_allocation(fontname);
1020 fprintf(stderr, "no font defined, using %s\n", fontname);
1022 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
1023 horizontal_layout = !strcmp(value.addr, "horizontal");
1026 fprintf(stderr, "no layout defined, using horizontal\n");
1028 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1030 ps1 = normalize_str(value.addr);
1032 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1034 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1035 width = parse_int_with_percentage(value.addr, width, d_width);
1037 fprintf(stderr, "no width defined, using %d\n", width);
1039 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1040 height = parse_int_with_percentage(value.addr, height, d_height);
1042 fprintf(stderr, "no height defined, using %d\n", height);
1044 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1045 x = parse_int_with_pos(value.addr, x, d_width, width);
1047 fprintf(stderr, "no x defined, using %d\n", x);
1049 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1050 y = parse_int_with_pos(value.addr, y, d_height, height);
1052 fprintf(stderr, "no y defined, using %d\n", y);
1054 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1055 padding = parse_integer(value.addr, padding);
1057 fprintf(stderr, "no padding defined, using %d\n", padding);
1059 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1060 char **borders = parse_csslike(value.addr);
1061 if (borders != nil) {
1062 border_n = parse_integer(borders[0], 0);
1063 border_e = parse_integer(borders[1], 0);
1064 border_s = parse_integer(borders[2], 0);
1065 border_w = parse_integer(borders[3], 0);
1067 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1070 fprintf(stderr, "no border defined, using 0.\n");
1074 // TODO: tmp needs to be free'd after every allocation?
1077 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1078 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1080 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1082 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1083 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1085 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1088 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1089 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1091 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1093 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1094 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1096 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1098 // completion highlighted
1099 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1100 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1102 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1104 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1105 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1107 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1110 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1111 char **colors = parse_csslike(value.addr);
1112 if (colors != nil) {
1113 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1114 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1115 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1116 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1118 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1121 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1122 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1123 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1124 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1128 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1129 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1130 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1131 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1132 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1133 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1134 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1135 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1136 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1139 // second round of args parsing
1140 optind = 0; // reset the option index
1141 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1144 first_selected = true;
1147 // (embedding mymenu) this case was already catched.
1150 char *newprompt = strdup(optarg);
1151 if (newprompt != nil) {
1158 x = parse_int_with_pos(optarg, x, d_width, width);
1161 y = parse_int_with_pos(optarg, y, d_height, height);
1164 padding = parse_integer(optarg, padding);
1167 horizontal_layout = !strcmp(optarg, "horizontal");
1170 char *newfont = strdup(optarg);
1171 if (newfont != nil) {
1178 width = parse_int_with_percentage(optarg, width, d_width);
1181 height = parse_int_with_percentage(optarg, height, d_height);
1184 char **borders = parse_csslike(optarg);
1185 if (borders != nil) {
1186 border_n = parse_integer(borders[0], 0);
1187 border_e = parse_integer(borders[1], 0);
1188 border_s = parse_integer(borders[2], 0);
1189 border_w = parse_integer(borders[3], 0);
1191 fprintf(stderr, "Error parsing b option\n");
1196 char **colors = parse_csslike(optarg);
1197 if (colors != nil) {
1199 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1200 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1201 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1202 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1204 fprintf(stderr, "error while parsing B option\n");
1210 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1215 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1220 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1225 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1230 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1235 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1239 fprintf(stderr, "Unrecognized option %c\n", ch);
1245 // since only now we know if the first should be selected, update
1246 // the completion here
1247 update_completions(cs, text, lines, first_selected);
1251 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1253 char **missing_charset_list;
1254 int missing_charset_count;
1255 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1257 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1258 return EX_UNAVAILABLE;
1262 // create the window
1263 XSetWindowAttributes attr;
1264 attr.override_redirect = true;
1265 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1267 Window w = XCreateWindow(d, // display
1268 parent_window, // parent
1269 x + offset_x, y + offset_y, // x y
1270 width, height, // w h
1272 CopyFromParent, // depth
1273 InputOutput, // class
1274 CopyFromParent, // visual
1275 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1278 set_win_atoms_hints(d, w, width, height);
1280 // we want some events
1281 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1284 // if embed, listen for other events as well
1286 XSelectInput(d, parent_window, FocusChangeMask);
1287 Window *children, parent, root;
1288 unsigned int children_no;
1289 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1290 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1291 XSelectInput(d, children[i], FocusChangeMask);
1298 take_keyboard(d, w);
1300 // Create some graphics contexts
1302 /* values.font = font->fid; */
1304 struct rendering r = {
1312 .border_n = border_n,
1313 .border_e = border_e,
1314 .border_s = border_s,
1315 .border_w = border_w,
1316 .horizontal_layout = horizontal_layout,
1318 .ps1len = strlen(ps1),
1319 .prompt = XCreateGC(d, w, 0, &values),
1320 .prompt_bg = XCreateGC(d, w, 0, &values),
1321 .completion = XCreateGC(d, w, 0, &values),
1322 .completion_bg = XCreateGC(d, w, 0, &values),
1323 .completion_highlighted = XCreateGC(d, w, 0, &values),
1324 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1325 .border_n_bg = XCreateGC(d, w, 0, &values),
1326 .border_e_bg = XCreateGC(d, w, 0, &values),
1327 .border_s_bg = XCreateGC(d, w, 0, &values),
1328 .border_w_bg = XCreateGC(d, w, 0, &values),
1337 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1340 XRenderColor xrcolor;
1341 xrcolor.red = p_fg.red;
1342 xrcolor.green = p_fg.red;
1343 xrcolor.blue = p_fg.red;
1344 xrcolor.alpha = 65535;
1345 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1348 xrcolor.red = compl_fg.red;
1349 xrcolor.green = compl_fg.green;
1350 xrcolor.blue = compl_fg.blue;
1351 xrcolor.alpha = 65535;
1352 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1354 // completion highlighted
1355 xrcolor.red = compl_highlighted_fg.red;
1356 xrcolor.green = compl_highlighted_fg.green;
1357 xrcolor.blue = compl_highlighted_fg.blue;
1358 xrcolor.alpha = 65535;
1359 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1362 // load the colors in our GCs
1363 XSetForeground(d, r.prompt, p_fg.pixel);
1364 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1365 XSetForeground(d, r.completion, compl_fg.pixel);
1366 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1367 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1368 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1369 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1370 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1371 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1372 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1374 // open the X input method
1375 XIM xim = XOpenIM(d, xdb, resname, resclass);
1376 check_allocation(xim);
1378 XIMStyles *xis = nil;
1379 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1380 fprintf(stderr, "Input Styles could not be retrieved\n");
1381 return EX_UNAVAILABLE;
1384 XIMStyle bestMatchStyle = 0;
1385 for (int i = 0; i < xis->count_styles; ++i) {
1386 XIMStyle ts = xis->supported_styles[i];
1387 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1388 bestMatchStyle = ts;
1394 if (!bestMatchStyle) {
1395 fprintf(stderr, "No matching input style could be determined\n");
1398 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1399 check_allocation(xic);
1401 // draw the window for the first time
1405 while (status == LOOPING) {
1409 if (XFilterEvent(&e, w))
1414 XRefreshKeyboardMapping(&e.xmapping);
1419 if (e.xfocus.window != w)
1423 case VisibilityNotify:
1424 if (e.xvisibility.state != VisibilityUnobscured)
1429 /* fprintf(stderr, "Map Notify!\n"); */
1430 /* TODO: update the computed window and height! */
1431 /* get_wh(d, &w, width, height); */
1436 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1439 switch (parse_event(d, ev, xic, &input)) {
1447 // if first_selected is active and the first completion is
1448 // active be sure to 'expand' the text to match the selection
1449 if (first_selected && cs && cs->selected == 0) {
1451 text = strdup(cs->completions->completion);
1453 fprintf(stderr, "Memory allocation error");
1456 textlen = strlen(text);
1461 complete(cs, first_selected, true, &text, &textlen, &status);
1466 complete(cs, first_selected, false, &text, &textlen, &status);
1471 popc(text, textlen);
1472 update_completions(cs, text, lines, first_selected);
1476 // `textlen` is the lenght of the allocated string, not the
1477 // lenght of the ACTUAL string
1478 int p = strlen(text) -1;
1479 if (p > 0) { // delete the current char
1484 // erase the alphanumeric char
1485 while (p >= 0 && isalnum(text[p])) {
1490 // erase also trailing white spaces
1491 while (p >= 0 && isspace(text[p])) {
1495 update_completions(cs, text, lines, first_selected);
1500 for (int i = 0; i < textlen; ++i)
1502 update_completions(cs, text, lines, first_selected);
1507 int str_len = strlen(input);
1509 // sometimes a strange key is pressed (i.e. ctrl alone),
1510 // so input will be empty. Don't need to update completion
1515 for (int i = 0; i < str_len; ++i) {
1516 textlen = pushc(&text, textlen, input[i]);
1517 if (textlen == -1) {
1518 fprintf(stderr, "Memory allocation error\n");
1523 if (status != ERR) {
1524 update_completions(cs, text, lines, first_selected);
1530 case TOGGLE_FIRST_SELECTED:
1531 first_selected = !first_selected;
1532 if (first_selected && cs->selected < 0)
1534 if (!first_selected && cs->selected == 0)
1545 printf("%s\n", text);
1547 release_keyboard(r.d);
1550 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1551 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1552 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1561 while ((l = *lns) != nil) {
1569 XDestroyWindow(r.d, r.w);