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 INITIAL_ITEMS 64
52 #define cannot_allocate_memory { \
53 fprintf(stderr, "Could not allocate memory\n"); \
54 abort(); \
55 }
57 #define check_allocation(a) { \
58 if (a == nil) \
59 cannot_allocate_memory; \
60 }
62 enum state {LOOPING, OK, ERR};
64 enum text_type {PROMPT, COMPL, COMPL_HIGH};
66 struct rendering {
67 Display *d;
68 Window w;
69 GC prompt;
70 GC prompt_bg;
71 GC completion;
72 GC completion_bg;
73 GC completion_highlighted;
74 GC completion_highlighted_bg;
75 #ifdef USE_XFT
76 XftDraw *xftdraw;
77 XftColor xft_prompt;
78 XftColor xft_completion;
79 XftColor xft_completion_highlighted;
80 XftFont *font;
81 #else
82 XFontSet *font;
83 #endif
84 int width;
85 int height;
86 bool horizontal_layout;
87 char *ps1;
88 int ps1len;
89 };
91 struct completions {
92 char *completion;
93 bool selected;
94 struct completions *next;
95 };
97 struct completions *compl_new() {
98 struct completions *c = malloc(sizeof(struct completions));
100 if (c == nil)
101 return c;
103 c->completion = nil;
104 c->selected = false;
105 c->next = nil;
106 return c;
109 void compl_delete(struct completions *c) {
110 free(c);
113 struct completions *compl_select_next(struct completions *c, bool n) {
114 if (c == nil)
115 return nil;
116 if (n) {
117 c->selected = true;
118 return c;
121 struct completions *orig = c;
122 while (c != nil) {
123 if (c->selected) {
124 c->selected = false;
125 if (c->next != nil) {
126 // the current one is selected and the next one exists
127 c->next->selected = true;
128 return c->next;
129 } else {
130 // the current one is selected and the next one is nill,
131 // select the first one
132 orig->selected = true;
133 return orig;
136 c = c->next;
138 return nil;
141 struct completions *compl_select_prev(struct completions *c, bool n) {
142 if (c == nil)
143 return nil;
145 struct completions *cc = c;
147 if (n) // select the last one
148 while (cc != nil) {
149 if (cc->next == nil) {
150 cc->selected = true;
151 return cc;
153 cc = cc->next;
155 else // select the previous one
156 while (cc != nil) {
157 if (cc->next != nil && cc->next->selected) {
158 cc->next->selected = false;
159 cc->selected = true;
160 return cc;
162 cc = cc->next;
165 return nil;
168 struct completions *filter(char *text, char **lines) {
169 int i = 0;
170 struct completions *root = compl_new();
171 struct completions *c = root;
173 for (;;) {
174 char *l = lines[i];
175 if (l == nil)
176 break;
178 if (strcasestr(l, text) != nil) {
179 c->next = compl_new();
180 c = c->next;
181 c->completion = l;
184 ++i;
187 struct completions *r = root->next;
188 compl_delete(root);
189 return r;
192 // push the character c at the end of the string pointed by p
193 int pushc(char **p, int maxlen, char c) {
194 int len = strnlen(*p, maxlen);
196 if (!(len < maxlen -2)) {
197 maxlen += maxlen >> 1;
198 char *newptr = realloc(*p, maxlen);
199 if (newptr == nil) { // bad!
200 return -1;
202 *p = newptr;
205 (*p)[len] = c;
206 (*p)[len+1] = '\0';
207 return maxlen;
210 int utf8strnlen(char *s, int maxlen) {
211 int len = 0;
212 while (*s && maxlen > 0) {
213 len += (*s++ & 0xc0) != 0x80;
214 maxlen--;
216 return len;
219 // remove the last *glyph* from the *utf8* string!
220 // this is different from just setting the last byte to 0 (in some
221 // cases ofc). The actual implementation is quite inefficient because
222 // it remove the last char until the number of glyphs doesn't change
223 void popc(char *p, int maxlen) {
224 int len = strnlen(p, maxlen);
226 if (len == 0)
227 return;
229 int ulen = utf8strnlen(p, maxlen);
230 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
231 len--;
232 p[len] = 0;
236 // If the string is surrounded by quotes (`"`) remove them and replace
237 // every `\"` in the string with `"`
238 char *normalize_str(const char *str) {
239 int len = strlen(str);
240 if (len == 0)
241 return nil;
243 char *s = calloc(len, sizeof(char));
244 check_allocation(s);
245 int p = 0;
246 while (*str) {
247 char c = *str;
248 if (*str == '\\') {
249 if (*(str + 1)) {
250 s[p] = *(str + 1);
251 p++;
252 str += 2; // skip this and the next char
253 continue;
254 } else {
255 break;
258 if (c == '"') {
259 str++; // skip only this char
260 continue;
262 s[p] = c;
263 p++;
264 str++;
266 return s;
269 // read an arbitrary long line from stdin and return a pointer to it
270 // TODO: resize the allocated memory to exactly fit the string once
271 // read?
272 char *readline(bool *eof) {
273 int maxlen = 8;
274 char *str = calloc(maxlen, sizeof(char));
275 if (str == nil) {
276 fprintf(stderr, "Cannot allocate memory!\n");
277 exit(EX_UNAVAILABLE);
280 int c;
281 while((c = getchar()) != EOF) {
282 if (c == '\n')
283 return str;
284 else
285 maxlen = pushc(&str, maxlen, c);
287 if (maxlen == -1) {
288 fprintf(stderr, "Cannot allocate memory!\n");
289 exit(EX_UNAVAILABLE);
292 *eof = true;
293 return str;
296 int readlines (char ***lns, int items) {
297 bool finished = false;
298 int n = 0;
299 char **lines = *lns;
300 while (true) {
301 lines[n] = readline(&finished);
303 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
304 free(lines[n]);
305 --n; // forget about this line
308 if (finished)
309 break;
311 ++n;
313 if (n == items - 1) {
314 items += items >>1;
315 char **l = realloc(lines, sizeof(char*) * items);
316 check_allocation(l);
317 *lns = l;
318 lines = l;
322 n++;
323 lines[n] = nil;
324 return items;
327 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
328 int height;
329 int width;
330 #ifdef USE_XFT
331 XGlyphInfo gi;
332 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
333 height = (r->font->ascent - r->font->descent)/2;
334 width = gi.width - gi.x;
335 #else
336 XRectangle rect;
337 XmbTextExtents(*r->font, str, len, nil, &rect);
338 height = rect.height;
339 width = rect.width;
340 #endif
341 if (ret_width != nil) *ret_width = width;
342 if (ret_height != nil) *ret_height = height;
343 return width;
346 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
347 #ifdef USE_XFT
348 XftColor xftcolor;
349 if (tt == PROMPT) xftcolor = r->xft_prompt;
350 if (tt == COMPL) xftcolor = r->xft_completion;
351 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
353 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
354 #else
355 GC gc;
356 if (tt == PROMPT) gc = r->prompt;
357 if (tt == COMPL) gc = r->completion;
358 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
359 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
360 #endif
363 char *strdupn(char *str) {
364 int len = strlen(str);
366 if (str == nil || len == 0)
367 return nil;
369 char *dup = strdup(str);
370 if (dup == nil)
371 return nil;
373 for (int i = 0; i < len; ++i)
374 if (dup[i] == ' ')
375 dup[i] = 'n';
377 return dup;
380 // |------------------|----------------------------------------------|
381 // | 20 char text | completion | completion | completion | compl |
382 // |------------------|----------------------------------------------|
383 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
384 // TODO: make these dynamic?
385 int prompt_width = 20; // char
386 int padding = 10;
388 int width, height;
389 char *ps1_dup = strdupn(r->ps1);
390 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
391 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
392 free(ps1_dup);
393 int start_at = ps1xlen;
395 start_at = text_extents("n", 1, r, nil, nil);
396 start_at = start_at * prompt_width + padding;
398 int texty = (height + r->height) >>1;
400 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
402 int text_len = strlen(text);
403 if (text_len > prompt_width)
404 text = text + (text_len - prompt_width);
405 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
406 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
408 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
410 while (cs != nil) {
411 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
412 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
414 int len = strlen(cs->completion);
415 int text_width = text_extents(cs->completion, len, r, nil, nil);
417 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
419 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
421 start_at += text_width + padding * 2;
423 if (start_at > r->width)
424 break; // don't draw completion if the space isn't enough
426 cs = cs->next;
429 XFlush(r->d);
432 // |-----------------------------------------------------------------|
433 // | prompt |
434 // |-----------------------------------------------------------------|
435 // | completion |
436 // |-----------------------------------------------------------------|
437 // | completion |
438 // |-----------------------------------------------------------------|
439 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
440 // should be padding and not padding*2, but the text doesn't seem to
441 // be vertically centered otherwise....
442 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
443 int padding = 10; // TODO make this dynamic
445 int height, width;
446 text_extents("fjpgl", 5, r, &width, &height);
447 int start_at = height + padding*2;
449 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
450 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
452 char *ps1_dup = strdupn(r->ps1);
453 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
454 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
455 free(ps1_dup);
457 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
458 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
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 text_extents(cs->completion, len, r, &width, &height);
466 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
467 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
469 start_at += height + padding *2;
471 if (start_at > r->height)
472 break; // don't draw completion if the space isn't enough
474 cs = cs->next;
477 XFlush(r->d);
480 void draw(struct rendering *r, char *text, struct completions *cs) {
481 if (r->horizontal_layout)
482 draw_horizontally(r, text, cs);
483 else
484 draw_vertically(r, text, cs);
487 /* Set some WM stuff */
488 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
489 Atom type;
490 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
491 XChangeProperty(
492 d,
493 w,
494 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
495 XInternAtom(d, "ATOM", false),
496 32,
497 PropModeReplace,
498 (unsigned char *)&type,
500 );
502 /* some window managers honor this properties */
503 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
504 XChangeProperty(d,
505 w,
506 XInternAtom(d, "_NET_WM_STATE", false),
507 XInternAtom(d, "ATOM", false),
508 32,
509 PropModeReplace,
510 (unsigned char *)&type,
512 );
514 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
515 XChangeProperty(d,
516 w,
517 XInternAtom(d, "_NET_WM_STATE", false),
518 XInternAtom(d, "ATOM", false),
519 32,
520 PropModeAppend,
521 (unsigned char *)&type,
523 );
525 // setting window hints
526 XClassHint *class_hint = XAllocClassHint();
527 if (class_hint == nil) {
528 fprintf(stderr, "Could not allocate memory for class hint\n");
529 exit(EX_UNAVAILABLE);
531 class_hint->res_name = resname;
532 class_hint->res_class = resclass;
533 XSetClassHint(d, w, class_hint);
534 XFree(class_hint);
536 XSizeHints *size_hint = XAllocSizeHints();
537 if (size_hint == nil) {
538 fprintf(stderr, "Could not allocate memory for size hint\n");
539 exit(EX_UNAVAILABLE);
541 size_hint->flags = PMinSize | PBaseSize;
542 size_hint->min_width = width;
543 size_hint->base_width = width;
544 size_hint->min_height = height;
545 size_hint->base_height = height;
547 XFlush(d);
550 void get_wh(Display *d, Window *w, int *width, int *height) {
551 XWindowAttributes win_attr;
552 XGetWindowAttributes(d, *w, &win_attr);
553 *height = win_attr.height;
554 *width = win_attr.width;
557 // I know this may seem a little hackish BUT is the only way I managed
558 // to actually grab that goddam keyboard. Only one call to
559 // XGrabKeyboard does not always end up with the keyboard grabbed!
560 int take_keyboard(Display *d, Window w) {
561 int i;
562 for (i = 0; i < 100; i++) {
563 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
564 return 1;
565 usleep(1000);
567 return 0;
570 void release_keyboard(Display *d) {
571 XUngrabKeyboard(d, CurrentTime);
574 int parse_integer(const char *str, int default_value, int max) {
575 int len = strlen(str);
576 if (len > 0 && str[len-1] == '%') {
577 char *cpy = strdup(str);
578 check_allocation(cpy);
579 cpy[len-1] = '\0';
580 int val = parse_integer(cpy, default_value, max);
581 free(cpy);
582 return val * max / 100;
585 errno = 0;
586 char *ep;
587 long lval = strtol(str, &ep, 10);
588 if (str[0] == '\0' || *ep != '\0') { // NaN
589 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
590 return default_value;
592 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
593 (lval > INT_MAX || lval < INT_MIN)) {
594 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
595 return default_value;
597 return lval;
600 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
601 if (!strcmp(str, "middle")) {
602 return (max - self)/2;
604 return parse_integer(str, default_value, max);
607 int main() {
608 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
609 int nlines = readlines(&lines, INITIAL_ITEMS);
611 setlocale(LC_ALL, getenv("LANG"));
613 enum state status = LOOPING;
615 // where the monitor start (used only with xinerama)
616 int offset_x = 0;
617 int offset_y = 0;
619 // width and height of the window
620 int width = 400;
621 int height = 20;
623 // position on the screen
624 int x = 0;
625 int y = 0;
627 char *ps1 = strdup("$ ");
628 check_allocation(ps1);
630 char *fontname = strdup(default_fontname);
631 check_allocation(fontname);
633 int textlen = 10;
634 char *text = malloc(textlen * sizeof(char));
635 check_allocation(text);
637 struct completions *cs = filter(text, lines);
638 bool nothing_selected = true;
640 // start talking to xorg
641 Display *d = XOpenDisplay(nil);
642 if (d == nil) {
643 fprintf(stderr, "Could not open display!\n");
644 return EX_UNAVAILABLE;
647 // get display size
648 // XXX: is getting the default root window dimension correct?
649 XWindowAttributes xwa;
650 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
651 int d_width = xwa.width;
652 int d_height = xwa.height;
654 #ifdef USE_XINERAMA
655 if (XineramaIsActive(d)) {
656 // find the mice
657 int number_of_screens = XScreenCount(d);
658 bool result;
659 Window r;
660 Window root;
661 int root_x, root_y, win_x, win_y;
662 unsigned int mask;
663 bool res;
664 for (int i = 0; i < number_of_screens; ++i) {
665 root = XRootWindow(d, i);
666 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
667 if (res) break;
669 if (!res) {
670 fprintf(stderr, "No mouse found.\n");
671 root_x = 0;
672 root_y = 0;
675 // now find in which monitor the mice is on
676 int monitors;
677 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
678 if (info) {
679 for (int i = 0; i < monitors; ++i) {
680 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
681 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
682 offset_x = info[i].x_org;
683 offset_y = info[i].y_org;
684 d_width = info[i].width;
685 d_height = info[i].height;
686 break;
690 XFree(info);
692 #endif
694 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
695 XColor p_fg, p_bg,
696 compl_fg, compl_bg,
697 compl_highlighted_fg, compl_highlighted_bg;
699 bool horizontal_layout = true;
701 // read resource
702 XrmInitialize();
703 char *xrm = XResourceManagerString(d);
704 XrmDatabase xdb = nil;
705 if (xrm != nil) {
706 xdb = XrmGetStringDatabase(xrm);
707 XrmValue value;
708 char *datatype[20];
710 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
711 fontname = strdup(value.addr);
712 check_allocation(fontname);
714 else
715 fprintf(stderr, "no font defined, using %s\n", fontname);
717 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
718 char *v = strdup(value.addr);
719 check_allocation(v);
720 horizontal_layout = !strcmp(v, "horizontal");
721 free(v);
723 else
724 fprintf(stderr, "no layout defined, using horizontal\n");
726 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
727 free(ps1);
728 ps1 = normalize_str(value.addr);
729 } else
730 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
732 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
733 width = parse_integer(value.addr, width, d_width);
734 else
735 fprintf(stderr, "no width defined, using %d\n", width);
737 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
738 height = parse_integer(value.addr, height, d_height);
739 else
740 fprintf(stderr, "no height defined, using %d\n", height);
742 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
743 x = parse_int_with_middle(value.addr, x, d_width, width);
744 else
745 fprintf(stderr, "no x defined, using %d\n", width);
747 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
748 y = parse_int_with_middle(value.addr, y, d_height, height);
749 else
750 fprintf(stderr, "no y defined, using %d\n", height);
752 XColor tmp;
753 // TODO: tmp needs to be free'd after every allocation?
755 // prompt
756 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
757 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
758 else
759 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
761 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
762 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
763 else
764 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
766 // completion
767 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
768 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
769 else
770 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
772 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
773 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
774 else
775 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
777 // completion highlighted
778 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
779 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
780 else
781 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
783 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
784 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
785 else
786 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
787 } else {
788 XColor tmp;
789 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
790 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
791 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
792 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
793 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
794 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
797 // load the font
798 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
799 /* if (font == nil) { */
800 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
801 /* font = XLoadQueryFont(d, "fixed"); */
802 /* } */
803 // load the font
804 #ifdef USE_XFT
805 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
806 #else
807 char **missing_charset_list;
808 int missing_charset_count;
809 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
810 if (font == nil) {
811 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
812 return EX_UNAVAILABLE;
814 #endif
816 // create the window
817 XSetWindowAttributes attr;
818 attr.override_redirect = true;
820 Window w = XCreateWindow(d, // display
821 DefaultRootWindow(d), // parent
822 x + offset_x, y + offset_y, // x y
823 width, height, // w h
824 0, // border width
825 DefaultDepth(d, DefaultScreen(d)), // depth
826 InputOutput, // class
827 DefaultVisual(d, DefaultScreen(d)), // visual
828 CWOverrideRedirect, // value mask
829 &attr);
831 set_win_atoms_hints(d, w, width, height);
833 // we want some events
834 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
836 // make the window appear on the screen
837 XMapWindow(d, w);
839 // wait for the MapNotify event (i.e. the event "window rendered")
840 for (;;) {
841 XEvent e;
842 XNextEvent(d, &e);
843 if (e.type == MapNotify)
844 break;
847 // get the *real* width & height after the window was rendered
848 get_wh(d, &w, &width, &height);
850 // grab keyboard
851 take_keyboard(d, w);
853 // Create some graphics contexts
854 XGCValues values;
855 /* values.font = font->fid; */
857 struct rendering r = {
858 .d = d,
859 .w = w,
860 #ifdef USE_XFT
861 .font = font,
862 #else
863 .font = &font,
864 #endif
865 .prompt = XCreateGC(d, w, 0, &values),
866 .prompt_bg = XCreateGC(d, w, 0, &values),
867 .completion = XCreateGC(d, w, 0, &values),
868 .completion_bg = XCreateGC(d, w, 0, &values),
869 .completion_highlighted = XCreateGC(d, w, 0, &values),
870 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
871 .width = width,
872 .height = height,
873 .horizontal_layout = horizontal_layout,
874 .ps1 = ps1,
875 .ps1len = strlen(ps1)
876 };
878 #ifdef USE_XFT
879 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
881 // prompt
882 XRenderColor xrcolor;
883 xrcolor.red = p_fg.red;
884 xrcolor.green = p_fg.red;
885 xrcolor.blue = p_fg.red;
886 xrcolor.alpha = 65535;
887 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
889 // completion
890 xrcolor.red = compl_fg.red;
891 xrcolor.green = compl_fg.green;
892 xrcolor.blue = compl_fg.blue;
893 xrcolor.alpha = 65535;
894 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
896 // completion highlighted
897 xrcolor.red = compl_highlighted_fg.red;
898 xrcolor.green = compl_highlighted_fg.green;
899 xrcolor.blue = compl_highlighted_fg.blue;
900 xrcolor.alpha = 65535;
901 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
902 #endif
904 // load the colors in our GCs
905 XSetForeground(d, r.prompt, p_fg.pixel);
906 XSetForeground(d, r.prompt_bg, p_bg.pixel);
907 XSetForeground(d, r.completion, compl_fg.pixel);
908 XSetForeground(d, r.completion_bg, compl_bg.pixel);
909 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
910 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
912 // open the X input method
913 XIM xim = XOpenIM(d, xdb, resname, resclass);
914 check_allocation(xim);
916 XIMStyles *xis = nil;
917 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
918 fprintf(stderr, "Input Styles could not be retrieved\n");
919 return EX_UNAVAILABLE;
922 XIMStyle bestMatchStyle = 0;
923 for (int i = 0; i < xis->count_styles; ++i) {
924 XIMStyle ts = xis->supported_styles[i];
925 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
926 bestMatchStyle = ts;
927 break;
930 XFree(xis);
932 if (!bestMatchStyle) {
933 fprintf(stderr, "No matching input style could be determined\n");
936 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
937 check_allocation(xic);
939 // draw the window for the first time
940 draw(&r, text, cs);
942 // main loop
943 while (status == LOOPING) {
944 XEvent e;
945 XNextEvent(d, &e);
947 if (XFilterEvent(&e, w))
948 continue;
950 switch (e.type) {
951 case KeymapNotify:
952 XRefreshKeyboardMapping(&e.xmapping);
953 break;
955 case KeyPress: {
956 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
958 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
959 bool shift = (ev->state & ShiftMask);
960 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
961 : compl_select_next(cs, nothing_selected);
962 if (n != nil) {
963 nothing_selected = false;
964 free(text);
965 text = strdup(n->completion);
966 if (text == nil) {
967 fprintf(stderr, "Memory allocation error!\n");
968 status = ERR;
969 break;
971 textlen = strlen(text);
973 draw(&r, text, cs);
974 break;
977 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
978 nothing_selected = true;
979 popc(text, textlen);
980 update_completions(cs, text, lines);
981 draw(&r, text, cs);
982 break;
985 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
986 status = OK;
987 break;
990 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
991 status = ERR;
992 break;
995 // try to read what the user pressed
996 int symbol = 0;
997 Status s = 0;
998 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1000 if (s == XBufferOverflow) {
1001 // should not happen since there are no utf-8 characters
1002 // larger than 24bits, but is something to be aware of when
1003 // used to directly write to a string buffer
1004 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1005 break;
1007 char *str = (char*)&symbol;
1009 if (ev->state & ControlMask) {
1010 // check for some key bindings
1011 if (!strcmp(str, "")) { // C-u
1012 nothing_selected = true;
1013 for (int i = 0; i < textlen; ++i)
1014 text[i] = 0;
1015 update_completions(cs, text, lines);
1017 if (!strcmp(str, "")) { // C-h
1018 nothing_selected = true;
1019 popc(text, textlen);
1020 update_completions(cs, text, lines);
1022 if (!strcmp(str, "")) { // C-w
1023 nothing_selected = true;
1025 // `textlen` is the length of the allocated string, not the
1026 // length of the ACTUAL string
1027 int p = strlen(text) - 1;
1028 if (p >= 0) { // delete the current char
1029 text[p] = 0;
1030 p--;
1032 while (p >= 0 && isalnum(text[p])) {
1033 text[p] = 0;
1034 p--;
1036 // erase also trailing white space
1037 while (p >= 0 && isspace(text[p])) {
1038 text[p] = 0;
1039 p--;
1041 update_completions(cs, text, lines);
1043 if (!strcmp(str, "\r")) { // C-m
1044 status = OK;
1046 draw(&r, text, cs);
1047 break;
1050 int str_len = strlen(str);
1051 for (int i = 0; i < str_len; ++i) {
1052 textlen = pushc(&text, textlen, str[i]);
1053 if (textlen == -1) {
1054 fprintf(stderr, "Memory allocation error\n");
1055 status = ERR;
1056 break;
1058 nothing_selected = true;
1059 update_completions(cs, text, lines);
1063 draw(&r, text, cs);
1064 break;
1066 default:
1067 fprintf(stderr, "Unknown event %d\n", e.type);
1071 release_keyboard(d);
1073 if (status == OK)
1074 printf("%s\n", text);
1076 for (int i = 0; i < nlines; ++i) {
1077 free(lines[i]);
1080 #ifdef USE_XFT
1081 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1082 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1083 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1084 #endif
1086 free(ps1);
1087 free(fontname);
1088 free(text);
1089 free(lines);
1090 compl_delete(cs);
1092 XDestroyWindow(d, w);
1093 XCloseDisplay(d);
1095 return status == OK ? 0 : 1;