Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
12 #include <X11/Xlib.h>
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 # include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 # include <X11/Xft/Xft.h>
24 #endif
26 #define nil NULL
27 #define resname "MyMenu"
28 #define resclass "mymenu"
30 #ifdef USE_XFT
31 # define default_fontname "monospace"
32 #else
33 # define default_fontname "fixed"
34 #endif
36 #define MIN(a, b) ((a) < (b) ? (a) : (b))
37 #define MAX(a, b) ((a) > (b) ? (a) : (b))
39 // If we don't have it or we don't want an "ignore case" completion
40 // style, fall back to `strstr(3)`
41 #ifndef USE_STRCASESTR
42 #define strcasestr strstr
43 #endif
45 #define update_completions(cs, text, lines) { \
46 compl_delete(cs); \
47 cs = filter(text, lines); \
48 }
50 #define 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 struct completions *compl_select_next(struct completions *c, bool n) {
132 if (c == nil)
133 return nil;
134 if (n) {
135 c->selected = true;
136 return c;
139 struct completions *orig = c;
140 while (c != nil) {
141 if (c->selected) {
142 c->selected = false;
143 if (c->next != nil) {
144 // the current one is selected and the next one exists
145 c->next->selected = true;
146 return c->next;
147 } else {
148 // the current one is selected and the next one is nill,
149 // select the first one
150 orig->selected = true;
151 return orig;
154 c = c->next;
156 return nil;
159 struct completions *compl_select_prev(struct completions *c, bool n) {
160 if (c == nil)
161 return nil;
163 struct completions *cc = c;
165 if (n) // select the last one
166 while (cc != nil) {
167 if (cc->next == nil) {
168 cc->selected = true;
169 return cc;
171 cc = cc->next;
173 else // select the previous one
174 while (cc != nil) {
175 if (cc->next != nil && cc->next->selected) {
176 cc->next->selected = false;
177 cc->selected = true;
178 return cc;
180 cc = cc->next;
183 return nil;
186 struct completions *filter(char *text, char **lines) {
187 int i = 0;
188 struct completions *root = compl_new();
189 struct completions *c = root;
191 for (;;) {
192 char *l = lines[i];
193 if (l == nil)
194 break;
196 if (strcasestr(l, text) != nil) {
197 c->next = compl_new();
198 c = c->next;
199 c->completion = l;
202 ++i;
205 struct completions *r = root->next;
206 compl_delete(root);
207 return r;
210 // push the character c at the end of the string pointed by p
211 int pushc(char **p, int maxlen, char c) {
212 int len = strnlen(*p, maxlen);
214 if (!(len < maxlen -2)) {
215 maxlen += maxlen >> 1;
216 char *newptr = realloc(*p, maxlen);
217 if (newptr == nil) { // bad!
218 return -1;
220 *p = newptr;
223 (*p)[len] = c;
224 (*p)[len+1] = '\0';
225 return maxlen;
228 int utf8strnlen(char *s, int maxlen) {
229 int len = 0;
230 while (*s && maxlen > 0) {
231 len += (*s++ & 0xc0) != 0x80;
232 maxlen--;
234 return len;
237 // remove the last *glyph* from the *utf8* string!
238 // this is different from just setting the last byte to 0 (in some
239 // cases ofc). The actual implementation is quite inefficient because
240 // it remove the last char until the number of glyphs doesn't change
241 void popc(char *p, int maxlen) {
242 int len = strnlen(p, maxlen);
244 if (len == 0)
245 return;
247 int ulen = utf8strnlen(p, maxlen);
248 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
249 len--;
250 p[len] = 0;
254 // If the string is surrounded by quotes (`"`) remove them and replace
255 // every `\"` in the string with `"`
256 char *normalize_str(const char *str) {
257 int len = strlen(str);
258 if (len == 0)
259 return nil;
261 char *s = calloc(len, sizeof(char));
262 check_allocation(s);
263 int p = 0;
264 while (*str) {
265 char c = *str;
266 if (*str == '\\') {
267 if (*(str + 1)) {
268 s[p] = *(str + 1);
269 p++;
270 str += 2; // skip this and the next char
271 continue;
272 } else {
273 break;
276 if (c == '"') {
277 str++; // skip only this char
278 continue;
280 s[p] = c;
281 p++;
282 str++;
284 return s;
287 // read an arbitrary long line from stdin and return a pointer to it
288 // TODO: resize the allocated memory to exactly fit the string once
289 // read?
290 char *readline(bool *eof) {
291 int maxlen = 8;
292 char *str = calloc(maxlen, sizeof(char));
293 if (str == nil) {
294 fprintf(stderr, "Cannot allocate memory!\n");
295 exit(EX_UNAVAILABLE);
298 int c;
299 while((c = getchar()) != EOF) {
300 if (c == '\n')
301 return str;
302 else
303 maxlen = pushc(&str, maxlen, c);
305 if (maxlen == -1) {
306 fprintf(stderr, "Cannot allocate memory!\n");
307 exit(EX_UNAVAILABLE);
310 *eof = true;
311 return str;
314 int readlines (char ***lns, int items) {
315 bool finished = false;
316 int n = 0;
317 char **lines = *lns;
318 while (true) {
319 lines[n] = readline(&finished);
321 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
322 free(lines[n]);
323 --n; // forget about this line
326 if (finished)
327 break;
329 ++n;
331 if (n == items - 1) {
332 items += items >>1;
333 char **l = realloc(lines, sizeof(char*) * items);
334 check_allocation(l);
335 *lns = l;
336 lines = l;
340 n++;
341 lines[n] = nil;
342 return items;
345 // Compute the dimension of the string str once rendered, return the
346 // width and save the width and the height in ret_width and ret_height
347 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
348 int height;
349 int width;
350 #ifdef USE_XFT
351 XGlyphInfo gi;
352 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
353 // Honestly I don't know why this won't work, but I found that this
354 // formula seems to work with various ttf font
355 /* height = gi.height; */
356 height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2;
357 width = gi.width - gi.x;
358 #else
359 XRectangle rect;
360 XmbTextExtents(*r->font, str, len, nil, &rect);
361 height = rect.height;
362 width = rect.width;
363 #endif
364 if (ret_width != nil) *ret_width = width;
365 if (ret_height != nil) *ret_height = height;
366 return width;
369 // Draw the string str
370 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
371 #ifdef USE_XFT
372 XftColor xftcolor;
373 if (tt == PROMPT) xftcolor = r->xft_prompt;
374 if (tt == COMPL) xftcolor = r->xft_completion;
375 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
377 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
378 #else
379 GC gc;
380 if (tt == PROMPT) gc = r->prompt;
381 if (tt == COMPL) gc = r->completion;
382 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
383 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
384 #endif
387 // Duplicate the string str and substitute every space with a 'n'
388 char *strdupn(char *str) {
389 int len = strlen(str);
391 if (str == nil || len == 0)
392 return nil;
394 char *dup = strdup(str);
395 if (dup == nil)
396 return nil;
398 for (int i = 0; i < len; ++i)
399 if (dup[i] == ' ')
400 dup[i] = 'n';
402 return dup;
405 // |------------------|----------------------------------------------|
406 // | 20 char text | completion | completion | completion | compl |
407 // |------------------|----------------------------------------------|
408 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
409 // TODO: make these dynamic?
410 int prompt_width = 20; // char
411 int padding = 10;
413 int width, height;
414 char *ps1_dup = strdupn(r->ps1);
415 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
416 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
417 free(ps1_dup);
418 int start_at = ps1xlen;
420 start_at = text_extents("n", 1, r, nil, nil);
421 start_at = start_at * prompt_width + padding;
423 int texty = (height + r->height) >>1;
425 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
427 int text_len = strlen(text);
428 if (text_len > prompt_width)
429 text = text + (text_len - prompt_width);
430 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
431 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
433 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
435 while (cs != nil) {
436 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
437 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
439 int len = strlen(cs->completion);
440 int text_width = text_extents(cs->completion, len, r, nil, nil);
442 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
444 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
446 start_at += text_width + padding * 2;
448 if (start_at > r->width)
449 break; // don't draw completion if the space isn't enough
451 cs = cs->next;
454 XFlush(r->d);
457 // |-----------------------------------------------------------------|
458 // | prompt |
459 // |-----------------------------------------------------------------|
460 // | completion |
461 // |-----------------------------------------------------------------|
462 // | completion |
463 // |-----------------------------------------------------------------|
464 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
465 // should be padding and not padding*2, but the text doesn't seem to
466 // be vertically centered otherwise....
467 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
468 int padding = 10; // TODO make this dynamic
470 int height, width;
471 text_extents("fjpgl", 5, r, &width, &height);
472 int start_at = height + padding*2;
474 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
475 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
477 char *ps1_dup = strdupn(r->ps1);
478 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
479 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
480 free(ps1_dup);
482 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
483 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
485 while (cs != nil) {
486 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
487 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
489 int len = strlen(cs->completion);
490 text_extents(cs->completion, len, r, &width, &height);
491 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
492 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
494 start_at += height + padding *2;
496 if (start_at > r->height)
497 break; // don't draw completion if the space isn't enough
499 cs = cs->next;
502 XFlush(r->d);
505 void draw(struct rendering *r, char *text, struct completions *cs) {
506 if (r->horizontal_layout)
507 draw_horizontally(r, text, cs);
508 else
509 draw_vertically(r, text, cs);
512 /* Set some WM stuff */
513 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
514 Atom type;
515 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
516 XChangeProperty(
517 d,
518 w,
519 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
520 XInternAtom(d, "ATOM", false),
521 32,
522 PropModeReplace,
523 (unsigned char *)&type,
525 );
527 /* some window managers honor this properties */
528 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
529 XChangeProperty(d,
530 w,
531 XInternAtom(d, "_NET_WM_STATE", false),
532 XInternAtom(d, "ATOM", false),
533 32,
534 PropModeReplace,
535 (unsigned char *)&type,
537 );
539 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
540 XChangeProperty(d,
541 w,
542 XInternAtom(d, "_NET_WM_STATE", false),
543 XInternAtom(d, "ATOM", false),
544 32,
545 PropModeAppend,
546 (unsigned char *)&type,
548 );
550 // setting window hints
551 XClassHint *class_hint = XAllocClassHint();
552 if (class_hint == nil) {
553 fprintf(stderr, "Could not allocate memory for class hint\n");
554 exit(EX_UNAVAILABLE);
556 class_hint->res_name = resname;
557 class_hint->res_class = resclass;
558 XSetClassHint(d, w, class_hint);
559 XFree(class_hint);
561 XSizeHints *size_hint = XAllocSizeHints();
562 if (size_hint == nil) {
563 fprintf(stderr, "Could not allocate memory for size hint\n");
564 exit(EX_UNAVAILABLE);
566 size_hint->flags = PMinSize | PBaseSize;
567 size_hint->min_width = width;
568 size_hint->base_width = width;
569 size_hint->min_height = height;
570 size_hint->base_height = height;
572 XFlush(d);
575 void get_wh(Display *d, Window *w, int *width, int *height) {
576 XWindowAttributes win_attr;
577 XGetWindowAttributes(d, *w, &win_attr);
578 *height = win_attr.height;
579 *width = win_attr.width;
582 // I know this may seem a little hackish BUT is the only way I managed
583 // to actually grab that goddam keyboard. Only one call to
584 // XGrabKeyboard does not always end up with the keyboard grabbed!
585 int take_keyboard(Display *d, Window w) {
586 int i;
587 for (i = 0; i < 100; i++) {
588 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
589 return 1;
590 usleep(1000);
592 return 0;
595 void release_keyboard(Display *d) {
596 XUngrabKeyboard(d, CurrentTime);
599 int parse_integer(const char *str, int default_value) {
600 /* int len = strlen(str); */
601 /* if (len > 0 && str[len-1] == '%') { */
602 /* char *cpy = strdup(str); */
603 /* check_allocation(cpy); */
604 /* cpy[len-1] = '\0'; */
605 /* int val = parse_integer(cpy, default_value, max); */
606 /* free(cpy); */
607 /* return val * max / 100; */
608 /* } */
610 errno = 0;
611 char *ep;
612 long lval = strtol(str, &ep, 10);
613 if (str[0] == '\0' || *ep != '\0') { // NaN
614 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
615 return default_value;
617 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
618 (lval > INT_MAX || lval < INT_MIN)) {
619 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
620 return default_value;
622 return lval;
625 int parse_int_with_percentage(const char *str, int default_value, int max) {
626 int len = strlen(str);
627 if (len > 0 && str[len-1] == '%') {
628 char *cpy = strdup(str);
629 check_allocation(cpy);
630 cpy[len-1] = '\0';
631 int val = parse_integer(cpy, default_value);
632 free(cpy);
633 return val * max / 100;
635 return parse_integer(str, default_value);
638 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
639 if (!strcmp(str, "middle")) {
640 return (max - self)/2;
642 return parse_int_with_percentage(str, default_value, max);
645 int main() {
646 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
647 int nlines = readlines(&lines, INITIAL_ITEMS);
649 setlocale(LC_ALL, getenv("LANG"));
651 enum state status = LOOPING;
653 // where the monitor start (used only with xinerama)
654 int offset_x = 0;
655 int offset_y = 0;
657 // width and height of the window
658 int width = 400;
659 int height = 20;
661 // position on the screen
662 int x = 0;
663 int y = 0;
665 char *ps1 = strdup("$ ");
666 check_allocation(ps1);
668 char *fontname = strdup(default_fontname);
669 check_allocation(fontname);
671 int textlen = 10;
672 char *text = malloc(textlen * sizeof(char));
673 check_allocation(text);
675 struct completions *cs = filter(text, lines);
676 bool nothing_selected = true;
678 // start talking to xorg
679 Display *d = XOpenDisplay(nil);
680 if (d == nil) {
681 fprintf(stderr, "Could not open display!\n");
682 return EX_UNAVAILABLE;
685 // get display size
686 // XXX: is getting the default root window dimension correct?
687 XWindowAttributes xwa;
688 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
689 int d_width = xwa.width;
690 int d_height = xwa.height;
692 #ifdef USE_XINERAMA
693 if (XineramaIsActive(d)) {
694 // find the mice
695 int number_of_screens = XScreenCount(d);
696 bool result;
697 Window r;
698 Window root;
699 int root_x, root_y, win_x, win_y;
700 unsigned int mask;
701 bool res;
702 for (int i = 0; i < number_of_screens; ++i) {
703 root = XRootWindow(d, i);
704 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
705 if (res) break;
707 if (!res) {
708 fprintf(stderr, "No mouse found.\n");
709 root_x = 0;
710 root_y = 0;
713 // now find in which monitor the mice is on
714 int monitors;
715 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
716 if (info) {
717 for (int i = 0; i < monitors; ++i) {
718 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
719 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
720 offset_x = info[i].x_org;
721 offset_y = info[i].y_org;
722 d_width = info[i].width;
723 d_height = info[i].height;
724 break;
728 XFree(info);
730 #endif
732 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
733 XColor p_fg, p_bg,
734 compl_fg, compl_bg,
735 compl_highlighted_fg, compl_highlighted_bg;
737 bool horizontal_layout = true;
739 // read resource
740 XrmInitialize();
741 char *xrm = XResourceManagerString(d);
742 XrmDatabase xdb = nil;
743 if (xrm != nil) {
744 xdb = XrmGetStringDatabase(xrm);
745 XrmValue value;
746 char *datatype[20];
748 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
749 fontname = strdup(value.addr);
750 check_allocation(fontname);
752 else
753 fprintf(stderr, "no font defined, using %s\n", fontname);
755 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
756 char *v = strdup(value.addr);
757 check_allocation(v);
758 horizontal_layout = !strcmp(v, "horizontal");
759 free(v);
761 else
762 fprintf(stderr, "no layout defined, using horizontal\n");
764 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
765 free(ps1);
766 ps1 = normalize_str(value.addr);
767 } else
768 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
770 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
771 width = parse_int_with_percentage(value.addr, width, d_width);
772 else
773 fprintf(stderr, "no width defined, using %d\n", width);
775 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
776 height = parse_int_with_percentage(value.addr, height, d_height);
777 else
778 fprintf(stderr, "no height defined, using %d\n", height);
780 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
781 x = parse_int_with_middle(value.addr, x, d_width, width);
782 else
783 fprintf(stderr, "no x defined, using %d\n", width);
785 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
786 y = parse_int_with_middle(value.addr, y, d_height, height);
787 else
788 fprintf(stderr, "no y defined, using %d\n", height);
790 XColor tmp;
791 // TODO: tmp needs to be free'd after every allocation?
793 // prompt
794 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
795 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
796 else
797 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
799 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
800 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
801 else
802 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
804 // completion
805 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
806 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
807 else
808 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
810 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
811 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
812 else
813 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
815 // completion highlighted
816 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
817 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
818 else
819 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
821 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
822 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
823 else
824 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
825 } else {
826 XColor tmp;
827 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
828 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
829 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
830 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
831 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
832 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
835 // load the font
836 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
837 /* if (font == nil) { */
838 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
839 /* font = XLoadQueryFont(d, "fixed"); */
840 /* } */
841 // load the font
842 #ifdef USE_XFT
843 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
844 #else
845 char **missing_charset_list;
846 int missing_charset_count;
847 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
848 if (font == nil) {
849 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
850 return EX_UNAVAILABLE;
852 #endif
854 // create the window
855 XSetWindowAttributes attr;
856 attr.override_redirect = true;
858 Window w = XCreateWindow(d, // display
859 DefaultRootWindow(d), // parent
860 x + offset_x, y + offset_y, // x y
861 width, height, // w h
862 0, // border width
863 DefaultDepth(d, DefaultScreen(d)), // depth
864 InputOutput, // class
865 DefaultVisual(d, DefaultScreen(d)), // visual
866 CWOverrideRedirect, // value mask
867 &attr);
869 set_win_atoms_hints(d, w, width, height);
871 // we want some events
872 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
874 // make the window appear on the screen
875 XMapWindow(d, w);
877 // wait for the MapNotify event (i.e. the event "window rendered")
878 for (;;) {
879 XEvent e;
880 XNextEvent(d, &e);
881 if (e.type == MapNotify)
882 break;
885 // get the *real* width & height after the window was rendered
886 get_wh(d, &w, &width, &height);
888 // grab keyboard
889 take_keyboard(d, w);
891 // Create some graphics contexts
892 XGCValues values;
893 /* values.font = font->fid; */
895 struct rendering r = {
896 .d = d,
897 .w = w,
898 #ifdef USE_XFT
899 .font = font,
900 #else
901 .font = &font,
902 #endif
903 .prompt = XCreateGC(d, w, 0, &values),
904 .prompt_bg = XCreateGC(d, w, 0, &values),
905 .completion = XCreateGC(d, w, 0, &values),
906 .completion_bg = XCreateGC(d, w, 0, &values),
907 .completion_highlighted = XCreateGC(d, w, 0, &values),
908 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
909 .width = width,
910 .height = height,
911 .horizontal_layout = horizontal_layout,
912 .ps1 = ps1,
913 .ps1len = strlen(ps1)
914 };
916 #ifdef USE_XFT
917 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
919 // prompt
920 XRenderColor xrcolor;
921 xrcolor.red = p_fg.red;
922 xrcolor.green = p_fg.red;
923 xrcolor.blue = p_fg.red;
924 xrcolor.alpha = 65535;
925 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
927 // completion
928 xrcolor.red = compl_fg.red;
929 xrcolor.green = compl_fg.green;
930 xrcolor.blue = compl_fg.blue;
931 xrcolor.alpha = 65535;
932 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
934 // completion highlighted
935 xrcolor.red = compl_highlighted_fg.red;
936 xrcolor.green = compl_highlighted_fg.green;
937 xrcolor.blue = compl_highlighted_fg.blue;
938 xrcolor.alpha = 65535;
939 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
940 #endif
942 // load the colors in our GCs
943 XSetForeground(d, r.prompt, p_fg.pixel);
944 XSetForeground(d, r.prompt_bg, p_bg.pixel);
945 XSetForeground(d, r.completion, compl_fg.pixel);
946 XSetForeground(d, r.completion_bg, compl_bg.pixel);
947 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
948 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
950 // open the X input method
951 XIM xim = XOpenIM(d, xdb, resname, resclass);
952 check_allocation(xim);
954 XIMStyles *xis = nil;
955 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
956 fprintf(stderr, "Input Styles could not be retrieved\n");
957 return EX_UNAVAILABLE;
960 XIMStyle bestMatchStyle = 0;
961 for (int i = 0; i < xis->count_styles; ++i) {
962 XIMStyle ts = xis->supported_styles[i];
963 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
964 bestMatchStyle = ts;
965 break;
968 XFree(xis);
970 if (!bestMatchStyle) {
971 fprintf(stderr, "No matching input style could be determined\n");
974 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
975 check_allocation(xic);
977 // draw the window for the first time
978 draw(&r, text, cs);
980 // main loop
981 while (status == LOOPING) {
982 XEvent e;
983 XNextEvent(d, &e);
985 if (XFilterEvent(&e, w))
986 continue;
988 switch (e.type) {
989 case KeymapNotify:
990 XRefreshKeyboardMapping(&e.xmapping);
991 break;
993 case KeyPress: {
994 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
996 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
997 bool shift = (ev->state & ShiftMask);
998 complete(cs, nothing_selected, shift, text, textlen, status);
999 draw(&r, text, cs);
1000 break;
1003 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1004 nothing_selected = true;
1005 popc(text, textlen);
1006 update_completions(cs, text, lines);
1007 draw(&r, text, cs);
1008 break;
1011 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1012 status = OK;
1013 break;
1016 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1017 status = ERR;
1018 break;
1021 // try to read what the user pressed
1022 int symbol = 0;
1023 Status s = 0;
1024 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1026 if (s == XBufferOverflow) {
1027 // should not happen since there are no utf-8 characters
1028 // larger than 24bits, but is something to be aware of when
1029 // used to directly write to a string buffer
1030 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1031 break;
1033 char *str = (char*)&symbol;
1035 if (ev->state & ControlMask) {
1036 // check for some key bindings
1037 if (!strcmp(str, "")) { // C-u
1038 nothing_selected = true;
1039 for (int i = 0; i < textlen; ++i)
1040 text[i] = 0;
1041 update_completions(cs, text, lines);
1043 if (!strcmp(str, "")) { // C-h
1044 nothing_selected = true;
1045 popc(text, textlen);
1046 update_completions(cs, text, lines);
1048 if (!strcmp(str, "")) { // C-w
1049 nothing_selected = true;
1051 // `textlen` is the length of the allocated string, not the
1052 // length of the ACTUAL string
1053 int p = strlen(text) - 1;
1054 if (p >= 0) { // delete the current char
1055 text[p] = 0;
1056 p--;
1058 while (p >= 0 && isalnum(text[p])) {
1059 text[p] = 0;
1060 p--;
1062 // erase also trailing white space
1063 while (p >= 0 && isspace(text[p])) {
1064 text[p] = 0;
1065 p--;
1067 update_completions(cs, text, lines);
1069 if (!strcmp(str, "\r")) { // C-m
1070 status = OK;
1072 if (!strcmp(str, "")) {
1073 complete(cs, nothing_selected, true, text, textlen, status);
1075 if (!strcmp(str, "")) {
1076 complete(cs, nothing_selected, false, text, textlen, status);
1078 draw(&r, text, cs);
1079 break;
1082 int str_len = strlen(str);
1083 for (int i = 0; i < str_len; ++i) {
1084 textlen = pushc(&text, textlen, str[i]);
1085 if (textlen == -1) {
1086 fprintf(stderr, "Memory allocation error\n");
1087 status = ERR;
1088 break;
1090 nothing_selected = true;
1091 update_completions(cs, text, lines);
1095 draw(&r, text, cs);
1096 break;
1098 default:
1099 fprintf(stderr, "Unknown event %d\n", e.type);
1103 release_keyboard(d);
1105 if (status == OK)
1106 printf("%s\n", text);
1108 for (int i = 0; i < nlines; ++i) {
1109 free(lines[i]);
1112 #ifdef USE_XFT
1113 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1114 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1115 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1116 #endif
1118 free(ps1);
1119 free(fontname);
1120 free(text);
1121 free(lines);
1122 compl_delete(cs);
1124 XDestroyWindow(d, w);
1125 XCloseDisplay(d);
1127 return status == OK ? 0 : 1;