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 #define nil NULL
41 #define resname "MyMenu"
42 #define resclass "mymenu"
44 #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
46 #define OVERLAP(a,b,c,d) (((a)==(c) && (b)==(d)) || MIN((a)+(b), (c)+(d)) - MAX((a), (c)) > 0)
47 #define INTERSECT(x,y,w,h,x1,y1,w1,h1) (OVERLAP((x),(w),(x1),(w1)) && OVERLAP((y),(h),(y1),(h1)))
49 #define update_completions(cs, text, lines) { \
50 compl_delete(cs); \
51 cs = filter(text, lines); \
52 }
54 // TODO: dynamic?
55 #define INITIAL_ITEMS 64
57 #define TODO(s) { \
58 fprintf(stderr, "TODO! " s "\n"); \
59 }
61 #define cannot_allocate_memory { \
62 fprintf(stderr, "Could not allocate memory\n"); \
63 exit(EX_UNAVAILABLE); \
64 }
66 #define check_allocation(a) { \
67 if (a == nil) \
68 cannot_allocate_memory; \
69 }
71 enum state {LOOPING, OK, ERR};
73 struct rendering {
74 Display *d;
75 Window w;
76 GC prompt;
77 GC prompt_bg;
78 GC completion;
79 GC completion_bg;
80 GC completion_highlighted;
81 GC completion_highlighted_bg;
82 int width;
83 int height;
84 XFontSet *font;
85 bool horizontal_layout;
86 char *ps1;
87 int ps1len;
88 };
90 struct completions {
91 char *completion;
92 bool selected;
93 struct completions *next;
94 };
96 struct completions *compl_new() {
97 struct completions *c = malloc(sizeof(struct completions));
99 if (c == nil)
100 return c;
102 c->completion = nil;
103 c->selected = false;
104 c->next = nil;
105 return c;
108 void compl_delete(struct completions *c) {
109 free(c);
112 struct completions *compl_select_next(struct completions *c, bool n) {
113 if (c == nil)
114 return nil;
115 if (n) {
116 c->selected = true;
117 return c;
120 struct completions *orig = c;
121 while (c != nil) {
122 if (c->selected) {
123 c->selected = false;
124 if (c->next != nil) {
125 // the current one is selected and the next one exists
126 c->next->selected = true;
127 return c->next;
128 } else {
129 // the current one is selected and the next one is nill,
130 // select the first one
131 orig->selected = true;
132 return orig;
135 c = c->next;
137 return nil;
140 struct completions *compl_select_prev(struct completions *c, bool n) {
141 if (c == nil)
142 return nil;
144 struct completions *cc = c;
146 if (n) // select the last one
147 while (cc != nil) {
148 if (cc->next == nil) {
149 cc->selected = true;
150 return cc;
152 cc = cc->next;
154 else // select the previous one
155 while (cc != nil) {
156 if (cc->next != nil && cc->next->selected) {
157 cc->next->selected = false;
158 cc->selected = true;
159 return cc;
161 cc = cc->next;
164 return nil;
167 struct completions *filter(char *text, char **lines) {
168 int i = 0;
169 struct completions *root = compl_new();
170 struct completions *c = root;
172 for (;;) {
173 char *l = lines[i];
174 if (l == nil)
175 break;
177 if (strstr(l, text) != nil) {
178 c->next = compl_new();
179 c = c->next;
180 c->completion = l;
183 ++i;
186 struct completions *r = root->next;
187 compl_delete(root);
188 return r;
191 // push the character c at the end of the string pointed by p
192 int pushc(char **p, int maxlen, char c) {
193 int len = strnlen(*p, maxlen);
195 if (!(len < maxlen -2)) {
196 maxlen += maxlen >> 1;
197 char *newptr = realloc(*p, maxlen);
198 if (newptr == nil) { // bad!
199 return -1;
201 *p = newptr;
204 (*p)[len] = c;
205 (*p)[len+1] = '\0';
206 return maxlen;
209 int utf8strnlen(char *s, int maxlen) {
210 int len = 0;
211 while (*s && maxlen > 0) {
212 len += (*s++ & 0xc0) != 0x80;
213 maxlen--;
215 return len;
218 // remove the last *glyph* from the *utf8* string!
219 // this is different from just setting the last byte to 0 (in some
220 // cases ofc). The actual implementation is quite inefficient because
221 // it remove the last char until the number of glyphs doesn't change
222 void popc(char *p, int maxlen) {
223 int len = strnlen(p, maxlen);
225 if (len == 0)
226 return;
228 int ulen = utf8strnlen(p, maxlen);
229 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
230 len--;
231 p[len] = 0;
235 // If the string is surrounded by quotes (`"`) remove them and replace
236 // every `\"` in the string with `"`
237 char *normalize_str(const char *str) {
238 int len = strlen(str);
239 if (len == 0)
240 return nil;
242 char *s = calloc(len, sizeof(char));
243 check_allocation(s);
244 int p = 0;
245 while (*str) {
246 char c = *str;
247 if (*str == '\\') {
248 if (*(str + 1)) {
249 s[p] = *(str + 1);
250 p++;
251 str += 2; // skip this and the next char
252 continue;
253 } else {
254 break;
257 if (c == '"') {
258 str++; // skip only this char
259 continue;
261 s[p] = c;
262 p++;
263 str++;
265 return s;
268 // read an arbitrary long line from stdin and return a pointer to it
269 // TODO: resize the allocated memory to exactly fit the string once
270 // read?
271 char *readline(bool *eof) {
272 int maxlen = 8;
273 char *str = calloc(maxlen, sizeof(char));
274 if (str == nil) {
275 fprintf(stderr, "Cannot allocate memory!\n");
276 exit(EX_UNAVAILABLE);
279 int c;
280 while((c = getchar()) != EOF) {
281 if (c == '\n')
282 return str;
283 else
284 maxlen = pushc(&str, maxlen, c);
286 if (maxlen == -1) {
287 fprintf(stderr, "Cannot allocate memory!\n");
288 exit(EX_UNAVAILABLE);
291 *eof = true;
292 return str;
295 int readlines (char ***lns, int items) {
296 bool finished = false;
297 int n = 0;
298 char **lines = *lns;
299 while (true) {
300 lines[n] = readline(&finished);
302 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
303 free(lines[n]);
304 --n; // forget about this line
307 if (finished)
308 break;
310 ++n;
312 if (n == items - 1) {
313 items += items >>1;
314 char **l = realloc(lines, sizeof(char*) * items);
315 check_allocation(l);
316 *lns = l;
317 lines = l;
321 n++;
322 lines[n] = nil;
323 return items;
326 // |------------------|----------------------------------------------|
327 // | 20 char text | completion | completion | completion | compl |
328 // |------------------|----------------------------------------------|
329 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
330 // TODO: make these dynamic?
331 int prompt_width = 20; // char
332 int padding = 10;
333 /* int start_at = XTextWidth(r->font, " ", 1) * prompt_width + padding; */
335 XRectangle rect;
336 int ps1xlen = XmbTextExtents(*r->font, r->ps1, r->ps1len, nil, &rect);
337 int start_at = ps1xlen;
339 start_at += XmbTextExtents(*r->font, " ", 1, nil, &rect);
340 start_at = start_at * prompt_width + padding;
342 int texty = (rect.height + r->height) >>1;
344 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
346 int text_len = strlen(text);
347 if (text_len > prompt_width)
348 text = text + (text_len - prompt_width);
349 /* XDrawString(r->d, r->w, r->prompt, padding, texty, text, MIN(text_len, prompt_width)); */
350 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding, texty, r->ps1, r->ps1len);
351 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding + ps1xlen, texty, text, MIN(text_len, prompt_width));
353 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
355 while (cs != nil) {
356 GC g = cs->selected ? r->completion_highlighted : r->completion;
357 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
359 int len = strlen(cs->completion);
360 /* int text_width = XTextWidth(r->font, cs->completion, len); */
361 int text_width = XmbTextExtents(*r->font, cs->completion, len, nil, nil);
363 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
365 /* XDrawString(r->d, r->w, g, start_at + padding, texty, cs->completion, len); */
366 Xutf8DrawString(r->d, r->w, *r->font, g, start_at + padding, texty, cs->completion, len);
368 start_at += text_width + padding * 2;
370 if (start_at > r->width)
371 break; // don't draw completion if the space isn't enough
373 cs = cs->next;
376 XFlush(r->d);
379 // |-----------------------------------------------------------------|
380 // | prompt |
381 // |-----------------------------------------------------------------|
382 // | completion |
383 // |-----------------------------------------------------------------|
384 // | completion |
385 // |-----------------------------------------------------------------|
386 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
387 // should be padding and not padding*2, but the text doesn't seem to
388 // be vertically centered otherwise....
389 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
390 int padding = 10; // TODO make this dynamic
392 XRectangle rect;
393 XmbTextExtents(*r->font, "fjpgl", 5, &rect, nil);
394 int start_at = rect.height + padding*2;
396 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
397 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
398 int ps1xlen = XmbTextExtents(*r->font, r->ps1, r->ps1len, nil, nil);
399 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding, padding*2, r->ps1, r->ps1len);
400 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding + ps1xlen, padding*2, text, strlen(text));
402 while (cs != nil) {
403 GC g = cs->selected ? r->completion_highlighted : r->completion;
404 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
406 int len = strlen(cs->completion);
407 XmbTextExtents(*r->font, cs->completion, len, &rect, nil);
408 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, rect.height + padding*2);
409 Xutf8DrawString(r->d, r->w, *r->font, g, padding, start_at + padding*2, cs->completion, len);
411 start_at += rect.height + padding *2;
413 if (start_at > r->height)
414 break; // don't draw completion if the space isn't enough
416 cs = cs->next;
419 XFlush(r->d);
422 void draw(struct rendering *r, char *text, struct completions *cs) {
423 if (r->horizontal_layout)
424 draw_horizontally(r, text, cs);
425 else
426 draw_vertically(r, text, cs);
429 /* Set some WM stuff */
430 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
431 Atom type;
432 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
433 XChangeProperty(
434 d,
435 w,
436 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
437 XInternAtom(d, "ATOM", false),
438 32,
439 PropModeReplace,
440 (unsigned char *)&type,
442 );
444 /* some window managers honor this properties */
445 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
446 XChangeProperty(d,
447 w,
448 XInternAtom(d, "_NET_WM_STATE", false),
449 XInternAtom(d, "ATOM", false),
450 32,
451 PropModeReplace,
452 (unsigned char *)&type,
454 );
456 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
457 XChangeProperty(d,
458 w,
459 XInternAtom(d, "_NET_WM_STATE", false),
460 XInternAtom(d, "ATOM", false),
461 32,
462 PropModeAppend,
463 (unsigned char *)&type,
465 );
467 // setting window hints
468 XClassHint *class_hint = XAllocClassHint();
469 if (class_hint == nil) {
470 fprintf(stderr, "Could not allocate memory for class hint\n");
471 exit(EX_UNAVAILABLE);
473 class_hint->res_name = "mymenu";
474 class_hint->res_class = "mymenu";
475 XSetClassHint(d, w, class_hint);
476 XFree(class_hint);
478 XSizeHints *size_hint = XAllocSizeHints();
479 if (size_hint == nil) {
480 fprintf(stderr, "Could not allocate memory for size hint\n");
481 exit(EX_UNAVAILABLE);
483 size_hint->min_width = width;
484 size_hint->base_width = width;
485 size_hint->min_height = height;
486 size_hint->base_height = height;
488 XFlush(d);
491 void get_wh(Display *d, Window *w, int *width, int *height) {
492 XWindowAttributes win_attr;
493 XGetWindowAttributes(d, *w, &win_attr);
494 *height = win_attr.height;
495 *width = win_attr.width;
498 // I know this may seem a little hackish BUT is the only way I managed
499 // to actually grab that goddam keyboard. Only one call to
500 // XGrabKeyboard does not always end up with the keyboard grabbed!
501 int take_keyboard(Display *d, Window w) {
502 int i;
503 for (i = 0; i < 100; i++) {
504 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
505 return 1;
506 usleep(1000);
508 return 0;
511 void release_keyboard(Display *d) {
512 XUngrabKeyboard(d, CurrentTime);
515 int parse_integer(const char *str, int default_value, int max) {
516 int len = strlen(str);
517 if (len > 0 && str[len-1] == '%') {
518 char *cpy = strdup(str);
519 check_allocation(cpy);
520 cpy[len-1] = '\0';
521 int val = parse_integer(cpy, default_value, max);
522 free(cpy);
523 return val * max / 100;
526 errno = 0;
527 char *ep;
528 long lval = strtol(str, &ep, 10);
529 if (str[0] == '\0' || *ep != '\0') { // NaN
530 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
531 return default_value;
533 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
534 (lval > INT_MAX || lval < INT_MIN)) {
535 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
536 return default_value;
538 return lval;
541 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
542 if (!strcmp(str, "middle")) {
543 return (max - self)/2;
545 return parse_integer(str, default_value, max);
548 int main() {
549 /* char *lines[INITIAL_ITEMS] = {0}; */
550 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
551 int nlines = readlines(&lines, INITIAL_ITEMS);
553 setlocale(LC_ALL, getenv("LANG"));
555 enum state status = LOOPING;
557 // where the monitor start (used only with xinerama)
558 int offset_x = 0;
559 int offset_y = 0;
561 // width and height of the window
562 int width = 400;
563 int height = 20;
565 // position on the screen
566 int x = 0;
567 int y = 0;
569 char *ps1 = strdup("$ ");
570 check_allocation(ps1);
572 char *fontname = strdup("fixed");
573 check_allocation(fontname);
575 int textlen = 10;
576 char *text = malloc(textlen * sizeof(char));
577 check_allocation(text);
579 struct completions *cs = filter(text, lines);
580 bool nothing_selected = true;
582 // start talking to xorg
583 Display *d = XOpenDisplay(nil);
584 if (d == nil) {
585 fprintf(stderr, "Could not open display!\n");
586 return EX_UNAVAILABLE;
589 // get display size
590 // XXX: is getting the default root window dimension correct?
591 XWindowAttributes xwa;
592 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
593 int d_width = xwa.width;
594 int d_height = xwa.height;
596 #ifdef USE_XINERAMA
597 // TODO: this bit still needs to be improved
598 if (XineramaIsActive(d)) {
599 int monitors;
600 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
601 if (info)
602 for (int i = 0; i < monitors; ++i) {
603 if (INTERSECT(x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
604 offset_x = info[x].x_org;
605 offset_y = info[y].y_org;
606 d_width = info[i].width;
607 d_height = info[i].height;
610 XFree(info);
612 #endif
614 /* fprintf(stderr, "offset_x:\t%d\n" */
615 /* "offset_y:\t%d\n" */
616 /* "d_width:\t%d\n" */
617 /* "d_height:\t%d\n" */
618 /* , offset_x, offset_y, d_width, d_height); */
620 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
621 XColor p_fg, p_bg,
622 compl_fg, compl_bg,
623 compl_highlighted_fg, compl_highlighted_bg;
625 bool horizontal_layout = true;
627 // read resource
628 XrmInitialize();
629 char *xrm = XResourceManagerString(d);
630 XrmDatabase xdb = nil;
631 if (xrm != nil) {
632 xdb = XrmGetStringDatabase(xrm);
633 XrmValue value;
634 char *datatype[20];
636 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
637 fontname = strdup(value.addr);
638 check_allocation(fontname);
640 else
641 fprintf(stderr, "no font defined, using %s\n", fontname);
643 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
644 char *v = strdup(value.addr);
645 check_allocation(v);
646 horizontal_layout = !strcmp(v, "horizontal");
647 free(v);
649 else
650 fprintf(stderr, "no layout defined, using horizontal\n");
652 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
653 free(ps1);
654 ps1 = normalize_str(value.addr);
655 } else
656 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
658 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
659 width = parse_integer(value.addr, width, d_width);
660 else
661 fprintf(stderr, "no width defined, using %d\n", width);
663 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
664 height = parse_integer(value.addr, height, d_height);
665 else
666 fprintf(stderr, "no height defined, using %d\n", height);
668 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
669 x = parse_int_with_middle(value.addr, x, d_width, width);
670 else
671 fprintf(stderr, "no x defined, using %d\n", width);
673 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
674 y = parse_int_with_middle(value.addr, y, d_height, height);
675 else
676 fprintf(stderr, "no y defined, using %d\n", height);
678 XColor tmp;
679 // TODO: tmp needs to be free'd after every allocation?
681 // prompt
682 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
683 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
684 else
685 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
687 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
688 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
689 else
690 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
692 // completion
693 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
694 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
695 else
696 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
698 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
699 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
700 else
701 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
703 // completion highlighted
704 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
705 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
706 else
707 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
709 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
710 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
711 else
712 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
713 } else {
714 XColor tmp;
715 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
716 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
717 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
718 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
719 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
720 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
723 // load the font
724 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
725 /* if (font == nil) { */
726 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
727 /* font = XLoadQueryFont(d, "fixed"); */
728 /* } */
729 // load the font
730 char **missing_charset_list;
731 int missing_charset_count;
732 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
733 if (font == nil) {
734 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
735 return EX_UNAVAILABLE;
738 // create the window
739 XSetWindowAttributes attr;
741 Window w = XCreateWindow(d, // display
742 DefaultRootWindow(d), // parent
743 x + offset_x, y + offset_y, // x y
744 width, height, // w h
745 0, // border width
746 DefaultDepth(d, DefaultScreen(d)), // depth
747 InputOutput, // class
748 DefaultVisual(d, DefaultScreen(d)), // visual
749 0, // value mask
750 &attr);
752 set_win_atoms_hints(d, w, width, height);
754 // we want some events
755 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeyReleaseMask | KeymapStateMask);
757 // make the window appear on the screen
758 XMapWindow(d, w);
760 // wait for the MapNotify event (i.e. the event "window rendered")
761 for (;;) {
762 XEvent e;
763 XNextEvent(d, &e);
764 if (e.type == MapNotify)
765 break;
768 // get the *real* width & height after the window was rendered
769 get_wh(d, &w, &width, &height);
771 // grab keyboard
772 take_keyboard(d, w);
774 // Create some graphics contexts
775 XGCValues values;
776 /* values.font = font->fid; */
778 struct rendering r = {
779 .d = d,
780 .w = w,
781 .prompt = XCreateGC(d, w, 0, &values),
782 .prompt_bg = XCreateGC(d, w, 0, &values),
783 .completion = XCreateGC(d, w, 0, &values),
784 .completion_bg = XCreateGC(d, w, 0, &values),
785 .completion_highlighted = XCreateGC(d, w, 0, &values),
786 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
787 /* .prompt = XCreateGC(d, w, GCFont, &values), */
788 /* .prompt_bg = XCreateGC(d, w, GCFont, &values), */
789 /* .completion = XCreateGC(d, w, GCFont, &values), */
790 /* .completion_bg = XCreateGC(d, w, GCFont, &values), */
791 /* .completion_highlighted = XCreateGC(d, w, GCFont, &values), */
792 /* .completion_highlighted_bg = XCreateGC(d, w, GCFont, &values), */
793 .width = width,
794 .height = height,
795 .font = &font,
796 .horizontal_layout = horizontal_layout,
797 .ps1 = ps1,
798 .ps1len = strlen(ps1)
799 };
801 // load the colors in our GCs
802 XSetForeground(d, r.prompt, p_fg.pixel);
803 XSetForeground(d, r.prompt_bg, p_bg.pixel);
804 XSetForeground(d, r.completion, compl_fg.pixel);
805 XSetForeground(d, r.completion_bg, compl_bg.pixel);
806 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
807 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
809 // open the X input method
810 XIM xim = XOpenIM(d, xdb, resname, resclass);
811 check_allocation(xim);
813 XIMStyles *xis = nil;
814 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
815 fprintf(stderr, "Input Styles could not be retrieved\n");
816 return EX_UNAVAILABLE;
819 XIMStyle bestMatchStyle = 0;
820 for (int i = 0; i < xis->count_styles; ++i) {
821 XIMStyle ts = xis->supported_styles[i];
822 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
823 bestMatchStyle = ts;
824 break;
827 XFree(xis);
829 if (!bestMatchStyle) {
830 fprintf(stderr, "No matching input style could be determined\n");
833 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
834 check_allocation(xic);
836 // draw the window for the first time
837 draw(&r, text, cs);
839 // main loop
840 while (status == LOOPING) {
841 XEvent e;
842 XNextEvent(d, &e);
844 if (XFilterEvent(&e, w))
845 continue;
847 switch (e.type) {
848 case KeymapNotify:
849 XRefreshKeyboardMapping(&e.xmapping);
850 break;
852 case KeyRelease: break; // ignore this
854 case KeyPress: {
855 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
857 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
858 bool shift = (ev->state & ShiftMask);
859 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
860 : compl_select_next(cs, nothing_selected);
861 if (n != nil) {
862 nothing_selected = false;
863 free(text);
864 text = strdup(n->completion);
865 if (text == nil) {
866 fprintf(stderr, "Memory allocation error!\n");
867 status = ERR;
868 break;
870 textlen = strlen(text);
872 draw(&r, text, cs);
873 break;
876 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
877 nothing_selected = true;
878 popc(text, textlen);
879 update_completions(cs, text, lines);
880 draw(&r, text, cs);
881 break;
884 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
885 status = OK;
886 break;
889 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
890 status = ERR;
891 break;
894 // try to read what the user pressed
895 int symbol = 0;
896 Status s = 0;
897 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
899 if (s == XBufferOverflow) {
900 // should not happen since there are no utf-8 characters
901 // larger than 24bits, but is something to be aware of when
902 // used to directly write to a string buffer
903 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
904 break;
906 char *str = (char*)&symbol;
908 if (ev->state & ControlMask) {
909 // check for some key bindings
910 if (!strcmp(str, "")) { // C-u
911 nothing_selected = true;
912 for (int i = 0; i < textlen; ++i)
913 text[i] = 0;
914 update_completions(cs, text, lines);
916 if (!strcmp(str, "")) { // C-h
917 nothing_selected = true;
918 popc(text, textlen);
919 update_completions(cs, text, lines);
921 if (!strcmp(str, "")) { // C-w
922 nothing_selected = true;
924 // `textlen` is the length of the allocated string, not the
925 // length of the ACTUAL string
926 int p = strlen(text) - 1;
927 if (p >= 0) { // delete the current char
928 text[p] = 0;
929 p--;
931 while (p >= 0 && isalnum(text[p])) {
932 text[p] = 0;
933 p--;
935 // erase also trailing white space
936 while (p >= 0 && isspace(text[p])) {
937 text[p] = 0;
938 p--;
940 update_completions(cs, text, lines);
942 if (!strcmp(str, "\r")) { // C-m
943 status = OK;
945 draw(&r, text, cs);
946 break;
949 int str_len = strlen(str);
950 for (int i = 0; i < str_len; ++i) {
951 textlen = pushc(&text, textlen, str[i]);
952 if (textlen == -1) {
953 fprintf(stderr, "Memory allocation error\n");
954 status = ERR;
955 break;
957 nothing_selected = true;
958 update_completions(cs, text, lines);
962 draw(&r, text, cs);
963 break;
965 default:
966 fprintf(stderr, "Unknown event %d\n", e.type);
970 release_keyboard(d);
972 if (status == OK)
973 printf("%s\n", text);
975 for (int i = 0; i < nlines; ++i) {
976 free(lines[i]);
979 free(ps1);
980 free(fontname);
981 free(text);
982 free(lines);
983 compl_delete(cs);
985 XDestroyWindow(d, w);
986 XCloseDisplay(d);
988 return status == OK ? 0 : 1;