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 #ifdef USE_XFT
49 # define default_fontname "monospace"
50 #else
51 # define default_fontname "fixed"
52 #endif
54 #define MIN(a, b) ((a) < (b) ? (a) : (b))
55 #define MAX(a, b) ((a) > (b) ? (a) : (b))
57 // If we don't have it or we don't want an "ignore case" completion
58 // style, fall back to `strstr(3)`
59 #ifndef USE_STRCASESTR
60 #define strcasestr strstr
61 #endif
63 #define update_completions(cs, text, lines) { \
64 compl_delete(cs); \
65 cs = filter(text, lines); \
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 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
346 int height;
347 int width;
348 #ifdef USE_XFT
349 XGlyphInfo gi;
350 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
351 height = (r->font->ascent - r->font->descent)/2;
352 width = gi.width - gi.x;
353 #else
354 XRectangle rect;
355 XmbTextExtents(*r->font, str, len, nil, &rect);
356 height = rect.height;
357 width = rect.width;
358 #endif
359 if (ret_width != nil) *ret_width = width;
360 if (ret_height != nil) *ret_height = height;
361 return width;
364 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
365 #ifdef USE_XFT
366 XftColor xftcolor;
367 if (tt == PROMPT) xftcolor = r->xft_prompt;
368 if (tt == COMPL) xftcolor = r->xft_completion;
369 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
371 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
372 #else
373 GC gc;
374 if (tt == PROMPT) gc = r->prompt;
375 if (tt == COMPL) gc = r->completion;
376 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
377 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
378 #endif
381 char *strdupn(char *str) {
382 int len = strlen(str);
384 if (str == nil || len == 0)
385 return nil;
387 char *dup = strdup(str);
388 if (dup == nil)
389 return nil;
391 for (int i = 0; i < len; ++i)
392 if (dup[i] == ' ')
393 dup[i] = 'n';
395 return dup;
398 // |------------------|----------------------------------------------|
399 // | 20 char text | completion | completion | completion | compl |
400 // |------------------|----------------------------------------------|
401 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
402 // TODO: make these dynamic?
403 int prompt_width = 20; // char
404 int padding = 10;
406 int width, height;
407 char *ps1_dup = strdupn(r->ps1);
408 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
409 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
410 free(ps1_dup);
411 int start_at = ps1xlen;
413 start_at = text_extents("n", 1, r, nil, nil);
414 start_at = start_at * prompt_width + padding;
416 int texty = (height + r->height) >>1;
418 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
420 int text_len = strlen(text);
421 if (text_len > prompt_width)
422 text = text + (text_len - prompt_width);
423 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
424 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
426 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
428 while (cs != nil) {
429 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
430 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
432 int len = strlen(cs->completion);
433 int text_width = text_extents(cs->completion, len, r, nil, nil);
435 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
437 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
439 start_at += text_width + padding * 2;
441 if (start_at > r->width)
442 break; // don't draw completion if the space isn't enough
444 cs = cs->next;
447 XFlush(r->d);
450 // |-----------------------------------------------------------------|
451 // | prompt |
452 // |-----------------------------------------------------------------|
453 // | completion |
454 // |-----------------------------------------------------------------|
455 // | completion |
456 // |-----------------------------------------------------------------|
457 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
458 // should be padding and not padding*2, but the text doesn't seem to
459 // be vertically centered otherwise....
460 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
461 int padding = 10; // TODO make this dynamic
463 int height, width;
464 text_extents("fjpgl", 5, r, &width, &height);
465 int start_at = height + padding*2;
467 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
468 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
470 char *ps1_dup = strdupn(r->ps1);
471 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
472 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
473 free(ps1_dup);
475 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
476 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
478 while (cs != nil) {
479 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
480 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
482 int len = strlen(cs->completion);
483 text_extents(cs->completion, len, r, &width, &height);
484 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
485 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
487 start_at += height + padding *2;
489 if (start_at > r->height)
490 break; // don't draw completion if the space isn't enough
492 cs = cs->next;
495 XFlush(r->d);
498 void draw(struct rendering *r, char *text, struct completions *cs) {
499 if (r->horizontal_layout)
500 draw_horizontally(r, text, cs);
501 else
502 draw_vertically(r, text, cs);
505 /* Set some WM stuff */
506 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
507 Atom type;
508 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
509 XChangeProperty(
510 d,
511 w,
512 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
513 XInternAtom(d, "ATOM", false),
514 32,
515 PropModeReplace,
516 (unsigned char *)&type,
518 );
520 /* some window managers honor this properties */
521 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
522 XChangeProperty(d,
523 w,
524 XInternAtom(d, "_NET_WM_STATE", false),
525 XInternAtom(d, "ATOM", false),
526 32,
527 PropModeReplace,
528 (unsigned char *)&type,
530 );
532 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
533 XChangeProperty(d,
534 w,
535 XInternAtom(d, "_NET_WM_STATE", false),
536 XInternAtom(d, "ATOM", false),
537 32,
538 PropModeAppend,
539 (unsigned char *)&type,
541 );
543 // setting window hints
544 XClassHint *class_hint = XAllocClassHint();
545 if (class_hint == nil) {
546 fprintf(stderr, "Could not allocate memory for class hint\n");
547 exit(EX_UNAVAILABLE);
549 class_hint->res_name = resname;
550 class_hint->res_class = resclass;
551 XSetClassHint(d, w, class_hint);
552 XFree(class_hint);
554 XSizeHints *size_hint = XAllocSizeHints();
555 if (size_hint == nil) {
556 fprintf(stderr, "Could not allocate memory for size hint\n");
557 exit(EX_UNAVAILABLE);
559 size_hint->flags = PMinSize | PBaseSize;
560 size_hint->min_width = width;
561 size_hint->base_width = width;
562 size_hint->min_height = height;
563 size_hint->base_height = height;
565 XFlush(d);
568 void get_wh(Display *d, Window *w, int *width, int *height) {
569 XWindowAttributes win_attr;
570 XGetWindowAttributes(d, *w, &win_attr);
571 *height = win_attr.height;
572 *width = win_attr.width;
575 // I know this may seem a little hackish BUT is the only way I managed
576 // to actually grab that goddam keyboard. Only one call to
577 // XGrabKeyboard does not always end up with the keyboard grabbed!
578 int take_keyboard(Display *d, Window w) {
579 int i;
580 for (i = 0; i < 100; i++) {
581 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
582 return 1;
583 usleep(1000);
585 return 0;
588 void release_keyboard(Display *d) {
589 XUngrabKeyboard(d, CurrentTime);
592 int parse_integer(const char *str, int default_value, int max) {
593 int len = strlen(str);
594 if (len > 0 && str[len-1] == '%') {
595 char *cpy = strdup(str);
596 check_allocation(cpy);
597 cpy[len-1] = '\0';
598 int val = parse_integer(cpy, default_value, max);
599 free(cpy);
600 return val * max / 100;
603 errno = 0;
604 char *ep;
605 long lval = strtol(str, &ep, 10);
606 if (str[0] == '\0' || *ep != '\0') { // NaN
607 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
608 return default_value;
610 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
611 (lval > INT_MAX || lval < INT_MIN)) {
612 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
613 return default_value;
615 return lval;
618 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
619 if (!strcmp(str, "middle")) {
620 return (max - self)/2;
622 return parse_integer(str, default_value, max);
625 int main() {
626 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
627 int nlines = readlines(&lines, INITIAL_ITEMS);
629 setlocale(LC_ALL, getenv("LANG"));
631 enum state status = LOOPING;
633 // where the monitor start (used only with xinerama)
634 int offset_x = 0;
635 int offset_y = 0;
637 // width and height of the window
638 int width = 400;
639 int height = 20;
641 // position on the screen
642 int x = 0;
643 int y = 0;
645 char *ps1 = strdup("$ ");
646 check_allocation(ps1);
648 char *fontname = strdup(default_fontname);
649 check_allocation(fontname);
651 int textlen = 10;
652 char *text = malloc(textlen * sizeof(char));
653 check_allocation(text);
655 struct completions *cs = filter(text, lines);
656 bool nothing_selected = true;
658 // start talking to xorg
659 Display *d = XOpenDisplay(nil);
660 if (d == nil) {
661 fprintf(stderr, "Could not open display!\n");
662 return EX_UNAVAILABLE;
665 // get display size
666 // XXX: is getting the default root window dimension correct?
667 XWindowAttributes xwa;
668 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
669 int d_width = xwa.width;
670 int d_height = xwa.height;
672 #ifdef USE_XINERAMA
673 if (XineramaIsActive(d)) {
674 // find the mice
675 int number_of_screens = XScreenCount(d);
676 bool result;
677 Window r;
678 Window root;
679 int root_x, root_y, win_x, win_y;
680 unsigned int mask;
681 bool res;
682 for (int i = 0; i < number_of_screens; ++i) {
683 root = XRootWindow(d, i);
684 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
685 if (res) break;
687 if (!res) {
688 fprintf(stderr, "No mouse found.\n");
689 root_x = 0;
690 root_y = 0;
693 // now find in which monitor the mice is on
694 int monitors;
695 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
696 if (info) {
697 for (int i = 0; i < monitors; ++i) {
698 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
699 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
700 offset_x = info[i].x_org;
701 offset_y = info[i].y_org;
702 d_width = info[i].width;
703 d_height = info[i].height;
704 break;
708 XFree(info);
710 #endif
712 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
713 XColor p_fg, p_bg,
714 compl_fg, compl_bg,
715 compl_highlighted_fg, compl_highlighted_bg;
717 bool horizontal_layout = true;
719 // read resource
720 XrmInitialize();
721 char *xrm = XResourceManagerString(d);
722 XrmDatabase xdb = nil;
723 if (xrm != nil) {
724 xdb = XrmGetStringDatabase(xrm);
725 XrmValue value;
726 char *datatype[20];
728 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
729 fontname = strdup(value.addr);
730 check_allocation(fontname);
732 else
733 fprintf(stderr, "no font defined, using %s\n", fontname);
735 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
736 char *v = strdup(value.addr);
737 check_allocation(v);
738 horizontal_layout = !strcmp(v, "horizontal");
739 free(v);
741 else
742 fprintf(stderr, "no layout defined, using horizontal\n");
744 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
745 free(ps1);
746 ps1 = normalize_str(value.addr);
747 } else
748 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
750 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
751 width = parse_integer(value.addr, width, d_width);
752 else
753 fprintf(stderr, "no width defined, using %d\n", width);
755 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
756 height = parse_integer(value.addr, height, d_height);
757 else
758 fprintf(stderr, "no height defined, using %d\n", height);
760 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
761 x = parse_int_with_middle(value.addr, x, d_width, width);
762 else
763 fprintf(stderr, "no x defined, using %d\n", width);
765 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
766 y = parse_int_with_middle(value.addr, y, d_height, height);
767 else
768 fprintf(stderr, "no y defined, using %d\n", height);
770 XColor tmp;
771 // TODO: tmp needs to be free'd after every allocation?
773 // prompt
774 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
775 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
776 else
777 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
779 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
780 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
781 else
782 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
784 // completion
785 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
786 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
787 else
788 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
790 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
791 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
792 else
793 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
795 // completion highlighted
796 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
797 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
798 else
799 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
801 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
802 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
803 else
804 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
805 } else {
806 XColor tmp;
807 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
808 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
809 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
810 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
811 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
812 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
815 // load the font
816 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
817 /* if (font == nil) { */
818 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
819 /* font = XLoadQueryFont(d, "fixed"); */
820 /* } */
821 // load the font
822 #ifdef USE_XFT
823 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
824 #else
825 char **missing_charset_list;
826 int missing_charset_count;
827 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
828 if (font == nil) {
829 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
830 return EX_UNAVAILABLE;
832 #endif
834 // create the window
835 XSetWindowAttributes attr;
836 attr.override_redirect = true;
838 Window w = XCreateWindow(d, // display
839 DefaultRootWindow(d), // parent
840 x + offset_x, y + offset_y, // x y
841 width, height, // w h
842 0, // border width
843 DefaultDepth(d, DefaultScreen(d)), // depth
844 InputOutput, // class
845 DefaultVisual(d, DefaultScreen(d)), // visual
846 CWOverrideRedirect, // value mask
847 &attr);
849 set_win_atoms_hints(d, w, width, height);
851 // we want some events
852 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
854 // make the window appear on the screen
855 XMapWindow(d, w);
857 // wait for the MapNotify event (i.e. the event "window rendered")
858 for (;;) {
859 XEvent e;
860 XNextEvent(d, &e);
861 if (e.type == MapNotify)
862 break;
865 // get the *real* width & height after the window was rendered
866 get_wh(d, &w, &width, &height);
868 // grab keyboard
869 take_keyboard(d, w);
871 // Create some graphics contexts
872 XGCValues values;
873 /* values.font = font->fid; */
875 struct rendering r = {
876 .d = d,
877 .w = w,
878 #ifdef USE_XFT
879 .font = font,
880 #else
881 .font = &font,
882 #endif
883 .prompt = XCreateGC(d, w, 0, &values),
884 .prompt_bg = XCreateGC(d, w, 0, &values),
885 .completion = XCreateGC(d, w, 0, &values),
886 .completion_bg = XCreateGC(d, w, 0, &values),
887 .completion_highlighted = XCreateGC(d, w, 0, &values),
888 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
889 .width = width,
890 .height = height,
891 .horizontal_layout = horizontal_layout,
892 .ps1 = ps1,
893 .ps1len = strlen(ps1)
894 };
896 #ifdef USE_XFT
897 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
899 // prompt
900 XRenderColor xrcolor;
901 xrcolor.red = p_fg.red;
902 xrcolor.green = p_fg.red;
903 xrcolor.blue = p_fg.red;
904 xrcolor.alpha = 65535;
905 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
907 // completion
908 xrcolor.red = compl_fg.red;
909 xrcolor.green = compl_fg.green;
910 xrcolor.blue = compl_fg.blue;
911 xrcolor.alpha = 65535;
912 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
914 // completion highlighted
915 xrcolor.red = compl_highlighted_fg.red;
916 xrcolor.green = compl_highlighted_fg.green;
917 xrcolor.blue = compl_highlighted_fg.blue;
918 xrcolor.alpha = 65535;
919 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
920 #endif
922 // load the colors in our GCs
923 XSetForeground(d, r.prompt, p_fg.pixel);
924 XSetForeground(d, r.prompt_bg, p_bg.pixel);
925 XSetForeground(d, r.completion, compl_fg.pixel);
926 XSetForeground(d, r.completion_bg, compl_bg.pixel);
927 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
928 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
930 // open the X input method
931 XIM xim = XOpenIM(d, xdb, resname, resclass);
932 check_allocation(xim);
934 XIMStyles *xis = nil;
935 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
936 fprintf(stderr, "Input Styles could not be retrieved\n");
937 return EX_UNAVAILABLE;
940 XIMStyle bestMatchStyle = 0;
941 for (int i = 0; i < xis->count_styles; ++i) {
942 XIMStyle ts = xis->supported_styles[i];
943 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
944 bestMatchStyle = ts;
945 break;
948 XFree(xis);
950 if (!bestMatchStyle) {
951 fprintf(stderr, "No matching input style could be determined\n");
954 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
955 check_allocation(xic);
957 // draw the window for the first time
958 draw(&r, text, cs);
960 // main loop
961 while (status == LOOPING) {
962 XEvent e;
963 XNextEvent(d, &e);
965 if (XFilterEvent(&e, w))
966 continue;
968 switch (e.type) {
969 case KeymapNotify:
970 XRefreshKeyboardMapping(&e.xmapping);
971 break;
973 case KeyPress: {
974 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
976 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
977 bool shift = (ev->state & ShiftMask);
978 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
979 : compl_select_next(cs, nothing_selected);
980 if (n != nil) {
981 nothing_selected = false;
982 free(text);
983 text = strdup(n->completion);
984 if (text == nil) {
985 fprintf(stderr, "Memory allocation error!\n");
986 status = ERR;
987 break;
989 textlen = strlen(text);
991 draw(&r, text, cs);
992 break;
995 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
996 nothing_selected = true;
997 popc(text, textlen);
998 update_completions(cs, text, lines);
999 draw(&r, text, cs);
1000 break;
1003 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
1004 status = OK;
1005 break;
1008 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1009 status = ERR;
1010 break;
1013 // try to read what the user pressed
1014 int symbol = 0;
1015 Status s = 0;
1016 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1018 if (s == XBufferOverflow) {
1019 // should not happen since there are no utf-8 characters
1020 // larger than 24bits, but is something to be aware of when
1021 // used to directly write to a string buffer
1022 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1023 break;
1025 char *str = (char*)&symbol;
1027 if (ev->state & ControlMask) {
1028 // check for some key bindings
1029 if (!strcmp(str, "")) { // C-u
1030 nothing_selected = true;
1031 for (int i = 0; i < textlen; ++i)
1032 text[i] = 0;
1033 update_completions(cs, text, lines);
1035 if (!strcmp(str, "")) { // C-h
1036 nothing_selected = true;
1037 popc(text, textlen);
1038 update_completions(cs, text, lines);
1040 if (!strcmp(str, "")) { // C-w
1041 nothing_selected = true;
1043 // `textlen` is the length of the allocated string, not the
1044 // length of the ACTUAL string
1045 int p = strlen(text) - 1;
1046 if (p >= 0) { // delete the current char
1047 text[p] = 0;
1048 p--;
1050 while (p >= 0 && isalnum(text[p])) {
1051 text[p] = 0;
1052 p--;
1054 // erase also trailing white space
1055 while (p >= 0 && isspace(text[p])) {
1056 text[p] = 0;
1057 p--;
1059 update_completions(cs, text, lines);
1061 if (!strcmp(str, "\r")) { // C-m
1062 status = OK;
1064 draw(&r, text, cs);
1065 break;
1068 int str_len = strlen(str);
1069 for (int i = 0; i < str_len; ++i) {
1070 textlen = pushc(&text, textlen, str[i]);
1071 if (textlen == -1) {
1072 fprintf(stderr, "Memory allocation error\n");
1073 status = ERR;
1074 break;
1076 nothing_selected = true;
1077 update_completions(cs, text, lines);
1081 draw(&r, text, cs);
1082 break;
1084 default:
1085 fprintf(stderr, "Unknown event %d\n", e.type);
1089 release_keyboard(d);
1091 if (status == OK)
1092 printf("%s\n", text);
1094 for (int i = 0; i < nlines; ++i) {
1095 free(lines[i]);
1098 #ifdef USE_XFT
1099 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1100 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1101 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1102 #endif
1104 free(ps1);
1105 free(fontname);
1106 free(text);
1107 free(lines);
1108 compl_delete(cs);
1110 XDestroyWindow(d, w);
1111 XCloseDisplay(d);
1113 return status == OK ? 0 : 1;