Blob


1 /* mymenu -- simple dmenu alternative */
3 /* Copyright (C) 2018 Omar Polo <omar.polo@europecom.net>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h> // strdup, strnlen, ...
22 #include <ctype.h> // isalnum
23 #include <locale.h> // setlocale
24 #include <unistd.h>
25 #include <sysexits.h>
26 #include <stdbool.h>
27 #include <limits.h>
28 #include <errno.h>
30 #include <X11/Xlib.h>
31 #include <X11/Xutil.h> // XLookupString
32 #include <X11/Xresource.h>
33 #include <X11/Xcms.h> // colors
34 #include <X11/keysym.h>
36 #ifdef USE_XINERAMA
37 # include <X11/extensions/Xinerama.h>
38 #endif
40 #ifdef USE_XFT
41 # include <X11/Xft/Xft.h>
42 #endif
44 #define nil NULL
45 #define resname "MyMenu"
46 #define resclass "mymenu"
48 #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define OVERLAP(a,b,c,d) (((a)==(c) && (b)==(d)) || MIN((a)+(b), (c)+(d)) - MAX((a), (c)) > 0)
51 #define INTERSECT(x,y,w,h,x1,y1,w1,h1) (OVERLAP((x),(w),(x1),(w1)) && OVERLAP((y),(h),(y1),(h1)))
53 #define update_completions(cs, text, lines) { \
54 compl_delete(cs); \
55 cs = filter(text, lines); \
56 }
58 // TODO: dynamic?
59 #define INITIAL_ITEMS 64
61 #define TODO(s) { \
62 fprintf(stderr, "TODO! " s "\n"); \
63 }
65 #define cannot_allocate_memory { \
66 fprintf(stderr, "Could not allocate memory\n"); \
67 exit(EX_UNAVAILABLE); \
68 }
70 #define check_allocation(a) { \
71 if (a == nil) \
72 cannot_allocate_memory; \
73 }
75 enum state {LOOPING, OK, ERR};
77 enum text_type {PROMPT, COMPL, COMPL_HIGH};
79 struct rendering {
80 Display *d;
81 Window w;
82 GC prompt;
83 GC prompt_bg;
84 GC completion;
85 GC completion_bg;
86 GC completion_highlighted;
87 GC completion_highlighted_bg;
88 #ifdef USE_XFT
89 XftDraw *xftdraw;
90 XftColor xft_prompt;
91 XftColor xft_completion;
92 XftColor xft_completion_highlighted;
93 XftFont *font;
94 #else
95 XFontSet *font;
96 #endif
97 int width;
98 int height;
99 bool horizontal_layout;
100 char *ps1;
101 int ps1len;
102 };
104 struct completions {
105 char *completion;
106 bool selected;
107 struct completions *next;
108 };
110 struct completions *compl_new() {
111 struct completions *c = malloc(sizeof(struct completions));
113 if (c == nil)
114 return c;
116 c->completion = nil;
117 c->selected = false;
118 c->next = nil;
119 return c;
122 void compl_delete(struct completions *c) {
123 free(c);
126 struct completions *compl_select_next(struct completions *c, bool n) {
127 if (c == nil)
128 return nil;
129 if (n) {
130 c->selected = true;
131 return c;
134 struct completions *orig = c;
135 while (c != nil) {
136 if (c->selected) {
137 c->selected = false;
138 if (c->next != nil) {
139 // the current one is selected and the next one exists
140 c->next->selected = true;
141 return c->next;
142 } else {
143 // the current one is selected and the next one is nill,
144 // select the first one
145 orig->selected = true;
146 return orig;
149 c = c->next;
151 return nil;
154 struct completions *compl_select_prev(struct completions *c, bool n) {
155 if (c == nil)
156 return nil;
158 struct completions *cc = c;
160 if (n) // select the last one
161 while (cc != nil) {
162 if (cc->next == nil) {
163 cc->selected = true;
164 return cc;
166 cc = cc->next;
168 else // select the previous one
169 while (cc != nil) {
170 if (cc->next != nil && cc->next->selected) {
171 cc->next->selected = false;
172 cc->selected = true;
173 return cc;
175 cc = cc->next;
178 return nil;
181 struct completions *filter(char *text, char **lines) {
182 int i = 0;
183 struct completions *root = compl_new();
184 struct completions *c = root;
186 for (;;) {
187 char *l = lines[i];
188 if (l == nil)
189 break;
191 if (strstr(l, text) != nil) {
192 c->next = compl_new();
193 c = c->next;
194 c->completion = l;
197 ++i;
200 struct completions *r = root->next;
201 compl_delete(root);
202 return r;
205 // push the character c at the end of the string pointed by p
206 int pushc(char **p, int maxlen, char c) {
207 int len = strnlen(*p, maxlen);
209 if (!(len < maxlen -2)) {
210 maxlen += maxlen >> 1;
211 char *newptr = realloc(*p, maxlen);
212 if (newptr == nil) { // bad!
213 return -1;
215 *p = newptr;
218 (*p)[len] = c;
219 (*p)[len+1] = '\0';
220 return maxlen;
223 int utf8strnlen(char *s, int maxlen) {
224 int len = 0;
225 while (*s && maxlen > 0) {
226 len += (*s++ & 0xc0) != 0x80;
227 maxlen--;
229 return len;
232 // remove the last *glyph* from the *utf8* string!
233 // this is different from just setting the last byte to 0 (in some
234 // cases ofc). The actual implementation is quite inefficient because
235 // it remove the last char until the number of glyphs doesn't change
236 void popc(char *p, int maxlen) {
237 int len = strnlen(p, maxlen);
239 if (len == 0)
240 return;
242 int ulen = utf8strnlen(p, maxlen);
243 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
244 len--;
245 p[len] = 0;
249 // If the string is surrounded by quotes (`"`) remove them and replace
250 // every `\"` in the string with `"`
251 char *normalize_str(const char *str) {
252 int len = strlen(str);
253 if (len == 0)
254 return nil;
256 char *s = calloc(len, sizeof(char));
257 check_allocation(s);
258 int p = 0;
259 while (*str) {
260 char c = *str;
261 if (*str == '\\') {
262 if (*(str + 1)) {
263 s[p] = *(str + 1);
264 p++;
265 str += 2; // skip this and the next char
266 continue;
267 } else {
268 break;
271 if (c == '"') {
272 str++; // skip only this char
273 continue;
275 s[p] = c;
276 p++;
277 str++;
279 return s;
282 // read an arbitrary long line from stdin and return a pointer to it
283 // TODO: resize the allocated memory to exactly fit the string once
284 // read?
285 char *readline(bool *eof) {
286 int maxlen = 8;
287 char *str = calloc(maxlen, sizeof(char));
288 if (str == nil) {
289 fprintf(stderr, "Cannot allocate memory!\n");
290 exit(EX_UNAVAILABLE);
293 int c;
294 while((c = getchar()) != EOF) {
295 if (c == '\n')
296 return str;
297 else
298 maxlen = pushc(&str, maxlen, c);
300 if (maxlen == -1) {
301 fprintf(stderr, "Cannot allocate memory!\n");
302 exit(EX_UNAVAILABLE);
305 *eof = true;
306 return str;
309 int readlines (char ***lns, int items) {
310 bool finished = false;
311 int n = 0;
312 char **lines = *lns;
313 while (true) {
314 lines[n] = readline(&finished);
316 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
317 free(lines[n]);
318 --n; // forget about this line
321 if (finished)
322 break;
324 ++n;
326 if (n == items - 1) {
327 items += items >>1;
328 char **l = realloc(lines, sizeof(char*) * items);
329 check_allocation(l);
330 *lns = l;
331 lines = l;
335 n++;
336 lines[n] = nil;
337 return items;
340 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
341 int height;
342 int width;
343 #ifdef USE_XFT
344 XGlyphInfo gi;
345 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
346 height = (r->font->ascent - r->font->descent)/2;
347 width = gi.width - gi.x;
348 #else
349 XRectangle rect;
350 XmbTextExtents(*r->font, str, len, nil, &rect);
351 height = rect.height;
352 width = rect.width;
353 #endif
354 if (ret_width != nil) *ret_width = width;
355 if (ret_height != nil) *ret_height = height;
356 return width;
359 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
360 #ifdef USE_XFT
361 XftColor xftcolor;
362 if (tt == PROMPT) xftcolor = r->xft_prompt;
363 if (tt == COMPL) xftcolor = r->xft_completion;
364 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
366 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
367 #else
368 GC gc;
369 if (tt == PROMPT) gc = r->prompt;
370 if (tt == COMPL) gc = r->completion;
371 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
372 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
373 #endif
376 char *strdupn(char *str) {
377 int len = strlen(str);
379 if (str == nil || len == 0)
380 return nil;
382 char *dup = strdup(str);
383 if (dup == nil)
384 return nil;
386 for (int i = 0; i < len; ++i)
387 if (dup[i] == ' ')
388 dup[i] = 'n';
390 return dup;
393 // |------------------|----------------------------------------------|
394 // | 20 char text | completion | completion | completion | compl |
395 // |------------------|----------------------------------------------|
396 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
397 // TODO: make these dynamic?
398 int prompt_width = 20; // char
399 int padding = 10;
401 int width, height;
402 char *ps1_dup = strdupn(r->ps1);
403 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
404 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
405 free(ps1_dup);
406 int start_at = ps1xlen;
408 start_at = text_extents("n", 1, r, nil, nil);
409 start_at = start_at * prompt_width + padding;
411 int texty = (height + r->height) >>1;
413 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
415 int text_len = strlen(text);
416 if (text_len > prompt_width)
417 text = text + (text_len - prompt_width);
418 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
419 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
421 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
423 while (cs != nil) {
424 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
425 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
427 int len = strlen(cs->completion);
428 int text_width = text_extents(cs->completion, len, r, nil, nil);
430 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
432 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
434 start_at += text_width + padding * 2;
436 if (start_at > r->width)
437 break; // don't draw completion if the space isn't enough
439 cs = cs->next;
442 XFlush(r->d);
445 // |-----------------------------------------------------------------|
446 // | prompt |
447 // |-----------------------------------------------------------------|
448 // | completion |
449 // |-----------------------------------------------------------------|
450 // | completion |
451 // |-----------------------------------------------------------------|
452 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
453 // should be padding and not padding*2, but the text doesn't seem to
454 // be vertically centered otherwise....
455 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
456 int padding = 10; // TODO make this dynamic
458 int height, width;
459 text_extents("fjpgl", 5, r, &width, &height);
460 int start_at = height + padding*2;
462 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
463 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
465 char *ps1_dup = strdupn(r->ps1);
466 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
467 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
468 free(ps1_dup);
470 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
471 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
473 while (cs != nil) {
474 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
475 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
477 int len = strlen(cs->completion);
478 text_extents(cs->completion, len, r, &width, &height);
479 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
480 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
482 start_at += height + padding *2;
484 if (start_at > r->height)
485 break; // don't draw completion if the space isn't enough
487 cs = cs->next;
490 XFlush(r->d);
493 void draw(struct rendering *r, char *text, struct completions *cs) {
494 if (r->horizontal_layout)
495 draw_horizontally(r, text, cs);
496 else
497 draw_vertically(r, text, cs);
500 /* Set some WM stuff */
501 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
502 Atom type;
503 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
504 XChangeProperty(
505 d,
506 w,
507 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
508 XInternAtom(d, "ATOM", false),
509 32,
510 PropModeReplace,
511 (unsigned char *)&type,
513 );
515 /* some window managers honor this properties */
516 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
517 XChangeProperty(d,
518 w,
519 XInternAtom(d, "_NET_WM_STATE", false),
520 XInternAtom(d, "ATOM", false),
521 32,
522 PropModeReplace,
523 (unsigned char *)&type,
525 );
527 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
528 XChangeProperty(d,
529 w,
530 XInternAtom(d, "_NET_WM_STATE", false),
531 XInternAtom(d, "ATOM", false),
532 32,
533 PropModeAppend,
534 (unsigned char *)&type,
536 );
538 // setting window hints
539 XClassHint *class_hint = XAllocClassHint();
540 if (class_hint == nil) {
541 fprintf(stderr, "Could not allocate memory for class hint\n");
542 exit(EX_UNAVAILABLE);
544 class_hint->res_name = "mymenu";
545 class_hint->res_class = "mymenu";
546 XSetClassHint(d, w, class_hint);
547 XFree(class_hint);
549 XSizeHints *size_hint = XAllocSizeHints();
550 if (size_hint == nil) {
551 fprintf(stderr, "Could not allocate memory for size hint\n");
552 exit(EX_UNAVAILABLE);
554 size_hint->min_width = width;
555 size_hint->base_width = width;
556 size_hint->min_height = height;
557 size_hint->base_height = height;
559 XFlush(d);
562 void get_wh(Display *d, Window *w, int *width, int *height) {
563 XWindowAttributes win_attr;
564 XGetWindowAttributes(d, *w, &win_attr);
565 *height = win_attr.height;
566 *width = win_attr.width;
569 // I know this may seem a little hackish BUT is the only way I managed
570 // to actually grab that goddam keyboard. Only one call to
571 // XGrabKeyboard does not always end up with the keyboard grabbed!
572 int take_keyboard(Display *d, Window w) {
573 int i;
574 for (i = 0; i < 100; i++) {
575 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
576 return 1;
577 usleep(1000);
579 return 0;
582 void release_keyboard(Display *d) {
583 XUngrabKeyboard(d, CurrentTime);
586 int parse_integer(const char *str, int default_value, int max) {
587 int len = strlen(str);
588 if (len > 0 && str[len-1] == '%') {
589 char *cpy = strdup(str);
590 check_allocation(cpy);
591 cpy[len-1] = '\0';
592 int val = parse_integer(cpy, default_value, max);
593 free(cpy);
594 return val * max / 100;
597 errno = 0;
598 char *ep;
599 long lval = strtol(str, &ep, 10);
600 if (str[0] == '\0' || *ep != '\0') { // NaN
601 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
602 return default_value;
604 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
605 (lval > INT_MAX || lval < INT_MIN)) {
606 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
607 return default_value;
609 return lval;
612 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
613 if (!strcmp(str, "middle")) {
614 return (max - self)/2;
616 return parse_integer(str, default_value, max);
619 int main() {
620 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
621 int nlines = readlines(&lines, INITIAL_ITEMS);
623 setlocale(LC_ALL, getenv("LANG"));
625 enum state status = LOOPING;
627 // where the monitor start (used only with xinerama)
628 int offset_x = 0;
629 int offset_y = 0;
631 // width and height of the window
632 int width = 400;
633 int height = 20;
635 // position on the screen
636 int x = 0;
637 int y = 0;
639 char *ps1 = strdup("$ ");
640 check_allocation(ps1);
642 char *fontname = strdup("fixed");
643 check_allocation(fontname);
645 int textlen = 10;
646 char *text = malloc(textlen * sizeof(char));
647 check_allocation(text);
649 struct completions *cs = filter(text, lines);
650 bool nothing_selected = true;
652 // start talking to xorg
653 Display *d = XOpenDisplay(nil);
654 if (d == nil) {
655 fprintf(stderr, "Could not open display!\n");
656 return EX_UNAVAILABLE;
659 // get display size
660 // XXX: is getting the default root window dimension correct?
661 XWindowAttributes xwa;
662 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
663 int d_width = xwa.width;
664 int d_height = xwa.height;
666 #ifdef USE_XINERAMA
667 // TODO: this bit still needs to be improved
668 if (XineramaIsActive(d)) {
669 int monitors;
670 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
671 if (info)
672 for (int i = 0; i < monitors; ++i) {
673 if (INTERSECT(x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
674 offset_x = info[x].x_org;
675 offset_y = info[y].y_org;
676 d_width = info[i].width;
677 d_height = info[i].height;
680 XFree(info);
682 #endif
684 /* fprintf(stderr, "offset_x:\t%d\n" */
685 /* "offset_y:\t%d\n" */
686 /* "d_width:\t%d\n" */
687 /* "d_height:\t%d\n" */
688 /* , offset_x, offset_y, d_width, d_height); */
690 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
691 XColor p_fg, p_bg,
692 compl_fg, compl_bg,
693 compl_highlighted_fg, compl_highlighted_bg;
695 bool horizontal_layout = true;
697 // read resource
698 XrmInitialize();
699 char *xrm = XResourceManagerString(d);
700 XrmDatabase xdb = nil;
701 if (xrm != nil) {
702 xdb = XrmGetStringDatabase(xrm);
703 XrmValue value;
704 char *datatype[20];
706 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
707 fontname = strdup(value.addr);
708 check_allocation(fontname);
710 else
711 fprintf(stderr, "no font defined, using %s\n", fontname);
713 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
714 char *v = strdup(value.addr);
715 check_allocation(v);
716 horizontal_layout = !strcmp(v, "horizontal");
717 free(v);
719 else
720 fprintf(stderr, "no layout defined, using horizontal\n");
722 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
723 free(ps1);
724 ps1 = normalize_str(value.addr);
725 } else
726 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
728 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
729 width = parse_integer(value.addr, width, d_width);
730 else
731 fprintf(stderr, "no width defined, using %d\n", width);
733 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
734 height = parse_integer(value.addr, height, d_height);
735 else
736 fprintf(stderr, "no height defined, using %d\n", height);
738 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
739 x = parse_int_with_middle(value.addr, x, d_width, width);
740 else
741 fprintf(stderr, "no x defined, using %d\n", width);
743 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
744 y = parse_int_with_middle(value.addr, y, d_height, height);
745 else
746 fprintf(stderr, "no y defined, using %d\n", height);
748 XColor tmp;
749 // TODO: tmp needs to be free'd after every allocation?
751 // prompt
752 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
753 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
754 else
755 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
757 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
758 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
759 else
760 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
762 // completion
763 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
764 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
765 else
766 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
768 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
769 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
770 else
771 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
773 // completion highlighted
774 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
775 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
776 else
777 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
779 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
780 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
781 else
782 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
783 } else {
784 XColor tmp;
785 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
786 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
787 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
788 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
789 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
790 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
793 // load the font
794 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
795 /* if (font == nil) { */
796 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
797 /* font = XLoadQueryFont(d, "fixed"); */
798 /* } */
799 // load the font
800 #ifdef USE_XFT
801 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
802 #else
803 char **missing_charset_list;
804 int missing_charset_count;
805 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
806 if (font == nil) {
807 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
808 return EX_UNAVAILABLE;
810 #endif
812 // create the window
813 XSetWindowAttributes attr;
815 Window w = XCreateWindow(d, // display
816 DefaultRootWindow(d), // parent
817 x + offset_x, y + offset_y, // x y
818 width, height, // w h
819 0, // border width
820 DefaultDepth(d, DefaultScreen(d)), // depth
821 InputOutput, // class
822 DefaultVisual(d, DefaultScreen(d)), // visual
823 0, // value mask
824 &attr);
826 set_win_atoms_hints(d, w, width, height);
828 // we want some events
829 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
831 // make the window appear on the screen
832 XMapWindow(d, w);
834 // wait for the MapNotify event (i.e. the event "window rendered")
835 for (;;) {
836 XEvent e;
837 XNextEvent(d, &e);
838 if (e.type == MapNotify)
839 break;
842 // get the *real* width & height after the window was rendered
843 get_wh(d, &w, &width, &height);
845 // grab keyboard
846 take_keyboard(d, w);
848 // Create some graphics contexts
849 XGCValues values;
850 /* values.font = font->fid; */
852 struct rendering r = {
853 .d = d,
854 .w = w,
855 #ifdef USE_XFT
856 .font = font,
857 #else
858 .font = &font,
859 #endif
860 .prompt = XCreateGC(d, w, 0, &values),
861 .prompt_bg = XCreateGC(d, w, 0, &values),
862 .completion = XCreateGC(d, w, 0, &values),
863 .completion_bg = XCreateGC(d, w, 0, &values),
864 .completion_highlighted = XCreateGC(d, w, 0, &values),
865 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
866 .width = width,
867 .height = height,
868 .horizontal_layout = horizontal_layout,
869 .ps1 = ps1,
870 .ps1len = strlen(ps1)
871 };
873 #ifdef USE_XFT
874 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
876 // prompt
877 XRenderColor xrcolor;
878 xrcolor.red = p_fg.red;
879 xrcolor.green = p_fg.red;
880 xrcolor.blue = p_fg.red;
881 xrcolor.alpha = 65535;
882 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
884 // completion
885 xrcolor.red = compl_fg.red;
886 xrcolor.green = compl_fg.green;
887 xrcolor.blue = compl_fg.blue;
888 xrcolor.alpha = 65535;
889 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
891 // completion highlighted
892 xrcolor.red = compl_highlighted_fg.red;
893 xrcolor.green = compl_highlighted_fg.green;
894 xrcolor.blue = compl_highlighted_fg.blue;
895 xrcolor.alpha = 65535;
896 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
897 #endif
899 // load the colors in our GCs
900 XSetForeground(d, r.prompt, p_fg.pixel);
901 XSetForeground(d, r.prompt_bg, p_bg.pixel);
902 XSetForeground(d, r.completion, compl_fg.pixel);
903 XSetForeground(d, r.completion_bg, compl_bg.pixel);
904 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
905 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
907 // open the X input method
908 XIM xim = XOpenIM(d, xdb, resname, resclass);
909 check_allocation(xim);
911 XIMStyles *xis = nil;
912 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
913 fprintf(stderr, "Input Styles could not be retrieved\n");
914 return EX_UNAVAILABLE;
917 XIMStyle bestMatchStyle = 0;
918 for (int i = 0; i < xis->count_styles; ++i) {
919 XIMStyle ts = xis->supported_styles[i];
920 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
921 bestMatchStyle = ts;
922 break;
925 XFree(xis);
927 if (!bestMatchStyle) {
928 fprintf(stderr, "No matching input style could be determined\n");
931 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
932 check_allocation(xic);
934 // draw the window for the first time
935 draw(&r, text, cs);
937 // main loop
938 while (status == LOOPING) {
939 XEvent e;
940 XNextEvent(d, &e);
942 if (XFilterEvent(&e, w))
943 continue;
945 switch (e.type) {
946 case KeymapNotify:
947 XRefreshKeyboardMapping(&e.xmapping);
948 break;
950 case KeyPress: {
951 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
953 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
954 bool shift = (ev->state & ShiftMask);
955 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
956 : compl_select_next(cs, nothing_selected);
957 if (n != nil) {
958 nothing_selected = false;
959 free(text);
960 text = strdup(n->completion);
961 if (text == nil) {
962 fprintf(stderr, "Memory allocation error!\n");
963 status = ERR;
964 break;
966 textlen = strlen(text);
968 draw(&r, text, cs);
969 break;
972 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
973 nothing_selected = true;
974 popc(text, textlen);
975 update_completions(cs, text, lines);
976 draw(&r, text, cs);
977 break;
980 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
981 status = OK;
982 break;
985 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
986 status = ERR;
987 break;
990 // try to read what the user pressed
991 int symbol = 0;
992 Status s = 0;
993 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
995 if (s == XBufferOverflow) {
996 // should not happen since there are no utf-8 characters
997 // larger than 24bits, but is something to be aware of when
998 // used to directly write to a string buffer
999 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1000 break;
1002 char *str = (char*)&symbol;
1004 if (ev->state & ControlMask) {
1005 // check for some key bindings
1006 if (!strcmp(str, "")) { // C-u
1007 nothing_selected = true;
1008 for (int i = 0; i < textlen; ++i)
1009 text[i] = 0;
1010 update_completions(cs, text, lines);
1012 if (!strcmp(str, "")) { // C-h
1013 nothing_selected = true;
1014 popc(text, textlen);
1015 update_completions(cs, text, lines);
1017 if (!strcmp(str, "")) { // C-w
1018 nothing_selected = true;
1020 // `textlen` is the length of the allocated string, not the
1021 // length of the ACTUAL string
1022 int p = strlen(text) - 1;
1023 if (p >= 0) { // delete the current char
1024 text[p] = 0;
1025 p--;
1027 while (p >= 0 && isalnum(text[p])) {
1028 text[p] = 0;
1029 p--;
1031 // erase also trailing white space
1032 while (p >= 0 && isspace(text[p])) {
1033 text[p] = 0;
1034 p--;
1036 update_completions(cs, text, lines);
1038 if (!strcmp(str, "\r")) { // C-m
1039 status = OK;
1041 draw(&r, text, cs);
1042 break;
1045 int str_len = strlen(str);
1046 for (int i = 0; i < str_len; ++i) {
1047 textlen = pushc(&text, textlen, str[i]);
1048 if (textlen == -1) {
1049 fprintf(stderr, "Memory allocation error\n");
1050 status = ERR;
1051 break;
1053 nothing_selected = true;
1054 update_completions(cs, text, lines);
1058 draw(&r, text, cs);
1059 break;
1061 default:
1062 fprintf(stderr, "Unknown event %d\n", e.type);
1066 release_keyboard(d);
1068 if (status == OK)
1069 printf("%s\n", text);
1071 for (int i = 0; i < nlines; ++i) {
1072 free(lines[i]);
1075 #ifdef USE_XFT
1076 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1077 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1078 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1079 #endif
1081 free(ps1);
1082 free(fontname);
1083 free(text);
1084 free(lines);
1085 compl_delete(cs);
1087 XDestroyWindow(d, w);
1088 XCloseDisplay(d);
1090 return status == OK ? 0 : 1;