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 resname "MyMenu"
28 #define resclass "mymenu"
31 # define default_fontname "monospace"
33 # define default_fontname "fixed"
36 #define MIN(a, b) ((a) < (b) ? (a) : (b))
37 #define MAX(a, b) ((a) > (b) ? (a) : (b))
39 // If we don't have it or we don't want an "ignore case" completion
40 // style, fall back to `strstr(3)`
41 #ifndef USE_STRCASESTR
42 # define strcasestr strstr
45 #define update_completions(cs, text, lines, first_selected) { \
46 compl_delete_rec(cs); \
47 cs = filter(text, lines); \
48 if (first_selected && cs != nil) \
49 cs->selected = true; \
52 #define complete(cs, nothing_selected, p, text, textlen, status) { \
53 struct completions *n = p \
54 ? compl_select_prev(cs, nothing_selected) \
55 : compl_select_next(cs, nothing_selected); \
58 nothing_selected = false; \
60 text = strdup(n->completion); \
62 fprintf(stderr, "Memory allocation error!\n"); \
66 textlen = strlen(text); \
70 #define INITIAL_ITEMS 64
72 #define cannot_allocate_memory { \
73 fprintf(stderr, "Could not allocate memory\n"); \
77 #define check_allocation(a) { \
79 cannot_allocate_memory; \
82 enum state {LOOPING, OK, ERR};
84 enum text_type {PROMPT, COMPL, COMPL_HIGH};
92 bool horizontal_layout;
99 GC completion_highlighted;
100 GC completion_highlighted_bg;
105 XftColor xft_completion;
106 XftColor xft_completion_highlighted;
115 struct completions *next;
118 struct completions *compl_new() {
119 struct completions *c = malloc(sizeof(struct completions));
130 void compl_delete(struct completions *c) {
134 void compl_delete_rec(struct completions *c) {
136 struct completions *t = c->next;
142 struct completions *compl_select_next(struct completions *c, bool n) {
150 struct completions *orig = c;
154 if (c->next != nil) {
155 // the current one is selected and the next one exists
156 c->next->selected = true;
159 // the current one is selected and the next one is nill,
160 // select the first one
161 orig->selected = true;
170 struct completions *compl_select_prev(struct completions *c, bool n) {
174 struct completions *cc = c;
176 if (n || c->selected) { // select the last one
179 if (cc->next == nil) {
186 else // select the previous one
188 if (cc->next != nil && cc->next->selected) {
189 cc->next->selected = false;
199 struct completions *filter(char *text, char **lines) {
201 struct completions *root = compl_new();
202 struct completions *c = root;
211 if (strcasestr(l, text) != nil) {
212 c->next = compl_new();
215 compl_delete_rec(root);
224 struct completions *r = root->next;
229 // push the character c at the end of the string pointed by p
230 int pushc(char **p, int maxlen, char c) {
231 int len = strnlen(*p, maxlen);
233 if (!(len < maxlen -2)) {
234 maxlen += maxlen >> 1;
235 char *newptr = realloc(*p, maxlen);
236 if (newptr == nil) { // bad!
247 int utf8strnlen(char *s, int maxlen) {
249 while (*s && maxlen > 0) {
250 len += (*s++ & 0xc0) != 0x80;
256 // remove the last *glyph* from the *utf8* string!
257 // this is different from just setting the last byte to 0 (in some
258 // cases ofc). The actual implementation is quite inefficient because
259 // it remove the last char until the number of glyphs doesn't change
260 void popc(char *p, int maxlen) {
261 int len = strnlen(p, maxlen);
266 int ulen = utf8strnlen(p, maxlen);
267 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
273 // If the string is surrounded by quotes (`"`) remove them and replace
274 // every `\"` in the string with `"`
275 char *normalize_str(const char *str) {
276 int len = strlen(str);
280 char *s = calloc(len, sizeof(char));
289 str += 2; // skip this and the next char
296 str++; // skip only this char
306 // read an arbitrary long line from stdin and return a pointer to it
307 // TODO: resize the allocated memory to exactly fit the string once
309 char *readline(bool *eof) {
311 char *str = calloc(maxlen, sizeof(char));
313 fprintf(stderr, "Cannot allocate memory!\n");
314 exit(EX_UNAVAILABLE);
318 while((c = getchar()) != EOF) {
322 maxlen = pushc(&str, maxlen, c);
325 fprintf(stderr, "Cannot allocate memory!\n");
326 exit(EX_UNAVAILABLE);
333 // read an arbitrary amount of text until an EOF and store it in
334 // lns. `items` is the capacity of lns. It may increase lns with
335 // `realloc(3)` to store more line. Return the number of lines
336 // read. The last item will always be a NULL pointer. It ignore the
337 // "null" (empty) lines
338 int readlines (char ***lns, int items) {
339 bool finished = false;
343 lines[n] = readline(&finished);
345 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
347 --n; // forget about this line
355 if (n == items - 1) {
357 char **l = realloc(lines, sizeof(char*) * items);
369 // Compute the dimension of the string str once rendered, return the
370 // width and save the width and the height in ret_width and ret_height
371 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
376 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
377 /* height = gi.height; */
378 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
379 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
380 height = r->font->ascent - r->font->descent;
381 width = gi.width - gi.x;
384 XmbTextExtents(*r->font, str, len, nil, &rect);
385 height = rect.height;
388 if (ret_width != nil) *ret_width = width;
389 if (ret_height != nil) *ret_height = height;
393 // Draw the string str
394 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
397 if (tt == PROMPT) xftcolor = r->xft_prompt;
398 if (tt == COMPL) xftcolor = r->xft_completion;
399 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
401 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
404 if (tt == PROMPT) gc = r->prompt;
405 if (tt == COMPL) gc = r->completion;
406 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
407 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
411 // Duplicate the string str and substitute every space with a 'n'
412 char *strdupn(char *str) {
413 int len = strlen(str);
415 if (str == nil || len == 0)
418 char *dup = strdup(str);
422 for (int i = 0; i < len; ++i)
429 // |------------------|----------------------------------------------|
430 // | 20 char text | completion | completion | completion | compl |
431 // |------------------|----------------------------------------------|
432 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
433 int prompt_width = 20; // char
436 char *ps1_dup = strdupn(r->ps1);
440 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
441 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
443 int start_at = ps1xlen;
445 start_at = text_extents("n", 1, r, nil, nil);
446 start_at = start_at * prompt_width + r->padding;
448 int texty = (height + r->height) >>1;
450 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
452 int text_len = strlen(text);
453 if (text_len > prompt_width)
454 text = text + (text_len - prompt_width);
455 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
456 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
458 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
461 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
462 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
464 int len = strlen(cs->completion);
465 int text_width = text_extents(cs->completion, len, r, nil, nil);
467 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
469 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
471 start_at += text_width + r->padding * 2;
473 if (start_at > r->width)
474 break; // don't draw completion if the space isn't enough
482 // |-----------------------------------------------------------------|
484 // |-----------------------------------------------------------------|
486 // |-----------------------------------------------------------------|
488 // |-----------------------------------------------------------------|
489 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
491 text_extents("fjpgl", 5, r, nil, &height);
492 int start_at = height + r->padding;
494 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
495 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
497 char *ps1_dup = strdupn(r->ps1);
498 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
499 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
502 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
503 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
504 start_at += r->padding;
507 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
508 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
510 int len = strlen(cs->completion);
511 text_extents(cs->completion, len, r, &width, &height);
512 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
513 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
515 start_at += height + r->padding *2;
517 if (start_at > r->height)
518 break; // don't draw completion if the space isn't enough
526 void draw(struct rendering *r, char *text, struct completions *cs) {
527 if (r->horizontal_layout)
528 draw_horizontally(r, text, cs);
530 draw_vertically(r, text, cs);
533 /* Set some WM stuff */
534 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
536 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
540 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
541 XInternAtom(d, "ATOM", false),
544 (unsigned char *)&type,
548 /* some window managers honor this properties */
549 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
552 XInternAtom(d, "_NET_WM_STATE", false),
553 XInternAtom(d, "ATOM", false),
556 (unsigned char *)&type,
560 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
563 XInternAtom(d, "_NET_WM_STATE", false),
564 XInternAtom(d, "ATOM", false),
567 (unsigned char *)&type,
571 // setting window hints
572 XClassHint *class_hint = XAllocClassHint();
573 if (class_hint == nil) {
574 fprintf(stderr, "Could not allocate memory for class hint\n");
575 exit(EX_UNAVAILABLE);
577 class_hint->res_name = resname;
578 class_hint->res_class = resclass;
579 XSetClassHint(d, w, class_hint);
582 XSizeHints *size_hint = XAllocSizeHints();
583 if (size_hint == nil) {
584 fprintf(stderr, "Could not allocate memory for size hint\n");
585 exit(EX_UNAVAILABLE);
587 size_hint->flags = PMinSize | PBaseSize;
588 size_hint->min_width = width;
589 size_hint->base_width = width;
590 size_hint->min_height = height;
591 size_hint->base_height = height;
596 void get_wh(Display *d, Window *w, int *width, int *height) {
597 XWindowAttributes win_attr;
598 XGetWindowAttributes(d, *w, &win_attr);
599 *height = win_attr.height;
600 *width = win_attr.width;
603 // I know this may seem a little hackish BUT is the only way I managed
604 // to actually grab that goddam keyboard. Only one call to
605 // XGrabKeyboard does not always end up with the keyboard grabbed!
606 int take_keyboard(Display *d, Window w) {
608 for (i = 0; i < 100; i++) {
609 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
616 void release_keyboard(Display *d) {
617 XUngrabKeyboard(d, CurrentTime);
620 int parse_integer(const char *str, int default_value) {
621 /* int len = strlen(str); */
622 /* if (len > 0 && str[len-1] == '%') { */
623 /* char *cpy = strdup(str); */
624 /* check_allocation(cpy); */
625 /* cpy[len-1] = '\0'; */
626 /* int val = parse_integer(cpy, default_value, max); */
628 /* return val * max / 100; */
633 long lval = strtol(str, &ep, 10);
634 if (str[0] == '\0' || *ep != '\0') { // NaN
635 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
636 return default_value;
638 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
639 (lval > INT_MAX || lval < INT_MIN)) {
640 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
641 return default_value;
646 int parse_int_with_percentage(const char *str, int default_value, int max) {
647 int len = strlen(str);
648 if (len > 0 && str[len-1] == '%') {
649 char *cpy = strdup(str);
650 check_allocation(cpy);
652 int val = parse_integer(cpy, default_value);
654 return val * max / 100;
656 return parse_integer(str, default_value);
659 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
660 if (!strcmp(str, "middle")) {
661 return (max - self)/2;
663 return parse_int_with_percentage(str, default_value, max);
666 void usage(char *prgname) {
667 fprintf(stderr, "Usage: %s [flags]\n", prgname);
668 fprintf(stderr, "\t-a: automatic mode, the first completion is "
669 "always selected;\n");
670 fprintf(stderr, "\t-h: print this help.\n");
673 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
674 release_keyboard(r->d);
677 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
678 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
679 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
688 while ((l = *lns) != nil) {
695 XDestroyWindow(r->d, r->w);
701 int main(int argc, char **argv) {
702 // by default the first completion isn't selected
703 bool first_selected = false;
705 // parse the command line options
707 while ((ch = getopt(argc, argv, "ah")) != -1) {
710 first_selected = true;
721 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
722 readlines(&lines, INITIAL_ITEMS);
724 setlocale(LC_ALL, getenv("LANG"));
726 enum state status = LOOPING;
728 // where the monitor start (used only with xinerama)
732 // width and height of the window
736 // position on the screen
740 // the default padding
743 char *ps1 = strdup("$ ");
744 check_allocation(ps1);
746 char *fontname = strdup(default_fontname);
747 check_allocation(fontname);
750 char *text = malloc(textlen * sizeof(char));
751 check_allocation(text);
753 bool nothing_selected = first_selected;
754 /* struct completions *cs = filter(text, lines); */
755 struct completions *cs = nil;
756 update_completions(cs, text, lines, first_selected);
758 // start talking to xorg
759 Display *d = XOpenDisplay(nil);
761 fprintf(stderr, "Could not open display!\n");
762 return EX_UNAVAILABLE;
766 // XXX: is getting the default root window dimension correct?
767 XWindowAttributes xwa;
768 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
769 int d_width = xwa.width;
770 int d_height = xwa.height;
773 if (XineramaIsActive(d)) {
775 int number_of_screens = XScreenCount(d);
778 int root_x, root_y, win_x, win_y;
781 for (int i = 0; i < number_of_screens; ++i) {
782 root = XRootWindow(d, i);
783 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
787 fprintf(stderr, "No mouse found.\n");
792 // now find in which monitor the mice is on
794 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
796 for (int i = 0; i < monitors; ++i) {
797 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
798 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
799 offset_x = info[i].x_org;
800 offset_y = info[i].y_org;
801 d_width = info[i].width;
802 d_height = info[i].height;
811 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
814 compl_highlighted_fg, compl_highlighted_bg;
816 bool horizontal_layout = true;
820 char *xrm = XResourceManagerString(d);
821 XrmDatabase xdb = nil;
823 xdb = XrmGetStringDatabase(xrm);
827 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
828 fontname = strdup(value.addr);
829 check_allocation(fontname);
832 fprintf(stderr, "no font defined, using %s\n", fontname);
834 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
835 char *v = strdup(value.addr);
837 horizontal_layout = !strcmp(v, "horizontal");
841 fprintf(stderr, "no layout defined, using horizontal\n");
843 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
845 ps1 = normalize_str(value.addr);
847 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
849 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
850 width = parse_int_with_percentage(value.addr, width, d_width);
852 fprintf(stderr, "no width defined, using %d\n", width);
854 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
855 height = parse_int_with_percentage(value.addr, height, d_height);
857 fprintf(stderr, "no height defined, using %d\n", height);
859 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
860 x = parse_int_with_middle(value.addr, x, d_width, width);
862 fprintf(stderr, "no x defined, using %d\n", x);
864 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
865 y = parse_int_with_middle(value.addr, y, d_height, height);
867 fprintf(stderr, "no y defined, using %d\n", y);
869 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
870 padding = parse_integer(value.addr, padding);
872 fprintf(stderr, "no y defined, using %d\n", padding);
875 // TODO: tmp needs to be free'd after every allocation?
878 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
879 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
881 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
883 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
884 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
886 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
889 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
890 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
892 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
894 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
895 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
897 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
899 // completion highlighted
900 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
901 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
903 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
905 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
906 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
908 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
911 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
912 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
913 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
914 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
915 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
916 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
920 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
921 /* if (font == nil) { */
922 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
923 /* font = XLoadQueryFont(d, "fixed"); */
927 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
929 char **missing_charset_list;
930 int missing_charset_count;
931 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
933 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
934 return EX_UNAVAILABLE;
939 XSetWindowAttributes attr;
940 attr.override_redirect = true;
942 Window w = XCreateWindow(d, // display
943 DefaultRootWindow(d), // parent
944 x + offset_x, y + offset_y, // x y
945 width, height, // w h
947 DefaultDepth(d, DefaultScreen(d)), // depth
948 InputOutput, // class
949 DefaultVisual(d, DefaultScreen(d)), // visual
950 CWOverrideRedirect, // value mask
953 set_win_atoms_hints(d, w, width, height);
955 // we want some events
956 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
958 // make the window appear on the screen
961 // wait for the MapNotify event (i.e. the event "window rendered")
965 if (e.type == MapNotify)
969 // get the *real* width & height after the window was rendered
970 get_wh(d, &w, &width, &height);
975 // Create some graphics contexts
977 /* values.font = font->fid; */
979 struct rendering r = {
987 .prompt = XCreateGC(d, w, 0, &values),
988 .prompt_bg = XCreateGC(d, w, 0, &values),
989 .completion = XCreateGC(d, w, 0, &values),
990 .completion_bg = XCreateGC(d, w, 0, &values),
991 .completion_highlighted = XCreateGC(d, w, 0, &values),
992 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
996 .horizontal_layout = horizontal_layout,
998 .ps1len = strlen(ps1)
1002 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1005 XRenderColor xrcolor;
1006 xrcolor.red = p_fg.red;
1007 xrcolor.green = p_fg.red;
1008 xrcolor.blue = p_fg.red;
1009 xrcolor.alpha = 65535;
1010 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1013 xrcolor.red = compl_fg.red;
1014 xrcolor.green = compl_fg.green;
1015 xrcolor.blue = compl_fg.blue;
1016 xrcolor.alpha = 65535;
1017 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1019 // completion highlighted
1020 xrcolor.red = compl_highlighted_fg.red;
1021 xrcolor.green = compl_highlighted_fg.green;
1022 xrcolor.blue = compl_highlighted_fg.blue;
1023 xrcolor.alpha = 65535;
1024 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1027 // load the colors in our GCs
1028 XSetForeground(d, r.prompt, p_fg.pixel);
1029 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1030 XSetForeground(d, r.completion, compl_fg.pixel);
1031 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1032 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1033 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1035 // open the X input method
1036 XIM xim = XOpenIM(d, xdb, resname, resclass);
1037 check_allocation(xim);
1039 XIMStyles *xis = nil;
1040 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1041 fprintf(stderr, "Input Styles could not be retrieved\n");
1042 return EX_UNAVAILABLE;
1045 XIMStyle bestMatchStyle = 0;
1046 for (int i = 0; i < xis->count_styles; ++i) {
1047 XIMStyle ts = xis->supported_styles[i];
1048 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1049 bestMatchStyle = ts;
1055 if (!bestMatchStyle) {
1056 fprintf(stderr, "No matching input style could be determined\n");
1059 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1060 check_allocation(xic);
1062 // draw the window for the first time
1066 while (status == LOOPING) {
1070 if (XFilterEvent(&e, w))
1075 XRefreshKeyboardMapping(&e.xmapping);
1079 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1081 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
1082 bool shift = (ev->state & ShiftMask);
1083 complete(cs, nothing_selected, shift, text, textlen, status);
1088 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1089 nothing_selected = first_selected;
1090 popc(text, textlen);
1091 update_completions(cs, text, lines, first_selected);
1096 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1098 if (first_selected) {
1099 complete(cs, first_selected, false, text, textlen, status);
1104 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1109 // try to read what the user pressed
1112 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1114 if (s == XBufferOverflow) {
1115 // should not happen since there are no utf-8 characters
1116 // larger than 24bits, but is something to be aware of when
1117 // used to directly write to a string buffer
1118 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1121 char *str = (char*)&symbol;
1123 if (ev->state & ControlMask) {
1124 // check for some key bindings
1125 if (!strcmp(str, "")) { // C-u
1126 nothing_selected = first_selected;
1127 for (int i = 0; i < textlen; ++i)
1129 update_completions(cs, text, lines, first_selected);
1131 if (!strcmp(str, "")) { // C-h
1132 nothing_selected = first_selected;
1133 popc(text, textlen);
1134 update_completions(cs, text, lines, first_selected);
1136 if (!strcmp(str, "")) { // C-w
1137 nothing_selected = first_selected;
1139 // `textlen` is the length of the allocated string, not the
1140 // length of the ACTUAL string
1141 int p = strlen(text) - 1;
1142 if (p >= 0) { // delete the current char
1146 while (p >= 0 && isalnum(text[p])) {
1150 // erase also trailing white space
1151 while (p >= 0 && isspace(text[p])) {
1155 update_completions(cs, text, lines, first_selected);
1157 if (!strcmp(str, "\r")) { // C-m
1159 if (first_selected) {
1160 complete(cs, first_selected, false, text, textlen, status);
1163 if (!strcmp(str, "")) {
1164 complete(cs, nothing_selected, true, text, textlen, status);
1166 if (!strcmp(str, "")) {
1167 complete(cs, nothing_selected, false, text, textlen, status);
1173 int str_len = strlen(str);
1174 for (int i = 0; i < str_len; ++i) {
1175 textlen = pushc(&text, textlen, str[i]);
1176 if (textlen == -1) {
1177 fprintf(stderr, "Memory allocation error\n");
1181 nothing_selected = first_selected;
1182 update_completions(cs, text, lines, first_selected);
1190 fprintf(stderr, "Unknown event %d\n", e.type);
1195 printf("%s\n", text);
1197 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);