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 GC prompt;
88 GC prompt_bg;
89 GC completion;
90 GC completion_bg;
91 GC completion_highlighted;
92 GC completion_highlighted_bg;
93 #ifdef USE_XFT
94 XftDraw *xftdraw;
95 XftColor xft_prompt;
96 XftColor xft_completion;
97 XftColor xft_completion_highlighted;
98 XftFont *font;
99 #else
100 XFontSet *font;
101 #endif
102 int width;
103 int height;
104 bool horizontal_layout;
105 char *ps1;
106 int ps1len;
107 };
109 struct completions {
110 char *completion;
111 bool selected;
112 struct completions *next;
113 };
115 struct completions *compl_new() {
116 struct completions *c = malloc(sizeof(struct completions));
118 if (c == nil)
119 return c;
121 c->completion = nil;
122 c->selected = false;
123 c->next = nil;
124 return c;
127 void compl_delete(struct completions *c) {
128 free(c);
131 void compl_delete_rec(struct completions *c) {
132 while (c != nil) {
133 struct completions *t = c->next;
134 free(c);
135 c = t;
139 struct completions *compl_select_next(struct completions *c, bool n) {
140 if (c == nil)
141 return nil;
142 if (n) {
143 c->selected = true;
144 return c;
147 struct completions *orig = c;
148 while (c != nil) {
149 if (c->selected) {
150 c->selected = false;
151 if (c->next != nil) {
152 // the current one is selected and the next one exists
153 c->next->selected = true;
154 return c->next;
155 } else {
156 // the current one is selected and the next one is nill,
157 // select the first one
158 orig->selected = true;
159 return orig;
162 c = c->next;
164 return nil;
167 struct completions *compl_select_prev(struct completions *c, bool n) {
168 if (c == nil)
169 return nil;
171 struct completions *cc = c;
173 if (n) // select the last one
174 while (cc != nil) {
175 if (cc->next == nil) {
176 cc->selected = true;
177 return cc;
179 cc = cc->next;
181 else // select the previous one
182 while (cc != nil) {
183 if (cc->next != nil && cc->next->selected) {
184 cc->next->selected = false;
185 cc->selected = true;
186 return cc;
188 cc = cc->next;
191 return nil;
194 struct completions *filter(char *text, char **lines) {
195 int i = 0;
196 struct completions *root = compl_new();
197 struct completions *c = root;
198 if (c == nil)
199 return nil;
201 for (;;) {
202 char *l = lines[i];
203 if (l == nil)
204 break;
206 if (strcasestr(l, text) != nil) {
207 c->next = compl_new();
208 c = c->next;
209 if (c == nil) {
210 compl_delete_rec(root);
211 return nil;
213 c->completion = l;
216 ++i;
219 struct completions *r = root->next;
220 compl_delete(root);
221 return r;
224 // push the character c at the end of the string pointed by p
225 int pushc(char **p, int maxlen, char c) {
226 int len = strnlen(*p, maxlen);
228 if (!(len < maxlen -2)) {
229 maxlen += maxlen >> 1;
230 char *newptr = realloc(*p, maxlen);
231 if (newptr == nil) { // bad!
232 return -1;
234 *p = newptr;
237 (*p)[len] = c;
238 (*p)[len+1] = '\0';
239 return maxlen;
242 int utf8strnlen(char *s, int maxlen) {
243 int len = 0;
244 while (*s && maxlen > 0) {
245 len += (*s++ & 0xc0) != 0x80;
246 maxlen--;
248 return len;
251 // remove the last *glyph* from the *utf8* string!
252 // this is different from just setting the last byte to 0 (in some
253 // cases ofc). The actual implementation is quite inefficient because
254 // it remove the last char until the number of glyphs doesn't change
255 void popc(char *p, int maxlen) {
256 int len = strnlen(p, maxlen);
258 if (len == 0)
259 return;
261 int ulen = utf8strnlen(p, maxlen);
262 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
263 len--;
264 p[len] = 0;
268 // If the string is surrounded by quotes (`"`) remove them and replace
269 // every `\"` in the string with `"`
270 char *normalize_str(const char *str) {
271 int len = strlen(str);
272 if (len == 0)
273 return nil;
275 char *s = calloc(len, sizeof(char));
276 check_allocation(s);
277 int p = 0;
278 while (*str) {
279 char c = *str;
280 if (*str == '\\') {
281 if (*(str + 1)) {
282 s[p] = *(str + 1);
283 p++;
284 str += 2; // skip this and the next char
285 continue;
286 } else {
287 break;
290 if (c == '"') {
291 str++; // skip only this char
292 continue;
294 s[p] = c;
295 p++;
296 str++;
298 return s;
301 // read an arbitrary long line from stdin and return a pointer to it
302 // TODO: resize the allocated memory to exactly fit the string once
303 // read?
304 char *readline(bool *eof) {
305 int maxlen = 8;
306 char *str = calloc(maxlen, sizeof(char));
307 if (str == nil) {
308 fprintf(stderr, "Cannot allocate memory!\n");
309 exit(EX_UNAVAILABLE);
312 int c;
313 while((c = getchar()) != EOF) {
314 if (c == '\n')
315 return str;
316 else
317 maxlen = pushc(&str, maxlen, c);
319 if (maxlen == -1) {
320 fprintf(stderr, "Cannot allocate memory!\n");
321 exit(EX_UNAVAILABLE);
324 *eof = true;
325 return str;
328 int readlines (char ***lns, int items) {
329 bool finished = false;
330 int n = 0;
331 char **lines = *lns;
332 while (true) {
333 lines[n] = readline(&finished);
335 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
336 free(lines[n]);
337 --n; // forget about this line
340 if (finished)
341 break;
343 ++n;
345 if (n == items - 1) {
346 items += items >>1;
347 char **l = realloc(lines, sizeof(char*) * items);
348 check_allocation(l);
349 *lns = l;
350 lines = l;
354 n++;
355 lines[n] = nil;
356 return items;
359 // Compute the dimension of the string str once rendered, return the
360 // width and save the width and the height in ret_width and ret_height
361 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
362 int height;
363 int width;
364 #ifdef USE_XFT
365 XGlyphInfo gi;
366 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
367 // Honestly I don't know why this won't work, but I found that this
368 // formula seems to work with various ttf font
369 /* height = gi.height; */
370 height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2;
371 width = gi.width - gi.x;
372 #else
373 XRectangle rect;
374 XmbTextExtents(*r->font, str, len, nil, &rect);
375 height = rect.height;
376 width = rect.width;
377 #endif
378 if (ret_width != nil) *ret_width = width;
379 if (ret_height != nil) *ret_height = height;
380 return width;
383 // Draw the string str
384 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
385 #ifdef USE_XFT
386 XftColor xftcolor;
387 if (tt == PROMPT) xftcolor = r->xft_prompt;
388 if (tt == COMPL) xftcolor = r->xft_completion;
389 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
391 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
392 #else
393 GC gc;
394 if (tt == PROMPT) gc = r->prompt;
395 if (tt == COMPL) gc = r->completion;
396 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
397 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
398 #endif
401 // Duplicate the string str and substitute every space with a 'n'
402 char *strdupn(char *str) {
403 int len = strlen(str);
405 if (str == nil || len == 0)
406 return nil;
408 char *dup = strdup(str);
409 if (dup == nil)
410 return nil;
412 for (int i = 0; i < len; ++i)
413 if (dup[i] == ' ')
414 dup[i] = 'n';
416 return dup;
419 // |------------------|----------------------------------------------|
420 // | 20 char text | completion | completion | completion | compl |
421 // |------------------|----------------------------------------------|
422 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
423 // TODO: make these dynamic?
424 int prompt_width = 20; // char
425 int padding = 10;
427 int width, height;
428 char *ps1_dup = strdupn(r->ps1);
429 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
430 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
431 free(ps1_dup);
432 int start_at = ps1xlen;
434 start_at = text_extents("n", 1, r, nil, nil);
435 start_at = start_at * prompt_width + padding;
437 int texty = (height + r->height) >>1;
439 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
441 int text_len = strlen(text);
442 if (text_len > prompt_width)
443 text = text + (text_len - prompt_width);
444 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
445 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
447 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
449 while (cs != nil) {
450 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
451 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
453 int len = strlen(cs->completion);
454 int text_width = text_extents(cs->completion, len, r, nil, nil);
456 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
458 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
460 start_at += text_width + padding * 2;
462 if (start_at > r->width)
463 break; // don't draw completion if the space isn't enough
465 cs = cs->next;
468 XFlush(r->d);
471 // |-----------------------------------------------------------------|
472 // | prompt |
473 // |-----------------------------------------------------------------|
474 // | completion |
475 // |-----------------------------------------------------------------|
476 // | completion |
477 // |-----------------------------------------------------------------|
478 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
479 // should be padding and not padding*2, but the text doesn't seem to
480 // be vertically centered otherwise....
481 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
482 int padding = 10; // TODO make this dynamic
484 int height, width;
485 text_extents("fjpgl", 5, r, &width, &height);
486 int start_at = height + padding*2;
488 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
489 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
491 char *ps1_dup = strdupn(r->ps1);
492 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
493 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
494 free(ps1_dup);
496 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
497 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
499 while (cs != nil) {
500 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
501 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
503 int len = strlen(cs->completion);
504 text_extents(cs->completion, len, r, &width, &height);
505 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
506 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
508 start_at += height + padding *2;
510 if (start_at > r->height)
511 break; // don't draw completion if the space isn't enough
513 cs = cs->next;
516 XFlush(r->d);
519 void draw(struct rendering *r, char *text, struct completions *cs) {
520 if (r->horizontal_layout)
521 draw_horizontally(r, text, cs);
522 else
523 draw_vertically(r, text, cs);
526 /* Set some WM stuff */
527 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
528 Atom type;
529 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
530 XChangeProperty(
531 d,
532 w,
533 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
534 XInternAtom(d, "ATOM", false),
535 32,
536 PropModeReplace,
537 (unsigned char *)&type,
539 );
541 /* some window managers honor this properties */
542 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
543 XChangeProperty(d,
544 w,
545 XInternAtom(d, "_NET_WM_STATE", false),
546 XInternAtom(d, "ATOM", false),
547 32,
548 PropModeReplace,
549 (unsigned char *)&type,
551 );
553 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
554 XChangeProperty(d,
555 w,
556 XInternAtom(d, "_NET_WM_STATE", false),
557 XInternAtom(d, "ATOM", false),
558 32,
559 PropModeAppend,
560 (unsigned char *)&type,
562 );
564 // setting window hints
565 XClassHint *class_hint = XAllocClassHint();
566 if (class_hint == nil) {
567 fprintf(stderr, "Could not allocate memory for class hint\n");
568 exit(EX_UNAVAILABLE);
570 class_hint->res_name = resname;
571 class_hint->res_class = resclass;
572 XSetClassHint(d, w, class_hint);
573 XFree(class_hint);
575 XSizeHints *size_hint = XAllocSizeHints();
576 if (size_hint == nil) {
577 fprintf(stderr, "Could not allocate memory for size hint\n");
578 exit(EX_UNAVAILABLE);
580 size_hint->flags = PMinSize | PBaseSize;
581 size_hint->min_width = width;
582 size_hint->base_width = width;
583 size_hint->min_height = height;
584 size_hint->base_height = height;
586 XFlush(d);
589 void get_wh(Display *d, Window *w, int *width, int *height) {
590 XWindowAttributes win_attr;
591 XGetWindowAttributes(d, *w, &win_attr);
592 *height = win_attr.height;
593 *width = win_attr.width;
596 // I know this may seem a little hackish BUT is the only way I managed
597 // to actually grab that goddam keyboard. Only one call to
598 // XGrabKeyboard does not always end up with the keyboard grabbed!
599 int take_keyboard(Display *d, Window w) {
600 int i;
601 for (i = 0; i < 100; i++) {
602 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
603 return 1;
604 usleep(1000);
606 return 0;
609 void release_keyboard(Display *d) {
610 XUngrabKeyboard(d, CurrentTime);
613 int parse_integer(const char *str, int default_value) {
614 /* int len = strlen(str); */
615 /* if (len > 0 && str[len-1] == '%') { */
616 /* char *cpy = strdup(str); */
617 /* check_allocation(cpy); */
618 /* cpy[len-1] = '\0'; */
619 /* int val = parse_integer(cpy, default_value, max); */
620 /* free(cpy); */
621 /* return val * max / 100; */
622 /* } */
624 errno = 0;
625 char *ep;
626 long lval = strtol(str, &ep, 10);
627 if (str[0] == '\0' || *ep != '\0') { // NaN
628 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
629 return default_value;
631 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
632 (lval > INT_MAX || lval < INT_MIN)) {
633 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
634 return default_value;
636 return lval;
639 int parse_int_with_percentage(const char *str, int default_value, int max) {
640 int len = strlen(str);
641 if (len > 0 && str[len-1] == '%') {
642 char *cpy = strdup(str);
643 check_allocation(cpy);
644 cpy[len-1] = '\0';
645 int val = parse_integer(cpy, default_value);
646 free(cpy);
647 return val * max / 100;
649 return parse_integer(str, default_value);
652 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
653 if (!strcmp(str, "middle")) {
654 return (max - self)/2;
656 return parse_int_with_percentage(str, default_value, max);
659 int main() {
660 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
661 int nlines = readlines(&lines, INITIAL_ITEMS);
663 setlocale(LC_ALL, getenv("LANG"));
665 enum state status = LOOPING;
667 // where the monitor start (used only with xinerama)
668 int offset_x = 0;
669 int offset_y = 0;
671 // width and height of the window
672 int width = 400;
673 int height = 20;
675 // position on the screen
676 int x = 0;
677 int y = 0;
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", width);
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", height);
803 XColor tmp;
804 // TODO: tmp needs to be free'd after every allocation?
806 // prompt
807 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
808 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
809 else
810 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
812 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
813 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
814 else
815 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
817 // completion
818 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
819 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
820 else
821 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
823 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
824 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
825 else
826 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
828 // completion highlighted
829 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
830 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
831 else
832 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
834 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
835 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
836 else
837 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
838 } else {
839 XColor tmp;
840 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
841 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
842 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
843 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
844 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
845 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
848 // load the font
849 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
850 /* if (font == nil) { */
851 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
852 /* font = XLoadQueryFont(d, "fixed"); */
853 /* } */
854 // load the font
855 #ifdef USE_XFT
856 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
857 #else
858 char **missing_charset_list;
859 int missing_charset_count;
860 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
861 if (font == nil) {
862 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
863 return EX_UNAVAILABLE;
865 #endif
867 // create the window
868 XSetWindowAttributes attr;
869 attr.override_redirect = true;
871 Window w = XCreateWindow(d, // display
872 DefaultRootWindow(d), // parent
873 x + offset_x, y + offset_y, // x y
874 width, height, // w h
875 0, // border width
876 DefaultDepth(d, DefaultScreen(d)), // depth
877 InputOutput, // class
878 DefaultVisual(d, DefaultScreen(d)), // visual
879 CWOverrideRedirect, // value mask
880 &attr);
882 set_win_atoms_hints(d, w, width, height);
884 // we want some events
885 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
887 // make the window appear on the screen
888 XMapWindow(d, w);
890 // wait for the MapNotify event (i.e. the event "window rendered")
891 for (;;) {
892 XEvent e;
893 XNextEvent(d, &e);
894 if (e.type == MapNotify)
895 break;
898 // get the *real* width & height after the window was rendered
899 get_wh(d, &w, &width, &height);
901 // grab keyboard
902 take_keyboard(d, w);
904 // Create some graphics contexts
905 XGCValues values;
906 /* values.font = font->fid; */
908 struct rendering r = {
909 .d = d,
910 .w = w,
911 #ifdef USE_XFT
912 .font = font,
913 #else
914 .font = &font,
915 #endif
916 .prompt = XCreateGC(d, w, 0, &values),
917 .prompt_bg = XCreateGC(d, w, 0, &values),
918 .completion = XCreateGC(d, w, 0, &values),
919 .completion_bg = XCreateGC(d, w, 0, &values),
920 .completion_highlighted = XCreateGC(d, w, 0, &values),
921 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
922 .width = width,
923 .height = height,
924 .horizontal_layout = horizontal_layout,
925 .ps1 = ps1,
926 .ps1len = strlen(ps1)
927 };
929 #ifdef USE_XFT
930 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
932 // prompt
933 XRenderColor xrcolor;
934 xrcolor.red = p_fg.red;
935 xrcolor.green = p_fg.red;
936 xrcolor.blue = p_fg.red;
937 xrcolor.alpha = 65535;
938 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
940 // completion
941 xrcolor.red = compl_fg.red;
942 xrcolor.green = compl_fg.green;
943 xrcolor.blue = compl_fg.blue;
944 xrcolor.alpha = 65535;
945 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
947 // completion highlighted
948 xrcolor.red = compl_highlighted_fg.red;
949 xrcolor.green = compl_highlighted_fg.green;
950 xrcolor.blue = compl_highlighted_fg.blue;
951 xrcolor.alpha = 65535;
952 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
953 #endif
955 // load the colors in our GCs
956 XSetForeground(d, r.prompt, p_fg.pixel);
957 XSetForeground(d, r.prompt_bg, p_bg.pixel);
958 XSetForeground(d, r.completion, compl_fg.pixel);
959 XSetForeground(d, r.completion_bg, compl_bg.pixel);
960 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
961 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
963 // open the X input method
964 XIM xim = XOpenIM(d, xdb, resname, resclass);
965 check_allocation(xim);
967 XIMStyles *xis = nil;
968 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
969 fprintf(stderr, "Input Styles could not be retrieved\n");
970 return EX_UNAVAILABLE;
973 XIMStyle bestMatchStyle = 0;
974 for (int i = 0; i < xis->count_styles; ++i) {
975 XIMStyle ts = xis->supported_styles[i];
976 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
977 bestMatchStyle = ts;
978 break;
981 XFree(xis);
983 if (!bestMatchStyle) {
984 fprintf(stderr, "No matching input style could be determined\n");
987 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
988 check_allocation(xic);
990 // draw the window for the first time
991 draw(&r, text, cs);
993 // main loop
994 while (status == LOOPING) {
995 XEvent e;
996 XNextEvent(d, &e);
998 if (XFilterEvent(&e, w))
999 continue;
1001 switch (e.type) {
1002 case KeymapNotify:
1003 XRefreshKeyboardMapping(&e.xmapping);
1004 break;
1006 case KeyPress: {
1007 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1009 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
1010 bool shift = (ev->state & ShiftMask);
1011 complete(cs, nothing_selected, shift, text, textlen, status);
1012 draw(&r, text, cs);
1013 break;
1016 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1017 nothing_selected = true;
1018 popc(text, textlen);
1019 update_completions(cs, text, lines);
1020 draw(&r, text, cs);
1021 break;
1024 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1025 status = OK;
1026 break;
1029 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1030 status = ERR;
1031 break;
1034 // try to read what the user pressed
1035 int symbol = 0;
1036 Status s = 0;
1037 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1039 if (s == XBufferOverflow) {
1040 // should not happen since there are no utf-8 characters
1041 // larger than 24bits, but is something to be aware of when
1042 // used to directly write to a string buffer
1043 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1044 break;
1046 char *str = (char*)&symbol;
1048 if (ev->state & ControlMask) {
1049 // check for some key bindings
1050 if (!strcmp(str, "")) { // C-u
1051 nothing_selected = true;
1052 for (int i = 0; i < textlen; ++i)
1053 text[i] = 0;
1054 update_completions(cs, text, lines);
1056 if (!strcmp(str, "")) { // C-h
1057 nothing_selected = true;
1058 popc(text, textlen);
1059 update_completions(cs, text, lines);
1061 if (!strcmp(str, "")) { // C-w
1062 nothing_selected = true;
1064 // `textlen` is the length of the allocated string, not the
1065 // length of the ACTUAL string
1066 int p = strlen(text) - 1;
1067 if (p >= 0) { // delete the current char
1068 text[p] = 0;
1069 p--;
1071 while (p >= 0 && isalnum(text[p])) {
1072 text[p] = 0;
1073 p--;
1075 // erase also trailing white space
1076 while (p >= 0 && isspace(text[p])) {
1077 text[p] = 0;
1078 p--;
1080 update_completions(cs, text, lines);
1082 if (!strcmp(str, "\r")) { // C-m
1083 status = OK;
1085 if (!strcmp(str, "")) {
1086 complete(cs, nothing_selected, true, text, textlen, status);
1088 if (!strcmp(str, "")) {
1089 complete(cs, nothing_selected, false, text, textlen, status);
1091 draw(&r, text, cs);
1092 break;
1095 int str_len = strlen(str);
1096 for (int i = 0; i < str_len; ++i) {
1097 textlen = pushc(&text, textlen, str[i]);
1098 if (textlen == -1) {
1099 fprintf(stderr, "Memory allocation error\n");
1100 status = ERR;
1101 break;
1103 nothing_selected = true;
1104 update_completions(cs, text, lines);
1108 draw(&r, text, cs);
1109 break;
1111 default:
1112 fprintf(stderr, "Unknown event %d\n", e.type);
1116 release_keyboard(d);
1118 if (status == OK)
1119 printf("%s\n", text);
1121 for (int i = 0; i < nlines; ++i) {
1122 free(lines[i]);
1125 #ifdef USE_XFT
1126 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1127 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1128 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1129 #endif
1131 free(ps1);
1132 free(fontname);
1133 free(text);
1134 free(lines);
1135 compl_delete(cs);
1137 XDestroyWindow(d, w);
1138 XCloseDisplay(d);
1140 return status == OK ? 0 : 1;