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, first_selected) { \
46 compl_delete_rec(cs); \
47 cs = filter(text, lines); \
48 if (first_selected && cs != nil) \
49 cs->selected = true; \
50 }
52 #define complete(cs, nothing_selected, p, text, textlen, status) { \
53 struct completions *n = p \
54 ? compl_select_prev(cs, nothing_selected) \
55 : compl_select_next(cs, nothing_selected); \
56 \
57 if (n != nil) { \
58 nothing_selected = false; \
59 free(text); \
60 text = strdup(n->completion); \
61 if (text == nil) { \
62 fprintf(stderr, "Memory allocation error!\n"); \
63 status = ERR; \
64 break; \
65 } \
66 textlen = strlen(text); \
67 } \
68 }
70 #define INITIAL_ITEMS 64
72 #define cannot_allocate_memory { \
73 fprintf(stderr, "Could not allocate memory\n"); \
74 abort(); \
75 }
77 #define check_allocation(a) { \
78 if (a == nil) \
79 cannot_allocate_memory; \
80 }
82 enum state {LOOPING, OK, ERR};
84 enum text_type {PROMPT, COMPL, COMPL_HIGH};
86 struct rendering {
87 Display *d;
88 Window w;
89 int width;
90 int height;
91 int padding;
92 bool horizontal_layout;
93 char *ps1;
94 int ps1len;
95 GC prompt;
96 GC prompt_bg;
97 GC completion;
98 GC completion_bg;
99 GC completion_highlighted;
100 GC completion_highlighted_bg;
101 #ifdef USE_XFT
102 XftFont *font;
103 XftDraw *xftdraw;
104 XftColor xft_prompt;
105 XftColor xft_completion;
106 XftColor xft_completion_highlighted;
107 #else
108 XFontSet *font;
109 #endif
110 };
112 struct completions {
113 char *completion;
114 bool selected;
115 struct completions *next;
116 };
118 struct completions *compl_new() {
119 struct completions *c = malloc(sizeof(struct completions));
121 if (c == nil)
122 return c;
124 c->completion = nil;
125 c->selected = false;
126 c->next = nil;
127 return c;
130 void compl_delete(struct completions *c) {
131 free(c);
134 void compl_delete_rec(struct completions *c) {
135 while (c != nil) {
136 struct completions *t = c->next;
137 free(c);
138 c = t;
142 struct completions *compl_select_next(struct completions *c, bool n) {
143 if (c == nil)
144 return nil;
145 if (n) {
146 c->selected = true;
147 return c;
150 struct completions *orig = c;
151 while (c != nil) {
152 if (c->selected) {
153 c->selected = false;
154 if (c->next != nil) {
155 // the current one is selected and the next one exists
156 c->next->selected = true;
157 return c->next;
158 } else {
159 // the current one is selected and the next one is nill,
160 // select the first one
161 orig->selected = true;
162 return orig;
165 c = c->next;
167 return nil;
170 struct completions *compl_select_prev(struct completions *c, bool n) {
171 if (c == nil)
172 return nil;
174 struct completions *cc = c;
176 if (n || c->selected) { // select the last one
177 c->selected = false;
178 while (cc != nil) {
179 if (cc->next == nil) {
180 cc->selected = true;
181 return cc;
183 cc = cc->next;
186 else // select the previous one
187 while (cc != nil) {
188 if (cc->next != nil && cc->next->selected) {
189 cc->next->selected = false;
190 cc->selected = true;
191 return cc;
193 cc = cc->next;
196 return nil;
199 struct completions *filter(char *text, char **lines) {
200 int i = 0;
201 struct completions *root = compl_new();
202 struct completions *c = root;
203 if (c == nil)
204 return nil;
206 for (;;) {
207 char *l = lines[i];
208 if (l == nil)
209 break;
211 if (strcasestr(l, text) != nil) {
212 c->next = compl_new();
213 c = c->next;
214 if (c == nil) {
215 compl_delete_rec(root);
216 return nil;
218 c->completion = l;
221 ++i;
224 struct completions *r = root->next;
225 compl_delete(root);
226 return r;
229 // push the character c at the end of the string pointed by p
230 int pushc(char **p, int maxlen, char c) {
231 int len = strnlen(*p, maxlen);
233 if (!(len < maxlen -2)) {
234 maxlen += maxlen >> 1;
235 char *newptr = realloc(*p, maxlen);
236 if (newptr == nil) { // bad!
237 return -1;
239 *p = newptr;
242 (*p)[len] = c;
243 (*p)[len+1] = '\0';
244 return maxlen;
247 int utf8strnlen(char *s, int maxlen) {
248 int len = 0;
249 while (*s && maxlen > 0) {
250 len += (*s++ & 0xc0) != 0x80;
251 maxlen--;
253 return len;
256 // remove the last *glyph* from the *utf8* string!
257 // this is different from just setting the last byte to 0 (in some
258 // cases ofc). The actual implementation is quite inefficient because
259 // it remove the last char until the number of glyphs doesn't change
260 void popc(char *p, int maxlen) {
261 int len = strnlen(p, maxlen);
263 if (len == 0)
264 return;
266 int ulen = utf8strnlen(p, maxlen);
267 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
268 len--;
269 p[len] = 0;
273 // If the string is surrounded by quotes (`"`) remove them and replace
274 // every `\"` in the string with `"`
275 char *normalize_str(const char *str) {
276 int len = strlen(str);
277 if (len == 0)
278 return nil;
280 char *s = calloc(len, sizeof(char));
281 check_allocation(s);
282 int p = 0;
283 while (*str) {
284 char c = *str;
285 if (*str == '\\') {
286 if (*(str + 1)) {
287 s[p] = *(str + 1);
288 p++;
289 str += 2; // skip this and the next char
290 continue;
291 } else {
292 break;
295 if (c == '"') {
296 str++; // skip only this char
297 continue;
299 s[p] = c;
300 p++;
301 str++;
303 return s;
306 // read an arbitrary long line from stdin and return a pointer to it
307 // TODO: resize the allocated memory to exactly fit the string once
308 // read?
309 char *readline(bool *eof) {
310 int maxlen = 8;
311 char *str = calloc(maxlen, sizeof(char));
312 if (str == nil) {
313 fprintf(stderr, "Cannot allocate memory!\n");
314 exit(EX_UNAVAILABLE);
317 int c;
318 while((c = getchar()) != EOF) {
319 if (c == '\n')
320 return str;
321 else
322 maxlen = pushc(&str, maxlen, c);
324 if (maxlen == -1) {
325 fprintf(stderr, "Cannot allocate memory!\n");
326 exit(EX_UNAVAILABLE);
329 *eof = true;
330 return str;
333 // read an arbitrary amount of text until an EOF and store it in
334 // lns. `items` is the capacity of lns. It may increase lns with
335 // `realloc(3)` to store more line. Return the number of lines
336 // read. The last item will always be a NULL pointer. It ignore the
337 // "null" (empty) lines
338 int readlines (char ***lns, int items) {
339 bool finished = false;
340 int n = 0;
341 char **lines = *lns;
342 while (true) {
343 lines[n] = readline(&finished);
345 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
346 free(lines[n]);
347 --n; // forget about this line
350 if (finished)
351 break;
353 ++n;
355 if (n == items - 1) {
356 items += items >>1;
357 char **l = realloc(lines, sizeof(char*) * items);
358 check_allocation(l);
359 *lns = l;
360 lines = l;
364 n++;
365 lines[n] = nil;
366 return items;
369 // Compute the dimension of the string str once rendered, return the
370 // width and save the width and the height in ret_width and ret_height
371 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
372 int height;
373 int width;
374 #ifdef USE_XFT
375 XGlyphInfo gi;
376 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
377 /* height = gi.height; */
378 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
379 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
380 height = r->font->ascent - r->font->descent;
381 width = gi.width - gi.x;
382 #else
383 XRectangle rect;
384 XmbTextExtents(*r->font, str, len, nil, &rect);
385 height = rect.height;
386 width = rect.width;
387 #endif
388 if (ret_width != nil) *ret_width = width;
389 if (ret_height != nil) *ret_height = height;
390 return width;
393 // Draw the string str
394 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
395 #ifdef USE_XFT
396 XftColor xftcolor;
397 if (tt == PROMPT) xftcolor = r->xft_prompt;
398 if (tt == COMPL) xftcolor = r->xft_completion;
399 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
401 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
402 #else
403 GC gc;
404 if (tt == PROMPT) gc = r->prompt;
405 if (tt == COMPL) gc = r->completion;
406 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
407 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
408 #endif
411 // Duplicate the string str and substitute every space with a 'n'
412 char *strdupn(char *str) {
413 int len = strlen(str);
415 if (str == nil || len == 0)
416 return nil;
418 char *dup = strdup(str);
419 if (dup == nil)
420 return nil;
422 for (int i = 0; i < len; ++i)
423 if (dup[i] == ' ')
424 dup[i] = 'n';
426 return dup;
429 // |------------------|----------------------------------------------|
430 // | 20 char text | completion | completion | completion | compl |
431 // |------------------|----------------------------------------------|
432 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
433 int prompt_width = 20; // char
435 int width, height;
436 char *ps1_dup = strdupn(r->ps1);
437 if (ps1_dup == nil)
438 return;
440 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
441 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
442 free(ps1_dup);
443 int start_at = ps1xlen;
445 start_at = text_extents("n", 1, r, nil, nil);
446 start_at = start_at * prompt_width + r->padding;
448 int texty = (height + r->height) >>1;
450 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
452 int text_len = strlen(text);
453 if (text_len > prompt_width)
454 text = text + (text_len - prompt_width);
455 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
456 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
458 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
460 while (cs != nil) {
461 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
462 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
464 int len = strlen(cs->completion);
465 int text_width = text_extents(cs->completion, len, r, nil, nil);
467 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
469 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
471 start_at += text_width + r->padding * 2;
473 if (start_at > r->width)
474 break; // don't draw completion if the space isn't enough
476 cs = cs->next;
479 XFlush(r->d);
482 // |-----------------------------------------------------------------|
483 // | prompt |
484 // |-----------------------------------------------------------------|
485 // | completion |
486 // |-----------------------------------------------------------------|
487 // | completion |
488 // |-----------------------------------------------------------------|
489 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
490 int height, width;
491 text_extents("fjpgl", 5, r, nil, &height);
492 int start_at = height + r->padding;
494 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
495 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
497 char *ps1_dup = strdupn(r->ps1);
498 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
499 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
500 free(ps1_dup);
502 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
503 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
504 start_at += r->padding;
506 while (cs != nil) {
507 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
508 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
510 int len = strlen(cs->completion);
511 text_extents(cs->completion, len, r, &width, &height);
512 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
513 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
515 start_at += height + r->padding *2;
517 if (start_at > r->height)
518 break; // don't draw completion if the space isn't enough
520 cs = cs->next;
523 XFlush(r->d);
526 void draw(struct rendering *r, char *text, struct completions *cs) {
527 if (r->horizontal_layout)
528 draw_horizontally(r, text, cs);
529 else
530 draw_vertically(r, text, cs);
533 /* Set some WM stuff */
534 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
535 Atom type;
536 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
537 XChangeProperty(
538 d,
539 w,
540 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
541 XInternAtom(d, "ATOM", false),
542 32,
543 PropModeReplace,
544 (unsigned char *)&type,
546 );
548 /* some window managers honor this properties */
549 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
550 XChangeProperty(d,
551 w,
552 XInternAtom(d, "_NET_WM_STATE", false),
553 XInternAtom(d, "ATOM", false),
554 32,
555 PropModeReplace,
556 (unsigned char *)&type,
558 );
560 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
561 XChangeProperty(d,
562 w,
563 XInternAtom(d, "_NET_WM_STATE", false),
564 XInternAtom(d, "ATOM", false),
565 32,
566 PropModeAppend,
567 (unsigned char *)&type,
569 );
571 // setting window hints
572 XClassHint *class_hint = XAllocClassHint();
573 if (class_hint == nil) {
574 fprintf(stderr, "Could not allocate memory for class hint\n");
575 exit(EX_UNAVAILABLE);
577 class_hint->res_name = resname;
578 class_hint->res_class = resclass;
579 XSetClassHint(d, w, class_hint);
580 XFree(class_hint);
582 XSizeHints *size_hint = XAllocSizeHints();
583 if (size_hint == nil) {
584 fprintf(stderr, "Could not allocate memory for size hint\n");
585 exit(EX_UNAVAILABLE);
587 size_hint->flags = PMinSize | PBaseSize;
588 size_hint->min_width = width;
589 size_hint->base_width = width;
590 size_hint->min_height = height;
591 size_hint->base_height = height;
593 XFlush(d);
596 void get_wh(Display *d, Window *w, int *width, int *height) {
597 XWindowAttributes win_attr;
598 XGetWindowAttributes(d, *w, &win_attr);
599 *height = win_attr.height;
600 *width = win_attr.width;
603 // I know this may seem a little hackish BUT is the only way I managed
604 // to actually grab that goddam keyboard. Only one call to
605 // XGrabKeyboard does not always end up with the keyboard grabbed!
606 int take_keyboard(Display *d, Window w) {
607 int i;
608 for (i = 0; i < 100; i++) {
609 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
610 return 1;
611 usleep(1000);
613 return 0;
616 void release_keyboard(Display *d) {
617 XUngrabKeyboard(d, CurrentTime);
620 int parse_integer(const char *str, int default_value) {
621 /* int len = strlen(str); */
622 /* if (len > 0 && str[len-1] == '%') { */
623 /* char *cpy = strdup(str); */
624 /* check_allocation(cpy); */
625 /* cpy[len-1] = '\0'; */
626 /* int val = parse_integer(cpy, default_value, max); */
627 /* free(cpy); */
628 /* return val * max / 100; */
629 /* } */
631 errno = 0;
632 char *ep;
633 long lval = strtol(str, &ep, 10);
634 if (str[0] == '\0' || *ep != '\0') { // NaN
635 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
636 return default_value;
638 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
639 (lval > INT_MAX || lval < INT_MIN)) {
640 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
641 return default_value;
643 return lval;
646 int parse_int_with_percentage(const char *str, int default_value, int max) {
647 int len = strlen(str);
648 if (len > 0 && str[len-1] == '%') {
649 char *cpy = strdup(str);
650 check_allocation(cpy);
651 cpy[len-1] = '\0';
652 int val = parse_integer(cpy, default_value);
653 free(cpy);
654 return val * max / 100;
656 return parse_integer(str, default_value);
659 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
660 if (!strcmp(str, "middle")) {
661 return (max - self)/2;
663 return parse_int_with_percentage(str, default_value, max);
666 void usage(char *prgname) {
667 fprintf(stderr, "Usage: %s [flags]\n", prgname);
668 fprintf(stderr, "\t-a: automatic mode, the first completion is "
669 "always selected;\n");
670 fprintf(stderr, "\t-h: print this help.\n");
673 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
674 release_keyboard(r->d);
676 #ifdef USE_XFT
677 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
678 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
679 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
680 #endif
682 free(ps1);
683 free(fontname);
684 free(text);
686 char *l = nil;
687 char **lns = lines;
688 while ((l = *lns) != nil) {
689 free(l);
690 ++lns;
692 free(lines);
693 compl_delete(cs);
695 XDestroyWindow(r->d, r->w);
696 XCloseDisplay(r->d);
698 return status;
701 int main(int argc, char **argv) {
702 // by default the first completion isn't selected
703 bool first_selected = false;
705 // parse the command line options
706 int ch;
707 while ((ch = getopt(argc, argv, "ah")) != -1) {
708 switch (ch) {
709 case 'a':
710 first_selected = true;
711 break;
712 case 'h':
713 usage(*argv);
714 return 0;
715 default:
716 usage(*argv);
717 return EX_USAGE;
721 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
722 readlines(&lines, INITIAL_ITEMS);
724 setlocale(LC_ALL, getenv("LANG"));
726 enum state status = LOOPING;
728 // where the monitor start (used only with xinerama)
729 int offset_x = 0;
730 int offset_y = 0;
732 // width and height of the window
733 int width = 400;
734 int height = 20;
736 // position on the screen
737 int x = 0;
738 int y = 0;
740 // the default padding
741 int padding = 10;
743 char *ps1 = strdup("$ ");
744 check_allocation(ps1);
746 char *fontname = strdup(default_fontname);
747 check_allocation(fontname);
749 int textlen = 10;
750 char *text = malloc(textlen * sizeof(char));
751 check_allocation(text);
753 bool nothing_selected = first_selected;
754 /* struct completions *cs = filter(text, lines); */
755 struct completions *cs = nil;
756 update_completions(cs, text, lines, first_selected);
758 // start talking to xorg
759 Display *d = XOpenDisplay(nil);
760 if (d == nil) {
761 fprintf(stderr, "Could not open display!\n");
762 return EX_UNAVAILABLE;
765 // get display size
766 // XXX: is getting the default root window dimension correct?
767 XWindowAttributes xwa;
768 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
769 int d_width = xwa.width;
770 int d_height = xwa.height;
772 #ifdef USE_XINERAMA
773 if (XineramaIsActive(d)) {
774 // find the mice
775 int number_of_screens = XScreenCount(d);
776 Window r;
777 Window root;
778 int root_x, root_y, win_x, win_y;
779 unsigned int mask;
780 bool res;
781 for (int i = 0; i < number_of_screens; ++i) {
782 root = XRootWindow(d, i);
783 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
784 if (res) break;
786 if (!res) {
787 fprintf(stderr, "No mouse found.\n");
788 root_x = 0;
789 root_y = 0;
792 // now find in which monitor the mice is on
793 int monitors;
794 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
795 if (info) {
796 for (int i = 0; i < monitors; ++i) {
797 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
798 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
799 offset_x = info[i].x_org;
800 offset_y = info[i].y_org;
801 d_width = info[i].width;
802 d_height = info[i].height;
803 break;
807 XFree(info);
809 #endif
811 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
812 XColor p_fg, p_bg,
813 compl_fg, compl_bg,
814 compl_highlighted_fg, compl_highlighted_bg;
816 bool horizontal_layout = true;
818 // read resource
819 XrmInitialize();
820 char *xrm = XResourceManagerString(d);
821 XrmDatabase xdb = nil;
822 if (xrm != nil) {
823 xdb = XrmGetStringDatabase(xrm);
824 XrmValue value;
825 char *datatype[20];
827 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
828 fontname = strdup(value.addr);
829 check_allocation(fontname);
831 else
832 fprintf(stderr, "no font defined, using %s\n", fontname);
834 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
835 char *v = strdup(value.addr);
836 check_allocation(v);
837 horizontal_layout = !strcmp(v, "horizontal");
838 free(v);
840 else
841 fprintf(stderr, "no layout defined, using horizontal\n");
843 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
844 free(ps1);
845 ps1 = normalize_str(value.addr);
846 } else
847 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
849 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
850 width = parse_int_with_percentage(value.addr, width, d_width);
851 else
852 fprintf(stderr, "no width defined, using %d\n", width);
854 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
855 height = parse_int_with_percentage(value.addr, height, d_height);
856 else
857 fprintf(stderr, "no height defined, using %d\n", height);
859 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
860 x = parse_int_with_middle(value.addr, x, d_width, width);
861 else
862 fprintf(stderr, "no x defined, using %d\n", x);
864 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
865 y = parse_int_with_middle(value.addr, y, d_height, height);
866 else
867 fprintf(stderr, "no y defined, using %d\n", y);
869 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
870 padding = parse_integer(value.addr, padding);
871 else
872 fprintf(stderr, "no y defined, using %d\n", padding);
874 XColor tmp;
875 // TODO: tmp needs to be free'd after every allocation?
877 // prompt
878 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
879 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
880 else
881 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
883 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
884 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
885 else
886 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
888 // completion
889 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
890 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
891 else
892 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
894 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
895 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
896 else
897 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
899 // completion highlighted
900 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
901 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
902 else
903 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
905 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
906 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
907 else
908 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
909 } else {
910 XColor tmp;
911 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
912 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
913 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
914 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
915 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
916 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
919 // load the font
920 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
921 /* if (font == nil) { */
922 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
923 /* font = XLoadQueryFont(d, "fixed"); */
924 /* } */
925 // load the font
926 #ifdef USE_XFT
927 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
928 #else
929 char **missing_charset_list;
930 int missing_charset_count;
931 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
932 if (font == nil) {
933 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
934 return EX_UNAVAILABLE;
936 #endif
938 // create the window
939 XSetWindowAttributes attr;
940 attr.override_redirect = true;
942 Window w = XCreateWindow(d, // display
943 DefaultRootWindow(d), // parent
944 x + offset_x, y + offset_y, // x y
945 width, height, // w h
946 0, // border width
947 DefaultDepth(d, DefaultScreen(d)), // depth
948 InputOutput, // class
949 DefaultVisual(d, DefaultScreen(d)), // visual
950 CWOverrideRedirect, // value mask
951 &attr);
953 set_win_atoms_hints(d, w, width, height);
955 // we want some events
956 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
958 // make the window appear on the screen
959 XMapWindow(d, w);
961 // wait for the MapNotify event (i.e. the event "window rendered")
962 for (;;) {
963 XEvent e;
964 XNextEvent(d, &e);
965 if (e.type == MapNotify)
966 break;
969 // get the *real* width & height after the window was rendered
970 get_wh(d, &w, &width, &height);
972 // grab keyboard
973 take_keyboard(d, w);
975 // Create some graphics contexts
976 XGCValues values;
977 /* values.font = font->fid; */
979 struct rendering r = {
980 .d = d,
981 .w = w,
982 #ifdef USE_XFT
983 .font = font,
984 #else
985 .font = &font,
986 #endif
987 .prompt = XCreateGC(d, w, 0, &values),
988 .prompt_bg = XCreateGC(d, w, 0, &values),
989 .completion = XCreateGC(d, w, 0, &values),
990 .completion_bg = XCreateGC(d, w, 0, &values),
991 .completion_highlighted = XCreateGC(d, w, 0, &values),
992 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
993 .width = width,
994 .height = height,
995 .padding = padding,
996 .horizontal_layout = horizontal_layout,
997 .ps1 = ps1,
998 .ps1len = strlen(ps1)
999 };
1001 #ifdef USE_XFT
1002 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1004 // prompt
1005 XRenderColor xrcolor;
1006 xrcolor.red = p_fg.red;
1007 xrcolor.green = p_fg.red;
1008 xrcolor.blue = p_fg.red;
1009 xrcolor.alpha = 65535;
1010 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1012 // completion
1013 xrcolor.red = compl_fg.red;
1014 xrcolor.green = compl_fg.green;
1015 xrcolor.blue = compl_fg.blue;
1016 xrcolor.alpha = 65535;
1017 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1019 // completion highlighted
1020 xrcolor.red = compl_highlighted_fg.red;
1021 xrcolor.green = compl_highlighted_fg.green;
1022 xrcolor.blue = compl_highlighted_fg.blue;
1023 xrcolor.alpha = 65535;
1024 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1025 #endif
1027 // load the colors in our GCs
1028 XSetForeground(d, r.prompt, p_fg.pixel);
1029 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1030 XSetForeground(d, r.completion, compl_fg.pixel);
1031 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1032 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1033 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1035 // open the X input method
1036 XIM xim = XOpenIM(d, xdb, resname, resclass);
1037 check_allocation(xim);
1039 XIMStyles *xis = nil;
1040 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1041 fprintf(stderr, "Input Styles could not be retrieved\n");
1042 return EX_UNAVAILABLE;
1045 XIMStyle bestMatchStyle = 0;
1046 for (int i = 0; i < xis->count_styles; ++i) {
1047 XIMStyle ts = xis->supported_styles[i];
1048 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1049 bestMatchStyle = ts;
1050 break;
1053 XFree(xis);
1055 if (!bestMatchStyle) {
1056 fprintf(stderr, "No matching input style could be determined\n");
1059 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1060 check_allocation(xic);
1062 // draw the window for the first time
1063 draw(&r, text, cs);
1065 // main loop
1066 while (status == LOOPING) {
1067 XEvent e;
1068 XNextEvent(d, &e);
1070 if (XFilterEvent(&e, w))
1071 continue;
1073 switch (e.type) {
1074 case KeymapNotify:
1075 XRefreshKeyboardMapping(&e.xmapping);
1076 break;
1078 case KeyPress: {
1079 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1081 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
1082 bool shift = (ev->state & ShiftMask);
1083 complete(cs, nothing_selected, shift, text, textlen, status);
1084 draw(&r, text, cs);
1085 break;
1088 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1089 nothing_selected = first_selected;
1090 popc(text, textlen);
1091 update_completions(cs, text, lines, first_selected);
1092 draw(&r, text, cs);
1093 break;
1096 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1097 status = OK;
1098 if (first_selected) {
1099 complete(cs, first_selected, false, text, textlen, status);
1101 break;
1104 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1105 status = ERR;
1106 break;
1109 // try to read what the user pressed
1110 int symbol = 0;
1111 Status s = 0;
1112 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1114 if (s == XBufferOverflow) {
1115 // should not happen since there are no utf-8 characters
1116 // larger than 24bits, but is something to be aware of when
1117 // used to directly write to a string buffer
1118 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1119 break;
1121 char *str = (char*)&symbol;
1123 if (ev->state & ControlMask) {
1124 // check for some key bindings
1125 if (!strcmp(str, "")) { // C-u
1126 nothing_selected = first_selected;
1127 for (int i = 0; i < textlen; ++i)
1128 text[i] = 0;
1129 update_completions(cs, text, lines, first_selected);
1131 if (!strcmp(str, "")) { // C-h
1132 nothing_selected = first_selected;
1133 popc(text, textlen);
1134 update_completions(cs, text, lines, first_selected);
1136 if (!strcmp(str, "")) { // C-w
1137 nothing_selected = first_selected;
1139 // `textlen` is the length of the allocated string, not the
1140 // length of the ACTUAL string
1141 int p = strlen(text) - 1;
1142 if (p >= 0) { // delete the current char
1143 text[p] = 0;
1144 p--;
1146 while (p >= 0 && isalnum(text[p])) {
1147 text[p] = 0;
1148 p--;
1150 // erase also trailing white space
1151 while (p >= 0 && isspace(text[p])) {
1152 text[p] = 0;
1153 p--;
1155 update_completions(cs, text, lines, first_selected);
1157 if (!strcmp(str, "\r")) { // C-m
1158 status = OK;
1159 if (first_selected) {
1160 complete(cs, first_selected, false, text, textlen, status);
1163 if (!strcmp(str, "")) {
1164 complete(cs, nothing_selected, true, text, textlen, status);
1166 if (!strcmp(str, "")) {
1167 complete(cs, nothing_selected, false, text, textlen, status);
1169 draw(&r, text, cs);
1170 break;
1173 int str_len = strlen(str);
1174 for (int i = 0; i < str_len; ++i) {
1175 textlen = pushc(&text, textlen, str[i]);
1176 if (textlen == -1) {
1177 fprintf(stderr, "Memory allocation error\n");
1178 status = ERR;
1179 break;
1181 nothing_selected = first_selected;
1182 update_completions(cs, text, lines, first_selected);
1186 draw(&r, text, cs);
1187 break;
1189 default:
1190 fprintf(stderr, "Unknown event %d\n", e.type);
1194 if (status == OK)
1195 printf("%s\n", text);
1197 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);