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 };
88 struct completions {
89 char *completion;
90 bool selected;
91 struct completions *next;
92 };
94 struct completions *compl_new() {
95 struct completions *c = malloc(sizeof(struct completions));
97 if (c == nil)
98 return c;
100 c->completion = nil;
101 c->selected = false;
102 c->next = nil;
103 return c;
106 void compl_delete(struct completions *c) {
107 free(c);
110 struct completions *compl_select_next(struct completions *c, bool n) {
111 if (c == nil)
112 return nil;
113 if (n) {
114 c->selected = true;
115 return c;
118 struct completions *orig = c;
119 while (c != nil) {
120 if (c->selected) {
121 c->selected = false;
122 if (c->next != nil) {
123 // the current one is selected and the next one exists
124 c->next->selected = true;
125 return c->next;
126 } else {
127 // the current one is selected and the next one is nill,
128 // select the first one
129 orig->selected = true;
130 return orig;
133 c = c->next;
135 return nil;
138 struct completions *compl_select_prev(struct completions *c, bool n) {
139 if (c == nil)
140 return nil;
142 struct completions *cc = c;
144 if (n) // select the last one
145 while (cc != nil) {
146 if (cc->next == nil) {
147 cc->selected = true;
148 return cc;
150 cc = cc->next;
152 else // select the previous one
153 while (cc != nil) {
154 if (cc->next != nil && cc->next->selected) {
155 cc->next->selected = false;
156 cc->selected = true;
157 return cc;
159 cc = cc->next;
162 return nil;
165 struct completions *filter(char *text, char **lines) {
166 int i = 0;
167 struct completions *root = compl_new();
168 struct completions *c = root;
170 for (;;) {
171 char *l = lines[i];
172 if (l == nil)
173 break;
175 if (strstr(l, text) != nil) {
176 c->next = compl_new();
177 c = c->next;
178 c->completion = l;
181 ++i;
184 struct completions *r = root->next;
185 compl_delete(root);
186 return r;
189 // push the character c at the end of the string pointed by p
190 int pushc(char **p, int maxlen, char c) {
191 int len = strnlen(*p, maxlen);
193 if (!(len < maxlen -2)) {
194 maxlen += maxlen >> 1;
195 char *newptr = realloc(*p, maxlen);
196 if (newptr == nil) { // bad!
197 return -1;
199 *p = newptr;
202 (*p)[len] = c;
203 (*p)[len+1] = '\0';
204 return maxlen;
207 int utf8strnlen(char *s, int maxlen) {
208 int len = 0;
209 while (*s && maxlen > 0) {
210 len += (*s++ & 0xc0) != 0x80;
211 maxlen--;
213 return len;
216 // remove the last *glyph* from the *utf8* string!
217 // this is different from just setting the last byte to 0 (in some
218 // cases ofc). The actual implementation is quite inefficient because
219 // it remove the last char until the number of glyphs doesn't change
220 void popc(char *p, int maxlen) {
221 int len = strnlen(p, maxlen);
223 if (len == 0)
224 return;
226 int ulen = utf8strnlen(p, maxlen);
227 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
228 len--;
229 p[len] = 0;
233 // read an arbitrary long line from stdin and return a pointer to it
234 // TODO: resize the allocated memory to exactly fit the string once
235 // read?
236 char *readline(bool *eof) {
237 int maxlen = 8;
238 char *str = calloc(maxlen, sizeof(char));
239 if (str == nil) {
240 fprintf(stderr, "Cannot allocate memory!\n");
241 exit(EX_UNAVAILABLE);
244 int c;
245 while((c = getchar()) != EOF) {
246 if (c == '\n')
247 return str;
248 else
249 maxlen = pushc(&str, maxlen, c);
251 if (maxlen == -1) {
252 fprintf(stderr, "Cannot allocate memory!\n");
253 exit(EX_UNAVAILABLE);
256 *eof = true;
257 return str;
260 int readlines (char ***lns, int items) {
261 bool finished = false;
262 int n = 0;
263 char **lines = *lns;
264 while (true) {
265 lines[n] = readline(&finished);
267 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
268 free(lines[n]);
269 --n; // forget about this line
272 if (finished)
273 break;
275 ++n;
277 if (n == items - 1) {
278 items += items >>1;
279 char **l = realloc(lines, sizeof(char*) * items);
280 check_allocation(l);
281 *lns = l;
282 lines = l;
286 n++;
287 lines[n] = nil;
288 return items;
291 // |------------------|----------------------------------------------|
292 // | 20 char text | completion | completion | completion | compl |
293 // |------------------|----------------------------------------------|
294 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
295 // TODO: make these dynamic?
296 int prompt_width = 20; // char
297 int padding = 10;
298 /* int start_at = XTextWidth(r->font, " ", 1) * prompt_width + padding; */
300 XRectangle rect;
301 int start_at = XmbTextExtents(*r->font, " ", 1, nil, &rect);
302 start_at = start_at * prompt_width + padding;
304 int texty = (rect.height + r->height) >>1;
306 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
308 int text_len = strlen(text);
309 if (text_len > prompt_width)
310 text = text + (text_len - prompt_width);
311 /* XDrawString(r->d, r->w, r->prompt, padding, texty, text, MIN(text_len, prompt_width)); */
312 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding, texty, text, MIN(text_len, prompt_width));
314 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
316 while (cs != nil) {
317 GC g = cs->selected ? r->completion_highlighted : r->completion;
318 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
320 int len = strlen(cs->completion);
321 /* int text_width = XTextWidth(r->font, cs->completion, len); */
322 int text_width = XmbTextExtents(*r->font, cs->completion, len, nil, nil);
324 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
326 /* XDrawString(r->d, r->w, g, start_at + padding, texty, cs->completion, len); */
327 Xutf8DrawString(r->d, r->w, *r->font, g, start_at + padding, texty, cs->completion, len);
329 start_at += text_width + padding * 2;
331 if (start_at > r->width)
332 break; // don't draw completion if the space isn't enough
334 cs = cs->next;
337 XFlush(r->d);
340 // |-----------------------------------------------------------------|
341 // | prompt |
342 // |-----------------------------------------------------------------|
343 // | completion |
344 // |-----------------------------------------------------------------|
345 // | completion |
346 // |-----------------------------------------------------------------|
347 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
348 // should be padding and not padding*2, but the text doesn't seem to
349 // be vertically centered otherwise....
350 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
351 int padding = 10; // TODO make this dynamic
353 XRectangle rect;
354 XmbTextExtents(*r->font, "fjpgl", 5, &rect, nil);
355 int start_at = rect.height + padding*2;
357 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
358 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
359 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding, padding*2, text, strlen(text));
361 while (cs != nil) {
362 GC g = cs->selected ? r->completion_highlighted : r->completion;
363 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
365 int len = strlen(cs->completion);
366 XmbTextExtents(*r->font, cs->completion, len, &rect, nil);
367 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, rect.height + padding*2);
368 Xutf8DrawString(r->d, r->w, *r->font, g, padding, start_at + padding*2, cs->completion, len);
370 start_at += rect.height + padding *2;
372 if (start_at > r->height)
373 break; // don't draw completion if the space isn't enough
375 cs = cs->next;
378 XFlush(r->d);
381 void draw(struct rendering *r, char *text, struct completions *cs) {
382 if (r->horizontal_layout)
383 draw_horizontally(r, text, cs);
384 else
385 draw_vertically(r, text, cs);
388 /* Set some WM stuff */
389 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
390 Atom type;
391 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
392 XChangeProperty(
393 d,
394 w,
395 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
396 XInternAtom(d, "ATOM", false),
397 32,
398 PropModeReplace,
399 (unsigned char *)&type,
401 );
403 /* some window managers honor this properties */
404 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
405 XChangeProperty(d,
406 w,
407 XInternAtom(d, "_NET_WM_STATE", false),
408 XInternAtom(d, "ATOM", false),
409 32,
410 PropModeReplace,
411 (unsigned char *)&type,
413 );
415 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
416 XChangeProperty(d,
417 w,
418 XInternAtom(d, "_NET_WM_STATE", false),
419 XInternAtom(d, "ATOM", false),
420 32,
421 PropModeAppend,
422 (unsigned char *)&type,
424 );
426 // setting window hints
427 XClassHint *class_hint = XAllocClassHint();
428 if (class_hint == nil) {
429 fprintf(stderr, "Could not allocate memory for class hint\n");
430 exit(EX_UNAVAILABLE);
432 class_hint->res_name = "mymenu";
433 class_hint->res_class = "mymenu";
434 XSetClassHint(d, w, class_hint);
435 XFree(class_hint);
437 XSizeHints *size_hint = XAllocSizeHints();
438 if (size_hint == nil) {
439 fprintf(stderr, "Could not allocate memory for size hint\n");
440 exit(EX_UNAVAILABLE);
442 size_hint->min_width = width;
443 size_hint->base_width = width;
444 size_hint->min_height = height;
445 size_hint->base_height = height;
447 XFlush(d);
450 void get_wh(Display *d, Window *w, int *width, int *height) {
451 XWindowAttributes win_attr;
452 XGetWindowAttributes(d, *w, &win_attr);
453 *height = win_attr.height;
454 *width = win_attr.width;
457 // I know this may seem a little hackish BUT is the only way I managed
458 // to actually grab that goddam keyboard. Only one call to
459 // XGrabKeyboard does not always end up with the keyboard grabbed!
460 int take_keyboard(Display *d, Window w) {
461 int i;
462 for (i = 0; i < 100; i++) {
463 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
464 return 1;
465 usleep(1000);
467 return 0;
470 void release_keyboard(Display *d) {
471 XUngrabKeyboard(d, CurrentTime);
474 int parse_integer(const char *str, int default_value, int max) {
475 int len = strlen(str);
476 if (len > 0 && str[len-1] == '%') {
477 char *cpy = strdup(str);
478 check_allocation(cpy);
479 cpy[len-1] = '\0';
480 int val = parse_integer(cpy, default_value, max);
481 free(cpy);
482 return val * max / 100;
485 errno = 0;
486 char *ep;
487 long lval = strtol(str, &ep, 10);
488 if (str[0] == '\0' || *ep != '\0') { // NaN
489 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
490 return default_value;
492 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
493 (lval > INT_MAX || lval < INT_MIN)) {
494 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
495 return default_value;
497 return lval;
500 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
501 if (!strcmp(str, "middle")) {
502 return (max - self)/2;
504 return parse_integer(str, default_value, max);
507 int main() {
508 /* char *lines[INITIAL_ITEMS] = {0}; */
509 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
510 int nlines = readlines(&lines, INITIAL_ITEMS);
512 setlocale(LC_ALL, getenv("LANG"));
514 enum state status = LOOPING;
516 // where the monitor start (used only with xinerama)
517 int offset_x = 0;
518 int offset_y = 0;
520 // width and height of the window
521 int width = 400;
522 int height = 20;
524 // position on the screen
525 int x = 0;
526 int y = 0;
528 char *fontname = strdup("fixed");
529 check_allocation(fontname);
531 int textlen = 10;
532 char *text = malloc(textlen * sizeof(char));
533 check_allocation(text);
535 struct completions *cs = filter(text, lines);
536 bool nothing_selected = true;
538 // start talking to xorg
539 Display *d = XOpenDisplay(nil);
540 if (d == nil) {
541 fprintf(stderr, "Could not open display!\n");
542 return EX_UNAVAILABLE;
545 // get display size
546 // XXX: is getting the default root window dimension correct?
547 XWindowAttributes xwa;
548 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
549 int d_width = xwa.width;
550 int d_height = xwa.height;
552 #ifdef USE_XINERAMA
553 // TODO: this bit still needs to be improved
554 if (XineramaIsActive(d)) {
555 int monitors;
556 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
557 if (info)
558 for (int i = 0; i < monitors; ++i) {
559 if (INTERSECT(x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
560 offset_x = info[x].x_org;
561 offset_y = info[y].y_org;
562 d_width = info[i].width;
563 d_height = info[i].height;
566 XFree(info);
568 #endif
570 /* fprintf(stderr, "offset_x:\t%d\n" */
571 /* "offset_y:\t%d\n" */
572 /* "d_width:\t%d\n" */
573 /* "d_height:\t%d\n" */
574 /* , offset_x, offset_y, d_width, d_height); */
576 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
577 XColor p_fg, p_bg,
578 compl_fg, compl_bg,
579 compl_highlighted_fg, compl_highlighted_bg;
581 bool horizontal_layout = true;
583 // read resource
584 XrmInitialize();
585 char *xrm = XResourceManagerString(d);
586 XrmDatabase xdb = nil;
587 if (xrm != nil) {
588 xdb = XrmGetStringDatabase(xrm);
589 XrmValue value;
590 char *datatype[20];
592 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
593 fontname = strdup(value.addr);
594 check_allocation(fontname);
596 else
597 fprintf(stderr, "no font defined, using %s\n", fontname);
599 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
600 char *v = strdup(value.addr);
601 check_allocation(v);
602 horizontal_layout = !strcmp(v, "horizontal");
603 free(v);
605 else
606 fprintf(stderr, "no layout defined, using horizontal\n");
608 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
609 width = parse_integer(value.addr, width, d_width);
610 else
611 fprintf(stderr, "no width defined, using %d\n", width);
613 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
614 height = parse_integer(value.addr, height, d_height);
615 else
616 fprintf(stderr, "no height defined, using %d\n", height);
618 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
619 x = parse_int_with_middle(value.addr, x, d_width, width);
620 else
621 fprintf(stderr, "no x defined, using %d\n", width);
623 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
624 y = parse_int_with_middle(value.addr, y, d_height, height);
625 else
626 fprintf(stderr, "no y defined, using %d\n", height);
628 XColor tmp;
629 // TODO: tmp needs to be free'd after every allocation?
631 // prompt
632 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
633 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
634 else
635 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
637 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
638 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
639 else
640 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
642 // completion
643 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
644 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
645 else
646 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
648 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
649 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
650 else
651 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
653 // completion highlighted
654 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
655 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
656 else
657 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
659 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
660 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
661 else
662 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
663 } else {
664 XColor tmp;
665 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
666 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
667 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
668 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
669 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
670 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
673 // load the font
674 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
675 /* if (font == nil) { */
676 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
677 /* font = XLoadQueryFont(d, "fixed"); */
678 /* } */
679 // load the font
680 char **missing_charset_list;
681 int missing_charset_count;
682 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
683 if (font == nil) {
684 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
685 return EX_UNAVAILABLE;
688 // create the window
689 XSetWindowAttributes attr;
691 Window w = XCreateWindow(d, // display
692 DefaultRootWindow(d), // parent
693 x + offset_x, y + offset_y, // x y
694 width, height, // w h
695 0, // border width
696 DefaultDepth(d, DefaultScreen(d)), // depth
697 InputOutput, // class
698 DefaultVisual(d, DefaultScreen(d)), // visual
699 0, // value mask
700 &attr);
702 set_win_atoms_hints(d, w, width, height);
704 // we want some events
705 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeyReleaseMask | KeymapStateMask);
707 // make the window appear on the screen
708 XMapWindow(d, w);
710 // wait for the MapNotify event (i.e. the event "window rendered")
711 for (;;) {
712 XEvent e;
713 XNextEvent(d, &e);
714 if (e.type == MapNotify)
715 break;
718 // get the *real* width & height after the window was rendered
719 get_wh(d, &w, &width, &height);
721 // grab keyboard
722 take_keyboard(d, w);
724 // Create some graphics contexts
725 XGCValues values;
726 /* values.font = font->fid; */
728 struct rendering r = {
729 .d = d,
730 .w = w,
731 .prompt = XCreateGC(d, w, 0, &values),
732 .prompt_bg = XCreateGC(d, w, 0, &values),
733 .completion = XCreateGC(d, w, 0, &values),
734 .completion_bg = XCreateGC(d, w, 0, &values),
735 .completion_highlighted = XCreateGC(d, w, 0, &values),
736 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
737 /* .prompt = XCreateGC(d, w, GCFont, &values), */
738 /* .prompt_bg = XCreateGC(d, w, GCFont, &values), */
739 /* .completion = XCreateGC(d, w, GCFont, &values), */
740 /* .completion_bg = XCreateGC(d, w, GCFont, &values), */
741 /* .completion_highlighted = XCreateGC(d, w, GCFont, &values), */
742 /* .completion_highlighted_bg = XCreateGC(d, w, GCFont, &values), */
743 .width = width,
744 .height = height,
745 .font = &font,
746 .horizontal_layout = horizontal_layout
747 };
749 // load the colors in our GCs
750 XSetForeground(d, r.prompt, p_fg.pixel);
751 XSetForeground(d, r.prompt_bg, p_bg.pixel);
752 XSetForeground(d, r.completion, compl_fg.pixel);
753 XSetForeground(d, r.completion_bg, compl_bg.pixel);
754 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
755 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
757 // open the X input method
758 XIM xim = XOpenIM(d, xdb, resname, resclass);
759 check_allocation(xim);
761 XIMStyles *xis = nil;
762 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
763 fprintf(stderr, "Input Styles could not be retrieved\n");
764 return EX_UNAVAILABLE;
767 XIMStyle bestMatchStyle = 0;
768 for (int i = 0; i < xis->count_styles; ++i) {
769 XIMStyle ts = xis->supported_styles[i];
770 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
771 bestMatchStyle = ts;
772 break;
775 XFree(xis);
777 if (!bestMatchStyle) {
778 fprintf(stderr, "No matching input style could be determined\n");
781 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
782 check_allocation(xic);
784 // draw the window for the first time
785 draw(&r, text, cs);
787 // main loop
788 while (status == LOOPING) {
789 XEvent e;
790 XNextEvent(d, &e);
792 if (XFilterEvent(&e, w))
793 continue;
795 switch (e.type) {
796 case KeymapNotify:
797 XRefreshKeyboardMapping(&e.xmapping);
798 break;
800 case KeyRelease: break; // ignore this
802 case KeyPress: {
803 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
805 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
806 bool shift = (ev->state & ShiftMask);
807 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
808 : compl_select_next(cs, nothing_selected);
809 if (n != nil) {
810 nothing_selected = false;
811 free(text);
812 text = strdup(n->completion);
813 if (text == nil) {
814 fprintf(stderr, "Memory allocation error!\n");
815 status = ERR;
816 break;
818 textlen = strlen(text);
820 draw(&r, text, cs);
821 break;
824 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
825 nothing_selected = true;
826 popc(text, textlen);
827 update_completions(cs, text, lines);
828 draw(&r, text, cs);
829 break;
832 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
833 status = OK;
834 break;
837 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
838 status = ERR;
839 break;
842 // try to read what the user pressed
843 int symbol = 0;
844 Status s = 0;
845 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
847 if (s == XBufferOverflow) {
848 // should not happen since there are no utf-8 characters
849 // larger than 24bits, but is something to be aware of when
850 // used to directly write to a string buffer
851 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
852 break;
854 char *str = (char*)&symbol;
856 if (ev->state & ControlMask) {
857 // check for some key bindings
858 if (!strcmp(str, "")) { // C-u
859 nothing_selected = true;
860 for (int i = 0; i < textlen; ++i)
861 text[i] = 0;
862 update_completions(cs, text, lines);
864 if (!strcmp(str, "")) { // C-h
865 nothing_selected = true;
866 popc(text, textlen);
867 update_completions(cs, text, lines);
869 if (!strcmp(str, "")) { // C-w
870 nothing_selected = true;
872 // `textlen` is the length of the allocated string, not the
873 // length of the ACTUAL string
874 int p = strlen(text) - 1;
875 if (p >= 0) { // delete the current char
876 text[p] = 0;
877 p--;
879 while (p >= 0 && isalnum(text[p])) {
880 text[p] = 0;
881 p--;
883 // erase also trailing white space
884 while (p >= 0 && isspace(text[p])) {
885 text[p] = 0;
886 p--;
888 update_completions(cs, text, lines);
890 if (!strcmp(str, "\r")) { // C-m
891 status = OK;
893 draw(&r, text, cs);
894 break;
897 int str_len = strlen(str);
898 for (int i = 0; i < str_len; ++i) {
899 textlen = pushc(&text, textlen, str[i]);
900 if (textlen == -1) {
901 fprintf(stderr, "Memory allocation error\n");
902 status = ERR;
903 break;
905 nothing_selected = true;
906 update_completions(cs, text, lines);
910 draw(&r, text, cs);
911 break;
913 default:
914 fprintf(stderr, "Unknown event %d\n", e.type);
918 release_keyboard(d);
920 if (status == OK)
921 printf("%s\n", text);
923 for (int i = 0; i < nlines; ++i) {
924 free(lines[i]);
927 free(fontname);
928 free(text);
929 free(lines);
930 compl_delete(cs);
932 /* XDestroyWindow(d, w); */
933 XCloseDisplay(d);
935 return status == OK ? 0 : 1;