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"
37 # define default_fontname "monospace"
39 # define default_fontname "fixed"
42 #define MIN(a, b) ((a) < (b) ? (a) : (b))
43 #define MAX(a, b) ((a) > (b) ? (a) : (b))
45 // If we don't have it or we don't want an "ignore case" completion
46 // style, fall back to `strstr(3)`
47 #ifndef USE_STRCASESTR
48 # define strcasestr strstr
51 #define INITIAL_ITEMS 64
53 #define check_allocation(a) { \
55 fprintf(stderr, "Could not allocate memory\n"); \
60 // The possible state of the event loop.
61 enum state {LOOPING, OK, ERR};
63 // for the drawing-related function. The text to be rendered could be
64 // the prompt, a completion or a highlighted completion
65 enum text_type {PROMPT, COMPL, COMPL_HIGH};
67 // These are the possible action to be performed after user input.
86 bool horizontal_layout;
93 GC completion_highlighted;
94 GC completion_highlighted_bg;
99 XftColor xft_completion;
100 XftColor xft_completion_highlighted;
106 // A simple linked list to store the completions.
110 struct completions *next;
113 // return a newly allocated (and empty) completion list
114 struct completions *compl_new() {
115 struct completions *c = malloc(sizeof(struct completions));
126 // delete ONLY the given completion (i.e. does not free c->next...)
127 void compl_delete(struct completions *c) {
131 // delete all completion
132 void compl_delete_rec(struct completions *c) {
134 struct completions *t = c->next;
140 // given a completion list, select the next completion and return the
141 // element that is selected
142 struct completions *compl_select_next(struct completions *c) {
146 struct completions *orig = c;
150 if (c->next != nil) {
151 // the current one is selected and the next one exists
152 c->next->selected = true;
155 // the current one is selected and the next one is nil,
156 // select the first one
157 orig->selected = true;
164 orig->selected = true;
168 // given a completion list, select the previous and return the element
170 struct completions *compl_select_prev(struct completions *c) {
174 struct completions *last = nil;
176 if (c->selected) { // if the first is selected, select the last one
179 if (c->next == nil) {
187 // if the selected one is inside the list, select the previous one
189 if (c->next == nil) { // if c is the last, save it for later
193 if (c->next && c->next->selected) {
195 c->next->selected = false;
201 // if nothing were selected, select the last one
207 // create a completion list from a text and the list of possible completions
208 struct completions *filter(char *text, char **lines) {
210 struct completions *root = compl_new();
211 struct completions *c = root;
220 if (strcasestr(l, text) != nil) {
221 c->next = compl_new();
224 compl_delete_rec(root);
233 struct completions *r = root->next;
238 // update the given completion, that is: clean the old cs & generate a new one.
239 struct completions *update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
240 compl_delete_rec(cs);
241 cs = filter(text, lines);
242 if (first_selected && cs != nil)
247 // select the next, or the previous, selection and update some
248 // state. `text' will be updated with the text of the completion and
249 // `textlen' with the new lenght of `text'. If the memory cannot be
250 // allocated, `status' will be set to `ERR'.
251 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
252 // if the first is always selected, and the first entry is different
253 // from the text, expand the text and return
257 && strcmp(cs->completion, *text) != 0
260 *text = strdup(cs->completion);
262 fprintf(stderr, "Memory allocation error!\n");
266 *textlen = strlen(*text);
270 struct completions *n = p
271 ? compl_select_prev(cs)
272 : compl_select_next(cs);
276 *text = strdup(n->completion);
278 fprintf(stderr, "Memory allocation error!\n");
282 *textlen = strlen(*text);
287 // push the character c at the end of the string pointed by p
288 int pushc(char **p, int maxlen, char c) {
289 int len = strnlen(*p, maxlen);
291 if (!(len < maxlen -2)) {
292 maxlen += maxlen >> 1;
293 char *newptr = realloc(*p, maxlen);
294 if (newptr == nil) { // bad!
305 // return the number of character
306 int utf8strnlen(char *s, int maxlen) {
308 while (*s && maxlen > 0) {
309 len += (*s++ & 0xc0) != 0x80;
315 // remove the last *glyph* from the *utf8* string!
316 // this is different from just setting the last byte to 0 (in some
317 // cases ofc). The actual implementation is quite inefficient because
318 // it remove the last byte until the number of glyphs doesn't change
319 void popc(char *p, int maxlen) {
320 int len = strnlen(p, maxlen);
325 int ulen = utf8strnlen(p, maxlen);
326 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
332 // If the string is surrounded by quotes (`"`) remove them and replace
333 // every `\"` in the string with `"`
334 char *normalize_str(const char *str) {
335 int len = strlen(str);
339 char *s = calloc(len, sizeof(char));
348 str += 2; // skip this and the next char
355 str++; // skip only this char
365 // read an arbitrary long line from stdin and return a pointer to it
366 // TODO: resize the allocated memory to exactly fit the string once
368 char *readline(bool *eof) {
370 char *str = calloc(maxlen, sizeof(char));
372 fprintf(stderr, "Cannot allocate memory!\n");
373 exit(EX_UNAVAILABLE);
377 while((c = getchar()) != EOF) {
381 maxlen = pushc(&str, maxlen, c);
384 fprintf(stderr, "Cannot allocate memory!\n");
385 exit(EX_UNAVAILABLE);
392 // read an arbitrary amount of text until an EOF and store it in
393 // lns. `items` is the capacity of lns. It may increase lns with
394 // `realloc(3)` to store more line. Return the number of lines
395 // read. The last item will always be a NULL pointer. It ignore the
396 // "null" (empty) lines
397 int readlines (char ***lns, int items) {
398 bool finished = false;
402 lines[n] = readline(&finished);
404 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
406 --n; // forget about this line
414 if (n == items - 1) {
416 char **l = realloc(lines, sizeof(char*) * items);
428 // Compute the dimension of the string str once rendered, return the
429 // width and save the width and the height in ret_width and ret_height
430 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
435 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
436 /* height = gi.height; */
437 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
438 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
439 height = r->font->ascent - r->font->descent;
440 width = gi.width - gi.x;
443 XmbTextExtents(*r->font, str, len, nil, &rect);
444 height = rect.height;
447 if (ret_width != nil) *ret_width = width;
448 if (ret_height != nil) *ret_height = height;
452 // Draw the string str
453 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
456 if (tt == PROMPT) xftcolor = r->xft_prompt;
457 if (tt == COMPL) xftcolor = r->xft_completion;
458 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
460 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
463 if (tt == PROMPT) gc = r->prompt;
464 if (tt == COMPL) gc = r->completion;
465 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
466 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
470 // Duplicate the string str and substitute every space with a 'n'
471 char *strdupn(char *str) {
472 int len = strlen(str);
474 if (str == nil || len == 0)
477 char *dup = strdup(str);
481 for (int i = 0; i < len; ++i)
488 // |------------------|----------------------------------------------|
489 // | 20 char text | completion | completion | completion | compl |
490 // |------------------|----------------------------------------------|
491 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
492 int prompt_width = 20; // char
495 char *ps1_dup = strdupn(r->ps1);
499 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
500 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
502 int start_at = ps1xlen;
504 start_at = text_extents("n", 1, r, nil, nil);
505 start_at = start_at * prompt_width + r->padding;
507 int texty = (height + r->height) >>1;
509 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
511 int text_len = strlen(text);
512 if (text_len > prompt_width)
513 text = text + (text_len - prompt_width);
514 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
515 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
517 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
520 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
521 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
523 int len = strlen(cs->completion);
524 int text_width = text_extents(cs->completion, len, r, nil, nil);
526 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
528 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
530 start_at += text_width + r->padding * 2;
532 if (start_at > r->width)
533 break; // don't draw completion if the space isn't enough
541 // |-----------------------------------------------------------------|
543 // |-----------------------------------------------------------------|
545 // |-----------------------------------------------------------------|
547 // |-----------------------------------------------------------------|
548 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
550 text_extents("fjpgl", 5, r, nil, &height);
551 int start_at = height + r->padding;
553 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
554 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
556 char *ps1_dup = strdupn(r->ps1);
557 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
558 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
561 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
562 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
563 start_at += r->padding;
566 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
567 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
569 int len = strlen(cs->completion);
570 text_extents(cs->completion, len, r, &width, &height);
571 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
572 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
574 start_at += height + r->padding *2;
576 if (start_at > r->height)
577 break; // don't draw completion if the space isn't enough
585 void draw(struct rendering *r, char *text, struct completions *cs) {
586 if (r->horizontal_layout)
587 draw_horizontally(r, text, cs);
589 draw_vertically(r, text, cs);
592 /* Set some WM stuff */
593 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
595 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
599 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
600 XInternAtom(d, "ATOM", false),
603 (unsigned char *)&type,
607 /* some window managers honor this properties */
608 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
611 XInternAtom(d, "_NET_WM_STATE", false),
612 XInternAtom(d, "ATOM", false),
615 (unsigned char *)&type,
619 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
622 XInternAtom(d, "_NET_WM_STATE", false),
623 XInternAtom(d, "ATOM", false),
626 (unsigned char *)&type,
630 // setting window hints
631 XClassHint *class_hint = XAllocClassHint();
632 if (class_hint == nil) {
633 fprintf(stderr, "Could not allocate memory for class hint\n");
634 exit(EX_UNAVAILABLE);
636 class_hint->res_name = resname;
637 class_hint->res_class = resclass;
638 XSetClassHint(d, w, class_hint);
641 XSizeHints *size_hint = XAllocSizeHints();
642 if (size_hint == nil) {
643 fprintf(stderr, "Could not allocate memory for size hint\n");
644 exit(EX_UNAVAILABLE);
646 size_hint->flags = PMinSize | PBaseSize;
647 size_hint->min_width = width;
648 size_hint->base_width = width;
649 size_hint->min_height = height;
650 size_hint->base_height = height;
655 // write the width and height of the window `w' respectively in `width'
657 void get_wh(Display *d, Window *w, int *width, int *height) {
658 XWindowAttributes win_attr;
659 XGetWindowAttributes(d, *w, &win_attr);
660 *height = win_attr.height;
661 *width = win_attr.width;
664 // I know this may seem a little hackish BUT is the only way I managed
665 // to actually grab that goddam keyboard. Only one call to
666 // XGrabKeyboard does not always end up with the keyboard grabbed!
667 int take_keyboard(Display *d, Window w) {
669 for (i = 0; i < 100; i++) {
670 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
677 // release the keyboard.
678 void release_keyboard(Display *d) {
679 XUngrabKeyboard(d, CurrentTime);
682 // Given a string, try to parse it as a number or return
684 int parse_integer(const char *str, int default_value) {
687 long lval = strtol(str, &ep, 10);
688 if (str[0] == '\0' || *ep != '\0') { // NaN
689 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
690 return default_value;
692 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
693 (lval > INT_MAX || lval < INT_MIN)) {
694 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
695 return default_value;
700 // like parse_integer, but if the value ends with a `%' then its
701 // treated like a percentage (`max' is used to compute the percentage)
702 int parse_int_with_percentage(const char *str, int default_value, int max) {
703 int len = strlen(str);
704 if (len > 0 && str[len-1] == '%') {
705 char *cpy = strdup(str);
706 check_allocation(cpy);
708 int val = parse_integer(cpy, default_value);
710 return val * max / 100;
712 return parse_integer(str, default_value);
715 // like parse_int_with_percentage but understands the special value
716 // "middle" that is (max - self) / 2
717 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
718 if (!strcmp(str, "middle")) {
719 return (max - self)/2;
721 return parse_int_with_percentage(str, default_value, max);
724 // Given the name of the program (argv[0]?) print a small help on stderr
725 void usage(char *prgname) {
726 fprintf(stderr, "Usage: %s [flags]\n", prgname);
727 fprintf(stderr, "\t-a: automatic mode, the first completion is "
728 "always selected;\n");
729 fprintf(stderr, "\t-h: print this help.\n");
732 // Given an event, try to understand what the user wants. If the
733 // return value is ADD_CHAR then `input' is a pointer to a string that
734 // will need to be free'ed.
735 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
736 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
739 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
740 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
742 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
745 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
748 // try to read what the user pressed
751 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
752 if (s == XBufferOverflow) {
753 // should not happen since there are no utf-8 characters larger
755 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
758 char *str = (char*)&symbol;
760 if (ev->state & ControlMask) {
761 if (!strcmp(str, "")) // C-u
763 if (!strcmp(str, "")) // C-w
765 if (!strcmp(str, "")) // C-h
767 if (!strcmp(str, "\r")) // C-m
769 if (!strcmp(str, "")) // C-p
771 if (!strcmp(str, "")) // C-n
773 if (!strcmp(str, "")) // C-c
775 if (!strcmp(str, "\t")) // C-i
776 return TOGGLE_FIRST_SELECTED;
779 *input = strdup((char*)&symbol);
781 fprintf(stderr, "Error while allocating memory for key.\n");
788 // clean up some resources
789 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
790 release_keyboard(r->d);
793 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
794 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
795 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
804 while ((l = *lns) != nil) {
811 XDestroyWindow(r->d, r->w);
817 int main(int argc, char **argv) {
819 // stdio & rpat: to read and write stdio/stdout
820 // unix: to connect to Xorg
821 pledge("stdio rpath unix", "");
824 // by default the first completion isn't selected
825 bool first_selected = false;
827 // parse the command line options
829 while ((ch = getopt(argc, argv, "ahv")) != -1) {
832 first_selected = true;
838 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
846 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
847 readlines(&lines, INITIAL_ITEMS);
849 setlocale(LC_ALL, getenv("LANG"));
851 enum state status = LOOPING;
853 // where the monitor start (used only with xinerama)
857 // width and height of the window
861 // position on the screen
865 // the default padding
868 char *ps1 = strdup("$ ");
869 check_allocation(ps1);
871 char *fontname = strdup(default_fontname);
872 check_allocation(fontname);
875 char *text = malloc(textlen * sizeof(char));
876 check_allocation(text);
878 /* struct completions *cs = filter(text, lines); */
879 struct completions *cs = nil;
880 cs = update_completions(cs, text, lines, first_selected);
882 // start talking to xorg
883 Display *d = XOpenDisplay(nil);
885 fprintf(stderr, "Could not open display!\n");
886 return EX_UNAVAILABLE;
890 // XXX: is getting the default root window dimension correct?
891 XWindowAttributes xwa;
892 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
893 int d_width = xwa.width;
894 int d_height = xwa.height;
897 if (XineramaIsActive(d)) {
899 int number_of_screens = XScreenCount(d);
902 int root_x, root_y, win_x, win_y;
905 for (int i = 0; i < number_of_screens; ++i) {
906 root = XRootWindow(d, i);
907 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
911 fprintf(stderr, "No mouse found.\n");
916 // now find in which monitor the mice is on
918 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
920 for (int i = 0; i < monitors; ++i) {
921 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
922 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
923 offset_x = info[i].x_org;
924 offset_y = info[i].y_org;
925 d_width = info[i].width;
926 d_height = info[i].height;
935 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
938 compl_highlighted_fg, compl_highlighted_bg;
940 bool horizontal_layout = true;
944 char *xrm = XResourceManagerString(d);
945 XrmDatabase xdb = nil;
947 xdb = XrmGetStringDatabase(xrm);
951 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
952 fontname = strdup(value.addr);
953 check_allocation(fontname);
956 fprintf(stderr, "no font defined, using %s\n", fontname);
958 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
959 char *v = strdup(value.addr);
961 horizontal_layout = !strcmp(v, "horizontal");
965 fprintf(stderr, "no layout defined, using horizontal\n");
967 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
969 ps1 = normalize_str(value.addr);
971 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
973 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
974 width = parse_int_with_percentage(value.addr, width, d_width);
976 fprintf(stderr, "no width defined, using %d\n", width);
978 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
979 height = parse_int_with_percentage(value.addr, height, d_height);
981 fprintf(stderr, "no height defined, using %d\n", height);
983 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
984 x = parse_int_with_middle(value.addr, x, d_width, width);
986 fprintf(stderr, "no x defined, using %d\n", x);
988 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
989 y = parse_int_with_middle(value.addr, y, d_height, height);
991 fprintf(stderr, "no y defined, using %d\n", y);
993 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
994 padding = parse_integer(value.addr, padding);
996 fprintf(stderr, "no padding defined, using %d\n", padding);
999 // TODO: tmp needs to be free'd after every allocation?
1002 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1003 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1005 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1007 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1008 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1010 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1013 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1014 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1016 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1018 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1019 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1021 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1023 // completion highlighted
1024 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1025 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1027 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1029 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1030 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1032 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1035 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1036 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1037 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1038 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1039 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1040 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1045 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1047 char **missing_charset_list;
1048 int missing_charset_count;
1049 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1051 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1052 return EX_UNAVAILABLE;
1056 // create the window
1057 XSetWindowAttributes attr;
1058 attr.override_redirect = true;
1060 Window w = XCreateWindow(d, // display
1061 DefaultRootWindow(d), // parent
1062 x + offset_x, y + offset_y, // x y
1063 width, height, // w h
1065 DefaultDepth(d, DefaultScreen(d)), // depth
1066 InputOutput, // class
1067 DefaultVisual(d, DefaultScreen(d)), // visual
1068 CWOverrideRedirect, // value mask
1071 set_win_atoms_hints(d, w, width, height);
1073 // we want some events
1074 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1076 // make the window appear on the screen
1079 // wait for the MapNotify event (i.e. the event "window rendered")
1083 if (e.type == MapNotify)
1087 // get the *real* width & height after the window was rendered
1088 get_wh(d, &w, &width, &height);
1091 take_keyboard(d, w);
1093 // Create some graphics contexts
1095 /* values.font = font->fid; */
1097 struct rendering r = {
1105 .prompt = XCreateGC(d, w, 0, &values),
1106 .prompt_bg = XCreateGC(d, w, 0, &values),
1107 .completion = XCreateGC(d, w, 0, &values),
1108 .completion_bg = XCreateGC(d, w, 0, &values),
1109 .completion_highlighted = XCreateGC(d, w, 0, &values),
1110 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1114 .horizontal_layout = horizontal_layout,
1116 .ps1len = strlen(ps1)
1120 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1123 XRenderColor xrcolor;
1124 xrcolor.red = p_fg.red;
1125 xrcolor.green = p_fg.red;
1126 xrcolor.blue = p_fg.red;
1127 xrcolor.alpha = 65535;
1128 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1131 xrcolor.red = compl_fg.red;
1132 xrcolor.green = compl_fg.green;
1133 xrcolor.blue = compl_fg.blue;
1134 xrcolor.alpha = 65535;
1135 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1137 // completion highlighted
1138 xrcolor.red = compl_highlighted_fg.red;
1139 xrcolor.green = compl_highlighted_fg.green;
1140 xrcolor.blue = compl_highlighted_fg.blue;
1141 xrcolor.alpha = 65535;
1142 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1145 // load the colors in our GCs
1146 XSetForeground(d, r.prompt, p_fg.pixel);
1147 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1148 XSetForeground(d, r.completion, compl_fg.pixel);
1149 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1150 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1151 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1153 // open the X input method
1154 XIM xim = XOpenIM(d, xdb, resname, resclass);
1155 check_allocation(xim);
1157 XIMStyles *xis = nil;
1158 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1159 fprintf(stderr, "Input Styles could not be retrieved\n");
1160 return EX_UNAVAILABLE;
1163 XIMStyle bestMatchStyle = 0;
1164 for (int i = 0; i < xis->count_styles; ++i) {
1165 XIMStyle ts = xis->supported_styles[i];
1166 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1167 bestMatchStyle = ts;
1173 if (!bestMatchStyle) {
1174 fprintf(stderr, "No matching input style could be determined\n");
1177 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1178 check_allocation(xic);
1180 // draw the window for the first time
1184 while (status == LOOPING) {
1188 if (XFilterEvent(&e, w))
1193 XRefreshKeyboardMapping(&e.xmapping);
1197 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1200 switch (parse_event(d, ev, xic, &input)) {
1208 // if first_selected is active and the first completion is
1209 // active be sure to 'expand' the text to match the selection
1210 if (first_selected && cs && cs->selected) {
1212 text = strdup(cs->completion);
1214 fprintf(stderr, "Memory allocation error");
1217 textlen = strlen(text);
1222 complete(cs, first_selected, true, &text, &textlen, &status);
1227 complete(cs, first_selected, false, &text, &textlen, &status);
1232 popc(text, textlen);
1233 cs = update_completions(cs, text, lines, first_selected);
1237 // `textlen` is the lenght of the allocated string, not the
1238 // lenght of the ACTUAL string
1239 int p = strlen(text) -1;
1240 if (p > 0) { // delete the current char
1245 // erase the alphanumeric char
1246 while (p >= 0 && isalnum(text[p])) {
1251 // erase also trailing white spaces
1252 while (p >= 0 && isspace(text[p])) {
1256 cs = update_completions(cs, text, lines, first_selected);
1261 for (int i = 0; i < textlen; ++i)
1263 cs = update_completions(cs, text, lines, first_selected);
1268 int str_len = strlen(input);
1269 for (int i = 0; i < str_len; ++i) {
1270 textlen = pushc(&text, textlen, input[i]);
1271 if (textlen == -1) {
1272 fprintf(stderr, "Memory allocation error\n");
1276 cs = update_completions(cs, text, lines, first_selected);
1282 case TOGGLE_FIRST_SELECTED:
1283 first_selected = !first_selected;
1285 cs->selected = !cs->selected;
1291 fprintf(stderr, "Unknown event %d\n", e.type);
1298 printf("%s\n", text);
1300 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);