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(a, b) (((a) < (b)) ? (a) : (b))
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
51 #define update_completions(cs, text, lines) { \
52 compl_delete(cs); \
53 cs = filter(text, lines); \
54 }
56 #define INITIAL_ITEMS 64
58 #define TODO(s) { \
59 fprintf(stderr, "TODO! " s "\n"); \
60 }
62 #define cannot_allocate_memory { \
63 fprintf(stderr, "Could not allocate memory\n"); \
64 exit(EX_UNAVAILABLE); \
65 }
67 #define check_allocation(a) { \
68 if (a == nil) \
69 cannot_allocate_memory; \
70 }
72 enum state {LOOPING, OK, ERR};
74 enum text_type {PROMPT, COMPL, COMPL_HIGH};
76 struct rendering {
77 Display *d;
78 Window w;
79 GC prompt;
80 GC prompt_bg;
81 GC completion;
82 GC completion_bg;
83 GC completion_highlighted;
84 GC completion_highlighted_bg;
85 #ifdef USE_XFT
86 XftDraw *xftdraw;
87 XftColor xft_prompt;
88 XftColor xft_completion;
89 XftColor xft_completion_highlighted;
90 XftFont *font;
91 #else
92 XFontSet *font;
93 #endif
94 int width;
95 int height;
96 bool horizontal_layout;
97 char *ps1;
98 int ps1len;
99 };
101 struct completions {
102 char *completion;
103 bool selected;
104 struct completions *next;
105 };
107 struct completions *compl_new() {
108 struct completions *c = malloc(sizeof(struct completions));
110 if (c == nil)
111 return c;
113 c->completion = nil;
114 c->selected = false;
115 c->next = nil;
116 return c;
119 void compl_delete(struct completions *c) {
120 free(c);
123 struct completions *compl_select_next(struct completions *c, bool n) {
124 if (c == nil)
125 return nil;
126 if (n) {
127 c->selected = true;
128 return c;
131 struct completions *orig = c;
132 while (c != nil) {
133 if (c->selected) {
134 c->selected = false;
135 if (c->next != nil) {
136 // the current one is selected and the next one exists
137 c->next->selected = true;
138 return c->next;
139 } else {
140 // the current one is selected and the next one is nill,
141 // select the first one
142 orig->selected = true;
143 return orig;
146 c = c->next;
148 return nil;
151 struct completions *compl_select_prev(struct completions *c, bool n) {
152 if (c == nil)
153 return nil;
155 struct completions *cc = c;
157 if (n) // select the last one
158 while (cc != nil) {
159 if (cc->next == nil) {
160 cc->selected = true;
161 return cc;
163 cc = cc->next;
165 else // select the previous one
166 while (cc != nil) {
167 if (cc->next != nil && cc->next->selected) {
168 cc->next->selected = false;
169 cc->selected = true;
170 return cc;
172 cc = cc->next;
175 return nil;
178 struct completions *filter(char *text, char **lines) {
179 int i = 0;
180 struct completions *root = compl_new();
181 struct completions *c = root;
183 for (;;) {
184 char *l = lines[i];
185 if (l == nil)
186 break;
188 if (strstr(l, text) != nil) {
189 c->next = compl_new();
190 c = c->next;
191 c->completion = l;
194 ++i;
197 struct completions *r = root->next;
198 compl_delete(root);
199 return r;
202 // push the character c at the end of the string pointed by p
203 int pushc(char **p, int maxlen, char c) {
204 int len = strnlen(*p, maxlen);
206 if (!(len < maxlen -2)) {
207 maxlen += maxlen >> 1;
208 char *newptr = realloc(*p, maxlen);
209 if (newptr == nil) { // bad!
210 return -1;
212 *p = newptr;
215 (*p)[len] = c;
216 (*p)[len+1] = '\0';
217 return maxlen;
220 int utf8strnlen(char *s, int maxlen) {
221 int len = 0;
222 while (*s && maxlen > 0) {
223 len += (*s++ & 0xc0) != 0x80;
224 maxlen--;
226 return len;
229 // remove the last *glyph* from the *utf8* string!
230 // this is different from just setting the last byte to 0 (in some
231 // cases ofc). The actual implementation is quite inefficient because
232 // it remove the last char until the number of glyphs doesn't change
233 void popc(char *p, int maxlen) {
234 int len = strnlen(p, maxlen);
236 if (len == 0)
237 return;
239 int ulen = utf8strnlen(p, maxlen);
240 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
241 len--;
242 p[len] = 0;
246 // If the string is surrounded by quotes (`"`) remove them and replace
247 // every `\"` in the string with `"`
248 char *normalize_str(const char *str) {
249 int len = strlen(str);
250 if (len == 0)
251 return nil;
253 char *s = calloc(len, sizeof(char));
254 check_allocation(s);
255 int p = 0;
256 while (*str) {
257 char c = *str;
258 if (*str == '\\') {
259 if (*(str + 1)) {
260 s[p] = *(str + 1);
261 p++;
262 str += 2; // skip this and the next char
263 continue;
264 } else {
265 break;
268 if (c == '"') {
269 str++; // skip only this char
270 continue;
272 s[p] = c;
273 p++;
274 str++;
276 return s;
279 // read an arbitrary long line from stdin and return a pointer to it
280 // TODO: resize the allocated memory to exactly fit the string once
281 // read?
282 char *readline(bool *eof) {
283 int maxlen = 8;
284 char *str = calloc(maxlen, sizeof(char));
285 if (str == nil) {
286 fprintf(stderr, "Cannot allocate memory!\n");
287 exit(EX_UNAVAILABLE);
290 int c;
291 while((c = getchar()) != EOF) {
292 if (c == '\n')
293 return str;
294 else
295 maxlen = pushc(&str, maxlen, c);
297 if (maxlen == -1) {
298 fprintf(stderr, "Cannot allocate memory!\n");
299 exit(EX_UNAVAILABLE);
302 *eof = true;
303 return str;
306 int readlines (char ***lns, int items) {
307 bool finished = false;
308 int n = 0;
309 char **lines = *lns;
310 while (true) {
311 lines[n] = readline(&finished);
313 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
314 free(lines[n]);
315 --n; // forget about this line
318 if (finished)
319 break;
321 ++n;
323 if (n == items - 1) {
324 items += items >>1;
325 char **l = realloc(lines, sizeof(char*) * items);
326 check_allocation(l);
327 *lns = l;
328 lines = l;
332 n++;
333 lines[n] = nil;
334 return items;
337 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
338 int height;
339 int width;
340 #ifdef USE_XFT
341 XGlyphInfo gi;
342 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
343 height = (r->font->ascent - r->font->descent)/2;
344 width = gi.width - gi.x;
345 #else
346 XRectangle rect;
347 XmbTextExtents(*r->font, str, len, nil, &rect);
348 height = rect.height;
349 width = rect.width;
350 #endif
351 if (ret_width != nil) *ret_width = width;
352 if (ret_height != nil) *ret_height = height;
353 return width;
356 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
357 #ifdef USE_XFT
358 XftColor xftcolor;
359 if (tt == PROMPT) xftcolor = r->xft_prompt;
360 if (tt == COMPL) xftcolor = r->xft_completion;
361 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
363 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
364 #else
365 GC gc;
366 if (tt == PROMPT) gc = r->prompt;
367 if (tt == COMPL) gc = r->completion;
368 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
369 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
370 #endif
373 char *strdupn(char *str) {
374 int len = strlen(str);
376 if (str == nil || len == 0)
377 return nil;
379 char *dup = strdup(str);
380 if (dup == nil)
381 return nil;
383 for (int i = 0; i < len; ++i)
384 if (dup[i] == ' ')
385 dup[i] = 'n';
387 return dup;
390 // |------------------|----------------------------------------------|
391 // | 20 char text | completion | completion | completion | compl |
392 // |------------------|----------------------------------------------|
393 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
394 // TODO: make these dynamic?
395 int prompt_width = 20; // char
396 int padding = 10;
398 int width, height;
399 char *ps1_dup = strdupn(r->ps1);
400 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
401 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
402 free(ps1_dup);
403 int start_at = ps1xlen;
405 start_at = text_extents("n", 1, r, nil, nil);
406 start_at = start_at * prompt_width + padding;
408 int texty = (height + r->height) >>1;
410 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
412 int text_len = strlen(text);
413 if (text_len > prompt_width)
414 text = text + (text_len - prompt_width);
415 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
416 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
418 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
420 while (cs != nil) {
421 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
422 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
424 int len = strlen(cs->completion);
425 int text_width = text_extents(cs->completion, len, r, nil, nil);
427 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
429 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
431 start_at += text_width + padding * 2;
433 if (start_at > r->width)
434 break; // don't draw completion if the space isn't enough
436 cs = cs->next;
439 XFlush(r->d);
442 // |-----------------------------------------------------------------|
443 // | prompt |
444 // |-----------------------------------------------------------------|
445 // | completion |
446 // |-----------------------------------------------------------------|
447 // | completion |
448 // |-----------------------------------------------------------------|
449 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
450 // should be padding and not padding*2, but the text doesn't seem to
451 // be vertically centered otherwise....
452 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
453 int padding = 10; // TODO make this dynamic
455 int height, width;
456 text_extents("fjpgl", 5, r, &width, &height);
457 int start_at = height + padding*2;
459 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
460 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
462 char *ps1_dup = strdupn(r->ps1);
463 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
464 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
465 free(ps1_dup);
467 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
468 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
470 while (cs != nil) {
471 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
472 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
474 int len = strlen(cs->completion);
475 text_extents(cs->completion, len, r, &width, &height);
476 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
477 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
479 start_at += height + padding *2;
481 if (start_at > r->height)
482 break; // don't draw completion if the space isn't enough
484 cs = cs->next;
487 XFlush(r->d);
490 void draw(struct rendering *r, char *text, struct completions *cs) {
491 if (r->horizontal_layout)
492 draw_horizontally(r, text, cs);
493 else
494 draw_vertically(r, text, cs);
497 /* Set some WM stuff */
498 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
499 Atom type;
500 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
501 XChangeProperty(
502 d,
503 w,
504 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
505 XInternAtom(d, "ATOM", false),
506 32,
507 PropModeReplace,
508 (unsigned char *)&type,
510 );
512 /* some window managers honor this properties */
513 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
514 XChangeProperty(d,
515 w,
516 XInternAtom(d, "_NET_WM_STATE", false),
517 XInternAtom(d, "ATOM", false),
518 32,
519 PropModeReplace,
520 (unsigned char *)&type,
522 );
524 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
525 XChangeProperty(d,
526 w,
527 XInternAtom(d, "_NET_WM_STATE", false),
528 XInternAtom(d, "ATOM", false),
529 32,
530 PropModeAppend,
531 (unsigned char *)&type,
533 );
535 // setting window hints
536 XClassHint *class_hint = XAllocClassHint();
537 if (class_hint == nil) {
538 fprintf(stderr, "Could not allocate memory for class hint\n");
539 exit(EX_UNAVAILABLE);
541 class_hint->res_name = resname;
542 class_hint->res_class = resclass;
543 XSetClassHint(d, w, class_hint);
544 XFree(class_hint);
546 XSizeHints *size_hint = XAllocSizeHints();
547 if (size_hint == nil) {
548 fprintf(stderr, "Could not allocate memory for size hint\n");
549 exit(EX_UNAVAILABLE);
551 size_hint->flags = PMinSize | PBaseSize;
552 size_hint->min_width = width;
553 size_hint->base_width = width;
554 size_hint->min_height = height;
555 size_hint->base_height = height;
557 XFlush(d);
560 void get_wh(Display *d, Window *w, int *width, int *height) {
561 XWindowAttributes win_attr;
562 XGetWindowAttributes(d, *w, &win_attr);
563 *height = win_attr.height;
564 *width = win_attr.width;
567 // I know this may seem a little hackish BUT is the only way I managed
568 // to actually grab that goddam keyboard. Only one call to
569 // XGrabKeyboard does not always end up with the keyboard grabbed!
570 int take_keyboard(Display *d, Window w) {
571 int i;
572 for (i = 0; i < 100; i++) {
573 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
574 return 1;
575 usleep(1000);
577 return 0;
580 void release_keyboard(Display *d) {
581 XUngrabKeyboard(d, CurrentTime);
584 int parse_integer(const char *str, int default_value, int max) {
585 int len = strlen(str);
586 if (len > 0 && str[len-1] == '%') {
587 char *cpy = strdup(str);
588 check_allocation(cpy);
589 cpy[len-1] = '\0';
590 int val = parse_integer(cpy, default_value, max);
591 free(cpy);
592 return val * max / 100;
595 errno = 0;
596 char *ep;
597 long lval = strtol(str, &ep, 10);
598 if (str[0] == '\0' || *ep != '\0') { // NaN
599 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
600 return default_value;
602 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
603 (lval > INT_MAX || lval < INT_MIN)) {
604 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
605 return default_value;
607 return lval;
610 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
611 if (!strcmp(str, "middle")) {
612 return (max - self)/2;
614 return parse_integer(str, default_value, max);
617 int main() {
618 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
619 int nlines = readlines(&lines, INITIAL_ITEMS);
621 setlocale(LC_ALL, getenv("LANG"));
623 enum state status = LOOPING;
625 // where the monitor start (used only with xinerama)
626 int offset_x = 0;
627 int offset_y = 0;
629 // width and height of the window
630 int width = 400;
631 int height = 20;
633 // position on the screen
634 int x = 0;
635 int y = 0;
637 char *ps1 = strdup("$ ");
638 check_allocation(ps1);
640 char *fontname = strdup("fixed");
641 check_allocation(fontname);
643 int textlen = 10;
644 char *text = malloc(textlen * sizeof(char));
645 check_allocation(text);
647 struct completions *cs = filter(text, lines);
648 bool nothing_selected = true;
650 // start talking to xorg
651 Display *d = XOpenDisplay(nil);
652 if (d == nil) {
653 fprintf(stderr, "Could not open display!\n");
654 return EX_UNAVAILABLE;
657 // get display size
658 // XXX: is getting the default root window dimension correct?
659 XWindowAttributes xwa;
660 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
661 int d_width = xwa.width;
662 int d_height = xwa.height;
664 #ifdef USE_XINERAMA
665 if (XineramaIsActive(d)) {
666 // find the mice
667 int number_of_screens = XScreenCount(d);
668 bool result;
669 Window r;
670 Window root;
671 int root_x, root_y, win_x, win_y;
672 unsigned int mask;
673 bool res;
674 for (int i = 0; i < number_of_screens; ++i) {
675 root = XRootWindow(d, i);
676 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
677 if (res) break;
679 if (!res) {
680 fprintf(stderr, "No mouse found.\n");
681 root_x = 0;
682 root_y = 0;
685 // now find in which monitor the mice is on
686 int monitors;
687 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
688 if (info) {
689 for (int i = 0; i < monitors; ++i) {
690 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
691 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
692 offset_x = info[i].x_org;
693 offset_y = info[i].y_org;
694 d_width = info[i].width;
695 d_height = info[i].height;
696 break;
700 XFree(info);
702 #endif
704 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
705 XColor p_fg, p_bg,
706 compl_fg, compl_bg,
707 compl_highlighted_fg, compl_highlighted_bg;
709 bool horizontal_layout = true;
711 // read resource
712 XrmInitialize();
713 char *xrm = XResourceManagerString(d);
714 XrmDatabase xdb = nil;
715 if (xrm != nil) {
716 xdb = XrmGetStringDatabase(xrm);
717 XrmValue value;
718 char *datatype[20];
720 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
721 fontname = strdup(value.addr);
722 check_allocation(fontname);
724 else
725 fprintf(stderr, "no font defined, using %s\n", fontname);
727 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
728 char *v = strdup(value.addr);
729 check_allocation(v);
730 horizontal_layout = !strcmp(v, "horizontal");
731 free(v);
733 else
734 fprintf(stderr, "no layout defined, using horizontal\n");
736 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
737 free(ps1);
738 ps1 = normalize_str(value.addr);
739 } else
740 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
742 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
743 width = parse_integer(value.addr, width, d_width);
744 else
745 fprintf(stderr, "no width defined, using %d\n", width);
747 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
748 height = parse_integer(value.addr, height, d_height);
749 else
750 fprintf(stderr, "no height defined, using %d\n", height);
752 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
753 x = parse_int_with_middle(value.addr, x, d_width, width);
754 else
755 fprintf(stderr, "no x defined, using %d\n", width);
757 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
758 y = parse_int_with_middle(value.addr, y, d_height, height);
759 else
760 fprintf(stderr, "no y defined, using %d\n", height);
762 XColor tmp;
763 // TODO: tmp needs to be free'd after every allocation?
765 // prompt
766 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
767 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
768 else
769 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
771 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
772 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
773 else
774 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
776 // completion
777 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
778 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
779 else
780 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
782 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
783 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
784 else
785 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
787 // completion highlighted
788 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
789 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
790 else
791 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
793 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
794 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
795 else
796 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
797 } else {
798 XColor tmp;
799 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
800 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
801 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
802 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
803 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
804 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
807 // load the font
808 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
809 /* if (font == nil) { */
810 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
811 /* font = XLoadQueryFont(d, "fixed"); */
812 /* } */
813 // load the font
814 #ifdef USE_XFT
815 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
816 #else
817 char **missing_charset_list;
818 int missing_charset_count;
819 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
820 if (font == nil) {
821 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
822 return EX_UNAVAILABLE;
824 #endif
826 // create the window
827 XSetWindowAttributes attr;
828 attr.override_redirect = true;
830 Window w = XCreateWindow(d, // display
831 DefaultRootWindow(d), // parent
832 x + offset_x, y + offset_y, // x y
833 width, height, // w h
834 0, // border width
835 DefaultDepth(d, DefaultScreen(d)), // depth
836 InputOutput, // class
837 DefaultVisual(d, DefaultScreen(d)), // visual
838 CWOverrideRedirect, // value mask
839 &attr);
841 set_win_atoms_hints(d, w, width, height);
843 // we want some events
844 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
846 // make the window appear on the screen
847 XMapWindow(d, w);
849 // wait for the MapNotify event (i.e. the event "window rendered")
850 for (;;) {
851 XEvent e;
852 XNextEvent(d, &e);
853 if (e.type == MapNotify)
854 break;
857 // get the *real* width & height after the window was rendered
858 get_wh(d, &w, &width, &height);
860 // grab keyboard
861 take_keyboard(d, w);
863 // Create some graphics contexts
864 XGCValues values;
865 /* values.font = font->fid; */
867 struct rendering r = {
868 .d = d,
869 .w = w,
870 #ifdef USE_XFT
871 .font = font,
872 #else
873 .font = &font,
874 #endif
875 .prompt = XCreateGC(d, w, 0, &values),
876 .prompt_bg = XCreateGC(d, w, 0, &values),
877 .completion = XCreateGC(d, w, 0, &values),
878 .completion_bg = XCreateGC(d, w, 0, &values),
879 .completion_highlighted = XCreateGC(d, w, 0, &values),
880 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
881 .width = width,
882 .height = height,
883 .horizontal_layout = horizontal_layout,
884 .ps1 = ps1,
885 .ps1len = strlen(ps1)
886 };
888 #ifdef USE_XFT
889 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
891 // prompt
892 XRenderColor xrcolor;
893 xrcolor.red = p_fg.red;
894 xrcolor.green = p_fg.red;
895 xrcolor.blue = p_fg.red;
896 xrcolor.alpha = 65535;
897 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
899 // completion
900 xrcolor.red = compl_fg.red;
901 xrcolor.green = compl_fg.green;
902 xrcolor.blue = compl_fg.blue;
903 xrcolor.alpha = 65535;
904 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
906 // completion highlighted
907 xrcolor.red = compl_highlighted_fg.red;
908 xrcolor.green = compl_highlighted_fg.green;
909 xrcolor.blue = compl_highlighted_fg.blue;
910 xrcolor.alpha = 65535;
911 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
912 #endif
914 // load the colors in our GCs
915 XSetForeground(d, r.prompt, p_fg.pixel);
916 XSetForeground(d, r.prompt_bg, p_bg.pixel);
917 XSetForeground(d, r.completion, compl_fg.pixel);
918 XSetForeground(d, r.completion_bg, compl_bg.pixel);
919 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
920 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
922 // open the X input method
923 XIM xim = XOpenIM(d, xdb, resname, resclass);
924 check_allocation(xim);
926 XIMStyles *xis = nil;
927 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
928 fprintf(stderr, "Input Styles could not be retrieved\n");
929 return EX_UNAVAILABLE;
932 XIMStyle bestMatchStyle = 0;
933 for (int i = 0; i < xis->count_styles; ++i) {
934 XIMStyle ts = xis->supported_styles[i];
935 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
936 bestMatchStyle = ts;
937 break;
940 XFree(xis);
942 if (!bestMatchStyle) {
943 fprintf(stderr, "No matching input style could be determined\n");
946 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
947 check_allocation(xic);
949 // draw the window for the first time
950 draw(&r, text, cs);
952 // main loop
953 while (status == LOOPING) {
954 XEvent e;
955 XNextEvent(d, &e);
957 if (XFilterEvent(&e, w))
958 continue;
960 switch (e.type) {
961 case KeymapNotify:
962 XRefreshKeyboardMapping(&e.xmapping);
963 break;
965 case KeyPress: {
966 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
968 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
969 bool shift = (ev->state & ShiftMask);
970 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
971 : compl_select_next(cs, nothing_selected);
972 if (n != nil) {
973 nothing_selected = false;
974 free(text);
975 text = strdup(n->completion);
976 if (text == nil) {
977 fprintf(stderr, "Memory allocation error!\n");
978 status = ERR;
979 break;
981 textlen = strlen(text);
983 draw(&r, text, cs);
984 break;
987 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
988 nothing_selected = true;
989 popc(text, textlen);
990 update_completions(cs, text, lines);
991 draw(&r, text, cs);
992 break;
995 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
996 status = OK;
997 break;
1000 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
1001 status = ERR;
1002 break;
1005 // try to read what the user pressed
1006 int symbol = 0;
1007 Status s = 0;
1008 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
1010 if (s == XBufferOverflow) {
1011 // should not happen since there are no utf-8 characters
1012 // larger than 24bits, but is something to be aware of when
1013 // used to directly write to a string buffer
1014 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1015 break;
1017 char *str = (char*)&symbol;
1019 if (ev->state & ControlMask) {
1020 // check for some key bindings
1021 if (!strcmp(str, "")) { // C-u
1022 nothing_selected = true;
1023 for (int i = 0; i < textlen; ++i)
1024 text[i] = 0;
1025 update_completions(cs, text, lines);
1027 if (!strcmp(str, "")) { // C-h
1028 nothing_selected = true;
1029 popc(text, textlen);
1030 update_completions(cs, text, lines);
1032 if (!strcmp(str, "")) { // C-w
1033 nothing_selected = true;
1035 // `textlen` is the length of the allocated string, not the
1036 // length of the ACTUAL string
1037 int p = strlen(text) - 1;
1038 if (p >= 0) { // delete the current char
1039 text[p] = 0;
1040 p--;
1042 while (p >= 0 && isalnum(text[p])) {
1043 text[p] = 0;
1044 p--;
1046 // erase also trailing white space
1047 while (p >= 0 && isspace(text[p])) {
1048 text[p] = 0;
1049 p--;
1051 update_completions(cs, text, lines);
1053 if (!strcmp(str, "\r")) { // C-m
1054 status = OK;
1056 draw(&r, text, cs);
1057 break;
1060 int str_len = strlen(str);
1061 for (int i = 0; i < str_len; ++i) {
1062 textlen = pushc(&text, textlen, str[i]);
1063 if (textlen == -1) {
1064 fprintf(stderr, "Memory allocation error\n");
1065 status = ERR;
1066 break;
1068 nothing_selected = true;
1069 update_completions(cs, text, lines);
1073 draw(&r, text, cs);
1074 break;
1076 default:
1077 fprintf(stderr, "Unknown event %d\n", e.type);
1081 release_keyboard(d);
1083 if (status == OK)
1084 printf("%s\n", text);
1086 for (int i = 0; i < nlines; ++i) {
1087 free(lines[i]);
1090 #ifdef USE_XFT
1091 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1092 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1093 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1094 #endif
1096 free(ps1);
1097 free(fontname);
1098 free(text);
1099 free(lines);
1100 compl_delete(cs);
1102 XDestroyWindow(d, w);
1103 XCloseDisplay(d);
1105 return status == OK ? 0 : 1;