Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
12 #include <X11/Xlib.h>
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 # include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 # include <X11/Xft/Xft.h>
24 #endif
26 #define nil NULL
27 #define resname "MyMenu"
28 #define resclass "mymenu"
30 #ifdef USE_XFT
31 # define default_fontname "monospace"
32 #else
33 # define default_fontname "fixed"
34 #endif
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
43 #endif
45 #define update_completions(cs, text, lines) { \
46 compl_delete(cs); \
47 cs = filter(text, lines); \
48 }
50 #define INITIAL_ITEMS 64
52 #define cannot_allocate_memory { \
53 fprintf(stderr, "Could not allocate memory\n"); \
54 abort(); \
55 }
57 #define check_allocation(a) { \
58 if (a == nil) \
59 cannot_allocate_memory; \
60 }
62 enum state {LOOPING, OK, ERR};
64 enum text_type {PROMPT, COMPL, COMPL_HIGH};
66 struct rendering {
67 Display *d;
68 Window w;
69 GC prompt;
70 GC prompt_bg;
71 GC completion;
72 GC completion_bg;
73 GC completion_highlighted;
74 GC completion_highlighted_bg;
75 #ifdef USE_XFT
76 XftDraw *xftdraw;
77 XftColor xft_prompt;
78 XftColor xft_completion;
79 XftColor xft_completion_highlighted;
80 XftFont *font;
81 #else
82 XFontSet *font;
83 #endif
84 int width;
85 int height;
86 bool horizontal_layout;
87 char *ps1;
88 int ps1len;
89 };
91 struct completions {
92 char *completion;
93 bool selected;
94 struct completions *next;
95 };
97 struct completions *compl_new() {
98 struct completions *c = malloc(sizeof(struct completions));
100 if (c == nil)
101 return c;
103 c->completion = nil;
104 c->selected = false;
105 c->next = nil;
106 return c;
109 void compl_delete(struct completions *c) {
110 free(c);
113 struct completions *compl_select_next(struct completions *c, bool n) {
114 if (c == nil)
115 return nil;
116 if (n) {
117 c->selected = true;
118 return c;
121 struct completions *orig = c;
122 while (c != nil) {
123 if (c->selected) {
124 c->selected = false;
125 if (c->next != nil) {
126 // the current one is selected and the next one exists
127 c->next->selected = true;
128 return c->next;
129 } else {
130 // the current one is selected and the next one is nill,
131 // select the first one
132 orig->selected = true;
133 return orig;
136 c = c->next;
138 return nil;
141 struct completions *compl_select_prev(struct completions *c, bool n) {
142 if (c == nil)
143 return nil;
145 struct completions *cc = c;
147 if (n) // select the last one
148 while (cc != nil) {
149 if (cc->next == nil) {
150 cc->selected = true;
151 return cc;
153 cc = cc->next;
155 else // select the previous one
156 while (cc != nil) {
157 if (cc->next != nil && cc->next->selected) {
158 cc->next->selected = false;
159 cc->selected = true;
160 return cc;
162 cc = cc->next;
165 return nil;
168 struct completions *filter(char *text, char **lines) {
169 int i = 0;
170 struct completions *root = compl_new();
171 struct completions *c = root;
173 for (;;) {
174 char *l = lines[i];
175 if (l == nil)
176 break;
178 if (strcasestr(l, text) != nil) {
179 c->next = compl_new();
180 c = c->next;
181 c->completion = l;
184 ++i;
187 struct completions *r = root->next;
188 compl_delete(root);
189 return r;
192 // push the character c at the end of the string pointed by p
193 int pushc(char **p, int maxlen, char c) {
194 int len = strnlen(*p, maxlen);
196 if (!(len < maxlen -2)) {
197 maxlen += maxlen >> 1;
198 char *newptr = realloc(*p, maxlen);
199 if (newptr == nil) { // bad!
200 return -1;
202 *p = newptr;
205 (*p)[len] = c;
206 (*p)[len+1] = '\0';
207 return maxlen;
210 int utf8strnlen(char *s, int maxlen) {
211 int len = 0;
212 while (*s && maxlen > 0) {
213 len += (*s++ & 0xc0) != 0x80;
214 maxlen--;
216 return len;
219 // remove the last *glyph* from the *utf8* string!
220 // this is different from just setting the last byte to 0 (in some
221 // cases ofc). The actual implementation is quite inefficient because
222 // it remove the last char until the number of glyphs doesn't change
223 void popc(char *p, int maxlen) {
224 int len = strnlen(p, maxlen);
226 if (len == 0)
227 return;
229 int ulen = utf8strnlen(p, maxlen);
230 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
231 len--;
232 p[len] = 0;
236 // If the string is surrounded by quotes (`"`) remove them and replace
237 // every `\"` in the string with `"`
238 char *normalize_str(const char *str) {
239 int len = strlen(str);
240 if (len == 0)
241 return nil;
243 char *s = calloc(len, sizeof(char));
244 check_allocation(s);
245 int p = 0;
246 while (*str) {
247 char c = *str;
248 if (*str == '\\') {
249 if (*(str + 1)) {
250 s[p] = *(str + 1);
251 p++;
252 str += 2; // skip this and the next char
253 continue;
254 } else {
255 break;
258 if (c == '"') {
259 str++; // skip only this char
260 continue;
262 s[p] = c;
263 p++;
264 str++;
266 return s;
269 // read an arbitrary long line from stdin and return a pointer to it
270 // TODO: resize the allocated memory to exactly fit the string once
271 // read?
272 char *readline(bool *eof) {
273 int maxlen = 8;
274 char *str = calloc(maxlen, sizeof(char));
275 if (str == nil) {
276 fprintf(stderr, "Cannot allocate memory!\n");
277 exit(EX_UNAVAILABLE);
280 int c;
281 while((c = getchar()) != EOF) {
282 if (c == '\n')
283 return str;
284 else
285 maxlen = pushc(&str, maxlen, c);
287 if (maxlen == -1) {
288 fprintf(stderr, "Cannot allocate memory!\n");
289 exit(EX_UNAVAILABLE);
292 *eof = true;
293 return str;
296 int readlines (char ***lns, int items) {
297 bool finished = false;
298 int n = 0;
299 char **lines = *lns;
300 while (true) {
301 lines[n] = readline(&finished);
303 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
304 free(lines[n]);
305 --n; // forget about this line
308 if (finished)
309 break;
311 ++n;
313 if (n == items - 1) {
314 items += items >>1;
315 char **l = realloc(lines, sizeof(char*) * items);
316 check_allocation(l);
317 *lns = l;
318 lines = l;
322 n++;
323 lines[n] = nil;
324 return items;
327 // Compute the dimension of the string str once rendered, return the
328 // width and save the width and the height in ret_width and ret_height
329 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
330 int height;
331 int width;
332 #ifdef USE_XFT
333 XGlyphInfo gi;
334 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
335 // Honestly I don't know why this won't work, but I found that this
336 // formula seems to work with various ttf font
337 /* height = gi.height; */
338 height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2;
339 width = gi.width - gi.x;
340 #else
341 XRectangle rect;
342 XmbTextExtents(*r->font, str, len, nil, &rect);
343 height = rect.height;
344 width = rect.width;
345 #endif
346 if (ret_width != nil) *ret_width = width;
347 if (ret_height != nil) *ret_height = height;
348 return width;
351 // Draw the string str
352 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
353 #ifdef USE_XFT
354 XftColor xftcolor;
355 if (tt == PROMPT) xftcolor = r->xft_prompt;
356 if (tt == COMPL) xftcolor = r->xft_completion;
357 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
359 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
360 #else
361 GC gc;
362 if (tt == PROMPT) gc = r->prompt;
363 if (tt == COMPL) gc = r->completion;
364 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
365 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
366 #endif
369 // Duplicate the string str and substitute every space with a 'n'
370 char *strdupn(char *str) {
371 int len = strlen(str);
373 if (str == nil || len == 0)
374 return nil;
376 char *dup = strdup(str);
377 if (dup == nil)
378 return nil;
380 for (int i = 0; i < len; ++i)
381 if (dup[i] == ' ')
382 dup[i] = 'n';
384 return dup;
387 // |------------------|----------------------------------------------|
388 // | 20 char text | completion | completion | completion | compl |
389 // |------------------|----------------------------------------------|
390 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
391 // TODO: make these dynamic?
392 int prompt_width = 20; // char
393 int padding = 10;
395 int width, height;
396 char *ps1_dup = strdupn(r->ps1);
397 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
398 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
399 free(ps1_dup);
400 int start_at = ps1xlen;
402 start_at = text_extents("n", 1, r, nil, nil);
403 start_at = start_at * prompt_width + padding;
405 int texty = (height + r->height) >>1;
407 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
409 int text_len = strlen(text);
410 if (text_len > prompt_width)
411 text = text + (text_len - prompt_width);
412 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
413 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
415 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
417 while (cs != nil) {
418 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
419 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
421 int len = strlen(cs->completion);
422 int text_width = text_extents(cs->completion, len, r, nil, nil);
424 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
426 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
428 start_at += text_width + padding * 2;
430 if (start_at > r->width)
431 break; // don't draw completion if the space isn't enough
433 cs = cs->next;
436 XFlush(r->d);
439 // |-----------------------------------------------------------------|
440 // | prompt |
441 // |-----------------------------------------------------------------|
442 // | completion |
443 // |-----------------------------------------------------------------|
444 // | completion |
445 // |-----------------------------------------------------------------|
446 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
447 // should be padding and not padding*2, but the text doesn't seem to
448 // be vertically centered otherwise....
449 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
450 int padding = 10; // TODO make this dynamic
452 int height, width;
453 text_extents("fjpgl", 5, r, &width, &height);
454 int start_at = height + padding*2;
456 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
457 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
459 char *ps1_dup = strdupn(r->ps1);
460 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
461 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
462 free(ps1_dup);
464 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
465 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
467 while (cs != nil) {
468 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
469 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
471 int len = strlen(cs->completion);
472 text_extents(cs->completion, len, r, &width, &height);
473 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
474 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
476 start_at += height + padding *2;
478 if (start_at > r->height)
479 break; // don't draw completion if the space isn't enough
481 cs = cs->next;
484 XFlush(r->d);
487 void draw(struct rendering *r, char *text, struct completions *cs) {
488 if (r->horizontal_layout)
489 draw_horizontally(r, text, cs);
490 else
491 draw_vertically(r, text, cs);
494 /* Set some WM stuff */
495 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
496 Atom type;
497 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
498 XChangeProperty(
499 d,
500 w,
501 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
502 XInternAtom(d, "ATOM", false),
503 32,
504 PropModeReplace,
505 (unsigned char *)&type,
507 );
509 /* some window managers honor this properties */
510 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
511 XChangeProperty(d,
512 w,
513 XInternAtom(d, "_NET_WM_STATE", false),
514 XInternAtom(d, "ATOM", false),
515 32,
516 PropModeReplace,
517 (unsigned char *)&type,
519 );
521 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
522 XChangeProperty(d,
523 w,
524 XInternAtom(d, "_NET_WM_STATE", false),
525 XInternAtom(d, "ATOM", false),
526 32,
527 PropModeAppend,
528 (unsigned char *)&type,
530 );
532 // setting window hints
533 XClassHint *class_hint = XAllocClassHint();
534 if (class_hint == nil) {
535 fprintf(stderr, "Could not allocate memory for class hint\n");
536 exit(EX_UNAVAILABLE);
538 class_hint->res_name = resname;
539 class_hint->res_class = resclass;
540 XSetClassHint(d, w, class_hint);
541 XFree(class_hint);
543 XSizeHints *size_hint = XAllocSizeHints();
544 if (size_hint == nil) {
545 fprintf(stderr, "Could not allocate memory for size hint\n");
546 exit(EX_UNAVAILABLE);
548 size_hint->flags = PMinSize | PBaseSize;
549 size_hint->min_width = width;
550 size_hint->base_width = width;
551 size_hint->min_height = height;
552 size_hint->base_height = height;
554 XFlush(d);
557 void get_wh(Display *d, Window *w, int *width, int *height) {
558 XWindowAttributes win_attr;
559 XGetWindowAttributes(d, *w, &win_attr);
560 *height = win_attr.height;
561 *width = win_attr.width;
564 // I know this may seem a little hackish BUT is the only way I managed
565 // to actually grab that goddam keyboard. Only one call to
566 // XGrabKeyboard does not always end up with the keyboard grabbed!
567 int take_keyboard(Display *d, Window w) {
568 int i;
569 for (i = 0; i < 100; i++) {
570 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
571 return 1;
572 usleep(1000);
574 return 0;
577 void release_keyboard(Display *d) {
578 XUngrabKeyboard(d, CurrentTime);
581 int parse_integer(const char *str, int default_value) {
582 /* int len = strlen(str); */
583 /* if (len > 0 && str[len-1] == '%') { */
584 /* char *cpy = strdup(str); */
585 /* check_allocation(cpy); */
586 /* cpy[len-1] = '\0'; */
587 /* int val = parse_integer(cpy, default_value, max); */
588 /* free(cpy); */
589 /* return val * max / 100; */
590 /* } */
592 errno = 0;
593 char *ep;
594 long lval = strtol(str, &ep, 10);
595 if (str[0] == '\0' || *ep != '\0') { // NaN
596 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
597 return default_value;
599 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
600 (lval > INT_MAX || lval < INT_MIN)) {
601 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
602 return default_value;
604 return lval;
607 int parse_int_with_percentage(const char *str, int default_value, int max) {
608 int len = strlen(str);
609 if (len > 0 && str[len-1] == '%') {
610 char *cpy = strdup(str);
611 check_allocation(cpy);
612 cpy[len-1] = '\0';
613 int val = parse_integer(cpy, default_value);
614 free(cpy);
615 return val * max / 100;
617 fprintf(stderr, "%s isn't a valid number/percentage\n", str);
618 return default_value;
621 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
622 if (!strcmp(str, "middle")) {
623 return (max - self)/2;
625 return parse_int_with_percentage(str, default_value, max);
628 int main() {
629 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
630 int nlines = readlines(&lines, INITIAL_ITEMS);
632 setlocale(LC_ALL, getenv("LANG"));
634 enum state status = LOOPING;
636 // where the monitor start (used only with xinerama)
637 int offset_x = 0;
638 int offset_y = 0;
640 // width and height of the window
641 int width = 400;
642 int height = 20;
644 // position on the screen
645 int x = 0;
646 int y = 0;
648 char *ps1 = strdup("$ ");
649 check_allocation(ps1);
651 char *fontname = strdup(default_fontname);
652 check_allocation(fontname);
654 int textlen = 10;
655 char *text = malloc(textlen * sizeof(char));
656 check_allocation(text);
658 struct completions *cs = filter(text, lines);
659 bool nothing_selected = true;
661 // start talking to xorg
662 Display *d = XOpenDisplay(nil);
663 if (d == nil) {
664 fprintf(stderr, "Could not open display!\n");
665 return EX_UNAVAILABLE;
668 // get display size
669 // XXX: is getting the default root window dimension correct?
670 XWindowAttributes xwa;
671 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
672 int d_width = xwa.width;
673 int d_height = xwa.height;
675 #ifdef USE_XINERAMA
676 if (XineramaIsActive(d)) {
677 // find the mice
678 int number_of_screens = XScreenCount(d);
679 bool result;
680 Window r;
681 Window root;
682 int root_x, root_y, win_x, win_y;
683 unsigned int mask;
684 bool res;
685 for (int i = 0; i < number_of_screens; ++i) {
686 root = XRootWindow(d, i);
687 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
688 if (res) break;
690 if (!res) {
691 fprintf(stderr, "No mouse found.\n");
692 root_x = 0;
693 root_y = 0;
696 // now find in which monitor the mice is on
697 int monitors;
698 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
699 if (info) {
700 for (int i = 0; i < monitors; ++i) {
701 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
702 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
703 offset_x = info[i].x_org;
704 offset_y = info[i].y_org;
705 d_width = info[i].width;
706 d_height = info[i].height;
707 break;
711 XFree(info);
713 #endif
715 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
716 XColor p_fg, p_bg,
717 compl_fg, compl_bg,
718 compl_highlighted_fg, compl_highlighted_bg;
720 bool horizontal_layout = true;
722 // read resource
723 XrmInitialize();
724 char *xrm = XResourceManagerString(d);
725 XrmDatabase xdb = nil;
726 if (xrm != nil) {
727 xdb = XrmGetStringDatabase(xrm);
728 XrmValue value;
729 char *datatype[20];
731 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
732 fontname = strdup(value.addr);
733 check_allocation(fontname);
735 else
736 fprintf(stderr, "no font defined, using %s\n", fontname);
738 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
739 char *v = strdup(value.addr);
740 check_allocation(v);
741 horizontal_layout = !strcmp(v, "horizontal");
742 free(v);
744 else
745 fprintf(stderr, "no layout defined, using horizontal\n");
747 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
748 free(ps1);
749 ps1 = normalize_str(value.addr);
750 } else
751 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
753 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
754 width = parse_int_with_percentage(value.addr, width, d_width);
755 else
756 fprintf(stderr, "no width defined, using %d\n", width);
758 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
759 height = parse_int_with_percentage(value.addr, height, d_height);
760 else
761 fprintf(stderr, "no height defined, using %d\n", height);
763 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
764 x = parse_int_with_middle(value.addr, x, d_width, width);
765 else
766 fprintf(stderr, "no x defined, using %d\n", width);
768 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
769 y = parse_int_with_middle(value.addr, y, d_height, height);
770 else
771 fprintf(stderr, "no y defined, using %d\n", height);
773 XColor tmp;
774 // TODO: tmp needs to be free'd after every allocation?
776 // prompt
777 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
778 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
779 else
780 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
782 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
783 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
784 else
785 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
787 // completion
788 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
789 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
790 else
791 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
793 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
794 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
795 else
796 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
798 // completion highlighted
799 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
800 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
801 else
802 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
804 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
805 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
806 else
807 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
808 } else {
809 XColor tmp;
810 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
811 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
812 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
813 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
814 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
815 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
818 // load the font
819 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
820 /* if (font == nil) { */
821 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
822 /* font = XLoadQueryFont(d, "fixed"); */
823 /* } */
824 // load the font
825 #ifdef USE_XFT
826 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
827 #else
828 char **missing_charset_list;
829 int missing_charset_count;
830 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
831 if (font == nil) {
832 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
833 return EX_UNAVAILABLE;
835 #endif
837 // create the window
838 XSetWindowAttributes attr;
839 attr.override_redirect = true;
841 Window w = XCreateWindow(d, // display
842 DefaultRootWindow(d), // parent
843 x + offset_x, y + offset_y, // x y
844 width, height, // w h
845 0, // border width
846 DefaultDepth(d, DefaultScreen(d)), // depth
847 InputOutput, // class
848 DefaultVisual(d, DefaultScreen(d)), // visual
849 CWOverrideRedirect, // value mask
850 &attr);
852 set_win_atoms_hints(d, w, width, height);
854 // we want some events
855 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
857 // make the window appear on the screen
858 XMapWindow(d, w);
860 // wait for the MapNotify event (i.e. the event "window rendered")
861 for (;;) {
862 XEvent e;
863 XNextEvent(d, &e);
864 if (e.type == MapNotify)
865 break;
868 // get the *real* width & height after the window was rendered
869 get_wh(d, &w, &width, &height);
871 // grab keyboard
872 take_keyboard(d, w);
874 // Create some graphics contexts
875 XGCValues values;
876 /* values.font = font->fid; */
878 struct rendering r = {
879 .d = d,
880 .w = w,
881 #ifdef USE_XFT
882 .font = font,
883 #else
884 .font = &font,
885 #endif
886 .prompt = XCreateGC(d, w, 0, &values),
887 .prompt_bg = XCreateGC(d, w, 0, &values),
888 .completion = XCreateGC(d, w, 0, &values),
889 .completion_bg = XCreateGC(d, w, 0, &values),
890 .completion_highlighted = XCreateGC(d, w, 0, &values),
891 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
892 .width = width,
893 .height = height,
894 .horizontal_layout = horizontal_layout,
895 .ps1 = ps1,
896 .ps1len = strlen(ps1)
897 };
899 #ifdef USE_XFT
900 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
902 // prompt
903 XRenderColor xrcolor;
904 xrcolor.red = p_fg.red;
905 xrcolor.green = p_fg.red;
906 xrcolor.blue = p_fg.red;
907 xrcolor.alpha = 65535;
908 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
910 // completion
911 xrcolor.red = compl_fg.red;
912 xrcolor.green = compl_fg.green;
913 xrcolor.blue = compl_fg.blue;
914 xrcolor.alpha = 65535;
915 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
917 // completion highlighted
918 xrcolor.red = compl_highlighted_fg.red;
919 xrcolor.green = compl_highlighted_fg.green;
920 xrcolor.blue = compl_highlighted_fg.blue;
921 xrcolor.alpha = 65535;
922 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
923 #endif
925 // load the colors in our GCs
926 XSetForeground(d, r.prompt, p_fg.pixel);
927 XSetForeground(d, r.prompt_bg, p_bg.pixel);
928 XSetForeground(d, r.completion, compl_fg.pixel);
929 XSetForeground(d, r.completion_bg, compl_bg.pixel);
930 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
931 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
933 // open the X input method
934 XIM xim = XOpenIM(d, xdb, resname, resclass);
935 check_allocation(xim);
937 XIMStyles *xis = nil;
938 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
939 fprintf(stderr, "Input Styles could not be retrieved\n");
940 return EX_UNAVAILABLE;
943 XIMStyle bestMatchStyle = 0;
944 for (int i = 0; i < xis->count_styles; ++i) {
945 XIMStyle ts = xis->supported_styles[i];
946 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
947 bestMatchStyle = ts;
948 break;
951 XFree(xis);
953 if (!bestMatchStyle) {
954 fprintf(stderr, "No matching input style could be determined\n");
957 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
958 check_allocation(xic);
960 // draw the window for the first time
961 draw(&r, text, cs);
963 // main loop
964 while (status == LOOPING) {
965 XEvent e;
966 XNextEvent(d, &e);
968 if (XFilterEvent(&e, w))
969 continue;
971 switch (e.type) {
972 case KeymapNotify:
973 XRefreshKeyboardMapping(&e.xmapping);
974 break;
976 case KeyPress: {
977 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
979 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
980 bool shift = (ev->state & ShiftMask);
981 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
982 : compl_select_next(cs, nothing_selected);
983 if (n != nil) {
984 nothing_selected = false;
985 free(text);
986 text = strdup(n->completion);
987 if (text == nil) {
988 fprintf(stderr, "Memory allocation error!\n");
989 status = ERR;
990 break;
992 textlen = strlen(text);
994 draw(&r, text, cs);
995 break;
998 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
999 nothing_selected = true;
1000 popc(text, textlen);
1001 update_completions(cs, text, lines);
1002 draw(&r, text, cs);
1003 break;
1006 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1007 status = OK;
1008 break;
1011 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1012 status = ERR;
1013 break;
1016 // try to read what the user pressed
1017 int symbol = 0;
1018 Status s = 0;
1019 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1021 if (s == XBufferOverflow) {
1022 // should not happen since there are no utf-8 characters
1023 // larger than 24bits, but is something to be aware of when
1024 // used to directly write to a string buffer
1025 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1026 break;
1028 char *str = (char*)&symbol;
1030 if (ev->state & ControlMask) {
1031 // check for some key bindings
1032 if (!strcmp(str, "")) { // C-u
1033 nothing_selected = true;
1034 for (int i = 0; i < textlen; ++i)
1035 text[i] = 0;
1036 update_completions(cs, text, lines);
1038 if (!strcmp(str, "")) { // C-h
1039 nothing_selected = true;
1040 popc(text, textlen);
1041 update_completions(cs, text, lines);
1043 if (!strcmp(str, "")) { // C-w
1044 nothing_selected = true;
1046 // `textlen` is the length of the allocated string, not the
1047 // length of the ACTUAL string
1048 int p = strlen(text) - 1;
1049 if (p >= 0) { // delete the current char
1050 text[p] = 0;
1051 p--;
1053 while (p >= 0 && isalnum(text[p])) {
1054 text[p] = 0;
1055 p--;
1057 // erase also trailing white space
1058 while (p >= 0 && isspace(text[p])) {
1059 text[p] = 0;
1060 p--;
1062 update_completions(cs, text, lines);
1064 if (!strcmp(str, "\r")) { // C-m
1065 status = OK;
1067 draw(&r, text, cs);
1068 break;
1071 int str_len = strlen(str);
1072 for (int i = 0; i < str_len; ++i) {
1073 textlen = pushc(&text, textlen, str[i]);
1074 if (textlen == -1) {
1075 fprintf(stderr, "Memory allocation error\n");
1076 status = ERR;
1077 break;
1079 nothing_selected = true;
1080 update_completions(cs, text, lines);
1084 draw(&r, text, cs);
1085 break;
1087 default:
1088 fprintf(stderr, "Unknown event %d\n", e.type);
1092 release_keyboard(d);
1094 if (status == OK)
1095 printf("%s\n", text);
1097 for (int i = 0; i < nlines; ++i) {
1098 free(lines[i]);
1101 #ifdef USE_XFT
1102 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1103 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1104 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1105 #endif
1107 free(ps1);
1108 free(fontname);
1109 free(text);
1110 free(lines);
1111 compl_delete(cs);
1113 XDestroyWindow(d, w);
1114 XCloseDisplay(d);
1116 return status == OK ? 0 : 1;