Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
12 #include <X11/Xlib.h>
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 # include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 # include <X11/Xft/Xft.h>
24 #endif
26 #define nil NULL
27 #define resname "MyMenu"
28 #define resclass "mymenu"
30 #ifdef USE_XFT
31 # define default_fontname "monospace"
32 #else
33 # define default_fontname "fixed"
34 #endif
36 #define MIN(a, b) ((a) < (b) ? (a) : (b))
37 #define MAX(a, b) ((a) > (b) ? (a) : (b))
39 // If we don't have it or we don't want an "ignore case" completion
40 // style, fall back to `strstr(3)`
41 #ifndef USE_STRCASESTR
42 # define strcasestr strstr
43 #endif
45 #define update_completions(cs, text, lines) { \
46 compl_delete_rec(cs); \
47 cs = filter(text, lines); \
48 }
50 #define complete(cs, nothing_selected, p, text, textlen, status) { \
51 struct completions *n = p \
52 ? compl_select_prev(cs, nothing_selected) \
53 : compl_select_next(cs, nothing_selected); \
54 \
55 if (n != nil) { \
56 nothing_selected = false; \
57 free(text); \
58 text = strdup(n->completion); \
59 if (text == nil) { \
60 fprintf(stderr, "Memory allocation error!\n"); \
61 status = ERR; \
62 break; \
63 } \
64 textlen = strlen(text); \
65 } \
66 }
68 #define INITIAL_ITEMS 64
70 #define cannot_allocate_memory { \
71 fprintf(stderr, "Could not allocate memory\n"); \
72 abort(); \
73 }
75 #define check_allocation(a) { \
76 if (a == nil) \
77 cannot_allocate_memory; \
78 }
80 enum state {LOOPING, OK, ERR};
82 enum text_type {PROMPT, COMPL, COMPL_HIGH};
84 struct rendering {
85 Display *d;
86 Window w;
87 int width;
88 int height;
89 int padding;
90 bool horizontal_layout;
91 char *ps1;
92 int ps1len;
93 GC prompt;
94 GC prompt_bg;
95 GC completion;
96 GC completion_bg;
97 GC completion_highlighted;
98 GC completion_highlighted_bg;
99 #ifdef USE_XFT
100 XftFont *font;
101 XftDraw *xftdraw;
102 XftColor xft_prompt;
103 XftColor xft_completion;
104 XftColor xft_completion_highlighted;
105 #else
106 XFontSet *font;
107 #endif
108 };
110 struct completions {
111 char *completion;
112 bool selected;
113 struct completions *next;
114 };
116 struct completions *compl_new() {
117 struct completions *c = malloc(sizeof(struct completions));
119 if (c == nil)
120 return c;
122 c->completion = nil;
123 c->selected = false;
124 c->next = nil;
125 return c;
128 void compl_delete(struct completions *c) {
129 free(c);
132 void compl_delete_rec(struct completions *c) {
133 while (c != nil) {
134 struct completions *t = c->next;
135 free(c);
136 c = t;
140 struct completions *compl_select_next(struct completions *c, bool n) {
141 if (c == nil)
142 return nil;
143 if (n) {
144 c->selected = true;
145 return c;
148 struct completions *orig = c;
149 while (c != nil) {
150 if (c->selected) {
151 c->selected = false;
152 if (c->next != nil) {
153 // the current one is selected and the next one exists
154 c->next->selected = true;
155 return c->next;
156 } else {
157 // the current one is selected and the next one is nill,
158 // select the first one
159 orig->selected = true;
160 return orig;
163 c = c->next;
165 return nil;
168 struct completions *compl_select_prev(struct completions *c, bool n) {
169 if (c == nil)
170 return nil;
172 struct completions *cc = c;
174 if (n || c->selected) { // select the last one
175 c->selected = false;
176 while (cc != nil) {
177 if (cc->next == nil) {
178 cc->selected = true;
179 return cc;
181 cc = cc->next;
184 else // select the previous one
185 while (cc != nil) {
186 if (cc->next != nil && cc->next->selected) {
187 cc->next->selected = false;
188 cc->selected = true;
189 return cc;
191 cc = cc->next;
194 return nil;
197 struct completions *filter(char *text, char **lines) {
198 int i = 0;
199 struct completions *root = compl_new();
200 struct completions *c = root;
201 if (c == nil)
202 return nil;
204 for (;;) {
205 char *l = lines[i];
206 if (l == nil)
207 break;
209 if (strcasestr(l, text) != nil) {
210 c->next = compl_new();
211 c = c->next;
212 if (c == nil) {
213 compl_delete_rec(root);
214 return nil;
216 c->completion = l;
219 ++i;
222 struct completions *r = root->next;
223 compl_delete(root);
224 return r;
227 // push the character c at the end of the string pointed by p
228 int pushc(char **p, int maxlen, char c) {
229 int len = strnlen(*p, maxlen);
231 if (!(len < maxlen -2)) {
232 maxlen += maxlen >> 1;
233 char *newptr = realloc(*p, maxlen);
234 if (newptr == nil) { // bad!
235 return -1;
237 *p = newptr;
240 (*p)[len] = c;
241 (*p)[len+1] = '\0';
242 return maxlen;
245 int utf8strnlen(char *s, int maxlen) {
246 int len = 0;
247 while (*s && maxlen > 0) {
248 len += (*s++ & 0xc0) != 0x80;
249 maxlen--;
251 return len;
254 // remove the last *glyph* from the *utf8* string!
255 // this is different from just setting the last byte to 0 (in some
256 // cases ofc). The actual implementation is quite inefficient because
257 // it remove the last char until the number of glyphs doesn't change
258 void popc(char *p, int maxlen) {
259 int len = strnlen(p, maxlen);
261 if (len == 0)
262 return;
264 int ulen = utf8strnlen(p, maxlen);
265 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
266 len--;
267 p[len] = 0;
271 // If the string is surrounded by quotes (`"`) remove them and replace
272 // every `\"` in the string with `"`
273 char *normalize_str(const char *str) {
274 int len = strlen(str);
275 if (len == 0)
276 return nil;
278 char *s = calloc(len, sizeof(char));
279 check_allocation(s);
280 int p = 0;
281 while (*str) {
282 char c = *str;
283 if (*str == '\\') {
284 if (*(str + 1)) {
285 s[p] = *(str + 1);
286 p++;
287 str += 2; // skip this and the next char
288 continue;
289 } else {
290 break;
293 if (c == '"') {
294 str++; // skip only this char
295 continue;
297 s[p] = c;
298 p++;
299 str++;
301 return s;
304 // read an arbitrary long line from stdin and return a pointer to it
305 // TODO: resize the allocated memory to exactly fit the string once
306 // read?
307 char *readline(bool *eof) {
308 int maxlen = 8;
309 char *str = calloc(maxlen, sizeof(char));
310 if (str == nil) {
311 fprintf(stderr, "Cannot allocate memory!\n");
312 exit(EX_UNAVAILABLE);
315 int c;
316 while((c = getchar()) != EOF) {
317 if (c == '\n')
318 return str;
319 else
320 maxlen = pushc(&str, maxlen, c);
322 if (maxlen == -1) {
323 fprintf(stderr, "Cannot allocate memory!\n");
324 exit(EX_UNAVAILABLE);
327 *eof = true;
328 return str;
331 int readlines (char ***lns, int items) {
332 bool finished = false;
333 int n = 0;
334 char **lines = *lns;
335 while (true) {
336 lines[n] = readline(&finished);
338 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
339 free(lines[n]);
340 --n; // forget about this line
343 if (finished)
344 break;
346 ++n;
348 if (n == items - 1) {
349 items += items >>1;
350 char **l = realloc(lines, sizeof(char*) * items);
351 check_allocation(l);
352 *lns = l;
353 lines = l;
357 n++;
358 lines[n] = nil;
359 return items;
362 // Compute the dimension of the string str once rendered, return the
363 // width and save the width and the height in ret_width and ret_height
364 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
365 int height;
366 int width;
367 #ifdef USE_XFT
368 XGlyphInfo gi;
369 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
370 /* height = gi.height; */
371 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
372 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
373 height = r->font->ascent - r->font->descent;
374 width = gi.width - gi.x;
375 #else
376 XRectangle rect;
377 XmbTextExtents(*r->font, str, len, nil, &rect);
378 height = rect.height;
379 width = rect.width;
380 #endif
381 if (ret_width != nil) *ret_width = width;
382 if (ret_height != nil) *ret_height = height;
383 return width;
386 // Draw the string str
387 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
388 #ifdef USE_XFT
389 XftColor xftcolor;
390 if (tt == PROMPT) xftcolor = r->xft_prompt;
391 if (tt == COMPL) xftcolor = r->xft_completion;
392 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
394 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
395 #else
396 GC gc;
397 if (tt == PROMPT) gc = r->prompt;
398 if (tt == COMPL) gc = r->completion;
399 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
400 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
401 #endif
404 // Duplicate the string str and substitute every space with a 'n'
405 char *strdupn(char *str) {
406 int len = strlen(str);
408 if (str == nil || len == 0)
409 return nil;
411 char *dup = strdup(str);
412 if (dup == nil)
413 return nil;
415 for (int i = 0; i < len; ++i)
416 if (dup[i] == ' ')
417 dup[i] = 'n';
419 return dup;
422 // |------------------|----------------------------------------------|
423 // | 20 char text | completion | completion | completion | compl |
424 // |------------------|----------------------------------------------|
425 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
426 int prompt_width = 20; // char
428 int width, height;
429 char *ps1_dup = strdupn(r->ps1);
430 if (ps1_dup == nil)
431 return;
433 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
434 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
435 free(ps1_dup);
436 int start_at = ps1xlen;
438 start_at = text_extents("n", 1, r, nil, nil);
439 start_at = start_at * prompt_width + r->padding;
441 int texty = (height + r->height) >>1;
443 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
445 int text_len = strlen(text);
446 if (text_len > prompt_width)
447 text = text + (text_len - prompt_width);
448 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
449 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
451 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
453 while (cs != nil) {
454 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
455 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
457 int len = strlen(cs->completion);
458 int text_width = text_extents(cs->completion, len, r, nil, nil);
460 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
462 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
464 start_at += text_width + r->padding * 2;
466 if (start_at > r->width)
467 break; // don't draw completion if the space isn't enough
469 cs = cs->next;
472 XFlush(r->d);
475 // |-----------------------------------------------------------------|
476 // | prompt |
477 // |-----------------------------------------------------------------|
478 // | completion |
479 // |-----------------------------------------------------------------|
480 // | completion |
481 // |-----------------------------------------------------------------|
482 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
483 int height, width;
484 text_extents("fjpgl", 5, r, nil, &height);
485 int start_at = height + r->padding;
487 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
488 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
490 char *ps1_dup = strdupn(r->ps1);
491 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
492 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
493 free(ps1_dup);
495 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
496 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
497 start_at += r->padding;
499 while (cs != nil) {
500 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
501 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
503 int len = strlen(cs->completion);
504 text_extents(cs->completion, len, r, &width, &height);
505 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
506 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
508 start_at += height + r->padding *2;
510 if (start_at > r->height)
511 break; // don't draw completion if the space isn't enough
513 cs = cs->next;
516 XFlush(r->d);
519 void draw(struct rendering *r, char *text, struct completions *cs) {
520 if (r->horizontal_layout)
521 draw_horizontally(r, text, cs);
522 else
523 draw_vertically(r, text, cs);
526 /* Set some WM stuff */
527 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
528 Atom type;
529 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
530 XChangeProperty(
531 d,
532 w,
533 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
534 XInternAtom(d, "ATOM", false),
535 32,
536 PropModeReplace,
537 (unsigned char *)&type,
539 );
541 /* some window managers honor this properties */
542 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
543 XChangeProperty(d,
544 w,
545 XInternAtom(d, "_NET_WM_STATE", false),
546 XInternAtom(d, "ATOM", false),
547 32,
548 PropModeReplace,
549 (unsigned char *)&type,
551 );
553 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
554 XChangeProperty(d,
555 w,
556 XInternAtom(d, "_NET_WM_STATE", false),
557 XInternAtom(d, "ATOM", false),
558 32,
559 PropModeAppend,
560 (unsigned char *)&type,
562 );
564 // setting window hints
565 XClassHint *class_hint = XAllocClassHint();
566 if (class_hint == nil) {
567 fprintf(stderr, "Could not allocate memory for class hint\n");
568 exit(EX_UNAVAILABLE);
570 class_hint->res_name = resname;
571 class_hint->res_class = resclass;
572 XSetClassHint(d, w, class_hint);
573 XFree(class_hint);
575 XSizeHints *size_hint = XAllocSizeHints();
576 if (size_hint == nil) {
577 fprintf(stderr, "Could not allocate memory for size hint\n");
578 exit(EX_UNAVAILABLE);
580 size_hint->flags = PMinSize | PBaseSize;
581 size_hint->min_width = width;
582 size_hint->base_width = width;
583 size_hint->min_height = height;
584 size_hint->base_height = height;
586 XFlush(d);
589 void get_wh(Display *d, Window *w, int *width, int *height) {
590 XWindowAttributes win_attr;
591 XGetWindowAttributes(d, *w, &win_attr);
592 *height = win_attr.height;
593 *width = win_attr.width;
596 // I know this may seem a little hackish BUT is the only way I managed
597 // to actually grab that goddam keyboard. Only one call to
598 // XGrabKeyboard does not always end up with the keyboard grabbed!
599 int take_keyboard(Display *d, Window w) {
600 int i;
601 for (i = 0; i < 100; i++) {
602 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
603 return 1;
604 usleep(1000);
606 return 0;
609 void release_keyboard(Display *d) {
610 XUngrabKeyboard(d, CurrentTime);
613 int parse_integer(const char *str, int default_value) {
614 /* int len = strlen(str); */
615 /* if (len > 0 && str[len-1] == '%') { */
616 /* char *cpy = strdup(str); */
617 /* check_allocation(cpy); */
618 /* cpy[len-1] = '\0'; */
619 /* int val = parse_integer(cpy, default_value, max); */
620 /* free(cpy); */
621 /* return val * max / 100; */
622 /* } */
624 errno = 0;
625 char *ep;
626 long lval = strtol(str, &ep, 10);
627 if (str[0] == '\0' || *ep != '\0') { // NaN
628 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
629 return default_value;
631 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
632 (lval > INT_MAX || lval < INT_MIN)) {
633 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
634 return default_value;
636 return lval;
639 int parse_int_with_percentage(const char *str, int default_value, int max) {
640 int len = strlen(str);
641 if (len > 0 && str[len-1] == '%') {
642 char *cpy = strdup(str);
643 check_allocation(cpy);
644 cpy[len-1] = '\0';
645 int val = parse_integer(cpy, default_value);
646 free(cpy);
647 return val * max / 100;
649 return parse_integer(str, default_value);
652 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
653 if (!strcmp(str, "middle")) {
654 return (max - self)/2;
656 return parse_int_with_percentage(str, default_value, max);
659 int main() {
660 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
661 int nlines = readlines(&lines, INITIAL_ITEMS);
663 setlocale(LC_ALL, getenv("LANG"));
665 enum state status = LOOPING;
667 // where the monitor start (used only with xinerama)
668 int offset_x = 0;
669 int offset_y = 0;
671 // width and height of the window
672 int width = 400;
673 int height = 20;
675 // position on the screen
676 int x = 0;
677 int y = 0;
679 int padding = 10;
681 char *ps1 = strdup("$ ");
682 check_allocation(ps1);
684 char *fontname = strdup(default_fontname);
685 check_allocation(fontname);
687 int textlen = 10;
688 char *text = malloc(textlen * sizeof(char));
689 check_allocation(text);
691 struct completions *cs = filter(text, lines);
692 bool nothing_selected = true;
694 // start talking to xorg
695 Display *d = XOpenDisplay(nil);
696 if (d == nil) {
697 fprintf(stderr, "Could not open display!\n");
698 return EX_UNAVAILABLE;
701 // get display size
702 // XXX: is getting the default root window dimension correct?
703 XWindowAttributes xwa;
704 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
705 int d_width = xwa.width;
706 int d_height = xwa.height;
708 #ifdef USE_XINERAMA
709 if (XineramaIsActive(d)) {
710 // find the mice
711 int number_of_screens = XScreenCount(d);
712 Window r;
713 Window root;
714 int root_x, root_y, win_x, win_y;
715 unsigned int mask;
716 bool res;
717 for (int i = 0; i < number_of_screens; ++i) {
718 root = XRootWindow(d, i);
719 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
720 if (res) break;
722 if (!res) {
723 fprintf(stderr, "No mouse found.\n");
724 root_x = 0;
725 root_y = 0;
728 // now find in which monitor the mice is on
729 int monitors;
730 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
731 if (info) {
732 for (int i = 0; i < monitors; ++i) {
733 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
734 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
735 offset_x = info[i].x_org;
736 offset_y = info[i].y_org;
737 d_width = info[i].width;
738 d_height = info[i].height;
739 break;
743 XFree(info);
745 #endif
747 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
748 XColor p_fg, p_bg,
749 compl_fg, compl_bg,
750 compl_highlighted_fg, compl_highlighted_bg;
752 bool horizontal_layout = true;
754 // read resource
755 XrmInitialize();
756 char *xrm = XResourceManagerString(d);
757 XrmDatabase xdb = nil;
758 if (xrm != nil) {
759 xdb = XrmGetStringDatabase(xrm);
760 XrmValue value;
761 char *datatype[20];
763 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
764 fontname = strdup(value.addr);
765 check_allocation(fontname);
767 else
768 fprintf(stderr, "no font defined, using %s\n", fontname);
770 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
771 char *v = strdup(value.addr);
772 check_allocation(v);
773 horizontal_layout = !strcmp(v, "horizontal");
774 free(v);
776 else
777 fprintf(stderr, "no layout defined, using horizontal\n");
779 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
780 free(ps1);
781 ps1 = normalize_str(value.addr);
782 } else
783 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
785 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
786 width = parse_int_with_percentage(value.addr, width, d_width);
787 else
788 fprintf(stderr, "no width defined, using %d\n", width);
790 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
791 height = parse_int_with_percentage(value.addr, height, d_height);
792 else
793 fprintf(stderr, "no height defined, using %d\n", height);
795 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
796 x = parse_int_with_middle(value.addr, x, d_width, width);
797 else
798 fprintf(stderr, "no x defined, using %d\n", x);
800 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
801 y = parse_int_with_middle(value.addr, y, d_height, height);
802 else
803 fprintf(stderr, "no y defined, using %d\n", y);
805 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
806 padding = parse_integer(value.addr, padding);
807 else
808 fprintf(stderr, "no y defined, using %d\n", padding);
810 XColor tmp;
811 // TODO: tmp needs to be free'd after every allocation?
813 // prompt
814 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
815 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
816 else
817 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
819 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
820 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
821 else
822 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
824 // completion
825 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
826 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
827 else
828 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
830 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
831 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
832 else
833 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
835 // completion highlighted
836 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
837 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
838 else
839 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
841 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
842 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
843 else
844 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
845 } else {
846 XColor tmp;
847 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
848 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
849 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
850 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
851 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
852 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
855 // load the font
856 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
857 /* if (font == nil) { */
858 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
859 /* font = XLoadQueryFont(d, "fixed"); */
860 /* } */
861 // load the font
862 #ifdef USE_XFT
863 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
864 #else
865 char **missing_charset_list;
866 int missing_charset_count;
867 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
868 if (font == nil) {
869 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
870 return EX_UNAVAILABLE;
872 #endif
874 // create the window
875 XSetWindowAttributes attr;
876 attr.override_redirect = true;
878 Window w = XCreateWindow(d, // display
879 DefaultRootWindow(d), // parent
880 x + offset_x, y + offset_y, // x y
881 width, height, // w h
882 0, // border width
883 DefaultDepth(d, DefaultScreen(d)), // depth
884 InputOutput, // class
885 DefaultVisual(d, DefaultScreen(d)), // visual
886 CWOverrideRedirect, // value mask
887 &attr);
889 set_win_atoms_hints(d, w, width, height);
891 // we want some events
892 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
894 // make the window appear on the screen
895 XMapWindow(d, w);
897 // wait for the MapNotify event (i.e. the event "window rendered")
898 for (;;) {
899 XEvent e;
900 XNextEvent(d, &e);
901 if (e.type == MapNotify)
902 break;
905 // get the *real* width & height after the window was rendered
906 get_wh(d, &w, &width, &height);
908 // grab keyboard
909 take_keyboard(d, w);
911 // Create some graphics contexts
912 XGCValues values;
913 /* values.font = font->fid; */
915 struct rendering r = {
916 .d = d,
917 .w = w,
918 #ifdef USE_XFT
919 .font = font,
920 #else
921 .font = &font,
922 #endif
923 .prompt = XCreateGC(d, w, 0, &values),
924 .prompt_bg = XCreateGC(d, w, 0, &values),
925 .completion = XCreateGC(d, w, 0, &values),
926 .completion_bg = XCreateGC(d, w, 0, &values),
927 .completion_highlighted = XCreateGC(d, w, 0, &values),
928 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
929 .width = width,
930 .height = height,
931 .padding = padding,
932 .horizontal_layout = horizontal_layout,
933 .ps1 = ps1,
934 .ps1len = strlen(ps1)
935 };
937 #ifdef USE_XFT
938 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
940 // prompt
941 XRenderColor xrcolor;
942 xrcolor.red = p_fg.red;
943 xrcolor.green = p_fg.red;
944 xrcolor.blue = p_fg.red;
945 xrcolor.alpha = 65535;
946 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
948 // completion
949 xrcolor.red = compl_fg.red;
950 xrcolor.green = compl_fg.green;
951 xrcolor.blue = compl_fg.blue;
952 xrcolor.alpha = 65535;
953 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
955 // completion highlighted
956 xrcolor.red = compl_highlighted_fg.red;
957 xrcolor.green = compl_highlighted_fg.green;
958 xrcolor.blue = compl_highlighted_fg.blue;
959 xrcolor.alpha = 65535;
960 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
961 #endif
963 // load the colors in our GCs
964 XSetForeground(d, r.prompt, p_fg.pixel);
965 XSetForeground(d, r.prompt_bg, p_bg.pixel);
966 XSetForeground(d, r.completion, compl_fg.pixel);
967 XSetForeground(d, r.completion_bg, compl_bg.pixel);
968 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
969 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
971 // open the X input method
972 XIM xim = XOpenIM(d, xdb, resname, resclass);
973 check_allocation(xim);
975 XIMStyles *xis = nil;
976 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
977 fprintf(stderr, "Input Styles could not be retrieved\n");
978 return EX_UNAVAILABLE;
981 XIMStyle bestMatchStyle = 0;
982 for (int i = 0; i < xis->count_styles; ++i) {
983 XIMStyle ts = xis->supported_styles[i];
984 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
985 bestMatchStyle = ts;
986 break;
989 XFree(xis);
991 if (!bestMatchStyle) {
992 fprintf(stderr, "No matching input style could be determined\n");
995 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
996 check_allocation(xic);
998 // draw the window for the first time
999 draw(&r, text, cs);
1001 // main loop
1002 while (status == LOOPING) {
1003 XEvent e;
1004 XNextEvent(d, &e);
1006 if (XFilterEvent(&e, w))
1007 continue;
1009 switch (e.type) {
1010 case KeymapNotify:
1011 XRefreshKeyboardMapping(&e.xmapping);
1012 break;
1014 case KeyPress: {
1015 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1017 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
1018 bool shift = (ev->state & ShiftMask);
1019 complete(cs, nothing_selected, shift, text, textlen, status);
1020 draw(&r, text, cs);
1021 break;
1024 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
1025 nothing_selected = true;
1026 popc(text, textlen);
1027 update_completions(cs, text, lines);
1028 draw(&r, text, cs);
1029 break;
1032 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1033 status = OK;
1034 break;
1037 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1038 status = ERR;
1039 break;
1042 // try to read what the user pressed
1043 int symbol = 0;
1044 Status s = 0;
1045 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1047 if (s == XBufferOverflow) {
1048 // should not happen since there are no utf-8 characters
1049 // larger than 24bits, but is something to be aware of when
1050 // used to directly write to a string buffer
1051 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1052 break;
1054 char *str = (char*)&symbol;
1056 if (ev->state & ControlMask) {
1057 // check for some key bindings
1058 if (!strcmp(str, "")) { // C-u
1059 nothing_selected = true;
1060 for (int i = 0; i < textlen; ++i)
1061 text[i] = 0;
1062 update_completions(cs, text, lines);
1064 if (!strcmp(str, "")) { // C-h
1065 nothing_selected = true;
1066 popc(text, textlen);
1067 update_completions(cs, text, lines);
1069 if (!strcmp(str, "")) { // C-w
1070 nothing_selected = true;
1072 // `textlen` is the length of the allocated string, not the
1073 // length of the ACTUAL string
1074 int p = strlen(text) - 1;
1075 if (p >= 0) { // delete the current char
1076 text[p] = 0;
1077 p--;
1079 while (p >= 0 && isalnum(text[p])) {
1080 text[p] = 0;
1081 p--;
1083 // erase also trailing white space
1084 while (p >= 0 && isspace(text[p])) {
1085 text[p] = 0;
1086 p--;
1088 update_completions(cs, text, lines);
1090 if (!strcmp(str, "\r")) { // C-m
1091 status = OK;
1093 if (!strcmp(str, "")) {
1094 complete(cs, nothing_selected, true, text, textlen, status);
1096 if (!strcmp(str, "")) {
1097 complete(cs, nothing_selected, false, text, textlen, status);
1099 draw(&r, text, cs);
1100 break;
1103 int str_len = strlen(str);
1104 for (int i = 0; i < str_len; ++i) {
1105 textlen = pushc(&text, textlen, str[i]);
1106 if (textlen == -1) {
1107 fprintf(stderr, "Memory allocation error\n");
1108 status = ERR;
1109 break;
1111 nothing_selected = true;
1112 update_completions(cs, text, lines);
1116 draw(&r, text, cs);
1117 break;
1119 default:
1120 fprintf(stderr, "Unknown event %d\n", e.type);
1124 release_keyboard(d);
1126 if (status == OK)
1127 printf("%s\n", text);
1129 for (int i = 0; i < nlines; ++i) {
1130 free(lines[i]);
1133 #ifdef USE_XFT
1134 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1135 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1136 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1137 #endif
1139 free(ps1);
1140 free(fontname);
1141 free(text);
1142 free(lines);
1143 compl_delete(cs);
1145 XDestroyWindow(d, w);
1146 XCloseDisplay(d);
1148 return status == OK ? 0 : 1;