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 INITIAL_ITEMS 64
51 #define cannot_allocate_memory { \
52 fprintf(stderr, "Could not allocate memory\n"); \
56 #define check_allocation(a) { \
58 cannot_allocate_memory; \
61 enum state {LOOPING, OK, ERR};
63 enum text_type {PROMPT, COMPL, COMPL_HIGH};
82 bool horizontal_layout;
89 GC completion_highlighted;
90 GC completion_highlighted_bg;
95 XftColor xft_completion;
96 XftColor xft_completion_highlighted;
105 struct completions *next;
108 // return a newly allocated (and empty) completion list
109 struct completions *compl_new() {
110 struct completions *c = malloc(sizeof(struct completions));
121 // delete ONLY the given completion (i.e. does not free c->next...)
122 void compl_delete(struct completions *c) {
126 // delete all completion
127 void compl_delete_rec(struct completions *c) {
129 struct completions *t = c->next;
135 // given a completion list, select the next completion and return the
136 // element that is selected
137 struct completions *compl_select_next(struct completions *c) {
141 struct completions *orig = c;
145 if (c->next != nil) {
146 // the current one is selected and the next one exists
147 c->next->selected = true;
150 // the current one is selected and the next one is nil,
151 // select the first one
152 orig->selected = true;
159 orig->selected = true;
163 // given a completion list, select the previous and return the element
165 struct completions *compl_select_prev(struct completions *c) {
169 struct completions *last = nil;
171 if (c->selected) { // if the first is selected, select the last one
174 if (c->next == nil) {
182 // if the selected one is inside the list, select the previous one
184 if (c->next == nil) { // if c is the last, save it for later
188 if (c->next && c->next->selected) {
190 c->next->selected = false;
196 // if nothing were selected, select the last one
201 /* if (n || c->selected) { // select the last one */
202 /* c->selected = false; */
203 /* while (cc != nil) { */
204 /* if (cc->next == nil) { */
205 /* cc->selected = true; */
211 /* else // select the previous one */
212 /* while (cc != nil) { */
213 /* if (cc->next != nil && cc->next->selected) { */
214 /* cc->next->selected = false; */
215 /* cc->selected = true; */
223 // create a completion list from a text and the list of possible completions
224 struct completions *filter(char *text, char **lines) {
226 struct completions *root = compl_new();
227 struct completions *c = root;
236 if (strcasestr(l, text) != nil) {
237 c->next = compl_new();
240 compl_delete_rec(root);
249 struct completions *r = root->next;
254 // update the given completion, that is: clean the old cs & generate a new one.
255 struct completions *update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
256 compl_delete_rec(cs);
257 cs = filter(text, lines);
258 if (first_selected && cs != nil)
263 // select the next, or the previous, selection and update some
264 // state. `text' will be updated with the text of the completion and
265 // `textlen' with the new lenght of `text'. If the memory cannot be
266 // allocated, `status' will be set to `ERR'.
267 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
269 // if the first is always selected, and the first entry is different
270 // from the text, expand the text and return
274 && strcmp(cs->completion, *text) != 0
277 *text = strdup(cs->completion);
279 fprintf(stderr, "Memory allocation error!\n");
283 *textlen = strlen(*text);
287 struct completions *n = p
288 ? compl_select_prev(cs)
289 : compl_select_next(cs);
293 *text = strdup(n->completion);
295 fprintf(stderr, "Memory allocation error!\n");
299 *textlen = strlen(*text);
304 // push the character c at the end of the string pointed by p
305 int pushc(char **p, int maxlen, char c) {
306 int len = strnlen(*p, maxlen);
308 if (!(len < maxlen -2)) {
309 maxlen += maxlen >> 1;
310 char *newptr = realloc(*p, maxlen);
311 if (newptr == nil) { // bad!
322 // return the number of character
323 int utf8strnlen(char *s, int maxlen) {
325 while (*s && maxlen > 0) {
326 len += (*s++ & 0xc0) != 0x80;
332 // remove the last *glyph* from the *utf8* string!
333 // this is different from just setting the last byte to 0 (in some
334 // cases ofc). The actual implementation is quite inefficient because
335 // it remove the last byte until the number of glyphs doesn't change
336 void popc(char *p, int maxlen) {
337 int len = strnlen(p, maxlen);
342 int ulen = utf8strnlen(p, maxlen);
343 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
349 // If the string is surrounded by quotes (`"`) remove them and replace
350 // every `\"` in the string with `"`
351 char *normalize_str(const char *str) {
352 int len = strlen(str);
356 char *s = calloc(len, sizeof(char));
365 str += 2; // skip this and the next char
372 str++; // skip only this char
382 // read an arbitrary long line from stdin and return a pointer to it
383 // TODO: resize the allocated memory to exactly fit the string once
385 char *readline(bool *eof) {
387 char *str = calloc(maxlen, sizeof(char));
389 fprintf(stderr, "Cannot allocate memory!\n");
390 exit(EX_UNAVAILABLE);
394 while((c = getchar()) != EOF) {
398 maxlen = pushc(&str, maxlen, c);
401 fprintf(stderr, "Cannot allocate memory!\n");
402 exit(EX_UNAVAILABLE);
409 // read an arbitrary amount of text until an EOF and store it in
410 // lns. `items` is the capacity of lns. It may increase lns with
411 // `realloc(3)` to store more line. Return the number of lines
412 // read. The last item will always be a NULL pointer. It ignore the
413 // "null" (empty) lines
414 int readlines (char ***lns, int items) {
415 bool finished = false;
419 lines[n] = readline(&finished);
421 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
423 --n; // forget about this line
431 if (n == items - 1) {
433 char **l = realloc(lines, sizeof(char*) * items);
445 // Compute the dimension of the string str once rendered, return the
446 // width and save the width and the height in ret_width and ret_height
447 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
452 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
453 /* height = gi.height; */
454 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
455 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
456 height = r->font->ascent - r->font->descent;
457 width = gi.width - gi.x;
460 XmbTextExtents(*r->font, str, len, nil, &rect);
461 height = rect.height;
464 if (ret_width != nil) *ret_width = width;
465 if (ret_height != nil) *ret_height = height;
469 // Draw the string str
470 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
473 if (tt == PROMPT) xftcolor = r->xft_prompt;
474 if (tt == COMPL) xftcolor = r->xft_completion;
475 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
477 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
480 if (tt == PROMPT) gc = r->prompt;
481 if (tt == COMPL) gc = r->completion;
482 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
483 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
487 // Duplicate the string str and substitute every space with a 'n'
488 char *strdupn(char *str) {
489 int len = strlen(str);
491 if (str == nil || len == 0)
494 char *dup = strdup(str);
498 for (int i = 0; i < len; ++i)
505 // |------------------|----------------------------------------------|
506 // | 20 char text | completion | completion | completion | compl |
507 // |------------------|----------------------------------------------|
508 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
509 int prompt_width = 20; // char
512 char *ps1_dup = strdupn(r->ps1);
516 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
517 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
519 int start_at = ps1xlen;
521 start_at = text_extents("n", 1, r, nil, nil);
522 start_at = start_at * prompt_width + r->padding;
524 int texty = (height + r->height) >>1;
526 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
528 int text_len = strlen(text);
529 if (text_len > prompt_width)
530 text = text + (text_len - prompt_width);
531 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
532 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
534 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
537 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
538 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
540 int len = strlen(cs->completion);
541 int text_width = text_extents(cs->completion, len, r, nil, nil);
543 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
545 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
547 start_at += text_width + r->padding * 2;
549 if (start_at > r->width)
550 break; // don't draw completion if the space isn't enough
558 // |-----------------------------------------------------------------|
560 // |-----------------------------------------------------------------|
562 // |-----------------------------------------------------------------|
564 // |-----------------------------------------------------------------|
565 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
567 text_extents("fjpgl", 5, r, nil, &height);
568 int start_at = height + r->padding;
570 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
571 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
573 char *ps1_dup = strdupn(r->ps1);
574 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
575 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
578 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
579 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
580 start_at += r->padding;
583 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
584 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
586 int len = strlen(cs->completion);
587 text_extents(cs->completion, len, r, &width, &height);
588 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
589 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
591 start_at += height + r->padding *2;
593 if (start_at > r->height)
594 break; // don't draw completion if the space isn't enough
602 void draw(struct rendering *r, char *text, struct completions *cs) {
603 if (r->horizontal_layout)
604 draw_horizontally(r, text, cs);
606 draw_vertically(r, text, cs);
609 /* Set some WM stuff */
610 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
612 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
616 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
617 XInternAtom(d, "ATOM", false),
620 (unsigned char *)&type,
624 /* some window managers honor this properties */
625 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
628 XInternAtom(d, "_NET_WM_STATE", false),
629 XInternAtom(d, "ATOM", false),
632 (unsigned char *)&type,
636 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
639 XInternAtom(d, "_NET_WM_STATE", false),
640 XInternAtom(d, "ATOM", false),
643 (unsigned char *)&type,
647 // setting window hints
648 XClassHint *class_hint = XAllocClassHint();
649 if (class_hint == nil) {
650 fprintf(stderr, "Could not allocate memory for class hint\n");
651 exit(EX_UNAVAILABLE);
653 class_hint->res_name = resname;
654 class_hint->res_class = resclass;
655 XSetClassHint(d, w, class_hint);
658 XSizeHints *size_hint = XAllocSizeHints();
659 if (size_hint == nil) {
660 fprintf(stderr, "Could not allocate memory for size hint\n");
661 exit(EX_UNAVAILABLE);
663 size_hint->flags = PMinSize | PBaseSize;
664 size_hint->min_width = width;
665 size_hint->base_width = width;
666 size_hint->min_height = height;
667 size_hint->base_height = height;
672 void get_wh(Display *d, Window *w, int *width, int *height) {
673 XWindowAttributes win_attr;
674 XGetWindowAttributes(d, *w, &win_attr);
675 *height = win_attr.height;
676 *width = win_attr.width;
679 // I know this may seem a little hackish BUT is the only way I managed
680 // to actually grab that goddam keyboard. Only one call to
681 // XGrabKeyboard does not always end up with the keyboard grabbed!
682 int take_keyboard(Display *d, Window w) {
684 for (i = 0; i < 100; i++) {
685 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
692 // release the keyboard.
693 void release_keyboard(Display *d) {
694 XUngrabKeyboard(d, CurrentTime);
697 int parse_integer(const char *str, int default_value) {
700 long lval = strtol(str, &ep, 10);
701 if (str[0] == '\0' || *ep != '\0') { // NaN
702 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
703 return default_value;
705 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
706 (lval > INT_MAX || lval < INT_MIN)) {
707 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
708 return default_value;
713 // like parse_integer, but if the value ends with a `%' then its
714 // treated like a percentage (`max' is used to compute the percentage)
715 int parse_int_with_percentage(const char *str, int default_value, int max) {
716 int len = strlen(str);
717 if (len > 0 && str[len-1] == '%') {
718 char *cpy = strdup(str);
719 check_allocation(cpy);
721 int val = parse_integer(cpy, default_value);
723 return val * max / 100;
725 return parse_integer(str, default_value);
728 // like parse_int_with_percentage but understands the special value
729 // "middle" that is (max - self) / 2
730 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
731 if (!strcmp(str, "middle")) {
732 return (max - self)/2;
734 return parse_int_with_percentage(str, default_value, max);
737 // Given the name of the program (argv[0]?) print a small help on stderr
738 void usage(char *prgname) {
739 fprintf(stderr, "Usage: %s [flags]\n", prgname);
740 fprintf(stderr, "\t-a: automatic mode, the first completion is "
741 "always selected;\n");
742 fprintf(stderr, "\t-h: print this help.\n");
745 // Given an event, try to understand what the user wants. If the
746 // return value is ADD_CHAR then `input' is a pointer to a string that
747 // will need to be free'ed.
748 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
749 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
752 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
753 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
755 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
758 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
761 // try to read what the user pressed
764 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
765 if (s == XBufferOverflow) {
766 // should not happen since there are no utf-8 characters larger
768 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
771 char *str = (char*)&symbol;
773 if (ev->state & ControlMask) {
774 if (!strcmp(str, "")) // C-u
776 if (!strcmp(str, "")) // C-w
778 if (!strcmp(str, "")) // C-h
780 if (!strcmp(str, "\r")) // C-m
782 if (!strcmp(str, "")) // C-p
784 if (!strcmp(str, "")) // C-n
786 if (!strcmp(str, "")) // C-c
790 *input = strdup((char*)&symbol);
792 fprintf(stderr, "Error while allocating memory for key.\n");
799 // clean up some resources
800 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
801 release_keyboard(r->d);
804 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
805 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
806 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
815 while ((l = *lns) != nil) {
822 XDestroyWindow(r->d, r->w);
828 int main(int argc, char **argv) {
829 // by default the first completion isn't selected
830 bool first_selected = false;
832 // parse the command line options
834 while ((ch = getopt(argc, argv, "ahv")) != -1) {
837 first_selected = true;
843 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
851 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
852 readlines(&lines, INITIAL_ITEMS);
854 setlocale(LC_ALL, getenv("LANG"));
856 enum state status = LOOPING;
858 // where the monitor start (used only with xinerama)
862 // width and height of the window
866 // position on the screen
870 // the default padding
873 char *ps1 = strdup("$ ");
874 check_allocation(ps1);
876 char *fontname = strdup(default_fontname);
877 check_allocation(fontname);
880 char *text = malloc(textlen * sizeof(char));
881 check_allocation(text);
883 /* struct completions *cs = filter(text, lines); */
884 struct completions *cs = nil;
885 cs = update_completions(cs, text, lines, first_selected);
887 // start talking to xorg
888 Display *d = XOpenDisplay(nil);
890 fprintf(stderr, "Could not open display!\n");
891 return EX_UNAVAILABLE;
895 // XXX: is getting the default root window dimension correct?
896 XWindowAttributes xwa;
897 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
898 int d_width = xwa.width;
899 int d_height = xwa.height;
902 if (XineramaIsActive(d)) {
904 int number_of_screens = XScreenCount(d);
907 int root_x, root_y, win_x, win_y;
910 for (int i = 0; i < number_of_screens; ++i) {
911 root = XRootWindow(d, i);
912 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
916 fprintf(stderr, "No mouse found.\n");
921 // now find in which monitor the mice is on
923 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
925 for (int i = 0; i < monitors; ++i) {
926 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
927 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
928 offset_x = info[i].x_org;
929 offset_y = info[i].y_org;
930 d_width = info[i].width;
931 d_height = info[i].height;
940 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
943 compl_highlighted_fg, compl_highlighted_bg;
945 bool horizontal_layout = true;
949 char *xrm = XResourceManagerString(d);
950 XrmDatabase xdb = nil;
952 xdb = XrmGetStringDatabase(xrm);
956 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
957 fontname = strdup(value.addr);
958 check_allocation(fontname);
961 fprintf(stderr, "no font defined, using %s\n", fontname);
963 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
964 char *v = strdup(value.addr);
966 horizontal_layout = !strcmp(v, "horizontal");
970 fprintf(stderr, "no layout defined, using horizontal\n");
972 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
974 ps1 = normalize_str(value.addr);
976 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
978 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
979 width = parse_int_with_percentage(value.addr, width, d_width);
981 fprintf(stderr, "no width defined, using %d\n", width);
983 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
984 height = parse_int_with_percentage(value.addr, height, d_height);
986 fprintf(stderr, "no height defined, using %d\n", height);
988 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
989 x = parse_int_with_middle(value.addr, x, d_width, width);
991 fprintf(stderr, "no x defined, using %d\n", x);
993 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
994 y = parse_int_with_middle(value.addr, y, d_height, height);
996 fprintf(stderr, "no y defined, using %d\n", y);
998 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
999 padding = parse_integer(value.addr, padding);
1001 fprintf(stderr, "no y defined, using %d\n", padding);
1004 // TODO: tmp needs to be free'd after every allocation?
1007 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1008 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1010 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1012 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1013 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1015 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1018 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1019 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1021 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1023 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1024 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1026 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1028 // completion highlighted
1029 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1030 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1032 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1034 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1035 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1037 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1040 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1041 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1042 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1043 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1044 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1045 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1049 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
1050 /* if (font == nil) { */
1051 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
1052 /* font = XLoadQueryFont(d, "fixed"); */
1056 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1058 char **missing_charset_list;
1059 int missing_charset_count;
1060 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1062 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1063 return EX_UNAVAILABLE;
1067 // create the window
1068 XSetWindowAttributes attr;
1069 attr.override_redirect = true;
1071 Window w = XCreateWindow(d, // display
1072 DefaultRootWindow(d), // parent
1073 x + offset_x, y + offset_y, // x y
1074 width, height, // w h
1076 DefaultDepth(d, DefaultScreen(d)), // depth
1077 InputOutput, // class
1078 DefaultVisual(d, DefaultScreen(d)), // visual
1079 CWOverrideRedirect, // value mask
1082 set_win_atoms_hints(d, w, width, height);
1084 // we want some events
1085 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1087 // make the window appear on the screen
1090 // wait for the MapNotify event (i.e. the event "window rendered")
1094 if (e.type == MapNotify)
1098 // get the *real* width & height after the window was rendered
1099 get_wh(d, &w, &width, &height);
1102 take_keyboard(d, w);
1104 // Create some graphics contexts
1106 /* values.font = font->fid; */
1108 struct rendering r = {
1116 .prompt = XCreateGC(d, w, 0, &values),
1117 .prompt_bg = XCreateGC(d, w, 0, &values),
1118 .completion = XCreateGC(d, w, 0, &values),
1119 .completion_bg = XCreateGC(d, w, 0, &values),
1120 .completion_highlighted = XCreateGC(d, w, 0, &values),
1121 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1125 .horizontal_layout = horizontal_layout,
1127 .ps1len = strlen(ps1)
1131 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1134 XRenderColor xrcolor;
1135 xrcolor.red = p_fg.red;
1136 xrcolor.green = p_fg.red;
1137 xrcolor.blue = p_fg.red;
1138 xrcolor.alpha = 65535;
1139 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1142 xrcolor.red = compl_fg.red;
1143 xrcolor.green = compl_fg.green;
1144 xrcolor.blue = compl_fg.blue;
1145 xrcolor.alpha = 65535;
1146 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1148 // completion highlighted
1149 xrcolor.red = compl_highlighted_fg.red;
1150 xrcolor.green = compl_highlighted_fg.green;
1151 xrcolor.blue = compl_highlighted_fg.blue;
1152 xrcolor.alpha = 65535;
1153 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1156 // load the colors in our GCs
1157 XSetForeground(d, r.prompt, p_fg.pixel);
1158 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1159 XSetForeground(d, r.completion, compl_fg.pixel);
1160 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1161 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1162 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1164 // open the X input method
1165 XIM xim = XOpenIM(d, xdb, resname, resclass);
1166 check_allocation(xim);
1168 XIMStyles *xis = nil;
1169 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1170 fprintf(stderr, "Input Styles could not be retrieved\n");
1171 return EX_UNAVAILABLE;
1174 XIMStyle bestMatchStyle = 0;
1175 for (int i = 0; i < xis->count_styles; ++i) {
1176 XIMStyle ts = xis->supported_styles[i];
1177 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1178 bestMatchStyle = ts;
1184 if (!bestMatchStyle) {
1185 fprintf(stderr, "No matching input style could be determined\n");
1188 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1189 check_allocation(xic);
1191 // draw the window for the first time
1195 while (status == LOOPING) {
1199 if (XFilterEvent(&e, w))
1204 XRefreshKeyboardMapping(&e.xmapping);
1208 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1211 switch (parse_event(d, ev, xic, &input)) {
1218 if (first_selected) {
1219 complete(cs, first_selected, false, &text, &textlen, &status);
1224 complete(cs, first_selected, true, &text, &textlen, &status);
1229 complete(cs, first_selected, false, &text, &textlen, &status);
1234 popc(text, textlen);
1235 cs = update_completions(cs, text, lines, first_selected);
1239 // `textlen` is the lenght of the allocated string, not the
1240 // lenght of the ACTUAL string
1241 int p = strlen(text) -1;
1242 if (p > 0) { // delete the current char
1247 // erase the alphanumeric char
1248 while (p >= 0 && isalnum(text[p])) {
1253 // erase also trailing white spaces
1254 while (p >= 0 && isspace(text[p])) {
1258 cs = update_completions(cs, text, lines, first_selected);
1263 for (int i = 0; i < textlen; ++i)
1265 cs = update_completions(cs, text, lines, first_selected);
1270 int str_len = strlen(input);
1271 for (int i = 0; i < str_len; ++i) {
1272 textlen = pushc(&text, textlen, input[i]);
1273 if (textlen == -1) {
1274 fprintf(stderr, "Memory allocation error\n");
1278 cs = update_completions(cs, text, lines, first_selected);
1288 fprintf(stderr, "Unknown event %d\n", e.type);
1293 printf("%s\n", text);
1295 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);