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 MAX_ITEMS 256
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 };
87 struct completions {
88 char *completion;
89 bool selected;
90 struct completions *next;
91 };
93 struct completions *compl_new() {
94 struct completions *c = malloc(sizeof(struct completions));
96 if (c == nil)
97 return c;
99 c->completion = nil;
100 c->selected = false;
101 c->next = nil;
102 return c;
105 void compl_delete(struct completions *c) {
106 free(c);
109 struct completions *compl_select_next(struct completions *c, bool n) {
110 if (c == nil)
111 return nil;
112 if (n) {
113 c->selected = true;
114 return c;
117 struct completions *orig = c;
118 while (c != nil) {
119 if (c->selected) {
120 c->selected = false;
121 if (c->next != nil) {
122 // the current one is selected and the next one exists
123 c->next->selected = true;
124 return c->next;
125 } else {
126 // the current one is selected and the next one is nill,
127 // select the first one
128 orig->selected = true;
129 return orig;
132 c = c->next;
134 return nil;
137 struct completions *compl_select_prev(struct completions *c, bool n) {
138 if (c == nil)
139 return nil;
141 struct completions *cc = c;
143 if (n) // select the last one
144 while (cc != nil) {
145 if (cc->next == nil) {
146 cc->selected = true;
147 return cc;
149 cc = cc->next;
151 else // select the previous one
152 while (cc != nil) {
153 if (cc->next != nil && cc->next->selected) {
154 cc->next->selected = false;
155 cc->selected = true;
156 return cc;
158 cc = cc->next;
161 return nil;
164 struct completions *filter(char *text, char **lines) {
165 int i = 0;
166 struct completions *root = compl_new();
167 struct completions *c = root;
169 for (;;) {
170 char *l = lines[i];
171 if (l == nil)
172 break;
174 if (strstr(l, text) != nil) {
175 c->next = compl_new();
176 c = c->next;
177 c->completion = l;
180 ++i;
183 struct completions *r = root->next;
184 compl_delete(root);
185 return r;
188 // push the character c at the end of the string pointed by p
189 int pushc(char **p, int maxlen, char c) {
190 int len = strnlen(*p, maxlen);
192 if (!(len < maxlen -2)) {
193 maxlen += maxlen >> 1;
194 char *newptr = realloc(*p, maxlen);
195 if (newptr == nil) { // bad!
196 return -1;
198 *p = newptr;
201 (*p)[len] = c;
202 (*p)[len+1] = '\0';
203 return maxlen;
206 int utf8strnlen(char *s, int maxlen) {
207 int len = 0;
208 while (*s && maxlen > 0) {
209 len += (*s++ & 0xc0) != 0x80;
210 maxlen--;
212 return len;
215 // remove the last *glyph* from the *utf8* string!
216 // this is different from just setting the last byte to 0 (in some
217 // cases ofc). The actual implementation is quite inefficient because
218 // it remove the last char until the number of glyphs doesn't change
219 void popc(char *p, int maxlen) {
220 int len = strnlen(p, maxlen);
222 if (len == 0)
223 return;
225 int ulen = utf8strnlen(p, maxlen);
226 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
227 len--;
228 p[len] = 0;
232 // read an arbitrary long line from stdin and return a pointer to it
233 // TODO: resize the allocated memory to exactly fit the string once
234 // read?
235 char *readline(bool *eof) {
236 int maxlen = 8;
237 char *str = calloc(maxlen, sizeof(char));
238 if (str == nil) {
239 fprintf(stderr, "Cannot allocate memory!\n");
240 exit(EX_UNAVAILABLE);
243 int c;
244 while((c = getchar()) != EOF) {
245 if (c == '\n')
246 return str;
247 else
248 maxlen = pushc(&str, maxlen, c);
250 if (maxlen == -1) {
251 fprintf(stderr, "Cannot allocate memory!\n");
252 exit(EX_UNAVAILABLE);
255 *eof = true;
256 return str;
259 int readlines (char **lines) {
260 bool finished = false;
261 int n = 0;
262 while (n < MAX_ITEMS) {
263 lines[n] = readline(&finished);
265 if (strlen(lines[n]) == 0 || lines[n][0] == '\n')
266 --n; // forget about this line
268 if (finished)
269 break;
271 ++n;
273 /* for (n = 0; n < MAX_ITEMS -1; ++n) { */
274 /* lines[n] = readline(&finished); */
275 /* if (finished) */
276 /* break; */
277 /* } */
278 n++;
279 lines[n] = nil;
280 return n;
283 // |------------------|----------------------------------------------|
284 // | 20 char text | completion | completion | completion | compl |
285 // |------------------|----------------------------------------------|
286 void draw(struct rendering *r, char *text, struct completions *cs) {
287 // TODO: make these dynamic?
288 int prompt_width = 20; // char
289 int padding = 10;
290 /* int start_at = XTextWidth(r->font, " ", 1) * prompt_width + padding; */
292 XRectangle rect;
293 int start_at = XmbTextExtents(*r->font, " ", 1, nil, &rect);
294 start_at = start_at * prompt_width + padding;
296 int texty = (rect.height + r->height) >>1;
298 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
300 int text_len = strlen(text);
301 if (text_len > prompt_width)
302 text = text + (text_len - prompt_width);
303 /* XDrawString(r->d, r->w, r->prompt, padding, texty, text, MIN(text_len, prompt_width)); */
304 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding, texty, text, MIN(text_len, prompt_width));
306 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
308 while (cs != nil) {
309 GC g = cs->selected ? r->completion_highlighted : r->completion;
310 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
312 int len = strlen(cs->completion);
313 /* int text_width = XTextWidth(r->font, cs->completion, len); */
314 int text_width = XmbTextExtents(*r->font, cs->completion, len, nil, nil);
316 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
318 /* XDrawString(r->d, r->w, g, start_at + padding, texty, cs->completion, len); */
319 Xutf8DrawString(r->d, r->w, *r->font, g, start_at + padding, texty, cs->completion, len);
321 start_at += text_width + padding * 2;
323 cs = cs->next;
326 XFlush(r->d);
329 /* Set some WM stuff */
330 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
331 Atom type;
332 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
333 XChangeProperty(
334 d,
335 w,
336 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
337 XInternAtom(d, "ATOM", false),
338 32,
339 PropModeReplace,
340 (unsigned char *)&type,
342 );
344 /* some window managers honor this properties */
345 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
346 XChangeProperty(d,
347 w,
348 XInternAtom(d, "_NET_WM_STATE", false),
349 XInternAtom(d, "ATOM", false),
350 32,
351 PropModeReplace,
352 (unsigned char *)&type,
354 );
356 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
357 XChangeProperty(d,
358 w,
359 XInternAtom(d, "_NET_WM_STATE", false),
360 XInternAtom(d, "ATOM", false),
361 32,
362 PropModeAppend,
363 (unsigned char *)&type,
365 );
367 // setting window hints
368 XClassHint *class_hint = XAllocClassHint();
369 if (class_hint == nil) {
370 fprintf(stderr, "Could not allocate memory for class hint\n");
371 exit(EX_UNAVAILABLE);
373 class_hint->res_name = "mymenu";
374 class_hint->res_class = "mymenu";
375 XSetClassHint(d, w, class_hint);
376 XFree(class_hint);
378 XSizeHints *size_hint = XAllocSizeHints();
379 if (size_hint == nil) {
380 fprintf(stderr, "Could not allocate memory for size hint\n");
381 exit(EX_UNAVAILABLE);
383 size_hint->min_width = width;
384 size_hint->base_width = width;
385 size_hint->min_height = height;
386 size_hint->base_height = height;
388 XFlush(d);
391 void get_wh(Display *d, Window *w, int *width, int *height) {
392 XWindowAttributes win_attr;
393 XGetWindowAttributes(d, *w, &win_attr);
394 *height = win_attr.height;
395 *width = win_attr.width;
398 // I know this may seem a little hackish BUT is the only way I managed
399 // to actually grab that goddam keyboard. Only one call to
400 // XGrabKeyboard does not always end up with the keyboard grabbed!
401 int take_keyboard(Display *d, Window w) {
402 int i;
403 for (i = 0; i < 100; i++) {
404 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
405 return 1;
406 usleep(1000);
408 return 0;
411 void release_keyboard(Display *d) {
412 XUngrabKeyboard(d, CurrentTime);
415 int parse_integer(const char *str, int default_value, int max) {
416 int len = strlen(str);
417 if (len > 0 && str[len-1] == '%') {
418 char *cpy = strdup(str);
419 check_allocation(cpy);
420 cpy[len-1] = '\0';
421 int val = parse_integer(cpy, default_value, max);
422 free(cpy);
423 return val * max / 100;
426 errno = 0;
427 char *ep;
428 long lval = strtol(str, &ep, 10);
429 if (str[0] == '\0' || *ep != '\0') { // NaN
430 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
431 return default_value;
433 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
434 (lval > INT_MAX || lval < INT_MIN)) {
435 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
436 return default_value;
438 return lval;
441 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
442 if (!strcmp(str, "middle")) {
443 return (max - self)/2;
445 return parse_integer(str, default_value, max);
448 int main() {
449 char *lines[MAX_ITEMS] = {0};
450 readlines(lines);
452 setlocale(LC_ALL, getenv("LANG"));
454 enum state status = LOOPING;
456 // where the monitor start (used only with xinerama)
457 int offset_x = 0;
458 int offset_y = 0;
460 // width and height of the window
461 int width = 400;
462 int height = 20;
464 // position on the screen
465 int x = 0;
466 int y = 0;
468 char *fontname = strdup("fixed");
469 check_allocation(fontname);
471 int textlen = 10;
472 char *text = malloc(textlen * sizeof(char));
473 check_allocation(text);
475 struct completions *cs = filter(text, lines);
476 bool nothing_selected = true;
478 // start talking to xorg
479 Display *d = XOpenDisplay(nil);
480 if (d == nil) {
481 fprintf(stderr, "Could not open display!\n");
482 return EX_UNAVAILABLE;
485 // get display size
486 // XXX: is getting the default root window dimension correct?
487 XWindowAttributes xwa;
488 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
489 int d_width = xwa.width;
490 int d_height = xwa.height;
492 #ifdef USE_XINERAMA
493 // TODO: this bit still needs to be improved
494 if (XineramaIsActive(d)) {
495 int monitors;
496 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
497 if (info)
498 for (int i = 0; i < monitors; ++i) {
499 if (INTERSECT(x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
500 offset_x = info[x].x_org;
501 offset_y = info[y].y_org;
502 d_width = info[i].width;
503 d_height = info[i].height;
506 XFree(info);
508 #endif
510 /* fprintf(stderr, "offset_x:\t%d\n" */
511 /* "offset_y:\t%d\n" */
512 /* "d_width:\t%d\n" */
513 /* "d_height:\t%d\n" */
514 /* , offset_x, offset_y, d_width, d_height); */
516 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
517 XColor p_fg, p_bg,
518 compl_fg, compl_bg,
519 compl_highlighted_fg, compl_highlighted_bg;
521 // read resource
522 XrmInitialize();
523 char *xrm = XResourceManagerString(d);
524 XrmDatabase xdb = nil;
525 if (xrm != nil) {
526 xdb = XrmGetStringDatabase(xrm);
527 XrmValue value;
528 char *datatype[20];
530 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
531 fontname = strdup(value.addr);
532 check_allocation(fontname);
534 else
535 fprintf(stderr, "no font defined, using %s\n", fontname);
537 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
538 width = parse_integer(value.addr, width, d_width);
539 else
540 fprintf(stderr, "no width defined, using %d\n", width);
542 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
543 height = parse_integer(value.addr, height, d_height);
544 else
545 fprintf(stderr, "no height defined, using %d\n", height);
547 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
548 x = parse_int_with_middle(value.addr, x, d_width, width);
549 else
550 fprintf(stderr, "no x defined, using %d\n", width);
552 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
553 y = parse_int_with_middle(value.addr, y, d_height, height);
554 else
555 fprintf(stderr, "no y defined, using %d\n", height);
557 XColor tmp;
558 // TODO: tmp needs to be free'd after every allocation?
560 // prompt
561 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
562 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
563 else
564 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
566 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
567 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
568 else
569 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
571 // completion
572 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
573 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
574 else
575 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
577 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
578 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
579 else
580 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
582 // completion highlighted
583 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
584 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
585 else
586 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
588 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
589 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
590 else
591 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
592 } else {
593 XColor tmp;
594 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
595 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
596 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
597 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
598 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
599 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
602 // load the font
603 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
604 /* if (font == nil) { */
605 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
606 /* font = XLoadQueryFont(d, "fixed"); */
607 /* } */
608 // load the font
609 char **missing_charset_list;
610 int missing_charset_count;
611 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
612 if (font == nil) {
613 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
614 return EX_UNAVAILABLE;
617 // create the window
618 XSetWindowAttributes attr;
620 Window w = XCreateWindow(d, // display
621 DefaultRootWindow(d), // parent
622 x + offset_x, y + offset_y, // x y
623 width, height, // w h
624 0, // border width
625 DefaultDepth(d, DefaultScreen(d)), // depth
626 InputOutput, // class
627 DefaultVisual(d, DefaultScreen(d)), // visual
628 0, // value mask
629 &attr);
631 set_win_atoms_hints(d, w, width, height);
633 // we want some events
634 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeyReleaseMask | KeymapStateMask);
636 // make the window appear on the screen
637 XMapWindow(d, w);
639 // wait for the MapNotify event (i.e. the event "window rendered")
640 for (;;) {
641 XEvent e;
642 XNextEvent(d, &e);
643 if (e.type == MapNotify)
644 break;
647 // get the *real* width & height after the window was rendered
648 get_wh(d, &w, &width, &height);
650 // grab keyboard
651 take_keyboard(d, w);
653 // Create some graphics contexts
654 XGCValues values;
655 /* values.font = font->fid; */
657 struct rendering r = {
658 .d = d,
659 .w = w,
660 .prompt = XCreateGC(d, w, 0, &values),
661 .prompt_bg = XCreateGC(d, w, 0, &values),
662 .completion = XCreateGC(d, w, 0, &values),
663 .completion_bg = XCreateGC(d, w, 0, &values),
664 .completion_highlighted = XCreateGC(d, w, 0, &values),
665 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
666 /* .prompt = XCreateGC(d, w, GCFont, &values), */
667 /* .prompt_bg = XCreateGC(d, w, GCFont, &values), */
668 /* .completion = XCreateGC(d, w, GCFont, &values), */
669 /* .completion_bg = XCreateGC(d, w, GCFont, &values), */
670 /* .completion_highlighted = XCreateGC(d, w, GCFont, &values), */
671 /* .completion_highlighted_bg = XCreateGC(d, w, GCFont, &values), */
672 .width = width,
673 .height = height,
674 .font = &font
675 };
677 // load the colors in our GCs
678 XSetForeground(d, r.prompt, p_fg.pixel);
679 XSetForeground(d, r.prompt_bg, p_bg.pixel);
680 XSetForeground(d, r.completion, compl_fg.pixel);
681 XSetForeground(d, r.completion_bg, compl_bg.pixel);
682 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
683 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
685 // open the X input method
686 XIM xim = XOpenIM(d, xdb, resname, resclass);
687 check_allocation(xim);
689 XIMStyles *xis = nil;
690 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
691 fprintf(stderr, "Input Styles could not be retrieved\n");
692 return EX_UNAVAILABLE;
695 XIMStyle bestMatchStyle = 0;
696 for (int i = 0; i < xis->count_styles; ++i) {
697 XIMStyle ts = xis->supported_styles[i];
698 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
699 bestMatchStyle = ts;
700 break;
703 XFree(xis);
705 if (!bestMatchStyle) {
706 fprintf(stderr, "No matching input style could be determined\n");
709 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
710 check_allocation(xic);
712 // draw the window for the first time
713 draw(&r, text, cs);
715 // main loop
716 while (status == LOOPING) {
717 XEvent e;
718 XNextEvent(d, &e);
720 if (XFilterEvent(&e, w))
721 continue;
723 switch (e.type) {
724 case KeymapNotify:
725 XRefreshKeyboardMapping(&e.xmapping);
726 break;
728 case KeyRelease: break; // ignore this
730 case KeyPress: {
731 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
733 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
734 bool shift = (ev->state & ShiftMask);
735 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
736 : compl_select_next(cs, nothing_selected);
737 if (n != nil) {
738 nothing_selected = false;
739 free(text);
740 text = strdup(n->completion);
741 if (text == nil) {
742 fprintf(stderr, "Memory allocation error!\n");
743 status = ERR;
744 break;
746 textlen = strlen(text);
748 draw(&r, text, cs);
749 break;
752 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
753 nothing_selected = true;
754 popc(text, textlen);
755 update_completions(cs, text, lines);
756 draw(&r, text, cs);
757 break;
760 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
761 status = OK;
762 break;
765 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
766 status = ERR;
767 break;
770 // try to read what the user pressed
771 int symbol = 0;
772 Status s = 0;
773 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
775 if (s == XBufferOverflow) {
776 // should not happen since there are no utf-8 characters
777 // larger than 24bits, but is something to be aware of when
778 // used to directly write to a string buffer
779 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
780 break;
782 char *str = (char*)&symbol;
784 if (ev->state & ControlMask) {
785 // check for some key bindings
786 if (!strcmp(str, "")) { // C-u
787 nothing_selected = true;
788 for (int i = 0; i < textlen; ++i)
789 text[i] = 0;
790 update_completions(cs, text, lines);
792 if (!strcmp(str, "")) { // C-h
793 nothing_selected = true;
794 popc(text, textlen);
795 update_completions(cs, text, lines);
797 if (!strcmp(str, "")) { // C-w
798 nothing_selected = true;
800 // `textlen` is the length of the allocated string, not the
801 // length of the ACTUAL string
802 int p = strlen(text) - 1;
803 if (p >= 0) { // delete the current char
804 text[p] = 0;
805 p--;
807 while (p >= 0 && isalnum(text[p])) {
808 text[p] = 0;
809 p--;
811 // erase also trailing white space
812 while (p >= 0 && isspace(text[p])) {
813 text[p] = 0;
814 p--;
816 update_completions(cs, text, lines);
818 if (!strcmp(str, "\r")) { // C-m
819 status = OK;
821 draw(&r, text, cs);
822 break;
825 int str_len = strlen(str);
826 for (int i = 0; i < str_len; ++i) {
827 textlen = pushc(&text, textlen, str[i]);
828 if (textlen == -1) {
829 fprintf(stderr, "Memory allocation error\n");
830 status = ERR;
831 break;
833 nothing_selected = true;
834 update_completions(cs, text, lines);
838 draw(&r, text, cs);
839 break;
841 default:
842 fprintf(stderr, "Unknown event %d\n", e.type);
846 release_keyboard(d);
848 if (status == OK)
849 printf("%s\n", text);
851 free(fontname);
852 free(text);
853 compl_delete(cs);
855 /* XDestroyWindow(d, w); */
856 XCloseDisplay(d);
858 return status == OK ? 0 : 1;