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_rec(cs); \
47 cs = filter(text, lines); \
48 }
50 #define complete(cs, nothing_selected, p, text, textlen, status) { \
51 struct completions *n = p \
52 ? compl_select_prev(cs, nothing_selected) \
53 : compl_select_next(cs, nothing_selected); \
54 \
55 if (n != nil) { \
56 nothing_selected = false; \
57 free(text); \
58 text = strdup(n->completion); \
59 if (text == nil) { \
60 fprintf(stderr, "Memory allocation error!\n"); \
61 status = ERR; \
62 break; \
63 } \
64 textlen = strlen(text); \
65 } \
66 }
68 #define INITIAL_ITEMS 64
70 #define cannot_allocate_memory { \
71 fprintf(stderr, "Could not allocate memory\n"); \
72 abort(); \
73 }
75 #define check_allocation(a) { \
76 if (a == nil) \
77 cannot_allocate_memory; \
78 }
80 enum state {LOOPING, OK, ERR};
82 enum text_type {PROMPT, COMPL, COMPL_HIGH};
84 struct rendering {
85 Display *d;
86 Window w;
87 int width;
88 int height;
89 int padding;
90 bool horizontal_layout;
91 char *ps1;
92 int ps1len;
93 GC prompt;
94 GC prompt_bg;
95 GC completion;
96 GC completion_bg;
97 GC completion_highlighted;
98 GC completion_highlighted_bg;
99 #ifdef USE_XFT
100 XftFont *font;
101 XftDraw *xftdraw;
102 XftColor xft_prompt;
103 XftColor xft_completion;
104 XftColor xft_completion_highlighted;
105 #else
106 XFontSet *font;
107 #endif
108 };
110 struct completions {
111 char *completion;
112 bool selected;
113 struct completions *next;
114 };
116 struct completions *compl_new() {
117 struct completions *c = malloc(sizeof(struct completions));
119 if (c == nil)
120 return c;
122 c->completion = nil;
123 c->selected = false;
124 c->next = nil;
125 return c;
128 void compl_delete(struct completions *c) {
129 free(c);
132 void compl_delete_rec(struct completions *c) {
133 while (c != nil) {
134 struct completions *t = c->next;
135 free(c);
136 c = t;
140 struct completions *compl_select_next(struct completions *c, bool n) {
141 if (c == nil)
142 return nil;
143 if (n) {
144 c->selected = true;
145 return c;
148 struct completions *orig = c;
149 while (c != nil) {
150 if (c->selected) {
151 c->selected = false;
152 if (c->next != nil) {
153 // the current one is selected and the next one exists
154 c->next->selected = true;
155 return c->next;
156 } else {
157 // the current one is selected and the next one is nill,
158 // select the first one
159 orig->selected = true;
160 return orig;
163 c = c->next;
165 return nil;
168 struct completions *compl_select_prev(struct completions *c, bool n) {
169 if (c == nil)
170 return nil;
172 struct completions *cc = c;
174 if (n) // select the last one
175 while (cc != nil) {
176 if (cc->next == nil) {
177 cc->selected = true;
178 return cc;
180 cc = cc->next;
182 else // select the previous one
183 while (cc != nil) {
184 if (cc->next != nil && cc->next->selected) {
185 cc->next->selected = false;
186 cc->selected = true;
187 return cc;
189 cc = cc->next;
192 return nil;
195 struct completions *filter(char *text, char **lines) {
196 int i = 0;
197 struct completions *root = compl_new();
198 struct completions *c = root;
199 if (c == nil)
200 return nil;
202 for (;;) {
203 char *l = lines[i];
204 if (l == nil)
205 break;
207 if (strcasestr(l, text) != nil) {
208 c->next = compl_new();
209 c = c->next;
210 if (c == nil) {
211 compl_delete_rec(root);
212 return nil;
214 c->completion = l;
217 ++i;
220 struct completions *r = root->next;
221 compl_delete(root);
222 return r;
225 // push the character c at the end of the string pointed by p
226 int pushc(char **p, int maxlen, char c) {
227 int len = strnlen(*p, maxlen);
229 if (!(len < maxlen -2)) {
230 maxlen += maxlen >> 1;
231 char *newptr = realloc(*p, maxlen);
232 if (newptr == nil) { // bad!
233 return -1;
235 *p = newptr;
238 (*p)[len] = c;
239 (*p)[len+1] = '\0';
240 return maxlen;
243 int utf8strnlen(char *s, int maxlen) {
244 int len = 0;
245 while (*s && maxlen > 0) {
246 len += (*s++ & 0xc0) != 0x80;
247 maxlen--;
249 return len;
252 // remove the last *glyph* from the *utf8* string!
253 // this is different from just setting the last byte to 0 (in some
254 // cases ofc). The actual implementation is quite inefficient because
255 // it remove the last char until the number of glyphs doesn't change
256 void popc(char *p, int maxlen) {
257 int len = strnlen(p, maxlen);
259 if (len == 0)
260 return;
262 int ulen = utf8strnlen(p, maxlen);
263 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
264 len--;
265 p[len] = 0;
269 // If the string is surrounded by quotes (`"`) remove them and replace
270 // every `\"` in the string with `"`
271 char *normalize_str(const char *str) {
272 int len = strlen(str);
273 if (len == 0)
274 return nil;
276 char *s = calloc(len, sizeof(char));
277 check_allocation(s);
278 int p = 0;
279 while (*str) {
280 char c = *str;
281 if (*str == '\\') {
282 if (*(str + 1)) {
283 s[p] = *(str + 1);
284 p++;
285 str += 2; // skip this and the next char
286 continue;
287 } else {
288 break;
291 if (c == '"') {
292 str++; // skip only this char
293 continue;
295 s[p] = c;
296 p++;
297 str++;
299 return s;
302 // read an arbitrary long line from stdin and return a pointer to it
303 // TODO: resize the allocated memory to exactly fit the string once
304 // read?
305 char *readline(bool *eof) {
306 int maxlen = 8;
307 char *str = calloc(maxlen, sizeof(char));
308 if (str == nil) {
309 fprintf(stderr, "Cannot allocate memory!\n");
310 exit(EX_UNAVAILABLE);
313 int c;
314 while((c = getchar()) != EOF) {
315 if (c == '\n')
316 return str;
317 else
318 maxlen = pushc(&str, maxlen, c);
320 if (maxlen == -1) {
321 fprintf(stderr, "Cannot allocate memory!\n");
322 exit(EX_UNAVAILABLE);
325 *eof = true;
326 return str;
329 int readlines (char ***lns, int items) {
330 bool finished = false;
331 int n = 0;
332 char **lines = *lns;
333 while (true) {
334 lines[n] = readline(&finished);
336 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
337 free(lines[n]);
338 --n; // forget about this line
341 if (finished)
342 break;
344 ++n;
346 if (n == items - 1) {
347 items += items >>1;
348 char **l = realloc(lines, sizeof(char*) * items);
349 check_allocation(l);
350 *lns = l;
351 lines = l;
355 n++;
356 lines[n] = nil;
357 return items;
360 // Compute the dimension of the string str once rendered, return the
361 // width and save the width and the height in ret_width and ret_height
362 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
363 int height;
364 int width;
365 #ifdef USE_XFT
366 XGlyphInfo gi;
367 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
368 /* height = gi.height; */
369 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
370 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
371 height = r->font->ascent - r->font->descent;
372 width = gi.width - gi.x;
373 #else
374 XRectangle rect;
375 XmbTextExtents(*r->font, str, len, nil, &rect);
376 height = rect.height;
377 width = rect.width;
378 #endif
379 if (ret_width != nil) *ret_width = width;
380 if (ret_height != nil) *ret_height = height;
381 return width;
384 // Draw the string str
385 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
386 #ifdef USE_XFT
387 XftColor xftcolor;
388 if (tt == PROMPT) xftcolor = r->xft_prompt;
389 if (tt == COMPL) xftcolor = r->xft_completion;
390 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
392 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
393 #else
394 GC gc;
395 if (tt == PROMPT) gc = r->prompt;
396 if (tt == COMPL) gc = r->completion;
397 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
398 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
399 #endif
402 // Duplicate the string str and substitute every space with a 'n'
403 char *strdupn(char *str) {
404 int len = strlen(str);
406 if (str == nil || len == 0)
407 return nil;
409 char *dup = strdup(str);
410 if (dup == nil)
411 return nil;
413 for (int i = 0; i < len; ++i)
414 if (dup[i] == ' ')
415 dup[i] = 'n';
417 return dup;
420 // |------------------|----------------------------------------------|
421 // | 20 char text | completion | completion | completion | compl |
422 // |------------------|----------------------------------------------|
423 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
424 int prompt_width = 20; // char
426 int width, height;
427 char *ps1_dup = strdupn(r->ps1);
428 if (ps1_dup == nil)
429 return;
431 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
432 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
433 free(ps1_dup);
434 int start_at = ps1xlen;
436 start_at = text_extents("n", 1, r, nil, nil);
437 start_at = start_at * prompt_width + r->padding;
439 int texty = (height + r->height) >>1;
441 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
443 int text_len = strlen(text);
444 if (text_len > prompt_width)
445 text = text + (text_len - prompt_width);
446 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
447 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
449 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
451 while (cs != nil) {
452 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
453 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
455 int len = strlen(cs->completion);
456 int text_width = text_extents(cs->completion, len, r, nil, nil);
458 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
460 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
462 start_at += text_width + r->padding * 2;
464 if (start_at > r->width)
465 break; // don't draw completion if the space isn't enough
467 cs = cs->next;
470 XFlush(r->d);
473 // |-----------------------------------------------------------------|
474 // | prompt |
475 // |-----------------------------------------------------------------|
476 // | completion |
477 // |-----------------------------------------------------------------|
478 // | completion |
479 // |-----------------------------------------------------------------|
480 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
481 int height, width;
482 text_extents("fjpgl", 5, r, nil, &height);
483 int start_at = height + r->padding;
485 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
486 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
488 char *ps1_dup = strdupn(r->ps1);
489 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
490 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
491 free(ps1_dup);
493 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
494 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
495 start_at += r->padding;
497 while (cs != nil) {
498 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
499 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
501 int len = strlen(cs->completion);
502 text_extents(cs->completion, len, r, &width, &height);
503 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
504 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
506 start_at += height + r->padding *2;
508 if (start_at > r->height)
509 break; // don't draw completion if the space isn't enough
511 cs = cs->next;
514 XFlush(r->d);
517 void draw(struct rendering *r, char *text, struct completions *cs) {
518 if (r->horizontal_layout)
519 draw_horizontally(r, text, cs);
520 else
521 draw_vertically(r, text, cs);
524 /* Set some WM stuff */
525 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
526 Atom type;
527 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
528 XChangeProperty(
529 d,
530 w,
531 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
532 XInternAtom(d, "ATOM", false),
533 32,
534 PropModeReplace,
535 (unsigned char *)&type,
537 );
539 /* some window managers honor this properties */
540 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
541 XChangeProperty(d,
542 w,
543 XInternAtom(d, "_NET_WM_STATE", false),
544 XInternAtom(d, "ATOM", false),
545 32,
546 PropModeReplace,
547 (unsigned char *)&type,
549 );
551 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
552 XChangeProperty(d,
553 w,
554 XInternAtom(d, "_NET_WM_STATE", false),
555 XInternAtom(d, "ATOM", false),
556 32,
557 PropModeAppend,
558 (unsigned char *)&type,
560 );
562 // setting window hints
563 XClassHint *class_hint = XAllocClassHint();
564 if (class_hint == nil) {
565 fprintf(stderr, "Could not allocate memory for class hint\n");
566 exit(EX_UNAVAILABLE);
568 class_hint->res_name = resname;
569 class_hint->res_class = resclass;
570 XSetClassHint(d, w, class_hint);
571 XFree(class_hint);
573 XSizeHints *size_hint = XAllocSizeHints();
574 if (size_hint == nil) {
575 fprintf(stderr, "Could not allocate memory for size hint\n");
576 exit(EX_UNAVAILABLE);
578 size_hint->flags = PMinSize | PBaseSize;
579 size_hint->min_width = width;
580 size_hint->base_width = width;
581 size_hint->min_height = height;
582 size_hint->base_height = height;
584 XFlush(d);
587 void get_wh(Display *d, Window *w, int *width, int *height) {
588 XWindowAttributes win_attr;
589 XGetWindowAttributes(d, *w, &win_attr);
590 *height = win_attr.height;
591 *width = win_attr.width;
594 // I know this may seem a little hackish BUT is the only way I managed
595 // to actually grab that goddam keyboard. Only one call to
596 // XGrabKeyboard does not always end up with the keyboard grabbed!
597 int take_keyboard(Display *d, Window w) {
598 int i;
599 for (i = 0; i < 100; i++) {
600 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
601 return 1;
602 usleep(1000);
604 return 0;
607 void release_keyboard(Display *d) {
608 XUngrabKeyboard(d, CurrentTime);
611 int parse_integer(const char *str, int default_value) {
612 /* int len = strlen(str); */
613 /* if (len > 0 && str[len-1] == '%') { */
614 /* char *cpy = strdup(str); */
615 /* check_allocation(cpy); */
616 /* cpy[len-1] = '\0'; */
617 /* int val = parse_integer(cpy, default_value, max); */
618 /* free(cpy); */
619 /* return val * max / 100; */
620 /* } */
622 errno = 0;
623 char *ep;
624 long lval = strtol(str, &ep, 10);
625 if (str[0] == '\0' || *ep != '\0') { // NaN
626 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
627 return default_value;
629 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
630 (lval > INT_MAX || lval < INT_MIN)) {
631 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
632 return default_value;
634 return lval;
637 int parse_int_with_percentage(const char *str, int default_value, int max) {
638 int len = strlen(str);
639 if (len > 0 && str[len-1] == '%') {
640 char *cpy = strdup(str);
641 check_allocation(cpy);
642 cpy[len-1] = '\0';
643 int val = parse_integer(cpy, default_value);
644 free(cpy);
645 return val * max / 100;
647 return parse_integer(str, default_value);
650 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
651 if (!strcmp(str, "middle")) {
652 return (max - self)/2;
654 return parse_int_with_percentage(str, default_value, max);
657 int main() {
658 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
659 int nlines = readlines(&lines, INITIAL_ITEMS);
661 setlocale(LC_ALL, getenv("LANG"));
663 enum state status = LOOPING;
665 // where the monitor start (used only with xinerama)
666 int offset_x = 0;
667 int offset_y = 0;
669 // width and height of the window
670 int width = 400;
671 int height = 20;
673 // position on the screen
674 int x = 0;
675 int y = 0;
677 int padding = 10;
679 char *ps1 = strdup("$ ");
680 check_allocation(ps1);
682 char *fontname = strdup(default_fontname);
683 check_allocation(fontname);
685 int textlen = 10;
686 char *text = malloc(textlen * sizeof(char));
687 check_allocation(text);
689 struct completions *cs = filter(text, lines);
690 bool nothing_selected = true;
692 // start talking to xorg
693 Display *d = XOpenDisplay(nil);
694 if (d == nil) {
695 fprintf(stderr, "Could not open display!\n");
696 return EX_UNAVAILABLE;
699 // get display size
700 // XXX: is getting the default root window dimension correct?
701 XWindowAttributes xwa;
702 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
703 int d_width = xwa.width;
704 int d_height = xwa.height;
706 #ifdef USE_XINERAMA
707 if (XineramaIsActive(d)) {
708 // find the mice
709 int number_of_screens = XScreenCount(d);
710 Window r;
711 Window root;
712 int root_x, root_y, win_x, win_y;
713 unsigned int mask;
714 bool res;
715 for (int i = 0; i < number_of_screens; ++i) {
716 root = XRootWindow(d, i);
717 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
718 if (res) break;
720 if (!res) {
721 fprintf(stderr, "No mouse found.\n");
722 root_x = 0;
723 root_y = 0;
726 // now find in which monitor the mice is on
727 int monitors;
728 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
729 if (info) {
730 for (int i = 0; i < monitors; ++i) {
731 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
732 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
733 offset_x = info[i].x_org;
734 offset_y = info[i].y_org;
735 d_width = info[i].width;
736 d_height = info[i].height;
737 break;
741 XFree(info);
743 #endif
745 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
746 XColor p_fg, p_bg,
747 compl_fg, compl_bg,
748 compl_highlighted_fg, compl_highlighted_bg;
750 bool horizontal_layout = true;
752 // read resource
753 XrmInitialize();
754 char *xrm = XResourceManagerString(d);
755 XrmDatabase xdb = nil;
756 if (xrm != nil) {
757 xdb = XrmGetStringDatabase(xrm);
758 XrmValue value;
759 char *datatype[20];
761 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
762 fontname = strdup(value.addr);
763 check_allocation(fontname);
765 else
766 fprintf(stderr, "no font defined, using %s\n", fontname);
768 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
769 char *v = strdup(value.addr);
770 check_allocation(v);
771 horizontal_layout = !strcmp(v, "horizontal");
772 free(v);
774 else
775 fprintf(stderr, "no layout defined, using horizontal\n");
777 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
778 free(ps1);
779 ps1 = normalize_str(value.addr);
780 } else
781 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
783 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
784 width = parse_int_with_percentage(value.addr, width, d_width);
785 else
786 fprintf(stderr, "no width defined, using %d\n", width);
788 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
789 height = parse_int_with_percentage(value.addr, height, d_height);
790 else
791 fprintf(stderr, "no height defined, using %d\n", height);
793 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
794 x = parse_int_with_middle(value.addr, x, d_width, width);
795 else
796 fprintf(stderr, "no x defined, using %d\n", x);
798 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
799 y = parse_int_with_middle(value.addr, y, d_height, height);
800 else
801 fprintf(stderr, "no y defined, using %d\n", y);
803 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
804 padding = parse_integer(value.addr, padding);
805 else
806 fprintf(stderr, "no y defined, using %d\n", padding);
808 XColor tmp;
809 // TODO: tmp needs to be free'd after every allocation?
811 // prompt
812 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
813 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
814 else
815 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
817 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
818 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
819 else
820 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
822 // completion
823 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
824 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
825 else
826 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
828 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
829 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
830 else
831 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
833 // completion highlighted
834 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
835 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
836 else
837 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
839 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
840 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
841 else
842 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
843 } else {
844 XColor tmp;
845 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
846 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
847 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
848 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
849 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
850 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
853 // load the font
854 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
855 /* if (font == nil) { */
856 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
857 /* font = XLoadQueryFont(d, "fixed"); */
858 /* } */
859 // load the font
860 #ifdef USE_XFT
861 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
862 #else
863 char **missing_charset_list;
864 int missing_charset_count;
865 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
866 if (font == nil) {
867 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
868 return EX_UNAVAILABLE;
870 #endif
872 // create the window
873 XSetWindowAttributes attr;
874 attr.override_redirect = true;
876 Window w = XCreateWindow(d, // display
877 DefaultRootWindow(d), // parent
878 x + offset_x, y + offset_y, // x y
879 width, height, // w h
880 0, // border width
881 DefaultDepth(d, DefaultScreen(d)), // depth
882 InputOutput, // class
883 DefaultVisual(d, DefaultScreen(d)), // visual
884 CWOverrideRedirect, // value mask
885 &attr);
887 set_win_atoms_hints(d, w, width, height);
889 // we want some events
890 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
892 // make the window appear on the screen
893 XMapWindow(d, w);
895 // wait for the MapNotify event (i.e. the event "window rendered")
896 for (;;) {
897 XEvent e;
898 XNextEvent(d, &e);
899 if (e.type == MapNotify)
900 break;
903 // get the *real* width & height after the window was rendered
904 get_wh(d, &w, &width, &height);
906 // grab keyboard
907 take_keyboard(d, w);
909 // Create some graphics contexts
910 XGCValues values;
911 /* values.font = font->fid; */
913 struct rendering r = {
914 .d = d,
915 .w = w,
916 #ifdef USE_XFT
917 .font = font,
918 #else
919 .font = &font,
920 #endif
921 .prompt = XCreateGC(d, w, 0, &values),
922 .prompt_bg = XCreateGC(d, w, 0, &values),
923 .completion = XCreateGC(d, w, 0, &values),
924 .completion_bg = XCreateGC(d, w, 0, &values),
925 .completion_highlighted = XCreateGC(d, w, 0, &values),
926 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
927 .width = width,
928 .height = height,
929 .padding = padding,
930 .horizontal_layout = horizontal_layout,
931 .ps1 = ps1,
932 .ps1len = strlen(ps1)
933 };
935 #ifdef USE_XFT
936 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
938 // prompt
939 XRenderColor xrcolor;
940 xrcolor.red = p_fg.red;
941 xrcolor.green = p_fg.red;
942 xrcolor.blue = p_fg.red;
943 xrcolor.alpha = 65535;
944 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
946 // completion
947 xrcolor.red = compl_fg.red;
948 xrcolor.green = compl_fg.green;
949 xrcolor.blue = compl_fg.blue;
950 xrcolor.alpha = 65535;
951 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
953 // completion highlighted
954 xrcolor.red = compl_highlighted_fg.red;
955 xrcolor.green = compl_highlighted_fg.green;
956 xrcolor.blue = compl_highlighted_fg.blue;
957 xrcolor.alpha = 65535;
958 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
959 #endif
961 // load the colors in our GCs
962 XSetForeground(d, r.prompt, p_fg.pixel);
963 XSetForeground(d, r.prompt_bg, p_bg.pixel);
964 XSetForeground(d, r.completion, compl_fg.pixel);
965 XSetForeground(d, r.completion_bg, compl_bg.pixel);
966 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
967 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
969 // open the X input method
970 XIM xim = XOpenIM(d, xdb, resname, resclass);
971 check_allocation(xim);
973 XIMStyles *xis = nil;
974 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
975 fprintf(stderr, "Input Styles could not be retrieved\n");
976 return EX_UNAVAILABLE;
979 XIMStyle bestMatchStyle = 0;
980 for (int i = 0; i < xis->count_styles; ++i) {
981 XIMStyle ts = xis->supported_styles[i];
982 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
983 bestMatchStyle = ts;
984 break;
987 XFree(xis);
989 if (!bestMatchStyle) {
990 fprintf(stderr, "No matching input style could be determined\n");
993 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
994 check_allocation(xic);
996 // draw the window for the first time
997 draw(&r, text, cs);
999 // main loop
1000 while (status == LOOPING) {
1001 XEvent e;
1002 XNextEvent(d, &e);
1004 if (XFilterEvent(&e, w))
1005 continue;
1007 switch (e.type) {
1008 case KeymapNotify:
1009 XRefreshKeyboardMapping(&e.xmapping);
1010 break;
1012 case KeyPress: {
1013 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1015 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
1016 bool shift = (ev->state & ShiftMask);
1017 complete(cs, nothing_selected, shift, text, textlen, status);
1018 draw(&r, text, cs);
1019 break;
1022 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1023 nothing_selected = true;
1024 popc(text, textlen);
1025 update_completions(cs, text, lines);
1026 draw(&r, text, cs);
1027 break;
1030 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1031 status = OK;
1032 break;
1035 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1036 status = ERR;
1037 break;
1040 // try to read what the user pressed
1041 int symbol = 0;
1042 Status s = 0;
1043 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1045 if (s == XBufferOverflow) {
1046 // should not happen since there are no utf-8 characters
1047 // larger than 24bits, but is something to be aware of when
1048 // used to directly write to a string buffer
1049 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1050 break;
1052 char *str = (char*)&symbol;
1054 if (ev->state & ControlMask) {
1055 // check for some key bindings
1056 if (!strcmp(str, "")) { // C-u
1057 nothing_selected = true;
1058 for (int i = 0; i < textlen; ++i)
1059 text[i] = 0;
1060 update_completions(cs, text, lines);
1062 if (!strcmp(str, "")) { // C-h
1063 nothing_selected = true;
1064 popc(text, textlen);
1065 update_completions(cs, text, lines);
1067 if (!strcmp(str, "")) { // C-w
1068 nothing_selected = true;
1070 // `textlen` is the length of the allocated string, not the
1071 // length of the ACTUAL string
1072 int p = strlen(text) - 1;
1073 if (p >= 0) { // delete the current char
1074 text[p] = 0;
1075 p--;
1077 while (p >= 0 && isalnum(text[p])) {
1078 text[p] = 0;
1079 p--;
1081 // erase also trailing white space
1082 while (p >= 0 && isspace(text[p])) {
1083 text[p] = 0;
1084 p--;
1086 update_completions(cs, text, lines);
1088 if (!strcmp(str, "\r")) { // C-m
1089 status = OK;
1091 if (!strcmp(str, "")) {
1092 complete(cs, nothing_selected, true, text, textlen, status);
1094 if (!strcmp(str, "")) {
1095 complete(cs, nothing_selected, false, text, textlen, status);
1097 draw(&r, text, cs);
1098 break;
1101 int str_len = strlen(str);
1102 for (int i = 0; i < str_len; ++i) {
1103 textlen = pushc(&text, textlen, str[i]);
1104 if (textlen == -1) {
1105 fprintf(stderr, "Memory allocation error\n");
1106 status = ERR;
1107 break;
1109 nothing_selected = true;
1110 update_completions(cs, text, lines);
1114 draw(&r, text, cs);
1115 break;
1117 default:
1118 fprintf(stderr, "Unknown event %d\n", e.type);
1122 release_keyboard(d);
1124 if (status == OK)
1125 printf("%s\n", text);
1127 for (int i = 0; i < nlines; ++i) {
1128 free(lines[i]);
1131 #ifdef USE_XFT
1132 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1133 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1134 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1135 #endif
1137 free(ps1);
1138 free(fontname);
1139 free(text);
1140 free(lines);
1141 compl_delete(cs);
1143 XDestroyWindow(d, w);
1144 XCloseDisplay(d);
1146 return status == OK ? 0 : 1;