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 MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define mod(a, b) (a < 0 ? (a % b + b) : (a % b))
50 // If we don't have it or we don't want an "ignore case" completion
51 // style, fall back to `strstr(3)`
52 #ifndef USE_STRCASESTR
53 # define strcasestr strstr
56 #define INITIAL_ITEMS 64
58 #define check_allocation(a) { \
60 fprintf(stderr, "Could not allocate memory\n"); \
65 #define inner_height(r) (r->height - r->border_n - r->border_s)
66 #define inner_width(r) (r->width - r->border_e - r->border_w)
68 // The possible state of the event loop.
69 enum state {LOOPING, OK, ERR};
71 // for the drawing-related function. The text to be rendered could be
72 // the prompt, a completion or a highlighted completion
73 enum text_type {PROMPT, COMPL, COMPL_HIGH};
75 // These are the possible action to be performed after user input.
89 Display *d; // connection to xorg
94 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
95 int y_zero; // the same a x_zero, only for the y axis
103 bool horizontal_layout;
114 GC completion_highlighted;
115 GC completion_highlighted_bg;
124 XftColor xft_completion;
125 XftColor xft_completion_highlighted;
131 // A simple linked list to store the completions.
134 struct completion *next;
138 struct completion *completions;
143 // return a newly allocated (and empty) completion list
144 struct completions *compls_new() {
145 struct completions *cs = malloc(sizeof(struct completions));
150 cs->completions = nil;
156 struct completion *compl_new() {
157 struct completion *c = malloc(sizeof(struct completion));
166 // delete ONLY the given completion (i.e. does not free c->next...)
167 void compl_delete(struct completion *c) {
171 // delete the current completion and the next (c->next) and so on...
172 void compl_delete_rec(struct completion *c) {
174 struct completion *t = c->next;
180 void compls_delete(struct completions *cs) {
184 compl_delete_rec(cs->completions);
188 // create a completion list from a text and the list of possible
189 // completions (null terminated). Expects a non-null `cs'.
190 void filter(struct completions *cs, char *text, char **lines) {
191 struct completion *c = compl_new();
202 char *l = lines[index];
206 if (strcasestr(l, text) != nil) {
209 c->next = compl_new();
221 struct completion *f = cs->completions->next;
222 compl_delete(cs->completions);
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, bool first_selected) {
230 compl_delete_rec(cs->completions);
231 filter(cs, text, lines);
232 if (first_selected && cs->lenght > 0)
236 // select the next, or the previous, selection and update some
237 // state. `text' will be updated with the text of the completion and
238 // `textlen' with the new lenght of `text'. If the memory cannot be
239 // allocated, `status' will be set to `ERR'.
240 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
241 if (cs == nil || cs->lenght == 0)
244 // if the first is always selected, and the first entry is different
245 // from the text, expand the text and return
248 && strcmp(cs->completions->completion, *text) != 0
251 *text = strdup(cs->completions->completion);
256 *textlen = strlen(*text);
260 int index = cs->selected;
262 if (index == -1 && p)
264 index = cs->selected = mod((p ? index - 1 : index + 1), cs->lenght);
266 struct completion *n = cs->completions;
268 // find the selected item
275 *text = strdup(n->completion);
277 fprintf(stderr, "Memory allocation error!\n");
281 *textlen = strlen(*text);
284 // push the character c at the end of the string pointed by p
285 int pushc(char **p, int maxlen, char c) {
286 int len = strnlen(*p, maxlen);
288 if (!(len < maxlen -2)) {
289 maxlen += maxlen >> 1;
290 char *newptr = realloc(*p, maxlen);
291 if (newptr == nil) { // bad!
302 // return the number of character
303 int utf8strnlen(char *s, int maxlen) {
305 while (*s && maxlen > 0) {
306 len += (*s++ & 0xc0) != 0x80;
312 // remove the last *glyph* from the *utf8* string!
313 // this is different from just setting the last byte to 0 (in some
314 // cases ofc). The actual implementation is quite inefficient because
315 // it remove the last byte until the number of glyphs doesn't change
316 void popc(char *p, int maxlen) {
317 int len = strnlen(p, maxlen);
322 int ulen = utf8strnlen(p, maxlen);
323 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
329 // If the string is surrounded by quotes (`"`) remove them and replace
330 // every `\"` in the string with `"`
331 char *normalize_str(const char *str) {
332 int len = strlen(str);
336 char *s = calloc(len, sizeof(char));
345 str += 2; // skip this and the next char
352 str++; // skip only this char
362 // read an arbitrary long line from stdin and return a pointer to it
363 // TODO: resize the allocated memory to exactly fit the string once
365 char *readline(bool *eof) {
367 char *str = calloc(maxlen, sizeof(char));
369 fprintf(stderr, "Cannot allocate memory!\n");
370 exit(EX_UNAVAILABLE);
374 while((c = getchar()) != EOF) {
378 maxlen = pushc(&str, maxlen, c);
381 fprintf(stderr, "Cannot allocate memory!\n");
382 exit(EX_UNAVAILABLE);
389 // read an arbitrary amount of text until an EOF and store it in
390 // lns. `items` is the capacity of lns. It may increase lns with
391 // `realloc(3)` to store more line. Return the number of lines
392 // read. The last item will always be a NULL pointer. It ignore the
393 // "null" (empty) lines
394 int readlines (char ***lns, int items) {
395 bool finished = false;
399 lines[n] = readline(&finished);
401 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
403 --n; // forget about this line
411 if (n == items - 1) {
413 char **l = realloc(lines, sizeof(char*) * items);
425 // Compute the dimension of the string str once rendered, return the
426 // width and save the width and the height in ret_width and ret_height
427 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
432 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
433 /* height = gi.height; */
434 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
435 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
436 height = r->font->ascent - r->font->descent;
437 width = gi.width - gi.x;
440 XmbTextExtents(*r->font, str, len, nil, &rect);
441 height = rect.height;
444 if (ret_width != nil) *ret_width = width;
445 if (ret_height != nil) *ret_height = height;
449 // Draw the string str
450 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
453 if (tt == PROMPT) xftcolor = r->xft_prompt;
454 if (tt == COMPL) xftcolor = r->xft_completion;
455 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
457 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
460 if (tt == PROMPT) gc = r->prompt;
461 if (tt == COMPL) gc = r->completion;
462 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
463 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
467 // Duplicate the string str and substitute every space with a 'n'
468 char *strdupn(char *str) {
469 int len = strlen(str);
471 if (str == nil || len == 0)
474 char *dup = strdup(str);
478 for (int i = 0; i < len; ++i)
485 // |------------------|----------------------------------------------|
486 // | 20 char text | completion | completion | completion | compl |
487 // |------------------|----------------------------------------------|
488 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
489 int prompt_width = 20; // char
492 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
493 int start_at = ps1xlen;
495 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
496 start_at = start_at * prompt_width + r->padding;
498 int texty = (height + r->height) >>1;
500 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
502 int text_len = strlen(text);
503 if (text_len > prompt_width)
504 text = text + (text_len - prompt_width);
505 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
506 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
508 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, r->height);
510 struct completion *c = cs->completions;
511 for (int i = 0; c != nil; ++i) {
512 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
513 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
515 int len = strlen(c->completion);
516 int text_width = text_extents(c->completion, len, r, nil, nil);
518 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
520 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
522 start_at += text_width + r->padding * 2;
524 if (start_at > inner_width(r))
525 break; // don't draw completion if the space isn't enough
531 // |-----------------------------------------------------------------|
533 // |-----------------------------------------------------------------|
535 // |-----------------------------------------------------------------|
537 // |-----------------------------------------------------------------|
538 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
540 text_extents("fjpgl", 5, r, nil, &height);
541 int start_at = height + r->padding;
543 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
544 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
546 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
548 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
549 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
551 start_at += r->padding;
553 struct completion *c = cs->completions;
554 for (int i = 0; c != nil; ++i){
555 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
556 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
558 int len = strlen(c->completion);
559 text_extents(c->completion, len, r, &width, &height);
560 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
561 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
563 start_at += height + r->padding *2;
565 if (start_at > inner_height(r))
566 break; // don't draw completion if the space isn't enough
572 void draw(struct rendering *r, char *text, struct completions *cs) {
573 if (r->horizontal_layout)
574 draw_horizontally(r, text, cs);
576 draw_vertically(r, text, cs);
580 if (r->border_w != 0)
581 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
583 if (r->border_e != 0)
584 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
586 if (r->border_n != 0)
587 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
589 if (r->border_s != 0)
590 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
592 // send all the work to x
596 /* Set some WM stuff */
597 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
599 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
603 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
604 XInternAtom(d, "ATOM", false),
607 (unsigned char *)&type,
611 /* some window managers honor this properties */
612 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
615 XInternAtom(d, "_NET_WM_STATE", false),
616 XInternAtom(d, "ATOM", false),
619 (unsigned char *)&type,
623 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
626 XInternAtom(d, "_NET_WM_STATE", false),
627 XInternAtom(d, "ATOM", false),
630 (unsigned char *)&type,
634 // setting window hints
635 XClassHint *class_hint = XAllocClassHint();
636 if (class_hint == nil) {
637 fprintf(stderr, "Could not allocate memory for class hint\n");
638 exit(EX_UNAVAILABLE);
640 class_hint->res_name = resname;
641 class_hint->res_class = resclass;
642 XSetClassHint(d, w, class_hint);
645 XSizeHints *size_hint = XAllocSizeHints();
646 if (size_hint == nil) {
647 fprintf(stderr, "Could not allocate memory for size hint\n");
648 exit(EX_UNAVAILABLE);
650 size_hint->flags = PMinSize | PBaseSize;
651 size_hint->min_width = width;
652 size_hint->base_width = width;
653 size_hint->min_height = height;
654 size_hint->base_height = height;
659 // write the width and height of the window `w' respectively in `width'
661 void get_wh(Display *d, Window *w, int *width, int *height) {
662 XWindowAttributes win_attr;
663 XGetWindowAttributes(d, *w, &win_attr);
664 *height = win_attr.height;
665 *width = win_attr.width;
668 // I know this may seem a little hackish BUT is the only way I managed
669 // to actually grab that goddam keyboard. Only one call to
670 // XGrabKeyboard does not always end up with the keyboard grabbed!
671 int take_keyboard(Display *d, Window w) {
673 for (i = 0; i < 100; i++) {
674 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
681 // release the keyboard.
682 void release_keyboard(Display *d) {
683 XUngrabKeyboard(d, CurrentTime);
686 // Given a string, try to parse it as a number or return
688 int parse_integer(const char *str, int default_value) {
691 long lval = strtol(str, &ep, 10);
692 if (str[0] == '\0' || *ep != '\0') { // NaN
693 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
694 return default_value;
696 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
697 (lval > INT_MAX || lval < INT_MIN)) {
698 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
699 return default_value;
704 // like parse_integer, but if the value ends with a `%' then its
705 // treated like a percentage (`max' is used to compute the percentage)
706 int parse_int_with_percentage(const char *str, int default_value, int max) {
707 int len = strlen(str);
708 if (len > 0 && str[len-1] == '%') {
709 char *cpy = strdup(str);
710 check_allocation(cpy);
712 int val = parse_integer(cpy, default_value);
714 return val * max / 100;
716 return parse_integer(str, default_value);
719 // like parse_int_with_percentage but understands the special value
720 // "middle" that is (max - self) / 2
721 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
722 if (!strcmp(str, "middle")) {
723 return (max - self)/2;
725 return parse_int_with_percentage(str, default_value, max);
728 // parse a string like a css value (for example like the css
729 // margin/padding properties). Will ALWAYS return an array of 4 word
730 // TODO: harden this function!
731 char **parse_csslike(const char *str) {
732 char *s = strdup(str);
736 char **ret = malloc(4 * sizeof(char*));
744 while ((token = strsep(&s, " ")) != NULL && i < 4) {
745 ret[i] = strdup(token);
750 for (int j = 1; j < 4; j++)
751 ret[j] = strdup(ret[0]);
754 ret[2] = strdup(ret[0]);
755 ret[3] = strdup(ret[1]);
759 ret[3] = strdup(ret[1]);
761 // Before we didn't check for the return type of strdup, here we will
763 bool any_null = false;
764 for (int i = 0; i < 4; ++i)
765 any_null = ret[i] == nil || any_null;
768 for (int i = 0; i < 4; ++i)
772 if (i == 0 || any_null) {
781 // Given an event, try to understand what the user wants. If the
782 // return value is ADD_CHAR then `input' is a pointer to a string that
783 // will need to be free'ed.
784 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
785 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
788 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
789 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
791 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
794 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
797 // try to read what the user pressed
798 char str[SYM_BUF_SIZE] = {0};
800 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
801 if (s == XBufferOverflow) {
802 // should not happen since there are no utf-8 characters larger
804 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
808 if (ev->state & ControlMask) {
809 if (!strcmp(str, "")) // C-u
811 if (!strcmp(str, "")) // C-w
813 if (!strcmp(str, "")) // C-h
815 if (!strcmp(str, "\r")) // C-m
817 if (!strcmp(str, "")) // C-p
819 if (!strcmp(str, "")) // C-n
821 if (!strcmp(str, "")) // C-c
823 if (!strcmp(str, "\t")) // C-i
824 return TOGGLE_FIRST_SELECTED;
827 *input = strdup(str);
829 fprintf(stderr, "Error while allocating memory for key.\n");
836 // Given the name of the program (argv[0]?) print a small help on stderr
837 void usage(char *prgname) {
838 fprintf(stderr, "Usage: %s [flags]\n", prgname);
839 fprintf(stderr, "\t-a: automatic mode, the first completion is "
840 "always selected;\n");
841 fprintf(stderr, "\t-h: print this help.\n");
844 int main(int argc, char **argv) {
846 // stdio & rpat: to read and write stdio/stdout
847 // unix: to connect to Xorg
848 pledge("stdio rpath unix", "");
851 // by default the first completion isn't selected
852 bool first_selected = false;
854 // parse the command line options
856 while ((ch = getopt(argc, argv, "ahv")) != -1) {
859 first_selected = true;
865 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
873 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
874 readlines(&lines, INITIAL_ITEMS);
876 setlocale(LC_ALL, getenv("LANG"));
878 enum state status = LOOPING;
880 // where the monitor start (used only with xinerama)
884 // width and height of the window
888 // position on the screen
892 // the default padding
895 // the default borders
901 // the prompt. We duplicate the string so later is easy to free (in
902 // the case the user provide its own prompt)
903 char *ps1 = strdup("$ ");
904 check_allocation(ps1);
906 // same for the font name
907 char *fontname = strdup(default_fontname);
908 check_allocation(fontname);
911 char *text = malloc(textlen * sizeof(char));
912 check_allocation(text);
914 /* struct completions *cs = filter(text, lines); */
915 struct completions *cs = compls_new();
916 check_allocation(cs);
918 update_completions(cs, text, lines, first_selected);
920 // start talking to xorg
921 Display *d = XOpenDisplay(nil);
923 fprintf(stderr, "Could not open display!\n");
924 return EX_UNAVAILABLE;
928 // XXX: is getting the default root window dimension correct?
929 XWindowAttributes xwa;
930 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
931 int d_width = xwa.width;
932 int d_height = xwa.height;
935 if (XineramaIsActive(d)) {
937 int number_of_screens = XScreenCount(d);
940 int root_x, root_y, win_x, win_y;
943 for (int i = 0; i < number_of_screens; ++i) {
944 root = XRootWindow(d, i);
945 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
949 fprintf(stderr, "No mouse found.\n");
954 // now find in which monitor the mice is on
956 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
958 for (int i = 0; i < monitors; ++i) {
959 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
960 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
961 offset_x = info[i].x_org;
962 offset_y = info[i].y_org;
963 d_width = info[i].width;
964 d_height = info[i].height;
973 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
976 compl_highlighted_fg, compl_highlighted_bg,
977 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
979 bool horizontal_layout = true;
983 char *xrm = XResourceManagerString(d);
984 XrmDatabase xdb = nil;
986 xdb = XrmGetStringDatabase(xrm);
990 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
991 fontname = strdup(value.addr);
992 check_allocation(fontname);
995 fprintf(stderr, "no font defined, using %s\n", fontname);
997 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
998 char *v = strdup(value.addr);
1000 horizontal_layout = !strcmp(v, "horizontal");
1004 fprintf(stderr, "no layout defined, using horizontal\n");
1006 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1008 ps1 = normalize_str(value.addr);
1010 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1012 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1013 width = parse_int_with_percentage(value.addr, width, d_width);
1015 fprintf(stderr, "no width defined, using %d\n", width);
1017 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1018 height = parse_int_with_percentage(value.addr, height, d_height);
1020 fprintf(stderr, "no height defined, using %d\n", height);
1022 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1023 x = parse_int_with_middle(value.addr, x, d_width, width);
1025 fprintf(stderr, "no x defined, using %d\n", x);
1027 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1028 y = parse_int_with_middle(value.addr, y, d_height, height);
1030 fprintf(stderr, "no y defined, using %d\n", y);
1032 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1033 padding = parse_integer(value.addr, padding);
1035 fprintf(stderr, "no padding defined, using %d\n", padding);
1037 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1038 char **borders = parse_csslike(value.addr);
1039 if (borders != nil) {
1040 border_n = parse_integer(borders[0], 0);
1041 border_e = parse_integer(borders[1], 0);
1042 border_s = parse_integer(borders[2], 0);
1043 border_w = parse_integer(borders[3], 0);
1045 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1048 fprintf(stderr, "no border defined, using 0.\n");
1052 // TODO: tmp needs to be free'd after every allocation?
1055 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1056 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1058 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1060 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1061 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1063 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1066 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1067 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1069 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1071 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1072 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1074 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1076 // completion highlighted
1077 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1078 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1080 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1082 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1083 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1085 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1088 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1089 char **colors = parse_csslike(value.addr);
1090 if (colors != nil) {
1091 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1092 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1093 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1094 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1096 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1099 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1100 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1101 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1102 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1106 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1107 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1108 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1109 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1110 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1111 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1112 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1113 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1114 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1119 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1121 char **missing_charset_list;
1122 int missing_charset_count;
1123 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1125 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1126 return EX_UNAVAILABLE;
1130 // create the window
1131 XSetWindowAttributes attr;
1132 attr.override_redirect = true;
1134 Window w = XCreateWindow(d, // display
1135 DefaultRootWindow(d), // parent
1136 x + offset_x, y + offset_y, // x y
1137 width, height, // w h
1139 DefaultDepth(d, DefaultScreen(d)), // depth
1140 InputOutput, // class
1141 DefaultVisual(d, DefaultScreen(d)), // visual
1142 CWOverrideRedirect, // value mask
1145 set_win_atoms_hints(d, w, width, height);
1147 // we want some events
1148 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1150 // make the window appear on the screen
1153 // wait for the MapNotify event (i.e. the event "window rendered")
1157 if (e.type == MapNotify)
1161 // get the *real* width & height after the window was rendered
1162 get_wh(d, &w, &width, &height);
1165 take_keyboard(d, w);
1167 // Create some graphics contexts
1169 /* values.font = font->fid; */
1171 struct rendering r = {
1179 .border_n = border_n,
1180 .border_e = border_e,
1181 .border_s = border_s,
1182 .border_w = border_w,
1183 .horizontal_layout = horizontal_layout,
1185 .ps1len = strlen(ps1),
1186 .prompt = XCreateGC(d, w, 0, &values),
1187 .prompt_bg = XCreateGC(d, w, 0, &values),
1188 .completion = XCreateGC(d, w, 0, &values),
1189 .completion_bg = XCreateGC(d, w, 0, &values),
1190 .completion_highlighted = XCreateGC(d, w, 0, &values),
1191 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1192 .border_n_bg = XCreateGC(d, w, 0, &values),
1193 .border_e_bg = XCreateGC(d, w, 0, &values),
1194 .border_s_bg = XCreateGC(d, w, 0, &values),
1195 .border_w_bg = XCreateGC(d, w, 0, &values),
1204 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1207 XRenderColor xrcolor;
1208 xrcolor.red = p_fg.red;
1209 xrcolor.green = p_fg.red;
1210 xrcolor.blue = p_fg.red;
1211 xrcolor.alpha = 65535;
1212 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1215 xrcolor.red = compl_fg.red;
1216 xrcolor.green = compl_fg.green;
1217 xrcolor.blue = compl_fg.blue;
1218 xrcolor.alpha = 65535;
1219 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1221 // completion highlighted
1222 xrcolor.red = compl_highlighted_fg.red;
1223 xrcolor.green = compl_highlighted_fg.green;
1224 xrcolor.blue = compl_highlighted_fg.blue;
1225 xrcolor.alpha = 65535;
1226 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1229 // load the colors in our GCs
1230 XSetForeground(d, r.prompt, p_fg.pixel);
1231 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1232 XSetForeground(d, r.completion, compl_fg.pixel);
1233 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1234 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1235 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1236 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1237 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1238 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1239 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1241 // open the X input method
1242 XIM xim = XOpenIM(d, xdb, resname, resclass);
1243 check_allocation(xim);
1245 XIMStyles *xis = nil;
1246 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1247 fprintf(stderr, "Input Styles could not be retrieved\n");
1248 return EX_UNAVAILABLE;
1251 XIMStyle bestMatchStyle = 0;
1252 for (int i = 0; i < xis->count_styles; ++i) {
1253 XIMStyle ts = xis->supported_styles[i];
1254 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1255 bestMatchStyle = ts;
1261 if (!bestMatchStyle) {
1262 fprintf(stderr, "No matching input style could be determined\n");
1265 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1266 check_allocation(xic);
1268 // draw the window for the first time
1272 while (status == LOOPING) {
1276 if (XFilterEvent(&e, w))
1281 XRefreshKeyboardMapping(&e.xmapping);
1285 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1288 switch (parse_event(d, ev, xic, &input)) {
1296 // if first_selected is active and the first completion is
1297 // active be sure to 'expand' the text to match the selection
1298 if (first_selected && cs && cs->selected == 0) {
1300 text = strdup(cs->completions->completion);
1302 fprintf(stderr, "Memory allocation error");
1305 textlen = strlen(text);
1310 complete(cs, first_selected, true, &text, &textlen, &status);
1315 complete(cs, first_selected, false, &text, &textlen, &status);
1320 popc(text, textlen);
1321 update_completions(cs, text, lines, first_selected);
1325 // `textlen` is the lenght of the allocated string, not the
1326 // lenght of the ACTUAL string
1327 int p = strlen(text) -1;
1328 if (p > 0) { // delete the current char
1333 // erase the alphanumeric char
1334 while (p >= 0 && isalnum(text[p])) {
1339 // erase also trailing white spaces
1340 while (p >= 0 && isspace(text[p])) {
1344 update_completions(cs, text, lines, first_selected);
1349 for (int i = 0; i < textlen; ++i)
1351 update_completions(cs, text, lines, first_selected);
1356 int str_len = strlen(input);
1358 // sometimes a strange key is pressed (i.e. ctrl alone),
1359 // so input will be empty. Don't need to update completion
1364 for (int i = 0; i < str_len; ++i) {
1365 textlen = pushc(&text, textlen, input[i]);
1366 if (textlen == -1) {
1367 fprintf(stderr, "Memory allocation error\n");
1372 if (status != ERR) {
1373 update_completions(cs, text, lines, first_selected);
1379 case TOGGLE_FIRST_SELECTED:
1380 first_selected = !first_selected;
1381 if (first_selected && cs->selected < 0)
1383 if (!first_selected && cs->selected == 0)
1394 printf("%s\n", text);
1396 release_keyboard(r.d);
1399 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1400 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1401 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1410 while ((l = *lns) != nil) {
1418 XDestroyWindow(r.d, r.w);