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"
31 #define resname "MyMenu"
32 #define resclass "mymenu"
35 # define default_fontname "monospace"
37 # define default_fontname "fixed"
40 #define MIN(a, b) ((a) < (b) ? (a) : (b))
41 #define MAX(a, b) ((a) > (b) ? (a) : (b))
43 // If we don't have it or we don't want an "ignore case" completion
44 // style, fall back to `strstr(3)`
45 #ifndef USE_STRCASESTR
46 # define strcasestr strstr
49 #define update_completions(cs, text, lines, first_selected) { \
50 compl_delete_rec(cs); \
51 cs = filter(text, lines); \
52 if (first_selected && cs != nil) \
53 cs->selected = true; \
56 #define complete(cs, nothing_selected, p, text, textlen, status) { \
57 struct completions *n = p \
58 ? compl_select_prev(cs, nothing_selected) \
59 : compl_select_next(cs, nothing_selected); \
62 nothing_selected = false; \
64 text = strdup(n->completion); \
66 fprintf(stderr, "Memory allocation error!\n"); \
70 textlen = strlen(text); \
74 #define INITIAL_ITEMS 64
76 #define cannot_allocate_memory { \
77 fprintf(stderr, "Could not allocate memory\n"); \
81 #define check_allocation(a) { \
83 cannot_allocate_memory; \
86 enum state {LOOPING, OK, ERR};
88 enum text_type {PROMPT, COMPL, COMPL_HIGH};
96 bool horizontal_layout;
103 GC completion_highlighted;
104 GC completion_highlighted_bg;
109 XftColor xft_completion;
110 XftColor xft_completion_highlighted;
119 struct completions *next;
122 struct completions *compl_new() {
123 struct completions *c = malloc(sizeof(struct completions));
134 void compl_delete(struct completions *c) {
138 void compl_delete_rec(struct completions *c) {
140 struct completions *t = c->next;
146 struct completions *compl_select_next(struct completions *c, bool n) {
154 struct completions *orig = c;
158 if (c->next != nil) {
159 // the current one is selected and the next one exists
160 c->next->selected = true;
163 // the current one is selected and the next one is nill,
164 // select the first one
165 orig->selected = true;
174 struct completions *compl_select_prev(struct completions *c, bool n) {
178 struct completions *cc = c;
180 if (n || c->selected) { // select the last one
183 if (cc->next == nil) {
190 else // select the previous one
192 if (cc->next != nil && cc->next->selected) {
193 cc->next->selected = false;
203 struct completions *filter(char *text, char **lines) {
205 struct completions *root = compl_new();
206 struct completions *c = root;
215 if (strcasestr(l, text) != nil) {
216 c->next = compl_new();
219 compl_delete_rec(root);
228 struct completions *r = root->next;
233 // push the character c at the end of the string pointed by p
234 int pushc(char **p, int maxlen, char c) {
235 int len = strnlen(*p, maxlen);
237 if (!(len < maxlen -2)) {
238 maxlen += maxlen >> 1;
239 char *newptr = realloc(*p, maxlen);
240 if (newptr == nil) { // bad!
251 int utf8strnlen(char *s, int maxlen) {
253 while (*s && maxlen > 0) {
254 len += (*s++ & 0xc0) != 0x80;
260 // remove the last *glyph* from the *utf8* string!
261 // this is different from just setting the last byte to 0 (in some
262 // cases ofc). The actual implementation is quite inefficient because
263 // it remove the last char until the number of glyphs doesn't change
264 void popc(char *p, int maxlen) {
265 int len = strnlen(p, maxlen);
270 int ulen = utf8strnlen(p, maxlen);
271 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
277 // If the string is surrounded by quotes (`"`) remove them and replace
278 // every `\"` in the string with `"`
279 char *normalize_str(const char *str) {
280 int len = strlen(str);
284 char *s = calloc(len, sizeof(char));
293 str += 2; // skip this and the next char
300 str++; // skip only this char
310 // read an arbitrary long line from stdin and return a pointer to it
311 // TODO: resize the allocated memory to exactly fit the string once
313 char *readline(bool *eof) {
315 char *str = calloc(maxlen, sizeof(char));
317 fprintf(stderr, "Cannot allocate memory!\n");
318 exit(EX_UNAVAILABLE);
322 while((c = getchar()) != EOF) {
326 maxlen = pushc(&str, maxlen, c);
329 fprintf(stderr, "Cannot allocate memory!\n");
330 exit(EX_UNAVAILABLE);
337 // read an arbitrary amount of text until an EOF and store it in
338 // lns. `items` is the capacity of lns. It may increase lns with
339 // `realloc(3)` to store more line. Return the number of lines
340 // read. The last item will always be a NULL pointer. It ignore the
341 // "null" (empty) lines
342 int readlines (char ***lns, int items) {
343 bool finished = false;
347 lines[n] = readline(&finished);
349 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
351 --n; // forget about this line
359 if (n == items - 1) {
361 char **l = realloc(lines, sizeof(char*) * items);
373 // Compute the dimension of the string str once rendered, return the
374 // width and save the width and the height in ret_width and ret_height
375 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
380 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
381 /* height = gi.height; */
382 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
383 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
384 height = r->font->ascent - r->font->descent;
385 width = gi.width - gi.x;
388 XmbTextExtents(*r->font, str, len, nil, &rect);
389 height = rect.height;
392 if (ret_width != nil) *ret_width = width;
393 if (ret_height != nil) *ret_height = height;
397 // Draw the string str
398 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
401 if (tt == PROMPT) xftcolor = r->xft_prompt;
402 if (tt == COMPL) xftcolor = r->xft_completion;
403 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
405 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
408 if (tt == PROMPT) gc = r->prompt;
409 if (tt == COMPL) gc = r->completion;
410 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
411 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
415 // Duplicate the string str and substitute every space with a 'n'
416 char *strdupn(char *str) {
417 int len = strlen(str);
419 if (str == nil || len == 0)
422 char *dup = strdup(str);
426 for (int i = 0; i < len; ++i)
433 // |------------------|----------------------------------------------|
434 // | 20 char text | completion | completion | completion | compl |
435 // |------------------|----------------------------------------------|
436 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
437 int prompt_width = 20; // char
440 char *ps1_dup = strdupn(r->ps1);
444 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
445 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
447 int start_at = ps1xlen;
449 start_at = text_extents("n", 1, r, nil, nil);
450 start_at = start_at * prompt_width + r->padding;
452 int texty = (height + r->height) >>1;
454 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
456 int text_len = strlen(text);
457 if (text_len > prompt_width)
458 text = text + (text_len - prompt_width);
459 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
460 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
462 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
465 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
466 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
468 int len = strlen(cs->completion);
469 int text_width = text_extents(cs->completion, len, r, nil, nil);
471 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
473 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
475 start_at += text_width + r->padding * 2;
477 if (start_at > r->width)
478 break; // don't draw completion if the space isn't enough
486 // |-----------------------------------------------------------------|
488 // |-----------------------------------------------------------------|
490 // |-----------------------------------------------------------------|
492 // |-----------------------------------------------------------------|
493 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
495 text_extents("fjpgl", 5, r, nil, &height);
496 int start_at = height + r->padding;
498 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
499 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
501 char *ps1_dup = strdupn(r->ps1);
502 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
503 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
506 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
507 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
508 start_at += r->padding;
511 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
512 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
514 int len = strlen(cs->completion);
515 text_extents(cs->completion, len, r, &width, &height);
516 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
517 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
519 start_at += height + r->padding *2;
521 if (start_at > r->height)
522 break; // don't draw completion if the space isn't enough
530 void draw(struct rendering *r, char *text, struct completions *cs) {
531 if (r->horizontal_layout)
532 draw_horizontally(r, text, cs);
534 draw_vertically(r, text, cs);
537 /* Set some WM stuff */
538 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
540 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
544 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
545 XInternAtom(d, "ATOM", false),
548 (unsigned char *)&type,
552 /* some window managers honor this properties */
553 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
556 XInternAtom(d, "_NET_WM_STATE", false),
557 XInternAtom(d, "ATOM", false),
560 (unsigned char *)&type,
564 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
567 XInternAtom(d, "_NET_WM_STATE", false),
568 XInternAtom(d, "ATOM", false),
571 (unsigned char *)&type,
575 // setting window hints
576 XClassHint *class_hint = XAllocClassHint();
577 if (class_hint == nil) {
578 fprintf(stderr, "Could not allocate memory for class hint\n");
579 exit(EX_UNAVAILABLE);
581 class_hint->res_name = resname;
582 class_hint->res_class = resclass;
583 XSetClassHint(d, w, class_hint);
586 XSizeHints *size_hint = XAllocSizeHints();
587 if (size_hint == nil) {
588 fprintf(stderr, "Could not allocate memory for size hint\n");
589 exit(EX_UNAVAILABLE);
591 size_hint->flags = PMinSize | PBaseSize;
592 size_hint->min_width = width;
593 size_hint->base_width = width;
594 size_hint->min_height = height;
595 size_hint->base_height = height;
600 void get_wh(Display *d, Window *w, int *width, int *height) {
601 XWindowAttributes win_attr;
602 XGetWindowAttributes(d, *w, &win_attr);
603 *height = win_attr.height;
604 *width = win_attr.width;
607 // I know this may seem a little hackish BUT is the only way I managed
608 // to actually grab that goddam keyboard. Only one call to
609 // XGrabKeyboard does not always end up with the keyboard grabbed!
610 int take_keyboard(Display *d, Window w) {
612 for (i = 0; i < 100; i++) {
613 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
620 void release_keyboard(Display *d) {
621 XUngrabKeyboard(d, CurrentTime);
624 int parse_integer(const char *str, int default_value) {
625 /* int len = strlen(str); */
626 /* if (len > 0 && str[len-1] == '%') { */
627 /* char *cpy = strdup(str); */
628 /* check_allocation(cpy); */
629 /* cpy[len-1] = '\0'; */
630 /* int val = parse_integer(cpy, default_value, max); */
632 /* return val * max / 100; */
637 long lval = strtol(str, &ep, 10);
638 if (str[0] == '\0' || *ep != '\0') { // NaN
639 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
640 return default_value;
642 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
643 (lval > INT_MAX || lval < INT_MIN)) {
644 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
645 return default_value;
650 int parse_int_with_percentage(const char *str, int default_value, int max) {
651 int len = strlen(str);
652 if (len > 0 && str[len-1] == '%') {
653 char *cpy = strdup(str);
654 check_allocation(cpy);
656 int val = parse_integer(cpy, default_value);
658 return val * max / 100;
660 return parse_integer(str, default_value);
663 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
664 if (!strcmp(str, "middle")) {
665 return (max - self)/2;
667 return parse_int_with_percentage(str, default_value, max);
670 void usage(char *prgname) {
671 fprintf(stderr, "Usage: %s [flags]\n", prgname);
672 fprintf(stderr, "\t-a: automatic mode, the first completion is "
673 "always selected;\n");
674 fprintf(stderr, "\t-h: print this help.\n");
677 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
678 release_keyboard(r->d);
681 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
682 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
683 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
692 while ((l = *lns) != nil) {
699 XDestroyWindow(r->d, r->w);
705 int main(int argc, char **argv) {
706 // by default the first completion isn't selected
707 bool first_selected = false;
709 // parse the command line options
711 while ((ch = getopt(argc, argv, "ahv")) != -1) {
714 first_selected = true;
720 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
728 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
729 readlines(&lines, INITIAL_ITEMS);
731 setlocale(LC_ALL, getenv("LANG"));
733 enum state status = LOOPING;
735 // where the monitor start (used only with xinerama)
739 // width and height of the window
743 // position on the screen
747 // the default padding
750 char *ps1 = strdup("$ ");
751 check_allocation(ps1);
753 char *fontname = strdup(default_fontname);
754 check_allocation(fontname);
757 char *text = malloc(textlen * sizeof(char));
758 check_allocation(text);
760 bool nothing_selected = first_selected;
761 /* struct completions *cs = filter(text, lines); */
762 struct completions *cs = nil;
763 update_completions(cs, text, lines, first_selected);
765 // start talking to xorg
766 Display *d = XOpenDisplay(nil);
768 fprintf(stderr, "Could not open display!\n");
769 return EX_UNAVAILABLE;
773 // XXX: is getting the default root window dimension correct?
774 XWindowAttributes xwa;
775 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
776 int d_width = xwa.width;
777 int d_height = xwa.height;
780 if (XineramaIsActive(d)) {
782 int number_of_screens = XScreenCount(d);
785 int root_x, root_y, win_x, win_y;
788 for (int i = 0; i < number_of_screens; ++i) {
789 root = XRootWindow(d, i);
790 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
794 fprintf(stderr, "No mouse found.\n");
799 // now find in which monitor the mice is on
801 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
803 for (int i = 0; i < monitors; ++i) {
804 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
805 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
806 offset_x = info[i].x_org;
807 offset_y = info[i].y_org;
808 d_width = info[i].width;
809 d_height = info[i].height;
818 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
821 compl_highlighted_fg, compl_highlighted_bg;
823 bool horizontal_layout = true;
827 char *xrm = XResourceManagerString(d);
828 XrmDatabase xdb = nil;
830 xdb = XrmGetStringDatabase(xrm);
834 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
835 fontname = strdup(value.addr);
836 check_allocation(fontname);
839 fprintf(stderr, "no font defined, using %s\n", fontname);
841 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
842 char *v = strdup(value.addr);
844 horizontal_layout = !strcmp(v, "horizontal");
848 fprintf(stderr, "no layout defined, using horizontal\n");
850 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
852 ps1 = normalize_str(value.addr);
854 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
856 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
857 width = parse_int_with_percentage(value.addr, width, d_width);
859 fprintf(stderr, "no width defined, using %d\n", width);
861 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
862 height = parse_int_with_percentage(value.addr, height, d_height);
864 fprintf(stderr, "no height defined, using %d\n", height);
866 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
867 x = parse_int_with_middle(value.addr, x, d_width, width);
869 fprintf(stderr, "no x defined, using %d\n", x);
871 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
872 y = parse_int_with_middle(value.addr, y, d_height, height);
874 fprintf(stderr, "no y defined, using %d\n", y);
876 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
877 padding = parse_integer(value.addr, padding);
879 fprintf(stderr, "no y defined, using %d\n", padding);
882 // TODO: tmp needs to be free'd after every allocation?
885 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
886 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
888 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
890 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
891 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
893 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
896 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
897 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
899 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
901 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
902 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
904 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
906 // completion highlighted
907 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
908 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
910 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
912 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
913 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
915 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
918 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
919 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
920 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
921 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
922 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
923 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
927 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
928 /* if (font == nil) { */
929 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
930 /* font = XLoadQueryFont(d, "fixed"); */
934 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
936 char **missing_charset_list;
937 int missing_charset_count;
938 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
940 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
941 return EX_UNAVAILABLE;
946 XSetWindowAttributes attr;
947 attr.override_redirect = true;
949 Window w = XCreateWindow(d, // display
950 DefaultRootWindow(d), // parent
951 x + offset_x, y + offset_y, // x y
952 width, height, // w h
954 DefaultDepth(d, DefaultScreen(d)), // depth
955 InputOutput, // class
956 DefaultVisual(d, DefaultScreen(d)), // visual
957 CWOverrideRedirect, // value mask
960 set_win_atoms_hints(d, w, width, height);
962 // we want some events
963 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
965 // make the window appear on the screen
968 // wait for the MapNotify event (i.e. the event "window rendered")
972 if (e.type == MapNotify)
976 // get the *real* width & height after the window was rendered
977 get_wh(d, &w, &width, &height);
982 // Create some graphics contexts
984 /* values.font = font->fid; */
986 struct rendering r = {
994 .prompt = XCreateGC(d, w, 0, &values),
995 .prompt_bg = XCreateGC(d, w, 0, &values),
996 .completion = XCreateGC(d, w, 0, &values),
997 .completion_bg = XCreateGC(d, w, 0, &values),
998 .completion_highlighted = XCreateGC(d, w, 0, &values),
999 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1003 .horizontal_layout = horizontal_layout,
1005 .ps1len = strlen(ps1)
1009 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1012 XRenderColor xrcolor;
1013 xrcolor.red = p_fg.red;
1014 xrcolor.green = p_fg.red;
1015 xrcolor.blue = p_fg.red;
1016 xrcolor.alpha = 65535;
1017 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1020 xrcolor.red = compl_fg.red;
1021 xrcolor.green = compl_fg.green;
1022 xrcolor.blue = compl_fg.blue;
1023 xrcolor.alpha = 65535;
1024 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1026 // completion highlighted
1027 xrcolor.red = compl_highlighted_fg.red;
1028 xrcolor.green = compl_highlighted_fg.green;
1029 xrcolor.blue = compl_highlighted_fg.blue;
1030 xrcolor.alpha = 65535;
1031 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1034 // load the colors in our GCs
1035 XSetForeground(d, r.prompt, p_fg.pixel);
1036 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1037 XSetForeground(d, r.completion, compl_fg.pixel);
1038 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1039 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1040 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1042 // open the X input method
1043 XIM xim = XOpenIM(d, xdb, resname, resclass);
1044 check_allocation(xim);
1046 XIMStyles *xis = nil;
1047 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1048 fprintf(stderr, "Input Styles could not be retrieved\n");
1049 return EX_UNAVAILABLE;
1052 XIMStyle bestMatchStyle = 0;
1053 for (int i = 0; i < xis->count_styles; ++i) {
1054 XIMStyle ts = xis->supported_styles[i];
1055 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1056 bestMatchStyle = ts;
1062 if (!bestMatchStyle) {
1063 fprintf(stderr, "No matching input style could be determined\n");
1066 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1067 check_allocation(xic);
1069 // draw the window for the first time
1073 while (status == LOOPING) {
1077 if (XFilterEvent(&e, w))
1082 XRefreshKeyboardMapping(&e.xmapping);
1086 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1088 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
1089 bool shift = (ev->state & ShiftMask);
1090 complete(cs, nothing_selected, shift, text, textlen, status);
1095 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1096 nothing_selected = first_selected;
1097 popc(text, textlen);
1098 update_completions(cs, text, lines, first_selected);
1103 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1105 if (first_selected) {
1106 complete(cs, first_selected, false, text, textlen, status);
1111 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1116 // try to read what the user pressed
1119 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1121 if (s == XBufferOverflow) {
1122 // should not happen since there are no utf-8 characters
1123 // larger than 24bits, but is something to be aware of when
1124 // used to directly write to a string buffer
1125 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1128 char *str = (char*)&symbol;
1130 if (ev->state & ControlMask) {
1131 // check for some key bindings
1132 if (!strcmp(str, "")) { // C-u
1133 nothing_selected = first_selected;
1134 for (int i = 0; i < textlen; ++i)
1136 update_completions(cs, text, lines, first_selected);
1138 if (!strcmp(str, "")) { // C-h
1139 nothing_selected = first_selected;
1140 popc(text, textlen);
1141 update_completions(cs, text, lines, first_selected);
1143 if (!strcmp(str, "")) { // C-w
1144 nothing_selected = first_selected;
1146 // `textlen` is the length of the allocated string, not the
1147 // length of the ACTUAL string
1148 int p = strlen(text) - 1;
1149 if (p >= 0) { // delete the current char
1153 while (p >= 0 && isalnum(text[p])) {
1157 // erase also trailing white space
1158 while (p >= 0 && isspace(text[p])) {
1162 update_completions(cs, text, lines, first_selected);
1164 if (!strcmp(str, "\r")) { // C-m
1166 if (first_selected) {
1167 complete(cs, first_selected, false, text, textlen, status);
1170 if (!strcmp(str, "")) {
1171 complete(cs, nothing_selected, true, text, textlen, status);
1173 if (!strcmp(str, "")) {
1174 complete(cs, nothing_selected, false, text, textlen, status);
1180 int str_len = strlen(str);
1181 for (int i = 0; i < str_len; ++i) {
1182 textlen = pushc(&text, textlen, str[i]);
1183 if (textlen == -1) {
1184 fprintf(stderr, "Memory allocation error\n");
1188 nothing_selected = first_selected;
1189 update_completions(cs, text, lines, first_selected);
1197 fprintf(stderr, "Unknown event %d\n", e.type);
1202 printf("%s\n", text);
1204 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);