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 #ifndef VERSION
27 # define VERSION "unknown"
28 #endif
30 #define nil NULL
31 #define resname "MyMenu"
32 #define resclass "mymenu"
34 #ifdef USE_XFT
35 # define default_fontname "monospace"
36 #else
37 # define default_fontname "fixed"
38 #endif
40 #define MIN(a, b) ((a) < (b) ? (a) : (b))
41 #define MAX(a, b) ((a) > (b) ? (a) : (b))
43 // If we don't have it or we don't want an "ignore case" completion
44 // style, fall back to `strstr(3)`
45 #ifndef USE_STRCASESTR
46 # define strcasestr strstr
47 #endif
49 #define update_completions(cs, text, lines, first_selected) { \
50 compl_delete_rec(cs); \
51 cs = filter(text, lines); \
52 if (first_selected && cs != nil) \
53 cs->selected = true; \
54 }
56 #define complete(cs, nothing_selected, p, text, textlen, status) { \
57 struct completions *n = p \
58 ? compl_select_prev(cs, nothing_selected) \
59 : compl_select_next(cs, nothing_selected); \
60 \
61 if (n != nil) { \
62 nothing_selected = false; \
63 free(text); \
64 text = strdup(n->completion); \
65 if (text == nil) { \
66 fprintf(stderr, "Memory allocation error!\n"); \
67 status = ERR; \
68 break; \
69 } \
70 textlen = strlen(text); \
71 } \
72 }
74 #define INITIAL_ITEMS 64
76 #define cannot_allocate_memory { \
77 fprintf(stderr, "Could not allocate memory\n"); \
78 abort(); \
79 }
81 #define check_allocation(a) { \
82 if (a == nil) \
83 cannot_allocate_memory; \
84 }
86 enum state {LOOPING, OK, ERR};
88 enum text_type {PROMPT, COMPL, COMPL_HIGH};
90 struct rendering {
91 Display *d;
92 Window w;
93 int width;
94 int height;
95 int padding;
96 bool horizontal_layout;
97 char *ps1;
98 int ps1len;
99 GC prompt;
100 GC prompt_bg;
101 GC completion;
102 GC completion_bg;
103 GC completion_highlighted;
104 GC completion_highlighted_bg;
105 #ifdef USE_XFT
106 XftFont *font;
107 XftDraw *xftdraw;
108 XftColor xft_prompt;
109 XftColor xft_completion;
110 XftColor xft_completion_highlighted;
111 #else
112 XFontSet *font;
113 #endif
114 };
116 struct completions {
117 char *completion;
118 bool selected;
119 struct completions *next;
120 };
122 struct completions *compl_new() {
123 struct completions *c = malloc(sizeof(struct completions));
125 if (c == nil)
126 return c;
128 c->completion = nil;
129 c->selected = false;
130 c->next = nil;
131 return c;
134 void compl_delete(struct completions *c) {
135 free(c);
138 void compl_delete_rec(struct completions *c) {
139 while (c != nil) {
140 struct completions *t = c->next;
141 free(c);
142 c = t;
146 struct completions *compl_select_next(struct completions *c, bool n) {
147 if (c == nil)
148 return nil;
149 if (n) {
150 c->selected = true;
151 return c;
154 struct completions *orig = c;
155 while (c != nil) {
156 if (c->selected) {
157 c->selected = false;
158 if (c->next != nil) {
159 // the current one is selected and the next one exists
160 c->next->selected = true;
161 return c->next;
162 } else {
163 // the current one is selected and the next one is nill,
164 // select the first one
165 orig->selected = true;
166 return orig;
169 c = c->next;
171 return nil;
174 struct completions *compl_select_prev(struct completions *c, bool n) {
175 if (c == nil)
176 return nil;
178 struct completions *cc = c;
180 if (n || c->selected) { // select the last one
181 c->selected = false;
182 while (cc != nil) {
183 if (cc->next == nil) {
184 cc->selected = true;
185 return cc;
187 cc = cc->next;
190 else // select the previous one
191 while (cc != nil) {
192 if (cc->next != nil && cc->next->selected) {
193 cc->next->selected = false;
194 cc->selected = true;
195 return cc;
197 cc = cc->next;
200 return nil;
203 struct completions *filter(char *text, char **lines) {
204 int i = 0;
205 struct completions *root = compl_new();
206 struct completions *c = root;
207 if (c == nil)
208 return nil;
210 for (;;) {
211 char *l = lines[i];
212 if (l == nil)
213 break;
215 if (strcasestr(l, text) != nil) {
216 c->next = compl_new();
217 c = c->next;
218 if (c == nil) {
219 compl_delete_rec(root);
220 return nil;
222 c->completion = l;
225 ++i;
228 struct completions *r = root->next;
229 compl_delete(root);
230 return r;
233 // push the character c at the end of the string pointed by p
234 int pushc(char **p, int maxlen, char c) {
235 int len = strnlen(*p, maxlen);
237 if (!(len < maxlen -2)) {
238 maxlen += maxlen >> 1;
239 char *newptr = realloc(*p, maxlen);
240 if (newptr == nil) { // bad!
241 return -1;
243 *p = newptr;
246 (*p)[len] = c;
247 (*p)[len+1] = '\0';
248 return maxlen;
251 int utf8strnlen(char *s, int maxlen) {
252 int len = 0;
253 while (*s && maxlen > 0) {
254 len += (*s++ & 0xc0) != 0x80;
255 maxlen--;
257 return len;
260 // remove the last *glyph* from the *utf8* string!
261 // this is different from just setting the last byte to 0 (in some
262 // cases ofc). The actual implementation is quite inefficient because
263 // it remove the last char until the number of glyphs doesn't change
264 void popc(char *p, int maxlen) {
265 int len = strnlen(p, maxlen);
267 if (len == 0)
268 return;
270 int ulen = utf8strnlen(p, maxlen);
271 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
272 len--;
273 p[len] = 0;
277 // If the string is surrounded by quotes (`"`) remove them and replace
278 // every `\"` in the string with `"`
279 char *normalize_str(const char *str) {
280 int len = strlen(str);
281 if (len == 0)
282 return nil;
284 char *s = calloc(len, sizeof(char));
285 check_allocation(s);
286 int p = 0;
287 while (*str) {
288 char c = *str;
289 if (*str == '\\') {
290 if (*(str + 1)) {
291 s[p] = *(str + 1);
292 p++;
293 str += 2; // skip this and the next char
294 continue;
295 } else {
296 break;
299 if (c == '"') {
300 str++; // skip only this char
301 continue;
303 s[p] = c;
304 p++;
305 str++;
307 return s;
310 // read an arbitrary long line from stdin and return a pointer to it
311 // TODO: resize the allocated memory to exactly fit the string once
312 // read?
313 char *readline(bool *eof) {
314 int maxlen = 8;
315 char *str = calloc(maxlen, sizeof(char));
316 if (str == nil) {
317 fprintf(stderr, "Cannot allocate memory!\n");
318 exit(EX_UNAVAILABLE);
321 int c;
322 while((c = getchar()) != EOF) {
323 if (c == '\n')
324 return str;
325 else
326 maxlen = pushc(&str, maxlen, c);
328 if (maxlen == -1) {
329 fprintf(stderr, "Cannot allocate memory!\n");
330 exit(EX_UNAVAILABLE);
333 *eof = true;
334 return str;
337 // read an arbitrary amount of text until an EOF and store it in
338 // lns. `items` is the capacity of lns. It may increase lns with
339 // `realloc(3)` to store more line. Return the number of lines
340 // read. The last item will always be a NULL pointer. It ignore the
341 // "null" (empty) lines
342 int readlines (char ***lns, int items) {
343 bool finished = false;
344 int n = 0;
345 char **lines = *lns;
346 while (true) {
347 lines[n] = readline(&finished);
349 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
350 free(lines[n]);
351 --n; // forget about this line
354 if (finished)
355 break;
357 ++n;
359 if (n == items - 1) {
360 items += items >>1;
361 char **l = realloc(lines, sizeof(char*) * items);
362 check_allocation(l);
363 *lns = l;
364 lines = l;
368 n++;
369 lines[n] = nil;
370 return items;
373 // Compute the dimension of the string str once rendered, return the
374 // width and save the width and the height in ret_width and ret_height
375 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
376 int height;
377 int width;
378 #ifdef USE_XFT
379 XGlyphInfo gi;
380 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
381 /* height = gi.height; */
382 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
383 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
384 height = r->font->ascent - r->font->descent;
385 width = gi.width - gi.x;
386 #else
387 XRectangle rect;
388 XmbTextExtents(*r->font, str, len, nil, &rect);
389 height = rect.height;
390 width = rect.width;
391 #endif
392 if (ret_width != nil) *ret_width = width;
393 if (ret_height != nil) *ret_height = height;
394 return width;
397 // Draw the string str
398 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
399 #ifdef USE_XFT
400 XftColor xftcolor;
401 if (tt == PROMPT) xftcolor = r->xft_prompt;
402 if (tt == COMPL) xftcolor = r->xft_completion;
403 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
405 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
406 #else
407 GC gc;
408 if (tt == PROMPT) gc = r->prompt;
409 if (tt == COMPL) gc = r->completion;
410 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
411 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
412 #endif
415 // Duplicate the string str and substitute every space with a 'n'
416 char *strdupn(char *str) {
417 int len = strlen(str);
419 if (str == nil || len == 0)
420 return nil;
422 char *dup = strdup(str);
423 if (dup == nil)
424 return nil;
426 for (int i = 0; i < len; ++i)
427 if (dup[i] == ' ')
428 dup[i] = 'n';
430 return dup;
433 // |------------------|----------------------------------------------|
434 // | 20 char text | completion | completion | completion | compl |
435 // |------------------|----------------------------------------------|
436 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
437 int prompt_width = 20; // char
439 int width, height;
440 char *ps1_dup = strdupn(r->ps1);
441 if (ps1_dup == nil)
442 return;
444 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
445 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
446 free(ps1_dup);
447 int start_at = ps1xlen;
449 start_at = text_extents("n", 1, r, nil, nil);
450 start_at = start_at * prompt_width + r->padding;
452 int texty = (height + r->height) >>1;
454 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
456 int text_len = strlen(text);
457 if (text_len > prompt_width)
458 text = text + (text_len - prompt_width);
459 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
460 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
462 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
464 while (cs != nil) {
465 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
466 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
468 int len = strlen(cs->completion);
469 int text_width = text_extents(cs->completion, len, r, nil, nil);
471 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
473 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
475 start_at += text_width + r->padding * 2;
477 if (start_at > r->width)
478 break; // don't draw completion if the space isn't enough
480 cs = cs->next;
483 XFlush(r->d);
486 // |-----------------------------------------------------------------|
487 // | prompt |
488 // |-----------------------------------------------------------------|
489 // | completion |
490 // |-----------------------------------------------------------------|
491 // | completion |
492 // |-----------------------------------------------------------------|
493 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
494 int height, width;
495 text_extents("fjpgl", 5, r, nil, &height);
496 int start_at = height + r->padding;
498 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
499 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
501 char *ps1_dup = strdupn(r->ps1);
502 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
503 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
504 free(ps1_dup);
506 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
507 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
508 start_at += r->padding;
510 while (cs != nil) {
511 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
512 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
514 int len = strlen(cs->completion);
515 text_extents(cs->completion, len, r, &width, &height);
516 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
517 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
519 start_at += height + r->padding *2;
521 if (start_at > r->height)
522 break; // don't draw completion if the space isn't enough
524 cs = cs->next;
527 XFlush(r->d);
530 void draw(struct rendering *r, char *text, struct completions *cs) {
531 if (r->horizontal_layout)
532 draw_horizontally(r, text, cs);
533 else
534 draw_vertically(r, text, cs);
537 /* Set some WM stuff */
538 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
539 Atom type;
540 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
541 XChangeProperty(
542 d,
543 w,
544 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
545 XInternAtom(d, "ATOM", false),
546 32,
547 PropModeReplace,
548 (unsigned char *)&type,
550 );
552 /* some window managers honor this properties */
553 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
554 XChangeProperty(d,
555 w,
556 XInternAtom(d, "_NET_WM_STATE", false),
557 XInternAtom(d, "ATOM", false),
558 32,
559 PropModeReplace,
560 (unsigned char *)&type,
562 );
564 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
565 XChangeProperty(d,
566 w,
567 XInternAtom(d, "_NET_WM_STATE", false),
568 XInternAtom(d, "ATOM", false),
569 32,
570 PropModeAppend,
571 (unsigned char *)&type,
573 );
575 // setting window hints
576 XClassHint *class_hint = XAllocClassHint();
577 if (class_hint == nil) {
578 fprintf(stderr, "Could not allocate memory for class hint\n");
579 exit(EX_UNAVAILABLE);
581 class_hint->res_name = resname;
582 class_hint->res_class = resclass;
583 XSetClassHint(d, w, class_hint);
584 XFree(class_hint);
586 XSizeHints *size_hint = XAllocSizeHints();
587 if (size_hint == nil) {
588 fprintf(stderr, "Could not allocate memory for size hint\n");
589 exit(EX_UNAVAILABLE);
591 size_hint->flags = PMinSize | PBaseSize;
592 size_hint->min_width = width;
593 size_hint->base_width = width;
594 size_hint->min_height = height;
595 size_hint->base_height = height;
597 XFlush(d);
600 void get_wh(Display *d, Window *w, int *width, int *height) {
601 XWindowAttributes win_attr;
602 XGetWindowAttributes(d, *w, &win_attr);
603 *height = win_attr.height;
604 *width = win_attr.width;
607 // I know this may seem a little hackish BUT is the only way I managed
608 // to actually grab that goddam keyboard. Only one call to
609 // XGrabKeyboard does not always end up with the keyboard grabbed!
610 int take_keyboard(Display *d, Window w) {
611 int i;
612 for (i = 0; i < 100; i++) {
613 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
614 return 1;
615 usleep(1000);
617 return 0;
620 void release_keyboard(Display *d) {
621 XUngrabKeyboard(d, CurrentTime);
624 int parse_integer(const char *str, int default_value) {
625 /* int len = strlen(str); */
626 /* if (len > 0 && str[len-1] == '%') { */
627 /* char *cpy = strdup(str); */
628 /* check_allocation(cpy); */
629 /* cpy[len-1] = '\0'; */
630 /* int val = parse_integer(cpy, default_value, max); */
631 /* free(cpy); */
632 /* return val * max / 100; */
633 /* } */
635 errno = 0;
636 char *ep;
637 long lval = strtol(str, &ep, 10);
638 if (str[0] == '\0' || *ep != '\0') { // NaN
639 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
640 return default_value;
642 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
643 (lval > INT_MAX || lval < INT_MIN)) {
644 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
645 return default_value;
647 return lval;
650 int parse_int_with_percentage(const char *str, int default_value, int max) {
651 int len = strlen(str);
652 if (len > 0 && str[len-1] == '%') {
653 char *cpy = strdup(str);
654 check_allocation(cpy);
655 cpy[len-1] = '\0';
656 int val = parse_integer(cpy, default_value);
657 free(cpy);
658 return val * max / 100;
660 return parse_integer(str, default_value);
663 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
664 if (!strcmp(str, "middle")) {
665 return (max - self)/2;
667 return parse_int_with_percentage(str, default_value, max);
670 void usage(char *prgname) {
671 fprintf(stderr, "Usage: %s [flags]\n", prgname);
672 fprintf(stderr, "\t-a: automatic mode, the first completion is "
673 "always selected;\n");
674 fprintf(stderr, "\t-h: print this help.\n");
677 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
678 release_keyboard(r->d);
680 #ifdef USE_XFT
681 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
682 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
683 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
684 #endif
686 free(ps1);
687 free(fontname);
688 free(text);
690 char *l = nil;
691 char **lns = lines;
692 while ((l = *lns) != nil) {
693 free(l);
694 ++lns;
696 free(lines);
697 compl_delete(cs);
699 XDestroyWindow(r->d, r->w);
700 XCloseDisplay(r->d);
702 return status;
705 int main(int argc, char **argv) {
706 // by default the first completion isn't selected
707 bool first_selected = false;
709 // parse the command line options
710 int ch;
711 while ((ch = getopt(argc, argv, "ahv")) != -1) {
712 switch (ch) {
713 case 'a':
714 first_selected = true;
715 break;
716 case 'h':
717 usage(*argv);
718 return 0;
719 case 'v':
720 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
721 return 0;
722 default:
723 usage(*argv);
724 return EX_USAGE;
728 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
729 readlines(&lines, INITIAL_ITEMS);
731 setlocale(LC_ALL, getenv("LANG"));
733 enum state status = LOOPING;
735 // where the monitor start (used only with xinerama)
736 int offset_x = 0;
737 int offset_y = 0;
739 // width and height of the window
740 int width = 400;
741 int height = 20;
743 // position on the screen
744 int x = 0;
745 int y = 0;
747 // the default padding
748 int padding = 10;
750 char *ps1 = strdup("$ ");
751 check_allocation(ps1);
753 char *fontname = strdup(default_fontname);
754 check_allocation(fontname);
756 int textlen = 10;
757 char *text = malloc(textlen * sizeof(char));
758 check_allocation(text);
760 bool nothing_selected = first_selected;
761 /* struct completions *cs = filter(text, lines); */
762 struct completions *cs = nil;
763 update_completions(cs, text, lines, first_selected);
765 // start talking to xorg
766 Display *d = XOpenDisplay(nil);
767 if (d == nil) {
768 fprintf(stderr, "Could not open display!\n");
769 return EX_UNAVAILABLE;
772 // get display size
773 // XXX: is getting the default root window dimension correct?
774 XWindowAttributes xwa;
775 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
776 int d_width = xwa.width;
777 int d_height = xwa.height;
779 #ifdef USE_XINERAMA
780 if (XineramaIsActive(d)) {
781 // find the mice
782 int number_of_screens = XScreenCount(d);
783 Window r;
784 Window root;
785 int root_x, root_y, win_x, win_y;
786 unsigned int mask;
787 bool res;
788 for (int i = 0; i < number_of_screens; ++i) {
789 root = XRootWindow(d, i);
790 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
791 if (res) break;
793 if (!res) {
794 fprintf(stderr, "No mouse found.\n");
795 root_x = 0;
796 root_y = 0;
799 // now find in which monitor the mice is on
800 int monitors;
801 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
802 if (info) {
803 for (int i = 0; i < monitors; ++i) {
804 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
805 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
806 offset_x = info[i].x_org;
807 offset_y = info[i].y_org;
808 d_width = info[i].width;
809 d_height = info[i].height;
810 break;
814 XFree(info);
816 #endif
818 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
819 XColor p_fg, p_bg,
820 compl_fg, compl_bg,
821 compl_highlighted_fg, compl_highlighted_bg;
823 bool horizontal_layout = true;
825 // read resource
826 XrmInitialize();
827 char *xrm = XResourceManagerString(d);
828 XrmDatabase xdb = nil;
829 if (xrm != nil) {
830 xdb = XrmGetStringDatabase(xrm);
831 XrmValue value;
832 char *datatype[20];
834 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
835 fontname = strdup(value.addr);
836 check_allocation(fontname);
838 else
839 fprintf(stderr, "no font defined, using %s\n", fontname);
841 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
842 char *v = strdup(value.addr);
843 check_allocation(v);
844 horizontal_layout = !strcmp(v, "horizontal");
845 free(v);
847 else
848 fprintf(stderr, "no layout defined, using horizontal\n");
850 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
851 free(ps1);
852 ps1 = normalize_str(value.addr);
853 } else
854 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
856 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
857 width = parse_int_with_percentage(value.addr, width, d_width);
858 else
859 fprintf(stderr, "no width defined, using %d\n", width);
861 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
862 height = parse_int_with_percentage(value.addr, height, d_height);
863 else
864 fprintf(stderr, "no height defined, using %d\n", height);
866 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
867 x = parse_int_with_middle(value.addr, x, d_width, width);
868 else
869 fprintf(stderr, "no x defined, using %d\n", x);
871 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
872 y = parse_int_with_middle(value.addr, y, d_height, height);
873 else
874 fprintf(stderr, "no y defined, using %d\n", y);
876 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
877 padding = parse_integer(value.addr, padding);
878 else
879 fprintf(stderr, "no y defined, using %d\n", padding);
881 XColor tmp;
882 // TODO: tmp needs to be free'd after every allocation?
884 // prompt
885 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
886 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
887 else
888 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
890 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
891 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
892 else
893 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
895 // completion
896 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
897 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
898 else
899 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
901 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
902 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
903 else
904 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
906 // completion highlighted
907 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
908 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
909 else
910 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
912 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
913 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
914 else
915 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
916 } else {
917 XColor tmp;
918 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
919 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
920 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
921 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
922 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
923 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
926 // load the font
927 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
928 /* if (font == nil) { */
929 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
930 /* font = XLoadQueryFont(d, "fixed"); */
931 /* } */
932 // load the font
933 #ifdef USE_XFT
934 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
935 #else
936 char **missing_charset_list;
937 int missing_charset_count;
938 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
939 if (font == nil) {
940 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
941 return EX_UNAVAILABLE;
943 #endif
945 // create the window
946 XSetWindowAttributes attr;
947 attr.override_redirect = true;
949 Window w = XCreateWindow(d, // display
950 DefaultRootWindow(d), // parent
951 x + offset_x, y + offset_y, // x y
952 width, height, // w h
953 0, // border width
954 DefaultDepth(d, DefaultScreen(d)), // depth
955 InputOutput, // class
956 DefaultVisual(d, DefaultScreen(d)), // visual
957 CWOverrideRedirect, // value mask
958 &attr);
960 set_win_atoms_hints(d, w, width, height);
962 // we want some events
963 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
965 // make the window appear on the screen
966 XMapWindow(d, w);
968 // wait for the MapNotify event (i.e. the event "window rendered")
969 for (;;) {
970 XEvent e;
971 XNextEvent(d, &e);
972 if (e.type == MapNotify)
973 break;
976 // get the *real* width & height after the window was rendered
977 get_wh(d, &w, &width, &height);
979 // grab keyboard
980 take_keyboard(d, w);
982 // Create some graphics contexts
983 XGCValues values;
984 /* values.font = font->fid; */
986 struct rendering r = {
987 .d = d,
988 .w = w,
989 #ifdef USE_XFT
990 .font = font,
991 #else
992 .font = &font,
993 #endif
994 .prompt = XCreateGC(d, w, 0, &values),
995 .prompt_bg = XCreateGC(d, w, 0, &values),
996 .completion = XCreateGC(d, w, 0, &values),
997 .completion_bg = XCreateGC(d, w, 0, &values),
998 .completion_highlighted = XCreateGC(d, w, 0, &values),
999 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1000 .width = width,
1001 .height = height,
1002 .padding = padding,
1003 .horizontal_layout = horizontal_layout,
1004 .ps1 = ps1,
1005 .ps1len = strlen(ps1)
1008 #ifdef USE_XFT
1009 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1011 // prompt
1012 XRenderColor xrcolor;
1013 xrcolor.red = p_fg.red;
1014 xrcolor.green = p_fg.red;
1015 xrcolor.blue = p_fg.red;
1016 xrcolor.alpha = 65535;
1017 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1019 // completion
1020 xrcolor.red = compl_fg.red;
1021 xrcolor.green = compl_fg.green;
1022 xrcolor.blue = compl_fg.blue;
1023 xrcolor.alpha = 65535;
1024 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1026 // completion highlighted
1027 xrcolor.red = compl_highlighted_fg.red;
1028 xrcolor.green = compl_highlighted_fg.green;
1029 xrcolor.blue = compl_highlighted_fg.blue;
1030 xrcolor.alpha = 65535;
1031 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1032 #endif
1034 // load the colors in our GCs
1035 XSetForeground(d, r.prompt, p_fg.pixel);
1036 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1037 XSetForeground(d, r.completion, compl_fg.pixel);
1038 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1039 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1040 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1042 // open the X input method
1043 XIM xim = XOpenIM(d, xdb, resname, resclass);
1044 check_allocation(xim);
1046 XIMStyles *xis = nil;
1047 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1048 fprintf(stderr, "Input Styles could not be retrieved\n");
1049 return EX_UNAVAILABLE;
1052 XIMStyle bestMatchStyle = 0;
1053 for (int i = 0; i < xis->count_styles; ++i) {
1054 XIMStyle ts = xis->supported_styles[i];
1055 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1056 bestMatchStyle = ts;
1057 break;
1060 XFree(xis);
1062 if (!bestMatchStyle) {
1063 fprintf(stderr, "No matching input style could be determined\n");
1066 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1067 check_allocation(xic);
1069 // draw the window for the first time
1070 draw(&r, text, cs);
1072 // main loop
1073 while (status == LOOPING) {
1074 XEvent e;
1075 XNextEvent(d, &e);
1077 if (XFilterEvent(&e, w))
1078 continue;
1080 switch (e.type) {
1081 case KeymapNotify:
1082 XRefreshKeyboardMapping(&e.xmapping);
1083 break;
1085 case KeyPress: {
1086 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1088 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
1089 bool shift = (ev->state & ShiftMask);
1090 complete(cs, nothing_selected, shift, text, textlen, status);
1091 draw(&r, text, cs);
1092 break;
1095 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1096 nothing_selected = first_selected;
1097 popc(text, textlen);
1098 update_completions(cs, text, lines, first_selected);
1099 draw(&r, text, cs);
1100 break;
1103 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1104 status = OK;
1105 if (first_selected) {
1106 complete(cs, first_selected, false, text, textlen, status);
1108 break;
1111 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1112 status = ERR;
1113 break;
1116 // try to read what the user pressed
1117 int symbol = 0;
1118 Status s = 0;
1119 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1121 if (s == XBufferOverflow) {
1122 // should not happen since there are no utf-8 characters
1123 // larger than 24bits, but is something to be aware of when
1124 // used to directly write to a string buffer
1125 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1126 break;
1128 char *str = (char*)&symbol;
1130 if (ev->state & ControlMask) {
1131 // check for some key bindings
1132 if (!strcmp(str, "")) { // C-u
1133 nothing_selected = first_selected;
1134 for (int i = 0; i < textlen; ++i)
1135 text[i] = 0;
1136 update_completions(cs, text, lines, first_selected);
1138 if (!strcmp(str, "")) { // C-h
1139 nothing_selected = first_selected;
1140 popc(text, textlen);
1141 update_completions(cs, text, lines, first_selected);
1143 if (!strcmp(str, "")) { // C-w
1144 nothing_selected = first_selected;
1146 // `textlen` is the length of the allocated string, not the
1147 // length of the ACTUAL string
1148 int p = strlen(text) - 1;
1149 if (p >= 0) { // delete the current char
1150 text[p] = 0;
1151 p--;
1153 while (p >= 0 && isalnum(text[p])) {
1154 text[p] = 0;
1155 p--;
1157 // erase also trailing white space
1158 while (p >= 0 && isspace(text[p])) {
1159 text[p] = 0;
1160 p--;
1162 update_completions(cs, text, lines, first_selected);
1164 if (!strcmp(str, "\r")) { // C-m
1165 status = OK;
1166 if (first_selected) {
1167 complete(cs, first_selected, false, text, textlen, status);
1170 if (!strcmp(str, "")) {
1171 complete(cs, nothing_selected, true, text, textlen, status);
1173 if (!strcmp(str, "")) {
1174 complete(cs, nothing_selected, false, text, textlen, status);
1176 draw(&r, text, cs);
1177 break;
1180 int str_len = strlen(str);
1181 for (int i = 0; i < str_len; ++i) {
1182 textlen = pushc(&text, textlen, str[i]);
1183 if (textlen == -1) {
1184 fprintf(stderr, "Memory allocation error\n");
1185 status = ERR;
1186 break;
1188 nothing_selected = first_selected;
1189 update_completions(cs, text, lines, first_selected);
1193 draw(&r, text, cs);
1194 break;
1196 default:
1197 fprintf(stderr, "Unknown event %d\n", e.type);
1201 if (status == OK)
1202 printf("%s\n", text);
1204 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);